@railway-ts/use-form 0.1.30 → 0.1.32

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 CHANGED
@@ -528,7 +528,15 @@ resetForm(): void
528
528
 
529
529
  ### getFieldError
530
530
 
531
- Returns the error message for a field only if it has been touched, otherwise `undefined`.
531
+ Returns the error message for a field path, gated on user interaction.
532
+
533
+ - **Leaf paths**: returns the error iff the field itself has been touched.
534
+ - **Group / parent paths**: returns the error iff *any* descendant field has been
535
+ touched. Cross-field validation errors that schemas attach to a non-leaf path
536
+ (e.g. `S.refineAt("confirm", v => v.password === v.confirm, …)` or
537
+ `S.refineAt("r2", …)` over a tuple) surface naturally on the group container,
538
+ without callers having to read `form.errors` and `form.touched` directly.
539
+
532
540
  Eliminates the common `touched[field] ? errors[field] : undefined` boilerplate.
533
541
 
534
542
  ```typescript
@@ -539,11 +547,11 @@ getFieldError<TField extends ExtractFieldPaths<TValues>>(
539
547
 
540
548
  **Parameters:**
541
549
 
542
- - `field` - Field path with autocomplete
550
+ - `field` - Field path with autocomplete (leaf or parent)
543
551
 
544
- **Returns:** The error message string if the field is touched and has an error, otherwise `undefined`.
552
+ **Returns:** The error message string if visible per the rules above, otherwise `undefined`.
545
553
 
546
- **Example:**
554
+ **Example — leaf:**
547
555
 
548
556
  ```typescript
549
557
  // Instead of:
@@ -553,6 +561,27 @@ getFieldError<TField extends ExtractFieldPaths<TValues>>(
553
561
  {form.getFieldError("email") && <span>{form.getFieldError("email")}</span>}
554
562
  ```
555
563
 
564
+ **Example — group / parent path:**
565
+
566
+ ```typescript
567
+ const schema = S.chain(
568
+ S.object({
569
+ password: S.required(S.string()),
570
+ confirm: S.required(S.string()),
571
+ }),
572
+ S.refineAt('confirm', (v) => v.password === v.confirm, 'Passwords must match'),
573
+ );
574
+
575
+ // In a fieldset that owns both inputs — error becomes visible once any
576
+ // descendant of `confirm` is touched (or `confirm` itself, for a leaf).
577
+ {form.getFieldError('confirm') && <p className="err">{form.getFieldError('confirm')}</p>}
578
+ ```
579
+
580
+ The descendant scan uses a path-prefix check that guards against sibling
581
+ collisions — `r2` does not match a touch on `r20`. `getFieldError` never
582
+ aggregates *across* paths: it only returns an error attached at the queried
583
+ path, gated on touch of the path or any of its descendants.
584
+
556
585
  ### getFieldId
557
586
 
558
587
  Returns a stable HTML element ID for a field without creating onChange/onBlur handlers.
@@ -1520,11 +1549,39 @@ String type for field paths.
1520
1549
  type FieldPath = string;
1521
1550
  ```
1522
1551
 
1523
- Supports dot notation and bracket notation:
1552
+ **Canonical form is dot notation.** Form state — `form.touched`, `form.errors`,
1553
+ `form.clientErrors`, `form.serverErrors`, `form.fieldErrors`,
1554
+ `form.validatingFields` — is always keyed in dot form, including numeric array
1555
+ and tuple indices:
1524
1556
 
1525
1557
  - `"user.name"`
1526
- - `"addresses[0]"`
1527
- - `"users[2].email"`
1558
+ - `"addresses.0"`
1559
+ - `"users.2.email"`
1560
+ - `"position.0"` (for a `[number, number, number]` tuple)
1561
+
1562
+ `ExtractFieldPaths<TValues>` only emits dot-form paths, so type-checked
1563
+ callers always pass dot form to `getFieldProps`, `setFieldValue`,
1564
+ `getFieldError`, etc.
1565
+
1566
+ **Bracket notation is accepted at API boundaries** for back-compat. When you
1567
+ pass `"addresses[0]"` to a method (`setFieldValue`, `setFieldTouched`,
1568
+ `getFieldError`, `setServerErrors`, …), it is normalized to `"addresses.0"`
1569
+ before being written to or read from form state. So:
1570
+
1571
+ ```typescript
1572
+ form.setFieldTouched('addresses[0]', true); // OK — stored as touched["addresses.0"]
1573
+ form.getFieldError('addresses[0]'); // OK — resolves to errors["addresses.0"]
1574
+ ```
1575
+
1576
+ **Direct map reads must use dot form**, because keys are stored canonically:
1577
+
1578
+ ```typescript
1579
+ form.errors['addresses.0.city']; // ✓ canonical
1580
+ form.errors['addresses[0].city']; // ✗ undefined — keys aren't stored bracket-form
1581
+ ```
1582
+
1583
+ When in doubt, prefer the method-based accessors (`getFieldError`) — they
1584
+ normalize the input — or the dot-form key from `ExtractFieldPaths`.
1528
1585
 
1529
1586
  ## Railway Types
1530
1587
 
@@ -1555,4 +1612,9 @@ type ValidationError = {
1555
1612
  };
1556
1613
  ```
1557
1614
 
1558
- Validation error with field path (as array) and message. The `formatErrors` function converts the path array to dot notation string for display.
1615
+ Validation error with field path (as array) and message. The `formatErrors`
1616
+ helper from `@railway-ts/pipelines/schema` joins these path arrays into
1617
+ string keys, using bracket notation for numeric segments
1618
+ (`["users", "0", "name"] → "users[0].name"`). `useForm` normalizes those
1619
+ keys to canonical dot form before storing them in `form.errors`, so what
1620
+ you read off the form is always `"users.0.name"`.
@@ -368,6 +368,12 @@ Array helpers provide full type safety -- `helpers.getFieldProps(index, 'name')`
368
368
  | `getFieldError(index, field)` | Get error for item field |
369
369
  | `getFieldId(index, field, optionValue?)` | Get unique ID for labels/accessibility |
370
370
 
371
+ For **fixed-length tuples** (e.g. `[number, number, number]` from `tupleOf`),
372
+ skip `arrayHelpers` entirely — `ExtractFieldPaths` emits per-index dot
373
+ paths (`position.0`, `position.1`, …) that you bind directly with
374
+ `getFieldProps('position.0')`. See
375
+ [Recipes › Tuple Fields](./RECIPES.md#tuple-fields-vec3-coordinates-fixed-length-arrays).
376
+
371
377
  ---
372
378
 
373
379
  ## What's Next
package/docs/RECIPES.md CHANGED
@@ -8,31 +8,32 @@ Patterns and techniques. Each recipe is self-contained.
8
8
 
9
9
  1. [CRUD Form with Server Errors](#crud-form-with-server-errors)
10
10
  2. [Nested Objects](#nested-objects)
11
- 3. [Dynamic Arrays](#dynamic-arrays)
12
- 4. [Checkbox and Radio Groups](#checkbox-and-radio-groups)
13
- 5. [File Uploads](#file-uploads)
14
- 6. [Auto-Submit and Debounced Search](#auto-submit-and-debounced-search)
15
- 7. [Multi-Step Wizard](#multi-step-wizard)
16
- 8. [Dependent Fields / Cross-Field Validation](#dependent-fields--cross-field-validation)
17
- 9. [Conditional Validation](#conditional-validation)
18
- 10. [Discriminated Unions](#discriminated-unions)
19
- 11. [Custom Validators](#custom-validators)
20
- 12. [Programmatic Field Updates](#programmatic-field-updates)
21
- 13. [Syncing Values to External State](#syncing-values-to-external-state)
22
- 14. [Reacting to Individual Field Changes](#reacting-to-individual-field-changes)
23
- 15. [submitCount Patterns](#submitcount-patterns)
24
- 16. [Understanding Error Priority](#understanding-error-priority)
25
- 17. [Standard Schema: Bring Your Own Validator](#standard-schema-bring-your-own-validator)
26
- 18. [Per-Field Async Validation (fieldValidators)](#per-field-async-validation-fieldvalidators)
27
- 19. [Pattern-Matching Submit Results](#pattern-matching-submit-results)
28
- 20. [Custom Field Components](#custom-field-components)
29
- 21. [Performance Patterns](#performance-patterns)
30
- 22. [UI Library Integration](#ui-library-integration)
31
- 23. [Testing Forms](#testing-forms)
32
- 24. [Form State Persistence](#form-state-persistence)
33
- 25. [Unsaved Changes Warning](#unsaved-changes-warning)
34
- 26. [Capstone: Full Registration Form (Result Pattern)](#capstone-full-registration-form-result-pattern)
35
- 27. [Capstone: Full Registration Form (React Query)](#capstone-full-registration-form-react-query)
11
+ 3. [Tuple Fields (vec3, coordinates, fixed-length arrays)](#tuple-fields-vec3-coordinates-fixed-length-arrays)
12
+ 4. [Dynamic Arrays](#dynamic-arrays)
13
+ 5. [Checkbox and Radio Groups](#checkbox-and-radio-groups)
14
+ 6. [File Uploads](#file-uploads)
15
+ 7. [Auto-Submit and Debounced Search](#auto-submit-and-debounced-search)
16
+ 8. [Multi-Step Wizard](#multi-step-wizard)
17
+ 9. [Dependent Fields / Cross-Field Validation](#dependent-fields--cross-field-validation)
18
+ 10. [Conditional Validation](#conditional-validation)
19
+ 11. [Discriminated Unions](#discriminated-unions)
20
+ 12. [Custom Validators](#custom-validators)
21
+ 13. [Programmatic Field Updates](#programmatic-field-updates)
22
+ 14. [Syncing Values to External State](#syncing-values-to-external-state)
23
+ 15. [Reacting to Individual Field Changes](#reacting-to-individual-field-changes)
24
+ 16. [submitCount Patterns](#submitcount-patterns)
25
+ 17. [Understanding Error Priority](#understanding-error-priority)
26
+ 18. [Standard Schema: Bring Your Own Validator](#standard-schema-bring-your-own-validator)
27
+ 19. [Per-Field Async Validation (fieldValidators)](#per-field-async-validation-fieldvalidators)
28
+ 20. [Pattern-Matching Submit Results](#pattern-matching-submit-results)
29
+ 21. [Custom Field Components](#custom-field-components)
30
+ 22. [Performance Patterns](#performance-patterns)
31
+ 23. [UI Library Integration](#ui-library-integration)
32
+ 24. [Testing Forms](#testing-forms)
33
+ 25. [Form State Persistence](#form-state-persistence)
34
+ 26. [Unsaved Changes Warning](#unsaved-changes-warning)
35
+ 27. [Capstone: Full Registration Form (Result Pattern)](#capstone-full-registration-form-result-pattern)
36
+ 28. [Capstone: Full Registration Form (React Query)](#capstone-full-registration-form-react-query)
36
37
 
37
38
  ---
38
39
 
@@ -182,6 +183,128 @@ Errors also use dot notation: `form.getFieldError('address.city')`, `form.getFie
182
183
 
183
184
  ---
184
185
 
186
+ ## Tuple Fields (vec3, coordinates, fixed-length arrays)
187
+
188
+ **Problem:** A field is a fixed-length tuple — three numbers for a position
189
+ vector, two for lat/long, four for a CMYK color — and each element needs its
190
+ own input with its own error message. This is *not* the dynamic-array case
191
+ (no push/remove/reorder); the shape is part of the schema.
192
+
193
+ **Solution:** Use `tupleOf(elementValidator, length)` from
194
+ `@railway-ts/pipelines/schema`. `ExtractFieldPaths<TValues>` automatically
195
+ emits per-index sub-paths in dot form (`r1.0`, `r1.1`, `r1.2`), which you
196
+ bind directly with `getFieldProps`. No `arrayHelpers` involved.
197
+
198
+ ```tsx
199
+ import { useForm, type UseFormReturn, type ExtractFieldPaths } from '@railway-ts/use-form';
200
+ import {
201
+ object,
202
+ required,
203
+ tupleOf,
204
+ parseNumber,
205
+ chain,
206
+ positive,
207
+ type InferSchemaType,
208
+ } from '@railway-ts/pipelines/schema';
209
+
210
+ const vec3 = tupleOf(chain(parseNumber(), positive('Must be positive')), 3);
211
+
212
+ const lambertSchema = object({
213
+ r1: required(vec3),
214
+ r2: required(vec3),
215
+ });
216
+
217
+ type LambertValues = InferSchemaType<typeof lambertSchema>;
218
+
219
+ function LambertForm() {
220
+ const form = useForm<LambertValues>(lambertSchema, {
221
+ initialValues: {
222
+ r1: [7000, 0, 0],
223
+ r2: [0, 7000, 0],
224
+ },
225
+ validationMode: 'blur',
226
+ });
227
+
228
+ return (
229
+ <form onSubmit={(e) => void form.handleSubmit(e)} noValidate>
230
+ <VecFieldset
231
+ label="r₁"
232
+ unit="km"
233
+ form={form}
234
+ names={['r1.0', 'r1.1', 'r1.2']}
235
+ />
236
+ <VecFieldset
237
+ label="r₂"
238
+ unit="km"
239
+ form={form}
240
+ names={['r2.0', 'r2.1', 'r2.2']}
241
+ />
242
+
243
+ <button type="submit">Solve</button>
244
+ </form>
245
+ );
246
+ }
247
+ ```
248
+
249
+ The `VecFieldset` component is a thin wrapper that renders three inputs and
250
+ surfaces the first error. Because `form.errors` is dot-keyed, you read it
251
+ directly with the same path you'd pass to `getFieldProps`:
252
+
253
+ ```tsx
254
+ type VecFieldsetProps<TValues extends Record<string, unknown>> = {
255
+ label: React.ReactNode;
256
+ unit?: React.ReactNode;
257
+ form: UseFormReturn<TValues>;
258
+ names: readonly ExtractFieldPaths<TValues>[];
259
+ };
260
+
261
+ function VecFieldset<TValues extends Record<string, unknown>>({
262
+ label,
263
+ unit,
264
+ form,
265
+ names,
266
+ }: VecFieldsetProps<TValues>) {
267
+ const errors = names.map((n) => (form.touched[n] ? form.errors[n] : undefined));
268
+ const firstError = errors.find((e): e is string => Boolean(e));
269
+
270
+ return (
271
+ <fieldset>
272
+ <legend>
273
+ {label}
274
+ {unit && <span> ({unit})</span>}
275
+ </legend>
276
+ <div style={{ display: 'flex', gap: '0.5rem' }}>
277
+ {names.map((name, i) => (
278
+ <input
279
+ key={name}
280
+ type="number"
281
+ step="any"
282
+ aria-invalid={Boolean(errors[i])}
283
+ {...form.getFieldProps(name)}
284
+ />
285
+ ))}
286
+ </div>
287
+ {firstError && <span role="alert">{firstError}</span>}
288
+ </fieldset>
289
+ );
290
+ }
291
+ ```
292
+
293
+ **Key points:**
294
+
295
+ - `form.errors['r1.0']` is the canonical key. Pre-0.1.31 builds keyed errors
296
+ in bracket form (`r1[0]`); on those versions you'd have to translate the
297
+ path before reading. Upgrade if you're on an older release.
298
+ - `ExtractFieldPaths<LambertValues>` includes `'r1' | 'r1.0' | 'r1.1' |
299
+ 'r1.2' | 'r2' | …`, so the `names` array is type-checked against the
300
+ schema. Renaming a tuple field or changing its arity surfaces as a type
301
+ error at the call site.
302
+ - For dynamic-length arrays (`array(...)`, not `tupleOf`), use
303
+ [`arrayHelpers`](#dynamic-arrays) instead — `ExtractFieldPaths` treats
304
+ variable-length arrays as terminal and won't generate per-index paths.
305
+
306
+ ---
307
+
185
308
  ## Dynamic Arrays
186
309
 
187
310
  **Problem:** You need a list that users can add to, remove from, and reorder -- like contacts, line items, or todo lists.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@railway-ts/use-form",
3
- "version": "0.1.30",
3
+ "version": "0.1.32",
4
4
  "description": "React form hook that works with @railway-ts/pipelines to manage form state, validation, and submission.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",