@formisch/preact 0.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.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) Fabian Hiller
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # Formisch for Preact
2
+
3
+ Formisch is a schema-based, headless form library for Preact. It manages form state and validation. It is type-safe, fast by default and its bundle size is small due to its modular design. Try it out in our [playground](https://stackblitz.com/edit/formisch-playground-preact)!
4
+
5
+ ## Highlights
6
+
7
+ - Small bundle size starting at 2.5 kB
8
+ - Schema-based validation with Valibot
9
+ - Type safety with autocompletion in editor
10
+ - It's fast – DOM updates are fine-grained
11
+ - Minimal, readable and well thought out API
12
+ - Supports all native HTML form fields
13
+
14
+ ## Example
15
+
16
+ Every form starts with the `useForm$` hook. It initializes your form's store based on the provided Valibot schema and infers its types. Next, wrap your form in the `<Form />` component. It's a thin layer around the native `<form />` element that handles form validation and submission. Then, you can access the state of a field with the `useField` hook or the `<Field />` component to connect your inputs.
17
+
18
+ ```tsx
19
+ import { Field, Form, useForm$ } from '@formisch/preact';
20
+ import * as v from 'valibot';
21
+
22
+ const LoginSchema = v.object({
23
+ email: v.pipe(v.string(), v.email()),
24
+ password: v.pipe(v.string(), v.minLength(8)),
25
+ });
26
+
27
+ export default function LoginPage() {
28
+ const loginForm = useForm({
29
+ schema: LoginSchema,
30
+ });
31
+
32
+ return (
33
+ <Form of={loginForm} onSubmit={(output) => console.log(output)}>
34
+ <Field
35
+ of={loginForm}
36
+ path={['email']}
37
+ render={(field) => (
38
+ <div>
39
+ <input {...field.props} value={field.input} type="email" />
40
+ {field.errors.value && <div>{field.errors.value[0]}</div>}
41
+ </div>
42
+ )}
43
+ />
44
+ <Field
45
+ of={loginForm}
46
+ path={['password']}
47
+ render={(field) => (
48
+ <div>
49
+ <input {...field.props} value={field.input} type="password" />
50
+ {field.errors.value && <div>{field.errors.value[0]}</div>}
51
+ </div>
52
+ )}
53
+ />
54
+ <button type="submit">Login</button>
55
+ </Form>
56
+ );
57
+ }
58
+ ```
59
+
60
+ In addition, Formisch offers several functions (we call them "methods") that can be used to read and manipulate the form state. These include `focus`, `getErrors`, `getAllErrors`, `getInput`, `insert`, `move`, `remove`, `replace`, `reset`, `setErrors`, `setInput`, `submit`, `swap` and `validate`. These methods allow you to control the form programmatically.
61
+
62
+ ## Feedback
63
+
64
+ Find a bug or have an idea how to improve the library? Please fill out an [issue](https://github.com/fabian-hiller/formisch/issues/new). Together we can make forms even better!
65
+
66
+ ## License
67
+
68
+ This project is available free of charge and licensed under the [MIT license](https://github.com/fabian-hiller/formisch/blob/main/LICENSE.md).
@@ -0,0 +1,393 @@
1
+ import * as v from "valibot";
2
+ import { ReadonlySignal, Signal } from "@preact/signals";
3
+ import { JSX } from "preact";
4
+
5
+ //#region ../../packages/core/dist/index.preact.d.ts
6
+ //#region src/types/schema.d.ts
7
+ type Schema = v.GenericSchema | v.GenericSchemaAsync;
8
+ //#endregion
9
+ //#region src/types/signal.d.ts
10
+
11
+ //#endregion
12
+ //#region src/types/field.d.ts
13
+ /**
14
+ * Value type of the field element.
15
+ */
16
+ type FieldElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
17
+ interface InternalBaseStore {
18
+ kind: "array" | "object" | "value";
19
+ name: string;
20
+ schema: Schema;
21
+ elements: FieldElement[];
22
+ errors: Signal<[string, ...string[]] | null>;
23
+ }
24
+ interface InternalArrayStore extends InternalBaseStore {
25
+ kind: "array";
26
+ children: InternalFieldStore[];
27
+ initialItems: Signal<string[]>;
28
+ startItems: Signal<string[]>;
29
+ items: Signal<string[]>;
30
+ isTouched: Signal<boolean>;
31
+ isDirty: Signal<boolean>;
32
+ }
33
+ interface InternalObjectStore extends InternalBaseStore {
34
+ kind: "object";
35
+ children: Record<string, InternalFieldStore>;
36
+ }
37
+ interface InternalValueStore extends InternalBaseStore {
38
+ kind: "value";
39
+ initialInput: Signal<unknown>;
40
+ startInput: Signal<unknown>;
41
+ input: Signal<unknown>;
42
+ isTouched: Signal<boolean>;
43
+ isDirty: Signal<boolean>;
44
+ }
45
+ type InternalFieldStore = InternalArrayStore | InternalObjectStore | InternalValueStore;
46
+ //#endregion
47
+ //#region src/values.d.ts
48
+ declare const INTERNAL: "~internal";
49
+ //#endregion
50
+ //#region src/types/utils.d.ts
51
+ /**
52
+ * Checks if a type is `any`.
53
+ */
54
+ type IsAny<Type> = 0 extends 1 & Type ? true : false;
55
+ /**
56
+ * Checks if a type is `never`.
57
+ */
58
+ type IsNever<Type> = [Type] extends [never] ? true : false;
59
+ /**
60
+ * Constructs a type that is maybe a promise.
61
+ */
62
+ type MaybePromise<TValue> = TValue | Promise<TValue>;
63
+ /**
64
+ * Makes all properties deeply optional.
65
+ */
66
+ type DeepPartial<TValue> = TValue extends readonly unknown[] ? number extends TValue["length"] ? TValue : { [Key in keyof TValue]?: DeepPartial<TValue[Key]> | undefined } : TValue extends Record<PropertyKey, unknown> ? { [Key in keyof TValue]?: DeepPartial<TValue[Key]> | undefined } : TValue | undefined;
67
+ /**
68
+ * Makes all value properties optional.
69
+ */
70
+ type PartialValues<TValue> = TValue extends readonly unknown[] ? number extends TValue["length"] ? TValue : { [Key in keyof TValue]: PartialValues<TValue[Key]> } : TValue extends Record<PropertyKey, unknown> ? { [Key in keyof TValue]: PartialValues<TValue[Key]> } : TValue | undefined;
71
+ //#endregion
72
+ //#region src/types/form.d.ts
73
+ /**
74
+ * Value type of the validation mode.
75
+ */
76
+ type ValidationMode = "initial" | "touch" | "input" | "change" | "blur" | "submit";
77
+ interface FormConfig<TSchema extends Schema = Schema> {
78
+ readonly schema: TSchema;
79
+ readonly initialInput?: DeepPartial<v.InferInput<TSchema>> | undefined;
80
+ readonly validateOn?: ValidationMode | undefined;
81
+ readonly revalidateOn?: Exclude<ValidationMode, "initial"> | undefined;
82
+ }
83
+ interface InternalFormStore<TSchema extends Schema = Schema> extends InternalObjectStore {
84
+ element?: HTMLFormElement;
85
+ validators: number;
86
+ validateOn: ValidationMode;
87
+ revalidateOn: Exclude<ValidationMode, "initial">;
88
+ validate: (input: unknown) => Promise<v.SafeParseResult<TSchema>>;
89
+ isSubmitting: Signal<boolean>;
90
+ isSubmitted: Signal<boolean>;
91
+ isValidating: Signal<boolean>;
92
+ }
93
+ interface BaseFormStore<TSchema extends Schema = Schema> {
94
+ [INTERNAL]: InternalFormStore<TSchema>;
95
+ }
96
+ type SubmitHandler<TSchema extends Schema> = (output: v.InferOutput<TSchema>, event: SubmitEvent) => MaybePromise<void>;
97
+ //#endregion
98
+ //#region src/types/path.d.ts
99
+ /**
100
+ * Path key type.
101
+ */
102
+ type PathKey = string | number;
103
+ /**
104
+ * Path type.
105
+ */
106
+ type Path = readonly PathKey[];
107
+ /**
108
+ * Required path type.
109
+ */
110
+ type RequiredPath = readonly [PathKey, ...Path];
111
+ /**
112
+ * Extracts the exact keys of a tuple, array or object.
113
+ */
114
+ type KeyOf<TValue> = IsAny<TValue> extends true ? never : TValue extends readonly unknown[] ? number extends TValue["length"] ? number : { [TKey in keyof TValue]: TKey extends `${infer TIndex extends number}` ? TIndex : never }[number] : TValue extends Record<string, unknown> ? keyof TValue & PathKey : never;
115
+ /**
116
+ * Merges array and object unions into a single object.
117
+ *
118
+ * Hint: This is necessary to make any property accessible. By default,
119
+ * properties that do not exist in all union options are not accessible
120
+ * and result in "any" when accessed.
121
+ */
122
+ type MergeUnion<T> = { [K in KeyOf<T>]: T extends Record<K, infer V> ? V : never };
123
+ /**
124
+ * Lazily evaluate only the first valid path segment based on the given value.
125
+ */
126
+ type LazyPath<TValue, TPathToCheck extends Path, TValidPath extends Path = readonly []> = TPathToCheck extends readonly [] ? TValidPath : TPathToCheck extends readonly [infer TFirstKey extends KeyOf<TValue>, ...infer TPathRest extends Path] ? LazyPath<MergeUnion<TValue>[TFirstKey], TPathRest, readonly [...TValidPath, TFirstKey]> : IsNever<KeyOf<TValue>> extends false ? readonly [...TValidPath, KeyOf<TValue>] : TValidPath;
127
+ /**
128
+ * Returns the path if valid, otherwise the first possible valid path based on
129
+ * the given value.
130
+ */
131
+ type ValidPath<TValue, TPath extends RequiredPath> = TPath extends LazyPath<TValue, TPath> ? TPath : LazyPath<TValue, TPath>;
132
+ /**
133
+ * Extracts the value type at the given path.
134
+ */
135
+ type PathValue<TValue, TPath extends Path> = TPath extends readonly [infer TKey, ...infer TRest extends Path] ? TKey extends KeyOf<TValue> ? PathValue<MergeUnion<TValue>[TKey], TRest> : unknown : TValue;
136
+ /**
137
+ * Checks if a value is an array or contains one.
138
+ */
139
+ type IsOrHasArray<TValue> = IsAny<TValue> extends true ? false : TValue extends readonly unknown[] ? true : TValue extends Record<string, unknown> ? true extends { [TKey in keyof TValue]: IsOrHasArray<TValue[TKey]> }[keyof TValue] ? true : false : false;
140
+ /**
141
+ * Extracts the exact keys of a tuple, array or object that contain arrays.
142
+ */
143
+ type KeyOfArrayPath<TValue> = IsAny<TValue> extends true ? never : TValue extends readonly (infer TItem)[] ? number extends TValue["length"] ? IsOrHasArray<TItem> extends true ? number : never : { [TKey in keyof TValue]: TKey extends `${infer TIndex extends number}` ? IsOrHasArray<TValue[TKey]> extends true ? TIndex : never : never }[number] : TValue extends Record<string, unknown> ? { [TKey in keyof TValue]: IsOrHasArray<TValue[TKey]> extends true ? TKey : never }[keyof TValue] & PathKey : never;
144
+ /**
145
+ * Lazily evaluate only the first valid array path segment based on the given value.
146
+ */
147
+ type LazyArrayPath<TValue, TPathToCheck extends Path, TValidPath extends Path = readonly []> = TPathToCheck extends readonly [] ? TValue extends readonly unknown[] ? TValidPath : readonly [...TValidPath, KeyOfArrayPath<TValue>] : TPathToCheck extends readonly [infer TFirstKey extends KeyOfArrayPath<TValue>, ...infer TPathRest extends Path] ? LazyArrayPath<MergeUnion<TValue>[TFirstKey], TPathRest, readonly [...TValidPath, TFirstKey]> : IsNever<KeyOfArrayPath<TValue>> extends false ? readonly [...TValidPath, KeyOfArrayPath<TValue>] : never;
148
+ /**
149
+ * Returns the path if valid, otherwise the first possible valid array path based on
150
+ * the given value.
151
+ */
152
+ type ValidArrayPath<TValue, TPath extends RequiredPath> = TPath extends LazyArrayPath<TValue, TPath> ? TPath : LazyArrayPath<TValue, TPath>;
153
+ //#endregion
154
+ //#region src/array/copyItemState/copyItemState.d.ts
155
+ /**
156
+ * Copies the deeply nested state (signal values) from one array item to another.
157
+ * This includes the `isTouched`, `isDirty`, `startInput`, `input`, `startItems`, and `items` properties.
158
+ * Recursively walks through the field stores and copies all signal values.
159
+ *
160
+ * @param internalArrayStore - The field store of the array (not the array item)
161
+ * @param fromIndex - The source index to copy from
162
+ * @param toIndex - The destination index to copy to
163
+ */
164
+ //#endregion
165
+ //#region ../../packages/methods/dist/index.preact.d.ts
166
+ //#region src/focus/focus.d.ts
167
+ interface FocusFieldConfig<TSchema extends Schema, TFieldPath extends RequiredPath> {
168
+ readonly form: BaseFormStore<TSchema>;
169
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
170
+ }
171
+ declare function focus<TSchema extends Schema, TFieldPath extends RequiredPath>(config: FocusFieldConfig<TSchema, TFieldPath>): void;
172
+ //#endregion
173
+ //#region src/getAllErrors/getAllErrors.d.ts
174
+ declare function getAllErrors(form: BaseFormStore): [string, ...string[]] | null;
175
+ //#endregion
176
+ //#region src/getErrors/getErrors.d.ts
177
+ interface GetFormErrorsConfig {
178
+ readonly path?: undefined;
179
+ }
180
+ interface GetFieldErrorsConfig<TSchema extends Schema, TFieldPath extends RequiredPath> {
181
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
182
+ }
183
+ declare function getErrors<TSchema extends Schema>(form: BaseFormStore<TSchema>): [string, ...string[]] | null;
184
+ declare function getErrors<TSchema extends Schema, TFieldPath extends RequiredPath | undefined = undefined>(form: BaseFormStore<TSchema>, config: TFieldPath extends RequiredPath ? GetFieldErrorsConfig<TSchema, TFieldPath> : GetFormErrorsConfig): [string, ...string[]] | null;
185
+ //#endregion
186
+ //#region src/getInput/getInput.d.ts
187
+ interface GetFormInputConfig {
188
+ readonly path?: undefined;
189
+ }
190
+ interface GetFieldInputConfig<TSchema extends Schema, TFieldPath extends RequiredPath> {
191
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
192
+ }
193
+ declare function getInput<TSchema extends Schema>(form: BaseFormStore<TSchema>): PartialValues<v.InferInput<TSchema>>;
194
+ declare function getInput<TSchema extends Schema, TFieldPath extends RequiredPath | undefined = undefined>(form: BaseFormStore<TSchema>, config: TFieldPath extends RequiredPath ? GetFieldInputConfig<TSchema, TFieldPath> : GetFormInputConfig): PartialValues<TFieldPath extends RequiredPath ? PathValue<v.InferInput<TSchema>, TFieldPath> : v.InferInput<TSchema>>;
195
+ //#endregion
196
+ //#region src/insert/insert.d.ts
197
+ interface InsertConfig<TSchema extends Schema, TFieldArrayPath extends RequiredPath> {
198
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
199
+ readonly at?: number | undefined;
200
+ readonly initialInput?: DeepPartial<PathValue<v.InferInput<TSchema>, [...TFieldArrayPath, number]>> | undefined;
201
+ }
202
+ declare function insert<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: BaseFormStore<TSchema>, config: InsertConfig<TSchema, TFieldArrayPath>): void;
203
+ //#endregion
204
+ //#region src/move/move.d.ts
205
+ interface MoveConfig<TSchema extends Schema, TFieldArrayPath extends RequiredPath> {
206
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
207
+ readonly from: number;
208
+ readonly to: number;
209
+ }
210
+ declare function move<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: BaseFormStore<TSchema>, config: MoveConfig<TSchema, TFieldArrayPath>): void;
211
+ //#endregion
212
+ //#region src/remove/remove.d.ts
213
+ interface RemoveConfig<TSchema extends Schema, TFieldArrayPath extends RequiredPath> {
214
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
215
+ readonly at: number;
216
+ }
217
+ declare function remove<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: BaseFormStore<TSchema>, config: RemoveConfig<TSchema, TFieldArrayPath>): void;
218
+ //#endregion
219
+ //#region src/replace/replace.d.ts
220
+ interface ReplaceConfig<TSchema extends Schema, TFieldArrayPath extends RequiredPath> {
221
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
222
+ readonly at: number;
223
+ readonly initialInput?: DeepPartial<PathValue<v.InferInput<TSchema>, [...TFieldArrayPath, number]>> | undefined;
224
+ }
225
+ declare function replace<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: BaseFormStore<TSchema>, config: ReplaceConfig<TSchema, TFieldArrayPath>): void;
226
+ //#endregion
227
+ //#region src/reset/reset.d.ts
228
+ interface ResetBaseConfig {
229
+ readonly keepInput?: boolean | undefined;
230
+ readonly keepTouched?: boolean | undefined;
231
+ readonly keepErrors?: boolean | undefined;
232
+ }
233
+ interface ResetFormConfig<TSchema extends Schema> extends ResetBaseConfig {
234
+ readonly path?: undefined;
235
+ readonly initialInput?: DeepPartial<v.InferInput<TSchema>> | undefined;
236
+ readonly keepSubmitCount?: boolean | undefined;
237
+ readonly keepSubmitted?: boolean | undefined;
238
+ }
239
+ interface ResetFieldConfig<TSchema extends Schema, TFieldPath extends RequiredPath> extends ResetBaseConfig {
240
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
241
+ readonly initialInput?: DeepPartial<PathValue<v.InferInput<TSchema>, TFieldPath>>;
242
+ }
243
+ declare function reset(form: BaseFormStore): void;
244
+ declare function reset<TSchema extends Schema, TFieldPath extends RequiredPath | undefined = undefined>(form: BaseFormStore<TSchema>, config: TFieldPath extends RequiredPath ? ResetFieldConfig<TSchema, TFieldPath> : ResetFormConfig<TSchema>): void;
245
+ //#endregion
246
+ //#region src/setErrors/setErrors.d.ts
247
+ interface SetFormErrorsConfig {
248
+ readonly path?: undefined;
249
+ readonly errors: [string, ...string[]] | null;
250
+ }
251
+ interface SetFieldErrorsConfig<TSchema extends Schema, TFieldPath extends RequiredPath> {
252
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
253
+ readonly errors: [string, ...string[]] | null;
254
+ }
255
+ declare function setErrors<TSchema extends Schema, TFieldPath extends RequiredPath | undefined = undefined>(form: BaseFormStore<TSchema>, config: TFieldPath extends RequiredPath ? SetFieldErrorsConfig<TSchema, TFieldPath> : SetFormErrorsConfig): void;
256
+ //#endregion
257
+ //#region src/setInput/setInput.d.ts
258
+ interface SetFormInputConfig<TSchema extends Schema> {
259
+ readonly path?: undefined;
260
+ readonly input: v.InferInput<TSchema>;
261
+ }
262
+ interface SetFieldInputConfig<TSchema extends Schema, TFieldPath extends RequiredPath> {
263
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
264
+ readonly input: PathValue<v.InferInput<TSchema>, TFieldPath>;
265
+ }
266
+ declare function setInput<TSchema extends Schema>(form: BaseFormStore<TSchema>, config: SetFormInputConfig<TSchema>): void;
267
+ declare function setInput<TSchema extends Schema, TFieldPath extends RequiredPath | undefined = undefined>(form: BaseFormStore<TSchema>, config: TFieldPath extends RequiredPath ? SetFieldInputConfig<TSchema, TFieldPath> : SetFormInputConfig<TSchema>): void;
268
+ //#endregion
269
+ //#region src/submit/submit.d.ts
270
+ declare function submit(form: BaseFormStore): void;
271
+ //#endregion
272
+ //#region src/swap/swap.d.ts
273
+ interface SwapConfig<TSchema extends Schema, TFieldArrayPath extends RequiredPath> {
274
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
275
+ readonly at: number;
276
+ readonly and: number;
277
+ }
278
+ declare function swap<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: BaseFormStore<TSchema>, config: SwapConfig<TSchema, TFieldArrayPath>): void;
279
+ //#endregion
280
+ //#region src/validate/validate.d.ts
281
+ interface ValidateFormConfig {
282
+ readonly shouldFocus?: boolean | undefined;
283
+ }
284
+ declare function validate<TSchema extends Schema>(form: BaseFormStore<TSchema>, config?: ValidateFormConfig): Promise<v.SafeParseResult<TSchema>>;
285
+ //#endregion
286
+ //#endregion
287
+ //#region src/types/field.d.ts
288
+ /**
289
+ * Value type of the field element props.
290
+ */
291
+ interface FieldElementProps {
292
+ readonly name: string;
293
+ readonly autofocus: boolean;
294
+ readonly ref: (element: FieldElement) => void;
295
+ readonly onFocus: JSX.FocusEventHandler<FieldElement>;
296
+ readonly onInput: JSX.InputEventHandler<FieldElement>;
297
+ readonly onChange: JSX.GenericEventHandler<FieldElement>;
298
+ readonly onBlur: JSX.FocusEventHandler<FieldElement>;
299
+ }
300
+ /**
301
+ * Value type of the field store.
302
+ */
303
+ interface FieldStore<TSchema extends Schema = Schema, TFieldPath extends RequiredPath = RequiredPath> {
304
+ readonly path: ReadonlySignal<ValidPath<v.InferInput<TSchema>, TFieldPath>>;
305
+ readonly input: ReadonlySignal<PartialValues<PathValue<v.InferInput<TSchema>, TFieldPath>>>;
306
+ readonly errors: ReadonlySignal<[string, ...string[]] | null>;
307
+ readonly isTouched: ReadonlySignal<boolean>;
308
+ readonly isDirty: ReadonlySignal<boolean>;
309
+ readonly isValid: ReadonlySignal<boolean>;
310
+ readonly props: FieldElementProps;
311
+ }
312
+ /**
313
+ * Value type of the field array store.
314
+ */
315
+ interface FieldArrayStore<TSchema extends Schema = Schema, TFieldArrayPath extends RequiredPath = RequiredPath> {
316
+ readonly path: ReadonlySignal<ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>>;
317
+ readonly items: ReadonlySignal<string[]>;
318
+ readonly errors: ReadonlySignal<[string, ...string[]] | null>;
319
+ readonly isTouched: ReadonlySignal<boolean>;
320
+ readonly isDirty: ReadonlySignal<boolean>;
321
+ readonly isValid: ReadonlySignal<boolean>;
322
+ }
323
+ //#endregion
324
+ //#region src/types/form.d.ts
325
+ interface FormStore<TSchema extends Schema = Schema> extends BaseFormStore<TSchema> {
326
+ readonly isSubmitting: ReadonlySignal<boolean>;
327
+ readonly isSubmitted: ReadonlySignal<boolean>;
328
+ readonly isValidating: ReadonlySignal<boolean>;
329
+ readonly isTouched: ReadonlySignal<boolean>;
330
+ readonly isDirty: ReadonlySignal<boolean>;
331
+ readonly isValid: ReadonlySignal<boolean>;
332
+ readonly errors: ReadonlySignal<[string, ...string[]] | null>;
333
+ }
334
+ //#endregion
335
+ //#region src/components/Field/Field.d.ts
336
+ /**
337
+ * Properties of the `Field` component.
338
+ */
339
+ interface FieldProps<TSchema extends Schema = Schema, TFieldPath extends RequiredPath = RequiredPath> {
340
+ readonly of: FormStore<TSchema>;
341
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
342
+ readonly render: (store: FieldStore<TSchema, TFieldPath>) => JSX.Element;
343
+ }
344
+ /**
345
+ * Headless form field that provides reactive properties and state.
346
+ */
347
+ declare function Field<TSchema extends Schema, TFieldPath extends RequiredPath>({
348
+ of,
349
+ path,
350
+ render
351
+ }: FieldProps<TSchema, TFieldPath>): JSX.Element;
352
+ //#endregion
353
+ //#region src/components/FieldArray/FieldArray.d.ts
354
+ /**
355
+ * Properties of the `FieldArray` component.
356
+ */
357
+ interface FieldArrayProps<TSchema extends Schema = Schema, TFieldArrayPath extends RequiredPath = RequiredPath> {
358
+ readonly of: FormStore<TSchema>;
359
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
360
+ readonly render: (store: FieldArrayStore<TSchema, TFieldArrayPath>) => JSX.Element;
361
+ }
362
+ /**
363
+ * Headless field array that provides reactive properties and state.
364
+ */
365
+ declare function FieldArray<TSchema extends Schema, TFieldArrayPath extends RequiredPath>({
366
+ of,
367
+ path,
368
+ render
369
+ }: FieldArrayProps<TSchema, TFieldArrayPath>): JSX.Element;
370
+ //#endregion
371
+ //#region src/components/Form/Form.d.ts
372
+ type FormProps<TSchema extends Schema = Schema> = Omit<JSX.FormHTMLAttributes<HTMLFormElement>, "onSubmit"> & {
373
+ of: FormStore<TSchema>;
374
+ onSubmit: SubmitHandler<TSchema>;
375
+ };
376
+ declare function Form<TSchema extends Schema>(props: FormProps<TSchema>): JSX.Element;
377
+ //#endregion
378
+ //#region src/hooks/useField/useField.d.ts
379
+ interface UseFieldConfig<TSchema extends Schema = Schema, TFieldPath extends RequiredPath = RequiredPath> {
380
+ readonly path: ValidPath<v.InferInput<TSchema>, TFieldPath>;
381
+ }
382
+ declare function useField<TSchema extends Schema, TFieldPath extends RequiredPath>(form: FormStore<TSchema>, config: UseFieldConfig<TSchema, TFieldPath>): FieldStore<TSchema, TFieldPath>;
383
+ //#endregion
384
+ //#region src/hooks/useFieldArray/useFieldArray.d.ts
385
+ interface UseFieldArrayConfig<TSchema extends Schema = Schema, TFieldArrayPath extends RequiredPath = RequiredPath> {
386
+ readonly path: ValidArrayPath<v.InferInput<TSchema>, TFieldArrayPath>;
387
+ }
388
+ declare function useFieldArray<TSchema extends Schema, TFieldArrayPath extends RequiredPath>(form: FormStore<TSchema>, config: UseFieldArrayConfig<TSchema, TFieldArrayPath>): FieldArrayStore<TSchema, TFieldArrayPath>;
389
+ //#endregion
390
+ //#region src/hooks/useForm/useForm.d.ts
391
+ declare function useForm<TSchema extends Schema>(config: FormConfig<TSchema>): FormStore<TSchema>;
392
+ //#endregion
393
+ export { Field, FieldArray, FieldArrayProps, FieldArrayStore, FieldElementProps, FieldProps, FieldStore, FocusFieldConfig, Form, FormProps, FormStore, GetFieldErrorsConfig, GetFieldInputConfig, GetFormErrorsConfig, GetFormInputConfig, InsertConfig, MoveConfig, RemoveConfig, ReplaceConfig, ResetFieldConfig, ResetFormConfig, SetFieldErrorsConfig, SetFieldInputConfig, SetFormErrorsConfig, SetFormInputConfig, SwapConfig, UseFieldArrayConfig, UseFieldConfig, ValidateFormConfig, focus, getAllErrors, getErrors, getInput, insert, move, remove, replace, reset, setErrors, setInput, submit, swap, useField, useFieldArray, useForm, validate };
package/dist/index.js ADDED
@@ -0,0 +1,674 @@
1
+ import * as v from "valibot";
2
+ import { batch, computed, signal as createSignal, untracked as untrack, useComputed, useSignal, useSignalEffect } from "@preact/signals";
3
+ import { useLayoutEffect, useMemo } from "preact/hooks";
4
+ import { jsx } from "preact/jsx-runtime";
5
+
6
+ //#region ../../packages/core/dist/index.preact.js
7
+ const framework = "preact";
8
+ function createId() {
9
+ return Math.random().toString(36).slice(2);
10
+ }
11
+ /**
12
+ * TODO: Add comment
13
+ * TODO: Should this stay in /primitives or move to /utils?
14
+ */
15
+ function initializeFieldStore(internalFieldStore, schema, initialInput, path) {
16
+ if (framework === "qwik" && schema.type === "lazy" || schema.type === "object_with_rest" || schema.type === "record" || schema.type === "tuple_with_rest" || schema.type === "promise") throw new Error(`"${schema.type}" schema is not supported`);
17
+ else if (schema.type === "lazy") initializeFieldStore(internalFieldStore, schema.getter(void 0), initialInput, path);
18
+ else if (schema.type === "exact_optional" || schema.type === "non_nullable" || schema.type === "non_nullish" || schema.type === "non_optional" || schema.type === "nullable" || schema.type === "nullish" || schema.type === "optional" || schema.type === "undefinedable") initializeFieldStore(internalFieldStore, schema.wrapped, initialInput ?? v.getDefault(schema), path);
19
+ else if (schema.type === "intersect" || schema.type === "union" || schema.type === "variant") for (const schemaOption of schema.options) initializeFieldStore(internalFieldStore, schemaOption, initialInput, path);
20
+ else {
21
+ internalFieldStore.schema = schema;
22
+ internalFieldStore.name = JSON.stringify(path);
23
+ internalFieldStore.elements = [];
24
+ internalFieldStore.errors = createSignal(null);
25
+ if (schema.type === "array" || schema.type === "loose_tuple" || schema.type === "strict_tuple" || schema.type === "tuple") {
26
+ if (internalFieldStore.kind && internalFieldStore.kind !== "array") throw new Error(`Store initialized as "${internalFieldStore.kind}" cannot be reinitialized as "array"`);
27
+ internalFieldStore.kind = "array";
28
+ if (internalFieldStore.kind === "array") {
29
+ internalFieldStore.children ??= [];
30
+ if (schema.type === "array") {
31
+ if (initialInput) for (let index = 0; index < initialInput.length; index++) {
32
+ internalFieldStore.children[index] = {};
33
+ path.push(index);
34
+ initializeFieldStore(internalFieldStore.children[index], schema.item, initialInput[index], path);
35
+ path.pop();
36
+ }
37
+ } else for (let index = 0; index < schema.items; index++) {
38
+ internalFieldStore.children[index] = {};
39
+ path.push(index);
40
+ initializeFieldStore(internalFieldStore.children[index], schema.items[index], initialInput && initialInput[index], path);
41
+ path.pop();
42
+ }
43
+ const initialItems = internalFieldStore.children.map(createId);
44
+ internalFieldStore.initialItems = createSignal(initialItems);
45
+ internalFieldStore.startItems = createSignal(initialItems);
46
+ internalFieldStore.items = createSignal(initialItems);
47
+ internalFieldStore.isTouched = createSignal(false);
48
+ internalFieldStore.isDirty = createSignal(false);
49
+ }
50
+ } else if (schema.type === "loose_object" || schema.type === "object" || schema.type === "strict_object") {
51
+ if (internalFieldStore.kind && internalFieldStore.kind !== "object") throw new Error(`Store initialized as "${internalFieldStore.kind}" cannot be reinitialized as "object"`);
52
+ internalFieldStore.kind = "object";
53
+ if (internalFieldStore.kind === "object") {
54
+ internalFieldStore.children ??= {};
55
+ for (const key in schema.entries) {
56
+ internalFieldStore.children[key] = {};
57
+ path.push(key);
58
+ initializeFieldStore(internalFieldStore.children[key], schema.entries[key], initialInput && initialInput[key], path);
59
+ path.pop();
60
+ }
61
+ }
62
+ } else {
63
+ internalFieldStore.kind = "value";
64
+ if (internalFieldStore.kind === "value") {
65
+ internalFieldStore.initialInput = createSignal(initialInput);
66
+ internalFieldStore.startInput = createSignal(initialInput);
67
+ internalFieldStore.input = createSignal(initialInput);
68
+ internalFieldStore.isTouched = createSignal(false);
69
+ internalFieldStore.isDirty = createSignal(false);
70
+ }
71
+ }
72
+ }
73
+ }
74
+ /**
75
+ * Copies the deeply nested state (signal values) from one array item to another.
76
+ * This includes the `isTouched`, `isDirty`, `startInput`, `input`, `startItems`, and `items` properties.
77
+ * Recursively walks through the field stores and copies all signal values.
78
+ *
79
+ * @param internalArrayStore - The field store of the array (not the array item)
80
+ * @param fromIndex - The source index to copy from
81
+ * @param toIndex - The destination index to copy to
82
+ */
83
+ function copyItemState(fromInternalFieldStore, toInternalFieldStore) {
84
+ batch(() => {
85
+ untrack(() => {
86
+ if (fromInternalFieldStore.kind === "array" && toInternalFieldStore.kind === "array") {
87
+ const fromItems = fromInternalFieldStore.items.value;
88
+ toInternalFieldStore.isTouched.value = fromInternalFieldStore.isTouched.value;
89
+ toInternalFieldStore.isDirty.value = fromInternalFieldStore.isDirty.value;
90
+ toInternalFieldStore.startItems.value = fromInternalFieldStore.startItems.value;
91
+ toInternalFieldStore.items.value = fromItems;
92
+ let path;
93
+ for (let index = 0; index < fromItems.length; index++) {
94
+ if (!toInternalFieldStore.children[index]) {
95
+ path ??= JSON.parse(toInternalFieldStore.name);
96
+ toInternalFieldStore.children[index] = {};
97
+ path.push(index);
98
+ initializeFieldStore(toInternalFieldStore.children[index], toInternalFieldStore.schema.item, void 0, path);
99
+ path.pop();
100
+ }
101
+ copyItemState(fromInternalFieldStore.children[index], toInternalFieldStore.children[index]);
102
+ }
103
+ } else if (fromInternalFieldStore.kind === "object" && toInternalFieldStore.kind === "object") for (const key in fromInternalFieldStore.children) copyItemState(fromInternalFieldStore.children[key], toInternalFieldStore.children[key]);
104
+ else if (fromInternalFieldStore.kind === "value" && toInternalFieldStore.kind === "value") {
105
+ toInternalFieldStore.isTouched.value = fromInternalFieldStore.isTouched.value;
106
+ toInternalFieldStore.isDirty.value = fromInternalFieldStore.isDirty.value;
107
+ toInternalFieldStore.startInput.value = fromInternalFieldStore.startInput.value;
108
+ toInternalFieldStore.input.value = fromInternalFieldStore.input.value;
109
+ }
110
+ });
111
+ });
112
+ }
113
+ /**
114
+ * Resets the state of an array item (signal values) deeply nested.
115
+ * Sets `isTouched` and `isDirty` to `false` and `startInput`, `input`,
116
+ * `startItems` and `items` to the new input.
117
+ * Keeps the `initialInput` and `initialItems` state unchanged for form reset functionality.
118
+ *
119
+ * @param internalFieldStore - The field store of the array item
120
+ * @param initialInput - The new input value (can be any type including array or object)
121
+ */
122
+ function resetItemState(internalFieldStore, initialInput) {
123
+ batch(() => {
124
+ if (internalFieldStore.kind === "array") {
125
+ internalFieldStore.isTouched.value = false;
126
+ internalFieldStore.isDirty.value = false;
127
+ if (initialInput) {
128
+ const newItems = initialInput.map(createId);
129
+ internalFieldStore.startItems.value = newItems;
130
+ internalFieldStore.items.value = newItems;
131
+ for (let index = 0; index < initialInput.length; index++) if (internalFieldStore.children[index]) resetItemState(internalFieldStore.children[index], initialInput[index]);
132
+ } else {
133
+ internalFieldStore.startItems.value = [];
134
+ internalFieldStore.items.value = [];
135
+ }
136
+ } else if (internalFieldStore.kind === "object") for (const key in internalFieldStore.children) resetItemState(internalFieldStore.children[key], initialInput?.[key]);
137
+ else {
138
+ internalFieldStore.isTouched.value = false;
139
+ internalFieldStore.isDirty.value = false;
140
+ internalFieldStore.startInput.value = initialInput;
141
+ internalFieldStore.input.value = initialInput;
142
+ }
143
+ });
144
+ }
145
+ /**
146
+ * Swaps the deeply nested state (signal values) between two field stores.
147
+ * This includes the `isTouched`, `isDirty`, `startInput`, `input`, `startItems`, and `items` properties.
148
+ * Recursively walks through the field stores and swaps all signal values.
149
+ *
150
+ * @param firstInternalFieldStore - The first field store to swap
151
+ * @param secondInternalFieldStore - The second field store to swap
152
+ */
153
+ function swapItemState(firstInternalFieldStore, secondInternalFieldStore) {
154
+ batch(() => {
155
+ untrack(() => {
156
+ if (firstInternalFieldStore.kind === "array" && secondInternalFieldStore.kind === "array") {
157
+ const firstItems = firstInternalFieldStore.items.value;
158
+ const secondItems = secondInternalFieldStore.items.value;
159
+ const tempIsTouched = firstInternalFieldStore.isTouched.value;
160
+ firstInternalFieldStore.isTouched.value = secondInternalFieldStore.isTouched.value;
161
+ secondInternalFieldStore.isTouched.value = tempIsTouched;
162
+ const tempIsDirty = firstInternalFieldStore.isDirty.value;
163
+ firstInternalFieldStore.isDirty.value = secondInternalFieldStore.isDirty.value;
164
+ secondInternalFieldStore.isDirty.value = tempIsDirty;
165
+ const tempStartItems = firstInternalFieldStore.startItems.value;
166
+ firstInternalFieldStore.startItems.value = secondInternalFieldStore.startItems.value;
167
+ secondInternalFieldStore.startItems.value = tempStartItems;
168
+ firstInternalFieldStore.items.value = secondItems;
169
+ secondInternalFieldStore.items.value = firstItems;
170
+ const maxLength = Math.max(firstItems.length, secondItems.length);
171
+ let firstPath;
172
+ let secondPath;
173
+ for (let index = 0; index < maxLength; index++) {
174
+ if (!firstInternalFieldStore.children[index]) {
175
+ firstPath ??= JSON.parse(firstInternalFieldStore.name);
176
+ firstInternalFieldStore.children[index] = {};
177
+ firstPath.push(index);
178
+ initializeFieldStore(firstInternalFieldStore.children[index], firstInternalFieldStore.schema.item, void 0, firstPath);
179
+ firstPath.pop();
180
+ }
181
+ if (!secondInternalFieldStore.children[index]) {
182
+ secondPath ??= JSON.parse(secondInternalFieldStore.name);
183
+ secondInternalFieldStore.children[index] = {};
184
+ secondPath.push(index);
185
+ initializeFieldStore(secondInternalFieldStore.children[index], secondInternalFieldStore.schema.item, void 0, secondPath);
186
+ secondPath.pop();
187
+ }
188
+ swapItemState(firstInternalFieldStore.children[index], secondInternalFieldStore.children[index]);
189
+ }
190
+ } else if (firstInternalFieldStore.kind === "object" && secondInternalFieldStore.kind === "object") for (const key in firstInternalFieldStore.children) swapItemState(firstInternalFieldStore.children[key], secondInternalFieldStore.children[key]);
191
+ else if (firstInternalFieldStore.kind === "value" && secondInternalFieldStore.kind === "value") {
192
+ const tempIsTouched = firstInternalFieldStore.isTouched.value;
193
+ firstInternalFieldStore.isTouched.value = secondInternalFieldStore.isTouched.value;
194
+ secondInternalFieldStore.isTouched.value = tempIsTouched;
195
+ const tempIsDirty = firstInternalFieldStore.isDirty.value;
196
+ firstInternalFieldStore.isDirty.value = secondInternalFieldStore.isDirty.value;
197
+ secondInternalFieldStore.isDirty.value = tempIsDirty;
198
+ const tempStartInput = firstInternalFieldStore.startInput.value;
199
+ firstInternalFieldStore.startInput.value = secondInternalFieldStore.startInput.value;
200
+ secondInternalFieldStore.startInput.value = tempStartInput;
201
+ const tempInput = firstInternalFieldStore.input.value;
202
+ firstInternalFieldStore.input.value = secondInternalFieldStore.input.value;
203
+ secondInternalFieldStore.input.value = tempInput;
204
+ }
205
+ });
206
+ });
207
+ }
208
+ function getFieldInput(internalFieldStore) {
209
+ if (internalFieldStore.kind === "array") {
210
+ const value = [];
211
+ for (let index = 0; index < internalFieldStore.items.value.length; index++) value[index] = getFieldInput(internalFieldStore.children[index]);
212
+ return value;
213
+ }
214
+ if (internalFieldStore.kind === "object") {
215
+ const value = {};
216
+ for (const key in internalFieldStore.children) value[key] = getFieldInput(internalFieldStore.children[key]);
217
+ return value;
218
+ }
219
+ return internalFieldStore.input.value;
220
+ }
221
+ /**
222
+ * Returns the current input of the element.
223
+ *
224
+ * @param element The field element.
225
+ * @param interalFieldStore The interal field store.
226
+ *
227
+ * @returns The element input.
228
+ */
229
+ function getElementInput(element, internalFieldStore) {
230
+ if (element.options && element.multiple) return [...element.options].filter((option) => option.selected && !option.disabled).map((option) => option.value);
231
+ if (element.type === "checkbox") {
232
+ const options = document.getElementsByName(element.name);
233
+ if (options.length > 1) return [...options].filter((option) => option.checked).map((option) => option.value);
234
+ return element.checked;
235
+ }
236
+ if (element.type === "radio") {
237
+ const prevValue = untrack(() => getFieldInput(internalFieldStore));
238
+ if (element.checked) return [...prevValue, element.value];
239
+ return prevValue.filter((value) => value !== element.value);
240
+ }
241
+ if (element.type === "file") {
242
+ if (element.multiple) return [...element.files];
243
+ return element.files[0];
244
+ }
245
+ return element.value;
246
+ }
247
+ function getFieldBool(internalFieldStore, type) {
248
+ if (internalFieldStore.kind === "array") {
249
+ if (internalFieldStore[type].value) return true;
250
+ for (let index = 0; index < internalFieldStore.items.value.length; index++) if (getFieldBool(internalFieldStore.children[index], type)) return true;
251
+ return false;
252
+ }
253
+ if (internalFieldStore.kind == "object") {
254
+ if (type === "errors" && internalFieldStore[type].value) return true;
255
+ for (const key in internalFieldStore.children) if (getFieldBool(internalFieldStore.children[key], type)) return true;
256
+ return false;
257
+ }
258
+ return !!internalFieldStore[type].value;
259
+ }
260
+ function getFieldStore(internalFormStore, path) {
261
+ let internalFieldStore = internalFormStore;
262
+ for (const key of path) internalFieldStore = internalFieldStore.children[key];
263
+ return internalFieldStore;
264
+ }
265
+ function setFieldBool(internalFieldStore, type, bool) {
266
+ batch(() => {
267
+ if (internalFieldStore.kind === "array") {
268
+ internalFieldStore[type].value = bool;
269
+ for (let index = 0; index < untrack(() => internalFieldStore.items.value).length; index++) setFieldBool(internalFieldStore.children[index], type, bool);
270
+ } else if (internalFieldStore.kind == "object") for (const key in internalFieldStore.children) setFieldBool(internalFieldStore.children[key], type, bool);
271
+ else internalFieldStore[type].value = bool;
272
+ });
273
+ }
274
+ function setFieldInput(internalFieldStore, input) {
275
+ batch(() => {
276
+ if (internalFieldStore.kind === "array") {
277
+ const items = untrack(() => internalFieldStore.items.value);
278
+ if (input.length < items.length) internalFieldStore.items.value = items.slice(0, input.length);
279
+ else if (input.length > items.length) {
280
+ if (input.length > internalFieldStore.children.length) {
281
+ const path = JSON.parse(internalFieldStore.name);
282
+ for (let index = internalFieldStore.children.length; index < input.length; index++) {
283
+ internalFieldStore.children[index] = {};
284
+ path.push(index);
285
+ initializeFieldStore(internalFieldStore.children[index], internalFieldStore.schema.item, input[index], path);
286
+ path.pop();
287
+ }
288
+ }
289
+ internalFieldStore.items.value = [...items, ...input.slice(items.length).map(createId)];
290
+ }
291
+ for (let index = 0; index < items.length; index++) setFieldInput(internalFieldStore.children[index], input[index]);
292
+ internalFieldStore.isDirty.value = untrack(() => internalFieldStore.startItems.value).length !== items.length;
293
+ } else if (internalFieldStore.kind === "object") for (const key in internalFieldStore.children) setFieldInput(internalFieldStore.children[key], input[key]);
294
+ else {
295
+ internalFieldStore.input.value = input;
296
+ const startInput = untrack(() => internalFieldStore.startInput.value);
297
+ internalFieldStore.isDirty.value = startInput !== input && (startInput !== void 0 || input !== "" && !Number.isNaN(input));
298
+ }
299
+ });
300
+ }
301
+ function setInitialFieldInput(internalFieldStore, initialInput) {
302
+ batch(() => {
303
+ if (internalFieldStore.kind === "array") {
304
+ if (initialInput.length > internalFieldStore.children.length) {
305
+ const path = JSON.parse(internalFieldStore.name);
306
+ for (let index = internalFieldStore.children.length; index < initialInput.length; index++) {
307
+ internalFieldStore.children[index] = {};
308
+ path.push(index);
309
+ initializeFieldStore(internalFieldStore.children[index], internalFieldStore.schema.item, initialInput[index], path);
310
+ path.pop();
311
+ }
312
+ }
313
+ internalFieldStore.initialItems.value = initialInput.map(createId);
314
+ for (let index = 0; index < internalFieldStore.children.length; index++) setInitialFieldInput(internalFieldStore.children[index], initialInput?.[index]);
315
+ } else if (internalFieldStore.kind === "object") for (const key in internalFieldStore.children) setInitialFieldInput(internalFieldStore.children[key], initialInput?.[key]);
316
+ else internalFieldStore.initialInput.value = initialInput;
317
+ });
318
+ }
319
+ function walkFieldStore(internalFieldStore, callback) {
320
+ callback(internalFieldStore);
321
+ if (internalFieldStore.kind === "array") for (let index = 0; index < untrack(() => internalFieldStore.items.value).length; index++) walkFieldStore(internalFieldStore.children[index], callback);
322
+ else if (internalFieldStore.kind === "object") for (const key in internalFieldStore.children) walkFieldStore(internalFieldStore.children[key], callback);
323
+ }
324
+ function createFormStore(config, validate$1) {
325
+ const store = {};
326
+ initializeFieldStore(store, config.schema, config.initialInput, []);
327
+ store.validateOn = config.validateOn ?? "submit";
328
+ store.revalidateOn = config.revalidateOn ?? "input";
329
+ store.validate = validate$1;
330
+ store.isSubmitting = createSignal(false);
331
+ store.isSubmitted = createSignal(false);
332
+ store.isValidating = createSignal(false);
333
+ return store;
334
+ }
335
+ async function validateFormInput(internalFormStore, config) {
336
+ internalFormStore.validators++;
337
+ internalFormStore.isValidating.value = true;
338
+ const result = await internalFormStore.validate(untrack(() => getFieldInput(internalFormStore)));
339
+ let rootErrors;
340
+ let nestedErrors;
341
+ if (result.issues) {
342
+ nestedErrors = {};
343
+ for (const issue of result.issues) if (issue.path) {
344
+ const path = [];
345
+ for (const pathItem of issue.path) {
346
+ const key = pathItem.key;
347
+ const keyType = typeof key;
348
+ const itemType = pathItem.type;
349
+ if (keyType !== "string" && keyType !== "number" || itemType === "map" || itemType === "set") break;
350
+ path.push(key);
351
+ }
352
+ const name = JSON.stringify(path);
353
+ const fieldErrors = nestedErrors[name];
354
+ if (fieldErrors) fieldErrors.push(issue.message);
355
+ else nestedErrors[name] = [issue.message];
356
+ } else if (rootErrors) rootErrors.push(issue.message);
357
+ else rootErrors = [issue.message];
358
+ }
359
+ let shouldFocus = config?.shouldFocus ?? false;
360
+ batch(() => {
361
+ walkFieldStore(internalFormStore, (internalFieldStore) => {
362
+ if (internalFieldStore.name === "[]") internalFieldStore.errors.value = rootErrors ?? null;
363
+ else {
364
+ const fieldErrors = nestedErrors?.[internalFieldStore.name] ?? null;
365
+ internalFieldStore.errors.value = fieldErrors;
366
+ if (shouldFocus && fieldErrors) {
367
+ internalFieldStore.elements[0]?.focus();
368
+ shouldFocus = false;
369
+ }
370
+ }
371
+ });
372
+ internalFormStore.validators--;
373
+ internalFormStore.isValidating.value = internalFormStore.validators > 0;
374
+ });
375
+ return result;
376
+ }
377
+ function validateIfRequired(internalFormStore, internalFieldStore, validationModes) {
378
+ if (validationModes === (internalFormStore.validateOn === "initial" || (internalFormStore.validateOn === "submit" ? untrack(() => internalFormStore.isSubmitted.value) : untrack(() => getFieldBool(internalFieldStore, "errors"))) ? internalFormStore.revalidateOn : internalFormStore.validateOn)) validateFormInput(internalFormStore);
379
+ }
380
+ const INTERNAL = "~internal";
381
+
382
+ //#endregion
383
+ //#region ../../packages/methods/dist/index.preact.js
384
+ function focus(config) {
385
+ getFieldStore(config.form[INTERNAL], config.path).elements[0]?.focus();
386
+ }
387
+ function getAllErrors(form) {
388
+ let allErrors = null;
389
+ walkFieldStore(form[INTERNAL], (internalFieldStore) => {
390
+ const errors = internalFieldStore.errors.value;
391
+ if (errors) if (allErrors) allErrors.push(...errors);
392
+ else allErrors = [...errors];
393
+ });
394
+ return allErrors;
395
+ }
396
+ function getErrors(form, config) {
397
+ return (config?.path ? getFieldStore(form[INTERNAL], config.path) : form[INTERNAL]).errors.value;
398
+ }
399
+ function getInput(form, config) {
400
+ return getFieldInput(config?.path ? getFieldStore(form[INTERNAL], config.path) : form[INTERNAL]);
401
+ }
402
+ function insert(form, config) {
403
+ const internalFormStore = form[INTERNAL];
404
+ const internalArrayStore = getFieldStore(internalFormStore, config.path);
405
+ const items = untrack(() => internalArrayStore.items.value);
406
+ const insertIndex = config.at === void 0 ? items.length : config.at;
407
+ if (insertIndex >= 0 && insertIndex <= items.length) batch(() => {
408
+ const newItems = [...items];
409
+ newItems.splice(insertIndex, 0, createId());
410
+ internalArrayStore.items.value = newItems;
411
+ for (let index = items.length; index > insertIndex; index--) copyItemState(internalArrayStore.children[index - 1], internalArrayStore.children[index]);
412
+ if (!internalArrayStore.children[insertIndex]) {
413
+ const path = JSON.parse(internalArrayStore.name);
414
+ internalArrayStore.children[insertIndex] = {};
415
+ path.push(insertIndex);
416
+ initializeFieldStore(internalArrayStore.children[insertIndex], internalArrayStore.schema.item, config.initialInput, path);
417
+ } else resetItemState(internalArrayStore.children[insertIndex], config.initialInput);
418
+ internalArrayStore.isTouched.value = true;
419
+ internalArrayStore.isDirty.value = true;
420
+ validateIfRequired(internalFormStore, internalArrayStore, "input");
421
+ });
422
+ }
423
+ function move(form, config) {
424
+ const internalFormStore = form[INTERNAL];
425
+ const internalArrayStore = getFieldStore(internalFormStore, config.path);
426
+ const items = untrack(() => internalArrayStore.items.value);
427
+ if (config.from >= 0 && config.from <= items.length - 1 && config.to >= 0 && config.to <= items.length - 1 && config.from !== config.to) batch(() => {
428
+ const newItems = [...items];
429
+ newItems.splice(config.to, 0, newItems.splice(config.from, 1)[0]);
430
+ internalArrayStore.items.value = newItems;
431
+ const tempInternalFieldStore = {};
432
+ initializeFieldStore(tempInternalFieldStore, internalArrayStore.schema.item, void 0, []);
433
+ copyItemState(internalArrayStore.children[config.from < config.to ? config.from : config.to], tempInternalFieldStore);
434
+ if (config.from < config.to) for (let index = config.from; index < config.to; index++) copyItemState(internalArrayStore.children[index + 1], internalArrayStore.children[index]);
435
+ else for (let index = config.from; index > config.to; index--) copyItemState(internalArrayStore.children[index - 1], internalArrayStore.children[index]);
436
+ copyItemState(tempInternalFieldStore, internalArrayStore.children[config.from < config.to ? config.to : config.from]);
437
+ internalArrayStore.isTouched.value = true;
438
+ internalArrayStore.isDirty.value = internalArrayStore.startItems.value.join() !== newItems.join();
439
+ validateIfRequired(internalFormStore, internalArrayStore, "input");
440
+ });
441
+ }
442
+ function remove(form, config) {
443
+ const internalFormStore = form[INTERNAL];
444
+ const internalArrayStore = getFieldStore(internalFormStore, config.path);
445
+ const items = untrack(() => internalArrayStore.items.value);
446
+ if (config.at >= 0 && config.at <= items.length - 1) batch(() => {
447
+ const newItems = [...items];
448
+ newItems.splice(config.at, 1);
449
+ internalArrayStore.items.value = newItems;
450
+ for (let index = config.at; index < items.length - 1; index++) copyItemState(internalArrayStore.children[index + 1], internalArrayStore.children[index]);
451
+ internalArrayStore.isTouched.value = true;
452
+ internalArrayStore.isDirty.value = internalArrayStore.startItems.value.join() !== newItems.join();
453
+ validateIfRequired(internalFormStore, internalArrayStore, "input");
454
+ });
455
+ }
456
+ function replace(form, config) {
457
+ const internalFormStore = form[INTERNAL];
458
+ const internalArrayStore = getFieldStore(internalFormStore, config.path);
459
+ const items = untrack(() => internalArrayStore.items.value);
460
+ if (config.at >= 0 && config.at <= items.length - 1) batch(() => {
461
+ const newItems = [...items];
462
+ newItems[config.at] = createId();
463
+ internalArrayStore.items.value = newItems;
464
+ resetItemState(internalArrayStore.children[config.at], config.initialInput);
465
+ internalArrayStore.isTouched.value = true;
466
+ internalArrayStore.isDirty.value = true;
467
+ validateIfRequired(internalFormStore, internalArrayStore, "input");
468
+ });
469
+ }
470
+ function reset(form, config) {
471
+ batch(() => {
472
+ untrack(() => {
473
+ const internalFormStore = form[INTERNAL];
474
+ const internalFieldStore = config?.path ? getFieldStore(internalFormStore, config.path) : internalFormStore;
475
+ if (config?.initialInput) setInitialFieldInput(internalFieldStore, config.initialInput);
476
+ walkFieldStore(internalFieldStore, (internalFieldStore$1) => {
477
+ if (!config?.keepErrors) internalFieldStore$1.errors.value = null;
478
+ if (internalFieldStore$1.kind === "array") {
479
+ internalFieldStore$1.startItems.value = internalFieldStore$1.initialItems.value;
480
+ if (!config?.keepInput || internalFieldStore$1.startItems.value.length === internalFieldStore$1.items.value.length) internalFieldStore$1.items.value = internalFieldStore$1.initialItems.value;
481
+ if (!config?.keepTouched) internalFieldStore$1.isTouched.value = false;
482
+ internalFieldStore$1.isDirty.value = internalFieldStore$1.startItems.value !== internalFieldStore$1.items.value;
483
+ } else if (internalFieldStore$1.kind === "value") {
484
+ internalFieldStore$1.startInput.value = internalFieldStore$1.initialInput.value;
485
+ if (!config?.keepInput) internalFieldStore$1.input.value = internalFieldStore$1.initialInput.value;
486
+ if (!config?.keepTouched) internalFieldStore$1.isTouched.value = false;
487
+ internalFieldStore$1.isDirty.value = internalFieldStore$1.startInput.value !== internalFieldStore$1.input.value;
488
+ for (const element of internalFieldStore$1.elements) if (element.type === "file") element.value = "";
489
+ }
490
+ });
491
+ if (!config?.path) {
492
+ if (!config?.keepSubmitted) internalFormStore.isSubmitted.value = false;
493
+ if (internalFormStore.validateOn === "initial") validateFormInput(internalFormStore);
494
+ }
495
+ });
496
+ });
497
+ }
498
+ function setErrors(form, config) {
499
+ (config.path ? getFieldStore(form[INTERNAL], config.path) : form[INTERNAL]).errors.value = config.errors;
500
+ }
501
+ function setInput(form, config) {
502
+ batch(() => {
503
+ const internalFormStore = form[INTERNAL];
504
+ const internalFieldStore = config.path ? getFieldStore(internalFormStore, config.path) : internalFormStore;
505
+ setFieldBool(internalFieldStore, "isTouched", true);
506
+ setFieldInput(internalFieldStore, config.input);
507
+ validateIfRequired(internalFormStore, internalFieldStore, "input");
508
+ });
509
+ }
510
+ function submit(form) {
511
+ form[INTERNAL].element?.requestSubmit();
512
+ }
513
+ function swap(form, config) {
514
+ const internalFormStore = form[INTERNAL];
515
+ const internalArrayStore = getFieldStore(internalFormStore, config.path);
516
+ const items = untrack(() => internalArrayStore.items.value);
517
+ if (config.at >= 0 && config.at <= items.length - 1 && config.and >= 0 && config.and <= items.length - 1 && config.at !== config.and) batch(() => {
518
+ const newItems = [...items];
519
+ const tempItemId = newItems[config.at];
520
+ newItems[config.at] = newItems[config.and];
521
+ newItems[config.and] = tempItemId;
522
+ internalArrayStore.items.value = newItems;
523
+ swapItemState(internalArrayStore.children[config.at], internalArrayStore.children[config.and]);
524
+ internalArrayStore.isTouched.value = true;
525
+ internalArrayStore.isDirty.value = internalArrayStore.startItems.value.join() !== newItems.join();
526
+ validateIfRequired(internalFormStore, internalArrayStore, "input");
527
+ });
528
+ }
529
+ function validate(form, config) {
530
+ return validateFormInput(form[INTERNAL], config);
531
+ }
532
+
533
+ //#endregion
534
+ //#region src/hooks/usePathSignal/usePathSignal.ts
535
+ function isEqual(a, b) {
536
+ if (a.length !== b.length) return false;
537
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
538
+ return true;
539
+ }
540
+ function usePathSignal(path) {
541
+ const signal = useSignal(path);
542
+ if (!isEqual(signal.value, path)) signal.value = path;
543
+ return signal;
544
+ }
545
+
546
+ //#endregion
547
+ //#region src/hooks/useField/useField.ts
548
+ function useField(form, config) {
549
+ const pathSignal = usePathSignal(config.path);
550
+ const internalFieldStore = useComputed(() => getFieldStore(form[INTERNAL], pathSignal.value));
551
+ useSignalEffect(() => {
552
+ return () => {
553
+ internalFieldStore.value.elements = internalFieldStore.value.elements.filter((element) => element.isConnected);
554
+ };
555
+ });
556
+ return useMemo(() => ({
557
+ path: pathSignal,
558
+ input: computed(() => getFieldInput(internalFieldStore.value)),
559
+ errors: computed(() => internalFieldStore.value.errors.value),
560
+ isTouched: computed(() => getFieldBool(internalFieldStore.value, "isTouched")),
561
+ isDirty: computed(() => getFieldBool(internalFieldStore.value, "isDirty")),
562
+ isValid: computed(() => !getFieldBool(internalFieldStore.value, "errors")),
563
+ props: {
564
+ get name() {
565
+ return internalFieldStore.value.name;
566
+ },
567
+ autofocus: !!internalFieldStore.value.errors.value,
568
+ ref(element) {
569
+ internalFieldStore.value.elements.push(element);
570
+ },
571
+ onFocus() {
572
+ setFieldBool(internalFieldStore.value, "isTouched", true);
573
+ validateIfRequired(form[INTERNAL], internalFieldStore.value, "touch");
574
+ },
575
+ onInput(event) {
576
+ const nextValue = getElementInput(event.currentTarget, internalFieldStore.value);
577
+ setFieldInput(internalFieldStore.value, nextValue);
578
+ validateIfRequired(form[INTERNAL], internalFieldStore.value, "input");
579
+ },
580
+ onChange() {
581
+ validateIfRequired(form[INTERNAL], internalFieldStore.value, "change");
582
+ },
583
+ onBlur() {
584
+ validateIfRequired(form[INTERNAL], internalFieldStore.value, "blur");
585
+ }
586
+ }
587
+ }), []);
588
+ }
589
+
590
+ //#endregion
591
+ //#region src/hooks/useFieldArray/useFieldArray.ts
592
+ function useFieldArray(form, config) {
593
+ const pathSignal = usePathSignal(config.path);
594
+ const internalFieldStore = useComputed(() => getFieldStore(form[INTERNAL], pathSignal.value));
595
+ return useMemo(() => ({
596
+ path: pathSignal,
597
+ items: computed(() => internalFieldStore.value.items.value),
598
+ errors: computed(() => internalFieldStore.value.errors.value),
599
+ isTouched: computed(() => getFieldBool(internalFieldStore.value, "isTouched")),
600
+ isDirty: computed(() => getFieldBool(internalFieldStore.value, "isDirty")),
601
+ isValid: computed(() => !getFieldBool(internalFieldStore.value, "errors"))
602
+ }), []);
603
+ }
604
+
605
+ //#endregion
606
+ //#region src/hooks/useForm/useForm.ts
607
+ function useForm(config) {
608
+ const form = useMemo(() => {
609
+ const internalFormStore = createFormStore(config, async (input) => v.safeParseAsync(config.schema, input));
610
+ return {
611
+ [INTERNAL]: internalFormStore,
612
+ isSubmitting: internalFormStore.isSubmitting,
613
+ isSubmitted: internalFormStore.isSubmitted,
614
+ isValidating: internalFormStore.isValidating,
615
+ isTouched: computed(() => getFieldBool(internalFormStore, "isTouched")),
616
+ isDirty: computed(() => getFieldBool(internalFormStore, "isDirty")),
617
+ isValid: computed(() => !getFieldBool(internalFormStore, "errors")),
618
+ errors: internalFormStore.errors
619
+ };
620
+ }, []);
621
+ useLayoutEffect(() => {
622
+ if (config.validateOn === "initial") validateFormInput(form[INTERNAL]);
623
+ }, []);
624
+ return form;
625
+ }
626
+
627
+ //#endregion
628
+ //#region src/components/Field/Field.tsx
629
+ /**
630
+ * Headless form field that provides reactive properties and state.
631
+ */
632
+ function Field({ of, path, render }) {
633
+ const field = useField(of, { path });
634
+ return render(field);
635
+ }
636
+
637
+ //#endregion
638
+ //#region src/components/FieldArray/FieldArray.tsx
639
+ /**
640
+ * Headless field array that provides reactive properties and state.
641
+ */
642
+ function FieldArray({ of, path, render }) {
643
+ const field = useFieldArray(of, { path });
644
+ return render(field);
645
+ }
646
+
647
+ //#endregion
648
+ //#region src/components/Form/Form.tsx
649
+ function Form({ of, onSubmit,...other }) {
650
+ return /* @__PURE__ */ jsx("form", {
651
+ ...other,
652
+ novalidate: true,
653
+ ref: (element) => {
654
+ of[INTERNAL].element = element;
655
+ },
656
+ onSubmit: async (event) => {
657
+ event.preventDefault();
658
+ const internalFormStore = of[INTERNAL];
659
+ internalFormStore.isSubmitted.value = true;
660
+ internalFormStore.isSubmitting.value = true;
661
+ try {
662
+ const result = await validateFormInput(internalFormStore, { shouldFocus: true });
663
+ if (result.success) await onSubmit(result.output, event);
664
+ } catch (error) {
665
+ internalFormStore.errors.value = [error instanceof Error ? error.message : "An unknown error has occurred."];
666
+ } finally {
667
+ internalFormStore.isSubmitting.value = false;
668
+ }
669
+ }
670
+ });
671
+ }
672
+
673
+ //#endregion
674
+ export { Field, FieldArray, Form, focus, getAllErrors, getErrors, getInput, insert, move, remove, replace, reset, setErrors, setInput, submit, swap, useField, useFieldArray, useForm, validate };
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@formisch/preact",
3
+ "description": "The modular and type-safe form library for Preact",
4
+ "version": "0.1.0",
5
+ "license": "MIT",
6
+ "author": "Fabian Hiller",
7
+ "homepage": "https://formisch.dev",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/fabian-hiller/formisch"
11
+ },
12
+ "keywords": [
13
+ "preact",
14
+ "modular",
15
+ "typescript",
16
+ "schema",
17
+ "validation",
18
+ "parsing",
19
+ "bundle-size",
20
+ "type-safe"
21
+ ],
22
+ "type": "module",
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/types/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/types/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "sideEffects": false,
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "build": "tsdown",
40
+ "lint": "eslint \"src/**/*.ts*\""
41
+ },
42
+ "devDependencies": {
43
+ "@eslint/js": "^9.31.0",
44
+ "@formisch/core": "workspace:*",
45
+ "@formisch/methods": "workspace:*",
46
+ "@preact/preset-vite": "^2.9.3",
47
+ "@preact/signals": "^2.2.1",
48
+ "eslint": "^9.31.0",
49
+ "eslint-config-preact": "^2.0.0",
50
+ "preact": "^10.25.3",
51
+ "tsdown": "^0.12.9",
52
+ "typescript": "^5.8.3",
53
+ "typescript-eslint": "^8.37.0",
54
+ "vite": "^6.0.4"
55
+ },
56
+ "peerDependencies": {
57
+ "@preact/signals": "^2.0.0",
58
+ "preact": "^10.0.0",
59
+ "typescript": ">=5",
60
+ "valibot": "^1.0.0"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "typescript": {
64
+ "optional": true
65
+ }
66
+ }
67
+ }