fondu 0.9.6 → 0.10.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 +7 -12
- package/dist/client/app.d.ts +40 -0
- package/dist/client/app.js +162 -0
- package/dist/client/navigation.d.ts +35 -0
- package/dist/client/navigation.js +210 -0
- package/dist/client/progress.d.ts +16 -0
- package/dist/client/progress.js +51 -0
- package/dist/client.d.ts +4 -15
- package/dist/client.js +3 -47
- package/dist/index.d.ts +3 -4
- package/dist/index.js +3 -4
- package/dist/paths.d.ts +10 -7
- package/dist/paths.js +15 -15
- package/dist/server/app.d.ts +4 -5
- package/dist/server/app.js +81 -16
- package/dist/server/document.d.ts +3 -3
- package/dist/server/document.js +7 -6
- package/dist/server/errors.d.ts +4 -2
- package/dist/server/errors.js +21 -10
- package/dist/server/flash.d.ts +4 -7
- package/dist/server/flash.js +9 -14
- package/dist/server/handler.d.ts +1 -1
- package/dist/server/handler.js +1 -1
- package/dist/server/http.d.ts +7 -5
- package/dist/server/http.js +15 -6
- package/dist/server/prerender.d.ts +1 -1
- package/dist/server/prerender.js +6 -6
- package/dist/server/protocol.d.ts +22 -35
- package/dist/server/protocol.js +65 -195
- package/dist/server/routes.d.ts +1 -1
- package/dist/server/validate.d.ts +7 -9
- package/dist/server/validate.js +8 -21
- package/dist/types.d.ts +10 -6
- package/dist/virtual.d.ts +3 -5
- package/dist/vite/hmr.d.ts +3 -3
- package/dist/vite/hmr.js +5 -5
- package/dist/vite/index.d.ts +9 -5
- package/dist/vite/index.js +158 -79
- package/dist/vite/prerender.d.ts +3 -3
- package/dist/vite/prerender.js +17 -12
- package/dist/vite/strip.d.ts +21 -0
- package/dist/vite/strip.js +301 -0
- package/dist/vite/typegen.d.ts +3 -2
- package/dist/vite/typegen.js +6 -10
- package/package.json +2 -9
- package/dist/server/props.d.ts +0 -85
- package/dist/server/props.js +0 -44
- package/dist/vite/layouts.d.ts +0 -10
- package/dist/vite/layouts.js +0 -110
- package/dist/vite/vitest-cache.d.ts +0 -19
- package/dist/vite/vitest-cache.js +0 -30
package/README.md
CHANGED
|
@@ -2,17 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://fondu.dev)
|
|
4
4
|
|
|
5
|
-
Fondu is a small meta-framework for full-stack React apps, built on Hono
|
|
6
|
-
|
|
5
|
+
Fondu is a small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers
|
|
6
|
+
and Node.
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
props,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
Fondu writes only what none of them does: Inertia's server side for Hono (the protocol, forms' errors and flash
|
|
13
|
-
data), file routes, typed pages and URLs, the document and error pages. Everything else is Hono's, Vite's and
|
|
14
|
-
Inertia's. [Fondu and @hono/inertia](https://fondu.dev/docs#fondu-and-honoinertia) says how it compares with Hono's
|
|
15
|
-
own middleware.
|
|
8
|
+
The files in `app/routes/` are the URLs: Hono handlers that run on the server, and for a page, the React component its
|
|
9
|
+
loader renders with props, in the same file (the browser gets the component alone). In the browser, links and forms are plain `<a>` and `<form>`: Fondu's small client, on the Navigation API, swaps
|
|
10
|
+
the pages in place, without an API to write or a client-side router to keep in sync.
|
|
16
11
|
|
|
17
12
|
## Quick start
|
|
18
13
|
|
|
@@ -26,7 +21,7 @@ It asks where the app runs (Bun, Cloudflare Workers or Node; or `--target bun|cl
|
|
|
26
21
|
code checks (oxfmt, oxlint, lefthook, commitlint; or `--checks`), and writes a small app: a route, its page, the
|
|
27
22
|
error page, Tailwind CSS, editor snippets and an `AGENTS.md` for coding agents. `--yes` asks nothing more.
|
|
28
23
|
|
|
29
|
-
[demo.fondu.dev](https://demo.fondu.dev) ([apps/demo](https://github.com/fondujs/fondu/tree/main/apps/demo)) shows Fondu's
|
|
24
|
+
[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,
|
|
30
25
|
on Cloudflare Workers with D1 and Better Auth.
|
|
31
26
|
|
|
32
27
|
## Docs
|
|
@@ -40,7 +35,7 @@ server-side rendering, static pages, MDX pages, internationalization, deploying,
|
|
|
40
35
|
```
|
|
41
36
|
packages/fondu the package
|
|
42
37
|
packages/create-fondu `bun create fondu`
|
|
43
|
-
apps/demo Fondu's
|
|
38
|
+
apps/demo Fondu's features, one page each — Workers, D1, Better Auth, coss ui
|
|
44
39
|
apps/site fondu.dev: the docs, MDX and static pages on Workers
|
|
45
40
|
```
|
|
46
41
|
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type ReactElement } from 'react';
|
|
2
|
+
import type { Flash, Shared } from '../types.js';
|
|
3
|
+
import { type Page } from './navigation.js';
|
|
4
|
+
import { type ProgressOptions } from './progress.js';
|
|
5
|
+
type Loader = () => Promise<unknown>;
|
|
6
|
+
/**
|
|
7
|
+
* @internal the app's entry (the Vite plugin writes it), in the browser and for the server render: `import.meta.glob`
|
|
8
|
+
* of the pages and layouts of `app/routes/`, and `fondu({ prerender, progress })`. In the browser it starts the app:
|
|
9
|
+
* it hydrates the server's page and starts navigating.
|
|
10
|
+
*/
|
|
11
|
+
export declare function __entry(pageModules: Record<string, Loader>, layouts: Record<string, Loader>, settings: {
|
|
12
|
+
prerender: boolean;
|
|
13
|
+
progress: ProgressOptions | false;
|
|
14
|
+
}): void;
|
|
15
|
+
/**
|
|
16
|
+
* @internal The page a URL most likely is, by its route file's patterns (static segments first): its modules load with its
|
|
17
|
+
* data. Only a guess (a param's listed values are the server's), so the page shown is the one the server says.
|
|
18
|
+
*/
|
|
19
|
+
export declare function pageAt(pathname: string): string | undefined;
|
|
20
|
+
/** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
|
|
21
|
+
export declare function renderPage(page: Page, renderToString: (element: ReactElement) => string): Promise<{
|
|
22
|
+
head: string;
|
|
23
|
+
body: string;
|
|
24
|
+
}>;
|
|
25
|
+
/** a form's field errors, as a page gets them (its `errors` prop): field name → message */
|
|
26
|
+
export type Errors = Record<string, string>;
|
|
27
|
+
/** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
|
|
28
|
+
export declare function usePage<P = Shared>(): {
|
|
29
|
+
component: string;
|
|
30
|
+
props: P & {
|
|
31
|
+
errors: Errors;
|
|
32
|
+
};
|
|
33
|
+
url: string;
|
|
34
|
+
flash: Partial<Flash>;
|
|
35
|
+
};
|
|
36
|
+
/** true while a navigation or a form's submission is on its way */
|
|
37
|
+
export declare function useNavigating(): boolean;
|
|
38
|
+
/** this page's props asked for again: the page keeps its state and the scroll position */
|
|
39
|
+
export declare function reload(): void;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { createContext, createElement, useContext, useLayoutEffect, useState, useSyncExternalStore, } from 'react';
|
|
2
|
+
import { flushSync } from 'react-dom';
|
|
3
|
+
import { createRoot, hydrateRoot } from 'react-dom/client';
|
|
4
|
+
import { layoutsOf, pageId, routePatterns } from '../paths.js';
|
|
5
|
+
import { again, startNavigation } from './navigation.js';
|
|
6
|
+
import { progressBar } from './progress.js';
|
|
7
|
+
const ROUTES = '/app/routes/';
|
|
8
|
+
// set by the app's entry (the Vite plugin's): the pages and layouts of app/routes/, and the build's settings
|
|
9
|
+
let pages = new Map();
|
|
10
|
+
let layoutModules = {};
|
|
11
|
+
/**
|
|
12
|
+
* @internal the app's entry (the Vite plugin writes it), in the browser and for the server render: `import.meta.glob`
|
|
13
|
+
* of the pages and layouts of `app/routes/`, and `fondu({ prerender, progress })`. In the browser it starts the app:
|
|
14
|
+
* it hydrates the server's page and starts navigating.
|
|
15
|
+
*/
|
|
16
|
+
export function __entry(pageModules, layouts, settings) {
|
|
17
|
+
pages = new Map(Object.entries(pageModules).map(([key, loader]) => [pageId(key.slice(ROUTES.length)), loader]));
|
|
18
|
+
layoutModules = layouts;
|
|
19
|
+
if (typeof document !== 'undefined')
|
|
20
|
+
start(settings);
|
|
21
|
+
}
|
|
22
|
+
const defaultOf = async (loader) => (await loader()).default;
|
|
23
|
+
/** a page's component, and the `_layout.tsx` files of its directories it's drawn in, outermost first */
|
|
24
|
+
async function load(component) {
|
|
25
|
+
const page = pages.get(component);
|
|
26
|
+
if (!page)
|
|
27
|
+
throw new Error(`fondu: there is no page "${component}" in app/routes/`);
|
|
28
|
+
const chain = layoutsOf(component)
|
|
29
|
+
.map((dir) => ['tsx', 'jsx']
|
|
30
|
+
.map((ext) => `${ROUTES}${dir ? `${dir}/` : ''}_layout.${ext}`)
|
|
31
|
+
.find((k) => k in layoutModules))
|
|
32
|
+
.filter((k) => k !== undefined);
|
|
33
|
+
const [Component, ...layouts] = await Promise.all([
|
|
34
|
+
defaultOf(page),
|
|
35
|
+
...chain.map((k) => defaultOf(layoutModules[k])),
|
|
36
|
+
]);
|
|
37
|
+
return { Component, layouts };
|
|
38
|
+
}
|
|
39
|
+
// ---- the page on screen, for usePage()
|
|
40
|
+
const PageContext = createContext(null);
|
|
41
|
+
/** the browser's: called once the app is on the screen, with what puts another page there */
|
|
42
|
+
let mounted;
|
|
43
|
+
function App({ initial }) {
|
|
44
|
+
const [{ page, view, mounts }, set] = useState(initial);
|
|
45
|
+
useLayoutEffect(() => mounted?.(set), [set]);
|
|
46
|
+
const { Component, layouts } = view;
|
|
47
|
+
// the page mounted anew by each navigation, its layouts kept (the same components: React keeps them)
|
|
48
|
+
const content = layouts.reduceRight((children, L) => createElement(L, null, children), createElement(Component, { key: mounts, ...page.props }));
|
|
49
|
+
return createElement(PageContext.Provider, { value: page }, content);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* @internal The page a URL most likely is, by its route file's patterns (static segments first): its modules load with its
|
|
53
|
+
* data. Only a guess (a param's listed values are the server's), so the page shown is the one the server says.
|
|
54
|
+
*/
|
|
55
|
+
export function pageAt(pathname) {
|
|
56
|
+
const parts = pathname.split('/').filter(Boolean);
|
|
57
|
+
let best;
|
|
58
|
+
for (const id of pages.keys()) {
|
|
59
|
+
if (id.split('/').some((s) => s.startsWith('_')))
|
|
60
|
+
continue;
|
|
61
|
+
for (const pattern of routePatterns(id)) {
|
|
62
|
+
const segments = pattern.split('/').filter(Boolean);
|
|
63
|
+
let score = 0;
|
|
64
|
+
let i = 0;
|
|
65
|
+
for (const s of segments) {
|
|
66
|
+
const part = parts[i];
|
|
67
|
+
if (part === undefined)
|
|
68
|
+
score = -1;
|
|
69
|
+
else if (s.endsWith('{.+}'))
|
|
70
|
+
score += 1; // a catch-all: the rest
|
|
71
|
+
else if (s.startsWith(':'))
|
|
72
|
+
score += 2;
|
|
73
|
+
else
|
|
74
|
+
score += s === part ? 3 : -Infinity;
|
|
75
|
+
i = s.endsWith('{.+}') ? parts.length : i + 1;
|
|
76
|
+
if (score < 0)
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
if (score >= 0 && i === parts.length && (!best || score > best.score))
|
|
80
|
+
best = { id, score };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return best?.id;
|
|
84
|
+
}
|
|
85
|
+
// ---- pending navigations, for useNavigating()
|
|
86
|
+
let navigating = false;
|
|
87
|
+
let submitting = false;
|
|
88
|
+
const listeners = new Set();
|
|
89
|
+
const subscribe = (listener) => {
|
|
90
|
+
listeners.add(listener);
|
|
91
|
+
return () => listeners.delete(listener);
|
|
92
|
+
};
|
|
93
|
+
function setNavigating(value, form) {
|
|
94
|
+
navigating = value;
|
|
95
|
+
submitting = form;
|
|
96
|
+
for (const l of listeners)
|
|
97
|
+
l();
|
|
98
|
+
}
|
|
99
|
+
// ---- the app
|
|
100
|
+
/** the browser's app: the server's page hydrated, then navigations */
|
|
101
|
+
function start(settings) {
|
|
102
|
+
const progress = settings.progress;
|
|
103
|
+
if (progress)
|
|
104
|
+
subscribe(progressBar(progress, () => navigating && (progress.forms !== false || !submitting)));
|
|
105
|
+
const data = document.querySelector('script[data-page="app"]')?.textContent;
|
|
106
|
+
const root = document.getElementById('app');
|
|
107
|
+
if (!data || !root)
|
|
108
|
+
throw new Error('fondu: the document has no page (script[data-page="app"], #app)');
|
|
109
|
+
const initial = JSON.parse(data);
|
|
110
|
+
void load(initial.component).then((view) => {
|
|
111
|
+
// dev: the stylesheet the server gave the page until its layouts brought their CSS (they have now)
|
|
112
|
+
document.querySelector('[data-fondu-dev-css]')?.remove();
|
|
113
|
+
const app = createElement(App, { initial: { page: initial, view, mounts: 0 } });
|
|
114
|
+
// navigations start once the page is on the screen (hydrated)
|
|
115
|
+
mounted = (set) => {
|
|
116
|
+
mounted = undefined;
|
|
117
|
+
startNavigation({
|
|
118
|
+
initial,
|
|
119
|
+
prerender: settings.prerender,
|
|
120
|
+
pending: setNavigating,
|
|
121
|
+
preload(pathname) {
|
|
122
|
+
const page = pageAt(pathname);
|
|
123
|
+
if (page)
|
|
124
|
+
load(page).catch(() => { });
|
|
125
|
+
},
|
|
126
|
+
async show(page, fresh, stale) {
|
|
127
|
+
const view = await load(page.component);
|
|
128
|
+
if (stale())
|
|
129
|
+
return;
|
|
130
|
+
flushSync(() => set((now) => ({ page, view, mounts: now.mounts + Number(fresh) })));
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
if (root.hasChildNodes())
|
|
135
|
+
hydrateRoot(root, app);
|
|
136
|
+
else
|
|
137
|
+
createRoot(root).render(app);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
/** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
|
|
141
|
+
export async function renderPage(page, renderToString) {
|
|
142
|
+
const view = await load(page.component);
|
|
143
|
+
const html = renderToString(createElement('div', { id: 'app' }, createElement(App, { initial: { page, view, mounts: 0 } })));
|
|
144
|
+
// React puts the tags it hoists (`<title>`, `<meta>`, `<link>`) before the root's markup
|
|
145
|
+
const at = html.indexOf('<div id="app"');
|
|
146
|
+
return { head: html.slice(0, at), body: html.slice(at) };
|
|
147
|
+
}
|
|
148
|
+
/** the page on screen: its props (the shared ones, `errors`), its URL, its flash data */
|
|
149
|
+
export function usePage() {
|
|
150
|
+
const page = useContext(PageContext);
|
|
151
|
+
if (!page)
|
|
152
|
+
throw new Error('fondu: usePage() is for components of a page');
|
|
153
|
+
return page;
|
|
154
|
+
}
|
|
155
|
+
/** true while a navigation or a form's submission is on its way */
|
|
156
|
+
export function useNavigating() {
|
|
157
|
+
return useSyncExternalStore(subscribe, () => navigating, () => false);
|
|
158
|
+
}
|
|
159
|
+
/** this page's props asked for again: the page keeps its state and the scroll position */
|
|
160
|
+
export function reload() {
|
|
161
|
+
again();
|
|
162
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** what the server sends for a page: its id (its route file, `users/[id]`), its props, its URL, the build's version */
|
|
2
|
+
export interface Page {
|
|
3
|
+
component: string;
|
|
4
|
+
props: Record<string, unknown>;
|
|
5
|
+
url: string;
|
|
6
|
+
version: string | null;
|
|
7
|
+
flash: Record<string, unknown>;
|
|
8
|
+
}
|
|
9
|
+
interface Options {
|
|
10
|
+
initial: Page;
|
|
11
|
+
/**
|
|
12
|
+
* puts the page on the screen (in the DOM once it resolves); `fresh`: mounted anew, else it keeps its state (a form
|
|
13
|
+
* back with its errors, reload()); not once `stale()` (superseded while its modules loaded)
|
|
14
|
+
*/
|
|
15
|
+
show: (page: Page, fresh: boolean, stale: () => boolean) => Promise<void>;
|
|
16
|
+
/** `fondu({ prerender: true })`: GET navigations read `/_fondu/pages/<path>.json` */
|
|
17
|
+
prerender: boolean;
|
|
18
|
+
/** a navigation started (true; `form`: a form's submission) or ended (false) */
|
|
19
|
+
pending: (pending: boolean, form: boolean) => void;
|
|
20
|
+
/** a GET navigation to `pathname` started: its page's modules may load with its data */
|
|
21
|
+
preload: (pathname: string) => void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Same-origin links, GET and POST forms, Back and Forward, through the Navigation API: the page fetched as JSON and
|
|
25
|
+
* shown in place. Without the Navigation API, links and forms load documents.
|
|
26
|
+
*/
|
|
27
|
+
export declare function startNavigation({ initial, show, prerender, pending, preload }: Options): void;
|
|
28
|
+
/**
|
|
29
|
+
* `href` loaded as a document. Every other navigation is the client's, `location.assign()` and `location.href = …`
|
|
30
|
+
* too: this is for what a page can't change in place (`<html lang>`: another language).
|
|
31
|
+
*/
|
|
32
|
+
export declare function loadDocument(href: string): void;
|
|
33
|
+
/** the page asked for again, its state and the scroll position kept */
|
|
34
|
+
export declare function again(): void;
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { pageDataPath } from '../paths.js';
|
|
2
|
+
const noop = () => { };
|
|
3
|
+
const navigation = () => globalThis.navigation;
|
|
4
|
+
/**
|
|
5
|
+
* Same-origin links, GET and POST forms, Back and Forward, through the Navigation API: the page fetched as JSON and
|
|
6
|
+
* shown in place. Without the Navigation API, links and forms load documents.
|
|
7
|
+
*/
|
|
8
|
+
export function startNavigation({ initial, show, prerender, pending, preload }) {
|
|
9
|
+
const nav = navigation();
|
|
10
|
+
if (!nav)
|
|
11
|
+
return;
|
|
12
|
+
let version = initial.version;
|
|
13
|
+
let submitting;
|
|
14
|
+
let current = 0;
|
|
15
|
+
// the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigating()), and for
|
|
16
|
+
// assistive technology
|
|
17
|
+
const begin = (form = null) => {
|
|
18
|
+
const id = ++current;
|
|
19
|
+
form?.setAttribute('aria-busy', 'true');
|
|
20
|
+
pending(true, form !== null);
|
|
21
|
+
return () => {
|
|
22
|
+
form?.removeAttribute('aria-busy');
|
|
23
|
+
if (id === current)
|
|
24
|
+
pending(false, false);
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
const here = () => location.pathname + location.search;
|
|
28
|
+
const display = (page, scroll, fresh, history) => nav.navigate(page.url, { history, info: { fondu: { page, scroll, fresh } } });
|
|
29
|
+
/**
|
|
30
|
+
* A document load: a POST's after the page it was sent from (`push`); a GET's in place of the entry it committed:
|
|
31
|
+
* `instead` when that entry was pushed. A document replacing it would take the entries before it, of this
|
|
32
|
+
* document, for its own (Chromium): Back would change the URL only. So back to the entry it was pushed from, then
|
|
33
|
+
* the document pushed from there.
|
|
34
|
+
*/
|
|
35
|
+
const documentLoad = async (url, history) => {
|
|
36
|
+
// http(s) only: a header's URL never runs as `javascript:` (an app's redirect to a URL it was given)
|
|
37
|
+
if (!isWebUrl(url))
|
|
38
|
+
return console.error(`fondu: not loading ${url}: not an http(s) URL`);
|
|
39
|
+
const info = { fondu: 'document' };
|
|
40
|
+
if (history === 'instead')
|
|
41
|
+
await nav.back({ info }).committed?.catch(noop);
|
|
42
|
+
nav.navigate(url, { history: history === 'replace' ? 'replace' : 'push', info });
|
|
43
|
+
};
|
|
44
|
+
/** the page a response is, or undefined when it's handled here (a new build, not a page) */
|
|
45
|
+
const read = async (response, url, history) => {
|
|
46
|
+
const post = history === 'push';
|
|
47
|
+
const to = response.headers.get('X-Fondu-Location');
|
|
48
|
+
if (response.status === 409 && to)
|
|
49
|
+
return void documentLoad(to, history);
|
|
50
|
+
// a redirect to a #fragment, followed here: fetch() would lose it
|
|
51
|
+
const redirect = response.headers.get('X-Fondu-Redirect');
|
|
52
|
+
if (redirect && isWebUrl(redirect))
|
|
53
|
+
return void nav.navigate(redirect, { history: post ? 'push' : 'replace' });
|
|
54
|
+
if (!response.headers.has('X-Fondu')) {
|
|
55
|
+
// a proxy's error page, a file: the URL as a document (a POST's redirect: its target); the answer to a POST
|
|
56
|
+
// itself can't be asked for again
|
|
57
|
+
if (!post || response.redirected)
|
|
58
|
+
return void documentLoad(url, history);
|
|
59
|
+
const html = await response.text();
|
|
60
|
+
document.open();
|
|
61
|
+
document.write(html);
|
|
62
|
+
document.close();
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const page = (await response.json());
|
|
66
|
+
if (version && page.version && page.version !== version)
|
|
67
|
+
return void documentLoad(page.url, history);
|
|
68
|
+
version = page.version;
|
|
69
|
+
return page;
|
|
70
|
+
};
|
|
71
|
+
const headers = () => ({ 'X-Fondu': 'true', ...(version && { 'X-Fondu-Version': version }) });
|
|
72
|
+
const failed = (url, history) => (error) => {
|
|
73
|
+
if (error.name !== 'AbortError')
|
|
74
|
+
void documentLoad(url, history); // offline: the browser says so
|
|
75
|
+
};
|
|
76
|
+
nav.addEventListener('navigate', (event) => {
|
|
77
|
+
const info = event.info;
|
|
78
|
+
const url = new URL(event.destination.url);
|
|
79
|
+
if (info?.fondu === 'document' || !event.canIntercept || event.hashChange)
|
|
80
|
+
return;
|
|
81
|
+
// `location.reload()` (Vite's full reload, an app's own): the document, as asked; `reload()` is fondu/client's
|
|
82
|
+
if (event.navigationType === 'reload' && info?.fondu !== 'reload')
|
|
83
|
+
return;
|
|
84
|
+
if (event.downloadRequest !== null || url.origin !== location.origin)
|
|
85
|
+
return;
|
|
86
|
+
submitting?.abort();
|
|
87
|
+
// a page already fetched (a form's answer, a redirect's target): shown by this navigation
|
|
88
|
+
if (typeof info?.fondu === 'object') {
|
|
89
|
+
const { page, scroll, fresh } = info.fondu;
|
|
90
|
+
event.intercept({
|
|
91
|
+
scroll: 'manual',
|
|
92
|
+
// the same page (a form back with its errors): the focus stays where it was, as the scroll position does
|
|
93
|
+
focusReset: fresh ? 'after-transition' : 'manual',
|
|
94
|
+
async handler() {
|
|
95
|
+
await show(page, fresh, () => event.signal.aborted);
|
|
96
|
+
if (scroll && !event.signal.aborted)
|
|
97
|
+
scrollAfter(event);
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
// a POST form: sent outside the navigation (no history entry for the POST), its answer shown by one
|
|
103
|
+
if (event.formData) {
|
|
104
|
+
event.preventDefault();
|
|
105
|
+
const done = begin(formOf(event));
|
|
106
|
+
const controller = (submitting = new AbortController());
|
|
107
|
+
fetch(url, {
|
|
108
|
+
method: 'POST',
|
|
109
|
+
body: event.formData,
|
|
110
|
+
headers: headers(),
|
|
111
|
+
signal: controller.signal,
|
|
112
|
+
})
|
|
113
|
+
.then(async (response) => {
|
|
114
|
+
const page = await read(response, response.url, 'push');
|
|
115
|
+
if (!page || controller.signal.aborted)
|
|
116
|
+
return;
|
|
117
|
+
// the same URL: in place, at the same scroll position; back with errors, the form and its values stay too
|
|
118
|
+
const same = page.url === here();
|
|
119
|
+
const errors = Object.keys(page.props.errors ?? {}).length > 0;
|
|
120
|
+
// pending until the page is on the screen
|
|
121
|
+
const shown = display(page, !same, !(same && errors), same ? 'replace' : 'push');
|
|
122
|
+
await shown.finished?.catch(noop);
|
|
123
|
+
})
|
|
124
|
+
.catch((error) => {
|
|
125
|
+
if (error.name !== 'AbortError')
|
|
126
|
+
throw error; // the form stays, to send again
|
|
127
|
+
})
|
|
128
|
+
.finally(done);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
event.intercept({
|
|
132
|
+
scroll: 'manual',
|
|
133
|
+
focusReset: event.navigationType === 'reload' ? 'manual' : 'after-transition',
|
|
134
|
+
async handler() {
|
|
135
|
+
const done = begin(formOf(event));
|
|
136
|
+
const pushed = event.navigationType === 'push' ? 'instead' : 'replace';
|
|
137
|
+
try {
|
|
138
|
+
// Back and Forward too: the server's page, as for a link (nothing kept in memory to go stale, as a
|
|
139
|
+
// private page after signing out); the scroll position is the browser's
|
|
140
|
+
const path = url.pathname + url.search;
|
|
141
|
+
preload(url.pathname);
|
|
142
|
+
const from = prerender ? pageDataPath(url.pathname) + url.search : url;
|
|
143
|
+
const response = await fetch(from, { headers: headers(), signal: event.signal });
|
|
144
|
+
const page = await read(response, url.href, pushed);
|
|
145
|
+
if (!page || event.signal.aborted)
|
|
146
|
+
return;
|
|
147
|
+
// redirected: the page at its own URL, in place of this entry
|
|
148
|
+
if (page.url !== path)
|
|
149
|
+
return void (await display(page, true, true, 'replace').finished?.catch(noop));
|
|
150
|
+
const reload = event.navigationType === 'reload';
|
|
151
|
+
// Back and Forward commit after the navigate event: scrolled before, the page would show at the top first
|
|
152
|
+
await nav.transition?.committed;
|
|
153
|
+
// superseded meanwhile (Back pressed before it was on the screen): neither shown nor scrolled
|
|
154
|
+
await show(page, !reload, () => event.signal.aborted);
|
|
155
|
+
if (!reload && !event.signal.aborted)
|
|
156
|
+
scrollAfter(event);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
failed(url.href, pushed)(error);
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
done();
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
const isWebUrl = (url) => {
|
|
169
|
+
try {
|
|
170
|
+
return /^https?:$/.test(new URL(url, location.href).protocol);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
/** the form a navigation sends (a POST's, a GET form's): the element it started from, a form or its submitter */
|
|
177
|
+
function formOf(event) {
|
|
178
|
+
const from = event.sourceElement;
|
|
179
|
+
if (from instanceof HTMLFormElement)
|
|
180
|
+
return from;
|
|
181
|
+
return from?.form ?? null;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* `href` loaded as a document. Every other navigation is the client's, `location.assign()` and `location.href = …`
|
|
185
|
+
* too: this is for what a page can't change in place (`<html lang>`: another language).
|
|
186
|
+
*/
|
|
187
|
+
export function loadDocument(href) {
|
|
188
|
+
const nav = navigation();
|
|
189
|
+
if (nav)
|
|
190
|
+
nav.navigate(href, { info: { fondu: 'document' } });
|
|
191
|
+
else
|
|
192
|
+
location.assign(href);
|
|
193
|
+
}
|
|
194
|
+
/** the page asked for again, its state and the scroll position kept */
|
|
195
|
+
export function again() {
|
|
196
|
+
const nav = navigation();
|
|
197
|
+
if (nav)
|
|
198
|
+
nav.reload({ info: { fondu: 'reload' } });
|
|
199
|
+
else
|
|
200
|
+
location.reload();
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Where a navigation leaves the page: Back and Forward where it was, a #fragment at its target, else the top (which
|
|
204
|
+
* `event.scroll()` does too since whatwg/html#11987; Chromium 141 doesn't yet).
|
|
205
|
+
*/
|
|
206
|
+
function scrollAfter(event) {
|
|
207
|
+
event.scroll();
|
|
208
|
+
if (event.navigationType !== 'traverse' && !new URL(event.destination.url).hash)
|
|
209
|
+
window.scrollTo(0, 0);
|
|
210
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** `fondu({ progress })`: the bar at the top of the page while a navigation or a form's submission is on its way */
|
|
2
|
+
export interface ProgressOptions {
|
|
3
|
+
/** how long a navigation runs before the bar shows, in ms (a quick one shows none); default 350 */
|
|
4
|
+
delay?: number;
|
|
5
|
+
/** the bar's color, any CSS color (`var(--brand)`); default the page's text color (`currentColor`) */
|
|
6
|
+
color?: string;
|
|
7
|
+
/** for forms' submissions too; default true (`false`: their buttons show it, with the form's `aria-busy`) */
|
|
8
|
+
forms?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
|
|
12
|
+
* transition, slower as it gets there), filled and faded out when it is done. Drawn with CSSOM styles (no stylesheet,
|
|
13
|
+
* nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree: `useNavigating()`
|
|
14
|
+
* is the app's way to say it in its own words. With reduced motion, a still bar.
|
|
15
|
+
*/
|
|
16
|
+
export declare function progressBar({ delay, color }: ProgressOptions, pending: () => boolean): () => void;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
|
|
3
|
+
* transition, slower as it gets there), filled and faded out when it is done. Drawn with CSSOM styles (no stylesheet,
|
|
4
|
+
* nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree: `useNavigating()`
|
|
5
|
+
* is the app's way to say it in its own words. With reduced motion, a still bar.
|
|
6
|
+
*/
|
|
7
|
+
export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
|
|
8
|
+
const still = matchMedia('(prefers-reduced-motion: reduce)');
|
|
9
|
+
let bar;
|
|
10
|
+
let wait;
|
|
11
|
+
const show = () => {
|
|
12
|
+
wait = undefined;
|
|
13
|
+
const el = (bar = document.createElement('div')); // a new one: the last may still be fading out
|
|
14
|
+
Object.assign(el.style, {
|
|
15
|
+
position: 'fixed',
|
|
16
|
+
inset: '0 0 auto',
|
|
17
|
+
zIndex: '2147483647',
|
|
18
|
+
height: '2px',
|
|
19
|
+
background: color,
|
|
20
|
+
transformOrigin: 'left',
|
|
21
|
+
transform: still.matches ? 'scaleX(1)' : 'scaleX(0)',
|
|
22
|
+
pointerEvents: 'none',
|
|
23
|
+
});
|
|
24
|
+
el.setAttribute('aria-hidden', 'true');
|
|
25
|
+
document.body.append(el);
|
|
26
|
+
if (still.matches)
|
|
27
|
+
return;
|
|
28
|
+
el.getBoundingClientRect(); // its start computed: the transition runs from 0
|
|
29
|
+
el.style.transition = 'transform 10s cubic-bezier(0.05, 0.7, 0.1, 1)';
|
|
30
|
+
el.style.transform = 'scaleX(0.95)';
|
|
31
|
+
};
|
|
32
|
+
const done = () => {
|
|
33
|
+
clearTimeout(wait);
|
|
34
|
+
wait = undefined;
|
|
35
|
+
const el = bar;
|
|
36
|
+
bar = undefined;
|
|
37
|
+
if (!el)
|
|
38
|
+
return;
|
|
39
|
+
// from where it is: a transition starts from the value on the screen
|
|
40
|
+
el.style.transition = 'transform 200ms ease-out, opacity 200ms 100ms';
|
|
41
|
+
el.style.transform = 'scaleX(1)';
|
|
42
|
+
el.style.opacity = '0';
|
|
43
|
+
setTimeout(() => el.remove(), 400);
|
|
44
|
+
};
|
|
45
|
+
return () => {
|
|
46
|
+
if (!pending())
|
|
47
|
+
return done();
|
|
48
|
+
if (wait === undefined && bar === undefined)
|
|
49
|
+
wait = setTimeout(show, delay);
|
|
50
|
+
};
|
|
51
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Routes } from './types.js';
|
|
|
2
2
|
/**
|
|
3
3
|
* Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
|
|
4
4
|
* one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
|
|
5
|
-
*
|
|
5
|
+
* A form's action too: `<form method="post" action={href('/logout')}>`.
|
|
6
6
|
*/
|
|
7
7
|
type Keys = keyof Routes & string;
|
|
8
8
|
type Actions = {
|
|
@@ -16,17 +16,6 @@ type Args<P extends string> = [ParamNames<P>] extends [never] ? [] : [params: {
|
|
|
16
16
|
[K in ParamNames<P>]: string | number;
|
|
17
17
|
}];
|
|
18
18
|
export declare function href<P extends Href>(path: P, ...[params]: Args<P>): string;
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
* object of another build reloads the page as a document, as the server's 409 would.
|
|
23
|
-
*/
|
|
24
|
-
export declare function prerendered(): void;
|
|
25
|
-
/**
|
|
26
|
-
* The build adds this to the client entry: in production, a GET visit answered with something that isn't an Inertia
|
|
27
|
-
* page (a proxy's 502, a CDN's 524) loads the URL as a document, as a site without Inertia would, instead of showing
|
|
28
|
-
* that answer in Inertia's dialog. Fondu's own answers to visits are pages, errors included. Other methods keep the
|
|
29
|
-
* dialog (loading the URL would drop the form); a visit's own `onHttpException` comes first.
|
|
30
|
-
*/
|
|
31
|
-
export declare function documentFallback(): void;
|
|
32
|
-
export {};
|
|
19
|
+
export { usePage, useNavigating, reload, __entry, renderPage, type Errors } from './client/app.js';
|
|
20
|
+
export { loadDocument, type Page } from './client/navigation.js';
|
|
21
|
+
export type { ProgressOptions } from './client/progress.js';
|
package/dist/client.js
CHANGED
|
@@ -1,50 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { fillPattern, pageDataPath } from './paths.js';
|
|
1
|
+
import { fillPattern } from './paths.js';
|
|
3
2
|
export function href(path, ...[params]) {
|
|
4
3
|
return fillPattern(path, params);
|
|
5
4
|
}
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
* `/_fondu/pages/<path>.json`, a static file for a prerendered page, the server's answer for any other. A page
|
|
9
|
-
* object of another build reloads the page as a document, as the server's 409 would.
|
|
10
|
-
*/
|
|
11
|
-
export function prerendered() {
|
|
12
|
-
const loaded = document.querySelector('script[data-page]')?.textContent;
|
|
13
|
-
const version = loaded ? JSON.parse(loaded).version : null;
|
|
14
|
-
http.onRequest((config) => {
|
|
15
|
-
const url = new URL(config.url, location.href);
|
|
16
|
-
if (config.method !== 'get' || !config.headers?.['X-Inertia'] || url.origin !== location.origin)
|
|
17
|
-
return config;
|
|
18
|
-
return { ...config, url: pageDataPath(url.pathname) + url.search };
|
|
19
|
-
});
|
|
20
|
-
http.onResponse((response) => {
|
|
21
|
-
if (!version || response.status !== 200 || !response.headers['x-inertia'])
|
|
22
|
-
return response;
|
|
23
|
-
const page = JSON.parse(response.data);
|
|
24
|
-
if (!page.version || page.version === version)
|
|
25
|
-
return response;
|
|
26
|
-
return {
|
|
27
|
-
status: 409,
|
|
28
|
-
data: '',
|
|
29
|
-
headers: { 'x-inertia-location': page.url, 'x-inertia-version': page.version },
|
|
30
|
-
};
|
|
31
|
-
});
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* The build adds this to the client entry: in production, a GET visit answered with something that isn't an Inertia
|
|
35
|
-
* page (a proxy's 502, a CDN's 524) loads the URL as a document, as a site without Inertia would, instead of showing
|
|
36
|
-
* that answer in Inertia's dialog. Fondu's own answers to visits are pages, errors included. Other methods keep the
|
|
37
|
-
* dialog (loading the URL would drop the form); a visit's own `onHttpException` comes first.
|
|
38
|
-
*/
|
|
39
|
-
export function documentFallback() {
|
|
40
|
-
let visit;
|
|
41
|
-
router.on('start', (event) => {
|
|
42
|
-
visit = event.detail.visit;
|
|
43
|
-
});
|
|
44
|
-
router.on('httpException', (event) => {
|
|
45
|
-
if (event.detail.response.headers['x-inertia'] || visit?.method !== 'get')
|
|
46
|
-
return;
|
|
47
|
-
event.preventDefault();
|
|
48
|
-
window.location.href = visit.url.href;
|
|
49
|
-
});
|
|
50
|
-
}
|
|
5
|
+
export { usePage, useNavigating, reload, __entry, renderPage } from './client/app.js';
|
|
6
|
+
export { loadDocument } from './client/navigation.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
export { defineHandler, defineMiddleware } from './server/handler.js';
|
|
2
|
-
export { render, share,
|
|
3
|
-
export { back
|
|
4
|
-
export {
|
|
5
|
-
export { flash, clearHistory } from './server/flash.js';
|
|
2
|
+
export { render, share, type RenderOptions } from './server/protocol.js';
|
|
3
|
+
export { back } from './server/http.js';
|
|
4
|
+
export { flash } from './server/flash.js';
|
|
6
5
|
export { ValidationError, type StandardSchemaV1 } from './server/validate.js';
|
|
7
6
|
export { withoutSsr, type DocumentParts, type DocumentTemplate } from './server/document.js';
|
|
8
7
|
export type { Register } from './types.js';
|