Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/canonicalize-reuse-collapse-lookups.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Canonicalization: improve performance of collapsing utilities (e.g. `mt-2 mb-2` → `my-2`) when the same utilities appear in many class lists or variants
46 changes: 46 additions & 0 deletions packages/tailwindcss/src/canonicalize-candidates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2230,6 +2230,52 @@ describe('regressions', () => {
designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b_.bar)_to_(.limit)]:flex']),
).toEqual(['in-foo-hex-plus-bar:flex'])
})

test('reuses dynamic utility lookups across candidate collapse groups', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@theme {
--spacing: 0.25rem;
}
`,
{ base: __dirname },
)

let options: CanonicalizeOptions = {
collapse: true,
logicalToPhysical: true,
rem: 16,
}

// Warm the pre-computed utilities, which walk the functional utilities
// once. A single candidate doesn't collapse, so this doesn't compute any
// dynamic utility lookups yet.
designSystem.canonicalizeCandidates(['mt-2'], options)

using keysSpy = vi.spyOn(designSystem.utilities, 'keys')

expect(
designSystem.canonicalizeCandidates(
['mt-2', 'mb-2', 'hover:mt-2', 'hover:mb-2', 'focus:mt-2', 'focus:mb-2'],
options,
),
).toEqual(['my-2', 'hover:my-2', 'focus:my-2'])

// One walk for each distinct candidate (`mt-2` and `mb-2`), not one for each
// variant group.
let functionalKeysCalls = keysSpy.mock.calls.filter((args) => args[0] === 'functional').length
expect(functionalKeysCalls).toBe(2)

// Re-running with repeated candidates across another variant group reuses the cached lookups
// without invoking `utilities.keys('functional')` again.
let countBefore = keysSpy.mock.calls.length
expect(designSystem.canonicalizeCandidates(['active:mt-2', 'active:mb-2'], options)).toEqual([
'active:my-2',
])
let countAfter = keysSpy.mock.calls.length
expect(countAfter).toBe(countBefore)
})
})

describe('normalizeEscapes', () => {
Expand Down
90 changes: 53 additions & 37 deletions packages/tailwindcss/src/canonicalize-candidates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ interface DesignSystem extends BaseDesignSystem {
SignatureOptions,
DefaultMap<string, DefaultMap<string, Set<string>>>
>
[DYNAMIC_UTILITIES_KEY]: DefaultMap<
SignatureOptions,
DefaultMap<string, DefaultMap<string, DefaultMap<string, Set<string>>>>
>
[PRE_COMPUTED_UTILITIES_KEY]: DefaultMap<SignatureOptions, DefaultMap<string, string[]>>
[VARIANT_SIGNATURE_KEY]: DefaultMap<RemValue, DefaultMap<string, string | symbol>>
[PRE_COMPUTED_VARIANTS_KEY]: DefaultMap<RemValue, DefaultMap<string, string[]>>
Expand All @@ -130,6 +134,7 @@ export function prepareDesignSystemStorage(
createUtilityThemeVariablesCache(designSystem)
designSystem.storage[STATIC_UTILITIES_KEY] ??= createStaticUtilitiesCache()
designSystem.storage[UTILITY_PROPERTIES_KEY] ??= createUtilityPropertiesCache(designSystem)
designSystem.storage[DYNAMIC_UTILITIES_KEY] ??= createDynamicUtilitiesCache(designSystem)
designSystem.storage[PRE_COMPUTED_UTILITIES_KEY] ??= createPreComputedUtilitiesCache(designSystem)
designSystem.storage[VARIANT_SIGNATURE_KEY] ??= createVariantSignatureCache(designSystem)
designSystem.storage[PRE_COMPUTED_VARIANTS_KEY] ??= createPreComputedVariantsCache(designSystem)
Expand Down Expand Up @@ -276,6 +281,7 @@ function collapseCandidates(options: InternalCanonicalizeOptions, candidates: st
designSystem.storage[UTILITY_PROPERTIES_KEY].get(signatureOptions)
let staticUtilities = designSystem.storage[STATIC_UTILITIES_KEY].get(signatureOptions)
let themeVariables = designSystem.storage[UTILITY_THEME_VARIABLES_KEY].get(signatureOptions)
let dynamicUtilities = designSystem.storage[DYNAMIC_UTILITIES_KEY].get(signatureOptions)

// For each candidate, compute the used properties and values. E.g.: `mt-1` → `margin-top` → `0.25rem`
//
Expand Down Expand Up @@ -339,43 +345,6 @@ function collapseCandidates(options: InternalCanonicalizeOptions, candidates: st
}
}

let dynamicUtilities = new DefaultMap((candidate: string) => {
let result = new DefaultMap(
(_property: string) => new DefaultMap((_value: string) => new Set<string>()),
)

let relevantProperties = new Set(computeUtilitiesPropertiesLookup.get(candidate).keys())
if (relevantProperties.size === 0) return result

for (let parsedCandidate of parseCandidate(designSystem, candidate)) {
if (parsedCandidate.kind !== 'functional' || parsedCandidate.value === null) {
continue
}

for (let root of designSystem.utilities.keys('functional')) {
if (root === parsedCandidate.root) continue // Skip self

let replacement = printUnprefixedCandidate(designSystem, {
...cloneCandidate(parsedCandidate),
root,
})

let propertyValues = computeUtilitiesPropertiesLookup.get(replacement)
for (let [property, values] of propertyValues) {
if (!relevantProperties.has(property)) continue // Skip properties that are not relevant for the current candidate

for (let value of values) {
result.get(property).get(value).add(replacement)
}
}
}

return result
}

return result
})

// For each property, lookup other utilities that also set this property and
// this exact value. If multiple properties are used, use the intersection of
// each property.
Expand Down Expand Up @@ -3315,6 +3284,53 @@ function createUtilityPropertiesCache(
})
}

const DYNAMIC_UTILITIES_KEY = Symbol()
function createDynamicUtilitiesCache(
designSystem: DesignSystem,
): DesignSystem['storage'][typeof DYNAMIC_UTILITIES_KEY] {
return new DefaultMap((signatureOptions: SignatureOptions) => {
let computeUtilitiesPropertiesLookup =
designSystem.storage[UTILITY_PROPERTIES_KEY].get(signatureOptions)

return new DefaultMap((candidate: string) => {
let result = new DefaultMap(
(_property: string) => new DefaultMap((_value: string) => new Set<string>()),
)

let relevantProperties = new Set(computeUtilitiesPropertiesLookup.get(candidate).keys())
if (relevantProperties.size === 0) return result

for (let parsedCandidate of parseCandidate(designSystem, candidate)) {
if (parsedCandidate.kind !== 'functional' || parsedCandidate.value === null) {
continue
}

for (let root of designSystem.utilities.keys('functional')) {
if (root === parsedCandidate.root) continue // Skip self

let replacement = printUnprefixedCandidate(designSystem, {
...cloneCandidate(parsedCandidate),
root,
})

let propertyValues = computeUtilitiesPropertiesLookup.get(replacement)
for (let [property, values] of propertyValues) {
if (!relevantProperties.has(property)) continue // Skip properties that are not relevant for the current candidate

for (let value of values) {
result.get(property).get(value).add(replacement)
}
}
}

return result
}

return result
})
})
}

// For all static utilities in the system, compute a lookup table that maps the
// utility signature to the utility name. This is used to find the utility name
// for a given utility signature.
Expand Down
Loading