forked from mantinedev/postcss-preset-mantine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostcss-light-dark.js
64 lines (51 loc) · 1.71 KB
/
postcss-light-dark.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
const postcss = require('postcss');
const FUNCTION = 'light-dark(';
function splitStringAtCharacter(character, search) {
let characterIndex = 0;
let openedParentheses = 0;
while (
characterIndex < search.length &&
(search[characterIndex] !== character || openedParentheses)
) {
if (search[characterIndex] === '(') {
openedParentheses += 1;
}
if (search[characterIndex] === ')') {
openedParentheses -= 1;
}
characterIndex += 1;
}
return [search.slice(0, characterIndex), search.slice(characterIndex + 1)];
}
function getLightDarkValue(value) {
const [prefix, ...search] = value.split(FUNCTION);
if (!search.length) {
return { light: value, dark: value };
}
const [macro, suffix] = splitStringAtCharacter(')', search.join(FUNCTION));
const [light, dark] = splitStringAtCharacter(',', macro);
const parsedSuffix = getLightDarkValue(suffix);
return {
light: prefix + getLightDarkValue(light.trim()).light + parsedSuffix.light,
dark: prefix + getLightDarkValue(dark.trim()).dark + parsedSuffix.dark,
};
}
module.exports = () => {
return {
postcssPlugin: 'postcss-light-dark',
Once(root) {
root.walkDecls((decl) => {
const { value, prop } = decl;
if (value.includes('light-dark')) {
const { light: lightVal, dark: darkVal } = getLightDarkValue(value);
const darkMixin = postcss.atRule({ name: 'mixin', params: 'dark' });
darkMixin.append(postcss.decl({ prop, value: darkVal }));
decl.parent.insertAfter(decl, darkMixin);
decl.parent.insertAfter(decl, postcss.decl({ prop, value: lightVal }));
decl.remove();
}
});
},
};
};
module.exports.postcss = true;