Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
18 changes: 8 additions & 10 deletions src/utils/shadow-root.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { BUILD } from '@app-data';
import { globalStyles } from '@app-globals';
import { supportsConstructableStylesheets } from '@platform';
import { CMP_FLAGS } from '@utils';

import type * as d from '../declarations';
import { createStyleSheetIfNeededAndSupported } from './style';

let globalStyleSheet: CSSStyleSheet | null | undefined;

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

/**
* If constructable stylesheets are supported, we can use them to
* add the global styles to the shadow root.
*/
if (supportsConstructableStylesheets) {
const sheet = new CSSStyleSheet();
sheet.replaceSync(globalStyles);
shadowRoot.adoptedStyleSheets.push(sheet);
}
// 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);
}
16 changes: 16 additions & 0 deletions src/utils/style.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { supportsConstructableStylesheets } from '@platform';

/**
* If (1) styles is not empty string, and (2) constructable stylesheets are supported,
* then make a stylesheet.
*
* @param styles - The styles to add to the stylesheet. If empty string, then no stylesheet is returned.
* @returns A stylesheet if it can be created, otherwise undefined.
*/
export function createStyleSheetIfNeededAndSupported(styles: string): CSSStyleSheet | undefined {
if (!styles || !supportsConstructableStylesheets) return undefined;

const sheet = new CSSStyleSheet();
sheet.replaceSync(styles);
return sheet;
}
Loading