Skip to content

Commit d502f99

Browse files
committed
Add util for resolving a CSS custom property value
1 parent 9c18667 commit d502f99

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

projects/js-packages/charts/src/utils/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,6 @@ export { mergeThemes } from './merge-themes';
2323

2424
// Color utilities
2525
export * from './color-utils';
26+
27+
// CSS utilities
28+
export { resolveCssVariable } from './resolve-css-var';
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* Resolves a CSS custom property (variable) to its computed value
3+
*
4+
* @param cssVar - A CSS variable string like 'var(--my-color)'
5+
* @return The computed value or null if invalid
6+
*/
7+
export const resolveCssVariable = ( cssVar: string ): string | null => {
8+
if ( typeof window === 'undefined' || typeof document === 'undefined' ) {
9+
return null;
10+
}
11+
12+
// Extract the variable name from var(--variable-name)
13+
const match = cssVar.match( /var\(\s*(--[^),\s]+)\s*(?:,\s*([^)]+))?\s*\)/ );
14+
if ( ! match ) {
15+
return null;
16+
}
17+
18+
const varName = match[ 1 ];
19+
const fallback = match[ 2 ];
20+
21+
// Get computed style from root element
22+
const computedValue = getComputedStyle( document.documentElement )
23+
.getPropertyValue( varName )
24+
.trim();
25+
26+
return computedValue || fallback || null;
27+
};

0 commit comments

Comments
 (0)