@real-router/svelte 0.24.5 → 0.24.6

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/README.md CHANGED
@@ -481,7 +481,7 @@ Opt-in preservation of scroll position across navigations:
481
481
  </RouterProvider>
482
482
  ```
483
483
 
484
- Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"native"`. Custom containers via `scrollContainer: () => HTMLElement | null`. Lifecycle tied to the provider — created on mount, destroyed on unmount. Under `@real-router/browser-plugin`, replace transitions now preserve scroll position and programmatic reloads restore from `sessionStorage` (portable via `state.transition.replace` / `state.transition.reload`). See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for the full behaviour matrix.
484
+ Restores scroll on back/forward, scrolls to top (or `#hash`) on push. Three modes: `"restore"` (default), `"top"`, `"native"`. Custom containers via `scrollContainer: () => HTMLElement | null`. Lifecycle tied to the provider — created on mount, destroyed on unmount. Under `@real-router/browser-plugin`, replace transitions now preserve scroll position and programmatic reloads restore from `sessionStorage` (portable via `state.transition.replace` / `state.transition.reload`). In `"restore"` mode under `@real-router/hash-plugin`, Back and Forward leave the scroll where it is: the plugin publishes no step through history. See [Scroll Restoration guide](https://github.com/greydragon888/real-router/wiki/Scroll-Restoration) for the full behaviour matrix.
485
485
 
486
486
  ## Scroll Spy
487
487
 
@@ -1,10 +1,11 @@
1
1
  /** Captured like the deciding seven, but this one BUILDS the guarantee (#2072). */
2
2
  const objectCreate = Object.create;
3
3
  const DEFAULT_STORAGE_KEY = "real-router:scroll";
4
- // Bounded retry budget for resolving a late-mounting scroll container on the
5
- // restore path. A per-route container (e.g. an `overflow:auto` div rendered
6
- // only on one route) can be committed to the DOM a few frames after the
7
- // navigation settles — heavier routes paint later than the subscribe's rAF.
4
+ // Bounded retry budget on the restore path. The restored route — a per-route
5
+ // container (e.g. an `overflow:auto` div rendered only on one route), or the
6
+ // content that makes the document tall enough — can be committed to the DOM a
7
+ // few frames after the navigation settles: heavier routes paint later than
8
+ // the subscribe's rAF.
8
9
  // ~10 frames (≈160ms at 60fps) comfortably covers a React commit of a large
9
10
  // route without being perceptible. See the doc-block on `restorePos`.
10
11
  const RESTORE_RETRY_FRAMES = 10;
@@ -108,65 +109,63 @@ export function createScrollRestoration(router, options) {
108
109
  globalThis.scrollTo({ top, left: 0, behavior });
109
110
  }
110
111
  };
111
- // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a
112
- // scroll container that both MOUNTS and LAYS OUT a few frames AFTER the
113
- // navigation settles.
112
+ // ⚑ A restore loop stops once a later commit has taken a new token: without
113
+ // it a loop whose target is unreachable writes the previous route's offset
114
+ // onto the current page the moment that page's layout grows (#1924).
114
115
  //
115
- // The capture-side `readPos` always runs against an already-mounted DOM (the
116
- // route being left). On restore the target route — and its container — is
117
- // still being committed by the view layer. The subscribe callback schedules a
118
- // single rAF; for a heavy route (e.g. a long virtual list) the framework's
119
- // commit can land AFTER that frame. Two distinct failures follow, each losing
120
- // the saved position (Scenario 6 e2e, reproduced under CI's slower runner):
116
+ // Every commit takes one except a replace on the same route that neither
117
+ // steps through history nor reloads — a scroll-spy hash update, a query
118
+ // synced into the URL — which leaves the restore running. It is taken at the
119
+ // commit rather than in the frame, so a second commit in the same frame
120
+ // retires a restore before its first write.
121
+ // `view-transitions.ts` carries the same idea as `scheduledVT` (#781).
122
+ let restoreToken = 0;
123
+ // Restore path (back / traverse / reload). Unlike `writePos`, this tolerates a
124
+ // target route that MOUNTS and LAYS OUT a few frames AFTER the navigation
125
+ // settles: the view layer can commit it after the subscribe's frame. Two
126
+ // failures follow, each losing the saved position:
121
127
  //
122
128
  // 1. Container not mounted yet → `getContainer()` is `null`, the scroll
123
129
  // silently falls back to `window`, which on a container-only route has
124
130
  // nothing to scroll.
125
- // 2. Container mounted but its content not laid out yet → `scrollHeight`
126
- // is still small, so a single `scrollTo({ top })` clamps short of the
127
- // saved position and never re-applies once layout grows.
131
+ // 2. Content not laid out yet, in the container or in the document → a
132
+ // single `scrollTo({ top })` clamps short of the saved position and
133
+ // never re-applies once layout grows.
128
134
  //
129
- // With no `scrollContainer` getter the target is always `window`, present
130
- // from the first frame — restore in a single shot (unchanged behaviour). When
131
- // a getter is configured we cannot tell "this route legitimately uses window"
132
- // from "the container is still mounting", so re-apply the scroll on every
133
- // frame for a bounded budget: window as a fallback while the container is
134
- // absent (harmless clamp on container routes), the container itself once it
135
- // appears. For instant restores we stop early the moment the position sticks;
136
- // smooth restores animate asynchronously, so they run the full budget. The
137
- // frame budget is the hard backstop against an unreachable target (saved
138
- // position taller than the restored content).
139
- let restoreToken = 0;
140
- const restorePos = (top) => {
141
- if (!getContainer) {
142
- globalThis.scrollTo({ top, left: 0, behavior });
143
- return;
144
- }
135
+ // Scenario 6 of the scroll-restoration example's e2e reproduces both in a
136
+ // container.
137
+ //
138
+ // So the scroll is re-applied on every frame until the target can hold the
139
+ // position — its content is tall enough, and one scroll then lands it,
140
+ // instant or smooth — or until the budget, the backstop against an
141
+ // unreachable target, runs out. A smooth scroll re-applied on every frame
142
+ // arrives later in WebKit, which is why the loop stops at the first frame
143
+ // that can hold it rather than at the first that shows it. With no getter
144
+ // the target is `window`. With one we cannot tell "this route uses window"
145
+ // from "the container is still mounting": window takes the scroll as a
146
+ // fallback while the container is absent (a harmless clamp on container
147
+ // routes), and only the container, once it appears, ends the loop early.
148
+ const restorePos = (route, token) => {
149
+ const top = loadStore()[keyOf(route)] ?? 0;
145
150
  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);
151
+ const holds = (scroller) => scroller.scrollHeight - scroller.clientHeight >= top - 1;
154
152
  const attempt = () => {
155
153
  if (destroyed || token !== restoreToken) {
156
154
  return;
157
155
  }
158
- const element = getContainer();
156
+ const element = getContainer?.();
159
157
  if (element) {
160
158
  element.scrollTo({ top, left: 0, behavior });
161
- // Instant restore landed within rounding tolerance → done; no point
162
- // re-applying. Smooth restore never matches synchronously, so let it
163
- // ride the budget.
164
- if (behavior !== "smooth" && Math.abs(element.scrollTop - top) <= 1) {
159
+ if (holds(element)) {
165
160
  return;
166
161
  }
167
162
  }
168
163
  else {
169
164
  globalThis.scrollTo({ top, left: 0, behavior });
165
+ if (!getContainer &&
166
+ holds(document.scrollingElement ?? document.documentElement)) {
167
+ return;
168
+ }
170
169
  }
171
170
  if (frames >= RESTORE_RETRY_FRAMES) {
172
171
  return;
@@ -227,20 +226,65 @@ export function createScrollRestoration(router, options) {
227
226
  // value survives the transit). A real user scroll in this <16ms window is
228
227
  // physically impossible.
229
228
  let scrollSettled = true;
229
+ // browser-plugin writes state into every entry it commits, so a popstate onto
230
+ // an entry without state lands on one it did not commit — a fragment
231
+ // navigation (an in-page anchor, `location.hash = …`) or an entry other code
232
+ // pushed — rather than stepping through history. An entry whose state other
233
+ // code has cleared reads the same. The location cannot tell a fragment
234
+ // navigation from a step: after a URL rewritten without a commit
235
+ // (`replaceHistoryState`) the router's location is stale, and an anchor click
236
+ // seems to change it. `event.state` is read rather than `history.state`,
237
+ // which the plugin has stamped by the frame; the flag is read in the frame
238
+ // rather than in `subscribe`, because the plugin's listener can commit before
239
+ // this one runs.
240
+ //
241
+ // ⚠ The flag is the last popstate's: one that arrives between a commit and
242
+ // its frame decides that frame.
243
+ let landedOnNewEntry = false;
244
+ const onPopState = (event) => {
245
+ // `null` in a browser; `undefined` under jsdom.
246
+ landedOnNewEntry = event.state === null || event.state === undefined;
247
+ };
230
248
  const unsubscribe = router.subscribe(({ route, previousRoute }) => {
231
- const nav = route.context
232
- .navigation;
249
+ const context = route.context;
250
+ const nav = context.navigation;
251
+ const memory = context.memory?.direction;
252
+ const fromPopState = context.browser?.source === "popstate";
253
+ // A step through history, from the namespace of the URL plugin that
254
+ // publishes one. browser-plugin marks every popstate, a fragment
255
+ // navigation's included; the frame below tells the two apart.
256
+ const historyStep = fromPopState ||
257
+ nav?.direction === "back" ||
258
+ nav?.navigationType === "traverse" ||
259
+ memory === "back" ||
260
+ memory === "forward";
261
+ // Optional although the type requires it: core commits a foreign State's
262
+ // ABSENT `transition` rather than fabricating one (#1792 / #1976), and this
263
+ // runs on whatever `subscribe` hands over. Absent falls through to the
264
+ // plugin arm. A flag is read for truthiness: core commits a JS caller's
265
+ // non-boolean flag unchanged.
266
+ const transition = route.transition;
267
+ const reload = (transition?.reload ?? false) || nav?.navigationType === "reload";
268
+ const replace = (transition?.replace ?? false) || nav?.navigationType === "replace";
269
+ const settled = scrollSettled;
233
270
  // Browsers dispatch reload as the initial navigation after refresh, so
234
271
  // previousRoute is undefined and capture is naturally skipped. The
235
272
  // pre-refresh position was already persisted via pagehide. Capture is also
236
273
  // skipped while the scroll is unsettled — a second navigation in the same
237
274
  // frame, before the prior nav's rAF snap (see `scrollSettled`, #782).
238
- if (previousRoute && scrollSettled) {
275
+ if (previousRoute && settled) {
239
276
  putPos(keyOf(previousRoute), readPos());
240
277
  }
241
278
  // This navigation's scroll effect is now pending: the viewport position no
242
279
  // longer belongs to `route` until the rAF below runs and settles it.
243
280
  scrollSettled = false;
281
+ if (!replace ||
282
+ historyStep ||
283
+ reload ||
284
+ previousRoute?.name !== route.name) {
285
+ restoreToken += 1;
286
+ }
287
+ const token = restoreToken;
244
288
  requestAnimationFrame(() => {
245
289
  if (destroyed) {
246
290
  return;
@@ -253,38 +297,39 @@ export function createScrollRestoration(router, options) {
253
297
  return;
254
298
  }
255
299
  // Restore branches (reload, back/traverse) MUST be evaluated before the
256
- // replace-skip below. Since #657 lifted `replace` into TransitionMeta, a
257
- // history TRAVERSAL (back/forward) under navigation-plugin carries
258
- // `transition.replace === true` — a traversal reuses an existing history
259
- // entry, which is replace-shaped at the history level. If the replace-skip
260
- // ran first it would swallow every back/forward navigation and restore
261
- // would never fire (the Scenario 6 e2e regression). Genuine in-place
262
- // replaces (`router.navigate({ replace: true })`, navigateToNotFound) are
263
- // not traversals and fall through to the skip below.
300
+ // replace-skip below: a history TRAVERSAL reuses an existing entry, which
301
+ // is replace-shaped at the history level, so browser-plugin and
302
+ // memory-plugin commit every one with `transition.replace === true`, and
303
+ // navigation-plugin every one the browser starts. The skip would swallow
304
+ // them. Genuine in-place replaces (`router.navigate({ replace: true })`,
305
+ // navigateToNotFound) are not traversals and fall through to the skip
306
+ // below.
264
307
  //
265
- // Both arms of each check are required: `transition.reload` only fires for
266
- // programmatic `router.navigate({reload:true})`. F5 under navigation-plugin
267
- // primes `nav.navigationType === "reload"` via #531 getActivationType but
268
- // leaves opts.reload undefined, so dropping the plugin arm would regress F5
269
- // scroll-restore. Browser-plugin's F5 is not covered (no priming, out of
270
- // scope).
271
- // `?.` on a required field: core commits a foreign State's ABSENT
272
- // `transition` rather than fabricating one (#1792 / #1976), and this runs
273
- // on whatever `subscribe` hands over. Absent falls through to the plugin
274
- // arm, which is the pre-#1976 answer for a state carrying no meta.
275
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
276
- if (route.transition?.reload || nav?.navigationType === "reload") {
277
- restorePos(loadStore()[keyOf(route)] ?? 0);
308
+ // Both arms of the reload check are required: `transition.reload` only
309
+ // fires for programmatic `router.navigate({reload:true})`. F5 under
310
+ // navigation-plugin primes `nav.navigationType === "reload"` via #531
311
+ // getActivationType but leaves opts.reload undefined, so dropping the
312
+ // plugin arm would regress F5 scroll-restore. Browser-plugin's F5 is not
313
+ // covered (no priming, out of scope).
314
+ if (reload) {
315
+ restorePos(route, token);
278
316
  return;
279
317
  }
280
- if (nav?.direction === "back" || nav?.navigationType === "traverse") {
281
- restorePos(loadStore()[keyOf(route)] ?? 0);
318
+ // A fragment navigation lands on an entry the plugin did not commit
319
+ // (`landedOnNewEntry`). A popstate that keeps the location has nothing
320
+ // to restore either: a restore would write back the position just
321
+ // captured. Unsettled, the page still shows an older location, the
322
+ // capture was skipped, and the popstate restores.
323
+ const keepsLocation = settled &&
324
+ previousRoute !== undefined &&
325
+ keyOf(previousRoute) === keyOf(route);
326
+ if (historyStep &&
327
+ !(fromPopState && (landedOnNewEntry || keepsLocation))) {
328
+ restorePos(route, token);
282
329
  return;
283
330
  }
284
331
  // Genuine in-place replace (not a traversal) — leave scroll untouched.
285
- // `?.` for the same reason as the reload arm above.
286
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- the required field is genuinely absent on a foreign committed State
287
- if (route.transition?.replace || nav?.navigationType === "replace") {
332
+ if (replace) {
288
333
  return;
289
334
  }
290
335
  scrollToHashOrTop(route);
@@ -297,6 +342,7 @@ export function createScrollRestoration(router, options) {
297
342
  }
298
343
  };
299
344
  globalThis.addEventListener("pagehide", onPageHide);
345
+ globalThis.addEventListener("popstate", onPopState);
300
346
  return {
301
347
  destroy: () => {
302
348
  // No `if (destroyed) return` guard: every teardown below is idempotent —
@@ -308,6 +354,7 @@ export function createScrollRestoration(router, options) {
308
354
  destroyed = true;
309
355
  unsubscribe();
310
356
  globalThis.removeEventListener("pagehide", onPageHide);
357
+ globalThis.removeEventListener("popstate", onPopState);
311
358
  try {
312
359
  history.scrollRestoration = prevScrollRestoration;
313
360
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@real-router/svelte",
3
- "version": "0.24.5",
3
+ "version": "0.24.6",
4
4
  "type": "module",
5
5
  "description": "Svelte 5 integration for Real-Router",
6
6
  "svelte": "./dist/index.js",
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@real-router/browser-plugin": "^0.27.0",
58
- "@real-router/core": "^0.154.0",
58
+ "@real-router/core": "^0.157.0",
59
59
  "@sveltejs/package": "2.5.8",
60
60
  "@sveltejs/vite-plugin-svelte": "7.3.1",
61
61
  "@testing-library/jest-dom": "~7.0.1",
@@ -66,7 +66,7 @@
66
66
  "svelte-check": "4.7.6"
67
67
  },
68
68
  "peerDependencies": {
69
- "@real-router/core": ">=0.154.0",
69
+ "@real-router/core": ">=0.157.0",
70
70
  "svelte": ">=5.7.0"
71
71
  },
72
72
  "scripts": {