Skip to content

Commit d2998f7

Browse files
committed
Fix: Add support for Css variables
Fix: Optimized code structure Optimized code structure Fix: Add support for Css variables
1 parent 0b3a452 commit d2998f7

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/context/stylesheets.ts

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@ export class StyleSheets {
55
private rootSvg: Element
66
private readonly loadExternalSheets: boolean
77
private readonly styleSheets: CSSStyleSheet[]
8-
8+
private cssValueMap: Map<string, string>
99
constructor(rootSvg: Element, loadExtSheets: boolean) {
1010
this.rootSvg = rootSvg
1111
this.loadExternalSheets = loadExtSheets
1212
this.styleSheets = []
13+
this.cssValueMap = new Map()
1314
}
1415

1516
public async load(): Promise<void> {
@@ -88,6 +89,27 @@ export class StyleSheets {
8889
}
8990
}
9091

92+
getCssValue(selector: string): string | undefined {
93+
const value: string = selector
94+
.replace(/var\(/g, '')
95+
.replace(/\)/g, '')
96+
.replace(/^\s+|\s+$/g, '')
97+
if (this.cssValueMap.get(value)) {
98+
return this.cssValueMap.get(value)
99+
}
100+
for (const sheet of this.styleSheets) {
101+
for (let i = 0; i < sheet.cssRules.length; i++) {
102+
const rule = sheet.cssRules[i] as CSSStyleRule
103+
const res = rule.style.getPropertyValue(value)
104+
if (res) {
105+
this.cssValueMap.set(value, res)
106+
return res
107+
}
108+
}
109+
}
110+
return undefined
111+
}
112+
91113
private static splitSelectorAtCommas(selectorText: string): string[] {
92114
const initialRegex = /,|["']/g
93115
const closingDoubleQuotesRegex = /[^\\]["]/g
@@ -184,6 +206,17 @@ export class StyleSheets {
184206
const mostSpecificRule = matchingRules.reduce((previousValue, currentValue) =>
185207
compare(previousValue, currentValue) === 1 ? previousValue : currentValue
186208
)
187-
return mostSpecificRule.style.getPropertyValue(propertyCss) || undefined
209+
let resValue: string = mostSpecificRule.style.getPropertyValue(propertyCss)
210+
const varReg = /var\(.*?\)/gi
211+
if (resValue && varReg.test(resValue)) {
212+
const cssValueList: RegExpMatchArray = resValue.match(varReg) || []
213+
cssValueList.map(cssValue => {
214+
const res = this.getCssValue(cssValue)
215+
if (res) {
216+
resValue = resValue.replace(cssValue, res)
217+
}
218+
})
219+
}
220+
return resValue || undefined
188221
}
189222
}

0 commit comments

Comments
 (0)