@rangojs/router 0.36.0 → 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.
- package/dist/bin/{chunk-THW7E5A2.js → chunk-A64EG6MI.js} +22 -19
- package/dist/bin/{client-urls-projection-DHUUOJZM.js → client-urls-projection-RLDSA3BL.js} +1 -1
- package/dist/bin/rango.js +1 -1
- package/dist/bin/{runtime-discovery-UECTPF6K.js → runtime-discovery-T7ZLA6E3.js} +2 -2
- package/dist/bin/{temp-rsc-server-QLNMTFEE.js → temp-rsc-server-FGGXPKVQ.js} +2 -2
- package/dist/types/browser/event-controller.d.ts +61 -0
- package/dist/types/browser/fetched-loader-handles.d.ts +76 -0
- package/dist/types/browser/navigation-store.d.ts +3 -2
- package/dist/types/browser/react/use-handle.d.ts +18 -5
- package/dist/types/browser/react/use-push-handle.d.ts +44 -0
- package/dist/types/browser/types.d.ts +44 -0
- package/dist/types/client.d.ts +1 -0
- package/dist/types/client.rsc.d.ts +1 -0
- package/dist/types/handle.d.ts +13 -5
- package/dist/types/handles/client-pushes.d.ts +51 -0
- package/dist/types/handles/deferred-resolution.d.ts +14 -0
- package/dist/types/handles/pushed-by.d.ts +36 -0
- package/dist/types/loader-store.d.ts +13 -0
- package/dist/types/rsc/prefetch-render-error.d.ts +2 -1
- package/dist/types/server/handle-store.d.ts +8 -0
- package/dist/types/testing/dom.entry.d.ts +1 -1
- package/dist/types/testing/flight.entry.d.ts +1 -1
- package/dist/types/testing/render-route.d.ts +76 -14
- package/dist/types/testing/serve-shell-request.d.ts +31 -0
- package/dist/vite/index.js +23 -20
- package/package.json +1 -1
- package/skills/breadcrumbs/SKILL.md +68 -6
- package/skills/caching/SKILL.md +4 -2
- package/skills/catalog.json +3 -3
- package/skills/client-urls/SKILL.md +13 -1
- package/skills/document-cache/SKILL.md +31 -1
- package/skills/hooks/SKILL.md +8 -4
- package/skills/hooks/data.md +10 -1
- package/skills/hooks/handle-and-actions.md +402 -26
- package/skills/hooks/navigation.md +4 -0
- package/skills/hooks/urls.md +3 -0
- package/skills/links/SKILL.md +5 -3
- package/skills/loader/SKILL.md +40 -1
- package/skills/migrate-nextjs/SKILL.md +5 -0
- package/skills/migrate-react-router/component-migration.md +4 -1
- package/skills/parallel/SKILL.md +8 -0
- package/skills/ppr/SKILL.md +1 -0
- package/skills/rango/SKILL.md +6 -3
- package/skills/testing/client-components.md +35 -32
- package/skills/testing/handles.md +58 -6
- package/skills/testing/serve-shell-request.md +33 -14
- package/skills/ux-architecture/SKILL.md +4 -0
- package/src/browser/event-controller.ts +311 -2
- package/src/browser/fetched-loader-handles.ts +269 -0
- package/src/browser/navigation-store.ts +261 -2
- package/src/browser/partial-update.ts +3 -2
- package/src/browser/react/use-handle.ts +74 -27
- package/src/browser/react/use-push-handle.ts +113 -0
- package/src/browser/rsc-router.tsx +11 -14
- package/src/browser/types.ts +48 -0
- package/src/cache/document-cache-policy.ts +6 -5
- package/src/client.rsc.tsx +1 -0
- package/src/client.tsx +31 -1
- package/src/handle.ts +13 -5
- package/src/handles/client-pushes.ts +120 -0
- package/src/handles/deferred-resolution.ts +41 -2
- package/src/handles/pushed-by.ts +130 -1
- package/src/loader-store.ts +26 -0
- package/src/rsc/loader-fetch.ts +64 -5
- package/src/rsc/prefetch-render-error.ts +2 -1
- package/src/rsc/request-stages.ts +7 -6
- package/src/rsc/rsc-rendering.ts +32 -14
- package/src/server/handle-store.ts +23 -0
- package/src/ssr/ssr-root.tsx +6 -0
- package/src/testing/dom.entry.ts +2 -0
- package/src/testing/flight.entry.ts +1 -0
- package/src/testing/render-route.tsx +319 -72
- package/src/testing/serve-shell-request.ts +62 -1
- package/src/use-loader.tsx +44 -4
|
@@ -7,6 +7,7 @@ import type {
|
|
|
7
7
|
UpdateSubscriber,
|
|
8
8
|
ResolvedSegment,
|
|
9
9
|
HandleData,
|
|
10
|
+
PageRead,
|
|
10
11
|
ShownEntry,
|
|
11
12
|
} from "./types.js";
|
|
12
13
|
import type { EventController } from "./event-controller.js";
|
|
@@ -57,6 +58,54 @@ type HistoryCacheEntry = [
|
|
|
57
58
|
boolean?,
|
|
58
59
|
];
|
|
59
60
|
|
|
61
|
+
/**
|
|
62
|
+
* The newest page read that landed on a page for one loader
|
|
63
|
+
* (NavigationStore.beginPageRead). `result` is the read's data, which every
|
|
64
|
+
* loader segment of the loader on the page shows. `base` is the data the
|
|
65
|
+
* server last sent for those segments, each distinct value once (a held
|
|
66
|
+
* layout copy beside a re-run route copy holds two). `previous` is the
|
|
67
|
+
* result of the read it replaced, or `result` when none did. A write of the
|
|
68
|
+
* page's segments swaps a loader segment that holds base, previous or any
|
|
69
|
+
* other read's result (readResults) for `result`: a commit that reconciled
|
|
70
|
+
* from the entry before several reads landed holds an older one of them.
|
|
71
|
+
* readResults holds objects only, so an older result that is a string or a
|
|
72
|
+
* number is known only while it is `previous`.
|
|
73
|
+
*/
|
|
74
|
+
interface PageReadRecord {
|
|
75
|
+
readonly base: readonly unknown[];
|
|
76
|
+
readonly result: unknown;
|
|
77
|
+
readonly previous: unknown;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A read sent from no cached entry: it has no page to land on. */
|
|
81
|
+
const NO_PAGE_READ: PageRead = {
|
|
82
|
+
historyKeys: () => [],
|
|
83
|
+
current: () => false,
|
|
84
|
+
land: () => false,
|
|
85
|
+
holds: () => false,
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const NO_PAGE_READ_LOADERS: ReadonlySet<string> = new Set();
|
|
89
|
+
|
|
90
|
+
const isObject = (value: unknown): value is object =>
|
|
91
|
+
typeof value === "object" && value !== null;
|
|
92
|
+
|
|
93
|
+
/** The distinct loader data of `loaderId`'s segments, in segment order. */
|
|
94
|
+
function loaderDataOf(
|
|
95
|
+
segments: readonly ResolvedSegment[],
|
|
96
|
+
loaderId: string,
|
|
97
|
+
): unknown[] {
|
|
98
|
+
const data: unknown[] = [];
|
|
99
|
+
for (const s of segments) {
|
|
100
|
+
if (s.type !== "loader" || s.loaderId !== loaderId) continue;
|
|
101
|
+
if (!data.includes(s.loaderData)) data.push(s.loaderData);
|
|
102
|
+
}
|
|
103
|
+
return data;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const sameData = (a: readonly unknown[], b: readonly unknown[]): boolean =>
|
|
107
|
+
a === b || (a.length === b.length && a.every((value, i) => value === b[i]));
|
|
108
|
+
|
|
60
109
|
/**
|
|
61
110
|
* Clone the handleData CONTAINERS (the handle-name map and each segment map) so
|
|
62
111
|
* a cache entry is decoupled from the live map that eventController mutates — it
|
|
@@ -84,8 +133,9 @@ export function cloneHandleData(handleData: HandleData): HandleData {
|
|
|
84
133
|
* Handle data to write into the history cache for the page on screen. During
|
|
85
134
|
* the hydration window getHandleState() is the document snapshot while late
|
|
86
135
|
* pushes sit queued in the controller (they are already in the cache entry,
|
|
87
|
-
* written by
|
|
88
|
-
* entry's own data is the
|
|
136
|
+
* written at arrival by fetched-loader-handles.ts applyLateHandles), so
|
|
137
|
+
* writing the snapshot back would drop them; the entry's own data is the
|
|
138
|
+
* live view then.
|
|
89
139
|
*/
|
|
90
140
|
export function liveHandleDataForCache(
|
|
91
141
|
eventController: Pick<
|
|
@@ -268,6 +318,130 @@ export function createNavigationStore(
|
|
|
268
318
|
// never overwrite a newer same-URL visit's state.
|
|
269
319
|
let navInstance = 0;
|
|
270
320
|
|
|
321
|
+
// The page reads that landed, by the page's segments array (the twin keys
|
|
322
|
+
// of a shallow navigation share it) and loader id (PageReadRecord). A
|
|
323
|
+
// write of the page's segments carries them over (carryPageReads).
|
|
324
|
+
const pageReads = new WeakMap<
|
|
325
|
+
ResolvedSegment[],
|
|
326
|
+
Map<string, PageReadRecord>
|
|
327
|
+
>();
|
|
328
|
+
|
|
329
|
+
// Every result a page read landed. The server never sends one, so a loader
|
|
330
|
+
// segment holding one was copied from an entry before a newer read landed.
|
|
331
|
+
// Weak, so a page that polls keeps no chain of old results.
|
|
332
|
+
const readResults = new WeakSet<object>();
|
|
333
|
+
|
|
334
|
+
// The page each entry's segments array shows. An array written under a key
|
|
335
|
+
// in place of another (an action, a refresh, a new visit of the URL) shows
|
|
336
|
+
// that array's page, and a shallow navigation shares the array under its
|
|
337
|
+
// new key, so a read in flight lands on every entry of the page it was
|
|
338
|
+
// sent from, written before or after it was sent (beginPageRead).
|
|
339
|
+
const pageOfSegments = new WeakMap<ResolvedSegment[], object>();
|
|
340
|
+
|
|
341
|
+
function pageOf(segments: ResolvedSegment[]): object {
|
|
342
|
+
let page = pageOfSegments.get(segments);
|
|
343
|
+
if (!page) pageOfSegments.set(segments, (page = {}));
|
|
344
|
+
return page;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function entryAt(historyKey: string): HistoryCacheEntry | undefined {
|
|
348
|
+
return historyCache.find(([key]) => key === historyKey);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* What the page holds for `loaderId` as the server sent it: the record's
|
|
353
|
+
* base once a read landed, else the loader segments' own data.
|
|
354
|
+
*/
|
|
355
|
+
function serverDataOf(
|
|
356
|
+
segments: ResolvedSegment[],
|
|
357
|
+
loaderId: string,
|
|
358
|
+
): readonly unknown[] {
|
|
359
|
+
return (
|
|
360
|
+
pageReads.get(segments)?.get(loaderId)?.base ??
|
|
361
|
+
loaderDataOf(segments, loaderId)
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** `value` is data `record`'s result stands in for (PageReadRecord). */
|
|
366
|
+
function replacedBy(record: PageReadRecord, value: unknown): boolean {
|
|
367
|
+
return (
|
|
368
|
+
value === record.previous ||
|
|
369
|
+
record.base.includes(value) ||
|
|
370
|
+
(isObject(value) && readResults.has(value))
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* The indexes of the loader segments of `segments` for `loaderId` that
|
|
376
|
+
* hold data `record` replaces. Undefined when one holds other data: the
|
|
377
|
+
* server sent it anew (the loader re-ran). By data, not by segment object,
|
|
378
|
+
* so a write that copies a segment keeps the read.
|
|
379
|
+
*/
|
|
380
|
+
function swapsFor(
|
|
381
|
+
segments: readonly ResolvedSegment[],
|
|
382
|
+
loaderId: string,
|
|
383
|
+
record: PageReadRecord,
|
|
384
|
+
): number[] | undefined {
|
|
385
|
+
const indexes: number[] = [];
|
|
386
|
+
for (let i = 0; i < segments.length; i++) {
|
|
387
|
+
const s = segments[i];
|
|
388
|
+
if (s.type !== "loader" || s.loaderId !== loaderId) continue;
|
|
389
|
+
if (s.loaderData === record.result) continue;
|
|
390
|
+
if (!replacedBy(record, s.loaderData)) return undefined;
|
|
391
|
+
indexes.push(i);
|
|
392
|
+
}
|
|
393
|
+
return indexes;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** Swap, in place, each segment at `indexes` for a copy carrying `result`. */
|
|
397
|
+
function swapIn(
|
|
398
|
+
segments: ResolvedSegment[],
|
|
399
|
+
indexes: readonly number[],
|
|
400
|
+
result: unknown,
|
|
401
|
+
): void {
|
|
402
|
+
for (const i of indexes) {
|
|
403
|
+
segments[i] = { ...segments[i], loaderData: result };
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** applyPageReads for one record: false, nothing swapped, on a miss. */
|
|
408
|
+
function applyPageRead(
|
|
409
|
+
segments: ResolvedSegment[],
|
|
410
|
+
loaderId: string,
|
|
411
|
+
record: PageReadRecord,
|
|
412
|
+
): boolean {
|
|
413
|
+
const indexes = swapsFor(segments, loaderId, record);
|
|
414
|
+
if (!indexes) return false;
|
|
415
|
+
swapIn(segments, indexes, record.result);
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** The records of `records` that still hold on `segments` (applyPageRead). */
|
|
420
|
+
function applyPageReads(
|
|
421
|
+
records: Map<string, PageReadRecord>,
|
|
422
|
+
segments: ResolvedSegment[],
|
|
423
|
+
): Map<string, PageReadRecord> {
|
|
424
|
+
const kept = new Map<string, PageReadRecord>();
|
|
425
|
+
for (const [loaderId, record] of records) {
|
|
426
|
+
if (applyPageRead(segments, loaderId, record)) kept.set(loaderId, record);
|
|
427
|
+
}
|
|
428
|
+
return kept;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** A write of `to` in place of `from` keeps the reads `from` showed. */
|
|
432
|
+
function carryPageReads(
|
|
433
|
+
from: ResolvedSegment[] | undefined,
|
|
434
|
+
to: ResolvedSegment[],
|
|
435
|
+
): void {
|
|
436
|
+
if (!from || from === to) return;
|
|
437
|
+
const records = pageReads.get(from);
|
|
438
|
+
if (!records) return;
|
|
439
|
+
const kept = applyPageReads(records, to);
|
|
440
|
+
if (kept.size === 0) return;
|
|
441
|
+
const existing = pageReads.get(to);
|
|
442
|
+
pageReads.set(to, existing ? new Map([...kept, ...existing]) : kept);
|
|
443
|
+
}
|
|
444
|
+
|
|
271
445
|
// Current history key (set on navigation, stored in history.state)
|
|
272
446
|
let currentHistoryKey = config?.initialHistoryKey || generateHistoryKey();
|
|
273
447
|
|
|
@@ -549,6 +723,83 @@ export function createNavigationStore(
|
|
|
549
723
|
return navInstance;
|
|
550
724
|
},
|
|
551
725
|
|
|
726
|
+
/**
|
|
727
|
+
* The read lands on each entry of the page it was sent from that holds
|
|
728
|
+
* the same server data for the loader (by identity): a commit that kept
|
|
729
|
+
* the loader's segment, a shallow navigation and leaving the page keep
|
|
730
|
+
* it; a new visit or a commit that re-ran the loader does not. A read
|
|
731
|
+
* that landed before it leaves it current: reads of one loader under two
|
|
732
|
+
* buckets each land, the last one's result winning.
|
|
733
|
+
*/
|
|
734
|
+
beginPageRead(loaderId: string): PageRead {
|
|
735
|
+
const sentFrom = entryAt(currentHistoryKey)?.[1];
|
|
736
|
+
if (!sentFrom) return NO_PAGE_READ;
|
|
737
|
+
const page = pageOf(sentFrom);
|
|
738
|
+
const base = serverDataOf(sentFrom, loaderId);
|
|
739
|
+
let landed: PageReadRecord | undefined;
|
|
740
|
+
const holdsBase = (segments: ResolvedSegment[]): boolean =>
|
|
741
|
+
pageOfSegments.get(segments) === page &&
|
|
742
|
+
sameData(serverDataOf(segments, loaderId), base);
|
|
743
|
+
const holdsLanded = (segments: ResolvedSegment[]): boolean =>
|
|
744
|
+
landed !== undefined &&
|
|
745
|
+
pageReads.get(segments)?.get(loaderId) === landed;
|
|
746
|
+
return {
|
|
747
|
+
historyKeys: () =>
|
|
748
|
+
historyCache
|
|
749
|
+
.filter(([, segments]) =>
|
|
750
|
+
landed ? holdsLanded(segments) : holdsBase(segments),
|
|
751
|
+
)
|
|
752
|
+
.map(([key]) => key),
|
|
753
|
+
current: () => historyCache.some(([, segments]) => holdsBase(segments)),
|
|
754
|
+
land(result: unknown): boolean {
|
|
755
|
+
const pages: ResolvedSegment[][] = [];
|
|
756
|
+
for (const [, segments] of historyCache) {
|
|
757
|
+
if (holdsBase(segments) && !pages.includes(segments)) {
|
|
758
|
+
pages.push(segments);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (pages.length === 0) return false;
|
|
762
|
+
// An earlier read's result gives way like the server's data: the
|
|
763
|
+
// last read to land is what the page shows.
|
|
764
|
+
const earlier = pageReads.get(pages[0])?.get(loaderId);
|
|
765
|
+
const record: PageReadRecord = {
|
|
766
|
+
base,
|
|
767
|
+
result,
|
|
768
|
+
previous: earlier ? earlier.result : result,
|
|
769
|
+
};
|
|
770
|
+
// Every loader segment of the loader takes the result, or none:
|
|
771
|
+
// the read's data and its values land together or not at all.
|
|
772
|
+
const swaps = pages.map((s) => swapsFor(s, loaderId, record));
|
|
773
|
+
if (swaps.includes(undefined)) return false;
|
|
774
|
+
pages.forEach((segments, i) => {
|
|
775
|
+
swapIn(segments, swaps[i]!, result);
|
|
776
|
+
let records = pageReads.get(segments);
|
|
777
|
+
if (!records) pageReads.set(segments, (records = new Map()));
|
|
778
|
+
records.set(loaderId, record);
|
|
779
|
+
});
|
|
780
|
+
if (isObject(result)) readResults.add(result);
|
|
781
|
+
landed = record;
|
|
782
|
+
return true;
|
|
783
|
+
},
|
|
784
|
+
holds: () => historyCache.some(([, segments]) => holdsLanded(segments)),
|
|
785
|
+
};
|
|
786
|
+
},
|
|
787
|
+
|
|
788
|
+
getPageReadLoaders(historyKey: string): ReadonlySet<string> {
|
|
789
|
+
const entry = entryAt(historyKey);
|
|
790
|
+
const records = entry && pageReads.get(entry[1]);
|
|
791
|
+
return records?.size ? new Set(records.keys()) : NO_PAGE_READ_LOADERS;
|
|
792
|
+
},
|
|
793
|
+
|
|
794
|
+
replaceEntrySegments(
|
|
795
|
+
segments: ResolvedSegment[],
|
|
796
|
+
next: readonly ResolvedSegment[],
|
|
797
|
+
): void {
|
|
798
|
+
segments.splice(0, segments.length, ...next);
|
|
799
|
+
const records = pageReads.get(segments);
|
|
800
|
+
if (records) pageReads.set(segments, applyPageReads(records, segments));
|
|
801
|
+
},
|
|
802
|
+
|
|
552
803
|
/**
|
|
553
804
|
* Store segments for a history entry
|
|
554
805
|
* Updates existing entry if key exists, otherwise adds new entry
|
|
@@ -577,6 +828,14 @@ export function createNavigationStore(
|
|
|
577
828
|
([key]) => key === historyKey,
|
|
578
829
|
);
|
|
579
830
|
if (existingIndex !== -1) {
|
|
831
|
+
// The write keeps the reads the entry showed (applyPageReads): a
|
|
832
|
+
// commit that reconciled from the entry before a read landed would
|
|
833
|
+
// otherwise write its older snapshot over the read's data.
|
|
834
|
+
const previous = historyCache[existingIndex][1];
|
|
835
|
+
carryPageReads(previous, segments);
|
|
836
|
+
if (!pageOfSegments.has(segments)) {
|
|
837
|
+
pageOfSegments.set(segments, pageOf(previous));
|
|
838
|
+
}
|
|
580
839
|
historyCache[existingIndex] = [
|
|
581
840
|
historyKey,
|
|
582
841
|
segments,
|
|
@@ -555,8 +555,9 @@ export function createPartialUpdater(
|
|
|
555
555
|
// the tree: the entry is rewritten in place, not re-cached.
|
|
556
556
|
// cacheSegmentsForHistory would advance the store's nav instance and
|
|
557
557
|
// disown the tree's handle stream, and would reset the entry's stale
|
|
558
|
-
// flag.
|
|
559
|
-
|
|
558
|
+
// flag. Through the store, which carries over a fetched read that
|
|
559
|
+
// landed while the answer rendered (NavigationStore.replaceEntrySegments).
|
|
560
|
+
store.replaceEntrySegments(live, reconciled.segments);
|
|
560
561
|
store.setSegmentIds(matched);
|
|
561
562
|
filled = true;
|
|
562
563
|
} catch (thrown) {
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
|
|
3
|
-
import { useContext,
|
|
3
|
+
import { useContext, useLayoutEffect, useRef, useState } from "react";
|
|
4
4
|
import type { Handle } from "../../handle.js";
|
|
5
5
|
import { collectHandleData } from "../../handle.js";
|
|
6
6
|
import type { HandleData } from "../types.js";
|
|
7
7
|
import { NavigationStoreContext } from "./context.js";
|
|
8
|
-
import {
|
|
8
|
+
import { samePushValue } from "../../handles/client-pushes.js";
|
|
9
9
|
import { useCommitted } from "./use-route-state.js";
|
|
10
10
|
import type { RouteStateSignal } from "../event-controller.js";
|
|
11
11
|
|
|
@@ -13,7 +13,8 @@ import type { RouteStateSignal } from "../event-controller.js";
|
|
|
13
13
|
* Hook to access collected handle data.
|
|
14
14
|
*
|
|
15
15
|
* Returns the collected value from all route segments that pushed to this handle.
|
|
16
|
-
* Re-renders when
|
|
16
|
+
* Re-renders when the collected value changes (navigation, actions); while
|
|
17
|
+
* its content is equal it keeps the reference it returned (useCommitAnchoredState).
|
|
17
18
|
*
|
|
18
19
|
* @param handle - The handle to read
|
|
19
20
|
* @param selector - Optional selector for performance (only re-render when selected value changes)
|
|
@@ -43,12 +44,16 @@ export function useHandle<T, A, S>(
|
|
|
43
44
|
|
|
44
45
|
// Until every boundary has hydrated the store returns the state the
|
|
45
46
|
// document's HTML was rendered with (EventController.lockHydration), so a
|
|
46
|
-
// reader hydrating late reads what SSR rendered (issue #1035).
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
// reader hydrating late reads what SSR rendered (issue #1035). In each
|
|
48
|
+
// segment the client's pushes (usePushHandle) follow the server's values
|
|
49
|
+
// (EventController.withClientHandles); collect then runs over both.
|
|
50
|
+
const collect = (
|
|
51
|
+
state = ctx?.eventController.getHandleState(),
|
|
52
|
+
): Rango.FlightSerialize<A> | S => {
|
|
49
53
|
const collected = collectHandleData(
|
|
50
54
|
handle,
|
|
51
|
-
state?.data ?? {},
|
|
55
|
+
ctx?.eventController.withClientHandles(state?.data ?? {}, handle.$$id) ??
|
|
56
|
+
{},
|
|
52
57
|
state?.segmentOrder ?? [],
|
|
53
58
|
) as Rango.FlightSerialize<A>;
|
|
54
59
|
return selectorRef.current ? selectorRef.current(collected) : collected;
|
|
@@ -56,13 +61,31 @@ export function useHandle<T, A, S>(
|
|
|
56
61
|
|
|
57
62
|
const [value, setValue] = useCommitAnchoredState(collect, true);
|
|
58
63
|
|
|
59
|
-
|
|
64
|
+
// A layout effect: a pusher publishes from its layout effect, and a reader
|
|
65
|
+
// mounted in the same commit reads it here or hears it, before the browser
|
|
66
|
+
// paints. From a passive effect it would read it after the first paint.
|
|
67
|
+
useLayoutEffect(() => {
|
|
60
68
|
if (!ctx) return;
|
|
69
|
+
const { eventController } = ctx;
|
|
61
70
|
const update = (signal?: RouteStateSignal): void =>
|
|
62
71
|
setValue(collect(), signal);
|
|
63
72
|
// A (possibly new) handle on an idle page reads the current state.
|
|
64
73
|
update();
|
|
65
|
-
|
|
74
|
+
const unsubscribe = eventController.subscribeToHandles(update);
|
|
75
|
+
// A client push is set at once. While a page is held it comes from the
|
|
76
|
+
// page on screen (the held page's components have not committed), so it
|
|
77
|
+
// merges with the server state shown there.
|
|
78
|
+
const unsubscribeClient = eventController.subscribeToClientHandles(
|
|
79
|
+
(handleId) => {
|
|
80
|
+
if (handleId !== undefined && handleId !== handle.$$id) return;
|
|
81
|
+
const held = eventController.getHeldHandleState();
|
|
82
|
+
setValue(collect(held), undefined, held !== undefined);
|
|
83
|
+
},
|
|
84
|
+
);
|
|
85
|
+
return () => {
|
|
86
|
+
unsubscribe();
|
|
87
|
+
unsubscribeClient();
|
|
88
|
+
};
|
|
66
89
|
}, [handle]);
|
|
67
90
|
|
|
68
91
|
return value;
|
|
@@ -86,14 +109,26 @@ export function useHandle<T, A, S>(
|
|
|
86
109
|
* useSegments reads can suspend, so it leaves it off and its path and
|
|
87
110
|
* location commit with their page.
|
|
88
111
|
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*
|
|
112
|
+
* `now`, from useHandle for a client push (usePushHandle) during a hold: set
|
|
113
|
+
* at once. The push comes from the page on screen and was merged with the
|
|
114
|
+
* server state shown there (EventController.getHeldHandleState); the release
|
|
115
|
+
* then sets the held page's state as before.
|
|
116
|
+
*
|
|
117
|
+
* A value equal to the last one sets nothing, so a reader renders only when
|
|
118
|
+
* its value moves and keeps its reference while the content is equal: a
|
|
119
|
+
* re-delivery (an action's revalidation, a refresh, a Back, a late push)
|
|
120
|
+
* decodes fresh objects, and an effect keyed on the value would run again.
|
|
121
|
+
* Equal is samePushValue's, the rule client pushes are compared with: arrays
|
|
122
|
+
* and plain objects by entries, React elements by type, key and props, dates
|
|
123
|
+
* by time, anything else (a promise, a URL, a function, a Map) by identity,
|
|
124
|
+
* and nothing past 32 levels. A value equal to what React committed keeps
|
|
125
|
+
* that reference, also when a different one waited in between. A release is
|
|
126
|
+
* compared with what React committed, as in useRouteState.
|
|
92
127
|
*/
|
|
93
128
|
export function useCommitAnchoredState<T>(
|
|
94
129
|
init: () => T,
|
|
95
130
|
waitForRelease?: boolean,
|
|
96
|
-
): [T, (value: T, signal?: RouteStateSignal) => void] {
|
|
131
|
+
): [T, (value: T, signal?: RouteStateSignal, now?: boolean) => void] {
|
|
97
132
|
// An app that enables the React Compiler compiles the router too; its memo
|
|
98
133
|
// cache gains nothing here and cost 107 B gzip in the router chunk.
|
|
99
134
|
"use no memo";
|
|
@@ -102,19 +137,31 @@ export function useCommitAnchoredState<T>(
|
|
|
102
137
|
last: value,
|
|
103
138
|
});
|
|
104
139
|
const committed = useCommitted(value);
|
|
105
|
-
const [set] = useState(
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
140
|
+
const [set] = useState(
|
|
141
|
+
() =>
|
|
142
|
+
(next: T, signal?: RouteStateSignal, now?: boolean): void => {
|
|
143
|
+
const r = ref.current;
|
|
144
|
+
if (signal) r.waiting = signal === "anchor";
|
|
145
|
+
if (!samePushValue(next, r.last)) {
|
|
146
|
+
// A value that moved while it waited and came back to what React
|
|
147
|
+
// committed keeps the committed reference.
|
|
148
|
+
r.last =
|
|
149
|
+
r.last !== committed.current &&
|
|
150
|
+
samePushValue(next, committed.current)
|
|
151
|
+
? committed.current
|
|
152
|
+
: next;
|
|
153
|
+
r.held = true;
|
|
154
|
+
} else if (signal === "release" && r.last !== committed.current) {
|
|
155
|
+
r.held = true;
|
|
156
|
+
}
|
|
157
|
+
if (
|
|
158
|
+
!r.held ||
|
|
159
|
+
(!now && r.waiting && (waitForRelease || signal !== "anchor"))
|
|
160
|
+
)
|
|
161
|
+
return;
|
|
162
|
+
r.held = false;
|
|
163
|
+
setValue(() => r.last);
|
|
164
|
+
},
|
|
165
|
+
);
|
|
119
166
|
return [value, set];
|
|
120
167
|
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useContext, useLayoutEffect, useState } from "react";
|
|
4
|
+
import type { Handle } from "../../handle.js";
|
|
5
|
+
import { OutletContext } from "../../outlet-context.js";
|
|
6
|
+
import type { ClientPushOwner } from "../../handles/client-pushes.js";
|
|
7
|
+
import { NavigationStoreContext } from "./context.js";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Push a handle's values from a client component: the client side of the
|
|
11
|
+
* server's `ctx.use(handle)`, for live data and live edits on the page (a
|
|
12
|
+
* value from `load()` or a fetch loader, a live count, a draft).
|
|
13
|
+
*
|
|
14
|
+
* The values belong to the segment the component renders in (its nearest
|
|
15
|
+
* route, layout or slot) and show after the server's values of that segment,
|
|
16
|
+
* in that position whatever arrives first; the handle's collect decides what
|
|
17
|
+
* wins (a later Meta title, a breadcrumb with the same href). Two components
|
|
18
|
+
* that push one handle in one segment show in tree order; one nested inside
|
|
19
|
+
* the other shows before it. They show with the render that pushed them: a
|
|
20
|
+
* render React discards or that suspends publishes nothing, and an unmount
|
|
21
|
+
* removes them.
|
|
22
|
+
*
|
|
23
|
+
* `push(value)` adds to the render in progress, so call it during render.
|
|
24
|
+
* Once that render commits, `push` throws: an effect, an event handler or a
|
|
25
|
+
* child that re-renders on its own calls `usePushHandle` itself, or passes
|
|
26
|
+
* the data down and pushes it in render.
|
|
27
|
+
*
|
|
28
|
+
* `push(promise)` works as on the server: the value takes its place when it
|
|
29
|
+
* is pushed, readers keep what they showed until it resolves, and one that
|
|
30
|
+
* rejects or resolves to null or undefined is dropped. A promise is the same
|
|
31
|
+
* value only as the same reference, so push a stable one (from a loader,
|
|
32
|
+
* `load()` kept in state, or `useMemo`); a newer render's push or an unmount
|
|
33
|
+
* drops a pending one's result.
|
|
34
|
+
*
|
|
35
|
+
* The values publish from a layout effect, which the server never runs: the
|
|
36
|
+
* SSR document and a PPR shell show the server's values alone. On the client
|
|
37
|
+
* they show in the commit of the render that pushed them, a navigation's
|
|
38
|
+
* included.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```tsx
|
|
42
|
+
* "use client";
|
|
43
|
+
* function ChatTitle() {
|
|
44
|
+
* const { data } = useFetchLoader(ChatLoader);
|
|
45
|
+
* const push = usePushHandle(Meta);
|
|
46
|
+
* if (data) push({ title: `${data.unread} unread` });
|
|
47
|
+
* return null;
|
|
48
|
+
* }
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
export function usePushHandle<T, A>(
|
|
52
|
+
handle: Handle<T, A>,
|
|
53
|
+
): (value: T | Promise<T | null | undefined>) => void {
|
|
54
|
+
// `pushed` must be new on every render: the React Compiler, which an app
|
|
55
|
+
// can apply to the router too, would keep one across renders.
|
|
56
|
+
"use no memo";
|
|
57
|
+
const controller = useContext(NavigationStoreContext)?.eventController;
|
|
58
|
+
// The nearest provider that names a segment: a clientUrls group's page and
|
|
59
|
+
// layouts render under OutletProviders with none (ClientUrlsRoot), inside
|
|
60
|
+
// the group route's segment.
|
|
61
|
+
let outlet = useContext(OutletContext);
|
|
62
|
+
while (outlet && !outlet.segment) outlet = outlet.parent ?? null;
|
|
63
|
+
const segmentId = outlet?.segment?.id;
|
|
64
|
+
const [owner] = useState((): ClientPushOwner & { warned?: boolean } => ({}));
|
|
65
|
+
// Renders this component again when another pusher of the handle joins
|
|
66
|
+
// its segment (EventController.setClientHandle keeps them in tree order).
|
|
67
|
+
const [generation, setGeneration] = useState(0);
|
|
68
|
+
const handleId = handle.$$id;
|
|
69
|
+
// This render's values; sealed once its commit published them.
|
|
70
|
+
const pushed: {
|
|
71
|
+
values: (T | Promise<T | null | undefined>)[];
|
|
72
|
+
sealed?: boolean;
|
|
73
|
+
} = {
|
|
74
|
+
values: [],
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// Removes the values when the component unmounts or moves to another
|
|
78
|
+
// handle or segment.
|
|
79
|
+
useLayoutEffect(() => {
|
|
80
|
+
if (!controller || segmentId === undefined) return;
|
|
81
|
+
return () =>
|
|
82
|
+
controller.setClientHandle(handleId, segmentId, owner, undefined);
|
|
83
|
+
}, [controller, handleId, segmentId]);
|
|
84
|
+
|
|
85
|
+
useLayoutEffect(() => {
|
|
86
|
+
pushed.sealed = true;
|
|
87
|
+
if (controller && segmentId !== undefined) {
|
|
88
|
+
owner.resync = () => setGeneration((n) => n + 1);
|
|
89
|
+
owner.generation = generation;
|
|
90
|
+
controller.setClientHandle(handleId, segmentId, owner, pushed.values);
|
|
91
|
+
} else if (
|
|
92
|
+
process.env.NODE_ENV !== "production" &&
|
|
93
|
+
pushed.values.length > 0 &&
|
|
94
|
+
!owner.warned
|
|
95
|
+
) {
|
|
96
|
+
owner.warned = true;
|
|
97
|
+
console.warn(
|
|
98
|
+
`[rango] usePushHandle(${handleId}): rendered outside a route segment (no router or no layout, route or slot above it), so its values belong to no segment and are not applied. Render the component inside a route, layout or slot.`,
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
return (value: T | Promise<T | null | undefined>): void => {
|
|
104
|
+
if (pushed.sealed) {
|
|
105
|
+
throw new Error(
|
|
106
|
+
process.env.NODE_ENV === "production"
|
|
107
|
+
? `[rango] usePushHandle(${handleId}): push() after its render committed`
|
|
108
|
+
: `[rango] usePushHandle(${handleId}): push() was called after the render that created it committed. Call push during the render of the component that called usePushHandle; an effect, an event handler or a child calls usePushHandle itself.`,
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
pushed.values.push(value);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from "./navigation-store.js";
|
|
11
11
|
import { createEventController } from "./event-controller.js";
|
|
12
12
|
import { resolveDeferredHandleValues } from "../handles/deferred-resolution.js";
|
|
13
|
+
import { applyLateHandles } from "./fetched-loader-handles.js";
|
|
13
14
|
import { validateRedirectOrigin } from "./validate-redirect-origin.js";
|
|
14
15
|
import { awaitDocumentRevealed } from "./document-revealed.js";
|
|
15
16
|
import { createNavigationClient } from "./navigation-client.js";
|
|
@@ -346,23 +347,19 @@ export async function initBrowserApp(
|
|
|
346
347
|
// deferred values here exactly like the nav lane's processHandles
|
|
347
348
|
// does before applying.
|
|
348
349
|
const lateData = await resolveDeferredHandleValues(rawLateData);
|
|
349
|
-
// Live store only while the document's page is on screen: a full
|
|
350
|
-
// replace with its `matched` would overwrite another page's handles.
|
|
351
|
-
const pageKeys = store.getPageHistoryKeys(initialHistoryKey);
|
|
352
|
-
const onScreen = pageKeys.includes(store.getHistoryKey());
|
|
353
350
|
bootLog("handles: late push", {
|
|
354
351
|
segments: Object.keys(lateData),
|
|
355
|
-
onScreen,
|
|
356
352
|
});
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
353
|
+
// Live store only while the document's page is on screen (a
|
|
354
|
+
// replace with its `matched` would overwrite another page's
|
|
355
|
+
// handles), merged with the reads that landed since the
|
|
356
|
+
// document, and the entry written from the result.
|
|
357
|
+
applyLateHandles(
|
|
358
|
+
{ store, eventController },
|
|
359
|
+
lateData,
|
|
360
|
+
initialPayload.metadata?.matched ?? [],
|
|
361
|
+
initialHistoryKey,
|
|
362
|
+
);
|
|
366
363
|
}
|
|
367
364
|
} catch (err) {
|
|
368
365
|
console.error("[rsc-router] Error consuming late handles:", err);
|