remix-validated-form 1.1.1-beta.0 → 2.0.0-beta.3
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 +0 -0
- package/.turbo/turbo-test.log +36 -0
- package/README.md +26 -21
- package/browser/ValidatedForm.d.ts +35 -1
- package/browser/ValidatedForm.js +76 -20
- package/browser/hooks.d.ts +28 -3
- package/browser/hooks.js +12 -1
- package/browser/index.d.ts +2 -0
- package/browser/index.js +1 -0
- package/browser/{flatten.d.ts → internal/flatten.d.ts} +2 -3
- package/browser/{flatten.js → internal/flatten.js} +2 -8
- 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 +5 -1
- package/browser/validation/createValidator.js +26 -4
- package/browser/validation/types.d.ts +12 -0
- package/browser/validation/types.js +0 -0
- package/browser/validation/validation.test.d.ts +0 -0
- package/browser/validation/validation.test.js +70 -0
- package/browser/validation/withYup.d.ts +3 -0
- package/browser/validation/withYup.js +3 -0
- package/browser/validation/withZod.d.ts +3 -0
- package/browser/validation/withZod.js +3 -0
- package/build/ValidatedForm.d.ts +35 -1
- package/build/ValidatedForm.js +75 -19
- package/build/hooks.d.ts +28 -3
- package/build/hooks.js +12 -1
- package/build/index.d.ts +2 -0
- package/build/index.js +1 -0
- package/build/{flatten.d.ts → internal/flatten.d.ts} +2 -3
- package/build/{flatten.js → internal/flatten.js} +4 -10
- 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 +5 -1
- package/build/validation/createValidator.js +26 -4
- package/build/validation/types.d.ts +12 -0
- package/build/validation/types.js +0 -0
- package/build/validation/validation.test.d.ts +0 -0
- package/build/validation/validation.test.js +70 -0
- package/build/validation/withYup.d.ts +3 -0
- package/build/validation/withYup.js +3 -0
- package/build/validation/withZod.d.ts +3 -0
- package/build/validation/withZod.js +3 -0
- package/jest.config.js +5 -0
- package/package.json +8 -33
- 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 -10
- package/LICENSE +0 -21
- package/sample-app/.env +0 -7
- package/sample-app/README.md +0 -53
- package/sample-app/app/components/ErrorBox.tsx +0 -34
- package/sample-app/app/components/FormInput.tsx +0 -40
- package/sample-app/app/components/FormSelect.tsx +0 -37
- package/sample-app/app/components/SubjectForm.tsx +0 -150
- package/sample-app/app/entry.client.tsx +0 -4
- package/sample-app/app/entry.server.tsx +0 -21
- package/sample-app/app/root.tsx +0 -92
- package/sample-app/app/routes/index.tsx +0 -5
- package/sample-app/app/routes/subjects/$id.edit.tsx +0 -100
- package/sample-app/app/routes/subjects/index.tsx +0 -112
- package/sample-app/app/routes/subjects/new.tsx +0 -48
- package/sample-app/app/services/db.server.ts +0 -23
- package/sample-app/app/types.ts +0 -6
- package/sample-app/package-lock.json +0 -4617
- package/sample-app/package.json +0 -36
- package/sample-app/prisma/dev.db +0 -0
- package/sample-app/prisma/schema.prisma +0 -34
- package/sample-app/public/favicon.ico +0 -0
- package/sample-app/remix.config.js +0 -10
- package/sample-app/remix.env.d.ts +0 -2
File without changes
|
@@ -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
@@ -15,6 +15,7 @@ A form library built for [remix](https://remix.run) to make validation easy.
|
|
15
15
|
https://user-images.githubusercontent.com/2811287/145734901-700a5085-a10b-4d89-88e1-5de9142b1e85.mov
|
16
16
|
|
17
17
|
To run `sample-app`:
|
18
|
+
|
18
19
|
```
|
19
20
|
git clone https://github.com/airjp73/remix-validated-form
|
20
21
|
cd remix-validated-form
|
@@ -101,9 +102,7 @@ const validator = withYup(
|
|
101
102
|
);
|
102
103
|
|
103
104
|
export const action: ActionFunction = async ({ request }) => {
|
104
|
-
const fieldValues = validator.validate(
|
105
|
-
Object.fromEntries(await request.formData())
|
106
|
-
);
|
105
|
+
const fieldValues = validator.validate(await request.formData());
|
107
106
|
if (fieldValues.error) return validationError(fieldValues.error);
|
108
107
|
const { firstName, lastName, email } = fieldValues.data;
|
109
108
|
|
@@ -141,7 +140,7 @@ export default function MyForm() {
|
|
141
140
|
|
142
141
|
## Nested objects and arrays
|
143
142
|
|
144
|
-
You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
|
143
|
+
You can use nested objects and arrays by using a period (`.`) or brackets (`[]`) for the field names.
|
145
144
|
|
146
145
|
```tsx
|
147
146
|
export default function MyForm() {
|
@@ -198,7 +197,10 @@ type Validator<DataType> = {
|
|
198
197
|
In order to make an adapter for your validation library of choice,
|
199
198
|
you can create a function that accepts a schema from the validation library and turns it into a validator.
|
200
199
|
|
201
|
-
Note the use of `createValidator`.
|
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`.
|
202
204
|
|
203
205
|
The out-of-the-box support for `yup` in this library works like this:
|
204
206
|
|
@@ -206,25 +208,28 @@ The out-of-the-box support for `yup` in this library works like this:
|
|
206
208
|
export const withYup = <Schema extends AnyObjectSchema>(
|
207
209
|
validationSchema: Schema
|
208
210
|
// For best result with Typescript, we should type the `Validator` we return based on the provided schema
|
209
|
-
): Validator<InferType<Schema>> =>
|
210
|
-
|
211
|
-
|
212
|
-
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
}
|
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
|
+
});
|
223
226
|
```
|
224
227
|
|
225
228
|
# Frequenty Asked Questions
|
226
229
|
|
227
230
|
## Why are my fields triggering the native HTML validations before `remix-validated-form` ones?
|
228
|
-
This is happening because you or the library you are using are passing the `required` attribute to the fields. This library doesn't take care of eliminating them and it's up to the user how they want to manage the validation errors. If you wan't to disable all native HTML validations you can add `noValidate` to `<ValidatedForm>`. We recommend this approach since the validation will still work even if JS is disabled.
|
229
|
-
|
230
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 && resetAfterSubmit) {
|
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
@@ -2,6 +2,9 @@ import get from "lodash/get";
|
|
2
2
|
import toPath from "lodash/toPath";
|
3
3
|
import { useContext, useMemo } from "react";
|
4
4
|
import { FormContext } from "./internal/formContext";
|
5
|
+
/**
|
6
|
+
* Provides the data and helpers necessary to set up a field.
|
7
|
+
*/
|
5
8
|
export const useField = (name) => {
|
6
9
|
const { fieldErrors, clearError, validateField, defaultValues } = useContext(FormContext);
|
7
10
|
const field = useMemo(() => ({
|
@@ -16,6 +19,14 @@ export const useField = (name) => {
|
|
16
19
|
}), [clearError, defaultValues, fieldErrors, name, validateField]);
|
17
20
|
return field;
|
18
21
|
};
|
19
|
-
|
22
|
+
/**
|
23
|
+
* Provides access to the entire form context.
|
24
|
+
* This is not usually necessary, but can be useful for advanced use cases.
|
25
|
+
*/
|
20
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
|
+
*/
|
21
32
|
export const useIsSubmitting = () => useFormContext().isSubmitting;
|
package/browser/index.d.ts
CHANGED
package/browser/index.js
CHANGED
@@ -1,5 +1,4 @@
|
|
1
|
-
import { GenericObject } from "
|
2
|
-
|
3
|
-
export declare function unflatten(params: GenericObject): {};
|
1
|
+
import { GenericObject } from "..";
|
2
|
+
export declare const objectFromPathEntries: (entries: [string, any][]) => {};
|
4
3
|
/** Flatten an object so there are no nested objects or arrays */
|
5
4
|
export declare function flatten(obj: GenericObject, preserveEmpty?: boolean): GenericObject;
|
@@ -1,18 +1,12 @@
|
|
1
|
-
// `flatten`
|
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
2
|
import assign from "lodash/assign";
|
3
3
|
import isArray from "lodash/isArray";
|
4
4
|
import isObject from "lodash/isObject";
|
5
5
|
import keys from "lodash/keys";
|
6
6
|
import mapKeys from "lodash/mapKeys";
|
7
|
-
import reduce from "lodash/reduce";
|
8
7
|
import set from "lodash/set";
|
9
8
|
import transform from "lodash/transform";
|
10
|
-
|
11
|
-
export function unflatten(params) {
|
12
|
-
return reduce(params, function (result, value, key) {
|
13
|
-
return set(result, key, value);
|
14
|
-
}, {});
|
15
|
-
}
|
9
|
+
export const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => set(acc, key, value), {});
|
16
10
|
/** Flatten an object so there are no nested objects or arrays */
|
17
11
|
export function flatten(obj, preserveEmpty = false) {
|
18
12
|
return transform(obj, function (result, value, key) {
|
@@ -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
|
+
}
|
@@ -0,0 +1,46 @@
|
|
1
|
+
// Copied from remix to use in tests
|
2
|
+
// https://github.com/remix-run/remix/blob/a69a631cb5add72d5fb24211ab2a0be367b6f2fd/packages/remix-node/form-data.ts
|
3
|
+
export class TestFormData {
|
4
|
+
constructor(body) {
|
5
|
+
this._params = new URLSearchParams(body);
|
6
|
+
}
|
7
|
+
append(name, value, fileName) {
|
8
|
+
if (typeof value !== "string") {
|
9
|
+
throw new Error("formData.append can only accept a string");
|
10
|
+
}
|
11
|
+
this._params.append(name, value);
|
12
|
+
}
|
13
|
+
delete(name) {
|
14
|
+
this._params.delete(name);
|
15
|
+
}
|
16
|
+
get(name) {
|
17
|
+
return this._params.get(name);
|
18
|
+
}
|
19
|
+
getAll(name) {
|
20
|
+
return this._params.getAll(name);
|
21
|
+
}
|
22
|
+
has(name) {
|
23
|
+
return this._params.has(name);
|
24
|
+
}
|
25
|
+
set(name, value, fileName) {
|
26
|
+
if (typeof value !== "string") {
|
27
|
+
throw new Error("formData.set can only accept a string");
|
28
|
+
}
|
29
|
+
this._params.set(name, value);
|
30
|
+
}
|
31
|
+
forEach(callbackfn, thisArg) {
|
32
|
+
this._params.forEach(callbackfn, thisArg);
|
33
|
+
}
|
34
|
+
entries() {
|
35
|
+
return this._params.entries();
|
36
|
+
}
|
37
|
+
keys() {
|
38
|
+
return this._params.keys();
|
39
|
+
}
|
40
|
+
values() {
|
41
|
+
return this._params.values();
|
42
|
+
}
|
43
|
+
*[Symbol.iterator]() {
|
44
|
+
yield* this._params;
|
45
|
+
}
|
46
|
+
}
|
@@ -1,3 +1,7 @@
|
|
1
1
|
import { Validator } from "..";
|
2
|
-
/**
|
2
|
+
/**
|
3
|
+
* Used to create a validator for a form.
|
4
|
+
* It provides built-in handling for unflattening nested objects and
|
5
|
+
* extracting the values from FormData.
|
6
|
+
*/
|
3
7
|
export declare function createValidator<T>(validator: Validator<T>): Validator<T>;
|
@@ -1,8 +1,30 @@
|
|
1
|
-
import {
|
2
|
-
|
1
|
+
import { objectFromPathEntries } from "../internal/flatten";
|
2
|
+
const preprocessFormData = (data) => {
|
3
|
+
// A slightly janky way of determining if the data is a FormData object
|
4
|
+
// since node doesn't really have FormData
|
5
|
+
if ("entries" in data && typeof data.entries === "function")
|
6
|
+
return objectFromPathEntries([...data.entries()]);
|
7
|
+
return objectFromPathEntries(Object.entries(data));
|
8
|
+
};
|
9
|
+
/**
|
10
|
+
* Used to create a validator for a form.
|
11
|
+
* It provides built-in handling for unflattening nested objects and
|
12
|
+
* extracting the values from FormData.
|
13
|
+
*/
|
3
14
|
export function createValidator(validator) {
|
4
15
|
return {
|
5
|
-
validate: (value) =>
|
6
|
-
|
16
|
+
validate: (value) => {
|
17
|
+
const data = preprocessFormData(value);
|
18
|
+
const result = validator.validate(data);
|
19
|
+
if (result.error) {
|
20
|
+
// Ideally, we should probably be returning a nested object like
|
21
|
+
// { fieldErrors: {}, submittedData: {} }
|
22
|
+
// We should do this in the next major version of the library
|
23
|
+
// but for now, we can sneak it in with the fieldErrors.
|
24
|
+
result.error._submittedData = data;
|
25
|
+
}
|
26
|
+
return result;
|
27
|
+
},
|
28
|
+
validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
|
7
29
|
};
|
8
30
|
}
|
@@ -1,7 +1,13 @@
|
|
1
1
|
export declare type FieldErrors = Record<string, string>;
|
2
|
+
export declare type FieldErrorsWithData = FieldErrors & {
|
3
|
+
_submittedData: any;
|
4
|
+
};
|
2
5
|
export declare type GenericObject = {
|
3
6
|
[key: string]: any;
|
4
7
|
};
|
8
|
+
/**
|
9
|
+
* The result when validating a form.
|
10
|
+
*/
|
5
11
|
export declare type ValidationResult<DataType> = {
|
6
12
|
data: DataType;
|
7
13
|
error: undefined;
|
@@ -9,9 +15,15 @@ export declare type ValidationResult<DataType> = {
|
|
9
15
|
error: FieldErrors;
|
10
16
|
data: undefined;
|
11
17
|
};
|
18
|
+
/**
|
19
|
+
* The result when validating an individual field in a form.
|
20
|
+
*/
|
12
21
|
export declare type ValidateFieldResult = {
|
13
22
|
error?: string;
|
14
23
|
};
|
24
|
+
/**
|
25
|
+
* A `Validator` can be passed to the `validator` prop of a `ValidatedForm`.
|
26
|
+
*/
|
15
27
|
export declare type Validator<DataType> = {
|
16
28
|
validate: (unvalidatedData: GenericObject) => ValidationResult<DataType>;
|
17
29
|
validateField: (unvalidatedData: GenericObject, field: string) => ValidateFieldResult;
|
File without changes
|
File without changes
|