fondu 0.11.1 → 0.12.1

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.
@@ -18,6 +18,19 @@ export declare function __entry(pageModules: Record<string, Loader>, layouts: Re
18
18
  * listed values are the server's), so the page shown is the one the server says.
19
19
  */
20
20
  export declare function pageAt(pathname: string): string | undefined;
21
+ /** a navigation on its way, or none: `useNavigation()` */
22
+ export type Navigation = {
23
+ state: 'idle';
24
+ to: null;
25
+ form: null;
26
+ } | {
27
+ /** `submitting`: a form's POST; `loading`: any other (a link, a GET form, `navigate()`, `reload()`) */
28
+ state: 'loading' | 'submitting';
29
+ /** where to: a path, its query and fragment (`/users/7?tab=posts`) */
30
+ to: string;
31
+ /** the form being sent (a GET form's too), else null */
32
+ form: HTMLFormElement | null;
33
+ };
21
34
  /** @internal the server render of a page: the head tags its components render (`<title>`…), and `<div id="app">` */
22
35
  export declare function renderPage(page: Page, renderToString: (element: ReactElement) => string): Promise<{
23
36
  head: string;
@@ -34,8 +47,11 @@ export declare function usePage<P = Shared>(): {
34
47
  url: string;
35
48
  flash: Partial<Flash>;
36
49
  };
37
- /** true while a navigation or a form's submission is on its way */
38
- export declare function useNavigating(): boolean;
50
+ /**
51
+ * The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
52
+ * from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
53
+ */
54
+ export declare function useNavigation(): Navigation;
39
55
  /** this page's props asked for again: the page keeps its state and the scroll position */
40
56
  export declare function reload(): void;
41
57
  export {};
@@ -103,17 +103,17 @@ export function pageAt(pathname) {
103
103
  }
104
104
  return best?.id;
105
105
  }
106
- // ---- pending navigations, for useNavigating()
107
- let navigating = false;
108
- let submitting = false;
106
+ const IDLE = { state: 'idle', to: null, form: null };
107
+ let navigation = IDLE;
109
108
  const listeners = new Set();
110
109
  const subscribe = (listener) => {
111
110
  listeners.add(listener);
112
111
  return () => listeners.delete(listener);
113
112
  };
114
- function setNavigating(value, form) {
115
- navigating = value;
116
- submitting = form;
113
+ function setNavigation(next) {
114
+ navigation = next
115
+ ? { state: next.post ? 'submitting' : 'loading', to: next.to, form: next.form }
116
+ : IDLE;
117
117
  for (const l of listeners)
118
118
  l();
119
119
  }
@@ -122,7 +122,7 @@ function setNavigating(value, form) {
122
122
  function start(settings) {
123
123
  const progress = settings.progress;
124
124
  if (progress)
125
- subscribe(progressBar(progress, () => navigating && (progress.forms !== false || !submitting)));
125
+ subscribe(progressBar(progress, () => navigation.state !== 'idle' && (progress.forms !== false || navigation.form === null)));
126
126
  const data = document.querySelector('script[data-page="app"]')?.textContent;
127
127
  const root = document.getElementById('app');
128
128
  if (!data || !root)
@@ -142,7 +142,7 @@ function start(settings) {
142
142
  startNavigation({
143
143
  initial,
144
144
  prerender: settings.prerender,
145
- pending: setNavigating,
145
+ pending: setNavigation,
146
146
  preload(pathname) {
147
147
  const page = pageAt(pathname);
148
148
  if (page)
@@ -179,9 +179,12 @@ export function usePage() {
179
179
  throw new Error('fondu: usePage() is for components of a page');
180
180
  return page;
181
181
  }
182
- /** true while a navigation or a form's submission is on its way */
183
- export function useNavigating() {
184
- return useSyncExternalStore(subscribe, () => navigating, () => false);
182
+ /**
183
+ * The navigation on its way: `state` is `idle`, `loading` (a link, `navigate()`…) or `submitting` (a form's POST),
184
+ * from the click or the submit until the next page is on the screen; `to`, where to; `form`, the form being sent.
185
+ */
186
+ export function useNavigation() {
187
+ return useSyncExternalStore(subscribe, () => navigation, () => IDLE);
185
188
  }
186
189
  /** this page's props asked for again: the page keeps its state and the scroll position */
187
190
  export function reload() {
@@ -0,0 +1,43 @@
1
+ import { type ChangeEvent, type FocusEvent, type FormEvent } from 'react';
2
+ import { type Issue } from '../form.js';
3
+ import { type Errors } from './app.js';
4
+ /** A Standard Schema (zod, valibot, arktype…), the part `useForm` uses */
5
+ interface Schema {
6
+ readonly '~standard': {
7
+ readonly validate: (value: unknown) => StandardResult | Promise<StandardResult>;
8
+ };
9
+ }
10
+ type StandardResult = {
11
+ readonly issues?: ReadonlyArray<Issue> | undefined;
12
+ };
13
+ /**
14
+ * A plain `<form>`, checked in the browser by the schema the server checks it with (any Standard Schema), its fields
15
+ * read as the server reads them (`tags[]`, `user[name]`). Spread `form` on the `<form>`, `field(name)` on each field:
16
+ *
17
+ * - on submit, an invalid form isn't sent, and its first field to fix gets the focus; a valid one is sent by Fondu's
18
+ * client. Back with the server's errors, the first field to fix gets the focus too
19
+ * - a field is checked as it is left for another with something typed, and again as it changes while it is wrong,
20
+ * so a fixed one loses its message (not as it is left for the submit button: the message would move it from under
21
+ * the pointer)
22
+ * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
23
+ * by the server's keys (`email`, `user.name`)
24
+ * - `submitting`: this form is being sent
25
+ *
26
+ * Without a schema: the server's errors and `submitting` only. Without JavaScript, the form is sent as it is, and the
27
+ * server's check answers.
28
+ */
29
+ export declare function useForm(schema?: Schema): {
30
+ form: {
31
+ ref: (form: HTMLFormElement | null) => void;
32
+ onSubmit: (event: FormEvent<HTMLFormElement>) => void;
33
+ };
34
+ field: (name: string) => {
35
+ name: string;
36
+ 'aria-invalid': true | undefined;
37
+ onBlur: (event: FocusEvent<Element>) => void;
38
+ onChange: (event: ChangeEvent<Element>) => void;
39
+ };
40
+ errors: Errors;
41
+ submitting: boolean;
42
+ };
43
+ export {};
@@ -0,0 +1,206 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react';
2
+ import { fieldKey, formObject, issueErrors, MalformedForm } from '../form.js';
3
+ import { useNavigation, usePage } from './app.js';
4
+ /** a form's fields as the server reads them: its body for a POST (`withValidator({ body })`), its query for a GET */
5
+ function fieldsOf(form, submitter) {
6
+ const data = new FormData(form, submitter ?? undefined);
7
+ // as the browser sends them: line breaks as CRLF (a <textarea>'s)
8
+ const crlf = (text) => text.replace(/\r\n|\r|\n/g, '\r\n');
9
+ const entries = [...data].map(([k, v]) => [crlf(k), typeof v === 'string' ? crlf(v) : v]);
10
+ const method = (submitter?.getAttribute('formmethod') ??
11
+ form.getAttribute('method') ??
12
+ 'get').toLowerCase();
13
+ if (method === 'post')
14
+ return formObject(entries);
15
+ // a query, as Hono's `c.req.query()`: each name's first value, a file by its name
16
+ const query = Object.create(null);
17
+ for (const [k, v] of entries)
18
+ query[k] ??= typeof v === 'string' ? v : v.name;
19
+ return query;
20
+ }
21
+ /** the schema's errors for these fields; none for fields that can't be one object (the server answers those) */
22
+ function check(schema, value) {
23
+ let fields;
24
+ try {
25
+ fields = value();
26
+ }
27
+ catch (error) {
28
+ if (error instanceof MalformedForm)
29
+ return {};
30
+ throw error;
31
+ }
32
+ const result = schema['~standard'].validate(fields);
33
+ const errors = (r) => (r.issues ? issueErrors(r.issues) : {});
34
+ return result instanceof Promise ? result.then(errors) : errors(result);
35
+ }
36
+ /** a field's errors: its own, and those inside it (`tags` has `tags.0`'s) */
37
+ const within = (key, errorKey) => errorKey === key || (key !== '' && errorKey.startsWith(`${key}.`));
38
+ /**
39
+ * A plain `<form>`, checked in the browser by the schema the server checks it with (any Standard Schema), its fields
40
+ * read as the server reads them (`tags[]`, `user[name]`). Spread `form` on the `<form>`, `field(name)` on each field:
41
+ *
42
+ * - on submit, an invalid form isn't sent, and its first field to fix gets the focus; a valid one is sent by Fondu's
43
+ * client. Back with the server's errors, the first field to fix gets the focus too
44
+ * - a field is checked as it is left for another with something typed, and again as it changes while it is wrong,
45
+ * so a fixed one loses its message (not as it is left for the submit button: the message would move it from under
46
+ * the pointer)
47
+ * - `errors`: the server's (the page's `errors` prop), each until its field is checked again, and the browser's;
48
+ * by the server's keys (`email`, `user.name`)
49
+ * - `submitting`: this form is being sent
50
+ *
51
+ * Without a schema: the server's errors and `submitting` only. Without JavaScript, the form is sent as it is, and the
52
+ * server's check answers.
53
+ */
54
+ export function useForm(schema) {
55
+ const server = usePage().props.errors;
56
+ const navigation = useNavigation();
57
+ const [element, setElement] = useState(null);
58
+ // the browser's messages (undefined: checked, fine), for these server errors: a new answer starts over
59
+ const [checked, setChecked] = useState({
60
+ for: server,
61
+ own: {},
62
+ });
63
+ // the server's errors on the screen, for a check that ends after a new answer
64
+ const latest = useRef(server);
65
+ useLayoutEffect(() => {
66
+ latest.current = server;
67
+ }, [server]);
68
+ const own = checked.for === server ? checked.own : {};
69
+ const errors = Object.create(null);
70
+ // own keys only: a field may be named like what objects inherit (`toString`)
71
+ for (const [k, m] of Object.entries(server))
72
+ if (!Object.hasOwn(own, k))
73
+ errors[k] = m;
74
+ for (const [k, m] of Object.entries(own))
75
+ if (m)
76
+ errors[k] = m;
77
+ const errorOf = (key) => Object.keys(errors).find((k) => within(key, k));
78
+ const dirty = useRef(new Set());
79
+ const runs = useRef(new Map());
80
+ const passed = useRef(false);
81
+ /** what a check found, for the fields it covers (`key`: one field and those inside it; else all) */
82
+ const apply = (found, from, key) => {
83
+ if (latest.current !== from)
84
+ return; // a new answer of the server since
85
+ setChecked((now) => {
86
+ const before = now.for === from ? now.own : {};
87
+ const next = { ...before };
88
+ const covered = (k) => key === undefined || within(key, k);
89
+ // a field's check settles the server's error too; the whole form's, what it can say (not a taken address)
90
+ for (const k of [...Object.keys(before), ...(key === undefined ? [] : Object.keys(from))])
91
+ if (covered(k))
92
+ next[k] = undefined;
93
+ for (const [k, m] of Object.entries(found))
94
+ if (covered(k))
95
+ next[k] = m;
96
+ return { for: from, own: next };
97
+ });
98
+ };
99
+ const focusFirst = (form, found) => {
100
+ const keys = Object.keys(found).filter((k) => k !== '');
101
+ for (const el of form.elements)
102
+ if (el instanceof HTMLElement &&
103
+ 'name' in el &&
104
+ typeof el.name === 'string' &&
105
+ el.name &&
106
+ keys.some((k) => within(fieldKey(el.name), k)))
107
+ return el.focus();
108
+ };
109
+ const validates = schema !== undefined;
110
+ const ref = useCallback((form) => {
111
+ setElement(form);
112
+ // its messages, in the page's language, not the browser's (without JavaScript, the browser's checks stay)
113
+ if (form && validates)
114
+ form.noValidate = true;
115
+ }, [validates]);
116
+ const submitting = navigation.form !== null && navigation.form === element;
117
+ // back with the server's errors: the first field to fix gets the focus
118
+ const sent = useRef(false);
119
+ useEffect(() => {
120
+ if (submitting) {
121
+ sent.current = true;
122
+ return;
123
+ }
124
+ if (!sent.current)
125
+ return;
126
+ sent.current = false;
127
+ if (element && Object.keys(server).length)
128
+ focusFirst(element, server);
129
+ }, [submitting, server, element]);
130
+ const checkField = (form, key) => {
131
+ if (!schema)
132
+ return;
133
+ const run = (runs.current.get(key) ?? 0) + 1;
134
+ runs.current.set(key, run);
135
+ const from = server;
136
+ const done = (found) => {
137
+ if (runs.current.get(key) === run)
138
+ apply(found, from, key);
139
+ };
140
+ const found = check(schema, () => fieldsOf(form));
141
+ if (found instanceof Promise)
142
+ void found.then(done);
143
+ else
144
+ done(found);
145
+ };
146
+ return {
147
+ form: {
148
+ ref,
149
+ onSubmit(event) {
150
+ if (!schema)
151
+ return;
152
+ if (passed.current) {
153
+ passed.current = false; // checked already: sent
154
+ return;
155
+ }
156
+ const form = event.currentTarget;
157
+ const submitter = event.nativeEvent.submitter;
158
+ const from = server;
159
+ const found = check(schema, () => fieldsOf(form, submitter));
160
+ const answer = (found) => {
161
+ apply(found, from);
162
+ if (Object.keys(found).length)
163
+ focusFirst(form, found);
164
+ };
165
+ if (!(found instanceof Promise)) {
166
+ if (Object.keys(found).length)
167
+ event.preventDefault();
168
+ return answer(found);
169
+ }
170
+ // an async schema: sent again once it says yes
171
+ event.preventDefault();
172
+ void found.then((found) => {
173
+ answer(found);
174
+ if (Object.keys(found).length || latest.current !== from)
175
+ return;
176
+ passed.current = true;
177
+ form.requestSubmit(submitter && 'form' in submitter ? submitter : null);
178
+ });
179
+ },
180
+ },
181
+ field: (name) => {
182
+ const key = fieldKey(name);
183
+ return {
184
+ name,
185
+ 'aria-invalid': errorOf(key) !== undefined || undefined,
186
+ onBlur(event) {
187
+ // left for another field: not for the submit button, nor another window
188
+ const to = event.relatedTarget;
189
+ if (!(to instanceof HTMLElement) || to.type === 'submit')
190
+ return;
191
+ const form = event.currentTarget.form ?? element;
192
+ if (form && dirty.current.has(key))
193
+ checkField(form, key);
194
+ },
195
+ onChange(event) {
196
+ dirty.current.add(key);
197
+ const form = event.currentTarget.form ?? element;
198
+ if (form && errorOf(key) !== undefined)
199
+ checkField(form, key);
200
+ },
201
+ };
202
+ },
203
+ errors,
204
+ submitting,
205
+ };
206
+ }
@@ -15,8 +15,12 @@ interface Options {
15
15
  show: (page: Page, fresh: boolean, stale: () => boolean) => Promise<void>;
16
16
  /** `fondu({ prerender: true })`: GET navigations read `/_fondu/pages/<path>.json` */
17
17
  prerender: boolean;
18
- /** a navigation started (true; `form`: a form's submission) or ended (false) */
19
- pending: (pending: boolean, form: boolean) => void;
18
+ /** a navigation started (to `to`: a path, its query and fragment; `form`: a form's submission) or ended (null) */
19
+ pending: (navigation: {
20
+ to: string;
21
+ form: HTMLFormElement | null;
22
+ post: boolean;
23
+ } | null) => void;
20
24
  /** a GET navigation to `pathname` started: its page's modules may load with its data */
21
25
  preload: (pathname: string) => void;
22
26
  /** a URL path is one of the app's pages (by the route files' patterns): its links are the client's */
@@ -35,6 +39,13 @@ export declare function startNavigation({ initial, show, prerender, pending, pre
35
39
  * can't change in place (`<html lang>`: another language).
36
40
  */
37
41
  export declare function loadDocument(href: string): void;
42
+ /**
43
+ * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
44
+ * `replace`), anything else as a document
45
+ */
46
+ export declare function navigate(href: string, { replace }?: {
47
+ replace?: boolean;
48
+ }): void;
38
49
  /** the page asked for again, its state and the scroll position kept */
39
50
  export declare function again(): void;
40
51
  export {};
@@ -1,5 +1,7 @@
1
1
  import { pageDataPath, SCROLL_KEY, SCROLL_STORAGE } from '../paths.js';
2
2
  let visit;
3
+ /** a URL path is one of the app's pages (the client's, once it has started) */
4
+ let isAppPage;
3
5
  /**
4
6
  * Same-origin links and forms, Back and Forward, through the History API (as Void's client, MIT): the page fetched
5
7
  * as JSON, its URL in the history, the page shown in place, then the scroll position (Fondu's own, per history entry:
@@ -32,6 +34,7 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
32
34
  else
33
35
  location.assign(url);
34
36
  };
37
+ isAppPage = isPage;
35
38
  visit = (href, options) => {
36
39
  current?.abort();
37
40
  const controller = (current = new AbortController());
@@ -46,14 +49,14 @@ export function startNavigation({ initial, show, prerender, pending, preload, is
46
49
  // a kept page is on the screen at once: the server's comes quietly, no pending state (the navigation it
47
50
  // interrupted, aborted, ends here)
48
51
  const shown = options.kept;
49
- // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigating()), and for
52
+ // the form being sent is aria-busy: for its submit buttons' pending state (CSS, or useNavigation()), and for
50
53
  // assistive technology
51
54
  form?.setAttribute('aria-busy', 'true');
52
- pending(!shown, form !== null);
55
+ pending(shown ? null : { to: url.pathname + url.search + url.hash, form, post });
53
56
  const done = () => {
54
57
  form?.removeAttribute('aria-busy');
55
58
  if (!shown && current === controller)
56
- pending(false, false);
59
+ pending(null);
57
60
  };
58
61
  if (!post)
59
62
  preload(url.pathname);
@@ -431,6 +434,17 @@ function fileName(disposition) {
431
434
  export function loadDocument(href) {
432
435
  location.assign(href);
433
436
  }
437
+ /**
438
+ * `href` visited as a link to it would be: a page of the app in place (a new history entry, or this one's with
439
+ * `replace`), anything else as a document
440
+ */
441
+ export function navigate(href, { replace = false } = {}) {
442
+ const url = new URL(href, location.href);
443
+ const here = url.pathname + url.search === location.pathname + location.search;
444
+ if (!visit || url.origin !== location.origin || !isAppPage?.(url.pathname) || (here && url.hash))
445
+ return replace ? location.replace(url.href) : location.assign(url.href); // a #fragment of this page: the browser's
446
+ visit(url.href, { history: replace || url.href === location.href ? 'replace' : 'push' });
447
+ }
434
448
  /** the page asked for again, its state and the scroll position kept */
435
449
  export function again() {
436
450
  if (visit)
@@ -11,6 +11,6 @@ export interface ProgressOptions {
11
11
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
12
12
  * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
13
13
  * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
14
- * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
14
+ * `useNavigation()` is the app's way to say it in its own words. With reduced motion, a still bar.
15
15
  */
16
16
  export declare function progressBar({ delay, color }: ProgressOptions, pending: () => boolean): () => void;
@@ -2,7 +2,7 @@
2
2
  * The bar: shown once a navigation has run for `delay`, growing towards the end while it runs (one long CSS
3
3
  * transition, slower as it gets there), filled, then faded out, when it is done. Drawn with CSSOM styles (no
4
4
  * stylesheet, nothing for a Content Security Policy to refuse), above the page, out of the accessibility tree:
5
- * `useNavigating()` is the app's way to say it in its own words. With reduced motion, a still bar.
5
+ * `useNavigation()` is the app's way to say it in its own words. With reduced motion, a still bar.
6
6
  */
7
7
  export function progressBar({ delay = 350, color = 'currentColor' }, pending) {
8
8
  const still = matchMedia('(prefers-reduced-motion: reduce)');
package/dist/client.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import type { schemasOf } from './server/handler.js';
1
2
  import type { Routes } from './types.js';
2
3
  /**
3
4
  * Typed URLs from `app/routes/` (as React Router's `href`): `href('/users/:id', { id })` → `'/users/7'`;
4
5
  * one of a file's `actions`: `href('/users/:id?delete', { id })`. Only patterns that exist; params are required.
5
- * A form's action too: `<form method="post" action={href('/logout')}>`.
6
+ * A form's action too: `<form method="post" action={href('/logout')}>`. With `query` (typed by the route's
7
+ * `withValidator({ query })`, if it has one) and `hash`: `href('/search', { query: { q }, hash: 'results' })`.
6
8
  */
7
9
  type Keys = keyof Routes & string;
8
10
  type Actions = {
@@ -12,10 +14,42 @@ type Actions = {
12
14
  }[Keys];
13
15
  export type Href = [Keys] extends [never] ? string : Keys | Actions;
14
16
  type ParamNames<P extends string> = P extends `${string}:${infer Name}{${string}}${infer Rest}` ? Name | ParamNames<Rest> : P extends `${string}:${infer Name}/${infer Rest}` ? Name | ParamNames<`/${Rest}`> : P extends `${string}:${infer Name}?${string}` ? Name : P extends `${string}:${infer Name}` ? Name : never;
15
- type Args<P extends string> = [ParamNames<P>] extends [never] ? [] : [params: {
17
+ /** the handlers answering a GET of the URL (its page's `loader`, a `.ts` file's `GET`), or the action's */
18
+ type HandlersOf<P extends string> = P extends `${infer K}?${infer A}` ? K extends Keys ? Routes[K] extends {
19
+ actions: infer As;
20
+ } ? As[A & keyof As] : never : never : P extends Keys ? Routes[P] extends {
21
+ loader: infer L;
22
+ } ? L : Routes[P] extends {
23
+ GET: infer G;
24
+ } ? G : never : never;
25
+ /** a query value: what its schema takes (`unknown`, as a coercing schema's input: any) */
26
+ type QueryValue = string | number | boolean | null | undefined;
27
+ type QueryOf<P extends string> = HandlersOf<P> extends {
28
+ readonly [schemasOf]?: infer S;
29
+ } ? S extends {
30
+ query: {
31
+ '~standard': {
32
+ types?: infer T;
33
+ };
34
+ };
35
+ } ? NonNullable<T> extends {
36
+ input: infer I extends object;
37
+ } ? {
38
+ [K in keyof I]: unknown extends I[K] ? QueryValue : I[K];
39
+ } : Record<string, QueryValue> : Record<string, QueryValue> : Record<string, QueryValue>;
40
+ /** `query` is required when its schema requires a field */
41
+ type Extra<P extends string> = {
42
+ hash?: string;
43
+ } & ({} extends QueryOf<P> ? {
44
+ query?: QueryOf<P>;
45
+ } : {
46
+ query: QueryOf<P>;
47
+ });
48
+ type Args<P extends string> = [ParamNames<P>] extends [never] ? {} extends QueryOf<P> ? [options?: Extra<P>] : [options: Extra<P>] : [params: {
16
49
  [K in ParamNames<P>]: string | number;
17
- }];
18
- export declare function href<P extends Href>(path: P, ...[params]: Args<P>): string;
19
- export { usePage, useNavigating, reload, __entry, renderPage, type Errors } from './client/app.js';
20
- export { loadDocument, type Page } from './client/navigation.js';
50
+ } & Extra<P>];
51
+ export declare function href<P extends Href>(path: P, ...[options]: Args<P>): string;
52
+ export { usePage, useNavigation, reload, __entry, renderPage, type Errors, type Navigation, } from './client/app.js';
53
+ export { useForm } from './client/form.js';
54
+ export { loadDocument, navigate, type Page } from './client/navigation.js';
21
55
  export type { ProgressOptions } from './client/progress.js';
package/dist/client.js CHANGED
@@ -1,6 +1,19 @@
1
1
  import { fillPattern } from './paths.js';
2
- export function href(path, ...[params]) {
3
- return fillPattern(path, params);
2
+ export function href(path, ...[options]) {
3
+ const { query, hash, ...params } = (options ?? {});
4
+ let url = fillPattern(path, params);
5
+ const search = new URLSearchParams();
6
+ for (const [name, value] of Object.entries(query ?? {}))
7
+ for (const v of [value].flat())
8
+ if (v !== undefined && v !== null)
9
+ search.append(name, String(v));
10
+ const qs = search.toString();
11
+ if (qs)
12
+ url += (url.includes('?') ? '&' : '?') + qs;
13
+ if (hash)
14
+ url += `#${encodeURI(hash)}`;
15
+ return url;
4
16
  }
5
- export { usePage, useNavigating, reload, __entry, renderPage } from './client/app.js';
6
- export { loadDocument } from './client/navigation.js';
17
+ export { usePage, useNavigation, reload, __entry, renderPage, } from './client/app.js';
18
+ export { useForm } from './client/form.js';
19
+ export { loadDocument, navigate } from './client/navigation.js';
package/dist/form.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Form fields as one object, the same in the server (`readBody`, `withValidator`) and in the browser (`useForm`): a
3
+ * schema checked in the browser sees what the server's will.
4
+ */
5
+ /** a body that can't be one object: a 400 on the server */
6
+ export declare class MalformedForm extends Error {
7
+ }
8
+ type Entry = [string, FormDataEntryValue];
9
+ /**
10
+ * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
11
+ * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
12
+ * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
13
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
14
+ */
15
+ export declare function formObject(entries: Iterable<Entry>): Record<string, unknown>;
16
+ /** A Standard Schema's issue, the part used here */
17
+ export interface Issue {
18
+ readonly message: string;
19
+ readonly path?: ReadonlyArray<PropertyKey | {
20
+ readonly key: PropertyKey;
21
+ }> | undefined;
22
+ }
23
+ /** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
24
+ export declare const issueKey: (path: Issue['path']) => string;
25
+ /** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
26
+ export declare const fieldKey: (name: string) => string;
27
+ /** each field's first message (no prototype: a field named `toString` is a field like any other) */
28
+ export declare function issueErrors(issues: ReadonlyArray<Issue>): Record<string, string>;
29
+ export {};
package/dist/form.js ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Form fields as one object, the same in the server (`readBody`, `withValidator`) and in the browser (`useForm`): a
3
+ * schema checked in the browser sees what the server's will.
4
+ */
5
+ /** how deep form field names nest (`a[b][c]`: 3) */
6
+ const DEPTH = 32;
7
+ /** a body that can't be one object: a 400 on the server */
8
+ export class MalformedForm extends Error {
9
+ }
10
+ /**
11
+ * Form fields with PHP-style names, as forms write them (`notify[]`, `user[name]`); files are `File`s, empty file
12
+ * inputs are left out. A name given again is a list (`a=1&a=2`, `a[b]=1&a[b]=2`); `[]` is the index after the
13
+ * highest one so far. Names that would change the object itself (`__proto__`…) are ignored. Throws `MalformedForm`
14
+ * for fields that can't be one object (`a=1&a[b]=2`, names nested deeper than 32).
15
+ */
16
+ export function formObject(entries) {
17
+ const body = Object.create(null);
18
+ // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
19
+ const next = new WeakMap();
20
+ const isObject = (v) => typeof v === 'object' && !isFile(v) && !Array.isArray(v);
21
+ for (const [key, value] of entries) {
22
+ if (typeof value !== 'string' && value.size === 0 && value.name === '')
23
+ continue;
24
+ const path = key.replace(/\]/g, '').split('[');
25
+ if (path.length > DEPTH)
26
+ throw new MalformedForm(`a field name nests deeper than ${DEPTH}`);
27
+ if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
28
+ continue;
29
+ let target = body;
30
+ path.forEach((segment, i) => {
31
+ const name = segment === '' ? String(next.get(target) ?? 0) : segment;
32
+ if (/^\d+$/.test(name))
33
+ next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
34
+ const has = Object.hasOwn(target, name);
35
+ if (i === path.length - 1) {
36
+ if (has && isObject(target[name]))
37
+ throw new MalformedForm(`\`${key}\` is both a value and an object`);
38
+ // given again: a list, added to in place (a copy for each value is quadratic: a small body, much work)
39
+ const previous = target[name];
40
+ if (Array.isArray(previous))
41
+ previous.push(value);
42
+ else
43
+ target[name] = has ? [previous, value] : value;
44
+ }
45
+ else {
46
+ if (!has)
47
+ target[name] = Object.create(null);
48
+ else if (!isObject(target[name]))
49
+ throw new MalformedForm(`\`${key}\` is both a value and an object`);
50
+ target = target[name];
51
+ }
52
+ });
53
+ }
54
+ return arrays(body);
55
+ }
56
+ const isFile = (v) => typeof File !== 'undefined' && v instanceof File;
57
+ /** objects whose keys are 0..n-1 become arrays */
58
+ const arrays = (value) => {
59
+ if (typeof value !== 'object' || value === null || isFile(value) || Array.isArray(value))
60
+ return value;
61
+ const entries = Object.entries(value).map(([k, v]) => [k, arrays(v)]);
62
+ const isList = entries.length > 0 && entries.every(([k], i) => k === String(i));
63
+ return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
64
+ };
65
+ /** an issue's field: its path joined with dots (`user.name`, `tags.0`); the form's own issues are `''` */
66
+ export const issueKey = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
67
+ /** a field name's key in the errors: `user[name]` → `user.name`, `tags[]` → `tags` */
68
+ export const fieldKey = (name) => name.replace(/\]/g, '').split('[').filter(Boolean).join('.');
69
+ /** each field's first message (no prototype: a field named `toString` is a field like any other) */
70
+ export function issueErrors(issues) {
71
+ const errors = Object.create(null);
72
+ for (const issue of issues)
73
+ errors[issueKey(issue.path)] ??= issue.message;
74
+ return errors;
75
+ }
package/dist/paths.js CHANGED
@@ -19,6 +19,10 @@ export function routePatterns(file) {
19
19
  throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
20
20
  if (optional.length > 1)
21
21
  throw new Error(`fondu: routes/${file} has ${optional.length} optional segments; one at most`);
22
+ // href()'s options, next to the params
23
+ const reserved = segments.find((s) => /^\[{1,2}(?:\.\.\.)?(?:query|hash)\]{1,2}$/.test(s));
24
+ if (reserved)
25
+ throw new Error(`fondu: routes/${file}: a param can't be named ${reserved.replace(/[[\].]/g, '')} (href()'s query and hash); rename it`);
22
26
  const pattern = (withOptional) => '/' +
23
27
  segments
24
28
  .filter((s) => withOptional || !optional.includes(s))
@@ -2,12 +2,18 @@ import type { Context, Handler, MiddlewareHandler } from 'hono';
2
2
  import { type Input, type Schemas } from './validate.js';
3
3
  type Final<S extends Schemas> = (c: Context, input: Input<S>) => Response | Promise<Response>;
4
4
  type Handlers = Array<Handler | MiddlewareHandler>;
5
+ /** @internal a type only, never a value: the schemas a `withValidator` handler checks, for `href()`'s `query` */
6
+ export declare const schemasOf: unique symbol;
7
+ /** handlers of `withValidator`: with their schemas, in the type only (`href()` types the query by them) */
8
+ export type Validated<S extends Schemas> = Handlers & {
9
+ readonly [schemasOf]?: S;
10
+ };
5
11
  /** overloads, as Hono's `createHandlers` has them: the last handler's parameters are typed reliably */
6
12
  interface WithInput<S extends Schemas> {
7
- (handler: Final<S>): Handlers;
8
- (m1: MiddlewareHandler, handler: Final<S>): Handlers;
9
- (m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S>): Handlers;
10
- (m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S>): Handlers;
13
+ (handler: Final<S>): Validated<S>;
14
+ (m1: MiddlewareHandler, handler: Final<S>): Validated<S>;
15
+ (m1: MiddlewareHandler, m2: MiddlewareHandler, handler: Final<S>): Validated<S>;
16
+ (m1: MiddlewareHandler, m2: MiddlewareHandler, m3: MiddlewareHandler, handler: Final<S>): Validated<S>;
11
17
  }
12
18
  /**
13
19
  * Validated input for the handler, after the middleware (a guard runs before the request body is read):
@@ -34,11 +34,9 @@ export declare class ValidationError extends Error {
34
34
  }
35
35
  export declare function validationErrorResponse(c: Context, error: ValidationError): Response;
36
36
  /**
37
- * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
38
- * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
39
- * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
40
- * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
41
- * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
37
+ * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
38
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
39
+ * 400.
42
40
  */
43
41
  export declare function readBody(c: Context): Promise<unknown>;
44
42
  /** What `withValidator` checks: the request body (JSON or form), the query, the route params. */
@@ -1,4 +1,5 @@
1
1
  import { HTTPException } from 'hono/http-exception';
2
+ import { formObject, issueErrors, MalformedForm } from '../form.js';
2
3
  import { flashErrors } from './flash.js';
3
4
  import { back, wantsPage } from './http.js';
4
5
  /**
@@ -20,14 +21,10 @@ export function validationErrorResponse(c, error) {
20
21
  flashErrors(c, error.errors);
21
22
  return back(c);
22
23
  }
23
- /** how deep form field names nest (`a[b][c]`: 3) */
24
- const DEPTH = 32;
25
24
  /**
26
- * A request body as one object: JSON, or form fields with PHP-style names, as forms write them (`notify[]`,
27
- * `user[name]`); files are `File`s, empty file inputs are left out. A name given again is a list (`a=1&a=2`,
28
- * `a[b]=1&a[b]=2`); `[]` is the index after the highest one so far. Names that would change the object itself
29
- * (`__proto__`…) are ignored. A body that can't be one object (JSON or form data that doesn't parse,
30
- * `a=1&a[b]=2`, names nested deeper than 32) is a 400.
25
+ * A request body as one object: JSON, or form fields as `formObject` reads them (the browser's `useForm` too). A body
26
+ * that can't be one object (JSON or form data that doesn't parse, `a=1&a[b]=2`, names nested deeper than 32) is a
27
+ * 400.
31
28
  */
32
29
  export async function readBody(c) {
33
30
  const malformed = (why) => new HTTPException(400, { message: `Malformed request body: ${why}` });
@@ -37,49 +34,13 @@ export async function readBody(c) {
37
34
  if (!type.includes('multipart/form-data') && !type.includes('application/x-www-form-urlencoded'))
38
35
  return {};
39
36
  const form = await c.req.formData().catch(() => Promise.reject(malformed('invalid form data')));
40
- const body = Object.create(null);
41
- // `a[]`: each object's next index, the highest one so far + 1 (counted, not looked for: a body of many is linear)
42
- const next = new WeakMap();
43
- const isObject = (v) => typeof v === 'object' && !(v instanceof File) && !Array.isArray(v);
44
- for (const [key, value] of form.entries()) {
45
- if (typeof value !== 'string' && value.size === 0 && value.name === '')
46
- continue;
47
- const path = key.replace(/\]/g, '').split('[');
48
- if (path.length > DEPTH)
49
- throw malformed(`a field name nests deeper than ${DEPTH}`);
50
- if (path.some((p) => p === '__proto__' || p === 'constructor' || p === 'prototype'))
51
- continue;
52
- let target = body;
53
- path.forEach((segment, i) => {
54
- const name = segment === '' ? String(next.get(target) ?? 0) : segment;
55
- if (/^\d+$/.test(name))
56
- next.set(target, Math.max(next.get(target) ?? 0, Number(name) + 1));
57
- const has = Object.hasOwn(target, name);
58
- if (i === path.length - 1) {
59
- if (has && isObject(target[name]))
60
- throw malformed(`\`${key}\` is both a value and an object`);
61
- target[name] = has ? [target[name], value].flat() : value; // given again: a list
62
- }
63
- else {
64
- if (!has)
65
- target[name] = Object.create(null);
66
- else if (!isObject(target[name]))
67
- throw malformed(`\`${key}\` is both a value and an object`);
68
- target = target[name];
69
- }
70
- });
37
+ try {
38
+ return formObject(form.entries());
39
+ }
40
+ catch (error) {
41
+ throw error instanceof MalformedForm ? malformed(error.message) : error;
71
42
  }
72
- return arrays(body);
73
43
  }
74
- /** objects whose keys are 0..n-1 become arrays */
75
- const arrays = (value) => {
76
- if (typeof value !== 'object' || value === null || value instanceof File || Array.isArray(value))
77
- return value;
78
- const entries = Object.entries(value).map(([k, v]) => [k, arrays(v)]);
79
- const isList = entries.length > 0 && entries.every(([k], i) => k === String(i));
80
- return isList ? entries.map(([, v]) => v) : Object.fromEntries(entries);
81
- };
82
- const pathOf = (path) => (path ?? []).map((p) => String(typeof p === 'object' ? p.key : p)).join('.');
83
44
  /**
84
45
  * The validation step of `withValidator`: a middleware, and the validated input of its request. Params that don't
85
46
  * fit the schema are a 404 (`/users/abc` names no user); invalid body or query fields are a `ValidationError`.
@@ -101,8 +62,8 @@ export function validator(schemas) {
101
62
  if (result.issues && key === 'params')
102
63
  throw new HTTPException(404);
103
64
  if (result.issues)
104
- for (const issue of result.issues)
105
- errors[pathOf(issue.path)] ??= issue.message;
65
+ for (const [k, m] of Object.entries(issueErrors(result.issues)))
66
+ errors[k] ??= m;
106
67
  else
107
68
  input[key] = result.value;
108
69
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.11.1",
3
+ "version": "0.12.1",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono and Vite. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",