shelving 1.320.0 → 1.321.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 (83) hide show
  1. package/docs/guides/building-with-shelving.md +26 -0
  2. package/docs/llms-full.txt +629 -257
  3. package/docs/ui/BackButton.md +75 -0
  4. package/docs/ui/BackButtonProps.md +21 -0
  5. package/docs/ui/ClickableProps.md +0 -2
  6. package/docs/ui/Head.md +2 -2
  7. package/docs/ui/HorizontalTransition.md +1 -1
  8. package/docs/ui/LinkClickable.md +0 -1
  9. package/docs/ui/Meta.md +3 -1
  10. package/docs/ui/Navigation.md +93 -37
  11. package/docs/ui/NavigationEntryState.md +22 -0
  12. package/docs/ui/NavigationPosition.md +24 -0
  13. package/docs/ui/NavigationPositionContext.md +8 -0
  14. package/docs/ui/NavigationProps.md +12 -2
  15. package/docs/ui/NavigationStore/back.md +6 -4
  16. package/docs/ui/NavigationStore/forward.md +6 -2
  17. package/docs/ui/NavigationStore/history.md +15 -0
  18. package/docs/ui/NavigationStore/listen.md +14 -0
  19. package/docs/ui/NavigationStore/replace.md +15 -0
  20. package/docs/ui/NavigationStore.md +100 -19
  21. package/docs/ui/RouteCache.md +72 -36
  22. package/docs/ui/RouteCacheProps.md +3 -3
  23. package/docs/ui/Router.md +4 -2
  24. package/docs/ui/StackButton.md +64 -0
  25. package/docs/ui/StackButtonProps.md +21 -0
  26. package/docs/ui/VerticalTransition.md +1 -1
  27. package/docs/ui/mergeMeta.md +2 -1
  28. package/docs/ui.md +13 -10
  29. package/package.json +1 -1
  30. package/ui/button/Clickable.d.ts +1 -3
  31. package/ui/button/Clickable.js +2 -2
  32. package/ui/button/Clickable.tsx +0 -4
  33. package/ui/page/Head.d.ts +2 -2
  34. package/ui/page/Head.js +9 -8
  35. package/ui/page/Head.tsx +8 -6
  36. package/ui/router/BackButton.d.ts +22 -0
  37. package/ui/router/BackButton.js +19 -0
  38. package/ui/router/BackButton.md +47 -0
  39. package/ui/router/BackButton.tsx +34 -0
  40. package/ui/router/Navigation.d.ts +22 -12
  41. package/ui/router/Navigation.js +67 -51
  42. package/ui/router/Navigation.md +84 -27
  43. package/ui/router/Navigation.test.tsx +27 -7
  44. package/ui/router/Navigation.tsx +90 -53
  45. package/ui/router/NavigationContext.d.ts +9 -1
  46. package/ui/router/NavigationContext.js +9 -0
  47. package/ui/router/NavigationContext.tsx +11 -1
  48. package/ui/router/NavigationStore.d.ts +126 -19
  49. package/ui/router/NavigationStore.js +301 -30
  50. package/ui/router/NavigationStore.md +82 -9
  51. package/ui/router/NavigationStore.test.ts +384 -0
  52. package/ui/router/NavigationStore.tsx +347 -30
  53. package/ui/router/RouteCache.d.ts +15 -22
  54. package/ui/router/RouteCache.js +36 -47
  55. package/ui/router/RouteCache.md +59 -16
  56. package/ui/router/RouteCache.tsx +55 -62
  57. package/ui/router/Router.d.ts +2 -1
  58. package/ui/router/Router.js +9 -14
  59. package/ui/router/Router.md +2 -1
  60. package/ui/router/Router.tsx +9 -20
  61. package/ui/router/StackButton.d.ts +24 -0
  62. package/ui/router/StackButton.js +35 -0
  63. package/ui/router/StackButton.md +34 -0
  64. package/ui/router/StackButton.tsx +44 -0
  65. package/ui/router/index.d.ts +2 -2
  66. package/ui/router/index.js +2 -2
  67. package/ui/router/index.ts +2 -2
  68. package/ui/transition/HorizontalTransition.md +1 -1
  69. package/ui/transition/VerticalTransition.md +1 -1
  70. package/ui/util/meta.d.ts +4 -1
  71. package/ui/util/meta.ts +4 -1
  72. package/docs/ui/NavigationStore/redirect.md +0 -12
  73. package/docs/ui/RouteConfig.md +0 -75
  74. package/docs/ui/RouteConfigProps.md +0 -24
  75. package/docs/ui/RouteContext.md +0 -6
  76. package/docs/ui/RouteState.md +0 -30
  77. package/ui/router/RouteConfig.d.ts +0 -28
  78. package/ui/router/RouteConfig.js +0 -30
  79. package/ui/router/RouteConfig.md +0 -42
  80. package/ui/router/RouteConfig.tsx +0 -44
  81. package/ui/router/RouteContext.d.ts +0 -22
  82. package/ui/router/RouteContext.js +0 -8
  83. package/ui/router/RouteContext.tsx +0 -26
@@ -1,66 +1,383 @@
1
+ import { Store } from "../../store/Store.js";
1
2
  import { URLStore } from "../../store/URLStore.js";
2
- import { type PossibleURL, requireURL } from "../../util/url.js";
3
+ import { BLACKHOLE } from "../../util/function.js";
4
+ import type { AbsolutePath } from "../../util/path.js";
5
+ import { type ImmutableURL, matchURLPrefix, type PossibleURL, requireURL } from "../../util/url.js";
3
6
  import type { TransitionType } from "../transition/util.js";
4
7
 
5
8
  /**
6
- * Store holding the current navigation URL and driving browser history.
9
+ * State that `NavigationStore` saves on each browser history entry.
7
10
  *
8
- * - Extends `URLStore`; the current location is its `value`.
9
- * - `forward()` pushes a new history entry; `redirect()` replaces the current one.
10
- * - `back()` pushes a new history entry like `forward()`, but `<Navigation>` animates it as a back transition.
11
- * - TODO: switch to the browser Navigation API when broadly supported.
11
+ * @see https://shelving.cc/ui/NavigationEntryState
12
+ */
13
+ export interface NavigationEntryState {
14
+ /** Root path of the stack this page is in. */
15
+ readonly stack: AbsolutePath;
16
+ /** Position of this page in its stack, where `0` is the root. */
17
+ readonly depth: number;
18
+ }
19
+
20
+ /**
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.
23
+ *
24
+ * @see https://shelving.cc/ui/NavigationPosition
25
+ */
26
+ export interface NavigationPosition extends NavigationEntryState {
27
+ /** Depth of the top page of each stack that has pages. */
28
+ readonly tops: { readonly [stack: AbsolutePath]: number };
29
+ /** The page before the current one in its stack, or `undefined` at the bottom of the stack. */
30
+ readonly parent: AbsolutePath | undefined;
31
+ }
32
+
33
+ /** One page in a stack: the entry that holds it, plus its saved state. */
34
+ interface _Page extends NavigationEntryState {
35
+ readonly url: ImmutableURL;
36
+ readonly path: AbsolutePath;
37
+ readonly index: number;
38
+ readonly key: string;
39
+ }
40
+
41
+ /** The parts of `Navigation` the store uses (so tests can pass a fake). */
42
+ type _Navigation = Pick<
43
+ Navigation,
44
+ "entries" | "currentEntry" | "traverseTo" | "updateCurrentEntry" | "addEventListener" | "removeEventListener"
45
+ >;
46
+
47
+ /**
48
+ * Store that holds the current navigation URL, drives browser history, and keeps a stack of pages for each tab.
49
+ *
50
+ * - Extends `URLStore`, so its `value` is the current URL.
51
+ * - 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. It only changes when the stack changes.
53
+ * - 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.
54
+ * - Owned by `<Navigation>`. Read it with `requireNavigation()`.
12
55
  *
13
56
  * @see https://shelving.cc/ui/NavigationStore
14
57
  */
15
58
  export class NavigationStore extends URLStore {
16
- /** Transition type of the next URL change. `null` means no transition. `<Navigation>` reads it, then sets it back to `"forward"`. */
17
- transition: TransitionType | null = "forward";
59
+ /** Root path of each stack, in tab order. A single-stack app has one root. */
60
+ readonly stacks: readonly AbsolutePath[];
61
+
62
+ /**
63
+ * Root path of the current stack.
64
+ * - Always set. With no `stacks`, it is `"/"`.
65
+ * - It starts at the `stack` given to the constructor (default `"/"`). Without the Navigation API, it stays there.
66
+ */
67
+ readonly stack: Store<AbsolutePath>;
68
+
69
+ /**
70
+ * Transition type of the most recent change, read by `<Navigation>` when the value changes.
71
+ * - `null` means no transition: a replace, a change the browser already animated (for example a swipe-back), or no Navigation API.
72
+ */
73
+ transition: TransitionType | null = null;
74
+
75
+ /** The browser Navigation API, or `undefined` when it is not available. */
76
+ private readonly _navigation: _Navigation | undefined;
77
+ /** Transition sent with the next navigation, and whether the browser animates it. */
78
+ private _info: TransitionType | null | undefined = undefined;
79
+ /** `true` while the store changes history itself, so it ignores the events that causes. */
80
+ private _busy = false;
18
81
 
19
- constructor(url: PossibleURL = typeof window === "undefined" ? "/" : window.location.href, base?: PossibleURL) {
82
+ /** Stack of the page the app opens at, when its history entry has no saved stack. */
83
+ private readonly _start: AbsolutePath;
84
+
85
+ constructor(
86
+ url: PossibleURL = typeof window === "undefined" ? "/" : window.location.href,
87
+ base?: PossibleURL,
88
+ stack: AbsolutePath = "/",
89
+ ...stacks: AbsolutePath[]
90
+ ) {
20
91
  super(url, base);
92
+ this.stacks = stacks.length ? stacks : ["/"];
93
+ this._start = stack;
94
+ this._navigation = _getNavigation();
95
+ this.stack = new Store<AbsolutePath>(this._navigation ? this._getState(this._navigation.currentEntry).stack : stack);
96
+ }
97
+
98
+ /**
99
+ * Where the app is now: the current stack and depth, and the top depth of each stack.
100
+ *
101
+ * @returns The position, or `undefined` without the Navigation API.
102
+ * @see https://shelving.cc/ui/NavigationStore/position
103
+ */
104
+ get position(): NavigationPosition | undefined {
105
+ if (!this._navigation) return undefined;
106
+ const { stack, depth } = this._getState(this._navigation.currentEntry);
107
+ const tops: { [stack: AbsolutePath]: number } = {};
108
+ for (const s of this._getStacks()) {
109
+ const top = this._getPages(s).at(-1);
110
+ if (top) tops[s] = top.depth;
111
+ }
112
+ return { stack, depth, tops, parent: this.history(stack).at(-2) };
113
+ }
114
+
115
+ /**
116
+ * Start listening to the browser (back, forward and swipe).
117
+ * - Saves the current stack and depth on the current history entry, if it has none.
118
+ * - `<Navigation>` calls it once, when it mounts.
119
+ *
120
+ * @returns A function that stops listening.
121
+ * @see https://shelving.cc/ui/NavigationStore/listen
122
+ */
123
+ listen(): () => void {
124
+ const navigation = this._navigation;
125
+ if (!navigation) {
126
+ if (typeof window === "undefined") return BLACKHOLE;
127
+ const onPopState = () => this._change(window.location.href, null);
128
+ window.addEventListener("popstate", onPopState);
129
+ return () => window.removeEventListener("popstate", onPopState);
130
+ }
131
+
132
+ // Save the state of the entry the app opened at.
133
+ const { currentEntry } = navigation;
134
+ if (currentEntry && !_isEntryState(currentEntry.getState())) this._update(this._getState(currentEntry));
135
+
136
+ const onNavigate = (e: NavigateEvent) => {
137
+ const info = e.info;
138
+ this._info = e.hasUAVisualTransition ? null : info === "forward" || info === "back" ? info : undefined;
139
+ };
140
+ const onChange = (e: NavigationCurrentEntryChangeEvent) => {
141
+ if (this._busy) return;
142
+ const entry = navigation.currentEntry;
143
+ if (!entry?.url) return;
144
+ // Another script replaced the entry with no state (for example `history.replaceState()`), so put the old state back.
145
+ if (e.navigationType === "replace" && !_isEntryState(entry.getState())) {
146
+ const from = e.from.getState();
147
+ if (_isEntryState(from)) this._update(from);
148
+ }
149
+ const info = this._info;
150
+ this._info = undefined;
151
+ this._change(entry.url, info === undefined ? this._getDirection(e) : info, this._getState(entry).stack);
152
+ };
153
+ navigation.addEventListener("navigate", onNavigate);
154
+ navigation.addEventListener("currententrychange", onChange);
155
+ return () => {
156
+ navigation.removeEventListener("navigate", onNavigate);
157
+ navigation.removeEventListener("currententrychange", onChange);
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Get the pages in a stack, root first, or every page in every stack.
163
+ * - Read from the browser history entries up to the current one.
164
+ * - A stack whose root entry is gone (the browser keeps a limited history) still starts with its root.
165
+ * - Without the Navigation API this is always empty.
166
+ *
167
+ * @param stack Root path of the stack. Defaults to the current stack.
168
+ * @returns Paths relative to the app root, each with its `?query`.
169
+ * @example nav.history("/home") // ["/home", "/home/post/2"]
170
+ * @see https://shelving.cc/ui/NavigationStore/history
171
+ */
172
+ history(stack: AbsolutePath = this.stack.value): AbsolutePath[] {
173
+ const pages = this._getPages(stack);
174
+ const paths = pages.map(p => _getPathWithQuery(p));
175
+ if (pages[0] && pages[0].depth > 0) paths.unshift(stack);
176
+ return paths;
21
177
  }
22
178
 
23
179
  /**
24
- * Navigate forward to a URL, pushing a new browser history entry.
180
+ * Go forward to a URL, as a link does.
181
+ * - The URL is the top page of `stack`: switch to that stack, at the same depth. This is a tab switch.
182
+ * - Else push the URL onto `stack`, one level deeper than its top page.
183
+ * - The URL you are already on: replace it instead.
184
+ * - A change of stack slides by tab order. Else it slides forward.
25
185
  *
26
186
  * @param possible The destination URL, resolved against `base`.
187
+ * @param stack Root path of the stack to go to. Defaults to the current stack.
27
188
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
28
189
  * @example nav.forward("/settings");
29
190
  * @see https://shelving.cc/ui/NavigationStore/forward
30
191
  */
31
- forward(possible: PossibleURL): void {
32
- this.transition = "forward";
33
- this.value = requireURL(possible, this.base, this.forward);
34
- window.history.pushState(null, "", this.value);
192
+ forward(possible: PossibleURL, stack: AbsolutePath = this.stack.value): void {
193
+ const url = requireURL(possible, this.base, this.forward);
194
+ if (!this._navigation) {
195
+ this._push(url, "forward");
196
+ return;
197
+ }
198
+ const current = this.stack.value;
199
+ if (stack === current && url.href === this.value.href) {
200
+ this.replace(url);
201
+ return;
202
+ }
203
+ const top = this._getPages(stack).at(-1);
204
+ const depth = top ? (top.url.href === url.href ? top.depth : top.depth + 1) : 0;
205
+ this._push(url, this._getOrder(current, stack) ?? "forward", { stack, depth });
35
206
  }
36
207
 
37
208
  /**
38
- * Redirect to a URL, replacing the current browser history entry.
209
+ * Go back to a URL, as a back button does.
210
+ * - 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.
211
+ * - The URL is the root of `stack`: push it at depth 0.
212
+ * - Else push the URL in place of the top page of `stack`.
213
+ * - It works when the app was opened at the current page, so a back button always has somewhere to go.
39
214
  *
40
215
  * @param possible The destination URL, resolved against `base`.
216
+ * @param stack Root path of the stack to go back in. Defaults to the current stack.
41
217
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
42
- * @example nav.redirect("/login");
43
- * @see https://shelving.cc/ui/NavigationStore/redirect
218
+ * @example nav.back("/profile");
219
+ * @see https://shelving.cc/ui/NavigationStore/back
44
220
  */
45
- redirect(possible: PossibleURL): void {
46
- this.transition = "forward";
47
- this.value = requireURL(possible, this.base, this.redirect);
48
- window.history.replaceState(null, "", this.value);
221
+ back(possible: PossibleURL, stack: AbsolutePath = this.stack.value): void {
222
+ const url = requireURL(possible, this.base, this.back);
223
+ const navigation = this._navigation;
224
+ if (!navigation) {
225
+ this._push(url, "back");
226
+ return;
227
+ }
228
+ const current = this.stack.value;
229
+ const pages = this._getPages(stack);
230
+ const page = pages.slice(0, -1).findLast(p => p.url.href === url.href);
231
+ if (page && stack === current && page.index === (navigation.currentEntry?.index ?? 0) - 1) {
232
+ navigation.traverseTo(page.key, { info: this._getOrder(current, stack) ?? "back" }).finished?.catch(BLACKHOLE);
233
+ return;
234
+ }
235
+ // The URL is an earlier page in the stack, else the root of the stack, else it takes the place of the top page.
236
+ const depth = page ? page.depth : this._getPath(url) === stack ? 0 : (pages.at(-1)?.depth ?? 0);
237
+ this._push(url, this._getOrder(current, stack) ?? "back", { stack, depth });
49
238
  }
50
239
 
51
240
  /**
52
- * Navigate back to a URL, pushing a new browser history entry with the `"back"` transition type.
53
- * - Use it for a "back to" link, so the page slides back, not forward.
54
- * - It does not go back in the browser history, so it also works when the page was opened directly.
241
+ * Replace the current URL, with no transition.
242
+ * - The page stays in the same stack, at the same depth, so a cached page stays mounted.
243
+ * - Use it for a page that knows its canonical URL, or for in-page tabs.
244
+ * - 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")`.
55
245
  *
56
246
  * @param possible The destination URL, resolved against `base`.
247
+ * @param stack Root path of the stack to move the page into. Defaults to the current stack.
57
248
  * @throws RequiredError If `possible` cannot be resolved to a valid URL.
58
- * @example nav.back("/profile");
59
- * @see https://shelving.cc/ui/NavigationStore/back
249
+ * @example nav.replace("/login");
250
+ * @see https://shelving.cc/ui/NavigationStore/replace
60
251
  */
61
- back(possible: PossibleURL): void {
62
- this.transition = "back";
63
- this.value = requireURL(possible, this.base, this.back);
64
- window.history.pushState(null, "", this.value);
252
+ replace(possible: PossibleURL, stack: AbsolutePath = this.stack.value): void {
253
+ const url = requireURL(possible, this.base, this.replace);
254
+ const saved = this._navigation?.currentEntry?.getState();
255
+ let state = _isEntryState(saved) ? saved : undefined;
256
+ if (state && stack !== state.stack) {
257
+ const top = this._getPages(stack)
258
+ .filter(p => p.index !== this._navigation?.currentEntry?.index)
259
+ .at(-1);
260
+ state = { stack, depth: this._getPath(url) === stack ? 0 : top ? top.depth + 1 : 0 };
261
+ }
262
+ this._write(() => window.history.replaceState(null, "", url.href), state);
263
+ this._change(url, null, state?.stack);
264
+ }
265
+
266
+ /** Push a URL as a new history entry, with an optional state. */
267
+ private _push(url: ImmutableURL, transition: TransitionType, state?: NavigationEntryState): void {
268
+ this._write(() => window.history.pushState(null, "", url.href), state);
269
+ this._change(url, this._navigation ? transition : null, state?.stack);
270
+ }
271
+
272
+ /** Change history and then save a state on the new entry, ignoring the events that causes. */
273
+ private _write(write: () => void, state: NavigationEntryState | undefined): void {
274
+ this._busy = true;
275
+ try {
276
+ write();
277
+ if (state) this._update(state);
278
+ } finally {
279
+ this._busy = false;
280
+ }
281
+ }
282
+
283
+ /** Save a state on the current entry. */
284
+ private _update(state: NavigationEntryState): void {
285
+ const busy = this._busy;
286
+ this._busy = true;
287
+ try {
288
+ this._navigation?.updateCurrentEntry({ state });
289
+ } finally {
290
+ this._busy = busy;
291
+ }
292
+ }
293
+
294
+ /** Set the stack first, then the URL, so both are ready when `<Navigation>` reads them. */
295
+ private _change(url: PossibleURL, transition: TransitionType | null, stack?: AbsolutePath): void {
296
+ this.transition = transition;
297
+ if (stack) this.stack.value = stack;
298
+ this.value = url;
299
+ }
300
+
301
+ /** 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. */
302
+ private _getPages(stack: AbsolutePath): _Page[] {
303
+ const navigation = this._navigation;
304
+ if (!navigation) return [];
305
+ const entries = navigation.entries();
306
+ const pages: _Page[] = [];
307
+ let depth = Number.POSITIVE_INFINITY;
308
+ const current = navigation.currentEntry?.index ?? -1;
309
+ for (let i = current; i >= 0 && depth > 0; i--) {
310
+ const entry = entries[i];
311
+ // The current entry may not have its state saved yet (before `listen()`), so use its default.
312
+ const state = i === current && entry ? this._getState(entry) : entry?.getState();
313
+ if (!entry?.url || !_isEntryState(state) || state.stack !== stack || state.depth >= depth) continue;
314
+ const url = requireURL(entry.url, undefined, this._getPages);
315
+ const path = this._getPath(url);
316
+ if (!path) continue;
317
+ depth = state.depth;
318
+ pages.unshift({ ...state, url, path, index: entry.index, key: entry.key });
319
+ }
320
+ return pages;
321
+ }
322
+
323
+ /** Get the saved state of an entry, or for an entry with none (the page the app opened at), the starting stack at depth 0. */
324
+ private _getState(entry: NavigationHistoryEntry | null): NavigationEntryState {
325
+ const state = entry?.getState();
326
+ if (_isEntryState(state) && this._getStacks().includes(state.stack)) return state;
327
+ return { stack: this._start, depth: 0 };
328
+ }
329
+
330
+ /** Get every stack a page can be in: the listed stacks, plus the unstacked `"/"` stack. */
331
+ private _getStacks(): AbsolutePath[] {
332
+ return Array.from(new Set([...this.stacks, this._start, "/" as const]));
333
+ }
334
+
335
+ /** Get the path of a URL relative to the app root, or `undefined` if it is outside the app. */
336
+ private _getPath(url: ImmutableURL): AbsolutePath | undefined {
337
+ return matchURLPrefix(url, this.base ?? new URL("/", url));
338
+ }
339
+
340
+ /** Direction of a change the store did not make: tab order across stacks, else depth, else position. */
341
+ private _getDirection(e: NavigationCurrentEntryChangeEvent): TransitionType | null {
342
+ if (e.navigationType !== "traverse") return null;
343
+ const from = this._getState(e.from);
344
+ const to = this._getState(this._navigation?.currentEntry ?? null);
345
+ const order = this._getOrder(from.stack, to.stack);
346
+ if (order) return order;
347
+ if (to.depth !== from.depth) return to.depth < from.depth ? "back" : "forward";
348
+ return (this._navigation?.currentEntry?.index ?? 0) < e.from.index ? "back" : "forward";
65
349
  }
350
+
351
+ /** Slide direction between two stacks by tab order, or `undefined` for the same stack. */
352
+ private _getOrder(from: AbsolutePath, to: AbsolutePath): TransitionType | undefined {
353
+ if (from === to) return;
354
+ const a = this.stacks.indexOf(from);
355
+ const b = this.stacks.indexOf(to);
356
+ if (a < 0 || b < 0) return;
357
+ return b > a ? "forward" : "back";
358
+ }
359
+ }
360
+
361
+ /** Get the browser Navigation API, or `undefined` if it is missing or unusable (for example in a sandboxed frame). */
362
+ function _getNavigation(): _Navigation | undefined {
363
+ if (typeof navigation === "undefined" || typeof window === "undefined") return;
364
+ if (!navigation.currentEntry) return;
365
+ return navigation;
366
+ }
367
+
368
+ /** Get a page's path with its `?query`. */
369
+ function _getPathWithQuery({ path, url }: _Page): AbsolutePath {
370
+ return `${path}${url.search}` as AbsolutePath;
371
+ }
372
+
373
+ /** Is a value a `NavigationEntryState`? */
374
+ function _isEntryState(state: unknown): state is NavigationEntryState {
375
+ return (
376
+ typeof state === "object" &&
377
+ state !== null &&
378
+ "stack" in state &&
379
+ typeof state.stack === "string" &&
380
+ "depth" in state &&
381
+ typeof state.depth === "number"
382
+ );
66
383
  }
@@ -1,38 +1,31 @@
1
1
  import { type ReactNode } from "react";
2
2
  /**
3
- * Props for `<RouteCache>` — the `maxCached` size and the content `children` to keep alive per URL.
3
+ * Props for `<RouteCache>`: the `maxCached` size and the content `children` to keep alive for each page in the stacks.
4
4
  *
5
5
  * @see https://shelving.cc/ui/RouteCacheProps
6
6
  */
7
7
  export interface RouteCacheProps {
8
8
  /**
9
- * Number of recently-visited URLs to keep mounted (but hidden) so the entire state of their subtree —
10
- * scroll position of every scroll container, open/closed toggles, in-progress searches, form inputs,
11
- * focus — is restored intact when navigating back or forward to them.
12
- * - Defaults to `10`. Once the limit is reached the least-recently-visited entry is unmounted.
13
- * - Set to `0` (or less) to disable caching and unmount the subtree as you leave each URL.
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 top page of each stack is never dropped, even past the limit, so a tab always shows the page you left.
11
+ * - Set to `0` (or less) to turn the cache off and unmount each page as you leave it.
12
+ *
13
+ * @default 10
14
14
  */
15
15
  readonly maxCached?: number | undefined;
16
- /** The content to render for the current URL and keep alive (hidden) for recently-visited URLs. */
16
+ /** The content to render for the current page and keep alive (hidden) for the other pages in the stacks. */
17
17
  readonly children: ReactNode;
18
18
  }
19
19
  /**
20
- * Keep-alive page cache keyed by the current URL — drop it into a layout around its scrolling content region.
20
+ * Keep-alive page cache for the pages in the navigation stacks. Drop it into a layout around its scrolling content region.
21
21
  *
22
- * - Reads the live URL from the surrounding `<Meta>` context and keeps up to `maxCached` recently-visited
23
- * pages mounted but hidden (via React's `<Activity>`), so navigating back/forward to a page restores its
24
- * entire DOM and component state — scroll position, toggles, searches, inputs, focus — untouched.
25
- * - Pages are kept in a least-recently-used map keyed by `path`; the oldest is unmounted past the limit.
26
- * - A page that owns other paths with `<RouteConfig path>` stays mounted when the URL changes to one of them.
27
- * - A page with `<RouteConfig cache={false}>` is dropped as soon as you leave it, so the next visit shows a new page.
28
- * - Each snapshot is frozen under its own `<MetaContext>`, so the same single `children` element resolves a
29
- * different page per path and a hidden page never re-renders for someone else's URL.
30
- * - `<Activity mode="hidden">` preserves a hidden page's state while unmounting its effects, so its
31
- * subscriptions/observers/timers pause and resume cleanly as it is hidden and shown.
32
- * - Because it wraps the scroll container itself (rather than sitting below it inside the router), the
33
- * scroll position of every cached page is preserved — surrounding chrome (sidebar, drawer state) stays
34
- * outside the cache, so it is neither duplicated nor remounted on navigation.
35
- * - When `maxCached <= 0` the page is rendered directly with no caching (it unmounts as you leave it).
22
+ * - 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.
23
+ * - 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.
24
+ * - 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.
25
+ * - The top page of each stack is never dropped. Other pages can be dropped past `maxCached`, and show fresh (from the top) when you come back to them.
26
+ * - 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.
27
+ * - `<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.
28
+ * - Without the browser Navigation API (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
36
29
  *
37
30
  * @kind component
38
31
  * @see https://shelving.cc/ui/RouteCache
@@ -1,74 +1,63 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { Activity, useRef } from "react";
3
- import { matchPathTemplate } from "../../util/template.js";
2
+ import { Activity, use, useRef } from "react";
4
3
  import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
5
- import { RouteContext } from "./RouteContext.js";
4
+ import { NavigationPositionContext } from "./NavigationContext.js";
6
5
  /**
7
- * Keep-alive page cache keyed by the current URL — drop it into a layout around its scrolling content region.
6
+ * Keep-alive page cache for the pages in the navigation stacks. Drop it into a layout around its scrolling content region.
8
7
  *
9
- * - Reads the live URL from the surrounding `<Meta>` context and keeps up to `maxCached` recently-visited
10
- * pages mounted but hidden (via React's `<Activity>`), so navigating back/forward to a page restores its
11
- * entire DOM and component state — scroll position, toggles, searches, inputs, focus — untouched.
12
- * - Pages are kept in a least-recently-used map keyed by `path`; the oldest is unmounted past the limit.
13
- * - A page that owns other paths with `<RouteConfig path>` stays mounted when the URL changes to one of them.
14
- * - A page with `<RouteConfig cache={false}>` is dropped as soon as you leave it, so the next visit shows a new page.
15
- * - Each snapshot is frozen under its own `<MetaContext>`, so the same single `children` element resolves a
16
- * different page per path and a hidden page never re-renders for someone else's URL.
17
- * - `<Activity mode="hidden">` preserves a hidden page's state while unmounting its effects, so its
18
- * subscriptions/observers/timers pause and resume cleanly as it is hidden and shown.
19
- * - Because it wraps the scroll container itself (rather than sitting below it inside the router), the
20
- * scroll position of every cached page is preserved — surrounding chrome (sidebar, drawer state) stays
21
- * outside the cache, so it is neither duplicated nor remounted on navigation.
22
- * - When `maxCached <= 0` the page is rendered directly with no caching (it unmounts as you leave it).
8
+ * - 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.
9
+ * - 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.
10
+ * - 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.
11
+ * - The top page of each stack is never dropped. Other pages can be dropped past `maxCached`, and show fresh (from the top) when you come back to them.
12
+ * - 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.
13
+ * - `<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.
14
+ * - Without the browser Navigation API (older browsers, server renders), or with `maxCached` of `0`, it renders the current page directly with no cache.
23
15
  *
24
16
  * @kind component
25
17
  * @see https://shelving.cc/ui/RouteCache
26
18
  */
27
19
  export function RouteCache({ maxCached = 10, children }) {
28
- // Read the live URL from context; each navigation re-renders this with the new path.
20
+ // Read the live URL and the position in the stacks; each navigation re-renders this with both.
29
21
  const meta = requireMetaURL();
22
+ const position = use(NavigationPositionContext);
30
23
  const mapRef = useRef(undefined);
31
24
  const usedRef = useRef(0);
32
- // Caching disabled — render the page directly so it unmounts as soon as you leave it.
25
+ // Caching turned off: render the page directly, so it unmounts as soon as you leave it.
33
26
  if (maxCached <= 0)
34
27
  return _jsx(MetaContext, { value: meta, children: children });
35
- // Find the page for this path: its own entry, else the most recent page that owns the path with `<RouteConfig path>`.
28
+ // No stacks (server render, or no Navigation API): render only the current page.
29
+ // It is still inside an `<Activity>`, so a server render has the same structure as the first render in the browser, and hydration matches.
30
+ if (!position)
31
+ return (_jsx(Activity, { mode: "visible", children: _jsx(MetaContext, { value: meta, children: children }) }));
32
+ // Find (or make) the entry for the current page.
33
+ const { stack, depth, tops } = position;
36
34
  const map = (mapRef.current ??= new Map());
37
- const key = map.has(meta.path) ? meta.path : (_findOwner(map, meta.path) ?? meta.path);
38
- const entry = map.get(key) ?? { node: null, used: 0, state: {} };
35
+ const key = `${stack} ${depth}`;
36
+ const entry = map.get(key) ?? { node: null, used: 0, stack, depth };
39
37
  map.set(key, entry);
40
- // Snapshot the children under the live URL (frozen) so each kept-alive copy keeps rendering for the URL
41
- // it was captured at — the same `children` element resolves a different page per path.
42
- entry.node = (_jsx(RouteContext, { value: entry.state, children: _jsx(MetaContext, { value: meta, children: children }) }));
38
+ // Snapshot the children under the live URL (frozen), so each kept page keeps rendering for the URL it last had.
39
+ entry.node = _jsx(MetaContext, { value: meta, children: children });
43
40
  entry.used = ++usedRef.current;
44
- // Drop the pages that ask not to be cached (`<RouteConfig cache={false}>`) once they are not the current page.
45
- for (const [k, { state }] of map)
46
- if (k !== key && state.cache === false)
41
+ // Drop the pages that have left their stack.
42
+ for (const [k, { stack: s, depth: d }] of map)
43
+ if (k !== key && !(d <= (tops[s] ?? -1)))
47
44
  map.delete(k);
48
- // Evict the least-recently-used pages beyond the limit.
49
- while (map.size > maxCached)
50
- map.delete(_findLeastRecentlyUsed(map));
45
+ // Drop the least-recently-used pages past the limit, but never the current page or the top page of a stack.
46
+ while (map.size > maxCached) {
47
+ const lru = _findLeastRecentlyUsed(map, (k, { stack: s, depth: d }) => k !== key && tops[s] !== d);
48
+ if (lru === undefined)
49
+ break;
50
+ map.delete(lru);
51
+ }
51
52
  // Render every cached page; only the current one is visible, the rest are kept alive but hidden.
52
53
  return Array.from(map, ([k, cached]) => (_jsx(Activity, { mode: k === key ? "visible" : "hidden", children: cached.node }, k)));
53
54
  }
54
- /** Find the key of the most-recently-used entry whose `<RouteConfig path>` owns a path, or `undefined` if none does. */
55
- function _findOwner(map, path) {
56
- let ownerKey;
57
- let ownerUsed = Number.NEGATIVE_INFINITY;
58
- for (const [key, { state, used }] of map) {
59
- if (state.path && used > ownerUsed && matchPathTemplate(state.path, path)) {
60
- ownerUsed = used;
61
- ownerKey = key;
62
- }
63
- }
64
- return ownerKey;
65
- }
66
- /** Find the key of the least-recently-used (lowest `used` tick) entry in the cache map. */
67
- function _findLeastRecentlyUsed(map) {
55
+ /** Find the key of the least-recently-used entry that may be dropped, or `undefined` if none may. */
56
+ function _findLeastRecentlyUsed(map, droppable) {
68
57
  let lruKey;
69
58
  let lruUsed = Number.POSITIVE_INFINITY;
70
59
  for (const [key, entry] of map) {
71
- if (entry.used < lruUsed) {
60
+ if (entry.used < lruUsed && droppable(key, entry)) {
72
61
  lruUsed = entry.used;
73
62
  lruKey = key;
74
63
  }