This repository has been archived by the owner on Feb 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 77
/
get-custom-properties-from-root.js
58 lines (47 loc) · 1.99 KB
/
get-custom-properties-from-root.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
import { parse } from 'postcss-values-parser';
import { isBlockIgnored } from './is-ignored';
// return custom selectors from the css root, conditionally removing them
export default function getCustomPropertiesFromRoot(root, opts) {
// initialize custom selectors
const customPropertiesFromHtmlElement = {};
const customPropertiesFromRootPseudo = {};
// for each html or :root rule
root.nodes.slice().forEach(rule => {
const customPropertiesObject = isHtmlRule(rule)
? customPropertiesFromHtmlElement
: isRootRule(rule)
? customPropertiesFromRootPseudo
: null;
// for each custom property
if (customPropertiesObject) {
rule.nodes.slice().forEach(decl => {
if (isCustomDecl(decl) && !isBlockIgnored(decl)) {
const { prop } = decl;
// write the parsed value to the custom property
customPropertiesObject[prop] = parse(decl.value).nodes;
// conditionally remove the custom property declaration
if (!opts.preserve) {
decl.remove();
}
}
});
// conditionally remove the empty html or :root rule
if (!opts.preserve && isEmptyParent(rule) && !isBlockIgnored(rule)) {
rule.remove();
}
}
});
// return all custom properties, preferring :root properties over html properties
return { ...customPropertiesFromHtmlElement, ...customPropertiesFromRootPseudo };
}
// match html and :root rules
const htmlSelectorRegExp = /^html$/i;
const rootSelectorRegExp = /^:root$/i;
const customPropertyRegExp = /^--[A-z][\w-]*$/;
// whether the node is an html or :root rule
const isHtmlRule = node => node.type === 'rule' && htmlSelectorRegExp.test(node.selector) && Object(node.nodes).length;
const isRootRule = node => node.type === 'rule' && rootSelectorRegExp.test(node.selector) && Object(node.nodes).length;
// whether the node is an custom property
const isCustomDecl = node => node.type === 'decl' && customPropertyRegExp.test(node.prop);
// whether the node is a parent without children
const isEmptyParent = node => Object(node.nodes).length === 0;