@real-router/svelte 0.18.5 → 0.19.1
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/dom-utils/direction-tracker.js +47 -6
- package/dist/dom-utils/link-utils.d.ts +15 -0
- package/dist/dom-utils/link-utils.js +15 -0
- package/dist/dom-utils/route-announcer.js +55 -10
- package/dist/dom-utils/scroll-restore.d.ts +9 -31
- package/dist/dom-utils/scroll-restore.js +30 -149
- package/package.json +5 -5
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { events } from "@real-router/core";
|
|
2
|
+
import { getPluginApi } from "@real-router/core/api";
|
|
1
3
|
const NOOP_INSTANCE = Object.freeze({
|
|
2
4
|
destroy: () => {
|
|
3
5
|
/* no-op */
|
|
@@ -30,8 +32,27 @@ export function createDirectionTracker(router) {
|
|
|
30
32
|
}
|
|
31
33
|
let popstateFlag = false;
|
|
32
34
|
document.documentElement.dataset.navDirection = "forward";
|
|
35
|
+
let transitionInFlight = false;
|
|
36
|
+
let armedMidTransition = false;
|
|
37
|
+
// ⚑ The flag is SPENT by the transition it belongs to, whether or not that
|
|
38
|
+
// transition reaches a leave phase (#1924). It is armed by any `popstate` on
|
|
39
|
+
// `globalThis`, not only one the router consumes, so `history.back()` onto an
|
|
40
|
+
// entry that resolves to the current state — core answers `SAME_STATES`, and
|
|
41
|
+
// measured, that arc emits `TRANSITION_ERROR` with no `TRANSITION_START` and
|
|
42
|
+
// no leave — would otherwise leave it armed indefinitely and publish the next
|
|
43
|
+
// FORWARD navigation as "back".
|
|
44
|
+
//
|
|
45
|
+
// ⚠ A clock has no correct value to be set to. The leave phase is separated
|
|
46
|
+
// from its popstate by every deactivation guard, and a guard may await
|
|
47
|
+
// anything; the plugin also DEFERS a popstate that arrives during an
|
|
48
|
+
// in-flight transition and replays it from that transition's `finally`. The
|
|
49
|
+
// gap has no upper bound. Measured on the obvious choice: a task-boundary
|
|
50
|
+
// expiry disarms a live navigation on ONE async `canDeactivate`.
|
|
33
51
|
const onPopstate = () => {
|
|
34
52
|
popstateFlag = true;
|
|
53
|
+
// A deferred event belongs to the replay, not to the transition running
|
|
54
|
+
// now, so that transition's terminal event must not spend it.
|
|
55
|
+
armedMidTransition = transitionInFlight;
|
|
35
56
|
};
|
|
36
57
|
// IMPORTANT — listener-ordering: `popstate` fires on `window`, which
|
|
37
58
|
// has no DOM descendants, so capture phase is moot. Listeners are
|
|
@@ -41,15 +62,35 @@ export function createDirectionTracker(router) {
|
|
|
41
62
|
// the plugin's handler runs first and synchronously fires
|
|
42
63
|
// `subscribeLeave` while `popstateFlag` is still `false`.
|
|
43
64
|
globalThis.addEventListener("popstate", onPopstate);
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
65
|
+
const api = getPluginApi(router);
|
|
66
|
+
const onSettled = () => {
|
|
67
|
+
transitionInFlight = false;
|
|
68
|
+
if (armedMidTransition) {
|
|
69
|
+
armedMidTransition = false;
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
48
72
|
popstateFlag = false;
|
|
49
|
-
}
|
|
73
|
+
};
|
|
74
|
+
const unsubs = [
|
|
75
|
+
api.addEventListener(events.TRANSITION_START, () => {
|
|
76
|
+
transitionInFlight = true;
|
|
77
|
+
}),
|
|
78
|
+
api.addEventListener(events.TRANSITION_SUCCESS, onSettled),
|
|
79
|
+
api.addEventListener(events.TRANSITION_ERROR, onSettled),
|
|
80
|
+
api.addEventListener(events.TRANSITION_CANCEL, onSettled),
|
|
81
|
+
router.subscribeLeave(() => {
|
|
82
|
+
document.documentElement.dataset.navDirection = popstateFlag
|
|
83
|
+
? "back"
|
|
84
|
+
: "forward";
|
|
85
|
+
popstateFlag = false;
|
|
86
|
+
armedMidTransition = false;
|
|
87
|
+
}),
|
|
88
|
+
];
|
|
50
89
|
return {
|
|
51
90
|
destroy: () => {
|
|
52
|
-
|
|
91
|
+
for (const unsub of unsubs) {
|
|
92
|
+
unsub();
|
|
93
|
+
}
|
|
53
94
|
globalThis.removeEventListener("popstate", onPopstate);
|
|
54
95
|
delete document.documentElement.dataset.navDirection;
|
|
55
96
|
},
|
|
@@ -87,6 +87,21 @@ export declare function anchorTargetsAnotherContext(element: Element | null | un
|
|
|
87
87
|
* (#1442). Previous 3-arg call sites continue to work unchanged.
|
|
88
88
|
*/
|
|
89
89
|
export declare function buildHref(router: Router, routeName: string, routeParams: Params, routeSearch?: SearchParams, hash?: string): string | undefined;
|
|
90
|
+
/**
|
|
91
|
+
* `<Link>` click-handler navigation helper (#532).
|
|
92
|
+
*
|
|
93
|
+
* Wraps `router.navigate(name, params, search, opts)` — the query channel took
|
|
94
|
+
* slot 3 in RFC-4 M2 (#1548) — with same-route different-hash
|
|
95
|
+
* detection: when the consumer clicks a hash-bearing Link that targets the
|
|
96
|
+
* current route with the same params but a different fragment, core's
|
|
97
|
+
* SAME_STATES check would otherwise reject the navigation. The helper adds
|
|
98
|
+
* `force: true` and `hashChange: true` automatically — subscribers can then
|
|
99
|
+
* disambiguate via `state.context.url.hashChanged`.
|
|
100
|
+
*
|
|
101
|
+
* For pure programmatic same-route hash-only navigation, callers are
|
|
102
|
+
* documented to pass `{ force: true }` themselves; the auto-bypass here is
|
|
103
|
+
* a UX convenience for `<Link hash>` that all 6 framework adapters share.
|
|
104
|
+
*/
|
|
90
105
|
export declare function navigateWithHash(router: Router, routeName: string, routeParams: Params, routeSearch: SearchParams | undefined, hash: string | undefined, extraOptions?: NavigationOptions): Promise<State>;
|
|
91
106
|
export declare function buildActiveClassName(isActive: boolean, activeClassName: string | undefined, baseClassName: string | undefined): string | undefined;
|
|
92
107
|
/**
|
|
@@ -177,6 +177,21 @@ export function buildHref(router, routeName, routeParams, routeSearch, hash) {
|
|
|
177
177
|
return undefined;
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
|
+
/**
|
|
181
|
+
* `<Link>` click-handler navigation helper (#532).
|
|
182
|
+
*
|
|
183
|
+
* Wraps `router.navigate(name, params, search, opts)` — the query channel took
|
|
184
|
+
* slot 3 in RFC-4 M2 (#1548) — with same-route different-hash
|
|
185
|
+
* detection: when the consumer clicks a hash-bearing Link that targets the
|
|
186
|
+
* current route with the same params but a different fragment, core's
|
|
187
|
+
* SAME_STATES check would otherwise reject the navigation. The helper adds
|
|
188
|
+
* `force: true` and `hashChange: true` automatically — subscribers can then
|
|
189
|
+
* disambiguate via `state.context.url.hashChanged`.
|
|
190
|
+
*
|
|
191
|
+
* For pure programmatic same-route hash-only navigation, callers are
|
|
192
|
+
* documented to pass `{ force: true }` themselves; the auto-bypass here is
|
|
193
|
+
* a UX convenience for `<Link hash>` that all 6 framework adapters share.
|
|
194
|
+
*/
|
|
180
195
|
export function navigateWithHash(router, routeName, routeParams, routeSearch, hash, extraOptions) {
|
|
181
196
|
const opts = { ...extraOptions };
|
|
182
197
|
if (hash !== undefined) {
|
|
@@ -15,14 +15,31 @@ const NOOP_INSTANCE = Object.freeze({
|
|
|
15
15
|
// destroy() would detach the shared node while sibling providers (micro-
|
|
16
16
|
// frontends — the same multi-provider scenario `scroll-restore`'s `storageKey`
|
|
17
17
|
// exists for) keep writing to the now-orphaned node → silent screen reader (#783).
|
|
18
|
-
|
|
18
|
+
// ⚑ The ref-count and the generation live ON THE ELEMENT (#1924). The element
|
|
19
|
+
// is found with `document.querySelector`, so it is document-scoped, while a
|
|
20
|
+
// module variable is bundle-scoped — and a page carrying a second adapter
|
|
21
|
+
// bundle, the micro-frontend case the ref-count exists for, shares the element
|
|
22
|
+
// and not the scope.
|
|
23
|
+
//
|
|
24
|
+
// ⚠ Module-scoped counters reach #783 verbatim through that seam: the second
|
|
25
|
+
// bundle takes the `existing` branch, reads its own generation, passes the
|
|
26
|
+
// #1217 ownership guard, decrements its own count to zero and removes the live
|
|
27
|
+
// element.
|
|
28
|
+
const REFS_ATTR = "data-rr-announcer-refs";
|
|
29
|
+
const GENERATION_ATTR = "data-rr-announcer-generation";
|
|
30
|
+
function readCount(element) {
|
|
31
|
+
// `Number(null)` is 0, so an absent attribute needs no fallback term.
|
|
32
|
+
return Number(element.getAttribute(REFS_ATTR));
|
|
33
|
+
}
|
|
34
|
+
function writeCount(element, value) {
|
|
35
|
+
element.setAttribute(REFS_ATTR, String(value));
|
|
36
|
+
}
|
|
19
37
|
// Generation token (#1217): bumped each time a FRESH shared element is created.
|
|
20
38
|
// Each instance captures the generation live at construction; on destroy it
|
|
21
39
|
// touches the shared refcount / element ONLY if its generation is still current.
|
|
22
40
|
// A stale instance — whose element a host wiped without calling destroy() — must
|
|
23
41
|
// not decrement the new generation's refcount (→ negative) or remove its live
|
|
24
42
|
// element (a selector-based removeAnnouncer takes whoever is in the DOM).
|
|
25
|
-
let announcerGeneration = 0;
|
|
26
43
|
export function createRouteAnnouncer(router, options) {
|
|
27
44
|
// Defensive SSR / non-browser guard: in SSR (Node.js) or non-DOM
|
|
28
45
|
// environments, `document` is undefined and the announcer cannot
|
|
@@ -45,7 +62,7 @@ export function createRouteAnnouncer(router, options) {
|
|
|
45
62
|
let pendingText = null;
|
|
46
63
|
let clearTimeoutId;
|
|
47
64
|
const { element: announcer, generation: myGeneration } = getOrCreateAnnouncer();
|
|
48
|
-
|
|
65
|
+
writeCount(announcer, readCount(announcer) + 1);
|
|
49
66
|
const doAnnounce = (text, h1) => {
|
|
50
67
|
lastAnnouncedText = text;
|
|
51
68
|
clearTimeout(clearTimeoutId);
|
|
@@ -114,23 +131,44 @@ export function createRouteAnnouncer(router, options) {
|
|
|
114
131
|
// under us, the next getOrCreateAnnouncer bumped the generation for the
|
|
115
132
|
// fresh element. A stale instance must NOT decrement the new generation's
|
|
116
133
|
// refcount (→ negative) or remove its live element — bail if not current.
|
|
117
|
-
|
|
134
|
+
// ⚠ Against the DOCUMENT's generation, never the captured element's: the
|
|
135
|
+
// element a stale instance holds was removed, and its own attribute
|
|
136
|
+
// still reads its own generation, so comparing the two can only ever be
|
|
137
|
+
// equal and the guard would be dead.
|
|
138
|
+
if (myGeneration !== currentGeneration()) {
|
|
118
139
|
return;
|
|
119
140
|
}
|
|
120
|
-
|
|
141
|
+
const remaining = readCount(announcer) - 1;
|
|
142
|
+
writeCount(announcer, remaining);
|
|
121
143
|
// Only the last holder tears down the shared element — via our captured
|
|
122
144
|
// ref, not a selector query (which would delete whoever's element is
|
|
123
145
|
// currently in the DOM, i.e. a newer generation's).
|
|
124
|
-
if (
|
|
146
|
+
if (remaining === 0) {
|
|
125
147
|
removeAnnouncer(announcer);
|
|
126
148
|
}
|
|
127
149
|
},
|
|
128
150
|
};
|
|
129
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* The next generation, derived from the document rather than a module counter:
|
|
154
|
+
* a wiped element leaves no node to read, so the value is kept on `<html>`.
|
|
155
|
+
*/
|
|
156
|
+
function currentGeneration() {
|
|
157
|
+
return Number(document.documentElement.getAttribute(GENERATION_ATTR));
|
|
158
|
+
}
|
|
159
|
+
function nextGeneration() {
|
|
160
|
+
const root = document.documentElement;
|
|
161
|
+
const next = currentGeneration() + 1;
|
|
162
|
+
root.setAttribute(GENERATION_ATTR, String(next));
|
|
163
|
+
return next;
|
|
164
|
+
}
|
|
130
165
|
function getOrCreateAnnouncer() {
|
|
131
166
|
const existing = document.querySelector(`[${ANNOUNCER_ATTR}]`);
|
|
132
167
|
if (existing) {
|
|
133
|
-
return {
|
|
168
|
+
return {
|
|
169
|
+
element: existing,
|
|
170
|
+
generation: Number(existing.getAttribute(GENERATION_ATTR)),
|
|
171
|
+
};
|
|
134
172
|
}
|
|
135
173
|
// Creating a FRESH element means no live instance is validly sharing one, so
|
|
136
174
|
// the ref-count restarts from zero (the caller increments immediately after).
|
|
@@ -140,13 +178,17 @@ function getOrCreateAnnouncer() {
|
|
|
140
178
|
// count that prevents the new element from ever being torn down (#783).
|
|
141
179
|
// The generation bump (#1217) lets the wiped element's instances recognize
|
|
142
180
|
// themselves as stale so their destroy() does not touch this fresh element.
|
|
143
|
-
announcerRefCount = 0;
|
|
144
|
-
announcerGeneration += 1;
|
|
145
181
|
const element = document.createElement("div");
|
|
146
182
|
element.setAttribute("style", VISUALLY_HIDDEN);
|
|
147
183
|
element.setAttribute("aria-live", "assertive");
|
|
148
184
|
element.setAttribute("aria-atomic", "true");
|
|
149
185
|
element.setAttribute(ANNOUNCER_ATTR, "");
|
|
186
|
+
// A fresh element restarts the count at zero (the caller increments straight
|
|
187
|
+
// after) and takes the next generation, so instances holding the element a
|
|
188
|
+
// host wiped recognise themselves as stale. Both live on the node, so every
|
|
189
|
+
// bundle reads the same values.
|
|
190
|
+
writeCount(element, 0);
|
|
191
|
+
element.setAttribute(GENERATION_ATTR, String(nextGeneration()));
|
|
150
192
|
// Defensive SSR / pre-`<body>` guard: in some environments (early
|
|
151
193
|
// injection, deferred-body documents, certain SSR rehydration paths)
|
|
152
194
|
// `document.body` can be null when the announcer is constructed.
|
|
@@ -160,7 +202,10 @@ function getOrCreateAnnouncer() {
|
|
|
160
202
|
// runtime can return null per spec. The `as` cast narrows the type to
|
|
161
203
|
// include null so the `??` short-circuit is type-safe.
|
|
162
204
|
(document.body ?? document.documentElement).prepend(element);
|
|
163
|
-
return {
|
|
205
|
+
return {
|
|
206
|
+
element,
|
|
207
|
+
generation: Number(element.getAttribute(GENERATION_ATTR)),
|
|
208
|
+
};
|
|
164
209
|
}
|
|
165
210
|
function removeAnnouncer(element) {
|
|
166
211
|
element.remove();
|
|
@@ -29,40 +29,18 @@ export interface ScrollRestorationOptions {
|
|
|
29
29
|
export declare function createScrollRestoration(router: Router, options?: ScrollRestorationOptions): {
|
|
30
30
|
destroy: () => void;
|
|
31
31
|
};
|
|
32
|
-
export declare function keyOf(state: State): string;
|
|
33
32
|
/**
|
|
34
|
-
*
|
|
33
|
+
* Internal cache-key builder for scroll-position storage.
|
|
35
34
|
*
|
|
36
35
|
* **Exported for testing only — not part of the public API** (intentionally
|
|
37
|
-
* excluded from `index.ts` barrel). Adapter property tests import it
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
* ## Divergence from `@real-router/sources/canonicalJson` — by design
|
|
42
|
-
*
|
|
43
|
-
* Two independent implementations live in the monorepo:
|
|
36
|
+
* excluded from `index.ts` barrel). Adapter property tests import it rather
|
|
37
|
+
* than replicating it (§8b H20 / audit-2026-05-16 #S3): a replica drifts
|
|
38
|
+
* silently the moment the key changes. A change to the key format loses saved
|
|
39
|
+
* positions across an upgrade, so the test set is the contract.
|
|
44
40
|
*
|
|
45
|
-
*
|
|
46
|
-
* cache key builder. Uses `localeCompare` and a plain-object accumulator;
|
|
47
|
-
* tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s
|
|
48
|
-
* replacer happens to sort them; relies on `JSON.stringify`'s native cycle
|
|
49
|
-
* detector. Designed to be cheap on the navigation hot path. The
|
|
50
|
-
* surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,
|
|
51
|
-
* cyclic) and skips the offending capture/restore.
|
|
41
|
+
* ## Not memoized
|
|
52
42
|
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
* `Object.create(null)` accumulator to prevent prototype pollution, and a
|
|
56
|
-
* bespoke path-based cycle detector (the native one cannot see the cloned
|
|
57
|
-
* graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls
|
|
58
|
-
* back to a non-cached source.
|
|
59
|
-
*
|
|
60
|
-
* **They are intentionally NOT interchangeable.** Aligning them would either
|
|
61
|
-
* regress scroll-restore performance (byte-order + recursive clone is heavier
|
|
62
|
-
* per call) or weaken the sources cache (locale dependence breaks
|
|
63
|
-
* deterministic cache keys across machines). No cross-package equivalence
|
|
64
|
-
* test exists or should be added; the relationship is "different invariants,
|
|
65
|
-
* different costs, different consumers." Audit-2 / audit-2026-05-17 §2
|
|
66
|
-
* documents the choice.
|
|
43
|
+
* The key is a string property read, which is cheaper than the `WeakMap`
|
|
44
|
+
* lookup any cache would need — so there is nothing here to cache.
|
|
67
45
|
*/
|
|
68
|
-
export declare function
|
|
46
|
+
export declare function keyOf(state: State): string;
|
|
@@ -1,19 +1,5 @@
|
|
|
1
1
|
/** Captured like the deciding seven, but this one BUILDS the guarantee (#2072). */
|
|
2
2
|
const objectCreate = Object.create;
|
|
3
|
-
/**
|
|
4
|
-
* Intrinsics captured at module load (#1971).
|
|
5
|
-
*
|
|
6
|
-
* ⚑ These DECIDE — they answer "what is on this object" for a value this module
|
|
7
|
-
* did not build. Read off the live global they can be re-pointed after boot, and
|
|
8
|
-
* `shared/` is the half where that fails OPEN: measured in `browser-env`, a
|
|
9
|
-
* re-pointed `getPrototypeOf` admits a `Date` into `state.params` and a
|
|
10
|
-
* re-pointed `keys` skips option validation entirely.
|
|
11
|
-
*
|
|
12
|
-
* ⚠ Capture narrows the window from "any time after boot" to "before this module
|
|
13
|
-
* loads". It does not close it — a shim evaluated ahead of core still wins
|
|
14
|
-
* (#1798), which is the doctrine's own caveat and travels with it.
|
|
15
|
-
*/
|
|
16
|
-
const objectKeys = Object.keys;
|
|
17
3
|
const DEFAULT_STORAGE_KEY = "real-router:scroll";
|
|
18
4
|
// Bounded retry budget for resolving a late-mounting scroll container on the
|
|
19
5
|
// restore path. A per-route container (e.g. an `overflow:auto` div rendered
|
|
@@ -150,14 +136,23 @@ export function createScrollRestoration(router, options) {
|
|
|
150
136
|
// smooth restores animate asynchronously, so they run the full budget. The
|
|
151
137
|
// frame budget is the hard backstop against an unreachable target (saved
|
|
152
138
|
// position taller than the restored content).
|
|
139
|
+
let restoreToken = 0;
|
|
153
140
|
const restorePos = (top) => {
|
|
154
141
|
if (!getContainer) {
|
|
155
142
|
globalThis.scrollTo({ top, left: 0, behavior });
|
|
156
143
|
return;
|
|
157
144
|
}
|
|
158
145
|
let frames = 0;
|
|
146
|
+
// ⚑ A per-restore token, the idea `view-transitions.ts` carries as
|
|
147
|
+
// `scheduledVT` (#781) and this file already carries as `scrollSettled` on
|
|
148
|
+
// the capture side (#782). Without it the budget is gated by `destroyed`
|
|
149
|
+
// alone, so a loop whose target is unreachable — a container that clamps
|
|
150
|
+
// short and keeps retrying — is still running when the next navigation
|
|
151
|
+
// lands, and writes the PREVIOUS route's offset onto the current page the
|
|
152
|
+
// moment that container's layout grows (#1924).
|
|
153
|
+
const token = (restoreToken += 1);
|
|
159
154
|
const attempt = () => {
|
|
160
|
-
if (destroyed) {
|
|
155
|
+
if (destroyed || token !== restoreToken) {
|
|
161
156
|
return;
|
|
162
157
|
}
|
|
163
158
|
const element = getContainer();
|
|
@@ -223,7 +218,6 @@ export function createScrollRestoration(router, options) {
|
|
|
223
218
|
writePos(0);
|
|
224
219
|
};
|
|
225
220
|
let destroyed = false;
|
|
226
|
-
let unserializableWarned = false;
|
|
227
221
|
// Capture/effect seam guard (#782). previousRoute's position is captured
|
|
228
222
|
// synchronously in `subscribe`, but the snap/restore effect runs a frame
|
|
229
223
|
// later in rAF. Across that window the viewport still shows the route BEFORE
|
|
@@ -233,26 +227,6 @@ export function createScrollRestoration(router, options) {
|
|
|
233
227
|
// value survives the transit). A real user scroll in this <16ms window is
|
|
234
228
|
// physically impossible.
|
|
235
229
|
let scrollSettled = true;
|
|
236
|
-
// `keyOf` defers to `canonicalJson` which calls `JSON.stringify`. Two
|
|
237
|
-
// realistic inputs blow up the serializer and would otherwise crash the
|
|
238
|
-
// subscribe callback (taking scroll-restore offline for the whole session):
|
|
239
|
-
// - `BigInt` params → `TypeError: Do not know how to serialize a BigInt`
|
|
240
|
-
// - cyclic params (reactive proxies, DOM-ref back-pointers) → stack
|
|
241
|
-
// overflow.
|
|
242
|
-
// The defensive wrapper drops capture/restore for that specific navigation
|
|
243
|
-
// and warns once per provider — the rest of the cache stays usable.
|
|
244
|
-
const safeKeyOf = (state) => {
|
|
245
|
-
try {
|
|
246
|
-
return keyOf(state);
|
|
247
|
-
}
|
|
248
|
-
catch {
|
|
249
|
-
if (!unserializableWarned) {
|
|
250
|
-
unserializableWarned = true;
|
|
251
|
-
console.error(`[real-router] scroll-restore: route "${state.name}" has params that cannot be canonicalized (e.g. BigInt or cyclic structure). Scroll position will not be captured or restored for this route.`);
|
|
252
|
-
}
|
|
253
|
-
return null;
|
|
254
|
-
}
|
|
255
|
-
};
|
|
256
230
|
const unsubscribe = router.subscribe(({ route, previousRoute }) => {
|
|
257
231
|
const nav = route.context
|
|
258
232
|
.navigation;
|
|
@@ -262,10 +236,7 @@ export function createScrollRestoration(router, options) {
|
|
|
262
236
|
// skipped while the scroll is unsettled — a second navigation in the same
|
|
263
237
|
// frame, before the prior nav's rAF snap (see `scrollSettled`, #782).
|
|
264
238
|
if (previousRoute && scrollSettled) {
|
|
265
|
-
|
|
266
|
-
if (prevKey !== null) {
|
|
267
|
-
putPos(prevKey, readPos());
|
|
268
|
-
}
|
|
239
|
+
putPos(keyOf(previousRoute), readPos());
|
|
269
240
|
}
|
|
270
241
|
// This navigation's scroll effect is now pending: the viewport position no
|
|
271
242
|
// longer belongs to `route` until the rAF below runs and settles it.
|
|
@@ -303,13 +274,11 @@ export function createScrollRestoration(router, options) {
|
|
|
303
274
|
// arm, which is the pre-#1976 answer for a state carrying no meta.
|
|
304
275
|
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
|
|
305
276
|
if (route.transition?.reload || nav?.navigationType === "reload") {
|
|
306
|
-
|
|
307
|
-
restorePos(key === null ? 0 : (loadStore()[key] ?? 0));
|
|
277
|
+
restorePos(loadStore()[keyOf(route)] ?? 0);
|
|
308
278
|
return;
|
|
309
279
|
}
|
|
310
280
|
if (nav?.direction === "back" || nav?.navigationType === "traverse") {
|
|
311
|
-
|
|
312
|
-
restorePos(key === null ? 0 : (loadStore()[key] ?? 0));
|
|
281
|
+
restorePos(loadStore()[keyOf(route)] ?? 0);
|
|
313
282
|
return;
|
|
314
283
|
}
|
|
315
284
|
// Genuine in-place replace (not a traversal) — leave scroll untouched.
|
|
@@ -324,10 +293,7 @@ export function createScrollRestoration(router, options) {
|
|
|
324
293
|
const onPageHide = () => {
|
|
325
294
|
const current = router.getState();
|
|
326
295
|
if (current) {
|
|
327
|
-
|
|
328
|
-
if (key !== null) {
|
|
329
|
-
putPos(key, readPos());
|
|
330
|
-
}
|
|
296
|
+
putPos(keyOf(current), readPos());
|
|
331
297
|
}
|
|
332
298
|
};
|
|
333
299
|
globalThis.addEventListener("pagehide", onPageHide);
|
|
@@ -355,109 +321,24 @@ export function createScrollRestoration(router, options) {
|
|
|
355
321
|
* Internal cache-key builder for scroll-position storage.
|
|
356
322
|
*
|
|
357
323
|
* **Exported for testing only — not part of the public API** (intentionally
|
|
358
|
-
* excluded from `index.ts` barrel). Adapter property tests import it
|
|
359
|
-
*
|
|
360
|
-
*
|
|
361
|
-
*
|
|
362
|
-
* the test set is the contract.
|
|
363
|
-
*
|
|
364
|
-
* ## Identity-based memoization (audit-2026-05-17 §8b #2)
|
|
324
|
+
* excluded from `index.ts` barrel). Adapter property tests import it rather
|
|
325
|
+
* than replicating it (§8b H20 / audit-2026-05-16 #S3): a replica drifts
|
|
326
|
+
* silently the moment the key changes. A change to the key format loses saved
|
|
327
|
+
* positions across an upgrade, so the test set is the contract.
|
|
365
328
|
*
|
|
366
|
-
*
|
|
367
|
-
* `name` / `params` are immutable for the lifetime of the snapshot, and
|
|
368
|
-
* any change produces a new `State` reference. A `WeakMap<State, string>`
|
|
369
|
-
* therefore safely caches the canonicalised key by identity — repeat
|
|
370
|
-
* `keyOf(state)` calls on the same snapshot (typical on
|
|
371
|
-
* back/forward/traverse where the same prior `State` is re-emitted)
|
|
372
|
-
* skip the recursive `canonicalJson` pass entirely.
|
|
329
|
+
* ## Not memoized
|
|
373
330
|
*
|
|
374
|
-
* The
|
|
375
|
-
*
|
|
331
|
+
* The key is a string property read, which is cheaper than the `WeakMap`
|
|
332
|
+
* lookup any cache would need — so there is nothing here to cache.
|
|
376
333
|
*/
|
|
377
|
-
const KEY_CACHE = new WeakMap();
|
|
378
334
|
export function keyOf(state) {
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
//
|
|
384
|
-
//
|
|
385
|
-
//
|
|
386
|
-
//
|
|
387
|
-
|
|
388
|
-
KEY_CACHE.set(state, key);
|
|
389
|
-
return key;
|
|
390
|
-
}
|
|
391
|
-
/**
|
|
392
|
-
* Stable JSON serializer with sorted object keys.
|
|
393
|
-
*
|
|
394
|
-
* **Exported for testing only — not part of the public API** (intentionally
|
|
395
|
-
* excluded from `index.ts` barrel). Adapter property tests import it via
|
|
396
|
-
* the direct path to lock the key-order-insensitive property
|
|
397
|
-
* (`canonicalJson({a:1,b:2}) === canonicalJson({b:2,a:1})`).
|
|
398
|
-
*
|
|
399
|
-
* ## Divergence from `@real-router/sources/canonicalJson` — by design
|
|
400
|
-
*
|
|
401
|
-
* Two independent implementations live in the monorepo:
|
|
402
|
-
*
|
|
403
|
-
* - **`shared/dom-utils/scroll-restore.canonicalJson`** (this file) — scroll
|
|
404
|
-
* cache key builder. Uses `localeCompare` and a plain-object accumulator;
|
|
405
|
-
* tolerates `__proto__`-keyed inputs only insofar as `JSON.stringify`'s
|
|
406
|
-
* replacer happens to sort them; relies on `JSON.stringify`'s native cycle
|
|
407
|
-
* detector. Designed to be cheap on the navigation hot path. The
|
|
408
|
-
* surrounding [[safeKeyOf]] wrapper catches the two crash inputs (`BigInt`,
|
|
409
|
-
* cyclic) and skips the offending capture/restore.
|
|
410
|
-
*
|
|
411
|
-
* - **`@real-router/sources/canonicalJson`** — sources cache key builder.
|
|
412
|
-
* Uses byte-order compare (`< / >`) for locale-independence, a
|
|
413
|
-
* `Object.create(null)` accumulator to prevent prototype pollution, and a
|
|
414
|
-
* bespoke path-based cycle detector (the native one cannot see the cloned
|
|
415
|
-
* graph). Throws eagerly on `Map`/`Set`/`RegExp`/cycles — the caller falls
|
|
416
|
-
* back to a non-cached source.
|
|
417
|
-
*
|
|
418
|
-
* **They are intentionally NOT interchangeable.** Aligning them would either
|
|
419
|
-
* regress scroll-restore performance (byte-order + recursive clone is heavier
|
|
420
|
-
* per call) or weaken the sources cache (locale dependence breaks
|
|
421
|
-
* deterministic cache keys across machines). No cross-package equivalence
|
|
422
|
-
* test exists or should be added; the relationship is "different invariants,
|
|
423
|
-
* different costs, different consumers." Audit-2 / audit-2026-05-17 §2
|
|
424
|
-
* documents the choice.
|
|
425
|
-
*/
|
|
426
|
-
export function canonicalJson(value) {
|
|
427
|
-
return JSON.stringify(value, canonicalReplacer);
|
|
428
|
-
}
|
|
429
|
-
function canonicalReplacer(_key, val) {
|
|
430
|
-
// audit-2026-05-17 §5 MEDIUM (Sprint A.3) — function/Symbol marker.
|
|
431
|
-
// `JSON.stringify` silently drops function and symbol values from
|
|
432
|
-
// object output. Two routes that differ ONLY in a function/Symbol
|
|
433
|
-
// value would canonicalize to the same string → silent scroll-cache
|
|
434
|
-
// key collision (positions clobber each other). Replacing the value
|
|
435
|
-
// with a sentinel string breaks the collision while keeping the
|
|
436
|
-
// canonical form deterministic. The sentinels are intentionally
|
|
437
|
-
// ASCII-only and lexically distinct from valid JSON-stringified
|
|
438
|
-
// values; consumers will see `"<fn>"` / `"<sym>"` if they ever
|
|
439
|
-
// round-trip the cache key, signalling the substitution clearly.
|
|
440
|
-
if (typeof val === "function") {
|
|
441
|
-
return "<fn>";
|
|
442
|
-
}
|
|
443
|
-
if (typeof val === "symbol") {
|
|
444
|
-
return "<sym>";
|
|
445
|
-
}
|
|
446
|
-
if (val !== null && typeof val === "object" && !Array.isArray(val)) {
|
|
447
|
-
// Null-prototype accumulator: a plain `{}` would interpret
|
|
448
|
-
// `sorted["__proto__"] = x` as a prototype assignment (silently dropped
|
|
449
|
-
// from JSON.stringify output AND a prototype-pollution vector). Mirrors
|
|
450
|
-
// the same guard in `@real-router/sources/canonicalJson`. The two
|
|
451
|
-
// implementations are still intentionally divergent (see the doc-block
|
|
452
|
-
// on [[canonicalJson]] above), but prototype-safety is non-negotiable
|
|
453
|
-
// on both. Lock-test: scrollRestoreKey.properties.ts Invariant 11.
|
|
454
|
-
const sorted = objectCreate(null);
|
|
455
|
-
// eslint-disable-next-line unicorn/no-array-sort -- ng-packagr uses pre-ES2023 lib; toSorted unavailable
|
|
456
|
-
const keys = objectKeys(val).sort((left, right) => left.localeCompare(right));
|
|
457
|
-
for (const key of keys) {
|
|
458
|
-
sorted[key] = val[key];
|
|
459
|
-
}
|
|
460
|
-
return sorted;
|
|
461
|
-
}
|
|
462
|
-
return val;
|
|
335
|
+
// The key is the LOCATION, and `state.path` is the form core prints it in
|
|
336
|
+
// (#1923). Deriving it from the bags instead makes this a SECOND place that
|
|
337
|
+
// has to know how a value prints — and the two domains disagree there: the
|
|
338
|
+
// URL direction parses `?page=2` into the number `2`, an intent keeps `"2"`,
|
|
339
|
+
// and `packages/core/src/helpers.ts` says comparison is the single place that
|
|
340
|
+
// knows they describe one location. Reading the printed form asks core rather
|
|
341
|
+
// than re-deriving it, so a route's query, its `?id` carve-out twin and the
|
|
342
|
+
// order its params were written in are all already settled here.
|
|
343
|
+
return state.path;
|
|
463
344
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@real-router/svelte",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.19.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Svelte 5 integration for Real-Router",
|
|
6
6
|
"svelte": "./dist/index.js",
|
|
@@ -48,14 +48,14 @@
|
|
|
48
48
|
"license": "MIT",
|
|
49
49
|
"sideEffects": false,
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@real-router/core": "^0.
|
|
51
|
+
"@real-router/core": "^0.131.0",
|
|
52
52
|
"@real-router/route-utils": "^0.4.0",
|
|
53
|
-
"@real-router/sources": "^0.14.
|
|
53
|
+
"@real-router/sources": "^0.14.38"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
|
-
"@real-router/browser-plugin": "^0.22.
|
|
56
|
+
"@real-router/browser-plugin": "^0.22.18",
|
|
57
57
|
"@sveltejs/package": "2.5.8",
|
|
58
|
-
"@sveltejs/vite-plugin-svelte": "
|
|
58
|
+
"@sveltejs/vite-plugin-svelte": "7.3.0",
|
|
59
59
|
"@testing-library/jest-dom": "~6.9.1",
|
|
60
60
|
"@testing-library/svelte": "~5.4.2",
|
|
61
61
|
"@testing-library/user-event": "~14.6.1",
|