Skip to content
4 changes: 4 additions & 0 deletions .changelog/canonicalize-scope-variants.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### Fixed

- Canonicalization: don't replace `@scope` variants with unrelated `@scope` variants (e.g. `[@scope_(.card)]:flex` no longer becomes `in-blue:flex`)
- Canonicalization: don't treat `.foo .bar` and `.foo.bar` as the same in at-rule variants (e.g. `@scope (…)` or `@supports selector(…)`)
130 changes: 130 additions & 0 deletions packages/tailwindcss/src/canonicalize-candidates.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1149,6 +1149,7 @@ describe.each([['default'], ['with-variant'], ['important'], ['prefix']])('%s',
// Media queries
['[@media(pointer:fine)]:flex', 'pointer-fine:flex'],
['[@media_(pointer_:_fine)]:flex', 'pointer-fine:flex'],
['[@media_(pointer_:fine)]:flex', 'pointer-fine:flex'],
['[@media_not_(pointer_:_fine)]:flex', 'not-pointer-fine:flex'],
['[@media_print]:flex', 'print:flex'],
['[@media_not_print]:flex', 'not-print:flex'],
Expand Down Expand Up @@ -2100,6 +2101,135 @@ describe('regressions', () => {
])
expect(compare).not.toHaveBeenCalled()
})

test('does not treat different `@scope` variants as the same', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@custom-variant in-blue {
@scope ([data-theme='blue']) to ([data-theme]) {
@slot;
}
}
`,
{ base: __dirname },
)

expect(designSystem.canonicalizeCandidates(['[@scope_(.card)]:flex'])).toEqual([
'[@scope_(.card)]:flex',
])
expect(
designSystem.canonicalizeCandidates([
"[@scope_([data-theme='blue'])_to_([data-theme])]:flex",
]),
).toEqual(['in-blue:flex'])
})

test('does not treat a descendant combinator in an at-rule as a compound selector', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@custom-variant in-foo-bar {
@scope (.foo.bar) {
@slot;
}
}
@custom-variant supports-foo-bar {
@supports selector(.foo.bar) {
@slot;
}
}
@custom-variant in-foo-plus-bar {
@scope (.foo\+.bar) {
@slot;
}
}
@custom-variant in-foo-hex-plus-bar {
@scope (.foo\2b .bar) {
@slot;
}
}
@custom-variant in-foo-hex-plus-child-bar {
@scope (.foo\2b>.bar) {
@slot;
}
}
`,
{ base: __dirname },
)

// `.foo .bar` and `.foo.bar` match different elements
expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo_.bar)]:flex',
'[@supports_selector(.foo_.bar)]:flex',
]),
).toEqual(['[@scope_(.foo_.bar)]:flex', '[@supports_selector(.foo_.bar)]:flex'])

expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo.bar)]:flex',
'[@supports_selector(.foo.bar)]:flex',
]),
).toEqual(['in-foo-bar:flex', 'supports-foo-bar:flex'])

// An escaped `+` is part of the class name, so the space after it is
// still a descendant combinator
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\+_.bar)]:flex'])).toEqual([
'[@scope_(.foo\\+_.bar)]:flex',
])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\+.bar)]:flex'])).toEqual([
'in-foo-plus-bar:flex',
])

// A hex escape consumes one whitespace character after it, so only the
// second space is a descendant combinator
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b__.bar)]:flex'])).toEqual([
'[@scope_(.foo\\2b__.bar)]:flex',
])
expect(designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b_.bar)]:flex'])).toEqual([
'in-foo-hex-plus-bar:flex',
])

// The whitespace that ends a hex escape is optional when the next character
// can't be part of the escape
expect(
designSystem.canonicalizeCandidates([
'[@scope_(.foo\\2b>.bar)]:flex',
'[@scope_(.foo\\2b_>.bar)]:flex',
'[@scope_(.foo\\2b__>_.bar)]:flex',
]),
).toEqual(['in-foo-hex-plus-child-bar:flex'])
})

// CSS treats CRLF as one newline. The stylesheet parser already normalizes
// it, but a plugin variant keeps it in the at-rule params.
test('treats CRLF after a hex escape in an at-rule as one whitespace character', async () => {
let designSystem = await __unstable__loadDesignSystem(
css`
@tailwind utilities;
@plugin "my-plugin";
`,
{
async loadModule() {
return {
path: '',
base: '',
module: plugin(({ addVariant }) => {
addVariant('in-foo-hex-plus-bar', '@scope (.foo\\2b\r\n.bar) to (.limit)')
}),
}
},
},
)

expect(
designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b__.bar)_to_(.limit)]:flex']),
).toEqual(['[@scope_(.foo\\2b__.bar)_to_(.limit)]:flex'])
expect(
designSystem.canonicalizeCandidates(['[@scope_(.foo\\2b_.bar)_to_(.limit)]:flex']),
).toEqual(['in-foo-hex-plus-bar:flex'])
})
})

describe('normalizeEscapes', () => {
Expand Down
134 changes: 132 additions & 2 deletions packages/tailwindcss/src/canonicalize-candidates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3402,16 +3402,26 @@ function createVariantSignatureCache(

// Canonicalize selectors to their minimal form
walk(ast, (node) => {
// Variants that generate `@scope` rules wrap them in `context` nodes,
// which `toCss` doesn't print. Unwrap them so the signature includes
// the `@scope` rule.
if (node.kind === 'context') {
return WalkAction.Replace(node.nodes)
Comment thread
RobinMalfait marked this conversation as resolved.
Resolved
}

// At-rules
if (node.kind === 'at-rule') {
else 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(' ', '')
node.params = normalizeAtRuleParamsWhitespace(
node.params,
node.name !== '@media' && node.name !== '@container',
)
}
}

Expand Down Expand Up @@ -3494,6 +3504,126 @@ function createVariantSignatureCache(
})
}

// Remove whitespace in at-rule params that doesn't change their meaning, in a
// single pass. E.g.: `(width >= 64rem)` → `(width>=64rem)`.
//
// Whitespace between other characters is collapsed to a single space, because
// it can be a descendant combinator. E.g.: `@scope (.foo .bar)` and
// `@scope (.foo.bar)` match different elements. The same goes for whitespace
// before a `:` (`.foo :hover`), unless whitespace follows the `:` as well
// (`(pointer : fine)`), or the params can't contain selectors (`@media` and
// `@container`). Strings and escaped characters are kept as-is.
function normalizeAtRuleParamsWhitespace(params: string, canContainSelectors: boolean) {
let result = ''
let pendingSpace = false
let quote = 0

// Whether the last character in `result` is escaped. E.g.: the `+` in
// `.foo\+ .bar` is part of the class name, not a delimiter.
let escaped = false

// Whether `result` ends with a hex escape that has no whitespace after it
// yet. E.g.: `\2b` in `.foo\2b .bar`.
let openHexEscape = false

for (let i = 0; i < params.length; i++) {
let char = params.charCodeAt(i)

// Copy strings verbatim, including escapes
if (quote !== 0) {
result += params[i]
escaped = false
if (char === BACKSLASH && i + 1 < params.length) {
result += params[++i]
} else if (char === quote) {
quote = 0
}
continue
}

if (isWhitespace(char)) {
// Leading whitespace is dropped
pendingSpace = result.length > 0
continue
}

// Only keep whitespace between two characters that need it. Trailing
// whitespace is dropped, because no character follows it.
let space =
pendingSpace &&
(escaped || !dropsWhitespaceAfter(result.charCodeAt(result.length - 1))) &&
!dropsWhitespaceBefore(char) &&
!(char === COLON && (!canContainSelectors || isWhitespace(params.charCodeAt(i + 1))))
pendingSpace = false

// A hex escape needs whitespace to end it when a hex digit or another
// space follows. E.g.: `.foo\2b .bar` is `.foo\+ .bar`, but `.foo\2b>.bar`
// and `.foo\2b >.bar` are the same.
if (openHexEscape && (space || isHexDigit(char))) result += ' '
if (space) result += ' '

result += params[i]
escaped = false
openHexEscape = false

if (char === BACKSLASH && i + 1 < params.length) {
if (isHexDigit(params.charCodeAt(i + 1))) {
// A hex escape has up to 6 hex digits, and consumes one whitespace
// character after it. E.g.: `.foo\2b .bar` is `.foo\+.bar`, so only
// a second space would be a descendant combinator.
let end = i + 1
while (end < i + 7 && end < params.length && isHexDigit(params.charCodeAt(end))) end++
result += params.slice(i + 1, end)
i = end - 1
if (isWhitespace(params.charCodeAt(i + 1))) {
i++
Comment thread
RobinMalfait marked this conversation as resolved.
Resolved
Comment thread
RobinMalfait marked this conversation as resolved.
Resolved

// CSS treats CRLF as one newline
if (params.charCodeAt(i) === 0x0d && params.charCodeAt(i + 1) === 0x0a) i++
}
openHexEscape = true
} else {
result += params[++i]
}
escaped = true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} else if (char === SINGLE_QUOTE || char === DOUBLE_QUOTE) {
quote = char
}
}

return result
}

// `(`, `,`, `:`, `<`, `>`, `=`, `+`, `~` and `/`
function dropsWhitespaceAfter(char: number) {
return (
char === OPEN_PAREN ||
char === 0x2c ||
char === COLON ||
char === 0x3c ||
char === GREATER_THAN ||
char === 0x3d ||
char === 0x2b ||
char === 0x7e ||
char === 0x2f
)
}

// `(`, `)`, `,`, `<`, `>`, `=`, `+`, `~` and `/`
function dropsWhitespaceBefore(char: number) {
return (
char === OPEN_PAREN ||
char === CLOSE_PAREN ||
char === 0x2c ||
char === 0x3c ||
char === GREATER_THAN ||
char === 0x3d ||
char === 0x2b ||
char === 0x7e ||
char === 0x2f
)
}

export const PRE_COMPUTED_VARIANTS_KEY = Symbol()
function createPreComputedVariantsCache(
designSystem: DesignSystem,
Expand Down
Loading