@k8ordo/router 1.2.1 → 1.4.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.
@@ -40,22 +40,32 @@ export type NavigationHandler<T> = {
40
40
  * load — the page showing reads the search, and the search moved. Without
41
41
  * one, such a navigation is a state change: nothing loads. With one, it
42
42
  * loads and applies like a page change, but as a state change otherwise:
43
- * no scroll, no focus reset, no transition types.
43
+ * no focus reset and no transition types, and the viewport stays where it
44
+ * is — except going back or forward, where it goes back to where that entry
45
+ * was left once the page loaded again is on screen.
44
46
  */
45
47
  refresh?: (url: URL) => boolean;
46
48
  };
49
+ export type Position = {
50
+ readonly left: number;
51
+ readonly top: number;
52
+ };
47
53
  /**
48
- * Where the viewport goes once the new page is on screen. A traversal is the
49
- * browser's to restore, so it carries no instruction; a fragment scrolls to
50
- * its target; anything else starts at the top, the way a document load does.
54
+ * Where the viewport goes once the new page is on screen. Going back or
55
+ * forward, it is where the visitor left that entry; otherwise a fragment
56
+ * scrolls to its target, and anything else starts at the top, the way a
57
+ * document load does — as does a traversal to an entry no page was ever
58
+ * left from, one called off while it loaded.
51
59
  */
52
60
  export type ScrollPlan = {
53
61
  kind: 'top';
54
62
  } | {
55
63
  kind: 'fragment';
56
64
  id: string;
57
- };
58
- export declare const scrollPlanFor: (navigationType: NavigationType, hash: string) => ScrollPlan | null;
65
+ } | ({
66
+ kind: 'position';
67
+ } & Position);
68
+ export declare const scrollPlanFor: (navigationType: NavigationType, hash: string, leftAt: Position | undefined) => ScrollPlan;
59
69
  /**
60
70
  * What a `<ViewTransition>` in the application learns about the navigation
61
71
  * that changed the tree: `navigation` names any page change, and the second
@@ -91,7 +101,10 @@ export declare const NavigationGeneration: import("react").Context<number>;
91
101
  * is what makes `navigation.navigate().finished` mean "the page is showing".
92
102
  * A navigation that keeps the pathname on screen — `@k8ordo/state`'s
93
103
  * `update()` — is intercepted with no handler, so its `finished` settles as
94
- * soon as the navigation commits.
104
+ * soon as the navigation commits. Going back or forward between two entries
105
+ * of that page is the exception: it settles with the render the entry change
106
+ * starts in the background, and the position that entry was left at comes
107
+ * back onto what it renders.
95
108
  *
96
109
  * The new tree renders at the lane `useDeferredValue` gives it, not in a
97
110
  * transition. While any async action is pending, React holds every
@@ -13,8 +13,11 @@ import { addTransitionType, createContext, startTransition, useDeferredValue, us
13
13
  * still come through here.
14
14
  */
15
15
  const isOurs = (event) => event.canIntercept && !event.hashChange && event.downloadRequest === null && event.navigationType !== "reload" && event.formData === null;
16
- const scrollPlanFor = (navigationType, hash) => {
17
- if (navigationType === "traverse") return null;
16
+ const scrollPlanFor = (navigationType, hash, leftAt) => {
17
+ if (navigationType === "traverse" && leftAt !== void 0) return {
18
+ kind: "position",
19
+ ...leftAt
20
+ };
18
21
  if (hash.length > 1) {
19
22
  let id = hash.slice(1);
20
23
  try {
@@ -37,6 +40,14 @@ const scrollPlanFor = (navigationType, hash) => {
37
40
  */
38
41
  const transitionTypesFor = (navigationType) => ["navigation", `navigation-${navigationType}`];
39
42
  const applyScroll = (plan) => {
43
+ if (plan.kind === "position") {
44
+ window.scrollTo({
45
+ left: plan.left,
46
+ top: plan.top,
47
+ behavior: "instant"
48
+ });
49
+ return;
50
+ }
40
51
  if (plan.kind === "fragment") {
41
52
  const selector = `#${CSS.escape(plan.id)}, [name=${JSON.stringify(plan.id)}]`;
42
53
  const target = document.querySelector(selector);
@@ -50,6 +61,37 @@ const applyScroll = (plan) => {
50
61
  top: -1
51
62
  });
52
63
  };
64
+ const leftAt = /* @__PURE__ */ new Map();
65
+ const LEFT_AT_KEY = "@k8ordo/router:left-at";
66
+ const readLeftAt = () => {
67
+ try {
68
+ const saved = sessionStorage.getItem(LEFT_AT_KEY);
69
+ if (saved === null) return;
70
+ for (const [key, position] of JSON.parse(saved)) leftAt.set(key, position);
71
+ } catch {}
72
+ };
73
+ const rememberLeftAt = (entry) => {
74
+ leftAt.set(entry, {
75
+ left: window.scrollX,
76
+ top: window.scrollY
77
+ });
78
+ const live = new Set(navigation.entries().map(({ key }) => key));
79
+ for (const key of leftAt.keys()) if (!live.has(key)) leftAt.delete(key);
80
+ try {
81
+ sessionStorage.setItem(LEFT_AT_KEY, JSON.stringify([...leftAt]));
82
+ } catch {}
83
+ };
84
+ const keepPosition = (entry) => {
85
+ const left = window.scrollX;
86
+ const top = window.scrollY;
87
+ setTimeout(() => {
88
+ if (navigation.currentEntry?.key !== entry) return;
89
+ if (window.scrollX !== left || window.scrollY !== top) window.scrollTo({
90
+ left,
91
+ top
92
+ });
93
+ }, 0);
94
+ };
53
95
  /**
54
96
  * The pathname a page change is loading, in the table's terms — `null` when
55
97
  * none is. One per document, like the navigation it follows: there is one
@@ -96,7 +138,10 @@ const NavigationGeneration = createContext(-1);
96
138
  * is what makes `navigation.navigate().finished` mean "the page is showing".
97
139
  * A navigation that keeps the pathname on screen — `@k8ordo/state`'s
98
140
  * `update()` — is intercepted with no handler, so its `finished` settles as
99
- * soon as the navigation commits.
141
+ * soon as the navigation commits. Going back or forward between two entries
142
+ * of that page is the exception: it settles with the render the entry change
143
+ * starts in the background, and the position that entry was left at comes
144
+ * back onto what it renders.
100
145
  *
101
146
  * The new tree renders at the lane `useDeferredValue` gives it, not in a
102
147
  * transition. While any async action is pending, React holds every
@@ -121,33 +166,67 @@ function useInterceptedNavigation(handler) {
121
166
  const count = useRef(0);
122
167
  const [applied, setApplied] = useState(-1);
123
168
  const onScreen = useDeferredValue(applied);
169
+ const [traversed, setTraversed] = useState(-1);
170
+ const traversedOnScreen = useDeferredValue(traversed);
124
171
  const shown = useRef(null);
125
172
  const latest = useRef(-1);
173
+ const onScreenEntry = useRef(null);
126
174
  useEffect(() => {
127
175
  shown.current = normalizePathname(location.pathname);
176
+ readLeftAt();
128
177
  const onNavigate = (event) => {
178
+ const leaving = onScreenEntry.current ?? navigation.currentEntry?.key;
179
+ if (leaving !== void 0) rememberLeftAt(leaving);
129
180
  if (!isOurs(event)) return;
130
181
  const url = new URL(event.destination.url);
131
182
  const pathname = normalizePathname(url.pathname);
132
183
  const inPlace = pathname === shown.current;
184
+ const traverse = event.navigationType === "traverse";
133
185
  if (inPlace && !refresh(url)) {
186
+ const calledOff = event.destination.key === (onScreenEntry.current ?? navigation.currentEntry?.key);
187
+ onScreenEntry.current = null;
188
+ if (!traverse || calledOff) {
189
+ event.intercept({
190
+ scroll: "manual",
191
+ focusReset: "manual"
192
+ });
193
+ if (calledOff) keepPosition(event.destination.key);
194
+ return;
195
+ }
196
+ const id = count.current++;
197
+ const { promise, resolve, reject } = Promise.withResolvers();
198
+ promise.catch(() => void 0);
199
+ pending.current.set(id, {
200
+ resolve: () => {
201
+ resolve(void 0);
202
+ },
203
+ scroll: scrollPlanFor("traverse", url.hash, leftAt.get(event.destination.key)),
204
+ types: []
205
+ });
206
+ event.signal.addEventListener("abort", () => {
207
+ pending.current.delete(id);
208
+ reject(event.signal.reason);
209
+ }, { once: true });
210
+ setTraversed(id);
134
211
  event.intercept({
135
212
  scroll: "manual",
136
- focusReset: "manual"
213
+ focusReset: "manual",
214
+ handler: () => promise
137
215
  });
138
216
  return;
139
217
  }
140
218
  if (!claim(url)) return;
219
+ onScreenEntry.current ??= navigation.currentEntry?.key ?? null;
141
220
  const id = count.current++;
142
221
  latest.current = id;
143
222
  setPendingPathname(normalizePathname(withoutBase(url.pathname) ?? url.pathname));
144
223
  const settled = () => {
145
224
  if (latest.current === id) setPendingPathname(null);
146
225
  };
147
- const scroll = inPlace ? null : scrollPlanFor(event.navigationType, url.hash);
226
+ const scroll = inPlace && !traverse ? null : scrollPlanFor(event.navigationType, url.hash, leftAt.get(event.destination.key));
148
227
  event.intercept({
149
228
  ...inPlace ? { focusReset: "manual" } : {},
150
- scroll: scroll === null && !inPlace ? "after-transition" : "manual",
229
+ scroll: "manual",
151
230
  handler: async () => {
152
231
  event.signal.addEventListener("abort", settled, { once: true });
153
232
  let value;
@@ -180,14 +259,21 @@ function useInterceptedNavigation(handler) {
180
259
  navigation.removeEventListener("navigate", onNavigate);
181
260
  };
182
261
  }, []);
183
- useLayoutEffect(() => {
184
- const entry = pending.current.get(onScreen);
262
+ const settle = useEffectEvent((id) => {
263
+ const entry = pending.current.get(id);
185
264
  if (entry === void 0) return;
186
- pending.current.delete(onScreen);
265
+ pending.current.delete(id);
266
+ onScreenEntry.current = null;
187
267
  if (entry.scroll !== null) applyScroll(entry.scroll);
188
- if (latest.current === onScreen) setPendingPathname(null);
268
+ if (latest.current === id) setPendingPathname(null);
189
269
  entry.resolve();
270
+ });
271
+ useLayoutEffect(() => {
272
+ settle(onScreen);
190
273
  }, [onScreen]);
274
+ useLayoutEffect(() => {
275
+ settle(traversedOnScreen);
276
+ }, [traversedOnScreen]);
191
277
  useLayoutEffect(() => {
192
278
  if (applied === onScreen) return;
193
279
  const types = pending.current.get(applied)?.types ?? [];
package/dist/router.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  "use client";
2
+ import { normalizePathname } from "./paths.mjs";
2
3
  import { withoutBase } from "./base.mjs";
3
4
  import { NavigationGeneration, useInterceptedNavigation } from "./navigation.mjs";
4
5
  import { setBoundaryOutlet } from "./define-routes.mjs";
5
6
  import { PathnameProvider, appPathname } from "./location.mjs";
7
+ import { TreePathname } from "./tree-pathname.mjs";
6
8
  import { createContext, use, useDeferredValue, useMemo, useState } from "react";
7
9
  import { jsx } from "react/jsx-runtime";
8
10
  //#region src/router.tsx
@@ -35,6 +37,10 @@ const matchUrl = (routes, pathname) => {
35
37
  const own = withoutBase(pathname);
36
38
  return own === null ? null : routes.match(own);
37
39
  };
40
+ const appliedFor = (routes, pathname) => ({
41
+ match: matchUrl(routes, pathname),
42
+ pathname: normalizePathname(pathname)
43
+ });
38
44
  /**
39
45
  * Mounts a route table on the Navigation API: every same-origin navigation
40
46
  * that the table claims is handled in the client, and the rest is left to the
@@ -46,13 +52,14 @@ const matchUrl = (routes, pathname) => {
46
52
  * mounts.
47
53
  */
48
54
  function Router({ routes }) {
49
- const [latest, setLatest] = useState(() => matchUrl(routes, location.pathname));
55
+ const [latest, setLatest] = useState(() => appliedFor(routes, location.pathname));
50
56
  const { generation } = useInterceptedNavigation({
51
57
  claim: (url) => matchUrl(routes, url.pathname) !== null,
52
- load: (url) => matchUrl(routes, url.pathname),
58
+ load: (url) => appliedFor(routes, url.pathname),
53
59
  apply: setLatest
54
60
  });
55
- const match = useDeferredValue(latest);
61
+ const current = useDeferredValue(latest);
62
+ const { match } = current;
56
63
  const value = useMemo(() => ({
57
64
  routes,
58
65
  match
@@ -65,9 +72,12 @@ function Router({ routes }) {
65
72
  pathname: appPathname(),
66
73
  children: /* @__PURE__ */ jsx(NavigationGeneration, {
67
74
  value: generation,
68
- children: /* @__PURE__ */ jsx(RouterContext, {
69
- value,
70
- children: stack
75
+ children: /* @__PURE__ */ jsx(TreePathname, {
76
+ value: current.pathname,
77
+ children: /* @__PURE__ */ jsx(RouterContext, {
78
+ value,
79
+ children: stack
80
+ })
71
81
  })
72
82
  })
73
83
  });
@@ -0,0 +1,4 @@
1
+ import { Context } from "react";
2
+ //#region src/tree-pathname.d.ts
3
+ export declare const TreePathname: Context<string | null>;
4
+ //#endregion
@@ -0,0 +1,16 @@
1
+ "use client";
2
+ import { createContext } from "react";
3
+ //#region src/tree-pathname.ts
4
+ /**
5
+ * The pathname the tree a component renders in was applied for, normalized
6
+ * and in the URL's terms (`withBase`'s, not the table's), or `null` where no
7
+ * router says. Under interception the URL commits before the next tree
8
+ * arrives, so the two differ exactly while the tree on screen is being left.
9
+ * Not exported: `@k8ordo/state` reads it to keep a page state's values with
10
+ * the tree on screen, and `@k8ordo/framework`'s runtime provides it as
11
+ * `<Router>` does.
12
+ */
13
+ const KEY = Symbol.for("@k8ordo/router/tree-pathname");
14
+ const TreePathname = globalThis[KEY] ??= createContext(null);
15
+ //#endregion
16
+ export { TreePathname };
package/docs/GUIDE.md CHANGED
@@ -415,15 +415,22 @@ then, before the chunk is in.
415
415
 
416
416
  **A state change is not a page change.** When only the search or the entry
417
417
  state moved, the pathname is the one whose tree is on screen: the route tree
418
- is left alone, nothing remounts, and scroll and focus are not disturbed. This
419
- is why a search update never scrolls the page back to the top. Such a
420
- navigation is intercepted with no handler, so its `finished` —
421
- `@k8ordo/state`'s `update().finished` included — settles as soon as the
422
- navigation commits, with no render to wait for. The comparison is against the
418
+ is left alone, nothing remounts, and focus is not disturbed. A push or a
419
+ replace leaves scroll alone too — this is why a search update never scrolls
420
+ the page back to the top — and is intercepted with no handler, so its
421
+ `finished` — `@k8ordo/state`'s `update().finished` included — settles as
422
+ soon as the navigation commits, with no render to wait for. Going back or
423
+ forward between two entries of the page is the exception: the viewport
424
+ returns to where that entry was left, once the page has rendered the
425
+ entry — what it renders through `useDeferredValue` included — so a
426
+ filtered list comes back to where it was read, and that `finished` waits for
427
+ the render. The comparison is against the
423
428
  page showing, not against the address bar — interception commits the URL
424
429
  first, so a state update issued while another page is still loading is a page
425
430
  change: it lets that page finish arriving, and its `finished` waits for that
426
- render.
431
+ render. Going back while another page is still loading, to the entry of the
432
+ page still on screen, calls that page change off: the page stays where the
433
+ visitor scrolled it.
427
434
 
428
435
  **Route changes render in the background.** The new tree renders at the
429
436
  priority `useDeferredValue` gives it, so the old page stays on screen and
@@ -436,17 +443,42 @@ tagged with `addTransitionType` — `navigation`, and one of `navigation-push`,
436
443
  `navigation-replace`, `navigation-traverse` — which is what a
437
444
  `<ViewTransition>` reads to animate a page change and nothing else (below).
438
445
 
446
+ **The page being left keeps its own values.** `<Router>` tells
447
+ `@k8ordo/state`, per tree, the pathname it was applied for, so a page state
448
+ in the page still on screen keeps the values its URL had as it was left,
449
+ while the URL already names the next page; the next page renders with its
450
+ own from its first render. `usePathname()` follows the URL all the same. A
451
+ host of your own built on `useInterceptedNavigation` tells nothing, and a
452
+ page state under it follows the URL.
453
+
439
454
  **A new page starts at the top.** Once the new tree is on screen, the
440
455
  viewport goes where a document load would have put it: the top, or the
441
- element a `#fragment` names. Back and forward are left to the browser, which
442
- restores the position it saved. A state change never moves the viewport —
443
- same pathname, same place — so a filter update does not scroll the reader
444
- back to the top.
456
+ element a `#fragment` names.
457
+
458
+ **Back and forward return to where the entry was left.** The viewport goes
459
+ back to where the visitor left that entry — between two entries of the same
460
+ page too, and to an entry from before a reload, which still belongs to the
461
+ same document. The router puts it there itself, at once (a root
462
+ `scroll-behavior: smooth` does not animate it), rather than leaving it to the
463
+ browser: Chromium restores a position that the new page's layout clamped
464
+ while the navigation was in flight, so a page that measures itself as it
465
+ renders would come back at its bottom. Scrolling the page still on screen
466
+ while the next one loads does not change where the next one lands — what
467
+ moved was the page being left. An entry that was never on screen — a page
468
+ change called off while it loaded — starts at the top, or at its fragment,
469
+ as a new page does. Only the document's scroll position comes back: an
470
+ element scrolled inside the page and the pinch-zoom scale do not.
471
+
472
+ Any other state change never moves the viewport — same pathname, same
473
+ place — so a filter update does not scroll the reader back to the top.
445
474
 
446
475
  **Superseded navigations abort.** A second navigation aborts the first through
447
476
  the platform's own signal: the overtaken `finished` rejects with the abort
448
477
  reason, and its tree never reaches the screen even if its load had already
449
- come back. `load` receives that signal, so a payload fetch under the framework
478
+ come back. Going back or forward within a page counts too: replaced by a
479
+ navigation of its own before the page has rendered the entry — an effect
480
+ that corrects the URL, say — its `finished` rejects, and the position is not
481
+ restored. `load` receives that signal, so a payload fetch under the framework
450
482
  is cancelled outright. A `React.lazy` chunk cannot be — a dynamic import takes
451
483
  no signal — so in a client application it finishes in the background and is
452
484
  kept for the next visit, while the page it belonged to is never shown.
@@ -549,8 +581,10 @@ A fourth, optional member, `refresh: (url) => boolean`, says whether a
549
581
  navigation that keeps the pathname on screen still has to load — the page
550
582
  showing reads what moved. Without it such a navigation is a state change and
551
583
  loads nothing; with it, it loads and applies like a page change but as a
552
- state change otherwise: no scroll, no focus reset, no transition types. The
553
- framework's runtime answers it for a page that exports `search`.
584
+ state change otherwise: no focus reset and no transition types, and no
585
+ scroll but going back or forward, which returns to where that entry was left
586
+ once the page loaded again is on screen. The framework's runtime answers it
587
+ for a page that exports `search`.
554
588
 
555
589
  A host renders what `apply` set through `useDeferredValue`, in the same
556
590
  component that calls the hook. That is what renders the new page in the
package/docs/llms.txt CHANGED
@@ -17,7 +17,8 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
17
17
  wildcards, route groups, declaration order), mounting `<Router>` and
18
18
  `<Outlet>`, links without a `<Link>` component, `useMatch` for active
19
19
  sections, `Register` for checked patterns, what navigation guarantees
20
- (`finished` after commit, scroll to top or fragment on a new page), how
20
+ (`finished` after commit, scroll to top or fragment on a new page, and
21
+ back to where an entry was left on back and forward), how
21
22
  a `<ViewTransition>` animates page changes by the router's transition
22
23
  types, and how the framework reuses the navigation half (an application on
23
24
  `@k8ordo/framework` imports that half from `@k8ordo/framework`, which
@@ -94,8 +95,9 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
94
95
  uses to render server-produced trees instead; its host renders what
95
96
  `apply` set through `useDeferredValue`; its optional `refresh(url)` says
96
97
  whether a same-pathname navigation still has to load (the page showing reads
97
- the search), which then loads in place — no scroll, focus reset or
98
- transition types.
98
+ the search), which then loads in place — no focus reset or transition
99
+ types, and no scroll but going back or forward, which returns to where
100
+ that entry was left once the page loaded again is on screen.
99
101
  Exported types, by group — the table: `Routes` (`{ kind, record, match }`),
100
102
  `RoutesRecord`, `RouteNode`, `RouteComponent`, `Match`, `ErrorComponent`,
101
103
  `ErrorProps`; patterns: `PatternOf`, `NavigablePatternOf`, `NavigablePath`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/router",
3
- "version": "1.2.1",
3
+ "version": "1.4.0",
4
4
  "description": "The pathname axis of the URL, owned. One route table derives the types, the matching, the links, and the navigation, over the Navigation API and URLPattern.",
5
5
  "keywords": [
6
6
  "navigation-api",