Skip to content

Commit a0a92cd

Browse files
authored
fix(types): keep union props through styled(), and stabilize the hook sequence (#5789)
* docs: split AGENTS.md into specifications under docs/ AGENTS.md had grown to carry both the rules and the full specification of every subsystem, so the rules were hard to find and the specifications drifted unread. It now holds the rules and a map; each subject has one home under docs/. Tracing the moved text against the source turned up several claims that no longer described 6.x: - keyframes were documented as emitted in a dedicated <style> tag that component CSS must never be prepended to. 6.x concatenates them into one tag, and the cited getEmittedCSS does not exist on this branch. - stylisPluginRSC was documented as rewriting child-index selectors. It also expands adjacent sibling combinators, with its own limitations. - IS_BROWSER checks document as well as window. - nonce was documented as inherited by a nested StyleSheetManager. It is a sheet option resolved by getNonce, and is not part of the RSC context override. - createTheme's contract omitted GlobalStyle, without which nothing is emitted. - the stylis AST caveat said props "can alias" between a rule and its nested copy. The parser hands the nested ruleset the parent's array outright, which is now stated with the reproduction. CLAUDE.md was a real symlink to AGENTS.md and is now a pointer file, so writing either name cannot clobber the other. * fix(types): keep union props through styled(), and stabilize the hook sequence Three fixes plus the guardrails that keep each from recurring. `OverrideStyle` lost its distribution over unions when #5784 moved the test from a naked `P extends { style?: infer S }` to `'style' extends keyof P`. `keyof` a union is the keys common to every member, so an undistributed pass rebuilt `A | B` from the shared keys alone and dropped every member-specific prop. Restored with an outer `P extends unknown`. Fixes #5787. The same class, found while auditing the siblings: `Substitute` and `MergeProps` recognize an empty prop bag with `keyof B extends never`, which a union of disjoint shapes also satisfies, so such a union was dropped wholesale. Now discriminated with `{} extends B`. Predates 6.5.0. A per-member re-ask is the more complete fix and tips tsc into TS2589 against a caller spreading `as?: WebTarget`; the accepted limitation, an all-optional disjoint union, is pinned in the contract suite. At runtime, `useDebugValue` sat inside the render cache's miss branch and was skipped whenever props were unchanged. Moved past the if/else. The `use`-prefixed `useInjectedStyle` wrapper it lived in called no hooks of its own and is inlined, removing the seam that made a conditional call look safe. Guardrails: contract-suite cases for every union surface, each accepted prop paired with a rejected one so a widening cannot fake a pass; a runtime test asserting the hook sequence is identical across cache hit and miss; and a `unionTarget` kind in the consumer type-check fixture, which prices the distributive path and, because the run fails on any fixture compile error, fails outright if the union collapses again. Consumer type-check cost: +0.04% instantiations, types and memory flat. The recorded budget moved because the fixture grew, not because the cost did. * chore: address review feedback Reset the hook recorder's buffer in a finally so a throwing render cannot leave it live for the next one. Drop the hard-coded instantiation counts from the type-performance doc and point at the budget file and its command instead, per the project's rule against restating drift-prone numbers. Rewrite both changesets in terms of what a consumer observes rather than the type expressions involved.
1 parent ef5142a commit a0a92cd

21 files changed

Lines changed: 970 additions & 228 deletions

‎.changeset/disjoint-union-props.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Fix a styled component silently dropping props declared as a union whose members have no prop in common, which left every one of those props rejected. The same applied when `as` pointed at a component with such props. Where every member's props are optional the union is still flattened, so declare the combined optional shape instead.

‎.changeset/stable-hook-sequence.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Styled components now report the same debug value to React DevTools on every render. Previously the value was only reported on renders that recomputed styles, so it disappeared from the DevTools panel whenever a component re-rendered with unchanged style props.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Fix wrapping a component whose props are a union. Since 6.5.0 the wrapped version accepted only the props common to every member of the union, so a prop belonging to just one member was rejected even though the unwrapped component accepted it.

‎AGENTS.md‎

Lines changed: 47 additions & 195 deletions
Large diffs are not rendered by default.

‎CLAUDE.md‎

Lines changed: 0 additions & 1 deletion
This file was deleted.

‎CLAUDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Read AGENTS.md for the rules. Nothing else is here.

‎docs/attrs.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# attrs Behavior
2+
3+
`attrs` always wins over a directly passed prop. This is by design, not a precedence accident.
4+
5+
The function form is the escape hatch when a caller's value should win:
6+
7+
```js
8+
.attrs(({ as }) => ({ as: as || 'button' }))
9+
```
10+
11+
One exception to attrs winning: explicitly passing `undefined` for a prop prevents attrs from
12+
overwriting it, which is how a caller signals intent to reset the value (#5683).

‎docs/build-architecture.md‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Build Architecture
2+
3+
How the package is built, which environment flags exist, and how CSS injection order is decided.
4+
5+
## Environment flags
6+
7+
Three separate mechanisms answer "are we on a server", and they are not interchangeable.
8+
9+
`__SERVER__` is a build-time constant. Rollup replaces it per bundle, so a branch behind it is
10+
eliminated entirely from the browser build. It is the right gate for dead-code elimination and the
11+
wrong gate for anything needing paired cleanup: Jest resolves the server build through the `main`
12+
field in jsdom, where `__SERVER__` is `true`, so a `useLayoutEffect` gated on it is eliminated while
13+
the DOM mutations it was meant to clean up still happen. Gate cleanup on `styleSheet.server` or
14+
`IS_RSC` instead.
15+
16+
`IS_RSC` is `typeof React.createContext === 'undefined'`, evaluated once at module level. React 19's
17+
`react-server` export condition serves a build stripped of `createContext`, so `IS_RSC` is `true` at
18+
runtime inside server components; bundlers such as Next.js and Turbopack select that condition
19+
automatically. In browser, standalone and native builds rollup replaces the expression with `false`
20+
for dead-code elimination. Because it is module-level rather than per-render, gating a hook behind it
21+
does not violate the rules of hooks.
22+
23+
`styleSheet.server` is a runtime flag set by `ServerStyleSheet`. It exists because Turbopack resolves
24+
the `browser` entry when server-rendering client components, which makes `__SERVER__` false on the
25+
server; this flag is the fallback that still reports the truth there.
26+
27+
Combine all three (`__SERVER__ || IS_RSC || ssc.styleSheet.server`) with one deliberate exception:
28+
`createGlobalStyle`'s server-cache cleanup drops the `IS_RSC` term, because the `IS_RSC` branch above
29+
it has already handled the render and returned, so reaching that line under RSC means there was
30+
nothing left to clean.
31+
32+
`IS_BROWSER` is `typeof window !== 'undefined' && typeof document !== 'undefined'`. Both halves are
33+
needed: a non-browser host can define `window` without a DOM. It is a runtime check, so bundlers
34+
cannot tree-shake code behind it and it never substitutes for `__SERVER__`.
35+
36+
`React.useRef` is `undefined` in RSC server components. Gate it behind `__SERVER__` so the call is
37+
eliminated; never write `typeof React.useRef === 'function'`, which is a runtime conditional hook.
38+
39+
## Native entry isolation
40+
41+
The native entry must never transitively import DOM code through a value import. Use `import type`,
42+
and branded `Symbol.for()` checks in place of `instanceof`. React Native on Hermes 0.79+ fails at
43+
module evaluation time on a bare `document` reference, so the failure is a hard crash rather than a
44+
degraded path.
45+
46+
Verify with `grep -c 'document\.' native/dist/styled-components.native.cjs.js`, which must report 0.
47+
48+
## Module resolution
49+
50+
The `browser` field in `package.json` maps server bundles to their browser-specific alternatives. It
51+
is preferred over `exports`, which caused TS2742 in composite TypeScript projects.
52+
53+
## CSS injection ordering
54+
55+
Group IDs are allocated at call time, when `styled()`, `createGlobalStyle()` or `keyframes()` runs,
56+
and a lower ID sorts earlier in the stylesheet.
57+
58+
Keyframes register eagerly via `getGroupForId(this.id)` in the constructor rather than through
59+
`StyleSheet.registerId`, which would pull DOM imports into native builds.

‎docs/create-theme.md‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# createTheme
2+
3+
`createTheme(defaultTheme, options?)` returns an object whose every leaf is
4+
`var(--prefix-path, fallback)`, so the same theme is usable from both client and RSC styled
5+
components. The returned object *is* that tree of variable references, with the members below
6+
assigned onto it, so `theme.colors.primary` reads as the `var(...)` string directly.
7+
8+
Passing the contract to `ThemeProvider` keeps class name hashes stable across themes, which is what
9+
prevents a hydration mismatch when switching light and dark.
10+
11+
## Members
12+
13+
- `GlobalStyle` is a component that emits the variable declarations, and nothing renders the
14+
variables until it is mounted. Mount it inside the `ThemeProvider` whose theme supplies the values;
15+
changing that theme updates the declarations. Without it every leaf falls back to its default.
16+
- `raw` holds the original theme object.
17+
- `vars` holds the bare CSS custom property names (`--sc-path`), in the same shape as the theme. Use
18+
it in `createGlobalStyle` for dark mode overrides: `${vars.colors.bg}: #111;`.
19+
- `resolve(el?)` reads the computed CSS variable values from the DOM, defaulting to
20+
`document.documentElement`, and returns a plain object of resolved values. It is client-only and
21+
throws rather than degrading when called outside a browser.
22+
23+
## Options
24+
25+
- `prefix` defaults to `"sc"`.
26+
- `selector` defaults to `":root"`; use `":host"` for Shadow DOM.
27+
28+
## Dark mode
29+
30+
Combine `vars` with a `css` partial to write the overrides once and reuse them in both
31+
`@media (prefers-color-scheme: dark)` and a `.dark` class. This avoids a hydration flash and avoids
32+
hand-written variable names drifting from the theme.
33+
34+
## Implementation note
35+
36+
`reconstructWithOptions` must copy the `keyframeIds` Set to the new sheet.

‎docs/global-styles.md‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# GlobalStyle Shared-Group Architecture
2+
3+
Every component returned by a single `createGlobalStyle` call shares one stylesheet group, registered
4+
at call time via `StyleSheet.registerId(componentId)`. The returned component is wrapped in
5+
`React.memo`.
6+
7+
## Instance identity
8+
9+
Each mount needs its own instance ID, allocated by `allocateGSInstance`. The server allocates
10+
directly, since a server render is one-shot. The client allocates through a `useRef` so the ID stays
11+
stable across re-renders.
12+
13+
`instanceRules`, a `Map<number, { name: string; rules: string[] }>` on the module-level `GlobalStyle`
14+
object, tracks each mount's compiled CSS. `computeRules()` flattens and compiles the CSS and caches it
15+
there under the name `componentId + instance`, making `instanceRules` the single source of truth for a
16+
rebuild.
17+
18+
`rebuildGroup()` clears the shared group and re-inserts from the surviving instances. It is O(N) in
19+
mounted instances, which is typically one to three.
20+
21+
## Static and dynamic rules take different paths
22+
23+
`renderStyles` branches on `isStatic`, and the two branches share almost nothing.
24+
25+
Static rules never rebuild. The branch checks `hasNameForId(id, id + instance)` and inserts only on a
26+
miss. On a hit it still calls `computeRules` when `instanceRules` has no entry for the instance: that
27+
is the rehydration case, where the CSS is already in the DOM from the server but the module-level
28+
cache is empty, and populating it is what lets `rebuildGroup` restore this instance if a sibling
29+
unmounts later.
30+
31+
Dynamic rules recompute on every render, then compare. `computeRules` overwrites the entry first, so
32+
the comparison is against the previous entry captured beforehand; if the rule arrays are the same
33+
length and element-wise equal, the CSSOM rebuild is skipped. That fast path is client-only
34+
(`!styleSheet.server`): server-side `clearTag()` invalidates the DOM tag and not the module-level
35+
caches, so a cache-based fast path would skip a rebuild the DOM still needs. Any new fast path here
36+
must make the same check.
37+
38+
Server-side `instanceRules` entries must be deleted explicitly once styles are collected, because no
39+
`useLayoutEffect` cleanup runs on the server.
40+
41+
`rebuildGroup` must run synchronously. Nothing may yield between `clearRules` and the re-insert loop,
42+
or the group is observable while empty.
43+
44+
## Client lifecycle
45+
46+
The client uses two separate `useLayoutEffect`s:
47+
48+
1. One runs `renderStyles` on render and on dependency change.
49+
2. A second holds the `removeStyles` cleanup, keyed on `[instance, sheet, globalStyle]`, so cleanup
50+
fires only on unmount, sheet swap or HMR.
51+
52+
Collapsing these into a single effect with per-render cleanup wipes `instanceRules` before the
53+
rules-equality fast path can hit, which costs a double `rebuildGroup` on every render of every
54+
dynamic global style (#5730).

0 commit comments

Comments
 (0)