netjes 0.0.4 → 0.0.5
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 +8 -8
- package/cli/commands.mjs +32 -6
- package/dist/actions.d.ts +3 -2
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +5 -4
- package/dist/actions.js.map +1 -1
- package/dist/document.d.ts +3 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +4 -3
- package/dist/document.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lang.d.ts +10 -0
- package/dist/lang.d.ts.map +1 -0
- package/dist/lang.js +26 -0
- package/dist/lang.js.map +1 -0
- package/dist/link.d.ts +15 -3
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +15 -9
- package/dist/link.js.map +1 -1
- package/dist/mounted.d.ts +3 -7
- package/dist/mounted.d.ts.map +1 -1
- package/dist/mounted.js.map +1 -1
- package/dist/navigation-guard.d.ts +59 -0
- package/dist/navigation-guard.d.ts.map +1 -0
- package/dist/navigation-guard.js +116 -0
- package/dist/navigation-guard.js.map +1 -0
- package/dist/payload.d.ts +20 -2
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +25 -1
- package/dist/payload.js.map +1 -1
- package/dist/root.d.ts.map +1 -1
- package/dist/root.js +2 -1
- package/dist/root.js.map +1 -1
- package/dist/router.d.ts +101 -20
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +590 -68
- package/dist/router.js.map +1 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +5 -0
- package/dist/schema.js.map +1 -1
- package/dist/testing.d.ts +17 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +63 -22
- package/dist/testing.js.map +1 -1
- package/package.json +5 -1
- package/sidecar/server.mjs +80 -14
- package/skills/netjes/SKILL.md +2 -2
- package/skills/netjes/references/data-and-actions.md +5 -4
- package/skills/netjes/references/deployment.md +1 -1
- package/skills/netjes/references/routing.md +9 -5
- package/skills/netjes/references/testing.md +6 -3
- package/src/actions.tsx +5 -4
- package/src/document.tsx +11 -4
- package/src/index.ts +9 -0
- package/src/lang.ts +28 -0
- package/src/link.tsx +37 -9
- package/src/mounted.tsx +3 -3
- package/src/navigation-guard.ts +136 -0
- package/src/payload.ts +37 -3
- package/src/root.tsx +3 -1
- package/src/router.tsx +764 -104
- package/src/schema.ts +11 -0
- package/src/testing-vitest.ts +1 -1
- package/src/testing.tsx +67 -15
- package/template/Dockerfile +1 -1
- package/template/README.md +1 -1
- package/template/_AGENTS.md +4 -2
- package/template/docker-compose.override.yml +15 -3
- package/template/generated/netjes.ts +1 -1
package/src/router.tsx
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
createContext,
|
|
6
6
|
startTransition,
|
|
7
7
|
use,
|
|
8
|
+
useCallback,
|
|
8
9
|
useContext,
|
|
9
10
|
useEffect,
|
|
10
11
|
useLayoutEffect,
|
|
@@ -16,8 +17,10 @@ import { actionRequest, expectActionClient, fetchAction, setActionClient } from
|
|
|
16
17
|
import { deferredRegistry, revivePayload } from './deferred.ts';
|
|
17
18
|
import type { EncodedForm } from './form-data.ts';
|
|
18
19
|
import type { Href } from './href.ts';
|
|
20
|
+
import { documentLang as langOf } from './lang.ts';
|
|
19
21
|
import { type ErrorPageProps, MissingModuleError, type ModuleLoader, type RouteModules } from './modules.ts';
|
|
20
22
|
import { moveFocusAfterNavigation } from './navigation-focus.ts';
|
|
23
|
+
import { NavigationGuards, type NavigationGuardOptions } from './navigation-guard.ts';
|
|
21
24
|
import {
|
|
22
25
|
type ActionResponse,
|
|
23
26
|
type AntiforgeryToken,
|
|
@@ -26,6 +29,7 @@ import {
|
|
|
26
29
|
type NavigationPayload,
|
|
27
30
|
type PagePayload,
|
|
28
31
|
type Params,
|
|
32
|
+
REDIRECTED_HEADER,
|
|
29
33
|
SEGMENTS_HEADER,
|
|
30
34
|
SERVER_TIME_HEADER,
|
|
31
35
|
type SegmentRef,
|
|
@@ -35,25 +39,54 @@ import {
|
|
|
35
39
|
} from './payload.ts';
|
|
36
40
|
import { RouteAnnouncer } from './route-announcer.tsx';
|
|
37
41
|
import { ErrorBoundary, LayoutDepthContext, RouteTree, asError } from './route-tree.tsx';
|
|
38
|
-
import { type StandardSchemaV1, parseLenient, parseWith } from './schema.ts';
|
|
42
|
+
import { type StandardSchemaV1, parseLenient, parseOr, parseWith } from './schema.ts';
|
|
39
43
|
|
|
40
|
-
|
|
41
|
-
|
|
44
|
+
export type { NavigationAttempt, NavigationAttemptType, NavigationGuardOptions } from './navigation-guard.ts';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* A navigation, a refresh or a form post that ended without a page, while the page on screen stayed. `useNavigation()`
|
|
48
|
+
* holds it until the next navigation, refresh or form post starts.
|
|
49
|
+
*/
|
|
50
|
+
export type NavigationError = {
|
|
51
|
+
/**
|
|
52
|
+
* What failed: a navigation to another URL (a link, a GET form, `push`, `replace`, Back or Forward), `router.refresh()`
|
|
53
|
+
* (also the one a server action asks for), or a form post.
|
|
54
|
+
*/
|
|
55
|
+
kind: 'navigate' | 'refresh' | 'submit';
|
|
56
|
+
/** The status of an answer that was no page, or `null` when no answer came (the connection failed). */
|
|
57
|
+
status: number | null;
|
|
58
|
+
/** Where it went: the path and query, without the base path. */
|
|
59
|
+
location: string;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/** @deprecated The name `NavigationError` had while only form posts reported a failure. */
|
|
63
|
+
export type SubmitError = NavigationError;
|
|
42
64
|
|
|
43
65
|
/** What the router is doing: idle, or on its way to `location` for a navigation (`loading`) or a form post (`submitting`). */
|
|
44
66
|
export type NavigationState =
|
|
45
|
-
| { state: 'idle'; error?:
|
|
67
|
+
| { state: 'idle'; error?: NavigationError }
|
|
46
68
|
| { state: 'loading' | 'submitting'; location: string };
|
|
47
69
|
|
|
70
|
+
/** What `router.push` and `router.replace` take besides the href. */
|
|
71
|
+
export type NavigateOptions = {
|
|
72
|
+
/** Scroll to the top after navigating, or to the #fragment's element. Default true. */
|
|
73
|
+
scroll?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* `useHistoryState` values, by name, that the entry the navigation adds or replaces starts with, over the values of a
|
|
76
|
+
* page that stays on screen. The router keeps a copy (`structuredClone`).
|
|
77
|
+
*/
|
|
78
|
+
historyState?: Readonly<Record<string, unknown>>;
|
|
79
|
+
};
|
|
80
|
+
|
|
48
81
|
/** The client router that `useRouter()` returns. */
|
|
49
82
|
export type Router = {
|
|
50
83
|
/**
|
|
51
84
|
* Navigates, adding a history entry. The promise resolves once the router has handed the page to React, which can be
|
|
52
85
|
* before React shows it, or once the navigation has ended another way.
|
|
53
86
|
*/
|
|
54
|
-
push(href: Href, options?:
|
|
87
|
+
push(href: Href, options?: NavigateOptions): Promise<void>;
|
|
55
88
|
/** Navigates, replacing the history entry. The promise resolves as `push`'s does. */
|
|
56
|
-
replace(href: Href, options?:
|
|
89
|
+
replace(href: Href, options?: NavigateOptions): Promise<void>;
|
|
57
90
|
/** Fetches the page payload and modules ahead of a navigation. Links do this on hover, focus and touch. */
|
|
58
91
|
prefetch(href: Href): void;
|
|
59
92
|
/**
|
|
@@ -78,8 +111,8 @@ export type ActionListener = (response: ActionResponse) => void;
|
|
|
78
111
|
type FocusAtStart = { focusedAtStart?: Element | null };
|
|
79
112
|
|
|
80
113
|
export type InternalRouter = Omit<Router, 'push' | 'replace'> & {
|
|
81
|
-
push(href: Href, options?:
|
|
82
|
-
replace(href: Href, options?:
|
|
114
|
+
push(href: Href, options?: NavigateOptions & FocusAtStart): Promise<void>;
|
|
115
|
+
replace(href: Href, options?: NavigateOptions & FocusAtStart): Promise<void>;
|
|
83
116
|
submit(action: URL, body: SubmitBody, options?: FocusAtStart): Promise<void>;
|
|
84
117
|
onActionResponse(listener: ActionListener): () => void;
|
|
85
118
|
/**
|
|
@@ -124,6 +157,13 @@ const ANTIFORGERY_URL = '/_netjes/antiforgery';
|
|
|
124
157
|
const NONE: ScrollIntent = { kind: 'none' };
|
|
125
158
|
const TOP: ScrollIntent = { kind: 'top' };
|
|
126
159
|
const STATE_KEY = '__netjes';
|
|
160
|
+
/** Where an entry's `useHistoryState` values are, in `history.state`, beside the entry's key. */
|
|
161
|
+
const VALUES_KEY = '__netjesState';
|
|
162
|
+
/**
|
|
163
|
+
* Where an entry's place in the tab's history is, in `history.state`: one more than the entry before it, the same as the
|
|
164
|
+
* entry it replaced. After Back or Forward it tells the router how many steps the browser took, and which way.
|
|
165
|
+
*/
|
|
166
|
+
const INDEX_KEY = '__netjesIndex';
|
|
127
167
|
/**
|
|
128
168
|
* On `<html>` while the client router runs in the document, and the public sign that it does: end-to-end tests wait
|
|
129
169
|
* for it before they click. (The history entry's key is no such sign: the entry keeps it when the browser loads the
|
|
@@ -152,6 +192,42 @@ function readKey(state: unknown): string | undefined {
|
|
|
152
192
|
return typeof value === 'string' ? value : undefined;
|
|
153
193
|
}
|
|
154
194
|
|
|
195
|
+
function readIndex(state: unknown): number | undefined {
|
|
196
|
+
const value = isRecord(state) ? state[INDEX_KEY] : undefined;
|
|
197
|
+
return Number.isSafeInteger(value) ? (value as number) : undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The values `useHistoryState` keeps with one history entry, by name. */
|
|
201
|
+
type HistoryValues = Readonly<Record<string, unknown>>;
|
|
202
|
+
const NO_VALUES: HistoryValues = Object.freeze({});
|
|
203
|
+
|
|
204
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
205
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function readValues(state: unknown): HistoryValues {
|
|
209
|
+
const values = isRecord(state) ? state[VALUES_KEY] : undefined;
|
|
210
|
+
return isRecord(values) ? values : NO_VALUES;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** `values` with the names a navigation carries set over them. */
|
|
214
|
+
function withCarried(values: HistoryValues, carried: HistoryValues | undefined): HistoryValues {
|
|
215
|
+
return carried === undefined || Object.keys(carried).length === 0 ? values : { ...values, ...carried };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The state the router writes for an entry: its key, its place and its values, over `kept`, the state of the entry it
|
|
220
|
+
* replaces, so the keys an app or a library put there stay. A new entry keeps nothing of the one before.
|
|
221
|
+
*/
|
|
222
|
+
function entryState(key: string, index: number | undefined, values: HistoryValues, kept: unknown = null): Record<string, unknown> {
|
|
223
|
+
const state: Record<string, unknown> = { ...(isRecord(kept) ? kept : {}), [STATE_KEY]: key };
|
|
224
|
+
if (index === undefined) delete state[INDEX_KEY];
|
|
225
|
+
else state[INDEX_KEY] = index;
|
|
226
|
+
if (Object.keys(values).length > 0) state[VALUES_KEY] = values;
|
|
227
|
+
else delete state[VALUES_KEY];
|
|
228
|
+
return state;
|
|
229
|
+
}
|
|
230
|
+
|
|
155
231
|
/**
|
|
156
232
|
* Records how far the browser clock is from the server's, given a server time for "now": the `X-Netjes-Now` header
|
|
157
233
|
* of a data response, or for the initial document the payload's `renderedAt` (so the browser judges seeded data
|
|
@@ -208,6 +284,41 @@ function withHash(url: URL, hash: string): URL {
|
|
|
208
284
|
|
|
209
285
|
type FetchResult = NavigationPayload | { html: string; url: string } | { file: Blob; name: string } | { failed: number } | null;
|
|
210
286
|
|
|
287
|
+
/**
|
|
288
|
+
* No answer came for a request: the connection failed, the browser is offline, or the browser refused to follow a
|
|
289
|
+
* redirect (one to another origin that does not allow this one). `headers` are the request's, to ask again with.
|
|
290
|
+
*/
|
|
291
|
+
class NoAnswer extends Error {
|
|
292
|
+
override name = 'NoAnswer';
|
|
293
|
+
readonly url: URL;
|
|
294
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
295
|
+
|
|
296
|
+
constructor(url: URL, headers: Readonly<Record<string, string>>, cause: unknown) {
|
|
297
|
+
super(`netjes: no answer from ${url.href}`, { cause });
|
|
298
|
+
this.url = url;
|
|
299
|
+
this.headers = headers;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The browser says it has no network. `navigator.onLine` is true when it cannot tell, so only `false` counts. */
|
|
304
|
+
const offline = () => typeof navigator !== 'undefined' && navigator.onLine === false;
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Whether `failed` answers with a redirect, asked again without following it. A redirect to another origin that does
|
|
308
|
+
* not allow this one, such as an identity provider's sign-in page, fails `fetch` as a lost connection does; the browser
|
|
309
|
+
* follows it itself when it loads the URL as a document.
|
|
310
|
+
*/
|
|
311
|
+
async function answersWithRedirect(failed: NoAnswer, signal: AbortSignal): Promise<boolean> {
|
|
312
|
+
try {
|
|
313
|
+
const response = await fetch(failed.url.href, { headers: failed.headers, credentials: 'same-origin', redirect: 'manual', signal });
|
|
314
|
+
void response.body?.cancel().catch(() => {});
|
|
315
|
+
// A browser hides the redirect behind an opaque answer; other runtimes hand over the 3xx itself.
|
|
316
|
+
return response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);
|
|
317
|
+
} catch {
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
211
322
|
function attachmentName(disposition: string): string {
|
|
212
323
|
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
|
|
213
324
|
if (encoded) {
|
|
@@ -220,21 +331,46 @@ function attachmentName(disposition: string): string {
|
|
|
220
331
|
return /filename="?([^";]+)"?/i.exec(disposition)?.[1] ?? 'download';
|
|
221
332
|
}
|
|
222
333
|
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
token?: AntiforgeryToken
|
|
229
|
-
|
|
230
|
-
)
|
|
334
|
+
/** What a request for a page sends besides its method and body. */
|
|
335
|
+
type FetchOptions = {
|
|
336
|
+
/** The keys of the layout segments the router holds, whose loaders the server may skip (GETs only). */
|
|
337
|
+
segmentKeys?: readonly string[];
|
|
338
|
+
/** The antiforgery token a post sends as a header. */
|
|
339
|
+
token?: AntiforgeryToken | undefined;
|
|
340
|
+
/** Called as soon as a post's answer says it set or deleted a cookie. */
|
|
341
|
+
onCookiesChanged?: (() => void) | undefined;
|
|
342
|
+
/** A redirect led to this URL: the server answers `{ kind: 'document' }` where no page answers it. */
|
|
343
|
+
redirected?: boolean;
|
|
344
|
+
};
|
|
345
|
+
|
|
346
|
+
/** What `Navigator.load` takes besides the URL, the request and the signal. */
|
|
347
|
+
type LoadOptions = {
|
|
348
|
+
/** Send the keys of the layout segments the router holds, whose loaders the server may skip (GETs only). */
|
|
349
|
+
reuseSegments?: boolean | undefined;
|
|
350
|
+
/** Called as soon as a post's answer says it set or deleted a cookie; by default the router's own handling. */
|
|
351
|
+
onCookiesChanged?: (() => void) | undefined;
|
|
352
|
+
/** A redirect led to the URL: one that no page answers loads as a document. */
|
|
353
|
+
redirected?: boolean | undefined;
|
|
354
|
+
/** Called with each URL on this origin a redirect leads the load to, before it asks for that URL. */
|
|
355
|
+
onRedirect?: ((target: URL) => void) | undefined;
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
async function fetchPayload(url: URL, request: PageRequest, signal: AbortSignal, options: FetchOptions = {}): Promise<FetchResult> {
|
|
359
|
+
const { segmentKeys = [], token, onCookiesChanged, redirected = false } = options;
|
|
231
360
|
const headers: Record<string, string> = { [DATA_HEADER]: '1', Accept: 'application/json' };
|
|
361
|
+
if (request.method === 'GET' && redirected) headers[REDIRECTED_HEADER] = '1';
|
|
232
362
|
if (request.method === 'POST' && token?.headerName && token.requestToken) headers[token.headerName] = token.requestToken;
|
|
233
363
|
if (request.method === 'GET' && segmentKeys.length > 0) headers[SEGMENTS_HEADER] = segmentKeys.join(',');
|
|
234
364
|
if (request.method === 'POST' && request.contentType) headers['Content-Type'] = request.contentType;
|
|
235
365
|
const init: RequestInit = { method: request.method, headers, credentials: 'same-origin', signal };
|
|
236
366
|
if (request.method === 'POST' && request.body !== undefined) init.body = request.body;
|
|
237
|
-
|
|
367
|
+
let response: Response;
|
|
368
|
+
try {
|
|
369
|
+
response = await fetch(url.href, init);
|
|
370
|
+
} catch (error) {
|
|
371
|
+
if (signal.aborted) throw error;
|
|
372
|
+
throw new NoAnswer(url, headers, error);
|
|
373
|
+
}
|
|
238
374
|
// A form post that signed someone in or out; script cannot read Set-Cookie itself.
|
|
239
375
|
if (request.method === 'POST' && response.headers.get(COOKIES_HEADER) === 'changed') onCookiesChanged?.();
|
|
240
376
|
const type = response.headers.get('content-type') ?? '';
|
|
@@ -264,15 +400,26 @@ async function fetchPayload(
|
|
|
264
400
|
return withClockOffset(revivePayload(payload, registry.source), Number.isFinite(serverNow) ? serverNow : undefined);
|
|
265
401
|
}
|
|
266
402
|
if (type.includes('application/json')) {
|
|
267
|
-
|
|
403
|
+
let payload: NavigationPayload;
|
|
404
|
+
try {
|
|
405
|
+
payload = parseNavigationPayload(await response.json());
|
|
406
|
+
} catch (error) {
|
|
407
|
+
// A server error that is no Netjes page, such as a gateway's JSON error, fails a GET; anything else is a bug.
|
|
408
|
+
if (request.method === 'GET' && response.status >= 500 && !signal.aborted) return { failed: response.status };
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
268
411
|
if (payload.kind !== 'page') return payload;
|
|
269
412
|
// Without the header (a cache in front of UseNetjes) there is no fresh server time: take the timestamps as they
|
|
270
413
|
// are. Falling back to renderedAt would make a cached payload look brand new.
|
|
271
414
|
const serverNow = Number(response.headers.get(SERVER_TIME_HEADER) ?? Number.NaN);
|
|
272
415
|
return withClockOffset(payload, Number.isFinite(serverNow) ? serverNow : undefined);
|
|
273
416
|
}
|
|
274
|
-
// Something other than a Netjes page answered. A GET
|
|
275
|
-
|
|
417
|
+
// Something other than a Netjes page answered. A GET that failed on the server (a gateway's 502 while the app
|
|
418
|
+
// restarts, say) fails; any other the browser loads instead, so the router stops reading it (a file, say).
|
|
419
|
+
if (request.method === 'GET') {
|
|
420
|
+
void response.body?.cancel().catch(() => {});
|
|
421
|
+
return response.status >= 500 ? { failed: response.status } : null;
|
|
422
|
+
}
|
|
276
423
|
// A POST must not be sent again. Show what a native submission would have shown, where that is safe.
|
|
277
424
|
if (!response.ok) return { failed: response.status };
|
|
278
425
|
if (type.includes('text/html')) return { html: await response.text(), url: response.url || url.href };
|
|
@@ -311,12 +458,42 @@ type NavigatorDeps = {
|
|
|
311
458
|
version: string;
|
|
312
459
|
/** `UsePathBase`'s base path ('' at the root): added to the root-relative hrefs the app navigates to. */
|
|
313
460
|
basePath: string;
|
|
314
|
-
|
|
461
|
+
/** `letThrough`: a navigation the guards let go on, whose unload they do not ask about again. */
|
|
462
|
+
hardNavigate(href: string, letThrough: boolean): void;
|
|
315
463
|
showDocument(html: string, url: string): void;
|
|
316
464
|
download(file: Blob, name: string): void;
|
|
317
465
|
setPending(state: NavigationState): void;
|
|
318
|
-
/**
|
|
319
|
-
|
|
466
|
+
/**
|
|
467
|
+
* `focusedAtStart`: what had the focus when the navigation started, which decides where the focus goes after it.
|
|
468
|
+
* `entry`: the history entry the page is shown in, with its values, and whether Back or Forward put the page back
|
|
469
|
+
* from memory.
|
|
470
|
+
*/
|
|
471
|
+
commit(loaded: Loaded, scroll: ScrollIntent, focusedAtStart: Element | null, entry: CommittedEntry): void;
|
|
472
|
+
/** The values of the entry on screen changed without a navigation: a page set one, or the router read them at start. */
|
|
473
|
+
setEntry(entry: HistoryEntry): void;
|
|
474
|
+
/** The guards that hold Back and Forward. */
|
|
475
|
+
guards: NavigationGuards;
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* The history entry on screen, as `useHistoryState` reads it: its values, and the lineage of the page that holds them,
|
|
480
|
+
* to which a setter is bound.
|
|
481
|
+
*/
|
|
482
|
+
type HistoryEntry = { lineage: number; values: HistoryValues };
|
|
483
|
+
type CommittedEntry = HistoryEntry & { restored: boolean };
|
|
484
|
+
|
|
485
|
+
/** How `Navigator.navigate` goes. */
|
|
486
|
+
type NavigateCall = {
|
|
487
|
+
/** Scroll to the top, or to the fragment's element. Default true. */
|
|
488
|
+
scroll?: boolean | undefined;
|
|
489
|
+
/** What had the focus as the navigation started: by default what has it as `navigate` is called. */
|
|
490
|
+
focusedAtStart?: Element | null | undefined;
|
|
491
|
+
/** `useHistoryState` values the new entry starts with. */
|
|
492
|
+
historyState?: HistoryValues | undefined;
|
|
493
|
+
/** The guards let it go on: a full page load it ends in does not have the browser ask again. */
|
|
494
|
+
letThrough?: boolean | undefined;
|
|
495
|
+
/** A server action's redirect: a URL that no page answers loads as a document. */
|
|
496
|
+
redirected?: boolean | undefined;
|
|
320
497
|
};
|
|
321
498
|
|
|
322
499
|
type GoOptions = {
|
|
@@ -329,8 +506,18 @@ type GoOptions = {
|
|
|
329
506
|
reuseSegments: boolean;
|
|
330
507
|
/** Refreshing an intercepted page: load this page under it again too, and show the result in its slot again. */
|
|
331
508
|
interceptOver?: URL;
|
|
509
|
+
/** Back or Forward to an entry the router does not remember: the values that entry holds. */
|
|
510
|
+
entryValues?: HistoryValues;
|
|
511
|
+
/** The values a navigation carries into the entry it adds or replaces. */
|
|
512
|
+
historyState?: HistoryValues;
|
|
332
513
|
/** What had the focus as the navigation started, when the caller read it: else go() reads it as it starts. */
|
|
333
514
|
focusedAtStart?: Element | null;
|
|
515
|
+
/** The guards let it go on: a full page load it ends in does not have the browser ask again. */
|
|
516
|
+
letThrough?: boolean;
|
|
517
|
+
/** `router.refresh()`: a failure is reported as the refresh's. */
|
|
518
|
+
refresh?: boolean;
|
|
519
|
+
/** A server action's redirect led to the URL: one that no page answers loads as a document. */
|
|
520
|
+
redirected?: boolean;
|
|
334
521
|
};
|
|
335
522
|
|
|
336
523
|
/**
|
|
@@ -355,8 +542,44 @@ class Navigator {
|
|
|
355
542
|
private readonly entries = new Map<string, Loaded>();
|
|
356
543
|
private readonly scrollPositions = new Map<string, { x: number; y: number }>();
|
|
357
544
|
private currentKey = createKey();
|
|
545
|
+
/** The `useHistoryState` values of the entry on screen, as its `history.state` holds them. */
|
|
546
|
+
private values: HistoryValues = NO_VALUES;
|
|
547
|
+
/**
|
|
548
|
+
* The lineage of the values on screen, to which `useHistoryState`'s setters are bound. A navigation that keeps the
|
|
549
|
+
* page on screen gives the entry a new key but carries the page's values over, as the page keeps its React state, so
|
|
550
|
+
* it keeps the lineage too: a setter from before it still writes. A new one starts when the values start over
|
|
551
|
+
* (another page) or Back or Forward switch the entry, and a setter of the lineage before writes nothing.
|
|
552
|
+
*/
|
|
553
|
+
private lineage = 0;
|
|
554
|
+
/**
|
|
555
|
+
* The browser is on another entry than the page on screen: Back or Forward went to one whose page is still loading,
|
|
556
|
+
* or the router is stepping back (a guard held Back, or the page did not come). The page must not write its values
|
|
557
|
+
* into that entry.
|
|
558
|
+
*/
|
|
559
|
+
private betweenEntries = false;
|
|
358
560
|
/** The page on screen is from before cookies changed: kept for no history entry until one comes from the server. */
|
|
359
561
|
private currentIsStale = false;
|
|
562
|
+
/**
|
|
563
|
+
* The place in the tab's history (`INDEX_KEY`) of the entry on screen, or of the entry Back or Forward went to while
|
|
564
|
+
* its page loads, or undefined on an entry the router did not make (one an app or a library pushed itself), whose
|
|
565
|
+
* place it does not know.
|
|
566
|
+
*/
|
|
567
|
+
private index: number | undefined;
|
|
568
|
+
/**
|
|
569
|
+
* The place of the entry of the page on screen. It is `index`, but while Back or Forward loads the page of the entry
|
|
570
|
+
* it went to: a Back or Forward whose page does not come steps back to it, also one that went from an entry whose
|
|
571
|
+
* page was still loading, and a step back of the router's that lands on it has the browser on the page's entry.
|
|
572
|
+
*/
|
|
573
|
+
private shownIndex: number | undefined;
|
|
574
|
+
/**
|
|
575
|
+
* The router is stepping back to the entry at `index`, after a guard held Back or Forward (once there, it `ask`s) or
|
|
576
|
+
* a page did not come.
|
|
577
|
+
*/
|
|
578
|
+
private puttingBack: { index: number; ask(): void } | null = null;
|
|
579
|
+
/** The place a guard let Back or Forward go to: the step there is not held again. */
|
|
580
|
+
private letThrough: number | null = null;
|
|
581
|
+
/** The URL of the entry on screen as the browser shows it, fragment included (the first page's payload has none). */
|
|
582
|
+
private href = '';
|
|
360
583
|
/** Shared with the app's other tabs, where the browser has BroadcastChannel; null until started, and once stopped. */
|
|
361
584
|
private channel: BroadcastChannel | null = null;
|
|
362
585
|
|
|
@@ -366,14 +589,34 @@ class Navigator {
|
|
|
366
589
|
constructor(deps: NavigatorDeps, current: Loaded) {
|
|
367
590
|
this.deps = deps;
|
|
368
591
|
this.current = current;
|
|
592
|
+
// The entry the document was loaded into keeps its key and values when the browser loads it again (a reload).
|
|
593
|
+
// They are read here, so a page that sets a value before start() writes into that entry, and shown from start().
|
|
594
|
+
if (typeof window !== 'undefined') {
|
|
595
|
+
const existing = readKey(window.history.state);
|
|
596
|
+
if (existing) this.currentKey = existing;
|
|
597
|
+
this.values = readValues(window.history.state);
|
|
598
|
+
// A new document's entry is the last one of the tab's history. Only the steps between the entries matter, so a
|
|
599
|
+
// place that is off (the browser keeps 50 entries or so) changes nothing.
|
|
600
|
+
this.index = readIndex(window.history.state) ?? Math.max(window.history.length - 1, 0);
|
|
601
|
+
this.shownIndex = this.index;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** The lineage of the values on screen. */
|
|
606
|
+
get entryLineage(): number {
|
|
607
|
+
return this.lineage;
|
|
369
608
|
}
|
|
370
609
|
|
|
371
610
|
start(): () => void {
|
|
372
611
|
window.history.scrollRestoration = 'manual';
|
|
373
|
-
|
|
374
|
-
if (
|
|
375
|
-
|
|
612
|
+
this.href = window.location.href;
|
|
613
|
+
if (readKey(window.history.state) !== this.currentKey || readIndex(window.history.state) !== this.index) {
|
|
614
|
+
window.history.replaceState(entryState(this.currentKey, this.index, this.values, window.history.state), '');
|
|
615
|
+
}
|
|
376
616
|
this.remember(this.currentKey, this.current);
|
|
617
|
+
// The commit that hydrated the page rendered every value as its initial one, as the server did. An entry that holds
|
|
618
|
+
// values (after a reload) shows them now, before the browser paints; one with none renders nothing again.
|
|
619
|
+
if (this.values !== NO_VALUES) this.deps.setEntry({ lineage: this.lineage, values: this.values });
|
|
377
620
|
|
|
378
621
|
let frame = 0;
|
|
379
622
|
const onScroll = () => {
|
|
@@ -406,8 +649,25 @@ class Navigator {
|
|
|
406
649
|
this.channel = null;
|
|
407
650
|
}
|
|
408
651
|
|
|
409
|
-
/**
|
|
410
|
-
|
|
652
|
+
/**
|
|
653
|
+
* Sets a `useHistoryState` value of the entry on screen, computed from the entry's values, in its `history.state`,
|
|
654
|
+
* for a setter of the values' `lineage`. A setter of a page that has left (setting a value as it unmounts), or of the
|
|
655
|
+
* entry before Back or Forward, changes nothing, and so does any setter while the browser is on another entry.
|
|
656
|
+
*/
|
|
657
|
+
setValue(lineage: number, name: string, compute: (values: HistoryValues) => unknown) {
|
|
658
|
+
if (lineage !== this.lineage || this.betweenEntries) return;
|
|
659
|
+
const values = { ...this.values, [name]: compute(this.values) };
|
|
660
|
+
// First, so a value the browser cannot keep throws before anything changed.
|
|
661
|
+
window.history.replaceState(entryState(this.currentKey, this.index, values, window.history.state), '');
|
|
662
|
+
this.values = values;
|
|
663
|
+
this.deps.setEntry({ lineage, values });
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
async navigate(href: string, history: 'push' | 'replace', options: NavigateCall = {}): Promise<void> {
|
|
667
|
+
const { scroll = true, focusedAtStart = document.activeElement, historyState, letThrough = false, redirected = false } = options;
|
|
668
|
+
// A copy, as the browser keeps one: what the caller changes later does not reach the entry, and a value the
|
|
669
|
+
// browser cannot keep throws here, before the navigation starts.
|
|
670
|
+
const carried = historyState === undefined ? undefined : (structuredClone(historyState) as HistoryValues);
|
|
411
671
|
const url = new URL(withBasePath(href, this.deps.basePath), window.location.href);
|
|
412
672
|
if (!isWebUrl(url)) {
|
|
413
673
|
console.error(`netjes: refusing to navigate to ${url.protocol} URL`);
|
|
@@ -423,9 +683,20 @@ class Navigator {
|
|
|
423
683
|
this.cancelActive();
|
|
424
684
|
this.rememberScroll();
|
|
425
685
|
const key = createKey();
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
this.
|
|
686
|
+
// The page stays, and so do its values.
|
|
687
|
+
const values = withCarried(this.values, carried);
|
|
688
|
+
this.index = history === 'push' ? this.nextIndex() : this.index;
|
|
689
|
+
window.history[history === 'push' ? 'pushState' : 'replaceState'](
|
|
690
|
+
entryState(key, this.index, values, history === 'replace' ? window.history.state : null),
|
|
691
|
+
'',
|
|
692
|
+
url.href,
|
|
693
|
+
);
|
|
694
|
+
this.setCurrent(key, { ...this.current, url }, values, true);
|
|
695
|
+
this.deps.commit(this.current, scroll ? { kind: 'hash', hash: url.hash } : NONE, focusedAtStart, {
|
|
696
|
+
lineage: this.lineage,
|
|
697
|
+
values,
|
|
698
|
+
restored: false,
|
|
699
|
+
});
|
|
429
700
|
return;
|
|
430
701
|
}
|
|
431
702
|
|
|
@@ -436,9 +707,30 @@ class Navigator {
|
|
|
436
707
|
usePrefetch: true,
|
|
437
708
|
reuseSegments: true,
|
|
438
709
|
focusedAtStart,
|
|
710
|
+
letThrough,
|
|
711
|
+
redirected,
|
|
712
|
+
...(carried ? { historyState: carried } : {}),
|
|
439
713
|
});
|
|
440
714
|
}
|
|
441
715
|
|
|
716
|
+
/**
|
|
717
|
+
* Where a push or replace to `href` goes, as a guard is told (without the base path), or null for one no guard holds:
|
|
718
|
+
* to another origin or scheme, which the browser loads (a guard's `beforeunload` asks then), or to a fragment of the
|
|
719
|
+
* page on screen, which loads nothing and keeps the page.
|
|
720
|
+
*/
|
|
721
|
+
heldTarget(href: string): string | null {
|
|
722
|
+
let url: URL;
|
|
723
|
+
try {
|
|
724
|
+
url = new URL(withBasePath(href, this.deps.basePath), window.location.href);
|
|
725
|
+
} catch {
|
|
726
|
+
// navigate() fails on it as it would without a guard.
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
if (!isWebUrl(url) || url.origin !== window.location.origin) return null;
|
|
730
|
+
if (url.hash && samePage(url, this.current.url)) return null;
|
|
731
|
+
return withoutBasePath(url.pathname, this.deps.basePath) + url.search + url.hash;
|
|
732
|
+
}
|
|
733
|
+
|
|
442
734
|
submit(action: URL, body: SubmitBody, focusedAtStart = document.activeElement): Promise<void> {
|
|
443
735
|
return this.go(
|
|
444
736
|
action,
|
|
@@ -461,6 +753,7 @@ class Navigator {
|
|
|
461
753
|
pending: 'loading',
|
|
462
754
|
usePrefetch: false,
|
|
463
755
|
reuseSegments: false,
|
|
756
|
+
refresh: true,
|
|
464
757
|
...(base ? { interceptOver: withHash(base.url, '') } : {}),
|
|
465
758
|
});
|
|
466
759
|
}
|
|
@@ -572,7 +865,8 @@ class Navigator {
|
|
|
572
865
|
|
|
573
866
|
private startPrefetch(url: URL) {
|
|
574
867
|
const controller = new AbortController();
|
|
575
|
-
const
|
|
868
|
+
const result = this.load(url, { method: 'GET' }, controller.signal, { reuseSegments: true });
|
|
869
|
+
const prefetch: Prefetch = { at: Date.now(), result, controller, loading: true };
|
|
576
870
|
prefetch.result.then(
|
|
577
871
|
() => {
|
|
578
872
|
prefetch.loading = false;
|
|
@@ -586,20 +880,96 @@ class Navigator {
|
|
|
586
880
|
this.prefetched.set(url.href, prefetch);
|
|
587
881
|
}
|
|
588
882
|
|
|
883
|
+
/** The place of an entry pushed after the one on screen. */
|
|
884
|
+
private nextIndex(): number | undefined {
|
|
885
|
+
return this.index === undefined ? undefined : this.index + 1;
|
|
886
|
+
}
|
|
887
|
+
|
|
589
888
|
private onPopState(event: PopStateEvent) {
|
|
889
|
+
const index = readIndex(event.state);
|
|
890
|
+
const puttingBack = this.puttingBack;
|
|
891
|
+
this.puttingBack = null;
|
|
892
|
+
// The router's own step back, after a guard held Back or Forward or a page did not come: the browser shows the URL
|
|
893
|
+
// of the entry it was on again.
|
|
894
|
+
if (puttingBack && index === puttingBack.index) {
|
|
895
|
+
// That is the entry of the page on screen, unless a guard held Back while the page of the entry the browser was on
|
|
896
|
+
// still loads: the browser is back on that entry, which the page on screen must not write into. The places tell,
|
|
897
|
+
// also when that page has come meanwhile, or a refresh gave the page on screen a new key.
|
|
898
|
+
this.betweenEntries = index !== this.shownIndex;
|
|
899
|
+
puttingBack.ask();
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
590
902
|
const url = new URL(window.location.href);
|
|
903
|
+
const letThrough = this.letThrough !== null && index === this.letThrough;
|
|
904
|
+
this.letThrough = null;
|
|
905
|
+
// A step to another page takes the place of an attempt still waiting for its answer: it is asked about in its
|
|
906
|
+
// place, or it goes on. A step that keeps the page leaves the question open.
|
|
907
|
+
if (!samePage(url, this.current.url)) this.deps.guards.dropAttempt();
|
|
908
|
+
if (!letThrough && this.holdTraversal(url, index)) return;
|
|
909
|
+
// An entry with no place on the page on screen: a fragment the browser moved to itself (a plain `<a href="#…">`, a
|
|
910
|
+
// fragment typed in the address bar, `location.hash`), which fires `popstate` with no state. It adds an entry after
|
|
911
|
+
// the one on screen, which gets the next place, or replaces that entry when its URL is the one on screen (the same
|
|
912
|
+
// link followed again), which keeps its place. A place counted short only puts a held step back short of the
|
|
913
|
+
// entry on screen; one counted long could send it past the end of the history. Either way the entry gets a key,
|
|
914
|
+
// so the steps to it, from it and from the entries pushed after it are counted as any others.
|
|
915
|
+
const fragment = index === undefined && samePage(url, this.current.url);
|
|
916
|
+
this.index = !fragment ? index : url.href === this.href ? this.index : this.nextIndex();
|
|
591
917
|
const key = readKey(event.state) ?? createKey();
|
|
592
918
|
const saved = this.scrollPositions.get(key);
|
|
593
919
|
const scroll: ScrollIntent = saved ? { kind: 'restore', ...saved } : url.hash ? { kind: 'hash', hash: url.hash } : TOP;
|
|
594
920
|
const cached = this.entries.get(key);
|
|
595
921
|
const known = cached && samePage(cached.url, url) ? cached : samePage(url, this.current.url) ? this.current : null;
|
|
922
|
+
// A fragment the browser moved to itself keeps the page, and so its values, as a fragment link does; the entry
|
|
923
|
+
// starts with none of its own. Back or Forward shows the values of the entry it went to.
|
|
924
|
+
const values = fragment ? withCarried(this.values, readValues(event.state)) : readValues(event.state);
|
|
925
|
+
if (fragment) window.history.replaceState(entryState(key, this.index, values, event.state), '');
|
|
596
926
|
if (known) {
|
|
597
927
|
this.active?.controller.abort();
|
|
598
|
-
|
|
599
|
-
|
|
928
|
+
// From memory, unless the page on screen simply stays (Back over a fragment link).
|
|
929
|
+
const restored = known.payload !== this.current.payload;
|
|
930
|
+
this.setCurrent(key, { ...known, url }, values, fragment);
|
|
931
|
+
this.deps.commit(this.current, scroll, document.activeElement, { lineage: this.lineage, values, restored });
|
|
600
932
|
return;
|
|
601
933
|
}
|
|
602
|
-
|
|
934
|
+
this.betweenEntries = true;
|
|
935
|
+
void this.go(url, { method: 'GET' }, {
|
|
936
|
+
history: 'none',
|
|
937
|
+
scroll,
|
|
938
|
+
pending: 'loading',
|
|
939
|
+
key,
|
|
940
|
+
usePrefetch: false,
|
|
941
|
+
reuseSegments: true,
|
|
942
|
+
entryValues: values,
|
|
943
|
+
letThrough,
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* Holds Back or Forward to `url`, the entry at `index`, while a guard holds: steps back to the entry on screen, then
|
|
949
|
+
* asks the guards, and steps to the entry the reader chose when they let it, from wherever the page is by then (a
|
|
950
|
+
* fragment link may have added an entry meanwhile). Back over a fragment link keeps the page and is not held.
|
|
951
|
+
* Neither is a step to an entry whose place the router does not know: it cannot tell the way back, and guessing could
|
|
952
|
+
* take the reader somewhere else, so it lets it go.
|
|
953
|
+
*/
|
|
954
|
+
private holdTraversal(url: URL, index: number | undefined): boolean {
|
|
955
|
+
if (!this.deps.guards.holding || samePage(url, this.current.url)) return false;
|
|
956
|
+
const from = this.index;
|
|
957
|
+
if (index === undefined || from === undefined || index === from) return false;
|
|
958
|
+
const steps = index - from;
|
|
959
|
+
const to = withoutBasePath(url.pathname, this.deps.basePath) + url.search + url.hash;
|
|
960
|
+
this.puttingBack = {
|
|
961
|
+
index: from,
|
|
962
|
+
ask: () =>
|
|
963
|
+
void this.deps.guards.attempt(to, steps < 0 ? 'back' : 'forward', async () => {
|
|
964
|
+
const now = this.index;
|
|
965
|
+
if (now === undefined || now === index) return;
|
|
966
|
+
this.letThrough = index;
|
|
967
|
+
window.history.go(index - now);
|
|
968
|
+
}),
|
|
969
|
+
};
|
|
970
|
+
this.betweenEntries = true;
|
|
971
|
+
window.history.go(-steps);
|
|
972
|
+
return true;
|
|
603
973
|
}
|
|
604
974
|
|
|
605
975
|
private async go(url: URL, request: PageRequest, options: GoOptions): Promise<void> {
|
|
@@ -629,19 +999,36 @@ class Navigator {
|
|
|
629
999
|
this.active = navigation;
|
|
630
1000
|
this.deps.setPending({ state: options.pending, location: withoutBasePath(url.pathname, this.deps.basePath) + url.search });
|
|
631
1001
|
let committed = false;
|
|
632
|
-
let failure:
|
|
1002
|
+
let failure: NavigationError | undefined;
|
|
1003
|
+
// The request a failure belongs to. Once a form post is answered with a redirect, the post went through: from there
|
|
1004
|
+
// on the router is on its way to that URL, and a failure is that navigation's, not the post's, so the form does not
|
|
1005
|
+
// offer to send it again.
|
|
1006
|
+
const at: { url: URL; request: PageRequest } = { url, request };
|
|
1007
|
+
const onRedirect =
|
|
1008
|
+
request.method === 'POST'
|
|
1009
|
+
? (target: URL) => {
|
|
1010
|
+
at.url = target;
|
|
1011
|
+
at.request = { method: 'GET' };
|
|
1012
|
+
}
|
|
1013
|
+
: undefined;
|
|
633
1014
|
try {
|
|
634
1015
|
const prefetched = options.usePrefetch ? this.takePrefetched(url, controller.signal) : undefined;
|
|
635
|
-
const under = options.interceptOver ? this.load(options.interceptOver, { method: 'GET' }, controller.signal
|
|
1016
|
+
const under = options.interceptOver ? this.load(options.interceptOver, { method: 'GET' }, controller.signal) : undefined;
|
|
636
1017
|
under?.catch(() => {});
|
|
637
|
-
const result = await (prefetched ??
|
|
1018
|
+
const result = await (prefetched ??
|
|
1019
|
+
this.load(url, request, controller.signal, {
|
|
1020
|
+
reuseSegments: options.reuseSegments,
|
|
1021
|
+
onCookiesChanged: () => this.cookiesChanged(navigation),
|
|
1022
|
+
redirected: options.redirected,
|
|
1023
|
+
onRedirect,
|
|
1024
|
+
}));
|
|
638
1025
|
// Superseded by another navigation, or started over because cookies changed: then it ends with the new attempt.
|
|
639
1026
|
if (controller.signal.aborted) return navigation.restarted;
|
|
640
1027
|
// A post may have changed what other pages show; do not serve them from before it. One that changed cookies has
|
|
641
1028
|
// dropped them already, and started those in flight over.
|
|
642
1029
|
if (request.method === 'POST' && !navigation.changedCookies) this.prefetched.clear();
|
|
643
1030
|
if ('hard' in result) {
|
|
644
|
-
this.hard(result.hard);
|
|
1031
|
+
this.hard(result.hard, options.letThrough);
|
|
645
1032
|
return;
|
|
646
1033
|
}
|
|
647
1034
|
if ('document' in result) {
|
|
@@ -656,8 +1043,13 @@ class Navigator {
|
|
|
656
1043
|
}
|
|
657
1044
|
if ('failed' in result) {
|
|
658
1045
|
// Keep the page, and what the user typed, as it is; useNavigation() tells the page.
|
|
659
|
-
console.error(
|
|
660
|
-
|
|
1046
|
+
console.error(
|
|
1047
|
+
at.request.method === 'POST'
|
|
1048
|
+
? `netjes: the form submission failed with status ${result.failed}`
|
|
1049
|
+
: `netjes: loading ${at.url.pathname}${at.url.search} failed with status ${result.failed}, keeping the page`,
|
|
1050
|
+
);
|
|
1051
|
+
if (!this.keepPage(at.url, at.request, options)) return;
|
|
1052
|
+
failure = this.failure(at.url, at.request, options, result.failed);
|
|
661
1053
|
return;
|
|
662
1054
|
}
|
|
663
1055
|
|
|
@@ -671,31 +1063,49 @@ class Navigator {
|
|
|
671
1063
|
if (controller.signal.aborted) return navigation.restarted;
|
|
672
1064
|
const previous = this.current.url;
|
|
673
1065
|
const history = options.history === 'auto' ? (samePage(shown.url, previous) ? 'replace' : 'push') : options.history;
|
|
1066
|
+
// Back or Forward: the entry's own values. Else the page's values go with it while it stays on screen (a refresh,
|
|
1067
|
+
// another query or fragment), as its React state does; another page starts over. The values carried go on top.
|
|
1068
|
+
const carries = history !== 'none' && pageKeyOf(shown) === pageKeyOf(this.current);
|
|
1069
|
+
const values = history === 'none' ? (options.entryValues ?? NO_VALUES) : withCarried(carries ? this.values : NO_VALUES, options.historyState);
|
|
674
1070
|
let key = options.key ?? createKey();
|
|
675
1071
|
if (history === 'none') {
|
|
676
|
-
if (!options.key) window.history.replaceState(
|
|
1072
|
+
if (!options.key) window.history.replaceState(entryState(key, this.index, values, window.history.state), '');
|
|
677
1073
|
} else {
|
|
678
1074
|
this.rememberScroll();
|
|
679
1075
|
key = createKey();
|
|
680
|
-
|
|
1076
|
+
const kept = history === 'replace' ? window.history.state : null;
|
|
1077
|
+
this.index = history === 'push' ? this.nextIndex() : this.index;
|
|
1078
|
+
window.history[history === 'push' ? 'pushState' : 'replaceState'](entryState(key, this.index, values, kept), '', shown.url.href);
|
|
681
1079
|
}
|
|
682
1080
|
|
|
683
1081
|
this.currentIsStale = navigation.stale;
|
|
684
|
-
this.setCurrent(key, shown);
|
|
1082
|
+
this.setCurrent(key, shown, values, carries);
|
|
685
1083
|
this.forgetToken();
|
|
686
1084
|
committed = true;
|
|
687
1085
|
const scroll = shown.base ? NONE : options.scroll === 'auto' ? (shown.url.pathname === previous.pathname ? NONE : TOP) : options.scroll;
|
|
688
|
-
this.deps.commit(shown, scroll, focusedAtStart);
|
|
1086
|
+
this.deps.commit(shown, scroll, focusedAtStart, { lineage: this.lineage, values, restored: false });
|
|
689
1087
|
} catch (error) {
|
|
690
1088
|
if (controller.signal.aborted) return navigation.restarted;
|
|
691
|
-
if (request.method === 'POST') {
|
|
1089
|
+
if (at.request.method === 'POST') {
|
|
692
1090
|
// Never turn a failed submission into a GET: keep the page, and what the user typed, as it is.
|
|
693
1091
|
console.error('netjes: the form could not be submitted', error);
|
|
694
|
-
failure =
|
|
1092
|
+
failure = this.failure(at.url, at.request, options, null);
|
|
695
1093
|
return;
|
|
696
1094
|
}
|
|
1095
|
+
// No answer while the browser is online: keep the page, unless the URL redirects somewhere fetch cannot follow.
|
|
1096
|
+
// An offline browser loads the URL as a document, as any other failure does.
|
|
1097
|
+
if (error instanceof NoAnswer && !offline()) {
|
|
1098
|
+
const redirects = await answersWithRedirect(error, controller.signal);
|
|
1099
|
+
if (controller.signal.aborted) return navigation.restarted;
|
|
1100
|
+
if (!redirects) {
|
|
1101
|
+
console.error(`netjes: no answer for ${at.url.pathname}${at.url.search}, keeping the page`, error.cause);
|
|
1102
|
+
if (!this.keepPage(at.url, at.request, options)) return;
|
|
1103
|
+
failure = this.failure(at.url, at.request, options, null);
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
697
1107
|
console.error('netjes: navigation failed, loading the page from the server instead', error);
|
|
698
|
-
this.hard(url);
|
|
1108
|
+
this.hard(at.url, options.letThrough);
|
|
699
1109
|
} finally {
|
|
700
1110
|
if (this.active === navigation) {
|
|
701
1111
|
this.active = null;
|
|
@@ -704,25 +1114,57 @@ class Navigator {
|
|
|
704
1114
|
}
|
|
705
1115
|
}
|
|
706
1116
|
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
1117
|
+
/**
|
|
1118
|
+
* Keeps the page on screen after a navigation failed. Back or Forward has moved the browser to the entry it went to
|
|
1119
|
+
* already: the router steps back to the entry of the page on screen, so the address is the page's again, and a
|
|
1120
|
+
* page's history values and a refresh go to that entry. That is also where it steps back to when Back went from an
|
|
1121
|
+
* entry whose page was still loading (the reader pressed Back again meanwhile): that page never came. Where it cannot
|
|
1122
|
+
* tell either place (a step from or to an entry an app or a library added itself), it loads the URL as a document
|
|
1123
|
+
* instead and returns false.
|
|
1124
|
+
*/
|
|
1125
|
+
private keepPage(url: URL, request: PageRequest, options: GoOptions): boolean {
|
|
1126
|
+
if (request.method !== 'GET' || options.history !== 'none') return true;
|
|
1127
|
+
const now = this.index;
|
|
1128
|
+
const back = this.shownIndex;
|
|
1129
|
+
if (now === undefined || back === undefined || now === back) {
|
|
1130
|
+
this.hard(url, options.letThrough);
|
|
1131
|
+
return false;
|
|
1132
|
+
}
|
|
1133
|
+
this.index = back;
|
|
1134
|
+
// The step back is the router's own: once there, nothing more happens. Until then the browser is on the entry Back
|
|
1135
|
+
// went to.
|
|
1136
|
+
this.betweenEntries = true;
|
|
1137
|
+
this.puttingBack = { index: back, ask: () => {} };
|
|
1138
|
+
window.history.go(back - now);
|
|
1139
|
+
return true;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/** What `useNavigation()` reports for a navigation that kept the page on screen. */
|
|
1143
|
+
private failure(url: URL, request: PageRequest, options: GoOptions, status: number | null): NavigationError {
|
|
1144
|
+
const kind = request.method === 'POST' ? 'submit' : options.refresh ? 'refresh' : 'navigate';
|
|
1145
|
+
return { kind, status, location: withoutBasePath(url.pathname, this.deps.basePath) + url.search };
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
private async load(url: URL, request: PageRequest, signal: AbortSignal, options: LoadOptions = {}): Promise<LoadResult> {
|
|
1149
|
+
const { reuseSegments = false, onCookiesChanged = () => this.cookiesChanged() } = options;
|
|
714
1150
|
let target = url;
|
|
715
1151
|
let current = request;
|
|
1152
|
+
let redirected = options.redirected ?? false;
|
|
716
1153
|
// After a form post everything is loaded again: the post may have changed what any layout shows.
|
|
717
1154
|
let keys = reuseSegments && request.method === 'GET' ? this.heldSegmentKeys() : [];
|
|
718
1155
|
// Output-cached pages carry no token; a post from one needs a fetched one (as a header).
|
|
719
1156
|
const token = request.method === 'POST' && !this.current.payload.antiforgery ? await this.fetchedToken() : undefined;
|
|
720
1157
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
721
|
-
let payload = await fetchPayload(target, current, signal,
|
|
1158
|
+
let payload = await fetchPayload(target, current, signal, {
|
|
1159
|
+
segmentKeys: keys,
|
|
1160
|
+
token: current.method === 'POST' ? token : undefined,
|
|
1161
|
+
onCookiesChanged,
|
|
1162
|
+
redirected,
|
|
1163
|
+
});
|
|
722
1164
|
if (payload !== null && 'kind' in payload && payload.kind === 'page' && keys.length > 0) {
|
|
723
1165
|
const resolved = this.withReusedSegments(payload);
|
|
724
1166
|
// The server reused a segment this page no longer has (it changed meanwhile): load it in full.
|
|
725
|
-
payload = resolved ?? (await fetchPayload(target, current, signal));
|
|
1167
|
+
payload = resolved ?? (await fetchPayload(target, current, signal, { redirected }));
|
|
726
1168
|
}
|
|
727
1169
|
if (payload === null) return { hard: target };
|
|
728
1170
|
if ('html' in payload) return { document: payload.html, url: payload.url };
|
|
@@ -733,8 +1175,12 @@ class Navigator {
|
|
|
733
1175
|
if (target.origin !== window.location.origin) return { hard: target };
|
|
734
1176
|
if (current.method !== 'GET') keys = [];
|
|
735
1177
|
current = { method: 'GET' };
|
|
1178
|
+
redirected = true;
|
|
1179
|
+
options.onRedirect?.(target);
|
|
736
1180
|
continue;
|
|
737
1181
|
}
|
|
1182
|
+
// A URL no page answers, such as a file: the browser loads it, and its endpoint runs once.
|
|
1183
|
+
if (payload.kind === 'document') return { hard: target };
|
|
738
1184
|
|
|
739
1185
|
const finalUrl = pageUrl(payload.url, target);
|
|
740
1186
|
if (finalUrl.origin !== window.location.origin) throw new Error(`netjes: the page payload names another origin (${finalUrl.origin})`);
|
|
@@ -783,7 +1229,7 @@ class Navigator {
|
|
|
783
1229
|
return this.current.payload.segments.flatMap((segment) => (segment.key && segment.props && !segment.reused ? [segment.key] : []));
|
|
784
1230
|
}
|
|
785
1231
|
|
|
786
|
-
/** Fills in the props of segments the server marked reused from the current page, or null if one is missing. */
|
|
1232
|
+
/** Fills in the props and lang of segments the server marked reused from the current page, or null if one is missing. */
|
|
787
1233
|
private withReusedSegments(payload: PagePayload): PagePayload | null {
|
|
788
1234
|
if (!payload.segments.some((segment) => segment.reused)) return payload;
|
|
789
1235
|
const held = this.current.payload.segments;
|
|
@@ -795,13 +1241,13 @@ class Navigator {
|
|
|
795
1241
|
}
|
|
796
1242
|
const known = held.find((h) => h.id === segment.id && h.key === segment.key && h.props);
|
|
797
1243
|
if (!known) return null;
|
|
798
|
-
segments.push({ ...segment, props: known.props, reused: undefined });
|
|
1244
|
+
segments.push({ ...segment, props: known.props, lang: known.lang, reused: undefined });
|
|
799
1245
|
}
|
|
800
1246
|
return { ...payload, segments };
|
|
801
1247
|
}
|
|
802
1248
|
|
|
803
|
-
private hard(url: URL) {
|
|
804
|
-
if (isWebUrl(url)) this.deps.hardNavigate(url.href);
|
|
1249
|
+
private hard(url: URL, letThrough = false) {
|
|
1250
|
+
if (isWebUrl(url)) this.deps.hardNavigate(url.href, letThrough);
|
|
805
1251
|
else console.error(`netjes: refusing to navigate to ${url.protocol} URL`);
|
|
806
1252
|
}
|
|
807
1253
|
|
|
@@ -820,14 +1266,28 @@ class Navigator {
|
|
|
820
1266
|
if (Date.now() - hit.at >= PREFETCH_TTL_MS) return undefined;
|
|
821
1267
|
return hit.result.then(
|
|
822
1268
|
(result) =>
|
|
823
|
-
|
|
824
|
-
|
|
1269
|
+
// A page that failed on the server is asked for again: it may answer now.
|
|
1270
|
+
'failed' in result
|
|
1271
|
+
? this.load(url, { method: 'GET' }, signal, { reuseSegments: true })
|
|
1272
|
+
: 'payload' in result
|
|
1273
|
+
? { ...result, url: samePage(result.url, url) ? withHash(result.url, url.hash) : result.url }
|
|
1274
|
+
: result,
|
|
1275
|
+
() => this.load(url, { method: 'GET' }, signal, { reuseSegments: true }),
|
|
825
1276
|
);
|
|
826
1277
|
}
|
|
827
1278
|
|
|
828
|
-
|
|
1279
|
+
/**
|
|
1280
|
+
* `carries`: the page on screen stays and its values went with it, so its setters keep writing. Every caller has set
|
|
1281
|
+
* `index` to the place of the entry `key` names.
|
|
1282
|
+
*/
|
|
1283
|
+
private setCurrent(key: string, loaded: Loaded, values: HistoryValues, carries: boolean) {
|
|
829
1284
|
this.currentKey = key;
|
|
1285
|
+
this.shownIndex = this.index;
|
|
830
1286
|
this.current = loaded;
|
|
1287
|
+
this.href = loaded.url.href;
|
|
1288
|
+
this.values = values;
|
|
1289
|
+
if (!carries) this.lineage += 1;
|
|
1290
|
+
this.betweenEntries = false;
|
|
831
1291
|
if (!this.currentIsStale) this.remember(key, loaded);
|
|
832
1292
|
}
|
|
833
1293
|
|
|
@@ -880,12 +1340,28 @@ function applyScroll(intent: ScrollIntent): HTMLElement | null {
|
|
|
880
1340
|
}
|
|
881
1341
|
}
|
|
882
1342
|
|
|
883
|
-
type View = { loaded: Loaded; id: number; scroll: ScrollIntent; focusedAtStart: Element | null };
|
|
1343
|
+
type View = { loaded: Loaded; id: number; scroll: ScrollIntent; focusedAtStart: Element | null; restored: boolean };
|
|
884
1344
|
type ViewValue = { payload: PagePayload; url: URL };
|
|
885
1345
|
|
|
1346
|
+
/** What `useHistoryState` and `useHistoryRestore` read: the entry on screen, a way to write it, and the restores. */
|
|
1347
|
+
export type HistoryContextValue = {
|
|
1348
|
+
/** The lineage of the values on screen: kept while navigations carry the page's values over, new when they start over. */
|
|
1349
|
+
lineage: number;
|
|
1350
|
+
values: HistoryValues;
|
|
1351
|
+
/**
|
|
1352
|
+
* Sets the value `name` of the entry on screen to what `compute` makes of the entry's values, while the values on
|
|
1353
|
+
* screen are of `lineage`; else it does nothing. Stable.
|
|
1354
|
+
*/
|
|
1355
|
+
set(lineage: number, name: string, compute: (values: HistoryValues) => unknown): void;
|
|
1356
|
+
/** Calls `listener` whenever the page on screen was shown from memory after Back or Forward. Stable. */
|
|
1357
|
+
onRestore(listener: () => void): () => void;
|
|
1358
|
+
};
|
|
1359
|
+
|
|
886
1360
|
const RouterContext = createContext<InternalRouter | null>(null);
|
|
887
1361
|
const ViewContext = createContext<ViewValue | null>(null);
|
|
888
1362
|
const NavigationContext = createContext<NavigationState>(IDLE);
|
|
1363
|
+
const HistoryContext = createContext<HistoryContextValue | null>(null);
|
|
1364
|
+
const GuardsContext = createContext<NavigationGuards | null>(null);
|
|
889
1365
|
|
|
890
1366
|
export type RouterProviderProps = {
|
|
891
1367
|
initial: PagePayload;
|
|
@@ -897,6 +1373,12 @@ export type RouterProviderProps = {
|
|
|
897
1373
|
download?: (file: Blob, name: string) => void;
|
|
898
1374
|
/** Wraps every page and the error page, inside the router: where app-wide providers such as the QueryClient go. */
|
|
899
1375
|
shell?: ComponentType<{ children: ReactNode }> | undefined;
|
|
1376
|
+
/**
|
|
1377
|
+
* The `lang` the app's root gave the document (`DocumentInfo.lang`: the locale it was rendered in, or
|
|
1378
|
+
* `NetjesOptions.Lang`). With it, the router keeps `<html lang>` with the page on screen: the page loader's lang,
|
|
1379
|
+
* else the innermost layout loader's, else the page's locale, else this. Without it, it leaves `<html lang>` alone.
|
|
1380
|
+
*/
|
|
1381
|
+
documentLang?: string | undefined;
|
|
900
1382
|
};
|
|
901
1383
|
|
|
902
1384
|
function PassThrough({ children }: { children: ReactNode }) {
|
|
@@ -935,6 +1417,7 @@ export function RouterProvider({
|
|
|
935
1417
|
showDocument = defaultShowDocument,
|
|
936
1418
|
download = defaultDownload,
|
|
937
1419
|
shell: Shell = PassThrough,
|
|
1420
|
+
documentLang,
|
|
938
1421
|
}: RouterProviderProps) {
|
|
939
1422
|
const [view, setView] = useState<View>(() => ({
|
|
940
1423
|
loaded: {
|
|
@@ -945,8 +1428,10 @@ export function RouterProvider({
|
|
|
945
1428
|
id: 0,
|
|
946
1429
|
scroll: NONE,
|
|
947
1430
|
focusedAtStart: null,
|
|
1431
|
+
restored: false,
|
|
948
1432
|
}));
|
|
949
1433
|
const [navigation, setNavigation] = useState<NavigationState>(IDLE);
|
|
1434
|
+
const [guards] = useState(() => new NavigationGuards());
|
|
950
1435
|
const [navigator] = useState(() => {
|
|
951
1436
|
// Server actions called before the effect below registers this router wait for it (the server runs no effects).
|
|
952
1437
|
if (typeof document !== 'undefined') expectActionClient();
|
|
@@ -955,19 +1440,39 @@ export function RouterProvider({
|
|
|
955
1440
|
loader,
|
|
956
1441
|
version: initial.version,
|
|
957
1442
|
basePath: initial.basePath ?? '',
|
|
958
|
-
hardNavigate,
|
|
1443
|
+
hardNavigate: (href, letThrough) => {
|
|
1444
|
+
if (letThrough) guards.letUnloadThrough();
|
|
1445
|
+
hardNavigate(href);
|
|
1446
|
+
},
|
|
959
1447
|
showDocument,
|
|
960
1448
|
download,
|
|
961
1449
|
setPending: setNavigation,
|
|
962
|
-
commit: (loaded, scroll, focusedAtStart) =>
|
|
1450
|
+
commit: (loaded, scroll, focusedAtStart, { lineage, values, restored }) =>
|
|
963
1451
|
startTransition(() => {
|
|
964
|
-
setView((previous) => ({ loaded, id: previous.id + 1, scroll, focusedAtStart }));
|
|
1452
|
+
setView((previous) => ({ loaded, id: previous.id + 1, scroll, focusedAtStart, restored }));
|
|
965
1453
|
setNavigation(IDLE);
|
|
1454
|
+
// In the same transition as the page: the page that leaves never renders with the next entry's values.
|
|
1455
|
+
setEntry({ lineage, values });
|
|
966
1456
|
}),
|
|
1457
|
+
setEntry: (entry) => setEntry(entry),
|
|
1458
|
+
guards,
|
|
967
1459
|
},
|
|
968
1460
|
view.loaded,
|
|
969
1461
|
);
|
|
970
1462
|
});
|
|
1463
|
+
// Every value as its initial one until the router has started, as on the server, so hydration matches.
|
|
1464
|
+
const [entry, setEntry] = useState<HistoryEntry>(() => ({ lineage: navigator.entryLineage, values: NO_VALUES }));
|
|
1465
|
+
const [restoreListeners] = useState(() => new Set<() => void>());
|
|
1466
|
+
const [historyWriters] = useState(() => ({
|
|
1467
|
+
set: (lineage: number, name: string, compute: (values: HistoryValues) => unknown) => navigator.setValue(lineage, name, compute),
|
|
1468
|
+
onRestore: (listener: () => void) => {
|
|
1469
|
+
restoreListeners.add(listener);
|
|
1470
|
+
return () => {
|
|
1471
|
+
restoreListeners.delete(listener);
|
|
1472
|
+
};
|
|
1473
|
+
},
|
|
1474
|
+
}));
|
|
1475
|
+
const history = useMemo<HistoryContextValue>(() => ({ ...entry, ...historyWriters }), [entry, historyWriters]);
|
|
971
1476
|
|
|
972
1477
|
// In the commit that shows the page, before the browser dispatches the clicks that came in while React hydrated it:
|
|
973
1478
|
// a fragment link followed then must find this history entry keyed, to come back to.
|
|
@@ -1006,7 +1511,7 @@ export function RouterProvider({
|
|
|
1006
1511
|
// The user may have moved on while the action ran: then neither pull them back (redirect) nor reload the
|
|
1007
1512
|
// page they left (refresh, which would also cancel their navigation).
|
|
1008
1513
|
const movedOn = navigator.page !== page || navigator.navigating;
|
|
1009
|
-
if (!movedOn && response.redirect) await navigator.navigate(response.redirect, 'push', true);
|
|
1514
|
+
if (!movedOn && response.redirect) await navigator.navigate(response.redirect, 'push', { redirected: true });
|
|
1010
1515
|
else if (!movedOn && response.revalidate) await navigator.refresh();
|
|
1011
1516
|
// After signing in or out (an action that set or deleted a cookie), the page on screen shows whoever was
|
|
1012
1517
|
// signed in before until a page comes from the server: refresh it, like Next.js. That is the action's page
|
|
@@ -1031,6 +1536,18 @@ export function RouterProvider({
|
|
|
1031
1536
|
html.setAttribute(HYDRATED_ATTRIBUTE, '');
|
|
1032
1537
|
return () => html.removeAttribute(HYDRATED_ATTRIBUTE);
|
|
1033
1538
|
}, []);
|
|
1539
|
+
// After the effects of the page that Back or Forward put back, which subscribe as it mounts: a parent's effects run
|
|
1540
|
+
// after its children's.
|
|
1541
|
+
useEffect(() => {
|
|
1542
|
+
if (view.restored) for (const listener of [...restoreListeners]) listener();
|
|
1543
|
+
}, [view, restoreListeners]);
|
|
1544
|
+
useEffect(() => {
|
|
1545
|
+
const onPageShow = (event: PageTransitionEvent) => {
|
|
1546
|
+
if (event.persisted) for (const listener of [...restoreListeners]) listener();
|
|
1547
|
+
};
|
|
1548
|
+
window.addEventListener('pageshow', onPageShow);
|
|
1549
|
+
return () => window.removeEventListener('pageshow', onPageShow);
|
|
1550
|
+
}, [restoreListeners]);
|
|
1034
1551
|
// The key of the page on screen before this commit.
|
|
1035
1552
|
const committedPageKey = useRef(pageKeyOf(view.loaded));
|
|
1036
1553
|
// In the commit that shows the page, before the browser paints it, and after the layout effects of the page and its
|
|
@@ -1045,10 +1562,28 @@ export function RouterProvider({
|
|
|
1045
1562
|
moveFocusAfterNavigation({ target, replaced, keep: view.scroll.kind === 'none', focusedAtStart: view.focusedAtStart });
|
|
1046
1563
|
}, [view]);
|
|
1047
1564
|
|
|
1048
|
-
const router = useMemo<InternalRouter>(
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1565
|
+
const router = useMemo<InternalRouter>(() => {
|
|
1566
|
+
/**
|
|
1567
|
+
* A push or replace, asked of the guards that hold first. What had the focus and what the entry carries are read as
|
|
1568
|
+
* it is called, as without a guard: a value the browser cannot copy rejects it before any guard is asked.
|
|
1569
|
+
*/
|
|
1570
|
+
const guarded = (href: string, history: 'push' | 'replace', options: NavigateOptions & FocusAtStart = {}): Promise<void> => {
|
|
1571
|
+
const focusedAtStart = options.focusedAtStart === undefined ? document.activeElement : options.focusedAtStart;
|
|
1572
|
+
const to = navigator.heldTarget(href);
|
|
1573
|
+
if (to === null) return navigator.navigate(href, history, { ...options, focusedAtStart });
|
|
1574
|
+
// No guard holds: it goes at once, and takes the place of an attempt still waiting for its answer, as after a save.
|
|
1575
|
+
if (!guards.holding) return guards.attempt(to, history, () => navigator.navigate(href, history, { ...options, focusedAtStart }));
|
|
1576
|
+
let historyState: HistoryValues | undefined;
|
|
1577
|
+
try {
|
|
1578
|
+
historyState = options.historyState === undefined ? undefined : (structuredClone(options.historyState) as HistoryValues);
|
|
1579
|
+
} catch (error) {
|
|
1580
|
+
return Promise.reject(error);
|
|
1581
|
+
}
|
|
1582
|
+
return guards.attempt(to, history, () => navigator.navigate(href, history, { ...options, focusedAtStart, historyState, letThrough: true }));
|
|
1583
|
+
};
|
|
1584
|
+
return {
|
|
1585
|
+
push: (href, options) => guarded(href, 'push', options),
|
|
1586
|
+
replace: (href, options) => guarded(href, 'replace', options),
|
|
1052
1587
|
prefetch: (href) => navigator.prefetch(href),
|
|
1053
1588
|
refresh: () => navigator.refresh(),
|
|
1054
1589
|
back: () => window.history.back(),
|
|
@@ -1059,39 +1594,59 @@ export function RouterProvider({
|
|
|
1059
1594
|
return () => actionListeners.delete(listener);
|
|
1060
1595
|
},
|
|
1061
1596
|
onCookiesChanged: (listener) => navigator.onCookiesChanged(listener),
|
|
1062
|
-
}
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
const { payload, modules, url } = view.loaded;
|
|
1597
|
+
};
|
|
1598
|
+
}, [navigator, actionListeners, guards]);
|
|
1599
|
+
const { payload, url } = view.loaded;
|
|
1066
1600
|
const viewValue = useMemo<ViewValue>(() => ({ payload, url }), [payload, url]);
|
|
1601
|
+
// <html lang> for the page on screen. The server wrote the first page's, and Document keeps it as written, so the
|
|
1602
|
+
// attribute changes only when the lang does: an app that sets it itself keeps its value until then (a page whose
|
|
1603
|
+
// loader gives a lang, or another locale), and a page without one after that has the root's. In the commit that
|
|
1604
|
+
// shows the page, before it is painted.
|
|
1605
|
+
const lang = documentLang === undefined ? undefined : langOf(payload, documentLang);
|
|
1606
|
+
const shownLang = useRef(lang);
|
|
1607
|
+
useLayoutEffect(() => {
|
|
1608
|
+
if (lang === undefined || lang === shownLang.current) return;
|
|
1609
|
+
shownLang.current = lang;
|
|
1610
|
+
document.documentElement.lang = lang;
|
|
1611
|
+
}, [lang]);
|
|
1612
|
+
// The same element until another page is shown: a change of the router's state alone (a navigation on its way, a
|
|
1613
|
+
// value of the history entry) re-renders only the components that read it.
|
|
1614
|
+
const page = useMemo(
|
|
1615
|
+
() => (
|
|
1616
|
+
<Shell>
|
|
1617
|
+
<ErrorBoundary
|
|
1618
|
+
resetKey={view.id}
|
|
1619
|
+
fallback={(error) => <ErrorFallback error={error} errorPage={errorPage} loader={loader} payload={view.loaded.payload} />}
|
|
1620
|
+
>
|
|
1621
|
+
<RouteTree
|
|
1622
|
+
modules={view.loaded.modules}
|
|
1623
|
+
segments={view.loaded.payload.segments}
|
|
1624
|
+
props={view.loaded.payload.props}
|
|
1625
|
+
params={view.loaded.payload.params}
|
|
1626
|
+
status={view.loaded.payload.status}
|
|
1627
|
+
pageKind={view.loaded.payload.pageKind}
|
|
1628
|
+
pageKey={pageKeyOf(view.loaded)}
|
|
1629
|
+
retry={() => void router.refresh()}
|
|
1630
|
+
metadata={view.loaded.payload.metadata}
|
|
1631
|
+
/>
|
|
1632
|
+
</ErrorBoundary>
|
|
1633
|
+
</Shell>
|
|
1634
|
+
),
|
|
1635
|
+
[Shell, view, errorPage, loader, router],
|
|
1636
|
+
);
|
|
1067
1637
|
|
|
1068
1638
|
return (
|
|
1069
1639
|
<RouterContext value={router}>
|
|
1070
|
-
<
|
|
1071
|
-
<
|
|
1072
|
-
<
|
|
1073
|
-
<
|
|
1074
|
-
resetKey={view.id}
|
|
1075
|
-
fallback={(error) => <ErrorFallback error={error} errorPage={errorPage} loader={loader} payload={payload} />}
|
|
1076
|
-
>
|
|
1077
|
-
<RouteTree
|
|
1078
|
-
modules={modules}
|
|
1079
|
-
segments={payload.segments}
|
|
1080
|
-
props={payload.props}
|
|
1081
|
-
params={payload.params}
|
|
1082
|
-
status={payload.status}
|
|
1083
|
-
pageKind={payload.pageKind}
|
|
1084
|
-
pageKey={pageKeyOf(view.loaded)}
|
|
1085
|
-
retry={() => void router.refresh()}
|
|
1086
|
-
metadata={payload.metadata}
|
|
1087
|
-
/>
|
|
1088
|
-
</ErrorBoundary>
|
|
1089
|
-
</Shell>
|
|
1640
|
+
<GuardsContext value={guards}>
|
|
1641
|
+
<ViewContext value={viewValue}>
|
|
1642
|
+
<NavigationContext value={navigation}>
|
|
1643
|
+
<HistoryContext value={history}>{page}</HistoryContext>
|
|
1090
1644
|
{/* Outside the app's shell and error boundaries, which cannot remove it, and after them, so it reads what the
|
|
1091
1645
|
new page has set. */}
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1646
|
+
<RouteAnnouncer location={url.pathname + url.search} path={withoutBasePath(url.pathname, payload.basePath ?? '')} />
|
|
1647
|
+
</NavigationContext>
|
|
1648
|
+
</ViewContext>
|
|
1649
|
+
</GuardsContext>
|
|
1095
1650
|
</RouterContext>
|
|
1096
1651
|
);
|
|
1097
1652
|
}
|
|
@@ -1142,20 +1697,28 @@ export function RouterContexts({
|
|
|
1142
1697
|
payload,
|
|
1143
1698
|
url,
|
|
1144
1699
|
navigation,
|
|
1700
|
+
history,
|
|
1701
|
+
guards,
|
|
1145
1702
|
children,
|
|
1146
1703
|
}: {
|
|
1147
1704
|
router: InternalRouter;
|
|
1148
1705
|
payload: PagePayload;
|
|
1149
1706
|
url: URL;
|
|
1150
1707
|
navigation: NavigationState;
|
|
1708
|
+
history: HistoryContextValue;
|
|
1709
|
+
guards: NavigationGuards;
|
|
1151
1710
|
children: ReactNode;
|
|
1152
1711
|
}) {
|
|
1153
1712
|
const view = useMemo<ViewValue>(() => ({ payload, url }), [payload, url]);
|
|
1154
1713
|
return (
|
|
1155
1714
|
<RouterContext value={router}>
|
|
1156
|
-
<
|
|
1157
|
-
<
|
|
1158
|
-
|
|
1715
|
+
<GuardsContext value={guards}>
|
|
1716
|
+
<ViewContext value={view}>
|
|
1717
|
+
<NavigationContext value={navigation}>
|
|
1718
|
+
<HistoryContext value={history}>{children}</HistoryContext>
|
|
1719
|
+
</NavigationContext>
|
|
1720
|
+
</ViewContext>
|
|
1721
|
+
</GuardsContext>
|
|
1159
1722
|
</RouterContext>
|
|
1160
1723
|
);
|
|
1161
1724
|
}
|
|
@@ -1267,7 +1830,104 @@ export function usePagePayload(): PagePayload {
|
|
|
1267
1830
|
return useView().payload;
|
|
1268
1831
|
}
|
|
1269
1832
|
|
|
1270
|
-
/**
|
|
1833
|
+
/**
|
|
1834
|
+
* The router's state: `loading` during a navigation or a refresh, `submitting` during a form post, else `idle`, with
|
|
1835
|
+
* `error` after a navigation, a refresh or a form post that kept the page because it got no page (its `kind` says
|
|
1836
|
+
* which), until the next one starts.
|
|
1837
|
+
*/
|
|
1271
1838
|
export function useNavigation(): NavigationState {
|
|
1272
1839
|
return useContext(NavigationContext);
|
|
1273
1840
|
}
|
|
1841
|
+
|
|
1842
|
+
const NOT_SET = Symbol('not set');
|
|
1843
|
+
|
|
1844
|
+
/** Sets a value of `useHistoryState`: the value itself, or a function of the value before. */
|
|
1845
|
+
export type SetHistoryState<T> = (next: T | ((previous: T) => T)) => void;
|
|
1846
|
+
|
|
1847
|
+
function useHistory(): HistoryContextValue {
|
|
1848
|
+
const history = useContext(HistoryContext);
|
|
1849
|
+
if (!history) throw new Error('netjes: this hook must be used inside a Netjes page');
|
|
1850
|
+
return history;
|
|
1851
|
+
}
|
|
1852
|
+
|
|
1853
|
+
/**
|
|
1854
|
+
* A value kept with the history entry on screen, by `name`, like `useState`: Back, Forward and a reload bring the
|
|
1855
|
+
* entry's value back. A new entry starts from `initial`, or from the value its navigation carried (`historyState` on
|
|
1856
|
+
* `<Link>`, `router.push` and `router.replace`); a navigation that keeps the page on screen (another query, a fragment,
|
|
1857
|
+
* a refresh) keeps its values. The value is `initial` on the server and in the render that hydrates the page. Keep it
|
|
1858
|
+
* small and to what the browser can copy (`structuredClone`): ids, names and numbers, not rows.
|
|
1859
|
+
*
|
|
1860
|
+
* The setter writes into the entry on screen, and like `useState`'s, keeps working and stays the same function through
|
|
1861
|
+
* a navigation that keeps the page and its values: `await action(); setTicked([])` clears the ticks after an action
|
|
1862
|
+
* that refreshes the page. Once the page has left, or Back or Forward has gone to another entry, it changes nothing.
|
|
1863
|
+
*
|
|
1864
|
+
* With a schema, the entry's value is parsed by it, and one it rejects gives `initial`: an entry can hold what an older
|
|
1865
|
+
* build of the app, or another page, put there. Define the schema at module level.
|
|
1866
|
+
*/
|
|
1867
|
+
export function useHistoryState<T>(name: string, initial: T): [T, SetHistoryState<T>];
|
|
1868
|
+
export function useHistoryState<Schema extends StandardSchemaV1>(
|
|
1869
|
+
name: string,
|
|
1870
|
+
initial: StandardSchemaV1.InferOutput<Schema>,
|
|
1871
|
+
schema: Schema,
|
|
1872
|
+
): [StandardSchemaV1.InferOutput<Schema>, SetHistoryState<StandardSchemaV1.InferOutput<Schema>>];
|
|
1873
|
+
export function useHistoryState(name: string, initial: unknown, schema?: StandardSchemaV1): [unknown, SetHistoryState<unknown>] {
|
|
1874
|
+
const { lineage, values, set } = useHistory();
|
|
1875
|
+
// The first render's, as useState keeps its initial value: an array written inline is not a new value each render.
|
|
1876
|
+
const [fallback] = useState(() => initial);
|
|
1877
|
+
const resolve = useCallback(
|
|
1878
|
+
(entry: HistoryValues) => {
|
|
1879
|
+
if (!Object.hasOwn(entry, name)) return fallback;
|
|
1880
|
+
return schema ? parseOr(schema, entry[name], fallback, `history state '${name}'`) : entry[name];
|
|
1881
|
+
},
|
|
1882
|
+
[name, schema, fallback],
|
|
1883
|
+
);
|
|
1884
|
+
const stored = Object.hasOwn(values, name) ? values[name] : NOT_SET;
|
|
1885
|
+
// Parsed again only when the entry's value changes, not when another name's does.
|
|
1886
|
+
const value = useMemo(() => (stored === NOT_SET ? fallback : resolve({ [name]: stored })), [resolve, name, stored, fallback]);
|
|
1887
|
+
// Bound to the page's lineage, not to one entry: like a useState setter, it keeps working, and stays the same
|
|
1888
|
+
// function, through a navigation that keeps the page on screen with its values (a refresh, another query).
|
|
1889
|
+
const setValue = useCallback<SetHistoryState<unknown>>(
|
|
1890
|
+
(next) => set(lineage, name, (current) => (typeof next === 'function' ? (next as (previous: unknown) => unknown)(resolve(current)) : next)),
|
|
1891
|
+
[set, lineage, name, resolve],
|
|
1892
|
+
);
|
|
1893
|
+
return [value, setValue];
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
/**
|
|
1897
|
+
* Calls `callback` each time the page on screen was shown from memory after Back or Forward: a page the router kept
|
|
1898
|
+
* (it asks the server nothing), or the whole document the browser kept in its back-forward cache. What the page shows
|
|
1899
|
+
* is as old as the visit it is from, so the page can refresh itself (`router.refresh()`) or a part of it. A page the
|
|
1900
|
+
* router loads from the server, and Back over a fragment link of the page on screen, do not call it.
|
|
1901
|
+
*/
|
|
1902
|
+
export function useHistoryRestore(callback: () => void): void {
|
|
1903
|
+
const { onRestore } = useHistory();
|
|
1904
|
+
const latest = useRef(callback);
|
|
1905
|
+
useEffect(() => {
|
|
1906
|
+
latest.current = callback;
|
|
1907
|
+
});
|
|
1908
|
+
useEffect(() => onRestore(() => latest.current()), [onRestore]);
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/**
|
|
1912
|
+
* Holds every client navigation while `when` is true, and asks `onAttempt` first: links, `<Form method="get">`,
|
|
1913
|
+
* `router.push`, `router.replace`, `router.back`, `router.forward` and the browser's Back and Forward. The navigation
|
|
1914
|
+
* waits until the attempt's `proceed()` lets it go on, or its `stay()` keeps the page; for Back and Forward the router
|
|
1915
|
+
* puts the entry back first, so the address bar shows the page on screen while the question is open. `proceed()` works
|
|
1916
|
+
* whenever it is called, also once `when` is false (after a save), and a navigation that comes while one waits takes its
|
|
1917
|
+
* place. While it holds, `beforeunload` has the browser ask before the document unloads: a reload, closing the tab, a
|
|
1918
|
+
* link to another site. A link to a fragment of the page on screen, which keeps the page, is not held, and neither is a
|
|
1919
|
+
* form post, a server action or `router.refresh()`, nor the page the server's redirect in their answer leads to (the
|
|
1920
|
+
* sign-in page after the session expired). With several guards holding, each is asked in turn, the one that
|
|
1921
|
+
* started to hold last first, and the first `stay()` ends it. `onAttempt` is the latest render's. Throws outside a
|
|
1922
|
+
* Netjes page.
|
|
1923
|
+
*/
|
|
1924
|
+
export function useNavigationGuard(options: NavigationGuardOptions): void {
|
|
1925
|
+
const guards = useContext(GuardsContext);
|
|
1926
|
+
if (!guards) throw new Error('netjes: this hook must be used inside a Netjes page');
|
|
1927
|
+
const latest = useRef(options);
|
|
1928
|
+
useEffect(() => {
|
|
1929
|
+
latest.current = options;
|
|
1930
|
+
});
|
|
1931
|
+
const { when } = options;
|
|
1932
|
+
useEffect(() => (when ? guards.register(() => latest.current) : undefined), [guards, when]);
|
|
1933
|
+
}
|