@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/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,9 +1,10 @@
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
- * Detects whether a value is a Standard Schema v1 object by checking for
6
- * the `~standard` property with `version === 1`.
5
+ * Detects whether a value is a Standard Schema v1 schema by checking for
6
+ * the `~standard` property with `version === 1`. Schemas may be objects
7
+ * (Zod, Valibot) or callable functions (ArkType).
7
8
  */
8
9
  export declare function isStandardSchema(value: unknown): value is StandardSchemaV1;
9
10
  /**
@@ -43,6 +44,15 @@ type FormValidator<T extends Record<string, unknown>> = MaybeAsyncValidator<unkn
43
44
  */
44
45
  type FieldPath = string;
45
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[]>>);
46
56
  /**
47
57
  * Configuration options for the useForm hook.
48
58
  *
@@ -50,6 +60,7 @@ type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Arra
50
60
  * `initialValues` is required; all other options are optional.
51
61
  *
52
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
53
64
  *
54
65
  * @example
55
66
  * // Minimal configuration
@@ -74,15 +85,31 @@ type DeepPartial<T> = T extends Date | RegExp | File | Blob ? T : T extends Arra
74
85
  * onSubmit: saveSettings
75
86
  * });
76
87
  */
77
- interface FormOptions<TValues extends Record<string, unknown>> {
88
+ interface FormOptions<TValues extends Record<string, unknown>, TResult = TValues> {
78
89
  /**
79
90
  * Initial values for the form fields.
80
91
  * These values are used when the form is reset.
81
92
  */
82
- initialValues: TValues;
93
+ initialValues: NoInfer<TValues>;
83
94
  /**
84
95
  * Callback function that runs when the form is submitted with valid data.
85
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
+ *
86
113
  * @param values - The validated form values (guaranteed to be complete and valid)
87
114
  *
88
115
  * @example
@@ -92,11 +119,14 @@ interface FormOptions<TValues extends Record<string, unknown>> {
92
119
  * body: JSON.stringify(values)
93
120
  * });
94
121
  * if (!response.ok) {
95
- * // Handle server errors
122
+ * const errors: ValidationError[] = await response.json();
123
+ * return err(errors);
96
124
  * }
125
+ * const user: User = await response.json();
126
+ * return ok(user);
97
127
  * }
98
128
  */
99
- onSubmit?: (values: TValues) => void | Promise<void>;
129
+ onSubmit?: OnSubmit<TValues, TResult>;
100
130
  /**
101
131
  * Validation behavior preset that controls when validation occurs and when fields are marked as touched.
102
132
  *
@@ -703,8 +733,12 @@ interface ArrayHelpers<TItem, TFieldPaths extends string = ExtractFieldPaths<TIt
703
733
  * form actions, native HTML field integration, and array field helpers.
704
734
  *
705
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, …>`.
706
740
  */
707
- interface UseFormReturn<TValues extends Record<string, unknown>> {
741
+ interface UseFormReturn<TValues extends Record<string, unknown>, TResult = unknown> {
708
742
  /** Current values of all form fields. */
709
743
  values: TValues;
710
744
  /** Record of which fields have been interacted with by the user. */
@@ -713,7 +747,10 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
713
747
  errors: Record<FieldPath, string>;
714
748
  /** Validation errors from client-side (schema) validation only. */
715
749
  clientErrors: Record<FieldPath, string>;
716
- /** 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
+ */
717
754
  serverErrors: Record<FieldPath, string>;
718
755
  /** Validation errors from field-level validators (both sync and async). Takes precedence over client errors but not server errors. */
719
756
  fieldErrors: Record<FieldPath, string>;
@@ -723,7 +760,10 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
723
760
  isValidating: boolean;
724
761
  /** Per-field async validation tracking. `true` when that field's async validator is running. */
725
762
  validatingFields: Record<FieldPath, boolean>;
726
- /** 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
+ */
727
767
  isValid: boolean;
728
768
  /** Whether any form values have changed since initialization or last reset. */
729
769
  isDirty: boolean;
@@ -752,11 +792,12 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
752
792
  setValues: (values: DeepPartial<TValues>, shouldValidate?: boolean) => void;
753
793
  /**
754
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.
755
796
  *
756
797
  * @example
757
- * form.setServerErrors({ email: "Email already taken" });
798
+ * form.setServerErrors([{ path: ["email"], message: "Email already taken" }]);
758
799
  */
759
- setServerErrors: (errors: Record<FieldPath, string>) => void;
800
+ setServerErrors: (errors: ValidationError[]) => void;
760
801
  /**
761
802
  * Clears all server-side validation errors. Client-side errors are not affected.
762
803
  *
@@ -765,7 +806,12 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
765
806
  */
766
807
  clearServerErrors: () => void;
767
808
  /**
768
- * 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.
769
815
  *
770
816
  * @example
771
817
  * <form onSubmit={form.handleSubmit}>
@@ -773,7 +819,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
773
819
  * <button type="submit">Submit</button>
774
820
  * </form>
775
821
  */
776
- handleSubmit: (e?: FormEvent) => Promise<Result<TValues, ValidationError[]>>;
822
+ handleSubmit: (e?: SyntheticEvent) => Promise<Result<TResult, ValidationError[]>>;
777
823
  /**
778
824
  * Resets the form to its initial state — clears all values, errors, and touched state.
779
825
  *
@@ -896,6 +942,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
896
942
  * provides helpers for working with nested objects and dynamic arrays.
897
943
  *
898
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
899
946
  *
900
947
  * @param validator - Railway-oriented validator (sync or async) from @railway-ts/pipelines that validates form values
901
948
  * @param options - Configuration options for form behavior
@@ -967,14 +1014,13 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
967
1014
  * </form>
968
1015
  *
969
1016
  * @example
970
- * // Handle server errors
1017
+ * // Handle server errors: return err to place them on the form, ok to succeed
971
1018
  * const form = useForm(userValidator, {
1019
+ * initialValues: { name: "", email: "", age: 0 },
972
1020
  * onSubmit: async (values) => {
973
1021
  * const response = await api.createUser(values);
974
- * if (!response.ok) {
975
- * const errors = await response.json();
976
- * form.setServerErrors(errors);
977
- * }
1022
+ * if (!response.ok) return err((await response.json()) as ValidationError[]);
1023
+ * return ok((await response.json()) as User);
978
1024
  * }
979
1025
  * });
980
1026
  *
@@ -1000,7 +1046,7 @@ interface UseFormReturn<TValues extends Record<string, unknown>> {
1000
1046
  * </div>
1001
1047
  * );
1002
1048
  */
1003
- 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>;
1004
1050
  /**
1005
1051
  * Represents the subset of form methods needed for auto-submission
1006
1052
  * @template T - The type of form values