remix-validated-form 1.1.0 → 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.
- package/.turbo/turbo-build.log +9 -0
- package/.turbo/turbo-dev.log +78 -0
- package/.turbo/turbo-test.log +36 -0
- package/README.md +72 -19
- package/browser/ValidatedForm.d.ts +35 -1
- package/browser/ValidatedForm.js +76 -20
- package/browser/hooks.d.ts +28 -3
- package/browser/hooks.js +17 -2
- package/browser/index.d.ts +3 -0
- package/browser/index.js +2 -0
- package/browser/internal/flatten.d.ts +4 -0
- package/browser/internal/flatten.js +35 -0
- package/browser/internal/formContext.d.ts +18 -0
- package/browser/internal/formContext.js +0 -0
- package/browser/internal/submissionCallbacks.d.ts +1 -0
- package/browser/internal/submissionCallbacks.js +13 -0
- package/browser/internal/util.d.ts +0 -0
- package/browser/internal/util.js +0 -0
- package/browser/server.d.ts +5 -0
- package/browser/server.js +5 -0
- package/browser/test-data/testFormData.d.ts +15 -0
- package/browser/test-data/testFormData.js +46 -0
- package/browser/validation/createValidator.d.ts +7 -0
- package/browser/validation/createValidator.js +30 -0
- package/browser/validation/types.d.ts +17 -2
- package/browser/validation/types.js +0 -0
- package/browser/validation/validation.test.d.ts +0 -0
- package/browser/validation/validation.test.js +162 -8
- package/browser/validation/withYup.d.ts +3 -0
- package/browser/validation/withYup.js +31 -25
- package/browser/validation/withZod.d.ts +3 -0
- package/browser/validation/withZod.js +19 -4
- package/build/ValidatedForm.d.ts +35 -1
- package/build/ValidatedForm.js +75 -19
- package/build/hooks.d.ts +28 -3
- package/build/hooks.js +20 -2
- package/build/index.d.ts +3 -0
- package/build/index.js +2 -0
- package/build/internal/flatten.d.ts +4 -0
- package/build/internal/flatten.js +43 -0
- package/build/internal/formContext.d.ts +18 -0
- package/build/internal/formContext.js +0 -0
- package/build/internal/submissionCallbacks.d.ts +1 -0
- package/build/internal/submissionCallbacks.js +17 -0
- package/build/internal/util.d.ts +0 -0
- package/build/internal/util.js +0 -0
- package/build/server.d.ts +5 -0
- package/build/server.js +5 -0
- package/build/test-data/testFormData.d.ts +15 -0
- package/build/test-data/testFormData.js +50 -0
- package/build/validation/createValidator.d.ts +7 -0
- package/build/validation/createValidator.js +34 -0
- package/build/validation/types.d.ts +17 -2
- package/build/validation/types.js +0 -0
- package/build/validation/validation.test.d.ts +0 -0
- package/build/validation/validation.test.js +162 -8
- package/build/validation/withYup.d.ts +3 -0
- package/build/validation/withYup.js +31 -25
- package/build/validation/withZod.d.ts +3 -0
- package/build/validation/withZod.js +22 -4
- package/jest.config.js +5 -0
- package/package.json +18 -38
- package/src/ValidatedForm.tsx +227 -0
- package/src/hooks.ts +60 -0
- package/src/index.ts +8 -0
- package/src/internal/flatten.ts +48 -0
- package/src/internal/formContext.ts +36 -0
- package/src/internal/submissionCallbacks.ts +15 -0
- package/src/internal/util.ts +23 -0
- package/src/server.ts +10 -0
- package/src/test-data/testFormData.ts +55 -0
- package/src/validation/createValidator.ts +34 -0
- package/src/validation/types.ts +28 -0
- package/src/validation/validation.test.ts +322 -0
- package/src/validation/withYup.ts +43 -0
- package/src/validation/withZod.ts +51 -0
- package/tsconfig.json +5 -0
- package/.eslintcache +0 -1
- package/.eslintignore +0 -1
- package/.prettierignore +0 -8
- package/LICENSE +0 -21
@@ -0,0 +1,78 @@
|
|
1
|
+
[2K[1G[2m$ tsc --module ESNext --outDir ./browser --watch[22m
|
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
|
+
[2K[1G[2m$ jest src[22m
|
2
|
+
[0m[7m[1m[32m PASS [39m[22m[27m[0m [2msrc/validation/[22m[1mvalidation.test.ts[22m
|
3
|
+
Validation
|
4
|
+
Adapter for yup
|
5
|
+
validate
|
6
|
+
[32m✓[39m [2mshould return the data when valid (2 ms)[22m
|
7
|
+
[32m✓[39m [2mshould return field errors when invalid (1 ms)[22m
|
8
|
+
[32m✓[39m [2mshould unflatten data when validating[22m
|
9
|
+
[32m✓[39m [2mshould accept FormData directly and return errors (1 ms)[22m
|
10
|
+
[32m✓[39m [2mshould accept FormData directly and return valid data (1 ms)[22m
|
11
|
+
validateField
|
12
|
+
[32m✓[39m [2mshould not return an error if field is valid[22m
|
13
|
+
[32m✓[39m [2mshould not return an error if a nested field is valid (1 ms)[22m
|
14
|
+
[32m✓[39m [2mshould return an error if field is invalid (2 ms)[22m
|
15
|
+
[32m✓[39m [2mshould return an error if a nested field is invalid[22m
|
16
|
+
Adapter for zod
|
17
|
+
validate
|
18
|
+
[32m✓[39m [2mshould return the data when valid (1 ms)[22m
|
19
|
+
[32m✓[39m [2mshould return field errors when invalid[22m
|
20
|
+
[32m✓[39m [2mshould unflatten data when validating (1 ms)[22m
|
21
|
+
[32m✓[39m [2mshould accept FormData directly and return errors[22m
|
22
|
+
[32m✓[39m [2mshould accept FormData directly and return valid data[22m
|
23
|
+
validateField
|
24
|
+
[32m✓[39m [2mshould not return an error if field is valid (1 ms)[22m
|
25
|
+
[32m✓[39m [2mshould not return an error if a nested field is valid[22m
|
26
|
+
[32m✓[39m [2mshould return an error if field is invalid[22m
|
27
|
+
[32m✓[39m [2mshould return an error if a nested field is invalid[22m
|
28
|
+
withZod
|
29
|
+
[32m✓[39m [2mreturns coherent errors for complex schemas (1 ms)[22m
|
30
|
+
[32m✓[39m [2mreturns errors for fields that are unions[22m
|
31
|
+
|
32
|
+
[1mTest Suites: [22m[1m[32m1 passed[39m[22m, 1 total
|
33
|
+
[1mTests: [22m[1m[32m20 passed[39m[22m, 20 total
|
34
|
+
[1mSnapshots: [22m0 total
|
35
|
+
[1mTime:[22m 1.1 s, estimated 2 s
|
36
|
+
[2mRan all test suites[22m[2m matching [22m/src/i[2m.[22m
|
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/
|
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 "
|
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
|
-
|
170
|
-
|
171
|
-
|
172
|
-
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
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
|
-
|
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;
|
package/browser/ValidatedForm.js
CHANGED
@@ -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
|
8
|
+
function useFieldErrorsFromBackend(fetcher, subaction) {
|
9
|
+
var _a, _b;
|
8
10
|
const actionData = useActionData();
|
9
|
-
|
10
|
-
|
11
|
-
|
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 (
|
14
|
-
setFieldErrors(
|
15
|
-
}, [
|
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
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
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) =>
|
27
|
-
|
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
|
30
|
-
const
|
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
|
-
|
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
|
-
},
|
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
|
}
|
package/browser/hooks.d.ts
CHANGED
@@ -1,8 +1,33 @@
|
|
1
|
-
export declare
|
2
|
-
|
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
|
-
|
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
|
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
|
-
|
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;
|
package/browser/index.d.ts
CHANGED
@@ -3,3 +3,6 @@ export * from "./server";
|
|
3
3
|
export * from "./ValidatedForm";
|
4
4
|
export * from "./validation/types";
|
5
5
|
export * from "./validation/withYup";
|
6
|
+
export * from "./validation/withZod";
|
7
|
+
export * from "./validation/createValidator";
|
8
|
+
export type { FormContextValue } from "./internal/formContext";
|
package/browser/index.js
CHANGED
@@ -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
|
package/browser/internal/util.js
CHANGED
File without changes
|
package/browser/server.d.ts
CHANGED
@@ -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
|
+
}
|