@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 CHANGED
@@ -32,7 +32,7 @@ Bring your own Zod, Valibot, or ArkType via [Standard Schema](https://github.com
32
32
  bun add @railway-ts/use-form @railway-ts/pipelines # or npm, pnpm, yarn
33
33
  ```
34
34
 
35
- Requires React 18+ and @railway-ts/pipelines 0.2.
35
+ Requires React 19, TypeScript 6.0+, Node.js 22.12+ and @railway-ts/pipelines 0.3.
36
36
 
37
37
  ## Quick Start
38
38
 
@@ -87,6 +87,7 @@ import {
87
87
  minLength,
88
88
  ROOT_ERROR_KEY,
89
89
  type InferSchemaType,
90
+ type ValidationError,
90
91
  } from '@railway-ts/pipelines/schema';
91
92
  import { useForm } from '@railway-ts/use-form';
92
93
  import { useMutation, useQueryClient } from '@tanstack/react-query';
@@ -110,11 +111,11 @@ type Registration = InferSchemaType<typeof schema>;
110
111
 
111
112
  const checkUsername = (username: string): Promise<{ available: boolean }> =>
112
113
  fetch(`/api/check-username?u=${encodeURIComponent(username)}`).then((res) =>
113
- res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`),
114
+ res.ok ? res.json() : Promise.reject(new Error(`HTTP ${res.status}`)),
114
115
  );
115
116
 
116
117
  class ApiValidationError extends Error {
117
- constructor(public fieldErrors: Record<string, string>) {
118
+ constructor(public fieldErrors: ValidationError[]) {
118
119
  super('Validation failed');
119
120
  }
120
121
  }
@@ -126,7 +127,7 @@ const registerUser = async (values: Registration): Promise<void> => {
126
127
  body: JSON.stringify(values),
127
128
  });
128
129
 
129
- if (!res.ok) throw new ApiValidationError(await res.json());
130
+ if (!res.ok) throw new ApiValidationError((await res.json()) as ValidationError[]);
130
131
  };
131
132
 
132
133
  // --- Component ---
@@ -142,9 +143,8 @@ export function RegistrationForm() {
142
143
  if (error instanceof ApiValidationError) {
143
144
  form.setServerErrors(error.fieldErrors);
144
145
  } else {
145
- form.setServerErrors({
146
- [ROOT_ERROR_KEY]: 'Network error. Please try again.',
147
- });
146
+ // path [] is the submit error, shown at form.errors[ROOT_ERROR_KEY]
147
+ form.setServerErrors([{ path: [], message: 'Network error. Please try again.' }]);
148
148
  }
149
149
  },
150
150
  });
@@ -210,7 +210,7 @@ Cross-field validation, async username check, server errors, and React Query int
210
210
  - **Array helpers** -- type-safe `push`, `remove`, `swap`, `insert`, `replace` with field bindings
211
211
  - **Four validation modes** -- `live`, `blur`, `mount`, `submit`
212
212
  - **Auto-submission** -- `useFormAutoSubmission` for search/filter forms with debounced submit
213
- - **React 18 + 19** -- compatible with both, tree-shakeable ESM
213
+ - **React 19** -- tree-shakeable ESM
214
214
 
215
215
  ## Works With
216
216
 
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MaybeAsyncValidator, StandardSchemaV1, ValidationError } from "@railway-ts/pipelines/schema";
2
2
  import { Result } from "@railway-ts/pipelines/result";
3
- import { ChangeEvent, FormEvent } from "react";
3
+ import { ChangeEvent, SyntheticEvent } from "react";
4
4
  /**
5
5
  * Detects whether a value is a Standard Schema v1 schema by checking for
6
6
  * the `~standard` property with `version === 1`. Schemas may be objects
@@ -44,6 +44,15 @@ type FormValidator<T extends Record<string, unknown>> = MaybeAsyncValidator<unkn
44
44
  */
45
45
  type FieldPath = string;
46
46
  type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Array<unknown> ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]>; } : T;
47
+ /**
48
+ * The submit handler: it returns nothing on every path, or a `Result` on every path.
49
+ * Returning nothing is allowed only when `TResult` is the form values, since `handleSubmit`
50
+ * then resolves to the values. Any other `TResult` needs a `Result`.
51
+ *
52
+ * @template TValues - The type of form values being managed
53
+ * @template TResult - The value `handleSubmit` resolves to on success
54
+ */
55
+ type OnSubmit<TValues, TResult> = ((values: TValues) => [TResult] extends [TValues] ? ([TValues] extends [TResult] ? void | Promise<void> : never) : never) | ((values: TValues) => Result<TResult, ValidationError[]> | Promise<Result<TResult, ValidationError[]>>);
47
56
  /**
48
57
  * Configuration options for the useForm hook.
49
58
  *
@@ -51,6 +60,7 @@ type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Arra
51
60
  * `initialValues` is required; all other options are optional.
52
61
  *
53
62
  * @template TValues - The type of form values being managed
63
+ * @template TResult - The value `handleSubmit` resolves to on success: `onSubmit`'s `ok` value, or the form values
54
64
  *
55
65
  * @example
56
66
  * // Minimal configuration
@@ -75,15 +85,31 @@ type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Arra
75
85
  * onSubmit: saveSettings
76
86
  * });
77
87
  */
78
- interface FormOptions<TValues extends Record<string, unknown>> {
88
+ interface FormOptions<TValues extends Record<string, unknown>, TResult = TValues> {
79
89
  /**
80
90
  * Initial values for the form fields.
81
91
  * These values are used when the form is reset.
82
92
  */
83
- initialValues: TValues;
93
+ initialValues: NoInfer<TValues>;
84
94
  /**
85
95
  * Callback function that runs when the form is submitted with valid data.
86
96
  * Only called if validation passes. Can be sync or async.
97
+ *
98
+ * Return nothing on every path, or a `Result` on every path:
99
+ * - **Nothing:** `handleSubmit` resolves to `ok(values)`.
100
+ * - **`ok(value)`:** `handleSubmit` resolves to `ok(value)`.
101
+ * - **`err(errors)`:** each error is placed on its field, as `setServerErrors` does, and an error at
102
+ * path `[]` becomes the submit error. `handleSubmit` resolves to the same `err`.
103
+ *
104
+ * If it throws, rejects, or returns anything else, `handleSubmit` resolves to
105
+ * `err([{ path: [], message: "Something went wrong. Please try again." }])`, which becomes the submit error.
106
+ * The original error is logged with `console.error`.
107
+ *
108
+ * With an explicit type argument, `useForm<TValues>` fixes the success value to the form values.
109
+ * For an `onSubmit` that returns `Result<User, …>`, write `useForm<TValues, User>` or drop the type arguments.
110
+ * With an explicit `useForm<TValues, User>`, always pass an `onSubmit` that returns a `Result`: without one,
111
+ * `handleSubmit` resolves to the form values, though its type says `User`.
112
+ *
87
113
  * @param values - The validated form values (guaranteed to be complete and valid)
88
114
  *
89
115
  * @example
@@ -93,11 +119,14 @@ interface FormOptions<TValues extends Record<string, unknown>> {
93
119
  * body: JSON.stringify(values)
94
120
  * });
95
121
  * if (!response.ok) {
96
- * // Handle server errors
122
+ * const errors: ValidationError[] = await response.json();
123
+ * return err(errors);
97
124
  * }
125
+ * const user: User = await response.json();
126
+ * return ok(user);
98
127
  * }
99
128
  */
100
- onSubmit?: (values: TValues) => void | Promise<void>;
129
+ onSubmit?: OnSubmit<TValues, TResult>;
101
130
  /**
102
131
  * Validation behavior preset that controls when validation occurs and when fields are marked as touched.
103
132
  *
@@ -704,8 +733,12 @@ interface ArrayHelpers<TItem, TFieldPaths extends string = ExtractFieldPaths<TIt
704
733
  * form actions, native HTML field integration, and array field helpers.
705
734
  *
706
735
  * @template TValues - The shape of form values as a record with string keys
736
+ * @template TResult - The value `handleSubmit` resolves to on success: `onSubmit`'s `ok` value, or the form values.
737
+ * The default, `unknown`, lets a component typed `UseFormReturn<V>` accept any form of shape `V`, whatever its
738
+ * `onSubmit` returns. A component that reads `handleSubmit`'s `ok` value writes `UseFormReturn<V, V>`, or
739
+ * `UseFormReturn<V, U>` for an `onSubmit` that returns `Result<U, …>`.
707
740
  */
708
- interface UseFormReturn<TValues extends Record<string, unknown>> {
741
+ interface UseFormReturn<TValues extends Record<string, unknown>, TResult = unknown> {
709
742
  /** Current values of all form fields. */
710
743
  values: TValues;
711
744
  /** Record of which fields have been interacted with by the user. */
@@ -714,7 +747,10 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
714
747
  errors: Record<FieldPath, string>;
715
748
  /** Validation errors from client-side (schema) validation only. */
716
749
  clientErrors: Record<FieldPath, string>;
717
- /** Validation errors set via `setServerErrors()`. Automatically cleared when the related field value changes. */
750
+ /**
751
+ * Validation errors set via `setServerErrors()`, keyed by field path. Automatically cleared when the related
752
+ * field value changes. Includes the submit error at `_root` when one is set.
753
+ */
718
754
  serverErrors: Record<FieldPath, string>;
719
755
  /** Validation errors from field-level validators (both sync and async). Takes precedence over client errors but not server errors. */
720
756
  fieldErrors: Record<FieldPath, string>;
@@ -724,7 +760,10 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
724
760
  isValidating: boolean;
725
761
  /** Per-field async validation tracking. `true` when that field's async validator is running. */
726
762
  validatingFields: Record<FieldPath, boolean>;
727
- /** Whether the form is currently valid (no errors of any kind). */
763
+ /**
764
+ * Whether the form is currently valid: no client, field-validator or per-path server errors.
765
+ * The submit error never makes the form invalid. A client error at `_root` does.
766
+ */
728
767
  isValid: boolean;
729
768
  /** Whether any form values have changed since initialization or last reset. */
730
769
  isDirty: boolean;
@@ -753,11 +792,12 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
753
792
  setValues: (values: DeepPartial<TValues>, shouldValidate?: boolean) => void;
754
793
  /**
755
794
  * Sets server-side validation errors. These take precedence over client errors and are auto-cleared on field change.
795
+ * An error at path `[]` becomes the submit error. Every other error's path is marked touched.
756
796
  *
757
797
  * @example
758
- * form.setServerErrors({ email: "Email already taken" });
798
+ * form.setServerErrors([{ path: ["email"], message: "Email already taken" }]);
759
799
  */
760
- setServerErrors: (errors: Record<FieldPath, string>) => void;
800
+ setServerErrors: (errors: ValidationError[]) => void;
761
801
  /**
762
802
  * Clears all server-side validation errors. Client-side errors are not affected.
763
803
  *
@@ -766,7 +806,12 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
766
806
  */
767
807
  clearServerErrors: () => void;
768
808
  /**
769
- * Validates all fields, marks them as touched, and calls `onSubmit` if valid. Returns a Railway `Result`.
809
+ * Validates all fields, marks them as touched, and calls `onSubmit` if valid. Resolves to a Railway `Result`
810
+ * and never rejects:
811
+ * - `ok` with `onSubmit`'s `ok` value, or with the values when `onSubmit` returns nothing or is absent
812
+ * - `err` with the validation errors, or with `onSubmit`'s `err`
813
+ * - `err([{ path: [], message: "Something went wrong. Please try again." }])` when the submission throws,
814
+ * or `onSubmit` returns neither a `Result` nor nothing. This becomes the submit error.
770
815
  *
771
816
  * @example
772
817
  * <form onSubmit={form.handleSubmit}>
@@ -774,7 +819,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
774
819
  * <button type="submit">Submit</button>
775
820
  * </form>
776
821
  */
777
- handleSubmit: (e?: FormEvent) => Promise<Result<TValues, ValidationError[]>>;
822
+ handleSubmit: (e?: SyntheticEvent) => Promise<Result<TResult, ValidationError[]>>;
778
823
  /**
779
824
  * Resets the form to its initial state — clears all values, errors, and touched state.
780
825
  *
@@ -897,6 +942,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
897
942
  * provides helpers for working with nested objects and dynamic arrays.
898
943
  *
899
944
  * @template TValues - The shape of form values as a record with string keys
945
+ * @template TResult - The value `handleSubmit` resolves to on success: `onSubmit`'s `ok` value, or the form values
900
946
  *
901
947
  * @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
902
948
  * @param options - Configuration options for form behavior
@@ -968,14 +1014,13 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
968
1014
  * </form>
969
1015
  *
970
1016
  * @example
971
- * // Handle server errors
1017
+ * // Handle server errors: return err to place them on the form, ok to succeed
972
1018
  * const form = useForm(userValidator, {
1019
+ * initialValues: { name: "", email: "", age: 0 },
973
1020
  * onSubmit: async (values) => {
974
1021
  * const response = await api.createUser(values);
975
- * if (!response.ok) {
976
- * const errors = await response.json();
977
- * form.setServerErrors(errors);
978
- * }
1022
+ * if (!response.ok) return err((await response.json()) as ValidationError[]);
1023
+ * return ok((await response.json()) as User);
979
1024
  * }
980
1025
  * });
981
1026
  *
@@ -1001,7 +1046,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
1001
1046
  * </div>
1002
1047
  * );
1003
1048
  */
1004
- export declare const useForm: <TValues extends Record<string, unknown>>(validatorOrSchema: FormValidator<TValues>, options: FormOptions<TValues>) => UseFormReturn<TValues>;
1049
+ export declare const useForm: <TValues extends Record<string, unknown>, TResult = TValues>(validatorOrSchema: FormValidator<TValues>, options: FormOptions<TValues, TResult>) => UseFormReturn<TValues, TResult>;
1005
1050
  /**
1006
1051
  * Represents the subset of form methods needed for auto-submission
1007
1052
  * @template T - The type of form values