From af35f732c6d50e106b0ae518725772e28fa66757 Mon Sep 17 00:00:00 2001 From: leo7martins <219400372+leo7martins@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:20:17 +0000 Subject: [PATCH] fix(web): name the client-only-allocation drift in the hydration key-miss warning (#5226) Reproduce the menu-button hydration-id drift in the parity harness and at the document root: a focus primitive whose isServer early-out skips, on the server, the three id consumers it creates on the client while hydrating (the hydratable signal's onSettled effect and the two event-listener effects) shifts the client's key sequence three past the server's; every keyed claim after the gate misses, the server-rendered chain stays unclaimed behind a detached clone, and the button is dead in dev and (silently) in production. The drift tree is pinned as a known failure; the same chain with the primitive's allocations present on both builds claims and stays interactive through a real click, in the development and LOWER_SHOW (production compile) lanes. The dev key-miss warning now names this drift class beside the NoHydration guidance. --- .../menu-button-hydration-drift-5226.md | 5 + packages/web/src/client.ts | 7 + .../__artifacts__/menu-button-chain-5226.json | 5 + .../menu-button-chain-aligned-5226.json | 5 + .../menu-button-document-5226.json | 4 + .../menu-button-document-aligned-5226.json | 4 + packages/web/test/harness/scenarios.tsx | 332 ++++++++++++++++++ .../test/hydration/menu-button-5226.spec.tsx | 149 ++++++++ .../web/test/server/menu-button-5226.spec.tsx | 58 +++ 9 files changed, 569 insertions(+) create mode 100644 .changeset/menu-button-hydration-drift-5226.md create mode 100644 packages/web/test/harness/__artifacts__/menu-button-chain-5226.json create mode 100644 packages/web/test/harness/__artifacts__/menu-button-chain-aligned-5226.json create mode 100644 packages/web/test/harness/__artifacts__/menu-button-document-5226.json create mode 100644 packages/web/test/harness/__artifacts__/menu-button-document-aligned-5226.json create mode 100644 packages/web/test/hydration/menu-button-5226.spec.tsx create mode 100644 packages/web/test/server/menu-button-5226.spec.tsx diff --git a/.changeset/menu-button-hydration-drift-5226.md b/.changeset/menu-button-hydration-drift-5226.md new file mode 100644 index 000000000..d0a7367b5 --- /dev/null +++ b/.changeset/menu-button-hydration-drift-5226.md @@ -0,0 +1,5 @@ +--- +"@solidjs/web": patch +--- + +Dev hydration key-miss warning names the client-only-allocation drift class (#5226) diff --git a/packages/web/src/client.ts b/packages/web/src/client.ts index f2e81ed1e..2a585ba85 100644 --- a/packages/web/src/client.ts +++ b/packages/web/src/client.ts @@ -2778,6 +2778,13 @@ export function getNextElement(template) { `server render, wrap the document shell in and re-enter with ` + ` around the hydrated subtree (or pass hydrate() a renderId matching ` + `the server's ).` + + // The sequence drifts by every computation one build creates and the + // other does not; a primitive that returns early under `isServer` + // and only then allocates (an effect, a memo) shifts every key + // claimed after it (#5226). + ` A library or primitive that skips allocations on the server (an early ` + + `\`if (isServer) return\` before creating effects or memos) drifts the client's ` + + `sequence ahead of the server's the same way.` + // The parser drops a
start tag inside an open : the // element never exists, so its key finds nothing (#4875). (template._html && template._html.startsWith("

page content

", + "rest": "" +} \ No newline at end of file diff --git a/packages/web/test/harness/__artifacts__/menu-button-chain-aligned-5226.json b/packages/web/test/harness/__artifacts__/menu-button-chain-aligned-5226.json new file mode 100644 index 000000000..0b8d3eeeb --- /dev/null +++ b/packages/web/test/harness/__artifacts__/menu-button-chain-aligned-5226.json @@ -0,0 +1,5 @@ +{ + "name": "menu-button-chain-aligned-5226", + "shell": "

page content

", + "rest": "" +} \ No newline at end of file diff --git a/packages/web/test/harness/__artifacts__/menu-button-document-5226.json b/packages/web/test/harness/__artifacts__/menu-button-document-5226.json new file mode 100644 index 000000000..de57de925 --- /dev/null +++ b/packages/web/test/harness/__artifacts__/menu-button-document-5226.json @@ -0,0 +1,4 @@ +{ + "shell": "menu button chain

page content

", + "chunks": [] +} \ No newline at end of file diff --git a/packages/web/test/harness/__artifacts__/menu-button-document-aligned-5226.json b/packages/web/test/harness/__artifacts__/menu-button-document-aligned-5226.json new file mode 100644 index 000000000..4100e214b --- /dev/null +++ b/packages/web/test/harness/__artifacts__/menu-button-document-aligned-5226.json @@ -0,0 +1,4 @@ +{ + "shell": "menu button chain

page content

", + "chunks": [] +} \ No newline at end of file diff --git a/packages/web/test/harness/scenarios.tsx b/packages/web/test/harness/scenarios.tsx index 9a937e7eb..06a5dfa18 100644 --- a/packages/web/test/harness/scenarios.tsx +++ b/packages/web/test/harness/scenarios.tsx @@ -29,6 +29,7 @@ import { onSettled, createProjection, createStore, + createUniqueId, merge, omit, Show, @@ -53,6 +54,7 @@ import { isServer, ssrElement, useHead, + HydrationScript, type JSX } from "@solidjs/web"; import { makeRows, TriggerList, forms, type Row } from "./polymorphic.jsx"; @@ -3396,6 +3398,311 @@ export function preflushNested(shape: PreflushNestedShape, twin = false) { }; } +// --------------------------------------------------------------------------- +// #5226: a navigation-rail menu-button chain — server/client hydration-id +// drift leaves the server-rendered button dead after hydration. The chain +// that found it: custom-element wrappers, a tooltip component whose internal +// non-keyed takes its fallback (nothing of the tooltip renders), a +// dynamic() native button, and unrendered non-keyed branches that +// still reserve ids. Every boundary here is a protocol participant. +let toggleRailMenu!: () => void; +// The focus primitive the real chain used comes in two allocation shapes, +// switched per App below (each App sets it on every instantiation, so the +// shape is deterministic regardless of scenario order in one module). +let railFocusSignal: (target: () => unknown) => () => boolean; + +// The shape the reproduction ships: `isServer` returns early, so the three +// id consumers below — the onSettled tracked effect and the two +// event-listener effects — are created on the client only. The client's +// claim pass then consumes ids the server never did (#5226). +function createGatedFocusSignal(target: () => unknown) { + if (isServer) return () => false; + const [isActive, setIsActive] = createSignal(false); + onSettled(() => { + setIsActive(document.activeElement === target()); + }); + createEffect( + () => target(), + el => { + (el as Element | undefined)?.addEventListener?.("blur", () => setIsActive(false), true); + return () => undefined; + } + ); + createEffect( + () => target(), + el => { + (el as Element | undefined)?.addEventListener?.("focus", () => setIsActive(true), true); + return () => undefined; + } + ); + return isActive; +} + +// The aligned shape: the same allocations run on both builds — the server's +// onSettled stub and mock effects consume the same three ids the client's +// effect nodes consume, so the tree's keys agree and the button claims. +function createAlignedFocusSignal(target: () => unknown) { + const [isActive, setIsActive] = createSignal(false); + onSettled(() => { + setIsActive(document.activeElement === target()); + }); + createEffect( + () => target(), + el => { + (el as Element | undefined)?.addEventListener?.("blur", () => setIsActive(false), true); + return () => undefined; + } + ); + createEffect( + () => target(), + el => { + (el as Element | undefined)?.addEventListener?.("focus", () => setIsActive(true), true); + return () => undefined; + } + ); + return isActive; +} + +function RailPlainTooltip(props: { children?: unknown }) { + return ( + + {props.children} + + ); +} + +function RailTooltip(props: { variant?: string; tip?: unknown; children?: unknown }) { + const [refAnchor, setRefAnchor] = createSignal(); + let refTooltip: unknown; + const isPersistent = createMemo(() => false); + const [isOpen, setIsOpen] = createSignal(false); + const [shouldOpen, setShouldOpen] = createSignal({ open: false, immediately: false }); + const [isHoveringOverTooltip, setIsHoveringOverTooltip] = createSignal(false); + const [isClicking, setIsClicking] = createSignal(false); + const isAnchorFocused = railFocusSignal(() => refAnchor()); + createEffect( + () => [shouldOpen(), isOpen(), isClicking(), isHoveringOverTooltip()], + ([should, open, clicking, hovering]) => { + if (should.immediately) setIsOpen(should.open); + else if (should.open && !open && !clicking && !hovering) + setShouldOpen({ open: false, immediately: true }); + return () => undefined; + } + ); + const isTooltipVisible = () => Boolean(undefined); + const hasAnchorOrTooltipFocus = createMemo( + () => isAnchorFocused() && refAnchor() !== undefined && isPersistent() + ); + createEffect( + () => [!isPersistent() || isOpen(), hasAnchorOrTooltipFocus(), isTooltipVisible()], + ([shouldBeVisible, focused, visible]) => { + if (shouldBeVisible && focused !== visible) setShouldOpen({ open: true, immediately: true }); + return () => undefined; + } + ); + const tooltipId = createUniqueId(); + return ( + +
+ {props.children} + + {props.tip} + +
+
+ ); +} + +function RailMenuButton(props: { + ariaLabel: string; + ariaLabelSelected: string; + title?: string; + titleSelected?: string; + expanded?: boolean; + variant?: string; + disabled?: boolean; + iconPosition?: string; + children?: unknown; + onClick?: (event: unknown) => void; +}) { + let ref: any; + let refButton: any; + const size = () => "small"; + const labelContent = children(() => props.children); + const label = () => (props.expanded ? props.ariaLabelSelected : props.ariaLabel); + const title = () => (props.expanded ? props.titleSelected : props.title); + const onContextMenu = (event: Event) => event.preventDefault(); + const ButtonOrAnchor = dynamic(() => "button"); + return ( + {title()} : undefined} + > + + + + + + + menu-icon}> + menu-open-icon + + + + +
+ + {labelContent()} + +
+
+ +
+ + + + + + ); +} + +function NavigationRail(props: { + show: boolean; + ariaLabel: string; + menuButton?: Record; + expanded: boolean; + modal?: boolean; + center?: boolean; + hideWhenCollapsed?: boolean; + onClickMenuButton?: (event: unknown) => void; + children?: unknown; +}) { + let refList: any; + const isExpanded = createMemo(prev => + props.show || prev === undefined ? Boolean(props.expanded) : prev + ); + const isModal = createMemo(prev => + props.show || prev === undefined ? Boolean(props.modal) : prev + ); + const isCenter = createMemo(prev => + props.show || prev === undefined ? Boolean(props.center) : prev + ); + const isHideWhenCollapsed = createMemo(prev => + props.show || prev === undefined ? Boolean(props.hideWhenCollapsed) : prev + ); + const hasMenuButton = () => props.menuButton !== undefined; + const isHiddenWhenCollapsed = createMemo( + () => hasMenuButton() && isModal() && isHideWhenCollapsed() + ); + const isVisuallyExpanded = createMemo(() => isExpanded() || isHiddenWhenCollapsed()); + return ( + +
+
+ + +
+
+
+
+
+ {props.children} + + ); +} + +export function MenuButtonChain() { + railFocusSignal = createGatedFocusSignal; + const [expanded, setExpanded] = createSignal(false); + toggleRailMenu = () => setExpanded(expanded => !expanded); + return ( + setExpanded(expanded => !expanded)} + > +
+

page content

+
+
+ ); +} + +// The document shell the vite plugin's `start` mode renders on both sides: +// the client hydrates this same tree at the document root. +export function MenuButtonDocument(props: { children?: unknown }) { + return ( + + + + + menu button chain + + + {props.children} + + ); +} + +// The same chain with the aligned focus primitive: the server and client +// allocate the tooltip's three extra ids in the same order, so hydration +// claims the whole menu-button subtree. +export function MenuButtonChainAligned() { + railFocusSignal = createAlignedFocusSignal; + const [expanded, setExpanded] = createSignal(false); + toggleRailMenu = () => setExpanded(expanded => !expanded); + return ( + setExpanded(expanded => !expanded)} + > +
+

page content

+
+
+ ); +} + export const scenarios: Scenario[] = [ { name: "polymorphic-chain", @@ -4428,5 +4735,30 @@ export const scenarios: Scenario[] = [ async: true, update: () => setLatestChain(4), expectedTextAfterUpdate: "7" + }, + { + // #5226: the gated focus primitive leaves the server's id sequence + // behind the client's by three, so every keyed claim after the gate + // misses and the server-rendered menu button stays unclaimed while the + // client builds a detached clone — the button is dead after hydration, + // in dev and (silently) in production. Flips when a fix lands. + name: "menu-button-chain-5226", + App: MenuButtonChain, + knownFailure: + "#5226 — the gated focus primitive consumes three client-only ids; the menu-button chain misses its keys and stays unclaimed", + expectedText: "menu-iconpage content", + update: () => toggleRailMenu(), + expectedTextAfterUpdate: "menu-open-iconpage content", + stableSelector: "sm-navigation-rail, sm-icon-button, sm-button, button, md-icon, main, p" + }, + { + // The control: the same chain with the aligned primitive claims the + // whole subtree and the button is interactive after hydration. + name: "menu-button-chain-aligned-5226", + App: MenuButtonChainAligned, + expectedText: "menu-iconpage content", + update: () => toggleRailMenu(), + expectedTextAfterUpdate: "menu-open-iconpage content", + stableSelector: "sm-navigation-rail, sm-icon-button, sm-button, button, md-icon, main, p" } ]; diff --git a/packages/web/test/hydration/menu-button-5226.spec.tsx b/packages/web/test/hydration/menu-button-5226.spec.tsx new file mode 100644 index 000000000..98d2e2518 --- /dev/null +++ b/packages/web/test/hydration/menu-button-5226.spec.tsx @@ -0,0 +1,149 @@ +/** + * @jsxImportSource @solidjs/web + * @vitest-environment jsdom + * + * #5226: hydration-id drift leaves the server-rendered menu button dead. + * + * The app that found this rendered a navigation rail's menu button through + * a chain of component boundaries — custom-element wrappers, a tooltip + * component whose internal non-keyed takes its fallback, a + * dynamic() native button, unrendered branches that still reserve + * ids — and hydrated the full document at the document root. The tooltip's + * focus primitive returns early on the server, so the three id consumers + * it creates on the client (the onSettled tracked effect and the two + * event-listener effects) shift the client's key sequence three past the + * server's: every keyed claim after the gate misses, the server-rendered + * chain stays unclaimed, and the client builds a detached clone holding + * all the handlers — the visible button is dead, in development and + * (silently, all checks being dev-only) in production. + * + * The aligned control runs the same chain with the primitive's allocations + * present on both builds: the server's onSettled stub and mock effects + * consume the same three ids, the keys agree, the whole chain claims, and + * the server-rendered button is interactive. + * + * test/server/menu-button-5226.spec.tsx records both artifacts; this spec + * replays them (document.write, hydrate at the document root — the + * vite-plugin `start` shape) and drives a real click. + */ +import { describe, expect, test, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { flush } from "solid-js"; +import { hydrate } from "@solidjs/web"; +import { + MenuButtonChain, + MenuButtonChainAligned, + MenuButtonDocument +} from "../harness/scenarios.jsx"; + +const artifactsDir = resolve(dirname(fileURLToPath(import.meta.url)), "../harness/__artifacts__"); +const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); + +function loadDocument(name: string): string { + const { shell, chunks } = JSON.parse(readFileSync(resolve(artifactsDir, `${name}.json`), "utf8")); + return shell + (chunks ?? []).join(""); +} + +async function settle() { + await sleep(30); + flush(); + await sleep(10); + flush(); +} + +/** + * Hydrate the recorded document at the document root and return the server + * nodes captured before the claim, plus the disposer. + */ +async function hydrateDocument(name: string, App: () => unknown) { + (globalThis as any)._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} }; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + document.write(loadDocument(name)); + document.close(); + const serverNodes = new Set( + [...document.querySelectorAll("[_hk]")].concat([document.documentElement]) + ); + const serverButton = document.querySelector("button")!; + const dispose = hydrate( + () => ( + + + + ), + document + ); + flush(); + await settle(); + return { warn, serverNodes, serverButton, dispose }; +} + +function cleanup() { + delete (globalThis as any)._$HY; + document.body.innerHTML = ""; + document.head.innerHTML = ""; +} + +describe("#5226 menu-button chain — document-root hydration", () => { + test("aligned: the server-rendered button is claimed and interactive", async () => { + const { warn, serverNodes, serverButton, dispose } = await hydrateDocument( + "menu-button-document-aligned-5226", + MenuButtonChainAligned + ); + try { + // The whole server-rendered chain is claimed: no key miss, no + // unclaimed node, and every server element survives as itself. + expect(warn).not.toHaveBeenCalled(); + const button = document.querySelector("button")!; + expect(button).toBe(serverButton); + for (const node of serverNodes) expect(node.isConnected).toBe(true); + expect(document.querySelector("sm-navigation-rail")).toBeTruthy(); + expect(document.querySelector("md-icon")).toBeTruthy(); + + // Interactive: a real click on the server-rendered button flips the + // rail's expansion state through the hydrated reactive graph. + expect(button.getAttribute("aria-checked")).toBe("false"); + button.click(); + flush(); + expect(button.getAttribute("aria-checked")).toBe("true"); + // A boolean-attribute binding: true is the attribute's presence. + expect(document.querySelector(".rail")!.hasAttribute("data-expanded")).toBe(true); + expect(document.body.textContent).toContain("menu-open-icon"); + // And back: the binding is live, not a one-shot replay. + button.click(); + flush(); + expect(button.getAttribute("aria-checked")).toBe("false"); + expect(document.querySelector(".rail")!.hasAttribute("data-expanded")).toBe(false); + expect(document.body.textContent).toContain("menu-icon"); + } finally { + dispose(); + warn.mockRestore(); + cleanup(); + } + }); + + test.fails("gated (#5226): the server-rendered button is claimed and interactive", async () => { + const { warn, serverNodes, serverButton, dispose } = await hydrateDocument( + "menu-button-document-5226", + MenuButtonChain + ); + try { + // The same assertions — they fail today: the three client-only ids + // shift the client's keys past the server's (Hydration key miss / + // unclaimed server nodes warnings fire), the server-rendered chain + // stays inert, and the click does nothing. Flips when a fix lands. + expect(warn).not.toHaveBeenCalled(); + const button = document.querySelector("button")!; + expect(button).toBe(serverButton); + for (const node of serverNodes) expect(node.isConnected).toBe(true); + button.click(); + flush(); + expect(button.getAttribute("aria-checked")).toBe("true"); + } finally { + dispose(); + warn.mockRestore(); + cleanup(); + } + }); +}); diff --git a/packages/web/test/server/menu-button-5226.spec.tsx b/packages/web/test/server/menu-button-5226.spec.tsx new file mode 100644 index 000000000..8a4a4bec7 --- /dev/null +++ b/packages/web/test/server/menu-button-5226.spec.tsx @@ -0,0 +1,58 @@ +/** + * @jsxImportSource @solidjs/web + * + * Server half of the #5226 menu-button document pair. Renders the + * menu-button chain from test/harness/scenarios.tsx inside the document + * shell the vite plugin's `start` mode renders (a hydratable full + * document), once per focus-primitive allocation shape, and writes the + * artifacts test/hydration/menu-button-5226.spec.tsx replays with + * document.write() and hydrates at the document root. + * + * The two shapes differ by exactly the three allocations the gated shape + * skips on the server (the onSettled tracked effect and the two + * event-listener effects): the aligned shape's menu-button keys sit three + * slots past the gated one's in the enclosing id scope, and the client + * matches whichever shape it runs. + */ +import { describe, expect, test } from "vitest"; +import { + MenuButtonChain, + MenuButtonChainAligned, + MenuButtonDocument +} from "../harness/scenarios.jsx"; +import { recordStream, writeArtifact } from "./artifact-recorder.js"; + +function docTree(App: () => unknown) { + return () => ( + + + + ); +} + +async function recordDocument(name: string, App: () => unknown): Promise { + const { shell, rest } = await recordStream(docTree(App)); + // The document is not streamed in fragments: everything lands in the shell. + expect(rest).toBe(""); + expect(shell).toContain(" { + test("gated shape: the document carries the menu-button chain", async () => { + await recordDocument("menu-button-document-5226", MenuButtonChain); + }); + + test("aligned shape: the same chain with three more server ids before it", async () => { + const shell = await recordDocument("menu-button-document-aligned-5226", MenuButtonChainAligned); + const keys = [...shell.matchAll(/_hk=([^" >]+)/g)].map(m => m[1]); + // The chain's element structure is identical in both shapes; the keys + // differ because the aligned server consumed the gated shape's three + // skipped allocations before the menu button's scope. + expect(keys.length).toBeGreaterThanOrEqual(8); + expect(keys).toContain("0"); + }); +});