@railway-ts/use-form 0.2.1 → 0.3.0
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/README.md +8 -8
- package/dist/index.d.mts +63 -18
- package/dist/index.mjs +300 -141
- package/dist/index.mjs.map +1 -1
- package/docs/API.md +70 -33
- package/docs/GETTING_STARTED.md +14 -9
- package/docs/RECIPES.md +70 -69
- package/package.json +6 -6
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { err, isErr,
|
|
2
|
-
import { formatErrors, validate } from "@railway-ts/pipelines/schema";
|
|
3
|
-
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
|
|
1
|
+
import { err, isErr, isResult, ok } from "@railway-ts/pipelines/result";
|
|
2
|
+
import { ROOT_ERROR_KEY, formatErrors, validate } from "@railway-ts/pipelines/schema";
|
|
3
|
+
import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react";
|
|
4
4
|
// src/arrayHelpersFactory.ts
|
|
5
5
|
/**
|
|
6
6
|
* Factory function that creates an ArrayHelpers object for managing array fields in forms.
|
|
@@ -483,6 +483,20 @@ const isPathAffected = (path, changePath) => {
|
|
|
483
483
|
return normalizedPath === normalizedChangePath || normalizedPath.startsWith(`${normalizedChangePath}.`);
|
|
484
484
|
};
|
|
485
485
|
/**
|
|
486
|
+
* Checks whether two paths overlap: one is the other, or one contains the other.
|
|
487
|
+
* Symmetric form of {@link isPathAffected}.
|
|
488
|
+
*
|
|
489
|
+
* @param a - First path (dot or bracket notation)
|
|
490
|
+
* @param b - Second path (dot or bracket notation)
|
|
491
|
+
* @returns `true` if either path is affected by a change at the other
|
|
492
|
+
*
|
|
493
|
+
* @example
|
|
494
|
+
* pathsOverlap("address.city", "address"); // true
|
|
495
|
+
* pathsOverlap("address", "address.city"); // true
|
|
496
|
+
* pathsOverlap("address.city", "address.zip"); // false
|
|
497
|
+
*/
|
|
498
|
+
const pathsOverlap = (a, b) => isPathAffected(a, b) || isPathAffected(b, a);
|
|
499
|
+
/**
|
|
486
500
|
* Recursively collects all field paths from a nested object structure.
|
|
487
501
|
* Traverses the entire object tree and generates path strings for every field,
|
|
488
502
|
* including intermediate parent paths, nested objects, and array elements.
|
|
@@ -572,12 +586,42 @@ const deepMerge = (target, source) => {
|
|
|
572
586
|
}
|
|
573
587
|
return result;
|
|
574
588
|
};
|
|
589
|
+
/**
|
|
590
|
+
* Whether an object is a plain object: its prototype is `Object.prototype` or `null`.
|
|
591
|
+
*/
|
|
592
|
+
const isPlainObject = (value) => {
|
|
593
|
+
const proto = Object.getPrototypeOf(value);
|
|
594
|
+
return proto === Object.prototype || proto === null;
|
|
595
|
+
};
|
|
596
|
+
/**
|
|
597
|
+
* Compares two values by content wherever their content is visible, and by identity elsewhere.
|
|
598
|
+
* Used for `isDirty` and for deciding whether a submit repeats the running one.
|
|
599
|
+
*
|
|
600
|
+
* - `Date` and `RegExp` compare by value.
|
|
601
|
+
* - `Blob` and `File` compare by identity. Browsers keep a file's contents out of its fields.
|
|
602
|
+
* - Any other non-plain object with no own enumerable keys compares by identity: `Map`, `Set`,
|
|
603
|
+
* `Temporal` values, and classes with only private fields keep their state where keys can't see it.
|
|
604
|
+
* - Arrays, plain objects and class instances with own fields (such as dayjs values) compare by content.
|
|
605
|
+
*
|
|
606
|
+
* When unsure, it calls two values different. That costs at most an extra save or an
|
|
607
|
+
* "unsaved changes" prompt, where calling them equal could drop a save.
|
|
608
|
+
*
|
|
609
|
+
* @param a - The first value
|
|
610
|
+
* @param b - The second value
|
|
611
|
+
* @returns Whether the two values are equal
|
|
612
|
+
*
|
|
613
|
+
* @example
|
|
614
|
+
* deepEqual({ tags: ["a"] }, { tags: ["a"] }); // true
|
|
615
|
+
* deepEqual(new Date("2024-01-01"), new Date("2024-01-01")); // true
|
|
616
|
+
* deepEqual(new File(["a"], "a.txt"), new File(["a"], "a.txt")); // false: compared by identity
|
|
617
|
+
*/
|
|
575
618
|
const deepEqual = (a, b) => {
|
|
576
619
|
if (Object.is(a, b)) return true;
|
|
577
620
|
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
|
578
621
|
if (a instanceof RegExp && b instanceof RegExp) return a.toString() === b.toString();
|
|
579
622
|
if (a == null || b == null) return false;
|
|
580
623
|
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
624
|
+
if (typeof Blob !== "undefined" && (a instanceof Blob || b instanceof Blob)) return false;
|
|
581
625
|
if (Array.isArray(a)) {
|
|
582
626
|
if (!Array.isArray(b) || a.length !== b.length) return false;
|
|
583
627
|
return a.every((item, i) => deepEqual(item, b[i]));
|
|
@@ -585,6 +629,7 @@ const deepEqual = (a, b) => {
|
|
|
585
629
|
const keysA = Object.keys(a);
|
|
586
630
|
const keysB = Object.keys(b);
|
|
587
631
|
if (keysA.length !== keysB.length) return false;
|
|
632
|
+
if (keysA.length === 0 && !(isPlainObject(a) && isPlainObject(b))) return false;
|
|
588
633
|
return keysA.every((key) => Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]));
|
|
589
634
|
};
|
|
590
635
|
// src/fieldPropsFactory.ts
|
|
@@ -1077,10 +1122,11 @@ const formReducer = (state, action, initialValues) => {
|
|
|
1077
1122
|
const newValues = setValueByPath(state.values, action.field, action.value);
|
|
1078
1123
|
const newServerErrors = { ...state.serverErrors };
|
|
1079
1124
|
Object.keys(newServerErrors).forEach((errorPath) => {
|
|
1080
|
-
if (
|
|
1125
|
+
if (pathsOverlap(errorPath, action.field)) delete newServerErrors[errorPath];
|
|
1081
1126
|
});
|
|
1127
|
+
const { submitError: _submitError, ...rest } = state;
|
|
1082
1128
|
return {
|
|
1083
|
-
...
|
|
1129
|
+
...rest,
|
|
1084
1130
|
values: newValues,
|
|
1085
1131
|
serverErrors: newServerErrors,
|
|
1086
1132
|
isDirty: !deepEqual(newValues, initialValues)
|
|
@@ -1091,11 +1137,12 @@ const formReducer = (state, action, initialValues) => {
|
|
|
1091
1137
|
const newServerErrors = { ...state.serverErrors };
|
|
1092
1138
|
Object.keys(action.values).forEach((field) => {
|
|
1093
1139
|
Object.keys(newServerErrors).forEach((errorPath) => {
|
|
1094
|
-
if (
|
|
1140
|
+
if (pathsOverlap(errorPath, field)) delete newServerErrors[errorPath];
|
|
1095
1141
|
});
|
|
1096
1142
|
});
|
|
1143
|
+
const { submitError: _submitError, ...rest } = state;
|
|
1097
1144
|
return {
|
|
1098
|
-
...
|
|
1145
|
+
...rest,
|
|
1099
1146
|
values: newValues,
|
|
1100
1147
|
serverErrors: newServerErrors,
|
|
1101
1148
|
isDirty: !deepEqual(newValues, initialValues)
|
|
@@ -1112,14 +1159,25 @@ const formReducer = (state, action, initialValues) => {
|
|
|
1112
1159
|
...state,
|
|
1113
1160
|
clientErrors: normalizePathKeys(action.errors)
|
|
1114
1161
|
};
|
|
1115
|
-
case "SET_SERVER_ERRORS":
|
|
1116
|
-
...state
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1162
|
+
case "SET_SERVER_ERRORS": {
|
|
1163
|
+
const { submitError: _submitError, ...rest } = state;
|
|
1164
|
+
return {
|
|
1165
|
+
...rest,
|
|
1166
|
+
serverErrors: normalizePathKeys(action.errors),
|
|
1167
|
+
...action.submitError !== void 0 && { submitError: action.submitError }
|
|
1168
|
+
};
|
|
1169
|
+
}
|
|
1170
|
+
case "SET_SUBMIT_ERROR": return {
|
|
1120
1171
|
...state,
|
|
1121
|
-
|
|
1172
|
+
submitError: action.submitError
|
|
1122
1173
|
};
|
|
1174
|
+
case "CLEAR_SERVER_ERRORS": {
|
|
1175
|
+
const { submitError: _submitError, ...rest } = state;
|
|
1176
|
+
return {
|
|
1177
|
+
...rest,
|
|
1178
|
+
serverErrors: {}
|
|
1179
|
+
};
|
|
1180
|
+
}
|
|
1123
1181
|
case "SET_SUBMITTING": return {
|
|
1124
1182
|
...state,
|
|
1125
1183
|
isSubmitting: action.isSubmitting
|
|
@@ -1225,7 +1283,65 @@ function fromStandardSchema(schema) {
|
|
|
1225
1283
|
return convertResult(result);
|
|
1226
1284
|
};
|
|
1227
1285
|
}
|
|
1286
|
+
// src/submitScheduler.ts
|
|
1287
|
+
/**
|
|
1288
|
+
* Creates a {@link SubmitScheduler}. A double submit of the same values shares one
|
|
1289
|
+
* submission, and an edit made while a submission runs is submitted after it, not dropped.
|
|
1290
|
+
*
|
|
1291
|
+
* @template TValues - The shape of the submitted values
|
|
1292
|
+
* @template TOutcome - What a submission resolves to
|
|
1293
|
+
* @returns A scheduler with no submission running
|
|
1294
|
+
*
|
|
1295
|
+
* @example
|
|
1296
|
+
* const scheduler = createSubmitScheduler<FormValues, SubmitResult>();
|
|
1297
|
+
* const first = scheduler.submit(() => form.values, save);
|
|
1298
|
+
* const again = scheduler.submit(() => form.values, save); // same values: again === first
|
|
1299
|
+
*/
|
|
1300
|
+
const createSubmitScheduler = () => {
|
|
1301
|
+
let running;
|
|
1302
|
+
let followUp;
|
|
1303
|
+
const start = (values, run) => {
|
|
1304
|
+
const promise = run(values);
|
|
1305
|
+
running = {
|
|
1306
|
+
values,
|
|
1307
|
+
promise
|
|
1308
|
+
};
|
|
1309
|
+
const settle = () => {
|
|
1310
|
+
running = void 0;
|
|
1311
|
+
const next = followUp;
|
|
1312
|
+
if (next) {
|
|
1313
|
+
followUp = void 0;
|
|
1314
|
+
next.resolve(start(next.getValues(), next.run));
|
|
1315
|
+
}
|
|
1316
|
+
};
|
|
1317
|
+
promise.then(settle, settle);
|
|
1318
|
+
return promise;
|
|
1319
|
+
};
|
|
1320
|
+
const submit = (getValues, run) => {
|
|
1321
|
+
if (followUp) {
|
|
1322
|
+
followUp.getValues = getValues;
|
|
1323
|
+
followUp.run = run;
|
|
1324
|
+
return followUp.promise;
|
|
1325
|
+
}
|
|
1326
|
+
if (!running) return start(getValues(), run);
|
|
1327
|
+
if (deepEqual(getValues(), running.values)) return running.promise;
|
|
1328
|
+
let resolve;
|
|
1329
|
+
const promise = new Promise((resolvePromise) => {
|
|
1330
|
+
resolve = resolvePromise;
|
|
1331
|
+
});
|
|
1332
|
+
followUp = {
|
|
1333
|
+
promise,
|
|
1334
|
+
resolve,
|
|
1335
|
+
getValues,
|
|
1336
|
+
run
|
|
1337
|
+
};
|
|
1338
|
+
return promise;
|
|
1339
|
+
};
|
|
1340
|
+
return { submit };
|
|
1341
|
+
};
|
|
1228
1342
|
// src/useForm.ts
|
|
1343
|
+
/** The submit error for a submission that threw, or whose `onSubmit` returned neither a `Result` nor nothing. */
|
|
1344
|
+
const SUBMIT_ERROR_MESSAGE = "Something went wrong. Please try again.";
|
|
1229
1345
|
/**
|
|
1230
1346
|
* A powerful React form hook that combines Railway-oriented validation with native HTML support.
|
|
1231
1347
|
* Provides type-safe form state management, automatic validation, error handling, and direct
|
|
@@ -1236,6 +1352,7 @@ function fromStandardSchema(schema) {
|
|
|
1236
1352
|
* provides helpers for working with nested objects and dynamic arrays.
|
|
1237
1353
|
*
|
|
1238
1354
|
* @template TValues - The shape of form values as a record with string keys
|
|
1355
|
+
* @template TResult - The value `handleSubmit` resolves to on success: `onSubmit`'s `ok` value, or the form values
|
|
1239
1356
|
*
|
|
1240
1357
|
* @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
|
|
1241
1358
|
* @param options - Configuration options for form behavior
|
|
@@ -1307,14 +1424,13 @@ function fromStandardSchema(schema) {
|
|
|
1307
1424
|
* </form>
|
|
1308
1425
|
*
|
|
1309
1426
|
* @example
|
|
1310
|
-
* // Handle server errors
|
|
1427
|
+
* // Handle server errors: return err to place them on the form, ok to succeed
|
|
1311
1428
|
* const form = useForm(userValidator, {
|
|
1429
|
+
* initialValues: { name: "", email: "", age: 0 },
|
|
1312
1430
|
* onSubmit: async (values) => {
|
|
1313
1431
|
* const response = await api.createUser(values);
|
|
1314
|
-
* if (!response.ok)
|
|
1315
|
-
*
|
|
1316
|
-
* form.setServerErrors(errors);
|
|
1317
|
-
* }
|
|
1432
|
+
* if (!response.ok) return err((await response.json()) as ValidationError[]);
|
|
1433
|
+
* return ok((await response.json()) as User);
|
|
1318
1434
|
* }
|
|
1319
1435
|
* });
|
|
1320
1436
|
*
|
|
@@ -1381,7 +1497,7 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
1381
1497
|
});
|
|
1382
1498
|
const validationSeqRef = useRef(0);
|
|
1383
1499
|
const fieldValidationSeqRef = useRef({});
|
|
1384
|
-
const
|
|
1500
|
+
const [submitScheduler] = useState(createSubmitScheduler);
|
|
1385
1501
|
const errors = useMemo(() => {
|
|
1386
1502
|
const combined = {};
|
|
1387
1503
|
Object.entries(formState.clientErrors).forEach(([path, msg]) => {
|
|
@@ -1393,13 +1509,23 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
1393
1509
|
Object.entries(formState.serverErrors).forEach(([path, msg]) => {
|
|
1394
1510
|
combined[path] = msg;
|
|
1395
1511
|
});
|
|
1512
|
+
if (formState.submitError !== void 0) combined[ROOT_ERROR_KEY] = formState.submitError;
|
|
1396
1513
|
return combined;
|
|
1397
1514
|
}, [
|
|
1515
|
+
formState.clientErrors,
|
|
1516
|
+
formState.fieldErrors,
|
|
1517
|
+
formState.serverErrors,
|
|
1518
|
+
formState.submitError
|
|
1519
|
+
]);
|
|
1520
|
+
const serverErrors = useMemo(() => formState.submitError === void 0 ? formState.serverErrors : {
|
|
1521
|
+
...formState.serverErrors,
|
|
1522
|
+
[ROOT_ERROR_KEY]: formState.submitError
|
|
1523
|
+
}, [formState.serverErrors, formState.submitError]);
|
|
1524
|
+
const isValid = useMemo(() => Object.keys(formState.clientErrors).length === 0 && Object.keys(formState.fieldErrors).length === 0 && Object.keys(formState.serverErrors).length === 0, [
|
|
1398
1525
|
formState.clientErrors,
|
|
1399
1526
|
formState.fieldErrors,
|
|
1400
1527
|
formState.serverErrors
|
|
1401
1528
|
]);
|
|
1402
|
-
const isValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
|
|
1403
1529
|
const isValidating = useMemo(() => formState.isFormValidating || Object.keys(formState.validatingFields).length > 0, [formState.isFormValidating, formState.validatingFields]);
|
|
1404
1530
|
/**
|
|
1405
1531
|
* Dispatches the validation result to update client errors.
|
|
@@ -1684,37 +1810,39 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
1684
1810
|
* Sets server-side validation errors received from API responses.
|
|
1685
1811
|
* These errors take precedence over client-side errors in the merged `errors` object.
|
|
1686
1812
|
* Server errors are automatically cleared when the related field value changes.
|
|
1813
|
+
* An error at path `[]` becomes the submit error. Every other error's path is marked touched,
|
|
1814
|
+
* so the errors show through `getFieldError` straight away.
|
|
1687
1815
|
*
|
|
1688
|
-
* @param
|
|
1816
|
+
* @param errors - Server validation errors, each with a `path` and a `message`
|
|
1689
1817
|
*
|
|
1690
1818
|
* @example
|
|
1691
|
-
* //
|
|
1692
|
-
*
|
|
1693
|
-
*
|
|
1694
|
-
*
|
|
1695
|
-
*
|
|
1696
|
-
*
|
|
1697
|
-
*
|
|
1698
|
-
*
|
|
1699
|
-
* if (!response.ok) {
|
|
1700
|
-
* const errors = await response.json();
|
|
1701
|
-
* form.setServerErrors({
|
|
1702
|
-
* "email": "Email already taken",
|
|
1703
|
-
* "username": "Username not available"
|
|
1704
|
-
* });
|
|
1705
|
-
* return;
|
|
1706
|
-
* }
|
|
1707
|
-
* }
|
|
1819
|
+
* // Errors that arrive outside onSubmit, such as in a React Query mutation's onError
|
|
1820
|
+
* // (inside onSubmit, return err(errors) instead)
|
|
1821
|
+
* const mutation = useMutation({
|
|
1822
|
+
* mutationFn: api.createUser,
|
|
1823
|
+
* onError: (error) => {
|
|
1824
|
+
* if (error instanceof ApiValidationError) form.setServerErrors(error.fieldErrors);
|
|
1825
|
+
* },
|
|
1708
1826
|
* });
|
|
1709
1827
|
*
|
|
1710
1828
|
* @example
|
|
1711
1829
|
* // Set a single server error
|
|
1712
|
-
* form.setServerErrors({ "email": "This email is already registered" });
|
|
1830
|
+
* form.setServerErrors([{ path: ["email"], message: "This email is already registered" }]);
|
|
1831
|
+
*
|
|
1832
|
+
* @example
|
|
1833
|
+
* // A path [] error is the submit error, shown at errors._root
|
|
1834
|
+
* form.setServerErrors([{ path: [], message: "Service unavailable" }]);
|
|
1713
1835
|
*/
|
|
1714
|
-
const
|
|
1836
|
+
const placeServerErrors = useCallback((errors) => {
|
|
1837
|
+
const { [ROOT_ERROR_KEY]: submitError, ...perPath } = formatErrors(errors);
|
|
1715
1838
|
dispatch({
|
|
1716
1839
|
type: "SET_SERVER_ERRORS",
|
|
1717
|
-
errors:
|
|
1840
|
+
errors: perPath,
|
|
1841
|
+
...submitError !== void 0 && { submitError }
|
|
1842
|
+
});
|
|
1843
|
+
dispatch({
|
|
1844
|
+
type: "MARK_ALL_TOUCHED",
|
|
1845
|
+
fields: Object.keys(perPath)
|
|
1718
1846
|
});
|
|
1719
1847
|
}, []);
|
|
1720
1848
|
/**
|
|
@@ -1740,49 +1868,19 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
1740
1868
|
dispatch({ type: "CLEAR_SERVER_ERRORS" });
|
|
1741
1869
|
}, []);
|
|
1742
1870
|
/**
|
|
1743
|
-
*
|
|
1744
|
-
*
|
|
1745
|
-
*
|
|
1871
|
+
* Runs one submission of the given values: marks every field touched, counts the attempt,
|
|
1872
|
+
* clears server errors, validates, runs the field validators, then calls `onSubmit`.
|
|
1873
|
+
* `handleSubmit` decides when it runs, through the submit scheduler.
|
|
1746
1874
|
*
|
|
1747
|
-
*
|
|
1748
|
-
*
|
|
1749
|
-
*
|
|
1750
|
-
* @example
|
|
1751
|
-
* // Use in form element
|
|
1752
|
-
* <form onSubmit={form.handleSubmit}>
|
|
1753
|
-
* <input {...form.getFieldProps("email")} />
|
|
1754
|
-
* <button type="submit">Submit</button>
|
|
1755
|
-
* </form>
|
|
1875
|
+
* Never rejects. A throw anywhere, or an `onSubmit` value that is neither a `Result` nor nothing,
|
|
1876
|
+
* is logged and resolves to the generic submit error.
|
|
1756
1877
|
*
|
|
1757
|
-
* @
|
|
1758
|
-
*
|
|
1759
|
-
* <button onClick={form.handleSubmit}>
|
|
1760
|
-
* Save Changes
|
|
1761
|
-
* </button>
|
|
1762
|
-
*
|
|
1763
|
-
* @example
|
|
1764
|
-
* // Handle result programmatically with Railway pattern
|
|
1765
|
-
* import { match } from "@railway-ts/pipelines/result";
|
|
1766
|
-
*
|
|
1767
|
-
* const handleSave = async () => {
|
|
1768
|
-
* const result = await form.handleSubmit();
|
|
1769
|
-
* match(result, {
|
|
1770
|
-
* ok: (values) => {
|
|
1771
|
-
* console.log("Form submitted:", values);
|
|
1772
|
-
* navigate("/success");
|
|
1773
|
-
* },
|
|
1774
|
-
* err: (errors) => {
|
|
1775
|
-
* console.error("Validation errors:", errors);
|
|
1776
|
-
* },
|
|
1777
|
-
* });
|
|
1778
|
-
* };
|
|
1878
|
+
* @param values - The form values to submit
|
|
1879
|
+
* @returns Promise<Result<TResult, ValidationError[]>> - `onSubmit`'s Result, the validated data, or errors
|
|
1779
1880
|
*/
|
|
1780
|
-
const
|
|
1781
|
-
if (e) e.preventDefault();
|
|
1782
|
-
if (isHandlingSubmitRef.current) return err([]);
|
|
1783
|
-
isHandlingSubmitRef.current = true;
|
|
1881
|
+
const runSubmission = useCallback(async (values) => {
|
|
1784
1882
|
try {
|
|
1785
|
-
const {
|
|
1883
|
+
const { clientErrors, serverErrors } = formStateRef.current;
|
|
1786
1884
|
const valuePaths = collectFieldPaths(values);
|
|
1787
1885
|
const allPaths = Array.from(/* @__PURE__ */ new Set([
|
|
1788
1886
|
...valuePaths,
|
|
@@ -1800,75 +1898,136 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
1800
1898
|
type: "SET_FORM_VALIDATING",
|
|
1801
1899
|
isFormValidating: true
|
|
1802
1900
|
});
|
|
1803
|
-
|
|
1901
|
+
let validationResult;
|
|
1902
|
+
try {
|
|
1903
|
+
validationResult = await validate(values, validator);
|
|
1904
|
+
} finally {
|
|
1905
|
+
dispatch({
|
|
1906
|
+
type: "SET_FORM_VALIDATING",
|
|
1907
|
+
isFormValidating: false
|
|
1908
|
+
});
|
|
1909
|
+
}
|
|
1910
|
+
if (isErr(validationResult)) {
|
|
1911
|
+
dispatch({
|
|
1912
|
+
type: "SET_CLIENT_ERRORS",
|
|
1913
|
+
errors: formatErrors(validationResult.error)
|
|
1914
|
+
});
|
|
1915
|
+
return validationResult;
|
|
1916
|
+
}
|
|
1917
|
+
const validData = validationResult.value;
|
|
1804
1918
|
dispatch({
|
|
1805
|
-
type: "
|
|
1806
|
-
|
|
1919
|
+
type: "SET_SUBMITTING",
|
|
1920
|
+
isSubmitting: true
|
|
1807
1921
|
});
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
}));
|
|
1833
|
-
if (fieldResults.some((r) => r.error)) {
|
|
1834
|
-
dispatch({
|
|
1835
|
-
type: "SET_SUBMITTING",
|
|
1836
|
-
isSubmitting: false
|
|
1837
|
-
});
|
|
1838
|
-
return err(fieldResults.filter((r) => r.error).map((r) => ({
|
|
1839
|
-
path: [r.field],
|
|
1840
|
-
message: r.error
|
|
1841
|
-
})));
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
if (onSubmit) try {
|
|
1845
|
-
await onSubmit(validData);
|
|
1846
|
-
} catch (error) {
|
|
1847
|
-
console.error("Form submission error:", error);
|
|
1848
|
-
}
|
|
1849
|
-
dispatch({
|
|
1850
|
-
type: "SET_SUBMITTING",
|
|
1851
|
-
isSubmitting: false
|
|
1852
|
-
});
|
|
1853
|
-
return ok(validData);
|
|
1854
|
-
},
|
|
1855
|
-
err: (errors) => {
|
|
1856
|
-
dispatch({
|
|
1857
|
-
type: "SET_CLIENT_ERRORS",
|
|
1858
|
-
errors: formatErrors(errors)
|
|
1859
|
-
});
|
|
1860
|
-
return Promise.resolve(err(errors));
|
|
1922
|
+
try {
|
|
1923
|
+
if (fieldValidators) {
|
|
1924
|
+
const fieldEntries = Object.entries(fieldValidators);
|
|
1925
|
+
const fieldResults = await Promise.all(fieldEntries.map(async ([field, validatorFn]) => {
|
|
1926
|
+
const error = await validatorFn(getValueByPath(values, field), values);
|
|
1927
|
+
if (error) dispatch({
|
|
1928
|
+
type: "SET_FIELD_ERROR",
|
|
1929
|
+
field,
|
|
1930
|
+
error
|
|
1931
|
+
});
|
|
1932
|
+
else dispatch({
|
|
1933
|
+
type: "SET_FIELD_ERROR",
|
|
1934
|
+
field,
|
|
1935
|
+
error: void 0
|
|
1936
|
+
});
|
|
1937
|
+
return {
|
|
1938
|
+
field,
|
|
1939
|
+
error
|
|
1940
|
+
};
|
|
1941
|
+
}));
|
|
1942
|
+
if (fieldResults.some((r) => r.error)) return err(fieldResults.filter((r) => r.error).map((r) => ({
|
|
1943
|
+
path: [r.field],
|
|
1944
|
+
message: r.error
|
|
1945
|
+
})));
|
|
1861
1946
|
}
|
|
1947
|
+
const outcome = onSubmit ? await onSubmit(validData) : void 0;
|
|
1948
|
+
if (outcome === void 0) return ok(validData);
|
|
1949
|
+
if (!isResult(outcome)) throw new TypeError("onSubmit must return a Result or nothing");
|
|
1950
|
+
if (isErr(outcome)) placeServerErrors(outcome.error);
|
|
1951
|
+
return outcome;
|
|
1952
|
+
} finally {
|
|
1953
|
+
dispatch({
|
|
1954
|
+
type: "SET_SUBMITTING",
|
|
1955
|
+
isSubmitting: false
|
|
1956
|
+
});
|
|
1957
|
+
}
|
|
1958
|
+
} catch (error) {
|
|
1959
|
+
console.error("Form submission error:", error);
|
|
1960
|
+
dispatch({
|
|
1961
|
+
type: "SET_SUBMIT_ERROR",
|
|
1962
|
+
submitError: SUBMIT_ERROR_MESSAGE
|
|
1862
1963
|
});
|
|
1863
|
-
|
|
1864
|
-
|
|
1964
|
+
return err([{
|
|
1965
|
+
path: [],
|
|
1966
|
+
message: SUBMIT_ERROR_MESSAGE
|
|
1967
|
+
}]);
|
|
1865
1968
|
}
|
|
1866
1969
|
}, [
|
|
1867
1970
|
validator,
|
|
1868
1971
|
onSubmit,
|
|
1869
|
-
fieldValidators
|
|
1972
|
+
fieldValidators,
|
|
1973
|
+
placeServerErrors
|
|
1870
1974
|
]);
|
|
1871
1975
|
/**
|
|
1976
|
+
* Handles form submission using the Railway-oriented programming pattern.
|
|
1977
|
+
* Validates all fields, marks them as touched, and calls onSubmit if validation passes.
|
|
1978
|
+
* Returns a Promise that resolves to a Result and never rejects:
|
|
1979
|
+
* - `ok` with `onSubmit`'s `ok` value, or with the validated data when `onSubmit` returns nothing or is absent
|
|
1980
|
+
* - `err` with the validation errors, or with `onSubmit`'s `err`, whose errors are placed on their fields
|
|
1981
|
+
* - `err([{ path: [], message: "Something went wrong. Please try again." }])` when the submission throws,
|
|
1982
|
+
* or `onSubmit` returns neither a `Result` nor nothing. This becomes the submit error, and the original
|
|
1983
|
+
* error is logged with `console.error`.
|
|
1984
|
+
*
|
|
1985
|
+
* While a submission is running, a call with the same values shares its Promise, and a call
|
|
1986
|
+
* with changed values submits them once it finishes. Every call with an event calls `preventDefault()`.
|
|
1987
|
+
*
|
|
1988
|
+
* @param e - Optional form event (will preventDefault if provided)
|
|
1989
|
+
* @returns Promise<Result<TResult, ValidationError[]>> - Railway Result with `onSubmit`'s value, the validated data, or errors
|
|
1990
|
+
*
|
|
1991
|
+
* @example
|
|
1992
|
+
* // Use in form element
|
|
1993
|
+
* <form onSubmit={form.handleSubmit}>
|
|
1994
|
+
* <input {...form.getFieldProps("email")} />
|
|
1995
|
+
* <button type="submit">Submit</button>
|
|
1996
|
+
* </form>
|
|
1997
|
+
*
|
|
1998
|
+
* @example
|
|
1999
|
+
* // Use in button click handler
|
|
2000
|
+
* <button onClick={form.handleSubmit}>
|
|
2001
|
+
* Save Changes
|
|
2002
|
+
* </button>
|
|
2003
|
+
*
|
|
2004
|
+
* @example
|
|
2005
|
+
* // onSubmit returns the server's Result, and handleSubmit passes it on
|
|
2006
|
+
* import { match } from "@railway-ts/pipelines/result";
|
|
2007
|
+
*
|
|
2008
|
+
* const form = useForm(userValidator, {
|
|
2009
|
+
* initialValues: { name: "", email: "" },
|
|
2010
|
+
* onSubmit: (values) => api.createUser(values), // Promise<Result<User, ValidationError[]>>
|
|
2011
|
+
* });
|
|
2012
|
+
*
|
|
2013
|
+
* const handleSave = async () => {
|
|
2014
|
+
* const result = await form.handleSubmit();
|
|
2015
|
+
* match(result, {
|
|
2016
|
+
* ok: (user) => {
|
|
2017
|
+
* navigate(`/users/${user.id}`);
|
|
2018
|
+
* },
|
|
2019
|
+
* err: (errors) => {
|
|
2020
|
+
* // Already on the form: field errors under their paths, a path [] error at errors._root
|
|
2021
|
+
* console.warn("Not saved:", errors);
|
|
2022
|
+
* },
|
|
2023
|
+
* });
|
|
2024
|
+
* };
|
|
2025
|
+
*/
|
|
2026
|
+
const handleSubmit = useCallback((e) => {
|
|
2027
|
+
e?.preventDefault();
|
|
2028
|
+
return submitScheduler.submit(() => formStateRef.current.values, runSubmission);
|
|
2029
|
+
}, [submitScheduler, runSubmission]);
|
|
2030
|
+
/**
|
|
1872
2031
|
* Resets the form to its initial state.
|
|
1873
2032
|
* Clears all values (back to initialValues), errors, and touched state.
|
|
1874
2033
|
* If validationMode is "mount", triggers validation after reset.
|
|
@@ -2234,7 +2393,7 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
2234
2393
|
touched: formState.touched,
|
|
2235
2394
|
errors,
|
|
2236
2395
|
clientErrors: formState.clientErrors,
|
|
2237
|
-
serverErrors
|
|
2396
|
+
serverErrors,
|
|
2238
2397
|
fieldErrors: formState.fieldErrors,
|
|
2239
2398
|
isSubmitting: formState.isSubmitting,
|
|
2240
2399
|
isValidating,
|
|
@@ -2247,7 +2406,7 @@ const useForm = (validatorOrSchema, options) => {
|
|
|
2247
2406
|
setFieldValue,
|
|
2248
2407
|
setFieldTouched,
|
|
2249
2408
|
setValues,
|
|
2250
|
-
setServerErrors,
|
|
2409
|
+
setServerErrors: placeServerErrors,
|
|
2251
2410
|
clearServerErrors,
|
|
2252
2411
|
handleSubmit,
|
|
2253
2412
|
resetForm,
|