@railway-ts/use-form 0.2.0 → 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/dist/index.mjs CHANGED
@@ -1,6 +1,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";
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 (isPathAffected(errorPath, action.field)) delete newServerErrors[errorPath];
1125
+ if (pathsOverlap(errorPath, action.field)) delete newServerErrors[errorPath];
1081
1126
  });
1127
+ const { submitError: _submitError, ...rest } = state;
1082
1128
  return {
1083
- ...state,
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 (isPathAffected(errorPath, field)) delete newServerErrors[errorPath];
1140
+ if (pathsOverlap(errorPath, field)) delete newServerErrors[errorPath];
1095
1141
  });
1096
1142
  });
1143
+ const { submitError: _submitError, ...rest } = state;
1097
1144
  return {
1098
- ...state,
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": return {
1116
- ...state,
1117
- serverErrors: normalizePathKeys(action.errors)
1118
- };
1119
- case "CLEAR_SERVER_ERRORS": return {
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
- serverErrors: {}
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
@@ -1182,11 +1240,12 @@ const formReducer = (state, action, initialValues) => {
1182
1240
  };
1183
1241
  // src/standardSchema.ts
1184
1242
  /**
1185
- * Detects whether a value is a Standard Schema v1 object by checking for
1186
- * the `~standard` property with `version === 1`.
1243
+ * Detects whether a value is a Standard Schema v1 schema by checking for
1244
+ * the `~standard` property with `version === 1`. Schemas may be objects
1245
+ * (Zod, Valibot) or callable functions (ArkType).
1187
1246
  */
1188
1247
  function isStandardSchema(value) {
1189
- if (value == null || typeof value !== "object" || !("~standard" in value)) return false;
1248
+ if (value == null || typeof value !== "object" && typeof value !== "function" || !("~standard" in value)) return false;
1190
1249
  const standard = value["~standard"];
1191
1250
  return standard != null && typeof standard === "object" && "version" in standard && standard.version === 1;
1192
1251
  }
@@ -1224,7 +1283,65 @@ function fromStandardSchema(schema) {
1224
1283
  return convertResult(result);
1225
1284
  };
1226
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
+ };
1227
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.";
1228
1345
  /**
1229
1346
  * A powerful React form hook that combines Railway-oriented validation with native HTML support.
1230
1347
  * Provides type-safe form state management, automatic validation, error handling, and direct
@@ -1235,6 +1352,7 @@ function fromStandardSchema(schema) {
1235
1352
  * provides helpers for working with nested objects and dynamic arrays.
1236
1353
  *
1237
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
1238
1356
  *
1239
1357
  * @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
1240
1358
  * @param options - Configuration options for form behavior
@@ -1306,14 +1424,13 @@ function fromStandardSchema(schema) {
1306
1424
  * </form>
1307
1425
  *
1308
1426
  * @example
1309
- * // Handle server errors
1427
+ * // Handle server errors: return err to place them on the form, ok to succeed
1310
1428
  * const form = useForm(userValidator, {
1429
+ * initialValues: { name: "", email: "", age: 0 },
1311
1430
  * onSubmit: async (values) => {
1312
1431
  * const response = await api.createUser(values);
1313
- * if (!response.ok) {
1314
- * const errors = await response.json();
1315
- * form.setServerErrors(errors);
1316
- * }
1432
+ * if (!response.ok) return err((await response.json()) as ValidationError[]);
1433
+ * return ok((await response.json()) as User);
1317
1434
  * }
1318
1435
  * });
1319
1436
  *
@@ -1380,7 +1497,7 @@ const useForm = (validatorOrSchema, options) => {
1380
1497
  });
1381
1498
  const validationSeqRef = useRef(0);
1382
1499
  const fieldValidationSeqRef = useRef({});
1383
- const isHandlingSubmitRef = useRef(false);
1500
+ const [submitScheduler] = useState(createSubmitScheduler);
1384
1501
  const errors = useMemo(() => {
1385
1502
  const combined = {};
1386
1503
  Object.entries(formState.clientErrors).forEach(([path, msg]) => {
@@ -1392,13 +1509,23 @@ const useForm = (validatorOrSchema, options) => {
1392
1509
  Object.entries(formState.serverErrors).forEach(([path, msg]) => {
1393
1510
  combined[path] = msg;
1394
1511
  });
1512
+ if (formState.submitError !== void 0) combined[ROOT_ERROR_KEY] = formState.submitError;
1395
1513
  return combined;
1396
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, [
1397
1525
  formState.clientErrors,
1398
1526
  formState.fieldErrors,
1399
1527
  formState.serverErrors
1400
1528
  ]);
1401
- const isValid = useMemo(() => Object.keys(errors).length === 0, [errors]);
1402
1529
  const isValidating = useMemo(() => formState.isFormValidating || Object.keys(formState.validatingFields).length > 0, [formState.isFormValidating, formState.validatingFields]);
1403
1530
  /**
1404
1531
  * Dispatches the validation result to update client errors.
@@ -1683,37 +1810,39 @@ const useForm = (validatorOrSchema, options) => {
1683
1810
  * Sets server-side validation errors received from API responses.
1684
1811
  * These errors take precedence over client-side errors in the merged `errors` object.
1685
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.
1686
1815
  *
1687
- * @param serverErrors - Map of field paths to error messages from server
1816
+ * @param errors - Server validation errors, each with a `path` and a `message`
1688
1817
  *
1689
1818
  * @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
- * }
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
+ * },
1707
1826
  * });
1708
1827
  *
1709
1828
  * @example
1710
1829
  * // Set a single server error
1711
- * 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" }]);
1712
1835
  */
1713
- const setServerErrors = useCallback((serverErrors) => {
1836
+ const placeServerErrors = useCallback((errors) => {
1837
+ const { [ROOT_ERROR_KEY]: submitError, ...perPath } = formatErrors(errors);
1714
1838
  dispatch({
1715
1839
  type: "SET_SERVER_ERRORS",
1716
- errors: serverErrors
1840
+ errors: perPath,
1841
+ ...submitError !== void 0 && { submitError }
1842
+ });
1843
+ dispatch({
1844
+ type: "MARK_ALL_TOUCHED",
1845
+ fields: Object.keys(perPath)
1717
1846
  });
1718
1847
  }, []);
1719
1848
  /**
@@ -1739,49 +1868,19 @@ const useForm = (validatorOrSchema, options) => {
1739
1868
  dispatch({ type: "CLEAR_SERVER_ERRORS" });
1740
1869
  }, []);
1741
1870
  /**
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.
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.
1745
1874
  *
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>
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.
1755
1877
  *
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
- * };
1878
+ * @param values - The form values to submit
1879
+ * @returns Promise<Result<TResult, ValidationError[]>> - `onSubmit`'s Result, the validated data, or errors
1778
1880
  */
1779
- const handleSubmit = useCallback(async (e) => {
1780
- if (e) e.preventDefault();
1781
- if (isHandlingSubmitRef.current) return err([]);
1782
- isHandlingSubmitRef.current = true;
1881
+ const runSubmission = useCallback(async (values) => {
1783
1882
  try {
1784
- const { values, clientErrors, serverErrors } = formStateRef.current;
1883
+ const { clientErrors, serverErrors } = formStateRef.current;
1785
1884
  const valuePaths = collectFieldPaths(values);
1786
1885
  const allPaths = Array.from(/* @__PURE__ */ new Set([
1787
1886
  ...valuePaths,
@@ -1799,75 +1898,136 @@ const useForm = (validatorOrSchema, options) => {
1799
1898
  type: "SET_FORM_VALIDATING",
1800
1899
  isFormValidating: true
1801
1900
  });
1802
- const validationResult = await validate(values, validator);
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;
1803
1918
  dispatch({
1804
- type: "SET_FORM_VALIDATING",
1805
- isFormValidating: false
1919
+ type: "SET_SUBMITTING",
1920
+ isSubmitting: true
1806
1921
  });
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));
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
+ })));
1860
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
1861
1963
  });
1862
- } finally {
1863
- isHandlingSubmitRef.current = false;
1964
+ return err([{
1965
+ path: [],
1966
+ message: SUBMIT_ERROR_MESSAGE
1967
+ }]);
1864
1968
  }
1865
1969
  }, [
1866
1970
  validator,
1867
1971
  onSubmit,
1868
- fieldValidators
1972
+ fieldValidators,
1973
+ placeServerErrors
1869
1974
  ]);
1870
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
+ /**
1871
2031
  * Resets the form to its initial state.
1872
2032
  * Clears all values (back to initialValues), errors, and touched state.
1873
2033
  * If validationMode is "mount", triggers validation after reset.
@@ -2233,7 +2393,7 @@ const useForm = (validatorOrSchema, options) => {
2233
2393
  touched: formState.touched,
2234
2394
  errors,
2235
2395
  clientErrors: formState.clientErrors,
2236
- serverErrors: formState.serverErrors,
2396
+ serverErrors,
2237
2397
  fieldErrors: formState.fieldErrors,
2238
2398
  isSubmitting: formState.isSubmitting,
2239
2399
  isValidating,
@@ -2246,7 +2406,7 @@ const useForm = (validatorOrSchema, options) => {
2246
2406
  setFieldValue,
2247
2407
  setFieldTouched,
2248
2408
  setValues,
2249
- setServerErrors,
2409
+ setServerErrors: placeServerErrors,
2250
2410
  clearServerErrors,
2251
2411
  handleSubmit,
2252
2412
  resetForm,