@@ -2,6 +2,7 @@ import { walk, WalkAction } from '../../../../tailwindcss/src/ast'
2
2
import { type Candidate , type Variant } from '../../../../tailwindcss/src/candidate'
3
3
import type { Config } from '../../../../tailwindcss/src/compat/plugin-api'
4
4
import type { DesignSystem } from '../../../../tailwindcss/src/design-system'
5
+ import * as ValueParser from '../../../../tailwindcss/src/value-parser'
5
6
import { printCandidate } from '../candidates'
6
7
7
8
export function automaticVarInjection (
@@ -73,15 +74,32 @@ export function automaticVarInjection(
73
74
}
74
75
75
76
function injectVar ( value : string ) : { value : string ; didChange : boolean } {
77
+ let ast = ValueParser . parse ( value )
78
+
76
79
let didChange = false
77
- if ( value . startsWith ( '--' ) ) {
78
- value = `var(${ value } )`
79
- didChange = true
80
- } else if ( value . startsWith ( ' --' ) ) {
81
- value = value . slice ( 1 )
82
- didChange = true
80
+ for ( let [ idx , node ] of ast . entries ( ) ) {
81
+ // Convert `--my-color` to `var(--my-color)`
82
+ // Except if:
83
+ // - It's a function like `--spacing(…)`
84
+ // - It's preceeded by a space, e.g.: `bg-[_--my-color]` -> `bg-[--my-color]`
85
+ if (
86
+ node . kind === 'word' &&
87
+ node . value . startsWith ( '--' ) &&
88
+ ! ( ast [ idx - 1 ] ?. kind === 'separator' && ast [ idx - 1 ] ?. value === ' ' )
89
+ ) {
90
+ node . value = `var(${ node . value } )`
91
+ didChange = true
92
+ }
93
+
94
+ // Remove the space "hack" before a variable. E.g.: `bg-[_--my-color]` ->
95
+ // `bg-[--my-color]`
96
+ else if ( node . kind === 'separator' && node . value === ' ' ) {
97
+ ast . splice ( idx , 1 )
98
+ didChange = true
99
+ }
83
100
}
84
- return { value, didChange }
101
+
102
+ return { value : ValueParser . toCss ( ast ) , didChange }
85
103
}
86
104
87
105
function injectVarIntoVariant ( designSystem : DesignSystem , variant : Variant ) : boolean {
0 commit comments