forked from discord/postcss-theme-shorthand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (53 loc) · 1.98 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
66
const postcss = require('postcss');
module.exports = postcss.plugin('postcss-theme-shorthand', () => {
const ThemedPropRegExp = /^(light|dark)-/;
const LightThemeRegExp = /^light-/g;
const DarkThemeRegExp = /^dark-/g;
const LIGHT_THEME = '.theme-light';
const DARK_THEME = '.theme-dark';
// Holds a reference to the new css node for themeing,
// in case multiple light-/dark- props in a single selector
let currentLightNode;
let currentDarkNode;
function createNewNode(parent, selector) {
return parent.cloneBefore({ selector }).removeAll();
}
function addLightThemedStyle({ parent, prop, value, source }) {
const ruleSelectors = parent.selectors
.map(ruleSelector => `:global(${LIGHT_THEME}) ${ruleSelector}`)
.join(', ');
if (!currentLightNode || currentLightNode.selector !== ruleSelectors) {
currentLightNode = createNewNode(parent, ruleSelectors);
}
currentLightNode.append({
prop: prop.replace(LightThemeRegExp, ''),
value,
source
});
}
function addDarkThemedStyle({ parent, prop, value, source }) {
const ruleSelectors = parent.selectors
.map(ruleSelector => `:global(${DARK_THEME}) ${ruleSelector}`)
.join(', ');
if (!currentDarkNode || currentDarkNode.selector !== ruleSelectors) {
currentDarkNode = createNewNode(parent, ruleSelectors);
}
currentDarkNode.append({
prop: prop.replace(DarkThemeRegExp, ''),
value,
source
});
}
function ruleHandler(decl) {
const { prop } = decl;
if (prop.match(LightThemeRegExp) !== null) {
addLightThemedStyle(decl);
} else if (prop.match(DarkThemeRegExp) !== null) {
addDarkThemedStyle(decl);
}
decl.remove();
}
return function (css) {
css.walkDecls(ThemedPropRegExp, ruleHandler);
};
});