-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathselector-builder.ts
More file actions
588 lines (538 loc) · 18 KB
/
selector-builder.ts
File metadata and controls
588 lines (538 loc) · 18 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
import type { AttrOperation, Selector, SelectorList } from "lightningcss";
import { Specificity } from "../utilities";
import type {
AttributeQuery,
AttrSelectorOperator,
CompilerOptions,
ContainerQuery,
MediaCondition,
PseudoClassesQuery,
SpecificityArray,
} from "./compiler.types";
interface ReactNativeClassNameSelector {
type: "className";
specificity: SpecificityArray;
className: string;
mediaQuery?: MediaCondition[];
containerQuery?: ContainerQuery[];
pseudoClassesQuery?: PseudoClassesQuery;
attributeQuery?: AttributeQuery[];
pseudoElementQuery?: string[];
}
interface ReactNativeGlobalSelector {
type: "rootVariables" | "universalVariables";
}
type PartialSelector = Partial<ReactNativeClassNameSelector> & {
type: "className";
specificity: SpecificityArray;
};
const containerQueryMap = new WeakMap<WeakKey, ContainerQuery[]>();
const attributeQueryMap = new WeakMap<WeakKey, AttributeQuery[]>();
const mediaQueryMap = new WeakMap<WeakKey, MediaCondition[]>();
const pseudoClassesQueryMap = new WeakMap<WeakKey, PseudoClassesQuery>();
type ContainerQueryWithSpecificity = ContainerQuery & {
specificity: SpecificityArray;
m?: MediaCondition;
};
export function getClassNameSelectors(
selectors: SelectorList,
options: CompilerOptions = {},
) {
if (!selectors.length) {
return [];
}
return selectors.flatMap(
(selector): (ReactNativeGlobalSelector | PartialSelector)[] => {
const root: PartialSelector = {
type: "className",
specificity: [],
};
const specificity: SpecificityArray = [0];
if (isRootVariableSelector(selector)) {
return [{ type: "rootVariables" }];
} else if (isUniversalSelector(selector)) {
return [{ type: "universalVariables" }];
} else {
return (
parseComponents(
selector.reverse(),
options,
root,
root,
specificity,
) ?? []
);
}
},
);
}
function parseComponents(
[component, ...rest]: Selector,
options: CompilerOptions,
root: PartialSelector,
ref: PartialSelector | ContainerQuery,
specificity: SpecificityArray,
): PartialSelector[] | null {
if (!component || Array.isArray(component.type)) {
// Merge the specificity with the root specificity
for (let i = 0; i < specificity.length; i++) {
const value = specificity[i];
if (value !== undefined) {
root.specificity[i] = (root.specificity[i] ?? 0) + value;
}
}
// Return the root
return [root];
}
switch (component.type) {
case "id": // #id
case "namespace": // @namespace
case "universal": // * - universal selector
return null;
case "type": {
// div, span
if (
component.name === options.selectorPrefix ||
component.name === "html"
) {
return parseComponents(rest, options, root, ref, specificity);
} else {
return null;
}
}
case "nesting":
// &
// The SelectorList should be flattened, so we can skip these
return parseComponents(rest, options, root, ref, specificity);
case "combinator": {
// We only support the descendant combinator
if (component.value === "descendant") {
// Switch to now parsing a container query
ref = {};
return parseComponents(rest, options, root, ref, specificity);
}
return [];
}
case "pseudo-element": {
switch (component.kind) {
case "selection":
case "placeholder": {
specificity[Specificity.PseudoElements] =
(specificity[Specificity.PseudoElements] ?? 0) + 1;
root.pseudoElementQuery ??= [];
root.pseudoElementQuery.push(component.kind);
return parseComponents(rest, options, root, ref, specificity);
}
default: {
return [];
}
}
}
case "pseudo-class": {
switch (component.kind) {
case "hover": {
getPseudoClassesQuery(ref).h = 1;
specificity[Specificity.PseudoClass] =
(specificity[Specificity.PseudoClass] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
case "active": {
getPseudoClassesQuery(ref).a = 1;
specificity[Specificity.PseudoClass] =
(specificity[Specificity.PseudoClass] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
case "focus": {
getPseudoClassesQuery(ref).f = 1;
specificity[Specificity.PseudoClass] =
(specificity[Specificity.PseudoClass] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
case "disabled": {
getAttributeQuery(ref).push(["a", "disabled"]);
specificity[Specificity.PseudoClass] =
(specificity[Specificity.PseudoClass] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
case "empty": {
getAttributeQuery(ref).push(["a", "children", "!"]);
specificity[Specificity.PseudoClass] =
(specificity[Specificity.PseudoClass] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
case "where":
case "is": {
// Now get the selectors inside the `is` or `where` pseudo-class
const isWhereContainerQueries = component.selectors.flatMap(
(selector) => {
return parseIsWhereComponents(component.kind, selector) ?? [];
},
);
// Remember we're looping in reverse order,
// So `rest` contains the selectors BEFORE this one
const parents = parseComponents(
rest,
options,
root,
ref,
specificity,
);
if (!parents) {
return null;
}
// Each parent selector should be combined with each pseudo-class selector
return parents.flatMap((parent) => {
const originalParent = { ...parent };
return isWhereContainerQueries.map((containerQuery) => {
const { specificity, m, ...query } = containerQuery;
parent = { ...originalParent };
parent.specificity = [...originalParent.specificity];
if (m && m.length > 1) {
parent.mediaQuery = originalParent.mediaQuery
? [["&", [...originalParent.mediaQuery, m]]]
: [m];
}
if (component.kind === "is") {
for (let i = 0; i < specificity.length; i++) {
const value = specificity[i];
if (value !== undefined) {
parent.specificity[i] =
(parent.specificity[i] ?? 0) + value;
}
}
}
if (query.a || query.p || query.n !== undefined) {
parent.containerQuery = [
...(originalParent.containerQuery ?? []),
];
parent.containerQuery.push(query);
}
return parent;
});
});
}
default: {
return [];
}
}
}
case "attribute": {
if (component.name === "dir") {
if (!component.operation) {
return [];
}
const operator = operatorMap[component.operation.operator];
if (operator !== "=") {
return [];
}
getMediaQuery(ref).push([operator, "dir", component.operation.value]);
return parseComponents(rest, options, root, ref, specificity);
} else {
// specificity[Specificity.ClassName] =
// (specificity[Specificity.ClassName] ?? 0) + 1;
const attributeQuery: AttributeQuery = component.name.startsWith(
"data-",
)
? // [data-*] are turned into `dataSet` queries
["d", toRNProperty(component.name.replace("data-", ""))]
: // Everything else is turned into `attribute` queries
["a", toRNProperty(component.name)];
if (component.operation) {
let operator: AttrSelectorOperator | undefined;
switch (component.operation.operator) {
case "equal":
operator = "=";
break;
case "includes":
operator = "~=";
break;
case "dash-match":
operator = "|=";
break;
case "prefix":
operator = "^=";
break;
case "substring":
operator = "*=";
break;
case "suffix":
operator = "$=";
break;
default:
component.operation.operator satisfies never;
break;
}
if (operator) {
// Append the operator onto the attribute query
attributeQuery.push(operator, component.operation.value);
}
}
getAttributeQuery(ref).push(attributeQuery);
specificity[Specificity.ClassName] =
(specificity[Specificity.ClassName] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
}
case "class": {
if (component.name === options.selectorPrefix) {
// Skip this one
return parseComponents(rest, options, root, ref, specificity);
} else if (!isContainerQuery(ref) && !ref.className) {
ref.className = component.name;
specificity[Specificity.ClassName] =
(specificity[Specificity.ClassName] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
} else if (!isContainerQuery(ref)) {
// Only the first className is used, the rest are attribute queries
getAttributeQuery(ref).unshift([
"a",
"className",
"*=",
component.name,
]);
} else {
let containerQueries = containerQueryMap.get(root);
if (!containerQueries) {
containerQueries = [];
root.containerQuery = containerQueries;
containerQueryMap.set(root, containerQueries);
}
if (!ref.n) {
containerQueries.unshift(ref);
}
ref.n = ref.n ? `${ref.n}.${component.name}` : `g:${component.name}`;
}
specificity[Specificity.ClassName] =
(specificity[Specificity.ClassName] ?? 0) + 1;
return parseComponents(rest, options, root, ref, specificity);
}
}
}
function parseIsWhereComponents(
type: "is" | "where",
selector: Selector,
index = 0,
queries?: ContainerQueryWithSpecificity[],
): ContainerQueryWithSpecificity[] | null {
const component = selector[index];
if (!component || Array.isArray(component.type)) {
return queries ?? [];
}
switch (component.type) {
// These are not allowed in `is()` or `where()`
case "id": // #id
case "namespace": // @namespace
case "type": // div, span
case "nesting": // &
case "pseudo-element": // ::selection, ::placeholder, etc
return null;
case "combinator": {
// We only support the descendant combinator
if (component.value === "descendant") {
// Each "block" is a new container query
const children = parseIsWhereComponents(type, selector, index + 1);
return children && queries ? [...queries, ...children] : children;
}
return null;
}
case "universal": {
// * - universal selector
if (index !== selector.length - 1) {
// We only accept it in the last position
return null;
}
// This was the only component, so we return the ref
if (selector.length === 1) {
return queries ?? [{ specificity: [] }];
}
const previous = selector[index - 1];
// If the previous component is not a descendant combinator,
if (
!previous ||
previous.type !== "combinator" ||
previous.value !== "descendant"
) {
return null;
}
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "pseudo-class": {
// const specificity = ref.specificity;
// specificity[Specificity.ClassName] =
// (specificity[Specificity.ClassName] ?? 0) + 1;
switch (component.kind) {
case "dir": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getMediaQuery(query).push(["=", "dir", component.direction]);
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "hover": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getPseudoClassesQuery(query).h = 1;
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "active": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getPseudoClassesQuery(query).a = 1;
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "focus": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getPseudoClassesQuery(query).f = 1;
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "disabled": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getAttributeQuery(query).push(["a", "disabled"]);
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "empty": {
queries ??= [{ specificity: [] }];
queries.forEach((query) => {
getAttributeQuery(query).push(["a", "children", "!"]);
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "where":
case "is": {
// Now get the selectors inside the `is` or `where` pseudo-class
queries = component.selectors.flatMap((selector) => {
return parseIsWhereComponents(type, selector, 0, queries) ?? [];
});
return parseIsWhereComponents(type, selector, index + 1, queries);
}
default: {
return null;
}
}
}
case "attribute": {
if (component.name === "dir") {
return null;
}
if (type !== "where") {
// specificity[Specificity.ClassName] =
// (specificity[Specificity.ClassName] ?? 0) + 1;
}
const attributeQuery: AttributeQuery = component.name.startsWith("data-")
? // [data-*] are turned into `dataSet` queries
["d", toRNProperty(component.name.replace("data-", ""))]
: // Everything else is turned into `attribute` queries
["a", toRNProperty(component.name)];
if (component.operation) {
const operator = operatorMap[component.operation.operator];
// Append the operator onto the attribute query
attributeQuery.push(operator, component.operation.value);
}
queries ??= [{ specificity: [] }];
for (const query of queries) {
if (type === "is") {
query.specificity[Specificity.ClassName] =
(query.specificity[Specificity.ClassName] ?? 0) + 1;
}
getAttributeQuery(query).push(attributeQuery);
}
return parseIsWhereComponents(type, selector, index + 1, queries);
}
case "class": {
// In `is` and `where` selectors, the ref will always be a container query
queries ??= [{ specificity: [] }];
for (const query of queries) {
if (type === "is") {
query.specificity[Specificity.ClassName] =
(query.specificity[Specificity.ClassName] ?? 0) + 1;
}
query.n = query.n
? `${query.n}.${component.name}`
: `g:${component.name}`;
}
return parseIsWhereComponents(type, selector, index + 1, queries);
}
}
}
function isContainerQuery(
value: PartialSelector | ContainerQuery,
): value is ContainerQuery {
return !("type" in value);
}
function getPseudoClassesQuery(key: PartialSelector | ContainerQuery) {
let pseudoClassesQuery = pseudoClassesQueryMap.get(key);
if (!pseudoClassesQuery) {
if ("type" in key) {
pseudoClassesQuery = {};
key.pseudoClassesQuery = pseudoClassesQuery;
} else {
key.p ??= {};
pseudoClassesQuery = key.p;
}
pseudoClassesQueryMap.set(key, pseudoClassesQuery);
}
return pseudoClassesQuery;
}
function getAttributeQuery(
key: PartialSelector | ContainerQuery,
): AttributeQuery[] {
let attributeQuery = attributeQueryMap.get(key);
if (!attributeQuery) {
if ("type" in key) {
attributeQuery = [];
key.attributeQuery = attributeQuery;
} else {
key.a ??= [];
attributeQuery = key.a;
}
attributeQueryMap.set(key, attributeQuery);
}
return attributeQuery;
}
function getMediaQuery(
key: PartialSelector | ContainerQuery,
): MediaCondition[] {
let mediaQuery = mediaQueryMap.get(key);
if (!mediaQuery) {
if ("type" in key) {
mediaQuery = [];
key.mediaQuery = mediaQuery;
} else {
mediaQuery = [];
key.m ??= ["&", mediaQuery];
}
mediaQueryMap.set(key, mediaQuery);
}
return mediaQuery;
}
function isRootVariableSelector([first, second]: Selector) {
return (
first && !second && first.type === "pseudo-class" && first.kind === "root"
);
}
function isUniversalSelector([first, second]: Selector) {
return first && first.type === "universal" && !second;
}
export function toRNProperty<T extends string>(str: T) {
return str
.replace(/^-rn-/, "")
.replace(/-./g, (x) => x[1]?.toUpperCase() ?? "") as CamelCase<T>;
}
type CamelCase<S extends string> =
S extends `${infer P1}-${infer P2}${infer P3}`
? `${Lowercase<P1>}${Uppercase<P2>}${CamelCase<P3>}`
: Lowercase<S>;
const operatorMap: Record<AttrOperation["operator"], AttrSelectorOperator> = {
"equal": "=",
"includes": "~=",
"dash-match": "|=",
"prefix": "^=",
"substring": "*=",
"suffix": "$=",
};