netjes 0.0.3 → 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 +10 -8
- package/cli/commands.mjs +32 -6
- package/cli/info.mjs +268 -31
- package/cli/routes.mjs +35 -8
- 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/href.d.ts +7 -0
- package/dist/href.d.ts.map +1 -1
- package/dist/href.js +16 -5
- package/dist/href.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- 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 +51 -0
- package/dist/mounted.d.ts.map +1 -0
- package/dist/mounted.js +110 -0
- package/dist/mounted.js.map +1 -0
- 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 +28 -2
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +53 -1
- package/dist/payload.js.map +1 -1
- package/dist/render-document.d.ts +18 -4
- package/dist/render-document.d.ts.map +1 -1
- package/dist/render-document.js +79 -16
- package/dist/render-document.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 +23 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +63 -21
- package/dist/testing.js.map +1 -1
- package/package.json +5 -1
- package/sidecar/server.mjs +117 -24
- package/skills/netjes/SKILL.md +6 -5
- package/skills/netjes/references/data-and-actions.md +10 -5
- package/skills/netjes/references/deployment.md +1 -1
- package/skills/netjes/references/routing.md +21 -6
- package/skills/netjes/references/testing.md +6 -3
- package/src/actions.tsx +5 -4
- package/src/document.tsx +11 -4
- package/src/href.ts +16 -5
- package/src/index.ts +27 -1
- package/src/lang.ts +28 -0
- package/src/link.tsx +37 -9
- package/src/mounted.tsx +160 -0
- package/src/navigation-guard.ts +136 -0
- package/src/payload.ts +69 -3
- package/src/render-document.tsx +117 -20
- 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 +74 -15
- package/src/virtual.d.ts +6 -1
- package/template/Dockerfile +1 -1
- package/template/README.md +1 -1
- package/template/_AGENTS.md +7 -4
- package/template/docker-compose.override.yml +15 -3
- package/template/generated/netjes.ts +1 -1
- package/vite/packages.mjs +345 -0
- package/vite/plugin.d.ts +7 -0
- package/vite/plugin.mjs +208 -30
package/dist/router.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import { Suspense, createContext, startTransition, use, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
|
|
2
|
+
import { Suspense, createContext, startTransition, use, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, } from 'react';
|
|
3
3
|
import { actionRequest, expectActionClient, fetchAction, setActionClient } from './actions.js';
|
|
4
4
|
import { deferredRegistry, revivePayload } from './deferred.js';
|
|
5
|
+
import { documentLang as langOf } from './lang.js';
|
|
5
6
|
import { MissingModuleError } from './modules.js';
|
|
6
7
|
import { moveFocusAfterNavigation } from './navigation-focus.js';
|
|
7
|
-
import {
|
|
8
|
+
import { NavigationGuards } from './navigation-guard.js';
|
|
9
|
+
import { COOKIES_HEADER, DATA_HEADER, REDIRECTED_HEADER, SEGMENTS_HEADER, SERVER_TIME_HEADER, parseAntiforgery, parseNavigationPayload, } from './payload.js';
|
|
8
10
|
import { RouteAnnouncer } from './route-announcer.js';
|
|
9
11
|
import { ErrorBoundary, LayoutDepthContext, RouteTree, asError } from './route-tree.js';
|
|
10
|
-
import { parseLenient, parseWith } from './schema.js';
|
|
12
|
+
import { parseLenient, parseOr, parseWith } from './schema.js';
|
|
11
13
|
function isLoaded(result) {
|
|
12
14
|
return 'payload' in result;
|
|
13
15
|
}
|
|
@@ -21,6 +23,13 @@ const ANTIFORGERY_URL = '/_netjes/antiforgery';
|
|
|
21
23
|
const NONE = { kind: 'none' };
|
|
22
24
|
const TOP = { kind: 'top' };
|
|
23
25
|
const STATE_KEY = '__netjes';
|
|
26
|
+
/** Where an entry's `useHistoryState` values are, in `history.state`, beside the entry's key. */
|
|
27
|
+
const VALUES_KEY = '__netjesState';
|
|
28
|
+
/**
|
|
29
|
+
* 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
|
|
30
|
+
* entry it replaced. After Back or Forward it tells the router how many steps the browser took, and which way.
|
|
31
|
+
*/
|
|
32
|
+
const INDEX_KEY = '__netjesIndex';
|
|
24
33
|
/**
|
|
25
34
|
* On `<html>` while the client router runs in the document, and the public sign that it does: end-to-end tests wait
|
|
26
35
|
* for it before they click. (The history entry's key is no such sign: the entry keeps it when the browser loads the
|
|
@@ -46,6 +55,38 @@ function readKey(state) {
|
|
|
46
55
|
const value = state[STATE_KEY];
|
|
47
56
|
return typeof value === 'string' ? value : undefined;
|
|
48
57
|
}
|
|
58
|
+
function readIndex(state) {
|
|
59
|
+
const value = isRecord(state) ? state[INDEX_KEY] : undefined;
|
|
60
|
+
return Number.isSafeInteger(value) ? value : undefined;
|
|
61
|
+
}
|
|
62
|
+
const NO_VALUES = Object.freeze({});
|
|
63
|
+
function isRecord(value) {
|
|
64
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
65
|
+
}
|
|
66
|
+
function readValues(state) {
|
|
67
|
+
const values = isRecord(state) ? state[VALUES_KEY] : undefined;
|
|
68
|
+
return isRecord(values) ? values : NO_VALUES;
|
|
69
|
+
}
|
|
70
|
+
/** `values` with the names a navigation carries set over them. */
|
|
71
|
+
function withCarried(values, carried) {
|
|
72
|
+
return carried === undefined || Object.keys(carried).length === 0 ? values : { ...values, ...carried };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The state the router writes for an entry: its key, its place and its values, over `kept`, the state of the entry it
|
|
76
|
+
* replaces, so the keys an app or a library put there stay. A new entry keeps nothing of the one before.
|
|
77
|
+
*/
|
|
78
|
+
function entryState(key, index, values, kept = null) {
|
|
79
|
+
const state = { ...(isRecord(kept) ? kept : {}), [STATE_KEY]: key };
|
|
80
|
+
if (index === undefined)
|
|
81
|
+
delete state[INDEX_KEY];
|
|
82
|
+
else
|
|
83
|
+
state[INDEX_KEY] = index;
|
|
84
|
+
if (Object.keys(values).length > 0)
|
|
85
|
+
state[VALUES_KEY] = values;
|
|
86
|
+
else
|
|
87
|
+
delete state[VALUES_KEY];
|
|
88
|
+
return state;
|
|
89
|
+
}
|
|
49
90
|
/**
|
|
50
91
|
* Records how far the browser clock is from the server's, given a server time for "now": the `X-Netjes-Now` header
|
|
51
92
|
* of a data response, or for the initial document the payload's `renderedAt` (so the browser judges seeded data
|
|
@@ -95,6 +136,38 @@ function withHash(url, hash) {
|
|
|
95
136
|
copy.hash = hash;
|
|
96
137
|
return copy;
|
|
97
138
|
}
|
|
139
|
+
/**
|
|
140
|
+
* No answer came for a request: the connection failed, the browser is offline, or the browser refused to follow a
|
|
141
|
+
* redirect (one to another origin that does not allow this one). `headers` are the request's, to ask again with.
|
|
142
|
+
*/
|
|
143
|
+
class NoAnswer extends Error {
|
|
144
|
+
name = 'NoAnswer';
|
|
145
|
+
url;
|
|
146
|
+
headers;
|
|
147
|
+
constructor(url, headers, cause) {
|
|
148
|
+
super(`netjes: no answer from ${url.href}`, { cause });
|
|
149
|
+
this.url = url;
|
|
150
|
+
this.headers = headers;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** The browser says it has no network. `navigator.onLine` is true when it cannot tell, so only `false` counts. */
|
|
154
|
+
const offline = () => typeof navigator !== 'undefined' && navigator.onLine === false;
|
|
155
|
+
/**
|
|
156
|
+
* Whether `failed` answers with a redirect, asked again without following it. A redirect to another origin that does
|
|
157
|
+
* not allow this one, such as an identity provider's sign-in page, fails `fetch` as a lost connection does; the browser
|
|
158
|
+
* follows it itself when it loads the URL as a document.
|
|
159
|
+
*/
|
|
160
|
+
async function answersWithRedirect(failed, signal) {
|
|
161
|
+
try {
|
|
162
|
+
const response = await fetch(failed.url.href, { headers: failed.headers, credentials: 'same-origin', redirect: 'manual', signal });
|
|
163
|
+
void response.body?.cancel().catch(() => { });
|
|
164
|
+
// A browser hides the redirect behind an opaque answer; other runtimes hand over the 3xx itself.
|
|
165
|
+
return response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
98
171
|
function attachmentName(disposition) {
|
|
99
172
|
const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1];
|
|
100
173
|
if (encoded) {
|
|
@@ -107,8 +180,11 @@ function attachmentName(disposition) {
|
|
|
107
180
|
}
|
|
108
181
|
return /filename="?([^";]+)"?/i.exec(disposition)?.[1] ?? 'download';
|
|
109
182
|
}
|
|
110
|
-
async function fetchPayload(url, request, signal,
|
|
183
|
+
async function fetchPayload(url, request, signal, options = {}) {
|
|
184
|
+
const { segmentKeys = [], token, onCookiesChanged, redirected = false } = options;
|
|
111
185
|
const headers = { [DATA_HEADER]: '1', Accept: 'application/json' };
|
|
186
|
+
if (request.method === 'GET' && redirected)
|
|
187
|
+
headers[REDIRECTED_HEADER] = '1';
|
|
112
188
|
if (request.method === 'POST' && token?.headerName && token.requestToken)
|
|
113
189
|
headers[token.headerName] = token.requestToken;
|
|
114
190
|
if (request.method === 'GET' && segmentKeys.length > 0)
|
|
@@ -118,7 +194,15 @@ async function fetchPayload(url, request, signal, segmentKeys = [], token, onCoo
|
|
|
118
194
|
const init = { method: request.method, headers, credentials: 'same-origin', signal };
|
|
119
195
|
if (request.method === 'POST' && request.body !== undefined)
|
|
120
196
|
init.body = request.body;
|
|
121
|
-
|
|
197
|
+
let response;
|
|
198
|
+
try {
|
|
199
|
+
response = await fetch(url.href, init);
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
if (signal.aborted)
|
|
203
|
+
throw error;
|
|
204
|
+
throw new NoAnswer(url, headers, error);
|
|
205
|
+
}
|
|
122
206
|
// A form post that signed someone in or out; script cannot read Set-Cookie itself.
|
|
123
207
|
if (request.method === 'POST' && response.headers.get(COOKIES_HEADER) === 'changed')
|
|
124
208
|
onCookiesChanged?.();
|
|
@@ -156,7 +240,16 @@ async function fetchPayload(url, request, signal, segmentKeys = [], token, onCoo
|
|
|
156
240
|
return withClockOffset(revivePayload(payload, registry.source), Number.isFinite(serverNow) ? serverNow : undefined);
|
|
157
241
|
}
|
|
158
242
|
if (type.includes('application/json')) {
|
|
159
|
-
|
|
243
|
+
let payload;
|
|
244
|
+
try {
|
|
245
|
+
payload = parseNavigationPayload(await response.json());
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
// A server error that is no Netjes page, such as a gateway's JSON error, fails a GET; anything else is a bug.
|
|
249
|
+
if (request.method === 'GET' && response.status >= 500 && !signal.aborted)
|
|
250
|
+
return { failed: response.status };
|
|
251
|
+
throw error;
|
|
252
|
+
}
|
|
160
253
|
if (payload.kind !== 'page')
|
|
161
254
|
return payload;
|
|
162
255
|
// Without the header (a cache in front of UseNetjes) there is no fresh server time: take the timestamps as they
|
|
@@ -164,9 +257,12 @@ async function fetchPayload(url, request, signal, segmentKeys = [], token, onCoo
|
|
|
164
257
|
const serverNow = Number(response.headers.get(SERVER_TIME_HEADER) ?? Number.NaN);
|
|
165
258
|
return withClockOffset(payload, Number.isFinite(serverNow) ? serverNow : undefined);
|
|
166
259
|
}
|
|
167
|
-
// Something other than a Netjes page answered. A GET
|
|
168
|
-
|
|
169
|
-
|
|
260
|
+
// Something other than a Netjes page answered. A GET that failed on the server (a gateway's 502 while the app
|
|
261
|
+
// restarts, say) fails; any other the browser loads instead, so the router stops reading it (a file, say).
|
|
262
|
+
if (request.method === 'GET') {
|
|
263
|
+
void response.body?.cancel().catch(() => { });
|
|
264
|
+
return response.status >= 500 ? { failed: response.status } : null;
|
|
265
|
+
}
|
|
170
266
|
// A POST must not be sent again. Show what a native submission would have shown, where that is safe.
|
|
171
267
|
if (!response.ok)
|
|
172
268
|
return { failed: response.status };
|
|
@@ -212,8 +308,44 @@ class Navigator {
|
|
|
212
308
|
entries = new Map();
|
|
213
309
|
scrollPositions = new Map();
|
|
214
310
|
currentKey = createKey();
|
|
311
|
+
/** The `useHistoryState` values of the entry on screen, as its `history.state` holds them. */
|
|
312
|
+
values = NO_VALUES;
|
|
313
|
+
/**
|
|
314
|
+
* The lineage of the values on screen, to which `useHistoryState`'s setters are bound. A navigation that keeps the
|
|
315
|
+
* page on screen gives the entry a new key but carries the page's values over, as the page keeps its React state, so
|
|
316
|
+
* it keeps the lineage too: a setter from before it still writes. A new one starts when the values start over
|
|
317
|
+
* (another page) or Back or Forward switch the entry, and a setter of the lineage before writes nothing.
|
|
318
|
+
*/
|
|
319
|
+
lineage = 0;
|
|
320
|
+
/**
|
|
321
|
+
* The browser is on another entry than the page on screen: Back or Forward went to one whose page is still loading,
|
|
322
|
+
* or the router is stepping back (a guard held Back, or the page did not come). The page must not write its values
|
|
323
|
+
* into that entry.
|
|
324
|
+
*/
|
|
325
|
+
betweenEntries = false;
|
|
215
326
|
/** The page on screen is from before cookies changed: kept for no history entry until one comes from the server. */
|
|
216
327
|
currentIsStale = false;
|
|
328
|
+
/**
|
|
329
|
+
* The place in the tab's history (`INDEX_KEY`) of the entry on screen, or of the entry Back or Forward went to while
|
|
330
|
+
* its page loads, or undefined on an entry the router did not make (one an app or a library pushed itself), whose
|
|
331
|
+
* place it does not know.
|
|
332
|
+
*/
|
|
333
|
+
index;
|
|
334
|
+
/**
|
|
335
|
+
* The place of the entry of the page on screen. It is `index`, but while Back or Forward loads the page of the entry
|
|
336
|
+
* it went to: a Back or Forward whose page does not come steps back to it, also one that went from an entry whose
|
|
337
|
+
* page was still loading, and a step back of the router's that lands on it has the browser on the page's entry.
|
|
338
|
+
*/
|
|
339
|
+
shownIndex;
|
|
340
|
+
/**
|
|
341
|
+
* The router is stepping back to the entry at `index`, after a guard held Back or Forward (once there, it `ask`s) or
|
|
342
|
+
* a page did not come.
|
|
343
|
+
*/
|
|
344
|
+
puttingBack = null;
|
|
345
|
+
/** The place a guard let Back or Forward go to: the step there is not held again. */
|
|
346
|
+
letThrough = null;
|
|
347
|
+
/** The URL of the entry on screen as the browser shows it, fragment included (the first page's payload has none). */
|
|
348
|
+
href = '';
|
|
217
349
|
/** Shared with the app's other tabs, where the browser has BroadcastChannel; null until started, and once stopped. */
|
|
218
350
|
channel = null;
|
|
219
351
|
deps;
|
|
@@ -221,15 +353,34 @@ class Navigator {
|
|
|
221
353
|
constructor(deps, current) {
|
|
222
354
|
this.deps = deps;
|
|
223
355
|
this.current = current;
|
|
356
|
+
// The entry the document was loaded into keeps its key and values when the browser loads it again (a reload).
|
|
357
|
+
// They are read here, so a page that sets a value before start() writes into that entry, and shown from start().
|
|
358
|
+
if (typeof window !== 'undefined') {
|
|
359
|
+
const existing = readKey(window.history.state);
|
|
360
|
+
if (existing)
|
|
361
|
+
this.currentKey = existing;
|
|
362
|
+
this.values = readValues(window.history.state);
|
|
363
|
+
// A new document's entry is the last one of the tab's history. Only the steps between the entries matter, so a
|
|
364
|
+
// place that is off (the browser keeps 50 entries or so) changes nothing.
|
|
365
|
+
this.index = readIndex(window.history.state) ?? Math.max(window.history.length - 1, 0);
|
|
366
|
+
this.shownIndex = this.index;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
/** The lineage of the values on screen. */
|
|
370
|
+
get entryLineage() {
|
|
371
|
+
return this.lineage;
|
|
224
372
|
}
|
|
225
373
|
start() {
|
|
226
374
|
window.history.scrollRestoration = 'manual';
|
|
227
|
-
|
|
228
|
-
if (
|
|
229
|
-
this.currentKey
|
|
230
|
-
|
|
231
|
-
window.history.replaceState({ ...(window.history.state ?? {}), [STATE_KEY]: this.currentKey }, '');
|
|
375
|
+
this.href = window.location.href;
|
|
376
|
+
if (readKey(window.history.state) !== this.currentKey || readIndex(window.history.state) !== this.index) {
|
|
377
|
+
window.history.replaceState(entryState(this.currentKey, this.index, this.values, window.history.state), '');
|
|
378
|
+
}
|
|
232
379
|
this.remember(this.currentKey, this.current);
|
|
380
|
+
// The commit that hydrated the page rendered every value as its initial one, as the server did. An entry that holds
|
|
381
|
+
// values (after a reload) shows them now, before the browser paints; one with none renders nothing again.
|
|
382
|
+
if (this.values !== NO_VALUES)
|
|
383
|
+
this.deps.setEntry({ lineage: this.lineage, values: this.values });
|
|
233
384
|
let frame = 0;
|
|
234
385
|
const onScroll = () => {
|
|
235
386
|
if (frame)
|
|
@@ -261,8 +412,25 @@ class Navigator {
|
|
|
261
412
|
this.channel?.close();
|
|
262
413
|
this.channel = null;
|
|
263
414
|
}
|
|
264
|
-
/**
|
|
265
|
-
|
|
415
|
+
/**
|
|
416
|
+
* Sets a `useHistoryState` value of the entry on screen, computed from the entry's values, in its `history.state`,
|
|
417
|
+
* for a setter of the values' `lineage`. A setter of a page that has left (setting a value as it unmounts), or of the
|
|
418
|
+
* entry before Back or Forward, changes nothing, and so does any setter while the browser is on another entry.
|
|
419
|
+
*/
|
|
420
|
+
setValue(lineage, name, compute) {
|
|
421
|
+
if (lineage !== this.lineage || this.betweenEntries)
|
|
422
|
+
return;
|
|
423
|
+
const values = { ...this.values, [name]: compute(this.values) };
|
|
424
|
+
// First, so a value the browser cannot keep throws before anything changed.
|
|
425
|
+
window.history.replaceState(entryState(this.currentKey, this.index, values, window.history.state), '');
|
|
426
|
+
this.values = values;
|
|
427
|
+
this.deps.setEntry({ lineage, values });
|
|
428
|
+
}
|
|
429
|
+
async navigate(href, history, options = {}) {
|
|
430
|
+
const { scroll = true, focusedAtStart = document.activeElement, historyState, letThrough = false, redirected = false } = options;
|
|
431
|
+
// A copy, as the browser keeps one: what the caller changes later does not reach the entry, and a value the
|
|
432
|
+
// browser cannot keep throws here, before the navigation starts.
|
|
433
|
+
const carried = historyState === undefined ? undefined : structuredClone(historyState);
|
|
266
434
|
const url = new URL(withBasePath(href, this.deps.basePath), window.location.href);
|
|
267
435
|
if (!isWebUrl(url)) {
|
|
268
436
|
console.error(`netjes: refusing to navigate to ${url.protocol} URL`);
|
|
@@ -277,9 +445,16 @@ class Navigator {
|
|
|
277
445
|
this.cancelActive();
|
|
278
446
|
this.rememberScroll();
|
|
279
447
|
const key = createKey();
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
this.
|
|
448
|
+
// The page stays, and so do its values.
|
|
449
|
+
const values = withCarried(this.values, carried);
|
|
450
|
+
this.index = history === 'push' ? this.nextIndex() : this.index;
|
|
451
|
+
window.history[history === 'push' ? 'pushState' : 'replaceState'](entryState(key, this.index, values, history === 'replace' ? window.history.state : null), '', url.href);
|
|
452
|
+
this.setCurrent(key, { ...this.current, url }, values, true);
|
|
453
|
+
this.deps.commit(this.current, scroll ? { kind: 'hash', hash: url.hash } : NONE, focusedAtStart, {
|
|
454
|
+
lineage: this.lineage,
|
|
455
|
+
values,
|
|
456
|
+
restored: false,
|
|
457
|
+
});
|
|
283
458
|
return;
|
|
284
459
|
}
|
|
285
460
|
await this.go(url, { method: 'GET' }, {
|
|
@@ -289,8 +464,31 @@ class Navigator {
|
|
|
289
464
|
usePrefetch: true,
|
|
290
465
|
reuseSegments: true,
|
|
291
466
|
focusedAtStart,
|
|
467
|
+
letThrough,
|
|
468
|
+
redirected,
|
|
469
|
+
...(carried ? { historyState: carried } : {}),
|
|
292
470
|
});
|
|
293
471
|
}
|
|
472
|
+
/**
|
|
473
|
+
* Where a push or replace to `href` goes, as a guard is told (without the base path), or null for one no guard holds:
|
|
474
|
+
* to another origin or scheme, which the browser loads (a guard's `beforeunload` asks then), or to a fragment of the
|
|
475
|
+
* page on screen, which loads nothing and keeps the page.
|
|
476
|
+
*/
|
|
477
|
+
heldTarget(href) {
|
|
478
|
+
let url;
|
|
479
|
+
try {
|
|
480
|
+
url = new URL(withBasePath(href, this.deps.basePath), window.location.href);
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
// navigate() fails on it as it would without a guard.
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
if (!isWebUrl(url) || url.origin !== window.location.origin)
|
|
487
|
+
return null;
|
|
488
|
+
if (url.hash && samePage(url, this.current.url))
|
|
489
|
+
return null;
|
|
490
|
+
return withoutBasePath(url.pathname, this.deps.basePath) + url.search + url.hash;
|
|
491
|
+
}
|
|
294
492
|
submit(action, body, focusedAtStart = document.activeElement) {
|
|
295
493
|
return this.go(action, { method: 'POST', ...body }, { history: 'auto', scroll: 'auto', pending: 'submitting', usePrefetch: false, reuseSegments: false, focusedAtStart });
|
|
296
494
|
}
|
|
@@ -309,6 +507,7 @@ class Navigator {
|
|
|
309
507
|
pending: 'loading',
|
|
310
508
|
usePrefetch: false,
|
|
311
509
|
reuseSegments: false,
|
|
510
|
+
refresh: true,
|
|
312
511
|
...(base ? { interceptOver: withHash(base.url, '') } : {}),
|
|
313
512
|
});
|
|
314
513
|
}
|
|
@@ -415,7 +614,8 @@ class Navigator {
|
|
|
415
614
|
}
|
|
416
615
|
startPrefetch(url) {
|
|
417
616
|
const controller = new AbortController();
|
|
418
|
-
const
|
|
617
|
+
const result = this.load(url, { method: 'GET' }, controller.signal, { reuseSegments: true });
|
|
618
|
+
const prefetch = { at: Date.now(), result, controller, loading: true };
|
|
419
619
|
prefetch.result.then(() => {
|
|
420
620
|
prefetch.loading = false;
|
|
421
621
|
}, () => {
|
|
@@ -426,20 +626,99 @@ class Navigator {
|
|
|
426
626
|
});
|
|
427
627
|
this.prefetched.set(url.href, prefetch);
|
|
428
628
|
}
|
|
629
|
+
/** The place of an entry pushed after the one on screen. */
|
|
630
|
+
nextIndex() {
|
|
631
|
+
return this.index === undefined ? undefined : this.index + 1;
|
|
632
|
+
}
|
|
429
633
|
onPopState(event) {
|
|
634
|
+
const index = readIndex(event.state);
|
|
635
|
+
const puttingBack = this.puttingBack;
|
|
636
|
+
this.puttingBack = null;
|
|
637
|
+
// The router's own step back, after a guard held Back or Forward or a page did not come: the browser shows the URL
|
|
638
|
+
// of the entry it was on again.
|
|
639
|
+
if (puttingBack && index === puttingBack.index) {
|
|
640
|
+
// That is the entry of the page on screen, unless a guard held Back while the page of the entry the browser was on
|
|
641
|
+
// still loads: the browser is back on that entry, which the page on screen must not write into. The places tell,
|
|
642
|
+
// also when that page has come meanwhile, or a refresh gave the page on screen a new key.
|
|
643
|
+
this.betweenEntries = index !== this.shownIndex;
|
|
644
|
+
puttingBack.ask();
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
430
647
|
const url = new URL(window.location.href);
|
|
648
|
+
const letThrough = this.letThrough !== null && index === this.letThrough;
|
|
649
|
+
this.letThrough = null;
|
|
650
|
+
// A step to another page takes the place of an attempt still waiting for its answer: it is asked about in its
|
|
651
|
+
// place, or it goes on. A step that keeps the page leaves the question open.
|
|
652
|
+
if (!samePage(url, this.current.url))
|
|
653
|
+
this.deps.guards.dropAttempt();
|
|
654
|
+
if (!letThrough && this.holdTraversal(url, index))
|
|
655
|
+
return;
|
|
656
|
+
// An entry with no place on the page on screen: a fragment the browser moved to itself (a plain `<a href="#…">`, a
|
|
657
|
+
// fragment typed in the address bar, `location.hash`), which fires `popstate` with no state. It adds an entry after
|
|
658
|
+
// the one on screen, which gets the next place, or replaces that entry when its URL is the one on screen (the same
|
|
659
|
+
// link followed again), which keeps its place. A place counted short only puts a held step back short of the
|
|
660
|
+
// entry on screen; one counted long could send it past the end of the history. Either way the entry gets a key,
|
|
661
|
+
// so the steps to it, from it and from the entries pushed after it are counted as any others.
|
|
662
|
+
const fragment = index === undefined && samePage(url, this.current.url);
|
|
663
|
+
this.index = !fragment ? index : url.href === this.href ? this.index : this.nextIndex();
|
|
431
664
|
const key = readKey(event.state) ?? createKey();
|
|
432
665
|
const saved = this.scrollPositions.get(key);
|
|
433
666
|
const scroll = saved ? { kind: 'restore', ...saved } : url.hash ? { kind: 'hash', hash: url.hash } : TOP;
|
|
434
667
|
const cached = this.entries.get(key);
|
|
435
668
|
const known = cached && samePage(cached.url, url) ? cached : samePage(url, this.current.url) ? this.current : null;
|
|
669
|
+
// A fragment the browser moved to itself keeps the page, and so its values, as a fragment link does; the entry
|
|
670
|
+
// starts with none of its own. Back or Forward shows the values of the entry it went to.
|
|
671
|
+
const values = fragment ? withCarried(this.values, readValues(event.state)) : readValues(event.state);
|
|
672
|
+
if (fragment)
|
|
673
|
+
window.history.replaceState(entryState(key, this.index, values, event.state), '');
|
|
436
674
|
if (known) {
|
|
437
675
|
this.active?.controller.abort();
|
|
438
|
-
|
|
439
|
-
|
|
676
|
+
// From memory, unless the page on screen simply stays (Back over a fragment link).
|
|
677
|
+
const restored = known.payload !== this.current.payload;
|
|
678
|
+
this.setCurrent(key, { ...known, url }, values, fragment);
|
|
679
|
+
this.deps.commit(this.current, scroll, document.activeElement, { lineage: this.lineage, values, restored });
|
|
440
680
|
return;
|
|
441
681
|
}
|
|
442
|
-
|
|
682
|
+
this.betweenEntries = true;
|
|
683
|
+
void this.go(url, { method: 'GET' }, {
|
|
684
|
+
history: 'none',
|
|
685
|
+
scroll,
|
|
686
|
+
pending: 'loading',
|
|
687
|
+
key,
|
|
688
|
+
usePrefetch: false,
|
|
689
|
+
reuseSegments: true,
|
|
690
|
+
entryValues: values,
|
|
691
|
+
letThrough,
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
/**
|
|
695
|
+
* Holds Back or Forward to `url`, the entry at `index`, while a guard holds: steps back to the entry on screen, then
|
|
696
|
+
* asks the guards, and steps to the entry the reader chose when they let it, from wherever the page is by then (a
|
|
697
|
+
* fragment link may have added an entry meanwhile). Back over a fragment link keeps the page and is not held.
|
|
698
|
+
* Neither is a step to an entry whose place the router does not know: it cannot tell the way back, and guessing could
|
|
699
|
+
* take the reader somewhere else, so it lets it go.
|
|
700
|
+
*/
|
|
701
|
+
holdTraversal(url, index) {
|
|
702
|
+
if (!this.deps.guards.holding || samePage(url, this.current.url))
|
|
703
|
+
return false;
|
|
704
|
+
const from = this.index;
|
|
705
|
+
if (index === undefined || from === undefined || index === from)
|
|
706
|
+
return false;
|
|
707
|
+
const steps = index - from;
|
|
708
|
+
const to = withoutBasePath(url.pathname, this.deps.basePath) + url.search + url.hash;
|
|
709
|
+
this.puttingBack = {
|
|
710
|
+
index: from,
|
|
711
|
+
ask: () => void this.deps.guards.attempt(to, steps < 0 ? 'back' : 'forward', async () => {
|
|
712
|
+
const now = this.index;
|
|
713
|
+
if (now === undefined || now === index)
|
|
714
|
+
return;
|
|
715
|
+
this.letThrough = index;
|
|
716
|
+
window.history.go(index - now);
|
|
717
|
+
}),
|
|
718
|
+
};
|
|
719
|
+
this.betweenEntries = true;
|
|
720
|
+
window.history.go(-steps);
|
|
721
|
+
return true;
|
|
443
722
|
}
|
|
444
723
|
async go(url, request, options) {
|
|
445
724
|
// Read before anything this navigation starts can move it: inside the click (or the keypress) that started it,
|
|
@@ -468,11 +747,27 @@ class Navigator {
|
|
|
468
747
|
this.deps.setPending({ state: options.pending, location: withoutBasePath(url.pathname, this.deps.basePath) + url.search });
|
|
469
748
|
let committed = false;
|
|
470
749
|
let failure;
|
|
750
|
+
// The request a failure belongs to. Once a form post is answered with a redirect, the post went through: from there
|
|
751
|
+
// 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
|
|
752
|
+
// offer to send it again.
|
|
753
|
+
const at = { url, request };
|
|
754
|
+
const onRedirect = request.method === 'POST'
|
|
755
|
+
? (target) => {
|
|
756
|
+
at.url = target;
|
|
757
|
+
at.request = { method: 'GET' };
|
|
758
|
+
}
|
|
759
|
+
: undefined;
|
|
471
760
|
try {
|
|
472
761
|
const prefetched = options.usePrefetch ? this.takePrefetched(url, controller.signal) : undefined;
|
|
473
|
-
const under = options.interceptOver ? this.load(options.interceptOver, { method: 'GET' }, controller.signal
|
|
762
|
+
const under = options.interceptOver ? this.load(options.interceptOver, { method: 'GET' }, controller.signal) : undefined;
|
|
474
763
|
under?.catch(() => { });
|
|
475
|
-
const result = await (prefetched ??
|
|
764
|
+
const result = await (prefetched ??
|
|
765
|
+
this.load(url, request, controller.signal, {
|
|
766
|
+
reuseSegments: options.reuseSegments,
|
|
767
|
+
onCookiesChanged: () => this.cookiesChanged(navigation),
|
|
768
|
+
redirected: options.redirected,
|
|
769
|
+
onRedirect,
|
|
770
|
+
}));
|
|
476
771
|
// Superseded by another navigation, or started over because cookies changed: then it ends with the new attempt.
|
|
477
772
|
if (controller.signal.aborted)
|
|
478
773
|
return navigation.restarted;
|
|
@@ -481,7 +776,7 @@ class Navigator {
|
|
|
481
776
|
if (request.method === 'POST' && !navigation.changedCookies)
|
|
482
777
|
this.prefetched.clear();
|
|
483
778
|
if ('hard' in result) {
|
|
484
|
-
this.hard(result.hard);
|
|
779
|
+
this.hard(result.hard, options.letThrough);
|
|
485
780
|
return;
|
|
486
781
|
}
|
|
487
782
|
if ('document' in result) {
|
|
@@ -496,8 +791,12 @@ class Navigator {
|
|
|
496
791
|
}
|
|
497
792
|
if ('failed' in result) {
|
|
498
793
|
// Keep the page, and what the user typed, as it is; useNavigation() tells the page.
|
|
499
|
-
console.error(
|
|
500
|
-
|
|
794
|
+
console.error(at.request.method === 'POST'
|
|
795
|
+
? `netjes: the form submission failed with status ${result.failed}`
|
|
796
|
+
: `netjes: loading ${at.url.pathname}${at.url.search} failed with status ${result.failed}, keeping the page`);
|
|
797
|
+
if (!this.keepPage(at.url, at.request, options))
|
|
798
|
+
return;
|
|
799
|
+
failure = this.failure(at.url, at.request, options, result.failed);
|
|
501
800
|
return;
|
|
502
801
|
}
|
|
503
802
|
const base = under ? await under.catch(() => null) : null;
|
|
@@ -510,34 +809,54 @@ class Navigator {
|
|
|
510
809
|
return navigation.restarted;
|
|
511
810
|
const previous = this.current.url;
|
|
512
811
|
const history = options.history === 'auto' ? (samePage(shown.url, previous) ? 'replace' : 'push') : options.history;
|
|
812
|
+
// Back or Forward: the entry's own values. Else the page's values go with it while it stays on screen (a refresh,
|
|
813
|
+
// another query or fragment), as its React state does; another page starts over. The values carried go on top.
|
|
814
|
+
const carries = history !== 'none' && pageKeyOf(shown) === pageKeyOf(this.current);
|
|
815
|
+
const values = history === 'none' ? (options.entryValues ?? NO_VALUES) : withCarried(carries ? this.values : NO_VALUES, options.historyState);
|
|
513
816
|
let key = options.key ?? createKey();
|
|
514
817
|
if (history === 'none') {
|
|
515
818
|
if (!options.key)
|
|
516
|
-
window.history.replaceState(
|
|
819
|
+
window.history.replaceState(entryState(key, this.index, values, window.history.state), '');
|
|
517
820
|
}
|
|
518
821
|
else {
|
|
519
822
|
this.rememberScroll();
|
|
520
823
|
key = createKey();
|
|
521
|
-
|
|
824
|
+
const kept = history === 'replace' ? window.history.state : null;
|
|
825
|
+
this.index = history === 'push' ? this.nextIndex() : this.index;
|
|
826
|
+
window.history[history === 'push' ? 'pushState' : 'replaceState'](entryState(key, this.index, values, kept), '', shown.url.href);
|
|
522
827
|
}
|
|
523
828
|
this.currentIsStale = navigation.stale;
|
|
524
|
-
this.setCurrent(key, shown);
|
|
829
|
+
this.setCurrent(key, shown, values, carries);
|
|
525
830
|
this.forgetToken();
|
|
526
831
|
committed = true;
|
|
527
832
|
const scroll = shown.base ? NONE : options.scroll === 'auto' ? (shown.url.pathname === previous.pathname ? NONE : TOP) : options.scroll;
|
|
528
|
-
this.deps.commit(shown, scroll, focusedAtStart);
|
|
833
|
+
this.deps.commit(shown, scroll, focusedAtStart, { lineage: this.lineage, values, restored: false });
|
|
529
834
|
}
|
|
530
835
|
catch (error) {
|
|
531
836
|
if (controller.signal.aborted)
|
|
532
837
|
return navigation.restarted;
|
|
533
|
-
if (request.method === 'POST') {
|
|
838
|
+
if (at.request.method === 'POST') {
|
|
534
839
|
// Never turn a failed submission into a GET: keep the page, and what the user typed, as it is.
|
|
535
840
|
console.error('netjes: the form could not be submitted', error);
|
|
536
|
-
failure =
|
|
841
|
+
failure = this.failure(at.url, at.request, options, null);
|
|
537
842
|
return;
|
|
538
843
|
}
|
|
844
|
+
// No answer while the browser is online: keep the page, unless the URL redirects somewhere fetch cannot follow.
|
|
845
|
+
// An offline browser loads the URL as a document, as any other failure does.
|
|
846
|
+
if (error instanceof NoAnswer && !offline()) {
|
|
847
|
+
const redirects = await answersWithRedirect(error, controller.signal);
|
|
848
|
+
if (controller.signal.aborted)
|
|
849
|
+
return navigation.restarted;
|
|
850
|
+
if (!redirects) {
|
|
851
|
+
console.error(`netjes: no answer for ${at.url.pathname}${at.url.search}, keeping the page`, error.cause);
|
|
852
|
+
if (!this.keepPage(at.url, at.request, options))
|
|
853
|
+
return;
|
|
854
|
+
failure = this.failure(at.url, at.request, options, null);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
539
858
|
console.error('netjes: navigation failed, loading the page from the server instead', error);
|
|
540
|
-
this.hard(url);
|
|
859
|
+
this.hard(at.url, options.letThrough);
|
|
541
860
|
}
|
|
542
861
|
finally {
|
|
543
862
|
if (this.active === navigation) {
|
|
@@ -547,19 +866,56 @@ class Navigator {
|
|
|
547
866
|
}
|
|
548
867
|
}
|
|
549
868
|
}
|
|
550
|
-
|
|
869
|
+
/**
|
|
870
|
+
* Keeps the page on screen after a navigation failed. Back or Forward has moved the browser to the entry it went to
|
|
871
|
+
* already: the router steps back to the entry of the page on screen, so the address is the page's again, and a
|
|
872
|
+
* page's history values and a refresh go to that entry. That is also where it steps back to when Back went from an
|
|
873
|
+
* entry whose page was still loading (the reader pressed Back again meanwhile): that page never came. Where it cannot
|
|
874
|
+
* tell either place (a step from or to an entry an app or a library added itself), it loads the URL as a document
|
|
875
|
+
* instead and returns false.
|
|
876
|
+
*/
|
|
877
|
+
keepPage(url, request, options) {
|
|
878
|
+
if (request.method !== 'GET' || options.history !== 'none')
|
|
879
|
+
return true;
|
|
880
|
+
const now = this.index;
|
|
881
|
+
const back = this.shownIndex;
|
|
882
|
+
if (now === undefined || back === undefined || now === back) {
|
|
883
|
+
this.hard(url, options.letThrough);
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
this.index = back;
|
|
887
|
+
// The step back is the router's own: once there, nothing more happens. Until then the browser is on the entry Back
|
|
888
|
+
// went to.
|
|
889
|
+
this.betweenEntries = true;
|
|
890
|
+
this.puttingBack = { index: back, ask: () => { } };
|
|
891
|
+
window.history.go(back - now);
|
|
892
|
+
return true;
|
|
893
|
+
}
|
|
894
|
+
/** What `useNavigation()` reports for a navigation that kept the page on screen. */
|
|
895
|
+
failure(url, request, options, status) {
|
|
896
|
+
const kind = request.method === 'POST' ? 'submit' : options.refresh ? 'refresh' : 'navigate';
|
|
897
|
+
return { kind, status, location: withoutBasePath(url.pathname, this.deps.basePath) + url.search };
|
|
898
|
+
}
|
|
899
|
+
async load(url, request, signal, options = {}) {
|
|
900
|
+
const { reuseSegments = false, onCookiesChanged = () => this.cookiesChanged() } = options;
|
|
551
901
|
let target = url;
|
|
552
902
|
let current = request;
|
|
903
|
+
let redirected = options.redirected ?? false;
|
|
553
904
|
// After a form post everything is loaded again: the post may have changed what any layout shows.
|
|
554
905
|
let keys = reuseSegments && request.method === 'GET' ? this.heldSegmentKeys() : [];
|
|
555
906
|
// Output-cached pages carry no token; a post from one needs a fetched one (as a header).
|
|
556
907
|
const token = request.method === 'POST' && !this.current.payload.antiforgery ? await this.fetchedToken() : undefined;
|
|
557
908
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
558
|
-
let payload = await fetchPayload(target, current, signal,
|
|
909
|
+
let payload = await fetchPayload(target, current, signal, {
|
|
910
|
+
segmentKeys: keys,
|
|
911
|
+
token: current.method === 'POST' ? token : undefined,
|
|
912
|
+
onCookiesChanged,
|
|
913
|
+
redirected,
|
|
914
|
+
});
|
|
559
915
|
if (payload !== null && 'kind' in payload && payload.kind === 'page' && keys.length > 0) {
|
|
560
916
|
const resolved = this.withReusedSegments(payload);
|
|
561
917
|
// The server reused a segment this page no longer has (it changed meanwhile): load it in full.
|
|
562
|
-
payload = resolved ?? (await fetchPayload(target, current, signal));
|
|
918
|
+
payload = resolved ?? (await fetchPayload(target, current, signal, { redirected }));
|
|
563
919
|
}
|
|
564
920
|
if (payload === null)
|
|
565
921
|
return { hard: target };
|
|
@@ -576,8 +932,13 @@ class Navigator {
|
|
|
576
932
|
if (current.method !== 'GET')
|
|
577
933
|
keys = [];
|
|
578
934
|
current = { method: 'GET' };
|
|
935
|
+
redirected = true;
|
|
936
|
+
options.onRedirect?.(target);
|
|
579
937
|
continue;
|
|
580
938
|
}
|
|
939
|
+
// A URL no page answers, such as a file: the browser loads it, and its endpoint runs once.
|
|
940
|
+
if (payload.kind === 'document')
|
|
941
|
+
return { hard: target };
|
|
581
942
|
const finalUrl = pageUrl(payload.url, target);
|
|
582
943
|
if (finalUrl.origin !== window.location.origin)
|
|
583
944
|
throw new Error(`netjes: the page payload names another origin (${finalUrl.origin})`);
|
|
@@ -627,7 +988,7 @@ class Navigator {
|
|
|
627
988
|
heldSegmentKeys() {
|
|
628
989
|
return this.current.payload.segments.flatMap((segment) => (segment.key && segment.props && !segment.reused ? [segment.key] : []));
|
|
629
990
|
}
|
|
630
|
-
/** Fills in the props of segments the server marked reused from the current page, or null if one is missing. */
|
|
991
|
+
/** Fills in the props and lang of segments the server marked reused from the current page, or null if one is missing. */
|
|
631
992
|
withReusedSegments(payload) {
|
|
632
993
|
if (!payload.segments.some((segment) => segment.reused))
|
|
633
994
|
return payload;
|
|
@@ -641,13 +1002,13 @@ class Navigator {
|
|
|
641
1002
|
const known = held.find((h) => h.id === segment.id && h.key === segment.key && h.props);
|
|
642
1003
|
if (!known)
|
|
643
1004
|
return null;
|
|
644
|
-
segments.push({ ...segment, props: known.props, reused: undefined });
|
|
1005
|
+
segments.push({ ...segment, props: known.props, lang: known.lang, reused: undefined });
|
|
645
1006
|
}
|
|
646
1007
|
return { ...payload, segments };
|
|
647
1008
|
}
|
|
648
|
-
hard(url) {
|
|
1009
|
+
hard(url, letThrough = false) {
|
|
649
1010
|
if (isWebUrl(url))
|
|
650
|
-
this.deps.hardNavigate(url.href);
|
|
1011
|
+
this.deps.hardNavigate(url.href, letThrough);
|
|
651
1012
|
else
|
|
652
1013
|
console.error(`netjes: refusing to navigate to ${url.protocol} URL`);
|
|
653
1014
|
}
|
|
@@ -666,11 +1027,27 @@ class Navigator {
|
|
|
666
1027
|
this.prefetched.delete(key);
|
|
667
1028
|
if (Date.now() - hit.at >= PREFETCH_TTL_MS)
|
|
668
1029
|
return undefined;
|
|
669
|
-
return hit.result.then((result) =>
|
|
1030
|
+
return hit.result.then((result) =>
|
|
1031
|
+
// A page that failed on the server is asked for again: it may answer now.
|
|
1032
|
+
'failed' in result
|
|
1033
|
+
? this.load(url, { method: 'GET' }, signal, { reuseSegments: true })
|
|
1034
|
+
: 'payload' in result
|
|
1035
|
+
? { ...result, url: samePage(result.url, url) ? withHash(result.url, url.hash) : result.url }
|
|
1036
|
+
: result, () => this.load(url, { method: 'GET' }, signal, { reuseSegments: true }));
|
|
670
1037
|
}
|
|
671
|
-
|
|
1038
|
+
/**
|
|
1039
|
+
* `carries`: the page on screen stays and its values went with it, so its setters keep writing. Every caller has set
|
|
1040
|
+
* `index` to the place of the entry `key` names.
|
|
1041
|
+
*/
|
|
1042
|
+
setCurrent(key, loaded, values, carries) {
|
|
672
1043
|
this.currentKey = key;
|
|
1044
|
+
this.shownIndex = this.index;
|
|
673
1045
|
this.current = loaded;
|
|
1046
|
+
this.href = loaded.url.href;
|
|
1047
|
+
this.values = values;
|
|
1048
|
+
if (!carries)
|
|
1049
|
+
this.lineage += 1;
|
|
1050
|
+
this.betweenEntries = false;
|
|
674
1051
|
if (!this.currentIsStale)
|
|
675
1052
|
this.remember(key, loaded);
|
|
676
1053
|
}
|
|
@@ -726,6 +1103,8 @@ function applyScroll(intent) {
|
|
|
726
1103
|
const RouterContext = createContext(null);
|
|
727
1104
|
const ViewContext = createContext(null);
|
|
728
1105
|
const NavigationContext = createContext(IDLE);
|
|
1106
|
+
const HistoryContext = createContext(null);
|
|
1107
|
+
const GuardsContext = createContext(null);
|
|
729
1108
|
function PassThrough({ children }) {
|
|
730
1109
|
return children;
|
|
731
1110
|
}
|
|
@@ -749,7 +1128,7 @@ function defaultDownload(file, name) {
|
|
|
749
1128
|
link.remove();
|
|
750
1129
|
setTimeout(() => URL.revokeObjectURL(href), 10_000);
|
|
751
1130
|
}
|
|
752
|
-
export function RouterProvider({ initial, initialModules, loader, errorPage, hardNavigate = defaultHardNavigate, showDocument = defaultShowDocument, download = defaultDownload, shell: Shell = PassThrough, }) {
|
|
1131
|
+
export function RouterProvider({ initial, initialModules, loader, errorPage, hardNavigate = defaultHardNavigate, showDocument = defaultShowDocument, download = defaultDownload, shell: Shell = PassThrough, documentLang, }) {
|
|
753
1132
|
const [view, setView] = useState(() => ({
|
|
754
1133
|
loaded: {
|
|
755
1134
|
payload: initial,
|
|
@@ -759,8 +1138,10 @@ export function RouterProvider({ initial, initialModules, loader, errorPage, har
|
|
|
759
1138
|
id: 0,
|
|
760
1139
|
scroll: NONE,
|
|
761
1140
|
focusedAtStart: null,
|
|
1141
|
+
restored: false,
|
|
762
1142
|
}));
|
|
763
1143
|
const [navigation, setNavigation] = useState(IDLE);
|
|
1144
|
+
const [guards] = useState(() => new NavigationGuards());
|
|
764
1145
|
const [navigator] = useState(() => {
|
|
765
1146
|
// Server actions called before the effect below registers this router wait for it (the server runs no effects).
|
|
766
1147
|
if (typeof document !== 'undefined')
|
|
@@ -769,16 +1150,37 @@ export function RouterProvider({ initial, initialModules, loader, errorPage, har
|
|
|
769
1150
|
loader,
|
|
770
1151
|
version: initial.version,
|
|
771
1152
|
basePath: initial.basePath ?? '',
|
|
772
|
-
hardNavigate,
|
|
1153
|
+
hardNavigate: (href, letThrough) => {
|
|
1154
|
+
if (letThrough)
|
|
1155
|
+
guards.letUnloadThrough();
|
|
1156
|
+
hardNavigate(href);
|
|
1157
|
+
},
|
|
773
1158
|
showDocument,
|
|
774
1159
|
download,
|
|
775
1160
|
setPending: setNavigation,
|
|
776
|
-
commit: (loaded, scroll, focusedAtStart) => startTransition(() => {
|
|
777
|
-
setView((previous) => ({ loaded, id: previous.id + 1, scroll, focusedAtStart }));
|
|
1161
|
+
commit: (loaded, scroll, focusedAtStart, { lineage, values, restored }) => startTransition(() => {
|
|
1162
|
+
setView((previous) => ({ loaded, id: previous.id + 1, scroll, focusedAtStart, restored }));
|
|
778
1163
|
setNavigation(IDLE);
|
|
1164
|
+
// In the same transition as the page: the page that leaves never renders with the next entry's values.
|
|
1165
|
+
setEntry({ lineage, values });
|
|
779
1166
|
}),
|
|
1167
|
+
setEntry: (entry) => setEntry(entry),
|
|
1168
|
+
guards,
|
|
780
1169
|
}, view.loaded);
|
|
781
1170
|
});
|
|
1171
|
+
// Every value as its initial one until the router has started, as on the server, so hydration matches.
|
|
1172
|
+
const [entry, setEntry] = useState(() => ({ lineage: navigator.entryLineage, values: NO_VALUES }));
|
|
1173
|
+
const [restoreListeners] = useState(() => new Set());
|
|
1174
|
+
const [historyWriters] = useState(() => ({
|
|
1175
|
+
set: (lineage, name, compute) => navigator.setValue(lineage, name, compute),
|
|
1176
|
+
onRestore: (listener) => {
|
|
1177
|
+
restoreListeners.add(listener);
|
|
1178
|
+
return () => {
|
|
1179
|
+
restoreListeners.delete(listener);
|
|
1180
|
+
};
|
|
1181
|
+
},
|
|
1182
|
+
}));
|
|
1183
|
+
const history = useMemo(() => ({ ...entry, ...historyWriters }), [entry, historyWriters]);
|
|
782
1184
|
// In the commit that shows the page, before the browser dispatches the clicks that came in while React hydrated it:
|
|
783
1185
|
// a fragment link followed then must find this history entry keyed, to come back to.
|
|
784
1186
|
useLayoutEffect(() => navigator.start(), [navigator]);
|
|
@@ -817,7 +1219,7 @@ export function RouterProvider({ initial, initialModules, loader, errorPage, har
|
|
|
817
1219
|
// page they left (refresh, which would also cancel their navigation).
|
|
818
1220
|
const movedOn = navigator.page !== page || navigator.navigating;
|
|
819
1221
|
if (!movedOn && response.redirect)
|
|
820
|
-
await navigator.navigate(response.redirect, 'push', true);
|
|
1222
|
+
await navigator.navigate(response.redirect, 'push', { redirected: true });
|
|
821
1223
|
else if (!movedOn && response.revalidate)
|
|
822
1224
|
await navigator.refresh();
|
|
823
1225
|
// After signing in or out (an action that set or deleted a cookie), the page on screen shows whoever was
|
|
@@ -841,6 +1243,22 @@ export function RouterProvider({ initial, initialModules, loader, errorPage, har
|
|
|
841
1243
|
html.setAttribute(HYDRATED_ATTRIBUTE, '');
|
|
842
1244
|
return () => html.removeAttribute(HYDRATED_ATTRIBUTE);
|
|
843
1245
|
}, []);
|
|
1246
|
+
// After the effects of the page that Back or Forward put back, which subscribe as it mounts: a parent's effects run
|
|
1247
|
+
// after its children's.
|
|
1248
|
+
useEffect(() => {
|
|
1249
|
+
if (view.restored)
|
|
1250
|
+
for (const listener of [...restoreListeners])
|
|
1251
|
+
listener();
|
|
1252
|
+
}, [view, restoreListeners]);
|
|
1253
|
+
useEffect(() => {
|
|
1254
|
+
const onPageShow = (event) => {
|
|
1255
|
+
if (event.persisted)
|
|
1256
|
+
for (const listener of [...restoreListeners])
|
|
1257
|
+
listener();
|
|
1258
|
+
};
|
|
1259
|
+
window.addEventListener('pageshow', onPageShow);
|
|
1260
|
+
return () => window.removeEventListener('pageshow', onPageShow);
|
|
1261
|
+
}, [restoreListeners]);
|
|
844
1262
|
// The key of the page on screen before this commit.
|
|
845
1263
|
const committedPageKey = useRef(pageKeyOf(view.loaded));
|
|
846
1264
|
// In the commit that shows the page, before the browser paints it, and after the layout effects of the page and its
|
|
@@ -855,23 +1273,61 @@ export function RouterProvider({ initial, initialModules, loader, errorPage, har
|
|
|
855
1273
|
committedPageKey.current = key;
|
|
856
1274
|
moveFocusAfterNavigation({ target, replaced, keep: view.scroll.kind === 'none', focusedAtStart: view.focusedAtStart });
|
|
857
1275
|
}, [view]);
|
|
858
|
-
const router = useMemo(() =>
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
1276
|
+
const router = useMemo(() => {
|
|
1277
|
+
/**
|
|
1278
|
+
* A push or replace, asked of the guards that hold first. What had the focus and what the entry carries are read as
|
|
1279
|
+
* it is called, as without a guard: a value the browser cannot copy rejects it before any guard is asked.
|
|
1280
|
+
*/
|
|
1281
|
+
const guarded = (href, history, options = {}) => {
|
|
1282
|
+
const focusedAtStart = options.focusedAtStart === undefined ? document.activeElement : options.focusedAtStart;
|
|
1283
|
+
const to = navigator.heldTarget(href);
|
|
1284
|
+
if (to === null)
|
|
1285
|
+
return navigator.navigate(href, history, { ...options, focusedAtStart });
|
|
1286
|
+
// No guard holds: it goes at once, and takes the place of an attempt still waiting for its answer, as after a save.
|
|
1287
|
+
if (!guards.holding)
|
|
1288
|
+
return guards.attempt(to, history, () => navigator.navigate(href, history, { ...options, focusedAtStart }));
|
|
1289
|
+
let historyState;
|
|
1290
|
+
try {
|
|
1291
|
+
historyState = options.historyState === undefined ? undefined : structuredClone(options.historyState);
|
|
1292
|
+
}
|
|
1293
|
+
catch (error) {
|
|
1294
|
+
return Promise.reject(error);
|
|
1295
|
+
}
|
|
1296
|
+
return guards.attempt(to, history, () => navigator.navigate(href, history, { ...options, focusedAtStart, historyState, letThrough: true }));
|
|
1297
|
+
};
|
|
1298
|
+
return {
|
|
1299
|
+
push: (href, options) => guarded(href, 'push', options),
|
|
1300
|
+
replace: (href, options) => guarded(href, 'replace', options),
|
|
1301
|
+
prefetch: (href) => navigator.prefetch(href),
|
|
1302
|
+
refresh: () => navigator.refresh(),
|
|
1303
|
+
back: () => window.history.back(),
|
|
1304
|
+
forward: () => window.history.forward(),
|
|
1305
|
+
submit: (action, body, options) => navigator.submit(action, body, options?.focusedAtStart),
|
|
1306
|
+
onActionResponse: (listener) => {
|
|
1307
|
+
actionListeners.add(listener);
|
|
1308
|
+
return () => actionListeners.delete(listener);
|
|
1309
|
+
},
|
|
1310
|
+
onCookiesChanged: (listener) => navigator.onCookiesChanged(listener),
|
|
1311
|
+
};
|
|
1312
|
+
}, [navigator, actionListeners, guards]);
|
|
1313
|
+
const { payload, url } = view.loaded;
|
|
873
1314
|
const viewValue = useMemo(() => ({ payload, url }), [payload, url]);
|
|
874
|
-
|
|
1315
|
+
// <html lang> for the page on screen. The server wrote the first page's, and Document keeps it as written, so the
|
|
1316
|
+
// attribute changes only when the lang does: an app that sets it itself keeps its value until then (a page whose
|
|
1317
|
+
// loader gives a lang, or another locale), and a page without one after that has the root's. In the commit that
|
|
1318
|
+
// shows the page, before it is painted.
|
|
1319
|
+
const lang = documentLang === undefined ? undefined : langOf(payload, documentLang);
|
|
1320
|
+
const shownLang = useRef(lang);
|
|
1321
|
+
useLayoutEffect(() => {
|
|
1322
|
+
if (lang === undefined || lang === shownLang.current)
|
|
1323
|
+
return;
|
|
1324
|
+
shownLang.current = lang;
|
|
1325
|
+
document.documentElement.lang = lang;
|
|
1326
|
+
}, [lang]);
|
|
1327
|
+
// The same element until another page is shown: a change of the router's state alone (a navigation on its way, a
|
|
1328
|
+
// value of the history entry) re-renders only the components that read it.
|
|
1329
|
+
const page = useMemo(() => (_jsx(Shell, { children: _jsx(ErrorBoundary, { resetKey: view.id, fallback: (error) => _jsx(ErrorFallback, { error: error, errorPage: errorPage, loader: loader, payload: view.loaded.payload }), children: _jsx(RouteTree, { modules: view.loaded.modules, segments: view.loaded.payload.segments, props: view.loaded.payload.props, params: view.loaded.payload.params, status: view.loaded.payload.status, pageKind: view.loaded.payload.pageKind, pageKey: pageKeyOf(view.loaded), retry: () => void router.refresh(), metadata: view.loaded.payload.metadata }) }) })), [Shell, view, errorPage, loader, router]);
|
|
1330
|
+
return (_jsx(RouterContext, { value: router, children: _jsx(GuardsContext, { value: guards, children: _jsx(ViewContext, { value: viewValue, children: _jsxs(NavigationContext, { value: navigation, children: [_jsx(HistoryContext, { value: history, children: page }), _jsx(RouteAnnouncer, { location: url.pathname + url.search, path: withoutBasePath(url.pathname, payload.basePath ?? '') })] }) }) }) }));
|
|
875
1331
|
}
|
|
876
1332
|
const errorPageModules = new WeakMap();
|
|
877
1333
|
/**
|
|
@@ -895,9 +1351,9 @@ function LoadedErrorPage({ modules, props, error, payload, }) {
|
|
|
895
1351
|
return _jsx(RouteTree, { modules: use(modules), props: props, params: payload.params, status: 500, pageKind: "error", pageKey: "error", error: error });
|
|
896
1352
|
}
|
|
897
1353
|
/** The router's contexts without the router: for the test harness (netjes/testing), which fakes navigation. */
|
|
898
|
-
export function RouterContexts({ router, payload, url, navigation, children, }) {
|
|
1354
|
+
export function RouterContexts({ router, payload, url, navigation, history, guards, children, }) {
|
|
899
1355
|
const view = useMemo(() => ({ payload, url }), [payload, url]);
|
|
900
|
-
return (_jsx(RouterContext, { value: router, children: _jsx(ViewContext, { value: view, children: _jsx(NavigationContext, { value: navigation, children: children }) }) }));
|
|
1356
|
+
return (_jsx(RouterContext, { value: router, children: _jsx(GuardsContext, { value: guards, children: _jsx(ViewContext, { value: view, children: _jsx(NavigationContext, { value: navigation, children: _jsx(HistoryContext, { value: history, children: children }) }) }) }) }));
|
|
901
1357
|
}
|
|
902
1358
|
function useView() {
|
|
903
1359
|
const view = useContext(ViewContext);
|
|
@@ -976,8 +1432,74 @@ export function useSelectedLayoutSegment() {
|
|
|
976
1432
|
export function usePagePayload() {
|
|
977
1433
|
return useView().payload;
|
|
978
1434
|
}
|
|
979
|
-
/**
|
|
1435
|
+
/**
|
|
1436
|
+
* The router's state: `loading` during a navigation or a refresh, `submitting` during a form post, else `idle`, with
|
|
1437
|
+
* `error` after a navigation, a refresh or a form post that kept the page because it got no page (its `kind` says
|
|
1438
|
+
* which), until the next one starts.
|
|
1439
|
+
*/
|
|
980
1440
|
export function useNavigation() {
|
|
981
1441
|
return useContext(NavigationContext);
|
|
982
1442
|
}
|
|
1443
|
+
const NOT_SET = Symbol('not set');
|
|
1444
|
+
function useHistory() {
|
|
1445
|
+
const history = useContext(HistoryContext);
|
|
1446
|
+
if (!history)
|
|
1447
|
+
throw new Error('netjes: this hook must be used inside a Netjes page');
|
|
1448
|
+
return history;
|
|
1449
|
+
}
|
|
1450
|
+
export function useHistoryState(name, initial, schema) {
|
|
1451
|
+
const { lineage, values, set } = useHistory();
|
|
1452
|
+
// The first render's, as useState keeps its initial value: an array written inline is not a new value each render.
|
|
1453
|
+
const [fallback] = useState(() => initial);
|
|
1454
|
+
const resolve = useCallback((entry) => {
|
|
1455
|
+
if (!Object.hasOwn(entry, name))
|
|
1456
|
+
return fallback;
|
|
1457
|
+
return schema ? parseOr(schema, entry[name], fallback, `history state '${name}'`) : entry[name];
|
|
1458
|
+
}, [name, schema, fallback]);
|
|
1459
|
+
const stored = Object.hasOwn(values, name) ? values[name] : NOT_SET;
|
|
1460
|
+
// Parsed again only when the entry's value changes, not when another name's does.
|
|
1461
|
+
const value = useMemo(() => (stored === NOT_SET ? fallback : resolve({ [name]: stored })), [resolve, name, stored, fallback]);
|
|
1462
|
+
// Bound to the page's lineage, not to one entry: like a useState setter, it keeps working, and stays the same
|
|
1463
|
+
// function, through a navigation that keeps the page on screen with its values (a refresh, another query).
|
|
1464
|
+
const setValue = useCallback((next) => set(lineage, name, (current) => (typeof next === 'function' ? next(resolve(current)) : next)), [set, lineage, name, resolve]);
|
|
1465
|
+
return [value, setValue];
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Calls `callback` each time the page on screen was shown from memory after Back or Forward: a page the router kept
|
|
1469
|
+
* (it asks the server nothing), or the whole document the browser kept in its back-forward cache. What the page shows
|
|
1470
|
+
* 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
|
|
1471
|
+
* router loads from the server, and Back over a fragment link of the page on screen, do not call it.
|
|
1472
|
+
*/
|
|
1473
|
+
export function useHistoryRestore(callback) {
|
|
1474
|
+
const { onRestore } = useHistory();
|
|
1475
|
+
const latest = useRef(callback);
|
|
1476
|
+
useEffect(() => {
|
|
1477
|
+
latest.current = callback;
|
|
1478
|
+
});
|
|
1479
|
+
useEffect(() => onRestore(() => latest.current()), [onRestore]);
|
|
1480
|
+
}
|
|
1481
|
+
/**
|
|
1482
|
+
* Holds every client navigation while `when` is true, and asks `onAttempt` first: links, `<Form method="get">`,
|
|
1483
|
+
* `router.push`, `router.replace`, `router.back`, `router.forward` and the browser's Back and Forward. The navigation
|
|
1484
|
+
* waits until the attempt's `proceed()` lets it go on, or its `stay()` keeps the page; for Back and Forward the router
|
|
1485
|
+
* puts the entry back first, so the address bar shows the page on screen while the question is open. `proceed()` works
|
|
1486
|
+
* whenever it is called, also once `when` is false (after a save), and a navigation that comes while one waits takes its
|
|
1487
|
+
* place. While it holds, `beforeunload` has the browser ask before the document unloads: a reload, closing the tab, a
|
|
1488
|
+
* 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
|
|
1489
|
+
* form post, a server action or `router.refresh()`, nor the page the server's redirect in their answer leads to (the
|
|
1490
|
+
* sign-in page after the session expired). With several guards holding, each is asked in turn, the one that
|
|
1491
|
+
* started to hold last first, and the first `stay()` ends it. `onAttempt` is the latest render's. Throws outside a
|
|
1492
|
+
* Netjes page.
|
|
1493
|
+
*/
|
|
1494
|
+
export function useNavigationGuard(options) {
|
|
1495
|
+
const guards = useContext(GuardsContext);
|
|
1496
|
+
if (!guards)
|
|
1497
|
+
throw new Error('netjes: this hook must be used inside a Netjes page');
|
|
1498
|
+
const latest = useRef(options);
|
|
1499
|
+
useEffect(() => {
|
|
1500
|
+
latest.current = options;
|
|
1501
|
+
});
|
|
1502
|
+
const { when } = options;
|
|
1503
|
+
useEffect(() => (when ? guards.register(() => latest.current) : undefined), [guards, when]);
|
|
1504
|
+
}
|
|
983
1505
|
//# sourceMappingURL=router.js.map
|