Skip to content

Commit fd8b3df

Browse files
brenelzryansolidClaude via Cursor
authored
fix(web): stop loading useHead stylesheets from halting hydration (#3600)
* fix(web): stop loading useHead stylesheets from halting hydration The waitAsset gate memo is created without an owner, and the hydrating createMemo peeked a hydration id from that null owner. The gate is now transparent, and useHead skips it while hydrating, since that content is already visible. A streamed boundary whose swap the server holds on a stylesheet ($dfs) settled its _fr record before the swap ran. Resuming on the settle claimed against a document without the content and rendered a second copy, so the resume now waits for the swap. * chore(web,size): finish #3600 — useHead hydration carve-out in JSDoc, size caps re-measured over #3606 Rebased over #3605/#3606. `useHead`'s JSDoc names the documented-behavior carve-out: stylesheet reveal gating is skipped while `sharedConfig.hydrating` is true (hydration claims DOM the browser already painted; the server gated that paint), no FOUC introduced. Size caps re-measured on the rebased head (matches CI byte-for-byte): hydrating (no stores) 20,919 B (+36 over `next`'s 20,883) -> 20.95 KB; hydrating + stores 31,155 B (+10 over 31,145) -> 31.2 KB. `next` at ed60f05 already exceeds two caps — #3606 landed over #3605 unmeasured — so the observe tier (17,455 B, 0 B from this PR) is bumped to 17.5 KB with a note attributing it to #3606. `+ createStore` unchanged at 16,949. Co-authored-by: Claude via Cursor <[email protected]> --------- Co-authored-by: Ryan Carniato <[email protected]> Co-authored-by: Claude via Cursor <[email protected]>
1 parent ed60f05 commit fd8b3df

14 files changed

Lines changed: 484 additions & 19 deletions
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
"@solidjs/web": patch
3+
"solid-js": patch
4+
---
5+
6+
Fix `hydrate()` halting with `TypeError: Cannot read properties of null (reading '_config')` when a `useHead({ tag: "link", props: { rel: "stylesheet", href } })` sheet is still loading as hydration reaches it (the default with an async entry script), including on a late streamed boundary resume. The `waitAsset` gate memo is created without an owner, and the hydrating `createMemo` tried to peek a hydration id from that null owner; the gate is now `transparent`, so hydration never sees it. `useHead` also no longer gates stylesheets while hydrating: that content is already visible, and a pending read inside a boundary's claim window made the boundary render fresh DOM beside the server's.
7+
8+
A streamed `<Loading>` boundary whose fragment swap the server holds on a stylesheet (`$dfs`) now resumes when the swap lands, not when its `_fr` record settles. Resuming on the settle claimed against a document that did not have the content yet, then the delayed swap inserted a second copy.

‎packages/solid/src/client/hydration.ts‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2399,10 +2399,7 @@ function fragmentPending(hy: any, id: string): boolean {
23992399
if (_truncated.has(id)) return false;
24002400
const ref = hy.r[id + "_fr"];
24012401
if (!ref || typeof ref !== "object") return false;
2402-
if (!ref.s) return true;
2403-
if (hy.v && hy.v[id]) return false;
2404-
if (!document.getElementById(id)) return false;
2405-
return !!document.getElementById("pl-" + id);
2402+
return !ref.s || fragmentParked(id);
24062403
}
24072404

24082405
/**
@@ -2420,6 +2417,26 @@ function fragmentSuperseded(id: string): boolean {
24202417
return !!document.getElementById("pl-" + id);
24212418
}
24222419

2420+
/**
2421+
* A settled declaration whose swap has not run yet: its content template and
2422+
* `pl-*` placeholder are both still in the document. `$dfs` holds a swap like
2423+
* this until its stylesheets load, well after the `_fr` ref settles.
2424+
*/
2425+
function fragmentParked(id: string): boolean {
2426+
const hy = (globalThis as any)._$HY;
2427+
if (hy && hy.v && hy.v[id]) return false;
2428+
return !!document.getElementById(id) && !!document.getElementById("pl-" + id);
2429+
}
2430+
2431+
function whenRevealed(id: string, cb: () => void) {
2432+
if (!fragmentParked(id)) return cb();
2433+
const unsubscribe = subscribeFragments(revealed => {
2434+
if (revealed !== id) return;
2435+
unsubscribe();
2436+
queueMicrotask(cb);
2437+
});
2438+
}
2439+
24232440
function anyFragmentPending(): boolean {
24242441
const hy = (globalThis as any)._$HY;
24252442
if (!hy || !hy.r) return false;
@@ -2749,8 +2766,10 @@ function hydratedCreateLoadingBoundary<T, U>(
27492766
// land before any branch below reads the DOM — the settled branches
27502767
// all assume $df already ran.
27512768
replayHeldFragment(id);
2769+
// A parked fragment has settled but not swapped: it waits like a pending one.
2770+
const s = fr && typeof fr === "object" ? (fr.s === 1 && fragmentParked(id) ? 0 : fr.s) : 0;
27522771

2753-
if (fr && typeof fr === "object" && fr.s === 1 && !assetPromise && !fragmentSuperseded(id)) {
2772+
if (s === 1 && !assetPromise && !fragmentSuperseded(id)) {
27542773
// Fragment already settled and swapped in ($df ran before hydration):
27552774
// the content is in the DOM, so hydrate straight through. The fallback
27562775
// only hydrates when it is actually showing — rendering it here would
@@ -2763,7 +2782,7 @@ function hydratedCreateLoadingBoundary<T, U>(
27632782
settledSerializationResumeQueued = true;
27642783
const [, resume] = initBoundaryResume(o, id);
27652784

2766-
if (fr && typeof fr === "object" && fr.s === 1 && fragmentSuperseded(id)) {
2785+
if (s === 1 && fragmentSuperseded(id)) {
27672786
// SUPERSEDED (#2801's inverse): the declaration settled but its markup
27682787
// was retired before it shipped — an outer boundary settled first and
27692788
// its fragment carries the final branch instead, so this placeholder
@@ -2786,8 +2805,8 @@ function hydratedCreateLoadingBoundary<T, U>(
27862805
return fallback();
27872806
}
27882807

2789-
if (fr && typeof fr === "object" && (fr.s === 1 || fr.s === 2)) {
2790-
if (fr.s === 2) {
2808+
if (s === 1 || s === 2) {
2809+
if (s === 2) {
27912810
// Rejected stream fragments swap to an empty template; any outer error fallback
27922811
// has to be created as fresh client DOM, not claimed from server markup.
27932812
// Nothing else consumes the settled-rejected `_fr` promise once this
@@ -2819,7 +2838,13 @@ function hydratedCreateLoadingBoundary<T, U>(
28192838
// for this resume to claim instead of holding it; if the swap already
28202839
// arrived and was held awaiting a claimant, replay it now.
28212840
claimFragment(id);
2822-
waitAndResume(fr, resume, assetPromise, false, fragmentAbort(id));
2841+
waitAndResume(
2842+
fr,
2843+
shouldHydrate => (shouldHydrate ? whenRevealed(id, () => resume(true)) : resume(false)),
2844+
assetPromise,
2845+
false,
2846+
fragmentAbort(id)
2847+
);
28232848
return fallback();
28242849
}
28252850

‎packages/web/src/client.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,9 @@ export const waitAsset = (promise: Promise<unknown>): void => {
155155
if (!gate) {
156156
runWithOwner(null, () => {
157157
// NOT sync: the node must be async-aware (the promise is the value
158-
// being awaited; sync nodes reject thenable returns).
159-
gate = createMemo(() => promise);
158+
// being awaited; sync nodes reject thenable returns). Transparent: the
159+
// hydrating memo wrapper would otherwise peek an id off the null owner.
160+
gate = createMemo(() => promise, { transparent: true });
160161
});
161162
assetGates.set(promise, gate);
162163
}
@@ -1914,7 +1915,13 @@ function gateHeadResource(props) {
19141915
// errored) sheet must acquire synchronously — cached sheets add zero
19151916
// wait, adopted server-emitted sheets never stall — and even a
19161917
// settled promise costs a microtask through the async machinery.
1917-
if (gateable && entry.loadState === "pending" && typeof waitAsset === "function")
1918+
// Hydrating content is already visible; the server gated its reveal.
1919+
if (
1920+
gateable &&
1921+
!sharedConfig.hydrating &&
1922+
entry.loadState === "pending" &&
1923+
typeof waitAsset === "function"
1924+
)
19181925
waitAsset(entry.loadPromise);
19191926
},
19201927
() => acquireAsset(descriptor)
@@ -1926,7 +1933,10 @@ function gateHeadResource(props) {
19261933
* Resolution is last-committed group per identity (reactive updates keep
19271934
* the registration's original commit position); disposal restores the
19281935
* previous winner. During hydration the server-flushed head state stays
1929-
* authoritative until hydration completes. See docs/head-management-rfc.md.
1936+
* authoritative until hydration completes. Stylesheet reveal gating is
1937+
* skipped while `sharedConfig.hydrating` is true: hydration claims DOM the
1938+
* browser already painted, and the server gated that paint — no FOUC is
1939+
* introduced. See docs/head-management-rfc.md.
19301940
*/
19311941
export function useHead(tag: HeadTag | HeadTag[] | (() => HeadTag | HeadTag[])): void;
19321942

@@ -1937,7 +1947,9 @@ export function useHead(tag: HeadTag | HeadTag[] | (() => HeadTag | HeadTag[])):
19371947
* after registration). Props values may be getters (reactive); updates keep
19381948
* the registration's original commit position. Disposal removes the
19391949
* registration and re-resolves (previous committed winner is restored).
1940-
* See docs/head-management-rfc.md.
1950+
* Stylesheet reveal gating is skipped while `sharedConfig.hydrating` is
1951+
* true: hydration claims DOM the browser already painted, and the server
1952+
* gated that paint — no FOUC is introduced. See docs/head-management-rfc.md.
19411953
*/
19421954
export function useHead(tags) {
19431955
initHeadRegistry();
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"chunks": [
3+
"<html><head><link rel=\"stylesheet\" href=\"/styled-shell.css\"></head><body><div id=\"app-root\"><main _hk=0><button id=\"shell\">shell <!--$-->0<!--/--></button><!--$--><template id=\"pl-2\"></template><p _hk=20 id=\"waiting\">waiting</p><!--pl-2--><!--/--></main></div></body></html><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"$B\"]=($R[0]={2000:$R[1]=($R[2]=($R[3]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p,\"2_fr\":$R[4]=($R[5]=$R[3]()).p});(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r[\"$B\"]})(_$HY.r[\"$B\"]);</script>",
4+
"<script>($R[6]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[2],\"late\");$dfs(\"2\",1,0);function $df(e){return _$HY.f?_$HY.f(e):$dfr(e)}function $dfr(e,n,o,t){if(!(n=document.getElementById(e)))return 0;if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dq=_$HY.dq||{})[e]=1,0;for(;o&&(8!==o.nodeType||o.nodeValue!==\"pl-\"+e);)t=o.nextSibling,o.remove(),o=t;t=o.parentNode,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$HY.fe(e,t),_$HY.hp&&_$HY.hp[e]&&($dh(_$HY.hp[e]),delete _$HY.hp[e]),$dfd();return 1}function $dfl(e,o,n){if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dlq=_$HY.dlq||{})[e]=1,0;if(o._$fl)return 1;for(n=o.nextSibling;n;){if(8===n.nodeType&&n.nodeValue===\"pl-\"+e){o.parentNode&&o.parentNode.insertBefore(o.content.cloneNode(!0),n),o._$fl=1,$dfd();return 1}n=n.nextSibling}return 0}function $dflj(e,i){for(i=0;i<e.length;i++)$dfl(e[i])}function $dfd(e,i){if(e=_$HY.dq){_$HY.dq=0;for(i in e)$df(i)}if(e=_$HY.dlq){_$HY.dlq=0;for(i in e)$dfl(i)}}function $dfs(e,c,d){(_$HY.sc=_$HY.sc||{})[e]=c,d&&((_$HY.sd=_$HY.sd||{})[e]=1)}function $dfg(e,g,i,k){if(!(g=_$HY.sg&&_$HY.sg[e]))return;for(i=0;i<g.length;i++)if(_$HY.sc&&_$HY.sc[g[i]]>0)return;for(i=0;i<g.length;i++)k=g[i],delete _$HY.sg[k],$df(k)}function $dfc(e){if(--_$HY.sc[e]<=0){delete _$HY.sc[e],_$HY.sg&&_$HY.sg[e]?$dfg(e):!(_$HY.sd&&_$HY.sd[e])&&$df(e);_$HY.sd&&delete _$HY.sd[e]}}function $dfj(e,i,n){for(i=0;i<e.length;i++)if(_$HY.sc&&_$HY.sc[e[i]]>0){for(n=0;n<e.length;n++)(_$HY.sg=_$HY.sg||{})[e[n]]=e;return}for(i=0;i<e.length;i++)$df(e[i])};</script><link rel=\"stylesheet\" href=\"/styled-late.css\" onload=\"$dfc('2')\" onerror=\"$dfc('2')\"><template id=\"2\"><button _hk=20030 id=\"late\"><!--$-->late<!--/--> <!--$-->0<!--/--></button></template><script>$R[6]($R[5],!0);</script>"
5+
]
6+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "use-head-stylesheet-pending",
3+
"shell": "<div _hk=1><span>styled</span> n=<!--$-->0<!--/--></div><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"0\"]=$R[0]=($R[1]=($R[2]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p;($R[3]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[1],\"styled\");</script>",
4+
"rest": ""
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"name": "use-head-stylesheet-streamed-boundary",
3+
"shell": "<div _hk=0><span>lead </span><!--$--><template id=\"pl-1\"></template><p _hk=10>waiting</p><!--pl-1--><!--/--><span> tail <!--$-->0<!--/--></span></div><script>(self.$R=self.$R||{})[\"\"]=[];_$HY.r[\"$B\"]=($R[0]={1000:$R[1]=($R[2]=($R[3]=() => {\n\tconst resolver = {\n\t\tp: 0,\n\t\ts: 0,\n\t\tf: 0\n\t};\n\tresolver.p = new Promise((resolve, reject) => {\n\t\tresolver.s = resolve;\n\t\tresolver.f = reject;\n\t});\n\treturn resolver;\n})()).p,\"1_fr\":$R[4]=($R[5]=$R[3]()).p});(b=>{for(var k in b)_$HY.r[k]=b[k];delete _$HY.r[\"$B\"]})(_$HY.r[\"$B\"]);</script>",
4+
"rest": "<template id=\"1\"><section _hk=1001>late styled</section></template><script>($R[6]=(resolver, data) => {\n\tresolver.s(data);\n\tresolver.p.s = 1;\n\tresolver.p.v = data;\n})($R[2],\"late styled\");$df(\"1\");function $df(e){return _$HY.f?_$HY.f(e):$dfr(e)}function $dfr(e,n,o,t){if(!(n=document.getElementById(e)))return 0;if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dq=_$HY.dq||{})[e]=1,0;for(;o&&(8!==o.nodeType||o.nodeValue!==\"pl-\"+e);)t=o.nextSibling,o.remove(),o=t;t=o.parentNode,o.replaceWith(n.content),n.remove(),(_$HY.v=_$HY.v||{})[e]=1,_$HY.fe(e,t),_$HY.hp&&_$HY.hp[e]&&($dh(_$HY.hp[e]),delete _$HY.hp[e]),$dfd();return 1}function $dfl(e,o,n){if(!(o=document.getElementById(\"pl-\"+e)))return(_$HY.dlq=_$HY.dlq||{})[e]=1,0;if(o._$fl)return 1;for(n=o.nextSibling;n;){if(8===n.nodeType&&n.nodeValue===\"pl-\"+e){o.parentNode&&o.parentNode.insertBefore(o.content.cloneNode(!0),n),o._$fl=1,$dfd();return 1}n=n.nextSibling}return 0}function $dflj(e,i){for(i=0;i<e.length;i++)$dfl(e[i])}function $dfd(e,i){if(e=_$HY.dq){_$HY.dq=0;for(i in e)$df(i)}if(e=_$HY.dlq){_$HY.dlq=0;for(i in e)$dfl(i)}}function $dfs(e,c,d){(_$HY.sc=_$HY.sc||{})[e]=c,d&&((_$HY.sd=_$HY.sd||{})[e]=1)}function $dfg(e,g,i,k){if(!(g=_$HY.sg&&_$HY.sg[e]))return;for(i=0;i<g.length;i++)if(_$HY.sc&&_$HY.sc[g[i]]>0)return;for(i=0;i<g.length;i++)k=g[i],delete _$HY.sg[k],$df(k)}function $dfc(e){if(--_$HY.sc[e]<=0){delete _$HY.sc[e],_$HY.sg&&_$HY.sg[e]?$dfg(e):!(_$HY.sd&&_$HY.sd[e])&&$df(e);_$HY.sd&&delete _$HY.sd[e]}}function $dfj(e,i,n){for(i=0;i<e.length;i++)if(_$HY.sc&&_$HY.sc[e[i]]>0){for(n=0;n<e.length;n++)(_$HY.sg=_$HY.sg||{})[e[n]]=e;return}for(i=0;i<e.length;i++)$df(e[i])};</script><script>$R[6]($R[5],!0);</script>"
5+
}

‎packages/web/test/harness/document-shell.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,49 @@ export function HeadShellApp() {
118118
</html>
119119
);
120120
}
121+
122+
/**
123+
* Stylesheets from useHead under the document shell. The shell sheet is
124+
* still loading when hydrate() runs (the default with an async entry
125+
* script), and the late boundary's sheet holds its streamed swap through the
126+
* server's `$dfs` gate, so the boundary's `_fr` record settles before its
127+
* content is in the document.
128+
*/
129+
export const STYLED_SHELL_CSS = "/styled-shell.css";
130+
export const STYLED_LATE_CSS = "/styled-late.css";
131+
132+
function LateSheet() {
133+
useHead({ tag: "link", props: { rel: "stylesheet", href: STYLED_LATE_CSS } });
134+
return null;
135+
}
136+
137+
function LateStyled() {
138+
const data = createMemo(async () => {
139+
await new Promise(r => setTimeout(r, 10));
140+
return "late";
141+
});
142+
const [n, setN] = createSignal(0);
143+
return (
144+
<Show when={data()}>
145+
<LateSheet />
146+
<button id="late" onClick={() => setN(n() + 1)}>
147+
{data()} {n()}
148+
</button>
149+
</Show>
150+
);
151+
}
152+
153+
export function StyledIsland() {
154+
useHead({ tag: "link", props: { rel: "stylesheet", href: STYLED_SHELL_CSS } });
155+
const [n, setN] = createSignal(0);
156+
return (
157+
<main>
158+
<button id="shell" onClick={() => setN(n() + 1)}>
159+
shell {n()}
160+
</button>
161+
<Loading fallback={<p id="waiting">waiting</p>}>
162+
<LateStyled />
163+
</Loading>
164+
</main>
165+
);
166+
}

‎packages/web/test/harness/scenarios.tsx‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ import {
4444
clientOnly,
4545
isServer,
4646
ssrElement,
47+
useHead,
4748
type JSX
4849
} from "@solidjs/web";
4950
import { makeRows, TriggerList, forms, type Row } from "./polymorphic.jsx";
@@ -1921,6 +1922,58 @@ function EffectWriteShow() {
19211922
);
19221923
}
19231924

1925+
// ---------------------------------------------------------------------------
1926+
// useHead stylesheet whose sheet is still loading when hydrate() reaches it
1927+
// (jsdom never loads sheets, so the reveal gate is always pending here). The
1928+
// gate memo is created detached from the owner tree; it must stay out of the
1929+
// hydration id sequence instead of peeking the next child id of a null owner.
1930+
// The async memo after the call checks that no id was consumed.
1931+
const headCssHref = "/parity-head.css";
1932+
let bumpHeadCss!: () => void;
1933+
function UseHeadStylesheetPending() {
1934+
useHead({ tag: "link", props: { rel: "stylesheet", href: headCssHref } });
1935+
const [n, setN] = createSignal(0);
1936+
bumpHeadCss = () => setN(v => v + 1);
1937+
const label = createMemo(async () => {
1938+
await sleep(5);
1939+
return "styled";
1940+
});
1941+
return (
1942+
<div>
1943+
<span>{label()}</span> n={n()}
1944+
</div>
1945+
);
1946+
}
1947+
1948+
// Same gate reached on a late streamed boundary resume.
1949+
const headCssLateHref = "/parity-head-late.css";
1950+
function HeadCssBoundaryContent() {
1951+
useHead({ tag: "link", props: { rel: "stylesheet", href: headCssLateHref } });
1952+
const data = createMemo(async () => {
1953+
await sleep(10);
1954+
return "late styled";
1955+
});
1956+
return <section>{data()}</section>;
1957+
}
1958+
let bumpHeadCssStreamed!: () => void;
1959+
function UseHeadStylesheetStreamed() {
1960+
const [n, setN] = createSignal(0);
1961+
bumpHeadCssStreamed = () => setN(v => v + 1);
1962+
return (
1963+
<div>
1964+
<span>lead </span>
1965+
<Loading fallback={<p>waiting</p>}>
1966+
<HeadCssBoundaryContent />
1967+
</Loading>
1968+
<span> tail {n()}</span>
1969+
</div>
1970+
);
1971+
}
1972+
const loadHeadSheets = () => {
1973+
for (const link of document.querySelectorAll('link[href^="/parity-head"]'))
1974+
link.dispatchEvent(new Event("load"));
1975+
};
1976+
19241977
export const scenarios: Scenario[] = [
19251978
{
19261979
name: "polymorphic-chain",
@@ -2639,5 +2692,30 @@ export const scenarios: Scenario[] = [
26392692
expectedText: "toast!Hello",
26402693
serverText: "Hello",
26412694
stableSelector: "main"
2695+
},
2696+
{
2697+
name: "use-head-stylesheet-pending",
2698+
App: UseHeadStylesheetPending,
2699+
async: true,
2700+
expectedText: "styled n=0",
2701+
update: () => {
2702+
loadHeadSheets();
2703+
bumpHeadCss();
2704+
},
2705+
expectedTextAfterUpdate: "styled n=1",
2706+
stableSelector: "div, span"
2707+
},
2708+
{
2709+
name: "use-head-stylesheet-streamed-boundary",
2710+
App: UseHeadStylesheetStreamed,
2711+
async: true,
2712+
expectedText: "lead late styled tail 0",
2713+
serverText: "lead waiting tail 0",
2714+
update: () => {
2715+
loadHeadSheets();
2716+
bumpHeadCssStreamed();
2717+
},
2718+
expectedTextAfterUpdate: "lead late styled tail 1",
2719+
stableSelector: "div, span, section"
26422720
}
26432721
];

‎packages/web/test/hydration/document-shell.spec.tsx‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@ import {
2121
App,
2222
AsyncApp,
2323
HeadShellApp,
24+
StyledIsland,
2425
computeRuns,
2526
setHeadShellStarted,
26-
APP_ROOT_MARKUP
27+
APP_ROOT_MARKUP,
28+
STYLED_LATE_CSS
2729
} from "../harness/document-shell.jsx";
2830

2931
const artifactsDir = resolve(dirname(fileURLToPath(import.meta.url)), "../harness/__artifacts__");
@@ -162,4 +164,59 @@ describe("document-shell pattern — client hydrate (#3000)", () => {
162164
dispose();
163165
setHeadShellStarted(false);
164166
});
167+
168+
test("useHead stylesheets: loading sheets neither halt hydration nor resume a gated fragment early", async () => {
169+
(globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };
170+
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
171+
const error = vi.spyOn(console, "error").mockImplementation(() => {});
172+
const { chunks } = JSON.parse(
173+
readFileSync(resolve(artifactsDir, "document-shell-styled.json"), "utf-8")
174+
) as { chunks: string[] };
175+
176+
const container = document.createElement("div");
177+
document.body.appendChild(container);
178+
applyChunk(container, chunks[0], true);
179+
const root = container.querySelector("#app-root") as HTMLElement;
180+
181+
// jsdom never loads sheets: the shell's sheet is pending for all of hydration.
182+
const dispose = hydrate(() => <StyledIsland />, root);
183+
flush();
184+
await sleep(20);
185+
flush();
186+
root.querySelector<HTMLElement>("#shell")!.click();
187+
flush();
188+
expect(root.querySelector("#shell")!.textContent).toBe("shell 1");
189+
190+
// The late chunk settles the boundary's `_fr` record while `$dfs` holds
191+
// the swap on the boundary's own sheet.
192+
applyChunk(container, chunks[1], false);
193+
const serverLate = container
194+
.querySelector<HTMLTemplateElement>('template:not([id^="pl-"])')!
195+
.content.querySelector("#late");
196+
await sleep(30);
197+
flush();
198+
expect(root.querySelector("#waiting")).not.toBeNull();
199+
expect(root.querySelector("#late")).toBeNull();
200+
201+
const link = container.querySelector(`link[href="${STYLED_LATE_CSS}"]`)!;
202+
// jsdom runs inline handlers outside the scope the stream scripts were evaluated in.
203+
(0, eval)(link.getAttribute("onload")!);
204+
link.removeAttribute("onload");
205+
link.dispatchEvent(new Event("load"));
206+
await sleep(20);
207+
flush();
208+
209+
expect(root.querySelectorAll("#late")).toHaveLength(1);
210+
expect(root.querySelector("#late")).toBe(serverLate);
211+
root.querySelector<HTMLElement>("#late")!.click();
212+
flush();
213+
expect(root.textContent).toBe("shell 1late 1");
214+
215+
expect(error).not.toHaveBeenCalled();
216+
expect(warn).not.toHaveBeenCalled();
217+
warn.mockRestore();
218+
error.mockRestore();
219+
dispose();
220+
container.remove();
221+
});
165222
});

0 commit comments

Comments
 (0)