-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
65 lines (48 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var debug = require('debug')('variables')
module.exports = variables
function variables(string, map) {
return variables.replace(string, variables.parse(string, map))
}
/**
* Parse all the declared variables and save it to `map`.
*/
variables.parse = function (string, map) {
map = map || {}
var RE_ROOT = /(?:^|\s|\}):root\s*\{[^\}]+\}/g
var RE_VAR = /(?:^|\s|\{|;)--([\w-]+)\s*:\s*([^;\}]+)\s*[;\}]/g
var m_root
var m_var
var root
while (m_root = RE_ROOT.exec(string)) {
root = m_root[0]
while (m_var = RE_VAR.exec(root)) {
map[m_var[1]] = m_var[2]
}
}
debug('parsed: %o', map)
return map
}
/**
* Compile a regular expression for matching simple `var(<name)` statements
*/
variables.compile = function (map) {
return new RegExp('\\bvar\\(\\s*--(' + Object.keys(map).join('|') + ')\\s*\\)', 'g')
}
/**
* Replace all the var statements in a string with parsed `map`.
*/
variables.replace = function (string, map) {
if (!map || !Object.keys(map).length) return string
var RE_VARS = variables.compile(map)
var _prev
while (_prev !== string) string = (_prev = string).replace(RE_VARS, replacer)
var RE_FALLBACKS = /\bvar\(--([\w-]+)(?:\s*,\s*)?(.*)?\)/
var m_fallback
while (m_fallback = RE_FALLBACKS.exec(string))
string = string.replace(m_fallback[0],
map[m_fallback[1]] ? m_fallback[1] : m_fallback[2])
return string
function replacer(match, name) {
return map[name] || match
}
}