fondu 0.12.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/client/app.d.ts +36 -8
- package/dist/client/app.js +65 -41
- package/dist/client/form.d.ts +3 -1
- package/dist/client/form.js +11 -7
- package/dist/client/navigation.d.ts +4 -1
- package/dist/client/navigation.js +173 -29
- package/dist/client.d.ts +12 -8
- package/dist/client.js +7 -1
- package/dist/form.d.ts +2 -2
- package/dist/form.js +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/paths.d.ts +13 -2
- package/dist/paths.js +18 -7
- package/dist/server/app.d.ts +7 -3
- package/dist/server/app.js +38 -27
- package/dist/server/document.d.ts +10 -2
- package/dist/server/document.js +71 -19
- package/dist/server/errors.d.ts +0 -2
- package/dist/server/errors.js +4 -3
- package/dist/server/flash.d.ts +0 -2
- package/dist/server/flash.js +1 -1
- package/dist/server/http.d.ts +4 -0
- package/dist/server/http.js +5 -0
- package/dist/server/prerender.js +7 -49
- package/dist/server/protocol.d.ts +16 -2
- package/dist/server/protocol.js +95 -15
- package/dist/server/routes.d.ts +4 -1
- package/dist/server/routes.js +9 -1
- package/dist/server/static.d.ts +14 -0
- package/dist/server/static.js +37 -0
- package/dist/server/validate.d.ts +2 -6
- package/dist/virtual.d.ts +5 -1
- package/dist/vite/index.d.ts +4 -1
- package/dist/vite/index.js +33 -25
- package/dist/vite/prerender.d.ts +12 -9
- package/dist/vite/prerender.js +17 -13
- package/dist/vite/strip.d.ts +1 -3
- package/dist/vite/strip.js +3 -15
- package/dist/vite/typegen.d.ts +0 -6
- package/dist/vite/typegen.js +3 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,7 +19,7 @@ bun dev
|
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cloudflare|node`) and whether to add
|
|
22
|
-
code checks (oxfmt, oxlint
|
|
22
|
+
code checks (oxfmt, oxlint; or `--checks`), and writes a small app: a route, its page, the
|
|
23
23
|
error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents. `--yes` asks nothing more.
|
|
24
24
|
|
|
25
25
|
[demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo)) shows Fondu's features, one page each,
|
package/dist/client/app.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type ReactElement } from 'react';
|
|
1
|
+
import { type ReactElement, type ReactNode } from 'react';
|
|
2
2
|
import type { Flash, Shared } from '../types.js';
|
|
3
3
|
import { type Page } from './navigation.js';
|
|
4
4
|
import { type ProgressOptions } from './progress.js';
|
|
@@ -30,12 +30,22 @@ export type Navigation = {
|
|
|
30
30
|
to: string;
|
|
31
31
|
/** the form being sent (a GET form's too), else null */
|
|
32
32
|
form: HTMLFormElement | null;
|
|
33
|
+
} | {
|
|
34
|
+
/** a form's POST that could not be sent, or whose answer could not be read: the form stays, to send again */
|
|
35
|
+
state: 'failed';
|
|
36
|
+
to: string;
|
|
37
|
+
form: HTMLFormElement | null;
|
|
33
38
|
};
|
|
34
|
-
/**
|
|
35
|
-
export
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
+
/** what `react-dom/server`'s `renderToReadableStream` gives: the bytes of the HTML, and when all of it is rendered */
|
|
40
|
+
export type Rendered = ReadableStream<Uint8Array> & {
|
|
41
|
+
allReady: Promise<void>;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
|
|
45
|
+
* `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
|
|
46
|
+
* Suspense boundaries that were not ready add. Rejects if the shell fails to render.
|
|
47
|
+
*/
|
|
48
|
+
export declare function renderPage(page: Page, render: (element: ReactElement) => Promise<Rendered>, after?: ReactElement): Promise<Rendered>;
|
|
39
49
|
/** a form's field errors, as a page gets them (its `errors` prop): field name → message */
|
|
40
50
|
export type Errors = Record<string, string>;
|
|
41
51
|
/** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
|
|
@@ -50,8 +60,26 @@ export declare function usePage<P = Shared>(): {
|
|
|
50
60
|
/**
|
|
51
61
|
* The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
|
|
52
62
|
* from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
|
|
63
|
+
* `failed` is a form's POST that could not be sent, or whose answer could not be read (offline): the form stays, to
|
|
64
|
+
* send again, and the state lasts until the next navigation starts. A GET that fails is loaded as a document instead,
|
|
65
|
+
* where the browser says what is wrong.
|
|
53
66
|
*/
|
|
54
67
|
export declare function useNavigation(): Navigation;
|
|
55
|
-
/**
|
|
56
|
-
|
|
68
|
+
/**
|
|
69
|
+
* This page's props asked for again: the page keeps its state and the scroll position. `only`: those props alone,
|
|
70
|
+
* deferred or not, quietly (no navigation state)
|
|
71
|
+
*/
|
|
72
|
+
export declare function reload(options?: {
|
|
73
|
+
only?: string[];
|
|
74
|
+
}): void;
|
|
75
|
+
/**
|
|
76
|
+
* Children once the page has the props named by `data`; `fallback` while they are asked for; `failed` (default:
|
|
77
|
+
* `fallback`) once they were asked for and are not there (the request failed, or the loader's function threw)
|
|
78
|
+
*/
|
|
79
|
+
export declare function Deferred({ data, fallback, failed, children, }: {
|
|
80
|
+
data: string | string[];
|
|
81
|
+
fallback?: ReactNode;
|
|
82
|
+
failed?: ReactNode;
|
|
83
|
+
children?: ReactNode;
|
|
84
|
+
}): ReactNode;
|
|
57
85
|
export {};
|
package/dist/client/app.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Component, createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
|
|
1
|
+
import { Component, createContext, createElement, Fragment, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
|
|
2
2
|
import { flushSync } from 'react-dom';
|
|
3
3
|
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
4
|
-
import { layoutsOf, pageId, routePatterns } from '../paths.js';
|
|
4
|
+
import { decoded, layoutsOf, pageId, routePatterns } from '../paths.js';
|
|
5
5
|
import { again, startNavigation } from './navigation.js';
|
|
6
6
|
import { progressBar } from './progress.js';
|
|
7
7
|
const ROUTES = '/app/routes/';
|
|
@@ -9,6 +9,8 @@ const ERROR = '_error';
|
|
|
9
9
|
// set by the app's entry (the Vite plugin's): the pages and layouts of app/routes/, and the build's settings
|
|
10
10
|
let pages = new Map();
|
|
11
11
|
let layoutModules = {};
|
|
12
|
+
/** each page's URL patterns, segment by segment: for `pageAt` */
|
|
13
|
+
let patterns = [];
|
|
12
14
|
/**
|
|
13
15
|
* @internal the app's entry (the Vite plugin writes it), in the browser and for the server render: `import.meta.glob`
|
|
14
16
|
* of the pages and layouts of `app/routes/`, and `fondu({ prerender, progress })`. In the browser it starts the app:
|
|
@@ -17,6 +19,9 @@ let layoutModules = {};
|
|
|
17
19
|
export function __entry(pageModules, layouts, settings) {
|
|
18
20
|
pages = new Map(Object.entries(pageModules).map(([key, loader]) => [pageId(key.slice(ROUTES.length)), loader]));
|
|
19
21
|
layoutModules = layouts;
|
|
22
|
+
patterns = [...pages.keys()]
|
|
23
|
+
.filter((id) => !id.split('/').some((s) => s.startsWith('_'))) // the error page is no URL
|
|
24
|
+
.flatMap((id) => routePatterns(id).map((p) => ({ id, segments: p.split('/').filter(Boolean) })));
|
|
20
25
|
if (typeof document !== 'undefined')
|
|
21
26
|
start(settings);
|
|
22
27
|
}
|
|
@@ -27,10 +32,8 @@ async function load(component) {
|
|
|
27
32
|
if (!page)
|
|
28
33
|
throw new Error(`fondu: there is no page "${component}" in app/routes/`);
|
|
29
34
|
const chain = layoutsOf(component)
|
|
30
|
-
.map((dir) =>
|
|
31
|
-
.
|
|
32
|
-
.find((k) => k in layoutModules))
|
|
33
|
-
.filter((k) => k !== undefined);
|
|
35
|
+
.map((dir) => `${ROUTES}${dir ? `${dir}/` : ''}_layout.tsx`)
|
|
36
|
+
.filter((k) => k in layoutModules);
|
|
34
37
|
const [Component, ...layouts] = await Promise.all([
|
|
35
38
|
defaultOf(page),
|
|
36
39
|
...chain.map((k) => defaultOf(layoutModules[k])),
|
|
@@ -74,32 +77,28 @@ class Failed extends Component {
|
|
|
74
77
|
* listed values are the server's), so the page shown is the one the server says.
|
|
75
78
|
*/
|
|
76
79
|
export function pageAt(pathname) {
|
|
77
|
-
|
|
80
|
+
// decoded, as the server matches them (`/caf%C3%A9` is `café.tsx`)
|
|
81
|
+
const parts = pathname.split('/').filter(Boolean).map(decoded);
|
|
78
82
|
let best;
|
|
79
|
-
for (const id of
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
for (const
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
score += s === part ? 3 : -Infinity;
|
|
96
|
-
i = s.endsWith('{.+}') ? parts.length : i + 1;
|
|
97
|
-
if (score < 0)
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
if (score >= 0 && i === parts.length && (!best || score > best.score))
|
|
101
|
-
best = { id, score };
|
|
83
|
+
for (const { id, segments } of patterns) {
|
|
84
|
+
let score = 0;
|
|
85
|
+
let i = 0;
|
|
86
|
+
for (const s of segments) {
|
|
87
|
+
const part = parts[i];
|
|
88
|
+
if (part === undefined)
|
|
89
|
+
score = -1;
|
|
90
|
+
else if (s.endsWith('{.+}'))
|
|
91
|
+
score += 1; // a catch-all: the rest
|
|
92
|
+
else if (s.startsWith(':'))
|
|
93
|
+
score += 2;
|
|
94
|
+
else
|
|
95
|
+
score += s === part ? 3 : -Infinity;
|
|
96
|
+
i = s.endsWith('{.+}') ? parts.length : i + 1;
|
|
97
|
+
if (score < 0)
|
|
98
|
+
break;
|
|
102
99
|
}
|
|
100
|
+
if (score >= 0 && i === parts.length && (!best || score > best.score))
|
|
101
|
+
best = { id, score };
|
|
103
102
|
}
|
|
104
103
|
return best?.id;
|
|
105
104
|
}
|
|
@@ -112,7 +111,11 @@ const subscribe = (listener) => {
|
|
|
112
111
|
};
|
|
113
112
|
function setNavigation(next) {
|
|
114
113
|
navigation = next
|
|
115
|
-
? {
|
|
114
|
+
? {
|
|
115
|
+
state: next.failed ? 'failed' : next.post ? 'submitting' : 'loading',
|
|
116
|
+
to: next.to,
|
|
117
|
+
form: next.form,
|
|
118
|
+
}
|
|
116
119
|
: IDLE;
|
|
117
120
|
for (const l of listeners)
|
|
118
121
|
l();
|
|
@@ -122,7 +125,8 @@ function setNavigation(next) {
|
|
|
122
125
|
function start(settings) {
|
|
123
126
|
const progress = settings.progress;
|
|
124
127
|
if (progress)
|
|
125
|
-
subscribe(progressBar(progress, () => navigation.state
|
|
128
|
+
subscribe(progressBar(progress, () => (navigation.state === 'loading' || navigation.state === 'submitting') &&
|
|
129
|
+
(progress.forms !== false || navigation.form === null)));
|
|
126
130
|
const data = document.querySelector('script[data-page="app"]')?.textContent;
|
|
127
131
|
const root = document.getElementById('app');
|
|
128
132
|
if (!data || !root)
|
|
@@ -164,13 +168,14 @@ function start(settings) {
|
|
|
164
168
|
createRoot(root).render(app);
|
|
165
169
|
});
|
|
166
170
|
}
|
|
167
|
-
/**
|
|
168
|
-
|
|
171
|
+
/**
|
|
172
|
+
* @internal the server render of a page, streamed: the tags its components hoist (`<title>`…) first, then
|
|
173
|
+
* `<div id="app">`, then `after` (markup of the document's, in the shell: right after the page), then what the
|
|
174
|
+
* Suspense boundaries that were not ready add. Rejects if the shell fails to render.
|
|
175
|
+
*/
|
|
176
|
+
export async function renderPage(page, render, after) {
|
|
169
177
|
const view = await load(page.component);
|
|
170
|
-
|
|
171
|
-
// React puts the tags it hoists (`<title>`, `<meta>`, `<link>`) before the root's markup
|
|
172
|
-
const at = html.indexOf('<div id="app"');
|
|
173
|
-
return { head: html.slice(0, at), body: html.slice(at) };
|
|
178
|
+
return render(createElement(Fragment, null, createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })), after));
|
|
174
179
|
}
|
|
175
180
|
/** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
|
|
176
181
|
export function usePage() {
|
|
@@ -182,11 +187,30 @@ export function usePage() {
|
|
|
182
187
|
/**
|
|
183
188
|
* The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
|
|
184
189
|
* from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
|
|
190
|
+
* `failed` is a form's POST that could not be sent, or whose answer could not be read (offline): the form stays, to
|
|
191
|
+
* send again, and the state lasts until the next navigation starts. A GET that fails is loaded as a document instead,
|
|
192
|
+
* where the browser says what is wrong.
|
|
185
193
|
*/
|
|
186
194
|
export function useNavigation() {
|
|
187
195
|
return useSyncExternalStore(subscribe, () => navigation, () => IDLE);
|
|
188
196
|
}
|
|
189
|
-
/**
|
|
190
|
-
|
|
191
|
-
|
|
197
|
+
/**
|
|
198
|
+
* This page's props asked for again: the page keeps its state and the scroll position. `only`: those props alone,
|
|
199
|
+
* deferred or not, quietly (no navigation state)
|
|
200
|
+
*/
|
|
201
|
+
export function reload(options = {}) {
|
|
202
|
+
again(options.only);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Children once the page has the props named by `data`; `fallback` while they are asked for; `failed` (default:
|
|
206
|
+
* `fallback`) once they were asked for and are not there (the request failed, or the loader's function threw)
|
|
207
|
+
*/
|
|
208
|
+
export function Deferred({ data, fallback = null, failed = fallback, children, }) {
|
|
209
|
+
const page = useContext(PageContext);
|
|
210
|
+
if (!page)
|
|
211
|
+
throw new Error('fondu: <Deferred> is for components of a page');
|
|
212
|
+
const names = [data].flat();
|
|
213
|
+
if (names.every((name) => name in page.props))
|
|
214
|
+
return children;
|
|
215
|
+
return names.some((name) => page.deferred?.includes(name)) ? fallback : failed;
|
|
192
216
|
}
|
package/dist/client/form.d.ts
CHANGED
|
@@ -22,8 +22,9 @@ type StandardResult = {
|
|
|
22
22
|
* - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
|
|
23
23
|
* by the server's keys (`email`, `user.name`)
|
|
24
24
|
* - `submitting`: this form is being sent
|
|
25
|
+
* - `failed`: this form could not be sent (offline…): it stays, to send again
|
|
25
26
|
*
|
|
26
|
-
* Without a schema: the server's errors and `
|
|
27
|
+
* Without a schema: the server's errors, `submitting` and `failed` only. Without JavaScript, the form is sent as it is, and the
|
|
27
28
|
* server's check answers.
|
|
28
29
|
*/
|
|
29
30
|
export declare function useForm(schema?: Schema): {
|
|
@@ -39,5 +40,6 @@ export declare function useForm(schema?: Schema): {
|
|
|
39
40
|
};
|
|
40
41
|
errors: Errors;
|
|
41
42
|
submitting: boolean;
|
|
43
|
+
failed: boolean;
|
|
42
44
|
};
|
|
43
45
|
export {};
|
package/dist/client/form.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react';
|
|
2
|
-
import { fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
|
|
2
|
+
import { crlf, fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
|
|
3
3
|
import { useNavigation, usePage } from './app.js';
|
|
4
4
|
/** a form's fields as the server reads them: its body for a POST (`withValidator({ body })`), its query for a GET */
|
|
5
5
|
function fieldsOf(form, submitter) {
|
|
6
6
|
const data = new FormData(form, submitter ?? undefined);
|
|
7
|
-
// as the browser sends them: line breaks as CRLF (a <textarea>'s)
|
|
8
|
-
const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
9
7
|
const entries = [...data].map(([k, v]) => [crlf(k), typeof v === 'string' ? crlf(v) : v]);
|
|
10
8
|
const method = (submitter?.getAttribute('formmethod') ??
|
|
11
9
|
form.getAttribute('method') ??
|
|
@@ -47,8 +45,9 @@ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.st
|
|
|
47
45
|
* - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
|
|
48
46
|
* by the server's keys (`email`, `user.name`)
|
|
49
47
|
* - `submitting`: this form is being sent
|
|
48
|
+
* - `failed`: this form could not be sent (offline…): it stays, to send again
|
|
50
49
|
*
|
|
51
|
-
* Without a schema: the server's errors and `
|
|
50
|
+
* Without a schema: the server's errors, `submitting` and `failed` only. Without JavaScript, the form is sent as it is, and the
|
|
52
51
|
* server's check answers.
|
|
53
52
|
*/
|
|
54
53
|
export function useForm(schema) {
|
|
@@ -113,8 +112,10 @@ export function useForm(schema) {
|
|
|
113
112
|
if (form && validates)
|
|
114
113
|
form.noValidate = true;
|
|
115
114
|
}, [validates]);
|
|
116
|
-
const
|
|
117
|
-
|
|
115
|
+
const mine = navigation.form !== null && navigation.form === element;
|
|
116
|
+
const submitting = mine && navigation.state !== 'failed';
|
|
117
|
+
const failed = mine && navigation.state === 'failed';
|
|
118
|
+
// back with the server's errors: the first field to fix gets the focus (not for a form that was not sent: no answer)
|
|
118
119
|
const sent = useRef(false);
|
|
119
120
|
useEffect(() => {
|
|
120
121
|
if (submitting) {
|
|
@@ -124,9 +125,11 @@ export function useForm(schema) {
|
|
|
124
125
|
if (!sent.current)
|
|
125
126
|
return;
|
|
126
127
|
sent.current = false;
|
|
128
|
+
if (failed)
|
|
129
|
+
return;
|
|
127
130
|
if (element && Object.keys(server).length)
|
|
128
131
|
focusFirst(element, server);
|
|
129
|
-
}, [submitting, server, element]);
|
|
132
|
+
}, [submitting, failed, server, element]);
|
|
130
133
|
const checkField = (form, key) => {
|
|
131
134
|
if (!schema)
|
|
132
135
|
return;
|
|
@@ -202,5 +205,6 @@ export function useForm(schema) {
|
|
|
202
205
|
},
|
|
203
206
|
errors,
|
|
204
207
|
submitting,
|
|
208
|
+
failed,
|
|
205
209
|
};
|
|
206
210
|
}
|
|
@@ -5,6 +5,8 @@ export interface Page {
|
|
|
5
5
|
url: string;
|
|
6
6
|
version: string | null;
|
|
7
7
|
flash: Record<string, unknown>;
|
|
8
|
+
/** the props left out, to come with a request of their own (`defer()`); the client's: those not there yet */
|
|
9
|
+
deferred?: string[];
|
|
8
10
|
}
|
|
9
11
|
interface Options {
|
|
10
12
|
initial: Page;
|
|
@@ -20,6 +22,7 @@ interface Options {
|
|
|
20
22
|
to: string;
|
|
21
23
|
form: HTMLFormElement | null;
|
|
22
24
|
post: boolean;
|
|
25
|
+
failed?: boolean;
|
|
23
26
|
} | null) => void;
|
|
24
27
|
/** a GET navigation to `pathname` started: its page's modules may load with its data */
|
|
25
28
|
preload: (pathname: string) => void;
|
|
@@ -47,5 +50,5 @@ export declare function navigate(href: string, { replace }?: {
|
|
|
47
50
|
replace?: boolean;
|
|
48
51
|
}): void;
|
|
49
52
|
/** the page asked for again, its state and the scroll position kept */
|
|
50
|
-
export declare function again(): void;
|
|
53
|
+
export declare function again(only?: string[]): void;
|
|
51
54
|
export {};
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { crlf } from '../form.js';
|
|
1
2
|
import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
|
|
2
3
|
let visit;
|
|
4
|
+
/** the props of the page on the screen asked for, quietly (`defer()`, `reload({ only })`) */
|
|
5
|
+
let ask;
|
|
3
6
|
/** a URL path is one of the app's pages (the client's, once it has started) */
|
|
4
7
|
let isAppPage;
|
|
5
8
|
/**
|
|
@@ -23,7 +26,91 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
23
26
|
if (kept.size > 50)
|
|
24
27
|
kept.delete(kept.keys().next().value);
|
|
25
28
|
};
|
|
29
|
+
// the page on the screen, and how many were put there (an answer for another is dropped)
|
|
30
|
+
let on = initial;
|
|
31
|
+
let shows = 0;
|
|
32
|
+
const asking = new Set();
|
|
33
|
+
const put = async (page, fresh, stale) => {
|
|
34
|
+
await show(page, fresh, stale);
|
|
35
|
+
if (stale())
|
|
36
|
+
return;
|
|
37
|
+
on = page;
|
|
38
|
+
shows++;
|
|
39
|
+
// the page they were for is gone
|
|
40
|
+
for (const quiet of asking)
|
|
41
|
+
quiet.abort();
|
|
42
|
+
};
|
|
26
43
|
const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
|
|
44
|
+
/** where a page's JSON is: its URL, or its file (a prerendered build) */
|
|
45
|
+
const source = (url) => prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
|
|
46
|
+
// What a static page's file answered when the pointer rested on its link (`prerender`), by the URL a navigation
|
|
47
|
+
// would ask for: read into memory, the last 20. A file runs nothing, so asking early costs the app nothing; the
|
|
48
|
+
// click uses it once, and its version is checked as for any page object. A page without a file answers 204
|
|
49
|
+
// (nothing kept: its data is asked for at the click, when its loader should run)
|
|
50
|
+
const prefetched = new Map();
|
|
51
|
+
const prefetching = new Set();
|
|
52
|
+
const prefetch = async (url) => {
|
|
53
|
+
if (!prerender)
|
|
54
|
+
return;
|
|
55
|
+
const key = source(url);
|
|
56
|
+
if (prefetched.has(key) || prefetching.has(key))
|
|
57
|
+
return;
|
|
58
|
+
prefetching.add(key);
|
|
59
|
+
try {
|
|
60
|
+
const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
|
|
61
|
+
if (response.status === 200 && response.headers.has('X-Fondu')) {
|
|
62
|
+
prefetched.set(key, new Response(await response.text(), { headers: response.headers }));
|
|
63
|
+
if (prefetched.size > 20)
|
|
64
|
+
prefetched.delete(prefetched.keys().next().value);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
catch { } // offline: asked for at the click
|
|
68
|
+
prefetching.delete(key);
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Props of the page on the screen, asked for with a request of its own: the loader's answer for the same
|
|
72
|
+
* component, with these props only. Quiet: no navigation state, no history entry, no scroll; it is aborted when
|
|
73
|
+
* another page is put on the screen, and an answer for a page no longer there is dropped; whatever isn't the
|
|
74
|
+
* page's answer is a failure, never a navigation. What came is merged into the page, its state kept; what didn't is no longer pending (`<Deferred>`
|
|
75
|
+
* says it failed)
|
|
76
|
+
*/
|
|
77
|
+
ask = async (names) => {
|
|
78
|
+
const at = shows;
|
|
79
|
+
const page = on;
|
|
80
|
+
const controller = new AbortController();
|
|
81
|
+
asking.add(controller);
|
|
82
|
+
// a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
|
|
83
|
+
const absent = names.filter((n) => !(n in page.props) && !page.deferred?.includes(n));
|
|
84
|
+
if (absent.length)
|
|
85
|
+
void show((on = { ...page, deferred: [...(page.deferred ?? []), ...absent] }), false, () => shows !== at);
|
|
86
|
+
let got = {};
|
|
87
|
+
try {
|
|
88
|
+
const response = await fetch(source(new URL(page.url, location.href)), {
|
|
89
|
+
headers: {
|
|
90
|
+
...headers(),
|
|
91
|
+
'X-Fondu-Only': names.join(','),
|
|
92
|
+
'X-Fondu-Component': page.component,
|
|
93
|
+
},
|
|
94
|
+
signal: controller.signal,
|
|
95
|
+
});
|
|
96
|
+
const answer = response.ok && response.headers.has('X-Fondu') ? (await response.json()) : null;
|
|
97
|
+
if (answer?.component === page.component)
|
|
98
|
+
got = Object.fromEntries(Object.entries(answer.props).filter(([key]) => names.includes(key)));
|
|
99
|
+
}
|
|
100
|
+
catch { } // offline, aborted
|
|
101
|
+
asking.delete(controller);
|
|
102
|
+
if (controller.signal.aborted || shows !== at)
|
|
103
|
+
return;
|
|
104
|
+
const next = {
|
|
105
|
+
...on,
|
|
106
|
+
props: { ...on.props, ...got },
|
|
107
|
+
deferred: on.deferred?.filter((n) => !names.includes(n)),
|
|
108
|
+
};
|
|
109
|
+
on = next; // before the module is awaited: another answer merges into this one
|
|
110
|
+
await show(next, false, () => shows !== at);
|
|
111
|
+
if (shows === at)
|
|
112
|
+
keep(next);
|
|
113
|
+
};
|
|
27
114
|
/** a document load: in place of this entry, or after it */
|
|
28
115
|
const documentLoad = (url, replace) => {
|
|
29
116
|
// http(s) only: a header's URL never runs as `javascript:` (an app's redirect to a URL it was given)
|
|
@@ -52,31 +139,37 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
52
139
|
// the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigation()), and for
|
|
53
140
|
// assistive technology
|
|
54
141
|
form?.setAttribute('aria-busy', 'true');
|
|
55
|
-
|
|
142
|
+
const to = url.pathname + url.search + url.hash;
|
|
143
|
+
pending(shown ? null : { to, form, post });
|
|
144
|
+
let failed = false;
|
|
56
145
|
const done = () => {
|
|
57
146
|
form?.removeAttribute('aria-busy');
|
|
58
147
|
if (!shown && current === controller)
|
|
59
|
-
pending(null);
|
|
148
|
+
pending(failed ? { to, form, post, failed: true } : null);
|
|
60
149
|
};
|
|
61
150
|
if (!post)
|
|
62
151
|
preload(url.pathname);
|
|
63
|
-
const from = !post && prerender ?
|
|
152
|
+
const from = !post && prerender ? source(url) : url.pathname + url.search;
|
|
153
|
+
// a GET that is not asked for again: the answer kept for it, once (never a form's POST, reload() or Back's)
|
|
154
|
+
const early = !post && !options.keep && !shown ? prefetched.get(from) : undefined;
|
|
155
|
+
prefetched.delete(from);
|
|
64
156
|
void (async () => {
|
|
65
157
|
try {
|
|
66
158
|
if (shown) {
|
|
67
159
|
scroll.commit();
|
|
68
|
-
await
|
|
160
|
+
await put(shown, true, () => signal.aborted);
|
|
69
161
|
if (signal.aborted)
|
|
70
162
|
return;
|
|
71
163
|
announce();
|
|
72
164
|
restore(options.scroll, url.hash);
|
|
73
165
|
}
|
|
74
|
-
const response =
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
166
|
+
const response = early ??
|
|
167
|
+
(await fetch(from, {
|
|
168
|
+
method: post ? 'POST' : 'GET',
|
|
169
|
+
body: options.body,
|
|
170
|
+
headers: headers(),
|
|
171
|
+
signal,
|
|
172
|
+
}));
|
|
80
173
|
if (signal.aborted)
|
|
81
174
|
return;
|
|
82
175
|
if (post)
|
|
@@ -135,6 +228,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
135
228
|
const asked = url.pathname + url.search;
|
|
136
229
|
// the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
|
|
137
230
|
const fresh = shown ? asked !== page.url : !options.keep && !(same && errors);
|
|
231
|
+
// the page stays (reload(), Back's, a form's answer): what it asked for isn't taken away while it is asked again
|
|
232
|
+
if (!fresh && page.deferred)
|
|
233
|
+
for (const name of page.deferred)
|
|
234
|
+
if (name in on.props)
|
|
235
|
+
page.props[name] ??= on.props[name];
|
|
138
236
|
// its URL first, as the browser's own navigations: a page's render reads it (`location`, a URL's language);
|
|
139
237
|
// a redirect's, the fragment asked for if it is still this page's
|
|
140
238
|
const target = page.url + (asked === page.url ? url.hash : '');
|
|
@@ -147,10 +245,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
147
245
|
if (history !== 'none')
|
|
148
246
|
scroll.write(target, history === 'replace');
|
|
149
247
|
scroll.commit();
|
|
150
|
-
await
|
|
248
|
+
await put(page, fresh, () => signal.aborted);
|
|
151
249
|
if (signal.aborted)
|
|
152
250
|
return;
|
|
153
251
|
keep(page);
|
|
252
|
+
if (page.deferred?.length)
|
|
253
|
+
ask(page.deferred);
|
|
154
254
|
if (shown && !fresh)
|
|
155
255
|
return;
|
|
156
256
|
if (!options.keep)
|
|
@@ -162,10 +262,19 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
162
262
|
restore(options.history === 'none' ? options.scroll : null, url.hash);
|
|
163
263
|
}
|
|
164
264
|
catch (error) {
|
|
165
|
-
if (error.name === 'AbortError'
|
|
166
|
-
return;
|
|
167
|
-
if (
|
|
168
|
-
|
|
265
|
+
if (error.name === 'AbortError')
|
|
266
|
+
return;
|
|
267
|
+
if (shown) {
|
|
268
|
+
// offline, Back: the kept page stays; what it was still waiting for is asked now, to fail rather than wait
|
|
269
|
+
if (on.deferred?.length)
|
|
270
|
+
ask(on.deferred);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
// the form stays, to send again: the state says so
|
|
274
|
+
if (post) {
|
|
275
|
+
failed = true;
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
169
278
|
documentLoad(url.href, options.history !== 'push'); // offline: the browser says so
|
|
170
279
|
}
|
|
171
280
|
finally {
|
|
@@ -173,13 +282,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
173
282
|
}
|
|
174
283
|
})();
|
|
175
284
|
};
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
return;
|
|
180
|
-
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
181
|
-
return;
|
|
182
|
-
const link = event.target?.closest?.('a[href]');
|
|
285
|
+
/** the URL of a link the client may follow itself: same origin, this window, no download */
|
|
286
|
+
const linkOf = (target) => {
|
|
287
|
+
const link = target?.closest?.('a[href]');
|
|
183
288
|
if (!(link instanceof HTMLAnchorElement))
|
|
184
289
|
return;
|
|
185
290
|
if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
|
|
@@ -187,6 +292,17 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
187
292
|
const url = new URL(link.href);
|
|
188
293
|
if (url.origin !== location.origin || !isWebUrl(url.href))
|
|
189
294
|
return;
|
|
295
|
+
return url;
|
|
296
|
+
};
|
|
297
|
+
// links: a plain click on a same-origin <a href>, which the page let through
|
|
298
|
+
document.addEventListener('click', (event) => {
|
|
299
|
+
if (event.defaultPrevented || event.button !== 0)
|
|
300
|
+
return;
|
|
301
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
302
|
+
return;
|
|
303
|
+
const url = linkOf(event.target);
|
|
304
|
+
if (!url)
|
|
305
|
+
return;
|
|
190
306
|
// a #fragment of this page: the browser scrolls to it (the position left saved for Back)
|
|
191
307
|
if (url.pathname + url.search === location.pathname + location.search && url.hash) {
|
|
192
308
|
scroll.save();
|
|
@@ -198,6 +314,31 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
198
314
|
event.preventDefault();
|
|
199
315
|
visit(url.href, { history: url.href === location.href ? 'replace' : 'push' });
|
|
200
316
|
});
|
|
317
|
+
// a link's page modules load before the click: when the pointer rests on it (80 ms), or a touch starts on it, and
|
|
318
|
+
// a static page's data with them (its file: nothing runs); another page's data not, a loader runs for a visit,
|
|
319
|
+
// never for a page that may not be visited. Not when the visitor asked to save data; not for the keyboard
|
|
320
|
+
// (tabbing passes many links)
|
|
321
|
+
if (!navigator.connection?.saveData) {
|
|
322
|
+
const RESTING = 80; // milliseconds the pointer rests
|
|
323
|
+
let timer;
|
|
324
|
+
document.addEventListener('mouseover', (event) => {
|
|
325
|
+
const url = linkOf(event.target);
|
|
326
|
+
clearTimeout(timer);
|
|
327
|
+
if (url && isPage(url.pathname))
|
|
328
|
+
timer = setTimeout(() => {
|
|
329
|
+
preload(url.pathname);
|
|
330
|
+
void prefetch(url);
|
|
331
|
+
}, RESTING);
|
|
332
|
+
});
|
|
333
|
+
document.addEventListener('mouseout', () => clearTimeout(timer));
|
|
334
|
+
document.addEventListener('touchstart', (event) => {
|
|
335
|
+
const url = linkOf(event.target);
|
|
336
|
+
if (!url || !isPage(url.pathname))
|
|
337
|
+
return;
|
|
338
|
+
preload(url.pathname);
|
|
339
|
+
void prefetch(url);
|
|
340
|
+
}, { passive: true });
|
|
341
|
+
}
|
|
201
342
|
// forms: GET and POST to this origin, in this window, which the page let through
|
|
202
343
|
document.addEventListener('submit', (event) => {
|
|
203
344
|
if (event.defaultPrevented)
|
|
@@ -216,8 +357,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
216
357
|
return;
|
|
217
358
|
event.preventDefault();
|
|
218
359
|
const data = new FormData(form, submitter);
|
|
219
|
-
// as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
|
|
220
|
-
const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
|
|
360
|
+
// as the browser would send them: a file by its name in a URL or plain text, line breaks as CRLF
|
|
221
361
|
const fields = [...data].map(([k, v]) => [crlf(k), crlf(typeof v === 'string' ? v : v.name)]);
|
|
222
362
|
if (method === 'post') {
|
|
223
363
|
const enctype = attr('enctype', 'formenctype').toLowerCase();
|
|
@@ -258,6 +398,8 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
|
|
|
258
398
|
holdUntilLoaded(position);
|
|
259
399
|
}
|
|
260
400
|
keep(initial);
|
|
401
|
+
if (initial.deferred?.length)
|
|
402
|
+
ask(initial.deferred);
|
|
261
403
|
}
|
|
262
404
|
/**
|
|
263
405
|
* Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
|
|
@@ -446,9 +588,11 @@ export function navigate(href, { replace = false } = {}) {
|
|
|
446
588
|
visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
|
|
447
589
|
}
|
|
448
590
|
/** the page asked for again, its state and the scroll position kept */
|
|
449
|
-
export function again() {
|
|
450
|
-
if (visit)
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
location.
|
|
591
|
+
export function again(only) {
|
|
592
|
+
if (!visit)
|
|
593
|
+
return location.reload();
|
|
594
|
+
if (!only)
|
|
595
|
+
return visit(location.href, { history: 'none', keep: true });
|
|
596
|
+
if (only.length)
|
|
597
|
+
ask(only);
|
|
454
598
|
}
|