Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(Theme): keep shared injected CSS until the last Theme instance unmounts (#10178)

Cindy Zhangfa6174fa5e26
diff --git a/.changeset/theme-shared-css-refcount.md b/.changeset/theme-shared-css-refcount.md
new file mode 100644
index 0000000000..c99762a892
--- /dev/null
+++ b/.changeset/theme-shared-css-refcount.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `Theme` keeps its runtime-injected CSS in the document until the last mounted `Theme` using that theme unmounts. Before, the `Theme` that injected the CSS first owned the shared `<style>` tags, so unmounting it (a nested `Theme` around a dialog that mounted first, for example) stripped the component overrides and prose defaults from every other `Theme` still using that theme. Built themes, which import their CSS as a file, are unaffected.
+
+@thecodebasedot
diff --git a/packages/core/src/theme/Theme.test.tsx b/packages/core/src/theme/Theme.test.tsx
index dd79f1bb6e..f0631d8dd5 100644
--- a/packages/core/src/theme/Theme.test.tsx
+++ b/packages/core/src/theme/Theme.test.tsx
@@ -1,7 +1,9 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
-import {render, cleanup} from '@testing-library/react';
+import {hydrateRoot, type Root} from 'react-dom/client';
+import {renderToString} from 'react-dom/server';
+import {act, render, cleanup} from '@testing-library/react';
import React from 'react';
import {Theme} from './Theme';
import {defineTheme} from './defineTheme';
@@ -334,4 +336,174 @@ describe('Theme', () => {
expect(injected).toContain('@layer reset, astryx-base, astryx-theme;');
expect(injected).not.toContain(':root {');
});
+
+ it('keeps the shared CSS until the last Theme using it unmounts', () => {
+ function App({showInner}: {showInner: boolean}) {
+ return (
+ <Theme theme={testTheme}>
+ <span>outer</span>
+ {showInner && (
+ <Theme theme={testTheme}>
+ <span>inner</span>
+ </Theme>
+ )}
+ </Theme>
+ );
+ }
+ const selector = 'style[data-astryx-theme="test"]';
+ const {rerender, unmount} = render(<App showInner={true} />);
+ expect(document.head.querySelector(selector)).not.toBeNull();
+
+ // The inner Theme injected first (effects commit children before
+ // parents); its unmount must not strip the CSS the outer one still needs.
+ rerender(<App showInner={false} />);
+ expect(document.head.querySelector(selector)).not.toBeNull();
+
+ // Re-adding an instance reuses the shared CSS without regenerating it.
+ rerender(<App showInner={true} />);
+ expect(generateThemeCSSSpy).toHaveBeenCalledTimes(1);
+ expect(document.head.querySelectorAll(selector)).toHaveLength(1);
+
+ // The last instance leaving removes it.
+ unmount();
+ expect(document.head.querySelector(selector)).toBeNull();
+ });
+
+ it('keeps the original CSS while an edited same-name theme mounts inside it and after it unmounts', () => {
+ const edited = defineTheme({
+ name: 'test',
+ tokens: {
+ '--color-accent': ['#0000AA', '#5555FF'],
+ },
+ });
+ function App({showEdited}: {showEdited: boolean}) {
+ return (
+ <Theme theme={testTheme}>
+ {showEdited && (
+ <Theme theme={edited}>
+ <span>preview</span>
+ </Theme>
+ )}
+ </Theme>
+ );
+ }
+ const selector = 'style[data-astryx-theme="test"]';
+ const {rerender, unmount} = render(<App showEdited={false} />);
+ expect(document.head.querySelector(selector)?.textContent).toMatch(
+ /#aa0000/i,
+ );
+
+ // A preview of the edited copy mounts inside the original. The first
+ // Theme that injected the name keeps its CSS in the document.
+ rerender(<App showEdited={true} />);
+ expect(document.head.querySelectorAll(selector)).toHaveLength(1);
+ expect(document.head.querySelector(selector)?.textContent).toMatch(
+ /#aa0000/i,
+ );
+
+ rerender(<App showEdited={false} />);
+ const styles = document.head.querySelectorAll(selector);
+ expect(styles).toHaveLength(1);
+ expect(styles[0].textContent).toMatch(/#aa0000/i);
+
+ unmount();
+ expect(document.head.querySelector(selector)).toBeNull();
+ });
+
+ it('keeps the CSS for one root when a Theme in another root with the same id unmounts', () => {
+ const selector = 'style[data-astryx-theme="test"]';
+ const first = document.createElement('div');
+ const second = document.createElement('div');
+ document.body.append(first, second);
+ // Hydrated roots derive useId from tree position, so both Themes get
+ // the same id.
+ const ui = <Theme theme={testTheme}>content</Theme>;
+ first.innerHTML = renderToString(ui);
+ second.innerHTML = renderToString(ui);
+ let rootA: Root | undefined;
+ let rootB: Root | undefined;
+ act(() => {
+ rootA = hydrateRoot(first, ui);
+ });
+ act(() => {
+ rootB = hydrateRoot(second, ui);
+ });
+ expect(document.head.querySelectorAll(selector)).toHaveLength(1);
+
+ act(() => rootB?.unmount());
+ expect(document.head.querySelector(selector)).not.toBeNull();
+
+ act(() => rootA?.unmount());
+ expect(document.head.querySelector(selector)).toBeNull();
+ first.remove();
+ second.remove();
+ });
+
+ it("paints the owning Theme's new definition when only its theme changes", () => {
+ const edited = defineTheme({
+ name: 'test',
+ tokens: {
+ '--color-accent': ['#0000AA', '#5555FF'],
+ },
+ });
+ function App({ownerTheme}: {ownerTheme: typeof testTheme}) {
+ return (
+ <>
+ <Theme theme={ownerTheme}>
+ <span>owner</span>
+ </Theme>
+ <Theme theme={testTheme}>
+ <span>other</span>
+ </Theme>
+ </>
+ );
+ }
+ const selector = 'style[data-astryx-theme="test"]';
+ const {rerender, unmount} = render(<App ownerTheme={testTheme} />);
+ expect(document.head.querySelector(selector)?.textContent).toMatch(
+ /#aa0000/i,
+ );
+
+ // The first Theme owns the CSS. Its own theme changes; the other keeps
+ // the original. As on main, the owner's new definition paints.
+ rerender(<App ownerTheme={edited} />);
+ const styles = document.head.querySelectorAll(selector);
+ expect(styles).toHaveLength(1);
+ expect(styles[0].textContent).toMatch(/#0000aa/i);
+
+ unmount();
+ expect(document.head.querySelector(selector)).toBeNull();
+ });
+
+ it('replaces the shared CSS when a theme is redefined under the same name', () => {
+ const redefined = defineTheme({
+ name: 'test',
+ tokens: {
+ '--color-accent': ['#0000AA', '#5555FF'],
+ },
+ });
+ function App({theme}: {theme: typeof testTheme}) {
+ return (
+ <Theme theme={theme}>
+ <Theme theme={theme}>
+ <span>inner</span>
+ </Theme>
+ </Theme>
+ );
+ }
+ const selector = 'style[data-astryx-theme="test"]';
+ const {rerender, unmount} = render(<App theme={testTheme} />);
+ expect(document.head.querySelector(selector)?.textContent).toMatch(
+ /#aa0000/i,
+ );
+
+ rerender(<App theme={redefined} />);
+ const styles = document.head.querySelectorAll(selector);
+ expect(styles).toHaveLength(1);
+ expect(styles[0].textContent).toMatch(/#0000aa/i);
+ expect(styles[0].textContent).not.toMatch(/#aa0000/i);
+
+ unmount();
+ expect(document.head.querySelector(selector)).toBeNull();
+ });
});
diff --git a/packages/core/src/theme/Theme.tsx b/packages/core/src/theme/Theme.tsx
index e99bada9ba..acd90c1fc5 100644
--- a/packages/core/src/theme/Theme.tsx
+++ b/packages/core/src/theme/Theme.tsx
@@ -35,7 +35,7 @@
* ```
*/
-import React, {use, useId, useInsertionEffect, useMemo} from 'react';
+import React, {use, useId, useInsertionEffect, useMemo, useState} from 'react';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import * as stylex from '@stylexjs/stylex';
import type {ThemeMode} from './types';
@@ -108,10 +108,72 @@ ThemeNestingContext.displayName = 'ThemeNestingContext';
// Style injection for unbuilt themes
// =============================================================================
-/** Track which themes have already been injected */
-const injectedThemes = new Set<string>();
+/**
+ * The CSS is shared by the whole document. Remove it only when the last
+ * `Theme` that uses it unmounts.
+ */
+interface InjectedTheme {
+ /**
+ * Each mounted `Theme` that uses this name, with its theme and id. The key
+ * is one object per `Theme` instance: `useId` values can repeat across
+ * separate React roots.
+ */
+ users: Map<object, {theme: DefinedTheme; id: string}>;
+ /** The `Theme` whose theme is in the document. */
+ owner: object;
+ /**
+ * The owner that last handed the CSS over. When the same `Theme` sets up
+ * again in the same commit (its own theme changed), it takes the CSS back.
+ */
+ formerOwner: object | null;
+ /** The theme whose CSS is in the document. */
+ theme: DefinedTheme;
+ styles: HTMLStyleElement[];
+}
+const injectedThemes = new Map<string, InjectedTheme>();
const THEME_LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';
+function writeThemeStyles(theme: DefinedTheme, id: string): HTMLStyleElement[] {
+ const {prose, component} = generateThemeCSS(theme);
+ const styles: HTMLStyleElement[] = [];
+
+ // Prose defaults go into @layer reset — lowest priority, scoped to
+ // the theme region. Any class-based style (StyleX, .xds-*) wins.
+ if (prose) {
+ const proseStyle = document.createElement('style');
+ proseStyle.setAttribute(dataAttr('theme-prose'), theme.name);
+ proseStyle.setAttribute(dataAttr('id'), id);
+ proseStyle.textContent = `${THEME_LAYER_ORDER}\n@layer reset {\n${prose}\n}`;
+ document.head.appendChild(proseStyle);
+ styles.push(proseStyle);
+ }
+
+ // Component overrides go into @layer astryx-theme — above StyleX layers
+ // so themes can intentionally restyle components.
+ if (component) {
+ const compStyle = document.createElement('style');
+ compStyle.setAttribute(dataAttr('theme'), theme.name);
+ compStyle.setAttribute(dataAttr('id'), id);
+ compStyle.textContent = `${THEME_LAYER_ORDER}\n@layer astryx-theme {\n${component}\n}`;
+ document.head.appendChild(compStyle);
+ styles.push(compStyle);
+ }
+ return styles;
+}
+
+/** Replace an entry's CSS with `theme`'s. */
+function rewriteThemeStyles(
+ entry: InjectedTheme,
+ theme: DefinedTheme,
+ id: string,
+): void {
+ for (const style of entry.styles) {
+ style.remove();
+ }
+ entry.theme = theme;
+ entry.styles = writeThemeStyles(theme, id);
+}
+
/**
* Hook to inject theme CSS into the document.
* Built themes (from `astryx theme build`) skip injection — their CSS
@@ -119,6 +181,7 @@ const THEME_LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';
*/
function useThemeStyleInjection(theme: DefinedTheme): void {
const id = useId();
+ const [instance] = useState(() => ({}));
// Syncs the document's stylesheets with the runtime theme CSS.
useInsertionEffect(() => {
@@ -127,69 +190,65 @@ function useThemeStyleInjection(theme: DefinedTheme): void {
return;
}
- // Second and later `Theme`s using this theme do no work at all —
- // generation included. Its CSS is document-wide and identical for each.
const themeKey = `astryx-theme-${theme.name}`;
- if (injectedThemes.has(themeKey)) {
- return;
- }
-
- // One-time perf hint per theme
- warnOnce(
- `theme-injection:${theme.name}`,
- 'Theme',
- `"${theme.name}" is using runtime style injection. ` +
- `For better performance, use the pre-built theme:\n\n` +
- ` import {${theme.name}Theme} from '@astryxdesign/theme-${theme.name}/built';\n` +
- ` import '@astryxdesign/theme-${theme.name}/theme.css';\n\n` +
- `For custom themes, run \`npx @astryxdesign/cli theme build <file>\` to generate ` +
- `the built artifacts.`,
- );
-
- const {prose, component} = generateThemeCSS(theme);
- injectedThemes.add(themeKey);
- const cleanups: (() => void)[] = [() => injectedThemes.delete(themeKey)];
-
- // Prose defaults go into @layer reset — lowest priority, scoped to
- // the theme region. Any class-based style (StyleX, .xds-*) wins.
- if (prose) {
- const proseStyle = document.createElement('style');
- proseStyle.setAttribute(dataAttr('theme-prose'), theme.name);
- proseStyle.setAttribute(dataAttr('id'), id);
- proseStyle.textContent = `${THEME_LAYER_ORDER}\n@layer reset {\n${prose}\n}`;
- document.head.appendChild(proseStyle);
+ let entry = injectedThemes.get(themeKey);
+ if (entry == null) {
+ // One-time perf hint per theme
+ warnOnce(
+ `theme-injection:${theme.name}`,
+ 'Theme',
+ `"${theme.name}" is using runtime style injection. ` +
+ `For better performance, use the pre-built theme:\n\n` +
+ ` import {${theme.name}Theme} from '@astryxdesign/theme-${theme.name}/built';\n` +
+ ` import '@astryxdesign/theme-${theme.name}/theme.css';\n\n` +
+ `For custom themes, run \`npx @astryxdesign/cli theme build <file>\` to generate ` +
+ `the built artifacts.`,
+ );
+ entry = {
+ users: new Map(),
+ owner: instance,
+ formerOwner: null,
+ theme,
+ styles: writeThemeStyles(theme, id),
+ };
+ injectedThemes.set(themeKey, entry);
}
-
- // Component overrides go into @layer astryx-theme — above StyleX layers
- // so themes can intentionally restyle components.
- if (component) {
- const compStyle = document.createElement('style');
- compStyle.setAttribute(dataAttr('theme'), theme.name);
- compStyle.setAttribute(dataAttr('id'), id);
- compStyle.textContent = `${THEME_LAYER_ORDER}\n@layer astryx-theme {\n${component}\n}`;
- document.head.appendChild(compStyle);
- }
-
- if (prose || component) {
- cleanups.push(() => {
- // Matched by the astryx id marker, which is always written above.
- const proseEl = document.querySelector(
- `style[${dataAttr('theme-prose')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
- );
- const compEl = document.querySelector(
- `style[${dataAttr('theme')}="${theme.name}"][${dataAttr('id')}="${id}"]`,
- );
- proseEl?.remove();
- compEl?.remove();
- });
+ // A later `Theme` does no generation. The CSS of the first `Theme` that
+ // injected the name stays in the document.
+ entry.users.set(instance, {theme, id});
+ if (entry.formerOwner === instance) {
+ // The owner's own theme changed: its new definition paints, as on main.
+ entry.owner = instance;
+ entry.formerOwner = null;
+ if (entry.theme !== theme) {
+ rewriteThemeStyles(entry, theme, id);
+ }
}
+ const current = entry;
return () => {
- for (const cleanup of cleanups) {
- cleanup();
+ current.users.delete(instance);
+ if (current.users.size === 0) {
+ for (const style of current.styles) {
+ style.remove();
+ }
+ injectedThemes.delete(themeKey);
+ return;
+ }
+ if (current.owner !== instance) {
+ return;
+ }
+ // The earliest-mounted `Theme` that remains takes over the CSS. If its
+ // theme differs, as after a redefinition under the same name, its CSS
+ // replaces the old one.
+ const [nextOwner, next] = [...current.users][0];
+ current.owner = nextOwner;
+ current.formerOwner = instance;
+ if (next.theme !== current.theme) {
+ rewriteThemeStyles(current, next.theme, next.id);
}
};
- }, [theme, id]);
+ }, [theme, id, instance]);
}
// =============================================================================