Repository navigation
fix(Theme): keep shared injected CSS until the last Theme instance unmounts - #10178
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
AI review status for this pull request.
|
PR Analysis Report🔎 Preview ·
|
|
/approve-spec 4aa44ea |
There was a problem hiding this comment.
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-147never compares the stored theme with the newthemeprop, so when an app rebuilds a theme under the same name (a live accent picker, a theme editor, Fast Refresh) while twoThemes mount it, the page keeps the old CSS wheremainupdated 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]
| const existing = injectedThemes.get(themeKey); | ||
| if (existing) { | ||
| existing.count += 1; | ||
| return () => { |
There was a problem hiding this comment.
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.
| * 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. |
There was a problem hiding this comment.
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]>
|
/approve-spec f9eec80 |
There was a problem hiding this comment.
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
Themethat keeps the original and later unmounts (a theme-editor preview, say),Theme.tsx:184-192has already rewritten the shared tags and the cleanup at:198-206only lowers the count, so the remainingThemekeeps the edited CSS wheremainkept its own; track each mounted provider's definition (for example aMapfrom theuseId()value to its theme in place ofcount), 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]
| } 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); |
There was a problem hiding this comment.
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.
| * 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. |
There was a problem hiding this comment.
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."
| 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. */ |
There was a problem hiding this comment.
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]>
|
/approve-spec 47da2fa |
There was a problem hiding this comment.
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
nameare mounted at once, this head paints the definition whoseThemeset 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), wheremainkept 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. */ |
There was a problem hiding this comment.
Non-blocking: this restates rewriteThemeStyles; it can go.
| // A theme redefined under the same name (a live editor, Fast Refresh) | ||
| // replaces the CSS. The newest definition wins. |
There was a problem hiding this comment.
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."
| // When no remaining `Theme` uses the definition in the document, write | ||
| // the CSS of one that remains, so each keeps its own theme. |
There was a problem hiding this comment.
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]>
|
/approve-spec 0708ed1 |
There was a problem hiding this comment.
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
Themewhose CSS is in the document gets a new theme object under the same name while another same-nameThemestays mounted, the cleanup atTheme.tsx:210-229hands the CSS to that otherTheme, so the new definition never paints (onmainit does); keep ownership when the owner's own effect re-runs, and add a test that rerenders only the owningThemewith a same-name redefinition while anotherThemekeeps the original.
Non-blocking: the JSDoc on rewriteThemeStyles (Theme.tsx:155) restates its name.
[Automated review]
| const [nextOwner, nextTheme] = [...current.users][0]; | ||
| current.owner = nextOwner; | ||
| if (nextTheme !== current.theme) { | ||
| rewriteThemeStyles(current, nextTheme, nextOwner); |
There was a problem hiding this comment.
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]>
|
/approve-spec 999d1a4 |
There was a problem hiding this comment.
Changes requested: the shared-CSS lifetime fix works, but the release note overstates what was broken.
- Miss:
.changeset/theme-shared-css-refcount.md:5says unmounting a nested or siblingTheme, such as a dialog's, stripped the theme's CSS, but only theThemethat injected first did (a nestedThememounted 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]
| '@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. |
There was a problem hiding this comment.
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
Themethat injected the CSS first owned the shared<style>tags, so when it unmounted while otherThemes of that theme stayed mounted (a nestedThemerendered together with its parent, or the first of two siblingThemes), they lost the theme's token and component overrides and prose defaults.
| * 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. |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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]>
|
/approve-spec f118f8b |
There was a problem hiding this comment.
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:213keys mountedThemes byuseId(), and two roots hydrated withoutidentifierPrefixgive their top-levelThemes the same id, so unmounting either root removes the theme's CSS that the other still uses (onmainonly the first root's unmount did); key by a per-instance value such asuseState(() => 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]
| }); | ||
| // 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); |
There was a problem hiding this comment.
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]>
|
/approve-spec de80686 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
*/
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
Themeinstances of the same runtime-injected theme (a nestedThemearound a dialog, for example). When the instance that injected the CSS first unmounts, the shared<style>tags go with it, and every otherThemeon 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
Themerecord's runtime-injection behavior: injected theme CSS applies to every mountedThemeof that theme.Smallest restoration
Each runtime theme keeps a mount count; the shared CSS is removed only when the count reaches zero.
Evidence
main's source.main's source, 18 of 18 pass here).Review follow-up
main: the firstThemethat injected a name owns its CSS, and a laterThemewith a same-name definition does not replace it. The shared entry tracks each mountedTheme'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 everyTheme(a live editor, Fast Refresh) ends with the new CSS, and an edited preview mounted inside the original never replaces the original's CSS.Theme's own theme changes, it keeps the CSS and its new definition paints, as onmain: the handover in its cleanup is taken back when the sameThemesets up again in that commit.Themeis keyed by an object made once per instance, not byuseId: 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).Scope
Testing
main's source (red) and this head (green), plus CI-mode ESLint on the changed files.