-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (81 loc) · 2.34 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
91
92
93
94
const {name} = require('./package');
const fs = require('fs').promises;
const postcss = require('postcss');
const prefersReducedMotionValues = [
'no-preference',
'reduce'
];
function matchTargetProperty (atRule, value) {
const regExp = new RegExp('prefers-reduced-motion:\\s?' + value, 'g');
return atRule.params.match(regExp);
}
function containsConditionalGroupRules (rule) {
return ['media', 'supports', 'document'].includes(rule.name);
}
function isParentTypeRoot (rule) {
return !!(rule.parent && rule.parent.type === 'root');
}
function hasNodes (rule) {
return !!(rule.nodes && rule.nodes.length > 0);
}
async function writeFilePromise (filePath, data) {
let fileHandle = null;
try {
fileHandle = await fs.writeFile(filePath, data);
} finally {
}
}
module.exports = postcss.plugin(name, function (opts) {
const {value, exportTo} = opts || {};
return function (root, result) {
if (!prefersReducedMotionValues.indexOf(value)) {
result.warn('invalid prefer-reduced-motion value.');
}
if (!exportTo) {
result.warn('must set "exportTo" option.');
}
const valuesToKeep = prefersReducedMotionValues.filter((v) => {
return v !== value;
});
/**
* export file
*/
const exportFileRoot = root.clone();
exportFileRoot.walkRules((exportRule, i) => {
if (isParentTypeRoot(exportRule)) {
exportRule.remove();
exportRule.removeAll();
}
});
exportFileRoot.walkAtRules(exportAtRule => {
if (valuesToKeep) {
valuesToKeep.forEach((v) => {
if (matchTargetProperty(exportAtRule, v)) {
exportAtRule.remove();
exportAtRule.removeAll();
}
});
}
if (matchTargetProperty(exportAtRule, value) && hasNodes(exportAtRule)) {
exportAtRule.after(exportAtRule.nodes);
exportAtRule.remove();
exportAtRule.removeAll();
} else {
if (hasNodes(exportAtRule) && !containsConditionalGroupRules(exportAtRule)) {
exportAtRule.remove();
exportAtRule.removeAll();
}
}
});
writeFilePromise(exportTo, exportFileRoot).catch(console.error);
/**
* output file
*/
root.walkAtRules(atRule => {
if (matchTargetProperty(atRule, value)) {
atRule.remove();
atRule.removeAll();
}
});
};
});