Skip to content

fix(createGlobalStyle): keep each global style's CSS when two differ only in their functions - #5847

Merged
quantizor merged 7 commits into
6.xfrom
cursor/global-style-function-id-6x-4915
Nov 5, 2026
Merged

quantizor merged 7 commits into
6.xfrom
cursor/global-style-function-id-6x-4915

Conversation

@quantizor

@quantizor quantizor commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Two createGlobalStyle calls whose templates differ only in their interpolated functions, such as xstyled's Preflight and ColorModeProvider, could wipe each other's CSS. Mounting, rerendering, or unmounting one of them removed the other's rules from the page.

What changes

  • Each global style keeps its own CSS when two of them differ only in what their functions return, including bodies made of a single function (createGlobalStyle`${() => 'html { --a: 1; }'}`).
  • When two such global styles set the same property, the one mounted most recently wins. A prop or theme update doesn't change which one that is.
  • Server rendering emits the CSS of every such global style, and of every mount of one dynamic global style, not only the last.
  • Unmounting one of two identical static global styles keeps their CSS in place.

Class names and global style ids are unchanged, so server-rendered pages hydrate as before.

@changeset-bot

changeset-bot Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 48eff38

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
styled-components Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ No blocking issues — the backport is faithful and well covered; one follow-up question on the id counter's process-global scope.

Reviewed changes

Backport of #5846 to the 6.x line, fixing #5845 (function-bodied global styles collapse onto one id, so only the last one renders).

  • New id helper — packages/styled-components/src/utils/globalStyleId.ts: static rules still hash their JSON (unchanged from base, so existing static ids/SSR markers are byte-stable); rules containing a function mix a per-serialization count into the hash, starting at the first call, so colliding function-bodied globals get distinct ids. containsFunction walks the rules, treating styled components and keyframes as function-free since they carry their own id in the JSON.
  • Wiring — createGlobalStyle.ts calls the helper instead of generateComponentId(JSON.stringify(rules)).
  • Tests — new unit suite for the helper, a shared globalStyleShapes matrix exercised on the client and through ServerStyleSheet SSR, updated RSC snapshot ids, and the function-body count reset between cases in setupTestFramework.ts.

I read the full diff, confirmed the core helper is identical to the already-reviewed main version, ran the full web suite (1035 passed / 61 suites), tsc --noEmit, and prettier (all clean). I also reverted only the createGlobalStyle.ts id line to the base expression and re-ran the new tests: they fail (19 client + SSR cases), so the new coverage is load-bearing rather than passing against the old code.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog

pullfrog Bot commented Oct 29, 2026

Copy link
Copy Markdown

Follow-up detail for the note in my review (packages/styled-components/src/utils/globalStyleId.ts:12):

issuedBySerialization is a process-wide map that is never reset outside tests. Because JSON.stringify collapses every whole-function body to "[null]", that one key is shared by every function-bodied global in the app, so a salted id encodes a process-wide ordinal, not just the call's order within one render.

The consequence for hydration: on a warm server that has already evaluated other routes' modules, a page's function-bodied ids are offset by whatever earlier routes issued, while a fresh client starts its count at 0. When they differ, rehydration registers the server's group names and the client inserts its own group, duplicating the CSS rather than matching it — which is the case the changeset's "hydrates when the calls run in the same order" sentence rules out.

Is the supported deployment one where the module graph is re-evaluated per render (serverless / fresh process), so the count always starts at 0? If not, the changeset's third paragraph should be qualified to cover the process-wide count, or the counter needs a per-request reset. I did not stand up a real multi-route server to confirm this empirically, so treat it as a question rather than a confirmed bug.

Technical details
# Function-body ids depend on the process-wide issuance count

## Mechanism
- `packages/styled-components/src/utils/globalStyleId.ts:12` — `issuedBySerialization` is module-global and cleared only by `resetGlobalStyleComponentIds()`, which production code never calls.
- Whole-function bodies serialize to `"[null]"`, so every such call shares one counter; mixed shapes share a counter keyed on their static skeleton.
- Ids are `hash(serialized + "\0" + issued)`, so `issued` is a process-wide ordinal, not a per-render one.

## Consequence
- Warm server (modules cached): a route's function-bodied globals are issued after whatever other routes already issued, so their counts carry an offset.
- Fresh client: the count starts at 0 for whatever the page bundle evaluates.
- On mismatch, `rehydrateSheet` registers the server's ids while the client registers its own, so the CSS is duplicated.

## Required outcome
- Either confirm the deploy target re-evaluates modules per render (so counts start at 0 and the guarantee holds), or qualify the changeset's hydration claim to cover the process-wide count. A per-request reset would need a request boundary the helper currently has none of.

Pullfrog  | View workflow run | via Pullfrog | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Instance entries move to a module-level registry keyed by component id, so a rebuild re-inserts every global style sharing the id; server renders append a first-seen instance.
@quantizor
quantizor force-pushed the cursor/global-style-function-id-6x-4915 branch from 3167391 to 8d7d520 Compare November 3, 2026 04:06
@quantizor quantizor changed the title fix: give each function-bodied global style its own id fix(createGlobalStyle): keep each global style's CSS when two differ only in their functions Nov 3, 2026

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ No blocking issues — the fix was reworked into a shared per-id registry since the last review; one dead test assertion inline.

Reviewed changes

The branch was rewritten since the prior review: it drops the previous id-salting helper entirely and instead keeps the content-derived ids and fixes the shared-group rebuild.

  • Moved the per-instance rule cache into a shared per-id registry — GlobalStyle.ts replaces the object's private instanceRules with a module-level Map<componentId, Map<instance, {name, rules}>>, so instances created by different createGlobalStyle calls that share an id are tracked together.
  • rebuildGroup now restores every surviving instance for the id — it clears the group and re-inserts from the shared registry rather than only the current object's instances, which is what stops one colliding call from wiping the other's CSS.
  • Server path appends first-seen instances — renderStyles inserts instead of rebuilding when styleSheet.server && !prev, since server entries are deleted right after each instance renders and a rebuild would drop earlier instances.
  • HMR swap calls removeStyles — drops the instance's own entry before re-rendering so the rules-equality fast path cannot skip the re-insert.
  • Tests and docs — removed the 18-shape matrix and the id-helper unit suite, added a focused createGlobalStyle with the same id suite plus one SSR case, and updated docs/global-styles.md and the changeset. Full web suite runs green here (991 passed / 60 suites).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No new issues found — the sole prior finding was resolved and the PR is mergeable as-is.

Reviewed changes

The only commit since the prior review is a test-only cleanup that addresses prior feedback.

  • Dropped the vacuous styledComponentId assertion — removed the client "gives function-only bodies one id" case and replaced the SSR counterpart's assertion with a comment explaining that the shared group id in the snapshot already proves the two calls share an id. Shared-id coverage remains pinned by the SSR snapshot (data-styled.g4[id="sc-global-c"]{ content:"sc-global-c1,sc-global-c2,"}) plus the client behavioral cases.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

The only commit since the prior pullfrog review keys the shared per-instance registry by stylesheet, so entries from different sheets can no longer collide or be re-inserted into each other.

  • Registry keyed by StyleSheet — GlobalStyle.ts changes the module-level registry from Map<componentId, Map<instance, ...>> to WeakMap<StyleSheet, Map<componentId, Map<instance, ...>>>. Each sheet owns its own tag, so scoping by sheet keeps same-id/same-instance entries from one sheet out of another's rebuild.
  • All call sites thread the sheet through — getInstance, deleteInstance, and liveInstanceCount now take the stylesheet, and every caller in GlobalStyle.ts / createGlobalStyle.ts passes the same styleSheet it wrote computeRules against, so reads, deletes, and rebuildGroup all target one sheet.
  • New two-sheet test — a createGlobalStyle with the same id case renders two same-id globals into two independent sheets and asserts each tag holds only its own group, including after either unmounts.
  • Docs updated — docs/global-styles.md describes the sheet-first registry and why it is keyed that way.

I traced every getInstance/deleteInstance/rebuildGroup call site for sheet consistency, verified the RSC and ServerStyleSheet paths always resolve a stable sheet within a render, and ran the web suite green (991 passed / 60 suites) plus the focused createGlobalStyle files (67 passed). This sheet-scoping also removes the earlier cross-request clobber exposure the previous commit carried over from base.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Important

One edge case in the new server-append logic can drop a sibling mount's collected CSS. Details inline.

Reviewed changes

Two commits landed since the prior pullfrog review (838e9876), both reworking the shared-group instance registry.

  • Bounded server appends — a repeat render of the same instance into a per-request collection now rebuilds (replacing its earlier rules) instead of appending duplicates, keyed off styleSheet.hasNameForId(id, next.name).
  • Reallocate the instance id on a sheet swap — the client useRef now stores { instance, sheet } and allocates a fresh id from the new sheet when StyleSheetManager swaps sheets, since independent sheets count instances from 1.
  • Mount-order conflict resolution — dropped the order field and stable sort; rebuildGroup re-inserts in the registry map's insertion order, so the most recently mounted global wins a same-property conflict and a prop/theme update keeps its place.
  • HMR relies on effect teardown ordering — removed the render-effect prevGlobalStyleRef/removeStyles special case; the cleanup-only effect's teardown now runs before the render effect re-runs with the new globalStyle.
  • Registry refactor — computeRules split into buildEntry + entriesFor; renderStyles resolves the per-sheet/per-id map once and reuses it.
  • Tests, docs, changeset — added a repeated-render server case, a two-mount SSR case, mount-order and in-place-update cases, and a sheet-swap case; updated docs/global-styles.md and the changeset.

I read the full delta, traced the server append / rebuild branches against Sheet.clearRules (which clears names too), and reproduced the finding below with a focused unit case. The full createGlobalStyle suite is green here (72 passed).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ℹ️ No critical issues — the prior finding is fixed and well covered; one stale doc reference to tidy up.

Reviewed changes

The only commit since Pullfrog's prior review (f840c57b) keeps a server sheet's instance entries for the sheet's lifetime, so a repeat render rebuilds with every sibling instead of dropping the ones already emitted and deleted.

  • Server entries persist for the sheet — the per-render deleteInstance in the non-RSC server path is removed; a server sheet's registry entries now live until the sheet is collected. The RSC branch still deletes its own entry right after reading it, now unconditionally rather than only when the CSS is non-empty.
  • Append guard simplified — the dynamic branch appends only when styleSheet.server && !prev, dropping the hasNameForId check that pushed a repeat render into a rebuild whose registry had already been emptied.
  • Tests — the repeated-render unit case now renders instances 1, 2, 1 (no per-render delete) and expects both siblings in the group; a new server-sheet case rerenders one sibling and asserts the other survives.
  • Docs — docs/global-styles.md rewritten for sheet-lifetime server entries and the append/rebuild split.

I traced the append and rebuild branches across GlobalStyle.ts, createGlobalStyle.ts, Sheet.ts, and ServerStyleSheet, confirmed a name registered without a registry entry is unreachable on a server === true sheet (so the simplified guard cannot double-append), and ran the focused createGlobalStyle suites green (59 passed / 2 suites).

ℹ️ docs/build-architecture.md still documents the removed cleanup as the server-detection exception

The commit removes createGlobalStyle's server-cache cleanup, but docs/build-architecture.md still presents that exact cleanup as "the one deliberate exception" to the __SERVER__ || IS_RSC || ssc.styleSheet.server rule, with a rationale about the IS_RSC branch above it. The paragraph now describes deleted code, and the gate that actually remains in createGlobalStyle is not the exception it names.

Technical details
# Stale server-detection exception in build-architecture.md

## Affected sites
- `docs/build-architecture.md:28-31` — "Combine all three ... with one deliberate exception: `createGlobalStyle`'s server-cache cleanup drops the `IS_RSC` term, because the `IS_RSC` branch above it has already handled the render and returned ...". That cleanup is the `if (__SERVER__ || ssc.styleSheet.server) { deleteInstance(...) }` block removed in `48eff387`.
- `packages/styled-components/src/constructors/createGlobalStyle.ts:110` — the only remaining combined gate is `if (IS_RSC || ssc.styleSheet.server)`, which drops `__SERVER__` for its own reason (inline comment at lines 101-109). It is not the `IS_RSC`-dropping cleanup the doc describes.

## Required outcome
- `docs/build-architecture.md` no longer documents a cleanup that does not exist. Either drop the exception sentence, or restate the exception the code currently makes.

## Suggested approach (optional)
- The removed block was the sole home for this "one deliberate exception" claim; after deletion, the union rule stands with no exception in `createGlobalStyle`, so deleting the paragraph is the smallest correct edit. If the `IS_RSC || ssc.styleSheet.server` render gate is meant to be the documented exception, its rationale differs from the text currently in the file.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ No new issues found.

Reviewed changes

The only commit since Pullfrog's prior review (48eff387) corrects the build-architecture paragraph that review flagged as stale.

  • Restated the server-detection gate rule — docs/build-architecture.md no longer describes the removed createGlobalStyle server-cache cleanup as "the one deliberate exception" to the three-flag union. It now states that each gate uses the smallest subset of __SERVER__, IS_RSC and styleSheet.server that covers its cases, and explains why createGlobalStyle renders on IS_RSC || ssc.styleSheet.server without __SERVER__: the server build has no cleanup effect, so rendering there under jsdom would accumulate styles across renders.

I checked the new paragraph against createGlobalStyle.ts:110 and the rationale at :101-109; the gate and the reason match the code. Docs-only, no behavioral change.

Pullfrog  | Fix it ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@quantizor
quantizor merged commit 1ddadee into 6.x Nov 5, 2026
8 checks passed
@quantizor
quantizor deleted the cursor/global-style-function-id-6x-4915 branch November 5, 2026 19:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant