forked from tailwindlabs/tailwindcss
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.ts
More file actions
273 lines (229 loc) · 8.52 KB
/
compile.ts
File metadata and controls
273 lines (229 loc) · 8.52 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
import { rule, type AstNode, type Rule } from './ast'
import { parseCandidate, parseVariant, type Candidate, type Variant } from './candidate'
import { type DesignSystem } from './design-system'
import GLOBAL_PROPERTY_ORDER from './property-order'
import { DefaultMap } from './utils/default-map'
import { escape } from './utils/escape'
import type { Variants } from './variants'
type SortDetails = {
properties: number[]
variants: bigint
candidate: string
}
type CompileOptions = {
throwOnInvalidCandidate?: boolean
cache?: Map<string, [Candidate, AstNode, SortDetails]>
}
export function compileCandidates(
rawCandidates: string[],
designSystem: DesignSystem,
{ throwOnInvalidCandidate = false, cache }: CompileOptions = {},
) {
// Ensure the candidates are sorted alphabetically
rawCandidates.sort()
let nodeSorting = new Map<AstNode, SortDetails>()
let astNodes: AstNode[] = []
// A lazy map implementation that will return the variant if it exists. If it
// doesn't exist yet, the raw string variant will be parsed and added to the
// map.
let parsedVariants: DefaultMap<string, Variant | null> = new DefaultMap((variant, map) => {
return parseVariant(variant, designSystem.variants, map)
})
let candidates = new Map<Candidate, string>()
// Parse candidates and variants
for (let rawCandidate of rawCandidates) {
let existing = cache?.get(rawCandidate)
if (existing) {
candidates.set(existing[0], rawCandidate)
astNodes.push(existing[1])
nodeSorting.set(existing[1], existing[2])
continue
}
let candidate = parseCandidate(rawCandidate, designSystem.utilities, parsedVariants)
if (candidate === null) {
if (throwOnInvalidCandidate) {
throw new Error(`Cannot apply unknown utility class: ${rawCandidate}`)
}
continue // Bail, invalid candidate
}
candidates.set(candidate, rawCandidate)
}
// Sort the variants
let variants = Array.from(parsedVariants.values()).sort((a, z) => {
return designSystem.variants.compare(a, z)
})
// Create the AST
next: for (let [candidate, rawCandidate] of candidates) {
let existing = cache?.get(rawCandidate)
if (existing) continue
let nodes: AstNode[] = []
// Handle arbitrary properties
if (candidate.kind === 'arbitrary') {
let compileFn = designSystem.utilities.getArbitrary()
// Build the node
let compiledNodes = compileFn(candidate)
if (compiledNodes === undefined) {
if (throwOnInvalidCandidate) {
throw new Error(`Cannot apply unknown utility class: ${rawCandidate}`)
}
continue next
}
nodes = compiledNodes
}
// Handle named utilities
else if (candidate.kind === 'static' || candidate.kind === 'functional') {
// Safety: At this point it is safe to use TypeScript's non-null assertion
// operator because if the `candidate.root` didn't exist, `parseCandidate`
// would have returned `null` and we would have returned early resulting
// in not hitting this code path.
let { compileFn } = designSystem.utilities.get(candidate.root)!
// Build the node
let compiledNodes = compileFn(candidate)
if (compiledNodes === undefined) {
if (throwOnInvalidCandidate) {
throw new Error(`Cannot apply unknown utility class: ${rawCandidate}`)
}
continue next
}
nodes = compiledNodes
}
let propertySort = getPropertySort(nodes)
if (candidate.important) {
applyImportant(nodes)
}
let node: Rule = {
kind: 'rule',
selector: `.${escape(rawCandidate)}`,
nodes,
}
let variantOrder = 0n
for (let variant of candidate.variants) {
let result = applyVariant(node, variant, designSystem.variants)
// When the variant results in `null`, it means that the variant cannot be
// applied to the rule. Discard the candidate and continue to the next
// one.
if (result === null) {
if (throwOnInvalidCandidate) {
throw new Error(`Cannot apply unknown utility class: ${rawCandidate}`)
}
continue next
}
// Track the variant order which is a number with each bit representing a
// variant. This allows us to sort the rules based on the order of
// variants used.
variantOrder |= 1n << BigInt(variants.indexOf(variant))
}
nodeSorting.set(node, {
properties: propertySort,
variants: variantOrder,
candidate: rawCandidate,
})
astNodes.push(node)
cache?.set(rawCandidate, [candidate, node, nodeSorting.get(node)!])
}
astNodes.sort((a, z) => {
// Safety: At this point it is safe to use TypeScript's non-null assertion
// operator because if the ast nodes didn't exist, we introduced a bug
// above, but there is no need to re-check just to be sure. If this relied
// on pure user input, then we would need to check for its existence.
let aSorting = nodeSorting.get(a)!
let zSorting = nodeSorting.get(z)!
// Sort by variant order first
if (aSorting.variants - zSorting.variants !== 0n) {
return Number(aSorting.variants - zSorting.variants)
}
// Find the first property that is different between the two rules
let offset = 0
while (
aSorting.properties.length < offset &&
zSorting.properties.length < offset &&
aSorting.properties[offset] === zSorting.properties[offset]
) {
offset += 1
}
return (
// Sort by lowest property index first
(aSorting.properties[offset] ?? Infinity) - (zSorting.properties[offset] ?? Infinity) ||
// Sort by most properties first, then by least properties
zSorting.properties.length - aSorting.properties.length
)
})
return {
astNodes,
nodeSorting,
}
}
export function applyVariant(node: Rule, variant: Variant, variants: Variants): null | void {
if (variant.kind === 'arbitrary') {
node.nodes = [rule(variant.selector, node.nodes)]
return
}
// Safety: At this point it is safe to use TypeScript's non-null assertion
// operator because if the `candidate.root` didn't exist, `parseCandidate`
// would have returned `null` and we would have returned early resulting in
// not hitting this code path.
let { applyFn } = variants.get(variant.root)!
if (variant.kind === 'compound') {
let result = applyVariant(node, variant.variant, variants)
if (result === null) return null
for (let child of node.nodes) {
// Only some variants wrap children in rules. For example, the `force`
// variant is a noop on the AST. And the `has` variant modifies the
// selector rather than the children.
//
// This means `child` may be a declaration and we don't want to apply the
// variant to it. This also means the entire variant as a whole is not
// applicable to the rule and should generate nothing.
if (child.kind !== 'rule') return null
let result = applyFn(child as Rule, variant)
if (result === null) return null
}
return
}
// All other variants
let result = applyFn(node, variant)
if (result === null) return null
}
function applyImportant(ast: AstNode[]): void {
for (let node of ast) {
// Skip any `@at-root` rules — we don't want to make the contents of things
// like `@keyframes` or `@property` important.
if (node.kind === 'rule' && node.selector === '@at-root') {
continue
}
if (node.kind === 'declaration') {
node.important = true
} else if (node.kind === 'rule') {
applyImportant(node.nodes)
}
}
}
function getPropertySort(nodes: AstNode[]) {
// Determine sort order based on properties used
let propertySort = new Set<number>()
let q: AstNode[] = nodes.slice()
while (q.length > 0) {
// Safety: At this point it is safe to use TypeScript's non-null assertion
// operator because we guarded against `q.length > 0` above.
let node = q.shift()!
if (node.kind === 'declaration') {
if (node.property === '--tw-sort') {
let idx = GLOBAL_PROPERTY_ORDER.indexOf(node.value)
if (idx !== -1) {
propertySort.add(idx)
break
}
}
let idx = GLOBAL_PROPERTY_ORDER.indexOf(node.property)
if (idx !== -1) propertySort.add(idx)
} else if (node.kind === 'rule') {
// Don't consider properties within `@at-root` when determining the sort
// order for a rule.
if (node.selector === '@at-root') continue
for (let child of node.nodes) {
q.push(child)
}
}
}
return Array.from(propertySort).sort((a, z) => a - z)
}