shelving 1.323.2 → 1.324.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.
Files changed (84) hide show
  1. package/docs/guides/building-with-shelving.md +3 -3
  2. package/docs/llms-full.txt +345 -149
  3. package/docs/react/SequenceTransitionOptions.md +24 -0
  4. package/docs/react/useSequenceTransition.md +70 -0
  5. package/docs/react.md +2 -0
  6. package/docs/ui/BackButton.md +1 -1
  7. package/docs/ui/Head.md +1 -1
  8. package/docs/ui/HorizontalTransition.md +1 -1
  9. package/docs/ui/Image.md +3 -0
  10. package/docs/ui/Meta.md +2 -0
  11. package/docs/ui/Navigation.md +18 -17
  12. package/docs/ui/NavigationContext.md +2 -2
  13. package/docs/ui/NavigationDirection.md +12 -0
  14. package/docs/ui/NavigationEntryState.md +3 -3
  15. package/docs/ui/NavigationEvent.md +28 -0
  16. package/docs/ui/{NavigationStore → NavigationSequence}/back.md +6 -5
  17. package/docs/ui/NavigationSequence/committed.md +13 -0
  18. package/docs/ui/NavigationSequence/current.md +13 -0
  19. package/docs/ui/{NavigationStore → NavigationSequence}/forward.md +4 -4
  20. package/docs/ui/{NavigationStore → NavigationSequence}/history.md +3 -3
  21. package/docs/ui/{NavigationStore → NavigationSequence}/listen.md +3 -3
  22. package/docs/ui/NavigationSequence/publish.md +14 -0
  23. package/docs/ui/{NavigationStore → NavigationSequence}/replace.md +4 -4
  24. package/docs/ui/NavigationSequence.md +187 -0
  25. package/docs/ui/RouteCache.md +16 -15
  26. package/docs/ui/RouteCacheProps.md +1 -1
  27. package/docs/ui/Router.md +2 -2
  28. package/docs/ui/Transition.md +1 -1
  29. package/docs/ui/VerticalTransition.md +1 -1
  30. package/docs/ui/mergeMeta.md +1 -0
  31. package/docs/ui/requireContext.md +1 -1
  32. package/docs/ui/requireNavigation.md +3 -3
  33. package/docs/ui.md +6 -6
  34. package/package.json +1 -1
  35. package/react/index.d.ts +1 -0
  36. package/react/index.js +1 -0
  37. package/react/useSequenceTransition.d.ts +38 -0
  38. package/react/useSequenceTransition.js +44 -0
  39. package/ui/block/Image.d.ts +3 -0
  40. package/ui/block/Image.js +18 -1
  41. package/ui/block/Image.module.css +27 -0
  42. package/ui/block/Image.tsx +24 -1
  43. package/ui/page/Head.d.ts +1 -1
  44. package/ui/page/Head.js +9 -4
  45. package/ui/page/Head.tsx +8 -4
  46. package/ui/router/BackButton.js +6 -3
  47. package/ui/router/BackButton.md +1 -1
  48. package/ui/router/BackButton.tsx +6 -3
  49. package/ui/router/Navigation.d.ts +5 -5
  50. package/ui/router/Navigation.js +24 -49
  51. package/ui/router/Navigation.md +13 -12
  52. package/ui/router/Navigation.tsx +25 -59
  53. package/ui/router/NavigationContext.d.ts +7 -15
  54. package/ui/router/NavigationContext.js +4 -13
  55. package/ui/router/NavigationContext.tsx +7 -17
  56. package/ui/router/{NavigationStore.d.ts → NavigationSequence.d.ts} +93 -51
  57. package/ui/router/{NavigationStore.js → NavigationSequence.js} +132 -80
  58. package/ui/router/NavigationSequence.md +129 -0
  59. package/ui/router/{NavigationStore.test.ts → NavigationSequence.test.ts} +126 -61
  60. package/ui/router/{NavigationStore.tsx → NavigationSequence.tsx} +160 -92
  61. package/ui/router/RouteCache.d.ts +8 -7
  62. package/ui/router/RouteCache.js +34 -29
  63. package/ui/router/RouteCache.md +9 -8
  64. package/ui/router/RouteCache.tsx +39 -36
  65. package/ui/router/Router.d.ts +2 -2
  66. package/ui/router/Router.js +3 -5
  67. package/ui/router/Router.md +1 -1
  68. package/ui/router/Router.tsx +4 -5
  69. package/ui/router/StackButton.d.ts +1 -1
  70. package/ui/router/StackButton.js +5 -7
  71. package/ui/router/StackButton.tsx +6 -7
  72. package/ui/router/index.d.ts +1 -1
  73. package/ui/router/index.js +1 -1
  74. package/ui/router/index.ts +1 -1
  75. package/ui/transition/HorizontalTransition.md +1 -1
  76. package/ui/transition/Transition.md +1 -1
  77. package/ui/transition/VerticalTransition.md +1 -1
  78. package/ui/util/meta.d.ts +2 -0
  79. package/ui/util/meta.ts +2 -0
  80. package/ui/util/requireContext.md +1 -1
  81. package/docs/ui/NavigationPosition.md +0 -24
  82. package/docs/ui/NavigationPositionContext.md +0 -8
  83. package/docs/ui/NavigationStore.md +0 -164
  84. package/ui/router/NavigationStore.md +0 -110
@@ -1,12 +1,11 @@
1
- import { Store } from "../../store/Store.js";
2
- import { URLStore } from "../../store/URLStore.js";
1
+ import { DeferredSequence } from "../../sequence/DeferredSequence.js";
2
+ import { createDeferred } from "../../util/async.js";
3
3
  import { BLACKHOLE } from "../../util/function.js";
4
4
  import type { AbsolutePath } from "../../util/path.js";
5
- import { type ImmutableURL, matchURLPrefix, type PossibleURL, requireURL } from "../../util/url.js";
6
- import type { TransitionType } from "../transition/util.js";
5
+ import { getURL, type ImmutableURL, matchURLPrefix, type PossibleURL, requireURL } from "../../util/url.js";
7
6
 
8
7
  /**
9
- * State that `NavigationStore` saves on each browser history entry.
8
+ * State that `NavigationSequence` saves on each browser history entry.
10
9
  *
11
10
  * @see https://shelving.cc/ui/NavigationEntryState
12
11
  */
@@ -14,20 +13,32 @@ export interface NavigationEntryState {
14
13
  /** Root path of the stack this page is in, or `null` for a floating page. */
15
14
  readonly stack: AbsolutePath | null;
16
15
  /** Position of this page in its stack, where `0` is the root. */
17
- readonly depth: number;
16
+ readonly ordinal: number;
18
17
  }
19
18
 
20
19
  /**
21
- * Where the app is now in its stacks: the current stack and depth, the top depth of each stack, and the page before the current one.
22
- * - `undefined` when the browser has no Navigation API, or during a server render.
20
+ * Direction of a move in a `NavigationEvent`: `"forward"` or `"back"`.
23
21
  *
24
- * @see https://shelving.cc/ui/NavigationPosition
22
+ * @see https://shelving.cc/ui/NavigationDirection
25
23
  */
26
- export interface NavigationPosition extends NavigationEntryState {
27
- /** Depth of the top page of each stack that has pages, including the floating stack (`null`). */
28
- readonly tops: ReadonlyMap<AbsolutePath | null, number>;
29
- /** The page before the current one in its stack, or `undefined` at the bottom of the stack. */
30
- readonly parent: AbsolutePath | undefined;
24
+ export type NavigationDirection = "forward" | "back";
25
+
26
+ /**
27
+ * One change of page, published by `NavigationSequence`.
28
+ * - A move (a link, a back button, the browser back and forward buttons) has a `direction`, so `<Navigation>` shows it inside a view transition of that type.
29
+ * - A replace has no `direction`, so it shows at once with no transition.
30
+ *
31
+ * @see https://shelving.cc/ui/NavigationEvent
32
+ */
33
+ export interface NavigationEvent {
34
+ /** URL of the page. */
35
+ readonly url: ImmutableURL;
36
+ /** Root path of the stack the page is in, or `null` for a floating page. */
37
+ readonly stack: AbsolutePath | null;
38
+ /** Position of the page in its stack, where `0` is the root, or `undefined` without the Navigation API. */
39
+ readonly ordinal: number | undefined;
40
+ /** Direction of the move, or `undefined` for a replace or a change with no slide. */
41
+ readonly direction?: NavigationDirection | undefined;
31
42
  }
32
43
 
33
44
  /** One page in a stack: the entry that holds it, plus its saved state. */
@@ -45,38 +56,41 @@ type _Navigation = Pick<
45
56
  >;
46
57
 
47
58
  /**
48
- * Store that holds the current navigation URL, drives browser history, and keeps a stack of pages for each tab.
59
+ * Sequence of navigation events that drives browser history and keeps a stack of pages for each tab.
49
60
  *
50
- * - Extends `URLStore`, so its `value` is the current URL.
61
+ * - It is not a store: it holds no "current page" for the UI. Each change of page (a move, a replace, or the browser back and forward buttons) publishes one `NavigationEvent`, and `<Navigation>` keeps the page it shows in its own state.
62
+ * - `url`, `stack` and `ordinal` say where the browser history is now. The page on screen can differ for a moment, for example during a swipe-back preview. To read the page on screen, read `Meta`.
63
+ * - `publish()` sends an event by hand, for example to show the page below during a swipe-back.
51
64
  * - With the browser Navigation API, each history entry saves a `NavigationEntryState`, and each stack is read from `navigation.entries()` when it is needed. Nothing else is kept.
52
- * - `stack` is a sub-store that holds the root of the current stack, or `null` for a floating page. It only changes when the stack changes.
53
65
  * - A page outside the listed stacks is floating: its stack is `null`. The floating stack has no root page and no tab.
54
- * - In a listed stack, depth `0` is always the stack's root path.
66
+ * - In a listed stack, ordinal `0` is always the stack's root path.
55
67
  * - Without the Navigation API (older browsers and server renders) there are no stacks: `stack` stays the starting stack, `history()` is empty, and `stack` arguments are ignored.
56
68
  * - Owned by `<Navigation>`. Read it with `requireNavigation()`.
57
69
  *
58
- * @see https://shelving.cc/ui/NavigationStore
70
+ * @see https://shelving.cc/ui/NavigationSequence
59
71
  */
60
- export class NavigationStore extends URLStore {
72
+ export class NavigationSequence extends DeferredSequence<NavigationEvent> {
61
73
  /** Root path of each stack, in tab order. With none, every page floats. */
62
74
  readonly stacks: readonly AbsolutePath[];
63
75
 
64
76
  /**
65
- * Root path of the current stack, or `null` for a floating page.
66
- * - It starts at the `stack` given to the constructor (default `null`). Without the Navigation API, it stays there.
77
+ * Base URL of the app, used to resolve relative URLs and to work out paths.
78
+ *
79
+ * @see https://shelving.cc/ui/NavigationSequence/base
67
80
  */
68
- readonly stack: Store<AbsolutePath | null>;
81
+ readonly base: ImmutableURL | undefined;
69
82
 
70
- /**
71
- * Transition type of the most recent change, read by `<Navigation>` when the value changes.
72
- * - `null` means no transition: a replace, a change the browser already animated (for example a swipe-back), or no Navigation API.
73
- */
74
- transition: TransitionType | null = null;
83
+ /** URL the browser history is on now. */
84
+ private _url: ImmutableURL;
85
+ /** Stack the browser history is on now. Without the Navigation API, it stays at the starting stack. */
86
+ private _stack: AbsolutePath | null;
87
+ /** Callbacks waiting for `<Navigation>` to commit the next event. */
88
+ private _waiting: (() => void)[] = [];
75
89
 
76
90
  /** The browser Navigation API, or `undefined` when it is not available. */
77
91
  private readonly _navigation: _Navigation | undefined;
78
92
  /** Transition sent with the next navigation, and whether the browser animates it. */
79
- private _info: TransitionType | null | undefined = undefined;
93
+ private _info: NavigationDirection | null | undefined = undefined;
80
94
  /** `true` while the store changes history itself, so it ignores the events that causes. */
81
95
  private _busy = false;
82
96
 
@@ -89,46 +103,86 @@ export class NavigationStore extends URLStore {
89
103
  stack: AbsolutePath | null = null,
90
104
  ...stacks: AbsolutePath[]
91
105
  ) {
92
- super(url, base);
106
+ super();
107
+ this.base = getURL(base);
108
+ this._url = requireURL(url, this.base, NavigationSequence);
93
109
  this.stacks = stacks;
94
110
  this._start = stack !== null && stacks.includes(stack) ? stack : null;
95
111
  this._navigation = _getNavigation();
96
- this.stack = new Store<AbsolutePath | null>(this._navigation ? this._getState(this._navigation.currentEntry).stack : this._start);
112
+ this._stack = this._navigation ? this._getState(this._navigation.currentEntry).stack : this._start;
97
113
  }
98
114
 
99
115
  /**
100
- * Path of the current URL relative to the app root (without its `?query`), or `undefined` if the URL is outside the app.
116
+ * URL the browser history is on now.
101
117
  *
102
- * @see https://shelving.cc/ui/NavigationStore/path
118
+ * @see https://shelving.cc/ui/NavigationSequence/url
103
119
  */
104
- get path(): AbsolutePath | undefined {
105
- return this._getPath(this.value);
120
+ get url(): ImmutableURL {
121
+ return this._url;
106
122
  }
107
123
 
108
124
  /**
109
- * Where the app is now: the current stack and depth, and the top depth of each stack.
125
+ * Root path of the stack the browser history is on now, or `null` for a floating page.
110
126
  *
111
- * @returns The position, or `undefined` without the Navigation API.
112
- * @see https://shelving.cc/ui/NavigationStore/position
127
+ * @see https://shelving.cc/ui/NavigationSequence/stack
113
128
  */
114
- get position(): NavigationPosition | undefined {
115
- if (!this._navigation) return undefined;
116
- const { stack, depth } = this._getState(this._navigation.currentEntry);
117
- const tops = new Map<AbsolutePath | null, number>();
118
- for (const s of this._getStacks()) {
119
- const top = this._getPages(s).at(-1);
120
- if (top) tops.set(s, top.depth);
121
- }
122
- return { stack, depth, tops, parent: this.history(stack).at(-2) };
129
+ get stack(): AbsolutePath | null {
130
+ return this._stack;
131
+ }
132
+
133
+ /**
134
+ * Where the browser history is now, as an event with no direction.
135
+ * - `<Navigation>` reads it for its first render, and again when it starts listening, to catch up on changes it missed.
136
+ *
137
+ * @see https://shelving.cc/ui/NavigationSequence/current
138
+ */
139
+ current(): NavigationEvent {
140
+ const navigation = this._navigation;
141
+ return { url: this._url, stack: this._stack, ordinal: navigation ? this._getState(navigation.currentEntry).ordinal : undefined };
142
+ }
143
+
144
+ /**
145
+ * Publish an event by hand, without changing history.
146
+ * - For example, a swipe-back publishes the page below with `direction: "back"`, so React runs its back transition, and the swipe scrubs it.
147
+ * - Then the real `back()` publishes the same page again, which `<Navigation>` skips, or the swipe publishes the current page again to cancel.
148
+ *
149
+ * @param event The event to publish.
150
+ * @returns A promise that resolves when `<Navigation>` has committed the event.
151
+ * @see https://shelving.cc/ui/NavigationSequence/publish
152
+ */
153
+ publish(event: NavigationEvent): Promise<void> {
154
+ const { promise, resolve } = createDeferred<void>();
155
+ this._waiting.push(resolve);
156
+ this.resolve(event);
157
+ return promise;
158
+ }
159
+
160
+ /**
161
+ * Tell waiting `publish()` calls that `<Navigation>` has committed a page.
162
+ * - `<Navigation>` calls it after each commit.
163
+ *
164
+ * @see https://shelving.cc/ui/NavigationSequence/committed
165
+ */
166
+ committed(): void {
167
+ for (const resolve of this._waiting.splice(0)) resolve();
168
+ }
169
+
170
+ /**
171
+ * Path of the current URL relative to the app root (without its `?query`), or `undefined` if the URL is outside the app.
172
+ *
173
+ * @see https://shelving.cc/ui/NavigationSequence/path
174
+ */
175
+ get path(): AbsolutePath | undefined {
176
+ return this._getPath(this._url);
123
177
  }
124
178
 
125
179
  /**
126
180
  * Start listening to the browser (back, forward and swipe).
127
- * - Saves the current stack and depth on the current history entry, if it has none.
181
+ * - Saves the current stack and ordinal on the current history entry, if it has none.
128
182
  * - `<Navigation>` calls it once, when it mounts.
129
183
  *
130
184
  * @returns A function that stops listening.
131
- * @see https://shelving.cc/ui/NavigationStore/listen
185
+ * @see https://shelving.cc/ui/NavigationSequence/listen
132
186
  */
133
187
  listen(): () => void {
134
188
  const navigation = this._navigation;
@@ -178,18 +232,18 @@ export class NavigationStore extends URLStore {
178
232
  * @param stack Root path of the stack, or `null` for the floating stack. Defaults to the current stack.
179
233
  * @returns Paths relative to the app root, each with its `?query`.
180
234
  * @example nav.history("/home") // ["/home", "/home/post/2"]
181
- * @see https://shelving.cc/ui/NavigationStore/history
235
+ * @see https://shelving.cc/ui/NavigationSequence/history
182
236
  */
183
- history(stack: AbsolutePath | null = this.stack.value): AbsolutePath[] {
237
+ history(stack: AbsolutePath | null = this._stack): AbsolutePath[] {
184
238
  const pages = this._getPages(stack);
185
239
  const paths = pages.map(p => _getPathWithQuery(p));
186
- if (stack !== null && pages[0] && pages[0].depth > 0) paths.unshift(stack);
240
+ if (stack !== null && pages[0] && pages[0].ordinal > 0) paths.unshift(stack);
187
241
  return paths;
188
242
  }
189
243
 
190
244
  /**
191
245
  * Go forward to a URL, as a link does.
192
- * - The URL is the top page of `stack`: switch to that stack, at the same depth. This is a tab switch.
246
+ * - The URL is the top page of `stack`: switch to that stack, at the same ordinal. This is a tab switch.
193
247
  * - Else push the URL onto `stack`, one level deeper than its top page.
194
248
  * - The URL you are already on: replace it instead.
195
249
  * - A change of stack slides by tab order. Else it slides forward.
@@ -198,59 +252,68 @@ export class NavigationStore extends URLStore {
198
252
  * @param stack Root path of the stack to go to, or `null` for the floating stack. Defaults to the current stack.
199
253
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
200
254
  * @example nav.forward("/settings");
201
- * @see https://shelving.cc/ui/NavigationStore/forward
255
+ * @see https://shelving.cc/ui/NavigationSequence/forward
202
256
  */
203
- forward(possible: PossibleURL, stack: AbsolutePath | null = this.stack.value): void {
257
+ forward(possible: PossibleURL, stack: AbsolutePath | null = this._stack): void {
204
258
  const url = requireURL(possible, this.base, this.forward);
205
259
  if (!this._navigation) {
206
260
  this._push(url, "forward");
207
261
  return;
208
262
  }
209
- const current = this.stack.value;
210
- if (stack === current && url.href === this.value.href) {
263
+ const current = this._stack;
264
+ if (stack === current && url.href === this._url.href) {
211
265
  this.replace(url);
212
266
  return;
213
267
  }
214
268
  const top = this._getPages(stack).at(-1);
215
- const depth = top ? (top.url.href === url.href ? top.depth : top.depth + 1) : this._getBottomDepth(url, stack);
216
- this._push(url, this._getOrder(current, stack) ?? "forward", { stack, depth });
269
+ const ordinal = top ? (top.url.href === url.href ? top.ordinal : top.ordinal + 1) : this._getBottomOrdinal(url, stack);
270
+ this._push(url, this._getOrder(current, stack) ?? "forward", { stack, ordinal });
217
271
  }
218
272
 
219
273
  /**
220
274
  * Go back to a URL, as a back button does.
221
- * - The URL is an earlier page in `stack`: go back to it. When it is the entry just before the current one, this goes back in the browser history. Else it pushes the URL again at that page's depth.
222
- * - The URL is the root of `stack`: push it at depth 0.
275
+ * - The URL is an earlier page in `stack`: go back to it. When it is the entry just before the current one, this goes back in the browser history. Else it pushes the URL again at that page's ordinal.
276
+ * - The URL is the root of `stack`: push it at ordinal 0.
223
277
  * - Else push the URL in place of the top page of `stack`.
224
278
  * - It works when the app was opened at the current page, so a back button always has somewhere to go.
279
+ * - If the browser refuses to go back with the Navigation API, it uses `history.back()`.
225
280
  *
226
281
  * @param possible The destination URL, resolved against `base`.
227
282
  * @param stack Root path of the stack to go back in, or `null` for the floating stack. Defaults to the current stack.
228
283
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
229
284
  * @example nav.back("/profile");
230
- * @see https://shelving.cc/ui/NavigationStore/back
285
+ * @see https://shelving.cc/ui/NavigationSequence/back
231
286
  */
232
- back(possible: PossibleURL, stack: AbsolutePath | null = this.stack.value): void {
287
+ back(possible: PossibleURL, stack: AbsolutePath | null = this._stack): void {
233
288
  const url = requireURL(possible, this.base, this.back);
234
289
  const navigation = this._navigation;
235
290
  if (!navigation) {
236
291
  this._push(url, "back");
237
292
  return;
238
293
  }
239
- const current = this.stack.value;
294
+ const current = this._stack;
240
295
  const pages = this._getPages(stack);
241
296
  const page = pages.slice(0, -1).findLast(p => p.url.href === url.href);
242
297
  if (page && stack === current && page.index === (navigation.currentEntry?.index ?? 0) - 1) {
243
- navigation.traverseTo(page.key, { info: this._getOrder(current, stack) ?? "back" }).finished?.catch(BLACKHOLE);
298
+ // Some browsers refuse `traverseTo()` in some frames (Safari throws `SecurityError` in a sandboxed iframe), so fall back to `history.back()`.
299
+ const fallback = (e: unknown) => void (_isAbort(e) || window.history.back());
300
+ try {
301
+ const result = navigation.traverseTo(page.key, { info: this._getOrder(current, stack) ?? "back" });
302
+ result.committed?.catch(fallback);
303
+ result.finished?.catch(BLACKHOLE);
304
+ } catch (e) {
305
+ fallback(e);
306
+ }
244
307
  return;
245
308
  }
246
309
  // The URL is an earlier page in the stack, else the root of the stack, else it takes the place of the top page.
247
- const depth = page ? page.depth : this._getPath(url) === stack ? 0 : (pages.at(-1)?.depth ?? this._getBottomDepth(url, stack));
248
- this._push(url, this._getOrder(current, stack) ?? "back", { stack, depth });
310
+ const ordinal = page ? page.ordinal : this._getPath(url) === stack ? 0 : (pages.at(-1)?.ordinal ?? this._getBottomOrdinal(url, stack));
311
+ this._push(url, this._getOrder(current, stack) ?? "back", { stack, ordinal });
249
312
  }
250
313
 
251
314
  /**
252
315
  * Replace the current URL, with no transition.
253
- * - The page stays in the same stack, at the same depth, so a cached page stays mounted.
316
+ * - The page stays in the same stack, at the same ordinal, so a cached page stays mounted.
254
317
  * - Use it for a page that knows its canonical URL, or for in-page tabs.
255
318
  * - Pass a `stack` to move the page into that stack: at its root if the URL is the root, else on top of its pages. For example, a login page calls `replace("/home", "/home")`.
256
319
  *
@@ -258,9 +321,9 @@ export class NavigationStore extends URLStore {
258
321
  * @param stack Root path of the stack to move the page into, or `null` for the floating stack. Defaults to the current stack.
259
322
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
260
323
  * @example nav.replace("/login");
261
- * @see https://shelving.cc/ui/NavigationStore/replace
324
+ * @see https://shelving.cc/ui/NavigationSequence/replace
262
325
  */
263
- replace(possible: PossibleURL, stack: AbsolutePath | null = this.stack.value): void {
326
+ replace(possible: PossibleURL, stack: AbsolutePath | null = this._stack): void {
264
327
  const url = requireURL(possible, this.base, this.replace);
265
328
  const saved = this._navigation?.currentEntry?.getState();
266
329
  let state = _isEntryState(saved) ? saved : undefined;
@@ -268,14 +331,14 @@ export class NavigationStore extends URLStore {
268
331
  const top = this._getPages(stack)
269
332
  .filter(p => p.index !== this._navigation?.currentEntry?.index)
270
333
  .at(-1);
271
- state = { stack, depth: this._getPath(url) === stack ? 0 : top ? top.depth + 1 : this._getBottomDepth(url, stack) };
334
+ state = { stack, ordinal: this._getPath(url) === stack ? 0 : top ? top.ordinal + 1 : this._getBottomOrdinal(url, stack) };
272
335
  }
273
336
  this._write(() => window.history.replaceState(null, "", url.href), state);
274
337
  this._change(url, null, state?.stack);
275
338
  }
276
339
 
277
340
  /** Push a URL as a new history entry, with an optional state. */
278
- private _push(url: ImmutableURL, transition: TransitionType, state?: NavigationEntryState): void {
341
+ private _push(url: ImmutableURL, transition: NavigationDirection, state?: NavigationEntryState): void {
279
342
  this._write(() => window.history.pushState(null, "", url.href), state);
280
343
  this._change(url, this._navigation ? transition : null, state?.stack);
281
344
  }
@@ -302,45 +365,45 @@ export class NavigationStore extends URLStore {
302
365
  }
303
366
  }
304
367
 
305
- /** Set the stack first, then the URL, so both are ready when `<Navigation>` reads them. */
306
- private _change(url: PossibleURL, transition: TransitionType | null, stack?: AbsolutePath | null): void {
307
- this.transition = transition;
308
- if (stack !== undefined) this.stack.value = stack;
309
- this.value = url;
368
+ /** Record where history is now, and publish it as an event. */
369
+ private _change(url: PossibleURL, direction: NavigationDirection | null, stack?: AbsolutePath | null): void {
370
+ this._url = requireURL(url, this.base, this._change);
371
+ if (stack !== undefined) this._stack = stack;
372
+ this.resolve({ ...this.current(), direction: direction ?? undefined });
310
373
  }
311
374
 
312
- /** Get the pages in a stack, root first: the newest entry in the stack, then the newest earlier entry at a lower depth, down to depth 0. */
375
+ /** Get the pages in a stack, root first: the newest entry in the stack, then the newest earlier entry at a lower ordinal, down to ordinal 0. */
313
376
  private _getPages(stack: AbsolutePath | null): _Page[] {
314
377
  const navigation = this._navigation;
315
378
  if (!navigation) return [];
316
379
  const entries = navigation.entries();
317
380
  const pages: _Page[] = [];
318
- let depth = Number.POSITIVE_INFINITY;
381
+ let ordinal = Number.POSITIVE_INFINITY;
319
382
  const current = navigation.currentEntry?.index ?? -1;
320
- for (let i = current; i >= 0 && depth > 0; i--) {
383
+ for (let i = current; i >= 0 && ordinal > 0; i--) {
321
384
  const entry = entries[i];
322
385
  // The current entry may not have its state saved yet (before `listen()`), so use its default.
323
386
  const state = i === current && entry ? this._getState(entry) : entry?.getState();
324
- if (!entry?.url || !_isEntryState(state) || state.stack !== stack || state.depth >= depth) continue;
387
+ if (!entry?.url || !_isEntryState(state) || state.stack !== stack || state.ordinal >= ordinal) continue;
325
388
  const url = requireURL(entry.url, undefined, this._getPages);
326
389
  const path = this._getPath(url);
327
390
  if (!path) continue;
328
- depth = state.depth;
391
+ ordinal = state.ordinal;
329
392
  pages.unshift({ ...state, url, path, index: entry.index, key: entry.key });
330
393
  }
331
394
  return pages;
332
395
  }
333
396
 
334
- /** Get the saved state of an entry, or for an entry with none (for example the page the app opened at), the starting stack at its bottom depth. */
397
+ /** Get the saved state of an entry, or for an entry with none (for example the page the app opened at), the starting stack at its bottom ordinal. */
335
398
  private _getState(entry: NavigationHistoryEntry | null): NavigationEntryState {
336
399
  const state = entry?.getState();
337
400
  if (_isEntryState(state) && this._getStacks().includes(state.stack)) return state;
338
401
  const url = entry?.url ? requireURL(entry.url, undefined, this._getState) : undefined;
339
- return { stack: this._start, depth: url ? this._getBottomDepth(url, this._start) : 0 };
402
+ return { stack: this._start, ordinal: url ? this._getBottomOrdinal(url, this._start) : 0 };
340
403
  }
341
404
 
342
- /** Get the depth of a URL that is the first page of a stack: `0` for the stack's root path or for the floating stack, else `1` so the root stays below it. */
343
- private _getBottomDepth(url: ImmutableURL, stack: AbsolutePath | null): number {
405
+ /** Get the ordinal of a URL that is the first page of a stack: `0` for the stack's root path or for the floating stack, else `1` so the root stays below it. */
406
+ private _getBottomOrdinal(url: ImmutableURL, stack: AbsolutePath | null): number {
344
407
  return stack === null || this._getPath(url) === stack ? 0 : 1;
345
408
  }
346
409
 
@@ -354,19 +417,19 @@ export class NavigationStore extends URLStore {
354
417
  return matchURLPrefix(url, this.base ?? new URL("/", url));
355
418
  }
356
419
 
357
- /** Direction of a change the store did not make: tab order across stacks, else depth, else position. */
358
- private _getDirection(e: NavigationCurrentEntryChangeEvent): TransitionType | null {
420
+ /** Direction of a change the store did not make: tab order across stacks, else ordinal, else position. */
421
+ private _getDirection(e: NavigationCurrentEntryChangeEvent): NavigationDirection | null {
359
422
  if (e.navigationType !== "traverse") return null;
360
423
  const from = this._getState(e.from);
361
424
  const to = this._getState(this._navigation?.currentEntry ?? null);
362
425
  const order = this._getOrder(from.stack, to.stack);
363
426
  if (order) return order;
364
- if (to.depth !== from.depth) return to.depth < from.depth ? "back" : "forward";
427
+ if (to.ordinal !== from.ordinal) return to.ordinal < from.ordinal ? "back" : "forward";
365
428
  return (this._navigation?.currentEntry?.index ?? 0) < e.from.index ? "back" : "forward";
366
429
  }
367
430
 
368
431
  /** Slide direction between two stacks by tab order, or `undefined` for the same stack. */
369
- private _getOrder(from: AbsolutePath | null, to: AbsolutePath | null): TransitionType | undefined {
432
+ private _getOrder(from: AbsolutePath | null, to: AbsolutePath | null): NavigationDirection | undefined {
370
433
  if (from === to || from === null || to === null) return;
371
434
  const a = this.stacks.indexOf(from);
372
435
  const b = this.stacks.indexOf(to);
@@ -394,7 +457,12 @@ function _isEntryState(state: unknown): state is NavigationEntryState {
394
457
  state !== null &&
395
458
  "stack" in state &&
396
459
  (typeof state.stack === "string" || state.stack === null) &&
397
- "depth" in state &&
398
- typeof state.depth === "number"
460
+ "ordinal" in state &&
461
+ typeof state.ordinal === "number"
399
462
  );
400
463
  }
464
+
465
+ /** Is an error a navigation that was stopped by a newer one? That is not a failure, so it needs no fallback. */
466
+ function _isAbort(e: unknown): boolean {
467
+ return e instanceof Error && e.name === "AbortError";
468
+ }
@@ -7,8 +7,9 @@ import { type ReactNode } from "react";
7
7
  export interface RouteCacheProps {
8
8
  /**
9
9
  * Number of pages to keep mounted (but hidden), so the whole state of each one (scroll position, toggles, searches, form input, focus) is still there when you come back to it.
10
- * - The root page and the top page of each listed stack are never dropped, even past the limit, so a tab always shows the page you left and always has its root below.
10
+ * - The root page and the last page you saw in each listed stack are never dropped, even past the limit, so a tab always shows the page you left and always has its root below.
11
11
  * - Floating pages get no such protection.
12
+ * - Keep it at `2` or more, so a swipe-back can show the page below and still keep the page you are leaving.
12
13
  * - Set to `0` (or less) to turn the cache off and unmount each page as you leave it.
13
14
  *
14
15
  * @default 10
@@ -21,14 +22,14 @@ export interface RouteCacheProps {
21
22
  * Keep-alive page cache for the pages in the navigation stacks. Put it in a layout's content slot, around a `<Scroll vertical cover>` box.
22
23
  *
23
24
  * - Put a page transition around it, and a `<Scroll vertical cover>` inside it, so each kept page scrolls in its own box.
24
- * - Keeps each page in the stacks mounted but hidden (with React's `<Activity>`), so going back to a page, or switching back to a tab, shows it exactly as you left it.
25
- * - Each page is keyed by its stack and its depth in that stack, not by its URL. So `NavigationStore.replace()` (a canonical URL, an in-page tab) keeps the same page mounted, and the same URL open in two tabs is two separate pages.
26
- * - A page leaves the cache as soon as it leaves its stack: when you go back from it, or when a stack is popped to its root. After a browser back, a browser forward shows that page fresh.
27
- * - The root page and the top page of each listed stack are never dropped. Other pages, and every floating page, can be dropped past `maxCached`, and show fresh (from the top) when you come back to them.
25
+ * - Keeps each page mounted but hidden (with React's `<Activity>`), so going back to a page, or switching back to a tab, shows it exactly as you left it.
26
+ * - Each page is keyed by the `stack` and `ordinal` in `Meta`, not by its URL. So `NavigationSequence.replace()` (a canonical URL, an in-page tab) keeps the same page mounted, and the same URL open in two tabs is two separate pages.
27
+ * - It knows nothing about history. It only drops pages when it has more than `maxCached`: first the pages deeper than the current page in its stack (pages you went back from), then the least recently used. So after a back, a forward shows the page as you left it, and a cancelled swipe-back still has the page it started from.
28
+ * - The root page and the last page you saw in each listed stack are never dropped. Floating pages (stack `null`) get no such protection.
28
29
  * - When the current page is deeper than its stack's root and the root page is not cached (for example after a deep link), the root page is rendered hidden, so a swipe-back can show it.
29
- * - Each kept page is frozen under its own `<MetaContext>` and `NavigationPositionContext`, so the same `children` element renders a different page for each URL, and a hidden page never re-renders for another page's URL.
30
+ * - Each kept page is frozen under its own `<MetaContext>`, so the same `children` element renders a different page for each URL, and a hidden page never re-renders for another page's URL.
30
31
  * - `<Activity mode="hidden">` keeps a hidden page's state but unmounts its effects, so its subscriptions and timers pause and resume as it is hidden and shown.
31
- * - Without the browser Navigation API (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
32
+ * - With no `ordinal` in `Meta` (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
32
33
  *
33
34
  * @kind component
34
35
  * @see https://shelving.cc/ui/RouteCache
@@ -1,28 +1,27 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { Activity, use, useRef } from "react";
2
+ import { Activity, useRef } from "react";
3
3
  import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
4
4
  import { mergeMeta } from "../util/meta.js";
5
- import { NavigationPositionContext } from "./NavigationContext.js";
6
5
  /**
7
6
  * Keep-alive page cache for the pages in the navigation stacks. Put it in a layout's content slot, around a `<Scroll vertical cover>` box.
8
7
  *
9
8
  * - Put a page transition around it, and a `<Scroll vertical cover>` inside it, so each kept page scrolls in its own box.
10
- * - Keeps each page in the stacks mounted but hidden (with React's `<Activity>`), so going back to a page, or switching back to a tab, shows it exactly as you left it.
11
- * - Each page is keyed by its stack and its depth in that stack, not by its URL. So `NavigationStore.replace()` (a canonical URL, an in-page tab) keeps the same page mounted, and the same URL open in two tabs is two separate pages.
12
- * - A page leaves the cache as soon as it leaves its stack: when you go back from it, or when a stack is popped to its root. After a browser back, a browser forward shows that page fresh.
13
- * - The root page and the top page of each listed stack are never dropped. Other pages, and every floating page, can be dropped past `maxCached`, and show fresh (from the top) when you come back to them.
9
+ * - Keeps each page mounted but hidden (with React's `<Activity>`), so going back to a page, or switching back to a tab, shows it exactly as you left it.
10
+ * - Each page is keyed by the `stack` and `ordinal` in `Meta`, not by its URL. So `NavigationSequence.replace()` (a canonical URL, an in-page tab) keeps the same page mounted, and the same URL open in two tabs is two separate pages.
11
+ * - It knows nothing about history. It only drops pages when it has more than `maxCached`: first the pages deeper than the current page in its stack (pages you went back from), then the least recently used. So after a back, a forward shows the page as you left it, and a cancelled swipe-back still has the page it started from.
12
+ * - The root page and the last page you saw in each listed stack are never dropped. Floating pages (stack `null`) get no such protection.
14
13
  * - When the current page is deeper than its stack's root and the root page is not cached (for example after a deep link), the root page is rendered hidden, so a swipe-back can show it.
15
- * - Each kept page is frozen under its own `<MetaContext>` and `NavigationPositionContext`, so the same `children` element renders a different page for each URL, and a hidden page never re-renders for another page's URL.
14
+ * - Each kept page is frozen under its own `<MetaContext>`, so the same `children` element renders a different page for each URL, and a hidden page never re-renders for another page's URL.
16
15
  * - `<Activity mode="hidden">` keeps a hidden page's state but unmounts its effects, so its subscriptions and timers pause and resume as it is hidden and shown.
17
- * - Without the browser Navigation API (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
16
+ * - With no `ordinal` in `Meta` (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
18
17
  *
19
18
  * @kind component
20
19
  * @see https://shelving.cc/ui/RouteCache
21
20
  */
22
21
  export function RouteCache({ maxCached = 10, children }) {
23
- // Read the live URL and the position in the stacks; each navigation re-renders this with both.
22
+ // Read the page from meta; each navigation re-renders this with the new page.
24
23
  const meta = requireMetaURL();
25
- const position = use(NavigationPositionContext);
24
+ const { stack = null, ordinal } = meta;
26
25
  const mapRef = useRef(undefined);
27
26
  const usedRef = useRef(0);
28
27
  // Caching turned off: render the page directly, so it unmounts as soon as you leave it.
@@ -30,31 +29,29 @@ export function RouteCache({ maxCached = 10, children }) {
30
29
  return _jsx(MetaContext, { value: meta, children: children });
31
30
  // No stacks (server render, or no Navigation API): render only the current page.
32
31
  // It is still inside an `<Activity>`, so a server render has the same structure as the first render in the browser, and hydration matches.
33
- if (!position)
32
+ if (ordinal === undefined)
34
33
  return (_jsx(Activity, { mode: "visible", children: _jsx(MetaContext, { value: meta, children: children }) }));
35
34
  // Find (or make) the entry for the current page.
36
- const { stack, depth, tops } = position;
37
35
  const map = (mapRef.current ??= new Map());
38
- const key = `${stack} ${depth}`;
39
- const entry = map.get(key) ?? { node: null, used: 0, stack, depth };
36
+ const key = `${stack} ${ordinal}`;
37
+ const entry = map.get(key) ?? { node: null, used: 0, stack, ordinal };
40
38
  map.set(key, entry);
41
- // Snapshot the children under the live URL and position (frozen), so each kept page keeps rendering for the URL it last had.
42
- entry.node = _getNode(children, meta, position);
39
+ // Snapshot the children under the live meta (frozen), so each kept page keeps rendering for the URL it last had.
40
+ entry.node = _jsx(MetaContext, { value: meta, children: children });
43
41
  entry.used = ++usedRef.current;
44
42
  // A listed stack always has its root page below a deeper page, so render the root (hidden) if it is not cached.
45
43
  const rootKey = `${stack} 0`;
46
- if (stack !== null && depth > 0 && !map.has(rootKey)) {
47
- const rootMeta = { ...mergeMeta(meta, { url: stack, stack }, RouteCache), path: stack, params: {} };
48
- const rootPosition = { stack, depth: 0, tops, parent: undefined };
49
- map.set(rootKey, { node: _getNode(children, rootMeta, rootPosition), used: 0, stack, depth: 0 });
44
+ if (stack !== null && ordinal > 0 && !map.has(rootKey)) {
45
+ const rootMeta = { ...mergeMeta(meta, { url: stack, stack, ordinal: 0 }, RouteCache), path: stack, params: {} };
46
+ map.set(rootKey, { node: _jsx(MetaContext, { value: rootMeta, children: children }), used: 0, stack, ordinal: 0 });
50
47
  }
51
- // Drop the pages that have left their stack.
52
- for (const [k, { stack: s, depth: d }] of map)
53
- if (k !== key && !(d <= (tops.get(s) ?? -1)))
54
- map.delete(k);
55
- // Drop the least-recently-used pages past the limit, but never the current page, or the root or top page of a listed stack.
48
+ // Past the limit, drop pages: never the current page, a stack's root, or the last page seen in each listed stack.
49
+ const last = _getLastUsed(map);
50
+ const droppable = (k, e) => k !== key && (e.stack === null || (e.ordinal !== 0 && last.get(e.stack) !== k));
56
51
  while (map.size > maxCached) {
57
- const lru = _findLeastRecentlyUsed(map, (k, { stack: s, depth: d }) => k !== key && (s === null || (d !== 0 && tops.get(s) !== d)));
52
+ // First the pages deeper than the current page in its stack (pages you went back from), then the least recently used.
53
+ const lru = _findLeastRecentlyUsed(map, (k, e) => e.stack === stack && e.ordinal > ordinal && droppable(k, e)) ??
54
+ _findLeastRecentlyUsed(map, droppable);
58
55
  if (lru === undefined)
59
56
  break;
60
57
  map.delete(lru);
@@ -62,9 +59,17 @@ export function RouteCache({ maxCached = 10, children }) {
62
59
  // Render every cached page; only the current one is visible, the rest are kept alive but hidden.
63
60
  return Array.from(map, ([k, cached]) => (_jsx(Activity, { mode: k === key ? "visible" : "hidden", children: cached.node }, k)));
64
61
  }
65
- /** Freeze `children` under a URL and a position. */
66
- function _getNode(children, meta, position) {
67
- return (_jsx(NavigationPositionContext, { value: position, children: _jsx(MetaContext, { value: meta, children: children }) }));
62
+ /** Get the key of the most recently used page in each stack. */
63
+ function _getLastUsed(map) {
64
+ const last = new Map();
65
+ const used = new Map();
66
+ for (const [key, entry] of map) {
67
+ if (entry.used > (used.get(entry.stack) ?? -1)) {
68
+ used.set(entry.stack, entry.used);
69
+ last.set(entry.stack, key);
70
+ }
71
+ }
72
+ return last;
68
73
  }
69
74
  /** Find the key of the least-recently-used entry that may be dropped, or `undefined` if none may. */
70
75
  function _findLeastRecentlyUsed(map, droppable) {