-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (47 loc) · 2.02 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
const postcss = require("postcss");
module.exports = postcss.plugin('dash-dash', () => {
return (css, result) => {
let prevRule = null;
css.walkRules(rule => {
const rulesWithDashDash = rule.selectors.filter(
selector => /^(.+ )?--[a-z]\w*(-[a-z0-9]+)*--$/.test(selector)
);
if (rulesWithDashDash.length === 0) {
prevRule = rule;
return;
}
if (rule.selectors.length > 1 && rule.selectors.length > rulesWithDashDash) {
throw new Error('Something went wrong, -- should be on all the selectors' . rule.selectors.join());
}
const parts = rule.selectors[0].split(' ');
parts.reverse();
const prefix = parts[0];
console.log(prefix);
const newDecls = [];
rule.walkDecls(decl=> {
const newDecl = postcss.decl({
prop: decl.prop,
value: `var(${prefix}${decl.prop}, ${decl.value})`,
});
newDecls.push(newDecl);
decl.remove();
});
const expectedTargetSelectors = rule.selectors.map(selector=> selector.replace(` ${ prefix }`, ''))
const expectedTargetSelector = expectedTargetSelectors.join();
if (prevRule && prevRule.parent === rule.parent && prevRule.selectors.join() === expectedTargetSelector) {
console.log('FOUND EXISTING: ', prevRule.selectors.join());
prevRule.append(newDecls);
} else {
console.log('CREATING NEW', !prevRule ? 'prev rule is null' : expectedTargetSelector);
const newRule = postcss.rule({
selectors: expectedTargetSelectors,
source: rule.source,
});
newRule.append(...newDecls);
rule.after(newRule);
rule.remove();
prevRule = newRule;
}
})
}
})