forked from tailwindlabs/tailwindcss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcandidate.ts
More file actions
652 lines (557 loc) · 17 KB
/
candidate.ts
File metadata and controls
652 lines (557 loc) · 17 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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
import type { DesignSystem } from './design-system'
import { decodeArbitraryValue } from './utils/decode-arbitrary-value'
import { segment } from './utils/segment'
const COLON = 0x3a
const DASH = 0x2d
const LOWER_A = 0x61
const LOWER_Z = 0x7a
type ArbitraryUtilityValue = {
kind: 'arbitrary'
/**
* bg-[color:--my-color]
* ^^^^^
*/
dataType: string | null
/**
* bg-[#0088cc]
* ^^^^^^^
* bg-[--my_variable]
* var(^^^^^^^^^^^^^)
*/
value: string
/**
* bg-[--my_variable]
* ^^^^^^^^^^^^^
*/
dashedIdent: string | null
}
export type NamedUtilityValue = {
kind: 'named'
/**
* bg-red-500
* ^^^^^^^
*
* w-1/2
* ^
*/
value: string
/**
* w-1/2
* ^^^
*/
fraction: string | null
}
type ArbitraryModifier = {
kind: 'arbitrary'
/**
* bg-red-500/[50%]
* ^^^
*/
value: string
/**
* bg-red-500/[--my_variable]
* ^^^^^^^^^^^^^
*/
dashedIdent: string | null
}
type NamedModifier = {
kind: 'named'
/**
* bg-red-500/50
* ^^
*/
value: string
}
export type CandidateModifier = ArbitraryModifier | NamedModifier
type ArbitraryVariantValue = {
kind: 'arbitrary'
value: string
}
type NamedVariantValue = {
kind: 'named'
value: string
}
export type Variant =
/**
* Arbitrary variants are variants that take a selector and generate a variant
* on the fly.
*
* E.g.: `[&_p]`
*/
| {
kind: 'arbitrary'
selector: string
// If true, it can be applied as a child of a compound variant
compounds: boolean
}
/**
* Static variants are variants that don't take any arguments.
*
* E.g.: `hover`
*/
| {
kind: 'static'
root: string
// If true, it can be applied as a child of a compound variant
compounds: boolean
}
/**
* Functional variants are variants that can take an argument. The argument is
* either a named variant value or an arbitrary variant value.
*
* E.g.:
*
* - `aria-disabled`
* - `aria-[disabled]`
* - `@container-size` -> @container, with named value `size`
* - `@container-[inline-size]` -> @container, with arbitrary variant value `inline-size`
* - `@container` -> @container, with no value
*/
| {
kind: 'functional'
root: string
value: ArbitraryVariantValue | NamedVariantValue | null
modifier: ArbitraryModifier | NamedModifier | null
// If true, it can be applied as a child of a compound variant
compounds: boolean
}
/**
* Compound variants are variants that take another variant as an argument.
*
* E.g.:
*
* - `has-[&_p]`
* - `group-*`
* - `peer-*`
*/
| {
kind: 'compound'
root: string
modifier: ArbitraryModifier | NamedModifier | null
variant: Variant
// If true, it can be applied as a child of a compound variant
compounds: boolean
}
export type Candidate =
/**
* Arbitrary candidates are candidates that register utilities on the fly with
* a property and a value.
*
* E.g.:
*
* - `[color:red]`
* - `[color:red]/50`
* - `[color:red]/50!`
*/
| {
kind: 'arbitrary'
property: string
value: string
modifier: ArbitraryModifier | NamedModifier | null
variants: Variant[]
important: boolean
}
/**
* Static candidates are candidates that don't take any arguments.
*
* E.g.:
*
* - `underline`
* - `flex`
*/
| {
kind: 'static'
root: string
variants: Variant[]
negative: boolean
important: boolean
}
/**
* Functional candidates are candidates that can take an argument.
*
* E.g.:
*
* - `bg-red-500`
* - `bg-[#0088cc]`
* - `w-1/2`
*/
| {
kind: 'functional'
root: string
value: ArbitraryUtilityValue | NamedUtilityValue | null
modifier: ArbitraryModifier | NamedModifier | null
variants: Variant[]
negative: boolean
important: boolean
}
export function parseCandidate(input: string, designSystem: DesignSystem): Candidate | null {
// hover:focus:underline
// ^^^^^ ^^^^^^ -> Variants
// ^^^^^^^^^ -> Base
let rawVariants = segment(input, ':')
// Safety: At this point it is safe to use TypeScript's non-null assertion
// operator because even if the `input` was an empty string, splitting an
// empty string by `:` will always result in an array with at least one
// element.
let base = rawVariants.pop()!
let parsedCandidateVariants: Variant[] = []
for (let i = rawVariants.length - 1; i >= 0; --i) {
let parsedVariant = designSystem.parseVariant(rawVariants[i])
if (parsedVariant === null) return null
parsedCandidateVariants.push(parsedVariant)
}
let important = false
let negative = false
// Candidates that end with an exclamation mark are the important version with
// higher specificity of the non-important candidate, e.g. `mx-4!`.
if (base[base.length - 1] === '!') {
important = true
base = base.slice(0, -1)
}
// Legacy syntax with leading `!`, e.g. `!mx-4`.
else if (base[0] === '!') {
important = true
base = base.slice(1)
}
// Candidates that start with a dash are the negative versions of another
// candidate, e.g. `-mx-4`.
if (base[0] === '-') {
negative = true
base = base.slice(1)
}
// Check for an exact match of a static utility first as long as it does not
// look like an arbitrary value.
if (designSystem.utilities.has(base, 'static') && !base.includes('[')) {
return {
kind: 'static',
root: base,
variants: parsedCandidateVariants,
negative,
important,
}
}
// Figure out the new base and the modifier segment if present.
//
// E.g.:
//
// ```
// bg-red-500/50
// ^^^^^^^^^^ -> Base without modifier
// ^^ -> Modifier segment
// ```
let [baseWithoutModifier, modifierSegment = null, additionalModifier] = segment(base, '/')
// If there's more than one modifier, the utility is invalid.
//
// E.g.:
//
// - `bg-red-500/50/50`
if (additionalModifier) return null
// Arbitrary properties
if (baseWithoutModifier[0] === '[') {
// Arbitrary properties should end with a `]`.
if (baseWithoutModifier[baseWithoutModifier.length - 1] !== ']') return null
// The property part of the arbitrary property can only start with a-z
// lowercase or a dash `-` in case of vendor prefixes such as `-webkit-`
// or `-moz-`.
//
// Otherwise, it is an invalid candidate, and skip continue parsing.
let charCode = baseWithoutModifier.charCodeAt(1)
if (charCode !== DASH && !(charCode >= LOWER_A && charCode <= LOWER_Z)) {
return null
}
baseWithoutModifier = baseWithoutModifier.slice(1, -1)
// Arbitrary properties consist of a property and a value separated by a
// `:`. If the `:` cannot be found, then it is an invalid candidate, and we
// can skip continue parsing.
//
// Since the property and the value should be separated by a `:`, we can
// also verify that the colon is not the first or last character in the
// candidate, because that would make it invalid as well.
let idx = baseWithoutModifier.indexOf(':')
if (idx === -1 || idx === 0 || idx === baseWithoutModifier.length - 1) return null
let property = baseWithoutModifier.slice(0, idx)
let value = decodeArbitraryValue(baseWithoutModifier.slice(idx + 1))
return {
kind: 'arbitrary',
property,
value,
modifier: modifierSegment === null ? null : parseModifier(modifierSegment),
variants: parsedCandidateVariants,
important,
}
}
// The root of the utility, e.g.: `bg-red-500`
// ^^
let root: string | null = null
// The value of the utility, e.g.: `bg-red-500`
// ^^^^^^^
let value: string | null = null
// If the base of the utility ends with a `]`, then we know it's an arbitrary
// value. This also means that everything before the `[…]` part should be the
// root of the utility.
//
// E.g.:
//
// ```
// bg-[#0088cc]
// ^^ -> Root
// ^^^^^^^^^ -> Arbitrary value
//
// bg-red-[#0088cc]
// ^^^^^^ -> Root
// ^^^^^^^^^ -> Arbitrary value
// ```
if (baseWithoutModifier[baseWithoutModifier.length - 1] === ']') {
let idx = baseWithoutModifier.indexOf('-[')
if (idx === -1) return null
root = baseWithoutModifier.slice(0, idx)
// The root of the utility should exist as-is in the utilities map. If not,
// it's an invalid utility and we can skip continue parsing.
if (!designSystem.utilities.has(root, 'functional')) return null
value = baseWithoutModifier.slice(idx + 1)
}
// Not an arbitrary value
else {
;[root, value] = findRoot(baseWithoutModifier, (root: string) => {
return designSystem.utilities.has(root, 'functional')
})
}
// If there's no root, the candidate isn't a valid class and can be discarded.
if (root === null) return null
// If the leftover value is an empty string, it means that the value is an
// invalid named value, e.g.: `bg-`. This makes the candidate invalid and we
// can skip any further parsing.
if (value === '') return null
let candidate: Candidate = {
kind: 'functional',
root,
modifier: modifierSegment === null ? null : parseModifier(modifierSegment),
value: null,
variants: parsedCandidateVariants,
negative,
important,
}
if (value === null) return candidate
{
let startArbitraryIdx = value.indexOf('[')
let valueIsArbitrary = startArbitraryIdx !== -1
if (valueIsArbitrary) {
let arbitraryValue = value.slice(startArbitraryIdx + 1, -1)
// Extract an explicit typehint if present, e.g. `bg-[color:var(--my-var)])`
let typehint = ''
for (let i = 0; i < arbitraryValue.length; i++) {
let code = arbitraryValue.charCodeAt(i)
// If we hit a ":", we're at the end of a typehint.
if (code === COLON) {
typehint = arbitraryValue.slice(0, i)
arbitraryValue = arbitraryValue.slice(i + 1)
break
}
// Keep iterating as long as we've only seen valid typehint characters.
if (code === DASH || (code >= LOWER_A && code <= LOWER_Z)) {
continue
}
// If we see any other character, there's no typehint so break early.
break
}
// If an arbitrary value looks like a CSS variable, we automatically wrap
// it with `var(...)`.
//
// But since some CSS properties accept a `<dashed-ident>` as a value
// directly (e.g. `scroll-timeline-name`), we also store the original
// value in case the utility matcher is interested in it without
// `var(...)`.
let dashedIdent: string | null = null
if (arbitraryValue[0] === '-' && arbitraryValue[1] === '-') {
dashedIdent = arbitraryValue
arbitraryValue = `var(${arbitraryValue})`
} else {
arbitraryValue = decodeArbitraryValue(arbitraryValue)
}
candidate.value = {
kind: 'arbitrary',
dataType: typehint || null,
value: arbitraryValue,
dashedIdent,
}
} else {
// Some utilities support fractions as values, e.g. `w-1/2`. Since it's
// ambiguous whether the slash signals a modifier or not, we store the
// fraction separately in case the utility matcher is interested in it.
let fraction =
modifierSegment === null || candidate.modifier?.kind === 'arbitrary'
? null
: `${value.slice(value.lastIndexOf('-') + 1)}/${modifierSegment}`
candidate.value = {
kind: 'named',
value,
fraction,
}
}
}
return candidate
}
function parseModifier(modifier: string): CandidateModifier {
if (modifier[0] === '[' && modifier[modifier.length - 1] === ']') {
let arbitraryValue = modifier.slice(1, -1)
// If an arbitrary value looks like a CSS variable, we automatically wrap
// it with `var(...)`.
//
// But since some CSS properties accept a `<dashed-ident>` as a value
// directly (e.g. `scroll-timeline-name`), we also store the original
// value in case the utility matcher is interested in it without
// `var(...)`.
let dashedIdent: string | null = null
if (arbitraryValue[0] === '-' && arbitraryValue[1] === '-') {
dashedIdent = arbitraryValue
arbitraryValue = `var(${arbitraryValue})`
} else {
arbitraryValue = decodeArbitraryValue(arbitraryValue)
}
return {
kind: 'arbitrary',
value: arbitraryValue,
dashedIdent,
}
}
return {
kind: 'named',
value: modifier,
}
}
export function parseVariant(variant: string, designSystem: DesignSystem): Variant | null {
// Arbitrary variants
if (variant[0] === '[' && variant[variant.length - 1] === ']') {
/**
* TODO: Breaking change
*
* @deprecated Arbitrary variants containing at-rules with other selectors
* are deprecated. Use stacked variants instead.
*
* Before:
* - `[@media(width>=123px){&:hover}]:`
*
* After:
* - `[@media(width>=123px)]:[&:hover]:`
* - `[@media(width>=123px)]:hover:`
*/
if (variant[1] === '@' && variant.includes('&')) return null
let selector = decodeArbitraryValue(variant.slice(1, -1))
if (selector[0] !== '@') {
// Ensure `&` is always present by wrapping the selector in `&:is(…)`
//
// E.g.:
//
// - `[p]:flex`
if (!selector.includes('&')) {
selector = `&:is(${selector})`
}
}
return {
kind: 'arbitrary',
selector,
compounds: true,
}
}
// Static, functional and compound variants
{
// group-hover/group-name
// ^^^^^^^^^^^ -> Variant without modifier
// ^^^^^^^^^^ -> Modifier
let [variantWithoutModifier, modifier = null, additionalModifier] = segment(variant, '/')
// If there's more than one modifier, the variant is invalid.
//
// E.g.:
//
// - `group-hover/foo/bar`
if (additionalModifier) return null
let [root, value] = findRoot(variantWithoutModifier, (root) => {
return designSystem.variants.has(root)
})
// Variant is invalid, therefore the candidate is invalid and we can skip
// continue parsing it.
if (root === null) return null
switch (designSystem.variants.kind(root)) {
case 'static': {
// Static variants do not have a value
if (value !== null) return null
// Static variants do not have a modifier
if (modifier !== null) return null
return {
kind: 'static',
root,
compounds: designSystem.variants.compounds(root),
}
}
case 'functional': {
if (value === null) return null
if (value[0] === '[' && value[value.length - 1] === ']') {
return {
kind: 'functional',
root,
modifier: modifier === null ? null : parseModifier(modifier),
value: {
kind: 'arbitrary',
value: decodeArbitraryValue(value.slice(1, -1)),
},
compounds: designSystem.variants.compounds(root),
}
}
return {
kind: 'functional',
root,
modifier: modifier === null ? null : parseModifier(modifier),
value: { kind: 'named', value },
compounds: designSystem.variants.compounds(root),
}
}
case 'compound': {
if (value === null) return null
let subVariant = designSystem.parseVariant(value)
if (subVariant === null) return null
if (subVariant.compounds === false) return null
return {
kind: 'compound',
root,
modifier: modifier === null ? null : { kind: 'named', value: modifier },
variant: subVariant,
compounds: designSystem.variants.compounds(root),
}
}
}
}
return null
}
function findRoot(
input: string,
exists: (input: string) => boolean,
): [string | null, string | null] {
// If there is an exact match, then that's the root.
if (exists(input)) return [input, null]
// Otherwise test every permutation of the input by iteratively removing
// everything after the last dash.
let idx = input.lastIndexOf('-')
if (idx === -1) {
// Variants starting with `@` are special because they don't need a `-`
// after the `@` (E.g.: `@-lg` should be written as `@lg`).
if (input[0] === '@' && exists('@')) {
return ['@', input.slice(1)]
}
return [null, null]
}
// Determine the root and value by testing permutations of the incoming input.
//
// In case of a candidate like `bg-red-500`, this looks like:
//
// `bg-red-500` -> No match
// `bg-red` -> No match
// `bg` -> Match
do {
let maybeRoot = input.slice(0, idx)
if (exists(maybeRoot)) {
return [maybeRoot, input.slice(idx + 1)]
}
idx = input.lastIndexOf('-', idx - 1)
} while (idx > 0)
return [null, null]
}