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
package/ui/page/Head.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { type ReactElement } from "react";
2
2
  /**
3
- * Emit the current page's head metadata and sync browser history to its URL.
3
+ * Emit the current page's head metadata, and replace the browser URL with the page's canonical URL.
4
4
  * - Emits hoistable head elements (title, meta, links, stylesheets, scripts) inline; React 19 hoists each one into the document `<head>`.
5
5
  * - Does not render `<base>` (not hoistable — that lives in `<Head>` in the `<HTML>` shell component).
6
- * - Updates `window.history` to match the page URL.
6
+ * - When the meta `url` differs from the browser URL (a page that knows its canonical URL), calls `NavigationStore.replace()` with it. Outside `<Navigation>` it does not touch history.
7
7
  *
8
8
  * @kind component
9
9
  * @see https://shelving.cc/ui/Head
package/ui/page/Head.js CHANGED
@@ -1,15 +1,16 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useEffect } from "react";
2
+ import { use, useEffect } from "react";
3
3
  import { getProps } from "../../util/object.js";
4
4
  import { requireMeta } from "../misc/MetaContext.js";
5
+ import { NavigationContext } from "../router/NavigationContext.js";
5
6
  import { joinTitles } from "../util/meta.js";
6
7
  /** Meta tags with a capital first letter and hyphens, e.g. `Content-Security-Policy` or `Accept`, are `http-equiv=""` tags. */
7
8
  const R_HTTP_EQUIV = /^[A-Z][a-zA-Z0-9]*(-[A-Z][a-zA-Z0-9]*)*$/;
8
9
  /**
9
- * Emit the current page's head metadata and sync browser history to its URL.
10
+ * Emit the current page's head metadata, and replace the browser URL with the page's canonical URL.
10
11
  * - Emits hoistable head elements (title, meta, links, stylesheets, scripts) inline; React 19 hoists each one into the document `<head>`.
11
12
  * - Does not render `<base>` (not hoistable — that lives in `<Head>` in the `<HTML>` shell component).
12
- * - Updates `window.history` to match the page URL.
13
+ * - When the meta `url` differs from the browser URL (a page that knows its canonical URL), calls `NavigationStore.replace()` with it. Outside `<Navigation>` it does not touch history.
13
14
  *
14
15
  * @kind component
15
16
  * @see https://shelving.cc/ui/Head
@@ -17,12 +18,12 @@ const R_HTTP_EQUIV = /^[A-Z][a-zA-Z0-9]*(-[A-Z][a-zA-Z0-9]*)*$/;
17
18
  export function Head() {
18
19
  const meta = requireMeta();
19
20
  const { url, title, app, description, links, tags, stylesheets, modules, scripts } = meta;
21
+ // A page can set its canonical URL in meta. Replace the browser URL with it, through the navigation store so the history entry keeps its stack.
22
+ const nav = use(NavigationContext);
20
23
  useEffect(() => {
21
- if (typeof window === "undefined")
22
- return;
23
- if (url)
24
- window.history.replaceState(null, "", url);
25
- }, [url]);
24
+ if (nav && url && url.href !== nav.value.href)
25
+ nav.replace(url);
26
+ }, [nav, url]);
26
27
  const fullTitle = joinTitles(title, app);
27
28
  return (_jsxs(_Fragment, { children: [fullTitle && _jsx("title", { children: fullTitle }), description && _jsx("meta", { name: "description", content: description }), tags && getProps(tags).map(_renderTag), links && getProps(links).map(_renderLink), stylesheets?.map(_renderStylesheet), modules?.map(_renderModule), scripts?.map(_renderScript)] }));
28
29
  }
package/ui/page/Head.tsx CHANGED
@@ -1,17 +1,18 @@
1
- import { type ReactElement, useEffect } from "react";
1
+ import { type ReactElement, use, useEffect } from "react";
2
2
  import type { ArrayItem } from "../../util/array.js";
3
3
  import { getProps, type Prop } from "../../util/object.js";
4
4
  import { requireMeta } from "../misc/MetaContext.js";
5
+ import { NavigationContext } from "../router/NavigationContext.js";
5
6
  import { joinTitles, type MetaAssets, type MetaLinks, type MetaTags } from "../util/meta.js";
6
7
 
7
8
  /** Meta tags with a capital first letter and hyphens, e.g. `Content-Security-Policy` or `Accept`, are `http-equiv=""` tags. */
8
9
  const R_HTTP_EQUIV = /^[A-Z][a-zA-Z0-9]*(-[A-Z][a-zA-Z0-9]*)*$/;
9
10
 
10
11
  /**
11
- * Emit the current page's head metadata and sync browser history to its URL.
12
+ * Emit the current page's head metadata, and replace the browser URL with the page's canonical URL.
12
13
  * - Emits hoistable head elements (title, meta, links, stylesheets, scripts) inline; React 19 hoists each one into the document `<head>`.
13
14
  * - Does not render `<base>` (not hoistable — that lives in `<Head>` in the `<HTML>` shell component).
14
- * - Updates `window.history` to match the page URL.
15
+ * - When the meta `url` differs from the browser URL (a page that knows its canonical URL), calls `NavigationStore.replace()` with it. Outside `<Navigation>` it does not touch history.
15
16
  *
16
17
  * @kind component
17
18
  * @see https://shelving.cc/ui/Head
@@ -20,10 +21,11 @@ export function Head(): ReactElement {
20
21
  const meta = requireMeta();
21
22
  const { url, title, app, description, links, tags, stylesheets, modules, scripts } = meta;
22
23
 
24
+ // A page can set its canonical URL in meta. Replace the browser URL with it, through the navigation store so the history entry keeps its stack.
25
+ const nav = use(NavigationContext);
23
26
  useEffect(() => {
24
- if (typeof window === "undefined") return;
25
- if (url) window.history.replaceState(null, "", url);
26
- }, [url]);
27
+ if (nav && url && url.href !== nav.value.href) nav.replace(url);
28
+ }, [nav, url]);
27
29
 
28
30
  const fullTitle = joinTitles(title, app);
29
31
  return (
@@ -0,0 +1,22 @@
1
+ import { type ReactElement } from "react";
2
+ import type { AbsolutePath } from "../../util/path.js";
3
+ import { type ButtonProps } from "../button/Button.js";
4
+ /**
5
+ * Props for `<BackButton>`: the `href` to go back to when the stack has no page before this one, plus the usual `Button` props except `onClick`.
6
+ *
7
+ * @see https://shelving.cc/ui/BackButtonProps
8
+ */
9
+ export interface BackButtonProps extends Omit<ButtonProps, "href" | "onClick"> {
10
+ /** Where to go back to when the current stack has no page before this one (for example, the app was opened at this page). */
11
+ readonly href: AbsolutePath;
12
+ }
13
+ /**
14
+ * Back button for the current stack.
15
+ * - Goes back to the page before this one in the current stack, wherever you came from.
16
+ * - Goes to `href` when the stack has no page before this one: the app was opened at this page, or the browser has no Navigation API.
17
+ * - It is a plain link with `className="back"`, so it slides back, and it works in a server render and with a middle-click.
18
+ *
19
+ * @kind component
20
+ * @see https://shelving.cc/ui/BackButton
21
+ */
22
+ export declare function BackButton({ href, className, title, children, ...props }: BackButtonProps): ReactElement;
@@ -0,0 +1,19 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { use } from "react";
3
+ import { LeftIcon } from "../../icon/LeftIcon.js";
4
+ import { Button } from "../button/Button.js";
5
+ import { getClass } from "../util/css.js";
6
+ import { NavigationPositionContext } from "./NavigationContext.js";
7
+ /**
8
+ * Back button for the current stack.
9
+ * - Goes back to the page before this one in the current stack, wherever you came from.
10
+ * - Goes to `href` when the stack has no page before this one: the app was opened at this page, or the browser has no Navigation API.
11
+ * - It is a plain link with `className="back"`, so it slides back, and it works in a server render and with a middle-click.
12
+ *
13
+ * @kind component
14
+ * @see https://shelving.cc/ui/BackButton
15
+ */
16
+ export function BackButton({ href, className, title = "Back", children = _jsx(LeftIcon, {}), ...props }) {
17
+ const position = use(NavigationPositionContext);
18
+ return (_jsx(Button, { ...props, title: title, href: position?.parent ?? href, className: getClass("back", className), children: children }));
19
+ }
@@ -0,0 +1,47 @@
1
+ # BackButton
2
+
3
+ The back button for a page header. It goes back to the page before this one in the current stack, wherever you came from.
4
+
5
+ **Things to know:**
6
+
7
+ - It goes to the page before this one in the current stack. If you opened a post from a search, it goes back to the search.
8
+ - It goes to `href` when the stack has no page before this one: for example, when the app was opened at this page. So a back button always has somewhere to go. Set `href` to the page's natural parent. On an unstacked page (for example a deep link), it goes to `href` and stays unstacked. To go into a stack, the user taps a `<StackButton>`.
9
+ - It is a plain link with `className="back"`. `<Navigation>` turns a click into `NavigationStore.back()`, so the page slides back. A middle-click opens the link in a new browser tab.
10
+ - Its default content is a `<LeftIcon>` and its default `title` is "Back". Pass `children` and `title` to change them.
11
+ - It takes the usual `<Button>` props, except `onClick`.
12
+ - Without the browser Navigation API, and in a server render, it links to `href`.
13
+ - In a server-rendered app the server always renders `href`, and the browser may render the page before this one. React then warns about a hydration mismatch on the first render. A client-only app (with `<App>`) has no mismatch.
14
+
15
+ ## Usage
16
+
17
+ ```tsx
18
+ import { BackButton } from "shelving/ui";
19
+
20
+ function PostPage({ id }: { id: string }) {
21
+ return (
22
+ <>
23
+ <header>
24
+ <BackButton href="/home"/>
25
+ <h1>Post</h1>
26
+ </header>
27
+ {/* … */}
28
+ </>
29
+ );
30
+ }
31
+ ```
32
+
33
+ With a label:
34
+
35
+ ```tsx
36
+ <BackButton href="/profile">Back to profile</BackButton>
37
+ ```
38
+
39
+ To go back to one fixed page (not to the page before), use a link with `className="back"`:
40
+
41
+ ```tsx
42
+ <Button href="/profile" className="back">Profile</Button>
43
+ ```
44
+
45
+ ## Styling
46
+
47
+ `<BackButton>` renders a `<Button>`, so it has the same styling hooks. See `<Button>`.
@@ -0,0 +1,34 @@
1
+ import { type ReactElement, use } from "react";
2
+ import { LeftIcon } from "../../icon/LeftIcon.js";
3
+ import type { AbsolutePath } from "../../util/path.js";
4
+ import { Button, type ButtonProps } from "../button/Button.js";
5
+ import { getClass } from "../util/css.js";
6
+ import { NavigationPositionContext } from "./NavigationContext.js";
7
+
8
+ /**
9
+ * Props for `<BackButton>`: the `href` to go back to when the stack has no page before this one, plus the usual `Button` props except `onClick`.
10
+ *
11
+ * @see https://shelving.cc/ui/BackButtonProps
12
+ */
13
+ export interface BackButtonProps extends Omit<ButtonProps, "href" | "onClick"> {
14
+ /** Where to go back to when the current stack has no page before this one (for example, the app was opened at this page). */
15
+ readonly href: AbsolutePath;
16
+ }
17
+
18
+ /**
19
+ * Back button for the current stack.
20
+ * - Goes back to the page before this one in the current stack, wherever you came from.
21
+ * - Goes to `href` when the stack has no page before this one: the app was opened at this page, or the browser has no Navigation API.
22
+ * - It is a plain link with `className="back"`, so it slides back, and it works in a server render and with a middle-click.
23
+ *
24
+ * @kind component
25
+ * @see https://shelving.cc/ui/BackButton
26
+ */
27
+ export function BackButton({ href, className, title = "Back", children = <LeftIcon />, ...props }: BackButtonProps): ReactElement {
28
+ const position = use(NavigationPositionContext);
29
+ return (
30
+ <Button {...props} title={title} href={position?.parent ?? href} className={getClass("back", className)}>
31
+ {children}
32
+ </Button>
33
+ );
34
+ }
@@ -1,27 +1,37 @@
1
1
  import { type ReactElement } from "react";
2
+ import type { AbsolutePath } from "../../util/path.js";
2
3
  import { type PossibleMeta } from "../util/index.js";
3
4
  import type { OptionalChildProps } from "../util/props.js";
4
5
  /**
5
- * Props for `<Navigation>` — initial `Meta` (url/base) plus optional `children`.
6
+ * Props for `<Navigation>`: the initial `Meta` (url, root and stack), the `stacks`, and optional `children`.
6
7
  *
7
8
  * @see https://shelving.cc/ui/NavigationProps
8
9
  */
9
10
  export interface NavigationProps extends PossibleMeta, OptionalChildProps {
11
+ /**
12
+ * Root path of each stack, in tab order, for an app with a tab bar (for example `["/home", "/discover", "/profile"]`).
13
+ * - Each stack keeps its own pages, so each tab remembers where you left it, and a back button goes back within its tab.
14
+ * - With no stacks, the app has one stack at `"/"`, and `stack` in `Meta` is `"/"`.
15
+ */
16
+ readonly stacks?: readonly AbsolutePath[] | undefined;
17
+ /**
18
+ * Stack of the page the app opens at (for example `"/home"`), like `url` and `root`.
19
+ * - Read from this prop, else from the surrounding `<Meta>`, else `"/"`.
20
+ * - Used only when the opening history entry has no saved stack. A reload keeps the stack it had.
21
+ */
22
+ readonly stack?: AbsolutePath | undefined;
10
23
  }
11
24
  /**
12
- * Top-level navigation provider.
13
- * - Owns a single `NavigationStore` initialised from the surrounding `<Meta>` url/base.
14
- * - Intercepts same-origin anchor clicks (excluding `download` anchors) and turns them into `forward()` calls, or `back()` calls for an anchor with a `data-back` attribute.
15
- * - Listens for `popstate` to sync the store with browser back/forward.
16
- * - Publishes the live URL into the `Meta` context via `mergeMeta()`, so descendant `<Router>`s re-render on navigation and merge invariants hold (e.g. `root` defaults to the live URL's origin when unset).
17
- * - Publishes each URL change inside `startTransition()` with a `"forward"` or `"back"` transition type, so a `<Transition>` around the routes runs a view transition.
18
- * - Skips the transition when the browser already animated the change (`PopStateEvent.hasUAVisualTransition`, e.g. a swipe-back gesture).
25
+ * Top-level navigation provider, with one stack of pages for each tab.
26
+ * - Owns a single `NavigationStore` made from the surrounding `<Meta>` url and root.
27
+ * - Turns clicks on same-origin links into `NavigationStore.forward()`, or `NavigationStore.back()` for a link with `className="back"`, or `NavigationStore.replace()` for a link with `className="replace"`. Clicks with a modifier key, or on links with `download` or a `target`, are left to the browser.
28
+ * - Publishes the URL and the current `stack` into `Meta`, and the position in the stacks into `NavigationPositionContext`, all in one render.
29
+ * - Publishes each change inside `startTransition()` with a `"forward"` or `"back"` transition type, so a `<Transition>` around the routes runs a view transition. A replace, or a change the browser already animated (for example a swipe-back), has no transition.
30
+ * - Uses the browser Navigation API. Without it (older browsers, server renders) there are no stacks and no transitions.
19
31
  *
20
- * Exactly one `<Navigation>` per app — nested routers share this single store.
21
- *
22
- * TODO: switch click/popstate handling to the browser Navigation API when broadly supported.
32
+ * Exactly one `<Navigation>` per app. Nested routers share its store.
23
33
  *
24
34
  * @kind component
25
35
  * @see https://shelving.cc/ui/Navigation
26
36
  */
27
- export declare function Navigation({ children, ...meta }: NavigationProps): ReactElement;
37
+ export declare function Navigation({ children, stacks, ...meta }: NavigationProps): ReactElement;
@@ -4,73 +4,89 @@ import { useInstance } from "../../react/useInstance.js";
4
4
  import { MetaContext, requireMeta } from "../misc/MetaContext.js";
5
5
  import { setTransitionType } from "../transition/util.js";
6
6
  import { mergeMeta } from "../util/index.js";
7
- import { NavigationContext } from "./NavigationContext.js";
7
+ import { NavigationContext, NavigationPositionContext } from "./NavigationContext.js";
8
8
  import { NavigationStore } from "./NavigationStore.js";
9
9
  /**
10
- * Top-level navigation provider.
11
- * - Owns a single `NavigationStore` initialised from the surrounding `<Meta>` url/base.
12
- * - Intercepts same-origin anchor clicks (excluding `download` anchors) and turns them into `forward()` calls, or `back()` calls for an anchor with a `data-back` attribute.
13
- * - Listens for `popstate` to sync the store with browser back/forward.
14
- * - Publishes the live URL into the `Meta` context via `mergeMeta()`, so descendant `<Router>`s re-render on navigation and merge invariants hold (e.g. `root` defaults to the live URL's origin when unset).
15
- * - Publishes each URL change inside `startTransition()` with a `"forward"` or `"back"` transition type, so a `<Transition>` around the routes runs a view transition.
16
- * - Skips the transition when the browser already animated the change (`PopStateEvent.hasUAVisualTransition`, e.g. a swipe-back gesture).
10
+ * Top-level navigation provider, with one stack of pages for each tab.
11
+ * - Owns a single `NavigationStore` made from the surrounding `<Meta>` url and root.
12
+ * - Turns clicks on same-origin links into `NavigationStore.forward()`, or `NavigationStore.back()` for a link with `className="back"`, or `NavigationStore.replace()` for a link with `className="replace"`. Clicks with a modifier key, or on links with `download` or a `target`, are left to the browser.
13
+ * - Publishes the URL and the current `stack` into `Meta`, and the position in the stacks into `NavigationPositionContext`, all in one render.
14
+ * - Publishes each change inside `startTransition()` with a `"forward"` or `"back"` transition type, so a `<Transition>` around the routes runs a view transition. A replace, or a change the browser already animated (for example a swipe-back), has no transition.
15
+ * - Uses the browser Navigation API. Without it (older browsers, server renders) there are no stacks and no transitions.
17
16
  *
18
- * Exactly one `<Navigation>` per app — nested routers share this single store.
19
- *
20
- * TODO: switch click/popstate handling to the browser Navigation API when broadly supported.
17
+ * Exactly one `<Navigation>` per app. Nested routers share its store.
21
18
  *
22
19
  * @kind component
23
20
  * @see https://shelving.cc/ui/Navigation
24
21
  */
25
- export function Navigation({ children, ...meta }) {
22
+ export function Navigation({ children, stacks = [], ...meta }) {
26
23
  const current = requireMeta(meta);
27
- const nav = useInstance(NavigationStore, current.url, current.root);
24
+ const nav = useInstance(NavigationStore, current.url, current.root, current.stack ?? "/", ...stacks);
28
25
  // React runs a `<ViewTransition>` only for a transition update, and `useSyncExternalStore()` always renders a sync update.
29
- // So keep the published URL in state and copy each store change into it inside `startTransition()`.
30
- const [url, setURL] = useState(nav.value);
26
+ // So keep the published values in state, and copy each store change into it inside `startTransition()`.
27
+ const [published, setPublished] = useState(() => _getPublished(nav));
31
28
  useEffect(() => {
32
- if (typeof document === "undefined" || typeof window === "undefined")
33
- return;
34
- // Read the transition type the store set for this change, then reset it.
35
- const stop = nav.subscribe(value => {
36
- const t = nav.transition;
37
- nav.transition = "forward";
38
- if (!t)
39
- return setURL(value);
40
- // React renders a transition that starts inside a `popstate` event as a sync update with no view transition, so leave the event first.
41
- setTimeout(() => startTransition(() => {
42
- setTransitionType(t);
43
- setURL(value);
44
- }));
45
- });
46
- const onClick = (e) => {
47
- if (e.target instanceof Element) {
48
- const anchor = e.target.closest("a") ||
49
- (!e.target.closest("button, label") && e.target.closest(".targeted")?.querySelector("a.target[href]"));
50
- if (anchor instanceof HTMLAnchorElement && anchor.origin === window.location.origin && !anchor.hasAttribute("download")) {
51
- e.preventDefault();
52
- if (anchor.hasAttribute("data-back"))
53
- nav.back(anchor.href);
54
- else
55
- nav.forward(anchor.href);
56
- return false; // `return false` stops iOS web app opening every link in a new window.
57
- }
29
+ const stopListening = nav.listen();
30
+ // Publish the latest values once for each change, even when the URL and the stack both change.
31
+ let last = nav.value.href;
32
+ let lastStack = nav.stack.value;
33
+ let pending = false;
34
+ const publish = () => {
35
+ const { value, transition } = nav;
36
+ if (value.href === last && nav.stack.value === lastStack)
37
+ return;
38
+ last = value.href;
39
+ lastStack = nav.stack.value;
40
+ if (pending)
41
+ return;
42
+ pending = true;
43
+ if (!transition) {
44
+ pending = false;
45
+ return setPublished(_getPublished(nav));
58
46
  }
47
+ // React renders a transition that starts inside a browser history event as a sync update with no view transition, so leave the event first.
48
+ setTimeout(() => {
49
+ pending = false;
50
+ startTransition(() => {
51
+ setTransitionType(transition);
52
+ setPublished(_getPublished(nav));
53
+ });
54
+ });
59
55
  };
60
- const onPopState = (e) => {
61
- const href = window.location.href;
62
- // `"back"` for a `popstate`. `null` means no transition, because the browser already animated the change (e.g. a swipe-back gesture).
63
- if (href !== nav.value.href)
64
- nav.transition = e.hasUAVisualTransition ? null : "back";
65
- nav.value = href;
56
+ const stopURL = nav.subscribe(publish);
57
+ const stopStack = nav.stack.subscribe(publish);
58
+ // The first render may have run before the store saw the current history entry.
59
+ setPublished(p => (p.url.href === nav.value.href && p.stack === nav.stack.value ? p : _getPublished(nav)));
60
+ const onClick = (e) => {
61
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || !(e.target instanceof Element))
62
+ return;
63
+ const anchor = e.target.closest("a") ||
64
+ (!e.target.closest("button, label") && e.target.closest(".targeted")?.querySelector("a.target[href]"));
65
+ if (!(anchor instanceof HTMLAnchorElement) || anchor.origin !== window.location.origin)
66
+ return;
67
+ if (anchor.hasAttribute("download") || (anchor.target && anchor.target !== "_self"))
68
+ return;
69
+ e.preventDefault();
70
+ const { classList, href } = anchor;
71
+ if (classList.contains("back"))
72
+ nav.back(href);
73
+ else if (classList.contains("replace"))
74
+ nav.replace(href);
75
+ else
76
+ nav.forward(href);
77
+ return false; // `return false` stops iOS web app opening every link in a new window.
66
78
  };
67
79
  document.addEventListener("click", onClick);
68
- window.addEventListener("popstate", onPopState);
69
80
  return () => {
70
81
  document.removeEventListener("click", onClick);
71
- window.removeEventListener("popstate", onPopState);
72
- stop();
82
+ stopURL();
83
+ stopStack();
84
+ stopListening();
73
85
  };
74
86
  }, [nav]);
75
- return (_jsx(NavigationContext, { value: nav, children: _jsx(MetaContext, { value: mergeMeta(current, { url }, Navigation), children: children }) }));
87
+ const { url, stack, position } = published;
88
+ return (_jsx(NavigationContext, { value: nav, children: _jsx(NavigationPositionContext, { value: position, children: _jsx(MetaContext, { value: mergeMeta(current, { url, stack }, Navigation), children: children }) }) }));
89
+ }
90
+ function _getPublished(nav) {
91
+ return { url: nav.value, stack: nav.stack.value, position: nav.position };
76
92
  }
@@ -1,56 +1,113 @@
1
1
  # Navigation
2
2
 
3
- The top-level navigation provider for a client-side app. It owns a single `NavigationStore`, publishes the live URL into the `<Meta>` context so descendant `<Router>`s re-render on navigation, and wires up browser history. Use exactly one `<Navigation>` per app — nested routers all share its single store.
3
+ The top-level navigation provider for a client-side app. It owns one `NavigationStore`, turns link clicks into navigation, and publishes the live URL into `<Meta>`, so each `<Router>` re-renders when the URL changes. Use exactly one `<Navigation>` per app. Nested routers all share its store.
4
+
5
+ Give it `stacks` for an app with a tab bar. Each stack is one tab with its own history of pages, like a phone app: each tab remembers where you left it, and a back button goes back within its tab.
4
6
 
5
7
  **Things to know:**
6
8
 
7
- - Same-origin anchor clicks are intercepted automatically and turned into `forward()` calls. Add a `download` attribute to an anchor to opt out.
8
- - An anchor with a `data-back` attribute calls `back()` instead, so the page slides back. Set it with the `back` prop on `<Button>` or `<Link>`, e.g. on a "Back to profile" button.
9
- - It listens for `popstate` so the store stays in sync with browser back/forward.
10
- - It publishes each page change inside `startTransition()`, so a `<Transition>` around the routes animates it. A link click, `NavigationStore.forward()` or `NavigationStore.redirect()` sets the `"forward"` transition type. A `data-back` link click, `NavigationStore.back()`, and the browser back or forward button set `"back"` (`popstate` does not say which way it went).
11
- - When the browser already animated the change, for example a swipe-back gesture on a phone, there is no view transition, so the page does not slide twice. The browser says so with `hasUAVisualTransition` on the `popstate` event. Other browsers still slide.
12
- - The `popstate` update waits for the next task (`setTimeout()`). React renders a transition that starts inside `popstate` as a sync update with no view transition.
13
- - It initialises the store from the surrounding `<Meta>` url/base, so set those on an ancestor `<App>` / `<HTML>` / `<Page>`. In the browser the store falls back to `window.location.href` when no url is set.
14
- - The meta it publishes always has a `root` — when none is set anywhere, `root` defaults to the live URL's origin. Setting `root` explicitly on `<App>` / `<HTML>` is still strongly recommended, especially for apps served under a sub-path.
15
- - `<Router>` works with no `<Navigation>` at all (SSR, static rendering, tests) — `<Navigation>` is only what makes the URL *live* on the client.
9
+ - Same-origin link clicks become `NavigationStore.forward()`, so the page slides forward.
10
+ - A link with `className="back"` calls `NavigationStore.back()`, so the page slides back. `<BackButton>` sets this class for you.
11
+ - A link with `className="replace"` calls `NavigationStore.replace()`. It changes the URL with no new history entry and no slide, and keeps the same page mounted. Use it for tabs inside a page.
12
+ - Clicks with a modifier key (Cmd, Ctrl, Shift, Alt), a middle-click, and links with `download` or a `target` other than `_self` go to the browser as usual.
13
+ - It publishes each page change inside `startTransition()` with a `"forward"` or `"back"` transition type, so a `<Transition>` such as `<HorizontalTransition>` slides the page. A replace has no transition.
14
+ - The browser back and forward buttons slide too. Inside a stack the direction comes from the depth of the page. Across stacks it comes from tab order.
15
+ - When the browser already animated the change (for example a swipe-back on a phone), there is no view transition, so the page does not slide twice.
16
+ - It publishes `stack` (the root of the current stack) into `<Meta>` beside `url`, so any component can read the current tab with `requireMeta().stack`. With no `stacks`, the app has one stack, and `stack` is `"/"`.
17
+ - It reads the start URL and root from the surrounding `<Meta>`, so set `url` and `root` on an ancestor `<App>` or `<HTML>`. In the browser the URL falls back to `window.location.href`.
18
+ - `<Router>` works with no `<Navigation>` (server renders, static renders, tests). `<Navigation>` only makes the URL live on the client.
19
+
20
+ ### Browser support
21
+
22
+ Stacks and slides use the browser [Navigation API](https://developer.mozilla.org/en-US/docs/Web/API/Navigation_API). Without it (older browsers, a server render, or a sandboxed frame), `<Navigation>` falls back to plain navigation:
23
+
24
+ - Links still go through the app with no page reload, and the browser back button works.
25
+ - There are no stacks, no slides and no `<RouteCache>`. Each page mounts fresh.
26
+ - `<StackButton>` is a plain link to its stack's root. `<BackButton>` is a plain link to its `href`.
16
27
 
17
28
  ## Usage
18
29
 
30
+ ### Basic setup
31
+
19
32
  ```tsx
20
- import { HTML, Navigation, Router } from "shelving/ui";
33
+ import { App, Navigation, Router } from "shelving/ui";
21
34
 
22
- <HTML url={initialUrl} root="https://example.com/">
35
+ <App root="https://example.com/">
23
36
  <Navigation>
24
37
  <Router routes={ROUTES}/>
25
38
  </Navigation>
26
- </HTML>
39
+ </App>
27
40
  ```
28
41
 
29
- ### Page transitions
42
+ ### App with a tab bar
43
+
44
+ List the root path of each stack in tab order. Put a `<StackButton>` for each stack in the tab bar.
30
45
 
31
46
  ```tsx
32
- import { HorizontalTransition, Navigation, Router } from "shelving/ui";
47
+ import { App, HorizontalTransition, Navigation, RouteCache, Router, StackButton } from "shelving/ui";
33
48
 
34
- // Links slide right. Back links and the browser back button slide left.
35
- <Navigation>
36
- <HorizontalTransition>
37
- <Router routes={ROUTES}/>
38
- </HorizontalTransition>
39
- </Navigation>
49
+ const STACKS = ["/home", "/discover", "/profile"] as const;
50
+
51
+ <App root="https://example.com/">
52
+ <Navigation stacks={STACKS}>
53
+ <HorizontalTransition>
54
+ <RouteCache>
55
+ <Router routes={ROUTES}/>
56
+ </RouteCache>
57
+ </HorizontalTransition>
58
+ <nav className="tab-bar">
59
+ <StackButton stack="/home">Home</StackButton>
60
+ <StackButton stack="/discover">Discover</StackButton>
61
+ <StackButton stack="/profile">Profile</StackButton>
62
+ </nav>
63
+ </Navigation>
64
+ </App>
65
+ ```
66
+
67
+ To select a tab when the app starts, pass the starting `stack`. The app decides which stack the opening URL belongs to, for example:
68
+
69
+ ```tsx
70
+ const path = window.location.pathname;
71
+ const stack = STACKS.find(s => path === s || path.startsWith(`${s}/`));
72
+
73
+ <Navigation stacks={STACKS} stack={stack}>
74
+ ```
75
+
76
+ Put the transition **outside** `<RouteCache>`, around the whole cache. Safari (iOS 18) loses the exit animation when each page has its own `<ViewTransition>`.
77
+
78
+ The app opens in the `stack` you set on `<Navigation>` (or on the surrounding `<Meta>`, like `url` and `root`), else in the `/` stack. A page in the `/` stack, such as a deep link or a login page, is **unstacked**: no tab is selected, and links from it stay unstacked until you tap a tab or name a stack (for example `nav.replace("/home", "/home")` after a login). See `NavigationStore`.
79
+
80
+ Each link pushes a new page onto the current stack, wherever it points. So a link from `/home` to `/profile/settings` opens the settings page in the Home tab, and the Profile tab stays where it was. Tap a `<StackButton>` to change tab.
40
81
 
41
- // A "back to" link slides left too.
42
- <Button href="/profile" back>Back to profile</Button>
82
+ ### Links
83
+
84
+ ```tsx
85
+ // Opens a new page in the current stack. Slides forward.
86
+ <Button href="/home/post/1">Open post</Button>
87
+
88
+ // Goes back to a page. Slides back.
89
+ // If the page is already in the stack, the stack goes back to it.
90
+ <Button href="/home" className="back">Back to home</Button>
91
+
92
+ // The back button for a page header. Goes to the page before this one in the stack, or to `href`.
93
+ <BackButton href="/home"/>
94
+
95
+ // Changes the URL but keeps the same page. No slide, no new history entry.
96
+ <Button href="/profile/posts" className="replace">Posts</Button>
97
+ <Button href="/profile/likes" className="replace">Likes</Button>
43
98
  ```
44
99
 
45
100
  ### Imperative navigation
46
101
 
47
- Read the navigation store from anywhere in the tree with `requireNavigation()` for imperative URL changes:
102
+ Read the store from anywhere in the tree with `requireNavigation()`:
48
103
 
49
104
  ```tsx
50
105
  import { requireNavigation } from "shelving/ui";
51
106
 
52
107
  const nav = requireNavigation();
53
- nav.forward("/users/123"); // push a new history entry
54
- nav.redirect("/login"); // replace the current history entry
55
- nav.back("/users"); // push a new history entry that slides back
108
+ nav.forward("/home/post/1"); // Open a page in the current stack.
109
+ nav.back("/home"); // Go back to a page.
110
+ nav.replace("/login"); // Change the URL of the current page.
56
111
  ```
112
+
113
+ See `NavigationStore` for what each method does.
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
  import type { ReactNode } from "react";
3
3
  import { renderToStaticMarkup } from "react-dom/server";
4
- import { Button, Navigation, requireMetaURL } from "shelving/ui";
4
+ import { BackButton, Navigation, requireMetaURL, StackButton } from "shelving/ui";
5
5
 
6
6
  /** Render `requireMetaURL().path` from inside a component so its `use(MetaContext)` call is valid. */
7
7
  function Probe(): ReactNode {
@@ -27,14 +27,34 @@ describe("Navigation", () => {
27
27
  expect(html).toBe("/sub");
28
28
  });
29
29
 
30
- test("marks a back link with a data-back attribute", () => {
30
+ test("renders a back button as a link to its href with a back class", () => {
31
31
  const html = renderToStaticMarkup(
32
- <Navigation url="http://x.com/a">
33
- <Button href="/b" back>
34
- Back
35
- </Button>
32
+ <Navigation url="http://x.com/home/post/1" stacks={["/home", "/profile"]}>
33
+ <BackButton href="/home">Back</BackButton>
36
34
  </Navigation>,
37
35
  );
38
- expect(html).toContain('data-back="true"');
36
+ expect(html).toContain('href="http://x.com/home"');
37
+ expect(html).toContain('class="back"');
38
+ });
39
+
40
+ test("renders a stack button as a link to its root, selected in the starting stack", () => {
41
+ const html = renderToStaticMarkup(
42
+ <Navigation url="http://x.com/profile/settings" stacks={["/home", "/profile"]} stack="/profile">
43
+ <StackButton stack="/home">Home</StackButton>
44
+ <StackButton stack="/profile">Profile</StackButton>
45
+ </Navigation>,
46
+ );
47
+ expect(html).toContain('<a href="http://x.com/home">Home</a>');
48
+ expect(html).toContain('<a href="http://x.com/profile" aria-current="true">Profile</a>');
49
+ });
50
+
51
+ test("selects no stack button on an unstacked page", () => {
52
+ const html = renderToStaticMarkup(
53
+ <Navigation url="http://x.com/settings" stacks={["/home", "/profile"]}>
54
+ <StackButton stack="/home">Home</StackButton>
55
+ <StackButton stack="/profile">Profile</StackButton>
56
+ </Navigation>,
57
+ );
58
+ expect(html).not.toContain("aria-current");
39
59
  });
40
60
  });