@rangojs/router 0.36.1 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/bin/{chunk-THW7E5A2.js → chunk-A64EG6MI.js} +22 -19
  2. package/dist/bin/{client-urls-projection-DHUUOJZM.js → client-urls-projection-RLDSA3BL.js} +1 -1
  3. package/dist/bin/rango.js +1 -1
  4. package/dist/bin/{runtime-discovery-OPRGB3DF.js → runtime-discovery-T7ZLA6E3.js} +2 -2
  5. package/dist/bin/{temp-rsc-server-FV4ERMAS.js → temp-rsc-server-FGGXPKVQ.js} +2 -2
  6. package/dist/types/browser/event-controller.d.ts +53 -2
  7. package/dist/types/browser/fetched-loader-handles.d.ts +57 -14
  8. package/dist/types/browser/navigation-store.d.ts +3 -2
  9. package/dist/types/browser/react/use-handle.d.ts +18 -5
  10. package/dist/types/browser/react/use-push-handle.d.ts +44 -0
  11. package/dist/types/browser/types.d.ts +44 -0
  12. package/dist/types/client.d.ts +1 -0
  13. package/dist/types/client.rsc.d.ts +1 -0
  14. package/dist/types/handle.d.ts +13 -5
  15. package/dist/types/handles/client-pushes.d.ts +51 -0
  16. package/dist/types/handles/deferred-resolution.d.ts +7 -0
  17. package/dist/types/handles/pushed-by.d.ts +11 -0
  18. package/dist/types/loader-store.d.ts +13 -0
  19. package/dist/types/rsc/prefetch-render-error.d.ts +2 -1
  20. package/dist/types/server/handle-store.d.ts +8 -0
  21. package/dist/types/testing/dom.entry.d.ts +1 -1
  22. package/dist/types/testing/render-route.d.ts +74 -14
  23. package/dist/vite/index.js +23 -20
  24. package/package.json +1 -1
  25. package/skills/breadcrumbs/SKILL.md +68 -6
  26. package/skills/caching/SKILL.md +4 -2
  27. package/skills/catalog.json +3 -3
  28. package/skills/client-urls/SKILL.md +13 -1
  29. package/skills/document-cache/SKILL.md +31 -1
  30. package/skills/hooks/SKILL.md +8 -4
  31. package/skills/hooks/data.md +10 -1
  32. package/skills/hooks/handle-and-actions.md +402 -26
  33. package/skills/hooks/navigation.md +4 -0
  34. package/skills/hooks/urls.md +3 -0
  35. package/skills/links/SKILL.md +5 -3
  36. package/skills/loader/SKILL.md +28 -9
  37. package/skills/migrate-nextjs/SKILL.md +5 -0
  38. package/skills/migrate-react-router/component-migration.md +4 -1
  39. package/skills/parallel/SKILL.md +8 -0
  40. package/skills/ppr/SKILL.md +1 -0
  41. package/skills/rango/SKILL.md +6 -3
  42. package/skills/testing/client-components.md +35 -32
  43. package/skills/testing/handles.md +58 -6
  44. package/skills/ux-architecture/SKILL.md +4 -0
  45. package/src/browser/event-controller.ts +265 -4
  46. package/src/browser/fetched-loader-handles.ts +227 -54
  47. package/src/browser/navigation-store.ts +261 -2
  48. package/src/browser/partial-update.ts +3 -2
  49. package/src/browser/react/use-handle.ts +74 -27
  50. package/src/browser/react/use-push-handle.ts +113 -0
  51. package/src/browser/rsc-router.tsx +11 -14
  52. package/src/browser/types.ts +48 -0
  53. package/src/cache/document-cache-policy.ts +6 -5
  54. package/src/client.rsc.tsx +1 -0
  55. package/src/client.tsx +31 -1
  56. package/src/handle.ts +13 -5
  57. package/src/handles/client-pushes.ts +120 -0
  58. package/src/handles/deferred-resolution.ts +12 -0
  59. package/src/handles/pushed-by.ts +55 -1
  60. package/src/loader-store.ts +26 -0
  61. package/src/rsc/loader-fetch.ts +17 -0
  62. package/src/rsc/prefetch-render-error.ts +2 -1
  63. package/src/rsc/request-stages.ts +7 -6
  64. package/src/rsc/rsc-rendering.ts +32 -14
  65. package/src/server/handle-store.ts +23 -0
  66. package/src/ssr/ssr-root.tsx +5 -0
  67. package/src/testing/dom.entry.ts +2 -0
  68. package/src/testing/render-route.tsx +317 -72
  69. package/src/use-loader.tsx +16 -5
@@ -915,6 +915,11 @@ Without the flag the push still applies, but a slow loader's title lands
915
915
  post-hydration instead of in the document — see `/loader` → "Writing Handles
916
916
  from Loaders" for the delivery race.
917
917
 
918
+ A title a client component changes after render (a draft, a live count,
919
+ what a Next.js app sets with `document.title` in an effect) is pushed from
920
+ that component with `usePushHandle(Meta)` — never in the SSR'd `<head>`; see
921
+ `/hooks` → "Where should a handle value come from?".
922
+
918
923
  Add `<Html.Meta />` in the Document component's `<head>`:
919
924
 
920
925
  ```typescript
@@ -154,7 +154,10 @@ const HomePage: Handler<"home"> = (ctx) => {
154
154
  RR's data-derived `meta({ data })` maps to the same push from the LOADER that
155
155
  owns the data — `ctx.use(Meta)({ title: data.name })` in the loader body, with
156
156
  `loader(Def, { ssr: "await" })` when the title must be in the SSR'd
157
- head. See `/loader` → "Writing Handles from Loaders". The loader flag is
157
+ head. See `/loader` → "Writing Handles from Loaders". A title the client
158
+ changes after render (a draft, a live count; what RR apps set with
159
+ `document.title` in an effect) is pushed from the component with
160
+ `usePushHandle(Meta)` (`/hooks` → "Where should a handle value come from?"). The loader flag is
158
161
  unrelated to RR7's `ssr: "await"` (SPA mode), which has no route-wide Rango
159
162
  equivalent: it makes the server settle that loader before the first flush.
160
163
 
@@ -114,6 +114,14 @@ Parallel slot handlers can call `ctx.use(Meta)` or `ctx.use(Breadcrumbs)` to
114
114
  push handle data. (Loader bodies can too — see `/loader` → "Writing Handles
115
115
  from Loaders" — which often replaces the UI-less `@meta` slot below.)
116
116
 
117
+ A client component the slot renders pushes into the same segment with
118
+ `usePushHandle` (`/hooks` → "usePushHandle()"), after the slot's server
119
+ values, an intercept's slot included. A client component the route's own
120
+ page renders pushes into the route's segment, which is collected before the
121
+ route's slots: a route's `@meta` slot title beats a title that page pushes.
122
+ Push a live title from a component the `@meta` slot renders, or move that
123
+ server title into the route's handler or loader.
124
+
117
125
  A slot's pushes are stored under the slot's own segment (`<parent>.@slot`),
118
126
  separate from the parent's pushes:
119
127
 
@@ -1073,6 +1073,7 @@ Four things follow, in this order of scope:
1073
1073
  | a handler's push, a pinned `ssr: "await"` loader's push (`push(promise)` and `.defer()` too) | yes (the shell has it) | hydrates with it |
1074
1074
  | a push by an `ssr: "await"` loader whose value holds a promise | no | gets it right after hydration |
1075
1075
  | a live-lane loader's push | no | gets it right after hydration |
1076
+ | a client component's `usePushHandle` value | no | gets it right after hydration |
1076
1077
 
1077
1078
  So a title an `ssr: "await"` loader pushes to `Meta`, promise or not, is in
1078
1079
  every HIT's `<head>`: a crawler and a link preview see it. It bakes with the
@@ -160,7 +160,10 @@ stated, greppable contract.
160
160
  is TTL/SWR expiry plus tag-based invalidation: tag via `cache({ tags })` /
161
161
  `cacheTag(...tags)`, then `updateTag(...tags)` (awaitable) or `revalidateTag(...tags)`
162
162
  (background). Built-in stores index by tag.
163
- - `useLoader` / `useHandle` / `useFetchLoader` are client-only.
163
+ - `useLoader` / `useHandle` / `usePushHandle` / `useFetchLoader` are client-only.
164
+ A `usePushHandle` value is never in SSR HTML or a `ppr` shell: a value the
165
+ first paint must show is pushed on the server (`/hooks` → "Where should a
166
+ handle value come from?").
164
167
  - Caches are correctness-first: persistent store keys are version-segmented per
165
168
  `createRouter()` by a hash of its built code (a deploy that does not change a
166
169
  router keeps its cache; one that does reads under new keys), the forward/back cache is mutation-aware, and
@@ -355,7 +358,7 @@ Grouped by concern — read when you need to…
355
358
 
356
359
  | Skill | Description |
357
360
  | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
358
- | `/hooks` | Client-side React hooks |
361
+ | `/hooks` | Client-side React hooks; the home of handles (writers, order, `useHandle`, `usePushHandle`, where a handle value comes from) |
359
362
  | `/theme` | Light/dark mode with FOUC prevention |
360
363
  | `/i18n` | Locale routing with `:locale?`, resolution chains, react-intl integration |
361
364
  | `/fonts` | Load web fonts with preload hints |
@@ -364,7 +367,7 @@ Grouped by concern — read when you need to…
364
367
  | `/tailwind` | Set up Tailwind CSS v4 with `?url` imports |
365
368
  | `/view-transitions` | React View Transitions on layouts, routes, and parallel slots |
366
369
  | `/defer-hydration` | Full body HTML in the PPR shell + hydration off the critical path (gated Suspense boundary, content-as-fallback) |
367
- | `/breadcrumbs` | Built-in Breadcrumbs handle for breadcrumb navigation |
370
+ | `/breadcrumbs` | Built-in Breadcrumbs handle for breadcrumb navigation, pushed from handlers, loaders or client components |
368
371
  | `/react-compiler` | Enable React Compiler (opt-in) via plugin-react's native `compiler` option; client-only scope |
369
372
 
370
373
  **Observability & production health**:
@@ -8,26 +8,26 @@
8
8
 
9
9
  ### Options — `RenderRouteOptions`
10
10
 
11
- | Field | Type | Meaning |
12
- | ----------------------- | ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
13
- | `request` | `Request \| string` | Initial location. Only the URL is read (client render — headers/method ignored). Defaults to the leaf spec's static prefix or `"/"`. |
14
- | `loaderData` | `Record<string, unknown>` | Loader data keyed by loader `$$id`. `useLoader(L)` reads `loaderData[L.$$id]`. |
15
- | `outletPending` | `boolean` | Seed `useOutlet().pending` through each synthetic segment's production `OutletProvider`. Defaults to `false`; this is context seeding, not a simulated navigation/Suspense/action lifecycle. |
16
- | `loaders` | `ReadonlyArray<readonly [LoaderDefinition<any>, unknown]>` | Seed by REFERENCE: `[loader, data]` pairs. Robust for real `createLoader()` handles whose `$$id` is empty in a bare test. Prefer over `loaderData`. |
17
- | `params` | `Record<string, string>` | Explicit params, merged over (and overriding) params extracted from the `request` URL. |
18
- | `locationState` | `ReadonlyArray<readonly [LocationStateDefinition<any, any>, unknown]>` | Seed `useLocationState(def)` by REFERENCE: `[def, value]` pairs; keys an unkeyed `def` (like `withLocationStateKey(def)`) and writes `value` to `history.state` under `def.__rsc_ls_key`. See [Location state](#location-state). |
19
- | `documentLocationState` | `ReadonlyArray<readonly [LocationStateDefinition<any, any>, unknown]>` | The location state the document response carried (a handler, middleware or no-JS form action set it, or a document redirect's cookie brought it), as `[def, value]` pairs. Merged at start-up after `locationState` and the `clearOnReload` pass. See [State a document carried](#state-a-document-carried). |
20
- | `handles` | `ReadonlyArray<readonly [Handle<any, any>, unknown[]]>` | Seed `useHandle(handle)` by REFERENCE: `[handle, pushedValues[]]`. Accumulated GLOBALLY (not segment-scoped). |
21
- | `lateHandles` | `ReadonlyArray<readonly [Handle<any, any>, unknown[]]>` | Handle values that arrive AFTER hydration, as a late loader push does: `[handle, valuesAfterTheUpdate[]]` replaces that handle's `handles` seed once the root has hydrated (or mounted). See [Hydration](#hydration). |
22
- | `handle` | `HandleDataSeed` | Advanced: raw wire format `{ [handleId]: { [segmentId]: pushedValues[] } }`. Prefer `handles`. Merged with it. |
23
- | `routeMap` | `Record<string, string>` | Name -> pattern map (informational; client `useReverse` takes its map as an argument, so this is not consumed). |
24
- | `basename` | `string` | `createRouter({ basename })` value. Wired into `NavigationProvider` so `useRouter().basename`, `<Link>` prefixing, `useMount`/`useHref` resolve against the mount. Normalized like `createRouter`. Defaults to root. |
25
- | `mount` | `string` | `include()` mount prefix. Wraps the segment chain in a `MountContext` so `useMount()` returns the prefix. Normalized like a path prefix. Defaults to `"/"`. |
26
- | `theme` | `ThemeConfig \| true` | Theme config (`createRouter({ theme })` shape) to wrap the tree in a `ThemeProvider`. Defaults to no provider. A component calling `useTheme()` REQUIRES one. |
27
- | `nonce` | `string` | CSP nonce to seed via `NonceContext`, so a component calling `useNonce()` (e.g. an analytics/GTM head script) sees it — mirroring SSR. Defaults to `undefined` (the browser default). |
28
- | `defaultPrefetch` | `PrefetchStrategy` | Router default for `<Link>` and eligible plain anchors. `data-prefetch="false"`/`"none"` opts out one anchor; ancestor `data-prefetch-scope="false"`/`"none"` hard-disables the subtree; `"true"` permits routed resource suffixes elsewhere. |
29
- | `hydrate` | `boolean` | Render the same tree to HTML first (`renderToString`, no `window`/`document`), then hydrate that HTML instead of mounting fresh. The result gains `serverHtml`, `recoverableErrors` and `shellError`. See [Hydration](#hydration). |
30
- | `rewrite` | `string` | The path middleware rewrote `request` to (`throw rewrite()`): the leaf is matched against it for params, while the location (`usePathname`, `useSearchParams`) stays `request`, as a rewritten document renders and hydrates. |
11
+ | Field | Type | Meaning |
12
+ | ----------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
13
+ | `request` | `Request \| string` | Initial location. Only the URL is read (client render — headers/method ignored). Defaults to the leaf spec's static prefix or `"/"`. |
14
+ | `loaderData` | `Record<string, unknown>` | Loader data keyed by loader `$$id`. `useLoader(L)` reads `loaderData[L.$$id]`. |
15
+ | `outletPending` | `boolean` | Seed `useOutlet().pending` through each synthetic segment's production `OutletProvider`. Defaults to `false`; this is context seeding, not a simulated navigation/Suspense/action lifecycle. |
16
+ | `loaders` | `ReadonlyArray<readonly [LoaderDefinition<any>, unknown]>` | Seed by REFERENCE: `[loader, data]` pairs. Robust for real `createLoader()` handles whose `$$id` is empty in a bare test. Prefer over `loaderData`. |
17
+ | `params` | `Record<string, string>` | Explicit params, merged over (and overriding) params extracted from the `request` URL. |
18
+ | `locationState` | `ReadonlyArray<readonly [LocationStateDefinition<any, any>, unknown]>` | Seed `useLocationState(def)` by REFERENCE: `[def, value]` pairs; keys an unkeyed `def` (like `withLocationStateKey(def)`) and writes `value` to `history.state` under `def.__rsc_ls_key`. See [Location state](#location-state). |
19
+ | `documentLocationState` | `ReadonlyArray<readonly [LocationStateDefinition<any, any>, unknown]>` | The location state the document response carried (a handler, middleware or no-JS form action set it, or a document redirect's cookie brought it), as `[def, value]` pairs. Merged at start-up after `locationState` and the `clearOnReload` pass. See [State a document carried](#state-a-document-carried). |
20
+ | `handles` | `ReadonlyArray<readonly [Handle<any, any>, unknown[], HandleSegment?]>` | Seed `useHandle(handle)` by REFERENCE: `[handle, pushedValues[], segment?]`, the server's values in one segment (a spec's index in `routes`, `[index, "@slot"]`, or the leaf route when omitted). Collected over every segment, so a layout reads them too. A component's `usePushHandle` values follow them in its own segment. See [`./handles.md`](./handles.md). |
21
+ | `lateHandles` | `ReadonlyArray<readonly [Handle<any, any>, unknown[], HandleSegment?]>` | Handle values that arrive AFTER hydration, as a late loader push does: `[handle, valuesAfterTheUpdate[]]` replaces that handle's `handles` seed once the root has hydrated (or mounted). See [Hydration](#hydration). |
22
+ | `handle` | `HandleDataSeed` | Advanced: raw wire format `{ [handleId]: { [segmentId]: pushedValues[] } }`. Prefer `handles`. Merged with it. |
23
+ | `routeMap` | `Record<string, string>` | Name -> pattern map (informational; client `useReverse` takes its map as an argument, so this is not consumed). |
24
+ | `basename` | `string` | `createRouter({ basename })` value. Wired into `NavigationProvider` so `useRouter().basename`, `<Link>` prefixing, `useMount`/`useHref` resolve against the mount. Normalized like `createRouter`. Defaults to root. |
25
+ | `mount` | `string` | `include()` mount prefix. Wraps the segment chain in a `MountContext` so `useMount()` returns the prefix. Normalized like a path prefix. Defaults to `"/"`. |
26
+ | `theme` | `ThemeConfig \| true` | Theme config (`createRouter({ theme })` shape) to wrap the tree in a `ThemeProvider`. Defaults to no provider. A component calling `useTheme()` REQUIRES one. |
27
+ | `nonce` | `string` | CSP nonce to seed via `NonceContext`, so a component calling `useNonce()` (e.g. an analytics/GTM head script) sees it — mirroring SSR. Defaults to `undefined` (the browser default). |
28
+ | `defaultPrefetch` | `PrefetchStrategy` | Router default for `<Link>` and eligible plain anchors. `data-prefetch="false"`/`"none"` opts out one anchor; ancestor `data-prefetch-scope="false"`/`"none"` hard-disables the subtree; `"true"` permits routed resource suffixes elsewhere. |
29
+ | `hydrate` | `boolean` | Render the same tree to HTML first (`renderToString`, no `window`/`document`), then hydrate that HTML instead of mounting fresh. The result gains `serverHtml`, `recoverableErrors` and `shellError`. See [Hydration](#hydration). |
30
+ | `rewrite` | `string` | The path middleware rewrote `request` to (`throw rewrite()`): the leaf is matched against it for params, while the location (`usePathname`, `useSearchParams`) stays `request`, as a rewritten document renders and hydrates. |
31
31
 
32
32
  `RenderRouteSpec = { path, Component, layout?, loaderIds?, name?, transition? }` — one node of the route definition. The array is the layout chain root-to-leaf; the LAST entry is the leaf route (its pattern is matched against `request` to extract params; layout patterns are informational). `loaderIds` attaches seeded loaders to THIS node's segment; `layout` on the leaf wraps it; `name` is informational. `transition` is the `transition()` config this node declares (`{}` for a bare `transition()`), attached to its segment exactly as the DSL does — see [Held navigation](#held-navigation).
33
33
 
@@ -67,7 +67,7 @@ type RenderRouteResult = RenderResult & {
67
67
  url: string,
68
68
  options?: {
69
69
  loaders?: ReadonlyArray<readonly [LoaderDefinition<any>, unknown]>;
70
- handles?: ReadonlyArray<readonly [Handle<any, any>, unknown[]]>;
70
+ handles?: ReadonlyArray<HandleSeed>; // [handle, values, segment?]
71
71
  state?: HistoryState;
72
72
  replace?: boolean;
73
73
  transition?: boolean;
@@ -77,10 +77,11 @@ type RenderRouteResult = RenderResult & {
77
77
  },
78
78
  ): Promise<void>;
79
79
  // re-render the current location, as router.refresh() does:
80
- // a spec's when gets kind "revalidate" (`to` is `from`); `loaders` is the
81
- // data the response carries
80
+ // a spec's when gets kind "revalidate" (`to` is `from`); `loaders` and
81
+ // `handles` are what the response carries
82
82
  refresh(options?: {
83
83
  loaders?: ReadonlyArray<readonly [LoaderDefinition<any>, unknown]>;
84
+ handles?: ReadonlyArray<HandleSeed>;
84
85
  }): Promise<void>;
85
86
  // keep `url` as a prefetch made now carries it (the seeds then, `loaders`
86
87
  // over them); a later navigate(url) without `loaders` commits that data
@@ -95,6 +96,7 @@ type RenderRouteResult = RenderResult & {
95
96
  // every history entry and prefetch is marked stale
96
97
  action(options?: {
97
98
  loaders?: ReadonlyArray<readonly [LoaderDefinition<any>, unknown]>;
99
+ handles?: ReadonlyArray<HandleSeed>;
98
100
  keepClientCache?: boolean;
99
101
  }): Promise<void>;
100
102
  // what a later useLoader().load() (or refreshGroup refresh) of each
@@ -231,14 +233,14 @@ it("lists no product twice while the next page loads", async () => {
231
233
  });
232
234
  ```
233
235
 
234
- | To bring state to a reader | Do |
235
- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
236
- | a push / replace, the component's own | click its `<Link state>` or the control that calls `router.push(url, { state })`, then `waitFor` |
237
- | a push / replace whose loader the test holds | `router.navigate(url, { state, replace?, loaders: [[Loader, pendingPromise]] })` on a `transition` spec |
238
- | back/forward onto the mounted entry or one a navigation wrote | `window.history.back()` inside `await act(async () => { ... })`: the entry's page is restored with its state and handle values, as production's history-cache restore is |
239
- | back/forward onto an entry the test wrote | `history.replaceState(entry, "")`, then `window.dispatchEvent(new Event("popstate"))` inside `act`: readers take the entry as history holds it (also how a `Def.write()` becomes visible) |
240
- | a reader that mounts while a navigation is pending | hold the navigation as in the row above, then mount the reader inside `await act(async () => { ... })`: it reads the entry on screen |
241
- | a server action's state, a redirect's, an intercept | e2e |
236
+ | To bring state to a reader | Do |
237
+ | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
238
+ | a push / replace, the component's own | click its `<Link state>` or the control that calls `router.push(url, { state })`, then `waitFor` |
239
+ | a push / replace whose loader the test holds | `router.navigate(url, { state, replace?, loaders: [[Loader, pendingPromise]] })` on a `transition` spec |
240
+ | back/forward onto the mounted entry or one a navigation wrote | `window.history.back()` inside `await act(async () => { ... })`: the entry's page is restored with its state, from the router's history cache (its segments' loader data, a `load()` refresh included, and its handle values), as production's restore is |
241
+ | back/forward onto an entry the test wrote | `history.replaceState(entry, "")`, then `window.dispatchEvent(new Event("popstate"))` inside `act`: readers take the entry as history holds it (also how a `Def.write()` becomes visible) |
242
+ | a reader that mounts while a navigation is pending | hold the navigation as in the row above, then mount the reader inside `await act(async () => { ... })`: it reads the entry on screen |
243
+ | a server action's state, a redirect's, an intercept | e2e |
242
244
 
243
245
  ### Definitions with `clearOnReload`
244
246
 
@@ -453,6 +455,7 @@ it("dims the held price while the next product streams", async () => {
453
455
  | `useNavigation().state`, `useLinkStatus().pending` | Modeled: navigate() starts the navigation as a click does. `loading` from the call, `idle` in the commit, held with it; `pending` true for the destination's links until that commit, held with it too; a `<Link>` click marks that link only. |
454
456
  | `useAction().state` | Stays `idle`: navigate() runs no action. e2e. |
455
457
  | `useHandle()` on a held navigation, `navigate(url, { handles, loaders })` | Modeled: `handles` arrive on the response's handle stream, so readers keep the page being left's values while React holds the page and take the new ones with its commit. |
458
+ | `usePushHandle()` on a held navigation, a `load()` meanwhile | Modeled: the page on screen re-renders with its new data and its client value at once, with that page's server values; the held page's pushers publish with its commit. |
456
459
  | `useNavigation().isStreaming` past the commit, `navigate(url, { streamUntil })` | Modeled: the stream opens a task after the call (`pendingUrl` clears) and ends when the promise settles or a newer navigation aborts it; settle it inside `await act(async () => ...)`. |
457
460
  | A navigation started while React holds a page (a newer click, a `transition: false` commit) | `await router.navigate(...)` shows its page, with or without `act()`. A `<Link>` click goes inside `await act(async () => { ... })`: `fireEvent`'s synchronous `act()` drops React's retry of the held page. |
458
461
  | A back/forward restored from the history cache (`pop`) | Modeled for the mounted entry and one a navigate() wrote: the page and its handle values come back, decided by `transition({ when })` as kind `"pop"`. A stale entry's revalidation and a restore that fetches: e2e. |
@@ -464,7 +467,7 @@ it("dims the held price while the next product streams", async () => {
464
467
 
465
468
  ## `load()` and refresh groups
466
469
 
467
- `useLoader().load()`, `useFetchLoader().load()` and a `useRefreshLoaders()` refresh reach renderRoute's loader endpoint, so a refresh button, a polling component, or a value one reader refreshes and another shows is unit-testable without a server or a `fetch` stub. The endpoint answers a GET for a loader with the last value the test gave it: the render-time `loaders`/`loaderData`, or `router.respondToLoads({ loaders })`, which only sets the answer (a `navigate()`, `prefetch()`, `action()` or `refresh()` seeds the page it commits, not the answer). A `load({ params })` is answered with a `loaderError`. The value is read when `load()` sends its request. A pending Promise holds the answer until it settles (`isLoading` stays `true`), and a rejected one arrives as the loader's error. The value reaches the component as given, never serialized.
470
+ `useLoader().load()`, `useFetchLoader().load()` and a `useRefreshLoaders()` refresh reach renderRoute's loader endpoint, so a refresh button, a polling component, or a value one reader refreshes and another shows is unit-testable without a server or a `fetch` stub. The endpoint answers a GET for a loader with the last value the test gave it: the render-time `loaders`/`loaderData`, or `router.respondToLoads({ loaders, handles })`, which only sets the answer (a `navigate()`, `prefetch()`, `action()` or `refresh()` seeds the page it commits, not the answer). Its `handles` are what the loader's body pushes on such a read, applied to the loader's segment as the browser applies a real read's. A `load({ params })` is answered with a `loaderError`. The value is read when `load()` sends its request. A pending Promise holds the answer until it settles (`isLoading` stays `true`), and a rejected one arrives as the loader's error. The value reaches the component as given, never serialized.
468
471
 
469
472
  The answer decodes through `@vitejs/plugin-rsc/browser`, which `rangoTestAliases()` (and `rangoTestConfig()`) alias to the testing kit's stub; remove any `vi.mock("@vitejs/plugin-rsc/browser")` you wrote for it.
470
473
 
@@ -1,8 +1,8 @@
1
- # Testing a handle — collectHandle, plus the loader read/write and client read paths
1
+ # Testing a handle — collectHandle, plus the loader read/write and the client read and push paths
2
2
 
3
3
  **Layer:** unit (node + DOM) · **Import:** `@rangojs/router/testing` (collectHandle), `@rangojs/router/testing/dom` (renderRoute) · **DSL it tests:** a handle e.g. Breadcrumbs/Meta (see `/handler-use`, `/breadcrumbs`)
4
4
 
5
- A handle's `collect`/accumulator (the `createHandle(collect)` argument that maps per-segment pushed values into one accumulated result) is otherwise unreachable — `createHandle` keeps it in a private registry keyed by `$$id`. These primitives test it from different angles: `collectHandle` runs the REAL registered collect on per-segment values you SEED; `runLoader` seeds the POST-collect accumulated value a loader READS (`ctx.get(handle)` after the barrier); `runLoaderResult(...).handlePushes` records what a loader WRITES (`ctx.use(SomeHandle)({...})`, in push order); `renderRoute` seeds the RAW pushed values for a client component reading `useHandle`. None of them run the real push -> accumulate -> barrier wiring (that stays e2e).
5
+ A handle's `collect`/accumulator (the `createHandle(collect)` argument that maps per-segment pushed values into one accumulated result) is otherwise unreachable — `createHandle` keeps it in a private registry keyed by `$$id`. These primitives test it from different angles: `collectHandle` runs the REAL registered collect on per-segment values you SEED; `runLoader` seeds the POST-collect accumulated value a loader READS (`ctx.get(handle)` after the barrier); `runLoaderResult(...).handlePushes` records what a loader WRITES (`ctx.use(SomeHandle)({...})`, in push order); `renderRoute` seeds the RAW pushed values for a client component reading `useHandle`, and runs the real client layer for a component that pushes with `usePushHandle`. None of them run the server's push -> accumulate -> barrier wiring (that stays e2e). Which writer a value should have: [hooks → "Where should a handle value come from?"](../hooks/handle-and-actions.md#where-should-a-handle-value-come-from).
6
6
 
7
7
  ## API
8
8
 
@@ -24,12 +24,24 @@ A handle's `collect`/accumulator (the `createHandle(collect)` argument that maps
24
24
 
25
25
  ### renderRoute option — `handles` — `src/testing/render-route.tsx`
26
26
 
27
- | Field | Type | Meaning |
28
- | --------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
- | `handles` | `ReadonlyArray<readonly [Handle, unknown[]]>` | Seeds the CLIENT read path for `useHandle(handle)` — the RAW **pushed values array** (`unknown[]`), the values a route's handlers would have pushed. Attached to the leaf route segment under the handle's `$$id`, so `useHandle` runs the handle's REAL collect on them. |
27
+ | Field | Type | Meaning |
28
+ | --------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
+ | `handles` | `ReadonlyArray<readonly [Handle, unknown[], HandleSegment?]>` | Seeds the CLIENT read path for `useHandle(handle)` — the RAW **pushed values array** (`unknown[]`), the values a segment's handlers would have pushed. Attached to the segment the third element names (a spec's index in `routes`, or `[index, "@slot"]` for a slot that spec declares), the leaf route when omitted, so `useHandle` runs the handle's REAL collect on them. |
30
30
 
31
31
  `lateHandles` takes the same pairs for values that arrive after hydration (a late loader push): each replaces that handle's `handles` seed once the root has hydrated or mounted. With `hydrate: true` it pins that a reader hydrates with the document's values; see [`./client-components.md`](./client-components.md), "Hydration".
32
32
 
33
+ A spec's `slots` (`{ "@side": Side }`, or `{ Component, intercept: true }` for an intercept's) renders each slot as a segment of its own where the spec's component places `<ParallelOutlet name>`.
34
+
35
+ The router handle `renderRoute` returns reaches the rest of the client handle path:
36
+
37
+ | Member | What it does |
38
+ | ----------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
39
+ | `router.handleData(handle)` | What `useHandle(handle)` collects over, per segment id: the server's values, then the client's (`usePushHandle`). |
40
+ | `router.segmentId(segment?)` | The segment id a `HandleSegment` names on the page on screen. |
41
+ | `router.pushLateHandles([[h, values, seg?]], { pushedBy? })` | A server push that arrives after the commit (a settled `push(promise)`, a streamed loader, a `ppr` live-lane push): replaces that segment's server values, through production's late handle channel. `pushedBy: Loader` replaces only that loader's values; a loader a `load()` refreshed since keeps the read's. |
42
+ | `router.navigate(url, { handles })`, `router.action({ handles })` | The destination's or the revalidation's server pushes, on the response's handle stream as in production. |
43
+ | `router.respondToLoads({ loaders, handles })` | What a later `load()` or group refresh answers, and the values the loader's body pushes on that read, applied to the loader's segment as the browser applies a real read's. |
44
+
33
45
  **Shape contrast:** `renderRoute` feeds the barrier INPUT (the pushes, `unknown[]`); `runLoader` feeds its OUTPUT (the single accumulated value, `unknown`).
34
46
 
35
47
  **Across navigation:** seeded `handles` are applied once at the initial render and PERSIST across `router.navigate()` within the same test (like `loaderData`) — unlike a real navigation, which re-runs handlers. A layout/page reading `useHandle` still resolves the seeded values after `navigate()`.
@@ -143,10 +155,50 @@ it("renders the seeded trail (seed the INPUT pushes, the collect runs)", async (
143
155
  });
144
156
  ```
145
157
 
158
+ ```tsx
159
+ // chat-title.test.tsx — a client component that pushes the title
160
+ // @vitest-environment happy-dom
161
+ import { it, expect, afterEach } from "vitest";
162
+ import { act, cleanup, fireEvent } from "@testing-library/react";
163
+ import { renderRoute } from "@rangojs/router/testing/dom";
164
+ import { Meta, useHandle, usePushHandle } from "@rangojs/router/client";
165
+ import { useState } from "react";
166
+
167
+ afterEach(cleanup);
168
+
169
+ function Chat() {
170
+ const [unread, setUnread] = useState(0);
171
+ const push = usePushHandle(Meta);
172
+ if (unread > 0) push({ title: `Chat (${unread})` });
173
+ const title = useHandle(Meta).findLast((d) => "title" in d);
174
+ return (
175
+ <button onClick={() => setUnread((n) => n + 1)}>
176
+ {String(title?.title)}
177
+ </button>
178
+ );
179
+ }
180
+
181
+ it("the client's title follows the server's in its segment and wins", async () => {
182
+ const { getByRole, router } = await renderRoute(
183
+ [{ path: "/chat", Component: Chat }],
184
+ { request: "/chat", handles: [[Meta, [{ title: "Chat" }]]] },
185
+ );
186
+ expect(getByRole("button").textContent).toBe("Chat");
187
+ await act(async () => fireEvent.click(getByRole("button")));
188
+ expect(getByRole("button").textContent).toBe("Chat (1)");
189
+ expect(router.handleData(Meta)[router.segmentId()]).toEqual([
190
+ { title: "Chat" },
191
+ { title: "Chat (1)" },
192
+ ]);
193
+ });
194
+ ```
195
+
146
196
  ## Caveats
147
197
 
148
198
  - `collectHandle` tests the pure collect/accumulator in ISOLATION (parent -> child segment order, empty arrays filtered to match production). It does NOT run the real push -> accumulate -> barrier wiring — that stays e2e.
149
- - renderRoute `handles` seeds the CLIENT read path with the RAW pushed values array (`unknown[]`), attached to the leaf segment. Handle data accumulates GLOBALLY (not segment-scoped like loaders), so a LAYOUT reading the same handle sees the seeded values too, not just the leaf route.
199
+ - renderRoute `handles` seeds the CLIENT read path with the RAW pushed values array (`unknown[]`), attached to one segment (the leaf route by default). A handle collects over every segment, so a LAYOUT reading the same handle sees the seeded values too, not just the leaf route.
200
+ - A `usePushHandle` value is published from the component's layout effect, so it shows after `renderRoute` resolves (it awaits the commit). It is never in `serverHtml` with `hydrate: true`: SSR runs no effects, and the value applies once the hydration window closes.
201
+ - A promise a component pushes (`usePushHandle(Meta)(titlePromise)`) shows once it settles: resolve it inside `await act(async () => ...)`. Until then readers show what they showed before; a rejection or a `null` result is dropped.
150
202
  - runLoader `handles` seeds the POST-collect ACCUMULATED value (singular `unknown`) a loader reads via `ctx.get(handle)` after `await ctx.rendered()`; pair with `{ rendered: true }`. Shape contrast: renderRoute feeds the barrier INPUT (pushes[]), runLoader feeds its OUTPUT (the accumulated value).
151
203
  - Loader WRITES are the other direction: `ctx.use(SomeHandle)({...})` records into `runLoaderResult(...).handlePushes` (push order; a `.defer()` resolver's value is recorded when the resolver runs). Nothing to seed — assert the envelope.
152
204
  - The renderRoute path is the CLIENT tree only: it does NOT catch server/client boundary remount bugs, real Flight serialization errors, or loader execution.
@@ -435,6 +435,10 @@ The rule: **prefetch broadly, and flag what is expensive.**
435
435
  - Push from the loader that has the data: `ctx.use(Meta)({ title })`,
436
436
  `ctx.use(Breadcrumbs)({ label, href })`. This is how a group, which has no
437
437
  handlers, sets them (`/breadcrumbs`, "Pushing from Loaders").
438
+ - Push from the component with `usePushHandle(Meta)` when the value comes
439
+ from what the client holds (a draft, a live count, a selection); it shows
440
+ after the loader's value in the same segment. Which writer to pick:
441
+ `/hooks` → "Where should a handle value come from?".
438
442
  - Read them in chrome with `useHandle(Breadcrumbs)`, in a layout that stays.
439
443
  - `loader(Def, { ssr: "await" })` puts its pushes in the document's HTML (a
440
444
  title for search engines, a real 404 from `notFound()`). The document waits