11export function replaceCssVarsWithFallbacks ( str : string ) : string {
2+ return replaceCssVars ( str , ( name , fallback ) => {
3+ // If we have a fallback then we should use that value directly
4+ if ( fallback ) return fallback
5+
6+ // Don't replace the variable otherwise
7+ return null
8+ } )
9+ }
10+
11+ type CssVarReplacer = ( name : string , fallback : string | null ) => string | null
12+
13+ function replaceCssVars ( str : string , replace : CssVarReplacer ) : string {
214 for ( let i = 0 ; i < str . length ; ++ i ) {
315 if ( ! str . startsWith ( 'var(' , i ) ) continue
416
@@ -13,17 +25,25 @@ export function replaceCssVarsWithFallbacks(str: string): string {
1325 } else if ( str [ j ] === ',' && depth === 0 && fallbackStart === null ) {
1426 fallbackStart = j + 1
1527 } else if ( str [ j ] === ')' && depth === 0 ) {
16- if ( fallbackStart === null ) {
17- i = j + 1
28+ let varName = str . slice ( i + 4 , j )
29+ let fallback = fallbackStart === null ? null : str . slice ( fallbackStart , j )
30+ let replacement = replace ( varName , fallback )
31+
32+ if ( replacement !== null ) {
33+ str = str . slice ( 0 , i ) + replacement + str . slice ( j + 1 )
34+
35+ // We don't want to skip past anything here because `replacement`
36+ // might contain more var(…) calls in which case `i` will already
37+ // be pointing at the right spot to start looking for them
1838 break
1939 }
2040
21- let fallbackEnd = j
22- str = str . slice ( 0 , i ) + str . slice ( fallbackStart , fallbackEnd ) + str . slice ( j + 1 )
41+ // Skip past the closing parenthesis and onto the next `var(`
42+ i = j + 1
2343 break
2444 }
2545 }
2646 }
2747
2848 return str
29- }
49+ }
0 commit comments