@tschk/moonshine-router 0.4.4 → 0.4.80
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/README.md +199 -0
- package/package.json +7 -4
- package/src/data-http.ts +160 -0
- package/src/data-react.ts +41 -0
- package/src/data.ts +138 -0
- package/src/index.ts +1 -0
- package/src/navigation.ts +5 -0
- package/src/runtime.ts +16 -0
package/README.md
CHANGED
|
@@ -55,3 +55,202 @@ including `#`. Navigation and browser synchronization update it alongside
|
|
|
55
55
|
history and location. `getLocation()` and `location` retain pathname plus query
|
|
56
56
|
only. An explicit initial URL supplies its own fragment; the default runtime
|
|
57
57
|
starts from the browser URL.
|
|
58
|
+
|
|
59
|
+
## Opt-in client data
|
|
60
|
+
|
|
61
|
+
`@tschk/moonshine-router/data` adds loading and mutation ownership without React
|
|
62
|
+
or a host router. It does not import server route modules into the browser.
|
|
63
|
+
Supply client-safe operations, such as requests to your existing API routes:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { createDataRouter } from "@tschk/moonshine-router/data";
|
|
67
|
+
|
|
68
|
+
const router = createDataRouter(async ({ location, signal }) => {
|
|
69
|
+
const response = await fetch(
|
|
70
|
+
`/api/page?path=${encodeURIComponent(location)}`,
|
|
71
|
+
{
|
|
72
|
+
signal,
|
|
73
|
+
},
|
|
74
|
+
);
|
|
75
|
+
if (!response.ok) throw new Error(`Load failed: ${response.status}`);
|
|
76
|
+
return response.json();
|
|
77
|
+
}, "/");
|
|
78
|
+
|
|
79
|
+
const unsubscribe = router.data.subscribe(() => {
|
|
80
|
+
const { status, data, error } = router.data.peek();
|
|
81
|
+
// Render pending, ready or errored state with your chosen renderer.
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
await router.submit(async ({ signal }) => {
|
|
85
|
+
const response = await fetch("/api/save", { method: "POST", signal });
|
|
86
|
+
if (!response.ok) throw new Error(`Save failed: ${response.status}`);
|
|
87
|
+
return response.json();
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
await router.invalidate();
|
|
91
|
+
unsubscribe();
|
|
92
|
+
router.dispose();
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Loading starts immediately and follows pathname/query changes; history-only and
|
|
96
|
+
fragment changes do not reload. Invalidation retains the current location's data
|
|
97
|
+
while pending; navigation clears data from the previous location. Errors appear
|
|
98
|
+
in `data` and explicit invalidation rejects. Superseded loads cannot publish,
|
|
99
|
+
even if they ignore cancellation. Invalidation promises follow the latest load
|
|
100
|
+
until it settles. Each runtime owns its own work.
|
|
101
|
+
|
|
102
|
+
`submit` exposes `submitting`, returns the action result and revalidates after
|
|
103
|
+
success. Failed actions reject. A failed follow-up load appears in `data.error`
|
|
104
|
+
without changing the successful action result. A newer submission, navigation or
|
|
105
|
+
disposal aborts the old action. Any successful write still revalidates the current
|
|
106
|
+
location unless the runtime has been disposed.
|
|
107
|
+
Abort signals do not roll back a server write, and operations that ignore them
|
|
108
|
+
may still finish; their original promises retain their own results/errors.
|
|
109
|
+
Dispose aborts work and unsubscribes navigation; later loads/submissions reject.
|
|
110
|
+
|
|
111
|
+
Pass this runtime to `MoonshineRouter` for React consumers. TanStack's
|
|
112
|
+
`useRouter().invalidate()` delegates to it. Navigation-only runtimes reject that
|
|
113
|
+
call rather than silently succeeding. TanStack loading state follows this runtime; loader failures stay in its data
|
|
114
|
+
state when invalidating through the adapter. TanStack loader hooks, route
|
|
115
|
+
registries, matches, automatic SSR data transport and hydration remain unsupported. This
|
|
116
|
+
entry adds no automatic data endpoint, server serialization or route cache.
|
|
117
|
+
|
|
118
|
+
### Initial ready data
|
|
119
|
+
|
|
120
|
+
Pass an explicit location-bound seed as the third argument to reuse data already
|
|
121
|
+
loaded by the application, including server loader results:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
const seed = { location: "/posts?sort=new", data: { title: "Latest posts" } };
|
|
125
|
+
const router = createDataRouter(loadClientData, seed.location, seed);
|
|
126
|
+
// The state is immediately ready; loadClientData has not run.
|
|
127
|
+
await router.invalidate(); // Explicit reloads still run the client loader.
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
The seed location must exactly equal the runtime's canonical pathname plus
|
|
131
|
+
query. A mismatched path or query discards the seed and starts the normal initial
|
|
132
|
+
load; fragments are absent from that key. Falsy values and an explicitly typed
|
|
133
|
+
`undefined` payload are valid ready data. Later navigation, invalidation,
|
|
134
|
+
submission and disposal keep their ordinary behavior. Seeds are per runtime,
|
|
135
|
+
with no global cache, expiry policy or automatic refresh.
|
|
136
|
+
|
|
137
|
+
Applications choose the payload and own its transport and validation. When
|
|
138
|
+
embedding it in HTML, use the existing server `serializeData` helper for HTML-safe
|
|
139
|
+
JSON. This constructor does not read document scripts, serialize errors, infer
|
|
140
|
+
nested loader matches or hydrate existing DOM.
|
|
141
|
+
|
|
142
|
+
React applications can read the complete owning runtime state through the
|
|
143
|
+
separate `@tschk/moonshine-router/data-react` entry:
|
|
144
|
+
|
|
145
|
+
```tsx
|
|
146
|
+
import { useRouteData } from "@tschk/moonshine-router/data-react";
|
|
147
|
+
|
|
148
|
+
function Page() {
|
|
149
|
+
const { status, data, error } = useRouteData();
|
|
150
|
+
if (status === "errored") return <p>{String(error)}</p>;
|
|
151
|
+
return (
|
|
152
|
+
<output aria-busy={status === "pending"}>
|
|
153
|
+
{String(data ?? "Loading")}
|
|
154
|
+
</output>
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
Supply a `createDataRouter` runtime to the enclosing `MoonshineRouter`; a
|
|
160
|
+
navigation-only runtime rejects this hook. The hook returns the complete stable
|
|
161
|
+
state snapshot, including retained data during same-location reloads and loader
|
|
162
|
+
errors as values. Data is `unknown` and applications must narrow it before use.
|
|
163
|
+
Subscriptions follow the owning runtime and stop when the component unmounts.
|
|
164
|
+
SSR reads only that runtime's current snapshot; this does not extract or serialize
|
|
165
|
+
server data, suspend rendering, select nested route matches, or add hydration.
|
|
166
|
+
The renderer-neutral `/data` entry remains React-free.
|
|
167
|
+
|
|
168
|
+
Components can submit through that same owning runtime without capturing it
|
|
169
|
+
outside the provider:
|
|
170
|
+
|
|
171
|
+
```tsx
|
|
172
|
+
import {
|
|
173
|
+
useRouteSubmit,
|
|
174
|
+
useRouteSubmitting,
|
|
175
|
+
} from "@tschk/moonshine-router/data-react";
|
|
176
|
+
import type { RouteDataContext } from "@tschk/moonshine-router/data";
|
|
177
|
+
|
|
178
|
+
function Save({
|
|
179
|
+
write,
|
|
180
|
+
onError,
|
|
181
|
+
}: {
|
|
182
|
+
write: (context: RouteDataContext) => Promise<void>;
|
|
183
|
+
onError: (error: unknown) => void;
|
|
184
|
+
}) {
|
|
185
|
+
const submit = useRouteSubmit();
|
|
186
|
+
const pending = useRouteSubmitting();
|
|
187
|
+
return (
|
|
188
|
+
<button
|
|
189
|
+
disabled={pending}
|
|
190
|
+
onClick={() => void submit(write).catch(onError)}
|
|
191
|
+
>
|
|
192
|
+
Save
|
|
193
|
+
</button>
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`useRouteSubmit` preserves the action result type and returns the runtime's stable
|
|
199
|
+
runner. `useRouteSubmitting` follows its latest active submission, including
|
|
200
|
+
follow-up revalidation; it does not count all unresolved cancelled operations.
|
|
201
|
+
Both follow provider replacement and reject a navigation-only runtime. SSR reads
|
|
202
|
+
the owning state; unmount unsubscribes React, while the application still owns
|
|
203
|
+
runtime disposal. Failed actions reject their own promises. A successful action
|
|
204
|
+
keeps its result if the follow-up loader fails, with that error in `useRouteData`.
|
|
205
|
+
Successful cancelled/superseded actions still revalidate current data unless
|
|
206
|
+
disposed, since cancellation cannot undo their writes.
|
|
207
|
+
|
|
208
|
+
A real HTTP/Chromium form checks ten phases covering write success/failure,
|
|
209
|
+
supersession, reload failure, recovery, navigation and disposal, with input
|
|
210
|
+
identity/focus/selection retained during updates. The existing reader-only
|
|
211
|
+
consumer stays 3,084 raw / 1,343 gzip bytes; the whole form fixture is 60,836 gzip
|
|
212
|
+
bytes including React DOM and test controls. No host-router or timing comparison
|
|
213
|
+
is claimed. Applications own form serialization, transport and validation;
|
|
214
|
+
host `useSubmit`/`useNavigation` semantics and nested loader lifecycles remain open.
|
|
215
|
+
|
|
216
|
+
## Optional HTTP route data
|
|
217
|
+
|
|
218
|
+
`@tschk/moonshine-router/data-http` connects the data runtime to server route
|
|
219
|
+
loaders/actions. Enable `dataRequests` in the server handler or your Bun/Node
|
|
220
|
+
`moonshine.config.ts` first; see the [server protocol](../server/README.md#opt-in-route-data-responses).
|
|
221
|
+
This entry imports no renderer, React, host router or server module.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { createDataRouter } from "@tschk/moonshine-router/data";
|
|
225
|
+
import { createRouteDataClient } from "@tschk/moonshine-router/data-http";
|
|
226
|
+
import { decodePage } from "./validation"; // Your application validates unknown JSON.
|
|
227
|
+
|
|
228
|
+
const client = createRouteDataClient(); // Uses the browser origin.
|
|
229
|
+
const router = createDataRouter(async (context) =>
|
|
230
|
+
decodePage(await client.load(context)),
|
|
231
|
+
);
|
|
232
|
+
|
|
233
|
+
const result = await router.submit((context) =>
|
|
234
|
+
client.action(context, {
|
|
235
|
+
method: "POST",
|
|
236
|
+
body: new URLSearchParams({ title: "Updated" }),
|
|
237
|
+
}),
|
|
238
|
+
);
|
|
239
|
+
// result is unknown until your application validates it.
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
`load` returns the whole server loader-data map. `action` returns the action's
|
|
243
|
+
JSON value; the existing router then performs one independent reload. A failed
|
|
244
|
+
reload retains the successful action result. Bodyless protocol successes
|
|
245
|
+
(204/205) return `null`. Applications own body encoding, authentication,
|
|
246
|
+
authorization and payload validation. Opted-in loader/action results become
|
|
247
|
+
client-visible data; return only the values intended for the client.
|
|
248
|
+
|
|
249
|
+
Requests stay within the configured origin, carry the owning abort signal and
|
|
250
|
+
use same-origin credentials/mode. Nonbrowser callers supply `origin` explicitly.
|
|
251
|
+
Non-2xx responses are thrown as `Response` values for caller inspection; network
|
|
252
|
+
and abort failures retain their errors. Redirects are rejected by fetch and are
|
|
253
|
+
not converted into navigation. Explicit server `Response` values and error
|
|
254
|
+
boundaries remain ordinary HTTP, not protocol envelopes. Aborting observation
|
|
255
|
+
cannot roll back a server write; an uncertain outcome may need an explicit refresh.
|
|
256
|
+
This does not implement host forms, fetchers, RSC or hydration.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tschk/moonshine-router",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.80",
|
|
4
4
|
"description": "Renderer-neutral route graph and matcher with optional React navigation",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"type": "module",
|
|
@@ -9,7 +9,10 @@
|
|
|
9
9
|
"exports": {
|
|
10
10
|
".": "./src/index.ts",
|
|
11
11
|
"./graph": "./src/graph.ts",
|
|
12
|
-
"./runtime": "./src/runtime.ts"
|
|
12
|
+
"./runtime": "./src/runtime.ts",
|
|
13
|
+
"./data": "./src/data.ts",
|
|
14
|
+
"./data-react": "./src/data-react.ts",
|
|
15
|
+
"./data-http": "./src/data-http.ts"
|
|
13
16
|
},
|
|
14
17
|
"files": [
|
|
15
18
|
"src"
|
|
@@ -21,8 +24,8 @@
|
|
|
21
24
|
"test": "bun test"
|
|
22
25
|
},
|
|
23
26
|
"dependencies": {
|
|
24
|
-
"@tschk/moonshine": "^0.4.
|
|
25
|
-
"@tschk/moonshine-framework": "^0.4.
|
|
27
|
+
"@tschk/moonshine": "^0.4.80",
|
|
28
|
+
"@tschk/moonshine-framework": "^0.4.80"
|
|
26
29
|
},
|
|
27
30
|
"devDependencies": {
|
|
28
31
|
"@types/bun": "1.3.14",
|
package/src/data-http.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import {
|
|
2
|
+
normalizeRouteDataOrigin,
|
|
3
|
+
ROUTE_DATA_HEADER,
|
|
4
|
+
ROUTE_DATA_VERSION,
|
|
5
|
+
} from "@tschk/moonshine-framework/data-request";
|
|
6
|
+
import type { RouteDataContext } from "./data";
|
|
7
|
+
|
|
8
|
+
export type RouteDataClientOptions = {
|
|
9
|
+
origin?: string;
|
|
10
|
+
fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type RouteDataActionMethod = "POST" | "PUT" | "PATCH" | "DELETE";
|
|
14
|
+
|
|
15
|
+
export type RouteDataActionInit = Omit<
|
|
16
|
+
RequestInit,
|
|
17
|
+
"method" | "signal" | "credentials" | "redirect" | "mode"
|
|
18
|
+
> & { method: RouteDataActionMethod };
|
|
19
|
+
|
|
20
|
+
export type RouteDataClient = {
|
|
21
|
+
load(context: RouteDataContext): Promise<unknown>;
|
|
22
|
+
action(
|
|
23
|
+
context: RouteDataContext,
|
|
24
|
+
init: RouteDataActionInit,
|
|
25
|
+
): Promise<unknown>;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const ACTION_METHODS: Record<string, true> = {
|
|
29
|
+
POST: true,
|
|
30
|
+
PUT: true,
|
|
31
|
+
PATCH: true,
|
|
32
|
+
DELETE: true,
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
function resolveOrigin(value: string | undefined): string {
|
|
36
|
+
const raw =
|
|
37
|
+
value ??
|
|
38
|
+
("location" in globalThis ? globalThis.location?.origin : undefined);
|
|
39
|
+
if (typeof raw !== "string" || raw === "") {
|
|
40
|
+
throw new TypeError(
|
|
41
|
+
"createRouteDataClient requires an absolute http(s) origin; pass options.origin when no browser location exists",
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
return normalizeRouteDataOrigin(raw);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function resolveLocation(origin: string, location: string): string {
|
|
48
|
+
let url: URL;
|
|
49
|
+
try {
|
|
50
|
+
url = new URL(location, origin);
|
|
51
|
+
} catch {
|
|
52
|
+
throw new TypeError("Invalid route-data location");
|
|
53
|
+
}
|
|
54
|
+
if (url.origin !== origin || url.username !== "" || url.password !== "") {
|
|
55
|
+
throw new TypeError(
|
|
56
|
+
`Route-data location must be within origin ${origin} and without credentials`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
url.hash = "";
|
|
60
|
+
return url.href;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isJson(response: Response): boolean {
|
|
64
|
+
const type = response.headers.get("content-type");
|
|
65
|
+
return type !== null && /^\s*application\/json\s*(;|$)/i.test(type);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function reject(response: Response, message: string): never {
|
|
69
|
+
try {
|
|
70
|
+
void response.body?.cancel().catch(() => {});
|
|
71
|
+
} catch {}
|
|
72
|
+
throw new TypeError(message);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function decode(response: Response): Promise<unknown> {
|
|
76
|
+
if (!response.ok) throw response;
|
|
77
|
+
if (response.headers.get(ROUTE_DATA_HEADER) !== ROUTE_DATA_VERSION) {
|
|
78
|
+
return reject(
|
|
79
|
+
response,
|
|
80
|
+
`Route-data response is missing ${ROUTE_DATA_HEADER}: ${ROUTE_DATA_VERSION}`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
if (!isJson(response)) {
|
|
84
|
+
return reject(response, "Route-data response is not application/json");
|
|
85
|
+
}
|
|
86
|
+
if (response.status === 204 || response.status === 205) return null;
|
|
87
|
+
let body: unknown;
|
|
88
|
+
try {
|
|
89
|
+
body = await response.json();
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (error instanceof SyntaxError)
|
|
92
|
+
throw new TypeError("Route-data response body is not valid JSON", {
|
|
93
|
+
cause: error,
|
|
94
|
+
});
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
if (
|
|
98
|
+
typeof body !== "object" ||
|
|
99
|
+
body === null ||
|
|
100
|
+
Array.isArray(body) ||
|
|
101
|
+
!("data" in body) ||
|
|
102
|
+
!Object.hasOwn(body, "data")
|
|
103
|
+
) {
|
|
104
|
+
throw new TypeError(
|
|
105
|
+
"Route-data response must be an object envelope with an own data field",
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return body.data;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function createRouteDataClient(
|
|
112
|
+
options: RouteDataClientOptions = {},
|
|
113
|
+
): RouteDataClient {
|
|
114
|
+
const origin = resolveOrigin(options.origin);
|
|
115
|
+
const doFetch: NonNullable<RouteDataClientOptions["fetch"]> =
|
|
116
|
+
options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
117
|
+
|
|
118
|
+
async function send(
|
|
119
|
+
context: RouteDataContext,
|
|
120
|
+
method: string,
|
|
121
|
+
init: Omit<
|
|
122
|
+
RequestInit,
|
|
123
|
+
"method" | "signal" | "credentials" | "redirect" | "mode"
|
|
124
|
+
>,
|
|
125
|
+
): Promise<unknown> {
|
|
126
|
+
context.signal.throwIfAborted();
|
|
127
|
+
const url = resolveLocation(origin, context.location);
|
|
128
|
+
const headers = new Headers(init.headers);
|
|
129
|
+
headers.set(ROUTE_DATA_HEADER, ROUTE_DATA_VERSION);
|
|
130
|
+
const response = await doFetch(url, {
|
|
131
|
+
...init,
|
|
132
|
+
method,
|
|
133
|
+
headers,
|
|
134
|
+
signal: context.signal,
|
|
135
|
+
credentials: "same-origin",
|
|
136
|
+
mode: "same-origin",
|
|
137
|
+
redirect: "error",
|
|
138
|
+
});
|
|
139
|
+
return decode(response);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
load(context) {
|
|
144
|
+
return send(context, "GET", {});
|
|
145
|
+
},
|
|
146
|
+
action(context, init) {
|
|
147
|
+
const method =
|
|
148
|
+
typeof init?.method === "string" ? init.method.toUpperCase() : "";
|
|
149
|
+
if (!Object.hasOwn(ACTION_METHODS, method)) {
|
|
150
|
+
return Promise.reject(
|
|
151
|
+
new TypeError(
|
|
152
|
+
"Route-data action method must be POST, PUT, PATCH or DELETE",
|
|
153
|
+
),
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
const { method: _method, ...rest } = init;
|
|
157
|
+
return send(context, method, rest);
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
import { useSyncExternalStore } from "react";
|
|
4
|
+
import type { RouteDataState } from "./data";
|
|
5
|
+
import { useRouter } from "./navigation";
|
|
6
|
+
import type { MoonshineRouterInstance } from "./runtime";
|
|
7
|
+
|
|
8
|
+
/** Subscribe to the owning data runtime's complete state; loader errors stay in `error`. */
|
|
9
|
+
export function useRouteData(): RouteDataState<unknown> {
|
|
10
|
+
const source = useRouter().data;
|
|
11
|
+
if (!source) {
|
|
12
|
+
throw new Error(
|
|
13
|
+
"useRouteData requires a router with a data runtime; pass createDataRouter() as the MoonshineRouter runtime.",
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
return useSyncExternalStore(source.subscribe, source.peek, source.peek);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Return the owning data runtime's action runner, stable per runtime. */
|
|
20
|
+
export function useRouteSubmit(): NonNullable<
|
|
21
|
+
MoonshineRouterInstance["submit"]
|
|
22
|
+
> {
|
|
23
|
+
const submit = useRouter().submit;
|
|
24
|
+
if (!submit) {
|
|
25
|
+
throw new Error(
|
|
26
|
+
"useRouteSubmit requires a router with a data runtime; pass createDataRouter() as the MoonshineRouter runtime.",
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
return submit;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Subscribe to the owning runtime's current submission state. */
|
|
33
|
+
export function useRouteSubmitting(): boolean {
|
|
34
|
+
const source = useRouter().submitting;
|
|
35
|
+
if (!source) {
|
|
36
|
+
throw new Error(
|
|
37
|
+
"useRouteSubmitting requires a router with a data runtime; pass createDataRouter() as the MoonshineRouter runtime.",
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
return useSyncExternalStore(source.subscribe, source.peek, source.peek);
|
|
41
|
+
}
|
package/src/data.ts
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { createSignal, type Signal } from "@tschk/moonshine";
|
|
2
|
+
import { createMoonshineRouter, type MoonshineRouterInstance } from "./runtime";
|
|
3
|
+
|
|
4
|
+
export type RouteDataContext = { location: string; signal: AbortSignal };
|
|
5
|
+
export type RouteDataSeed<T> = { location: string; data: T };
|
|
6
|
+
export type RouteDataState<T> = {
|
|
7
|
+
location: string;
|
|
8
|
+
status: "pending" | "ready" | "errored";
|
|
9
|
+
data: T | undefined;
|
|
10
|
+
error: unknown;
|
|
11
|
+
};
|
|
12
|
+
export type DataRouter<T> = Omit<
|
|
13
|
+
MoonshineRouterInstance,
|
|
14
|
+
"data" | "invalidate" | "submit" | "submitting"
|
|
15
|
+
> & {
|
|
16
|
+
data: Signal<RouteDataState<T>>;
|
|
17
|
+
submitting: Signal<boolean>;
|
|
18
|
+
invalidate(): Promise<T | undefined>;
|
|
19
|
+
submit<R>(action: (context: RouteDataContext) => R | Promise<R>): Promise<R>;
|
|
20
|
+
dispose(): void;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Opt-in client data ownership. Loaders/actions receive cancellation, not server code. */
|
|
24
|
+
export function createDataRouter<T>(
|
|
25
|
+
load: (context: RouteDataContext) => T | Promise<T>,
|
|
26
|
+
initialPath?: string,
|
|
27
|
+
initialData?: RouteDataSeed<T>,
|
|
28
|
+
): DataRouter<T> {
|
|
29
|
+
const runtime = createMoonshineRouter(initialPath);
|
|
30
|
+
const location = runtime.location.peek();
|
|
31
|
+
const seed = initialData?.location === location ? initialData : undefined;
|
|
32
|
+
const data = createSignal<RouteDataState<T>>({
|
|
33
|
+
location,
|
|
34
|
+
status: seed ? "ready" : "pending",
|
|
35
|
+
data: seed?.data,
|
|
36
|
+
error: undefined,
|
|
37
|
+
});
|
|
38
|
+
const submitting = createSignal(false);
|
|
39
|
+
let disposed = false;
|
|
40
|
+
let generation = 0;
|
|
41
|
+
let actionGeneration = 0;
|
|
42
|
+
let controller: AbortController | undefined;
|
|
43
|
+
let actionController: AbortController | undefined;
|
|
44
|
+
|
|
45
|
+
let pending:
|
|
46
|
+
ReturnType<typeof Promise.withResolvers<T | undefined>> | undefined;
|
|
47
|
+
function invalidate(): Promise<T | undefined> {
|
|
48
|
+
if (disposed) return Promise.reject(new Error("Data router is disposed"));
|
|
49
|
+
const previous = pending;
|
|
50
|
+
const current = Promise.withResolvers<T | undefined>();
|
|
51
|
+
pending = current;
|
|
52
|
+
previous?.resolve(current.promise);
|
|
53
|
+
void runLoad(++generation).then(current.resolve, current.reject);
|
|
54
|
+
return current.promise;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function runLoad(token: number): Promise<T | undefined> {
|
|
58
|
+
const previous = controller;
|
|
59
|
+
const current = new AbortController();
|
|
60
|
+
controller = current;
|
|
61
|
+
previous?.abort();
|
|
62
|
+
if (disposed || token !== generation) return undefined;
|
|
63
|
+
const location = runtime.location.peek();
|
|
64
|
+
data.set({
|
|
65
|
+
location,
|
|
66
|
+
status: "pending",
|
|
67
|
+
data: data.peek().location === location ? data.peek().data : undefined,
|
|
68
|
+
error: undefined,
|
|
69
|
+
});
|
|
70
|
+
if (disposed || token !== generation) return undefined;
|
|
71
|
+
let value: T;
|
|
72
|
+
try {
|
|
73
|
+
value = await load({ location, signal: current.signal });
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (disposed || token !== generation) return undefined;
|
|
76
|
+
data.set({ ...data.peek(), status: "errored", error });
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
if (disposed || token !== generation) return undefined;
|
|
80
|
+
data.set({ location, status: "ready", data: value, error: undefined });
|
|
81
|
+
return value;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function cancelAction() {
|
|
85
|
+
const token = ++actionGeneration;
|
|
86
|
+
const previous = actionController;
|
|
87
|
+
actionController = undefined;
|
|
88
|
+
previous?.abort();
|
|
89
|
+
if (token === actionGeneration) submitting.set(false);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function submit<R>(
|
|
93
|
+
action: (context: RouteDataContext) => R | Promise<R>,
|
|
94
|
+
): Promise<R> {
|
|
95
|
+
if (disposed) throw new Error("Data router is disposed");
|
|
96
|
+
const token = ++actionGeneration;
|
|
97
|
+
const previous = actionController;
|
|
98
|
+
const current = new AbortController();
|
|
99
|
+
actionController = current;
|
|
100
|
+
previous?.abort();
|
|
101
|
+
current.signal.throwIfAborted();
|
|
102
|
+
if (disposed || token !== actionGeneration)
|
|
103
|
+
throw new DOMException("Action superseded", "AbortError");
|
|
104
|
+
const location = runtime.location.peek();
|
|
105
|
+
submitting.set(true);
|
|
106
|
+
try {
|
|
107
|
+
current.signal.throwIfAborted();
|
|
108
|
+
const result = await action({ location, signal: current.signal });
|
|
109
|
+
if (!disposed) await invalidate().catch(() => {});
|
|
110
|
+
return result;
|
|
111
|
+
} finally {
|
|
112
|
+
if (!disposed && token === actionGeneration) submitting.set(false);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const unsubscribe = runtime.location.subscribe(() => {
|
|
117
|
+
cancelAction();
|
|
118
|
+
void invalidate().catch(() => {});
|
|
119
|
+
});
|
|
120
|
+
if (!seed) void invalidate().catch(() => {});
|
|
121
|
+
return {
|
|
122
|
+
...runtime,
|
|
123
|
+
data,
|
|
124
|
+
submitting,
|
|
125
|
+
invalidate,
|
|
126
|
+
submit,
|
|
127
|
+
dispose() {
|
|
128
|
+
if (disposed) return;
|
|
129
|
+
disposed = true;
|
|
130
|
+
++generation;
|
|
131
|
+
pending?.resolve(undefined);
|
|
132
|
+
pending = undefined;
|
|
133
|
+
unsubscribe();
|
|
134
|
+
controller?.abort();
|
|
135
|
+
cancelAction();
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
package/src/index.ts
CHANGED
package/src/navigation.ts
CHANGED
|
@@ -43,6 +43,11 @@ export function navigate(
|
|
|
43
43
|
currentRouter().navigate(to, options);
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
+
/** The router `navigate` targets: the innermost mounted one, else the fallback. */
|
|
47
|
+
export function getRouter(): MoonshineRouterInstance {
|
|
48
|
+
return currentRouter();
|
|
49
|
+
}
|
|
50
|
+
|
|
46
51
|
/** Current pathname and query (reactive; active or fallback router). */
|
|
47
52
|
export function getLocation(): string {
|
|
48
53
|
return currentRouter().getLocation();
|
package/src/runtime.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { batch, createSignal, type Signal } from "@tschk/moonshine";
|
|
2
|
+
import type { RouteDataContext, RouteDataState } from "./data.js";
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* The location the signal carries: pathname plus query.
|
|
@@ -30,6 +31,21 @@ export type HistorySnapshot = {
|
|
|
30
31
|
};
|
|
31
32
|
|
|
32
33
|
export type MoonshineRouterInstance = {
|
|
34
|
+
/** Optional opt-in data runtime; absent on navigation-only routers. */
|
|
35
|
+
invalidate?: () => Promise<unknown>;
|
|
36
|
+
data?: {
|
|
37
|
+
peek(): RouteDataState<unknown>;
|
|
38
|
+
subscribe(listener: () => void): () => void;
|
|
39
|
+
};
|
|
40
|
+
/** Optional opt-in action runner; the owning data runtime's `submit`. */
|
|
41
|
+
submit?: <R>(
|
|
42
|
+
action: (context: RouteDataContext) => R | Promise<R>,
|
|
43
|
+
) => Promise<R>;
|
|
44
|
+
/** Optional opt-in subscription to the latest active submission. */
|
|
45
|
+
submitting?: {
|
|
46
|
+
peek(): boolean;
|
|
47
|
+
subscribe(listener: () => void): () => void;
|
|
48
|
+
};
|
|
33
49
|
/** Navigate via History API (no full reload). */
|
|
34
50
|
navigate: (
|
|
35
51
|
to: string,
|