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
@@ -1,6 +1,8 @@
|
|
1
1
|
import * as yup from "yup";
|
2
2
|
import { z } from "zod";
|
3
3
|
import { withYup } from "..";
|
4
|
+
import { objectFromPathEntries } from "../internal/flatten";
|
5
|
+
import { TestFormData } from "../test-data/testFormData";
|
4
6
|
import { withZod } from "./withZod";
|
5
7
|
const validationTestCases = [
|
6
8
|
{
|
@@ -77,9 +79,75 @@ describe("Validation", () => {
|
|
77
79
|
"address.country": anyString,
|
78
80
|
"address.streetAddress": anyString,
|
79
81
|
"pets[0].name": anyString,
|
82
|
+
_submittedData: obj,
|
80
83
|
},
|
81
84
|
});
|
82
85
|
});
|
86
|
+
it("should unflatten data when validating", () => {
|
87
|
+
const data = {
|
88
|
+
firstName: "John",
|
89
|
+
lastName: "Doe",
|
90
|
+
age: 30,
|
91
|
+
"address.streetAddress": "123 Main St",
|
92
|
+
"address.city": "Anytown",
|
93
|
+
"address.country": "USA",
|
94
|
+
"pets[0].animal": "dog",
|
95
|
+
"pets[0].name": "Fido",
|
96
|
+
};
|
97
|
+
expect(validator.validate(data)).toEqual({
|
98
|
+
data: {
|
99
|
+
firstName: "John",
|
100
|
+
lastName: "Doe",
|
101
|
+
age: 30,
|
102
|
+
address: {
|
103
|
+
streetAddress: "123 Main St",
|
104
|
+
city: "Anytown",
|
105
|
+
country: "USA",
|
106
|
+
},
|
107
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
108
|
+
},
|
109
|
+
error: undefined,
|
110
|
+
});
|
111
|
+
});
|
112
|
+
it("should accept FormData directly and return errors", () => {
|
113
|
+
const formData = new TestFormData();
|
114
|
+
formData.set("firstName", "John");
|
115
|
+
formData.set("lastName", "Doe");
|
116
|
+
formData.set("address.streetAddress", "123 Main St");
|
117
|
+
formData.set("address.country", "USA");
|
118
|
+
formData.set("pets[0].animal", "dog");
|
119
|
+
expect(validator.validate(formData)).toEqual({
|
120
|
+
data: undefined,
|
121
|
+
error: {
|
122
|
+
"address.city": anyString,
|
123
|
+
"pets[0].name": anyString,
|
124
|
+
_submittedData: objectFromPathEntries([...formData.entries()]),
|
125
|
+
},
|
126
|
+
});
|
127
|
+
});
|
128
|
+
it("should accept FormData directly and return valid data", () => {
|
129
|
+
const formData = new TestFormData();
|
130
|
+
formData.set("firstName", "John");
|
131
|
+
formData.set("lastName", "Doe");
|
132
|
+
formData.set("address.streetAddress", "123 Main St");
|
133
|
+
formData.set("address.country", "USA");
|
134
|
+
formData.set("address.city", "Anytown");
|
135
|
+
formData.set("pets[0].animal", "dog");
|
136
|
+
formData.set("pets[0].name", "Fido");
|
137
|
+
expect(validator.validate(formData)).toEqual({
|
138
|
+
data: {
|
139
|
+
firstName: "John",
|
140
|
+
lastName: "Doe",
|
141
|
+
address: {
|
142
|
+
streetAddress: "123 Main St",
|
143
|
+
country: "USA",
|
144
|
+
city: "Anytown",
|
145
|
+
},
|
146
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
147
|
+
},
|
148
|
+
error: undefined,
|
149
|
+
});
|
150
|
+
});
|
83
151
|
});
|
84
152
|
describe("validateField", () => {
|
85
153
|
it("should not return an error if field is valid", () => {
|
@@ -174,6 +242,7 @@ describe("withZod", () => {
|
|
174
242
|
type: anyString,
|
175
243
|
bar: anyString,
|
176
244
|
foo: anyString,
|
245
|
+
_submittedData: obj,
|
177
246
|
},
|
178
247
|
});
|
179
248
|
});
|
@@ -192,6 +261,7 @@ describe("withZod", () => {
|
|
192
261
|
error: {
|
193
262
|
field1: anyString,
|
194
263
|
field2: anyString,
|
264
|
+
_submittedData: obj,
|
195
265
|
},
|
196
266
|
});
|
197
267
|
expect(validator.validateField(obj, "field1")).toEqual({
|
@@ -1,3 +1,6 @@
|
|
1
1
|
import type { AnyObjectSchema, InferType } from "yup";
|
2
2
|
import { Validator } from "./types";
|
3
|
+
/**
|
4
|
+
* Create a `Validator` using a `yup` schema.
|
5
|
+
*/
|
3
6
|
export declare const withYup: <Schema extends AnyObjectSchema>(validationSchema: Schema) => Validator<InferType<Schema>>;
|
@@ -17,6 +17,9 @@ function pathToString(array) {
|
|
17
17
|
return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
|
18
18
|
}, "");
|
19
19
|
}
|
20
|
+
/**
|
21
|
+
* Create a validator using a `zod` schema.
|
22
|
+
*/
|
20
23
|
export function withZod(zodSchema) {
|
21
24
|
return createValidator({
|
22
25
|
validate: (value) => {
|
package/build/ValidatedForm.d.ts
CHANGED
@@ -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/build/ValidatedForm.js
CHANGED
@@ -9,36 +9,87 @@ const react_1 = require("@remix-run/react");
|
|
9
9
|
const react_2 = require("react");
|
10
10
|
const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
|
11
11
|
const formContext_1 = require("./internal/formContext");
|
12
|
+
const submissionCallbacks_1 = require("./internal/submissionCallbacks");
|
12
13
|
const util_1 = require("./internal/util");
|
13
|
-
function
|
14
|
+
function useFieldErrorsFromBackend(fetcher, subaction) {
|
15
|
+
var _a, _b;
|
14
16
|
const actionData = (0, react_1.useActionData)();
|
15
|
-
|
16
|
-
|
17
|
-
|
17
|
+
if (fetcher)
|
18
|
+
return (_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors;
|
19
|
+
if (!actionData)
|
20
|
+
return null;
|
21
|
+
if (actionData.fieldErrors) {
|
22
|
+
const submittedData = (_b = actionData.fieldErrors) === null || _b === void 0 ? void 0 : _b._submittedData;
|
23
|
+
const subactionsMatch = subaction
|
24
|
+
? subaction === (submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction)
|
25
|
+
: !(submittedData === null || submittedData === void 0 ? void 0 : submittedData.subaction);
|
26
|
+
return subactionsMatch ? actionData.fieldErrors : null;
|
27
|
+
}
|
28
|
+
return null;
|
29
|
+
}
|
30
|
+
function useFieldErrors(fieldErrorsFromBackend) {
|
31
|
+
const [fieldErrors, setFieldErrors] = (0, react_2.useState)(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
|
18
32
|
(0, react_2.useEffect)(() => {
|
19
|
-
if (
|
20
|
-
setFieldErrors(
|
21
|
-
}, [
|
33
|
+
if (fieldErrorsFromBackend)
|
34
|
+
setFieldErrors(fieldErrorsFromBackend);
|
35
|
+
}, [fieldErrorsFromBackend]);
|
22
36
|
return [fieldErrors, setFieldErrors];
|
23
37
|
}
|
24
|
-
const useIsSubmitting = (action, fetcher) => {
|
38
|
+
const useIsSubmitting = (action, subaction, fetcher) => {
|
25
39
|
const actionForCurrentPage = (0, react_1.useFormAction)();
|
26
40
|
const pendingFormSubmit = (0, react_1.useTransition)().submission;
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
41
|
+
if (fetcher)
|
42
|
+
return fetcher.state === "submitting";
|
43
|
+
if (!pendingFormSubmit)
|
44
|
+
return false;
|
45
|
+
const { formData, action: pendingAction } = pendingFormSubmit;
|
46
|
+
const pendingSubAction = formData.get("subaction");
|
47
|
+
const expectedAction = action !== null && action !== void 0 ? action : actionForCurrentPage;
|
48
|
+
if (subaction)
|
49
|
+
return expectedAction === pendingAction && subaction === pendingSubAction;
|
50
|
+
return expectedAction === pendingAction && !pendingSubAction;
|
31
51
|
};
|
32
|
-
const getDataFromForm = (el) =>
|
33
|
-
|
52
|
+
const getDataFromForm = (el) => new FormData(el);
|
53
|
+
/**
|
54
|
+
* The purpose for this logic is to handle validation errors when javascript is disabled.
|
55
|
+
* Normally (without js), when a form is submitted and the action returns the validation errors,
|
56
|
+
* the form will be reset. The errors will be displayed on the correct fields,
|
57
|
+
* but all the values in the form will be gone. This is not good UX.
|
58
|
+
*
|
59
|
+
* To get around this, we return the submitted form data from the server,
|
60
|
+
* and use those to populate the form via `defaultValues`.
|
61
|
+
* This results in a more seamless UX akin to what you would see when js is enabled.
|
62
|
+
*
|
63
|
+
* One potential downside is that resetting the form will reset the form
|
64
|
+
* to the _new_ default values that were returned from the server with the validation errors.
|
65
|
+
* However, this case is less of a problem than the janky UX caused by losing the form values.
|
66
|
+
* It will only ever be a problem if the form includes a `<button type="reset" />`
|
67
|
+
* and only if JS is disabled.
|
68
|
+
*/
|
69
|
+
function useDefaultValues(fieldErrors, defaultValues) {
|
70
|
+
const defaultsFromValidationError = fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors._submittedData;
|
71
|
+
return defaultsFromValidationError !== null && defaultsFromValidationError !== void 0 ? defaultsFromValidationError : defaultValues;
|
72
|
+
}
|
73
|
+
/**
|
74
|
+
* The primary form component of `remix-validated-form`.
|
75
|
+
*/
|
76
|
+
function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, ...rest }) {
|
34
77
|
var _a;
|
35
|
-
const
|
36
|
-
const
|
78
|
+
const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
|
79
|
+
const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
|
80
|
+
const isSubmitting = useIsSubmitting(action, subaction, fetcher);
|
81
|
+
const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
|
37
82
|
const formRef = (0, react_2.useRef)(null);
|
83
|
+
(0, submissionCallbacks_1.useSubmitComplete)(isSubmitting, () => {
|
84
|
+
var _a;
|
85
|
+
if (!fieldErrorsFromBackend && resetAfterSubmit) {
|
86
|
+
(_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
|
87
|
+
}
|
88
|
+
});
|
38
89
|
const contextValue = (0, react_2.useMemo)(() => ({
|
39
90
|
fieldErrors,
|
40
91
|
action,
|
41
|
-
defaultValues,
|
92
|
+
defaultValues: defaultsToUse,
|
42
93
|
isSubmitting: isSubmitting !== null && isSubmitting !== void 0 ? isSubmitting : false,
|
43
94
|
clearError: (fieldName) => {
|
44
95
|
setFieldErrors((prev) => (0, util_1.omit)(prev, fieldName));
|
@@ -56,7 +107,7 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
|
|
56
107
|
}), [
|
57
108
|
fieldErrors,
|
58
109
|
action,
|
59
|
-
|
110
|
+
defaultsToUse,
|
60
111
|
isSubmitting,
|
61
112
|
setFieldErrors,
|
62
113
|
validator,
|
@@ -71,6 +122,11 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
|
|
71
122
|
else {
|
72
123
|
onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, event);
|
73
124
|
}
|
74
|
-
},
|
125
|
+
}, onReset: (event) => {
|
126
|
+
onReset === null || onReset === void 0 ? void 0 : onReset(event);
|
127
|
+
if (event.defaultPrevented)
|
128
|
+
return;
|
129
|
+
setFieldErrors({});
|
130
|
+
}, children: (0, jsx_runtime_1.jsxs)(formContext_1.FormContext.Provider, { value: contextValue, children: [(0, jsx_runtime_1.jsx)("input", { type: "hidden", value: subaction, name: "subaction" }, void 0), children] }, void 0) }, void 0));
|
75
131
|
}
|
76
132
|
exports.ValidatedForm = ValidatedForm;
|
package/build/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/build/hooks.js
CHANGED
@@ -8,6 +8,9 @@ const get_1 = __importDefault(require("lodash/get"));
|
|
8
8
|
const toPath_1 = __importDefault(require("lodash/toPath"));
|
9
9
|
const react_1 = require("react");
|
10
10
|
const formContext_1 = require("./internal/formContext");
|
11
|
+
/**
|
12
|
+
* Provides the data and helpers necessary to set up a field.
|
13
|
+
*/
|
11
14
|
const useField = (name) => {
|
12
15
|
const { fieldErrors, clearError, validateField, defaultValues } = (0, react_1.useContext)(formContext_1.FormContext);
|
13
16
|
const field = (0, react_1.useMemo)(() => ({
|
@@ -23,8 +26,16 @@ const useField = (name) => {
|
|
23
26
|
return field;
|
24
27
|
};
|
25
28
|
exports.useField = useField;
|
26
|
-
|
29
|
+
/**
|
30
|
+
* Provides access to the entire form context.
|
31
|
+
* This is not usually necessary, but can be useful for advanced use cases.
|
32
|
+
*/
|
27
33
|
const useFormContext = () => (0, react_1.useContext)(formContext_1.FormContext);
|
28
34
|
exports.useFormContext = useFormContext;
|
35
|
+
/**
|
36
|
+
* Returns whether or not the parent form is currently being submitted.
|
37
|
+
* This is different from remix's `useTransition().submission` in that it
|
38
|
+
* is aware of what form it's in and when _that_ form is being submitted.
|
39
|
+
*/
|
29
40
|
const useIsSubmitting = () => (0, exports.useFormContext)().isSubmitting;
|
30
41
|
exports.useIsSubmitting = useIsSubmitting;
|
package/build/index.d.ts
CHANGED
package/build/index.js
CHANGED
@@ -16,3 +16,4 @@ __exportStar(require("./ValidatedForm"), exports);
|
|
16
16
|
__exportStar(require("./validation/types"), exports);
|
17
17
|
__exportStar(require("./validation/withYup"), exports);
|
18
18
|
__exportStar(require("./validation/withZod"), exports);
|
19
|
+
__exportStar(require("./validation/createValidator"), exports);
|
@@ -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;
|
@@ -3,23 +3,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
4
|
};
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
-
exports.flatten = exports.
|
7
|
-
// `flatten`
|
6
|
+
exports.flatten = exports.objectFromPathEntries = void 0;
|
7
|
+
// `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.
|
8
8
|
const assign_1 = __importDefault(require("lodash/assign"));
|
9
9
|
const isArray_1 = __importDefault(require("lodash/isArray"));
|
10
10
|
const isObject_1 = __importDefault(require("lodash/isObject"));
|
11
11
|
const keys_1 = __importDefault(require("lodash/keys"));
|
12
12
|
const mapKeys_1 = __importDefault(require("lodash/mapKeys"));
|
13
|
-
const reduce_1 = __importDefault(require("lodash/reduce"));
|
14
13
|
const set_1 = __importDefault(require("lodash/set"));
|
15
14
|
const transform_1 = __importDefault(require("lodash/transform"));
|
16
|
-
|
17
|
-
|
18
|
-
return (0, reduce_1.default)(params, function (result, value, key) {
|
19
|
-
return (0, set_1.default)(result, key, value);
|
20
|
-
}, {});
|
21
|
-
}
|
22
|
-
exports.unflatten = unflatten;
|
15
|
+
const objectFromPathEntries = (entries) => entries.reduce((acc, [key, value]) => (0, set_1.default)(acc, key, value), {});
|
16
|
+
exports.objectFromPathEntries = objectFromPathEntries;
|
23
17
|
/** Flatten an object so there are no nested objects or arrays */
|
24
18
|
function flatten(obj, preserveEmpty = false) {
|
25
19
|
return (0, transform_1.default)(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,17 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.useSubmitComplete = void 0;
|
4
|
+
const react_1 = require("react");
|
5
|
+
function useSubmitComplete(isSubmitting, callback) {
|
6
|
+
const isPending = (0, react_1.useRef)(false);
|
7
|
+
(0, react_1.useEffect)(() => {
|
8
|
+
if (isSubmitting) {
|
9
|
+
isPending.current = true;
|
10
|
+
}
|
11
|
+
if (!isSubmitting && isPending.current) {
|
12
|
+
isPending.current = false;
|
13
|
+
callback();
|
14
|
+
}
|
15
|
+
});
|
16
|
+
}
|
17
|
+
exports.useSubmitComplete = useSubmitComplete;
|
package/build/internal/util.d.ts
CHANGED
File without changes
|
package/build/internal/util.js
CHANGED
File without changes
|
package/build/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/build/server.js
CHANGED
@@ -2,5 +2,10 @@
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.validationError = void 0;
|
4
4
|
const server_runtime_1 = require("@remix-run/server-runtime");
|
5
|
+
/**
|
6
|
+
* Takes the errors from a `Validator` and returns a `Response`.
|
7
|
+
* The `ValidatedForm` on the frontend will automatically display the errors
|
8
|
+
* if this is returned from the action.
|
9
|
+
*/
|
5
10
|
const validationError = (errors) => (0, server_runtime_1.json)({ fieldErrors: errors }, { status: 422 });
|
6
11
|
exports.validationError = validationError;
|
@@ -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,50 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.TestFormData = void 0;
|
4
|
+
// Copied from remix to use in tests
|
5
|
+
// https://github.com/remix-run/remix/blob/a69a631cb5add72d5fb24211ab2a0be367b6f2fd/packages/remix-node/form-data.ts
|
6
|
+
class TestFormData {
|
7
|
+
constructor(body) {
|
8
|
+
this._params = new URLSearchParams(body);
|
9
|
+
}
|
10
|
+
append(name, value, fileName) {
|
11
|
+
if (typeof value !== "string") {
|
12
|
+
throw new Error("formData.append can only accept a string");
|
13
|
+
}
|
14
|
+
this._params.append(name, value);
|
15
|
+
}
|
16
|
+
delete(name) {
|
17
|
+
this._params.delete(name);
|
18
|
+
}
|
19
|
+
get(name) {
|
20
|
+
return this._params.get(name);
|
21
|
+
}
|
22
|
+
getAll(name) {
|
23
|
+
return this._params.getAll(name);
|
24
|
+
}
|
25
|
+
has(name) {
|
26
|
+
return this._params.has(name);
|
27
|
+
}
|
28
|
+
set(name, value, fileName) {
|
29
|
+
if (typeof value !== "string") {
|
30
|
+
throw new Error("formData.set can only accept a string");
|
31
|
+
}
|
32
|
+
this._params.set(name, value);
|
33
|
+
}
|
34
|
+
forEach(callbackfn, thisArg) {
|
35
|
+
this._params.forEach(callbackfn, thisArg);
|
36
|
+
}
|
37
|
+
entries() {
|
38
|
+
return this._params.entries();
|
39
|
+
}
|
40
|
+
keys() {
|
41
|
+
return this._params.keys();
|
42
|
+
}
|
43
|
+
values() {
|
44
|
+
return this._params.values();
|
45
|
+
}
|
46
|
+
*[Symbol.iterator]() {
|
47
|
+
yield* this._params;
|
48
|
+
}
|
49
|
+
}
|
50
|
+
exports.TestFormData = TestFormData;
|
@@ -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,12 +1,34 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.createValidator = void 0;
|
4
|
-
const flatten_1 = require("../flatten");
|
5
|
-
|
4
|
+
const flatten_1 = require("../internal/flatten");
|
5
|
+
const preprocessFormData = (data) => {
|
6
|
+
// A slightly janky way of determining if the data is a FormData object
|
7
|
+
// since node doesn't really have FormData
|
8
|
+
if ("entries" in data && typeof data.entries === "function")
|
9
|
+
return (0, flatten_1.objectFromPathEntries)([...data.entries()]);
|
10
|
+
return (0, flatten_1.objectFromPathEntries)(Object.entries(data));
|
11
|
+
};
|
12
|
+
/**
|
13
|
+
* Used to create a validator for a form.
|
14
|
+
* It provides built-in handling for unflattening nested objects and
|
15
|
+
* extracting the values from FormData.
|
16
|
+
*/
|
6
17
|
function createValidator(validator) {
|
7
18
|
return {
|
8
|
-
validate: (value) =>
|
9
|
-
|
19
|
+
validate: (value) => {
|
20
|
+
const data = preprocessFormData(value);
|
21
|
+
const result = validator.validate(data);
|
22
|
+
if (result.error) {
|
23
|
+
// Ideally, we should probably be returning a nested object like
|
24
|
+
// { fieldErrors: {}, submittedData: {} }
|
25
|
+
// We should do this in the next major version of the library
|
26
|
+
// but for now, we can sneak it in with the fieldErrors.
|
27
|
+
result.error._submittedData = data;
|
28
|
+
}
|
29
|
+
return result;
|
30
|
+
},
|
31
|
+
validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
|
10
32
|
};
|
11
33
|
}
|
12
34
|
exports.createValidator = createValidator;
|
@@ -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;
|