/
grid-template.js
70 lines (60 loc) · 2.47 KB
/
grid-template.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
import valueParser from "postcss-value-parser";
import addToCache from "./cache";
import isNum from "./isNum";
const RESERVED_KEYWORDS = [
"auto", "span", "inherit", "initial", "unset",
];
export default function () {
let cache = {};
let declCache = [];
return {
collect (node, encoder) {
if (node.type !== 'decl') {
return;
}
if (/(grid-template|grid-template-areas)/i.test(node.prop)) {
valueParser(node.value).walk(child => {
if (child.type === 'string') {
child.value.split(/\s+/).forEach(word => {
if (/\.+/.test(word)) { // reduce empty zones to a single `.`
node.value = node.value.replace(word, ".");
} else if (word && RESERVED_KEYWORDS.indexOf(word.toLowerCase()) === -1) {
addToCache(word, encoder, cache);
}
});
}
});
declCache.push(node);
} else if (node.prop.toLowerCase() === 'grid-area') {
valueParser(node.value).walk(child => {
if (child.type === 'word' && RESERVED_KEYWORDS.indexOf(child.value) === -1) {
addToCache(child.value, encoder, cache);
}
});
declCache.push(node);
}
},
transform () {
declCache.forEach(decl => {
decl.value = valueParser(decl.value).walk(node => {
if (/(grid-template|grid-template-areas)/i.test(decl.prop)) {
node.value.split(/\s+/).forEach(word => {
if (word in cache) {
node.value = node.value.replace(word, cache[word].ident);
}
});
node.value = node.value.replace(/\s+/g, " "); // merge white-spaces
}
if (decl.prop.toLowerCase() === 'grid-area' && !isNum(node)) {
if (node.value in cache) {
node.value = cache[node.value].ident;
}
}
return false;
}).toString();
});
// reset cache after transform
declCache = [];
},
};
}