remix-validated-form 1.1.1 → 2.0.0-beta.2

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.
Files changed (81) hide show
  1. package/.turbo/turbo-build.log +9 -0
  2. package/.turbo/turbo-dev.log +78 -0
  3. package/.turbo/turbo-test.log +36 -0
  4. package/README.md +72 -19
  5. package/browser/ValidatedForm.d.ts +35 -1
  6. package/browser/ValidatedForm.js +76 -20
  7. package/browser/hooks.d.ts +28 -3
  8. package/browser/hooks.js +17 -2
  9. package/browser/index.d.ts +2 -0
  10. package/browser/index.js +1 -0
  11. package/browser/internal/flatten.d.ts +4 -0
  12. package/browser/internal/flatten.js +35 -0
  13. package/browser/internal/formContext.d.ts +18 -0
  14. package/browser/internal/formContext.js +0 -0
  15. package/browser/internal/submissionCallbacks.d.ts +1 -0
  16. package/browser/internal/submissionCallbacks.js +13 -0
  17. package/browser/internal/util.d.ts +0 -0
  18. package/browser/internal/util.js +0 -0
  19. package/browser/server.d.ts +5 -0
  20. package/browser/server.js +5 -0
  21. package/browser/test-data/testFormData.d.ts +15 -0
  22. package/browser/test-data/testFormData.js +46 -0
  23. package/browser/validation/createValidator.d.ts +7 -0
  24. package/browser/validation/createValidator.js +30 -0
  25. package/browser/validation/types.d.ts +17 -2
  26. package/browser/validation/types.js +0 -0
  27. package/browser/validation/validation.test.d.ts +0 -0
  28. package/browser/validation/validation.test.js +162 -8
  29. package/browser/validation/withYup.d.ts +3 -0
  30. package/browser/validation/withYup.js +31 -25
  31. package/browser/validation/withZod.d.ts +3 -0
  32. package/browser/validation/withZod.js +19 -4
  33. package/build/ValidatedForm.d.ts +35 -1
  34. package/build/ValidatedForm.js +75 -19
  35. package/build/hooks.d.ts +28 -3
  36. package/build/hooks.js +20 -2
  37. package/build/index.d.ts +2 -0
  38. package/build/index.js +1 -0
  39. package/build/internal/flatten.d.ts +4 -0
  40. package/build/internal/flatten.js +43 -0
  41. package/build/internal/formContext.d.ts +18 -0
  42. package/build/internal/formContext.js +0 -0
  43. package/build/internal/submissionCallbacks.d.ts +1 -0
  44. package/build/internal/submissionCallbacks.js +17 -0
  45. package/build/internal/util.d.ts +0 -0
  46. package/build/internal/util.js +0 -0
  47. package/build/server.d.ts +5 -0
  48. package/build/server.js +5 -0
  49. package/build/test-data/testFormData.d.ts +15 -0
  50. package/build/test-data/testFormData.js +50 -0
  51. package/build/validation/createValidator.d.ts +7 -0
  52. package/build/validation/createValidator.js +34 -0
  53. package/build/validation/types.d.ts +17 -2
  54. package/build/validation/types.js +0 -0
  55. package/build/validation/validation.test.d.ts +0 -0
  56. package/build/validation/validation.test.js +162 -8
  57. package/build/validation/withYup.d.ts +3 -0
  58. package/build/validation/withYup.js +31 -25
  59. package/build/validation/withZod.d.ts +3 -0
  60. package/build/validation/withZod.js +22 -4
  61. package/jest.config.js +5 -0
  62. package/package.json +18 -38
  63. package/src/ValidatedForm.tsx +227 -0
  64. package/src/hooks.ts +60 -0
  65. package/src/index.ts +8 -0
  66. package/src/internal/flatten.ts +48 -0
  67. package/src/internal/formContext.ts +36 -0
  68. package/src/internal/submissionCallbacks.ts +15 -0
  69. package/src/internal/util.ts +23 -0
  70. package/src/server.ts +10 -0
  71. package/src/test-data/testFormData.ts +55 -0
  72. package/src/validation/createValidator.ts +34 -0
  73. package/src/validation/types.ts +28 -0
  74. package/src/validation/validation.test.ts +322 -0
  75. package/src/validation/withYup.ts +43 -0
  76. package/src/validation/withZod.ts +51 -0
  77. package/tsconfig.json +5 -0
  78. package/.eslintcache +0 -1
  79. package/.eslintignore +0 -1
  80. package/.prettierignore +0 -8
  81. package/LICENSE +0 -21
@@ -0,0 +1,9 @@
1
+ $ npm run build:browser && npm run build:main
2
+
3
+ > remix-validated-form@2.0.0 build:browser
4
+ > tsc --module ESNext --outDir ./browser
5
+
6
+
7
+ > remix-validated-form@2.0.0 build:main
8
+ > tsc --module CommonJS --outDir ./build
9
+
@@ -0,0 +1,78 @@
1
+ $ tsc --module ESNext --outDir ./browser --watch
2
+ c8:26:39 PM - Starting compilation in watch mode...
3
+
4
+
5
+ 8:26:40 PM - Found 0 errors. Watching for file changes.
6
+ c8:29:35 PM - File change detected. Starting incremental compilation...
7
+
8
+
9
+ 8:29:35 PM - Found 0 errors. Watching for file changes.
10
+ c8:30:13 PM - File change detected. Starting incremental compilation...
11
+
12
+
13
+ 8:30:13 PM - Found 0 errors. Watching for file changes.
14
+ c8:30:36 PM - File change detected. Starting incremental compilation...
15
+
16
+
17
+ 8:30:36 PM - Found 0 errors. Watching for file changes.
18
+ c8:31:03 PM - File change detected. Starting incremental compilation...
19
+
20
+
21
+ 8:31:03 PM - Found 0 errors. Watching for file changes.
22
+ c8:33:28 PM - File change detected. Starting incremental compilation...
23
+
24
+ src/ValidatedForm.tsx(67,7): error TS2304: Cannot find name 'defaultsFromValidationError'.
25
+ src/ValidatedForm.tsx(69,23): error TS2304: Cannot find name 'defaultsFromValidationError'.
26
+ src/ValidatedForm.tsx(70,10): error TS2304: Cannot find name 'defaultsFromValidationError'.
27
+ src/ValidatedForm.tsx(71,30): error TS2304: Cannot find name 'defaultsFromValidationError'.
28
+ src/ValidatedForm.tsx(71,60): error TS2304: Cannot find name 'defaultValues'.
29
+ src/ValidatedForm.tsx(152,58): error TS2554: Expected 0-1 arguments, but got 2.
30
+
31
+ 8:33:28 PM - Found 6 errors. Watching for file changes.
32
+ c8:35:37 PM - File change detected. Starting incremental compilation...
33
+
34
+ src/ValidatedForm.tsx(69,5): error TS1156: 'const' declarations can only be declared inside a block.
35
+ src/ValidatedForm.tsx(71,10): error TS2304: Cannot find name 'defaultsFromValidationError'.
36
+ src/ValidatedForm.tsx(72,10): error TS2454: Variable 'subactionsMatch' is used before being assigned.
37
+ src/ValidatedForm.tsx(72,28): error TS2304: Cannot find name 'defaultsFromValidationError'.
38
+ src/ValidatedForm.tsx(72,58): error TS2304: Cannot find name 'defaultValues'.
39
+
40
+ 8:35:38 PM - Found 5 errors. Watching for file changes.
41
+ c8:51:56 PM - File change detected. Starting incremental compilation...
42
+
43
+ src/ValidatedForm.tsx(69,5): error TS1156: 'const' declarations can only be declared inside a block.
44
+ src/ValidatedForm.tsx(71,10): error TS2304: Cannot find name 'defaultsFromValidationError'.
45
+ src/ValidatedForm.tsx(72,10): error TS2454: Variable 'subactionsMatch' is used before being assigned.
46
+ src/ValidatedForm.tsx(72,28): error TS2304: Cannot find name 'defaultsFromValidationError'.
47
+ src/ValidatedForm.tsx(72,58): error TS2304: Cannot find name 'defaultValues'.
48
+
49
+ 8:51:56 PM - Found 5 errors. Watching for file changes.
50
+ c8:52:01 PM - File change detected. Starting incremental compilation...
51
+
52
+ src/ValidatedForm.tsx(69,5): error TS1156: 'const' declarations can only be declared inside a block.
53
+ src/ValidatedForm.tsx(71,10): error TS2304: Cannot find name 'defaultsFromValidationError'.
54
+ src/ValidatedForm.tsx(72,10): error TS2454: Variable 'subactionsMatch' is used before being assigned.
55
+ src/ValidatedForm.tsx(72,28): error TS2304: Cannot find name 'defaultsFromValidationError'.
56
+ src/ValidatedForm.tsx(72,58): error TS2304: Cannot find name 'defaultValues'.
57
+
58
+ 8:52:01 PM - Found 5 errors. Watching for file changes.
59
+ c8:53:29 PM - File change detected. Starting incremental compilation...
60
+
61
+
62
+ 8:53:29 PM - Found 0 errors. Watching for file changes.
63
+ c8:54:22 PM - File change detected. Starting incremental compilation...
64
+
65
+
66
+ 8:54:22 PM - Found 0 errors. Watching for file changes.
67
+ c8:54:40 PM - File change detected. Starting incremental compilation...
68
+
69
+ src/ValidatedForm.tsx(157,42): error TS2345: Argument of type 'FieldErrorsWithData | null' is not assignable to parameter of type 'FieldErrorsWithData | undefined'.
70
+ Type 'null' is not assignable to type 'FieldErrorsWithData | undefined'.
71
+
72
+ 8:54:40 PM - Found 1 error. Watching for file changes.
73
+ c8:54:56 PM - File change detected. Starting incremental compilation...
74
+
75
+ src/ValidatedForm.tsx(70,20): error TS2322: Type 'null' is not assignable to type 'FieldErrorsWithData | undefined'.
76
+ src/ValidatedForm.tsx(77,3): error TS2322: Type 'null' is not assignable to type 'FieldErrorsWithData | undefined'.
77
+
78
+ 8:54:56 PM
@@ -0,0 +1,36 @@
1
+ $ jest src
2
+  PASS  src/validation/validation.test.ts
3
+ Validation
4
+ Adapter for yup
5
+ validate
6
+ ✓ should return the data when valid (2 ms)
7
+ ✓ should return field errors when invalid (1 ms)
8
+ ✓ should unflatten data when validating
9
+ ✓ should accept FormData directly and return errors (1 ms)
10
+ ✓ should accept FormData directly and return valid data (1 ms)
11
+ validateField
12
+ ✓ should not return an error if field is valid
13
+ ✓ should not return an error if a nested field is valid (1 ms)
14
+ ✓ should return an error if field is invalid (2 ms)
15
+ ✓ should return an error if a nested field is invalid
16
+ Adapter for zod
17
+ validate
18
+ ✓ should return the data when valid (1 ms)
19
+ ✓ should return field errors when invalid
20
+ ✓ should unflatten data when validating (1 ms)
21
+ ✓ should accept FormData directly and return errors
22
+ ✓ should accept FormData directly and return valid data
23
+ validateField
24
+ ✓ should not return an error if field is valid (1 ms)
25
+ ✓ should not return an error if a nested field is valid
26
+ ✓ should return an error if field is invalid
27
+ ✓ should return an error if a nested field is invalid
28
+ withZod
29
+ ✓ returns coherent errors for complex schemas (1 ms)
30
+ ✓ returns errors for fields that are unions
31
+
32
+ Test Suites: 1 passed, 1 total
33
+ Tests: 20 passed, 20 total
34
+ Snapshots: 0 total
35
+ Time: 1.1 s, estimated 2 s
36
+ Ran all test suites matching /src/i.
package/README.md CHANGED
@@ -7,11 +7,24 @@ A form library built for [remix](https://remix.run) to make validation easy.
7
7
  - Re-use validation on the server
8
8
  - Show validation errors from the server even without JS
9
9
  - Detect if the current form is submitting when there are multiple forms on the page
10
+ - Supports nested objects and arrays
10
11
  - Validation library agnostic
11
12
 
12
13
  # Demo
13
14
 
14
- https://user-images.githubusercontent.com/25882770/143505448-c4b7e660-7a73-4005-b2ca-17c65a15ef46.mov
15
+ https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
16
+
17
+ To run `sample-app`:
18
+
19
+ ```
20
+ git clone https://github.com/airjp73/remix-validated-form
21
+ cd remix-validated-form
22
+ npm i
23
+ cd sample-app
24
+ npm i
25
+ cd ..
26
+ npm run sample-app
27
+ ```
15
28
 
16
29
  # Getting started
17
30
 
@@ -57,7 +70,7 @@ export const MyInput = ({ name, label }: InputProps) => {
57
70
  To best take advantage of the per-form submission detection, we can create a submit button component.
58
71
 
59
72
  ```tsx
60
- import { useIsSubmitting } from "../../remix-validated-form";
73
+ import { useIsSubmitting } from "remix-validated-form";
61
74
 
62
75
  export const MySubmitButton = () => {
63
76
  const isSubmitting = useIsSubmitting();
@@ -89,9 +102,7 @@ const validator = withYup(
89
102
  );
90
103
 
91
104
  export const action: ActionFunction = async ({ request }) => {
92
- const fieldValues = validator.validate(
93
- Object.fromEntries(await request.formData())
94
- );
105
+ const fieldValues = validator.validate(await request.formData());
95
106
  if (fieldValues.error) return validationError(fieldValues.error);
96
107
  const { firstName, lastName, email } = fieldValues.data;
97
108
 
@@ -127,6 +138,33 @@ export default function MyForm() {
127
138
  }
128
139
  ```
129
140
 
141
+ ## Nested objects and arrays
142
+
143
+ You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
144
+
145
+ ```tsx
146
+ export default function MyForm() {
147
+ const { defaultValues } = useLoaderData();
148
+ return (
149
+ <ValidatedForm
150
+ validator={validator}
151
+ method="post"
152
+ defaultValues={defaultValues}
153
+ >
154
+ <MyInput name="firstName" label="First Name" />
155
+ <MyInput name="lastName" label="Last Name" />
156
+ <MyInput name="address.street" label="Street" />
157
+ <MyInput name="address.city" label="City" />
158
+ <MyInput name="phones[0].type" label="Phone 1 Type" />
159
+ <MyInput name="phones[0].number" label="Phone 1 Number" />
160
+ <MyInput name="phones[1].type" label="Phone 2 Type" />
161
+ <MyInput name="phones[1].number" label="Phone 2 Number" />
162
+ <MySubmitButton />
163
+ </ValidatedForm>
164
+ );
165
+ }
166
+ ```
167
+
130
168
  # Validation Library Support
131
169
 
132
170
  This library currently includes an out-of-the-box adapter for `yup` and `zod`,
@@ -159,24 +197,39 @@ type Validator<DataType> = {
159
197
  In order to make an adapter for your validation library of choice,
160
198
  you can create a function that accepts a schema from the validation library and turns it into a validator.
161
199
 
200
+ Note the use of `createValidator`.
201
+ It takes care of unflattening the data for nested objects and arrays
202
+ since the form doesn't know anything about object and arrays and this should be handled by the adapter.
203
+ For more on this you can check the implementations for `withZod` and `withYup`.
204
+
162
205
  The out-of-the-box support for `yup` in this library works like this:
163
206
 
164
207
  ```ts
165
208
  export const withYup = <Schema extends AnyObjectSchema>(
166
209
  validationSchema: Schema
167
210
  // For best result with Typescript, we should type the `Validator` we return based on the provided schema
168
- ): Validator<InferType<Schema>> => ({
169
- validate: (unvalidatedData) => {
170
- // Validate with yup and return the validated & typed data or the error
171
-
172
- if (isValid) return { data: { field1: "someValue" }, error: undefined };
173
- else return { error: { field1: "Some error!" }, data: undefined };
174
- },
175
- validateField: (unvalidatedData, field) => {
176
- // Validate the specific field with yup
177
-
178
- if (isValid) return { error: undefined };
179
- else return { error: "Some error" };
180
- },
181
- });
211
+ ): Validator<InferType<Schema>> =>
212
+ createValidator({
213
+ validate: (unvalidatedData) => {
214
+ // Validate with yup and return the validated & typed data or the error
215
+
216
+ if (isValid) return { data: { field1: "someValue" }, error: undefined };
217
+ else return { error: { field1: "Some error!" }, data: undefined };
218
+ },
219
+ validateField: (unvalidatedData, field) => {
220
+ // Validate the specific field with yup
221
+
222
+ if (isValid) return { error: undefined };
223
+ else return { error: "Some error" };
224
+ },
225
+ });
182
226
  ```
227
+
228
+ # Frequenty Asked Questions
229
+
230
+ ## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
231
+
232
+ This is happening because you or the library you are using is passing the `required` attribute to the fields.
233
+ This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors.
234
+ If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`.
235
+ We recommend this approach since the validation will still work even if JS is disabled.
@@ -2,10 +2,44 @@ import { Form as RemixForm, useFetcher } from "@remix-run/react";
2
2
  import React, { ComponentProps } from "react";
3
3
  import { Validator } from "./validation/types";
4
4
  export declare type FormProps<DataType> = {
5
+ /**
6
+ * A `Validator` object that describes how to validate the form.
7
+ */
5
8
  validator: Validator<DataType>;
9
+ /**
10
+ * A submit callback that gets called when the form is submitted
11
+ * after all validations have been run.
12
+ */
6
13
  onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
14
+ /**
15
+ * Allows you to provide a `fetcher` from remix's `useFetcher` hook.
16
+ * The form will use the fetcher for loading states, action data, etc
17
+ * instead of the default form action.
18
+ */
7
19
  fetcher?: ReturnType<typeof useFetcher>;
20
+ /**
21
+ * Accepts an object of default values for the form
22
+ * that will automatically be propagated to the form fields via `useField`.
23
+ */
8
24
  defaultValues?: Partial<DataType>;
25
+ /**
26
+ * A ref to the form element.
27
+ */
9
28
  formRef?: React.RefObject<HTMLFormElement>;
29
+ /**
30
+ * An optional sub-action to use for the form.
31
+ * Setting a value here will cause the form to be submitted with an extra `subaction` value.
32
+ * This can be useful when there are multiple forms on the screen handled by the same action.
33
+ */
34
+ subaction?: string;
35
+ /**
36
+ * Reset the form to the default values after the form has been successfully submitted.
37
+ * This is useful if you want to submit the same form multiple times,
38
+ * and don't redirect in-between submissions.
39
+ */
40
+ resetAfterSubmit?: boolean;
10
41
  } & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
11
- export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }: FormProps<DataType>): JSX.Element;
42
+ /**
43
+ * The primary form component of `remix-validated-form`.
44
+ */
45
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }: FormProps<DataType>): JSX.Element;
@@ -1,38 +1,89 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Form as RemixForm, useActionData, useFormAction, useTransition, } from "@remix-run/react";
3
3
  import { useEffect, useMemo, useRef, useState, } from "react";
4
4
  import invariant from "tiny-invariant";
5
5
  import { FormContext } from "./internal/formContext";
6
+ import { useSubmitComplete } from "./internal/submissionCallbacks";
6
7
  import { omit, mergeRefs } from "./internal/util";
7
- function useFieldErrors(fetcher) {
8
+ function useFieldErrorsFromBackend(fetcher, subaction) {
9
+ var _a, _b;
8
10
  const actionData = useActionData();
9
- const dataToUse = fetcher ? fetcher.data : actionData;
10
- const fieldErrorsFromAction = dataToUse === null || dataToUse === void 0 ? void 0 : dataToUse.fieldErrors;
11
- const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromAction !== null && fieldErrorsFromAction !== void 0 ? fieldErrorsFromAction : {});
11
+ if (fetcher)
12
+ return (_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors;
13
+ if (!actionData)
14
+ return null;
15
+ if (actionData.fieldErrors) {
16
+ const submittedData = (_b = actionData.fieldErrors) === null || _b === void 0 ? void 0 : _b._submittedData;
17
+ const subactionsMatch = subaction
18
+ ? subaction === (submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction)
19
+ : !(submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction);
20
+ return subactionsMatch ? actionData.fieldErrors : null;
21
+ }
22
+ return null;
23
+ }
24
+ function useFieldErrors(fieldErrorsFromBackend) {
25
+ const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
12
26
  useEffect(() => {
13
- if (fieldErrorsFromAction)
14
- setFieldErrors(fieldErrorsFromAction);
15
- }, [fieldErrorsFromAction]);
27
+ if (fieldErrorsFromBackend)
28
+ setFieldErrors(fieldErrorsFromBackend);
29
+ }, [fieldErrorsFromBackend]);
16
30
  return [fieldErrors, setFieldErrors];
17
31
  }
18
- const useIsSubmitting = (action, fetcher) => {
32
+ const useIsSubmitting = (action, subaction, fetcher) => {
19
33
  const actionForCurrentPage = useFormAction();
20
34
  const pendingFormSubmit = useTransition().submission;
21
- return fetcher
22
- ? fetcher.state === "submitting"
23
- : pendingFormSubmit &&
24
- pendingFormSubmit.action.endsWith(action !== null && action !== void 0 ? action : actionForCurrentPage);
35
+ if (fetcher)
36
+ return fetcher.state === "submitting";
37
+ if (!pendingFormSubmit)
38
+ return false;
39
+ const { formData, action: pendingAction } = pendingFormSubmit;
40
+ const pendingSubAction = formData.get("subaction");
41
+ const expectedAction = action !== null && action !== void 0 ? action : actionForCurrentPage;
42
+ if (subaction)
43
+ return expectedAction === pendingAction && subaction === pendingSubAction;
44
+ return expectedAction === pendingAction && !pendingSubAction;
25
45
  };
26
- const getDataFromForm = (el) => Object.fromEntries(new FormData(el));
27
- export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, ...rest }) {
46
+ const getDataFromForm = (el) => new FormData(el);
47
+ /**
48
+ * The purpose for this logic is to handle validation errors when javascript is disabled.
49
+ * Normally (without js), when a form is submitted and the action returns the validation errors,
50
+ * the form will be reset. The errors will be displayed on the correct fields,
51
+ * but all the values in the form will be gone. This is not good UX.
52
+ *
53
+ * To get around this, we return the submitted form data from the server,
54
+ * and use those to populate the form via `defaultValues`.
55
+ * This results in a more seamless UX akin to what you would see when js is enabled.
56
+ *
57
+ * One potential downside is that resetting the form will reset the form
58
+ * to the _new_ default values that were returned from the server with the validation errors.
59
+ * However, this case is less of a problem than the janky UX caused by losing the form values.
60
+ * It will only ever be a problem if the form includes a `<button type="reset" />`
61
+ * and only if JS is disabled.
62
+ */
63
+ function useDefaultValues(fieldErrors, defaultValues) {
64
+ const defaultsFromValidationError = fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors._submittedData;
65
+ return defaultsFromValidationError !== null && defaultsFromValidationError !== void 0 ? defaultsFromValidationError : defaultValues;
66
+ }
67
+ /**
68
+ * The primary form component of `remix-validated-form`.
69
+ */
70
+ export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }) {
28
71
  var _a;
29
- const [fieldErrors, setFieldErrors] = useFieldErrors(fetcher);
30
- const isSubmitting = useIsSubmitting(action, fetcher);
72
+ const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
73
+ const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
74
+ const isSubmitting = useIsSubmitting(action, subaction, fetcher);
75
+ const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
31
76
  const formRef = useRef(null);
77
+ useSubmitComplete(isSubmitting, () => {
78
+ var _a;
79
+ if (!fieldErrorsFromBackend) {
80
+ (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
81
+ }
82
+ });
32
83
  const contextValue = useMemo(() => ({
33
84
  fieldErrors,
34
85
  action,
35
- defaultValues,
86
+ defaultValues: defaultsToUse,
36
87
  isSubmitting: isSubmitting !== null && isSubmitting !== void 0 ? isSubmitting : false,
37
88
  clearError: (fieldName) => {
38
89
  setFieldErrors((prev) => omit(prev, fieldName));
@@ -50,7 +101,7 @@ export function ValidatedForm({ validator, onSubmit, children, fetcher, action,
50
101
  }), [
51
102
  fieldErrors,
52
103
  action,
53
- defaultValues,
104
+ defaultsToUse,
54
105
  isSubmitting,
55
106
  setFieldErrors,
56
107
  validator,
@@ -65,5 +116,10 @@ export function ValidatedForm({ validator, onSubmit, children, fetcher, action,
65
116
  else {
66
117
  onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, event);
67
118
  }
68
- }, children: _jsx(FormContext.Provider, { value: contextValue, children: children }, void 0) }, void 0));
119
+ }, onReset: (event) => {
120
+ onReset === null || onReset === void 0 ? void 0 : onReset(event);
121
+ if (event.defaultPrevented)
122
+ return;
123
+ setFieldErrors({});
124
+ }, children: _jsxs(FormContext.Provider, { value: contextValue, children: [_jsx("input", { type: "hidden", value: subaction, name: "subaction" }, void 0), children] }, void 0) }, void 0));
69
125
  }
@@ -1,8 +1,33 @@
1
- export declare const useField: (name: string) => {
2
- error: string;
1
+ export declare type FieldProps = {
2
+ /**
3
+ * The validation error message if there is one.
4
+ */
5
+ error?: string;
6
+ /**
7
+ * Clears the error message.
8
+ */
3
9
  clearError: () => void;
10
+ /**
11
+ * Validates the field.
12
+ */
4
13
  validate: () => void;
5
- defaultValue: any;
14
+ /**
15
+ * The default value of the field, if there is one.
16
+ */
17
+ defaultValue?: any;
6
18
  };
19
+ /**
20
+ * Provides the data and helpers necessary to set up a field.
21
+ */
22
+ export declare const useField: (name: string) => FieldProps;
23
+ /**
24
+ * Provides access to the entire form context.
25
+ * This is not usually necessary, but can be useful for advanced use cases.
26
+ */
7
27
  export declare const useFormContext: () => import("./internal/formContext").FormContextValue;
28
+ /**
29
+ * Returns whether or not the parent form is currently being submitted.
30
+ * This is different from remix's `useTransition().submission` in that it
31
+ * is aware of what form it's in and when _that_ form is being submitted.
32
+ */
8
33
  export declare const useIsSubmitting: () => boolean;
package/browser/hooks.js CHANGED
@@ -1,5 +1,10 @@
1
+ import get from "lodash/get";
2
+ import toPath from "lodash/toPath";
1
3
  import { useContext, useMemo } from "react";
2
4
  import { FormContext } from "./internal/formContext";
5
+ /**
6
+ * Provides the data and helpers necessary to set up a field.
7
+ */
3
8
  export const useField = (name) => {
4
9
  const { fieldErrors, clearError, validateField, defaultValues } = useContext(FormContext);
5
10
  const field = useMemo(() => ({
@@ -8,10 +13,20 @@ export const useField = (name) => {
8
13
  clearError(name);
9
14
  },
10
15
  validate: () => validateField(name),
11
- defaultValue: defaultValues === null || defaultValues === void 0 ? void 0 : defaultValues[name],
16
+ defaultValue: defaultValues
17
+ ? get(defaultValues, toPath(name), undefined)
18
+ : undefined,
12
19
  }), [clearError, defaultValues, fieldErrors, name, validateField]);
13
20
  return field;
14
21
  };
15
- // test commit
22
+ /**
23
+ * Provides access to the entire form context.
24
+ * This is not usually necessary, but can be useful for advanced use cases.
25
+ */
16
26
  export const useFormContext = () => useContext(FormContext);
27
+ /**
28
+ * Returns whether or not the parent form is currently being submitted.
29
+ * This is different from remix's `useTransition().submission` in that it
30
+ * is aware of what form it's in and when _that_ form is being submitted.
31
+ */
17
32
  export const useIsSubmitting = () => useFormContext().isSubmitting;
@@ -4,3 +4,5 @@ export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
6
  export * from "./validation/withZod";
7
+ export * from "./validation/createValidator";
8
+ export type { FormContextValue } from "./internal/formContext";
package/browser/index.js CHANGED
@@ -4,3 +4,4 @@ export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/withYup";
6
6
  export * from "./validation/withZod";
7
+ export * from "./validation/createValidator";
@@ -0,0 +1,4 @@
1
+ import { GenericObject } from "..";
2
+ export declare const objectFromPathEntries: (entries: [string, any][]) => {};
3
+ /** Flatten an object so there are no nested objects or arrays */
4
+ export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
@@ -0,0 +1,35 @@
1
+ // `flatten` is taken from https://github.com/richie5um/FlattenJS. Decided to implement them here instead of using that package because this is a core functionality of the library and this will add more flexibility in case we need to change the implementation.
2
+ import assign from "lodash/assign";
3
+ import isArray from "lodash/isArray";
4
+ import isObject from "lodash/isObject";
5
+ import keys from "lodash/keys";
6
+ import mapKeys from "lodash/mapKeys";
7
+ import set from "lodash/set";
8
+ import transform from "lodash/transform";
9
+ export const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => set(acc, key, value), {});
10
+ /** Flatten an object so there are no nested objects or arrays */
11
+ export function flatten(obj, preserveEmpty = false) {
12
+ return transform(obj, function (result, value, key) {
13
+ if (isObject(value)) {
14
+ let flatMap = mapKeys(flatten(value, preserveEmpty), function (_mvalue, mkey) {
15
+ if (isArray(value)) {
16
+ let index = mkey.indexOf(".");
17
+ if (-1 !== index) {
18
+ return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
19
+ }
20
+ return `${key}[${mkey}]`;
21
+ }
22
+ return `${key}.${mkey}`;
23
+ });
24
+ assign(result, flatMap);
25
+ // Preverve Empty arrays and objects
26
+ if (preserveEmpty && keys(flatMap).length === 0) {
27
+ result[key] = value;
28
+ }
29
+ }
30
+ else {
31
+ result[key] = value;
32
+ }
33
+ return result;
34
+ }, {});
35
+ }
@@ -1,11 +1,29 @@
1
1
  /// <reference types="react" />
2
2
  import { FieldErrors } from "../validation/types";
3
3
  export declare type FormContextValue = {
4
+ /**
5
+ * All the errors in all the fields in the form.
6
+ */
4
7
  fieldErrors: FieldErrors;
8
+ /**
9
+ * Clear the errors of the specified fields.
10
+ */
5
11
  clearError: (...names: string[]) => void;
12
+ /**
13
+ * Validate the specified field.
14
+ */
6
15
  validateField: (fieldName: string) => void;
16
+ /**
17
+ * The `action` prop of the form.
18
+ */
7
19
  action?: string;
20
+ /**
21
+ * Whether or not the form is submitting.
22
+ */
8
23
  isSubmitting: boolean;
24
+ /**
25
+ * The default values of the form.
26
+ */
9
27
  defaultValues?: {
10
28
  [fieldName: string]: any;
11
29
  };
File without changes
@@ -0,0 +1 @@
1
+ export declare function useSubmitComplete(isSubmitting: boolean, callback: () => void): void;
@@ -0,0 +1,13 @@
1
+ import { useEffect, useRef } from "react";
2
+ export function useSubmitComplete(isSubmitting, callback) {
3
+ const isPending = useRef(false);
4
+ useEffect(() => {
5
+ if (isSubmitting) {
6
+ isPending.current = true;
7
+ }
8
+ if (!isSubmitting && isPending.current) {
9
+ isPending.current = false;
10
+ callback();
11
+ }
12
+ });
13
+ }
File without changes
File without changes
@@ -1,2 +1,7 @@
1
1
  import { FieldErrors } from "./validation/types";
2
+ /**
3
+ * Takes the errors from a `Validator` and returns a `Response`.
4
+ * The `ValidatedForm` on the frontend will automatically display the errors
5
+ * if this is returned from the action.
6
+ */
2
7
  export declare const validationError: (errors: FieldErrors) => Response;
package/browser/server.js CHANGED
@@ -1,2 +1,7 @@
1
1
  import { json } from "@remix-run/server-runtime";
2
+ /**
3
+ * Takes the errors from a `Validator` and returns a `Response`.
4
+ * The `ValidatedForm` on the frontend will automatically display the errors
5
+ * if this is returned from the action.
6
+ */
2
7
  export const validationError = (errors) => json({ fieldErrors: errors }, { status: 422 });
@@ -0,0 +1,15 @@
1
+ export declare class TestFormData implements FormData {
2
+ private _params;
3
+ constructor(body?: string);
4
+ append(name: string, value: string | Blob, fileName?: string): void;
5
+ delete(name: string): void;
6
+ get(name: string): FormDataEntryValue | null;
7
+ getAll(name: string): FormDataEntryValue[];
8
+ has(name: string): boolean;
9
+ set(name: string, value: string | Blob, fileName?: string): void;
10
+ forEach(callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any): void;
11
+ entries(): IterableIterator<[string, FormDataEntryValue]>;
12
+ keys(): IterableIterator<string>;
13
+ values(): IterableIterator<FormDataEntryValue>;
14
+ [Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
15
+ }