/
collect.ts
163 lines (139 loc) · 4.49 KB
/
collect.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import type { AtRule, ChildNode } from 'postcss';
import postcss from 'postcss';
type CollectResult = {
critical: string;
other: string;
};
interface ClassnameModifiers {
ignoredClasses?: string[];
blockedClasses?: string[];
}
/**
* Used to escape `RegExp`
* [syntax characters](https://262.ecma-international.org/7.0/#sec-regular-expressions-patterns).
*/
function escapeRegex(string: string) {
return string.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
}
const extractClassesFromHtml = (
html: string,
ignoredClasses: string[]
): RegExp => {
const htmlClasses: string[] = [];
const regex = /\s+class="([^"]+)"/gm;
let match = regex.exec(html);
const ignoredClassesDeduped = new Set(ignoredClasses);
while (match !== null) {
match[1].split(' ').forEach((className) => {
// eslint-disable-next-line no-param-reassign
className = escapeRegex(className);
if (className !== '' && !ignoredClassesDeduped.has(className)) {
htmlClasses.push(className);
}
});
match = regex.exec(html);
}
return new RegExp(htmlClasses.join('|'), 'gm');
};
/**
* This utility extracts critical CSS from given HTML and CSS file to be used in SSR environments
* @param {string} html the HTML from which classes will be parsed
* @param {string} css the CSS file from which selectors will be parsed and determined as critical or other
* @param {string[]} ignoredClasses classes that, when present in the HTML, will not be included in the regular expression used to match selectors
* @param {string[]} blockedClasses classes that, when contained in a selector, will cause the selector to be marked as not critical
* @returns {CollectResult} object containing the critical and other CSS styles
*/
export default function collect(
html: string,
css: string,
classnameModifiers?: ClassnameModifiers
): CollectResult {
const animations = new Set();
const other = postcss.root();
const critical = postcss.root();
const stylesheet = postcss.parse(css);
const ignoredClasses = classnameModifiers?.ignoredClasses ?? [];
const blockedClasses = classnameModifiers?.blockedClasses ?? [];
const htmlClassesRegExp = extractClassesFromHtml(html, ignoredClasses);
const blockedClassesSanitized = blockedClasses.map(escapeRegex);
const blockedClassesRegExp = new RegExp(
blockedClassesSanitized.join('|'),
'gm'
);
const isCritical = (rule: ChildNode) => {
// Only check class names selectors
if ('selector' in rule && rule.selector.startsWith('.')) {
const isExcluded =
blockedClasses.length > 0 && blockedClassesRegExp.test(rule.selector);
if (isExcluded) return false;
return Boolean(rule.selector.match(htmlClassesRegExp));
}
return true;
};
const handleAtRule = (rule: AtRule) => {
if (rule.name === 'keyframes') {
return;
}
const criticalRule = rule.clone();
const otherRule = rule.clone();
let removedNodesFromOther = 0;
criticalRule.each((childRule: ChildNode, index: number) => {
if (isCritical(childRule)) {
otherRule.nodes[index - removedNodesFromOther]?.remove();
removedNodesFromOther += 1;
} else {
childRule.remove();
}
});
rule.remove();
if (criticalRule.nodes.length > 0) {
critical.append(criticalRule);
}
if (otherRule.nodes.length > 0) {
other.append(otherRule);
}
};
stylesheet.walkAtRules('font-face', (rule) => {
/**
* @font-face rules may be defined also in CSS conditional groups (eg. @media)
* we want only handle those from top-level, rest will be handled in stylesheet.walkRules
*/
if (rule.parent?.type === 'root') {
critical.append(rule);
}
});
const walkedAtRules = new Set();
stylesheet.walkRules((rule) => {
if (
rule.parent &&
'name' in rule.parent &&
(rule.parent as { name: string }).name === 'keyframes'
) {
return;
}
if (rule.parent?.type === 'atrule') {
if (!walkedAtRules.has(rule.parent)) {
handleAtRule(rule.parent as AtRule);
walkedAtRules.add(rule.parent);
}
return;
}
if (isCritical(rule)) {
critical.append(rule);
} else {
other.append(rule);
}
});
critical.walkDecls(/animation/, (decl) => {
animations.add(decl.value.split(' ')[0]);
});
stylesheet.walkAtRules('keyframes', (rule) => {
if (animations.has(rule.params)) {
critical.append(rule);
}
});
return {
critical: critical.toString(),
other: other.toString(),
};
}