@railway-ts/use-form 0.1.33 → 0.2.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.
@@ -0,0 +1,1086 @@
1
+ import { MaybeAsyncValidator, StandardSchemaV1, ValidationError } from "@railway-ts/pipelines/schema";
2
+ import { Result } from "@railway-ts/pipelines/result";
3
+ import { ChangeEvent, FormEvent } from "react";
4
+ /**
5
+ * Detects whether a value is a Standard Schema v1 object by checking for
6
+ * the `~standard` property with `version === 1`.
7
+ */
8
+ export declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
9
+ /**
10
+ * Wraps a Standard Schema v1 object into a `MaybeAsyncValidator` compatible
11
+ * with the railway-ts validation pipeline. This allows `useForm` to accept
12
+ * any Standard Schema v1 compliant validator (Valibot, ArkType, etc.).
13
+ */
14
+ export declare function fromStandardSchema<T extends Record<string, unknown>>(schema: StandardSchemaV1<unknown, T>): MaybeAsyncValidator<unknown, T>;
15
+ /**
16
+ * Accepts either a railway-ts `MaybeAsyncValidator` or a Standard Schema v1 object.
17
+ * Used as the validator parameter type for `useForm`.
18
+ */
19
+ type FormValidator<T extends Record<string, unknown>> = MaybeAsyncValidator<unknown, T> | StandardSchemaV1<unknown, T>;
20
+ /**
21
+ * Represents a path to a field in a nested object structure.
22
+ * Supports both dot notation for object properties and bracket notation for arrays.
23
+ *
24
+ * Field paths are used throughout the form API to identify and access nested values,
25
+ * set validation errors, track touched state, and bind form fields to HTML elements.
26
+ * Internally, bracket notation is normalized to dot notation (e.g., "arr[0]" → "arr.0").
27
+ *
28
+ * @example
29
+ * // Dot notation for nested properties
30
+ * "user.address.city"
31
+ *
32
+ * @example
33
+ * // Bracket notation for array elements
34
+ * "contacts[0]"
35
+ *
36
+ * @example
37
+ * // Combined notation for deeply nested structures
38
+ * "users[0].address.city"
39
+ *
40
+ * @example
41
+ * // Array element with nested property
42
+ * "team.members[2].email"
43
+ */
44
+ type FieldPath = string;
45
+ type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Array<unknown> ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]>; } : T;
46
+ /**
47
+ * Configuration options for the useForm hook.
48
+ *
49
+ * These options control the form's initial state, submission behavior, and validation timing.
50
+ * `initialValues` is required; all other options are optional.
51
+ *
52
+ * @template TValues - The type of form values being managed
53
+ *
54
+ * @example
55
+ * // Minimal configuration
56
+ * const form = useForm(userValidator, {
57
+ * initialValues: { email: "", password: "" }
58
+ * });
59
+ *
60
+ * @example
61
+ * // With submit handler
62
+ * const form = useForm(userValidator, {
63
+ * initialValues: { email: "", password: "" },
64
+ * onSubmit: async (values) => {
65
+ * await api.register(values);
66
+ * }
67
+ * });
68
+ *
69
+ * @example
70
+ * // With custom validation mode
71
+ * const form = useForm(settingsValidator, {
72
+ * initialValues: savedSettings,
73
+ * validationMode: "blur",
74
+ * onSubmit: saveSettings
75
+ * });
76
+ */
77
+ interface FormOptions<TValues extends Record<string, unknown>> {
78
+ /**
79
+ * Initial values for the form fields.
80
+ * These values are used when the form is reset.
81
+ */
82
+ initialValues: TValues;
83
+ /**
84
+ * Callback function that runs when the form is submitted with valid data.
85
+ * Only called if validation passes. Can be sync or async.
86
+ * @param values - The validated form values (guaranteed to be complete and valid)
87
+ *
88
+ * @example
89
+ * onSubmit: async (values) => {
90
+ * const response = await fetch('/api/users', {
91
+ * method: 'POST',
92
+ * body: JSON.stringify(values)
93
+ * });
94
+ * if (!response.ok) {
95
+ * // Handle server errors
96
+ * }
97
+ * }
98
+ */
99
+ onSubmit?: (values: TValues) => void | Promise<void>;
100
+ /**
101
+ * Validation behavior preset that controls when validation occurs and when fields are marked as touched.
102
+ *
103
+ * - **"live"** (default): Validate on both change and blur events. Mark fields as touched on first change.
104
+ * Best for immediate feedback during data entry.
105
+ *
106
+ * - **"blur"**: Validate only when a field loses focus. Don't mark touched on change.
107
+ * Best for reducing visual noise until user finishes with a field.
108
+ *
109
+ * - **"mount"**: Validate once on mount and mark all fields as touched immediately. No validation on change/blur.
110
+ * Best for displaying an existing record with validation errors visible upfront.
111
+ *
112
+ * - **"submit"**: Validate only when the form is submitted. Mark all fields as touched on submit.
113
+ * Best for simple forms where you want minimal interruption during data entry.
114
+ *
115
+ * @default "live"
116
+ */
117
+ validationMode?: "live" | "blur" | "mount" | "submit";
118
+ /**
119
+ * Per-field validator functions for field-level async validation.
120
+ * Run independently from the main schema validator, only for the changed field.
121
+ * A field validator only runs when the schema produces no error for that field.
122
+ * Return undefined for valid, or an error message string for invalid.
123
+ */
124
+ fieldValidators?: { [K in ExtractFieldPaths<TValues>]?: (value: FieldTypeAtPath<TValues, K>, values: TValues) => string | undefined | Promise<string | undefined>; };
125
+ /**
126
+ * Optional callback invoked whenever form values change.
127
+ *
128
+ * Fires on every value update (field edits, setFieldValue, setValues, resetForm)
129
+ * and once on mount with initialValues. Receives both current and previous values
130
+ * to enable efficient diffing without external state.
131
+ *
132
+ * The callback is stored in a ref internally, so inline functions are safe.
133
+ *
134
+ * @param values - The current form values after the change
135
+ * @param prevValues - The form values before the change (same as values on mount)
136
+ */
137
+ onValuesChange?: (values: TValues, prevValues: TValues) => void;
138
+ /**
139
+ * Optional callback invoked when an individual field value changes.
140
+ *
141
+ * Fires from setFieldValue only — not from setValues, resetForm, or other batch
142
+ * updates. For batch change detection, use onValuesChange with prevValues.
143
+ *
144
+ * All native bindings (getFieldProps, getSliderProps, getCheckboxProps, etc.)
145
+ * route through setFieldValue, so this catches every user-driven field interaction.
146
+ *
147
+ * The callback is stored in a ref internally, so inline functions are safe.
148
+ *
149
+ * @param field - The field path that changed (e.g., "email", "address.city")
150
+ * @param value - The new value for the field
151
+ * @param values - The complete form values after the change
152
+ */
153
+ onFieldChange?: (field: string, value: unknown, values: TValues) => void;
154
+ }
155
+ /**
156
+ * Props for native HTML text input elements and textareas.
157
+ * These props are returned by getFieldProps() and can be spread directly onto input elements.
158
+ *
159
+ * Works with: <input type="text">, <input type="email">, <input type="password">,
160
+ * <input type="url">, <input type="tel">, <input type="date">, <textarea>, etc.
161
+ *
162
+ * @example
163
+ * // Basic text input
164
+ * <input type="text" {...form.getFieldProps("username")} placeholder="Username" />
165
+ *
166
+ * @example
167
+ * // Email input with additional attributes
168
+ * <input type="email" {...form.getFieldProps("email")} required autoComplete="email" />
169
+ *
170
+ * @example
171
+ * // Textarea
172
+ * <textarea {...form.getFieldProps("bio")} rows={4} placeholder="Tell us about yourself" />
173
+ */
174
+ type NativeFieldProps = {
175
+ id: string;
176
+ name: string;
177
+ value: string | number;
178
+ onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
179
+ onBlur: () => void;
180
+ };
181
+ /**
182
+ * Props for native HTML select elements.
183
+ * These props are returned by getSelectFieldProps() and can be spread directly onto select elements.
184
+ *
185
+ * Works with: <select> (single selection only, not multiple)
186
+ *
187
+ * @example
188
+ * // Basic select
189
+ * <select {...form.getSelectFieldProps("country")}>
190
+ * <option value="">Select a country</option>
191
+ * <option value="US">United States</option>
192
+ * <option value="CA">Canada</option>
193
+ * </select>
194
+ *
195
+ * @example
196
+ * // Select with dynamic options
197
+ * <select {...form.getSelectFieldProps("role")}>
198
+ * {roles.map(role => (
199
+ * <option key={role.id} value={role.id}>{role.name}</option>
200
+ * ))}
201
+ * </select>
202
+ */
203
+ type NativeSelectProps = {
204
+ id: string;
205
+ name: string;
206
+ value: string | number;
207
+ onChange: (e: ChangeEvent<HTMLSelectElement>) => void;
208
+ onBlur: () => void;
209
+ };
210
+ /**
211
+ * Props for native HTML checkbox inputs bound to boolean fields.
212
+ * These props are returned by getCheckboxProps() and can be spread directly onto checkbox inputs.
213
+ *
214
+ * Works with: <input type="checkbox"> for single boolean values
215
+ * Note: For checkbox groups (multiple checkboxes for an array), use NativeCheckboxGroupOptionProps
216
+ *
217
+ * @example
218
+ * // Basic checkbox
219
+ * <label>
220
+ * <input type="checkbox" {...form.getCheckboxProps("acceptTerms")} />
221
+ * I accept the terms and conditions
222
+ * </label>
223
+ *
224
+ * @example
225
+ * // Checkbox with separate label
226
+ * <div>
227
+ * <input type="checkbox" {...form.getCheckboxProps("subscribe")} />
228
+ * <label htmlFor={form.getCheckboxProps("subscribe").id}>Subscribe to newsletter</label>
229
+ * </div>
230
+ */
231
+ type NativeCheckboxProps = {
232
+ id: string;
233
+ name: string;
234
+ checked: boolean;
235
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
236
+ onBlur: () => void;
237
+ };
238
+ /**
239
+ * Props for native HTML switch inputs (semantically identical to checkbox, styled differently).
240
+ * These props are returned by getSwitchProps() and can be spread directly onto checkbox inputs.
241
+ *
242
+ * Works with: <input type="checkbox"> styled as a toggle switch via CSS
243
+ *
244
+ * @example
245
+ * // Toggle switch
246
+ * <label className="switch">
247
+ * <input type="checkbox" {...form.getSwitchProps("settings.darkMode")} />
248
+ * <span className="slider"></span>
249
+ * </label>
250
+ *
251
+ * @example
252
+ * // Feature flag toggle
253
+ * <div className="setting-row">
254
+ * <span>Enable notifications</span>
255
+ * <input type="checkbox" {...form.getSwitchProps("notifications.enabled")} className="toggle" />
256
+ * </div>
257
+ */
258
+ type NativeSwitchProps = {
259
+ id: string;
260
+ name: string;
261
+ checked: boolean;
262
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
263
+ onBlur: () => void;
264
+ };
265
+ /**
266
+ * Props for native HTML range slider inputs.
267
+ * These props are returned by getSliderProps() and can be spread directly onto range inputs.
268
+ *
269
+ * Works with: <input type="range">
270
+ * Note: Native range inputs only support single numeric values, not arrays.
271
+ * For multi-thumb sliders, use a UI library adapter.
272
+ *
273
+ * @example
274
+ * // Volume slider
275
+ * <div>
276
+ * <label htmlFor={form.getSliderProps("volume").id}>Volume: {form.values.volume}%</label>
277
+ * <input type="range" min={0} max={100} {...form.getSliderProps("volume")} />
278
+ * </div>
279
+ *
280
+ * @example
281
+ * // Opacity slider with step
282
+ * <input type="range" min={0} max={1} step={0.1} {...form.getSliderProps("opacity")} />
283
+ */
284
+ type NativeSliderProps = {
285
+ id: string;
286
+ name: string;
287
+ type: "range";
288
+ value: number;
289
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
290
+ onBlur: () => void;
291
+ };
292
+ /**
293
+ * Props for native HTML file input elements.
294
+ * These props are returned by getFileFieldProps() and can be spread directly onto file inputs.
295
+ *
296
+ * Works with: <input type="file"> (single or multiple files)
297
+ *
298
+ * @example
299
+ * // Single file upload
300
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("avatar")} />
301
+ *
302
+ * @example
303
+ * // Multiple file upload
304
+ * <input type="file" multiple accept=".pdf,.doc,.docx" {...form.getFileFieldProps("documents")} />
305
+ *
306
+ * @example
307
+ * // File upload with preview
308
+ * <div>
309
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("photo")} />
310
+ * {form.values.photo && <img src={URL.createObjectURL(form.values.photo)} alt="Preview" />}
311
+ * </div>
312
+ */
313
+ type NativeFileFieldProps = {
314
+ id: string;
315
+ name: string;
316
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
317
+ onBlur: () => void;
318
+ };
319
+ /**
320
+ * Props for a single radio button option within a radio group.
321
+ * These props are returned by getRadioGroupOptionProps() and can be spread directly onto radio inputs.
322
+ *
323
+ * Works with: multiple <input type="radio"> elements sharing the same name attribute
324
+ *
325
+ * @example
326
+ * // Radio group for contact method
327
+ * <div>
328
+ * <label>
329
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "email")} />
330
+ * Email
331
+ * </label>
332
+ * <label>
333
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "phone")} />
334
+ * Phone
335
+ * </label>
336
+ * </div>
337
+ *
338
+ * @example
339
+ * // Radio group with descriptions
340
+ * {plans.map(plan => (
341
+ * <label key={plan.id}>
342
+ * <input type="radio" {...form.getRadioGroupOptionProps("plan", plan.id)} />
343
+ * <div>
344
+ * <strong>{plan.name}</strong>
345
+ * <p>{plan.description}</p>
346
+ * </div>
347
+ * </label>
348
+ * ))}
349
+ */
350
+ type NativeRadioGroupOptionProps = {
351
+ id: string;
352
+ name: string;
353
+ value: string | number;
354
+ checked: boolean;
355
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
356
+ onBlur: () => void;
357
+ };
358
+ /**
359
+ * Props for a single checkbox option within a checkbox group bound to an array field.
360
+ * These props are returned by getCheckboxGroupOptionProps() and can be spread directly onto checkbox inputs.
361
+ *
362
+ * Works with: multiple <input type="checkbox"> elements sharing the same name, bound to an array field
363
+ * Note: This is different from NativeCheckboxProps, which is for single boolean checkboxes
364
+ *
365
+ * @example
366
+ * // Checkbox group for selecting multiple interests
367
+ * <div>
368
+ * <label>
369
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "sports")} />
370
+ * Sports
371
+ * </label>
372
+ * <label>
373
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "music")} />
374
+ * Music
375
+ * </label>
376
+ * <label>
377
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "travel")} />
378
+ * Travel
379
+ * </label>
380
+ * </div>
381
+ * // form.values.interests = ["sports", "music"] when both are checked
382
+ *
383
+ * @example
384
+ * // Dynamic checkbox group from data
385
+ * {permissions.map(permission => (
386
+ * <label key={permission.id}>
387
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("userPermissions", permission.id)} />
388
+ * {permission.name}
389
+ * </label>
390
+ * ))}
391
+ */
392
+ type NativeCheckboxGroupOptionProps = {
393
+ id: string;
394
+ name: string;
395
+ value: string | number;
396
+ checked: boolean;
397
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
398
+ onBlur: () => void;
399
+ };
400
+ /**
401
+ * Extracts all valid field paths from a type, including nested paths and discriminated unions.
402
+ * This advanced utility type recursively traverses object structures to generate a union of
403
+ * all possible dot-notation paths that can be used to access fields.
404
+ *
405
+ * Special handling for:
406
+ * - Nested objects: Generates paths like "user.address.city"
407
+ * - Arrays: Treated as terminal values (returns just "items", not "items[0]")
408
+ * - Dates: Treated as terminal values
409
+ * - Functions: Treated as terminal values
410
+ * - Discriminated unions: Extracts paths from all union variants
411
+ *
412
+ * @template T - The type to extract field paths from
413
+ *
414
+ * @example
415
+ * // Simple object
416
+ * type User = { name: string; age: number };
417
+ * type Paths = ExtractFieldPaths<User>; // "name" | "age"
418
+ *
419
+ * @example
420
+ * // Nested object
421
+ * type User = { name: string; address: { city: string; zip: string } };
422
+ * type Paths = ExtractFieldPaths<User>; // "name" | "address" | "address.city" | "address.zip"
423
+ *
424
+ * @example
425
+ * // With arrays (arrays are terminal)
426
+ * type User = { name: string; tags: string[] };
427
+ * type Paths = ExtractFieldPaths<User>; // "name" | "tags"
428
+ *
429
+ * @example
430
+ * // Discriminated union
431
+ * type Payment =
432
+ * | { type: "card"; cardNumber: string }
433
+ * | { type: "paypal"; email: string };
434
+ * type Form = { payment: Payment };
435
+ * type Paths = ExtractFieldPaths<Form>; // "payment" | "payment.type" | "payment.cardNumber" | "payment.email"
436
+ */
437
+ /**
438
+ * Resolves the type at a dot-separated field path within a type.
439
+ * Companion to ExtractFieldPaths — while ExtractFieldPaths extracts all valid paths,
440
+ * FieldTypeAtPath resolves the value type at a given path.
441
+ *
442
+ * @template T - The root type to traverse
443
+ * @template P - A dot-separated path string
444
+ *
445
+ * @example
446
+ * type User = { name: string; address: { city: string; zip: number } };
447
+ * type City = FieldTypeAtPath<User, "address.city">; // string
448
+ * type Zip = FieldTypeAtPath<User, "address.zip">; // number
449
+ */
450
+ type FieldTypeAtPath<T, P extends string> = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? FieldTypeAtPath<NonNullable<T[K]>, Rest> : unknown : P extends keyof T ? T[P] : unknown;
451
+ type IsTuple<T extends readonly unknown[]> = number extends T["length"] ? false : true;
452
+ type TupleIndexPaths<T extends readonly unknown[]> = `${Extract<keyof T, number>}`;
453
+ type ExtractFieldPaths<T> = T extends readonly unknown[] ? never : T extends object ? { [K in keyof T]-?: K extends string | number ? NonNullable<T[K]> extends Date | ((...args: never[]) => unknown) ? `${K}` : NonNullable<T[K]> extends readonly unknown[] ? IsTuple<NonNullable<T[K]>> extends true ? `${K}` | `${K}.${TupleIndexPaths<NonNullable<T[K]>>}` : `${K}` : T[K] extends object | undefined ? T[K] extends {
454
+ type: string;
455
+ } ? T[K] extends (infer U) ? U extends {
456
+ type: infer Type;
457
+ } ? Type extends string ? `${K}` | `${K}.${ExtractFieldPaths<NonNullable<T[K]>>}` : never : never : never : `${K}` | `${K}.${ExtractFieldPaths<NonNullable<T[K]>>}` : `${K}` : never; }[keyof T] : never;
458
+ /**
459
+ * Extracts the array item type from an array field.
460
+ * This utility type inspects a field in the form values type and returns the type
461
+ * of items stored in the array, or never if the field is not an array.
462
+ *
463
+ * Works with both mutable arrays and readonly arrays.
464
+ *
465
+ * @template TValues - The form values type
466
+ * @template TField - The field path (must be an array field)
467
+ *
468
+ * @example
469
+ * // Extract item type from string array
470
+ * type User = { tags: string[] };
471
+ * type TagItem = GetArrayItemType<User, "tags">; // string
472
+ *
473
+ * @example
474
+ * // Extract item type from union array
475
+ * type User = { contacts: ("email" | "phone")[] };
476
+ * type ContactItem = GetArrayItemType<User, "contacts">; // "email" | "phone"
477
+ *
478
+ * @example
479
+ * // Extract item type from object array
480
+ * type User = { addresses: { city: string; zip: string }[] };
481
+ * type AddressItem = GetArrayItemType<User, "addresses">; // { city: string; zip: string }
482
+ *
483
+ * @example
484
+ * // Used with arrayHelpers for type-safe array operations
485
+ * const contactsHelpers = form.arrayHelpers<GetArrayItemType<UserForm, "contacts">>("contacts");
486
+ */
487
+ type GetArrayItemType<TValues extends Record<string, unknown>, TField extends keyof TValues> = NonNullable<TValues[TField]> extends readonly (infer TItem)[] ? TItem : NonNullable<TValues[TField]> extends (infer TItem)[] ? TItem : never;
488
+ /**
489
+ * Helper functions for working with array fields in forms.
490
+ * Provides type-safe methods to add, remove, update, and reorder array items,
491
+ * as well as bind native HTML elements to fields within array items.
492
+ *
493
+ * This interface is returned by form.arrayHelpers() and provides a complete
494
+ * toolkit for managing dynamic lists in forms (e.g., contacts, addresses, todo items).
495
+ *
496
+ * All mutations are performed immutably and trigger form state updates.
497
+ *
498
+ * @template TItem - The type of items stored in the array
499
+ * @template TFieldPaths - Union of valid field paths for the item type (auto-extracted)
500
+ *
501
+ * @example
502
+ * // Get helpers for a contacts array
503
+ * type Contact = { name: string; email: string };
504
+ * const contacts = form.arrayHelpers<Contact>("contacts");
505
+ *
506
+ * @example
507
+ * // Render a dynamic list with add/remove
508
+ * const helpers = form.arrayHelpers("addresses");
509
+ * return (
510
+ * <div>
511
+ * {helpers.values.map((_, index) => (
512
+ * <div key={index}>
513
+ * <input {...helpers.getFieldProps(index, "street")} />
514
+ * <input {...helpers.getFieldProps(index, "city")} />
515
+ * <button onClick={() => helpers.remove(index)}>Remove</button>
516
+ * </div>
517
+ * ))}
518
+ * <button onClick={() => helpers.push({ street: "", city: "" })}>Add Address</button>
519
+ * </div>
520
+ * );
521
+ */
522
+ interface ArrayHelpers<TItem, TFieldPaths extends string = ExtractFieldPaths<TItem>> {
523
+ /**
524
+ * Current array values. Use this to iterate over items when rendering.
525
+ *
526
+ * @example
527
+ * helpers.values.map((item, index) => (
528
+ * <div key={index}>...</div>
529
+ * ))
530
+ */
531
+ values: TItem[];
532
+ /**
533
+ * Adds a new item to the end of the array.
534
+ *
535
+ * @param value - The item to add
536
+ *
537
+ * @example
538
+ * helpers.push({ name: "", email: "" });
539
+ */
540
+ push: (value: TItem) => void;
541
+ /**
542
+ * Removes an item at the specified index.
543
+ *
544
+ * @param index - The zero-based index of the item to remove
545
+ *
546
+ * @example
547
+ * <button onClick={() => helpers.remove(index)}>Delete</button>
548
+ */
549
+ remove: (index: number) => void;
550
+ /**
551
+ * Inserts an item at the specified index. Items at and after the index shift to the right.
552
+ *
553
+ * @param index - The zero-based insertion position
554
+ * @param value - The item to insert
555
+ *
556
+ * @example
557
+ * helpers.insert(0, { name: "First", email: "first@example.com" });
558
+ */
559
+ insert: (index: number, value: TItem) => void;
560
+ /**
561
+ * Swaps the positions of two items. Useful for drag-and-drop reordering.
562
+ *
563
+ * @param indexA - The index of the first item
564
+ * @param indexB - The index of the second item
565
+ *
566
+ * @example
567
+ * <button onClick={() => helpers.swap(index, index - 1)}>Move Up</button>
568
+ */
569
+ swap: (indexA: number, indexB: number) => void;
570
+ /**
571
+ * Replaces an entire item at the specified index with a new value.
572
+ *
573
+ * @param index - The zero-based index of the item to replace
574
+ * @param value - The new item value
575
+ *
576
+ * @example
577
+ * helpers.replace(0, updatedContact);
578
+ */
579
+ replace: (index: number, value: TItem) => void;
580
+ /**
581
+ * Gets props for a native text input bound to a field within an array item.
582
+ * Provides type-safe autocomplete for subField parameter.
583
+ *
584
+ * @param index - The zero-based index of the array item
585
+ * @param subField - Field path within the array item (type-safe)
586
+ * @returns Props to spread onto a native input element
587
+ *
588
+ * @example
589
+ * <input type="text" {...helpers.getFieldProps(index, "name")} />
590
+ */
591
+ getFieldProps: (index: number, subField: TFieldPaths) => NativeFieldProps;
592
+ /**
593
+ * Gets props for a native select bound to a field within an array item.
594
+ * Provides type-safe autocomplete for subField parameter.
595
+ *
596
+ * @param index - The zero-based index of the array item
597
+ * @param subField - Field path within the array item (type-safe)
598
+ * @returns Props to spread onto a native select element
599
+ *
600
+ * @example
601
+ * <select {...helpers.getSelectFieldProps(index, "type")}>
602
+ * <option value="work">Work</option>
603
+ * <option value="personal">Personal</option>
604
+ * </select>
605
+ */
606
+ getSelectFieldProps: (index: number, subField: TFieldPaths) => NativeSelectProps;
607
+ /**
608
+ * Gets props for a native range input bound to a field within an array item.
609
+ * Provides type-safe autocomplete for subField parameter.
610
+ *
611
+ * @param index - The zero-based index of the array item
612
+ * @param subField - Field path within the array item (type-safe)
613
+ * @returns Props to spread onto a native range input element
614
+ *
615
+ * @example
616
+ * <input type="range" min={0} max={10} {...helpers.getSliderProps(index, "priority")} />
617
+ */
618
+ getSliderProps: (index: number, subField: TFieldPaths) => NativeSliderProps;
619
+ /**
620
+ * Gets props for a native checkbox bound to a field within an array item.
621
+ * Provides type-safe autocomplete for subField parameter.
622
+ *
623
+ * @param index - The zero-based index of the array item
624
+ * @param subField - Field path within the array item (type-safe)
625
+ * @returns Props to spread onto a native checkbox input
626
+ *
627
+ * @example
628
+ * <input type="checkbox" {...helpers.getCheckboxProps(index, "isActive")} />
629
+ */
630
+ getCheckboxProps: (index: number, subField: TFieldPaths) => NativeCheckboxProps;
631
+ /**
632
+ * Gets props for a native switch (checkbox styled as switch) bound to a field within an array item.
633
+ * Provides type-safe autocomplete for subField parameter.
634
+ *
635
+ * @param index - The zero-based index of the array item
636
+ * @param subField - Field path within the array item (type-safe)
637
+ * @returns Props to spread onto a native checkbox input (styled as switch)
638
+ *
639
+ * @example
640
+ * <input type="checkbox" {...helpers.getSwitchProps(index, "enabled")} />
641
+ */
642
+ getSwitchProps: (index: number, subField: TFieldPaths) => NativeSwitchProps;
643
+ /**
644
+ * Gets props for a native file input bound to a field within an array item.
645
+ * Provides type-safe autocomplete for subField parameter.
646
+ *
647
+ * @param index - The zero-based index of the array item
648
+ * @param subField - Field path within the array item (type-safe)
649
+ * @returns Props to spread onto a native file input
650
+ *
651
+ * @example
652
+ * <input type="file" accept="image/*" {...helpers.getFileFieldProps(index, "avatar")} />
653
+ */
654
+ getFileFieldProps: (index: number, subField: TFieldPaths) => NativeFileFieldProps;
655
+ /**
656
+ * Gets props for a radio group option bound to a field within an array item.
657
+ * Provides type-safe autocomplete for subField parameter.
658
+ *
659
+ * @param index - The zero-based index of the array item
660
+ * @param subField - Field path within the array item (type-safe)
661
+ * @param optionValue - The value this radio option represents
662
+ * @returns Props to spread onto a native radio input
663
+ *
664
+ * @example
665
+ * <input type="radio" {...helpers.getRadioGroupOptionProps(index, "status", "active")} />
666
+ */
667
+ getRadioGroupOptionProps: (index: number, subField: TFieldPaths, optionValue: string | number) => NativeRadioGroupOptionProps;
668
+ /**
669
+ * Returns the validation error for a field within an array item, but only
670
+ * if the field has been touched. Mirrors the top-level `form.getFieldError`
671
+ * behaviour using the `(index, subField)` pattern.
672
+ *
673
+ * @param index - The zero-based index of the array item
674
+ * @param subField - Field path within the array item (type-safe)
675
+ * @returns The error message string, or `undefined` if untouched / valid
676
+ *
677
+ * @example
678
+ * {helpers.getFieldError(index, "email") && (
679
+ * <span>{helpers.getFieldError(index, "email")}</span>
680
+ * )}
681
+ */
682
+ getFieldError: (index: number, subField: TFieldPaths) => string | undefined;
683
+ /**
684
+ * Returns a stable HTML element ID for a field within an array item.
685
+ * Useful for linking `<label htmlFor>` to an input without calling a full
686
+ * props factory. Mirrors the top-level `form.getFieldId`.
687
+ *
688
+ * @param index - The zero-based index of the array item
689
+ * @param subField - Field path within the array item (type-safe)
690
+ * @param optionValue - Optional value for radio group / checkbox group options
691
+ * @returns The element ID string
692
+ *
693
+ * @example
694
+ * <label htmlFor={helpers.getFieldId(index, "name")}>Name</label>
695
+ * <input {...helpers.getFieldProps(index, "name")} />
696
+ */
697
+ getFieldId: (index: number, subField: TFieldPaths, optionValue?: string | number) => string;
698
+ }
699
+ /**
700
+ * The return type of the `useForm` hook.
701
+ *
702
+ * Provides form state, field management methods, server error management,
703
+ * form actions, native HTML field integration, and array field helpers.
704
+ *
705
+ * @template TValues - The shape of form values as a record with string keys
706
+ */
707
+ interface UseFormReturn<TValues extends Record<string, unknown>> {
708
+ /** Current values of all form fields. */
709
+ values: TValues;
710
+ /** Record of which fields have been interacted with by the user. */
711
+ touched: Record<FieldPath, boolean>;
712
+ /** Merged validation errors (server errors take precedence over field errors, which take precedence over client errors). */
713
+ errors: Record<FieldPath, string>;
714
+ /** Validation errors from client-side (schema) validation only. */
715
+ clientErrors: Record<FieldPath, string>;
716
+ /** Validation errors set via `setServerErrors()`. Automatically cleared when the related field value changes. */
717
+ serverErrors: Record<FieldPath, string>;
718
+ /** Validation errors from field-level validators (both sync and async). Takes precedence over client errors but not server errors. */
719
+ fieldErrors: Record<FieldPath, string>;
720
+ /** Whether the form is currently being submitted. Useful for showing loading states on submit buttons. */
721
+ isSubmitting: boolean;
722
+ /** Whether any async validation (form-level or field-level) is currently in progress. */
723
+ isValidating: boolean;
724
+ /** Per-field async validation tracking. `true` when that field's async validator is running. */
725
+ validatingFields: Record<FieldPath, boolean>;
726
+ /** Whether the form is currently valid (no errors of any kind). */
727
+ isValid: boolean;
728
+ /** Whether any form values have changed since initialization or last reset. */
729
+ isDirty: boolean;
730
+ /** Number of times the form has been submitted via `handleSubmit`. Incremented at the start of each attempt. */
731
+ submitCount: number;
732
+ /**
733
+ * Updates a single field value and optionally triggers validation. Automatically clears related server errors.
734
+ *
735
+ * @example
736
+ * form.setFieldValue("email", "user@example.com");
737
+ */
738
+ setFieldValue: <TValue>(field: FieldPath, value: TValue, shouldValidate?: boolean) => void;
739
+ /**
740
+ * Marks a field as touched or untouched and optionally triggers validation.
741
+ *
742
+ * @example
743
+ * form.setFieldTouched("email");
744
+ */
745
+ setFieldTouched: (field: FieldPath, isTouched?: boolean, shouldValidate?: boolean) => void;
746
+ /**
747
+ * Updates multiple field values simultaneously. More efficient than calling `setFieldValue` multiple times.
748
+ *
749
+ * @example
750
+ * form.setValues({ firstName: "John", lastName: "Doe" });
751
+ */
752
+ setValues: (values: DeepPartial<TValues>, shouldValidate?: boolean) => void;
753
+ /**
754
+ * Sets server-side validation errors. These take precedence over client errors and are auto-cleared on field change.
755
+ *
756
+ * @example
757
+ * form.setServerErrors({ email: "Email already taken" });
758
+ */
759
+ setServerErrors: (errors: Record<FieldPath, string>) => void;
760
+ /**
761
+ * Clears all server-side validation errors. Client-side errors are not affected.
762
+ *
763
+ * @example
764
+ * form.clearServerErrors();
765
+ */
766
+ clearServerErrors: () => void;
767
+ /**
768
+ * Validates all fields, marks them as touched, and calls `onSubmit` if valid. Returns a Railway `Result`.
769
+ *
770
+ * @example
771
+ * <form onSubmit={form.handleSubmit}>
772
+ * <input {...form.getFieldProps("email")} />
773
+ * <button type="submit">Submit</button>
774
+ * </form>
775
+ */
776
+ handleSubmit: (e?: FormEvent) => Promise<Result<TValues, ValidationError[]>>;
777
+ /**
778
+ * Resets the form to its initial state — clears all values, errors, and touched state.
779
+ *
780
+ * @example
781
+ * form.resetForm();
782
+ */
783
+ resetForm: () => void;
784
+ /**
785
+ * Runs the validator against the given values and returns a Railway `Result`.
786
+ *
787
+ * @example
788
+ * const result = form.validateForm(currentValues);
789
+ */
790
+ validateForm: (values: TValues) => Result<TValues, ValidationError[]> | Promise<Result<TValues, ValidationError[]>>;
791
+ /**
792
+ * Returns the error message for a field only if it has been touched, otherwise `undefined`.
793
+ *
794
+ * @example
795
+ * {form.getFieldError("email") && <span>{form.getFieldError("email")}</span>}
796
+ */
797
+ getFieldError: <TField extends ExtractFieldPaths<TValues>>(field: TField) => string | undefined;
798
+ /**
799
+ * Returns a stable HTML element ID for a field. Useful for linking `<label htmlFor>` to inputs.
800
+ *
801
+ * @example
802
+ * <label htmlFor={form.getFieldId("username")}>Username</label>
803
+ * <input {...form.getFieldProps("username")} />
804
+ */
805
+ getFieldId: <TField extends ExtractFieldPaths<TValues>>(field: TField, optionValue?: string | number) => string;
806
+ /**
807
+ * Returns props (`id`, `name`, `value`, `onChange`, `onBlur`) to spread onto a native text input or textarea.
808
+ *
809
+ * @example
810
+ * <input type="text" {...form.getFieldProps("username")} placeholder="Username" />
811
+ */
812
+ getFieldProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeFieldProps;
813
+ /**
814
+ * Returns props to spread onto a native `<select>` element.
815
+ *
816
+ * @example
817
+ * <select {...form.getSelectFieldProps("country")}>
818
+ * <option value="">Select a country</option>
819
+ * <option value="US">United States</option>
820
+ * </select>
821
+ */
822
+ getSelectFieldProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeSelectProps;
823
+ /**
824
+ * Returns props (`id`, `name`, `checked`, `onChange`, `onBlur`) to spread onto a native checkbox for a boolean field.
825
+ *
826
+ * @example
827
+ * <label>
828
+ * <input type="checkbox" {...form.getCheckboxProps("acceptTerms")} />
829
+ * I accept the terms and conditions
830
+ * </label>
831
+ */
832
+ getCheckboxProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeCheckboxProps;
833
+ /**
834
+ * Returns props to spread onto a checkbox styled as a toggle switch for a boolean field.
835
+ *
836
+ * @example
837
+ * <label className="switch">
838
+ * <input type="checkbox" {...form.getSwitchProps("darkMode")} />
839
+ * <span className="slider" />
840
+ * </label>
841
+ */
842
+ getSwitchProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeSwitchProps;
843
+ /**
844
+ * Returns props to spread onto a native `<input type="range">` for a numeric field.
845
+ *
846
+ * @example
847
+ * <input type="range" min={0} max={100} {...form.getSliderProps("volume")} />
848
+ */
849
+ getSliderProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeSliderProps;
850
+ /**
851
+ * Returns props for a single checkbox within a checkbox group bound to an array field.
852
+ *
853
+ * @example
854
+ * <label>
855
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "sports")} />
856
+ * Sports
857
+ * </label>
858
+ */
859
+ getCheckboxGroupOptionProps: <TField extends ExtractFieldPaths<TValues>>(field: TField, optionValue: string | number) => NativeCheckboxGroupOptionProps;
860
+ /**
861
+ * Returns props to spread onto a native `<input type="file">`. Supports single and multiple file selection.
862
+ *
863
+ * @example
864
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("avatar")} />
865
+ */
866
+ getFileFieldProps: <TField extends ExtractFieldPaths<TValues>>(field: TField) => NativeFileFieldProps;
867
+ /**
868
+ * Returns props for a single radio button within a radio group bound to a scalar field.
869
+ *
870
+ * @example
871
+ * <label>
872
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "email")} />
873
+ * Email
874
+ * </label>
875
+ */
876
+ getRadioGroupOptionProps: <TField extends ExtractFieldPaths<TValues>>(field: TField, optionValue: string | number) => NativeRadioGroupOptionProps;
877
+ /**
878
+ * Returns helper functions for managing array fields — add, remove, reorder, and bind HTML elements to items.
879
+ *
880
+ * @example
881
+ * const helpers = form.arrayHelpers("contacts");
882
+ * helpers.push({ name: "", email: "" });
883
+ */
884
+ arrayHelpers: {
885
+ <TField extends keyof TValues & string>(field: TField): ArrayHelpers<GetArrayItemType<TValues, TField>, ExtractFieldPaths<GetArrayItemType<TValues, TField>>>;
886
+ <TField extends ExtractFieldPaths<TValues>, TItem = unknown>(field: TField): ArrayHelpers<TItem, ExtractFieldPaths<TItem>>;
887
+ };
888
+ }
889
+ /**
890
+ * A powerful React form hook that combines Railway-oriented validation with native HTML support.
891
+ * Provides type-safe form state management, automatic validation, error handling, and direct
892
+ * integration with native HTML form elements.
893
+ *
894
+ * This hook integrates with @railway-ts/pipelines for functional validation, supports multiple
895
+ * validation modes (live, blur, mount, submit), manages both client and server errors, and
896
+ * provides helpers for working with nested objects and dynamic arrays.
897
+ *
898
+ * @template TValues - The shape of form values as a record with string keys
899
+ *
900
+ * @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
901
+ * @param options - Configuration options for form behavior
902
+ * @param options.initialValues - Initial values for form fields (used on mount and reset)
903
+ * @param options.onSubmit - Callback invoked when form is submitted with valid data
904
+ * @param options.validationMode - Controls when validation occurs: "live" | "blur" | "mount" | "submit"
905
+ *
906
+ * @returns An object containing:
907
+ * **Form State:**
908
+ * - `values` - Current form field values (TValues)
909
+ * - `touched` - Record of which fields have been interacted with
910
+ * - `errors` - Combined client and server errors (server takes precedence)
911
+ * - `clientErrors` - Validation errors from the validator function
912
+ * - `serverErrors` - Manually set errors from server responses
913
+ * - `isValid` - Whether the form has no validation errors
914
+ * - `isDirty` - Whether any values have changed from initial state
915
+ * - `isSubmitting` - Whether the form is currently being submitted
916
+ * - `isValidating` - Whether async validation is currently in progress
917
+ *
918
+ * **Field Management:**
919
+ * - `setFieldValue(field, value, shouldValidate?)` - Update a single field
920
+ * - `setFieldTouched(field, isTouched?, shouldValidate?)` - Mark field as touched
921
+ * - `setValues(values, shouldValidate?)` - Update multiple fields at once
922
+ *
923
+ * **Server Error Management:**
924
+ * - `setServerErrors(errors)` - Set server-side validation errors
925
+ * - `clearServerErrors()` - Clear all server-side errors
926
+ *
927
+ * **Form Actions:**
928
+ * - `handleSubmit(e?)` - Validate and submit the form
929
+ * - `resetForm()` - Reset form to initial values and clear errors
930
+ * - `validateForm(values)` - Manually trigger validation
931
+ *
932
+ * **Native HTML Integration:**
933
+ * - `getFieldProps(field)` - Props for text inputs, email, textarea, etc.
934
+ * - `getSelectFieldProps(field)` - Props for select elements
935
+ * - `getCheckboxProps(field)` - Props for boolean checkboxes
936
+ * - `getSwitchProps(field)` - Props for toggle switches
937
+ * - `getSliderProps(field)` - Props for range inputs
938
+ * - `getCheckboxGroupOptionProps(field, value)` - Props for checkbox groups (arrays)
939
+ * - `getFileFieldProps(field)` - Props for file inputs
940
+ * - `getRadioGroupOptionProps(field, value)` - Props for radio groups
941
+ *
942
+ * **Array Field Helpers:**
943
+ * - `arrayHelpers(field)` - Get helpers for managing array fields (push, remove, swap, etc.)
944
+ *
945
+ * @example
946
+ * // Basic usage with validation
947
+ * const form = useForm(userValidator, {
948
+ * initialValues: { name: "", email: "", age: 0 },
949
+ * onSubmit: async (values) => {
950
+ * await api.createUser(values);
951
+ * },
952
+ * validationMode: "live"
953
+ * });
954
+ *
955
+ * @example
956
+ * // Render with native HTML elements
957
+ * <form onSubmit={form.handleSubmit}>
958
+ * <input type="text" {...form.getFieldProps("name")} />
959
+ * {form.touched.name && form.errors.name && <span>{form.errors.name}</span>}
960
+ *
961
+ * <input type="email" {...form.getFieldProps("email")} />
962
+ * {form.touched.email && form.errors.email && <span>{form.errors.email}</span>}
963
+ *
964
+ * <button type="submit" disabled={!form.isValid || form.isSubmitting}>
965
+ * {form.isSubmitting ? "Submitting..." : "Submit"}
966
+ * </button>
967
+ * </form>
968
+ *
969
+ * @example
970
+ * // Handle server errors
971
+ * const form = useForm(userValidator, {
972
+ * onSubmit: async (values) => {
973
+ * const response = await api.createUser(values);
974
+ * if (!response.ok) {
975
+ * const errors = await response.json();
976
+ * form.setServerErrors(errors);
977
+ * }
978
+ * }
979
+ * });
980
+ *
981
+ * @example
982
+ * // Working with arrays
983
+ * const form = useForm(contactsValidator, {
984
+ * initialValues: { contacts: [] }
985
+ * });
986
+ *
987
+ * const contactsHelpers = form.arrayHelpers("contacts");
988
+ * return (
989
+ * <div>
990
+ * {contactsHelpers.values.map((_, index) => (
991
+ * <div key={index}>
992
+ * <input {...contactsHelpers.getFieldProps(index, "name")} />
993
+ * <input {...contactsHelpers.getFieldProps(index, "email")} />
994
+ * <button onClick={() => contactsHelpers.remove(index)}>Remove</button>
995
+ * </div>
996
+ * ))}
997
+ * <button onClick={() => contactsHelpers.push({ name: "", email: "" })}>
998
+ * Add Contact
999
+ * </button>
1000
+ * </div>
1001
+ * );
1002
+ */
1003
+ export declare const useForm: <TValues extends Record<string, unknown>>(validatorOrSchema: FormValidator<TValues>, options: FormOptions<TValues>) => UseFormReturn<TValues>;
1004
+ /**
1005
+ * Represents the subset of form methods needed for auto-submission
1006
+ * @template T - The type of form values
1007
+ */
1008
+ type FormWithAutoSubmit<T> = {
1009
+ values: T;
1010
+ isDirty: boolean;
1011
+ isValid: boolean;
1012
+ validateForm: (values: T) => {
1013
+ ok: boolean;
1014
+ } | Promise<{
1015
+ ok: boolean;
1016
+ }>;
1017
+ handleSubmit: () => void;
1018
+ };
1019
+ /**
1020
+ * A React hook that automatically submits a form when it becomes valid and dirty.
1021
+ * Useful for creating auto-save or live-update form experiences.
1022
+ *
1023
+ * The hook monitors form values and automatically triggers submission when:
1024
+ * 1. The form is dirty (has been modified)
1025
+ * 2. The form is valid (passes all validation rules)
1026
+ * 3. The values have changed since the last validation
1027
+ *
1028
+ * Submission is debounced to avoid excessive API calls during rapid user input.
1029
+ *
1030
+ * @template T - The type of form values
1031
+ *
1032
+ * @param form - A form object containing values, validation state, and submission methods
1033
+ * @param delay - The debounce delay in milliseconds before auto-submitting (default: 200ms)
1034
+ * @returns null (this hook only produces side effects)
1035
+ *
1036
+ * @example
1037
+ * // Auto-submit a preferences form
1038
+ * const form = useForm(preferencesSchema, {
1039
+ * initialValues: { theme: 'light', notifications: true },
1040
+ * onSubmit: async (values) => {
1041
+ * await updateUserPreferences(values);
1042
+ * }
1043
+ * });
1044
+ *
1045
+ * useFormAutoSubmission(form, 500);
1046
+ *
1047
+ * @example
1048
+ * // Auto-save a draft
1049
+ * const form = useForm(draftSchema, {
1050
+ * initialValues: draft,
1051
+ * onSubmit: saveDraft,
1052
+ * validationMode: "live"
1053
+ * });
1054
+ *
1055
+ * useFormAutoSubmission(form);
1056
+ */
1057
+ export declare const useFormAutoSubmission: <T>(form: FormWithAutoSubmit<T>, delay?: number) => null;
1058
+ /**
1059
+ * A React hook that debounces a callback function, delaying its execution until after
1060
+ * a specified delay period has elapsed since the last time it was invoked.
1061
+ *
1062
+ * Useful for optimizing performance by limiting the rate at which a function is called,
1063
+ * such as in response to rapid user input or scroll events.
1064
+ *
1065
+ * @template T - The callback function type
1066
+ * @template Params - The parameter types of the callback function
1067
+ * @template Return - The return type of the callback function
1068
+ *
1069
+ * @param callback - The function to debounce
1070
+ * @param delay - The number of milliseconds to delay execution
1071
+ * @returns A debounced version of the callback function that can be called with the same parameters
1072
+ *
1073
+ * @example
1074
+ * // Debounce a search function
1075
+ * const debouncedSearch = useDebounce((query: string) => {
1076
+ * fetchSearchResults(query);
1077
+ * }, 300);
1078
+ *
1079
+ * @example
1080
+ * // Use in an input handler
1081
+ * const handleInputChange = useDebounce((value: string) => {
1082
+ * form.setFieldValue('search', value);
1083
+ * }, 500);
1084
+ */
1085
+ export declare function useDebounce<T extends (...args: Params) => Return, Params extends unknown[] = Parameters<T>, Return = ReturnType<T>>(callback: T, delay: number): (...args: Params) => void;
1086
+ export type { ExtractFieldPaths, FormValidator, GetArrayItemType, UseFormReturn };