|
1 | 1 | import postcss from 'postcss';
|
2 |
| -import deepAssign from 'deep-assign'; |
| 2 | +import {merge as assign} from 'lodash'; |
3 | 3 |
|
4 |
| -const VAR_FUNC_IDENTIFIER = 'var'; |
5 |
| -const maps = {}; |
| 4 | +function hasVar(str) { |
| 5 | + return str.indexOf('var('); |
| 6 | +} |
6 | 7 |
|
7 |
| -function resolveValue(value) { |
8 |
| - const hasVar = value.indexOf(`${VAR_FUNC_IDENTIFIER}(`); |
9 |
| - if (hasVar === -1) { |
| 8 | +function resolveValue(value, maps) { |
| 9 | + if (hasVar(value) === -1) { |
10 | 10 | return value;
|
11 | 11 | }
|
12 | 12 |
|
13 | 13 | return value.replace(/var\(--.*?\)/g, (match) => maps[match.slice(4, -1)] || match);
|
14 | 14 | }
|
15 | 15 |
|
| 16 | +function getProperty(nodes) { |
| 17 | + let propertys = {}; |
| 18 | + |
| 19 | + nodes.walkRules(rule => { |
| 20 | + if (rule.selector !== ':root') { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + rule.each(decl => { |
| 25 | + const {prop, value} = decl; |
| 26 | + propertys[prop] = value; |
| 27 | + }); |
| 28 | + }); |
| 29 | + |
| 30 | + return propertys; |
| 31 | +} |
| 32 | + |
16 | 33 | export default postcss.plugin('postcss-at-rules-variables', options => {
|
17 | 34 | const DEFAULT = {
|
18 | 35 | atRules: ['for', 'if', 'else', 'each']
|
19 | 36 | };
|
20 | 37 |
|
21 |
| - const mergeOptions = deepAssign(DEFAULT, options, (a, b) => { |
| 38 | + options = assign(DEFAULT, options, (a, b) => { |
22 | 39 | if (Array.isArray(a)) {
|
23 | 40 | return a.concat(b);
|
24 | 41 | }
|
25 | 42 | });
|
26 | 43 |
|
27 | 44 | return nodes => {
|
28 |
| - const reg = new RegExp(mergeOptions.atRules.join('|')); |
29 |
| - |
30 |
| - nodes.walkRules(rule => { |
31 |
| - if (rule.selector !== ':root') { |
32 |
| - return; |
33 |
| - } |
34 |
| - |
35 |
| - rule.each(decl => { |
36 |
| - const prop = decl.prop; |
37 |
| - const value = decl.value; |
38 |
| - maps[prop] = value; |
39 |
| - }); |
40 |
| - }); |
| 45 | + const maps = getProperty(nodes); |
| 46 | + const {atRules} = options; |
41 | 47 |
|
42 |
| - nodes.walkAtRules(reg, rules => { |
43 |
| - rules.params = resolveValue(rules.params); |
| 48 | + nodes.walkAtRules(new RegExp(atRules.join('|')), rules => { |
| 49 | + rules.params = resolveValue(rules.params, maps); |
44 | 50 | });
|
45 | 51 | };
|
46 | 52 | });
|
0 commit comments