@k8ordo/router 1.3.0 → 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.
@@ -41,24 +41,31 @@ export type NavigationHandler<T> = {
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
43
  * no focus reset and no transition types, and the viewport stays where it
44
- * is — except going back or forward, where the browser restores the
45
- * position that entry was left at once the page loaded again is on screen.
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.
46
46
  */
47
47
  refresh?: (url: URL) => boolean;
48
48
  };
49
+ export type Position = {
50
+ readonly left: number;
51
+ readonly top: number;
52
+ };
49
53
  /**
50
- * Where the viewport goes once the new page is on screen. A traversal is the
51
- * browser's to restore, so it carries no instruction — the browser restores
52
- * it once the handler settles; a fragment scrolls to its target; anything
53
- * 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.
54
59
  */
55
60
  export type ScrollPlan = {
56
61
  kind: 'top';
57
62
  } | {
58
63
  kind: 'fragment';
59
64
  id: string;
60
- };
61
- 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;
62
69
  /**
63
70
  * What a `<ViewTransition>` in the application learns about the navigation
64
71
  * that changed the tree: `navigation` names any page change, and the second
@@ -96,8 +103,8 @@ export declare const NavigationGeneration: import("react").Context<number>;
96
103
  * `update()` — is intercepted with no handler, so its `finished` settles as
97
104
  * soon as the navigation commits. Going back or forward between two entries
98
105
  * of that page is the exception: it settles with the render the entry change
99
- * starts in the background, so the browser restores the position onto what
100
- * that entry renders.
106
+ * starts in the background, and the position that entry was left at comes
107
+ * back onto what it renders.
101
108
  *
102
109
  * The new tree renders at the lane `useDeferredValue` gives it, not in a
103
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,8 +61,26 @@ const applyScroll = (plan) => {
50
61
  top: -1
51
62
  });
52
63
  };
53
- let anchoringHeld = 0;
54
- let anchoringBefore = "";
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
+ };
55
84
  const keepPosition = (entry) => {
56
85
  const left = window.scrollX;
57
86
  const top = window.scrollY;
@@ -63,23 +92,6 @@ const keepPosition = (entry) => {
63
92
  });
64
93
  }, 0);
65
94
  };
66
- const holdAnchoring = () => {
67
- const { style } = document.documentElement;
68
- if (anchoringHeld === 0) {
69
- anchoringBefore = style.overflowAnchor;
70
- style.overflowAnchor = "none";
71
- }
72
- anchoringHeld += 1;
73
- let released = false;
74
- return () => {
75
- if (released) return;
76
- released = true;
77
- anchoringHeld -= 1;
78
- if (anchoringHeld > 0) return;
79
- document.documentElement.getBoundingClientRect();
80
- style.overflowAnchor = anchoringBefore;
81
- };
82
- };
83
95
  /**
84
96
  * The pathname a page change is loading, in the table's terms — `null` when
85
97
  * none is. One per document, like the navigation it follows: there is one
@@ -128,8 +140,8 @@ const NavigationGeneration = createContext(-1);
128
140
  * `update()` — is intercepted with no handler, so its `finished` settles as
129
141
  * soon as the navigation commits. Going back or forward between two entries
130
142
  * of that page is the exception: it settles with the render the entry change
131
- * starts in the background, so the browser restores the position onto what
132
- * that entry renders.
143
+ * starts in the background, and the position that entry was left at comes
144
+ * back onto what it renders.
133
145
  *
134
146
  * The new tree renders at the lane `useDeferredValue` gives it, not in a
135
147
  * transition. While any async action is pending, React holds every
@@ -161,7 +173,10 @@ function useInterceptedNavigation(handler) {
161
173
  const onScreenEntry = useRef(null);
162
174
  useEffect(() => {
163
175
  shown.current = normalizePathname(location.pathname);
176
+ readLeftAt();
164
177
  const onNavigate = (event) => {
178
+ const leaving = onScreenEntry.current ?? navigation.currentEntry?.key;
179
+ if (leaving !== void 0) rememberLeftAt(leaving);
165
180
  if (!isOurs(event)) return;
166
181
  const url = new URL(event.destination.url);
167
182
  const pathname = normalizePathname(url.pathname);
@@ -181,22 +196,20 @@ function useInterceptedNavigation(handler) {
181
196
  const id = count.current++;
182
197
  const { promise, resolve, reject } = Promise.withResolvers();
183
198
  promise.catch(() => void 0);
184
- const release = holdAnchoring();
185
199
  pending.current.set(id, {
186
200
  resolve: () => {
187
201
  resolve(void 0);
188
202
  },
189
- scroll: null,
190
- types: [],
191
- release
203
+ scroll: scrollPlanFor("traverse", url.hash, leftAt.get(event.destination.key)),
204
+ types: []
192
205
  });
193
206
  event.signal.addEventListener("abort", () => {
194
207
  pending.current.delete(id);
195
- release();
196
208
  reject(event.signal.reason);
197
209
  }, { once: true });
198
210
  setTraversed(id);
199
211
  event.intercept({
212
+ scroll: "manual",
200
213
  focusReset: "manual",
201
214
  handler: () => promise
202
215
  });
@@ -210,12 +223,10 @@ function useInterceptedNavigation(handler) {
210
223
  const settled = () => {
211
224
  if (latest.current === id) setPendingPathname(null);
212
225
  };
213
- const scroll = inPlace ? null : scrollPlanFor(event.navigationType, url.hash);
214
- const release = inPlace && traverse ? holdAnchoring() : void 0;
215
- if (release !== void 0) event.signal.addEventListener("abort", release, { once: true });
226
+ const scroll = inPlace && !traverse ? null : scrollPlanFor(event.navigationType, url.hash, leftAt.get(event.destination.key));
216
227
  event.intercept({
217
228
  ...inPlace ? { focusReset: "manual" } : {},
218
- scroll: traverse ? "after-transition" : "manual",
229
+ scroll: "manual",
219
230
  handler: async () => {
220
231
  event.signal.addEventListener("abort", settled, { once: true });
221
232
  let value;
@@ -223,7 +234,6 @@ function useInterceptedNavigation(handler) {
223
234
  value = await load(url, event.signal);
224
235
  } catch (error) {
225
236
  settled();
226
- release?.();
227
237
  throw error;
228
238
  }
229
239
  if (event.signal.aborted) throw event.signal.reason;
@@ -231,8 +241,7 @@ function useInterceptedNavigation(handler) {
231
241
  pending.current.set(id, {
232
242
  resolve,
233
243
  scroll,
234
- types: inPlace ? [] : transitionTypesFor(event.navigationType),
235
- ...release === void 0 ? {} : { release }
244
+ types: inPlace ? [] : transitionTypesFor(event.navigationType)
236
245
  });
237
246
  event.signal.addEventListener("abort", () => {
238
247
  pending.current.delete(id);
@@ -255,7 +264,6 @@ function useInterceptedNavigation(handler) {
255
264
  if (entry === void 0) return;
256
265
  pending.current.delete(id);
257
266
  onScreenEntry.current = null;
258
- entry.release?.();
259
267
  if (entry.scroll !== null) applyScroll(entry.scroll);
260
268
  if (latest.current === id) setPendingPathname(null);
261
269
  entry.resolve();
package/docs/GUIDE.md CHANGED
@@ -420,9 +420,9 @@ replace leaves scroll alone too — this is why a search update never scrolls
420
420
  the page back to the top — and is intercepted with no handler, so its
421
421
  `finished` — `@k8ordo/state`'s `update().finished` included — settles as
422
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 browser
424
- restores the position that entry was left at, once the page has rendered
425
- the entry — what it renders through `useDeferredValue` included — so a
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
426
  filtered list comes back to where it was read, and that `finished` waits for
427
427
  the render. The comparison is against the
428
428
  page showing, not against the address bar — interception commits the URL
@@ -453,8 +453,22 @@ page state under it follows the URL.
453
453
 
454
454
  **A new page starts at the top.** Once the new tree is on screen, the
455
455
  viewport goes where a document load would have put it: the top, or the
456
- element a `#fragment` names. Back and forward are left to the browser, which
457
- restores the position it saved — between two entries of the same page too.
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
+
458
472
  Any other state change never moves the viewport — same pathname, same
459
473
  place — so a filter update does not scroll the reader back to the top.
460
474
 
@@ -568,7 +582,7 @@ navigation that keeps the pathname on screen still has to load — the page
568
582
  showing reads what moved. Without it such a navigation is a state change and
569
583
  loads nothing; with it, it loads and applies like a page change but as a
570
584
  state change otherwise: no focus reset and no transition types, and no
571
- scroll but going back or forward, where the browser restores the position
585
+ scroll but going back or forward, which returns to where that entry was left
572
586
  once the page loaded again is on screen. The framework's runtime answers it
573
587
  for a page that exports `search`.
574
588
 
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
@@ -95,8 +96,8 @@ When installed via npm, these docs live under `node_modules/@k8ordo/router/docs/
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
98
  the search), which then loads in place — no focus reset or transition
98
- types, and no scroll but going back or forward, where the browser restores
99
- the position once the page loaded again is on screen.
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.
100
101
  Exported types, by group — the table: `Routes` (`{ kind, record, match }`),
101
102
  `RoutesRecord`, `RouteNode`, `RouteComponent`, `Match`, `ErrorComponent`,
102
103
  `ErrorProps`; patterns: `PatternOf`, `NavigablePatternOf`, `NavigablePath`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@k8ordo/router",
3
- "version": "1.3.0",
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",