This repository was archived by the owner on Apr 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
78 lines (66 loc) · 2 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
'use strict';
const _ = require('lodash');
const cheerio = require('cheerio');
const postcss = require('postcss');
const postcssDiscardEmpty = require('postcss-discard-empty');
const postcssDiscardUnused = require('postcss-discard-unused');
const selectorParser = require('postcss-selector-parser');
const htmlFilterPlugin = (options) => {
const query = cheerio.load(options.html);
const transformSelector = (selector) => {
selector.walkPseudos((pseudo) => {
// Keep all :root selectors.
if (pseudo.value === 'root') {
return;
}
pseudo.remove();
});
};
const transformRule = (rule) => {
let cleanedSelectors = [];
// Keep all keyframe selectors.
if (/keyframes/.test(_.get(rule, 'parent.name', ''))) return;
rule.selectors.forEach((selector) => {
const pseudolessSelector = selectorParser(transformSelector).processSync(
selector
);
if (!pseudolessSelector) {
cleanedSelectors.push(selector);
return;
}
let matchingElements;
try {
matchingElements = query(pseudolessSelector);
} catch (cheerioError) {
throw new Error(
`Cheerio failed to interpret the following selector:\n ${selector}`
);
}
if (matchingElements.length !== 0) {
cleanedSelectors.push(selector);
}
});
// Remove the rule if it no longer has applicable selectors.
if (cleanedSelectors.length === 0) {
rule.remove();
} else {
rule.selector = cleanedSelectors.join(', ');
}
};
return {
postcssPlugin: 'postcss-html-filter',
Once: (root) => {
root.walkRules(transformRule);
return root;
}
}
};
const combinedPlugin = (options) => {
return postcss([
htmlFilterPlugin(options),
postcssDiscardEmpty, // Discard any at-rules we've emptied of rules.
postcssDiscardUnused // Discard unused at-rules, e.g. counter-styles, keyframes, font-faces.
])
}
combinedPlugin.postcss = true
module.exports = combinedPlugin;