Skip to content
Open
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
4 changes: 4 additions & 0 deletions .changelog/canonicalize-collapse-static-utilities.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Fixed

- Canonicalization: collapse static utilities without depending on the candidates that were canonicalized before (e.g. `overflow-x-hidden overflow-y-hidden` → `overflow-hidden`)
- Canonicalization: canonicalize utilities and variants whose name starts with the prefix (e.g. `o:outline-[2px]` → `o:outline-2` and `f:[&:focus]:flex` → `f:focus:flex`)
149 changes: 149 additions & 0 deletions packages/tailwindcss/src/canonicalize-candidates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1804,6 +1804,155 @@ describe('regressions', () => {
},
)

// https://github.com/tailwindlabs/tailwindcss/issues/20602
test.each([
[['overflow-x-hidden', 'overflow-y-hidden'], ['overflow-hidden']],
[['overflow-x-clip', 'overflow-y-clip'], ['overflow-clip']],
[['overscroll-x-none', 'overscroll-y-none'], ['overscroll-none']],
[['overflow-x-auto', 'overflow-y-auto'], ['overflow-auto']],
[['hover:overflow-x-hidden', 'hover:overflow-y-hidden'], ['hover:overflow-hidden']],
])(
'collapsing static utilities does not depend on previously canonicalized candidates',
async (candidates, expected) => {
// A new design system, so that no other candidates were canonicalized before
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
`,
{ base: __dirname },
)

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

expect(designSystem.canonicalizeCandidates(candidates, options)).toEqual(expected)

// A candidate with a value pre-computes all utilities, which must not
// change the result
designSystem.canonicalizeCandidates(['p-4'], options)
expect(designSystem.canonicalizeCandidates(candidates, options)).toEqual(expected)
},
)

test.each([
['', ['overflow-x-hidden', 'overflow-y-hidden'], ['overflow-hidden']],
['tw', ['tw:overflow-x-hidden', 'tw:overflow-y-hidden'], ['tw:overflow-hidden']],
])(
'collapsing static utilities does not pre-compute all utilities (prefix: "%s")',
async (prefix, candidates, expected) => {
let designSystem = await __unstable__loadDesignSystem(
prefix
? css`
@theme prefix(${prefix}) {
}
@tailwind utilities;
`
: css`
@tailwind utilities;
`,
{ base: __dirname },
)

// Pre-computing all utilities starts from the class list, and takes
// ~800ms with the default theme
let getClassList = vi.spyOn(designSystem, 'getClassList')

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

expect(designSystem.canonicalizeCandidates(candidates, options)).toEqual(expected)
expect(getClassList).not.toHaveBeenCalled()
},
)

test('collapsing a group with a single utility does not compute the static utilities', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
`,
{ base: __dirname },
)

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

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

// `group` is not a utility, so `flex` can't be collapsed with anything
expect(designSystem.canonicalizeCandidates(['group', 'flex'], options)).toEqual([
'group',
'flex',
])
expect(keys).not.toHaveBeenCalledWith('static')
})

test.each([
['', ['p-4'], ['overflow-x-hidden', 'overflow-y-hidden'], ['overflow-hidden']],
['tw', ['tw:p-4'], ['tw:overflow-x-hidden', 'tw:overflow-y-hidden'], ['tw:overflow-hidden']],
// A prefix that is also the start of a utility name, like `o` in `overflow-hidden`
['o', ['o:p-4'], ['o:overflow-x-hidden', 'o:overflow-y-hidden'], ['o:overflow-hidden']],
])(
'collapsing static utilities after pre-computing all utilities does not compute the static utilities again (prefix: "%s")',
async (prefix, before, candidates, expected) => {
let designSystem = await __unstable__loadDesignSystem(
prefix
? css`
@theme prefix(${prefix}) {
}
@tailwind utilities;
`
: css`
@tailwind utilities;
`,
{ base: __dirname },
)

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

// A candidate with a value pre-computes all utilities, which includes the
// static utilities
designSystem.canonicalizeCandidates(before, options)

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

expect(designSystem.canonicalizeCandidates(candidates, options)).toEqual(expected)
expect(keys).not.toHaveBeenCalledWith('static')
},
)

test.each([
['tw', 'tw:[&:focus]:flex', 'tw:focus:flex'],
// A prefix that is also the start of a variant name, like `f` in `focus`
['f', 'f:[&:focus]:flex', 'f:focus:flex'],
])(
'canonicalizing variants with a prefix (prefix: "%s")',
async (prefix, candidate, expected) => {
let designSystem = await __unstable__loadDesignSystem(
css`
@theme prefix(${prefix}) {
}
@tailwind utilities;
`,
{ base: __dirname },
)

expect(designSystem.canonicalizeCandidates([candidate], { rem: 16 })).toEqual([expected])
},
)

// https://github.com/tailwindlabs/tailwindcss/issues/20051
test(
'does not crash when plugin matchComponents rejects speculative values during collapse',
Expand Down
59 changes: 56 additions & 3 deletions packages/tailwindcss/src/canonicalize-candidates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ interface DesignSystem extends BaseDesignSystem {
SignatureOptions,
DefaultMap<string, DefaultMap<string, Set<string>>>
>
[PRE_COMPUTED_STATIC_UTILITIES_KEY]: DefaultMap<SignatureOptions, Set<string>>
[UTILITY_PROPERTIES_KEY]: DefaultMap<
SignatureOptions,
DefaultMap<string, DefaultMap<string, Set<string>>>
Expand Down Expand Up @@ -133,6 +134,8 @@ export function prepareDesignSystemStorage(
designSystem.storage[UTILITY_THEME_VARIABLES_KEY] ??=
createUtilityThemeVariablesCache(designSystem)
designSystem.storage[STATIC_UTILITIES_KEY] ??= createStaticUtilitiesCache()
designSystem.storage[PRE_COMPUTED_STATIC_UTILITIES_KEY] ??=
createPreComputedStaticUtilitiesCache(designSystem)
designSystem.storage[UTILITY_PROPERTIES_KEY] ??= createUtilityPropertiesCache(designSystem)
designSystem.storage[DYNAMIC_UTILITIES_KEY] ??= createDynamicUtilitiesCache(designSystem)
designSystem.storage[PRE_COMPUTED_UTILITIES_KEY] ??= createPreComputedUtilitiesCache(designSystem)
Expand Down Expand Up @@ -276,6 +279,10 @@ function collapseCandidates(options: InternalCanonicalizeOptions, candidates: st
return Array.from(result)

function collapseGroup(candidates: string[]) {
// A single candidate can't be collapsed with anything, so there is nothing
// to do. E.g.: `flex hover:underline`
if (candidates.length < 2) return candidates

let signatureOptions = options.signatureOptions
let computeUtilitiesPropertiesLookup =
designSystem.storage[UTILITY_PROPERTIES_KEY].get(signatureOptions)
Expand All @@ -291,6 +298,22 @@ function collapseCandidates(options: InternalCanonicalizeOptions, candidates: st
computeUtilitiesPropertiesLookup.get(candidate),
)

// A candidate without properties, like a class that isn't a utility, can't
// be collapsed with anything. E.g.: `group flex`
if (candidatePropertiesValues.filter((propertyValues) => propertyValues.size > 0).length < 2) {
return candidates
}

// A utility is only added to the index of static utilities once its
// properties are computed. Pre-computing all utilities does that, but it
// only happens for candidates with a value like `p-4`. So make sure that
// the static utilities are in there, otherwise the result depends on the
// candidates that were canonicalized before. E.g.: `overflow-x-hidden
// overflow-y-hidden` → `overflow-hidden`
if (!designSystem.storage[PRE_COMPUTED_UTILITIES_KEY].has(signatureOptions)) {
designSystem.storage[PRE_COMPUTED_STATIC_UTILITIES_KEY].get(signatureOptions)
}

// Hard-coded optimization: if any candidate sets `line-height` and another
// candidate sets `font-size`, we pre-compute the `text-*` utilities with
// this line-height to try and collapse to those combined values.
Expand Down Expand Up @@ -2923,7 +2946,7 @@ function compileUtilitySignatureAst(
) {
// Ensure the prefix is added to the utility if it is not already present.
utility =
designSystem.theme.prefix && !utility.startsWith(designSystem.theme.prefix)
designSystem.theme.prefix && !utility.startsWith(`${designSystem.theme.prefix}:`)
? `${designSystem.theme.prefix}:${utility}`
: utility

Expand Down Expand Up @@ -3248,6 +3271,36 @@ function createStaticUtilitiesCache(): DesignSystem['storage'][typeof STATIC_UTI
})
}

// Compute the properties of the static utilities, which adds them to the index
// of static utilities. These are the static utilities that pre-computing all
// utilities computes as well, but this takes a few milliseconds, while
// pre-computing all utilities takes almost a second with the default theme.
const PRE_COMPUTED_STATIC_UTILITIES_KEY = Symbol()
function createPreComputedStaticUtilitiesCache(
designSystem: DesignSystem,
): DesignSystem['storage'][typeof PRE_COMPUTED_STATIC_UTILITIES_KEY] {
return new DefaultMap((options: SignatureOptions) => {
let computeUtilitiesPropertiesLookup = designSystem.storage[UTILITY_PROPERTIES_KEY].get(options)
let prefix = designSystem.theme.prefix ? `${designSystem.theme.prefix}:` : ''

let utilities = new Set<string>()
for (let utility of designSystem.utilities.keys('static')) {
// Skip the utilities that the class list skips, like deprecated ones.
// E.g.: `bg-gradient-to-r`
if (designSystem.utilities.getCompletions(utility).length === 0) continue

// Use the same name as the candidates that we collapse, which have the
// prefix. E.g.: `tw:flex`
utility = `${prefix}${utility}`
if (computeUtilitiesPropertiesLookup.get(utility).size > 0) {
utilities.add(utility)
}
}

return utilities
})
}

const UTILITY_PROPERTIES_KEY = Symbol()
function createUtilityPropertiesCache(
designSystem: DesignSystem,
Expand All @@ -3256,7 +3309,7 @@ function createUtilityPropertiesCache(
return new DefaultMap((className) => {
let localPropertyValueLookup = new DefaultMap((_property) => new Set<string>())

if (designSystem.theme.prefix && !className.startsWith(designSystem.theme.prefix)) {
if (designSystem.theme.prefix && !className.startsWith(`${designSystem.theme.prefix}:`)) {
className = `${designSystem.theme.prefix}:${className}`
}
let parsed = designSystem.parseCandidate(className)
Expand Down Expand Up @@ -3408,7 +3461,7 @@ function createVariantSignatureCache(
try {
// Ensure the prefix is added to the utility if it is not already present.
variant =
designSystem.theme.prefix && !variant.startsWith(designSystem.theme.prefix)
designSystem.theme.prefix && !variant.startsWith(`${designSystem.theme.prefix}:`)
? `${designSystem.theme.prefix}:${variant}`
: variant

Expand Down