Skip to content

Fix polyfill in combination with unused CSS variable removal #17555

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 7, 2025
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
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- Nothing yet!
### Fixed

- Ensure `color-mix(…)` polyfills do not cause used CSS variables to be removed ([#17555](https://github.com/tailwindlabs/tailwindcss/pull/17555))

## [4.1.3] - 2025-04-04

Expand Down
142 changes: 72 additions & 70 deletions packages/tailwindcss/src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,10 +266,8 @@ export function optimizeAst(
) {
let atRoots: AstNode[] = []
let seenAtProperties = new Set<string>()
let cssThemeVariables = new DefaultMap<
Extract<AstNode, { nodes: AstNode[] }>['nodes'],
Set<Declaration>
>(() => new Set())
let cssThemeVariables = new DefaultMap<AstNode[], Set<Declaration>>(() => new Set())
let colorMixDeclarations = new DefaultMap<AstNode[], Set<Declaration>>(() => new Set())
let keyframes = new Set<AtRule>()
let usedKeyframeNames = new Set()

Expand All @@ -280,7 +278,7 @@ export function optimizeAst(

function transform(
node: AstNode,
parent: Extract<AstNode, { nodes: AstNode[] }>['nodes'],
parent: AstNode[],
context: Record<string, string | boolean> = {},
depth = 0,
) {
Expand Down Expand Up @@ -326,71 +324,7 @@ export function optimizeAst(
// Create fallback values for usages of the `color-mix(…)` function that reference variables
// found in the theme config.
if (polyfills & Polyfills.ColorMix && node.value.includes('color-mix(')) {
let ast = ValueParser.parse(node.value)

let requiresPolyfill = false
ValueParser.walk(ast, (node, { replaceWith }) => {
if (node.kind !== 'function' || node.value !== 'color-mix') return

let containsUnresolvableVars = false
let containsCurrentcolor = false
ValueParser.walk(node.nodes, (node, { replaceWith }) => {
if (node.kind == 'word' && node.value.toLowerCase() === 'currentcolor') {
containsCurrentcolor = true
requiresPolyfill = true
return
}
if (node.kind !== 'function' || node.value !== 'var') return
let firstChild = node.nodes[0]
if (!firstChild || firstChild.kind !== 'word') return

requiresPolyfill = true

let inlinedColor = designSystem.theme.resolveValue(null, [firstChild.value as any])
if (!inlinedColor) {
containsUnresolvableVars = true
return
}

replaceWith({ kind: 'word', value: inlinedColor })
})

if (containsUnresolvableVars || containsCurrentcolor) {
let separatorIndex = node.nodes.findIndex(
(node) => node.kind === 'separator' && node.value.trim().includes(','),
)
if (separatorIndex === -1) return
let firstColorValue =
node.nodes.length > separatorIndex ? node.nodes[separatorIndex + 1] : null
if (!firstColorValue) return
replaceWith(firstColorValue)
} else if (requiresPolyfill) {
// Change the colorspace to `srgb` since the fallback values should not be represented as
// `oklab(…)` functions again as their support in Safari <16 is very limited.
let colorspace = node.nodes[2]
if (
colorspace.kind === 'word' &&
(colorspace.value === 'oklab' ||
colorspace.value === 'oklch' ||
colorspace.value === 'lab' ||
colorspace.value === 'lch')
) {
colorspace.value = 'srgb'
}
}
})

if (requiresPolyfill) {
let fallback = {
...node,
value: ValueParser.toCss(ast),
}
let colorMixQuery = rule('@supports (color: color-mix(in lab, red, red))', [node])

parent.push(fallback, colorMixQuery)

return
}
colorMixDeclarations.get(parent).add(node)
}

parent.push(node)
Expand Down Expand Up @@ -595,6 +529,74 @@ export function optimizeAst(
newAst = newAst.concat(atRoots)

// Fallbacks
// Create fallback values for usages of the `color-mix(…)` function that reference variables
// found in the theme config.
if (polyfills & Polyfills.ColorMix) {
for (let [parent, declarations] of colorMixDeclarations) {
for (let declaration of declarations) {
let idx = parent.indexOf(declaration)
// If the declaration is no longer present, we don't need to create a polyfill anymore
if (idx === -1 || declaration.value == null) continue

let ast = ValueParser.parse(declaration.value)
let requiresPolyfill = false
ValueParser.walk(ast, (node, { replaceWith }) => {
if (node.kind !== 'function' || node.value !== 'color-mix') return
let containsUnresolvableVars = false
let containsCurrentcolor = false
ValueParser.walk(node.nodes, (node, { replaceWith }) => {
if (node.kind == 'word' && node.value.toLowerCase() === 'currentcolor') {
containsCurrentcolor = true
requiresPolyfill = true
return
}
if (node.kind !== 'function' || node.value !== 'var') return
let firstChild = node.nodes[0]
if (!firstChild || firstChild.kind !== 'word') return
requiresPolyfill = true
let inlinedColor = designSystem.theme.resolveValue(null, [firstChild.value as any])
if (!inlinedColor) {
containsUnresolvableVars = true
return
}
replaceWith({ kind: 'word', value: inlinedColor })
})
if (containsUnresolvableVars || containsCurrentcolor) {
let separatorIndex = node.nodes.findIndex(
(node) => node.kind === 'separator' && node.value.trim().includes(','),
)
if (separatorIndex === -1) return
let firstColorValue =
node.nodes.length > separatorIndex ? node.nodes[separatorIndex + 1] : null
if (!firstColorValue) return
replaceWith(firstColorValue)
} else if (requiresPolyfill) {
// Change the colorspace to `srgb` since the fallback values should not be represented as
// `oklab(…)` functions again as their support in Safari <16 is very limited.
let colorspace = node.nodes[2]
if (
colorspace.kind === 'word' &&
(colorspace.value === 'oklab' ||
colorspace.value === 'oklch' ||
colorspace.value === 'lab' ||
colorspace.value === 'lch')
) {
colorspace.value = 'srgb'
}
}
})
if (!requiresPolyfill) continue

let fallback = {
...declaration,
value: ValueParser.toCss(ast),
}
let colorMixQuery = rule('@supports (color: color-mix(in lab, red, red))', [declaration])
parent.splice(idx, 1, fallback, colorMixQuery)
}
}
}

if (polyfills & Polyfills.AtProperty) {
let fallbackAst = []

Expand Down
26 changes: 13 additions & 13 deletions packages/tailwindcss/src/compat/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1164,21 +1164,21 @@ test('utilities must be prefixed', async () => {
// Prefixed utilities are generated
expect(compiler.build(['tw:underline', 'tw:hover:line-through', 'tw:custom']))
.toMatchInlineSnapshot(`
".tw\\:custom {
color: red;
}
.tw\\:underline {
text-decoration-line: underline;
}
.tw\\:hover\\:line-through {
&:hover {
@media (hover: hover) {
text-decoration-line: line-through;
".tw\\:custom {
color: red;
}
.tw\\:underline {
text-decoration-line: underline;
}
.tw\\:hover\\:line-through {
&:hover {
@media (hover: hover) {
text-decoration-line: line-through;
}
}
}
}
"
`)
"
`)

// Non-prefixed utilities are ignored
compiler = await compile(input, {
Expand Down
90 changes: 45 additions & 45 deletions packages/tailwindcss/src/compat/plugin-api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,14 +243,14 @@ describe('theme', async () => {

expect(compiler.build(['animate-duration-316', 'animate-duration-slow']))
.toMatchInlineSnapshot(`
".animate-duration-316 {
animation-duration: 316ms;
}
.animate-duration-slow {
animation-duration: 800ms;
}
"
`)
".animate-duration-316 {
animation-duration: 316ms;
}
.animate-duration-slow {
animation-duration: 800ms;
}
"
`)
})

test('plugin theme can have opacity modifiers', async () => {
Expand Down Expand Up @@ -3340,16 +3340,16 @@ describe('matchUtilities()', () => {
}

expect(optimizeCss(await run(['@w-1', 'hover:@w-1'])).trim()).toMatchInlineSnapshot(`
".\\@w-1 {
".\\@w-1 {
width: 1px;
}

@media (hover: hover) {
.hover\\:\\@w-1:hover {
width: 1px;
}

@media (hover: hover) {
.hover\\:\\@w-1:hover {
width: 1px;
}
}"
`)
}"
`)
})

test('custom functional utilities can return an array of rules', async () => {
Expand Down Expand Up @@ -4153,30 +4153,30 @@ describe('addComponents()', () => {

expect(optimizeCss(compiled.build(['btn', 'btn-blue', 'btn-red'])).trim())
.toMatchInlineSnapshot(`
".btn {
border-radius: .25rem;
padding: .5rem 1rem;
font-weight: 600;
}
".btn {
border-radius: .25rem;
padding: .5rem 1rem;
font-weight: 600;
}

.btn-blue {
color: #fff;
background-color: #3490dc;
}
.btn-blue {
color: #fff;
background-color: #3490dc;
}

.btn-blue:hover {
background-color: #2779bd;
}
.btn-blue:hover {
background-color: #2779bd;
}

.btn-red {
color: #fff;
background-color: #e3342f;
}
.btn-red {
color: #fff;
background-color: #e3342f;
}

.btn-red:hover {
background-color: #cc1f1a;
}"
`)
.btn-red:hover {
background-color: #cc1f1a;
}"
`)
})
})

Expand Down Expand Up @@ -4212,16 +4212,16 @@ describe('matchComponents()', () => {

expect(optimizeCss(compiled.build(['prose', 'sm:prose-sm', 'hover:prose-lg'])).trim())
.toMatchInlineSnapshot(`
".prose {
--container-size: normal;
}

@media (hover: hover) {
.hover\\:prose-lg:hover {
--container-size: lg;
".prose {
--container-size: normal;
}
}"
`)

@media (hover: hover) {
.hover\\:prose-lg:hover {
--container-size: lg;
}
}"
`)
})
})

Expand Down
16 changes: 8 additions & 8 deletions packages/tailwindcss/src/css-functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -756,10 +756,10 @@ describe('theme(…)', () => {
}
`),
).toMatchInlineSnapshot(`
".fam {
font-family: ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}"
`)
".fam {
font-family: ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}"
`)
})

test('theme(fontFamily.sans) (config)', async () => {
Expand All @@ -776,10 +776,10 @@ describe('theme(…)', () => {
)

expect(optimizeCss(compiled.build([])).trim()).toMatchInlineSnapshot(`
".fam {
font-family: ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}"
`)
".fam {
font-family: ui-sans-serif, system-ui, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol, Noto Color Emoji;
}"
`)
})
})

Expand Down
Loading