source: frontend/node_modules/tailwindcss/src/lib/offsets.js

Last change on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 12 days ago

Fix frontend appearance

  • Property mode set to 100644
File size: 11.9 KB
RevLine 
[9af201e]1// @ts-check
2
3import bigSign from '../util/bigSign'
4import { remapBitfield } from './remap-bitfield.js'
5
6/**
7 * @typedef {'base' | 'defaults' | 'components' | 'utilities' | 'variants' | 'user'} Layer
8 */
9
10/**
11 * @typedef {object} VariantOption
12 * @property {number} id An unique identifier to identify `matchVariant`
13 * @property {function | undefined} sort The sort function
14 * @property {string|null} value The value we want to compare
15 * @property {string|null} modifier The modifier that was used (if any)
16 * @property {bigint} variant The variant bitmask
17 */
18
19/**
20 * @typedef {object} RuleOffset
21 * @property {Layer} layer The layer that this rule belongs to
22 * @property {Layer} parentLayer The layer that this rule originally belonged to. Only different from layer if this is a variant.
23 * @property {bigint} arbitrary 0n if false, 1n if true
24 * @property {bigint} variants Dynamic size. 1 bit per registered variant. 0n means no variants
25 * @property {bigint} parallelIndex Rule index for the parallel variant. 0 if not applicable.
26 * @property {bigint} index Index of the rule / utility in its given *parent* layer. Monotonically increasing.
27 * @property {bigint} propertyOffset Offset for the arbitrary property. Only valid after sorting.
28 * @property {string} property Name/Value of the arbitrary property.
29 * @property {VariantOption[]} options Some information on how we can sort arbitrary variants
30 */
31
32export class Offsets {
33 constructor() {
34 /**
35 * Offsets for the next rule in a given layer
36 *
37 * @type {Record<Layer, bigint>}
38 */
39 this.offsets = {
40 defaults: 0n,
41 base: 0n,
42 components: 0n,
43 utilities: 0n,
44 variants: 0n,
45 user: 0n,
46 }
47
48 /**
49 * Positions for a given layer
50 *
51 * @type {Record<Layer, bigint>}
52 */
53 this.layerPositions = {
54 defaults: 0n,
55 base: 1n,
56 components: 2n,
57 utilities: 3n,
58
59 // There isn't technically a "user" layer, but we need to give it a position
60 // Because it's used for ordering user-css from @apply
61 user: 4n,
62
63 variants: 5n,
64 }
65
66 /**
67 * The total number of functions currently registered across all variants (including arbitrary variants)
68 *
69 * @type {bigint}
70 */
71 this.reservedVariantBits = 0n
72
73 /**
74 * Positions for a given variant
75 *
76 * @type {Map<string, bigint>}
77 */
78 this.variantOffsets = new Map()
79 }
80
81 /**
82 * @param {Layer} layer
83 * @returns {RuleOffset}
84 */
85 create(layer) {
86 return {
87 layer,
88 parentLayer: layer,
89 arbitrary: 0n,
90 variants: 0n,
91 parallelIndex: 0n,
92 index: this.offsets[layer]++,
93 propertyOffset: 0n,
94 property: '',
95 options: [],
96 }
97 }
98
99 /**
100 * @param {string} name
101 * @returns {RuleOffset}
102 */
103 arbitraryProperty(name) {
104 return {
105 ...this.create('utilities'),
106 arbitrary: 1n,
107 property: name,
108 }
109 }
110
111 /**
112 * Get the offset for a variant
113 *
114 * @param {string} variant
115 * @param {number} index
116 * @returns {RuleOffset}
117 */
118 forVariant(variant, index = 0) {
119 let offset = this.variantOffsets.get(variant)
120 if (offset === undefined) {
121 throw new Error(`Cannot find offset for unknown variant ${variant}`)
122 }
123
124 return {
125 ...this.create('variants'),
126 variants: offset << BigInt(index),
127 }
128 }
129
130 /**
131 * @param {RuleOffset} rule
132 * @param {RuleOffset} variant
133 * @param {VariantOption} options
134 * @returns {RuleOffset}
135 */
136 applyVariantOffset(rule, variant, options) {
137 options.variant = variant.variants
138
139 return {
140 ...rule,
141 layer: 'variants',
142 parentLayer: rule.layer === 'variants' ? rule.parentLayer : rule.layer,
143 variants: rule.variants | variant.variants,
144 options: options.sort ? [].concat(options, rule.options) : rule.options,
145
146 // TODO: Technically this is wrong. We should be handling parallel index on a per variant basis.
147 // We'll take the max of all the parallel indexes for now.
148 // @ts-ignore
149 parallelIndex: max([rule.parallelIndex, variant.parallelIndex]),
150 }
151 }
152
153 /**
154 * @param {RuleOffset} offset
155 * @param {number} parallelIndex
156 * @returns {RuleOffset}
157 */
158 applyParallelOffset(offset, parallelIndex) {
159 return {
160 ...offset,
161 parallelIndex: BigInt(parallelIndex),
162 }
163 }
164
165 /**
166 * Each variant gets 1 bit per function / rule registered.
167 * This is because multiple variants can be applied to a single rule and we need to know which ones are present and which ones are not.
168 * Additionally, every unique group of variants is grouped together in the stylesheet.
169 *
170 * This grouping is order-independent. For instance, we do not differentiate between `hover:focus` and `focus:hover`.
171 *
172 * @param {string[]} variants
173 * @param {(name: string) => number} getLength
174 */
175 recordVariants(variants, getLength) {
176 for (let variant of variants) {
177 this.recordVariant(variant, getLength(variant))
178 }
179 }
180
181 /**
182 * The same as `recordVariants` but for a single arbitrary variant at runtime.
183 * @param {string} variant
184 * @param {number} fnCount
185 *
186 * @returns {RuleOffset} The highest offset for this variant
187 */
188 recordVariant(variant, fnCount = 1) {
189 this.variantOffsets.set(variant, 1n << this.reservedVariantBits)
190
191 // Ensure space is reserved for each "function" in the parallel variant
192 // by offsetting the next variant by the number of parallel variants
193 // in the one we just added.
194
195 // Single functions that return parallel variants are NOT handled separately here
196 // They're offset by 1 (or the number of functions) as usual
197 // And each rule returned is tracked separately since the functions are evaluated lazily.
198 // @see `RuleOffset.parallelIndex`
199 this.reservedVariantBits += BigInt(fnCount)
200
201 return {
202 ...this.create('variants'),
203 variants: this.variantOffsets.get(variant),
204 }
205 }
206
207 /**
208 * @param {RuleOffset} a
209 * @param {RuleOffset} b
210 * @returns {bigint}
211 */
212 compare(a, b) {
213 // Sort layers together
214 if (a.layer !== b.layer) {
215 return this.layerPositions[a.layer] - this.layerPositions[b.layer]
216 }
217
218 // When sorting the `variants` layer, we need to sort based on the parent layer as well within
219 // this variants layer.
220 if (a.parentLayer !== b.parentLayer) {
221 return this.layerPositions[a.parentLayer] - this.layerPositions[b.parentLayer]
222 }
223
224 // Sort based on the sorting function
225 for (let aOptions of a.options) {
226 for (let bOptions of b.options) {
227 if (aOptions.id !== bOptions.id) continue
228 if (!aOptions.sort || !bOptions.sort) continue
229
230 let maxFnVariant = max([aOptions.variant, bOptions.variant]) ?? 0n
231
232 // Create a mask of 0s from bits 1..N where N represents the mask of the Nth bit
233 let mask = ~(maxFnVariant | (maxFnVariant - 1n))
234 let aVariantsAfterFn = a.variants & mask
235 let bVariantsAfterFn = b.variants & mask
236
237 // If the variants the same, we _can_ sort them
238 if (aVariantsAfterFn !== bVariantsAfterFn) {
239 continue
240 }
241
242 let result = aOptions.sort(
243 {
244 value: aOptions.value,
245 modifier: aOptions.modifier,
246 },
247 {
248 value: bOptions.value,
249 modifier: bOptions.modifier,
250 }
251 )
252 if (result !== 0) return result
253 }
254 }
255
256 // Sort variants in the order they were registered
257 if (a.variants !== b.variants) {
258 return a.variants - b.variants
259 }
260
261 // Make sure each rule returned by a parallel variant is sorted in ascending order
262 if (a.parallelIndex !== b.parallelIndex) {
263 return a.parallelIndex - b.parallelIndex
264 }
265
266 // Always sort arbitrary properties after other utilities
267 if (a.arbitrary !== b.arbitrary) {
268 return a.arbitrary - b.arbitrary
269 }
270
271 // Always sort arbitrary properties alphabetically
272 if (a.propertyOffset !== b.propertyOffset) {
273 return a.propertyOffset - b.propertyOffset
274 }
275
276 // Sort utilities, components, etc… in the order they were registered
277 return a.index - b.index
278 }
279
280 /**
281 * Arbitrary variants are recorded in the order they're encountered.
282 * This means that the order is not stable between environments and sets of content files.
283 *
284 * In order to make the order stable, we need to remap the arbitrary variant offsets to
285 * be in alphabetical order starting from the offset of the first arbitrary variant.
286 */
287 recalculateVariantOffsets() {
288 // Sort the variants by their name
289 let variants = Array.from(this.variantOffsets.entries())
290 .filter(([v]) => v.startsWith('['))
291 .sort(([a], [z]) => fastCompare(a, z))
292
293 // Sort the list of offsets
294 // This is not necessarily a discrete range of numbers which is why
295 // we're using sort instead of creating a range from min/max
296 let newOffsets = variants.map(([, offset]) => offset).sort((a, z) => bigSign(a - z))
297
298 // Create a map from the old offsets to the new offsets in the new sort order
299 /** @type {[bigint, bigint][]} */
300 let mapping = variants.map(([, oldOffset], i) => [oldOffset, newOffsets[i]])
301
302 // Remove any variants that will not move letting us skip
303 // remapping if everything happens to be in order
304 return mapping.filter(([a, z]) => a !== z)
305 }
306
307 /**
308 * @template T
309 * @param {[RuleOffset, T][]} list
310 * @returns {[RuleOffset, T][]}
311 */
312 remapArbitraryVariantOffsets(list) {
313 let mapping = this.recalculateVariantOffsets()
314
315 // No arbitrary variants? Nothing to do.
316 // Everyhing already in order? Nothing to do.
317 if (mapping.length === 0) {
318 return list
319 }
320
321 // Remap every variant offset in the list
322 return list.map((item) => {
323 let [offset, rule] = item
324
325 offset = {
326 ...offset,
327 variants: remapBitfield(offset.variants, mapping),
328 }
329
330 return [offset, rule]
331 })
332 }
333
334 /**
335 * @template T
336 * @param {[RuleOffset, T][]} list
337 * @returns {[RuleOffset, T][]}
338 */
339 sortArbitraryProperties(list) {
340 // Collect all known arbitrary properties
341 let known = new Set()
342
343 for (let [offset] of list) {
344 if (offset.arbitrary === 1n) {
345 known.add(offset.property)
346 }
347 }
348
349 // No arbitrary properties? Nothing to do.
350 if (known.size === 0) {
351 return list
352 }
353
354 // Sort the properties alphabetically
355 let properties = Array.from(known).sort()
356
357 // Create a map from the property name to its offset
358 let offsets = new Map()
359
360 let offset = 1n
361 for (let property of properties) {
362 offsets.set(property, offset++)
363 }
364
365 // Apply the sorted offsets to the list
366 return list.map((item) => {
367 let [offset, rule] = item
368
369 offset = {
370 ...offset,
371 propertyOffset: offsets.get(offset.property) ?? 0n,
372 }
373
374 return [offset, rule]
375 })
376 }
377
378 /**
379 * @template T
380 * @param {[RuleOffset, T][]} list
381 * @returns {[RuleOffset, T][]}
382 */
383 sort(list) {
384 // Sort arbitrary variants so they're in alphabetical order
385 list = this.remapArbitraryVariantOffsets(list)
386
387 // Sort arbitrary properties so they're in alphabetical order
388 list = this.sortArbitraryProperties(list)
389
390 return list.sort(([a], [b]) => bigSign(this.compare(a, b)))
391 }
392}
393
394/**
395 *
396 * @param {bigint[]} nums
397 * @returns {bigint|null}
398 */
399function max(nums) {
400 let max = null
401
402 for (const num of nums) {
403 max = max ?? num
404 max = max > num ? max : num
405 }
406
407 return max
408}
409
410/**
411 * A fast ASCII order string comparison function.
412 *
413 * Using `.sort()` without a custom compare function is faster
414 * But you can only use that if you're sorting an array of
415 * only strings. If you're sorting strings inside objects
416 * or arrays, you need must use a custom compare function.
417 *
418 * @param {string} a
419 * @param {string} b
420 */
421function fastCompare(a, b) {
422 let aLen = a.length
423 let bLen = b.length
424 let minLen = aLen < bLen ? aLen : bLen
425
426 for (let i = 0; i < minLen; i++) {
427 let cmp = a.charCodeAt(i) - b.charCodeAt(i)
428 if (cmp !== 0) return cmp
429 }
430
431 return aLen - bLen
432}
Note: See TracBrowser for help on using the repository browser.