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
|
File without changes
|
@@ -22,6 +22,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
22
|
const yup = __importStar(require("yup"));
|
23
23
|
const zod_1 = require("zod");
|
24
24
|
const __1 = require("..");
|
25
|
+
const flatten_1 = require("../internal/flatten");
|
26
|
+
const testFormData_1 = require("../test-data/testFormData");
|
25
27
|
const withZod_1 = require("./withZod");
|
26
28
|
const validationTestCases = [
|
27
29
|
{
|
@@ -98,9 +100,75 @@ describe("Validation", () => {
|
|
98
100
|
"address.country": anyString,
|
99
101
|
"address.streetAddress": anyString,
|
100
102
|
"pets[0].name": anyString,
|
103
|
+
_submittedData: obj,
|
101
104
|
},
|
102
105
|
});
|
103
106
|
});
|
107
|
+
it("should unflatten data when validating", () => {
|
108
|
+
const data = {
|
109
|
+
firstName: "John",
|
110
|
+
lastName: "Doe",
|
111
|
+
age: 30,
|
112
|
+
"address.streetAddress": "123 Main St",
|
113
|
+
"address.city": "Anytown",
|
114
|
+
"address.country": "USA",
|
115
|
+
"pets[0].animal": "dog",
|
116
|
+
"pets[0].name": "Fido",
|
117
|
+
};
|
118
|
+
expect(validator.validate(data)).toEqual({
|
119
|
+
data: {
|
120
|
+
firstName: "John",
|
121
|
+
lastName: "Doe",
|
122
|
+
age: 30,
|
123
|
+
address: {
|
124
|
+
streetAddress: "123 Main St",
|
125
|
+
city: "Anytown",
|
126
|
+
country: "USA",
|
127
|
+
},
|
128
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
129
|
+
},
|
130
|
+
error: undefined,
|
131
|
+
});
|
132
|
+
});
|
133
|
+
it("should accept FormData directly and return errors", () => {
|
134
|
+
const formData = new testFormData_1.TestFormData();
|
135
|
+
formData.set("firstName", "John");
|
136
|
+
formData.set("lastName", "Doe");
|
137
|
+
formData.set("address.streetAddress", "123 Main St");
|
138
|
+
formData.set("address.country", "USA");
|
139
|
+
formData.set("pets[0].animal", "dog");
|
140
|
+
expect(validator.validate(formData)).toEqual({
|
141
|
+
data: undefined,
|
142
|
+
error: {
|
143
|
+
"address.city": anyString,
|
144
|
+
"pets[0].name": anyString,
|
145
|
+
_submittedData: (0, flatten_1.objectFromPathEntries)([...formData.entries()]),
|
146
|
+
},
|
147
|
+
});
|
148
|
+
});
|
149
|
+
it("should accept FormData directly and return valid data", () => {
|
150
|
+
const formData = new testFormData_1.TestFormData();
|
151
|
+
formData.set("firstName", "John");
|
152
|
+
formData.set("lastName", "Doe");
|
153
|
+
formData.set("address.streetAddress", "123 Main St");
|
154
|
+
formData.set("address.country", "USA");
|
155
|
+
formData.set("address.city", "Anytown");
|
156
|
+
formData.set("pets[0].animal", "dog");
|
157
|
+
formData.set("pets[0].name", "Fido");
|
158
|
+
expect(validator.validate(formData)).toEqual({
|
159
|
+
data: {
|
160
|
+
firstName: "John",
|
161
|
+
lastName: "Doe",
|
162
|
+
address: {
|
163
|
+
streetAddress: "123 Main St",
|
164
|
+
country: "USA",
|
165
|
+
city: "Anytown",
|
166
|
+
},
|
167
|
+
pets: [{ animal: "dog", name: "Fido" }],
|
168
|
+
},
|
169
|
+
error: undefined,
|
170
|
+
});
|
171
|
+
});
|
104
172
|
});
|
105
173
|
describe("validateField", () => {
|
106
174
|
it("should not return an error if field is valid", () => {
|
@@ -195,6 +263,7 @@ describe("withZod", () => {
|
|
195
263
|
type: anyString,
|
196
264
|
bar: anyString,
|
197
265
|
foo: anyString,
|
266
|
+
_submittedData: obj,
|
198
267
|
},
|
199
268
|
});
|
200
269
|
});
|
@@ -213,6 +282,7 @@ describe("withZod", () => {
|
|
213
282
|
error: {
|
214
283
|
field1: anyString,
|
215
284
|
field2: anyString,
|
285
|
+
_submittedData: obj,
|
216
286
|
},
|
217
287
|
});
|
218
288
|
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>>;
|
@@ -11,6 +11,9 @@ const validationErrorToFieldErrors = (error) => {
|
|
11
11
|
});
|
12
12
|
return fieldErrors;
|
13
13
|
};
|
14
|
+
/**
|
15
|
+
* Create a `Validator` using a `yup` schema.
|
16
|
+
*/
|
14
17
|
const withYup = (validationSchema) => {
|
15
18
|
return (0, createValidator_1.createValidator)({
|
16
19
|
validate: (data) => {
|
@@ -23,6 +23,9 @@ function pathToString(array) {
|
|
23
23
|
return string + (isNaN(Number(item)) ? prefix + item : "[" + item + "]");
|
24
24
|
}, "");
|
25
25
|
}
|
26
|
+
/**
|
27
|
+
* Create a validator using a `zod` schema.
|
28
|
+
*/
|
26
29
|
function withZod(zodSchema) {
|
27
30
|
return (0, createValidator_1.createValidator)({
|
28
31
|
validate: (value) => {
|
package/jest.config.js
CHANGED
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "remix-validated-form",
|
3
|
-
"version": "
|
3
|
+
"version": "2.0.0-beta.3",
|
4
4
|
"description": "Form component and utils for easy form validation in remix",
|
5
5
|
"browser": "./browser/index.js",
|
6
6
|
"main": "./build/index.js",
|
@@ -10,18 +10,14 @@
|
|
10
10
|
},
|
11
11
|
"sideEffects": false,
|
12
12
|
"scripts": {
|
13
|
-
"
|
14
|
-
"build
|
15
|
-
"build:
|
16
|
-
"build:
|
17
|
-
"build:sample": "tsc --project tsconfig.json --module CommonJS --outDir ./sample-app/remix-validated-form",
|
18
|
-
"sample-app": "npm run build:sample && cd sample-app && npm run dev",
|
13
|
+
"dev": "tsc --module ESNext --outDir ./browser --watch",
|
14
|
+
"build": "npm run build:browser && npm run build:main",
|
15
|
+
"build:browser": "tsc --module ESNext --outDir ./browser",
|
16
|
+
"build:main": "tsc --module CommonJS --outDir ./build",
|
19
17
|
"test": "jest src",
|
20
18
|
"test:watch": "jest src --watch",
|
21
|
-
"
|
22
|
-
"
|
23
|
-
"prepare": "husky install",
|
24
|
-
"prepublishOnly": "npm run build:browser && npm run build:main"
|
19
|
+
"prepublishOnly": "cp ../../README.md ./README.md && npm run build",
|
20
|
+
"postpublish": "rm ./README.md"
|
25
21
|
},
|
26
22
|
"author": {
|
27
23
|
"name": "Aaron Pettengill",
|
@@ -48,25 +44,10 @@
|
|
48
44
|
"@types/jest": "^27.0.3",
|
49
45
|
"@types/lodash": "^4.14.178",
|
50
46
|
"@types/react": "^17.0.37",
|
51
|
-
"@typescript-eslint/eslint-plugin": "^5.6.0",
|
52
|
-
"@typescript-eslint/parser": "^5.6.0",
|
53
|
-
"babel-eslint": "^10.1.0",
|
54
|
-
"eslint": "^7.32.0",
|
55
|
-
"eslint-config-react-app": "^6.0.0",
|
56
|
-
"eslint-plugin-cypress": "^2.12.1",
|
57
|
-
"eslint-plugin-flowtype": "^8.0.3",
|
58
|
-
"eslint-plugin-import": "^2.25.3",
|
59
|
-
"eslint-plugin-jsx-a11y": "^6.5.1",
|
60
|
-
"eslint-plugin-prettier": "^4.0.0",
|
61
|
-
"eslint-plugin-react": "^7.27.1",
|
62
|
-
"eslint-plugin-react-hooks": "^4.3.0",
|
63
47
|
"fetch-blob": "^3.1.3",
|
64
|
-
"husky": "^7.0.4",
|
65
|
-
"jest": "^27.4.4",
|
66
|
-
"lint-staged": "^12.1.2",
|
67
|
-
"prettier": "^2.5.1",
|
68
48
|
"react": "^17.0.2",
|
69
49
|
"ts-jest": "^27.1.1",
|
50
|
+
"tsconfig": "*",
|
70
51
|
"typescript": "^4.5.3",
|
71
52
|
"yup": "^0.32.11",
|
72
53
|
"zod": "^3.11.6"
|
@@ -74,11 +55,5 @@
|
|
74
55
|
"dependencies": {
|
75
56
|
"lodash": "^4.17.21",
|
76
57
|
"tiny-invariant": "^1.2.0"
|
77
|
-
},
|
78
|
-
"lint-staged": {
|
79
|
-
"**/*.{ts,tsx,js,jsx}": [
|
80
|
-
"prettier --write",
|
81
|
-
"eslint --cache --fix"
|
82
|
-
]
|
83
58
|
}
|
84
59
|
}
|
@@ -0,0 +1,227 @@
|
|
1
|
+
import {
|
2
|
+
Form as RemixForm,
|
3
|
+
useActionData,
|
4
|
+
useFetcher,
|
5
|
+
useFormAction,
|
6
|
+
useTransition,
|
7
|
+
} from "@remix-run/react";
|
8
|
+
import React, {
|
9
|
+
ComponentProps,
|
10
|
+
useEffect,
|
11
|
+
useMemo,
|
12
|
+
useRef,
|
13
|
+
useState,
|
14
|
+
} from "react";
|
15
|
+
import invariant from "tiny-invariant";
|
16
|
+
import { FormContext, FormContextValue } from "./internal/formContext";
|
17
|
+
import { useSubmitComplete } from "./internal/submissionCallbacks";
|
18
|
+
import { omit, mergeRefs } from "./internal/util";
|
19
|
+
import {
|
20
|
+
FieldErrors,
|
21
|
+
Validator,
|
22
|
+
FieldErrorsWithData,
|
23
|
+
} from "./validation/types";
|
24
|
+
|
25
|
+
export type FormProps<DataType> = {
|
26
|
+
/**
|
27
|
+
* A `Validator` object that describes how to validate the form.
|
28
|
+
*/
|
29
|
+
validator: Validator<DataType>;
|
30
|
+
/**
|
31
|
+
* A submit callback that gets called when the form is submitted
|
32
|
+
* after all validations have been run.
|
33
|
+
*/
|
34
|
+
onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void;
|
35
|
+
/**
|
36
|
+
* Allows you to provide a `fetcher` from remix's `useFetcher` hook.
|
37
|
+
* The form will use the fetcher for loading states, action data, etc
|
38
|
+
* instead of the default form action.
|
39
|
+
*/
|
40
|
+
fetcher?: ReturnType<typeof useFetcher>;
|
41
|
+
/**
|
42
|
+
* Accepts an object of default values for the form
|
43
|
+
* that will automatically be propagated to the form fields via `useField`.
|
44
|
+
*/
|
45
|
+
defaultValues?: Partial<DataType>;
|
46
|
+
/**
|
47
|
+
* A ref to the form element.
|
48
|
+
*/
|
49
|
+
formRef?: React.RefObject<HTMLFormElement>;
|
50
|
+
/**
|
51
|
+
* An optional sub-action to use for the form.
|
52
|
+
* Setting a value here will cause the form to be submitted with an extra `subaction` value.
|
53
|
+
* This can be useful when there are multiple forms on the screen handled by the same action.
|
54
|
+
*/
|
55
|
+
subaction?: string;
|
56
|
+
/**
|
57
|
+
* Reset the form to the default values after the form has been successfully submitted.
|
58
|
+
* This is useful if you want to submit the same form multiple times,
|
59
|
+
* and don't redirect in-between submissions.
|
60
|
+
*/
|
61
|
+
resetAfterSubmit?: boolean;
|
62
|
+
} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
|
63
|
+
|
64
|
+
function useFieldErrorsFromBackend(
|
65
|
+
fetcher?: ReturnType<typeof useFetcher>,
|
66
|
+
subaction?: string
|
67
|
+
): FieldErrorsWithData | null {
|
68
|
+
const actionData = useActionData<any>();
|
69
|
+
if (fetcher) return (fetcher.data as any)?.fieldErrors;
|
70
|
+
if (!actionData) return null;
|
71
|
+
if (actionData.fieldErrors) {
|
72
|
+
const submittedData = actionData.fieldErrors?._submittedData;
|
73
|
+
const subactionsMatch = subaction
|
74
|
+
? subaction === submittedData?.subaction
|
75
|
+
: !submittedData?.subaction;
|
76
|
+
return subactionsMatch ? actionData.fieldErrors : null;
|
77
|
+
}
|
78
|
+
return null;
|
79
|
+
}
|
80
|
+
|
81
|
+
function useFieldErrors(
|
82
|
+
fieldErrorsFromBackend?: any
|
83
|
+
): [FieldErrors, React.Dispatch<React.SetStateAction<FieldErrors>>] {
|
84
|
+
const [fieldErrors, setFieldErrors] = useState<FieldErrors>(
|
85
|
+
fieldErrorsFromBackend ?? {}
|
86
|
+
);
|
87
|
+
useEffect(() => {
|
88
|
+
if (fieldErrorsFromBackend) setFieldErrors(fieldErrorsFromBackend);
|
89
|
+
}, [fieldErrorsFromBackend]);
|
90
|
+
|
91
|
+
return [fieldErrors, setFieldErrors];
|
92
|
+
}
|
93
|
+
|
94
|
+
const useIsSubmitting = (
|
95
|
+
action?: string,
|
96
|
+
subaction?: string,
|
97
|
+
fetcher?: ReturnType<typeof useFetcher>
|
98
|
+
) => {
|
99
|
+
const actionForCurrentPage = useFormAction();
|
100
|
+
const pendingFormSubmit = useTransition().submission;
|
101
|
+
|
102
|
+
if (fetcher) return fetcher.state === "submitting";
|
103
|
+
if (!pendingFormSubmit) return false;
|
104
|
+
|
105
|
+
const { formData, action: pendingAction } = pendingFormSubmit;
|
106
|
+
const pendingSubAction = formData.get("subaction");
|
107
|
+
const expectedAction = action ?? actionForCurrentPage;
|
108
|
+
if (subaction)
|
109
|
+
return expectedAction === pendingAction && subaction === pendingSubAction;
|
110
|
+
return expectedAction === pendingAction && !pendingSubAction;
|
111
|
+
};
|
112
|
+
|
113
|
+
const getDataFromForm = (el: HTMLFormElement) => new FormData(el);
|
114
|
+
|
115
|
+
/**
|
116
|
+
* The purpose for this logic is to handle validation errors when javascript is disabled.
|
117
|
+
* Normally (without js), when a form is submitted and the action returns the validation errors,
|
118
|
+
* the form will be reset. The errors will be displayed on the correct fields,
|
119
|
+
* but all the values in the form will be gone. This is not good UX.
|
120
|
+
*
|
121
|
+
* To get around this, we return the submitted form data from the server,
|
122
|
+
* and use those to populate the form via `defaultValues`.
|
123
|
+
* This results in a more seamless UX akin to what you would see when js is enabled.
|
124
|
+
*
|
125
|
+
* One potential downside is that resetting the form will reset the form
|
126
|
+
* to the _new_ default values that were returned from the server with the validation errors.
|
127
|
+
* However, this case is less of a problem than the janky UX caused by losing the form values.
|
128
|
+
* It will only ever be a problem if the form includes a `<button type="reset" />`
|
129
|
+
* and only if JS is disabled.
|
130
|
+
*/
|
131
|
+
function useDefaultValues<DataType>(
|
132
|
+
fieldErrors?: FieldErrorsWithData | null,
|
133
|
+
defaultValues?: Partial<DataType>
|
134
|
+
) {
|
135
|
+
const defaultsFromValidationError = fieldErrors?._submittedData;
|
136
|
+
return defaultsFromValidationError ?? defaultValues;
|
137
|
+
}
|
138
|
+
|
139
|
+
/**
|
140
|
+
* The primary form component of `remix-validated-form`.
|
141
|
+
*/
|
142
|
+
export function ValidatedForm<DataType>({
|
143
|
+
validator,
|
144
|
+
onSubmit,
|
145
|
+
children,
|
146
|
+
fetcher,
|
147
|
+
action,
|
148
|
+
defaultValues,
|
149
|
+
formRef: formRefProp,
|
150
|
+
onReset,
|
151
|
+
subaction,
|
152
|
+
resetAfterSubmit,
|
153
|
+
...rest
|
154
|
+
}: FormProps<DataType>) {
|
155
|
+
const fieldErrorsFromBackend = useFieldErrorsFromBackend(fetcher, subaction);
|
156
|
+
const [fieldErrors, setFieldErrors] = useFieldErrors(fieldErrorsFromBackend);
|
157
|
+
const isSubmitting = useIsSubmitting(action, subaction, fetcher);
|
158
|
+
const defaultsToUse = useDefaultValues(fieldErrorsFromBackend, defaultValues);
|
159
|
+
const formRef = useRef<HTMLFormElement>(null);
|
160
|
+
useSubmitComplete(isSubmitting, () => {
|
161
|
+
if (!fieldErrorsFromBackend && resetAfterSubmit) {
|
162
|
+
formRef.current?.reset();
|
163
|
+
}
|
164
|
+
});
|
165
|
+
|
166
|
+
const contextValue = useMemo<FormContextValue>(
|
167
|
+
() => ({
|
168
|
+
fieldErrors,
|
169
|
+
action,
|
170
|
+
defaultValues: defaultsToUse,
|
171
|
+
isSubmitting: isSubmitting ?? false,
|
172
|
+
clearError: (fieldName) => {
|
173
|
+
setFieldErrors((prev) => omit(prev, fieldName));
|
174
|
+
},
|
175
|
+
validateField: (fieldName) => {
|
176
|
+
invariant(formRef.current, "Cannot find reference to form");
|
177
|
+
const { error } = validator.validateField(
|
178
|
+
getDataFromForm(formRef.current),
|
179
|
+
fieldName as any
|
180
|
+
);
|
181
|
+
if (error) {
|
182
|
+
setFieldErrors((prev) => ({
|
183
|
+
...prev,
|
184
|
+
[fieldName]: error,
|
185
|
+
}));
|
186
|
+
}
|
187
|
+
},
|
188
|
+
}),
|
189
|
+
[
|
190
|
+
fieldErrors,
|
191
|
+
action,
|
192
|
+
defaultsToUse,
|
193
|
+
isSubmitting,
|
194
|
+
setFieldErrors,
|
195
|
+
validator,
|
196
|
+
]
|
197
|
+
);
|
198
|
+
|
199
|
+
const Form = fetcher?.Form ?? RemixForm;
|
200
|
+
|
201
|
+
return (
|
202
|
+
<Form
|
203
|
+
ref={mergeRefs([formRef, formRefProp])}
|
204
|
+
{...rest}
|
205
|
+
action={action}
|
206
|
+
onSubmit={(event) => {
|
207
|
+
const result = validator.validate(getDataFromForm(event.currentTarget));
|
208
|
+
if (result.error) {
|
209
|
+
event.preventDefault();
|
210
|
+
setFieldErrors(result.error);
|
211
|
+
} else {
|
212
|
+
onSubmit?.(result.data, event);
|
213
|
+
}
|
214
|
+
}}
|
215
|
+
onReset={(event) => {
|
216
|
+
onReset?.(event);
|
217
|
+
if (event.defaultPrevented) return;
|
218
|
+
setFieldErrors({});
|
219
|
+
}}
|
220
|
+
>
|
221
|
+
<FormContext.Provider value={contextValue}>
|
222
|
+
<input type="hidden" value={subaction} name="subaction" />
|
223
|
+
{children}
|
224
|
+
</FormContext.Provider>
|
225
|
+
</Form>
|
226
|
+
);
|
227
|
+
}
|
package/src/hooks.ts
ADDED
@@ -0,0 +1,60 @@
|
|
1
|
+
import get from "lodash/get";
|
2
|
+
import toPath from "lodash/toPath";
|
3
|
+
import { useContext, useMemo } from "react";
|
4
|
+
import { FormContext } from "./internal/formContext";
|
5
|
+
|
6
|
+
export type FieldProps = {
|
7
|
+
/**
|
8
|
+
* The validation error message if there is one.
|
9
|
+
*/
|
10
|
+
error?: string;
|
11
|
+
/**
|
12
|
+
* Clears the error message.
|
13
|
+
*/
|
14
|
+
clearError: () => void;
|
15
|
+
/**
|
16
|
+
* Validates the field.
|
17
|
+
*/
|
18
|
+
validate: () => void;
|
19
|
+
/**
|
20
|
+
* The default value of the field, if there is one.
|
21
|
+
*/
|
22
|
+
defaultValue?: any;
|
23
|
+
};
|
24
|
+
|
25
|
+
/**
|
26
|
+
* Provides the data and helpers necessary to set up a field.
|
27
|
+
*/
|
28
|
+
export const useField = (name: string): FieldProps => {
|
29
|
+
const { fieldErrors, clearError, validateField, defaultValues } =
|
30
|
+
useContext(FormContext);
|
31
|
+
|
32
|
+
const field = useMemo<FieldProps>(
|
33
|
+
() => ({
|
34
|
+
error: fieldErrors[name],
|
35
|
+
clearError: () => {
|
36
|
+
clearError(name);
|
37
|
+
},
|
38
|
+
validate: () => validateField(name),
|
39
|
+
defaultValue: defaultValues
|
40
|
+
? get(defaultValues, toPath(name), undefined)
|
41
|
+
: undefined,
|
42
|
+
}),
|
43
|
+
[clearError, defaultValues, fieldErrors, name, validateField]
|
44
|
+
);
|
45
|
+
|
46
|
+
return field;
|
47
|
+
};
|
48
|
+
|
49
|
+
/**
|
50
|
+
* Provides access to the entire form context.
|
51
|
+
* This is not usually necessary, but can be useful for advanced use cases.
|
52
|
+
*/
|
53
|
+
export const useFormContext = () => useContext(FormContext);
|
54
|
+
|
55
|
+
/**
|
56
|
+
* Returns whether or not the parent form is currently being submitted.
|
57
|
+
* This is different from remix's `useTransition().submission` in that it
|
58
|
+
* is aware of what form it's in and when _that_ form is being submitted.
|
59
|
+
*/
|
60
|
+
export const useIsSubmitting = () => useFormContext().isSubmitting;
|
package/src/index.ts
ADDED
@@ -0,0 +1,8 @@
|
|
1
|
+
export * from "./hooks";
|
2
|
+
export * from "./server";
|
3
|
+
export * from "./ValidatedForm";
|
4
|
+
export * from "./validation/types";
|
5
|
+
export * from "./validation/withYup";
|
6
|
+
export * from "./validation/withZod";
|
7
|
+
export * from "./validation/createValidator";
|
8
|
+
export type { FormContextValue } from "./internal/formContext";
|
@@ -0,0 +1,48 @@
|
|
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
|
+
import { GenericObject } from "..";
|
10
|
+
|
11
|
+
export const objectFromPathEntries = (entries: [string, any][]) =>
|
12
|
+
entries.reduce((acc, [key, value]) => set(acc, key, value), {});
|
13
|
+
|
14
|
+
/** Flatten an object so there are no nested objects or arrays */
|
15
|
+
export function flatten(obj: GenericObject, preserveEmpty = false) {
|
16
|
+
return transform(
|
17
|
+
obj,
|
18
|
+
function (result: GenericObject, value, key) {
|
19
|
+
if (isObject(value)) {
|
20
|
+
let flatMap = mapKeys(
|
21
|
+
flatten(value, preserveEmpty),
|
22
|
+
function (_mvalue, mkey) {
|
23
|
+
if (isArray(value)) {
|
24
|
+
let index = mkey.indexOf(".");
|
25
|
+
if (-1 !== index) {
|
26
|
+
return `${key}[${mkey.slice(0, index)}]${mkey.slice(index)}`;
|
27
|
+
}
|
28
|
+
return `${key}[${mkey}]`;
|
29
|
+
}
|
30
|
+
return `${key}.${mkey}`;
|
31
|
+
}
|
32
|
+
);
|
33
|
+
|
34
|
+
assign(result, flatMap);
|
35
|
+
|
36
|
+
// Preverve Empty arrays and objects
|
37
|
+
if (preserveEmpty && keys(flatMap).length === 0) {
|
38
|
+
result[key] = value;
|
39
|
+
}
|
40
|
+
} else {
|
41
|
+
result[key] = value;
|
42
|
+
}
|
43
|
+
|
44
|
+
return result;
|
45
|
+
},
|
46
|
+
{}
|
47
|
+
);
|
48
|
+
}
|
@@ -0,0 +1,36 @@
|
|
1
|
+
import { createContext } from "react";
|
2
|
+
import { FieldErrors } from "../validation/types";
|
3
|
+
|
4
|
+
export type FormContextValue = {
|
5
|
+
/**
|
6
|
+
* All the errors in all the fields in the form.
|
7
|
+
*/
|
8
|
+
fieldErrors: FieldErrors;
|
9
|
+
/**
|
10
|
+
* Clear the errors of the specified fields.
|
11
|
+
*/
|
12
|
+
clearError: (...names: string[]) => void;
|
13
|
+
/**
|
14
|
+
* Validate the specified field.
|
15
|
+
*/
|
16
|
+
validateField: (fieldName: string) => void;
|
17
|
+
/**
|
18
|
+
* The `action` prop of the form.
|
19
|
+
*/
|
20
|
+
action?: string;
|
21
|
+
/**
|
22
|
+
* Whether or not the form is submitting.
|
23
|
+
*/
|
24
|
+
isSubmitting: boolean;
|
25
|
+
/**
|
26
|
+
* The default values of the form.
|
27
|
+
*/
|
28
|
+
defaultValues?: { [fieldName: string]: any };
|
29
|
+
};
|
30
|
+
|
31
|
+
export const FormContext = createContext<FormContextValue>({
|
32
|
+
fieldErrors: {},
|
33
|
+
clearError: () => {},
|
34
|
+
validateField: () => {},
|
35
|
+
isSubmitting: false,
|
36
|
+
});
|
@@ -0,0 +1,15 @@
|
|
1
|
+
import { useEffect, useRef } from "react";
|
2
|
+
|
3
|
+
export function useSubmitComplete(isSubmitting: boolean, callback: () => void) {
|
4
|
+
const isPending = useRef(false);
|
5
|
+
useEffect(() => {
|
6
|
+
if (isSubmitting) {
|
7
|
+
isPending.current = true;
|
8
|
+
}
|
9
|
+
|
10
|
+
if (!isSubmitting && isPending.current) {
|
11
|
+
isPending.current = false;
|
12
|
+
callback();
|
13
|
+
}
|
14
|
+
});
|
15
|
+
}
|
@@ -0,0 +1,23 @@
|
|
1
|
+
import type React from "react";
|
2
|
+
|
3
|
+
export const omit = (obj: any, ...keys: string[]) => {
|
4
|
+
const result = { ...obj };
|
5
|
+
for (const key of keys) {
|
6
|
+
delete result[key];
|
7
|
+
}
|
8
|
+
return result;
|
9
|
+
};
|
10
|
+
|
11
|
+
export const mergeRefs = <T = any>(
|
12
|
+
refs: Array<React.MutableRefObject<T> | React.LegacyRef<T> | undefined>
|
13
|
+
): React.RefCallback<T> => {
|
14
|
+
return (value: T) => {
|
15
|
+
refs.filter(Boolean).forEach((ref) => {
|
16
|
+
if (typeof ref === "function") {
|
17
|
+
ref(value);
|
18
|
+
} else if (ref != null) {
|
19
|
+
(ref as React.MutableRefObject<T | null>).current = value;
|
20
|
+
}
|
21
|
+
});
|
22
|
+
};
|
23
|
+
};
|
package/src/server.ts
ADDED
@@ -0,0 +1,10 @@
|
|
1
|
+
import { json } from "@remix-run/server-runtime";
|
2
|
+
import { FieldErrors } from "./validation/types";
|
3
|
+
|
4
|
+
/**
|
5
|
+
* Takes the errors from a `Validator` and returns a `Response`.
|
6
|
+
* The `ValidatedForm` on the frontend will automatically display the errors
|
7
|
+
* if this is returned from the action.
|
8
|
+
*/
|
9
|
+
export const validationError = (errors: FieldErrors) =>
|
10
|
+
json({ fieldErrors: errors }, { status: 422 });
|