1
1
export 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 {
2
14
for ( let i = 0 ; i < str . length ; ++ i ) {
3
15
if ( ! str . startsWith ( 'var(' , i ) ) continue
4
16
@@ -13,17 +25,25 @@ export function replaceCssVarsWithFallbacks(str: string): string {
13
25
} else if ( str [ j ] === ',' && depth === 0 && fallbackStart === null ) {
14
26
fallbackStart = j + 1
15
27
} 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
18
38
break
19
39
}
20
40
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
23
43
break
24
44
}
25
45
}
26
46
}
27
47
28
48
return str
29
- }
49
+ }
0 commit comments