11import { isServer } from 'lit' ;
22
3- import { isDefined } from '../components/common/util.js' ;
4-
53function isStyleRule ( rule : CSSRule ) : rule is CSSStyleRule {
6- return ! ! rule && 'style' in rule ;
4+ return rule != null && 'style' in rule ;
75}
86
97function cssKeyToJsKey ( key : string ) : string {
10- return key . replace ( '--' , '' ) . replace ( / - ./ g, ( x ) => x . toUpperCase ( ) [ 1 ] ) ;
8+ return key . replace ( / ^ - - | - ./ g, ( match ) => {
9+ return match . startsWith ( '--' ) ? '' : match . charAt ( 1 ) . toUpperCase ( ) ;
10+ } ) ;
1111}
1212
1313function getAllCssVariableNames ( ) : Set < string > {
1414 const cssVars = new Set < string > ( ) ;
15+ const styleSheets = Array . from ( document . styleSheets ) ;
1516
16- /* c8 ignore next 3 */
17- if ( isServer || ! isDefined ( globalThis . document ) ) {
18- return cssVars ;
19- }
17+ for ( const sheet of styleSheets ) {
18+ let rules : CSSRuleList | undefined ;
2019
21- // Filter out any external stylesheets which throw CORS errors
22- const styleSheets = Array . from ( globalThis . document . styleSheets ) . filter (
23- ( sheet ) => {
24- try {
25- return sheet . cssRules ;
26- } catch {
27- return false ;
28- }
20+ // Potential CORS or access errors
21+ try {
22+ rules = sheet . cssRules ;
23+ } catch {
24+ continue ;
2925 }
30- ) ;
3126
32- for ( const sheet of styleSheets ) {
33- const rules = Array . from ( sheet . cssRules ) . filter ( isStyleRule ) ;
27+ if ( ! rules ) {
28+ continue ;
29+ }
3430
35- for ( const rule of rules ) {
36- Array . from ( rule . style ) . forEach ( ( style ) => {
37- if ( style . startsWith ( '--' ) ) {
38- cssVars . add ( style ) ;
31+ for ( const rule of Array . from ( rules ) ) {
32+ if ( isStyleRule ( rule ) ) {
33+ const length = rule . style . length ;
34+
35+ for ( let i = 0 ; i < length ; i ++ ) {
36+ const style = rule . style [ i ] ;
37+
38+ if ( style . startsWith ( '--' ) ) {
39+ cssVars . add ( style ) ;
40+ }
3941 }
40- } ) ;
42+ }
4143 }
4244 }
4345
@@ -50,13 +52,7 @@ function getElementCssVariables(
5052 pseudo ?: string
5153) : Record < string , string > {
5254 const cssVars : Record < string , string > = { } ;
53-
54- /* c8 ignore next 3 */
55- if ( ! isDefined ( globalThis . getComputedStyle ) ) {
56- return cssVars ;
57- }
58-
59- const styles = globalThis . getComputedStyle ( element , pseudo ) ;
55+ const styles = getComputedStyle ( element , pseudo ) ;
6056
6157 for ( const key of allCssVars ) {
6258 const value = styles . getPropertyValue ( key ) ;
@@ -71,10 +67,10 @@ function getElementCssVariables(
7167
7268export function getAllCssVariables ( ) : Record < string , string > {
7369 /* c8 ignore next 2 */
74- return isServer || ! isDefined ( globalThis . document )
70+ return isServer
7571 ? { }
7672 : getElementCssVariables (
7773 getAllCssVariableNames ( ) ,
78- globalThis . document . documentElement
74+ document . documentElement
7975 ) ;
8076}
0 commit comments