-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathparseRule.js
More file actions
58 lines (52 loc) · 1.36 KB
/
parseRule.js
File metadata and controls
58 lines (52 loc) · 1.36 KB
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
const valueParser = require("postcss-value-parser");
function parseRuleDefinition(params) {
const { nodes } = valueParser(params);
if (
nodes.length !== 3 ||
nodes[0].type !== "word" ||
nodes[1].type !== "space" ||
nodes[2].type !== "function" ||
nodes[2].value !== "url" ||
nodes[2].nodes.length === 0
) {
throw Error('Invalid "@svg-load" definition');
}
return {
name: nodes[0].value,
url: nodes[2].nodes[0].value,
};
}
function getRuleParams(rule, variables) {
const params = {};
const selectors = {};
rule.each((node) => {
if (node.type === "decl") {
params[node.prop] = resolveValue(node.value, variables);
} else if (node.type === "rule") {
const selector = selectors[node.selectors] || {};
node.each((child) => {
if (child.type === "decl") {
selector[child.prop] = resolveValue(child.value, variables);
}
});
selectors[node.selectors] = selector;
}
});
return {
params,
selectors,
};
}
function resolveValue(value, variables) {
if (typeof value === "string" && value.startsWith("var(")) {
const name = value.replace("var(", "").replace(")", "");
if (Object.hasOwn(variables, name)) {
value = resolveValue(variables[name], variables);
}
}
return value;
}
module.exports = {
parseRuleDefinition,
getRuleParams,
};