@railway-ts/use-form 0.1.15 → 0.1.17

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,1446 @@
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
+ ): UseFormReturn<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
+ ### getFieldError
532
+
533
+ Returns the error message for a field only if it has been touched, otherwise `undefined`.
534
+ Eliminates the common `touched[field] ? errors[field] : undefined` boilerplate.
535
+
536
+ ```typescript
537
+ getFieldError<TField extends ExtractFieldPaths<TValues>>(
538
+ field: TField
539
+ ): string | undefined
540
+ ```
541
+
542
+ **Parameters:**
543
+
544
+ - `field` - Field path with autocomplete
545
+
546
+ **Returns:** The error message string if the field is touched and has an error, otherwise `undefined`.
547
+
548
+ **Example:**
549
+
550
+ ```typescript
551
+ // Instead of:
552
+ {form.touched.email && form.errors.email && <span>{form.errors.email}</span>}
553
+
554
+ // Use:
555
+ {form.getFieldError("email") && <span>{form.getFieldError("email")}</span>}
556
+ ```
557
+
558
+ ### getFieldId
559
+
560
+ Returns a stable HTML element ID for a field without creating onChange/onBlur handlers.
561
+ Useful for linking `<label htmlFor>` to an input without calling a full props factory.
562
+
563
+ ```typescript
564
+ getFieldId<TField extends ExtractFieldPaths<TValues>>(
565
+ field: TField,
566
+ optionValue?: string | number
567
+ ): string
568
+ ```
569
+
570
+ **Parameters:**
571
+
572
+ - `field` - Field path with autocomplete
573
+ - `optionValue` - Optional value for checkbox group / radio group options
574
+
575
+ **Returns:** The element ID string — the field path for simple fields, or `field-optionValue` for option fields.
576
+
577
+ **Example:**
578
+
579
+ ```typescript
580
+ // Simple field — returns "username"
581
+ <label htmlFor={form.getFieldId('username')}>Username</label>
582
+ <input {...form.getFieldProps('username')} />
583
+
584
+ // Checkbox group option — returns "contacts-email"
585
+ <label htmlFor={form.getFieldId('contacts', 'email')}>Email</label>
586
+ <input type="checkbox" {...form.getCheckboxGroupOptionProps('contacts', 'email')} />
587
+ ```
588
+
589
+ ### validateForm
590
+
591
+ Manually trigger validation.
592
+
593
+ ```typescript
594
+ validateForm(values: TValues): Result<TValues, ValidationError[]>
595
+ ```
596
+
597
+ **Parameters:**
598
+
599
+ - `values` - Values to validate
600
+
601
+ **Returns:**
602
+ Railway Result type with validated data or errors.
603
+
604
+ **Example:**
605
+
606
+ ```typescript
607
+ import { isOk } from '@railway-ts/pipelines/result';
608
+
609
+ const result = form.validateForm(form.values);
610
+ if (isOk(result)) {
611
+ console.log('Valid:', result.value);
612
+ } else {
613
+ console.log('Errors:', result.error);
614
+ }
615
+ ```
616
+
617
+ ## Field Props Factories
618
+
619
+ Methods that return props for native HTML elements.
620
+
621
+ ### getFieldProps
622
+
623
+ Props for text inputs and textareas.
624
+
625
+ ```typescript
626
+ getFieldProps<TField extends ExtractFieldPaths<TValues>>(
627
+ field: TField
628
+ ): NativeFieldProps
629
+ ```
630
+
631
+ **Returns:**
632
+
633
+ ```typescript
634
+ {
635
+ id: string;
636
+ name: string;
637
+ value: string | number;
638
+ onChange: (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => void;
639
+ onBlur: () => void;
640
+ }
641
+ ```
642
+
643
+ **Example:**
644
+
645
+ ```typescript
646
+ <input type="text" {...form.getFieldProps("username")} />
647
+ <input type="email" {...form.getFieldProps("email")} />
648
+ <textarea {...form.getFieldProps("bio")} />
649
+ ```
650
+
651
+ ### getSelectFieldProps
652
+
653
+ Props for select elements.
654
+
655
+ ```typescript
656
+ getSelectFieldProps<TField extends ExtractFieldPaths<TValues>>(
657
+ field: TField
658
+ ): NativeSelectProps
659
+ ```
660
+
661
+ **Returns:**
662
+
663
+ ```typescript
664
+ {
665
+ id: string;
666
+ name: string;
667
+ value: string | number;
668
+ onChange: (e: ChangeEvent<HTMLSelectElement>) => void;
669
+ onBlur: () => void;
670
+ }
671
+ ```
672
+
673
+ **Example:**
674
+
675
+ ```typescript
676
+ <select {...form.getSelectFieldProps("country")}>
677
+ <option value="us">United States</option>
678
+ <option value="ca">Canada</option>
679
+ </select>
680
+ ```
681
+
682
+ ### getCheckboxProps
683
+
684
+ Props for boolean checkbox fields.
685
+
686
+ ```typescript
687
+ getCheckboxProps<TField extends ExtractFieldPaths<TValues>>(
688
+ field: TField
689
+ ): NativeCheckboxProps
690
+ ```
691
+
692
+ **Returns:**
693
+
694
+ ```typescript
695
+ {
696
+ id: string;
697
+ name: string;
698
+ checked: boolean;
699
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
700
+ onBlur: () => void;
701
+ }
702
+ ```
703
+
704
+ **Example:**
705
+
706
+ ```typescript
707
+ <input type="checkbox" {...form.getCheckboxProps("agreeToTerms")} />
708
+ ```
709
+
710
+ ### getSwitchProps
711
+
712
+ Props for toggle switches (styled checkboxes).
713
+
714
+ ```typescript
715
+ getSwitchProps<TField extends ExtractFieldPaths<TValues>>(
716
+ field: TField
717
+ ): NativeSwitchProps
718
+ ```
719
+
720
+ **Returns:**
721
+
722
+ ```typescript
723
+ {
724
+ id: string;
725
+ name: string;
726
+ checked: boolean;
727
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
728
+ onBlur: () => void;
729
+ }
730
+ ```
731
+
732
+ **Example:**
733
+
734
+ ```typescript
735
+ <input type="checkbox" {...form.getSwitchProps("notifications")} />
736
+ ```
737
+
738
+ ### getSliderProps
739
+
740
+ Props for range inputs.
741
+
742
+ ```typescript
743
+ getSliderProps<TField extends ExtractFieldPaths<TValues>>(
744
+ field: TField
745
+ ): NativeSliderProps
746
+ ```
747
+
748
+ **Returns:**
749
+
750
+ ```typescript
751
+ {
752
+ id: string;
753
+ name: string;
754
+ value: number;
755
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
756
+ onBlur: () => void;
757
+ }
758
+ ```
759
+
760
+ **Example:**
761
+
762
+ ```typescript
763
+ <input type="range" {...form.getSliderProps("volume")} min={0} max={100} />
764
+ ```
765
+
766
+ ### getCheckboxGroupOptionProps
767
+
768
+ Props for checkbox groups (arrays).
769
+
770
+ ```typescript
771
+ getCheckboxGroupOptionProps<TField extends ExtractFieldPaths<TValues>>(
772
+ field: TField,
773
+ optionValue: string | number
774
+ ): NativeCheckboxGroupOptionProps
775
+ ```
776
+
777
+ **Parameters:**
778
+
779
+ - `field` - Path to array field
780
+ - `optionValue` - Value this checkbox represents
781
+
782
+ **Returns:**
783
+
784
+ ```typescript
785
+ {
786
+ id: string;
787
+ name: string;
788
+ checked: boolean;
789
+ value: string | number;
790
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
791
+ onBlur: () => void;
792
+ }
793
+ ```
794
+
795
+ **Example:**
796
+
797
+ ```typescript
798
+ <label>
799
+ <input
800
+ type="checkbox"
801
+ {...form.getCheckboxGroupOptionProps("preferences", "email")}
802
+ />
803
+ Email Notifications
804
+ </label>
805
+ <label>
806
+ <input
807
+ type="checkbox"
808
+ {...form.getCheckboxGroupOptionProps("preferences", "sms")}
809
+ />
810
+ SMS Notifications
811
+ </label>
812
+ ```
813
+
814
+ ### getRadioGroupOptionProps
815
+
816
+ Props for radio button groups.
817
+
818
+ ```typescript
819
+ getRadioGroupOptionProps<TField extends ExtractFieldPaths<TValues>>(
820
+ field: TField,
821
+ optionValue: string | number
822
+ ): NativeRadioGroupOptionProps
823
+ ```
824
+
825
+ **Parameters:**
826
+
827
+ - `field` - Path to field
828
+ - `optionValue` - Value this radio button represents
829
+
830
+ **Returns:**
831
+
832
+ ```typescript
833
+ {
834
+ id: string;
835
+ name: string;
836
+ checked: boolean;
837
+ value: string | number;
838
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
839
+ onBlur: () => void;
840
+ }
841
+ ```
842
+
843
+ **Example:**
844
+
845
+ ```typescript
846
+ <label>
847
+ <input type="radio" {...form.getRadioGroupOptionProps("theme", "light")} />
848
+ Light
849
+ </label>
850
+ <label>
851
+ <input type="radio" {...form.getRadioGroupOptionProps("theme", "dark")} />
852
+ Dark
853
+ </label>
854
+ ```
855
+
856
+ ### getFileFieldProps
857
+
858
+ Props for file input elements.
859
+
860
+ ```typescript
861
+ getFileFieldProps<TField extends ExtractFieldPaths<TValues>>(
862
+ field: TField
863
+ ): NativeFileFieldProps
864
+ ```
865
+
866
+ **Returns:**
867
+
868
+ ```typescript
869
+ {
870
+ id: string;
871
+ name: string;
872
+ onChange: (e: ChangeEvent<HTMLInputElement>) => void;
873
+ onBlur: () => void;
874
+ }
875
+ ```
876
+
877
+ **Example:**
878
+
879
+ ```typescript
880
+ <input type="file" {...form.getFileFieldProps("avatar")} accept="image/*" />
881
+ ```
882
+
883
+ ## Array Helpers
884
+
885
+ ### arrayHelpers
886
+
887
+ Get helpers for managing array fields.
888
+
889
+ ```typescript
890
+ arrayHelpers<TField extends keyof TValues & string>(
891
+ field: TField
892
+ ): ArrayHelpers<GetArrayItemType<TValues, TField>, ExtractFieldPaths<GetArrayItemType<TValues, TField>>>
893
+ ```
894
+
895
+ **Parameters:**
896
+
897
+ - `field` - Path to array field
898
+
899
+ **Returns:** `ArrayHelpers` object with methods and field binding helpers.
900
+
901
+ **Example:**
902
+
903
+ ```typescript
904
+ const helpers = form.arrayHelpers('contacts');
905
+ ```
906
+
907
+ ### ArrayHelpers Methods
908
+
909
+ #### values
910
+
911
+ Type: `TItem[]`
912
+
913
+ Current array values.
914
+
915
+ ```typescript
916
+ helpers.values; // [{ name: "John", email: "john@example.com" }, ...]
917
+ ```
918
+
919
+ #### push
920
+
921
+ Add item to end of array.
922
+
923
+ ```typescript
924
+ push(item: TItem): void
925
+ ```
926
+
927
+ **Example:**
928
+
929
+ ```typescript
930
+ helpers.push({ name: '', email: '' });
931
+ ```
932
+
933
+ #### remove
934
+
935
+ Remove item by index.
936
+
937
+ ```typescript
938
+ remove(index: number): void
939
+ ```
940
+
941
+ **Example:**
942
+
943
+ ```typescript
944
+ helpers.remove(2); // Remove third item
945
+ ```
946
+
947
+ #### insert
948
+
949
+ Insert item at specific position.
950
+
951
+ ```typescript
952
+ insert(index: number, item: TItem): void
953
+ ```
954
+
955
+ **Example:**
956
+
957
+ ```typescript
958
+ helpers.insert(1, { name: 'Jane', email: 'jane@example.com' });
959
+ ```
960
+
961
+ #### swap
962
+
963
+ Swap two items by index.
964
+
965
+ ```typescript
966
+ swap(indexA: number, indexB: number): void
967
+ ```
968
+
969
+ **Example:**
970
+
971
+ ```typescript
972
+ helpers.swap(0, 2); // Swap first and third items
973
+ ```
974
+
975
+ #### move
976
+
977
+ Move item from one position to another.
978
+
979
+ ```typescript
980
+ move(from: number, to: number): void
981
+ ```
982
+
983
+ **Example:**
984
+
985
+ ```typescript
986
+ helpers.move(2, 0); // Move third item to first position
987
+ ```
988
+
989
+ #### replace
990
+
991
+ Replace item at index.
992
+
993
+ ```typescript
994
+ replace(index: number, item: TItem): void
995
+ ```
996
+
997
+ **Example:**
998
+
999
+ ```typescript
1000
+ helpers.replace(1, { name: 'Updated', email: 'updated@example.com' });
1001
+ ```
1002
+
1003
+ ### ArrayHelpers Field Props
1004
+
1005
+ Array helpers also provide field prop factories for array items.
1006
+
1007
+ #### getFieldProps
1008
+
1009
+ Get props for item field.
1010
+
1011
+ ```typescript
1012
+ getFieldProps<TField extends ExtractFieldPaths<TItem>>(
1013
+ index: number,
1014
+ field: TField
1015
+ ): NativeFieldProps
1016
+ ```
1017
+
1018
+ **Example:**
1019
+
1020
+ ```typescript
1021
+ <input {...helpers.getFieldProps(0, "name")} />
1022
+ <input {...helpers.getFieldProps(0, "email")} />
1023
+ ```
1024
+
1025
+ #### getSelectFieldProps
1026
+
1027
+ Get select props for item field.
1028
+
1029
+ ```typescript
1030
+ getSelectFieldProps<TField extends ExtractFieldPaths<TItem>>(
1031
+ index: number,
1032
+ field: TField
1033
+ ): NativeSelectProps
1034
+ ```
1035
+
1036
+ **Example:**
1037
+
1038
+ ```typescript
1039
+ <select {...helpers.getSelectFieldProps(0, "country")}>
1040
+ <option value="us">US</option>
1041
+ </select>
1042
+ ```
1043
+
1044
+ #### getCheckboxProps
1045
+
1046
+ Get checkbox props for item field.
1047
+
1048
+ ```typescript
1049
+ getCheckboxProps<TField extends ExtractFieldPaths<TItem>>(
1050
+ index: number,
1051
+ field: TField
1052
+ ): NativeCheckboxProps
1053
+ ```
1054
+
1055
+ **Example:**
1056
+
1057
+ ```typescript
1058
+ <input type="checkbox" {...helpers.getCheckboxProps(0, "active")} />
1059
+ ```
1060
+
1061
+ #### getSwitchProps
1062
+
1063
+ Get switch props for item field.
1064
+
1065
+ ```typescript
1066
+ getSwitchProps<TField extends ExtractFieldPaths<TItem>>(
1067
+ index: number,
1068
+ field: TField
1069
+ ): NativeSwitchProps
1070
+ ```
1071
+
1072
+ **Example:**
1073
+
1074
+ ```typescript
1075
+ <input type="checkbox" {...helpers.getSwitchProps(0, "enabled")} />
1076
+ ```
1077
+
1078
+ #### getSliderProps
1079
+
1080
+ Get slider props for item field.
1081
+
1082
+ ```typescript
1083
+ getSliderProps<TField extends ExtractFieldPaths<TItem>>(
1084
+ index: number,
1085
+ field: TField
1086
+ ): NativeSliderProps
1087
+ ```
1088
+
1089
+ **Example:**
1090
+
1091
+ ```typescript
1092
+ <input type="range" {...helpers.getSliderProps(0, "priority")} />
1093
+ ```
1094
+
1095
+ #### getFileFieldProps
1096
+
1097
+ Get file input props for item field.
1098
+
1099
+ ```typescript
1100
+ getFileFieldProps<TField extends ExtractFieldPaths<TItem>>(
1101
+ index: number,
1102
+ field: TField
1103
+ ): NativeFileFieldProps
1104
+ ```
1105
+
1106
+ **Example:**
1107
+
1108
+ ```typescript
1109
+ <input type="file" {...helpers.getFileFieldProps(0, "document")} />
1110
+ ```
1111
+
1112
+ #### getRadioGroupOptionProps
1113
+
1114
+ Get radio button props for item field.
1115
+
1116
+ ```typescript
1117
+ getRadioGroupOptionProps<TField extends ExtractFieldPaths<TItem>>(
1118
+ index: number,
1119
+ field: TField,
1120
+ optionValue: string | number
1121
+ ): NativeRadioGroupOptionProps
1122
+ ```
1123
+
1124
+ **Example:**
1125
+
1126
+ ```typescript
1127
+ <input
1128
+ type="radio"
1129
+ {...helpers.getRadioGroupOptionProps(0, "status", "active")}
1130
+ />
1131
+ ```
1132
+
1133
+ ## useFormAutoSubmission
1134
+
1135
+ Hook for auto-submitting forms after debounced changes.
1136
+ Monitors form values and automatically triggers submission when the form
1137
+ is dirty, valid, and values have changed since the last validation.
1138
+
1139
+ ### Signature
1140
+
1141
+ ```typescript
1142
+ function useFormAutoSubmission<T>(
1143
+ form: FormWithAutoSubmit<T>,
1144
+ delay?: number
1145
+ ): null;
1146
+ ```
1147
+
1148
+ ### Parameters
1149
+
1150
+ #### form
1151
+
1152
+ A form instance from `useForm` (or any object with `values`, `isDirty`, `isValid`, `validateForm`, and `handleSubmit`).
1153
+
1154
+ #### delay
1155
+
1156
+ Type: `number`
1157
+ Optional, Default: `200`
1158
+
1159
+ Debounce delay in milliseconds before auto-submitting.
1160
+
1161
+ ### Example
1162
+
1163
+ ```typescript
1164
+ const form = useForm(validator, {
1165
+ initialValues: { search: '' },
1166
+ onSubmit: async (values) => {
1167
+ await fetch(`/api/search?q=${values.search}`);
1168
+ },
1169
+ validationMode: 'live',
1170
+ });
1171
+
1172
+ // Auto-submit 500ms after the user stops typing
1173
+ useFormAutoSubmission(form, 500);
1174
+ ```
1175
+
1176
+ ## useDebounce
1177
+
1178
+ Hook for debouncing a callback function.
1179
+
1180
+ ### Signature
1181
+
1182
+ ```typescript
1183
+ function useDebounce<T extends (...args: Param) => Return>(
1184
+ callback: T,
1185
+ delay: number
1186
+ ): (...args: Param) => void;
1187
+ ```
1188
+
1189
+ ### Parameters
1190
+
1191
+ - `callback` - The function to debounce
1192
+ - `delay` - Milliseconds to wait before invoking the callback
1193
+
1194
+ ### Returns
1195
+
1196
+ A debounced version of the callback. Calling it resets the delay timer; the original callback fires once the caller stops invoking for `delay` ms.
1197
+
1198
+ ### Example
1199
+
1200
+ ```typescript
1201
+ const debouncedSearch = useDebounce((query: string) => {
1202
+ fetchSearchResults(query);
1203
+ }, 300);
1204
+
1205
+ // In a handler:
1206
+ <input onChange={(e) => debouncedSearch(e.target.value)} />
1207
+ ```
1208
+
1209
+ ## Validation Functions
1210
+
1211
+ Functions from `@railway-ts/pipelines/schema` for cross-field validation.
1212
+
1213
+ ### refineAt
1214
+
1215
+ Create validators that target specific fields with errors while accessing the entire object.
1216
+
1217
+ ```typescript
1218
+ function refineAt<T>(
1219
+ targetPath: string | string[],
1220
+ predicate: (value: T) => boolean,
1221
+ message: string
1222
+ ): Validator<T, T>;
1223
+ ```
1224
+
1225
+ **Parameters:**
1226
+
1227
+ - `targetPath` - Field path where error should be attached (string or array)
1228
+ - `predicate` - Validation function receiving entire parent object, returns true if valid
1229
+ - `message` - Error message when validation fails
1230
+
1231
+ **Returns:** Validator function for use with `chain` at object level
1232
+
1233
+ **Example:**
1234
+
1235
+ ```typescript
1236
+ import { chain, refineAt } from '@railway-ts/pipelines/schema';
1237
+
1238
+ // Password confirmation
1239
+ const validator = chain(
1240
+ object({
1241
+ password: required(string()),
1242
+ confirmPassword: required(string()),
1243
+ }),
1244
+ refineAt(
1245
+ 'confirmPassword',
1246
+ (data) => data.password === data.confirmPassword,
1247
+ 'Passwords must match'
1248
+ )
1249
+ );
1250
+ ```
1251
+
1252
+ **Example:**
1253
+
1254
+ ```typescript
1255
+ // Conditional required field
1256
+ const baseSchema = object({
1257
+ accountType: required(stringEnum(['personal', 'business'])),
1258
+ taxId: optional(string()),
1259
+ });
1260
+
1261
+ type AccountData = InferSchemaType<typeof baseSchema>;
1262
+
1263
+ const accountValidator = chain(
1264
+ baseSchema,
1265
+ refineAt<AccountData>(
1266
+ 'taxId',
1267
+ (data) => data.accountType === 'personal' || !!data.taxId,
1268
+ 'Tax ID is required for business accounts'
1269
+ )
1270
+ );
1271
+ ```
1272
+
1273
+ **Example:**
1274
+
1275
+ ```typescript
1276
+ // Date range validation
1277
+ const bookingValidator = chain(
1278
+ object({
1279
+ checkIn: required(parseDate()),
1280
+ checkOut: required(parseDate()),
1281
+ }),
1282
+ refineAt(
1283
+ 'checkOut',
1284
+ (data) => data.checkOut > data.checkIn,
1285
+ 'Check-out must be after check-in'
1286
+ )
1287
+ );
1288
+ ```
1289
+
1290
+ **See also:** [Recipes - Dependent Fields](./RECIPES.md#dependent-fields--cross-field-validation) for more examples
1291
+
1292
+ ### Validation Paths
1293
+
1294
+ There are two patterns for where validation errors land:
1295
+
1296
+ **Single-field validation** -- validating the field's own value:
1297
+
1298
+ - Use `path: ''` in the error object
1299
+ - The library attaches the error to whatever field path this validator is nested under
1300
+ - Example: `avatar: required(fileValidator)` where `fileValidator` returns `err([{ path: '', message: '...' }])`
1301
+
1302
+ **Cross-field validation** -- validating based on other fields:
1303
+
1304
+ - Use `chain` at the **object level** with `refineAt`
1305
+ - The first argument to `refineAt` is the field path where the error should appear
1306
+ - The predicate receives the entire parent object
1307
+ - Example: `refineAt('confirmPassword', (data) => data.password === data.confirmPassword, '...')`
1308
+
1309
+ ```typescript
1310
+ // Single-field: error lands on the field itself
1311
+ const strongPassword = refine<string>((value) => {
1312
+ if (isStrong(value)) return ok(value);
1313
+ return err([{ path: '', message: 'Too weak' }]); // path: '' = "this field"
1314
+ });
1315
+
1316
+ // Cross-field: error lands on the specified target
1317
+ const schema = chain(
1318
+ object({ password: required(string()), confirm: required(string()) }),
1319
+ refineAt('confirm', (d) => d.password === d.confirm, 'Must match') // target = 'confirm'
1320
+ );
1321
+ ```
1322
+
1323
+ ## Type Utilities
1324
+
1325
+ ### UseFormReturn
1326
+
1327
+ The return type of the `useForm` hook. Use this to type variables, function parameters, or component props that accept a form instance.
1328
+
1329
+ ```typescript
1330
+ import { type UseFormReturn } from '@railway-ts/use-form';
1331
+
1332
+ type Props = {
1333
+ form: UseFormReturn<{ email: string; password: string }>;
1334
+ };
1335
+
1336
+ function SubmitButton({ form }: Props) {
1337
+ return (
1338
+ <button disabled={form.isSubmitting || !form.isValid}>
1339
+ Submit
1340
+ </button>
1341
+ );
1342
+ }
1343
+ ```
1344
+
1345
+ ### InferSchemaType
1346
+
1347
+ Extract TypeScript type from validator schema. Works with nested objects, arrays, and composed schemas.
1348
+
1349
+ ```typescript
1350
+ import { type InferSchemaType } from '@railway-ts/pipelines/schema';
1351
+
1352
+ const validator = object({
1353
+ name: required(string()),
1354
+ age: required(parseNumber()),
1355
+ });
1356
+
1357
+ type Form = InferSchemaType<typeof validator>;
1358
+ // { name: string; age: number; }
1359
+ ```
1360
+
1361
+ Compose with nested schemas:
1362
+
1363
+ ```typescript
1364
+ const addressSchema = object({
1365
+ city: required(string()),
1366
+ zip: required(string()),
1367
+ });
1368
+
1369
+ const userSchema = object({
1370
+ name: required(string()),
1371
+ addresses: array(addressSchema),
1372
+ primaryContact: required(contactSchema),
1373
+ });
1374
+
1375
+ type User = InferSchemaType<typeof userSchema>;
1376
+ type Address = InferSchemaType<typeof addressSchema>;
1377
+ type UserAddresses = User['addresses']; // Address[]
1378
+ ```
1379
+
1380
+ ### ExtractFieldPaths
1381
+
1382
+ Extract all valid dot-notation field paths from a type. Arrays and Dates are treated as terminal values -- `ExtractFieldPaths` returns `"tags"`, not `"tags[0]"`.
1383
+
1384
+ ```typescript
1385
+ import { type ExtractFieldPaths } from '@railway-ts/use-form';
1386
+
1387
+ type User = {
1388
+ name: string;
1389
+ address: {
1390
+ city: string;
1391
+ zip: string;
1392
+ };
1393
+ tags: string[];
1394
+ };
1395
+
1396
+ type Paths = ExtractFieldPaths<User>;
1397
+ // "name" | "address" | "address.city" | "address.zip" | "tags"
1398
+ ```
1399
+
1400
+ ### FieldPath
1401
+
1402
+ String type for field paths.
1403
+
1404
+ ```typescript
1405
+ type FieldPath = string;
1406
+ ```
1407
+
1408
+ Supports dot notation and bracket notation:
1409
+
1410
+ - `"user.name"`
1411
+ - `"addresses[0]"`
1412
+ - `"users[2].email"`
1413
+
1414
+ ## Railway Types
1415
+
1416
+ Types from @railway-ts/pipelines.
1417
+
1418
+ ### Result
1419
+
1420
+ ```typescript
1421
+ type Result<T, E> = Ok<T> | Err<E>;
1422
+ ```
1423
+
1424
+ Railway result type representing success or failure.
1425
+
1426
+ ### Validator
1427
+
1428
+ ```typescript
1429
+ type Validator<TInput, TOutput> = (
1430
+ value: TInput,
1431
+ path?: string[]
1432
+ ) => Result<TOutput, ValidationError[]>;
1433
+ ```
1434
+
1435
+ Function that validates input and returns typed output or errors.
1436
+
1437
+ ### ValidationError
1438
+
1439
+ ```typescript
1440
+ type ValidationError = {
1441
+ path: string[];
1442
+ message: string;
1443
+ };
1444
+ ```
1445
+
1446
+ Validation error with field path (as array) and message. The `formatErrors` function converts the path array to dot notation string for display.