Skip to content

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

Merged
cixzhang merged 7 commits into
mainfrom
split8675/theme-shared-css-refcount
Nov 7, 2026
Merged

cixzhang merged 7 commits into
mainfrom
split8675/theme-shared-css-refcount

Conversation

@cixzhang

@cixzhang cixzhang commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Split out of #8675 by @thecodebasedot: one fix per pull request, with the author's commits and attribution kept.

User impact

A page with two Theme instances of the same runtime-injected theme (a nested Theme around a dialog, for example). When the instance that injected the CSS first unmounts, the shared <style> tags go with it, and every other Theme on the page loses its component overrides and prose defaults. After this fix the CSS stays until the last instance using it unmounts. Built themes, which import their CSS as a file, are unaffected.

Problem and solution fit

Each runtime theme keeps a mount count; the shared CSS is removed only when the count reaches zero.

Expected behavior and authority

The Theme record's runtime-injection behavior: injected theme CSS applies to every mounted Theme of that theme.

Smallest restoration

Each runtime theme keeps a mount count; the shared CSS is removed only when the count reaches zero.

Evidence

  • Reproduction before the change: the regression test fails against main's source.
  • Result after the change: it passes.
  • Regression test: Theme.test.tsx: "keeps the shared CSS until the last Theme using it unmounts" (1 of 18 fails on main's source, 18 of 18 pass here).

Review follow-up

  • Which definition paints stays as on main: the first Theme that injected a name owns its CSS, and a later Theme with a same-name definition does not replace it. The shared entry tracks each mounted Theme's definition by its id. When the owner unmounts and others remain, the earliest-mounted one that remains takes over, and its theme's CSS replaces the old one if it differs. So a theme redefined under the same name in every Theme (a live editor, Fast Refresh) ends with the new CSS, and an edited preview mounted inside the original never replaces the original's CSS.
  • When the owning Theme's own theme changes, it keeps the CSS and its new definition paints, as on main: the handover in its cleanup is taken back when the same Theme sets up again in that commit.
  • Each Theme is keyed by an object made once per instance, not by useId: two separately hydrated roots give Themes at the same tree position the same id, and unmounting one root would strip the other's CSS. Test: "keeps the CSS for one root when a Theme in another root with the same id unmounts" (fails on the previous head, passes here).
  • Tests: "paints the owning Theme's new definition when only its theme changes", "replaces the shared CSS when a theme is redefined under the same name" and "keeps the original CSS while an edited same-name theme mounts inside it and after it unmounts". Theme suite: 1,687 passed.

Scope

  • One defect is restored.
  • Separable contradictory or unsettled tagalongs were removed or split.
  • No new public API, visual representation, default, or interaction model is hidden under the bug-fix label.
  • Public text and artifacts contain no internal Meta context.

Testing

  • The changed test files, run against main's source (red) and this head (green), plus CI-mode ESLint on the changed files.

…mounts

Runtime style injection was owned by whichever Theme instance ran its
insertion effect first, and every later instance of the same theme
skipped with no cleanup. Unmounting that owner, typically a nested
Theme wrapping a dialog, removed the document-wide <style> tags while
other Theme instances still relied on them. Track a per-theme mount
count and release the CSS only when it reaches zero.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YEUUZbBab9KaX34tjjQ1Go
(cherry picked from commit 9ed216f)
Co-authored-by: codebase <[email protected]>
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 6, 2026
@vercel

vercel Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
astryx Ready Ready Preview Nov 6, 2026 8:20am UTC

Request Review

@astracat-bot

astracat-bot Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

AI review status for this pull request.

Review status Updated
🟢 Reviewed (for maintainers only) Nov 6, 2026, 8:30 AM UTC

@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

PR Analysis Report

🔎 Preview · de80686

Storybook · Sandbox · built from this PR's head

Package size: @astryxdesign/core 6.63 MB packed (+945 B); no new dependencies.

API changes: none in this pull request

Committed API report behind this build: cli 19 rows, core 23 rows; run pnpm api:report.

Wide change (shared styles: packages/core/src/theme/Theme.tsx): add ci:run-visual, ci:run-a11y or ci:run-rtl to run them.


Generated by PR Enrichment workflow | View full report

@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec 4aa44ea

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The mount count fixes the shared-CSS removal (the new test fails against main's implementation and passes here), but it introduces one regression to fix first:

  • Theme.tsx:138-147 never compares the stored theme with the new theme prop, so when an app rebuilds a theme under the same name (a live accent picker, a theme editor, Fast Refresh) while two Themes mount it, the page keeps the old CSS where main updated it; store the theme on the entry, regenerate and rewrite the shared tags when it changes, and add a test that rerenders two providers with a redefined same-name theme.

Optional: the new comment above injectedThemes could be shorter, for example "The CSS is shared by the whole document. Remove it only when the last Theme that uses it unmounts."

CI has not run on this head yet because the pull request is a draft.

[Automated review]

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +138 to +141
const existing = injectedThemes.get(themeKey);
if (existing) {
existing.count += 1;
return () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This branch never compares existing's theme with the new theme prop. When an app rebuilds a theme under the same name (a live accent picker, a theme editor, Fast Refresh) while two Themes mount it, each provider's cleanup takes the count from 2 to 1 and this setup raises it again, so the CSS from the first definition stays; main re-injected it. Keeping the theme and its style elements on the entry and rewriting the tags when existing.theme !== theme fixes it; a test that rerenders two providers with a redefined same-name theme would cover it.

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +112 to +115
* Track which themes have already been injected, with how many mounted
* `Theme` instances currently rely on each. The CSS is document-wide and
* shared, so it is removed only when the last instance using it unmounts —
* never when one of several (a nested or sibling `Theme`) goes away.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: the second sentence is long and covers two topics, and the first restates the Map type. A shorter version: "The CSS is shared by the whole document. Remove it only when the last Theme that uses it unmounts."

… CSS

The shared entry keeps its theme and its style elements. A Theme whose
theme object differs from the entry's rewrites the elements for every
Theme that uses the name, as main re-injected it; the count still
decides when the CSS leaves.

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec f9eec80

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. The mount count fixes the shared-CSS removal, and the redefinition branch now replaces the CSS when every Theme moves to a new definition, but it leaves one case wrong:

  • When an edited copy of a theme under the same name mounts inside a Theme that keeps the original and later unmounts (a theme-editor preview, say), Theme.tsx:184-192 has already rewritten the shared tags and the cleanup at :198-206 only lowers the count, so the remaining Theme keeps the edited CSS where main kept its own; track each mounted provider's definition (for example a Map from the useId() value to its theme in place of count), rewrite the tags from a remaining provider's definition when none of them uses the written one, and add a test for that sequence.

Optional: the comment above injectedThemes could drop its first sentence, which restates the map, and the one-line comment on writeThemeStyles restates the function's name.

[Automated review]

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +184 to +191
} else if (entry.theme !== theme) {
// A theme redefined under the same name (a live editor, Fast Refresh)
// replaces the CSS for every `Theme` that uses it.
for (const style of entry.styles) {
style.remove();
}
entry.theme = theme;
entry.styles = writeThemeStyles(theme, id);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rewrite has no counterpart in the cleanup below, which only lowers the count. Suppose an edited copy of a theme under the same name mounts inside a Theme that keeps the original, and then unmounts (a theme-editor preview, say). The remaining Theme keeps the edited CSS, though useTheme() returns the original and main kept its own CSS. Track each mounted provider's definition, for example a Map from id to theme in place of count. When the last user of entry.theme leaves and others remain, rewrite the tags from one of theirs. A test that mounts and removes a same-name redefinition inside a Theme with testTheme would cover it.

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +112 to +114
* The runtime theme CSS in the document, by theme name. The CSS is shared by
* the whole document. It is removed only when the last `Theme` that uses it
* unmounts.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: the first sentence restates the Map and its key, and the last is passive. Suggested: "The CSS is shared by the whole document. Remove it only when the last Theme that uses it unmounts."

Comment thread packages/core/src/theme/Theme.tsx Outdated
const injectedThemes = new Map<string, InjectedTheme>();
const THEME_LAYER_ORDER = '@layer reset, astryx-base, astryx-theme;';

/** Write `theme`'s runtime CSS into the document head. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: this restates the function's name; it can go.

The shared entry tracks each mounted Theme's definition by its id. When
the last Theme that uses the definition in the document unmounts and
others remain, the CSS is rewritten from one that remains, so a Theme
that kept the original gets its own CSS back.

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec 47da2fa

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Needs an engineering owner's decision before approval. Tracking every mounted Theme fixes the shared-CSS removal: the new lifetime test fails on main and passes here, and an edited copy's CSS no longer outlives it. One behavior change has no governing rule in the current theme-application record:

  • Miss: while two different theme objects with the same name are mounted at once, this head paints the definition whose Theme set up last (an edited copy opened later restyles the whole page while it is open, and a copy mounted together with the original shows the original), where main kept the first one injected, so approval needs an engineering owner, the author included, to decide on this pull request which definition should win; if this head's rule is the intended one, no code change is needed.

Optional: the comments at Theme.tsx:198-199 and :216-217 describe the rule as "the newest definition wins" and "each keeps its own theme", which the mounted-together case contradicts, and the comment on rewriteThemeStyles restates its name.

[Automated review]

return styles;
}

/** Replace an entry's CSS with `theme`'s. */

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: this restates rewriteThemeStyles; it can go.

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +198 to +199
// A theme redefined under the same name (a live editor, Fast Refresh)
// replaces the CSS. The newest definition wins.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: "The newest definition wins" does not hold when both definitions mount in one commit. Insertion effects run children first, so the outer Theme sets up last and its definition wins, and a preview mounted with the original shows the original. Once the rule is settled, state it as it is, for example "The Theme that sets up last wins."

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +216 to +217
// When no remaining `Theme` uses the definition in the document, write
// the CSS of one that remains, so each keeps its own theme.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: "so each keeps its own theme" overstates. While the remaining Themes hold different definitions, only one paints. Suggested: "When no remaining Theme uses the written definition, write the most recently added one."

…s on main

A co-mounted same-name definition no longer replaces the CSS. As on
main, the first Theme that injected the name owns its CSS. When that
Theme unmounts and others remain, the earliest-mounted one that remains
takes over, and its theme's CSS replaces the old one if it differs.

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec 0708ed1

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested. Tracking every mounted Theme fixes the shared-CSS removal (the new lifetime test fails on main and passes here), and the first Theme to inject a name now keeps painting at mount, as on main, but one case regresses:

  • When the Theme whose CSS is in the document gets a new theme object under the same name while another same-name Theme stays mounted, the cleanup at Theme.tsx:210-229 hands the CSS to that other Theme, so the new definition never paints (on main it does); keep ownership when the owner's own effect re-runs, and add a test that rerenders only the owning Theme with a same-name redefinition while another Theme keeps the original.

Non-blocking: the JSDoc on rewriteThemeStyles (Theme.tsx:155) restates its name.

[Automated review]

Comment thread packages/core/src/theme/Theme.tsx Outdated
Comment on lines +225 to +228
const [nextOwner, nextTheme] = [...current.users][0];
current.owner = nextOwner;
if (nextTheme !== current.theme) {
rewriteThemeStyles(current, nextTheme, nextOwner);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This takeover also runs when this Theme is the owner and only its theme prop changes. React runs the cleanup before the re-run, so a same-name redefinition hands the CSS to the first remaining Theme (rewritten from that Theme's definition) and the re-run joins as a non-owner. Its new definition then never paints while another same-name Theme stays mounted, though it never unmounted; on main it repaints. For example, a preview mounted together with the original paints at first, then reverts to the original at its first edit.

Recording the outgoing owner's id here, and letting that id reclaim ownership and rewrite the CSS when its setup re-runs, would fix it. A test that rerenders only the owning Theme with a same-name redefinition while another Theme keeps the original would cover it.

… paints its new definition

When the owner hands the CSS over in its cleanup and the same Theme sets
up again in that commit, it takes the CSS back and its new definition
paints, as on main.

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec 999d1a4

@astracat-bot astracat-bot Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested: the shared-CSS lifetime fix works, but the release note overstates what was broken.

  • Miss: .changeset/theme-shared-css-refcount.md:5 says unmounting a nested or sibling Theme, such as a dialog's, stripped the theme's CSS, but only the Theme that injected first did (a nested Theme mounted in the same render as its parent, or the first of two siblings), so the note should name that condition.

The new lifetime test fails before the change and passes after it, and while two same-name definitions share the page the same one paints as before. The inline notes on the takeover comment and on a doubled CSS generation are non-blocking.

[Automated review]

Comment thread .changeset/theme-shared-css-refcount.md Outdated
'@astryxdesign/core': patch
---

[fix] `Theme` keeps its runtime-injected CSS in the document until the last mounted `Theme` using that theme unmounts. Before, the one instance that happened to inject first owned the shared `<style>` tags, so unmounting a nested or sibling `Theme` (a dialog wrapped in the same theme, for example) stripped the component overrides and prose defaults from every other `Theme` still on the page. Built themes, which import their CSS as a file, are unaffected.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Miss: earlier reviews did not flag this. On main only the Theme that injected first removed the shared tags: a nested Theme rendered together with its parent, or the first of two siblings. A Theme mounted later, such as one around a dialog opened after the page, or a later sibling, never owned them, so unmounting it kept the CSS. As written, this tells readers who wrap dialogs in Theme that they were affected. Suggested wording for the second sentence:

Before, the Theme that injected the CSS first owned the shared <style> tags, so when it unmounted while other Themes of that theme stayed mounted (a nested Theme rendered together with its parent, or the first of two sibling Themes), they lost the theme's token and component overrides and prose defaults.

Comment on lines +121 to +122
* 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: nothing clears formerOwner after the commit. If the owner switches to another theme name, the field stays set, and when that Theme later switches back it reclaims the CSS and its definition replaces the remaining Theme's. main ends in the same state, so only the comment is off. Suggested: "The owner that last handed the CSS over. When that Theme next sets up under this name, it takes the CSS back."

// injected the name stays in the document.
entry.users.set(id, theme);
if (entry.formerOwner === id) {
// The owner's own theme changed: its new definition paints, as on main.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: "as on main" will not mean anything once this is on main. Suggested: "The owner's own theme changed. It keeps the CSS, and its new definition paints."

… one whose unmount stripped the CSS

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec f118f8b

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested: the shared-CSS lifetime fix works within one React root and the release note is now accurate, but keying each Theme by useId() breaks pages that hydrate more than one root.

  • Miss: Theme.tsx:213 keys mounted Themes by useId(), and two roots hydrated without identifierPrefix give their top-level Themes the same id, so unmounting either root removes the theme's CSS that the other still uses (on main only the first root's unmount did); key by a per-instance value such as useState(() => Symbol('Theme')) and add a test that hydrates two roots and unmounts one.

The new lifetime test fails before the change and passes after it. The open inline notes on comment wording, and the doubled CSS generation when an owner's theme changes beside a different same-name definition, are non-blocking.

[Automated review]

Comment thread packages/core/src/theme/Theme.tsx Outdated
});
// A later `Theme` does no generation. The CSS of the first `Theme` that
// injected the name stays in the document.
entry.users.set(id, theme);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two Themes in separately hydrated roots share this key. React builds hydration ids from tree position, so with hydrateRoot and no identifierPrefix, the top-level Theme of each root gets _R_0_. When either root unmounts, users empties and the tags go while the other root still uses them; on main a non-owner's unmount kept the CSS (architecture:theme-application INV5).

Keying users, owner and formerOwner by a per-instance value that cannot collide fixes it, for example const [instance] = useState(() => Symbol('Theme')), with useId() kept for the data-astryx-id attribute. A test that renders two roots with renderToString, hydrates both and unmounts one would cover it.

…across hydrated roots

Two separately hydrated roots give Themes at the same tree position the
same useId, so unmounting one root dropped the other's share and
stripped the CSS. The shared entry now keys each Theme by an object
made once per instance; useId still labels the style elements.

Co-authored-by: codebase <[email protected]>
@cixzhang

cixzhang commented Nov 6, 2026

Copy link
Copy Markdown
Contributor Author

/approve-spec de80686

@astracat-bot astracat-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved pending CI: CI has not run on this head yet, and it starts when the pull request is marked ready for review.

Keying each Theme by an object it makes once fixes the shared-CSS removal for pages that hydrate more than one root: the new two-root test fails without that key and passes with it, and the lifetime test fails on main and passes here. The open inline notes on comment wording, the doubled CSS generation when an owner's theme changes beside a different same-name definition, and the changeset's omission of token overrides are non-blocking.

[Automated review]

*/
interface InjectedTheme {
/**
* Each mounted `Theme` that uses this name, with its theme and id. The key

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: "with its theme and id" restates the value type. The reason in the next sentence is the part worth keeping. Suggested:

/**
 * Each mounted `Theme` that uses this name. The key is an object made once
 * per instance, because `useId` values can repeat across separate React roots.
 */

@cixzhang
cixzhang marked this pull request as ready for review November 7, 2026 05:51
@cixzhang
cixzhang merged commit fa6174f into main Nov 7, 2026
122 checks passed
@github-actions
github-actions Bot deleted the split8675/theme-shared-css-refcount branch November 8, 2026 06:04

This branch was successfully deployed

1 active deployment
Preview — de806865 Deployed Nov 6, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants