shelving 1.297.2 → 1.299.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 +1 -1
- package/ui/input/QueryInput.d.ts +14 -6
- package/ui/input/QueryInput.js +19 -6
- package/ui/input/QueryInput.md +38 -0
- package/ui/input/QueryInput.test.tsx +18 -0
- package/ui/input/QueryInput.tsx +48 -22
- package/ui/router/RouteCache.d.ts +1 -0
- package/ui/router/RouteCache.js +27 -17
- package/ui/router/RouteCache.md +1 -0
- package/ui/router/RouteCache.tsx +36 -18
- package/ui/router/RouteContext.d.ts +20 -0
- package/ui/router/RouteContext.js +8 -0
- package/ui/router/RouteContext.tsx +24 -0
- package/ui/router/RoutePath.d.ts +24 -0
- package/ui/router/RoutePath.js +21 -0
- package/ui/router/RoutePath.md +26 -0
- package/ui/router/RoutePath.tsx +34 -0
- package/ui/router/Router.d.ts +2 -1
- package/ui/router/Router.js +17 -5
- package/ui/router/Router.tsx +25 -5
- package/ui/router/index.d.ts +2 -0
- package/ui/router/index.js +2 -0
- package/ui/router/index.ts +2 -0
package/package.json
CHANGED
package/ui/input/QueryInput.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ReactElement, type ReactNode } from "react";
|
|
2
2
|
import type { Schema } from "../../schema/Schema.js";
|
|
3
3
|
import { type PayloadFetchCallback } from "../../store/PayloadFetchStore.js";
|
|
4
4
|
import type { ImmutableArray } from "../../util/array.js";
|
|
@@ -15,11 +15,17 @@ export interface QueryInputProps<I, O> extends ValueInputProps<O> {
|
|
|
15
15
|
* Called with the current text value to return matching items whenever the text input changes.
|
|
16
16
|
* - Automatically debounced, so only called after a short delay.
|
|
17
17
|
* - Automatically shows a loading state while loading.
|
|
18
|
-
* - Returning `undefined` signals to close the popover.
|
|
18
|
+
* - Returning `undefined` signals to close the popover (or, with `popover={false}`, to show no list).
|
|
19
19
|
*/
|
|
20
20
|
onQuery: PayloadFetchCallback<I, ImmutableArray<O> | undefined>;
|
|
21
|
-
/** Format an item of type `O` for display in the picker. */
|
|
22
|
-
formatter?: ((value: O) =>
|
|
21
|
+
/** Format an item of type `O` for display in the picker, for example as text or as an avatar. */
|
|
22
|
+
formatter?: ((value: O) => ReactNode) | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* Show the results in a popover (the default), or set `false` to show them inline, as a list below the input.
|
|
25
|
+
* - Inline, the list shows at once: `onQuery()` is called with the schema's default value (e.g. `""`) on mount.
|
|
26
|
+
* - Inline, an empty input still queries, and picking an item keeps the list.
|
|
27
|
+
*/
|
|
28
|
+
popover?: boolean | undefined;
|
|
23
29
|
/** Message that shows when query returns `[]` empty array (set to `""` empty string to show no message). */
|
|
24
30
|
empty?: ReactNode | undefined;
|
|
25
31
|
}
|
|
@@ -27,10 +33,12 @@ export interface QueryInputProps<I, O> extends ValueInputProps<O> {
|
|
|
27
33
|
* Combo box that queries a list of items and lets the user pick one from a popover.
|
|
28
34
|
* - Shows an input based on a `schema` of type `I`; its values are piped to the `onQuery()` callback.
|
|
29
35
|
* - Shows a `<Popover>` with a radio list of returned items to pick a final value of type `O`.
|
|
36
|
+
* - With `popover={false}`, shows the radio list inline below the input instead, like a `<select>` list box.
|
|
30
37
|
* - Errors, loading, and empty states are handled automatically.
|
|
31
38
|
*
|
|
32
|
-
* @returns A combo box element wrapping the input and results popover.
|
|
39
|
+
* @returns A combo box element wrapping the input and results popover (or the inline list).
|
|
33
40
|
* @example <QueryInput schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
41
|
+
* @example <QueryInput popover={false} schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
34
42
|
* @see https://shelving.cc/ui/QueryInput
|
|
35
43
|
*/
|
|
36
|
-
export declare function QueryInput<I, O>({ empty, value, onValue, onQuery, formatter, className, ...props }: QueryInputProps<I, O>): ReactElement;
|
|
44
|
+
export declare function QueryInput<I, O>({ empty, value, onValue, onQuery, formatter, popover, className, ...props }: QueryInputProps<I, O>): ReactElement;
|
package/ui/input/QueryInput.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { useEffect } from "react";
|
|
2
3
|
import { useInstance } from "../../react/useInstance.js";
|
|
3
4
|
import { useStore } from "../../react/useStore.js";
|
|
4
5
|
import { PayloadFetchStore } from "../../store/PayloadFetchStore.js";
|
|
5
6
|
import { NONE, SECOND } from "../../util/constants.js";
|
|
6
7
|
import { formatValue } from "../../util/format.js";
|
|
8
|
+
import { Column } from "../block/Column.js";
|
|
7
9
|
import { ErrorNotice } from "../misc/Catcher.js";
|
|
8
10
|
import { LOADING_NOTICE, Notice } from "../notice/Notice.js";
|
|
9
11
|
import { ArrayRadioInputs } from "./ArrayRadioInputs.js";
|
|
@@ -13,28 +15,39 @@ import { SchemaInput } from "./SchemaInput.js";
|
|
|
13
15
|
* Combo box that queries a list of items and lets the user pick one from a popover.
|
|
14
16
|
* - Shows an input based on a `schema` of type `I`; its values are piped to the `onQuery()` callback.
|
|
15
17
|
* - Shows a `<Popover>` with a radio list of returned items to pick a final value of type `O`.
|
|
18
|
+
* - With `popover={false}`, shows the radio list inline below the input instead, like a `<select>` list box.
|
|
16
19
|
* - Errors, loading, and empty states are handled automatically.
|
|
17
20
|
*
|
|
18
|
-
* @returns A combo box element wrapping the input and results popover.
|
|
21
|
+
* @returns A combo box element wrapping the input and results popover (or the inline list).
|
|
19
22
|
* @example <QueryInput schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
23
|
+
* @example <QueryInput popover={false} schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
20
24
|
* @see https://shelving.cc/ui/QueryInput
|
|
21
25
|
*/
|
|
22
|
-
export function QueryInput({ empty = "No results", value, onValue, onQuery, formatter = formatValue, className, ...props }) {
|
|
26
|
+
export function QueryInput({ empty = "No results", value, onValue, onQuery, formatter = formatValue, popover = true, className, ...props }) {
|
|
23
27
|
const store = useStore(useInstance(PayloadFetchStore, NONE, undefined, onQuery, SECOND));
|
|
24
28
|
const busy = useStore(store.busy).value;
|
|
29
|
+
// Inline, query the schema's default value at once, so the list shows before anything is typed.
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!popover)
|
|
32
|
+
store.payload.value = props.schema.value;
|
|
33
|
+
}, [popover, store, props.schema]);
|
|
25
34
|
// Is popover open?
|
|
26
35
|
const isOpen = busy || !!store.reason || !!store.value;
|
|
27
36
|
const close = () => {
|
|
28
37
|
store.payload.value = NONE;
|
|
29
38
|
store.value = undefined;
|
|
30
39
|
};
|
|
40
|
+
const results = busy ? (LOADING_NOTICE) : store.reason ? (_jsx(ErrorNotice, { reason: store.reason })) : store.value?.length ? (_jsx(ArrayRadioInputs, { items: store.value, onValue: v => {
|
|
41
|
+
onValue(v); // Set the value.
|
|
42
|
+
if (popover)
|
|
43
|
+
close();
|
|
44
|
+
}, formatter: formatter, ...props })) : empty && store.value ? (_jsx(Notice, { children: empty })) : null;
|
|
45
|
+
if (!popover)
|
|
46
|
+
return (_jsxs(Column, { children: [_jsx(SchemaInput, { ...props, className: className, value: value, onValue: v => void (store.payload.value = v) }), results] }));
|
|
31
47
|
return (_jsxs(Popover, { open: isOpen, onClose: close, children: [_jsx(SchemaInput, { ...props, className: className, value: value, onValue: v => {
|
|
32
48
|
if (v)
|
|
33
49
|
store.payload.value = v;
|
|
34
50
|
else
|
|
35
51
|
close();
|
|
36
|
-
} }),
|
|
37
|
-
onValue(v); // Set the value.
|
|
38
|
-
close();
|
|
39
|
-
}, formatter: formatter, ...props })) : empty ? (_jsx(Notice, { children: empty })) : null] }));
|
|
52
|
+
} }), results] }));
|
|
40
53
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# QueryInput
|
|
2
|
+
|
|
3
|
+
Combo box that queries a list of items and lets the user pick one. The text in the input goes to `onQuery()`, and the items it returns show as a radio list.
|
|
4
|
+
|
|
5
|
+
**Things to know:**
|
|
6
|
+
|
|
7
|
+
- `onQuery()` is debounced (one second), and loading, error and empty states show automatically.
|
|
8
|
+
- By default the list shows in a `<Popover>`, which closes when the user picks an item.
|
|
9
|
+
- With `popover={false}` the list shows inline, below the input, like a `<select>` list box. It queries the schema's default value on mount, so the list shows before the user types. Picking an item keeps the list.
|
|
10
|
+
- `formatter` can return any `ReactNode`, for example an avatar, not only a string.
|
|
11
|
+
- `empty` sets the message for no results (`""` shows no message).
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
### Popover
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
import { QueryInput } from "shelving/ui";
|
|
19
|
+
|
|
20
|
+
<QueryInput name="user" schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
### Inline list with avatars
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
<QueryInput
|
|
27
|
+
popover={false}
|
|
28
|
+
name="user"
|
|
29
|
+
schema={SEARCH}
|
|
30
|
+
onQuery={search}
|
|
31
|
+
formatter={user => <Avatar user={user} />}
|
|
32
|
+
onValue={setUser}
|
|
33
|
+
/>
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Styling
|
|
37
|
+
|
|
38
|
+
The popover version uses the `<Popover>` styles. The inline version is a `<Column>` with the input and the `<ArrayRadioInputs>` list, so it uses their styles.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { renderToStaticMarkup } from "react-dom/server";
|
|
3
|
+
import { STRING } from "shelving/schema";
|
|
4
|
+
import { QueryInput } from "shelving/ui";
|
|
5
|
+
import { PASSTHROUGH } from "shelving/util/function";
|
|
6
|
+
|
|
7
|
+
describe("QueryInput", () => {
|
|
8
|
+
test("shows the input with no popover when `popover={false}`", () => {
|
|
9
|
+
const html = renderToStaticMarkup(<QueryInput popover={false} name="q" schema={STRING} onQuery={() => []} onValue={PASSTHROUGH} />);
|
|
10
|
+
expect(html).toContain('name="q"');
|
|
11
|
+
});
|
|
12
|
+
test("formatter can return a React element, not only a string", () => {
|
|
13
|
+
const element = (
|
|
14
|
+
<QueryInput<string, string> name="q" schema={STRING} onQuery={() => []} formatter={v => <strong>{v}</strong>} onValue={PASSTHROUGH} />
|
|
15
|
+
);
|
|
16
|
+
expect(element).toBeTruthy();
|
|
17
|
+
});
|
|
18
|
+
});
|
package/ui/input/QueryInput.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type ReactElement, type ReactNode, useEffect } from "react";
|
|
2
2
|
import { useInstance } from "../../react/useInstance.js";
|
|
3
3
|
import { useStore } from "../../react/useStore.js";
|
|
4
4
|
import type { Schema } from "../../schema/Schema.js";
|
|
@@ -6,6 +6,7 @@ import { type PayloadFetchCallback, PayloadFetchStore } from "../../store/Payloa
|
|
|
6
6
|
import type { ImmutableArray } from "../../util/array.js";
|
|
7
7
|
import { NONE, SECOND } from "../../util/constants.js";
|
|
8
8
|
import { formatValue } from "../../util/format.js";
|
|
9
|
+
import { Column } from "../block/Column.js";
|
|
9
10
|
import { ErrorNotice } from "../misc/Catcher.js";
|
|
10
11
|
import { LOADING_NOTICE, Notice } from "../notice/Notice.js";
|
|
11
12
|
import { ArrayRadioInputs } from "./ArrayRadioInputs.js";
|
|
@@ -26,12 +27,19 @@ export interface QueryInputProps<I, O> extends ValueInputProps<O> {
|
|
|
26
27
|
* Called with the current text value to return matching items whenever the text input changes.
|
|
27
28
|
* - Automatically debounced, so only called after a short delay.
|
|
28
29
|
* - Automatically shows a loading state while loading.
|
|
29
|
-
* - Returning `undefined` signals to close the popover.
|
|
30
|
+
* - Returning `undefined` signals to close the popover (or, with `popover={false}`, to show no list).
|
|
30
31
|
*/
|
|
31
32
|
onQuery: PayloadFetchCallback<I, ImmutableArray<O> | undefined>;
|
|
32
33
|
|
|
33
|
-
/** Format an item of type `O` for display in the picker. */
|
|
34
|
-
formatter?: ((value: O) =>
|
|
34
|
+
/** Format an item of type `O` for display in the picker, for example as text or as an avatar. */
|
|
35
|
+
formatter?: ((value: O) => ReactNode) | undefined;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Show the results in a popover (the default), or set `false` to show them inline, as a list below the input.
|
|
39
|
+
* - Inline, the list shows at once: `onQuery()` is called with the schema's default value (e.g. `""`) on mount.
|
|
40
|
+
* - Inline, an empty input still queries, and picking an item keeps the list.
|
|
41
|
+
*/
|
|
42
|
+
popover?: boolean | undefined;
|
|
35
43
|
|
|
36
44
|
/** Message that shows when query returns `[]` empty array (set to `""` empty string to show no message). */
|
|
37
45
|
empty?: ReactNode | undefined;
|
|
@@ -41,10 +49,12 @@ export interface QueryInputProps<I, O> extends ValueInputProps<O> {
|
|
|
41
49
|
* Combo box that queries a list of items and lets the user pick one from a popover.
|
|
42
50
|
* - Shows an input based on a `schema` of type `I`; its values are piped to the `onQuery()` callback.
|
|
43
51
|
* - Shows a `<Popover>` with a radio list of returned items to pick a final value of type `O`.
|
|
52
|
+
* - With `popover={false}`, shows the radio list inline below the input instead, like a `<select>` list box.
|
|
44
53
|
* - Errors, loading, and empty states are handled automatically.
|
|
45
54
|
*
|
|
46
|
-
* @returns A combo box element wrapping the input and results popover.
|
|
55
|
+
* @returns A combo box element wrapping the input and results popover (or the inline list).
|
|
47
56
|
* @example <QueryInput schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
57
|
+
* @example <QueryInput popover={false} schema={SEARCH} onQuery={search} value={user} onValue={setUser} />
|
|
48
58
|
* @see https://shelving.cc/ui/QueryInput
|
|
49
59
|
*/
|
|
50
60
|
export function QueryInput<I, O>({
|
|
@@ -53,12 +63,18 @@ export function QueryInput<I, O>({
|
|
|
53
63
|
onValue,
|
|
54
64
|
onQuery,
|
|
55
65
|
formatter = formatValue,
|
|
66
|
+
popover = true,
|
|
56
67
|
className,
|
|
57
68
|
...props
|
|
58
69
|
}: QueryInputProps<I, O>): ReactElement {
|
|
59
70
|
const store = useStore(useInstance(PayloadFetchStore, NONE, undefined, onQuery, SECOND));
|
|
60
71
|
const busy = useStore(store.busy).value;
|
|
61
72
|
|
|
73
|
+
// Inline, query the schema's default value at once, so the list shows before anything is typed.
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
if (!popover) store.payload.value = props.schema.value as I;
|
|
76
|
+
}, [popover, store, props.schema]);
|
|
77
|
+
|
|
62
78
|
// Is popover open?
|
|
63
79
|
const isOpen = busy || !!store.reason || !!store.value;
|
|
64
80
|
|
|
@@ -67,6 +83,32 @@ export function QueryInput<I, O>({
|
|
|
67
83
|
store.value = undefined;
|
|
68
84
|
};
|
|
69
85
|
|
|
86
|
+
const results = busy ? (
|
|
87
|
+
LOADING_NOTICE
|
|
88
|
+
) : store.reason ? (
|
|
89
|
+
<ErrorNotice reason={store.reason} />
|
|
90
|
+
) : store.value?.length ? (
|
|
91
|
+
<ArrayRadioInputs
|
|
92
|
+
items={store.value}
|
|
93
|
+
onValue={v => {
|
|
94
|
+
onValue(v); // Set the value.
|
|
95
|
+
if (popover) close();
|
|
96
|
+
}}
|
|
97
|
+
formatter={formatter}
|
|
98
|
+
{...props}
|
|
99
|
+
/>
|
|
100
|
+
) : empty && store.value ? (
|
|
101
|
+
<Notice>{empty}</Notice>
|
|
102
|
+
) : null;
|
|
103
|
+
|
|
104
|
+
if (!popover)
|
|
105
|
+
return (
|
|
106
|
+
<Column>
|
|
107
|
+
<SchemaInput {...props} className={className} value={value as I} onValue={v => void (store.payload.value = v as I)} />
|
|
108
|
+
{results}
|
|
109
|
+
</Column>
|
|
110
|
+
);
|
|
111
|
+
|
|
70
112
|
return (
|
|
71
113
|
<Popover open={isOpen} onClose={close}>
|
|
72
114
|
<SchemaInput
|
|
@@ -78,23 +120,7 @@ export function QueryInput<I, O>({
|
|
|
78
120
|
else close();
|
|
79
121
|
}}
|
|
80
122
|
/>
|
|
81
|
-
{
|
|
82
|
-
LOADING_NOTICE
|
|
83
|
-
) : store.reason ? (
|
|
84
|
-
<ErrorNotice reason={store.reason} />
|
|
85
|
-
) : store.value?.length ? (
|
|
86
|
-
<ArrayRadioInputs
|
|
87
|
-
items={store.value}
|
|
88
|
-
onValue={v => {
|
|
89
|
-
onValue(v); // Set the value.
|
|
90
|
-
close();
|
|
91
|
-
}}
|
|
92
|
-
formatter={formatter}
|
|
93
|
-
{...props}
|
|
94
|
-
/>
|
|
95
|
-
) : empty ? (
|
|
96
|
-
<Notice>{empty}</Notice>
|
|
97
|
-
) : null}
|
|
123
|
+
{results}
|
|
98
124
|
</Popover>
|
|
99
125
|
);
|
|
100
126
|
}
|
|
@@ -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
|
package/ui/router/RouteCache.js
CHANGED
|
@@ -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
|
|
34
|
-
//
|
|
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
|
|
38
|
-
const entry = map.get(
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
|
|
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
|
|
49
|
-
return Array.from(map, ([
|
|
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) {
|
package/ui/router/RouteCache.md
CHANGED
|
@@ -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.
|
package/ui/router/RouteCache.tsx
CHANGED
|
@@ -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
|
|
59
|
+
if (maxCached <= 0) return <MetaContext value={meta}>{children}</MetaContext>;
|
|
60
60
|
|
|
61
|
-
//
|
|
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
|
|
65
|
-
const entry = map.get(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
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
|
|
75
|
-
return Array.from(map, ([
|
|
76
|
-
<Activity key={
|
|
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
|
+
}
|
package/ui/router/Router.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
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
|
package/ui/router/Router.js
CHANGED
|
@@ -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
|
-
|
|
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 },
|
|
59
|
+
return _jsx(Route, { ...meta.params, ...placeholders }, key);
|
|
48
60
|
}
|
|
49
61
|
// No match, try the fallback.
|
|
50
62
|
if (fallback !== undefined)
|
package/ui/router/Router.tsx
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import type
|
|
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
|
-
|
|
42
|
-
|
|
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={
|
|
92
|
+
return <Route key={key} {...meta.params} {...placeholders} />;
|
|
73
93
|
}
|
|
74
94
|
|
|
75
95
|
// No match, try the fallback.
|
package/ui/router/index.d.ts
CHANGED
|
@@ -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";
|
package/ui/router/index.js
CHANGED
|
@@ -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";
|
package/ui/router/index.ts
CHANGED
|
@@ -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";
|