Improve --theme() CSS function to only accept modern syntax (#15580)

This PR makes sure that the `--theme(…)` CSS function can only be used
with the modern syntax. For backwards compatibility, the `theme(…)`
function must be used with the older dot notation.
This commit is contained in:
Robin Malfait 2025-01-09 17:25:25 +01:00 committed by GitHub
parent 82589eb2c1
commit fa2c83eb1e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 3 deletions

View File

@ -146,7 +146,7 @@ describe('--spacing(…)', () => {
})
describe('--theme(…)', () => {
test('theme(--color-red-500)', async () => {
test('--theme(--color-red-500)', async () => {
expect(
await compileCss(css`
@theme {
@ -166,6 +166,19 @@ describe('--theme(…)', () => {
}"
`)
})
test('--theme(…) can only be used with CSS variables from your theme', async () => {
expect(() =>
compileCss(css`
@theme {
--color-red-500: #f00;
}
.red {
color: --theme(colors.red.500);
}
`),
).rejects.toThrowErrorMatchingInlineSnapshot(`[Error: The --theme(…) function can only be used with CSS variables from your theme.]`)
})
})
describe('theme(…)', () => {

View File

@ -5,11 +5,11 @@ import { withAlpha } from './utilities'
import { segment } from './utils/segment'
import * as ValueParser from './value-parser'
const functions: Record<string, (designSystem: DesignSystem, ...args: string[]) => any> = {
const functions: Record<string, (designSystem: DesignSystem, ...args: string[]) => string> = {
'--alpha': alpha,
'--spacing': spacing,
'--theme': theme,
theme,
theme: legacyTheme,
}
function alpha(_designSystem: DesignSystem, value: string, alpha: string, ...rest: string[]) {
@ -50,6 +50,14 @@ function spacing(designSystem: DesignSystem, value: string, ...rest: string[]) {
}
function theme(designSystem: DesignSystem, path: string, ...fallback: string[]) {
if (!path.startsWith('--')) {
throw new Error(`The --theme(…) function can only be used with CSS variables from your theme.`)
}
return legacyTheme(designSystem, path, ...fallback)
}
function legacyTheme(designSystem: DesignSystem, path: string, ...fallback: string[]) {
path = eventuallyUnquote(path)
let resolvedValue = designSystem.resolveThemeValue(path)