-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.mjs
More file actions
220 lines (198 loc) · 6.83 KB
/
Copy pathindex.mjs
File metadata and controls
220 lines (198 loc) · 6.83 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import selectorParser from "postcss-selector-parser";
/**
* FomanticUI ships two variants of every component, a light default and a
* dark `.inverted` variant, both in the same stylesheet. This plugin
* extracts every rule that references `.inverted`, strips that class from the
* selector, and wraps the result inside a high-specificity theme selector. This
* provides a transformed FUI theme that can be layered on top of an existing
* theme so that when a browser or system prefers a dark color scheme, the
* inverted styles take precedence over the non-inverted styles.
*
* The output contains only the dark rules, scoped behind
* `html[data-theme="dark"]:not(#_)`. There is no duplication of the light
* styles, the original stylesheet provides those on its own.
*/
class PostCSSFomanticDarkPlugin {
// Configuration options
/**
* When true, each output rule is preceded by a CSS comment listing the
* original selector(s) it was derived from. Useful for debugging which
* source rules produced which output rules.
* @type {boolean}
*/
verbose = false;
/**
* Selectors that activate dark mode:
*
* - `html[data-theme="dark"]` -- Explicit dark theme
* - `html[data-theme="system"]`-- Dark theme only if `prefers-color-scheme`
* - `:host([…])` variants -- the same, but inside web component shadow DOM
*
* The `:not(#_)` suffix raises selector specificity to exceed the base theme
* selector specificities.
*/
static darkSelectors = [
'html[data-theme="dark"]:not(#_)',
'html[data-theme="system"]:not(#_)',
':host([data-theme="dark"]:not(#_))',
':host([data-theme="system"]:not(#_))',
].join(",\n");
constructor(options = {}) {
this.verbose = !!options.verbose;
this.postcssPlugin = "postcss-fomanticui-dark";
this.merged = new Map();
this.sourceList = new Map();
this.seenKeys = new Map();
this.sourceNode = new Map();
this.Rule = this.Rule.bind(this);
this.OnceExit = this.OnceExit.bind(this);
}
/**
* Accumulate transforms for inverted rules
*
* Rules targeting the same selector (after `.inverted`
* is removed) are merged into a single output bucket. Within each bucket,
* duplicate declarations (same property, value, specificity) are collapsed to
* keep the output as small as possible.
*
* Each individual selector in a comma-separated rule is evaluated
* independently.
*/
Rule(rule) {
// Don't process at-child nested rules, like rules in ``@media``
if (rule.parent.type !== "root") return;
const selectors = rule.selectors;
const transformed = [];
// Only select rules that have correct inverted class
for (const selector of selectors) {
if (!this.hasInverted(selector)) continue;
const stripped = this.stripInverted(selector);
if (stripped === selector) continue;
transformed.push(stripped);
}
if (transformed.length === 0) return;
const key = transformed.join(",\n");
// Avoid duplication of rules by tracking the selectors and values we've
// already processed.
if (!this.merged.has(key)) {
this.merged.set(key, []);
this.sourceList.set(key, []);
this.seenKeys.set(key, new Set());
this.sourceNode.set(key, rule);
}
this.sourceList.get(key).push(rule.selector);
const declarations = this.merged.get(key);
const seen = this.seenKeys.get(key);
rule.walkDecls((declaration) => {
const key = `${declaration.prop}:${declaration.value}${declaration.important ? "!important" : ""}`;
if (seen.has(key)) return;
seen.add(key);
declarations.push({
prop: declaration.prop,
value: declaration.value,
important: declaration.important,
});
});
}
/**
* Emit the collected dark rules.
*
* Replaces the entire stylesheet with a single wrapper rule scoped behind
* the dark-theme selectors, containing the merged output rules.
*/
OnceExit(root, { rule: makeRule, decl: makeDecl, comment: makeComment }) {
root.removeAll();
if (this.merged.size === 0) return;
const wrapper = makeRule({
selector: PostCSSFomanticDarkPlugin.darkSelectors,
});
for (const [selector, declarations] of this.merged) {
if (this.verbose) {
const originals = this.sourceList.get(selector);
if (originals.length) {
const note = makeComment({
text: ` from: ${originals.join(", ")} `,
});
note.source = this.sourceNode.get(selector)?.source;
wrapper.append(note);
}
}
const outRule = makeRule({ selector });
const source = this.sourceNode.get(selector);
if (source) outRule.source = source.source;
for (const { prop, value, important } of declarations) {
const declaration = makeDecl({ prop, value });
if (important) declaration.important = true;
outRule.append(declaration);
}
wrapper.append(outRule);
}
root.append(wrapper);
}
/**
* Check whether a class node is inside a ``:not()`` pseudo-class.
*
* @param {string} classNode - Name of selector class
* @returns {boolean}
*/
isInsideNotPseudo(classNode) {
let node = classNode.parent;
while (node) {
if (node.type === "pseudo" && node.value === ":not") {
return true;
}
node = node.parent;
}
return false;
}
/**
* Check for inverted style selectors
*
* Check for ``.inverted`` classes in selectors, with the exception of selectors
* like ``:not(.ui.inverted.segment)`` as this selector would be for light theme
* elements, not inverted.
*
* @param {string} selectors - a single CSS selector (not comma-separated)
* @returns {boolean}
*/
hasInverted(selectors) {
let found = false;
const parser = selectorParser((selectorsInner) => {
selectorsInner.walkClasses((classNode) => {
if (
classNode.value === "inverted" &&
!this.isInsideNotPseudo(classNode)
) {
found = true;
}
});
});
parser.processSync(selectors);
return found;
}
/**
* Strip inverted classes from usable selectors
*
* @param {string} selectors - a single CSS selector (not comma-separated)
* @returns {string} the selector with ``.inverted`` removed
*/
stripInverted(selectors) {
const parser = selectorParser((selectorsInner) => {
selectorsInner.walkClasses((classNode) => {
if (
classNode.value === "inverted" &&
!this.isInsideNotPseudo(classNode)
) {
classNode.remove();
}
});
});
return parser.processSync(selectors);
}
}
// Factory function, more standard for Webpack usage etc
export function postcssFomanticDarkPlugin(options) {
return new PostCSSFomanticDarkPlugin(options);
}
postcssFomanticDarkPlugin.postcss = true;
export default postcssFomanticDarkPlugin;