@nano_kit/preact-form 0.0.0 → 5.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 - present, TrigenSoftware
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
1
  # @nano_kit/preact-form
2
2
 
3
- A placeholder published to set up trusted publishing. The package starts at 5.1.0: https://nano-kit.js.org/form-integrations/preact/
3
+ [![ESM-only package][package]][package-url]
4
+ [![NPM version][npm]][npm-url]
5
+ [![Install size][size]][size-url]
6
+ [![Build status][build]][build-url]
7
+ [![Coverage status][coverage]][coverage-url]
8
+
9
+ [package]: https://img.shields.io/badge/package-ESM--only-ffe536.svg
10
+ [package-url]: https://nodejs.org/api/esm.html
11
+
12
+ [npm]: https://img.shields.io/npm/v/@nano_kit/preact-form.svg
13
+ [npm-url]: https://npmjs.com/package/@nano_kit/preact-form
14
+
15
+ [size]: https://img.shields.io/bundlejs/size/@nano_kit/preact-form
16
+ [size-url]: https://bundlejs.com/?q=@nano_kit/preact-form
17
+
18
+ [build]: https://img.shields.io/github/actions/workflow/status/TrigenSoftware/nano_kit/tests.yml?branch=main
19
+ [build-url]: https://github.com/TrigenSoftware/nano_kit/actions
20
+
21
+ [coverage]: https://img.shields.io/codecov/c/github/TrigenSoftware/nano_kit.svg
22
+ [coverage-url]: https://app.codecov.io/gh/TrigenSoftware/nano_kit
23
+
24
+ The `@nano_kit/preact-form` package binds forms of [@nano_kit/form](../form) to Preact components: its hooks give the props for a control and for a form element.
25
+
26
+ - **A hook per control**. `useTextField`, `useNumberField`, `useCheckboxField`, `useRadioField` and `useFileField` give the value, `onInput`, the check on blur and `aria-invalid`. `useFormField` binds a control of your own.
27
+ - **Your props stay yours**. Props of your own go through the hook, and a handler among them is called after the one of the hook.
28
+ - **A form in one spread**. `useForm` gives the props for the form element and the state of the form, and moves focus to the first control to fix after a failed attempt.
29
+ - **Type-safe**. A hook takes only a field of its kind, and the error codes of the field come back typed.
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pnpm add @nano_kit/store @nano_kit/form @nano_kit/preact @nano_kit/preact-form
35
+ # or
36
+ npm install @nano_kit/store @nano_kit/form @nano_kit/preact @nano_kit/preact-form
37
+ # or
38
+ yarn add @nano_kit/store @nano_kit/form @nano_kit/preact @nano_kit/preact-form
39
+ ```
40
+
41
+ ## Quick Start
42
+
43
+ Here is a sign in form: fields, a form over them, and a component that calls a hook for the form and for every field and spreads what they give.
44
+
45
+ ```tsx
46
+ import {
47
+ email,
48
+ field,
49
+ form,
50
+ required
51
+ } from '@nano_kit/form'
52
+ import { useForm, useTextField } from '@nano_kit/preact-form'
53
+
54
+ const $email = field('', required(), email())
55
+ const $password = field('', required())
56
+ const loginForm = form({
57
+ $email,
58
+ $password
59
+ }, values => signIn(values))
60
+
61
+ export function LoginForm() {
62
+ const [formProps, error, submitting] = useForm(loginForm)
63
+ const [emailProps, emailErrors] = useTextField($email)
64
+ const [passwordProps, passwordErrors] = useTextField($password)
65
+
66
+ return (
67
+ <form {...formProps}>
68
+ <input
69
+ {...emailProps}
70
+ type='email'
71
+ />
72
+ {emailErrors.length > 0 && (
73
+ <p>
74
+ {emailErrors[0]}
75
+ </p>
76
+ )}
77
+ <input
78
+ {...passwordProps}
79
+ type='password'
80
+ />
81
+ {passwordErrors.length > 0 && (
82
+ <p>
83
+ {passwordErrors[0]}
84
+ </p>
85
+ )}
86
+ <button disabled={submitting}>
87
+ Sign in
88
+ </button>
89
+ {error !== null && (
90
+ <p role='alert'>
91
+ {error}
92
+ </p>
93
+ )}
94
+ </form>
95
+ )
96
+ }
97
+ ```
98
+
99
+ ## Documentation
100
+
101
+ For comprehensive guides, API reference, and integration patterns, visit the [documentation website](https://nano-kit.js.org/form-integrations/preact).
@@ -0,0 +1,96 @@
1
+ import type { FocusEventHandler, InputEventHandler } from 'preact';
2
+ import { type Field } from '@nano_kit/form';
3
+ type Control = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
4
+ /**
5
+ * The handlers of a control the hooks put their own before.
6
+ */
7
+ export interface FieldHandlers {
8
+ onBlur?: FocusEventHandler<EventTarget> | undefined;
9
+ onInput?: InputEventHandler<EventTarget> | undefined;
10
+ }
11
+ /**
12
+ * What every hook of a field gives to its control.
13
+ */
14
+ export interface FormFieldProps {
15
+ 'aria-invalid': boolean;
16
+ onBlur: FocusEventHandler<EventTarget>;
17
+ }
18
+ /**
19
+ * Bind a field to a control: the control tells whether the field has errors, and the field is checked
20
+ * as the control is left. The value and what changes it are up to the control.
21
+ * @param $field - The field.
22
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
23
+ * @returns A tuple of the props of the control and the errors of the field.
24
+ */
25
+ export declare function useFormField<T, E, P extends object = object>($field: Field<T, E>, props?: P & FieldHandlers): readonly [P & FormFieldProps, readonly E[]];
26
+ /**
27
+ * Bind a field of a string to an input, a textarea or a select.
28
+ * @param $field - The field.
29
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
30
+ * @returns A tuple of the props of the control and the errors of the field.
31
+ */
32
+ export declare function useTextField<E, P extends object = object>($field: Field<string, E>, props?: P & FieldHandlers): readonly [P & FieldHandlers & {
33
+ readonly 'aria-invalid': boolean;
34
+ readonly onBlur: FocusEventHandler<EventTarget>;
35
+ readonly value: string;
36
+ readonly onInput: InputEventHandler<Control>;
37
+ }, readonly E[]];
38
+ /**
39
+ * Bind a field of a number to an input of a number. An input with no number in it is no value: `undefined`.
40
+ * @param $field - The field.
41
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
42
+ * @returns A tuple of the props of the control and the errors of the field.
43
+ */
44
+ export declare function useNumberField<E, P extends object = object>($field: Field<number | undefined, E>, props?: P & FieldHandlers): readonly [{
45
+ readonly type: 'number';
46
+ } & P & FieldHandlers & {
47
+ readonly 'aria-invalid': boolean;
48
+ readonly onBlur: FocusEventHandler<EventTarget>;
49
+ readonly value: number | "";
50
+ readonly onInput: InputEventHandler<Control>;
51
+ }, readonly E[]];
52
+ /**
53
+ * Bind a field of a flag to a checkbox.
54
+ * @param $field - The field.
55
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
56
+ * @returns A tuple of the props of the control and the errors of the field.
57
+ */
58
+ export declare function useCheckboxField<E, P extends object = object>($field: Field<boolean, E>, props?: P & FieldHandlers): readonly [{
59
+ readonly type: 'checkbox';
60
+ } & P & FieldHandlers & {
61
+ readonly 'aria-invalid': boolean;
62
+ readonly onBlur: FocusEventHandler<EventTarget>;
63
+ readonly checked: boolean;
64
+ readonly onInput: InputEventHandler<Control>;
65
+ }, readonly E[]];
66
+ /**
67
+ * Bind a field to one of the radio buttons that choose its value.
68
+ * @param $field - The field.
69
+ * @param value - The value the radio button stands for.
70
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
71
+ * @returns A tuple of the props of the control and the errors of the field.
72
+ */
73
+ export declare function useRadioField<T extends string | number | undefined, E, P extends object = object>($field: Field<T, E>, value: Exclude<T, undefined>, props?: P & FieldHandlers): readonly [{
74
+ readonly type: 'radio';
75
+ } & P & FieldHandlers & {
76
+ readonly 'aria-invalid': boolean;
77
+ readonly onBlur: FocusEventHandler<EventTarget>;
78
+ readonly value: Exclude<T, undefined>;
79
+ readonly checked: boolean;
80
+ readonly onInput: InputEventHandler<Control>;
81
+ }, readonly E[]];
82
+ /**
83
+ * Bind a field of a file to an input of a file. The first of the chosen files is taken.
84
+ * @param $field - The field.
85
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
86
+ * @returns A tuple of the props of the control and the errors of the field.
87
+ */
88
+ export declare function useFileField<E, P extends object = object>($field: Field<File | undefined, E>, props?: P & FieldHandlers): readonly [{
89
+ readonly type: 'file';
90
+ } & P & FieldHandlers & {
91
+ readonly 'aria-invalid': boolean;
92
+ readonly onBlur: FocusEventHandler<EventTarget>;
93
+ readonly onInput: InputEventHandler<Control>;
94
+ }, readonly E[]];
95
+ export {};
96
+ //# sourceMappingURL=field.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"field.d.ts","sourceRoot":"","sources":["../src/field.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iBAAiB,EACjB,iBAAiB,EAElB,MAAM,QAAQ,CAAA;AAEf,OAAO,EACL,KAAK,KAAK,EAEX,MAAM,gBAAgB,CAAA;AAGvB,KAAK,OAAO,GAAG,gBAAgB,GAAG,mBAAmB,GAAG,iBAAiB,CAAA;AAEzE;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,MAAM,CAAC,EAAE,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAA;IACnD,OAAO,CAAC,EAAE,iBAAiB,CAAC,WAAW,CAAC,GAAG,SAAS,CAAA;CACrD;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,cAAc,EAAE,OAAO,CAAA;IACvB,M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,KAAK,EAAE,OAAO,CAAC,CAAC,EAAE,SAAS,CAAC,EAC5B,KAAK,CAAC,EAAE,CAAC,GAAG,aAAa;mBAOf,OAAO;;6BAnID,OAAO;qBACf,iBAAiB,CAAC,WAAW,CAAC;;;;iBA0IvC;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EACvD,MAAM,EAAE,KAAK,CAAC,IAAI,GAAG,SAAS,EAAE,CAAC,CAAC,EAClC,KAAK,CAAC,EAAE,CAAC,GAAG,aAAa;mBAMf,MAAM;;6BA3JA,OAAO;qBACf,iBAAiB,CAAC,WAAW,CAAC;;iBAgKvC"}
package/dist/form.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ import type { Form } from '@nano_kit/form';
2
+ import type { GenericEventHandler, Ref, RefCallback, SubmitEventHandler } from 'preact';
3
+ /**
4
+ * The props of a form element the hook puts its own before.
5
+ */
6
+ export interface FormHandlers {
7
+ ref?: Ref<HTMLFormElement> | undefined;
8
+ onSubmit?: SubmitEventHandler<HTMLFormElement> | undefined;
9
+ onReset?: GenericEventHandler<HTMLFormElement> | undefined;
10
+ }
11
+ /**
12
+ * What the hook gives to a form element.
13
+ */
14
+ export interface FormProps {
15
+ ref: RefCallback<HTMLFormElement>;
16
+ noValidate: true;
17
+ 'aria-busy': boolean;
18
+ onSubmit: SubmitEventHandler<HTMLFormElement>;
19
+ onReset: GenericEventHandler<HTMLFormElement>;
20
+ }
21
+ /**
22
+ * Bind a form to a form element: a submit of the element is an attempt of the form, a reset of the element
23
+ * resets the form, and the element tells while a submit is going. Once an attempt is over, focus goes to
24
+ * the first control that asks for a fix.
25
+ * @param form - The form.
26
+ * @param props - Props to pass to the form element. A handler among them is called after the one of the hook.
27
+ * @param args - Arguments a submit of the element goes with, for a form whose handler takes them.
28
+ * @returns A tuple of the props of the form element, the message of the error of the last attempt,
29
+ * whether a submit is going and the count of attempts.
30
+ */
31
+ export declare function useForm<A extends unknown[], P extends object = object>(form: Form<A>, props?: P & FormHandlers, ...args: A): readonly [P & FormProps, string | null, boolean, number];
32
+ //# sourceMappingURL=form.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../src/form.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,KAAK,EACV,mBAAmB,EACnB,GAAG,EACH,WAAW,EACX,kBAAkB,EACnB,MAAM,QAAQ,CAAA;AAQf;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,EAAE,GAAG,CAAC,eAAe,CAAC,GAAG,SAAS,CAAA;IACtC,QAAQ,CAAC,EAAE,kBAAkB,CAAC,eAAe,CAAC,GAAG,SAAS,CAAA;IAC1D,OAAO,CAAC,EAAE,mBAAmB,CAAC,eAAe,CAAC,GAAG,SAAS,CAAA;CAC3D;AAED;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,GAAG,EAAE,WAAW,CAAC,eAAe,CAAC,CAAA;IACjC,UAAU,EAAE,IAAI,CAAA;IAChB,WAAW,EAAE,OAAO,CAAA;IACpB,QAAQ,EAAE,kBAAkB,CAAC,eAAe,CAAC,CAAA;IAC7C,OAAO,EAAE,mBAAmB,CAAC,eAAe,CAAC,CAAA;CAC9C;AAED;;;;;;;;;GASG;AACH,wBAAgB,OAAO,CAAC,CAAC,SAAS,OAAO,EAAE,EAAE,CAAC,SAAS,MAAM,GAAG,MAAM,EACpE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,EACb,KAAK,CAAC,EAAE,CAAC,GAAG,YAAY,EACxB,GAAG,IAAI,EAAE,CAAC,aA0CH,CAAC,GAAG,SAAS,kCAKrB"}
@@ -0,0 +1,3 @@
1
+ export * from './field.js';
2
+ export * from './form.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA;AAC1B,cAAc,WAAW,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,173 @@
1
+ import { useSignal } from "@nano_kit/preact";
2
+ import { validate } from "@nano_kit/form";
3
+ import { useEffect, useRef } from "preact/hooks";
4
+ //#region src/utils.ts
5
+ /**
6
+ * Make a handler that calls the handler of a hook and then the one that came with the props.
7
+ * @param own - The handler of the hook.
8
+ * @param given - The handler that came with the props.
9
+ * @returns The handler.
10
+ */
11
+ function chain(own, given) {
12
+ return given ? (...args) => {
13
+ own(...args);
14
+ given(...args);
15
+ } : own;
16
+ }
17
+ //#endregion
18
+ //#region src/field.ts
19
+ function input($field, props, read) {
20
+ return chain((event) => {
21
+ $field(read(event.currentTarget));
22
+ }, props?.onInput);
23
+ }
24
+ /**
25
+ * Bind a field to a control: the control tells whether the field has errors, and the field is checked
26
+ * as the control is left. The value and what changes it are up to the control.
27
+ * @param $field - The field.
28
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
29
+ * @returns A tuple of the props of the control and the errors of the field.
30
+ */
31
+ function useFormField($field, props) {
32
+ const errors = useSignal($field.$errors);
33
+ return [{
34
+ ...props,
35
+ "aria-invalid": errors.length > 0,
36
+ onBlur: chain(() => {
37
+ validate($field);
38
+ }, props?.onBlur)
39
+ }, errors];
40
+ }
41
+ /**
42
+ * Bind a field of a string to an input, a textarea or a select.
43
+ * @param $field - The field.
44
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
45
+ * @returns A tuple of the props of the control and the errors of the field.
46
+ */
47
+ function useTextField($field, props) {
48
+ const value = useSignal($field);
49
+ const [fieldProps, errors] = useFormField($field, props);
50
+ return [{
51
+ ...fieldProps,
52
+ value,
53
+ onInput: input($field, props, (control) => control.value)
54
+ }, errors];
55
+ }
56
+ /**
57
+ * Bind a field of a number to an input of a number. An input with no number in it is no value: `undefined`.
58
+ * @param $field - The field.
59
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
60
+ * @returns A tuple of the props of the control and the errors of the field.
61
+ */
62
+ function useNumberField($field, props) {
63
+ const value = useSignal($field);
64
+ const [fieldProps, errors] = useFormField($field, props);
65
+ return [{
66
+ type: "number",
67
+ ...fieldProps,
68
+ value: value ?? "",
69
+ onInput: input($field, props, (control) => Number.isNaN(control.valueAsNumber) ? void 0 : control.valueAsNumber)
70
+ }, errors];
71
+ }
72
+ /**
73
+ * Bind a field of a flag to a checkbox.
74
+ * @param $field - The field.
75
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
76
+ * @returns A tuple of the props of the control and the errors of the field.
77
+ */
78
+ function useCheckboxField($field, props) {
79
+ const checked = useSignal($field);
80
+ const [fieldProps, errors] = useFormField($field, props);
81
+ return [{
82
+ type: "checkbox",
83
+ ...fieldProps,
84
+ checked,
85
+ onInput: input($field, props, (control) => control.checked)
86
+ }, errors];
87
+ }
88
+ /**
89
+ * Bind a field to one of the radio buttons that choose its value.
90
+ * @param $field - The field.
91
+ * @param value - The value the radio button stands for.
92
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
93
+ * @returns A tuple of the props of the control and the errors of the field.
94
+ */
95
+ function useRadioField($field, value, props) {
96
+ const chosen = useSignal($field);
97
+ const [fieldProps, errors] = useFormField($field, props);
98
+ return [{
99
+ type: "radio",
100
+ ...fieldProps,
101
+ value,
102
+ checked: chosen === value,
103
+ onInput: input($field, props, () => value)
104
+ }, errors];
105
+ }
106
+ /**
107
+ * Bind a field of a file to an input of a file. The first of the chosen files is taken.
108
+ * @param $field - The field.
109
+ * @param props - Props to pass to the control. A handler among them is called after the one of the hook.
110
+ * @returns A tuple of the props of the control and the errors of the field.
111
+ */
112
+ function useFileField($field, props) {
113
+ const [fieldProps, errors] = useFormField($field, props);
114
+ return [{
115
+ type: "file",
116
+ ...fieldProps,
117
+ onInput: input($field, props, (control) => control.files?.[0])
118
+ }, errors];
119
+ }
120
+ //#endregion
121
+ //#region src/form.ts
122
+ /**
123
+ * Bind a form to a form element: a submit of the element is an attempt of the form, a reset of the element
124
+ * resets the form, and the element tells while a submit is going. Once an attempt is over, focus goes to
125
+ * the first control that asks for a fix.
126
+ * @param form - The form.
127
+ * @param props - Props to pass to the form element. A handler among them is called after the one of the hook.
128
+ * @param args - Arguments a submit of the element goes with, for a form whose handler takes them.
129
+ * @returns A tuple of the props of the form element, the message of the error of the last attempt,
130
+ * whether a submit is going and the count of attempts.
131
+ */
132
+ function useForm(form, props, ...args) {
133
+ const [actions, $error, $submitting, $attempt] = form;
134
+ const error = useSignal($error);
135
+ const submitting = useSignal($submitting);
136
+ const attempt = useSignal($attempt);
137
+ const elementRef = useRef(null);
138
+ const seenRef = useRef(attempt);
139
+ const ref = props?.ref;
140
+ useEffect(() => {
141
+ if (seenRef.current !== attempt) {
142
+ seenRef.current = attempt;
143
+ elementRef.current?.querySelector("[aria-invalid=\"true\"]")?.focus();
144
+ }
145
+ }, [attempt]);
146
+ return [
147
+ {
148
+ ...props,
149
+ ref(element) {
150
+ elementRef.current = element;
151
+ if (typeof ref === "function") ref(element);
152
+ else if (ref) ref.current = element;
153
+ },
154
+ noValidate: true,
155
+ "aria-busy": submitting,
156
+ onSubmit: chain((event) => {
157
+ event.preventDefault();
158
+ actions.submit(...args);
159
+ }, props?.onSubmit),
160
+ onReset: chain((event) => {
161
+ event.preventDefault();
162
+ actions.reset();
163
+ }, props?.onReset)
164
+ },
165
+ error,
166
+ submitting,
167
+ attempt
168
+ ];
169
+ }
170
+ //#endregion
171
+ export { useCheckboxField, useFileField, useForm, useFormField, useNumberField, useRadioField, useTextField };
172
+
173
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/utils.ts","../src/field.ts","../src/form.ts"],"sourcesContent":["/**\n * Make a handler that calls the handler of a hook and then the one that came with the props.\n * @param own - The handler of the hook.\n * @param given - The handler that came with the props.\n * @returns The handler.\n */\nexport function chain<A extends unknown[]>(\n own: (...args: A) => void,\n given: ((...args: A) => void) | undefined\n) {\n return given\n ? (...args: A) => {\n own(...args)\n given(...args)\n }\n : own\n}\n","import type {\n FocusEventHandler,\n InputEventHandler,\n TargetedInputEvent\n} from 'preact'\nimport { useSignal } from '@nano_kit/preact'\nimport {\n type Field,\n validate\n} from '@nano_kit/form'\nimport { chain } from './utils.js'\n\ntype Control = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement\n\n/**\n * The handlers of a control the hooks put their own before.\n */\nexport interface FieldHandlers {\n onBlur?: FocusEventHandler<EventTarget> | undefined\n onInput?: InputEventHandler<EventTarget> | undefined\n}\n\n/**\n * What every hook of a field gives to its control.\n */\nexport interface FormFieldProps {\n 'aria-invalid': boolean\n onBlur: FocusEventHandler<EventTarget>\n}\n\n// Write what a control holds to its field as the control is changed\nfunction input<T>(\n $field: (value: T) => void,\n props: FieldHandlers | undefined,\n read: (control: HTMLInputElement) => T\n) {\n return chain((event: TargetedInputEvent<HTMLInputElement>) => {\n $field(read(event.currentTarget))\n }, props?.onInput) as InputEventHandler<Control>\n}\n\n/**\n * Bind a field to a control: the control tells whether the field has errors, and the field is checked\n * as the control is left. The value and what changes it are up to the control.\n * @param $field - The field.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useFormField<T, E, P extends object = object>(\n $field: Field<T, E>,\n props?: P & FieldHandlers\n) {\n const errors = useSignal($field.$errors)\n\n return [\n {\n ...props as P,\n 'aria-invalid': errors.length > 0,\n onBlur: chain<Parameters<FocusEventHandler<EventTarget>>>(() => {\n validate($field)\n }, props?.onBlur)\n } as P & FormFieldProps,\n errors\n ] as const\n}\n\n/**\n * Bind a field of a string to an input, a textarea or a select.\n * @param $field - The field.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useTextField<E, P extends object = object>(\n $field: Field<string, E>,\n props?: P & FieldHandlers\n) {\n const value = useSignal($field)\n const [fieldProps, errors] = useFormField($field, props)\n\n return [\n {\n ...fieldProps,\n value,\n onInput: input($field, props, control => control.value)\n },\n errors\n ] as const\n}\n\n/**\n * Bind a field of a number to an input of a number. An input with no number in it is no value: `undefined`.\n * @param $field - The field.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useNumberField<E, P extends object = object>(\n $field: Field<number | undefined, E>,\n props?: P & FieldHandlers\n) {\n const value = useSignal($field)\n const [fieldProps, errors] = useFormField($field, props)\n\n return [\n {\n type: 'number',\n ...fieldProps,\n value: value ?? '',\n // An input with no number in it tells `NaN`\n onInput: input($field, props, control => (\n Number.isNaN(control.valueAsNumber) ? undefined : control.valueAsNumber\n ))\n },\n errors\n ] as const\n}\n\n/**\n * Bind a field of a flag to a checkbox.\n * @param $field - The field.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useCheckboxField<E, P extends object = object>(\n $field: Field<boolean, E>,\n props?: P & FieldHandlers\n) {\n const checked = useSignal($field)\n const [fieldProps, errors] = useFormField($field, props)\n\n return [\n {\n type: 'checkbox',\n ...fieldProps,\n checked,\n onInput: input($field, props, control => control.checked)\n },\n errors\n ] as const\n}\n\n/**\n * Bind a field to one of the radio buttons that choose its value.\n * @param $field - The field.\n * @param value - The value the radio button stands for.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useRadioField<T extends string | number | undefined, E, P extends object = object>(\n $field: Field<T, E>,\n value: Exclude<T, undefined>,\n props?: P & FieldHandlers\n) {\n const chosen = useSignal($field)\n const [fieldProps, errors] = useFormField($field, props)\n\n return [\n {\n type: 'radio',\n ...fieldProps,\n value,\n checked: chosen === value,\n onInput: input($field, props, () => value)\n },\n errors\n ] as const\n}\n\n/**\n * Bind a field of a file to an input of a file. The first of the chosen files is taken.\n * @param $field - The field.\n * @param props - Props to pass to the control. A handler among them is called after the one of the hook.\n * @returns A tuple of the props of the control and the errors of the field.\n */\nexport function useFileField<E, P extends object = object>(\n $field: Field<File | undefined, E>,\n props?: P & FieldHandlers\n) {\n const [fieldProps, errors] = useFormField($field, props)\n\n return [\n {\n type: 'file',\n ...fieldProps,\n onInput: input($field, props, control => control.files?.[0])\n },\n errors\n ] as const\n}\n","import type { Form } from '@nano_kit/form'\nimport type {\n GenericEventHandler,\n Ref,\n RefCallback,\n SubmitEventHandler\n} from 'preact'\nimport {\n useEffect,\n useRef\n} from 'preact/hooks'\nimport { useSignal } from '@nano_kit/preact'\nimport { chain } from './utils.js'\n\n/**\n * The props of a form element the hook puts its own before.\n */\nexport interface FormHandlers {\n ref?: Ref<HTMLFormElement> | undefined\n onSubmit?: SubmitEventHandler<HTMLFormElement> | undefined\n onReset?: GenericEventHandler<HTMLFormElement> | undefined\n}\n\n/**\n * What the hook gives to a form element.\n */\nexport interface FormProps {\n ref: RefCallback<HTMLFormElement>\n noValidate: true\n 'aria-busy': boolean\n onSubmit: SubmitEventHandler<HTMLFormElement>\n onReset: GenericEventHandler<HTMLFormElement>\n}\n\n/**\n * Bind a form to a form element: a submit of the element is an attempt of the form, a reset of the element\n * resets the form, and the element tells while a submit is going. Once an attempt is over, focus goes to\n * the first control that asks for a fix.\n * @param form - The form.\n * @param props - Props to pass to the form element. A handler among them is called after the one of the hook.\n * @param args - Arguments a submit of the element goes with, for a form whose handler takes them.\n * @returns A tuple of the props of the form element, the message of the error of the last attempt,\n * whether a submit is going and the count of attempts.\n */\nexport function useForm<A extends unknown[], P extends object = object>(\n form: Form<A>,\n props?: P & FormHandlers,\n ...args: A\n) {\n const [actions, $error, $submitting, $attempt] = form\n const error = useSignal($error)\n const submitting = useSignal($submitting)\n const attempt = useSignal($attempt)\n const elementRef = useRef<HTMLFormElement | null>(null)\n const seenRef = useRef(attempt)\n const ref = props?.ref\n\n useEffect(() => {\n // An attempt that was over before the form was shown moves no focus\n if (seenRef.current !== attempt) {\n seenRef.current = attempt\n elementRef.current?.querySelector<HTMLElement>('[aria-invalid=\"true\"]')?.focus()\n }\n }, [attempt])\n\n return [\n {\n ...props as P,\n ref(element) {\n elementRef.current = element\n\n // The ref that came with the props gets the element too\n if (typeof ref === 'function') {\n ref(element)\n } else if (ref) {\n ref.current = element\n }\n },\n noValidate: true,\n 'aria-busy': submitting,\n onSubmit: chain((event) => {\n event.preventDefault()\n void actions.submit(...args)\n }, props?.onSubmit),\n // The controls show the values of the fields: the element has nothing of its own to reset\n onReset: chain((event) => {\n event.preventDefault()\n actions.reset()\n }, props?.onReset)\n } as P & FormProps,\n error,\n submitting,\n attempt\n ] as const\n}\n"],"mappings":";;;;;;;;;;AAMA,SAAgB,MACd,KACA,OACA;CACA,OAAO,SACF,GAAG,SAAY;EAChB,IAAI,GAAG,IAAI;EACX,MAAM,GAAG,IAAI;CACf,IACE;AACN;;;ACeA,SAAS,MACP,QACA,OACA,MACA;CACA,OAAO,OAAO,UAAgD;EAC5D,OAAO,KAAK,MAAM,aAAa,CAAC;CAClC,GAAG,OAAO,OAAO;AACnB;;;;;;;;AASA,SAAgB,aACd,QACA,OACA;CACA,MAAM,SAAS,UAAU,OAAO,OAAO;CAEvC,OAAO,CACL;EACE,GAAG;EACH,gBAAgB,OAAO,SAAS;EAChC,QAAQ,YAAwD;GAC9D,SAAS,MAAM;EACjB,GAAG,OAAO,MAAM;CAClB,GACA,MACF;AACF;;;;;;;AAQA,SAAgB,aACd,QACA,OACA;CACA,MAAM,QAAQ,UAAU,MAAM;CAC9B,MAAM,CAAC,YAAY,UAAU,aAAa,QAAQ,KAAK;CAEvD,OAAO,CACL;EACE,GAAG;EACH;EACA,SAAS,MAAM,QAAQ,QAAO,YAAW,QAAQ,KAAK;CACxD,GACA,MACF;AACF;;;;;;;AAQA,SAAgB,eACd,QACA,OACA;CACA,MAAM,QAAQ,UAAU,MAAM;CAC9B,MAAM,CAAC,YAAY,UAAU,aAAa,QAAQ,KAAK;CAEvD,OAAO,CACL;E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AAG,CAAC,OAAO,CAAC;CAEZ,OAAO;EACL;GACE,GAAG;GACH,IAAI,SAAS;IACX,WAAW,UAAU;IAGrB,IAAI,OAAO,QAAQ,YACjB,IAAI,OAAO;SACN,IAAI,KACT,IAAI,UAAU;GAElB;GACA,YAAY;GACZ,aAAa;GACb,UAAU,OAAO,UAAU;IACzB,MAAM,eAAe;IACrB,QAAa,OAAO,GAAG,IAAI;GAC7B,GAAG,OAAO,QAAQ;GAElB,SAAS,OAAO,UAAU;IACxB,MAAM,eAAe;IACrB,QAAQ,MAAM;GAChB,GAAG,OAAO,OAAO;EACnB;EACA;EACA;EACA;CACF;AACF"}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Make a handler that calls the handler of a hook and then the one that came with the props.
3
+ * @param own - The handler of the hook.
4
+ * @param given - The handler that came with the props.
5
+ * @returns The handler.
6
+ */
7
+ export declare function chain<A extends unknown[]>(own: (...args: A) => void, given: ((...args: A) => void) | undefined): (...args: A) => void;
8
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,CAAC,SAAS,OAAO,EAAE,EACvC,GAAG,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,IAAI,EACzB,KAAK,EAAE,CAAC,CAAC,GAAG,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC,GAAG,SAAS,aAD1B,CAAC,KAAK,IAAI,CAS1B"}
package/package.json CHANGED
@@ -1,11 +1,47 @@
1
1
  {
2
2
  "name": "@nano_kit/preact-form",
3
- "version": "0.0.0",
4
- "description": "Placeholder published to set up trusted publishing. The package starts at 5.1.0.",
3
+ "type": "module",
4
+ "version": "5.1.0",
5
+ "description": "Preact integration for @nano_kit/form.",
6
+ "author": "dangreen",
5
7
  "license": "MIT",
8
+ "homepage": "https://nano-kit.js.org/form-integrations/preact",
9
+ "funding": "https://ko-fi.com/dangreen",
6
10
  "repository": {
7
11
  "type": "git",
8
12
  "url": "https://github.com/TrigenSoftware/nano_kit.git",
9
13
  "directory": "packages/preact-form"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/TrigenSoftware/nano_kit/issues"
17
+ },
18
+ "keywords": [
19
+ "preact",
20
+ "form",
21
+ "forms",
22
+ "field",
23
+ "validation",
24
+ "hooks",
25
+ "signal",
26
+ "nano_kit"
27
+ ],
28
+ "engines": {
29
+ "node": ">=24"
30
+ },
31
+ "sideEffects": false,
32
+ "exports": {
33
+ "./package.json": "./package.json",
34
+ ".": {
35
+ "types": "./dist/index.d.ts",
36
+ "default": "./dist/index.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "peerDependencies": {
43
+ "@nano_kit/form": "^5.1.0",
44
+ "@nano_kit/preact": "^5.1.0",
45
+ "preact": "^10.0.0 || ^11.0.0"
10
46
  }
11
- }
47
+ }