Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
simplify
  • Loading branch information
aeharding committed Jun 28, 2025
commit 1414c08e6fd1e523f50310b40f5eeae6f39367f0
31 changes: 5 additions & 26 deletions src/utils/shadow-root.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,7 @@ import { CMP_FLAGS } from '@utils';
import type * as d from '../declarations';
import { createStyleSheetIfNeededAndSupported } from './style';

/**
* Create a single, shared global stylesheet for all shadow roots.
*
* This singleton avoids the performance and memory hit of
* creating a new CSSStyleSheet every time a shadow root is created.
*
* Lazy getter due to "ReferenceError: Cannot access 'globalStyles'
* before initialization" if setup is run at root level
*
* internal state:
* - undefined: not yet computed
* - null: computed and cached, but stylesheet not needed/supported
* - CSSStyleSheet: computed and cached
*
* @returns CSSStyleSheet | null
*/
const getLazyGlobalStyleSheet = (() => {
let value: CSSStyleSheet | null | undefined;

return () => {
if (value === undefined) value = createStyleSheetIfNeededAndSupported(globalStyles) ?? null;

return value;
};
})();
let globalStyleSheet: CSSStyleSheet | null | undefined;

export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeMeta) {
const shadowRoot = BUILD.shadowDelegatesFocus
Expand All @@ -39,6 +15,9 @@ export function createShadowRoot(this: HTMLElement, cmpMeta: d.ComponentRuntimeM
})
: this.attachShadow({ mode: 'open' });

const globalStyleSheet = getLazyGlobalStyleSheet();
// Initialize if undefined, set to CSSStyleSheet or null
if (globalStyleSheet === undefined) globalStyleSheet = createStyleSheetIfNeededAndSupported(globalStyles) ?? null;

// Use initialized global stylesheet if available
if (globalStyleSheet) shadowRoot.adoptedStyleSheets.push(globalStyleSheet);
}
Loading