@railway-ts/use-form 0.1.33 → 0.1.34

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