From ab3169646cd49eea2a3ac310f5e70ae111f1a8cd Mon Sep 17 00:00:00 2001 From: Robin Malfait Date: Fri, 31 Jul 2026 16:20:18 +0200 Subject: [PATCH 1/3] add failing tests --- .../src/canonicalize-candidates.test.ts | 98 ++++++++++++++++++- 1 file changed, 95 insertions(+), 3 deletions(-) diff --git a/packages/tailwindcss/src/canonicalize-candidates.test.ts b/packages/tailwindcss/src/canonicalize-candidates.test.ts index 03229f450bea..550a9c9a24ac 100644 --- a/packages/tailwindcss/src/canonicalize-candidates.test.ts +++ b/packages/tailwindcss/src/canonicalize-candidates.test.ts @@ -414,9 +414,11 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s', // This should still migrate the `theme(…)` syntax to the modern syntax. ['bg-[theme(colors.red.500/50%)]/50', 'bg-[--theme(--color-red-500/50%)]/50'], - // Variants, we can't use `var(…)` especially inside of `@media(…)`. We can - // still upgrade the `theme(…)` to the modern syntax. - ['max-[theme(screens.lg)]:flex', 'max-[--theme(--breakpoint-lg)]:flex'], + // Variants, we can't use `var(…)` especially inside of `@media(…)`. But + // since the value matches the `lg` breakpoint exactly, we can migrate to + // the `max-lg` variant. + ['max-[theme(screens.lg)]:flex', 'max-lg:flex'], + ['min-[theme(screens.lg)]:flex', 'lg:flex'], // We could also map to `min-lg:flex` // There are no variables for `--spacing` multiples, so we can't convert this ['max-[theme(spacing.4)]:flex', 'max-[theme(spacing.4)]:flex'], @@ -719,6 +721,7 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s', @import 'tailwindcss'; @theme { --*: initial; + --breakpoint-lg: 64rem; } ` @@ -735,6 +738,11 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s', ['[@media(scripting:_none)]:flex', 'noscript:flex'], ['[@media_(scripting:_none)]:flex', 'noscript:flex'], + // Arbitrary variants with media queries cannot use `var(…)`, but if an + // equivalent variant exists we can use that one instead. + ['[@media(width>=theme(screens.lg))]:flex', 'lg:flex'], // `min-lg:flex` would also be valid + ['[@media(width { + test.each([ + // Breakpoints (`--breakpoint-lg: 64rem`, `--breakpoint-md: 48rem`) + ['min-[64rem]:flex', 'lg:flex'], + ['max-[64rem]:flex', 'max-lg:flex'], + ['min-[48rem]:flex', 'md:flex'], + ['max-[48rem]:flex', 'max-md:flex'], + + // With the `rem` option set, equivalent `px` values should also be + // canonicalized to the breakpoint variants. + ['min-[1024px]:flex', 'lg:flex'], + ['max-[1024px]:flex', 'max-lg:flex'], + + // Container queries (`--container-md: 28rem`) + ['@min-[28rem]:flex', '@md:flex'], + ['@max-[28rem]:flex', '@max-md:flex'], + ['@min-[448px]:flex', '@md:flex'], + ['@max-[448px]:flex', '@max-md:flex'], + + // Values that don't map to a known breakpoint or container size should + // stay as-is. + ['min-[123px]:flex', 'min-[123px]:flex'], + ['max-[123px]:flex', 'max-[123px]:flex'], + ['@min-[123px]:flex', '@min-[123px]:flex'], + ['@max-[123px]:flex', '@max-[123px]:flex'], + + // Named variants that produce the same CSS should be kept as-is + ['min-lg:flex', 'min-lg:flex'], + ['@min-md:flex', '@min-md:flex'], + ])(testName, { timeout }, async (candidate, expected) => { + let input = css` + @import 'tailwindcss'; + ` + + await expectCanonicalization(input, candidate, expected) + }) + + test.each([ + // Without the `rem` option, `px` values cannot be safely converted to + // `rem` based breakpoints. + ['min-[1024px]:flex', 'min-[1024px]:flex'], + ['@min-[448px]:flex', '@min-[448px]:flex'], + + // Same unit still works without the `rem` option + ['min-[64rem]:flex', 'lg:flex'], + ['max-[64rem]:flex', 'max-lg:flex'], + ['@min-[28rem]:flex', '@md:flex'], + ['@max-[28rem]:flex', '@max-md:flex'], + ])(`${testName} (no rem option)`, { timeout }, async (candidate, expected) => { + let input = css` + @import 'tailwindcss'; + ` + + await expectCanonicalization(input, candidate, expected, { + collapse: true, + logicalToPhysical: true, + }) + }) + }) + describe('modernize arbitrary variants', () => { test.each([ // Arbitrary variants @@ -1546,4 +1615,27 @@ describe('regressions', () => { 'bg-brand-purple', ]) }) + + // https://github.com/tailwindlabs/tailwindcss/issues/20365 + test('canonicalizes min/max media query and container query variants', async () => { + let designSystem = await __unstable__loadDesignSystem( + css` + @tailwind utilities; + @theme { + --breakpoint-lg: 64rem; + --container-lg: 32rem; + --spacing: 0.25rem; + } + `, + { base: __dirname }, + ) + + expect(designSystem.canonicalizeCandidates(['min-[64rem]:flex'])).toEqual(['lg:flex']) + expect(designSystem.canonicalizeCandidates(['max-[64rem]:flex'])).toEqual(['max-lg:flex']) + expect(designSystem.canonicalizeCandidates(['@min-[32rem]:flex'])).toEqual(['@lg:flex']) + expect(designSystem.canonicalizeCandidates(['@max-[32rem]:flex'])).toEqual(['@max-lg:flex']) + expect(designSystem.canonicalizeCandidates(['min-[1024px]:flex'], { rem: 16 })).toEqual([ + 'lg:flex', + ]) + }) }) From 74d0783cb021b608fa346d37b4fa09e2aa0345b0 Mon Sep 17 00:00:00 2001 From: Robin Malfait Date: Fri, 31 Jul 2026 16:20:26 +0200 Subject: [PATCH 2/3] try converting variants with arbitrary values to builtin variants --- .../template/migrate-arbitrary-variants.ts | 10 +- .../src/canonicalize-candidates.ts | 223 ++++++++++-------- 2 files changed, 131 insertions(+), 102 deletions(-) diff --git a/packages/@tailwindcss-upgrade/src/codemods/template/migrate-arbitrary-variants.ts b/packages/@tailwindcss-upgrade/src/codemods/template/migrate-arbitrary-variants.ts index 58efb0421253..258ba1b331cd 100644 --- a/packages/@tailwindcss-upgrade/src/codemods/template/migrate-arbitrary-variants.ts +++ b/packages/@tailwindcss-upgrade/src/codemods/template/migrate-arbitrary-variants.ts @@ -16,8 +16,8 @@ export function migrateArbitraryVariants( rawCandidate: string, ): string { let designSystem = prepareDesignSystemStorage(baseDesignSystem) - let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY] - let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY] + let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(null) + let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY].get(null) for (let readonlyCandidate of designSystem.parseCandidate(rawCandidate)) { // We are only interested in the variants @@ -35,7 +35,11 @@ export function migrateArbitraryVariants( if (typeof targetSignature !== 'string') continue let foundVariants = variants.get(targetSignature) - if (foundVariants.length !== 1) continue + if (foundVariants.length === 0) continue + + // The variant is already in a canonical form, e.g.: `min-lg` and `lg` + // produce the same CSS, but both are valid so we keep them as-is. + if (foundVariants.includes(targetString)) continue let foundVariant = foundVariants[0] let parsedVariant = designSystem.parseVariant(foundVariant) diff --git a/packages/tailwindcss/src/canonicalize-candidates.ts b/packages/tailwindcss/src/canonicalize-candidates.ts index eb9d8697c824..ad2648e12af4 100644 --- a/packages/tailwindcss/src/canonicalize-candidates.ts +++ b/packages/tailwindcss/src/canonicalize-candidates.ts @@ -72,12 +72,11 @@ interface InternalCanonicalizeOptions { signatureOptions: SignatureOptions } +type RemValue = number | null + interface DesignSystem extends BaseDesignSystem { storage: { - [SIGNATURE_OPTIONS_KEY]: DefaultMap< - number | null, // Rem value - DefaultMap - > + [SIGNATURE_OPTIONS_KEY]: DefaultMap> [COMPARE_CANDIDATES_KEY]: DefaultMap< SignatureOptions, (a: Candidate | string, b: Candidate | string) => boolean @@ -107,8 +106,8 @@ interface DesignSystem extends BaseDesignSystem { DefaultMap>> > [PRE_COMPUTED_UTILITIES_KEY]: DefaultMap> - [VARIANT_SIGNATURE_KEY]: DefaultMap - [PRE_COMPUTED_VARIANTS_KEY]: DefaultMap + [VARIANT_SIGNATURE_KEY]: DefaultMap> + [PRE_COMPUTED_VARIANTS_KEY]: DefaultMap> } } @@ -1537,8 +1536,8 @@ function arbitraryVariants( options: InternalCanonicalizeOptions, ): Variant | Variant[] { let designSystem = options.designSystem - let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY] - let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY] + let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(options.signatureOptions.rem) + let variants = designSystem.storage[PRE_COMPUTED_VARIANTS_KEY].get(options.signatureOptions.rem) let iterator = walkVariants(variant) for (let [variant] of iterator) { @@ -1549,7 +1548,11 @@ function arbitraryVariants( if (typeof targetSignature !== 'string') continue let foundVariants = variants.get(targetSignature) - if (foundVariants.length !== 1) continue + if (foundVariants.length === 0) continue + + // The variant is already in a canonical form, e.g.: `min-lg` and `lg` + // produce the same CSS, but both are valid so we keep them as-is. + if (foundVariants.includes(targetString)) continue let foundVariant = foundVariants[0] let parsedVariant = designSystem.parseVariant(foundVariant) @@ -1769,7 +1772,7 @@ function modernizeArbitraryValuesVariant( ): Variant | Variant[] { let result = [variant] let designSystem = options.designSystem - let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY] + let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(options.signatureOptions.rem) let iterator = walkVariants(variant) for (let [variant, parent] of iterator) { @@ -2785,100 +2788,110 @@ export const VARIANT_SIGNATURE_KEY = Symbol() function createVariantSignatureCache( designSystem: DesignSystem, ): DesignSystem['storage'][typeof VARIANT_SIGNATURE_KEY] { - return new DefaultMap((variant) => { - 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}` - : variant - - // Use `@apply` to normalize the selector to `.x` - let ast: AstNode[] = [styleRule('.x', [atRule('@apply', `${variant}:flex`)])] - substituteAtApply(ast, designSystem) - - // Canonicalize selectors to their minimal form - walk(ast, (node) => { - // At-rules - if (node.kind === 'at-rule' && node.params.includes(' ')) { - node.params = node.params.replaceAll(' ', '') - } + return new DefaultMap((rem: number | null) => { + return new DefaultMap((variant) => { + 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}` + : variant - // Style rules - else if (node.kind === 'rule') { - let selectorAst = SelectorParser.parse(node.selector) - let changed = false - walk(selectorAst, (node) => { - // Assumption: when we have a list of selectors: `.foo, .bar` we - // want to mark this as changed because this will be re-printed as - // `.foo,.bar`. - // - // Similarly, when we receive a combinator like `.foo + .bar`, this - // will be printed as `.foo+.bar`. - // - // It could be that this was already optimal, but then this would be - // a no-op situation. - if (node.kind === 'list' || node.kind === 'combinator') { - changed = true + // Use `@apply` to normalize the selector to `.x` + let ast: AstNode[] = [styleRule('.x', [atRule('@apply', `${variant}:flex`)])] + substituteAtApply(ast, designSystem) + + // Canonicalize selectors to their minimal form + walk(ast, (node) => { + // At-rules + if (node.kind === 'at-rule') { + // Normalize dimensions such that equivalent values in different + // units are considered the same. E.g.: with a root font size of + // `16px`, `@media (width >= 64rem)` and `@media (width >= 1024px)` + // are equivalent. + node.params = constantFoldDeclaration(node.params, rem) + + if (node.params.includes(' ')) { + node.params = node.params.replaceAll(' ', '') } + } - // Remove unnecessary `:is(…)` selectors - else if (node.kind === 'function' && node.value === ':is') { - // A single selector inside of `:is(…)` can be replaced with the - // selector itself. + // Style rules + else if (node.kind === 'rule') { + let selectorAst = SelectorParser.parse(node.selector) + let changed = false + walk(selectorAst, (node) => { + // Assumption: when we have a list of selectors: `.foo, .bar` we + // want to mark this as changed because this will be re-printed as + // `.foo,.bar`. + // + // Similarly, when we receive a combinator like `.foo + .bar`, this + // will be printed as `.foo+.bar`. // - // E.g.: `:is(.foo)` → `.foo` - if (node.nodes.length === 1) { + // It could be that this was already optimal, but then this would be + // a no-op situation. + if (node.kind === 'list' || node.kind === 'combinator') { changed = true - return WalkAction.Replace(node.nodes) } - // A selector with the universal selector `*` followed by a pseudo - // class, can be replaced with the pseudo class itself. + // Remove unnecessary `:is(…)` selectors + else if (node.kind === 'function' && node.value === ':is') { + // A single selector inside of `:is(…)` can be replaced with the + // selector itself. + // + // E.g.: `:is(.foo)` → `.foo` + if (node.nodes.length === 1) { + changed = true + return WalkAction.Replace(node.nodes) + } + + // A selector with the universal selector `*` followed by a pseudo + // class, can be replaced with the pseudo class itself. + else if ( + node.nodes.length === 2 && + node.nodes[0].kind === 'selector' && + node.nodes[0].value === '*' && + node.nodes[1].kind === 'selector' && + node.nodes[1].value[0] === ':' + ) { + changed = true + return WalkAction.Replace(node.nodes[1]) + } + } + + // Ensure `*` exists before pseudo selectors inside of `:not(…)`, + // `:where(…)`, … + // + // E.g.: + // + // `:not(:first-child)` → `:not(*:first-child)` + // else if ( - node.nodes.length === 2 && - node.nodes[0].kind === 'selector' && - node.nodes[0].value === '*' && - node.nodes[1].kind === 'selector' && - node.nodes[1].value[0] === ':' + node.kind === 'function' && + node.value[0] === ':' && + node.nodes[0]?.kind === 'selector' && + node.nodes[0]?.value[0] === ':' ) { changed = true - return WalkAction.Replace(node.nodes[1]) + node.nodes.unshift({ kind: 'selector', value: '*' }) } - } + }) - // Ensure `*` exists before pseudo selectors inside of `:not(…)`, - // `:where(…)`, … - // - // E.g.: - // - // `:not(:first-child)` → `:not(*:first-child)` - // - else if ( - node.kind === 'function' && - node.value[0] === ':' && - node.nodes[0]?.kind === 'selector' && - node.nodes[0]?.value[0] === ':' - ) { - changed = true - node.nodes.unshift({ kind: 'selector', value: '*' }) + if (changed) { + node.selector = SelectorParser.toCss(selectorAst, true) } - }) - - if (changed) { - node.selector = SelectorParser.toCss(selectorAst, true) } - } - }) + }) - // Compute the final signature, by generating the CSS for the variant - let signature = toCss(ast) - return signature - } catch { - // A unique symbol is returned to ensure that 2 signatures resulting in - // `null` are not considered equal. - return Symbol() - } + // Compute the final signature, by generating the CSS for the variant + let signature = toCss(ast) + return signature + } catch { + // A unique symbol is returned to ensure that 2 signatures resulting in + // `null` are not considered equal. + return Symbol() + } + }) }) } @@ -2886,19 +2899,31 @@ export const PRE_COMPUTED_VARIANTS_KEY = Symbol() function createPreComputedVariantsCache( designSystem: DesignSystem, ): DesignSystem['storage'][typeof PRE_COMPUTED_VARIANTS_KEY] { - let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY] - let lookup = new DefaultMap(() => []) + return new DefaultMap((rem: number | null) => { + let signatures = designSystem.storage[VARIANT_SIGNATURE_KEY].get(rem) + let lookup = new DefaultMap(() => []) - // Actual static variants - for (let [root, variant] of designSystem.variants.entries()) { - if (variant.kind === 'static') { - let signature = signatures.get(root) - if (typeof signature !== 'string') continue - lookup.get(signature).push(root) + for (let [root, variant] of designSystem.variants.entries()) { + // Actual static variants + if (variant.kind === 'static') { + let signature = signatures.get(root) + if (typeof signature !== 'string') continue + lookup.get(signature).push(root) + } + + // Functional variants with known values, e.g.: `max-lg`, `@min-md`, … + else if (variant.kind === 'functional') { + for (let value of designSystem.variants.getCompletions(root)) { + let name = root === '@' ? `@${value}` : `${root}-${value}` + let signature = signatures.get(name) + if (typeof signature !== 'string') continue + lookup.get(signature).push(name) + } + } } - } - return lookup + return lookup + }) } function temporarilyDisableThemeInline(designSystem: DesignSystem, cb: () => T): T { From 6b778e5f3aa6d5cde4b9bddd48378c3a91011224 Mon Sep 17 00:00:00 2001 From: Robin Malfait Date: Mon, 3 Aug 2026 13:00:41 +0200 Subject: [PATCH 3/3] update changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f218684748be..59642fd84267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix flattening of `@scope` at-rules ([#20369](https://github.com/tailwindlabs/tailwindcss/pull/20369)) - Fix standalone declarations in `@scope`, wrap them in `:where(:scope)` ([#20369](https://github.com/tailwindlabs/tailwindcss/pull/20369)) - Always emit a space for empty fallback values in CSS variables (e.g. `var(--tw-blur,)` → `var(--tw-blur, )`) ([#20373](https://github.com/tailwindlabs/tailwindcss/pull/20373)) +- Canonicalization: convert arbitrary breakpoint and container query variants to named equivalents (e.g. `max-[64rem]` → `max-lg`) ([#20380](https://github.com/tailwindlabs/tailwindcss/pull/20380)) ## [4.3.3] - 2026-07-16