rollup-plugin-react-scoped-css 1.2.6 → 1.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/css/scope-css.js +287 -50
  2. package/package.json +1 -1
@@ -1,41 +1,103 @@
1
- import { parse, generate, } from "css-tree";
1
+ import { parse, generate, List, } from "css-tree";
2
2
  /**
3
3
  * Keyframe selectors (`from`, `to`, `50%`) are also parsed as `Rule` nodes with
4
4
  * a `SelectorList` prelude. They need to be left alone, otherwise animations
5
5
  * break by becoming e.g. `0%[data-hash]`.
6
6
  */
7
7
  const isKeyframesAtRule = (name) => /^(-[a-z0-9]+-)?keyframes$/i.test(name);
8
- const getSelectors = (items) => {
9
- const selectorLists = [];
10
- items.forEach((node) => {
11
- if (node.type === "Rule" && node.prelude?.type === "SelectorList") {
12
- selectorLists.push(node.prelude.children);
13
- }
14
- else if (node.type === "Atrule" &&
15
- node.block &&
16
- !isKeyframesAtRule(node.name)) {
17
- // Recurse into conditional/group at-rules (`@media`, `@container`,
18
- // `@supports`, `@layer`, `@scope`, etc.) so their rules get scoped too.
19
- selectorLists.push(...getSelectors(node.block.children));
8
+ const isScopePiercingPseudoSelector = (node) => node.type === "PseudoElementSelector" &&
9
+ (node.name === "v-deep" || node.name === "deep");
10
+ /**
11
+ * CSS-tree parses the contents of `:deep(...)` as a `Raw` node, unlike
12
+ * `:is()`/`:where()` which it parses as selectors.
13
+ */
14
+ const isDeepFunctionSelector = (node) => node.type === "PseudoClassSelector" &&
15
+ (node.name === "deep" || node.name === "v-deep") &&
16
+ !!node.children;
17
+ /**
18
+ * Pseudo selectors that refer to the document root. They cannot be scoped
19
+ * because the root element never receives the scope attribute, so adding the
20
+ * attribute would only turn working rules into dead ones.
21
+ */
22
+ const isRootLikePseudoSelector = (node) => node.type === "PseudoClassSelector" &&
23
+ (node.name.toLowerCase() === "root" || node.name.toLowerCase() === "scope");
24
+ const isCombinator = (node) => node.type === "Combinator";
25
+ const isNestingSelector = (node) => node.type === "NestingSelector";
26
+ /**
27
+ * Simple selectors that can receive the scope attribute. `&` is excluded
28
+ * because the parent rule is already scoped, so `&[hash]` would be redundant.
29
+ */
30
+ const isHashableSelector = (node) => node.type === "TypeSelector" ||
31
+ node.type === "ClassSelector" ||
32
+ node.type === "IdSelector" ||
33
+ node.type === "AttributeSelector";
34
+ const getDeepFunctionSelectorText = (node) => {
35
+ const children = node.children;
36
+ if (!children || children.isEmpty) {
37
+ return null;
38
+ }
39
+ let text = "";
40
+ children.forEach((child) => {
41
+ if (child.type === "Raw") {
42
+ text += child.value;
20
43
  }
21
44
  });
22
- return selectorLists;
23
- };
24
- const isScopePiercingPseudoSelector = (item) => {
25
- return (item?.data?.type === "PseudoElementSelector" &&
26
- (item?.data?.name === "v-deep" || item?.data?.name === "deep"));
27
- };
28
- const isPseudoSelector = (item) => {
29
- return (item?.data?.type === "PseudoClassSelector" ||
30
- item?.data?.type === "PseudoElementSelector");
45
+ return text || null;
31
46
  };
32
- const isCombinator = (item) => {
33
- return item?.data?.type === "Combinator";
47
+ /**
48
+ * Splits a raw selector prelude on top-level `||` (column combinator) while
49
+ * ignoring `||` inside attribute selectors, functional pseudos, or strings.
50
+ */
51
+ const splitOnColumnCombinator = (value) => {
52
+ const parts = [];
53
+ let start = 0;
54
+ let parenthesisDepth = 0;
55
+ let bracketDepth = 0;
56
+ let quote = null;
57
+ for (let index = 0; index < value.length; index += 1) {
58
+ const char = value[index];
59
+ if (quote) {
60
+ if (char === "\\") {
61
+ index += 1;
62
+ }
63
+ else if (char === quote) {
64
+ quote = null;
65
+ }
66
+ continue;
67
+ }
68
+ if (char === '"' || char === "'") {
69
+ quote = char;
70
+ }
71
+ else if (char === "\\") {
72
+ index += 1;
73
+ }
74
+ else if (char === "(") {
75
+ parenthesisDepth += 1;
76
+ }
77
+ else if (char === ")") {
78
+ parenthesisDepth -= 1;
79
+ }
80
+ else if (char === "[") {
81
+ bracketDepth += 1;
82
+ }
83
+ else if (char === "]") {
84
+ bracketDepth -= 1;
85
+ }
86
+ else if (char === "|" &&
87
+ value[index + 1] === "|" &&
88
+ parenthesisDepth === 0 &&
89
+ bracketDepth === 0) {
90
+ parts.push(value.slice(start, index));
91
+ index += 1;
92
+ start = index + 1;
93
+ }
94
+ }
95
+ parts.push(value.slice(start));
96
+ return parts;
34
97
  };
35
98
  export function scopeCss(css, filename, hash, source = filename) {
36
99
  try {
37
100
  const ast = parse(css, { positions: true, filename: source });
38
- const selectorLists = getSelectors(ast.children);
39
101
  const attributeSelector = {
40
102
  type: "AttributeSelector",
41
103
  name: { type: "Identifier", name: hash },
@@ -43,40 +105,215 @@ export function scopeCss(css, filename, hash, source = filename) {
43
105
  value: null,
44
106
  flags: null,
45
107
  };
46
- selectorLists.forEach((selectorList) => {
47
- selectorList.forEach((selector) => {
48
- if (selector.type !== "Selector") {
108
+ const scopeSelectorList = (selectorLists) => {
109
+ selectorLists.forEach((selector) => {
110
+ if (selector.type === "Selector") {
111
+ scopeSelector(selector);
112
+ }
113
+ });
114
+ };
115
+ /**
116
+ * Inserts the scope attribute after every consecutive run of simple
117
+ * selectors. Pseudo selectors break a run, which preserves the previous
118
+ * behaviour of `a:hover.b` becoming `a[hash]:hover.b[hash]`.
119
+ */
120
+ const scopeRuns = (items, selectorChildren) => {
121
+ let run = [];
122
+ const flushRun = () => {
123
+ if (run.length === 0) {
49
124
  return;
50
125
  }
51
- let item = selector.children.head;
52
- const itemsToInsertScopeBefore = [];
53
- let currentChunkIndex = 0;
54
- while (item !== null) {
55
- if (isScopePiercingPseudoSelector(item)) {
56
- Object.assign(item.data, attributeSelector);
57
- break;
58
- }
59
- else if (isCombinator(item) || isPseudoSelector(item)) {
60
- currentChunkIndex += 1;
61
- }
62
- else if (item.next) {
63
- itemsToInsertScopeBefore[currentChunkIndex] = item.next;
126
+ const last = run[run.length - 1];
127
+ if (last.next) {
128
+ selectorChildren.insertData(attributeSelector, last.next);
129
+ }
130
+ else {
131
+ selectorChildren.appendData(attributeSelector);
132
+ }
133
+ run = [];
134
+ };
135
+ items.forEach((item) => {
136
+ if (isHashableSelector(item.data)) {
137
+ run.push(item);
138
+ }
139
+ else {
140
+ flushRun();
141
+ }
142
+ });
143
+ flushRun();
144
+ };
145
+ const scopeCompound = (items, selectorChildren) => {
146
+ if (items.length === 0) {
147
+ return;
148
+ }
149
+ if (items.some((item) => isHashableSelector(item.data))) {
150
+ scopeRuns(items, selectorChildren);
151
+ return;
152
+ }
153
+ // `&` is already scoped through its parent rule.
154
+ if (items.some((item) => isNestingSelector(item.data))) {
155
+ return;
156
+ }
157
+ // `:root` / `:scope` refer to the document root and can never match the
158
+ // scope attribute; leave them global.
159
+ if (items.some((item) => isRootLikePseudoSelector(item.data))) {
160
+ return;
161
+ }
162
+ if (items.some((item) => item.data.type === "PseudoElementSelector")) {
163
+ // An attribute cannot follow a pseudo-element, so it has to be
164
+ // prepended: `::before` -> `[hash]::before`.
165
+ selectorChildren.insertData(attributeSelector, items[0]);
166
+ return;
167
+ }
168
+ if (!items.some((item) => item.data.type === "PseudoClassSelector")) {
169
+ return;
170
+ }
171
+ // `:hover` -> `:hover[hash]`
172
+ const last = items[items.length - 1];
173
+ if (last.next) {
174
+ selectorChildren.insertData(attributeSelector, last.next);
175
+ }
176
+ else {
177
+ selectorChildren.appendData(attributeSelector);
178
+ }
179
+ };
180
+ const replaceDeepFunction = (selectorChildren, item) => {
181
+ const node = item.data;
182
+ const selectorText = getDeepFunctionSelectorText(node);
183
+ if (!selectorText) {
184
+ return;
185
+ }
186
+ let parsed;
187
+ try {
188
+ parsed = parse(selectorText, {
189
+ context: "selectorList",
190
+ });
191
+ }
192
+ catch {
193
+ return;
194
+ }
195
+ const selectors = parsed.children;
196
+ if (selectors.size === 1) {
197
+ // Splice the argument selector in place of `:deep(...)`.
198
+ const replacement = new List();
199
+ selectors.first.children.forEach((child) => {
200
+ replacement.appendData(child);
201
+ });
202
+ selectorChildren.replace(item, replacement);
203
+ }
204
+ else {
205
+ // A selector list cannot be spliced into a single selector, but
206
+ // `:is(...)` has the same matching semantics here.
207
+ node.name = "is";
208
+ node.children = new List();
209
+ node.children.appendData(parsed);
210
+ }
211
+ };
212
+ const scopeSelector = (selector) => {
213
+ const selectorChildren = selector.children;
214
+ const compounds = [];
215
+ let compound = [];
216
+ for (let item = selectorChildren.head; item !== null; item = item.next) {
217
+ if (isCombinator(item.data)) {
218
+ compounds.push(compound);
219
+ compound = [];
220
+ }
221
+ else {
222
+ compound.push(item);
223
+ }
224
+ }
225
+ compounds.push(compound);
226
+ for (const items of compounds) {
227
+ const piercingIndex = items.findIndex((item) => isScopePiercingPseudoSelector(item.data) ||
228
+ isDeepFunctionSelector(item.data));
229
+ if (piercingIndex !== -1) {
230
+ const piercingItem = items[piercingIndex];
231
+ if (isDeepFunctionSelector(piercingItem.data)) {
232
+ // Scope everything before `:deep(...)` in the same compound,
233
+ // then splice in the (unscoped) argument selector.
234
+ scopeRuns(items.slice(0, piercingIndex), selectorChildren);
235
+ replaceDeepFunction(selectorChildren, piercingItem);
64
236
  }
65
237
  else {
66
- selector.children.appendData(attributeSelector);
67
- break;
238
+ // Replace `::deep` / `::v-deep` with the scope attribute.
239
+ Object.assign(piercingItem.data, attributeSelector);
68
240
  }
69
- item = item?.next ?? null;
241
+ // Everything after a deep selector stays global.
242
+ return;
70
243
  }
71
- // This is true if one of the two break statements above was run. Which means we don't want to add to the last one.
72
- if (itemsToInsertScopeBefore[currentChunkIndex]) {
73
- itemsToInsertScopeBefore.pop();
244
+ scopeCompound(items, selectorChildren);
245
+ }
246
+ };
247
+ /**
248
+ * CSS-tree parses implicit nesting as a `Raw` node inside the parent
249
+ * rule. Re-parse it as a rule so its selector can be scoped and write the
250
+ * transformed rule back.
251
+ */
252
+ const scopeRawNestedRule = (node) => {
253
+ if (!node.value.includes("{")) {
254
+ return;
255
+ }
256
+ try {
257
+ const rule = parse(node.value, { context: "rule" });
258
+ if (rule.type !== "Rule") {
259
+ return;
74
260
  }
75
- itemsToInsertScopeBefore.forEach((scopePositionItem) => {
76
- selector.children.insertData(attributeSelector, scopePositionItem);
261
+ scopeRule(rule);
262
+ node.value = generate(rule);
263
+ }
264
+ catch {
265
+ // Leave constructs css-tree cannot parse untouched.
266
+ }
267
+ };
268
+ const scopeRawSelectorPrelude = (prelude) => {
269
+ const parts = splitOnColumnCombinator(prelude.value);
270
+ if (parts.length === 1) {
271
+ return;
272
+ }
273
+ try {
274
+ const scopedParts = parts.map((part) => {
275
+ const selectorList = parse(part.trim(), {
276
+ context: "selectorList",
277
+ });
278
+ scopeSelectorList(selectorList.children);
279
+ return generate(selectorList);
77
280
  });
281
+ prelude.value = scopedParts.join(" || ");
282
+ }
283
+ catch {
284
+ // Leave constructs css-tree cannot parse untouched.
285
+ }
286
+ };
287
+ const scopeNodes = (children, insideRule) => {
288
+ children.forEach((node) => {
289
+ if (node.type === "Rule") {
290
+ scopeRule(node);
291
+ }
292
+ else if (node.type === "Atrule" &&
293
+ node.block &&
294
+ !isKeyframesAtRule(node.name)) {
295
+ // Recurse into conditional/group at-rules (`@media`, `@container`,
296
+ // `@supports`, `@layer`, `@scope`, etc.) so their rules get scoped.
297
+ scopeNodes(node.block.children, insideRule);
298
+ }
299
+ else if (insideRule && node.type === "Raw") {
300
+ scopeRawNestedRule(node);
301
+ }
78
302
  });
79
- });
303
+ };
304
+ const scopeRule = (rule) => {
305
+ if (rule.prelude?.type === "SelectorList") {
306
+ scopeSelectorList(rule.prelude.children);
307
+ }
308
+ else if (rule.prelude?.type === "Raw") {
309
+ scopeRawSelectorPrelude(rule.prelude);
310
+ }
311
+ if (rule.block) {
312
+ // Nested rules (`& ...`) and nested at-rules live in the rule block.
313
+ scopeNodes(rule.block.children, true);
314
+ }
315
+ };
316
+ scopeNodes(ast.children, false);
80
317
  const { css: scopedCss, map } = generate(ast, {
81
318
  sourceMap: true,
82
319
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rollup-plugin-react-scoped-css",
3
- "version": "1.2.6",
3
+ "version": "1.2.7",
4
4
  "description": "Bring scoped CSS to React with Vite & Rollup. Lightweight component-level style isolation similar to Vue and Angular.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",