Skip to content

Commit 3badc9c

Browse files
committed
fix: circular reference, close #181
1 parent 7e7c178 commit 3badc9c

File tree

1 file changed

+31
-24
lines changed

1 file changed

+31
-24
lines changed

src/index.js

Lines changed: 31 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,47 @@
11
import postcss from 'postcss';
22

33
function hasVar(str) {
4-
return str.includes('var(');
4+
return str.includes('var(');
55
}
66

77
function resolveValue(value, maps) {
8-
return hasVar(value) ? value.replace(/var\(--.*?\)/g, match => maps[match.slice(4, -1)] || match) : value;
8+
return hasVar(value) ? value.replace(/var\(--.*?\)/g, match => maps[match.slice(4, -1)] || match) : value;
99
}
1010

1111
function getProperty(nodes) {
12-
let propertys = {};
12+
let propertys = {};
1313

14-
nodes.walkRules(rule => {
15-
if (rule.selector !== ':root') {
16-
return;
17-
}
14+
nodes.walkRules(rule => {
15+
if (rule.selector !== ':root') {
16+
return;
17+
}
1818

19-
rule.each(({prop, value}) => {
20-
propertys[prop] = value;
21-
});
22-
});
19+
rule.each(({prop, value}) => {
20+
propertys[prop] = value;
21+
});
22+
});
2323

24-
return propertys;
24+
return propertys;
25+
}
26+
27+
function circularReference(maps) {
28+
return Object.keys(maps).reduce((prevMaps, property) => {
29+
prevMaps[property] = resolveValue(maps[property], maps);
30+
return prevMaps;
31+
}, maps);
2532
}
2633

2734
export default postcss.plugin('postcss-at-rules-variables', (options = {}) => {
28-
options = {
29-
atRules: [...new Set(['for', 'if', 'else', 'each', 'mixin', 'custom-media', ...options.atRules || ''])],
30-
variables: options.variables || {}
31-
};
32-
33-
return nodes => {
34-
const maps = Object.assign(getProperty(nodes), options.variables);
35-
36-
nodes.walkAtRules(new RegExp(options.atRules.join('|')), rules => {
37-
rules.params = resolveValue(rules.params, maps);
38-
});
39-
};
35+
options = {
36+
atRules: [...new Set(['for', 'if', 'else', 'each', 'mixin', 'custom-media', ...options.atRules || ''])],
37+
variables: options.variables || {}
38+
};
39+
40+
return nodes => {
41+
const maps = circularReference(Object.assign(getProperty(nodes), options.variables));
42+
43+
nodes.walkAtRules(new RegExp(options.atRules.join('|')), rules => {
44+
rules.params = resolveValue(rules.params, maps);
45+
});
46+
};
4047
});

0 commit comments

Comments
 (0)