Skip to content

Commit dda8f69

Browse files
committed
fix(theming): add compat for older browsers
1 parent 7a9b84d commit dda8f69

1 file changed

Lines changed: 22 additions & 11 deletions

File tree

packages/theming/src/token.ts

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -127,25 +127,34 @@ export class InMemoryThemeTokenRegistry implements ThemeTokenRegistry {
127127
*
128128
* - On server, the tokens will be written to
129129
* the root element's style properties as CSS variables.
130-
* - On browser, the tokens will be written to
131-
* a `CSSStyleSheet` object adopted by the document.
130+
* - On modern browser, the tokens will be written to
131+
* a constructed `CSSStyleSheet` object adopted by the document.
132+
* - On legacy browser, the tokens will be written to
133+
* a `<style>` element appended to the document head.
132134
*/
133135
export class WriteTokensToRootCssVariables implements ThemeTokenRegistry {
134136
#document = inject(DOCUMENT);
135137
#platform = inject(PLATFORM_ID);
136138

137139
#delegate: ThemeTokenRegistry;
138-
#stylesheet?: CSSStyleSheet;
140+
#stylesheet?: CSSStyleSheet | HTMLStyleElement;
139141

140142
constructor(delegate: ThemeTokenRegistry) {
141143
this.#delegate = delegate;
142-
if (isPlatformBrowser(this.#platform)) {
143-
this.#stylesheet = new window.CSSStyleSheet();
144-
this.#document.adoptedStyleSheets = [
145-
...(this.#document.adoptedStyleSheets ?? []),
146-
this.#stylesheet,
147-
];
148-
}
144+
if (isPlatformBrowser(this.#platform))
145+
try {
146+
this.#stylesheet = new window.CSSStyleSheet();
147+
this.#document.adoptedStyleSheets = [
148+
...(this.#document.adoptedStyleSheets ?? []),
149+
this.#stylesheet,
150+
];
151+
} catch (error) {
152+
if (!(error instanceof TypeError)) throw error;
153+
// constructable CSSStyleSheet not supported
154+
// fallback to legacy style element
155+
this.#stylesheet = this.#document.createElement('style');
156+
this.#document.head.append(this.#stylesheet);
157+
}
149158
}
150159

151160
get(name: string): string | null {
@@ -180,7 +189,9 @@ export class WriteTokensToRootCssVariables implements ThemeTokenRegistry {
180189
}
181190

182191
#writeAllToStylesheet() {
183-
this.#stylesheet?.replaceSync(this.#buildCssText());
192+
if (this.#stylesheet instanceof HTMLElement)
193+
this.#stylesheet.innerText = this.#buildCssText();
194+
else this.#stylesheet?.replaceSync(this.#buildCssText());
184195
}
185196
#writeToInlineStyles(name: string, value: string | null) {
186197
this.#document.documentElement.style.setProperty(

0 commit comments

Comments
 (0)