@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.mjs CHANGED
@@ -1,1194 +1,2322 @@
1
- import { useMemo, useCallback, useReducer, useRef, useEffect } from 'react';
2
- import { isErr, err, match, ok } from '@railway-ts/pipelines/result';
3
- import { formatErrors, validate } from '@railway-ts/pipelines/schema';
4
-
5
- // src/useForm.ts
6
-
1
+ import { err, isErr, match, ok } from "@railway-ts/pipelines/result";
2
+ import { formatErrors, validate } from "@railway-ts/pipelines/schema";
3
+ import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
4
+ // src/arrayHelpersFactory.ts
5
+ /**
6
+ * Factory function that creates an ArrayHelpers object for managing array fields in forms.
7
+ * Provides type-safe methods to add, remove, update, and reorder array items, as well as
8
+ * bind native HTML elements to fields within array items.
9
+ *
10
+ * This is typically called internally by the useForm hook's arrayHelpers() method
11
+ * and not used directly by consumers.
12
+ *
13
+ * @template TItem - The type of items stored in the array
14
+ * @template TFieldPaths - Union of valid field paths for the item type
15
+ *
16
+ * @param field - The path to the array field in the form
17
+ * @param arrayValue - The current array values
18
+ * @param setFieldValue - Function to update a field value in the form
19
+ * @param getFieldProps - Function to get props for native text inputs
20
+ * @param getSelectFieldProps - Function to get props for native select elements
21
+ * @param getSliderProps - Function to get props for native range inputs
22
+ * @param getCheckboxProps - Function to get props for native checkboxes
23
+ * @param getSwitchProps - Function to get props for native switches
24
+ * @param getFileFieldProps - Function to get props for native file inputs
25
+ * @param getRadioGroupOptionProps - Function to get props for radio group options
26
+ * @returns An ArrayHelpers object with methods for array manipulation and field binding
27
+ *
28
+ * @example
29
+ * // Used internally by useForm
30
+ * const contactsHelpers = form.arrayHelpers("contacts");
31
+ * contactsHelpers.push({ name: "", email: "" });
32
+ * contactsHelpers.remove(0);
33
+ *
34
+ * @example
35
+ * // Accessing nested fields in array items
36
+ * const helpers = form.arrayHelpers("addresses");
37
+ * return helpers.values.map((_, index) => (
38
+ * <input {...helpers.getFieldProps(index, "street")} />
39
+ * ));
40
+ */
41
+ const createArrayHelpers = (field, arrayValue, setFieldValue, getFieldProps, getSelectFieldProps, getSliderProps, getCheckboxProps, getSwitchProps, getFileFieldProps, getRadioGroupOptionProps, getFieldError, getFieldId) => {
42
+ return {
43
+ /**
44
+ * The current array of values for this field.
45
+ * Use this to iterate over items when rendering the form.
46
+ *
47
+ * @example
48
+ * // Render array items
49
+ * helpers.values.map((contact, index) => (
50
+ * <div key={index}>
51
+ * <input {...helpers.getFieldProps(index, "name")} />
52
+ * </div>
53
+ * ))
54
+ */
55
+ values: arrayValue,
56
+ /**
57
+ * Adds a new item to the end of the array.
58
+ * The form state is updated immutably and all subscribed components re-render.
59
+ *
60
+ * @param value - The item to add to the array
61
+ *
62
+ * @example
63
+ * // Add a new contact
64
+ * const helpers = form.arrayHelpers("contacts");
65
+ * helpers.push({ name: "", email: "", phone: "" });
66
+ */
67
+ push: (value) => {
68
+ setFieldValue(field, [...arrayValue, value]);
69
+ },
70
+ /**
71
+ * Removes an item at the specified index from the array.
72
+ * If the index is out of bounds, no action is taken.
73
+ * The form state is updated immutably.
74
+ *
75
+ * @param index - The zero-based index of the item to remove
76
+ *
77
+ * @example
78
+ * // Remove the second contact
79
+ * const helpers = form.arrayHelpers("contacts");
80
+ * helpers.remove(1);
81
+ */
82
+ remove: (index) => {
83
+ if (index < 0 || index >= arrayValue.length) return;
84
+ const newArray = [...arrayValue];
85
+ newArray.splice(index, 1);
86
+ setFieldValue(field, newArray);
87
+ },
88
+ /**
89
+ * Inserts an item at the specified index in the array.
90
+ * Items at and after the index are shifted to the right.
91
+ * If the index is out of bounds, it's clamped to valid range [0, length].
92
+ *
93
+ * @param index - The zero-based insertion position
94
+ * @param value - The item to insert
95
+ *
96
+ * @example
97
+ * // Insert a contact at the beginning
98
+ * const helpers = form.arrayHelpers("contacts");
99
+ * helpers.insert(0, { name: "New Contact", email: "", phone: "" });
100
+ */
101
+ insert: (index, value) => {
102
+ const clamped = Math.max(0, Math.min(index, arrayValue.length));
103
+ const newArray = [...arrayValue];
104
+ newArray.splice(clamped, 0, value);
105
+ setFieldValue(field, newArray);
106
+ },
107
+ /**
108
+ * Swaps the positions of two items in the array.
109
+ * If either index is out of bounds or they are equal, no action is taken.
110
+ * Useful for drag-and-drop reordering interfaces.
111
+ *
112
+ * @param indexA - The zero-based index of the first item
113
+ * @param indexB - The zero-based index of the second item
114
+ *
115
+ * @example
116
+ * // Swap first and second contacts
117
+ * const helpers = form.arrayHelpers("contacts");
118
+ * helpers.swap(0, 1);
119
+ *
120
+ * @example
121
+ * // Move item up in list
122
+ * const moveUp = (index: number) => {
123
+ * if (index > 0) helpers.swap(index, index - 1);
124
+ * };
125
+ */
126
+ swap: (indexA, indexB) => {
127
+ if (indexA === indexB || indexA < 0 || indexB < 0 || indexA >= arrayValue.length || indexB >= arrayValue.length) return;
128
+ const newArray = [...arrayValue];
129
+ const a = newArray[indexA];
130
+ const b = newArray[indexB];
131
+ if (a === void 0 || b === void 0) return;
132
+ newArray[indexA] = b;
133
+ newArray[indexB] = a;
134
+ setFieldValue(field, newArray);
135
+ },
136
+ /**
137
+ * Replaces an entire item at the specified index with a new value.
138
+ * If the index is out of bounds, no action is taken.
139
+ *
140
+ * @param index - The zero-based index of the item to replace
141
+ * @param value - The new item value
142
+ *
143
+ * @example
144
+ * // Replace a contact entirely
145
+ * const helpers = form.arrayHelpers("contacts");
146
+ * helpers.replace(0, { name: "John Doe", email: "john@example.com", phone: "555-0100" });
147
+ */
148
+ replace: (index, value) => {
149
+ if (index < 0 || index >= arrayValue.length) return;
150
+ const newArray = [...arrayValue];
151
+ newArray[index] = value;
152
+ setFieldValue(field, newArray);
153
+ },
154
+ /**
155
+ * Gets props for a native text input bound to a field within an array item.
156
+ * Provides type-safe field path autocomplete for nested fields.
157
+ * Works with: <input type="text">, <input type="email">, <textarea>, etc.
158
+ *
159
+ * @param index - The zero-based index of the array item
160
+ * @param subField - The field path within the array item (type-safe and autocompleted)
161
+ * @returns Props object to spread onto a native input element
162
+ *
163
+ * @example
164
+ * // Text input for contact name
165
+ * helpers.values.map((_, index) => (
166
+ * <input type="text" {...helpers.getFieldProps(index, "name")} />
167
+ * ))
168
+ */
169
+ getFieldProps: (index, subField) => {
170
+ return getFieldProps(`${field}.${index}.${subField}`);
171
+ },
172
+ /**
173
+ * Gets props for a native select element bound to a field within an array item.
174
+ * Provides type-safe field path autocomplete for nested fields.
175
+ * Works with: <select>
176
+ *
177
+ * @param index - The zero-based index of the array item
178
+ * @param subField - The field path within the array item (type-safe and autocompleted)
179
+ * @returns Props object to spread onto a native select element
180
+ *
181
+ * @example
182
+ * // Select for contact type
183
+ * <select {...helpers.getSelectFieldProps(index, "type")}>
184
+ * <option value="work">Work</option>
185
+ * <option value="personal">Personal</option>
186
+ * </select>
187
+ */
188
+ getSelectFieldProps: (index, subField) => {
189
+ return getSelectFieldProps(`${field}.${index}.${subField}`);
190
+ },
191
+ /**
192
+ * Gets props for a native range input bound to a field within an array item.
193
+ * Provides type-safe field path autocomplete for nested fields.
194
+ * Works with: <input type="range">
195
+ *
196
+ * @param index - The zero-based index of the array item
197
+ * @param subField - The field path within the array item (type-safe and autocompleted)
198
+ * @returns Props object to spread onto a native range input element
199
+ *
200
+ * @example
201
+ * // Range slider for priority
202
+ * <input type="range" min={0} max={10} {...helpers.getSliderProps(index, "priority")} />
203
+ */
204
+ getSliderProps: (index, subField) => {
205
+ return getSliderProps(`${field}.${index}.${subField}`);
206
+ },
207
+ /**
208
+ * Gets props for a native checkbox bound to a field within an array item.
209
+ * Provides type-safe field path autocomplete for nested fields.
210
+ * Works with: <input type="checkbox">
211
+ *
212
+ * @param index - The zero-based index of the array item
213
+ * @param subField - The field path within the array item (type-safe and autocompleted)
214
+ * @returns Props object to spread onto a native checkbox input
215
+ *
216
+ * @example
217
+ * // Checkbox for marking contact as favorite
218
+ * <input type="checkbox" {...helpers.getCheckboxProps(index, "isFavorite")} />
219
+ */
220
+ getCheckboxProps: (index, subField) => {
221
+ return getCheckboxProps(`${field}.${index}.${subField}`);
222
+ },
223
+ /**
224
+ * Gets props for a native switch (checkbox styled as switch) bound to a field within an array item.
225
+ * Provides type-safe field path autocomplete for nested fields.
226
+ * Works with: <input type="checkbox"> (styled as switch via CSS)
227
+ *
228
+ * @param index - The zero-based index of the array item
229
+ * @param subField - The field path within the array item (type-safe and autocompleted)
230
+ * @returns Props object to spread onto a native checkbox input
231
+ *
232
+ * @example
233
+ * // Switch for enabling/disabling a feature
234
+ * <label className="switch">
235
+ * <input type="checkbox" {...helpers.getSwitchProps(index, "enabled")} />
236
+ * <span className="slider"></span>
237
+ * </label>
238
+ */
239
+ getSwitchProps: (index, subField) => {
240
+ return getSwitchProps(`${field}.${index}.${subField}`);
241
+ },
242
+ /**
243
+ * Gets props for a native file input bound to a field within an array item.
244
+ * Provides type-safe field path autocomplete for nested fields.
245
+ * Works with: <input type="file">
246
+ *
247
+ * @param index - The zero-based index of the array item
248
+ * @param subField - The field path within the array item (type-safe and autocompleted)
249
+ * @returns Props object to spread onto a native file input
250
+ *
251
+ * @example
252
+ * // File input for contact avatar
253
+ * <input type="file" accept="image/*" {...helpers.getFileFieldProps(index, "avatar")} />
254
+ */
255
+ getFileFieldProps: (index, subField) => {
256
+ return getFileFieldProps(`${field}.${index}.${subField}`);
257
+ },
258
+ /**
259
+ * Gets props for a radio group option bound to a field within an array item.
260
+ * Provides type-safe field path autocomplete for nested fields.
261
+ * Works with: multiple <input type="radio"> elements sharing the same name
262
+ *
263
+ * @param index - The zero-based index of the array item
264
+ * @param subField - The field path within the array item (type-safe and autocompleted)
265
+ * @param optionValue - The value this radio option represents
266
+ * @returns Props object to spread onto a native radio input
267
+ *
268
+ * @example
269
+ * // Radio group for contact method preference
270
+ * <label>
271
+ * <input type="radio" {...helpers.getRadioGroupOptionProps(index, "preferredMethod", "email")} />
272
+ * Email
273
+ * </label>
274
+ * <label>
275
+ * <input type="radio" {...helpers.getRadioGroupOptionProps(index, "preferredMethod", "phone")} />
276
+ * Phone
277
+ * </label>
278
+ */
279
+ getRadioGroupOptionProps: (index, subField, optionValue) => {
280
+ return getRadioGroupOptionProps(`${field}.${index}.${subField}`, optionValue);
281
+ },
282
+ getFieldError: (index, subField) => getFieldError(`${field}.${index}.${subField}`),
283
+ getFieldId: (index, subField, optionValue) => getFieldId(`${field}.${index}.${subField}`, optionValue)
284
+ };
285
+ };
7
286
  // src/utils.ts
8
- var normalizePath = (path) => path.replace(/\[(\d+)\]/g, ".$1");
9
- var normalizePathKeys = (map) => {
10
- const out = {};
11
- for (const k of Object.keys(map)) {
12
- out[normalizePath(k)] = map[k];
13
- }
14
- return out;
287
+ /**
288
+ * Canonical (dot) form for a field path. Numeric bracket segments are
289
+ * rewritten as dot segments: "users[0].name" → "users.0.name".
290
+ *
291
+ * Path-keyed maps stored in form state (touched, clientErrors, fieldErrors,
292
+ * serverErrors) are keyed by this canonical form, so lookups using either
293
+ * "r1.0" or "r1[0]" resolve to the same entry once normalized.
294
+ */
295
+ const normalizePath = (path) => path.replace(/\[(\d+)\]/g, ".$1");
296
+ /**
297
+ * Returns a new map whose keys have been rewritten to canonical dot form.
298
+ * Used at boundaries where bracket-keyed errors enter form state (e.g. the
299
+ * output of `formatErrors` from `@railway-ts/pipelines/schema`).
300
+ */
301
+ const normalizePathKeys = (map) => {
302
+ const out = {};
303
+ for (const k of Object.keys(map)) out[normalizePath(k)] = map[k];
304
+ return out;
15
305
  };
16
- var getValueByPath = (obj, path) => {
17
- if (!path) return obj;
18
- const parts = normalizePath(path).split(".").filter(Boolean);
19
- let current = obj;
20
- for (const part of parts) {
21
- if (current == null) return void 0;
22
- current = current[part];
23
- }
24
- return current;
306
+ /**
307
+ * Retrieves a value from a nested object using a path string.
308
+ * Supports both dot notation for object properties and bracket notation for array indices.
309
+ * Returns undefined if any part of the path doesn't exist.
310
+ *
311
+ * Internally normalizes bracket notation to dot notation (e.g., "arr[0]" → "arr.0")
312
+ * and traverses the object tree to find the value.
313
+ *
314
+ * @template TObj - The object type to extract from
315
+ * @template TValue - The expected return value type
316
+ *
317
+ * @param obj - The object to extract value from
318
+ * @param path - Path to the value using dot or bracket notation
319
+ * @returns The value at the path, or undefined if not found
320
+ *
321
+ * @example
322
+ * // Simple dot notation
323
+ * const user = { name: "John", age: 30 };
324
+ * getValueByPath(user, "name"); // "John"
325
+ *
326
+ * @example
327
+ * // Nested dot notation
328
+ * const user = { address: { city: "NYC", zip: "10001" } };
329
+ * getValueByPath(user, "address.city"); // "NYC"
330
+ *
331
+ * @example
332
+ * // Bracket notation for arrays
333
+ * const user = { contacts: ["email@example.com", "phone@example.com"] };
334
+ * getValueByPath(user, "contacts[0]"); // "email@example.com"
335
+ *
336
+ * @example
337
+ * // Combined notation for deeply nested structures
338
+ * const user = { teams: [{ name: "Engineering", members: [{ name: "Alice" }] }] };
339
+ * getValueByPath(user, "teams[0].members[0].name"); // "Alice"
340
+ *
341
+ * @example
342
+ * // Missing path returns undefined
343
+ * const user = { name: "John" };
344
+ * getValueByPath(user, "address.city"); // undefined
345
+ */
346
+ const getValueByPath = (obj, path) => {
347
+ if (!path) return obj;
348
+ const parts = normalizePath(path).split(".").filter(Boolean);
349
+ let current = obj;
350
+ for (const part of parts) {
351
+ if (current == null) return void 0;
352
+ current = current[part];
353
+ }
354
+ return current;
25
355
  };
26
- var setValueByPath = (obj, path, value) => {
27
- if (!path) return value;
28
- const parts = normalizePath(path).split(".").filter(Boolean);
29
- const result = Array.isArray(obj) ? [...obj] : { ...obj };
30
- let currNew = Array.isArray(result) ? result : result;
31
- let currOld = obj;
32
- for (let i = 0; i < parts.length; i++) {
33
- const keyStr = parts[i];
34
- const isIndex = /^\d+$/.test(keyStr);
35
- const key = isIndex ? Number(keyStr) : keyStr;
36
- if (i === parts.length - 1) {
37
- if (Array.isArray(currNew) && typeof key === "number") {
38
- currNew[key] = value;
39
- } else if (!Array.isArray(currNew) && typeof key === "string") {
40
- currNew[key] = value;
41
- }
42
- break;
43
- }
44
- let nextOld = void 0;
45
- if (currOld != null && typeof currOld === "object") {
46
- if (Array.isArray(currOld) && typeof key === "number") {
47
- nextOld = currOld[key];
48
- } else if (!Array.isArray(currOld) && typeof key === "string") {
49
- nextOld = currOld[key];
50
- }
51
- }
52
- let nextNew;
53
- if (nextOld == null) {
54
- const nextIsIndex = /^\d+$/.test(parts[i + 1] ?? "");
55
- nextNew = nextIsIndex ? [] : {};
56
- } else {
57
- nextNew = Array.isArray(nextOld) ? [...nextOld] : { ...nextOld };
58
- }
59
- if (Array.isArray(currNew) && typeof key === "number") {
60
- currNew[key] = nextNew;
61
- } else if (!Array.isArray(currNew) && typeof key === "string") {
62
- currNew[key] = nextNew;
63
- }
64
- currNew = nextNew;
65
- currOld = nextOld ?? (Array.isArray(nextNew) ? [] : {});
66
- }
67
- return result;
356
+ /**
357
+ * Sets a value in a nested object using a path string, returning a new object.
358
+ * Creates intermediate objects and arrays as needed without mutating the original.
359
+ * All updates are performed immutably using spreading.
360
+ *
361
+ * Internally normalizes bracket notation to dot notation and determines whether
362
+ * to create objects or arrays based on whether the next path segment is numeric.
363
+ *
364
+ * @template TObj - The object type to update
365
+ * @template TValue - The value type to set
366
+ *
367
+ * @param obj - The source object to set value in (not mutated)
368
+ * @param path - Path to the value using dot or bracket notation
369
+ * @param value - The value to set at the path
370
+ * @returns A new object with the updated value
371
+ *
372
+ * @example
373
+ * // Update existing nested property
374
+ * const user = { name: "John", address: { city: "NYC" } };
375
+ * const updated = setValueByPath(user, "address.city", "San Francisco");
376
+ * // updated = { name: "John", address: { city: "San Francisco" } }
377
+ * // user is unchanged (immutable)
378
+ *
379
+ * @example
380
+ * // Create missing intermediate objects
381
+ * const user = { name: "John" };
382
+ * const updated = setValueByPath(user, "address.city", "NYC");
383
+ * // updated = { name: "John", address: { city: "NYC" } }
384
+ *
385
+ * @example
386
+ * // Update array element
387
+ * const user = { contacts: ["old@example.com"] };
388
+ * const updated = setValueByPath(user, "contacts[0]", "new@example.com");
389
+ * // updated = { contacts: ["new@example.com"] }
390
+ *
391
+ * @example
392
+ * // Create missing arrays and nested properties
393
+ * const user = {};
394
+ * const updated = setValueByPath(user, "teams[0].name", "Engineering");
395
+ * // updated = { teams: [{ name: "Engineering" }] }
396
+ *
397
+ * @example
398
+ * // Deep nested update
399
+ * const form = { users: [{ address: { city: "NYC" } }] };
400
+ * const updated = setValueByPath(form, "users[0].address.zip", "10001");
401
+ * // updated = { users: [{ address: { city: "NYC", zip: "10001" } }] }
402
+ */
403
+ const setValueByPath = (obj, path, value) => {
404
+ if (!path) return value;
405
+ const parts = normalizePath(path).split(".").filter(Boolean);
406
+ const result = Array.isArray(obj) ? [...obj] : { ...obj };
407
+ let currNew = Array.isArray(result) ? result : result;
408
+ let currOld = obj;
409
+ for (let i = 0; i < parts.length; i++) {
410
+ const keyStr = parts[i];
411
+ const key = /^\d+$/.test(keyStr) ? Number(keyStr) : keyStr;
412
+ if (i === parts.length - 1) {
413
+ if (Array.isArray(currNew) && typeof key === "number") currNew[key] = value;
414
+ else if (!Array.isArray(currNew) && typeof key === "string") currNew[key] = value;
415
+ break;
416
+ }
417
+ let nextOld = void 0;
418
+ if (currOld != null && typeof currOld === "object") {
419
+ if (Array.isArray(currOld) && typeof key === "number") nextOld = currOld[key];
420
+ else if (!Array.isArray(currOld) && typeof key === "string") nextOld = currOld[key];
421
+ }
422
+ let nextNew;
423
+ if (nextOld == null) nextNew = /^\d+$/.test(parts[i + 1] ?? "") ? [] : {};
424
+ else nextNew = Array.isArray(nextOld) ? [...nextOld] : { ...nextOld };
425
+ if (Array.isArray(currNew) && typeof key === "number") currNew[key] = nextNew;
426
+ else if (!Array.isArray(currNew) && typeof key === "string") currNew[key] = nextNew;
427
+ currNew = nextNew;
428
+ currOld = nextOld ?? (Array.isArray(nextNew) ? [] : {});
429
+ }
430
+ return result;
68
431
  };
69
- var isPathAffected = (path, changePath) => {
70
- if (path === changePath) return true;
71
- const normalizedPath = normalizePath(path);
72
- const normalizedChangePath = normalizePath(changePath);
73
- return normalizedPath === normalizedChangePath || normalizedPath.startsWith(`${normalizedChangePath}.`);
432
+ /**
433
+ * Checks if a field path is affected by changes to another path.
434
+ * Used internally for determining which errors to clear when a field value changes.
435
+ *
436
+ * A path is considered affected if:
437
+ * 1. It exactly matches the change path
438
+ * 2. The change path is a parent of the path (e.g., "address" affects "address.city")
439
+ *
440
+ * Paths are normalized before comparison so bracket notation is handled correctly.
441
+ *
442
+ * @param path - The path to check if affected (e.g., error path)
443
+ * @param changePath - The path that was changed (e.g., field that was updated)
444
+ * @returns True if the path is affected by the change, false otherwise
445
+ *
446
+ * @example
447
+ * // Exact match
448
+ * isPathAffected("email", "email"); // true
449
+ *
450
+ * @example
451
+ * // Parent affects child
452
+ * isPathAffected("address.city", "address"); // true
453
+ * isPathAffected("address.city", "address.city"); // true
454
+ *
455
+ * @example
456
+ * // Child does not affect parent
457
+ * isPathAffected("address", "address.city"); // false
458
+ *
459
+ * @example
460
+ * // Unrelated paths
461
+ * isPathAffected("address.city", "name"); // false
462
+ *
463
+ * @example
464
+ * // Array notation (normalized internally)
465
+ * isPathAffected("contacts[0].email", "contacts"); // true
466
+ * isPathAffected("contacts[0].email", "contacts[0]"); // true
467
+ * isPathAffected("contacts[0].email", "contacts[1]"); // false
468
+ *
469
+ * @example
470
+ * // Practical use case: clearing server errors
471
+ * const serverErrors = {
472
+ * "address.city": "City is required",
473
+ * "address.zip": "Invalid ZIP"
474
+ * };
475
+ * // When user updates "address", both errors should be cleared
476
+ * Object.keys(serverErrors).filter(path => isPathAffected(path, "address"));
477
+ * // Returns ["address.city", "address.zip"]
478
+ */
479
+ const isPathAffected = (path, changePath) => {
480
+ if (path === changePath) return true;
481
+ const normalizedPath = normalizePath(path);
482
+ const normalizedChangePath = normalizePath(changePath);
483
+ return normalizedPath === normalizedChangePath || normalizedPath.startsWith(`${normalizedChangePath}.`);
74
484
  };
75
- var collectFieldPaths = (obj, prefix = "") => {
76
- const paths = [];
77
- const isLeaf = (v) => v == null || typeof v !== "object" || v instanceof Date || v instanceof RegExp;
78
- const visit = (value, path) => {
79
- if (path) paths.push(path);
80
- if (isLeaf(value)) return;
81
- if (Array.isArray(value)) {
82
- value.forEach((item, i) => visit(item, path ? `${path}.${i}` : `${i}`));
83
- return;
84
- }
85
- const entries = Object.entries(value);
86
- for (const [k, v] of entries) {
87
- const childPath = path ? `${path}.${k}` : k;
88
- visit(v, childPath);
89
- }
90
- };
91
- visit(obj, prefix);
92
- return paths;
485
+ /**
486
+ * Recursively collects all field paths from a nested object structure.
487
+ * Traverses the entire object tree and generates path strings for every field,
488
+ * including intermediate parent paths, nested objects, and array elements.
489
+ *
490
+ * Useful for operations that need to touch all fields in a form, such as:
491
+ * - Marking all fields as touched on form submission
492
+ * - Collecting all error paths for validation
493
+ * - Iterating over all form values
494
+ *
495
+ * Leaf values (primitives, Date, RegExp, null, undefined) are treated as terminal nodes.
496
+ * All segments are joined with dot notation; numeric array indices appear as their
497
+ * canonical dot form (e.g. "contacts.0.email"), matching the rest of form state.
498
+ *
499
+ * @param obj - The object to collect paths from (typically form values)
500
+ * @param prefix - Internal parameter for recursion, starting path prefix (default: "")
501
+ * @returns Array of all field paths found in the object
502
+ *
503
+ * @example
504
+ * // Simple object
505
+ * const user = { name: "John", age: 30 };
506
+ * collectFieldPaths(user);
507
+ * // Returns: ["name", "age"]
508
+ *
509
+ * @example
510
+ * // Nested object
511
+ * const user = { name: "John", address: { city: "NYC", zip: "10001" } };
512
+ * collectFieldPaths(user);
513
+ * // Returns: ["name", "address", "address.city", "address.zip"]
514
+ * // Note: "address" is included as a parent path
515
+ *
516
+ * @example
517
+ * // Arrays with objects
518
+ * const form = { contacts: [{ email: "a@example.com" }, { email: "b@example.com" }] };
519
+ * collectFieldPaths(form);
520
+ * // Returns: ["contacts", "contacts.0", "contacts.0.email", "contacts.1", "contacts.1.email"]
521
+ *
522
+ * @example
523
+ * // Mixed nesting
524
+ * const form = {
525
+ * user: { name: "John" },
526
+ * tags: ["react", "typescript"]
527
+ * };
528
+ * collectFieldPaths(form);
529
+ * // Returns: ["user", "user.name", "tags", "tags.0", "tags.1"]
530
+ *
531
+ * @example
532
+ * // Practical use: marking all fields as touched on submit
533
+ * const handleSubmit = () => {
534
+ * const allPaths = collectFieldPaths(form.values);
535
+ * allPaths.forEach(path => form.setFieldTouched(path, true));
536
+ * // Now all validation errors will be visible
537
+ * };
538
+ *
539
+ * @example
540
+ * // Leaf values (Date, null) are treated as terminals
541
+ * const form = { createdAt: new Date(), deletedAt: null };
542
+ * collectFieldPaths(form);
543
+ * // Returns: ["createdAt", "deletedAt"]
544
+ * // Does not try to traverse into Date or null
545
+ */
546
+ const collectFieldPaths = (obj, prefix = "") => {
547
+ const paths = [];
548
+ const isLeaf = (v) => v == null || typeof v !== "object" || v instanceof Date || v instanceof RegExp;
549
+ const visit = (value, path) => {
550
+ if (path) paths.push(path);
551
+ if (isLeaf(value)) return;
552
+ if (Array.isArray(value)) {
553
+ value.forEach((item, i) => visit(item, path ? `${path}.${i}` : `${i}`));
554
+ return;
555
+ }
556
+ const entries = Object.entries(value);
557
+ for (const [k, v] of entries) {
558
+ const childPath = path ? `${path}.${k}` : k;
559
+ visit(v, childPath);
560
+ }
561
+ };
562
+ visit(obj, prefix);
563
+ return paths;
93
564
  };
94
- var deepMerge = (target, source) => {
95
- const result = { ...target };
96
- for (const key of Object.keys(source)) {
97
- const srcVal = source[key];
98
- const tgtVal = target[key];
99
- if (srcVal != null && typeof srcVal === "object" && !Array.isArray(srcVal) && !(srcVal instanceof Date) && !(srcVal instanceof RegExp) && tgtVal != null && typeof tgtVal === "object" && !Array.isArray(tgtVal) && !(tgtVal instanceof Date) && !(tgtVal instanceof RegExp)) {
100
- result[key] = deepMerge(
101
- tgtVal,
102
- srcVal
103
- );
104
- } else {
105
- result[key] = srcVal;
106
- }
107
- }
108
- return result;
565
+ const deepMerge = (target, source) => {
566
+ const result = { ...target };
567
+ for (const key of Object.keys(source)) {
568
+ const srcVal = source[key];
569
+ const tgtVal = target[key];
570
+ if (srcVal != null && typeof srcVal === "object" && !Array.isArray(srcVal) && !(srcVal instanceof Date) && !(srcVal instanceof RegExp) && tgtVal != null && typeof tgtVal === "object" && !Array.isArray(tgtVal) && !(tgtVal instanceof Date) && !(tgtVal instanceof RegExp)) result[key] = deepMerge(tgtVal, srcVal);
571
+ else result[key] = srcVal;
572
+ }
573
+ return result;
109
574
  };
110
- var deepEqual = (a, b) => {
111
- if (Object.is(a, b)) return true;
112
- if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
113
- if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
114
- if (a == null || b == null) return false;
115
- if (typeof a !== "object" || typeof b !== "object") return false;
116
- if (Array.isArray(a)) {
117
- if (!Array.isArray(b) || a.length !== b.length) return false;
118
- return a.every((item, i) => deepEqual(item, b[i]));
119
- }
120
- const keysA = Object.keys(a);
121
- const keysB = Object.keys(b);
122
- if (keysA.length !== keysB.length) return false;
123
- return keysA.every(
124
- (key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key])
125
- );
575
+ const deepEqual = (a, b) => {
576
+ if (Object.is(a, b)) return true;
577
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
578
+ if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
579
+ if (a == null || b == null) return false;
580
+ if (typeof a !== "object" || typeof b !== "object") return false;
581
+ if (Array.isArray(a)) {
582
+ if (!Array.isArray(b) || a.length !== b.length) return false;
583
+ return a.every((item, i) => deepEqual(item, b[i]));
584
+ }
585
+ const keysA = Object.keys(a);
586
+ const keysB = Object.keys(b);
587
+ if (keysA.length !== keysB.length) return false;
588
+ return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));
589
+ };
590
+ // src/fieldPropsFactory.ts
591
+ /**
592
+ * Creates props for a native text input element bound to a form field.
593
+ * Automatically handles value normalization, change events, and blur tracking.
594
+ * Works with: <input type="text">, <input type="email">, <input type="date">, <textarea>, etc.
595
+ *
596
+ * The returned props include id, name, value, onChange, and onBlur handlers that
597
+ * are pre-configured to work with the form state management system.
598
+ *
599
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
600
+ * @param formValues - Current form values object
601
+ * @param handleChange - Function to update the field value in form state
602
+ * @param handleBlur - Function to mark the field as touched in form state
603
+ * @returns Props object to spread onto native text input elements
604
+ *
605
+ * @example
606
+ * // Native text input with placeholder
607
+ * <input type="text" {...form.getFieldProps("username")} placeholder="Username" />
608
+ *
609
+ * @example
610
+ * // Native email input
611
+ * <input type="email" {...form.getFieldProps("email")} />
612
+ *
613
+ * @example
614
+ * // Native textarea
615
+ * <textarea {...form.getFieldProps("bio")} rows={4} />
616
+ *
617
+ * @example
618
+ * // Nested field path
619
+ * <input type="text" {...form.getFieldProps("address.city")} />
620
+ *
621
+ * @example
622
+ * // Date input (values are auto-converted to/from ISO format)
623
+ * <input type="date" {...form.getFieldProps("birthDate")} />
624
+ */
625
+ const createNativeFieldProps = (field, formValues, handleChange, handleBlur) => {
626
+ const raw = getValueByPath(formValues, field);
627
+ return {
628
+ id: field,
629
+ name: field,
630
+ value: raw == null ? "" : typeof raw === "string" || typeof raw === "number" ? raw : raw instanceof Date ? isNaN(raw.getTime()) ? "" : raw.toISOString().split("T")[0] : JSON.stringify(raw),
631
+ onChange: (e) => {
632
+ handleChange(field, e.target.value);
633
+ },
634
+ onBlur: () => handleBlur(field, true)
635
+ };
636
+ };
637
+ /**
638
+ * Creates props for a native select element bound to a form field.
639
+ * Automatically handles value normalization, change events, and blur tracking.
640
+ * Works with: <select> (single selection only, not multiple)
641
+ *
642
+ * The returned props include id, name, value, onChange, and onBlur handlers that
643
+ * are pre-configured to work with the form state management system.
644
+ *
645
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
646
+ * @param formValues - Current form values object
647
+ * @param handleChange - Function to update the field value in form state
648
+ * @param handleBlur - Function to mark the field as touched in form state
649
+ * @returns Props object to spread onto native select elements
650
+ *
651
+ * @example
652
+ * // Native select with default option
653
+ * <select {...form.getSelectFieldProps("role")}>
654
+ * <option value="">Select a role…</option>
655
+ * <option value="user">User</option>
656
+ * <option value="admin">Admin</option>
657
+ * </select>
658
+ *
659
+ * @example
660
+ * // Select with nested field path
661
+ * <select {...form.getSelectFieldProps("address.country")}>
662
+ * <option value="US">United States</option>
663
+ * <option value="CA">Canada</option>
664
+ * <option value="UK">United Kingdom</option>
665
+ * </select>
666
+ *
667
+ * @example
668
+ * // Select with dynamic options
669
+ * <select {...form.getSelectFieldProps("category")}>
670
+ * {categories.map(cat => (
671
+ * <option key={cat.id} value={cat.id}>{cat.name}</option>
672
+ * ))}
673
+ * </select>
674
+ */
675
+ const createNativeSelectFieldProps = (field, formValues, handleChange, handleBlur) => {
676
+ const raw = getValueByPath(formValues, field);
677
+ return {
678
+ id: field,
679
+ name: field,
680
+ value: raw == null ? "" : typeof raw === "string" || typeof raw === "number" ? raw : JSON.stringify(raw),
681
+ onChange: (e) => handleChange(field, e.target.value),
682
+ onBlur: () => handleBlur(field, true)
683
+ };
684
+ };
685
+ /**
686
+ * Creates props for a native checkbox input bound to a boolean form field.
687
+ * The checkbox is checked when the field value is truthy, unchecked when falsy.
688
+ * Automatically handles checked state, change events, and blur tracking.
689
+ * Works with: <input type="checkbox">
690
+ *
691
+ * Note: For checkbox groups (multiple checkboxes bound to an array), use
692
+ * getCheckboxGroupOptionProps instead.
693
+ *
694
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
695
+ * @param formValues - Current form values object
696
+ * @param handleChange - Function to update the field value (receives boolean) in form state
697
+ * @param handleBlur - Function to mark the field as touched in form state
698
+ * @returns Props object to spread onto native checkbox inputs
699
+ *
700
+ * @example
701
+ * // Simple checkbox for boolean field
702
+ * <label>
703
+ * <input type="checkbox" {...form.getCheckboxProps("acceptTerms")} />
704
+ * I accept the terms and conditions
705
+ * </label>
706
+ *
707
+ * @example
708
+ * // Nested field path
709
+ * <label>
710
+ * <input type="checkbox" {...form.getCheckboxProps("preferences.newsletter")} />
711
+ * Subscribe to newsletter
712
+ * </label>
713
+ *
714
+ * @example
715
+ * // With accessible labeling
716
+ * <div>
717
+ * <input type="checkbox" {...form.getCheckboxProps("agreeToPolicy")} />
718
+ * <label htmlFor={form.getCheckboxProps("agreeToPolicy").id}>
719
+ * I agree to the privacy policy
720
+ * </label>
721
+ * </div>
722
+ */
723
+ const createNativeCheckboxProps = (field, formValues, handleChange, handleBlur) => {
724
+ return {
725
+ id: field,
726
+ name: field,
727
+ checked: !!getValueByPath(formValues, field),
728
+ onChange: (e) => handleChange(field, e.target.checked),
729
+ onBlur: () => handleBlur(field, true)
730
+ };
731
+ };
732
+ /**
733
+ * Creates props for a native switch input bound to a boolean form field.
734
+ * Semantically identical to checkbox, but typically styled as a toggle switch via CSS.
735
+ * The switch is "on" when the field value is truthy, "off" when falsy.
736
+ * Works with: <input type="checkbox"> (styled as switch via CSS)
737
+ *
738
+ * This is functionally the same as createNativeCheckboxProps but exists as a separate
739
+ * method to clarify the semantic intent when building toggle switch UIs.
740
+ *
741
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
742
+ * @param formValues - Current form values object
743
+ * @param handleChange - Function to update the field value (receives boolean) in form state
744
+ * @param handleBlur - Function to mark the field as touched in form state
745
+ * @returns Props object to spread onto native checkbox inputs styled as switches
746
+ *
747
+ * @example
748
+ * // Native checkbox styled as switch
749
+ * <label className="switch">
750
+ * <input type="checkbox" {...form.getSwitchProps("settings.darkMode")} />
751
+ * <span className="slider"></span>
752
+ * </label>
753
+ *
754
+ * @example
755
+ * // Switch with label
756
+ * <div className="setting-row">
757
+ * <label htmlFor={form.getSwitchProps("notifications.enabled").id}>
758
+ * Enable Notifications
759
+ * </label>
760
+ * <input type="checkbox" {...form.getSwitchProps("notifications.enabled")} className="toggle-switch" />
761
+ * </div>
762
+ *
763
+ * @example
764
+ * // Multiple switches for feature flags
765
+ * <input type="checkbox" {...form.getSwitchProps("features.experimentalUI")} />
766
+ * <input type="checkbox" {...form.getSwitchProps("features.betaFeatures")} />
767
+ */
768
+ const createNativeSwitchProps = (field, formValues, handleChange, handleBlur) => {
769
+ return {
770
+ id: field,
771
+ name: field,
772
+ checked: !!getValueByPath(formValues, field),
773
+ onChange: (e) => handleChange(field, e.target.checked),
774
+ onBlur: () => handleBlur(field, true)
775
+ };
776
+ };
777
+ /**
778
+ * Creates props for a native range input bound to a numeric form field.
779
+ * Automatically handles value normalization, change events, and blur tracking.
780
+ * Works with: <input type="range">
781
+ *
782
+ * Note: Native range inputs only support single numeric values, not arrays.
783
+ * For multi-thumb sliders or more complex range inputs, use a UI library adapter.
784
+ * If the field value is an array, only the first element is used.
785
+ *
786
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
787
+ * @param formValues - Current form values object
788
+ * @param handleChange - Function to update the field value (receives number) in form state
789
+ * @param handleBlur - Function to mark the field as touched in form state
790
+ * @returns Props object to spread onto native range input elements
791
+ *
792
+ * @example
793
+ * // Basic range input with value display
794
+ * <div>
795
+ * <input
796
+ * type="range"
797
+ * min={0}
798
+ * max={100}
799
+ * {...form.getSliderProps("settings.volume")}
800
+ * />
801
+ * <span>{form.values.settings?.volume}%</span>
802
+ * </div>
803
+ *
804
+ * @example
805
+ * // Range with step for decimal values
806
+ * <input
807
+ * type="range"
808
+ * min={0}
809
+ * max={1}
810
+ * step={0.1}
811
+ * {...form.getSliderProps("opacity")}
812
+ * />
813
+ *
814
+ * @example
815
+ * // Age slider with min/max and labels
816
+ * <label htmlFor={form.getSliderProps("age").id}>Age: {form.values.age}</label>
817
+ * <input type="range" min={18} max={100} {...form.getSliderProps("age")} />
818
+ */
819
+ const createNativeSliderProps = (field, formValues, handleChange, handleBlur) => {
820
+ const raw = getValueByPath(formValues, field);
821
+ const toNumber = (v) => typeof v === "string" ? Number(v || 0) : typeof v === "number" ? v : 0;
822
+ return {
823
+ id: field,
824
+ name: field,
825
+ type: "range",
826
+ value: Array.isArray(raw) ? toNumber(raw[0]) : toNumber(raw),
827
+ onChange: (e) => handleChange(field, Number(e.target.value)),
828
+ onBlur: () => handleBlur(field, true)
829
+ };
830
+ };
831
+ /**
832
+ * Creates props for a single checkbox option within a checkbox group bound to an array field.
833
+ * Each checkbox toggles the presence of its value in the array field.
834
+ * Checking adds the value to the array; unchecking removes it.
835
+ * Works with: multiple <input type="checkbox"> elements bound to the same array field
836
+ *
837
+ * This is different from createNativeCheckboxProps, which is for single boolean checkboxes.
838
+ *
839
+ * @param field - The path to the array field in form values
840
+ * @param optionValue - The value this checkbox represents (added/removed from array)
841
+ * @param formValues - Current form values object
842
+ * @param handleChange - Function to update the array field value in form state
843
+ * @param handleBlur - Function to mark the field as touched in form state
844
+ * @returns Props object to spread onto a checkbox input in a group
845
+ *
846
+ * @example
847
+ * // Multiple checkboxes for selecting interests (array field)
848
+ * <label>
849
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "sports")} />
850
+ * Sports
851
+ * </label>
852
+ * <label>
853
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "music")} />
854
+ * Music
855
+ * </label>
856
+ * <label>
857
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "travel")} />
858
+ * Travel
859
+ * </label>
860
+ * // form.values.interests = ["sports", "music"] when both are checked
861
+ *
862
+ * @example
863
+ * // Dynamic checkbox group from data
864
+ * {permissions.map(permission => (
865
+ * <label key={permission.id}>
866
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("userPermissions", permission.id)} />
867
+ * {permission.name}
868
+ * </label>
869
+ * ))}
870
+ */
871
+ const createCheckboxGroupOptionProps = (field, optionValue, formValues, handleChange, handleBlur) => {
872
+ const raw = getValueByPath(formValues, field);
873
+ const current = Array.isArray(raw) ? raw : [];
874
+ const isChecked = current.some((v) => String(v) === String(optionValue));
875
+ return {
876
+ id: `${field}-${String(optionValue)}`,
877
+ name: field,
878
+ value: optionValue,
879
+ checked: isChecked,
880
+ onChange: (e) => {
881
+ if (e.target.checked) {
882
+ if (!current.some((v) => String(v) === String(optionValue))) handleChange(field, [...current, optionValue]);
883
+ } else handleChange(field, current.filter((v) => String(v) !== String(optionValue)));
884
+ },
885
+ onBlur: () => handleBlur(field, true)
886
+ };
887
+ };
888
+ /**
889
+ * Creates props for a native file input bound to a form field.
890
+ * Automatically handles single or multiple file selection based on the input's `multiple` attribute.
891
+ * Works with: <input type="file">
892
+ *
893
+ * When a file is selected:
894
+ * - For single file inputs: field value is set to the File object or null if cleared
895
+ * - For multiple file inputs: field value is set to an array of File objects or empty array if cleared
896
+ *
897
+ * Note: File values are not displayed in the returned props (file inputs are controlled differently).
898
+ * Access the current file(s) via form.values[field].
899
+ *
900
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
901
+ * @param _formValues - Current form values object (not used for file inputs)
902
+ * @param handleChange - Function to update the field value (receives File, File[], or null) in form state
903
+ * @param handleBlur - Function to mark the field as touched in form state
904
+ * @returns Props object to spread onto native file input elements
905
+ *
906
+ * @example
907
+ * // Single file upload
908
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("avatar")} />
909
+ * {form.values.avatar && <p>Selected: {form.values.avatar.name}</p>}
910
+ *
911
+ * @example
912
+ * // Multiple file upload
913
+ * <input type="file" multiple accept=".pdf,.doc,.docx" {...form.getFileFieldProps("documents")} />
914
+ * {form.values.documents?.length > 0 && (
915
+ * <ul>
916
+ * {form.values.documents.map((file, i) => (
917
+ * <li key={i}>{file.name} ({file.size} bytes)</li>
918
+ * ))}
919
+ * </ul>
920
+ * )}
921
+ *
922
+ * @example
923
+ * // File input with preview
924
+ * <div>
925
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("profilePic")} />
926
+ * {form.values.profilePic && (
927
+ * <img src={URL.createObjectURL(form.values.profilePic)} alt="Preview" />
928
+ * )}
929
+ * </div>
930
+ */
931
+ const createNativeFileFieldProps = (field, _formValues, handleChange, handleBlur) => {
932
+ return {
933
+ id: field,
934
+ name: field,
935
+ onChange: (e) => {
936
+ const input = e.target;
937
+ const files = input.files;
938
+ if (!files || files.length === 0) {
939
+ handleChange(field, input.multiple ? [] : null);
940
+ return;
941
+ }
942
+ handleChange(field, input.multiple ? Array.from(files) : files[0]);
943
+ },
944
+ onBlur: () => handleBlur(field, true)
945
+ };
946
+ };
947
+ /**
948
+ * Creates props for a single radio button option within a radio group bound to a scalar form field.
949
+ * Multiple radio buttons with the same field name form a group where only one can be selected.
950
+ * Selecting a radio button sets the field value to that option's value.
951
+ * Works with: multiple <input type="radio"> elements sharing the same name attribute
952
+ *
953
+ * This is used for mutually exclusive choices, unlike checkbox groups where multiple can be selected.
954
+ *
955
+ * @param field - The path to the field in form values (supports dot notation and bracket notation)
956
+ * @param optionValue - The value this radio button represents
957
+ * @param formValues - Current form values object
958
+ * @param handleChange - Function to update the field value in form state
959
+ * @param handleBlur - Function to mark the field as touched in form state
960
+ * @returns Props object to spread onto a radio input in a group
961
+ *
962
+ * @example
963
+ * // Radio group for selecting a contact method
964
+ * <div>
965
+ * <label>
966
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "email")} />
967
+ * Email
968
+ * </label>
969
+ * <label>
970
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "phone")} />
971
+ * Phone
972
+ * </label>
973
+ * <label>
974
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "mail")} />
975
+ * Mail
976
+ * </label>
977
+ * </div>
978
+ * // form.values.contactMethod = "email" when email is selected
979
+ *
980
+ * @example
981
+ * // Dynamic radio group from data
982
+ * {sizes.map(size => (
983
+ * <label key={size.value}>
984
+ * <input type="radio" {...form.getRadioGroupOptionProps("size", size.value)} />
985
+ * {size.label}
986
+ * </label>
987
+ * ))}
988
+ *
989
+ * @example
990
+ * // Radio group with descriptions
991
+ * <div className="radio-group">
992
+ * <label>
993
+ * <input type="radio" {...form.getRadioGroupOptionProps("plan", "free")} />
994
+ * <span>Free Plan</span>
995
+ * <small>Basic features for personal use</small>
996
+ * </label>
997
+ * <label>
998
+ * <input type="radio" {...form.getRadioGroupOptionProps("plan", "pro")} />
999
+ * <span>Pro Plan</span>
1000
+ * <small>Advanced features for professionals</small>
1001
+ * </label>
1002
+ * </div>
1003
+ */
1004
+ const createRadioGroupOptionProps = (field, optionValue, formValues, handleChange, handleBlur) => {
1005
+ const current = getValueByPath(formValues, field);
1006
+ const checked = String(current) === String(optionValue);
1007
+ return {
1008
+ id: `${field}-${String(optionValue)}`,
1009
+ name: field,
1010
+ value: optionValue,
1011
+ checked,
1012
+ onChange: (e) => {
1013
+ if (e.target.checked) handleChange(field, optionValue);
1014
+ },
1015
+ onBlur: () => handleBlur(field, true)
1016
+ };
126
1017
  };
127
-
128
1018
  // src/formReducer.ts
129
- var formReducer = (state, action, initialValues) => {
130
- switch (action.type) {
131
- case "SET_FIELD_VALUE": {
132
- if (getValueByPath(state.values, action.field) === action.value) return state;
133
- const newValues = setValueByPath(state.values, action.field, action.value);
134
- const newServerErrors = { ...state.serverErrors };
135
- Object.keys(newServerErrors).forEach((errorPath) => {
136
- if (isPathAffected(errorPath, action.field)) {
137
- delete newServerErrors[errorPath];
138
- }
139
- });
140
- return {
141
- ...state,
142
- values: newValues,
143
- serverErrors: newServerErrors,
144
- isDirty: !deepEqual(newValues, initialValues)
145
- };
146
- }
147
- case "SET_VALUES": {
148
- const newValues = deepMerge(state.values, action.values);
149
- const newServerErrors = { ...state.serverErrors };
150
- Object.keys(action.values).forEach((field) => {
151
- Object.keys(newServerErrors).forEach((errorPath) => {
152
- if (isPathAffected(errorPath, field)) {
153
- delete newServerErrors[errorPath];
154
- }
155
- });
156
- });
157
- return {
158
- ...state,
159
- values: newValues,
160
- serverErrors: newServerErrors,
161
- isDirty: !deepEqual(newValues, initialValues)
162
- };
163
- }
164
- case "SET_FIELD_TOUCHED":
165
- return {
166
- ...state,
167
- touched: {
168
- ...state.touched,
169
- [normalizePath(action.field)]: action.isTouched
170
- }
171
- };
172
- case "SET_CLIENT_ERRORS":
173
- return {
174
- ...state,
175
- clientErrors: normalizePathKeys(action.errors)
176
- };
177
- case "SET_SERVER_ERRORS":
178
- return {
179
- ...state,
180
- serverErrors: normalizePathKeys(action.errors)
181
- };
182
- case "CLEAR_SERVER_ERRORS":
183
- return {
184
- ...state,
185
- serverErrors: {}
186
- };
187
- case "SET_SUBMITTING":
188
- return {
189
- ...state,
190
- isSubmitting: action.isSubmitting
191
- };
192
- case "INCREMENT_SUBMIT_COUNT":
193
- return { ...state, submitCount: state.submitCount + 1 };
194
- case "SET_FORM_VALIDATING":
195
- return {
196
- ...state,
197
- isFormValidating: action.isFormValidating
198
- };
199
- case "SET_FIELD_VALIDATING": {
200
- const key = normalizePath(action.field);
201
- const newValidatingFields = { ...state.validatingFields };
202
- if (action.isValidating) {
203
- newValidatingFields[key] = true;
204
- } else {
205
- delete newValidatingFields[key];
206
- }
207
- return {
208
- ...state,
209
- validatingFields: newValidatingFields
210
- };
211
- }
212
- case "SET_FIELD_ERROR": {
213
- const key = normalizePath(action.field);
214
- const newFieldErrors = { ...state.fieldErrors };
215
- if (action.error) {
216
- newFieldErrors[key] = action.error;
217
- } else {
218
- delete newFieldErrors[key];
219
- }
220
- return {
221
- ...state,
222
- fieldErrors: newFieldErrors
223
- };
224
- }
225
- case "RESET_FORM":
226
- return {
227
- values: initialValues,
228
- touched: {},
229
- clientErrors: {},
230
- serverErrors: {},
231
- fieldErrors: {},
232
- validatingFields: {},
233
- isSubmitting: false,
234
- isFormValidating: false,
235
- submitCount: 0,
236
- isDirty: false
237
- };
238
- case "MARK_ALL_TOUCHED": {
239
- const allTouched = {};
240
- action.fields.forEach((path) => {
241
- allTouched[normalizePath(path)] = true;
242
- });
243
- return {
244
- ...state,
245
- touched: {
246
- ...state.touched,
247
- ...allTouched
248
- }
249
- };
250
- }
251
- default:
252
- return state;
253
- }
1019
+ /**
1020
+ * Reducer function for form state management using the Redux-style reducer pattern.
1021
+ * Handles all form state transitions in an immutable, predictable way.
1022
+ *
1023
+ * This reducer processes various actions that modify form state including:
1024
+ * - Field value updates (single or batch)
1025
+ * - Touch state tracking (marking fields as interacted with)
1026
+ * - Client-side validation errors
1027
+ * - Server-side validation errors
1028
+ * - Form submission state
1029
+ * - Form reset to initial values
1030
+ *
1031
+ * All state updates are performed immutably - the reducer always returns a new state object
1032
+ * rather than mutating the existing state. Server errors are automatically cleared when
1033
+ * related fields are modified to provide a smooth user experience.
1034
+ *
1035
+ * @template TValues - The type of form values being managed
1036
+ *
1037
+ * @param state - The current form state before the action is applied
1038
+ * @param action - The action to perform (e.g., SET_FIELD_VALUE, SET_CLIENT_ERRORS, RESET_FORM)
1039
+ * @param initialValues - Initial form values used when resetting the form
1040
+ * @returns A new form state object reflecting the changes from the action
1041
+ *
1042
+ * @example
1043
+ * // Used internally by useForm hook with useReducer
1044
+ * const reducerFn = useCallback(
1045
+ * (state: FormState<TValues>, action: FormAction<TValues>) =>
1046
+ * formReducer(state, action, initialValues),
1047
+ * [initialValues]
1048
+ * );
1049
+ * const [formState, dispatch] = useReducer(reducerFn, initialState);
1050
+ *
1051
+ * @example
1052
+ * // Dispatching a field value change
1053
+ * dispatch({
1054
+ * type: "SET_FIELD_VALUE",
1055
+ * field: "email",
1056
+ * value: "user@example.com"
1057
+ * });
1058
+ *
1059
+ * @example
1060
+ * // Dispatching validation errors
1061
+ * dispatch({
1062
+ * type: "SET_CLIENT_ERRORS",
1063
+ * errors: { email: "Invalid email format", password: "Too short" }
1064
+ * });
1065
+ *
1066
+ * @example
1067
+ * // Marking all fields as touched on submit
1068
+ * dispatch({
1069
+ * type: "MARK_ALL_TOUCHED",
1070
+ * fields: ["name", "email", "password"]
1071
+ * });
1072
+ */
1073
+ const formReducer = (state, action, initialValues) => {
1074
+ switch (action.type) {
1075
+ case "SET_FIELD_VALUE": {
1076
+ if (getValueByPath(state.values, action.field) === action.value) return state;
1077
+ const newValues = setValueByPath(state.values, action.field, action.value);
1078
+ const newServerErrors = { ...state.serverErrors };
1079
+ Object.keys(newServerErrors).forEach((errorPath) => {
1080
+ if (isPathAffected(errorPath, action.field)) delete newServerErrors[errorPath];
1081
+ });
1082
+ return {
1083
+ ...state,
1084
+ values: newValues,
1085
+ serverErrors: newServerErrors,
1086
+ isDirty: !deepEqual(newValues, initialValues)
1087
+ };
1088
+ }
1089
+ case "SET_VALUES": {
1090
+ const newValues = deepMerge(state.values, action.values);
1091
+ const newServerErrors = { ...state.serverErrors };
1092
+ Object.keys(action.values).forEach((field) => {
1093
+ Object.keys(newServerErrors).forEach((errorPath) => {
1094
+ if (isPathAffected(errorPath, field)) delete newServerErrors[errorPath];
1095
+ });
1096
+ });
1097
+ return {
1098
+ ...state,
1099
+ values: newValues,
1100
+ serverErrors: newServerErrors,
1101
+ isDirty: !deepEqual(newValues, initialValues)
1102
+ };
1103
+ }
1104
+ case "SET_FIELD_TOUCHED": return {
1105
+ ...state,
1106
+ touched: {
1107
+ ...state.touched,
1108
+ [normalizePath(action.field)]: action.isTouched
1109
+ }
1110
+ };
1111
+ case "SET_CLIENT_ERRORS": return {
1112
+ ...state,
1113
+ clientErrors: normalizePathKeys(action.errors)
1114
+ };
1115
+ case "SET_SERVER_ERRORS": return {
1116
+ ...state,
1117
+ serverErrors: normalizePathKeys(action.errors)
1118
+ };
1119
+ case "CLEAR_SERVER_ERRORS": return {
1120
+ ...state,
1121
+ serverErrors: {}
1122
+ };
1123
+ case "SET_SUBMITTING": return {
1124
+ ...state,
1125
+ isSubmitting: action.isSubmitting
1126
+ };
1127
+ case "INCREMENT_SUBMIT_COUNT": return {
1128
+ ...state,
1129
+ submitCount: state.submitCount + 1
1130
+ };
1131
+ case "SET_FORM_VALIDATING": return {
1132
+ ...state,
1133
+ isFormValidating: action.isFormValidating
1134
+ };
1135
+ case "SET_FIELD_VALIDATING": {
1136
+ const key = normalizePath(action.field);
1137
+ const newValidatingFields = { ...state.validatingFields };
1138
+ if (action.isValidating) newValidatingFields[key] = true;
1139
+ else delete newValidatingFields[key];
1140
+ return {
1141
+ ...state,
1142
+ validatingFields: newValidatingFields
1143
+ };
1144
+ }
1145
+ case "SET_FIELD_ERROR": {
1146
+ const key = normalizePath(action.field);
1147
+ const newFieldErrors = { ...state.fieldErrors };
1148
+ if (action.error) newFieldErrors[key] = action.error;
1149
+ else delete newFieldErrors[key];
1150
+ return {
1151
+ ...state,
1152
+ fieldErrors: newFieldErrors
1153
+ };
1154
+ }
1155
+ case "RESET_FORM": return {
1156
+ values: initialValues,
1157
+ touched: {},
1158
+ clientErrors: {},
1159
+ serverErrors: {},
1160
+ fieldErrors: {},
1161
+ validatingFields: {},
1162
+ isSubmitting: false,
1163
+ isFormValidating: false,
1164
+ submitCount: 0,
1165
+ isDirty: false
1166
+ };
1167
+ case "MARK_ALL_TOUCHED": {
1168
+ const allTouched = {};
1169
+ action.fields.forEach((path) => {
1170
+ allTouched[normalizePath(path)] = true;
1171
+ });
1172
+ return {
1173
+ ...state,
1174
+ touched: {
1175
+ ...state.touched,
1176
+ ...allTouched
1177
+ }
1178
+ };
1179
+ }
1180
+ default: return state;
1181
+ }
254
1182
  };
1183
+ // src/standardSchema.ts
1184
+ /**
1185
+ * Detects whether a value is a Standard Schema v1 object by checking for
1186
+ * the `~standard` property with `version === 1`.
1187
+ */
255
1188
  function isStandardSchema(value) {
256
- if (value == null || typeof value !== "object" || !("~standard" in value)) {
257
- return false;
258
- }
259
- const standard = value["~standard"];
260
- return standard != null && typeof standard === "object" && "version" in standard && standard.version === 1;
1189
+ if (value == null || typeof value !== "object" || !("~standard" in value)) return false;
1190
+ const standard = value["~standard"];
1191
+ return standard != null && typeof standard === "object" && "version" in standard && standard.version === 1;
261
1192
  }
1193
+ /**
1194
+ * Converts Standard Schema paths (PropertyKey | { key: PropertyKey }) to
1195
+ * the string[] format used by railway-ts ValidationError paths.
1196
+ */
262
1197
  function convertPath(path) {
263
- if (!path) return [];
264
- return path.map((s) => typeof s === "object" && s !== null && "key" in s ? String(s.key) : String(s));
1198
+ if (!path) return [];
1199
+ return path.map((s) => typeof s === "object" && s !== null && "key" in s ? String(s.key) : String(s));
265
1200
  }
1201
+ /**
1202
+ * Maps a Standard Schema v1 result to a Railway Result.
1203
+ * `{ value }` → `ok(value)`, `{ issues }` → `err(ValidationError[])`.
1204
+ */
266
1205
  function convertResult(result) {
267
- if ("issues" in result && result.issues) {
268
- const errors = result.issues.map((issue) => ({
269
- path: convertPath(issue.path),
270
- message: issue.message
271
- }));
272
- return err(errors);
273
- }
274
- return ok(result.value);
1206
+ if ("issues" in result && result.issues) {
1207
+ const errors = result.issues.map((issue) => ({
1208
+ path: convertPath(issue.path),
1209
+ message: issue.message
1210
+ }));
1211
+ return err(errors);
1212
+ }
1213
+ return ok(result.value);
275
1214
  }
1215
+ /**
1216
+ * Wraps a Standard Schema v1 object into a `MaybeAsyncValidator` compatible
1217
+ * with the railway-ts validation pipeline. This allows `useForm` to accept
1218
+ * any Standard Schema v1 compliant validator (Valibot, ArkType, etc.).
1219
+ */
276
1220
  function fromStandardSchema(schema) {
277
- return (value) => {
278
- const result = schema["~standard"].validate(value);
279
- if (result instanceof Promise) {
280
- return result.then((r) => convertResult(r));
281
- }
282
- return convertResult(result);
283
- };
1221
+ return (value) => {
1222
+ const result = schema["~standard"].validate(value);
1223
+ if (result instanceof Promise) return result.then((r) => convertResult(r));
1224
+ return convertResult(result);
1225
+ };
284
1226
  }
285
-
286
- // src/arrayHelpersFactory.ts
287
- var createArrayHelpers = (field, arrayValue, setFieldValue, getFieldProps, getSelectFieldProps, getSliderProps, getCheckboxProps, getSwitchProps, getFileFieldProps, getRadioGroupOptionProps, getFieldError, getFieldId) => {
288
- return {
289
- /**
290
- * The current array of values for this field.
291
- * Use this to iterate over items when rendering the form.
292
- *
293
- * @example
294
- * // Render array items
295
- * helpers.values.map((contact, index) => (
296
- * <div key={index}>
297
- * <input {...helpers.getFieldProps(index, "name")} />
298
- * </div>
299
- * ))
300
- */
301
- values: arrayValue,
302
- /**
303
- * Adds a new item to the end of the array.
304
- * The form state is updated immutably and all subscribed components re-render.
305
- *
306
- * @param value - The item to add to the array
307
- *
308
- * @example
309
- * // Add a new contact
310
- * const helpers = form.arrayHelpers("contacts");
311
- * helpers.push({ name: "", email: "", phone: "" });
312
- */
313
- push: (value) => {
314
- const newArray = [...arrayValue, value];
315
- setFieldValue(field, newArray);
316
- },
317
- /**
318
- * Removes an item at the specified index from the array.
319
- * If the index is out of bounds, no action is taken.
320
- * The form state is updated immutably.
321
- *
322
- * @param index - The zero-based index of the item to remove
323
- *
324
- * @example
325
- * // Remove the second contact
326
- * const helpers = form.arrayHelpers("contacts");
327
- * helpers.remove(1);
328
- */
329
- remove: (index) => {
330
- if (index < 0 || index >= arrayValue.length) return;
331
- const newArray = [...arrayValue];
332
- newArray.splice(index, 1);
333
- setFieldValue(field, newArray);
334
- },
335
- /**
336
- * Inserts an item at the specified index in the array.
337
- * Items at and after the index are shifted to the right.
338
- * If the index is out of bounds, it's clamped to valid range [0, length].
339
- *
340
- * @param index - The zero-based insertion position
341
- * @param value - The item to insert
342
- *
343
- * @example
344
- * // Insert a contact at the beginning
345
- * const helpers = form.arrayHelpers("contacts");
346
- * helpers.insert(0, { name: "New Contact", email: "", phone: "" });
347
- */
348
- insert: (index, value) => {
349
- const clamped = Math.max(0, Math.min(index, arrayValue.length));
350
- const newArray = [...arrayValue];
351
- newArray.splice(clamped, 0, value);
352
- setFieldValue(field, newArray);
353
- },
354
- /**
355
- * Swaps the positions of two items in the array.
356
- * If either index is out of bounds or they are equal, no action is taken.
357
- * Useful for drag-and-drop reordering interfaces.
358
- *
359
- * @param indexA - The zero-based index of the first item
360
- * @param indexB - The zero-based index of the second item
361
- *
362
- * @example
363
- * // Swap first and second contacts
364
- * const helpers = form.arrayHelpers("contacts");
365
- * helpers.swap(0, 1);
366
- *
367
- * @example
368
- * // Move item up in list
369
- * const moveUp = (index: number) => {
370
- * if (index > 0) helpers.swap(index, index - 1);
371
- * };
372
- */
373
- swap: (indexA, indexB) => {
374
- if (indexA === indexB || indexA < 0 || indexB < 0 || indexA >= arrayValue.length || indexB >= arrayValue.length) {
375
- return;
376
- }
377
- const newArray = [...arrayValue];
378
- const a = newArray[indexA];
379
- const b = newArray[indexB];
380
- if (a === void 0 || b === void 0) {
381
- return;
382
- }
383
- newArray[indexA] = b;
384
- newArray[indexB] = a;
385
- setFieldValue(field, newArray);
386
- },
387
- /**
388
- * Replaces an entire item at the specified index with a new value.
389
- * If the index is out of bounds, no action is taken.
390
- *
391
- * @param index - The zero-based index of the item to replace
392
- * @param value - The new item value
393
- *
394
- * @example
395
- * // Replace a contact entirely
396
- * const helpers = form.arrayHelpers("contacts");
397
- * helpers.replace(0, { name: "John Doe", email: "john@example.com", phone: "555-0100" });
398
- */
399
- replace: (index, value) => {
400
- if (index < 0 || index >= arrayValue.length) return;
401
- const newArray = [...arrayValue];
402
- newArray[index] = value;
403
- setFieldValue(field, newArray);
404
- },
405
- /**
406
- * Gets props for a native text input bound to a field within an array item.
407
- * Provides type-safe field path autocomplete for nested fields.
408
- * Works with: <input type="text">, <input type="email">, <textarea>, etc.
409
- *
410
- * @param index - The zero-based index of the array item
411
- * @param subField - The field path within the array item (type-safe and autocompleted)
412
- * @returns Props object to spread onto a native input element
413
- *
414
- * @example
415
- * // Text input for contact name
416
- * helpers.values.map((_, index) => (
417
- * <input type="text" {...helpers.getFieldProps(index, "name")} />
418
- * ))
419
- */
420
- getFieldProps: (index, subField) => {
421
- const path = `${field}.${index}.${subField}`;
422
- return getFieldProps(path);
423
- },
424
- /**
425
- * Gets props for a native select element bound to a field within an array item.
426
- * Provides type-safe field path autocomplete for nested fields.
427
- * Works with: <select>
428
- *
429
- * @param index - The zero-based index of the array item
430
- * @param subField - The field path within the array item (type-safe and autocompleted)
431
- * @returns Props object to spread onto a native select element
432
- *
433
- * @example
434
- * // Select for contact type
435
- * <select {...helpers.getSelectFieldProps(index, "type")}>
436
- * <option value="work">Work</option>
437
- * <option value="personal">Personal</option>
438
- * </select>
439
- */
440
- getSelectFieldProps: (index, subField) => {
441
- const path = `${field}.${index}.${subField}`;
442
- return getSelectFieldProps(path);
443
- },
444
- /**
445
- * Gets props for a native range input bound to a field within an array item.
446
- * Provides type-safe field path autocomplete for nested fields.
447
- * Works with: <input type="range">
448
- *
449
- * @param index - The zero-based index of the array item
450
- * @param subField - The field path within the array item (type-safe and autocompleted)
451
- * @returns Props object to spread onto a native range input element
452
- *
453
- * @example
454
- * // Range slider for priority
455
- * <input type="range" min={0} max={10} {...helpers.getSliderProps(index, "priority")} />
456
- */
457
- getSliderProps: (index, subField) => {
458
- const path = `${field}.${index}.${subField}`;
459
- return getSliderProps(path);
460
- },
461
- /**
462
- * Gets props for a native checkbox bound to a field within an array item.
463
- * Provides type-safe field path autocomplete for nested fields.
464
- * Works with: <input type="checkbox">
465
- *
466
- * @param index - The zero-based index of the array item
467
- * @param subField - The field path within the array item (type-safe and autocompleted)
468
- * @returns Props object to spread onto a native checkbox input
469
- *
470
- * @example
471
- * // Checkbox for marking contact as favorite
472
- * <input type="checkbox" {...helpers.getCheckboxProps(index, "isFavorite")} />
473
- */
474
- getCheckboxProps: (index, subField) => {
475
- const path = `${field}.${index}.${subField}`;
476
- return getCheckboxProps(path);
477
- },
478
- /**
479
- * Gets props for a native switch (checkbox styled as switch) bound to a field within an array item.
480
- * Provides type-safe field path autocomplete for nested fields.
481
- * Works with: <input type="checkbox"> (styled as switch via CSS)
482
- *
483
- * @param index - The zero-based index of the array item
484
- * @param subField - The field path within the array item (type-safe and autocompleted)
485
- * @returns Props object to spread onto a native checkbox input
486
- *
487
- * @example
488
- * // Switch for enabling/disabling a feature
489
- * <label className="switch">
490
- * <input type="checkbox" {...helpers.getSwitchProps(index, "enabled")} />
491
- * <span className="slider"></span>
492
- * </label>
493
- */
494
- getSwitchProps: (index, subField) => {
495
- const path = `${field}.${index}.${subField}`;
496
- return getSwitchProps(path);
497
- },
498
- /**
499
- * Gets props for a native file input bound to a field within an array item.
500
- * Provides type-safe field path autocomplete for nested fields.
501
- * Works with: <input type="file">
502
- *
503
- * @param index - The zero-based index of the array item
504
- * @param subField - The field path within the array item (type-safe and autocompleted)
505
- * @returns Props object to spread onto a native file input
506
- *
507
- * @example
508
- * // File input for contact avatar
509
- * <input type="file" accept="image/*" {...helpers.getFileFieldProps(index, "avatar")} />
510
- */
511
- getFileFieldProps: (index, subField) => {
512
- const path = `${field}.${index}.${subField}`;
513
- return getFileFieldProps(path);
514
- },
515
- /**
516
- * Gets props for a radio group option bound to a field within an array item.
517
- * Provides type-safe field path autocomplete for nested fields.
518
- * Works with: multiple <input type="radio"> elements sharing the same name
519
- *
520
- * @param index - The zero-based index of the array item
521
- * @param subField - The field path within the array item (type-safe and autocompleted)
522
- * @param optionValue - The value this radio option represents
523
- * @returns Props object to spread onto a native radio input
524
- *
525
- * @example
526
- * // Radio group for contact method preference
527
- * <label>
528
- * <input type="radio" {...helpers.getRadioGroupOptionProps(index, "preferredMethod", "email")} />
529
- * Email
530
- * </label>
531
- * <label>
532
- * <input type="radio" {...helpers.getRadioGroupOptionProps(index, "preferredMethod", "phone")} />
533
- * Phone
534
- * </label>
535
- */
536
- getRadioGroupOptionProps: (index, subField, optionValue) => {
537
- const path = `${field}.${index}.${subField}`;
538
- return getRadioGroupOptionProps(path, optionValue);
539
- },
540
- getFieldError: (index, subField) => getFieldError(`${field}.${index}.${subField}`),
541
- getFieldId: (index, subField, optionValue) => getFieldId(`${field}.${index}.${subField}`, optionValue)
542
- };
543
- };
544
-
545
- // src/fieldPropsFactory.ts
546
- var createNativeFieldProps = (field, formValues, handleChange, handleBlur) => {
547
- const raw = getValueByPath(formValues, field);
548
- const value = raw == null ? "" : typeof raw === "string" || typeof raw === "number" ? raw : raw instanceof Date ? isNaN(raw.getTime()) ? "" : raw.toISOString().split("T")[0] : JSON.stringify(raw);
549
- return {
550
- id: field,
551
- name: field,
552
- value,
553
- onChange: (e) => {
554
- handleChange(field, e.target.value);
555
- },
556
- onBlur: () => handleBlur(field, true)
557
- };
558
- };
559
- var createNativeSelectFieldProps = (field, formValues, handleChange, handleBlur) => {
560
- const raw = getValueByPath(formValues, field);
561
- const value = raw == null ? "" : typeof raw === "string" || typeof raw === "number" ? raw : JSON.stringify(raw);
562
- return {
563
- id: field,
564
- name: field,
565
- value,
566
- onChange: (e) => handleChange(field, e.target.value),
567
- onBlur: () => handleBlur(field, true)
568
- };
569
- };
570
- var createNativeCheckboxProps = (field, formValues, handleChange, handleBlur) => {
571
- const value = getValueByPath(formValues, field);
572
- return {
573
- id: field,
574
- name: field,
575
- checked: !!value,
576
- onChange: (e) => handleChange(field, e.target.checked),
577
- onBlur: () => handleBlur(field, true)
578
- };
579
- };
580
- var createNativeSwitchProps = (field, formValues, handleChange, handleBlur) => {
581
- const value = getValueByPath(formValues, field);
582
- return {
583
- id: field,
584
- name: field,
585
- checked: !!value,
586
- onChange: (e) => handleChange(field, e.target.checked),
587
- onBlur: () => handleBlur(field, true)
588
- };
589
- };
590
- var createNativeSliderProps = (field, formValues, handleChange, handleBlur) => {
591
- const raw = getValueByPath(formValues, field);
592
- const toNumber = (v) => typeof v === "string" ? Number(v || 0) : typeof v === "number" ? v : 0;
593
- const value = Array.isArray(raw) ? toNumber(raw[0]) : toNumber(raw);
594
- return {
595
- id: field,
596
- name: field,
597
- type: "range",
598
- value,
599
- onChange: (e) => handleChange(field, Number(e.target.value)),
600
- onBlur: () => handleBlur(field, true)
601
- };
602
- };
603
- var createCheckboxGroupOptionProps = (field, optionValue, formValues, handleChange, handleBlur) => {
604
- const raw = getValueByPath(formValues, field);
605
- const current = Array.isArray(raw) ? raw : [];
606
- const isChecked = current.some((v) => String(v) === String(optionValue));
607
- return {
608
- id: `${field}-${String(optionValue)}`,
609
- name: field,
610
- value: optionValue,
611
- checked: isChecked,
612
- onChange: (e) => {
613
- if (e.target.checked) {
614
- if (!current.some((v) => String(v) === String(optionValue))) {
615
- handleChange(field, [...current, optionValue]);
616
- }
617
- } else {
618
- const next = current.filter((v) => String(v) !== String(optionValue));
619
- handleChange(field, next);
620
- }
621
- },
622
- onBlur: () => handleBlur(field, true)
623
- };
624
- };
625
- var createNativeFileFieldProps = (field, _formValues, handleChange, handleBlur) => {
626
- return {
627
- id: field,
628
- name: field,
629
- onChange: (e) => {
630
- const input = e.target;
631
- const files = input.files;
632
- if (!files || files.length === 0) {
633
- handleChange(field, input.multiple ? [] : null);
634
- return;
635
- }
636
- handleChange(field, input.multiple ? Array.from(files) : files[0]);
637
- },
638
- onBlur: () => handleBlur(field, true)
639
- };
640
- };
641
- var createRadioGroupOptionProps = (field, optionValue, formValues, handleChange, handleBlur) => {
642
- const current = getValueByPath(formValues, field);
643
- const checked = String(current) === String(optionValue);
644
- return {
645
- id: `${field}-${String(optionValue)}`,
646
- name: field,
647
- value: optionValue,
648
- checked,
649
- onChange: (e) => {
650
- if (e.target.checked) handleChange(field, optionValue);
651
- },
652
- onBlur: () => handleBlur(field, true)
653
- };
654
- };
655
-
656
1227
  // src/useForm.ts
657
- var useForm = (validatorOrSchema, options) => {
658
- const { initialValues, onSubmit, validationMode, fieldValidators, onValuesChange, onFieldChange } = options;
659
- const validator = useMemo(
660
- () => isStandardSchema(validatorOrSchema) ? fromStandardSchema(validatorOrSchema) : validatorOrSchema,
661
- [validatorOrSchema]
662
- );
663
- const mode = validationMode ?? "live";
664
- const validateOnChange = mode === "live";
665
- const validateOnBlur = mode === "live" || mode === "blur";
666
- const validateOnMount = mode === "mount";
667
- const touchOnChange = mode === "live";
668
- const reducerFn = useCallback(
669
- (state, action) => formReducer(state, action, initialValues),
670
- [initialValues]
671
- );
672
- const initialState = {
673
- values: initialValues,
674
- touched: {},
675
- clientErrors: {},
676
- serverErrors: {},
677
- fieldErrors: {},
678
- validatingFields: {},
679
- isSubmitting: false,
680
- isFormValidating: false,
681
- submitCount: 0,
682
- isDirty: false
683
- };
684
- const [formState, dispatch] = useReducer(reducerFn, initialState);
685
- const formStateRef = useRef(formState);
686
- useEffect(() => {
687
- formStateRef.current = formState;
688
- });
689
- const pendingValuesRef = useRef(null);
690
- const onValuesChangeRef = useRef(onValuesChange);
691
- useEffect(() => {
692
- onValuesChangeRef.current = onValuesChange;
693
- });
694
- const prevValuesRef = useRef(formState.values);
695
- useEffect(() => {
696
- onValuesChangeRef.current?.(formState.values, prevValuesRef.current);
697
- prevValuesRef.current = formState.values;
698
- }, [formState.values]);
699
- const onFieldChangeRef = useRef(onFieldChange);
700
- useEffect(() => {
701
- onFieldChangeRef.current = onFieldChange;
702
- });
703
- const validationSeqRef = useRef(0);
704
- const fieldValidationSeqRef = useRef({});
705
- const isHandlingSubmitRef = useRef(false);
706
- const errors = useMemo(() => {
707
- const combined = {};
708
- Object.entries(formState.clientErrors).forEach(([path, msg]) => {
709
- combined[path] = msg;
710
- });
711
- Object.entries(formState.fieldErrors).forEach(([path, msg]) => {
712
- combined[path] = msg;
713
- });
714
- Object.entries(formState.serverErrors).forEach(([path, msg]) => {
715
- combined[path] = msg;
716
- });
717
- return combined;
718
- }, [formState.clientErrors, formState.fieldErrors, formState.serverErrors]);
719
- const isValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
720
- const isValidating = useMemo(
721
- () => formState.isFormValidating || Object.keys(formState.validatingFields).length > 0,
722
- [formState.isFormValidating, formState.validatingFields]
723
- );
724
- const dispatchValidationResult = useCallback((result) => {
725
- if (isErr(result)) {
726
- dispatch({
727
- type: "SET_CLIENT_ERRORS",
728
- errors: formatErrors(result.error)
729
- });
730
- } else {
731
- dispatch({
732
- type: "SET_CLIENT_ERRORS",
733
- errors: {}
734
- });
735
- }
736
- }, []);
737
- const validateForm = useCallback(
738
- (values) => {
739
- const validationResult = validate(values, validator);
740
- if (validationResult instanceof Promise) {
741
- const seq = ++validationSeqRef.current;
742
- dispatch({ type: "SET_FORM_VALIDATING", isFormValidating: true });
743
- return validationResult.then((result) => {
744
- if (seq === validationSeqRef.current) {
745
- dispatchValidationResult(result);
746
- dispatch({ type: "SET_FORM_VALIDATING", isFormValidating: false });
747
- }
748
- return result;
749
- });
750
- }
751
- dispatchValidationResult(validationResult);
752
- return validationResult;
753
- },
754
- [validator, dispatchValidationResult]
755
- );
756
- const runFieldValidator = useCallback(
757
- (field, values) => {
758
- const validatorFn = fieldValidators?.[field];
759
- if (!validatorFn) return;
760
- dispatch({ type: "SET_FIELD_ERROR", field, error: void 0 });
761
- const fieldValue = getValueByPath(values, field);
762
- const result = validatorFn(fieldValue, values);
763
- if (result instanceof Promise) {
764
- const seqKey = normalizePath(field);
765
- if (!fieldValidationSeqRef.current[seqKey]) {
766
- fieldValidationSeqRef.current[seqKey] = 0;
767
- }
768
- const seq = ++fieldValidationSeqRef.current[seqKey];
769
- dispatch({ type: "SET_FIELD_VALIDATING", field, isValidating: true });
770
- void result.then((error) => {
771
- if (seq === fieldValidationSeqRef.current[seqKey]) {
772
- dispatch({ type: "SET_FIELD_ERROR", field, error });
773
- dispatch({
774
- type: "SET_FIELD_VALIDATING",
775
- field,
776
- isValidating: false
777
- });
778
- }
779
- });
780
- } else {
781
- dispatch({ type: "SET_FIELD_ERROR", field, error: result });
782
- }
783
- },
784
- [fieldValidators]
785
- );
786
- const runValidationPipeline = useCallback(
787
- (field, values) => {
788
- const currentErrors = formStateRef.current.clientErrors;
789
- const hasStale = Object.keys(currentErrors).some((p) => isPathAffected(p, field));
790
- if (hasStale) {
791
- const cleaned = { ...currentErrors };
792
- Object.keys(cleaned).forEach((p) => {
793
- if (isPathAffected(p, field)) delete cleaned[p];
794
- });
795
- dispatch({ type: "SET_CLIENT_ERRORS", errors: cleaned });
796
- }
797
- const schemaResult = validateForm(values);
798
- if (fieldValidators?.[field]) {
799
- const afterSchema = (result) => {
800
- const schemaErrors = isErr(result) ? normalizePathKeys(formatErrors(result.error)) : {};
801
- if (!schemaErrors[normalizePath(field)]) {
802
- runFieldValidator(field, values);
803
- } else {
804
- dispatch({ type: "SET_FIELD_ERROR", field, error: void 0 });
805
- dispatch({
806
- type: "SET_FIELD_VALIDATING",
807
- field,
808
- isValidating: false
809
- });
810
- }
811
- };
812
- if (schemaResult instanceof Promise) {
813
- void schemaResult.then(afterSchema);
814
- } else {
815
- afterSchema(schemaResult);
816
- }
817
- }
818
- },
819
- [validateForm, fieldValidators, runFieldValidator]
820
- );
821
- const didMountRef = useRef(false);
822
- useEffect(() => {
823
- if (validateOnMount && !didMountRef.current) {
824
- didMountRef.current = true;
825
- void validateForm(initialValues);
826
- const allFields = collectFieldPaths(initialValues);
827
- dispatch({
828
- type: "MARK_ALL_TOUCHED",
829
- fields: allFields
830
- });
831
- }
832
- }, [initialValues, validateForm, validateOnMount]);
833
- const setFieldValue = useCallback(
834
- (field, value, shouldValidate = validateOnChange) => {
835
- const baseValues = pendingValuesRef.current ?? formStateRef.current.values;
836
- const updatedValues = setValueByPath(baseValues, field, value);
837
- pendingValuesRef.current = updatedValues;
838
- onFieldChangeRef.current?.(field, value, updatedValues);
839
- pendingValuesRef.current = null;
840
- dispatch({
841
- type: "SET_FIELD_VALUE",
842
- field,
843
- value
844
- });
845
- if (touchOnChange && !formStateRef.current.touched[normalizePath(field)]) {
846
- dispatch({ type: "SET_FIELD_TOUCHED", field, isTouched: true });
847
- }
848
- if (shouldValidate) {
849
- runValidationPipeline(field, updatedValues);
850
- }
851
- },
852
- [validateOnChange, touchOnChange, runValidationPipeline]
853
- );
854
- const setValues = useCallback(
855
- (newValues, shouldValidate = validateOnChange) => {
856
- dispatch({
857
- type: "SET_VALUES",
858
- values: newValues
859
- });
860
- if (shouldValidate) {
861
- const updatedValues = deepMerge(formState.values, newValues);
862
- void validateForm(updatedValues);
863
- }
864
- },
865
- [formState.values, validateOnChange, validateForm]
866
- );
867
- const setFieldTouched = useCallback(
868
- (field, isTouched = true, shouldValidate = validateOnBlur) => {
869
- dispatch({
870
- type: "SET_FIELD_TOUCHED",
871
- field,
872
- isTouched
873
- });
874
- if (shouldValidate) {
875
- if (!validateOnChange) {
876
- runValidationPipeline(field, formState.values);
877
- } else if (!formState.touched[normalizePath(field)]) {
878
- void validateForm(formState.values);
879
- }
880
- }
881
- },
882
- [formState.values, formState.touched, validateOnBlur, validateOnChange, validateForm, runValidationPipeline]
883
- );
884
- const setServerErrors = useCallback((serverErrors) => {
885
- dispatch({
886
- type: "SET_SERVER_ERRORS",
887
- errors: serverErrors
888
- });
889
- }, []);
890
- const clearServerErrors = useCallback(() => {
891
- dispatch({
892
- type: "CLEAR_SERVER_ERRORS"
893
- });
894
- }, []);
895
- const handleSubmit = useCallback(
896
- async (e) => {
897
- if (e) {
898
- e.preventDefault();
899
- }
900
- if (isHandlingSubmitRef.current) {
901
- return err([]);
902
- }
903
- isHandlingSubmitRef.current = true;
904
- try {
905
- const { values, clientErrors, serverErrors } = formStateRef.current;
906
- const valuePaths = collectFieldPaths(values);
907
- const allPaths = Array.from(
908
- /* @__PURE__ */ new Set([...valuePaths, ...Object.keys(clientErrors), ...Object.keys(serverErrors)])
909
- );
910
- dispatch({
911
- type: "MARK_ALL_TOUCHED",
912
- fields: allPaths
913
- });
914
- dispatch({ type: "INCREMENT_SUBMIT_COUNT" });
915
- dispatch({
916
- type: "CLEAR_SERVER_ERRORS"
917
- });
918
- ++validationSeqRef.current;
919
- dispatch({ type: "SET_FORM_VALIDATING", isFormValidating: true });
920
- const validationResult = await validate(values, validator);
921
- dispatch({ type: "SET_FORM_VALIDATING", isFormValidating: false });
922
- return match(validationResult, {
923
- ok: async (validData) => {
924
- dispatch({
925
- type: "SET_SUBMITTING",
926
- isSubmitting: true
927
- });
928
- if (fieldValidators) {
929
- const fieldEntries = Object.entries(fieldValidators);
930
- const fieldResults = await Promise.all(
931
- fieldEntries.map(async ([field, validatorFn]) => {
932
- const fieldValue = getValueByPath(values, field);
933
- const error = await validatorFn(fieldValue, values);
934
- if (error) {
935
- dispatch({ type: "SET_FIELD_ERROR", field, error });
936
- } else {
937
- dispatch({
938
- type: "SET_FIELD_ERROR",
939
- field,
940
- error: void 0
941
- });
942
- }
943
- return { field, error };
944
- })
945
- );
946
- const hasFieldErrors = fieldResults.some((r) => r.error);
947
- if (hasFieldErrors) {
948
- dispatch({
949
- type: "SET_SUBMITTING",
950
- isSubmitting: false
951
- });
952
- return err(fieldResults.filter((r) => r.error).map((r) => ({ path: [r.field], message: r.error })));
953
- }
954
- }
955
- if (onSubmit) {
956
- try {
957
- await onSubmit(validData);
958
- } catch (error) {
959
- console.error("Form submission error:", error);
960
- }
961
- }
962
- dispatch({
963
- type: "SET_SUBMITTING",
964
- isSubmitting: false
965
- });
966
- return ok(validData);
967
- },
968
- err: (errors2) => {
969
- dispatch({
970
- type: "SET_CLIENT_ERRORS",
971
- errors: formatErrors(errors2)
972
- });
973
- return Promise.resolve(err(errors2));
974
- }
975
- });
976
- } finally {
977
- isHandlingSubmitRef.current = false;
978
- }
979
- },
980
- [validator, onSubmit, fieldValidators]
981
- );
982
- const resetForm = useCallback(() => {
983
- dispatch({
984
- type: "RESET_FORM"
985
- });
986
- if (validateOnMount) {
987
- void validateForm(initialValues);
988
- }
989
- }, [initialValues, validateForm, validateOnMount]);
990
- const getFieldError = useCallback(
991
- (field) => {
992
- const key = normalizePath(field);
993
- const err3 = errors[key];
994
- if (!err3) return void 0;
995
- for (const touchedKey in formState.touched) {
996
- if (formState.touched[touchedKey] && isPathAffected(touchedKey, key)) return err3;
997
- }
998
- return void 0;
999
- },
1000
- [formState.touched, errors]
1001
- );
1002
- const getFieldId = useCallback(
1003
- (field, optionValue) => {
1004
- return optionValue !== void 0 ? `${field}-${String(optionValue)}` : field;
1005
- },
1006
- []
1007
- );
1008
- const getFieldProps = useCallback(
1009
- (field) => {
1010
- return createNativeFieldProps(field, formState.values, setFieldValue, setFieldTouched);
1011
- },
1012
- [formState.values, setFieldValue, setFieldTouched]
1013
- );
1014
- const getSelectFieldProps = useCallback(
1015
- (field) => {
1016
- return createNativeSelectFieldProps(field, formState.values, setFieldValue, setFieldTouched);
1017
- },
1018
- [formState.values, setFieldValue, setFieldTouched]
1019
- );
1020
- const getCheckboxProps = useCallback(
1021
- (field) => {
1022
- return createNativeCheckboxProps(field, formState.values, setFieldValue, setFieldTouched);
1023
- },
1024
- [formState.values, setFieldValue, setFieldTouched]
1025
- );
1026
- const getSwitchProps = useCallback(
1027
- (field) => {
1028
- return createNativeSwitchProps(field, formState.values, setFieldValue, setFieldTouched);
1029
- },
1030
- [formState.values, setFieldValue, setFieldTouched]
1031
- );
1032
- const getSliderProps = useCallback(
1033
- (field) => {
1034
- return createNativeSliderProps(field, formState.values, setFieldValue, setFieldTouched);
1035
- },
1036
- [formState.values, setFieldValue, setFieldTouched]
1037
- );
1038
- const getCheckboxGroupOptionProps = useCallback(
1039
- (field, optionValue) => {
1040
- return createCheckboxGroupOptionProps(
1041
- field,
1042
- optionValue,
1043
- formState.values,
1044
- setFieldValue,
1045
- setFieldTouched
1046
- );
1047
- },
1048
- [formState.values, setFieldValue, setFieldTouched]
1049
- );
1050
- const getFileFieldProps = useCallback(
1051
- (field) => {
1052
- return createNativeFileFieldProps(field, formState.values, setFieldValue, setFieldTouched);
1053
- },
1054
- [formState.values, setFieldValue, setFieldTouched]
1055
- );
1056
- const getRadioGroupOptionProps = useCallback(
1057
- (field, optionValue) => {
1058
- return createRadioGroupOptionProps(
1059
- field,
1060
- optionValue,
1061
- formState.values,
1062
- setFieldValue,
1063
- setFieldTouched
1064
- );
1065
- },
1066
- [formState.values, setFieldValue, setFieldTouched]
1067
- );
1068
- const arrayHelpersImpl = useCallback(
1069
- (field) => {
1070
- const getFieldPropsAtPath = (path) => createNativeFieldProps(path, formState.values, setFieldValue, setFieldTouched);
1071
- const getSelectFieldPropsAtPath = (path) => createNativeSelectFieldProps(path, formState.values, setFieldValue, setFieldTouched);
1072
- const getSliderPropsAtPath = (path) => createNativeSliderProps(path, formState.values, setFieldValue, setFieldTouched);
1073
- const getCheckboxPropsAtPath = (path) => createNativeCheckboxProps(path, formState.values, setFieldValue, setFieldTouched);
1074
- const getSwitchPropsAtPath = (path) => createNativeSwitchProps(path, formState.values, setFieldValue, setFieldTouched);
1075
- const getFileFieldPropsAtPath = (path) => createNativeFileFieldProps(path, formState.values, setFieldValue, setFieldTouched);
1076
- const getRadioGroupOptionPropsAtPath = (path, opt) => createRadioGroupOptionProps(path, opt, formState.values, setFieldValue, setFieldTouched);
1077
- const getFieldErrorAtPath = (path) => {
1078
- const key = normalizePath(path);
1079
- return formState.touched[key] ? errors[key] : void 0;
1080
- };
1081
- const getFieldIdAtPath = (path, optionValue) => optionValue !== void 0 ? `${path}-${String(optionValue)}` : path;
1082
- const arrayValue = getValueByPath(formState.values, field) || [];
1083
- return createArrayHelpers(
1084
- field,
1085
- arrayValue,
1086
- setFieldValue,
1087
- getFieldPropsAtPath,
1088
- getSelectFieldPropsAtPath,
1089
- getSliderPropsAtPath,
1090
- getCheckboxPropsAtPath,
1091
- getSwitchPropsAtPath,
1092
- getFileFieldPropsAtPath,
1093
- getRadioGroupOptionPropsAtPath,
1094
- getFieldErrorAtPath,
1095
- getFieldIdAtPath
1096
- );
1097
- },
1098
- [formState.values, formState.touched, errors, setFieldValue, setFieldTouched]
1099
- );
1100
- const arrayHelpers = arrayHelpersImpl;
1101
- return {
1102
- // Form state
1103
- values: formState.values,
1104
- touched: formState.touched,
1105
- errors,
1106
- clientErrors: formState.clientErrors,
1107
- serverErrors: formState.serverErrors,
1108
- fieldErrors: formState.fieldErrors,
1109
- isSubmitting: formState.isSubmitting,
1110
- isValidating,
1111
- validatingFields: formState.validatingFields,
1112
- isValid,
1113
- isDirty: formState.isDirty,
1114
- submitCount: formState.submitCount,
1115
- // Error helper
1116
- getFieldError,
1117
- // ID helper
1118
- getFieldId,
1119
- // Field management
1120
- setFieldValue,
1121
- setFieldTouched,
1122
- setValues,
1123
- // Server error management
1124
- setServerErrors,
1125
- clearServerErrors,
1126
- // Form actions
1127
- handleSubmit,
1128
- resetForm,
1129
- validateForm,
1130
- // Native HTML field integration
1131
- getFieldProps,
1132
- getSelectFieldProps,
1133
- getCheckboxProps,
1134
- getSwitchProps,
1135
- getSliderProps,
1136
- getCheckboxGroupOptionProps,
1137
- getFileFieldProps,
1138
- getRadioGroupOptionProps,
1139
- // Array field helpers
1140
- arrayHelpers
1141
- };
1228
+ /**
1229
+ * A powerful React form hook that combines Railway-oriented validation with native HTML support.
1230
+ * Provides type-safe form state management, automatic validation, error handling, and direct
1231
+ * integration with native HTML form elements.
1232
+ *
1233
+ * This hook integrates with @railway-ts/pipelines for functional validation, supports multiple
1234
+ * validation modes (live, blur, mount, submit), manages both client and server errors, and
1235
+ * provides helpers for working with nested objects and dynamic arrays.
1236
+ *
1237
+ * @template TValues - The shape of form values as a record with string keys
1238
+ *
1239
+ * @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
1240
+ * @param options - Configuration options for form behavior
1241
+ * @param options.initialValues - Initial values for form fields (used on mount and reset)
1242
+ * @param options.onSubmit - Callback invoked when form is submitted with valid data
1243
+ * @param options.validationMode - Controls when validation occurs: "live" | "blur" | "mount" | "submit"
1244
+ *
1245
+ * @returns An object containing:
1246
+ * **Form State:**
1247
+ * - `values` - Current form field values (TValues)
1248
+ * - `touched` - Record of which fields have been interacted with
1249
+ * - `errors` - Combined client and server errors (server takes precedence)
1250
+ * - `clientErrors` - Validation errors from the validator function
1251
+ * - `serverErrors` - Manually set errors from server responses
1252
+ * - `isValid` - Whether the form has no validation errors
1253
+ * - `isDirty` - Whether any values have changed from initial state
1254
+ * - `isSubmitting` - Whether the form is currently being submitted
1255
+ * - `isValidating` - Whether async validation is currently in progress
1256
+ *
1257
+ * **Field Management:**
1258
+ * - `setFieldValue(field, value, shouldValidate?)` - Update a single field
1259
+ * - `setFieldTouched(field, isTouched?, shouldValidate?)` - Mark field as touched
1260
+ * - `setValues(values, shouldValidate?)` - Update multiple fields at once
1261
+ *
1262
+ * **Server Error Management:**
1263
+ * - `setServerErrors(errors)` - Set server-side validation errors
1264
+ * - `clearServerErrors()` - Clear all server-side errors
1265
+ *
1266
+ * **Form Actions:**
1267
+ * - `handleSubmit(e?)` - Validate and submit the form
1268
+ * - `resetForm()` - Reset form to initial values and clear errors
1269
+ * - `validateForm(values)` - Manually trigger validation
1270
+ *
1271
+ * **Native HTML Integration:**
1272
+ * - `getFieldProps(field)` - Props for text inputs, email, textarea, etc.
1273
+ * - `getSelectFieldProps(field)` - Props for select elements
1274
+ * - `getCheckboxProps(field)` - Props for boolean checkboxes
1275
+ * - `getSwitchProps(field)` - Props for toggle switches
1276
+ * - `getSliderProps(field)` - Props for range inputs
1277
+ * - `getCheckboxGroupOptionProps(field, value)` - Props for checkbox groups (arrays)
1278
+ * - `getFileFieldProps(field)` - Props for file inputs
1279
+ * - `getRadioGroupOptionProps(field, value)` - Props for radio groups
1280
+ *
1281
+ * **Array Field Helpers:**
1282
+ * - `arrayHelpers(field)` - Get helpers for managing array fields (push, remove, swap, etc.)
1283
+ *
1284
+ * @example
1285
+ * // Basic usage with validation
1286
+ * const form = useForm(userValidator, {
1287
+ * initialValues: { name: "", email: "", age: 0 },
1288
+ * onSubmit: async (values) => {
1289
+ * await api.createUser(values);
1290
+ * },
1291
+ * validationMode: "live"
1292
+ * });
1293
+ *
1294
+ * @example
1295
+ * // Render with native HTML elements
1296
+ * <form onSubmit={form.handleSubmit}>
1297
+ * <input type="text" {...form.getFieldProps("name")} />
1298
+ * {form.touched.name && form.errors.name && <span>{form.errors.name}</span>}
1299
+ *
1300
+ * <input type="email" {...form.getFieldProps("email")} />
1301
+ * {form.touched.email && form.errors.email && <span>{form.errors.email}</span>}
1302
+ *
1303
+ * <button type="submit" disabled={!form.isValid || form.isSubmitting}>
1304
+ * {form.isSubmitting ? "Submitting..." : "Submit"}
1305
+ * </button>
1306
+ * </form>
1307
+ *
1308
+ * @example
1309
+ * // Handle server errors
1310
+ * const form = useForm(userValidator, {
1311
+ * onSubmit: async (values) => {
1312
+ * const response = await api.createUser(values);
1313
+ * if (!response.ok) {
1314
+ * const errors = await response.json();
1315
+ * form.setServerErrors(errors);
1316
+ * }
1317
+ * }
1318
+ * });
1319
+ *
1320
+ * @example
1321
+ * // Working with arrays
1322
+ * const form = useForm(contactsValidator, {
1323
+ * initialValues: { contacts: [] }
1324
+ * });
1325
+ *
1326
+ * const contactsHelpers = form.arrayHelpers("contacts");
1327
+ * return (
1328
+ * <div>
1329
+ * {contactsHelpers.values.map((_, index) => (
1330
+ * <div key={index}>
1331
+ * <input {...contactsHelpers.getFieldProps(index, "name")} />
1332
+ * <input {...contactsHelpers.getFieldProps(index, "email")} />
1333
+ * <button onClick={() => contactsHelpers.remove(index)}>Remove</button>
1334
+ * </div>
1335
+ * ))}
1336
+ * <button onClick={() => contactsHelpers.push({ name: "", email: "" })}>
1337
+ * Add Contact
1338
+ * </button>
1339
+ * </div>
1340
+ * );
1341
+ */
1342
+ const useForm = (validatorOrSchema, options) => {
1343
+ const { initialValues, onSubmit, validationMode, fieldValidators, onValuesChange, onFieldChange } = options;
1344
+ const validator = useMemo(() => isStandardSchema(validatorOrSchema) ? fromStandardSchema(validatorOrSchema) : validatorOrSchema, [validatorOrSchema]);
1345
+ const mode = validationMode ?? "live";
1346
+ const validateOnChange = mode === "live";
1347
+ const validateOnBlur = mode === "live" || mode === "blur";
1348
+ const validateOnMount = mode === "mount";
1349
+ const touchOnChange = mode === "live";
1350
+ const reducerFn = useCallback((state, action) => formReducer(state, action, initialValues), [initialValues]);
1351
+ const [formState, dispatch] = useReducer(reducerFn, {
1352
+ values: initialValues,
1353
+ touched: {},
1354
+ clientErrors: {},
1355
+ serverErrors: {},
1356
+ fieldErrors: {},
1357
+ validatingFields: {},
1358
+ isSubmitting: false,
1359
+ isFormValidating: false,
1360
+ submitCount: 0,
1361
+ isDirty: false
1362
+ });
1363
+ const formStateRef = useRef(formState);
1364
+ useEffect(() => {
1365
+ formStateRef.current = formState;
1366
+ });
1367
+ const pendingValuesRef = useRef(null);
1368
+ const onValuesChangeRef = useRef(onValuesChange);
1369
+ useEffect(() => {
1370
+ onValuesChangeRef.current = onValuesChange;
1371
+ });
1372
+ const prevValuesRef = useRef(formState.values);
1373
+ useEffect(() => {
1374
+ onValuesChangeRef.current?.(formState.values, prevValuesRef.current);
1375
+ prevValuesRef.current = formState.values;
1376
+ }, [formState.values]);
1377
+ const onFieldChangeRef = useRef(onFieldChange);
1378
+ useEffect(() => {
1379
+ onFieldChangeRef.current = onFieldChange;
1380
+ });
1381
+ const validationSeqRef = useRef(0);
1382
+ const fieldValidationSeqRef = useRef({});
1383
+ const isHandlingSubmitRef = useRef(false);
1384
+ const errors = useMemo(() => {
1385
+ const combined = {};
1386
+ Object.entries(formState.clientErrors).forEach(([path, msg]) => {
1387
+ combined[path] = msg;
1388
+ });
1389
+ Object.entries(formState.fieldErrors).forEach(([path, msg]) => {
1390
+ combined[path] = msg;
1391
+ });
1392
+ Object.entries(formState.serverErrors).forEach(([path, msg]) => {
1393
+ combined[path] = msg;
1394
+ });
1395
+ return combined;
1396
+ }, [
1397
+ formState.clientErrors,
1398
+ formState.fieldErrors,
1399
+ formState.serverErrors
1400
+ ]);
1401
+ const isValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
1402
+ const isValidating = useMemo(() => formState.isFormValidating || Object.keys(formState.validatingFields).length > 0, [formState.isFormValidating, formState.validatingFields]);
1403
+ /**
1404
+ * Dispatches the validation result to update client errors.
1405
+ * Shared by both sync and async validation paths.
1406
+ */
1407
+ const dispatchValidationResult = useCallback((result) => {
1408
+ if (isErr(result)) dispatch({
1409
+ type: "SET_CLIENT_ERRORS",
1410
+ errors: formatErrors(result.error)
1411
+ });
1412
+ else dispatch({
1413
+ type: "SET_CLIENT_ERRORS",
1414
+ errors: {}
1415
+ });
1416
+ }, []);
1417
+ /**
1418
+ * Validates the current form values using the Railway-oriented validator and updates error state.
1419
+ * Accepts both sync and async validators (MaybeAsyncValidator).
1420
+ *
1421
+ * - When the validator is sync, returns `Result<TValues, ValidationError[]>` immediately.
1422
+ * - When the validator is async, returns `Promise<Result<TValues, ValidationError[]>>`.
1423
+ * A sequence counter protects against race conditions: only the latest async validation
1424
+ * result dispatches state updates.
1425
+ *
1426
+ * @param values - The form values to validate (usually form.values)
1427
+ * @returns Railway Result or Promise<Result> depending on the validator
1428
+ */
1429
+ const validateForm = useCallback((values) => {
1430
+ const validationResult = validate(values, validator);
1431
+ if (validationResult instanceof Promise) {
1432
+ const seq = ++validationSeqRef.current;
1433
+ dispatch({
1434
+ type: "SET_FORM_VALIDATING",
1435
+ isFormValidating: true
1436
+ });
1437
+ return validationResult.then((result) => {
1438
+ if (seq === validationSeqRef.current) {
1439
+ dispatchValidationResult(result);
1440
+ dispatch({
1441
+ type: "SET_FORM_VALIDATING",
1442
+ isFormValidating: false
1443
+ });
1444
+ }
1445
+ return result;
1446
+ });
1447
+ }
1448
+ dispatchValidationResult(validationResult);
1449
+ return validationResult;
1450
+ }, [validator, dispatchValidationResult]);
1451
+ /**
1452
+ * Runs a single field's validator with per-field race condition protection.
1453
+ * Only runs when the field has a registered fieldValidator.
1454
+ */
1455
+ const runFieldValidator = useCallback((field, values) => {
1456
+ const validatorFn = fieldValidators?.[field];
1457
+ if (!validatorFn) return;
1458
+ dispatch({
1459
+ type: "SET_FIELD_ERROR",
1460
+ field,
1461
+ error: void 0
1462
+ });
1463
+ const result = validatorFn(getValueByPath(values, field), values);
1464
+ if (result instanceof Promise) {
1465
+ const seqKey = normalizePath(field);
1466
+ if (!fieldValidationSeqRef.current[seqKey]) fieldValidationSeqRef.current[seqKey] = 0;
1467
+ const seq = ++fieldValidationSeqRef.current[seqKey];
1468
+ dispatch({
1469
+ type: "SET_FIELD_VALIDATING",
1470
+ field,
1471
+ isValidating: true
1472
+ });
1473
+ result.then((error) => {
1474
+ if (seq === fieldValidationSeqRef.current[seqKey]) {
1475
+ dispatch({
1476
+ type: "SET_FIELD_ERROR",
1477
+ field,
1478
+ error
1479
+ });
1480
+ dispatch({
1481
+ type: "SET_FIELD_VALIDATING",
1482
+ field,
1483
+ isValidating: false
1484
+ });
1485
+ }
1486
+ });
1487
+ } else dispatch({
1488
+ type: "SET_FIELD_ERROR",
1489
+ field,
1490
+ error: result
1491
+ });
1492
+ }, [fieldValidators]);
1493
+ /**
1494
+ * Runs schema validation followed by field-level validation for a single field.
1495
+ * If the schema produces an error for the field, the field validator is skipped.
1496
+ */
1497
+ const runValidationPipeline = useCallback((field, values) => {
1498
+ const currentErrors = formStateRef.current.clientErrors;
1499
+ if (Object.keys(currentErrors).some((p) => isPathAffected(p, field))) {
1500
+ const cleaned = { ...currentErrors };
1501
+ Object.keys(cleaned).forEach((p) => {
1502
+ if (isPathAffected(p, field)) delete cleaned[p];
1503
+ });
1504
+ dispatch({
1505
+ type: "SET_CLIENT_ERRORS",
1506
+ errors: cleaned
1507
+ });
1508
+ }
1509
+ const schemaResult = validateForm(values);
1510
+ if (fieldValidators?.[field]) {
1511
+ const afterSchema = (result) => {
1512
+ if (!(isErr(result) ? normalizePathKeys(formatErrors(result.error)) : {})[normalizePath(field)]) runFieldValidator(field, values);
1513
+ else {
1514
+ dispatch({
1515
+ type: "SET_FIELD_ERROR",
1516
+ field,
1517
+ error: void 0
1518
+ });
1519
+ dispatch({
1520
+ type: "SET_FIELD_VALIDATING",
1521
+ field,
1522
+ isValidating: false
1523
+ });
1524
+ }
1525
+ };
1526
+ if (schemaResult instanceof Promise) schemaResult.then(afterSchema);
1527
+ else afterSchema(schemaResult);
1528
+ }
1529
+ }, [
1530
+ validateForm,
1531
+ fieldValidators,
1532
+ runFieldValidator
1533
+ ]);
1534
+ const didMountRef = useRef(false);
1535
+ useEffect(() => {
1536
+ if (validateOnMount && !didMountRef.current) {
1537
+ didMountRef.current = true;
1538
+ validateForm(initialValues);
1539
+ const allFields = collectFieldPaths(initialValues);
1540
+ dispatch({
1541
+ type: "MARK_ALL_TOUCHED",
1542
+ fields: allFields
1543
+ });
1544
+ }
1545
+ }, [
1546
+ initialValues,
1547
+ validateForm,
1548
+ validateOnMount
1549
+ ]);
1550
+ /**
1551
+ * Updates a single field value and optionally triggers validation.
1552
+ * Automatically marks the field as touched (in "live" mode) and clears related server errors.
1553
+ *
1554
+ * @template TValue - The type of the value being set
1555
+ * @param field - The field path (supports dot notation and bracket notation)
1556
+ * @param value - The new value for the field
1557
+ * @param shouldValidate - Whether to trigger validation after update (default: depends on validationMode)
1558
+ *
1559
+ * @example
1560
+ * // Update a field programmatically
1561
+ * form.setFieldValue("email", "user@example.com");
1562
+ *
1563
+ * @example
1564
+ * // Update without triggering validation
1565
+ * form.setFieldValue("username", "newuser", false);
1566
+ *
1567
+ * @example
1568
+ * // Update nested field
1569
+ * form.setFieldValue("address.city", "San Francisco");
1570
+ *
1571
+ * @example
1572
+ * // Use in a custom input handler
1573
+ * const handleCustomChange = (value: string) => {
1574
+ * const formatted = value.toUpperCase();
1575
+ * form.setFieldValue("code", formatted);
1576
+ * };
1577
+ */
1578
+ const setFieldValue = useCallback((field, value, shouldValidate = validateOnChange) => {
1579
+ const baseValues = pendingValuesRef.current ?? formStateRef.current.values;
1580
+ const updatedValues = setValueByPath(baseValues, field, value);
1581
+ pendingValuesRef.current = updatedValues;
1582
+ onFieldChangeRef.current?.(field, value, updatedValues);
1583
+ pendingValuesRef.current = null;
1584
+ dispatch({
1585
+ type: "SET_FIELD_VALUE",
1586
+ field,
1587
+ value
1588
+ });
1589
+ if (touchOnChange && !formStateRef.current.touched[normalizePath(field)]) dispatch({
1590
+ type: "SET_FIELD_TOUCHED",
1591
+ field,
1592
+ isTouched: true
1593
+ });
1594
+ if (shouldValidate) runValidationPipeline(field, updatedValues);
1595
+ }, [
1596
+ validateOnChange,
1597
+ touchOnChange,
1598
+ runValidationPipeline
1599
+ ]);
1600
+ /**
1601
+ * Updates multiple field values simultaneously and optionally triggers validation.
1602
+ * More efficient than calling setFieldValue multiple times when updating several fields.
1603
+ * Automatically clears server errors for affected fields.
1604
+ *
1605
+ * @param newValues - Partial object containing the fields to update
1606
+ * @param shouldValidate - Whether to trigger validation after update (default: depends on validationMode)
1607
+ *
1608
+ * @example
1609
+ * // Update multiple fields at once
1610
+ * form.setValues({
1611
+ * firstName: "John",
1612
+ * lastName: "Doe",
1613
+ * email: "john@example.com"
1614
+ * });
1615
+ *
1616
+ * @example
1617
+ * // Update without validation
1618
+ * form.setValues({ theme: "dark", language: "en" }, false);
1619
+ *
1620
+ * @example
1621
+ * // Populate form from API response
1622
+ * const loadUser = async (id: string) => {
1623
+ * const user = await api.getUser(id);
1624
+ * form.setValues(user);
1625
+ * };
1626
+ */
1627
+ const setValues = useCallback((newValues, shouldValidate = validateOnChange) => {
1628
+ dispatch({
1629
+ type: "SET_VALUES",
1630
+ values: newValues
1631
+ });
1632
+ if (shouldValidate) {
1633
+ const updatedValues = deepMerge(formState.values, newValues);
1634
+ validateForm(updatedValues);
1635
+ }
1636
+ }, [
1637
+ formState.values,
1638
+ validateOnChange,
1639
+ validateForm
1640
+ ]);
1641
+ /**
1642
+ * Marks a field as touched or untouched and optionally triggers validation.
1643
+ * Touched fields typically display their validation errors to the user.
1644
+ *
1645
+ * @param field - The field path to mark
1646
+ * @param isTouched - Whether the field should be marked as touched (default: true)
1647
+ * @param shouldValidate - Whether to trigger validation after update (default: depends on validationMode)
1648
+ *
1649
+ * @example
1650
+ * // Mark a field as touched (will show validation errors)
1651
+ * form.setFieldTouched("email");
1652
+ *
1653
+ * @example
1654
+ * // Mark as untouched (hide validation errors)
1655
+ * form.setFieldTouched("password", false);
1656
+ *
1657
+ * @example
1658
+ * // Use in custom blur handler
1659
+ * const handleCustomBlur = () => {
1660
+ * form.setFieldTouched("username", true);
1661
+ * // Additional custom logic
1662
+ * };
1663
+ */
1664
+ const setFieldTouched = useCallback((field, isTouched = true, shouldValidate = validateOnBlur) => {
1665
+ dispatch({
1666
+ type: "SET_FIELD_TOUCHED",
1667
+ field,
1668
+ isTouched
1669
+ });
1670
+ if (shouldValidate) {
1671
+ if (!validateOnChange) runValidationPipeline(field, formState.values);
1672
+ else if (!formState.touched[normalizePath(field)]) validateForm(formState.values);
1673
+ }
1674
+ }, [
1675
+ formState.values,
1676
+ formState.touched,
1677
+ validateOnBlur,
1678
+ validateOnChange,
1679
+ validateForm,
1680
+ runValidationPipeline
1681
+ ]);
1682
+ /**
1683
+ * Sets server-side validation errors received from API responses.
1684
+ * These errors take precedence over client-side errors in the merged `errors` object.
1685
+ * Server errors are automatically cleared when the related field value changes.
1686
+ *
1687
+ * @param serverErrors - Map of field paths to error messages from server
1688
+ *
1689
+ * @example
1690
+ * // Handle server validation errors
1691
+ * const form = useForm(userValidator, {
1692
+ * onSubmit: async (values) => {
1693
+ * const response = await fetch("/api/users", {
1694
+ * method: "POST",
1695
+ * body: JSON.stringify(values)
1696
+ * });
1697
+ *
1698
+ * if (!response.ok) {
1699
+ * const errors = await response.json();
1700
+ * form.setServerErrors({
1701
+ * "email": "Email already taken",
1702
+ * "username": "Username not available"
1703
+ * });
1704
+ * return;
1705
+ * }
1706
+ * }
1707
+ * });
1708
+ *
1709
+ * @example
1710
+ * // Set a single server error
1711
+ * form.setServerErrors({ "email": "This email is already registered" });
1712
+ */
1713
+ const setServerErrors = useCallback((serverErrors) => {
1714
+ dispatch({
1715
+ type: "SET_SERVER_ERRORS",
1716
+ errors: serverErrors
1717
+ });
1718
+ }, []);
1719
+ /**
1720
+ * Clears all server-side validation errors.
1721
+ * Client-side validation errors are not affected.
1722
+ * Server errors are also automatically cleared when field values change.
1723
+ *
1724
+ * @example
1725
+ * // Clear server errors when user starts editing
1726
+ * const handleRetry = () => {
1727
+ * form.clearServerErrors();
1728
+ * // User can now resubmit
1729
+ * };
1730
+ *
1731
+ * @example
1732
+ * // Clear before resubmitting
1733
+ * const handleResubmit = () => {
1734
+ * form.clearServerErrors();
1735
+ * form.handleSubmit();
1736
+ * };
1737
+ */
1738
+ const clearServerErrors = useCallback(() => {
1739
+ dispatch({ type: "CLEAR_SERVER_ERRORS" });
1740
+ }, []);
1741
+ /**
1742
+ * Handles form submission using the Railway-oriented programming pattern.
1743
+ * Validates all fields, marks them as touched, and calls onSubmit if validation passes.
1744
+ * Returns a Promise that resolves to either the validated data or validation errors.
1745
+ *
1746
+ * @param e - Optional form event (will preventDefault if provided)
1747
+ * @returns Promise<Result<TValues, ValidationError[]>> - Railway Result with validated data or errors
1748
+ *
1749
+ * @example
1750
+ * // Use in form element
1751
+ * <form onSubmit={form.handleSubmit}>
1752
+ * <input {...form.getFieldProps("email")} />
1753
+ * <button type="submit">Submit</button>
1754
+ * </form>
1755
+ *
1756
+ * @example
1757
+ * // Use in button click handler
1758
+ * <button onClick={form.handleSubmit}>
1759
+ * Save Changes
1760
+ * </button>
1761
+ *
1762
+ * @example
1763
+ * // Handle result programmatically with Railway pattern
1764
+ * import { match } from "@railway-ts/pipelines/result";
1765
+ *
1766
+ * const handleSave = async () => {
1767
+ * const result = await form.handleSubmit();
1768
+ * match(result, {
1769
+ * ok: (values) => {
1770
+ * console.log("Form submitted:", values);
1771
+ * navigate("/success");
1772
+ * },
1773
+ * err: (errors) => {
1774
+ * console.error("Validation errors:", errors);
1775
+ * },
1776
+ * });
1777
+ * };
1778
+ */
1779
+ const handleSubmit = useCallback(async (e) => {
1780
+ if (e) e.preventDefault();
1781
+ if (isHandlingSubmitRef.current) return err([]);
1782
+ isHandlingSubmitRef.current = true;
1783
+ try {
1784
+ const { values, clientErrors, serverErrors } = formStateRef.current;
1785
+ const valuePaths = collectFieldPaths(values);
1786
+ const allPaths = Array.from(/* @__PURE__ */ new Set([
1787
+ ...valuePaths,
1788
+ ...Object.keys(clientErrors),
1789
+ ...Object.keys(serverErrors)
1790
+ ]));
1791
+ dispatch({
1792
+ type: "MARK_ALL_TOUCHED",
1793
+ fields: allPaths
1794
+ });
1795
+ dispatch({ type: "INCREMENT_SUBMIT_COUNT" });
1796
+ dispatch({ type: "CLEAR_SERVER_ERRORS" });
1797
+ ++validationSeqRef.current;
1798
+ dispatch({
1799
+ type: "SET_FORM_VALIDATING",
1800
+ isFormValidating: true
1801
+ });
1802
+ const validationResult = await validate(values, validator);
1803
+ dispatch({
1804
+ type: "SET_FORM_VALIDATING",
1805
+ isFormValidating: false
1806
+ });
1807
+ return match(validationResult, {
1808
+ ok: async (validData) => {
1809
+ dispatch({
1810
+ type: "SET_SUBMITTING",
1811
+ isSubmitting: true
1812
+ });
1813
+ if (fieldValidators) {
1814
+ const fieldEntries = Object.entries(fieldValidators);
1815
+ const fieldResults = await Promise.all(fieldEntries.map(async ([field, validatorFn]) => {
1816
+ const error = await validatorFn(getValueByPath(values, field), values);
1817
+ if (error) dispatch({
1818
+ type: "SET_FIELD_ERROR",
1819
+ field,
1820
+ error
1821
+ });
1822
+ else dispatch({
1823
+ type: "SET_FIELD_ERROR",
1824
+ field,
1825
+ error: void 0
1826
+ });
1827
+ return {
1828
+ field,
1829
+ error
1830
+ };
1831
+ }));
1832
+ if (fieldResults.some((r) => r.error)) {
1833
+ dispatch({
1834
+ type: "SET_SUBMITTING",
1835
+ isSubmitting: false
1836
+ });
1837
+ return err(fieldResults.filter((r) => r.error).map((r) => ({
1838
+ path: [r.field],
1839
+ message: r.error
1840
+ })));
1841
+ }
1842
+ }
1843
+ if (onSubmit) try {
1844
+ await onSubmit(validData);
1845
+ } catch (error) {
1846
+ console.error("Form submission error:", error);
1847
+ }
1848
+ dispatch({
1849
+ type: "SET_SUBMITTING",
1850
+ isSubmitting: false
1851
+ });
1852
+ return ok(validData);
1853
+ },
1854
+ err: (errors) => {
1855
+ dispatch({
1856
+ type: "SET_CLIENT_ERRORS",
1857
+ errors: formatErrors(errors)
1858
+ });
1859
+ return Promise.resolve(err(errors));
1860
+ }
1861
+ });
1862
+ } finally {
1863
+ isHandlingSubmitRef.current = false;
1864
+ }
1865
+ }, [
1866
+ validator,
1867
+ onSubmit,
1868
+ fieldValidators
1869
+ ]);
1870
+ /**
1871
+ * Resets the form to its initial state.
1872
+ * Clears all values (back to initialValues), errors, and touched state.
1873
+ * If validationMode is "mount", triggers validation after reset.
1874
+ *
1875
+ * @example
1876
+ * // Reset after successful submission
1877
+ * const form = useForm(userValidator, {
1878
+ * onSubmit: async (values) => {
1879
+ * await api.createUser(values);
1880
+ * form.resetForm(); // Clear form after success
1881
+ * }
1882
+ * });
1883
+ *
1884
+ * @example
1885
+ * // Cancel button
1886
+ * <button type="button" onClick={form.resetForm}>
1887
+ * Cancel
1888
+ * </button>
1889
+ *
1890
+ * @example
1891
+ * // Reset with confirmation
1892
+ * const handleReset = () => {
1893
+ * if (form.isDirty && !confirm("Discard changes?")) {
1894
+ * return;
1895
+ * }
1896
+ * form.resetForm();
1897
+ * };
1898
+ */
1899
+ const resetForm = useCallback(() => {
1900
+ dispatch({ type: "RESET_FORM" });
1901
+ if (validateOnMount) validateForm(initialValues);
1902
+ }, [
1903
+ initialValues,
1904
+ validateForm,
1905
+ validateOnMount
1906
+ ]);
1907
+ /**
1908
+ * Returns the error message for a field path, gated on user interaction.
1909
+ *
1910
+ * - Leaf paths: returns the error iff the field itself has been touched.
1911
+ * - Group / parent paths: returns the error iff *any* descendant field has
1912
+ * been touched. This makes cross-field validation errors that schemas
1913
+ * attach to a non-leaf path (e.g. `S.refineAt("confirm", v => v.password
1914
+ * === v.confirm, …)` or `S.refineAt("r2", …)` over a tuple) surface
1915
+ * naturally on the group container, without callers having to read
1916
+ * `form.errors` and `form.touched` directly.
1917
+ *
1918
+ * Eliminates the common `touched[field] ? errors[field] : undefined`
1919
+ * boilerplate and removes the leaf-only constraint that previously hid
1920
+ * group-level errors.
1921
+ *
1922
+ * @template TField - The field path type (auto-inferred with autocomplete)
1923
+ * @param field - The field path (with type-safe autocomplete)
1924
+ * @returns The error message string if visible per the rules above, otherwise `undefined`
1925
+ *
1926
+ * @example
1927
+ * // Leaf:
1928
+ * {form.getFieldError("email") && <span>{form.getFieldError("email")}</span>}
1929
+ *
1930
+ * @example
1931
+ * // Group — schema has `refineAt("r2", v => !equal(v.r1, v.r2), "must differ")`:
1932
+ * {form.getFieldError("r2") && <Banner msg={form.getFieldError("r2")} />}
1933
+ */
1934
+ const getFieldError = useCallback((field) => {
1935
+ const key = normalizePath(field);
1936
+ const err = errors[key];
1937
+ if (!err) return void 0;
1938
+ for (const touchedKey in formState.touched) if (formState.touched[touchedKey] && isPathAffected(touchedKey, key)) return err;
1939
+ }, [formState.touched, errors]);
1940
+ /**
1941
+ * Returns a stable HTML element ID for a field, without creating onChange/onBlur handlers.
1942
+ * Useful for linking `<label htmlFor>` to an input without calling a full props factory.
1943
+ *
1944
+ * @template TField - The field path type (auto-inferred with autocomplete)
1945
+ * @param field - The field path (with type-safe autocomplete)
1946
+ * @param optionValue - Optional value for checkbox group / radio group options
1947
+ * @returns The element ID string (field path, or `field-optionValue` for options)
1948
+ *
1949
+ * @example
1950
+ * <label htmlFor={form.getFieldId('username')}>Username</label>
1951
+ * <input {...form.getFieldProps('username')} />
1952
+ *
1953
+ * @example
1954
+ * <label htmlFor={form.getFieldId('contacts', 'email')}>Email</label>
1955
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps('contacts', 'email')} />
1956
+ */
1957
+ const getFieldId = useCallback((field, optionValue) => {
1958
+ return optionValue !== void 0 ? `${field}-${String(optionValue)}` : field;
1959
+ }, []);
1960
+ /**
1961
+ * Returns props to bind a native text input, email input, or textarea to a form field.
1962
+ * Provides type-safe autocomplete for valid field paths.
1963
+ * The returned object can be spread directly onto native HTML elements.
1964
+ *
1965
+ * @template TField - The field path type (auto-inferred with autocomplete)
1966
+ * @param field - The field path (with type-safe autocomplete)
1967
+ * @returns NativeFieldProps - Object with id, name, value, onChange, onBlur
1968
+ *
1969
+ * @example
1970
+ * // Text input
1971
+ * <input type="text" {...form.getFieldProps("username")} placeholder="Username" />
1972
+ *
1973
+ * @example
1974
+ * // Email input
1975
+ * <input type="email" {...form.getFieldProps("email")} required />
1976
+ *
1977
+ * @example
1978
+ * // Textarea
1979
+ * <textarea {...form.getFieldProps("bio")} rows={4} />
1980
+ *
1981
+ * @example
1982
+ * // Nested field
1983
+ * <input type="text" {...form.getFieldProps("address.city")} />
1984
+ */
1985
+ const getFieldProps = useCallback((field) => {
1986
+ return createNativeFieldProps(field, formState.values, setFieldValue, setFieldTouched);
1987
+ }, [
1988
+ formState.values,
1989
+ setFieldValue,
1990
+ setFieldTouched
1991
+ ]);
1992
+ /**
1993
+ * Returns props to bind a native select element to a form field.
1994
+ * Provides type-safe autocomplete for valid field paths.
1995
+ *
1996
+ * @template TField - The field path type (auto-inferred with autocomplete)
1997
+ * @param field - The field path (with type-safe autocomplete)
1998
+ * @returns NativeSelectProps - Object with id, name, value, onChange, onBlur
1999
+ *
2000
+ * @example
2001
+ * <select {...form.getSelectFieldProps("country")}>
2002
+ * <option value="">Select a country</option>
2003
+ * <option value="US">United States</option>
2004
+ * <option value="CA">Canada</option>
2005
+ * </select>
2006
+ */
2007
+ const getSelectFieldProps = useCallback((field) => {
2008
+ return createNativeSelectFieldProps(field, formState.values, setFieldValue, setFieldTouched);
2009
+ }, [
2010
+ formState.values,
2011
+ setFieldValue,
2012
+ setFieldTouched
2013
+ ]);
2014
+ /**
2015
+ * Returns props to bind a native checkbox input to a boolean form field.
2016
+ * Provides type-safe autocomplete for valid field paths.
2017
+ *
2018
+ * @template TField - The field path type (auto-inferred with autocomplete)
2019
+ * @param field - The field path (with type-safe autocomplete)
2020
+ * @returns NativeCheckboxProps - Object with id, name, checked, onChange, onBlur
2021
+ *
2022
+ * @example
2023
+ * <label>
2024
+ * <input type="checkbox" {...form.getCheckboxProps("acceptTerms")} />
2025
+ * I accept the terms and conditions
2026
+ * </label>
2027
+ */
2028
+ const getCheckboxProps = useCallback((field) => {
2029
+ return createNativeCheckboxProps(field, formState.values, setFieldValue, setFieldTouched);
2030
+ }, [
2031
+ formState.values,
2032
+ setFieldValue,
2033
+ setFieldTouched
2034
+ ]);
2035
+ /**
2036
+ * Returns props to bind a native switch (checkbox styled as toggle) to a boolean form field.
2037
+ * Provides type-safe autocomplete for valid field paths.
2038
+ *
2039
+ * @template TField - The field path type (auto-inferred with autocomplete)
2040
+ * @param field - The field path (with type-safe autocomplete)
2041
+ * @returns NativeSwitchProps - Object with id, name, checked, onChange, onBlur
2042
+ *
2043
+ * @example
2044
+ * <label className="switch">
2045
+ * <input type="checkbox" {...form.getSwitchProps("settings.darkMode")} />
2046
+ * <span className="slider"></span>
2047
+ * </label>
2048
+ */
2049
+ const getSwitchProps = useCallback((field) => {
2050
+ return createNativeSwitchProps(field, formState.values, setFieldValue, setFieldTouched);
2051
+ }, [
2052
+ formState.values,
2053
+ setFieldValue,
2054
+ setFieldTouched
2055
+ ]);
2056
+ /**
2057
+ * Returns props to bind a native range input to a numeric form field.
2058
+ * Provides type-safe autocomplete for valid field paths.
2059
+ * Note: Native range inputs only support single numeric values, not arrays.
2060
+ *
2061
+ * @template TField - The field path type (auto-inferred with autocomplete)
2062
+ * @param field - The field path (with type-safe autocomplete)
2063
+ * @returns NativeSliderProps - Object with id, name, type, value, onChange, onBlur
2064
+ *
2065
+ * @example
2066
+ * <div>
2067
+ * <label>Volume: {form.values.volume}%</label>
2068
+ * <input type="range" min={0} max={100} {...form.getSliderProps("volume")} />
2069
+ * </div>
2070
+ */
2071
+ const getSliderProps = useCallback((field) => {
2072
+ return createNativeSliderProps(field, formState.values, setFieldValue, setFieldTouched);
2073
+ }, [
2074
+ formState.values,
2075
+ setFieldValue,
2076
+ setFieldTouched
2077
+ ]);
2078
+ /**
2079
+ * Returns props for a single checkbox within a checkbox group bound to an array field.
2080
+ * Checking the box adds the value to the array; unchecking removes it.
2081
+ * Provides type-safe autocomplete for valid field paths.
2082
+ *
2083
+ * @template TField - The field path type (auto-inferred with autocomplete)
2084
+ * @param field - The field path (with type-safe autocomplete)
2085
+ * @param optionValue - The value this checkbox represents
2086
+ * @returns NativeCheckboxGroupOptionProps - Object with id, name, value, checked, onChange, onBlur
2087
+ *
2088
+ * @example
2089
+ * <label>
2090
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "sports")} />
2091
+ * Sports
2092
+ * </label>
2093
+ * <label>
2094
+ * <input type="checkbox" {...form.getCheckboxGroupOptionProps("interests", "music")} />
2095
+ * Music
2096
+ * </label>
2097
+ */
2098
+ const getCheckboxGroupOptionProps = useCallback((field, optionValue) => {
2099
+ return createCheckboxGroupOptionProps(field, optionValue, formState.values, setFieldValue, setFieldTouched);
2100
+ }, [
2101
+ formState.values,
2102
+ setFieldValue,
2103
+ setFieldTouched
2104
+ ]);
2105
+ /**
2106
+ * Returns props to bind a native file input to a form field.
2107
+ * Provides type-safe autocomplete for valid field paths.
2108
+ * Supports both single and multiple file selection.
2109
+ *
2110
+ * @template TField - The field path type (auto-inferred with autocomplete)
2111
+ * @param field - The field path (with type-safe autocomplete)
2112
+ * @returns NativeFileFieldProps - Object with id, name, onChange, onBlur
2113
+ *
2114
+ * @example
2115
+ * // Single file
2116
+ * <input type="file" accept="image/*" {...form.getFileFieldProps("avatar")} />
2117
+ *
2118
+ * @example
2119
+ * // Multiple files
2120
+ * <input type="file" multiple {...form.getFileFieldProps("documents")} />
2121
+ */
2122
+ const getFileFieldProps = useCallback((field) => {
2123
+ return createNativeFileFieldProps(field, formState.values, setFieldValue, setFieldTouched);
2124
+ }, [
2125
+ formState.values,
2126
+ setFieldValue,
2127
+ setFieldTouched
2128
+ ]);
2129
+ /**
2130
+ * Returns props for a single radio button within a radio group bound to a scalar field.
2131
+ * Only one radio button in the group can be selected at a time.
2132
+ * Provides type-safe autocomplete for valid field paths.
2133
+ *
2134
+ * @template TField - The field path type (auto-inferred with autocomplete)
2135
+ * @param field - The field path (with type-safe autocomplete)
2136
+ * @param optionValue - The value this radio button represents
2137
+ * @returns NativeRadioGroupOptionProps - Object with id, name, value, checked, onChange, onBlur
2138
+ *
2139
+ * @example
2140
+ * <label>
2141
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "email")} />
2142
+ * Email
2143
+ * </label>
2144
+ * <label>
2145
+ * <input type="radio" {...form.getRadioGroupOptionProps("contactMethod", "phone")} />
2146
+ * Phone
2147
+ * </label>
2148
+ */
2149
+ const getRadioGroupOptionProps = useCallback((field, optionValue) => {
2150
+ return createRadioGroupOptionProps(field, optionValue, formState.values, setFieldValue, setFieldTouched);
2151
+ }, [
2152
+ formState.values,
2153
+ setFieldValue,
2154
+ setFieldTouched
2155
+ ]);
2156
+ const arrayHelpers = useCallback((field) => {
2157
+ const getFieldPropsAtPath = (path) => createNativeFieldProps(path, formState.values, setFieldValue, setFieldTouched);
2158
+ const getSelectFieldPropsAtPath = (path) => createNativeSelectFieldProps(path, formState.values, setFieldValue, setFieldTouched);
2159
+ const getSliderPropsAtPath = (path) => createNativeSliderProps(path, formState.values, setFieldValue, setFieldTouched);
2160
+ const getCheckboxPropsAtPath = (path) => createNativeCheckboxProps(path, formState.values, setFieldValue, setFieldTouched);
2161
+ const getSwitchPropsAtPath = (path) => createNativeSwitchProps(path, formState.values, setFieldValue, setFieldTouched);
2162
+ const getFileFieldPropsAtPath = (path) => createNativeFileFieldProps(path, formState.values, setFieldValue, setFieldTouched);
2163
+ const getRadioGroupOptionPropsAtPath = (path, opt) => createRadioGroupOptionProps(path, opt, formState.values, setFieldValue, setFieldTouched);
2164
+ const getFieldErrorAtPath = (path) => {
2165
+ const key = normalizePath(path);
2166
+ return formState.touched[key] ? errors[key] : void 0;
2167
+ };
2168
+ const getFieldIdAtPath = (path, optionValue) => optionValue !== void 0 ? `${path}-${String(optionValue)}` : path;
2169
+ const arrayValue = getValueByPath(formState.values, field) || [];
2170
+ return createArrayHelpers(field, arrayValue, setFieldValue, getFieldPropsAtPath, getSelectFieldPropsAtPath, getSliderPropsAtPath, getCheckboxPropsAtPath, getSwitchPropsAtPath, getFileFieldPropsAtPath, getRadioGroupOptionPropsAtPath, getFieldErrorAtPath, getFieldIdAtPath);
2171
+ }, [
2172
+ formState.values,
2173
+ formState.touched,
2174
+ errors,
2175
+ setFieldValue,
2176
+ setFieldTouched
2177
+ ]);
2178
+ return {
2179
+ values: formState.values,
2180
+ touched: formState.touched,
2181
+ errors,
2182
+ clientErrors: formState.clientErrors,
2183
+ serverErrors: formState.serverErrors,
2184
+ fieldErrors: formState.fieldErrors,
2185
+ isSubmitting: formState.isSubmitting,
2186
+ isValidating,
2187
+ validatingFields: formState.validatingFields,
2188
+ isValid,
2189
+ isDirty: formState.isDirty,
2190
+ submitCount: formState.submitCount,
2191
+ getFieldError,
2192
+ getFieldId,
2193
+ setFieldValue,
2194
+ setFieldTouched,
2195
+ setValues,
2196
+ setServerErrors,
2197
+ clearServerErrors,
2198
+ handleSubmit,
2199
+ resetForm,
2200
+ validateForm,
2201
+ getFieldProps,
2202
+ getSelectFieldProps,
2203
+ getCheckboxProps,
2204
+ getSwitchProps,
2205
+ getSliderProps,
2206
+ getCheckboxGroupOptionProps,
2207
+ getFileFieldProps,
2208
+ getRadioGroupOptionProps,
2209
+ arrayHelpers
2210
+ };
1142
2211
  };
2212
+ // src/useDebounce.ts
2213
+ /**
2214
+ * A React hook that debounces a callback function, delaying its execution until after
2215
+ * a specified delay period has elapsed since the last time it was invoked.
2216
+ *
2217
+ * Useful for optimizing performance by limiting the rate at which a function is called,
2218
+ * such as in response to rapid user input or scroll events.
2219
+ *
2220
+ * @template T - The callback function type
2221
+ * @template Params - The parameter types of the callback function
2222
+ * @template Return - The return type of the callback function
2223
+ *
2224
+ * @param callback - The function to debounce
2225
+ * @param delay - The number of milliseconds to delay execution
2226
+ * @returns A debounced version of the callback function that can be called with the same parameters
2227
+ *
2228
+ * @example
2229
+ * // Debounce a search function
2230
+ * const debouncedSearch = useDebounce((query: string) => {
2231
+ * fetchSearchResults(query);
2232
+ * }, 300);
2233
+ *
2234
+ * @example
2235
+ * // Use in an input handler
2236
+ * const handleInputChange = useDebounce((value: string) => {
2237
+ * form.setFieldValue('search', value);
2238
+ * }, 500);
2239
+ */
1143
2240
  function useDebounce(callback, delay) {
1144
- const timeoutRef = useRef(null);
1145
- const callbackRef = useRef(callback);
1146
- useEffect(() => {
1147
- callbackRef.current = callback;
1148
- }, [callback]);
1149
- useEffect(() => {
1150
- return () => {
1151
- if (timeoutRef.current) {
1152
- clearTimeout(timeoutRef.current);
1153
- }
1154
- };
1155
- }, []);
1156
- return useCallback(
1157
- (...args) => {
1158
- if (timeoutRef.current) {
1159
- clearTimeout(timeoutRef.current);
1160
- }
1161
- timeoutRef.current = setTimeout(() => {
1162
- callbackRef.current(...args);
1163
- }, delay);
1164
- },
1165
- [delay]
1166
- );
2241
+ const timeoutRef = useRef(null);
2242
+ const callbackRef = useRef(callback);
2243
+ useEffect(() => {
2244
+ callbackRef.current = callback;
2245
+ }, [callback]);
2246
+ useEffect(() => {
2247
+ return () => {
2248
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
2249
+ };
2250
+ }, []);
2251
+ return useCallback((...args) => {
2252
+ if (timeoutRef.current) clearTimeout(timeoutRef.current);
2253
+ timeoutRef.current = setTimeout(() => {
2254
+ callbackRef.current(...args);
2255
+ }, delay);
2256
+ }, [delay]);
1167
2257
  }
1168
-
1169
2258
  // src/useFormAutoSubmission.ts
1170
- var useFormAutoSubmission = (form, delay = 200) => {
1171
- const { values, isDirty, isValid, validateForm, handleSubmit } = form;
1172
- const lastValidatedRef = useRef(null);
1173
- const debouncedSubmit = useDebounce(() => {
1174
- if (isValid) handleSubmit();
1175
- }, delay);
1176
- useEffect(() => {
1177
- if (!isDirty) return;
1178
- if (deepEqual(values, lastValidatedRef.current)) return;
1179
- lastValidatedRef.current = values;
1180
- const result = validateForm(values);
1181
- if (result instanceof Promise) {
1182
- void result.then((r) => {
1183
- if (r.ok) debouncedSubmit();
1184
- });
1185
- } else if (result.ok) {
1186
- debouncedSubmit();
1187
- }
1188
- }, [values, isDirty, debouncedSubmit, validateForm]);
1189
- return null;
2259
+ /**
2260
+ * A React hook that automatically submits a form when it becomes valid and dirty.
2261
+ * Useful for creating auto-save or live-update form experiences.
2262
+ *
2263
+ * The hook monitors form values and automatically triggers submission when:
2264
+ * 1. The form is dirty (has been modified)
2265
+ * 2. The form is valid (passes all validation rules)
2266
+ * 3. The values have changed since the last validation
2267
+ *
2268
+ * Submission is debounced to avoid excessive API calls during rapid user input.
2269
+ *
2270
+ * @template T - The type of form values
2271
+ *
2272
+ * @param form - A form object containing values, validation state, and submission methods
2273
+ * @param delay - The debounce delay in milliseconds before auto-submitting (default: 200ms)
2274
+ * @returns null (this hook only produces side effects)
2275
+ *
2276
+ * @example
2277
+ * // Auto-submit a preferences form
2278
+ * const form = useForm(preferencesSchema, {
2279
+ * initialValues: { theme: 'light', notifications: true },
2280
+ * onSubmit: async (values) => {
2281
+ * await updateUserPreferences(values);
2282
+ * }
2283
+ * });
2284
+ *
2285
+ * useFormAutoSubmission(form, 500);
2286
+ *
2287
+ * @example
2288
+ * // Auto-save a draft
2289
+ * const form = useForm(draftSchema, {
2290
+ * initialValues: draft,
2291
+ * onSubmit: saveDraft,
2292
+ * validationMode: "live"
2293
+ * });
2294
+ *
2295
+ * useFormAutoSubmission(form);
2296
+ */
2297
+ const useFormAutoSubmission = (form, delay = 200) => {
2298
+ const { values, isDirty, isValid, validateForm, handleSubmit } = form;
2299
+ const lastValidatedRef = useRef(null);
2300
+ const debouncedSubmit = useDebounce(() => {
2301
+ if (isValid) handleSubmit();
2302
+ }, delay);
2303
+ useEffect(() => {
2304
+ if (!isDirty) return;
2305
+ if (deepEqual(values, lastValidatedRef.current)) return;
2306
+ lastValidatedRef.current = values;
2307
+ const result = validateForm(values);
2308
+ if (result instanceof Promise) result.then((r) => {
2309
+ if (r.ok) debouncedSubmit();
2310
+ });
2311
+ else if (result.ok) debouncedSubmit();
2312
+ }, [
2313
+ values,
2314
+ isDirty,
2315
+ debouncedSubmit,
2316
+ validateForm
2317
+ ]);
2318
+ return null;
1190
2319
  };
1191
-
1192
2320
  export { fromStandardSchema, isStandardSchema, useDebounce, useForm, useFormAutoSubmission };
1193
- //# sourceMappingURL=index.mjs.map
2321
+
1194
2322
  //# sourceMappingURL=index.mjs.map