-
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathindex.ts
More file actions
185 lines (149 loc) · 5.87 KB
/
index.ts
File metadata and controls
185 lines (149 loc) · 5.87 KB
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
import selectorParser from 'postcss-selector-parser';
import { selectorSpecificity } from '@csstools/selector-specificity';
import type { Container, AtRule, PluginCreator, Result } from 'postcss';
import { Model } from './model';
import { adjustSelectorSpecificity } from './adjust-selector-specificity';
import { desugarAndParseLayerNames } from './desugar-and-parse-layer-names';
import { desugarNestedLayers } from './desugar-nested-layers';
import { getLayerAtRuleAncestor } from './get-layer-atrule-ancestor';
import { someAtRuleInTree } from './some-in-tree';
import { sortRootNodes } from './sort-root-nodes';
import { recordLayerOrder } from './record-layer-order';
import { ATRULES_WITH_NON_SELECTOR_BLOCK_LISTS, HAS_LAYER_REGEX, INVALID_LAYER_NAME, IS_IMPORT_REGEX, IS_LAYER_REGEX, IS_REVERT_LAYER_REGEX } from './constants';
import { splitImportantStyles } from './split-important-styles';
import type { pluginOptions } from './options';
import { isProcessableLayerRule } from './is-processable-layer-rule';
export type { pluginOptions } from './options';
const creator: PluginCreator<pluginOptions> = (opts?: pluginOptions) => {
const options = Object.assign({
onRevertLayerKeyword: 'warn',
onConditionalRulesChangingLayerOrder: 'warn',
onImportLayerRule: 'warn',
}, opts);
return {
postcssPlugin: 'postcss-cascade-layers',
OnceExit(root: Container, { result }: { result: Result }): void {
let hasAnyLayer = false;
root.walk((node) => {
if (node.type === 'decl') {
if (options.onRevertLayerKeyword && IS_REVERT_LAYER_REGEX.test(node.value)) {
node.warn(result, 'handling "revert-layer" is unsupported by this plugin and will cause style differences between browser versions.');
return;
}
return;
}
if (node.type === 'atrule') {
if (options.onImportLayerRule && IS_IMPORT_REGEX.test(node.name) && HAS_LAYER_REGEX.test(node.params)) {
node.warn(result, 'To use @import with layers, the postcss-import plugin is also required. This plugin alone will not support using the @import at-rule.');
return;
}
if (IS_LAYER_REGEX.test(node.name)) {
hasAnyLayer = true;
return;
}
return;
}
});
if (!hasAnyLayer) {
return;
}
splitImportantStyles(root);
const model = new Model();
desugarAndParseLayerNames(root, model);
recordLayerOrder(root, model, { result, options });
if (!model.layerCount) {
// Reset "invalid-layer" at rules
root.walkAtRules(INVALID_LAYER_NAME, (layerRule) => {
layerRule.name = 'layer';
});
// no layers, so nothing to transform.
return;
}
// record selector specificity
let highestASpecificity = 0;
root.walkRules((rule) => {
rule.selectors.forEach((selector) => {
try {
const specificity = selectorSpecificity(selectorParser().astSync(selector));
highestASpecificity = Math.max(highestASpecificity, specificity.a + 1);
} catch (err) {
rule.warn(result, `Failed to parse selector : "${selector}" with message: "${(err instanceof Error) ? err.message : err}"`);
}
});
});
// transform unlayered styles - need highest specificity (layerCount)
root.walkRules((rule) => {
// Skip any at rules that do not contain regular declarations (@keyframes)
if (rule.parent && rule.parent.type === 'atrule' && ATRULES_WITH_NON_SELECTOR_BLOCK_LISTS.includes((rule.parent as AtRule).name.toLowerCase())) {
return;
}
if (getLayerAtRuleAncestor(rule)) {
return;
}
if (rule.some((decl) => decl.type === 'decl' && decl.important)) {
// !important declarations have inverse priority in layers
// doing nothing will give the lowest specificity
return;
}
rule.selectors = rule.selectors.map((selector) => {
try {
return adjustSelectorSpecificity(selector, model.layerCount * highestASpecificity);
} catch (err) {
rule.warn(result, `Failed to parse selector : "${selector}" with message: "${(err instanceof Error) ? err.message : err}"`);
}
return selector;
});
});
// Sort layer names
model.sortLayerNames();
// Desugar nested layers
desugarNestedLayers(root, model);
// Transform order of CSS
// - split selector rules from non-selector rules
// - sort non-selector rules
sortRootNodes(root, model);
// transform layered styles:
// - give selectors the specificity they need based on layerPriority state
root.walkRules((rule) => {
// Skip any at rules that do not contain regular declarations (@keyframes)
if (rule.parent && rule.parent.type === 'atrule' && ATRULES_WITH_NON_SELECTOR_BLOCK_LISTS.includes((rule.parent as AtRule).name.toLowerCase())) {
return;
}
const layerForCurrentRule = getLayerAtRuleAncestor(rule);
if (!layerForCurrentRule) {
return;
}
const fullLayerName = model.getLayerParams(layerForCurrentRule).join('.');
const layerOrder = model.layerOrder.get(fullLayerName) ?? 0;
let specificityAdjustment = layerOrder * highestASpecificity;
if (rule.some((decl) => decl.type === 'decl' && decl.important)) {
// !important declarations have inverse priority in layers
specificityAdjustment = model.layerCount - specificityAdjustment;
}
rule.selectors = rule.selectors.map((selector) => {
return adjustSelectorSpecificity(selector, specificityAdjustment);
});
});
// Remove all @layer at-rules
// Contained styles are inserted before
while (someAtRuleInTree(root, (node) => isProcessableLayerRule(node))) {
root.walkAtRules((atRule) => {
if (!isProcessableLayerRule(atRule)) {
return;
}
if (atRule.nodes) {
atRule.replaceWith(atRule.nodes);
} else {
atRule.remove();
}
});
}
// Reset "invalid-layer" at rules
root.walkAtRules(INVALID_LAYER_NAME, (atRule) => {
atRule.name = 'layer';
});
},
};
};
creator.postcss = true;
export default creator;