fondu 0.13.0 → 0.15.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) => Object.hasOwn(page.props, name)))
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,98 @@ 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 link's page answered when asked early (`prerender`), by the URL a navigation would ask: its file (a
47
+ // Response, read into memory), or null (no file: 204, its data is asked for at the click, when its loader should
48
+ // run). A file runs nothing, so asking early costs the app nothing. Asked once in 30 seconds (TanStack Router's
49
+ // default: a deploy in between is found at the click); the click waits for an answer on its way and reads a file
50
+ // once, its version checked as for any page object. The last 20
51
+ const freshFor = 30_000;
52
+ const prefetched = new Map();
53
+ const prefetch = (url) => {
54
+ if (!prerender)
55
+ return;
56
+ const key = source(url);
57
+ const entry = prefetched.get(key);
58
+ if (entry && Date.now() - entry.at < freshFor)
59
+ return;
60
+ const answer = (async () => {
61
+ try {
62
+ const response = await fetch(key, { headers: { ...headers(), 'X-Fondu-Prefetch': 'true' } });
63
+ if (response.status === 200 && response.headers.has('X-Fondu'))
64
+ return new Response(await response.text(), { headers: response.headers });
65
+ }
66
+ catch {
67
+ // offline: asked for again
68
+ prefetched.delete(key);
69
+ }
70
+ return null;
71
+ })();
72
+ prefetched.delete(key);
73
+ prefetched.set(key, { answer, at: Date.now() });
74
+ if (prefetched.size > 20)
75
+ prefetched.delete(prefetched.keys().next().value);
76
+ };
77
+ /**
78
+ * Props of the page on the screen, asked for with a request of its own: the loader's answer for the same
79
+ * component, with these props only. Quiet: no navigation state, no history entry, no scroll; it is aborted when
80
+ * another page is put on the screen, and an answer for a page no longer there is dropped; whatever isn't the
81
+ * page's answer is a failure, never a navigation. What came is merged into the page, its state kept; what didn't
82
+ * is no longer pending (`<Deferred>` says it failed)
83
+ */
84
+ ask = async (names) => {
85
+ const at = shows;
86
+ const page = on;
87
+ const controller = new AbortController();
88
+ asking.add(controller);
89
+ // a prop asked for that is neither here nor coming (it failed): pending again, `<Deferred>` shows its fallback
90
+ const absent = names.filter((n) => !Object.hasOwn(page.props, n) && !page.deferred?.includes(n));
91
+ if (absent.length)
92
+ void show((on = { ...page, deferred: [...(page.deferred ?? []), ...absent] }), false, () => shows !== at);
93
+ let got = {};
94
+ try {
95
+ const response = await fetch(source(new URL(page.url, location.href)), {
96
+ headers: {
97
+ ...headers(),
98
+ 'X-Fondu-Only': names.join(','),
99
+ 'X-Fondu-Component': page.component,
100
+ },
101
+ signal: controller.signal,
102
+ });
103
+ const answer = response.ok && response.headers.has('X-Fondu') ? (await response.json()) : null;
104
+ if (answer?.component === page.component)
105
+ got = Object.fromEntries(Object.entries(answer.props).filter(([key]) => names.includes(key)));
106
+ }
107
+ catch { } // offline, aborted
108
+ asking.delete(controller);
109
+ if (controller.signal.aborted || shows !== at)
110
+ return;
111
+ const next = {
112
+ ...on,
113
+ props: { ...on.props, ...got },
114
+ deferred: on.deferred?.filter((n) => !names.includes(n)),
115
+ };
116
+ on = next; // before the module is awaited: another answer merges into this one
117
+ await show(next, false, () => shows !== at);
118
+ if (shows === at)
119
+ keep(next);
120
+ };
28
121
  /** a document load: in place of this entry, or after it */
29
122
  const documentLoad = (url, replace) => {
30
123
  // http(s) only: a header's URL never runs as `javascript:` (an app's redirect to a URL it was given)
@@ -53,31 +146,44 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
53
146
  // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigation()), and for
54
147
  // assistive technology
55
148
  form?.setAttribute('aria-busy', 'true');
56
- pending(shown ? null : { to: url.pathname + url.search + url.hash, form, post });
149
+ const to = url.pathname + url.search + url.hash;
150
+ pending(shown ? null : { to, form, post });
151
+ let failed = false;
57
152
  const done = () => {
58
153
  form?.removeAttribute('aria-busy');
59
154
  if (!shown && current === controller)
60
- pending(null);
155
+ pending(failed ? { to, form, post, failed: true } : null);
61
156
  };
62
157
  if (!post)
63
158
  preload(url.pathname);
64
- const from = !post && prerender ? pageDataPath(url.pathname) + url.search : url.pathname + url.search;
159
+ const from = !post && prerender ? source(url) : url.pathname + url.search;
160
+ // a GET that is not asked for again: the answer kept for it (never a form's POST, reload() or Back's)
161
+ const found = !post && !options.keep && !shown ? prefetched.get(from) : undefined;
162
+ const entry = found && Date.now() - found.at < freshFor ? found : undefined;
65
163
  void (async () => {
66
164
  try {
67
165
  if (shown) {
68
166
  scroll.commit();
69
- await show(shown, true, () => signal.aborted);
167
+ await put(shown, true, () => signal.aborted);
70
168
  if (signal.aborted)
71
169
  return;
72
170
  announce();
73
171
  restore(options.scroll, url.hash);
74
172
  }
75
- const response = await fetch(from, {
76
- method: post ? 'POST' : 'GET',
77
- body: options.body,
78
- headers: headers(),
79
- signal,
80
- });
173
+ // the file asked for early, waited for if it is on its way; none (null): the app is asked
174
+ const early = entry ? await entry.answer : null;
175
+ if (signal.aborted)
176
+ return;
177
+ // a Response is read once; a null stays, so the rests that follow ask nothing
178
+ if (early && prefetched.get(from) === entry)
179
+ prefetched.delete(from);
180
+ const response = early ??
181
+ (await fetch(from, {
182
+ method: post ? 'POST' : 'GET',
183
+ body: options.body,
184
+ headers: headers(),
185
+ signal,
186
+ }));
81
187
  if (signal.aborted)
82
188
  return;
83
189
  if (post)
@@ -136,9 +242,15 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
136
242
  const asked = url.pathname + url.search;
137
243
  // the kept page's entry: the server's page in its place, its state kept; redirected (signed out), anew
138
244
  const fresh = shown ? asked !== page.url : !options.keep && !(same && errors);
245
+ // the page stays (reload(), Back's, a form's answer): what it asked for isn't taken away while it is asked again
246
+ if (!fresh && page.deferred)
247
+ for (const name of page.deferred)
248
+ if (Object.hasOwn(on.props, name))
249
+ page.props[name] ??= on.props[name];
139
250
  // its URL first, as the browser's own navigations: a page's render reads it (`location`, a URL's language);
140
- // a redirect's, the fragment asked for if it is still this page's
141
- const target = page.url + (asked === page.url ? url.hash : '');
251
+ // a redirect's, the fragment asked for if it is still this page's; a form's answer to the page it was sent
252
+ // from: its #fragment stays, a dialog the fragment opened with it
253
+ const target = page.url + (same ? location.hash : asked === page.url ? url.hash : '');
142
254
  // a form's answer at its URL replaces the entry; Back's or reload()'s page redirected elsewhere too
143
255
  const history = options.history === 'push' && same
144
256
  ? 'replace'
@@ -148,10 +260,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
148
260
  if (history !== 'none')
149
261
  scroll.write(target, history === 'replace');
150
262
  scroll.commit();
151
- await show(page, fresh, () => signal.aborted);
263
+ await put(page, fresh, () => signal.aborted);
152
264
  if (signal.aborted)
153
265
  return;
154
266
  keep(page);
267
+ if (page.deferred?.length)
268
+ ask(page.deferred);
155
269
  if (shown && !fresh)
156
270
  return;
157
271
  if (!options.keep)
@@ -163,10 +277,19 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
163
277
  restore(options.history === 'none' ? options.scroll : null, url.hash);
164
278
  }
165
279
  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
280
+ if (error.name === 'AbortError')
281
+ return;
282
+ if (shown) {
283
+ // offline, Back: the kept page stays; what it was still waiting for is asked now, to fail rather than wait
284
+ if (on.deferred?.length)
285
+ ask(on.deferred);
286
+ return;
287
+ }
288
+ // the form stays, to send again: the state says so
289
+ if (post) {
290
+ failed = true;
291
+ return;
292
+ }
170
293
  documentLoad(url.href, options.history !== 'push'); // offline: the browser says so
171
294
  }
172
295
  finally {
@@ -174,13 +297,9 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
174
297
  }
175
298
  })();
176
299
  };
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]');
300
+ /** the URL of a link the client may follow itself: same origin, this window, no download */
301
+ const linkOf = (target) => {
302
+ const link = target?.closest?.('a[href]');
184
303
  if (!(link instanceof HTMLAnchorElement))
185
304
  return;
186
305
  if ((link.target && link.target !== '_self') || link.hasAttribute('download'))
@@ -188,6 +307,17 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
188
307
  const url = new URL(link.href);
189
308
  if (url.origin !== location.origin || !isWebUrl(url.href))
190
309
  return;
310
+ return url;
311
+ };
312
+ // links: a plain click on a same-origin <a href>, which the page let through
313
+ document.addEventListener('click', (event) => {
314
+ if (event.defaultPrevented || event.button !== 0)
315
+ return;
316
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
317
+ return;
318
+ const url = linkOf(event.target);
319
+ if (!url)
320
+ return;
191
321
  // a #fragment of this page: the browser scrolls to it (the position left saved for Back)
192
322
  if (url.pathname + url.search === location.pathname + location.search && url.hash) {
193
323
  scroll.save();
@@ -199,6 +329,31 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
199
329
  event.preventDefault();
200
330
  visit(url.href, { history: url.href === location.href ? 'replace' : 'push' });
201
331
  });
332
+ // a link's page modules load before the click: when the pointer rests on it (80 ms), or a touch starts on it, and
333
+ // a static page's data with them (its file: nothing runs); another page's data not, a loader runs for a visit,
334
+ // never for a page that may not be visited. Not when the visitor asked to save data; not for the keyboard
335
+ // (tabbing passes many links)
336
+ if (!navigator.connection?.saveData) {
337
+ const RESTING = 80; // milliseconds the pointer rests
338
+ let timer;
339
+ document.addEventListener('mouseover', (event) => {
340
+ const url = linkOf(event.target);
341
+ clearTimeout(timer);
342
+ if (url && isPage(url.pathname))
343
+ timer = setTimeout(() => {
344
+ preload(url.pathname);
345
+ void prefetch(url);
346
+ }, RESTING);
347
+ });
348
+ document.addEventListener('mouseout', () => clearTimeout(timer));
349
+ document.addEventListener('touchstart', (event) => {
350
+ const url = linkOf(event.target);
351
+ if (!url || !isPage(url.pathname))
352
+ return;
353
+ preload(url.pathname);
354
+ void prefetch(url);
355
+ }, { passive: true });
356
+ }
202
357
  // forms: GET and POST to this origin, in this window, which the page let through
203
358
  document.addEventListener('submit', (event) => {
204
359
  if (event.defaultPrevented)
@@ -234,8 +389,12 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
234
389
  // Back and Forward: the entry's page, where it was scrolled
235
390
  window.addEventListener('popstate', (event) => {
236
391
  const popped = scroll.pop(event.state);
237
- if (popped.fragment)
392
+ if (popped.fragment) {
393
+ // a #fragment that names no element (a dialog's `#settings/account`) leaves the page where it is, as the browser does
394
+ if (!popped.position && location.hash && !fragmentTarget(location.hash.slice(1)))
395
+ return;
238
396
  return restore(popped.position, location.hash);
397
+ }
239
398
  visit(location.href, {
240
399
  history: 'none',
241
400
  scroll: popped.position,
@@ -258,6 +417,8 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
258
417
  holdUntilLoaded(position);
259
418
  }
260
419
  keep(initial);
420
+ if (initial.deferred?.length)
421
+ ask(initial.deferred);
261
422
  }
262
423
  /**
263
424
  * Scroll positions, per history entry (a key in `history.state`), in memory and in sessionStorage (a reload, a page
@@ -446,9 +607,11 @@ export function navigate(href, { replace = false } = {}) {
446
607
  visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
447
608
  }
448
609
  /** 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();
610
+ export function again(only) {
611
+ if (!visit)
612
+ return location.reload();
613
+ if (!only)
614
+ return visit(location.href, { history: 'none', keep: true });
615
+ if (only.length)
616
+ ask(only);
454
617
  }