-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (67 loc) · 2.14 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import postcss from "postcss";
import {tokenRegex} from "./lib/tokenRegex";
function getKeyword(root) {
let keywords = [];
// Look for every keyword definition
root.walkAtRules("value", rule => {
// Create object so can look for keywords in CSS
let keyword = {};
let propsArray = [];
let propertyThing = /property\((.+)\)/;
rule.each(decl => {
// Grab value
if (decl.prop === "value") {
keyword.value = decl.value;
}
// Grab array of properties
if (rule.params.match(propertyThing)) {
let array = rule.params.match(propertyThing)[1].split(",");
for (let i = 0; i < array.length; i++) {
propsArray.push(array[i].trim())
}
}
});
// Create regex to allow matching of properties
keyword.props = new RegExp(propsArray.join("|"), 'i');
// Create regex to replace instances of word in declaration value
let nameString = rule.params.toString();
let name = nameString.replace(propertyThing, "").trim();
keyword.name = tokenRegex(name);
keywords.push(keyword);
});
// Reverse array so that keyword definitions that are declared later in document overide earlier rules
keywords.reverse();
return keywords;
}
export default postcss.plugin("postcss-custom-value", () => {
return root => {
// console.log("root, result", root, result);
const keywords = getKeyword(root);
// For each keyword definition
for (let i = 0; i < keywords.length; i++) {
let keyword = keywords[i];
// For each declration with matching properties
root.walkDecls(keyword.props, decl => {
// If value
if (decl.value.match(keyword.name)) {
// Replace instances of keyword name with correct value
var array1 = postcss.list.space(decl.value);
for (let b = 0; b < array1.length; b++) {
if (array1[b].match(keyword.name)) {
if (keyword.value.match(/\$0/gi)) {
array1[b] = keyword.value.replace(/\$0/gi, array1[b].match(keyword.name)[1]);
}
else {
array1[b] = array1[b].replace(keyword.name, keyword.value);
}
}
}
decl.value = array1.join(" ");
}
});
}
root.walkAtRules("value", rule => {
rule.remove();
});
};
});