fondu 0.13.0 → 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 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, lefthook, commitlint; or `--checks`), and writes a small app: a route, its page, the
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,
@@ -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
- /** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
35
- export declare function renderPage(page: Page, renderToString: (element: ReactElement) => string): Promise<{
36
- head: string;
37
- body: string;
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
- /** this page's props asked for again: the page keeps its state and the scroll position */
56
- export declare function reload(): void;
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 {};
@@ -1,4 +1,4 @@
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
4
  import { decoded, layoutsOf, pageId, routePatterns } from '../paths.js';
@@ -32,10 +32,8 @@ async function load(component) {
32
32
  if (!page)
33
33
  throw new Error(`fondu: there is no page "${component}" in app/routes/`);
34
34
  const chain = layoutsOf(component)
35
- .map((dir) => ['tsx', 'jsx']
36
- .map((ext) => `${ROUTES}${dir ? `${dir}/` : ''}_layout.${ext}`)
37
- .find((k) => k in layoutModules))
38
- .filter((k) => k !== undefined);
35
+ .map((dir) => `${ROUTES}${dir ? `${dir}/` : ''}_layout.tsx`)
36
+ .filter((k) => k in layoutModules);
39
37
  const [Component, ...layouts] = await Promise.all([
40
38
  defaultOf(page),
41
39
  ...chain.map((k) => defaultOf(layoutModules[k])),
@@ -113,7 +111,11 @@ const subscribe = (listener) => {
113
111
  };
114
112
  function setNavigation(next) {
115
113
  navigation = next
116
- ? { state: next.post ? 'submitting' : 'loading', to: next.to, form: next.form }
114
+ ? {
115
+ state: next.failed ? 'failed' : next.post ? 'submitting' : 'loading',
116
+ to: next.to,
117
+ form: next.form,
118
+ }
117
119
  : IDLE;
118
120
  for (const l of listeners)
119
121
  l();
@@ -123,7 +125,8 @@ function setNavigation(next) {
123
125
  function start(settings) {
124
126
  const progress = settings.progress;
125
127
  if (progress)
126
- subscribe(progressBar(progress, () => navigation.state !== 'idle' && (progress.forms !== false || navigation.form === null)));
128
+ subscribe(progressBar(progress, () => (navigation.state === 'loading' || navigation.state === 'submitting') &&
129
+ (progress.forms !== false || navigation.form === null)));
127
130
  const data = document.querySelector('script[data-page="app"]')?.textContent;
128
131
  const root = document.getElementById('app');
129
132
  if (!data || !root)
@@ -165,13 +168,14 @@ function start(settings) {
165
168
  createRoot(root).render(app);
166
169
  });
167
170
  }
168
- /** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
169
- export async function renderPage(page, renderToString) {
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) {
170
177
  const view = await load(page.component);
171
- const html = renderToString(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
172
- // React puts the tags it hoists (`<title>`, `<meta>`, `<link>`) before the root's markup
173
- const at = html.indexOf('<div id="app"');
174
- 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));
175
179
  }
176
180
  /** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
177
181
  export function usePage() {
@@ -183,11 +187,30 @@ export function usePage() {
183
187
  /**
184
188
  * The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
185
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.
186
193
  */
187
194
  export function useNavigation() {
188
195
  return useSyncExternalStore(subscribe, () => navigation, () => IDLE);
189
196
  }
190
- /** this page's props asked for again: the page keeps its state and the scroll position */
191
- export function reload() {
192
- again();
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;
193
216
  }
@@ -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 `submitting` only. Without JavaScript, the form is sent as it is, and the
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 {};
@@ -45,8 +45,9 @@ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.st
45
45
  * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
46
46
  * by the server's keys (`email`, `user.name`)
47
47
  * - `submitting`: this form is being sent
48
+ * - `failed`: this form could not be sent (offline…): it stays, to send again
48
49
  *
49
- * Without a schema: the server's errors and `submitting` only. Without JavaScript, the form is sent as it is, and the
50
+ * Without a schema: the server's errors, `submitting` and `failed` only. Without JavaScript, the form is sent as it is, and the
50
51
  * server's check answers.
51
52
  */
52
53
  export function useForm(schema) {
@@ -111,8 +112,10 @@ export function useForm(schema) {
111
112
  if (form && validates)
112
113
  form.noValidate = true;
113
114
  }, [validates]);
114
- const submitting = navigation.form !== null && navigation.form === element;
115
- // back with the server's errors: the first field to fix gets the focus
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)
116
119
  const sent = useRef(false);
117
120
  useEffect(() => {
118
121
  if (submitting) {
@@ -122,9 +125,11 @@ export function useForm(schema) {
122
125
  if (!sent.current)
123
126
  return;
124
127
  sent.current = false;
128
+ if (failed)
129
+ return;
125
130
  if (element && Object.keys(server).length)
126
131
  focusFirst(element, server);
127
- }, [submitting, server, element]);
132
+ }, [submitting, failed, server, element]);
128
133
  const checkField = (form, key) => {
129
134
  if (!schema)
130
135
  return;
@@ -200,5 +205,6 @@ export function useForm(schema) {
200
205
  },
201
206
  errors,
202
207
  submitting,
208
+ failed,
203
209
  };
204
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,6 +1,8 @@
1
1
  import { crlf } from '../form.js';
2
2
  import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
3
3
  let visit;
4
+ /** the props of the page on the screen asked for, quietly (`defer()`, `reload({ only })`) */
5
+ let ask;
4
6
  /** a URL path is one of the app's pages (the client's, once it has started) */
5
7
  let isAppPage;
6
8
  /**
@@ -24,7 +26,91 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
24
26
  if (kept.size > 50)
25
27
  kept.delete(kept.keys().next().value);
26
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
+ };
27
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
+ };
28
114
  /** a document load: in place of this entry, or after it */
29
115
  const documentLoad = (url, replace) => {
30
116
  // http(s) only: a header's URL never runs as `javascript:` (an app's redirect to a URL it was given)
@@ -53,31 +139,37 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
53
139
  // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigation()), and for
54
140
  // assistive technology
55
141
  form?.setAttribute('aria-busy', 'true');
56
- pending(shown ? null : { to: url.pathname + url.search + url.hash, form, post });
142
+ const to = url.pathname + url.search + url.hash;
143
+ pending(shown ? null : { to, form, post });
144
+ let failed = false;
57
145
  const done = () => {
58
146
  form?.removeAttribute('aria-busy');
59
147
  if (!shown && current === controller)
60
- pending(null);
148
+ pending(failed ? { to, form, post, failed: true } : null);
61
149
  };
62
150
  if (!post)
63
151
  preload(url.pathname);
64
- const from = !post && prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
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);
65
156
  void (async () => {
66
157
  try {
67
158
  if (shown) {
68
159
  scroll.commit();
69
- await show(shown, true, () => signal.aborted);
160
+ await put(shown, true, () => signal.aborted);
70
161
  if (signal.aborted)
71
162
  return;
72
163
  announce();
73
164
  restore(options.scroll, url.hash);
74
165
  }
75
- const response = await fetch(from, {
76
- method: post ? 'POST' : 'GET',
77
- body: options.body,
78
- headers: headers(),
79
- signal,
80
- });
166
+ const response = early ??
167
+ (await fetch(from, {
168
+ method: post ? 'POST' : 'GET',
169
+ body: options.body,
170
+ headers: headers(),
171
+ signal,
172
+ }));
81
173
  if (signal.aborted)
82
174
  return;
83
175
  if (post)
@@ -136,6 +228,11 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
136
228
  const asked = url.pathname + url.search;
137
229
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
138
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];
139
236
  // its URL first, as the browser's own navigations: a page's render reads it (`location`, a URL's language);
140
237
  // a redirect's, the fragment asked for if it is still this page's
141
238
  const target = page.url + (asked === page.url ? url.hash : '');
@@ -148,10 +245,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
148
245
  if (history !== 'none')
149
246
  scroll.write(target, history === 'replace');
150
247
  scroll.commit();
151
- await show(page, fresh, () => signal.aborted);
248
+ await put(page, fresh, () => signal.aborted);
152
249
  if (signal.aborted)
153
250
  return;
154
251
  keep(page);
252
+ if (page.deferred?.length)
253
+ ask(page.deferred);
155
254
  if (shown && !fresh)
156
255
  return;
157
256
  if (!options.keep)
@@ -163,10 +262,19 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
163
262
  restore(options.history === 'none' ? options.scroll : null, url.hash);
164
263
  }
165
264
  catch (error) {
166
- if (error.name === 'AbortError' || shown)
167
- return; // offline, Back: the kept page stays
168
- if (post)
169
- throw error; // the form stays, to send again
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
+ }
170
278
  documentLoad(url.href, options.history !== 'push'); // offline: the browser says so
171
279
  }
172
280
  finally {
@@ -174,13 +282,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
174
282
  }
175
283
  })();
176
284
  };
177
- // links: a plain click on a same-origin <a href>, which the page let through
178
- document.addEventListener('click', (event) => {
179
- if (event.defaultPrevented || event.button !== 0)
180
- return;
181
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
182
- return;
183
- 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]');
184
288
  if (!(link instanceof HTMLAnchorElement))
185
289
  return;
186
290
  if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
@@ -188,6 +292,17 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
188
292
  const url = new URL(link.href);
189
293
  if (url.origin !== location.origin || !isWebUrl(url.href))
190
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;
191
306
  // a #fragment of this page: the browser scrolls to it (the position left saved for Back)
192
307
  if (url.pathname + url.search === location.pathname + location.search && url.hash) {
193
308
  scroll.save();
@@ -199,6 +314,31 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
199
314
  event.preventDefault();
200
315
  visit(url.href, { history: url.href === location.href ? 'replace' : 'push' });
201
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
+ }
202
342
  // forms: GET and POST to this origin, in this window, which the page let through
203
343
  document.addEventListener('submit', (event) => {
204
344
  if (event.defaultPrevented)
@@ -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
- visit(location.href, { history: 'none', keep: true });
452
- else
453
- location.reload();
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
  }
package/dist/client.d.ts CHANGED
@@ -53,7 +53,7 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends Query
53
53
  * `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
54
54
  */
55
55
  export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
56
- export { usePage, useNavigation, reload, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
56
+ export { usePage, useNavigation, reload, Deferred, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
57
57
  export { useForm } from './client/form.js';
58
58
  export { loadDocument, navigate, type Page } from './client/navigation.js';
59
59
  export type { ProgressOptions } from './client/progress.js';
package/dist/client.js CHANGED
@@ -20,6 +20,6 @@ export function href(path, ...[options]) {
20
20
  url += `#${encodeURI(hash)}`;
21
21
  return url;
22
22
  }
23
- export { usePage, useNavigation, reload, __entry, renderPage, } from './client/app.js';
23
+ export { usePage, useNavigation, reload, Deferred, __entry, renderPage, } from './client/app.js';
24
24
  export { useForm } from './client/form.js';
25
25
  export { loadDocument, navigate } from './client/navigation.js';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share, type RenderOptions } from './server/protocol.js';
2
+ export { defer, render, share, type RenderOptions } from './server/protocol.js';
3
3
  export { back } from './server/http.js';
4
4
  export { flash } from './server/flash.js';
5
5
  export { ValidationError, type StandardSchemaV1 } from './server/validate.js';
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { defineHandler, defineMiddleware } from './server/handler.js';
2
- export { render, share } from './server/protocol.js';
2
+ export { defer, render, share } from './server/protocol.js';
3
3
  export { back } from './server/http.js';
4
4
  export { flash } from './server/flash.js';
5
5
  export { ValidationError } from './server/validate.js';
package/dist/paths.d.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  */
11
11
  export declare function routePatterns(file: string): string[];
12
12
  /**
13
- * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.jsx`, `.mdx` (a page), but
13
+ * a path inside `routes/` that is a route file: `.ts` (server code: handlers) or `.tsx`, `.mdx` (a page), but
14
14
  * tests and declarations, and neither its name nor a directory on its path starting with `_` (`_middleware.ts`,
15
15
  * `_layout.tsx`, `_parts/badge.tsx`)
16
16
  */
@@ -19,7 +19,7 @@ export declare function isRouteFile(file: string): boolean;
19
19
  export declare const METHODS: readonly ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'];
20
20
  export declare const HANDLERS: readonly ['loader', 'action', 'actions'];
21
21
  export declare const CONFIG: readonly ['prerender', 'params'];
22
- /** a route file that is a page (React: `.tsx`, `.jsx`, `.mdx`), not server code only (`.ts`) */
22
+ /** a route file that is a page (React: `.tsx`, `.mdx`), not server code only (`.ts`) */
23
23
  export declare const isPageFile: (file: string) => boolean;
24
24
  /** a page's id, its route file without the extension: `users/[id].tsx` → `users/[id]` (the client's name for it) */
25
25
  export declare const pageId: (file: string) => string;
@@ -49,6 +49,11 @@ export declare function decoded(segment: string): string;
49
49
  export declare const endsInIndex: (path: string) => boolean;
50
50
  /** the other way: `/_fondu/pages/docs/intro.json` → `/docs/intro`; null for any other path */
51
51
  export declare function pathOfPageData(pathname: string): string | null;
52
+ /**
53
+ * a prerendered page's document file from its path as a server reads it (decoded): `/docs/intro` → `docs/intro.html`,
54
+ * `/docs/` → `docs/index.html`
55
+ */
56
+ export declare const htmlFile: (decodedPath: string) => string;
52
57
  /** the files of a prerendered page: `/docs/intro` → `docs/intro.html` and `_fondu/pages/docs/intro.json` (decoded) */
53
58
  export declare function staticFiles(path: string): {
54
59
  html: string;