1
- import type { State } from " ./state"
1
+ import type { State } from ' ./state'
2
2
3
3
export function replaceCssVarsWithFallbacks ( state : State , str : string ) : string {
4
4
return replaceCssVars ( str , ( name , fallback ) => {
5
- // If we have a fallback then we should use that value directly
6
- if ( fallback ) return fallback
7
-
8
- // In a v4 project we should attempt to look up the value from the theme
9
- // this is because not all v4 projects will generate utilities where
10
- // variables have fallbacks
5
+ // Replace with the value from the design system first. The design system
6
+ // take precedences over other sources as that emulates the behavior of a
7
+ // browser where the fallback is only used if the variable is defined.
11
8
if ( state . designSystem && name . startsWith ( '--' ) ) {
12
- return state . designSystem . resolveThemeValue ?.( name ) ?? null
9
+ let value = state . designSystem . resolveThemeValue ?.( name ) ?? null
10
+ if ( value !== null ) return value
11
+ }
12
+
13
+ if ( fallback ) {
14
+ return fallback
13
15
}
14
16
15
- // Don't replace the variable otherwise
17
+ // Don't touch it since there's no suitable replacement
16
18
return null
17
19
} )
18
20
}
@@ -34,8 +36,17 @@ function replaceCssVars(str: string, replace: CssVarReplacer): string {
34
36
} else if ( str [ j ] === ',' && depth === 0 && fallbackStart === null ) {
35
37
fallbackStart = j + 1
36
38
} else if ( str [ j ] === ')' && depth === 0 ) {
37
- let varName = str . slice ( i + 4 , j )
38
- let fallback = fallbackStart === null ? null : str . slice ( fallbackStart , j )
39
+ let varName : string
40
+ let fallback : string | null
41
+
42
+ if ( fallbackStart === null ) {
43
+ varName = str . slice ( i + 4 , j )
44
+ fallback = null
45
+ } else {
46
+ varName = str . slice ( i + 4 , fallbackStart - 1 )
47
+ fallback = str . slice ( fallbackStart , j )
48
+ }
49
+
39
50
let replacement = replace ( varName , fallback )
40
51
41
52
if ( replacement !== null ) {
@@ -47,7 +58,8 @@ function replaceCssVars(str: string, replace: CssVarReplacer): string {
47
58
break
48
59
}
49
60
50
- // Skip past the closing parenthesis and onto the next `var(`
61
+ // It can't be replaced so we can avoid unncessary work by skipping over
62
+ // the entire var(…) call.
51
63
i = j + 1
52
64
break
53
65
}
0 commit comments