/
keyframes.js
62 lines (51 loc) · 1.82 KB
/
keyframes.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
import valueParser from "postcss-value-parser";
import addToCache from "./cache";
const RESERVED_KEYWORDS = [
"none", "inherit", "initial", "unset",
];
export default function () {
let cache = {};
let atRules = [];
let decls = [];
return {
collect (node, encoder) {
const {name, prop, type} = node;
if (
type === 'atrule' &&
/keyframes/i.test(name) &&
RESERVED_KEYWORDS.indexOf(node.params.toLowerCase()) === -1
) {
addToCache(node.params, encoder, cache);
atRules.push(node);
}
if (type === 'decl' && /animation/i.test(prop)) {
decls.push(node);
}
},
transform () {
let referenced = [];
// Iterate each property and change their names
decls.forEach(decl => {
decl.value = valueParser(decl.value).walk(node => {
if (node.type === 'word' && node.value in cache) {
if (!~referenced.indexOf(node.value)) {
referenced.push(node.value);
}
cache[node.value].count++;
node.value = cache[node.value].ident;
}
}).toString();
});
// Iterate each at rule and change their name if references to them have been found
atRules.forEach(rule => {
const cached = cache[rule.params];
if (cached && cached.count > 0 && !!~referenced.indexOf(rule.params)) {
rule.params = cached.ident;
}
});
// reset cache after transform
atRules = [];
decls = [];
},
};
}