shelving 1.297.1 → 1.298.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shelving",
3
- "version": "1.297.1",
3
+ "version": "1.298.0",
4
4
  "author": "Dave Houlbrooke <dave@shax.com>",
5
5
  "repository": {
6
6
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { XMarkIcon } from "@heroicons/react/24/solid";
3
- import { memo, Suspense, startTransition, useLayoutEffect, useRef, ViewTransition } from "react";
3
+ import { memo, Suspense, startTransition, ViewTransition } from "react";
4
4
  import { getButtonClass } from "../button/Button.js";
5
5
  import { getClass, getModuleClass } from "../util/css.js";
6
6
  import "../transition/FadeTransition.css";
@@ -18,12 +18,7 @@ import styles from "./Dialog.module.css";
18
18
  * @see https://shelving.cc/ui/Dialog
19
19
  */
20
20
  export const Dialog = memo(({ children, onClose, ...props }) => {
21
- const ref = useRef(null);
22
- // Open in a layout effect, not a passive effect. React runs layout effects inside the view transition's update, so the new snapshot shows the open dialog.
23
- useLayoutEffect(() => {
24
- ref.current?.showModal();
25
- }, []);
26
- return (_jsx(Suspense, { fallback: null, children: _jsx(ViewTransition, { enter: "fade", exit: "fade", children: _jsxs("dialog", { ref: ref, className: getModuleClass(styles, "dialog"), onClick: _closeOnBackdropClick, onCancel: e => {
21
+ return (_jsx(Suspense, { fallback: null, children: _jsx(ViewTransition, { enter: "fade", exit: "fade", children: _jsxs("dialog", { ref: _showModal, className: getModuleClass(styles, "dialog"), onClick: _closeOnBackdropClick, onCancel: e => {
27
22
  // Keep the dialog open and let the parent unmount it in a transition. An uncancelable request closes natively and fires `onClose` from the `close` event.
28
23
  if (!onClose || !e.cancelable)
29
24
  return;
@@ -31,6 +26,15 @@ export const Dialog = memo(({ children, onClose, ...props }) => {
31
26
  startTransition(() => onClose());
32
27
  }, onClose: onClose, ...props, children: [_jsx("div", { className: getModuleClass(styles, "content"), children: children }), _jsx("div", { className: getModuleClass(styles, "close"), children: _jsx(DialogCloseButton, {}) })] }) }) }));
33
28
  });
29
+ /**
30
+ * Open a `<dialog>` as a modal when React attaches it.
31
+ * - A ref callback, not a layout effect. React holds the layout effects of a view transition until its images are ready, and an image in a closed `<dialog>` is never ready, so a layout effect would never open a dialog with an image in it.
32
+ * - The ref callback still runs inside the view transition's update, so the new snapshot shows the open dialog.
33
+ */
34
+ function _showModal(dialog) {
35
+ if (dialog && !dialog.open)
36
+ dialog.showModal();
37
+ }
34
38
  /** When the user clicks anywhere on a `<dialog>` element (and the click isn't on a link etc), then close the dialog. */
35
39
  function _closeOnBackdropClick({ currentTarget, target }) {
36
40
  // Close the dialog when clicking on the dialog itself (but not its children).
@@ -1,5 +1,5 @@
1
1
  import { XMarkIcon } from "@heroicons/react/24/solid";
2
- import { type MouseEvent, memo, type ReactElement, Suspense, startTransition, useLayoutEffect, useRef, ViewTransition } from "react";
2
+ import { type MouseEvent, memo, type ReactElement, Suspense, startTransition, ViewTransition } from "react";
3
3
  import type { Callback } from "../../util/function.js";
4
4
  import { type ButtonVariants, getButtonClass } from "../button/Button.js";
5
5
  import { getClass, getModuleClass } from "../util/css.js";
@@ -30,20 +30,13 @@ export interface DialogProps extends OptionalChildProps {
30
30
  * @see https://shelving.cc/ui/Dialog
31
31
  */
32
32
  export const Dialog = memo(({ children, onClose, ...props }: DialogProps) => {
33
- const ref = useRef<HTMLDialogElement>(null);
34
-
35
- // Open in a layout effect, not a passive effect. React runs layout effects inside the view transition's update, so the new snapshot shows the open dialog.
36
- useLayoutEffect(() => {
37
- ref.current?.showModal();
38
- }, []);
39
-
40
33
  return (
41
34
  <Suspense fallback={null}>
42
35
  {/* The transition must wrap the `<dialog>`: React only animates a `<ViewTransition>` that comes before any DOM element in the inserted or deleted tree. Fade only on enter and exit, so an open dialog stays still while another dialog opens or closes. */}
43
36
  <ViewTransition enter="fade" exit="fade">
44
37
  {/** biome-ignore lint/a11y/useKeyWithClickEvents: Dialogs also show a close button. */}
45
38
  <dialog
46
- ref={ref}
39
+ ref={_showModal}
47
40
  className={getModuleClass(styles, "dialog")}
48
41
  onClick={_closeOnBackdropClick}
49
42
  onCancel={e => {
@@ -65,6 +58,15 @@ export const Dialog = memo(({ children, onClose, ...props }: DialogProps) => {
65
58
  );
66
59
  });
67
60
 
61
+ /**
62
+ * Open a `<dialog>` as a modal when React attaches it.
63
+ * - A ref callback, not a layout effect. React holds the layout effects of a view transition until its images are ready, and an image in a closed `<dialog>` is never ready, so a layout effect would never open a dialog with an image in it.
64
+ * - The ref callback still runs inside the view transition's update, so the new snapshot shows the open dialog.
65
+ */
66
+ function _showModal(dialog: HTMLDialogElement | null): void {
67
+ if (dialog && !dialog.open) dialog.showModal();
68
+ }
69
+
68
70
  /** When the user clicks anywhere on a `<dialog>` element (and the click isn't on a link etc), then close the dialog. */
69
71
  function _closeOnBackdropClick({ currentTarget, target }: MouseEvent<HTMLDialogElement>): void {
70
72
  // Close the dialog when clicking on the dialog itself (but not its children).
@@ -23,6 +23,7 @@ export interface RouteCacheProps {
23
23
  * pages mounted but hidden (via React's `<Activity>`), so navigating back/forward to a page restores its
24
24
  * entire DOM and component state — scroll position, toggles, searches, inputs, focus — untouched.
25
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 `<RoutePath>` stays mounted when the URL changes to one of them.
26
27
  * - Each snapshot is frozen under its own `<MetaContext>`, so the same single `children` element resolves a
27
28
  * different page per path and a hidden page never re-renders for someone else's URL.
28
29
  * - `<Activity mode="hidden">` preserves a hidden page's state while unmounting its effects, so its
@@ -1,6 +1,8 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Activity, useRef } from "react";
3
+ import { matchPathTemplate } from "../../util/template.js";
3
4
  import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
5
+ import { RouteContext } from "./RouteContext.js";
4
6
  /**
5
7
  * Keep-alive page cache keyed by the current URL — drop it into a layout around its scrolling content region.
6
8
  *
@@ -8,6 +10,7 @@ import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
8
10
  * pages mounted but hidden (via React's `<Activity>`), so navigating back/forward to a page restores its
9
11
  * entire DOM and component state — scroll position, toggles, searches, inputs, focus — untouched.
10
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 `<RoutePath>` stays mounted when the URL changes to one of them.
11
14
  * - Each snapshot is frozen under its own `<MetaContext>`, so the same single `children` element resolves a
12
15
  * different page per path and a hidden page never re-renders for someone else's URL.
13
16
  * - `<Activity mode="hidden">` preserves a hidden page's state while unmounting its effects, so its
@@ -25,28 +28,35 @@ export function RouteCache({ maxCached = 10, children }) {
25
28
  const meta = requireMetaURL();
26
29
  const mapRef = useRef(undefined);
27
30
  const usedRef = useRef(0);
28
- // Snapshot the children under the live URL (frozen) so each kept-alive copy keeps rendering for the URL
29
- // it was captured at — the same `children` element resolves a different page per path.
30
- const node = _jsx(MetaContext, { value: meta, children: children });
31
31
  // Caching disabled — render the page directly so it unmounts as soon as you leave it.
32
32
  if (maxCached <= 0)
33
- return node;
34
- // Insert or refresh the current page, then evict the least-recently-used pages beyond the limit.
35
- const { path } = meta;
33
+ return _jsx(MetaContext, { value: meta, children: children });
34
+ // Find the page for this path: its own entry, else the most recent page that owns the path with `<RoutePath>`.
36
35
  const map = (mapRef.current ??= new Map());
37
- const used = ++usedRef.current;
38
- const entry = map.get(path);
39
- if (entry) {
40
- entry.node = node;
41
- entry.used = used;
42
- }
43
- else {
44
- map.set(path, { node, used });
45
- }
36
+ const key = map.has(meta.path) ? meta.path : (_findOwner(map, meta.path) ?? meta.path);
37
+ const entry = map.get(key) ?? { node: null, used: 0, state: {} };
38
+ map.set(key, entry);
39
+ // Snapshot the children under the live URL (frozen) so each kept-alive copy keeps rendering for the URL
40
+ // it was captured at — the same `children` element resolves a different page per path.
41
+ entry.node = (_jsx(RouteContext, { value: entry.state, children: _jsx(MetaContext, { value: meta, children: children }) }));
42
+ entry.used = ++usedRef.current;
43
+ // Evict the least-recently-used pages beyond the limit.
46
44
  while (map.size > maxCached)
47
45
  map.delete(_findLeastRecentlyUsed(map));
48
- // Render every cached page; only the current `path` is visible, the rest are kept alive but hidden.
49
- return Array.from(map, ([key, cached]) => (_jsx(Activity, { mode: key === path ? "visible" : "hidden", children: cached.node }, key)));
46
+ // Render every cached page; only the current one is visible, the rest are kept alive but hidden.
47
+ return Array.from(map, ([k, cached]) => (_jsx(Activity, { mode: k === key ? "visible" : "hidden", children: cached.node }, k)));
48
+ }
49
+ /** Find the key of the most-recently-used entry whose `<RoutePath>` owns a path, or `undefined` if none does. */
50
+ function _findOwner(map, path) {
51
+ let ownerKey;
52
+ let ownerUsed = Number.NEGATIVE_INFINITY;
53
+ for (const [key, { state, used }] of map) {
54
+ if (state.path && used > ownerUsed && matchPathTemplate(state.path, path)) {
55
+ ownerUsed = used;
56
+ ownerKey = key;
57
+ }
58
+ }
59
+ return ownerKey;
50
60
  }
51
61
  /** Find the key of the least-recently-used (lowest `used` tick) entry in the cache map. */
52
62
  function _findLeastRecentlyUsed(map) {
@@ -7,6 +7,7 @@ Shelving's `<SidebarLayout>` and `<CenteredLayout>` already wrap their scrollabl
7
7
  **Things to know:**
8
8
 
9
9
  - Pages are kept in a least-recently-used map keyed by `path`. Once `maxCached` pages are retained the least-recently-visited one is unmounted (and loses its state). A never-seen or evicted page mounts fresh at the top.
10
+ - A page can own other paths with `<RoutePath>`, for example its tabs (`/dave/{tab}`). A navigation to one of those paths keeps the same page mounted: it keeps its scroll and state, and a `<ViewTransition>` around the page does not slide.
10
11
  - Pass `maxCached={0}` (or less) to disable caching entirely — the page renders directly and unmounts as soon as you leave it.
11
12
  - `<Activity mode="hidden">` preserves a hidden page's *state* while unmounting its *effects*, so subscriptions, observers (e.g. infinite-scroll), and timers pause and resume cleanly as the page is hidden and shown.
12
13
  - Each snapshot is frozen under its own `<Meta>` context, so the same single `children` element resolves a different page per path and a hidden page never re-renders for someone else's URL.
@@ -1,11 +1,14 @@
1
1
  import { Activity, type ReactNode, useRef } from "react";
2
2
  import type { AbsolutePath } from "../../util/path.js";
3
+ import { matchPathTemplate } from "../../util/template.js";
3
4
  import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
5
+ import { RouteContext, type RouteState } from "./RouteContext.js";
4
6
 
5
7
  /** A cached page: the rendered node plus a monotonic `used` tick for least-recently-used eviction. */
6
8
  interface CacheEntry {
7
9
  node: ReactNode;
8
10
  used: number;
11
+ readonly state: RouteState;
9
12
  }
10
13
 
11
14
  /**
@@ -33,6 +36,7 @@ export interface RouteCacheProps {
33
36
  * pages mounted but hidden (via React's `<Activity>`), so navigating back/forward to a page restores its
34
37
  * entire DOM and component state — scroll position, toggles, searches, inputs, focus — untouched.
35
38
  * - Pages are kept in a least-recently-used map keyed by `path`; the oldest is unmounted past the limit.
39
+ * - A page that owns other paths with `<RoutePath>` stays mounted when the URL changes to one of them.
36
40
  * - Each snapshot is frozen under its own `<MetaContext>`, so the same single `children` element resolves a
37
41
  * different page per path and a hidden page never re-renders for someone else's URL.
38
42
  * - `<Activity mode="hidden">` preserves a hidden page's state while unmounting its effects, so its
@@ -51,34 +55,48 @@ export function RouteCache({ maxCached = 10, children }: RouteCacheProps): React
51
55
  const mapRef = useRef<Map<AbsolutePath, CacheEntry>>(undefined);
52
56
  const usedRef = useRef(0);
53
57
 
54
- // Snapshot the children under the live URL (frozen) so each kept-alive copy keeps rendering for the URL
55
- // it was captured at — the same `children` element resolves a different page per path.
56
- const node = <MetaContext value={meta}>{children}</MetaContext>;
57
-
58
58
  // Caching disabled — render the page directly so it unmounts as soon as you leave it.
59
- if (maxCached <= 0) return node;
59
+ if (maxCached <= 0) return <MetaContext value={meta}>{children}</MetaContext>;
60
60
 
61
- // Insert or refresh the current page, then evict the least-recently-used pages beyond the limit.
62
- const { path } = meta;
61
+ // Find the page for this path: its own entry, else the most recent page that owns the path with `<RoutePath>`.
63
62
  const map = (mapRef.current ??= new Map());
64
- const used = ++usedRef.current;
65
- const entry = map.get(path);
66
- if (entry) {
67
- entry.node = node;
68
- entry.used = used;
69
- } else {
70
- map.set(path, { node, used });
71
- }
63
+ const key = map.has(meta.path) ? meta.path : (_findOwner(map, meta.path) ?? meta.path);
64
+ const entry = map.get(key) ?? { node: null, used: 0, state: {} };
65
+ map.set(key, entry);
66
+
67
+ // Snapshot the children under the live URL (frozen) so each kept-alive copy keeps rendering for the URL
68
+ // it was captured at — the same `children` element resolves a different page per path.
69
+ entry.node = (
70
+ <RouteContext value={entry.state}>
71
+ <MetaContext value={meta}>{children}</MetaContext>
72
+ </RouteContext>
73
+ );
74
+ entry.used = ++usedRef.current;
75
+
76
+ // Evict the least-recently-used pages beyond the limit.
72
77
  while (map.size > maxCached) map.delete(_findLeastRecentlyUsed(map));
73
78
 
74
- // Render every cached page; only the current `path` is visible, the rest are kept alive but hidden.
75
- return Array.from(map, ([key, cached]) => (
76
- <Activity key={key} mode={key === path ? "visible" : "hidden"}>
79
+ // Render every cached page; only the current one is visible, the rest are kept alive but hidden.
80
+ return Array.from(map, ([k, cached]) => (
81
+ <Activity key={k} mode={k === key ? "visible" : "hidden"}>
77
82
  {cached.node}
78
83
  </Activity>
79
84
  ));
80
85
  }
81
86
 
87
+ /** Find the key of the most-recently-used entry whose `<RoutePath>` owns a path, or `undefined` if none does. */
88
+ function _findOwner(map: Map<AbsolutePath, CacheEntry>, path: AbsolutePath): AbsolutePath | undefined {
89
+ let ownerKey: AbsolutePath | undefined;
90
+ let ownerUsed = Number.NEGATIVE_INFINITY;
91
+ for (const [key, { state, used }] of map) {
92
+ if (state.path && used > ownerUsed && matchPathTemplate(state.path, path)) {
93
+ ownerUsed = used;
94
+ ownerKey = key;
95
+ }
96
+ }
97
+ return ownerKey;
98
+ }
99
+
82
100
  /** Find the key of the least-recently-used (lowest `used` tick) entry in the cache map. */
83
101
  function _findLeastRecentlyUsed(map: Map<AbsolutePath, CacheEntry>): AbsolutePath {
84
102
  let lruKey!: AbsolutePath;
@@ -0,0 +1,20 @@
1
+ import type { AbsolutePath } from "../../util/path.js";
2
+ /**
3
+ * The route state of one page, shared by `<Router>`, `<RouteCache>` and `<RoutePath>`.
4
+ * - `path` is the template of the paths the page owns, set by `<RoutePath>`.
5
+ * - `cache` is the page's `<RouteCache>` entry, so `<RoutePath>` in a top-level page also tells the cache.
6
+ * - `router` marks a state made by `<Router>`, so a nested router does not pass the cache entry on.
7
+ *
8
+ * @see https://shelving.cc/ui/RouteState
9
+ */
10
+ export interface RouteState {
11
+ path?: AbsolutePath | undefined;
12
+ readonly cache?: RouteState | undefined;
13
+ readonly router?: true | undefined;
14
+ }
15
+ /**
16
+ * React context holding the `RouteState` of the current page, provided by `<Router>` and `<RouteCache>`.
17
+ *
18
+ * @see https://shelving.cc/ui/RouteContext
19
+ */
20
+ export declare const RouteContext: import("react").Context<RouteState | undefined>;
@@ -0,0 +1,8 @@
1
+ import { createContext } from "react";
2
+ /**
3
+ * React context holding the `RouteState` of the current page, provided by `<Router>` and `<RouteCache>`.
4
+ *
5
+ * @see https://shelving.cc/ui/RouteContext
6
+ */
7
+ export const RouteContext = createContext(undefined);
8
+ RouteContext.displayName = "RouteContext";
@@ -0,0 +1,24 @@
1
+ import { createContext } from "react";
2
+ import type { AbsolutePath } from "../../util/path.js";
3
+
4
+ /**
5
+ * The route state of one page, shared by `<Router>`, `<RouteCache>` and `<RoutePath>`.
6
+ * - `path` is the template of the paths the page owns, set by `<RoutePath>`.
7
+ * - `cache` is the page's `<RouteCache>` entry, so `<RoutePath>` in a top-level page also tells the cache.
8
+ * - `router` marks a state made by `<Router>`, so a nested router does not pass the cache entry on.
9
+ *
10
+ * @see https://shelving.cc/ui/RouteState
11
+ */
12
+ export interface RouteState {
13
+ path?: AbsolutePath | undefined;
14
+ readonly cache?: RouteState | undefined;
15
+ readonly router?: true | undefined;
16
+ }
17
+
18
+ /**
19
+ * React context holding the `RouteState` of the current page, provided by `<Router>` and `<RouteCache>`.
20
+ *
21
+ * @see https://shelving.cc/ui/RouteContext
22
+ */
23
+ export const RouteContext = createContext<RouteState | undefined>(undefined);
24
+ RouteContext.displayName = "RouteContext";
@@ -0,0 +1,24 @@
1
+ import { type ReactNode } from "react";
2
+ import type { AbsolutePath } from "../../util/path.js";
3
+ /**
4
+ * Props for `<RoutePath>` — the path template the page owns, and the page content.
5
+ *
6
+ * @see https://shelving.cc/ui/RoutePathProps
7
+ */
8
+ export interface RoutePathProps {
9
+ /** Path template the page owns, for example `/dave/{tab}`. Every path that matches it shows this same page. */
10
+ readonly path: AbsolutePath;
11
+ /** The page content. */
12
+ readonly children?: ReactNode;
13
+ }
14
+ /**
15
+ * Tell the surrounding `<Router>` (and `<RouteCache>`) that this page owns every path that matches a template.
16
+ * - A navigation to a path the page owns keeps the same page mounted, so it keeps its scroll and state,
17
+ * and a `<ViewTransition>` around the page does not run an enter or exit. The page updates for the new URL.
18
+ * - Use it for a page whose tabs each have their own path: `<RoutePath path="/dave/{tab}">`.
19
+ * - Put the real values in the template. `/{name}/{tab}` would make every person's profile one page.
20
+ *
21
+ * @kind component
22
+ * @see https://shelving.cc/ui/RoutePath
23
+ */
24
+ export declare function RoutePath({ path, children }: RoutePathProps): ReactNode;
@@ -0,0 +1,21 @@
1
+ import { use } from "react";
2
+ import { RouteContext } from "./RouteContext.js";
3
+ /**
4
+ * Tell the surrounding `<Router>` (and `<RouteCache>`) that this page owns every path that matches a template.
5
+ * - A navigation to a path the page owns keeps the same page mounted, so it keeps its scroll and state,
6
+ * and a `<ViewTransition>` around the page does not run an enter or exit. The page updates for the new URL.
7
+ * - Use it for a page whose tabs each have their own path: `<RoutePath path="/dave/{tab}">`.
8
+ * - Put the real values in the template. `/{name}/{tab}` would make every person's profile one page.
9
+ *
10
+ * @kind component
11
+ * @see https://shelving.cc/ui/RoutePath
12
+ */
13
+ export function RoutePath({ path, children }) {
14
+ const state = use(RouteContext);
15
+ if (state) {
16
+ state.path = path;
17
+ if (state.cache)
18
+ state.cache.path = path;
19
+ }
20
+ return children;
21
+ }
@@ -0,0 +1,26 @@
1
+ # RoutePath
2
+
3
+ Tell the surrounding `<Router>` (and `<RouteCache>`, if there is one) that a page owns every path that matches a template. A navigation between paths the page owns keeps the same page mounted: it keeps its scroll and state, and a `<ViewTransition>` around the page does not slide. Use it for a page whose tabs each have their own path.
4
+
5
+ **Things to know:**
6
+
7
+ - Without `<RoutePath>`, each path is its own page, so `/challenge/123` and `/challenge/456` stay separate pages.
8
+ - Put the real values in the template (`/dave/{tab}`). A template such as `/{name}/{tab}` makes every profile the same page.
9
+ - The page still renders for the new URL, so it reads the tab from the URL as usual.
10
+ - It works with or without a `<RouteCache>`. In a nested router's page, it tells only that nested router.
11
+
12
+ ## Usage
13
+
14
+ ```tsx
15
+ import { Page, RoutePath } from "shelving/ui";
16
+
17
+ function ProfilePage({ name, tab }: { name: string; tab?: string }) {
18
+ return (
19
+ <RoutePath path={`/${name}/{tab}`}>
20
+ <Page title={name}>
21
+ <ProfileTabs tab={tab} />
22
+ </Page>
23
+ </RoutePath>
24
+ );
25
+ }
26
+ ```
@@ -0,0 +1,34 @@
1
+ import { type ReactNode, use } from "react";
2
+ import type { AbsolutePath } from "../../util/path.js";
3
+ import { RouteContext } from "./RouteContext.js";
4
+
5
+ /**
6
+ * Props for `<RoutePath>` — the path template the page owns, and the page content.
7
+ *
8
+ * @see https://shelving.cc/ui/RoutePathProps
9
+ */
10
+ export interface RoutePathProps {
11
+ /** Path template the page owns, for example `/dave/{tab}`. Every path that matches it shows this same page. */
12
+ readonly path: AbsolutePath;
13
+ /** The page content. */
14
+ readonly children?: ReactNode;
15
+ }
16
+
17
+ /**
18
+ * Tell the surrounding `<Router>` (and `<RouteCache>`) that this page owns every path that matches a template.
19
+ * - A navigation to a path the page owns keeps the same page mounted, so it keeps its scroll and state,
20
+ * and a `<ViewTransition>` around the page does not run an enter or exit. The page updates for the new URL.
21
+ * - Use it for a page whose tabs each have their own path: `<RoutePath path="/dave/{tab}">`.
22
+ * - Put the real values in the template. `/{name}/{tab}` would make every person's profile one page.
23
+ *
24
+ * @kind component
25
+ * @see https://shelving.cc/ui/RoutePath
26
+ */
27
+ export function RoutePath({ path, children }: RoutePathProps): ReactNode {
28
+ const state = use(RouteContext);
29
+ if (state) {
30
+ state.path = path;
31
+ if (state.cache) state.cache.path = path;
32
+ }
33
+ return children;
34
+ }
@@ -1,4 +1,4 @@
1
- import type { ReactElement } from "react";
1
+ import { type ReactElement } from "react";
2
2
  import type { PossibleMeta } from "../util/meta.js";
3
3
  import type { Routes } from "./Routes.js";
4
4
  /**
@@ -21,6 +21,7 @@ export interface RouterProps extends PossibleMeta {
21
21
  * - When `base` is set, the effective path is the URL after stripping the base prefix.
22
22
  * - Nest by putting another `<Router>` inside a route's value; pass `base="/section"` (or wrap in `<Meta>`) to scope.
23
23
  * - Route `{placeholders}` are passed as props to function/component route values along with merged URL `?query` params. They are not published into context — descendants of a `ReactElement`-valued route can't see them automatically.
24
+ * - Each path is a new page, so a component route remounts when the path changes. A page that owns other paths with `<RoutePath>` stays mounted when the path changes to one of them.
24
25
  * - Returns `null` when there's no URL in context or the URL is outside the base.
25
26
  *
26
27
  * @kind component
@@ -1,15 +1,18 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { use, useRef } from "react";
2
3
  import { NotFoundError } from "../../error/RequestError.js";
3
4
  import { UnexpectedError } from "../../error/UnexpectedError.js";
4
5
  import { getProps } from "../../util/index.js";
5
6
  import { matchPathTemplate, renderPathTemplate } from "../../util/template.js";
6
7
  import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
8
+ import { RouteContext } from "./RouteContext.js";
7
9
  /**
8
10
  * Match the current URL against `routes` and render the matched element.
9
11
  * - Reads `url` and `base` from the surrounding `<Meta>` context (override via props).
10
12
  * - When `base` is set, the effective path is the URL after stripping the base prefix.
11
13
  * - Nest by putting another `<Router>` inside a route's value; pass `base="/section"` (or wrap in `<Meta>`) to scope.
12
14
  * - Route `{placeholders}` are passed as props to function/component route values along with merged URL `?query` params. They are not published into context — descendants of a `ReactElement`-valued route can't see them automatically.
15
+ * - Each path is a new page, so a component route remounts when the path changes. A page that owns other paths with `<RoutePath>` stays mounted when the path changes to one of them.
13
16
  * - Returns `null` when there's no URL in context or the URL is outside the base.
14
17
  *
15
18
  * @kind component
@@ -19,12 +22,21 @@ import { MetaContext, requireMetaURL } from "../misc/MetaContext.js";
19
22
  export function Router({ routes, fallback, ...meta }) {
20
23
  const combined = requireMetaURL(meta);
21
24
  const path = combined;
22
- const route = _matchRoute(routes, fallback, combined);
25
+ // Keep the current page when it owns the new path with `<RoutePath>`, else start a new page for this path.
26
+ // The top-level router passes the `<RouteCache>` entry on, so `<RoutePath>` in its page also tells the cache.
27
+ const parent = use(RouteContext);
28
+ const pageRef = useRef(undefined);
29
+ const prev = pageRef.current;
30
+ const page = prev && (prev.key === combined.path || (prev.state.path && matchPathTemplate(prev.state.path, combined.path)))
31
+ ? prev
32
+ : { key: combined.path, state: { router: true, cache: parent?.router ? undefined : parent } };
33
+ pageRef.current = page;
34
+ const route = _matchRoute(routes, fallback, combined, page.key);
23
35
  if (route)
24
- return _jsx(MetaContext, { value: combined, children: route });
36
+ return (_jsx(RouteContext, { value: page.state, children: _jsx(MetaContext, { value: combined, children: route }) }));
25
37
  throw new NotFoundError("Tree route not found", { received: path });
26
38
  }
27
- function _matchRoute(routes, fallback, meta, path = meta.path, depth = 0) {
39
+ function _matchRoute(routes, fallback, meta, key, path = meta.path, depth = 0) {
28
40
  for (const [route, Route] of getProps(routes)) {
29
41
  // Try to match this path.
30
42
  const placeholders = matchPathTemplate(route, path);
@@ -38,13 +50,13 @@ function _matchRoute(routes, fallback, meta, path = meta.path, depth = 0) {
38
50
  if (depth > 10)
39
51
  throw new UnexpectedError("Infinite redirect loop", { received: route, expected: path, caller: _matchRoute });
40
52
  // `placeholders` are already decoded by `matchPathTemplate`, so re-encode them into the redirect path with `renderPathTemplate` — the symmetric partner of the match above.
41
- return _matchRoute(routes, fallback, meta, renderPathTemplate(Route, placeholders), depth + 1);
53
+ return _matchRoute(routes, fallback, meta, key, renderPathTemplate(Route, placeholders), depth + 1);
42
54
  }
43
55
  // React element — render as-is.
44
56
  if (typeof Route !== "function")
45
57
  return Route;
46
58
  // Component — render with merged URL query params and route placeholders as props (placeholders win on conflict).
47
- return _jsx(Route, { ...meta.params, ...placeholders }, path);
59
+ return _jsx(Route, { ...meta.params, ...placeholders }, key);
48
60
  }
49
61
  // No match, try the fallback.
50
62
  if (fallback !== undefined)
@@ -1,10 +1,11 @@
1
- import type { ReactElement } from "react";
1
+ import { type ReactElement, use, useRef } from "react";
2
2
  import { NotFoundError } from "../../error/RequestError.js";
3
3
  import { UnexpectedError } from "../../error/UnexpectedError.js";
4
4
  import { getProps } from "../../util/index.js";
5
5
  import { matchPathTemplate, renderPathTemplate } from "../../util/template.js";
6
6
  import { MetaContext, type MetaURL, requireMetaURL } from "../misc/MetaContext.js";
7
7
  import type { PossibleMeta } from "../util/meta.js";
8
+ import { RouteContext, type RouteState } from "./RouteContext.js";
8
9
  import type { Routes } from "./Routes.js";
9
10
 
10
11
  /**
@@ -29,6 +30,7 @@ export interface RouterProps extends PossibleMeta {
29
30
  * - When `base` is set, the effective path is the URL after stripping the base prefix.
30
31
  * - Nest by putting another `<Router>` inside a route's value; pass `base="/section"` (or wrap in `<Meta>`) to scope.
31
32
  * - Route `{placeholders}` are passed as props to function/component route values along with merged URL `?query` params. They are not published into context — descendants of a `ReactElement`-valued route can't see them automatically.
33
+ * - Each path is a new page, so a component route remounts when the path changes. A page that owns other paths with `<RoutePath>` stays mounted when the path changes to one of them.
32
34
  * - Returns `null` when there's no URL in context or the URL is outside the base.
33
35
  *
34
36
  * @kind component
@@ -38,8 +40,25 @@ export interface RouterProps extends PossibleMeta {
38
40
  export function Router({ routes, fallback, ...meta }: RouterProps): ReactElement | null {
39
41
  const combined = requireMetaURL(meta);
40
42
  const path = combined;
41
- const route = _matchRoute(routes, fallback, combined);
42
- if (route) return <MetaContext value={combined}>{route}</MetaContext>;
43
+
44
+ // Keep the current page when it owns the new path with `<RoutePath>`, else start a new page for this path.
45
+ // The top-level router passes the `<RouteCache>` entry on, so `<RoutePath>` in its page also tells the cache.
46
+ const parent = use(RouteContext);
47
+ const pageRef = useRef<{ key: string; state: RouteState }>(undefined);
48
+ const prev = pageRef.current;
49
+ const page =
50
+ prev && (prev.key === combined.path || (prev.state.path && matchPathTemplate(prev.state.path, combined.path)))
51
+ ? prev
52
+ : { key: combined.path, state: { router: true, cache: parent?.router ? undefined : parent } as RouteState };
53
+ pageRef.current = page;
54
+
55
+ const route = _matchRoute(routes, fallback, combined, page.key);
56
+ if (route)
57
+ return (
58
+ <RouteContext value={page.state}>
59
+ <MetaContext value={combined}>{route}</MetaContext>
60
+ </RouteContext>
61
+ );
43
62
  throw new NotFoundError("Tree route not found", { received: path });
44
63
  }
45
64
 
@@ -47,6 +66,7 @@ function _matchRoute(
47
66
  routes: Routes,
48
67
  fallback: ReactElement | null | undefined,
49
68
  meta: MetaURL,
69
+ key: string,
50
70
  path = meta.path,
51
71
  depth = 0,
52
72
  ): ReactElement | null | undefined {
@@ -62,14 +82,14 @@ function _matchRoute(
62
82
  if (typeof Route === "string") {
63
83
  if (depth > 10) throw new UnexpectedError("Infinite redirect loop", { received: route, expected: path, caller: _matchRoute });
64
84
  // `placeholders` are already decoded by `matchPathTemplate`, so re-encode them into the redirect path with `renderPathTemplate` — the symmetric partner of the match above.
65
- return _matchRoute(routes, fallback, meta, renderPathTemplate(Route, placeholders), depth + 1);
85
+ return _matchRoute(routes, fallback, meta, key, renderPathTemplate(Route, placeholders), depth + 1);
66
86
  }
67
87
 
68
88
  // React element — render as-is.
69
89
  if (typeof Route !== "function") return Route;
70
90
 
71
91
  // Component — render with merged URL query params and route placeholders as props (placeholders win on conflict).
72
- return <Route key={path} {...meta.params} {...placeholders} />;
92
+ return <Route key={key} {...meta.params} {...placeholders} />;
73
93
  }
74
94
 
75
95
  // No match, try the fallback.
@@ -2,5 +2,7 @@ export * from "./Navigation.js";
2
2
  export * from "./NavigationContext.js";
3
3
  export * from "./NavigationStore.js";
4
4
  export * from "./RouteCache.js";
5
+ export * from "./RouteContext.js";
6
+ export * from "./RoutePath.js";
5
7
  export * from "./Router.js";
6
8
  export * from "./Routes.js";
@@ -2,5 +2,7 @@ export * from "./Navigation.js";
2
2
  export * from "./NavigationContext.js";
3
3
  export * from "./NavigationStore.js";
4
4
  export * from "./RouteCache.js";
5
+ export * from "./RouteContext.js";
6
+ export * from "./RoutePath.js";
5
7
  export * from "./Router.js";
6
8
  export * from "./Routes.js";
@@ -2,5 +2,7 @@ export * from "./Navigation.js";
2
2
  export * from "./NavigationContext.js";
3
3
  export * from "./NavigationStore.js";
4
4
  export * from "./RouteCache.js";
5
+ export * from "./RouteContext.js";
6
+ export * from "./RoutePath.js";
5
7
  export * from "./Router.js";
6
8
  export * from "./Routes.js";