@railway-ts/use-form 0.1.14 → 0.1.16

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/docs/API.md ADDED
@@ -0,0 +1,1368 @@
1
+ # API Reference
2
+
3
+ Complete API documentation for @railway-ts/use-form.
4
+
5
+ ## useForm
6
+
7
+ Main hook for form management.
8
+
9
+ ### Signature
10
+
11
+ ```typescript
12
+ function useForm<TValues extends Record<string, unknown>>(
13
+ validator:
14
+ | MaybeAsyncValidator<unknown, TValues>
15
+ | StandardSchemaV1<unknown, TValues>,
16
+ options: FormOptions<TValues>
17
+ ): FormReturn<TValues>;
18
+ ```
19
+
20
+ ### Parameters
21
+
22
+ #### validator
23
+
24
+ Type: `MaybeAsyncValidator<unknown, TValues> | StandardSchemaV1<unknown, TValues>`
25
+
26
+ A Railway-oriented validator from @railway-ts/pipelines, **or** any Standard Schema v1 compliant object (Zod 3.23+, Valibot v1+, ArkType 2.0+). Standard Schema objects are detected automatically by checking for the `~standard` property -- no adapters needed.
27
+
28
+ ```typescript
29
+ // Railway-ts schema
30
+ import { object, string, required } from '@railway-ts/pipelines/schema';
31
+ const validator = object({
32
+ email: required(string()),
33
+ password: required(string()),
34
+ });
35
+
36
+ // Or a Zod schema (Standard Schema v1)
37
+ import { z } from 'zod';
38
+ const validator = z.object({
39
+ email: z.string().email(),
40
+ password: z.string().min(8),
41
+ });
42
+
43
+ // Or a Valibot schema (Standard Schema v1)
44
+ import * as v from 'valibot';
45
+ const validator = v.object({
46
+ email: v.pipe(v.string(), v.email()),
47
+ password: v.pipe(v.string(), v.minLength(8)),
48
+ });
49
+ ```
50
+
51
+ #### options
52
+
53
+ Type: `FormOptions<TValues>`
54
+
55
+ Configuration object.
56
+
57
+ ```typescript
58
+ {
59
+ initialValues: TValues;
60
+ onSubmit?: (values: TValues) => void | Promise<void>;
61
+ validationMode?: "live" | "blur" | "mount" | "submit";
62
+ fieldValidators?: Partial<Record<ExtractFieldPaths<TValues>, FieldValidator>>;
63
+ onValuesChange?: (values: TValues, prevValues: TValues) => void;
64
+ onFieldChange?: (field: string, value: unknown, values: TValues) => void;
65
+ }
66
+ ```
67
+
68
+ ### Return Value
69
+
70
+ Returns an object with form state, methods, and field binding helpers.
71
+
72
+ ## FormOptions
73
+
74
+ Configuration options for useForm.
75
+
76
+ ### Properties
77
+
78
+ #### initialValues
79
+
80
+ Type: `TValues`
81
+ Required
82
+
83
+ Initial values for form fields. Used when form is reset.
84
+
85
+ ```typescript
86
+ initialValues: {
87
+ email: "",
88
+ password: "",
89
+ }
90
+ ```
91
+
92
+ #### onSubmit
93
+
94
+ Type: `(values: TValues) => void | Promise<void>`
95
+ Optional
96
+
97
+ Callback invoked when form is submitted with valid data.
98
+
99
+ ```typescript
100
+ onSubmit: async (values) => {
101
+ await api.submit(values);
102
+ };
103
+ ```
104
+
105
+ #### validationMode
106
+
107
+ Type: `"live" | "blur" | "mount" | "submit"`
108
+ Optional, Default: `"live"`
109
+
110
+ Controls when validation occurs.
111
+
112
+ - `live` - Validate on change and blur, mark touched on change
113
+ - `blur` - Validate on blur only
114
+ - `mount` - Validate once on mount, mark all fields touched
115
+ - `submit` - Validate only on submit
116
+
117
+ #### fieldValidators
118
+
119
+ Type: `{ [K in ExtractFieldPaths<TValues>]?: (value: FieldTypeAtPath<TValues, K>, values: TValues) => string | undefined | Promise<string | undefined> }`
120
+ Optional
121
+
122
+ Per-field validator functions for field-level async validation. The `value` parameter is typed based on the field path, so no cast is needed. Run independently from the main schema validator, only for the changed field. A field validator only runs when the schema produces **no error** for that field (schema passes first, then the field validator runs).
123
+
124
+ Return `undefined` for valid, or an error message string for invalid.
125
+
126
+ ```typescript
127
+ const form = useForm(userSchema, {
128
+ initialValues: { username: '', email: '' },
129
+ fieldValidators: {
130
+ username: async (value) => {
131
+ const available = await checkUsernameAvailable(value);
132
+ return available ? undefined : 'Username is already taken';
133
+ },
134
+ },
135
+ });
136
+
137
+ // Track per-field validation state
138
+ {form.validatingFields.username && <span>Checking...</span>}
139
+ ```
140
+
141
+ Field validator errors are stored in `fieldErrors` and merged into `errors` with priority above schema errors but below server errors.
142
+
143
+ #### onValuesChange
144
+
145
+ Type: `(values: TValues, prevValues: TValues) => void`
146
+ Optional
147
+
148
+ Callback invoked whenever form values change. Fires on field edits,
149
+ programmatic updates via `setFieldValue`/`setValues`, form reset, and
150
+ once on mount (where `prevValues` equals `values`). Inline functions
151
+ are safe — the callback is stored in a ref internally.
152
+
153
+ ```typescript
154
+ onValuesChange: (values, prevValues) => {
155
+ if (values.altitude !== prevValues.altitude) {
156
+ store.setAltitude(values.altitude);
157
+ }
158
+ },
159
+ ```
160
+
161
+ #### onFieldChange
162
+
163
+ Type: `(field: string, value: unknown, values: TValues) => void`
164
+ Optional
165
+
166
+ Callback invoked when an individual field changes via `setFieldValue`.
167
+ All native bindings route through `setFieldValue`, so this catches every
168
+ user interaction. Does not fire for batch updates (`setValues`, `resetForm`)
169
+ — use `onValuesChange` for those. Inline functions are safe.
170
+
171
+ Array helper operations (`push`, `remove`, `insert`, `swap`, `replace`) also
172
+ route through `setFieldValue`, so `onFieldChange` fires for them with the
173
+ array field path (e.g., `"contacts"`) and the full new array as the value.
174
+
175
+ ```typescript
176
+ onFieldChange: (field, value, values) => {
177
+ analytics.track('field_edited', { field });
178
+ },
179
+ ```
180
+
181
+ ## Form State
182
+
183
+ Properties returned by useForm.
184
+
185
+ ### values
186
+
187
+ Type: `TValues`
188
+
189
+ Current form field values.
190
+
191
+ ```typescript
192
+ form.values.email; // "user@example.com"
193
+ form.values.password; // "password123"
194
+ ```
195
+
196
+ ### touched
197
+
198
+ Type: `Record<FieldPath, boolean>`
199
+
200
+ Record of which fields have been interacted with.
201
+
202
+ ```typescript
203
+ form.touched.email; // true
204
+ form.touched.password; // false
205
+ ```
206
+
207
+ ### errors
208
+
209
+ Type: `Record<FieldPath, string>`
210
+
211
+ Combined client and server errors. Server errors take precedence.
212
+
213
+ ```typescript
214
+ form.errors.email; // "Email is required"
215
+ form.errors['addresses.0.city']; // "City is required"
216
+ ```
217
+
218
+ ### clientErrors
219
+
220
+ Type: `Record<FieldPath, string>`
221
+
222
+ Validation errors from the validator function.
223
+
224
+ ```typescript
225
+ form.clientErrors.email; // "Invalid email format"
226
+ ```
227
+
228
+ ### serverErrors
229
+
230
+ Type: `Record<FieldPath, string>`
231
+
232
+ Manually set errors from server responses.
233
+
234
+ ```typescript
235
+ form.serverErrors.username; // "Username already taken"
236
+ ```
237
+
238
+ ### isValid
239
+
240
+ Type: `boolean`
241
+
242
+ True when there are no validation errors.
243
+
244
+ ```typescript
245
+ <button disabled={!form.isValid}>Submit</button>
246
+ ```
247
+
248
+ ### isDirty
249
+
250
+ Type: `boolean`
251
+
252
+ True when any values have changed from initial state.
253
+
254
+ ```typescript
255
+ <button disabled={!form.isDirty}>Save Changes</button>
256
+ ```
257
+
258
+ ### isSubmitting
259
+
260
+ Type: `boolean`
261
+
262
+ True when form is currently being submitted.
263
+
264
+ ```typescript
265
+ <button disabled={form.isSubmitting}>
266
+ {form.isSubmitting ? "Submitting..." : "Submit"}
267
+ </button>
268
+ ```
269
+
270
+ ### isValidating
271
+
272
+ Type: `boolean`
273
+
274
+ Derived property. True when **any** async validation is in progress -- either form-level (from an async schema like `chainAsync`) or field-level (from `fieldValidators`). Use this to disable the submit button during any async check.
275
+
276
+ ```typescript
277
+ <button disabled={form.isSubmitting || form.isValidating || !form.isValid}>
278
+ Submit
279
+ </button>
280
+ ```
281
+
282
+ ### validatingFields
283
+
284
+ Type: `Record<FieldPath, boolean>`
285
+
286
+ Per-field tracking for `fieldValidators` only. Shows which specific fields currently have async validators running. Use this to show inline loading indicators next to individual fields.
287
+
288
+ ```typescript
289
+ {form.validatingFields.username && <span>Checking username...</span>}
290
+ ```
291
+
292
+ **isValidating vs validatingFields:** `isValidating` is a single boolean covering all async validation (form-wide). `validatingFields` is a record that only tracks `fieldValidators` -- it won't show `true` for form-level async schemas.
293
+
294
+ ### fieldErrors
295
+
296
+ Type: `Record<FieldPath, string>`
297
+
298
+ Errors from per-field validators (stored separately from schema errors).
299
+ These are merged into the `errors` object with priority above schema errors
300
+ but below server errors.
301
+
302
+ ```typescript
303
+ form.fieldErrors.email; // "Email is already taken"
304
+ ```
305
+
306
+ ### Error Priority
307
+
308
+ The `errors` object is a merged view of three separate error layers. When multiple layers have an error for the same field, higher-priority layers win:
309
+
310
+ | Priority | Source | Property | Populated when |
311
+ | ----------- | ----------------- | -------------- | ------------------------------------------------------------------------------ |
312
+ | 1 (lowest) | Schema validation | `clientErrors` | Schema validator runs (on change, blur, mount, or submit depending on mode) |
313
+ | 2 | Field validators | `fieldErrors` | `fieldValidators` option runs for a field (after schema passes for that field) |
314
+ | 3 (highest) | Server errors | `serverErrors` | You call `setServerErrors(...)` |
315
+
316
+ The merge is straightforward -- for each field path, the highest-priority non-empty error wins:
317
+
318
+ ```typescript
319
+ // What useForm does internally:
320
+ const errors = {
321
+ ...clientErrors, // Schema errors (base)
322
+ ...fieldErrors, // Field validator errors (override schema for same field)
323
+ ...serverErrors, // Server errors (highest priority)
324
+ };
325
+ ```
326
+
327
+ **When each layer gets cleared:**
328
+
329
+ - `clientErrors` -- replaced on every schema validation run (the entire object is swapped)
330
+ - `fieldErrors` -- cleared per-field when the field validator re-runs or the field's schema error reappears
331
+ - `serverErrors` -- auto-cleared per-field when the user edits the affected field; bulk-cleared on `clearServerErrors()` or new `handleSubmit`
332
+
333
+ A server error stays visible until the user changes the field, even if client validation passes. That's intentional -- the server said it's wrong, and only editing should dismiss it.
334
+
335
+ ### submitCount
336
+
337
+ Type: `number`
338
+
339
+ Number of times the form has been submitted (via handleSubmit).
340
+ Useful in `submit` mode for patterns like `submitCount === 0 || form.isValid`.
341
+
342
+ ```typescript
343
+ <button
344
+ type="submit"
345
+ disabled={form.submitCount > 0 && !form.isValid}
346
+ >
347
+ Submit
348
+ </button>
349
+ ```
350
+
351
+ ## Form Methods
352
+
353
+ ### setFieldValue
354
+
355
+ Update a single field value.
356
+
357
+ ```typescript
358
+ setFieldValue<TValue>(
359
+ field: FieldPath,
360
+ value: TValue,
361
+ shouldValidate?: boolean
362
+ ): void
363
+ ```
364
+
365
+ **Parameters:**
366
+
367
+ - `field` - Field path with autocomplete
368
+ - `value` - New value for the field (type-safe based on field type)
369
+ - `shouldValidate` - Whether to validate after update (default: based on validation mode)
370
+
371
+ **Example:**
372
+
373
+ ```typescript
374
+ form.setFieldValue('email', 'user@example.com');
375
+ form.setFieldValue('addresses.0.city', 'New York', false);
376
+ ```
377
+
378
+ ### setFieldTouched
379
+
380
+ Mark a field as touched or untouched.
381
+
382
+ ```typescript
383
+ setFieldTouched<TField extends ExtractFieldPaths<TValues>>(
384
+ field: TField,
385
+ isTouched?: boolean,
386
+ shouldValidate?: boolean
387
+ ): void
388
+ ```
389
+
390
+ **Parameters:**
391
+
392
+ - `field` - Field path with autocomplete
393
+ - `isTouched` - Whether field is touched (default: true)
394
+ - `shouldValidate` - Whether to validate after update (default: false)
395
+
396
+ **Example:**
397
+
398
+ ```typescript
399
+ form.setFieldTouched('email');
400
+ form.setFieldTouched('password', false);
401
+ ```
402
+
403
+ ### setValues
404
+
405
+ Update multiple field values at once. Nested objects are deep-merged so
406
+ sibling keys you don't mention are preserved.
407
+
408
+ ```typescript
409
+ setValues(values: DeepPartial<TValues>, shouldValidate?: boolean): void
410
+ ```
411
+
412
+ **Parameters:**
413
+
414
+ - `values` - Deep-partial object with new values (nested objects merge recursively; arrays, Dates, and primitives replace)
415
+ - `shouldValidate` - Whether to validate after update (default: based on validation mode)
416
+
417
+ **Example:**
418
+
419
+ ```typescript
420
+ // Flat update
421
+ form.setValues({
422
+ email: 'user@example.com',
423
+ password: 'newpassword',
424
+ });
425
+
426
+ // Nested update — only city changes; street and zip are preserved
427
+ form.setValues({
428
+ address: { city: 'NYC' },
429
+ });
430
+ ```
431
+
432
+ ### setServerErrors
433
+
434
+ Set server-side validation errors.
435
+
436
+ ```typescript
437
+ setServerErrors(errors: Record<FieldPath, string>): void
438
+ ```
439
+
440
+ **Parameters:**
441
+
442
+ - `errors` - Object mapping field paths to error messages
443
+
444
+ **Example:**
445
+
446
+ ```typescript
447
+ form.setServerErrors({
448
+ email: 'Email already exists',
449
+ username: 'Username taken',
450
+ });
451
+ ```
452
+
453
+ Server errors automatically clear when affected fields change.
454
+
455
+ ### clearServerErrors
456
+
457
+ Clear all server-side errors.
458
+
459
+ ```typescript
460
+ clearServerErrors(): void
461
+ ```
462
+
463
+ **Example:**
464
+
465
+ ```typescript
466
+ form.clearServerErrors();
467
+ ```
468
+
469
+ ### handleSubmit
470
+
471
+ Submit form with validation. Returns a Railway `Result` so you can pattern-match on the outcome.
472
+
473
+ ```typescript
474
+ handleSubmit(e?: FormEvent): Promise<Result<TValues, ValidationError[]>>
475
+ ```
476
+
477
+ **Parameters:**
478
+
479
+ - `e` - Optional form event (will call `preventDefault`)
480
+
481
+ **Returns:** `Promise<Result<TValues, ValidationError[]>>` -- `Ok` with validated data on success, `Err` with validation errors on failure.
482
+
483
+ **What it does:**
484
+
485
+ 1. Calls `preventDefault` on the event (if provided)
486
+ 2. Marks all fields as touched
487
+ 3. Clears existing server errors
488
+ 4. Runs schema validation (awaits if async)
489
+ 5. If schema passes and `fieldValidators` are configured, runs all field validators in parallel
490
+ 6. If everything passes, calls `onSubmit` (if provided)
491
+ 7. Returns the `Result`
492
+
493
+ **Example:**
494
+
495
+ ```typescript
496
+ // Use onSubmit callback (void discards the Promise for React 19 compatibility)
497
+ <form onSubmit={(e) => void form.handleSubmit(e)}>{/* fields */}</form>
498
+
499
+ // Advanced: pattern-match on the result
500
+ import { match } from "@railway-ts/pipelines/result";
501
+
502
+ const result = await form.handleSubmit();
503
+ match(result, {
504
+ ok: (values) => {
505
+ console.log("Submitted:", values);
506
+ navigate("/success");
507
+ },
508
+ err: (errors) => {
509
+ console.error("Validation errors:", errors);
510
+ scrollToFirstError();
511
+ },
512
+ });
513
+ ```
514
+
515
+ > **React 19 note:** React 19 form actions expect `onSubmit` handlers to not return a Promise. Use `(e) => void form.handleSubmit(e)` to discard the returned Promise and satisfy the type checker.
516
+
517
+ ### resetForm
518
+
519
+ Reset form to initial values and clear errors.
520
+
521
+ ```typescript
522
+ resetForm(): void
523
+ ```
524
+
525
+ **Example:**
526
+
527
+ ```typescript
528
+ <button onClick={() => form.resetForm()}>Reset</button>
529
+ ```
530
+
531
+ ### validateForm
532
+
533
+ Manually trigger validation.
534
+
535
+ ```typescript
536
+ validateForm(values: TValues): Result<TValues, ValidationError[]>
537
+ ```
538
+
539
+ **Parameters:**
540
+
541
+ - `values` - Values to validate
542
+
543
+ **Returns:**
544
+ Railway Result type with validated data or errors.
545
+
546
+ **Example:**
547
+
548
+ ```typescript
549
+ import { isOk } from '@railway-ts/pipelines/result';
550
+
551
+ const result = form.validateForm(form.values);
552
+ if (isOk(result)) {
553
+ console.log('Valid:', result.value);
554
+ } else {
555
+ console.log('Errors:', result.error);
556
+ }
557
+ ```
558
+
559
+ ## Field Props Factories
560
+
561
+ Methods that return props for native HTML elements.
562
+
563
+ ### getFieldProps
564
+
565
+ Props for text inputs and textareas.
566
+
567
+ ```typescript
568
+ getFieldProps<TField extends ExtractFieldPaths<TValues>>(
569
+ field: TField
570
+ ): NativeFieldProps
571
+ ```
572
+
573
+ **Returns:**
574
+
575
+ ```typescript
576
+ {
577
+ id: string;
578
+ name: string;
579
+ value: string | number;
580
+ onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
581
+ onBlur: () => void;
582
+ }
583
+ ```
584
+
585
+ **Example:**
586
+
587
+ ```typescript
588
+ <input type="text" {...form.getFieldProps("username")} />
589
+ <input type="email" {...form.getFieldProps("email")} />
590
+ <textarea {...form.getFieldProps("bio")} />
591
+ ```
592
+
593
+ ### getSelectFieldProps
594
+
595
+ Props for select elements.
596
+
597
+ ```typescript
598
+ getSelectFieldProps<TField extends ExtractFieldPaths<TValues>>(
599
+ field: TField
600
+ ): NativeSelectProps
601
+ ```
602
+
603
+ **Returns:**
604
+
605
+ ```typescript
606
+ {
607
+ id: string;
608
+ name: string;
609
+ value: string | number;
610
+ onChange: (e: ChangeEvent<HTMLSelectElement>) => void;
611
+ onBlur: () => void;
612
+ }
613
+ ```
614
+
615
+ **Example:**
616
+
617
+ ```typescript
618
+ <select {...form.getSelectFieldProps("country")}>
619
+ <option value="us">United States</option>
620
+ <option value="ca">Canada</option>
621
+ </select>
622
+ ```
623
+
624
+ ### getCheckboxProps
625
+
626
+ Props for boolean checkbox fields.
627
+
628
+ ```typescript
629
+ getCheckboxProps<TField extends ExtractFieldPaths<TValues>>(
630
+ field: TField
631
+ ): NativeCheckboxProps
632
+ ```
633
+
634
+ **Returns:**
635
+
636
+ ```typescript
637
+ {
638
+ id: string;
639
+ name: string;
640
+ checked: boolean;
641
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
642
+ onBlur: () => void;
643
+ }
644
+ ```
645
+
646
+ **Example:**
647
+
648
+ ```typescript
649
+ <input type="checkbox" {...form.getCheckboxProps("agreeToTerms")} />
650
+ ```
651
+
652
+ ### getSwitchProps
653
+
654
+ Props for toggle switches (styled checkboxes).
655
+
656
+ ```typescript
657
+ getSwitchProps<TField extends ExtractFieldPaths<TValues>>(
658
+ field: TField
659
+ ): NativeSwitchProps
660
+ ```
661
+
662
+ **Returns:**
663
+
664
+ ```typescript
665
+ {
666
+ id: string;
667
+ name: string;
668
+ checked: boolean;
669
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
670
+ onBlur: () => void;
671
+ }
672
+ ```
673
+
674
+ **Example:**
675
+
676
+ ```typescript
677
+ <input type="checkbox" {...form.getSwitchProps("notifications")} />
678
+ ```
679
+
680
+ ### getSliderProps
681
+
682
+ Props for range inputs.
683
+
684
+ ```typescript
685
+ getSliderProps<TField extends ExtractFieldPaths<TValues>>(
686
+ field: TField
687
+ ): NativeSliderProps
688
+ ```
689
+
690
+ **Returns:**
691
+
692
+ ```typescript
693
+ {
694
+ id: string;
695
+ name: string;
696
+ value: number;
697
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
698
+ onBlur: () => void;
699
+ }
700
+ ```
701
+
702
+ **Example:**
703
+
704
+ ```typescript
705
+ <input type="range" {...form.getSliderProps("volume")} min={0} max={100} />
706
+ ```
707
+
708
+ ### getCheckboxGroupOptionProps
709
+
710
+ Props for checkbox groups (arrays).
711
+
712
+ ```typescript
713
+ getCheckboxGroupOptionProps<TField extends ExtractFieldPaths<TValues>>(
714
+ field: TField,
715
+ optionValue: string | number
716
+ ): NativeCheckboxGroupOptionProps
717
+ ```
718
+
719
+ **Parameters:**
720
+
721
+ - `field` - Path to array field
722
+ - `optionValue` - Value this checkbox represents
723
+
724
+ **Returns:**
725
+
726
+ ```typescript
727
+ {
728
+ id: string;
729
+ name: string;
730
+ checked: boolean;
731
+ value: string | number;
732
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
733
+ onBlur: () => void;
734
+ }
735
+ ```
736
+
737
+ **Example:**
738
+
739
+ ```typescript
740
+ <label>
741
+ <input
742
+ type="checkbox"
743
+ {...form.getCheckboxGroupOptionProps("preferences", "email")}
744
+ />
745
+ Email Notifications
746
+ </label>
747
+ <label>
748
+ <input
749
+ type="checkbox"
750
+ {...form.getCheckboxGroupOptionProps("preferences", "sms")}
751
+ />
752
+ SMS Notifications
753
+ </label>
754
+ ```
755
+
756
+ ### getRadioGroupOptionProps
757
+
758
+ Props for radio button groups.
759
+
760
+ ```typescript
761
+ getRadioGroupOptionProps<TField extends ExtractFieldPaths<TValues>>(
762
+ field: TField,
763
+ optionValue: string | number
764
+ ): NativeRadioGroupOptionProps
765
+ ```
766
+
767
+ **Parameters:**
768
+
769
+ - `field` - Path to field
770
+ - `optionValue` - Value this radio button represents
771
+
772
+ **Returns:**
773
+
774
+ ```typescript
775
+ {
776
+ id: string;
777
+ name: string;
778
+ checked: boolean;
779
+ value: string | number;
780
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
781
+ onBlur: () => void;
782
+ }
783
+ ```
784
+
785
+ **Example:**
786
+
787
+ ```typescript
788
+ <label>
789
+ <input type="radio" {...form.getRadioGroupOptionProps("theme", "light")} />
790
+ Light
791
+ </label>
792
+ <label>
793
+ <input type="radio" {...form.getRadioGroupOptionProps("theme", "dark")} />
794
+ Dark
795
+ </label>
796
+ ```
797
+
798
+ ### getFileFieldProps
799
+
800
+ Props for file input elements.
801
+
802
+ ```typescript
803
+ getFileFieldProps<TField extends ExtractFieldPaths<TValues>>(
804
+ field: TField
805
+ ): NativeFileFieldProps
806
+ ```
807
+
808
+ **Returns:**
809
+
810
+ ```typescript
811
+ {
812
+ id: string;
813
+ name: string;
814
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
815
+ onBlur: () => void;
816
+ }
817
+ ```
818
+
819
+ **Example:**
820
+
821
+ ```typescript
822
+ <input type="file" {...form.getFileFieldProps("avatar")} accept="image/*" />
823
+ ```
824
+
825
+ ## Array Helpers
826
+
827
+ ### arrayHelpers
828
+
829
+ Get helpers for managing array fields.
830
+
831
+ ```typescript
832
+ arrayHelpers<TField extends keyof TValues & string>(
833
+ field: TField
834
+ ): ArrayHelpers<GetArrayItemType<TValues, TField>, ExtractFieldPaths<GetArrayItemType<TValues, TField>>>
835
+ ```
836
+
837
+ **Parameters:**
838
+
839
+ - `field` - Path to array field
840
+
841
+ **Returns:** `ArrayHelpers` object with methods and field binding helpers.
842
+
843
+ **Example:**
844
+
845
+ ```typescript
846
+ const helpers = form.arrayHelpers('contacts');
847
+ ```
848
+
849
+ ### ArrayHelpers Methods
850
+
851
+ #### values
852
+
853
+ Type: `TItem[]`
854
+
855
+ Current array values.
856
+
857
+ ```typescript
858
+ helpers.values; // [{ name: "John", email: "john@example.com" }, ...]
859
+ ```
860
+
861
+ #### push
862
+
863
+ Add item to end of array.
864
+
865
+ ```typescript
866
+ push(item: TItem): void
867
+ ```
868
+
869
+ **Example:**
870
+
871
+ ```typescript
872
+ helpers.push({ name: '', email: '' });
873
+ ```
874
+
875
+ #### remove
876
+
877
+ Remove item by index.
878
+
879
+ ```typescript
880
+ remove(index: number): void
881
+ ```
882
+
883
+ **Example:**
884
+
885
+ ```typescript
886
+ helpers.remove(2); // Remove third item
887
+ ```
888
+
889
+ #### insert
890
+
891
+ Insert item at specific position.
892
+
893
+ ```typescript
894
+ insert(index: number, item: TItem): void
895
+ ```
896
+
897
+ **Example:**
898
+
899
+ ```typescript
900
+ helpers.insert(1, { name: 'Jane', email: 'jane@example.com' });
901
+ ```
902
+
903
+ #### swap
904
+
905
+ Swap two items by index.
906
+
907
+ ```typescript
908
+ swap(indexA: number, indexB: number): void
909
+ ```
910
+
911
+ **Example:**
912
+
913
+ ```typescript
914
+ helpers.swap(0, 2); // Swap first and third items
915
+ ```
916
+
917
+ #### move
918
+
919
+ Move item from one position to another.
920
+
921
+ ```typescript
922
+ move(from: number, to: number): void
923
+ ```
924
+
925
+ **Example:**
926
+
927
+ ```typescript
928
+ helpers.move(2, 0); // Move third item to first position
929
+ ```
930
+
931
+ #### replace
932
+
933
+ Replace item at index.
934
+
935
+ ```typescript
936
+ replace(index: number, item: TItem): void
937
+ ```
938
+
939
+ **Example:**
940
+
941
+ ```typescript
942
+ helpers.replace(1, { name: 'Updated', email: 'updated@example.com' });
943
+ ```
944
+
945
+ ### ArrayHelpers Field Props
946
+
947
+ Array helpers also provide field prop factories for array items.
948
+
949
+ #### getFieldProps
950
+
951
+ Get props for item field.
952
+
953
+ ```typescript
954
+ getFieldProps<TField extends ExtractFieldPaths<TItem>>(
955
+ index: number,
956
+ field: TField
957
+ ): NativeFieldProps
958
+ ```
959
+
960
+ **Example:**
961
+
962
+ ```typescript
963
+ <input {...helpers.getFieldProps(0, "name")} />
964
+ <input {...helpers.getFieldProps(0, "email")} />
965
+ ```
966
+
967
+ #### getSelectFieldProps
968
+
969
+ Get select props for item field.
970
+
971
+ ```typescript
972
+ getSelectFieldProps<TField extends ExtractFieldPaths<TItem>>(
973
+ index: number,
974
+ field: TField
975
+ ): NativeSelectProps
976
+ ```
977
+
978
+ **Example:**
979
+
980
+ ```typescript
981
+ <select {...helpers.getSelectFieldProps(0, "country")}>
982
+ <option value="us">US</option>
983
+ </select>
984
+ ```
985
+
986
+ #### getCheckboxProps
987
+
988
+ Get checkbox props for item field.
989
+
990
+ ```typescript
991
+ getCheckboxProps<TField extends ExtractFieldPaths<TItem>>(
992
+ index: number,
993
+ field: TField
994
+ ): NativeCheckboxProps
995
+ ```
996
+
997
+ **Example:**
998
+
999
+ ```typescript
1000
+ <input type="checkbox" {...helpers.getCheckboxProps(0, "active")} />
1001
+ ```
1002
+
1003
+ #### getSwitchProps
1004
+
1005
+ Get switch props for item field.
1006
+
1007
+ ```typescript
1008
+ getSwitchProps<TField extends ExtractFieldPaths<TItem>>(
1009
+ index: number,
1010
+ field: TField
1011
+ ): NativeSwitchProps
1012
+ ```
1013
+
1014
+ **Example:**
1015
+
1016
+ ```typescript
1017
+ <input type="checkbox" {...helpers.getSwitchProps(0, "enabled")} />
1018
+ ```
1019
+
1020
+ #### getSliderProps
1021
+
1022
+ Get slider props for item field.
1023
+
1024
+ ```typescript
1025
+ getSliderProps<TField extends ExtractFieldPaths<TItem>>(
1026
+ index: number,
1027
+ field: TField
1028
+ ): NativeSliderProps
1029
+ ```
1030
+
1031
+ **Example:**
1032
+
1033
+ ```typescript
1034
+ <input type="range" {...helpers.getSliderProps(0, "priority")} />
1035
+ ```
1036
+
1037
+ #### getFileFieldProps
1038
+
1039
+ Get file input props for item field.
1040
+
1041
+ ```typescript
1042
+ getFileFieldProps<TField extends ExtractFieldPaths<TItem>>(
1043
+ index: number,
1044
+ field: TField
1045
+ ): NativeFileFieldProps
1046
+ ```
1047
+
1048
+ **Example:**
1049
+
1050
+ ```typescript
1051
+ <input type="file" {...helpers.getFileFieldProps(0, "document")} />
1052
+ ```
1053
+
1054
+ #### getRadioGroupOptionProps
1055
+
1056
+ Get radio button props for item field.
1057
+
1058
+ ```typescript
1059
+ getRadioGroupOptionProps<TField extends ExtractFieldPaths<TItem>>(
1060
+ index: number,
1061
+ field: TField,
1062
+ optionValue: string | number
1063
+ ): NativeRadioGroupOptionProps
1064
+ ```
1065
+
1066
+ **Example:**
1067
+
1068
+ ```typescript
1069
+ <input
1070
+ type="radio"
1071
+ {...helpers.getRadioGroupOptionProps(0, "status", "active")}
1072
+ />
1073
+ ```
1074
+
1075
+ ## useFormAutoSubmission
1076
+
1077
+ Hook for auto-submitting forms after debounced changes.
1078
+ Monitors form values and automatically triggers submission when the form
1079
+ is dirty, valid, and values have changed since the last validation.
1080
+
1081
+ ### Signature
1082
+
1083
+ ```typescript
1084
+ function useFormAutoSubmission<T>(
1085
+ form: FormWithAutoSubmit<T>,
1086
+ delay?: number
1087
+ ): null;
1088
+ ```
1089
+
1090
+ ### Parameters
1091
+
1092
+ #### form
1093
+
1094
+ A form instance from `useForm` (or any object with `values`, `isDirty`, `isValid`, `validateForm`, and `handleSubmit`).
1095
+
1096
+ #### delay
1097
+
1098
+ Type: `number`
1099
+ Optional, Default: `200`
1100
+
1101
+ Debounce delay in milliseconds before auto-submitting.
1102
+
1103
+ ### Example
1104
+
1105
+ ```typescript
1106
+ const form = useForm(validator, {
1107
+ initialValues: { search: '' },
1108
+ onSubmit: async (values) => {
1109
+ await fetch(`/api/search?q=${values.search}`);
1110
+ },
1111
+ validationMode: 'live',
1112
+ });
1113
+
1114
+ // Auto-submit 500ms after the user stops typing
1115
+ useFormAutoSubmission(form, 500);
1116
+ ```
1117
+
1118
+ ## useDebounce
1119
+
1120
+ Hook for debouncing a callback function.
1121
+
1122
+ ### Signature
1123
+
1124
+ ```typescript
1125
+ function useDebounce<T extends (...args: Param) => Return>(
1126
+ callback: T,
1127
+ delay: number
1128
+ ): (...args: Param) => void;
1129
+ ```
1130
+
1131
+ ### Parameters
1132
+
1133
+ - `callback` - The function to debounce
1134
+ - `delay` - Milliseconds to wait before invoking the callback
1135
+
1136
+ ### Returns
1137
+
1138
+ A debounced version of the callback. Calling it resets the delay timer; the original callback fires once the caller stops invoking for `delay` ms.
1139
+
1140
+ ### Example
1141
+
1142
+ ```typescript
1143
+ const debouncedSearch = useDebounce((query: string) => {
1144
+ fetchSearchResults(query);
1145
+ }, 300);
1146
+
1147
+ // In a handler:
1148
+ <input onChange={(e) => debouncedSearch(e.target.value)} />
1149
+ ```
1150
+
1151
+ ## Validation Functions
1152
+
1153
+ Functions from `@railway-ts/pipelines/schema` for cross-field validation.
1154
+
1155
+ ### refineAt
1156
+
1157
+ Create validators that target specific fields with errors while accessing the entire object.
1158
+
1159
+ ```typescript
1160
+ function refineAt<T>(
1161
+ targetPath: string | string[],
1162
+ predicate: (value: T) => boolean,
1163
+ message: string
1164
+ ): Validator<T, T>;
1165
+ ```
1166
+
1167
+ **Parameters:**
1168
+
1169
+ - `targetPath` - Field path where error should be attached (string or array)
1170
+ - `predicate` - Validation function receiving entire parent object, returns true if valid
1171
+ - `message` - Error message when validation fails
1172
+
1173
+ **Returns:** Validator function for use with `chain` at object level
1174
+
1175
+ **Example:**
1176
+
1177
+ ```typescript
1178
+ import { chain, refineAt } from '@railway-ts/pipelines/schema';
1179
+
1180
+ // Password confirmation
1181
+ const validator = chain(
1182
+ object({
1183
+ password: required(string()),
1184
+ confirmPassword: required(string()),
1185
+ }),
1186
+ refineAt(
1187
+ 'confirmPassword',
1188
+ (data) => data.password === data.confirmPassword,
1189
+ 'Passwords must match'
1190
+ )
1191
+ );
1192
+ ```
1193
+
1194
+ **Example:**
1195
+
1196
+ ```typescript
1197
+ // Conditional required field
1198
+ const baseSchema = object({
1199
+ accountType: required(stringEnum(['personal', 'business'])),
1200
+ taxId: optional(string()),
1201
+ });
1202
+
1203
+ type AccountData = InferSchemaType<typeof baseSchema>;
1204
+
1205
+ const accountValidator = chain(
1206
+ baseSchema,
1207
+ refineAt<AccountData>(
1208
+ 'taxId',
1209
+ (data) => data.accountType === 'personal' || !!data.taxId,
1210
+ 'Tax ID is required for business accounts'
1211
+ )
1212
+ );
1213
+ ```
1214
+
1215
+ **Example:**
1216
+
1217
+ ```typescript
1218
+ // Date range validation
1219
+ const bookingValidator = chain(
1220
+ object({
1221
+ checkIn: required(parseDate()),
1222
+ checkOut: required(parseDate()),
1223
+ }),
1224
+ refineAt(
1225
+ 'checkOut',
1226
+ (data) => data.checkOut > data.checkIn,
1227
+ 'Check-out must be after check-in'
1228
+ )
1229
+ );
1230
+ ```
1231
+
1232
+ **See also:** [Recipes - Dependent Fields](./RECIPES.md#dependent-fields--cross-field-validation) for more examples
1233
+
1234
+ ### Validation Paths
1235
+
1236
+ There are two patterns for where validation errors land:
1237
+
1238
+ **Single-field validation** -- validating the field's own value:
1239
+
1240
+ - Use `path: ''` in the error object
1241
+ - The library attaches the error to whatever field path this validator is nested under
1242
+ - Example: `avatar: required(fileValidator)` where `fileValidator` returns `err([{ path: '', message: '...' }])`
1243
+
1244
+ **Cross-field validation** -- validating based on other fields:
1245
+
1246
+ - Use `chain` at the **object level** with `refineAt`
1247
+ - The first argument to `refineAt` is the field path where the error should appear
1248
+ - The predicate receives the entire parent object
1249
+ - Example: `refineAt('confirmPassword', (data) => data.password === data.confirmPassword, '...')`
1250
+
1251
+ ```typescript
1252
+ // Single-field: error lands on the field itself
1253
+ const strongPassword = refine<string>((value) => {
1254
+ if (isStrong(value)) return ok(value);
1255
+ return err([{ path: '', message: 'Too weak' }]); // path: '' = "this field"
1256
+ });
1257
+
1258
+ // Cross-field: error lands on the specified target
1259
+ const schema = chain(
1260
+ object({ password: required(string()), confirm: required(string()) }),
1261
+ refineAt('confirm', (d) => d.password === d.confirm, 'Must match') // target = 'confirm'
1262
+ );
1263
+ ```
1264
+
1265
+ ## Type Utilities
1266
+
1267
+ ### InferSchemaType
1268
+
1269
+ Extract TypeScript type from validator schema. Works with nested objects, arrays, and composed schemas.
1270
+
1271
+ ```typescript
1272
+ import { type InferSchemaType } from '@railway-ts/pipelines/schema';
1273
+
1274
+ const validator = object({
1275
+ name: required(string()),
1276
+ age: required(parseNumber()),
1277
+ });
1278
+
1279
+ type Form = InferSchemaType<typeof validator>;
1280
+ // { name: string; age: number; }
1281
+ ```
1282
+
1283
+ Compose with nested schemas:
1284
+
1285
+ ```typescript
1286
+ const addressSchema = object({
1287
+ city: required(string()),
1288
+ zip: required(string()),
1289
+ });
1290
+
1291
+ const userSchema = object({
1292
+ name: required(string()),
1293
+ addresses: array(addressSchema),
1294
+ primaryContact: required(contactSchema),
1295
+ });
1296
+
1297
+ type User = InferSchemaType<typeof userSchema>;
1298
+ type Address = InferSchemaType<typeof addressSchema>;
1299
+ type UserAddresses = User['addresses']; // Address[]
1300
+ ```
1301
+
1302
+ ### ExtractFieldPaths
1303
+
1304
+ Extract all valid dot-notation field paths from a type. Arrays and Dates are treated as terminal values -- `ExtractFieldPaths` returns `"tags"`, not `"tags[0]"`.
1305
+
1306
+ ```typescript
1307
+ import { type ExtractFieldPaths } from '@railway-ts/use-form';
1308
+
1309
+ type User = {
1310
+ name: string;
1311
+ address: {
1312
+ city: string;
1313
+ zip: string;
1314
+ };
1315
+ tags: string[];
1316
+ };
1317
+
1318
+ type Paths = ExtractFieldPaths<User>;
1319
+ // "name" | "address" | "address.city" | "address.zip" | "tags"
1320
+ ```
1321
+
1322
+ ### FieldPath
1323
+
1324
+ String type for field paths.
1325
+
1326
+ ```typescript
1327
+ type FieldPath = string;
1328
+ ```
1329
+
1330
+ Supports dot notation and bracket notation:
1331
+
1332
+ - `"user.name"`
1333
+ - `"addresses[0]"`
1334
+ - `"users[2].email"`
1335
+
1336
+ ## Railway Types
1337
+
1338
+ Types from @railway-ts/pipelines.
1339
+
1340
+ ### Result
1341
+
1342
+ ```typescript
1343
+ type Result<T, E> = Ok<T> | Err<E>;
1344
+ ```
1345
+
1346
+ Railway result type representing success or failure.
1347
+
1348
+ ### Validator
1349
+
1350
+ ```typescript
1351
+ type Validator<TInput, TOutput> = (
1352
+ value: TInput,
1353
+ path?: string[]
1354
+ ) => Result<TOutput, ValidationError[]>;
1355
+ ```
1356
+
1357
+ Function that validates input and returns typed output or errors.
1358
+
1359
+ ### ValidationError
1360
+
1361
+ ```typescript
1362
+ type ValidationError = {
1363
+ path: string[];
1364
+ message: string;
1365
+ };
1366
+ ```
1367
+
1368
+ Validation error with field path (as array) and message. The `formatErrors` function converts the path array to dot notation string for display.