remix-validated-form 4.0.2 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/README.md +4 -4
  3. package/browser/ValidatedForm.d.ts +2 -2
  4. package/browser/ValidatedForm.js +142 -151
  5. package/browser/components.d.ts +5 -8
  6. package/browser/components.js +5 -5
  7. package/browser/hooks.d.ts +19 -14
  8. package/browser/hooks.js +41 -39
  9. package/browser/index.d.ts +1 -1
  10. package/browser/index.js +1 -0
  11. package/browser/internal/constants.d.ts +3 -0
  12. package/browser/internal/constants.js +3 -0
  13. package/browser/internal/formContext.d.ts +7 -49
  14. package/browser/internal/formContext.js +1 -1
  15. package/browser/internal/getInputProps.js +4 -3
  16. package/browser/internal/hooks.d.ts +22 -0
  17. package/browser/internal/hooks.js +110 -0
  18. package/browser/internal/state.d.ts +269 -0
  19. package/browser/internal/state.js +82 -0
  20. package/browser/internal/util.d.ts +1 -0
  21. package/browser/internal/util.js +2 -0
  22. package/browser/lowLevelHooks.d.ts +0 -0
  23. package/browser/lowLevelHooks.js +1 -0
  24. package/browser/server.d.ts +5 -0
  25. package/browser/server.js +5 -0
  26. package/browser/userFacingFormContext.d.ts +56 -0
  27. package/browser/userFacingFormContext.js +40 -0
  28. package/browser/validation/createValidator.js +4 -0
  29. package/browser/validation/types.d.ts +3 -0
  30. package/build/ValidatedForm.d.ts +2 -2
  31. package/build/ValidatedForm.js +138 -147
  32. package/build/hooks.d.ts +19 -14
  33. package/build/hooks.js +43 -45
  34. package/build/index.d.ts +1 -1
  35. package/build/index.js +1 -0
  36. package/build/internal/constants.d.ts +3 -0
  37. package/build/internal/constants.js +7 -0
  38. package/build/internal/formContext.d.ts +7 -49
  39. package/build/internal/formContext.js +2 -2
  40. package/build/internal/getInputProps.js +7 -3
  41. package/build/internal/hooks.d.ts +22 -0
  42. package/build/internal/hooks.js +130 -0
  43. package/build/internal/state.d.ts +269 -0
  44. package/build/internal/state.js +92 -0
  45. package/build/internal/util.d.ts +1 -0
  46. package/build/internal/util.js +3 -1
  47. package/build/server.d.ts +5 -0
  48. package/build/server.js +7 -1
  49. package/build/userFacingFormContext.d.ts +56 -0
  50. package/build/userFacingFormContext.js +44 -0
  51. package/build/validation/createValidator.js +4 -0
  52. package/build/validation/types.d.ts +3 -0
  53. package/package.json +3 -1
  54. package/src/ValidatedForm.tsx +205 -203
  55. package/src/hooks.ts +71 -54
  56. package/src/index.ts +1 -1
  57. package/src/internal/constants.ts +4 -0
  58. package/src/internal/formContext.ts +8 -49
  59. package/src/internal/getInputProps.ts +6 -4
  60. package/src/internal/hooks.ts +191 -0
  61. package/src/internal/state.ts +210 -0
  62. package/src/internal/util.ts +4 -0
  63. package/src/server.ts +16 -0
  64. package/src/userFacingFormContext.ts +129 -0
  65. package/src/validation/createValidator.ts +4 -0
  66. package/src/validation/types.ts +3 -1
@@ -1,9 +1,9 @@
1
1
  $ npm run build:browser && npm run build:main
2
2
 
3
- > remix-validated-form@4.0.1-beta.1 build:browser
3
+ > remix-validated-form@4.0.2 build:browser
4
4
  > tsc --module ESNext --outDir ./browser
5
5
 
6
6
 
7
- > remix-validated-form@4.0.1-beta.1 build:main
7
+ > remix-validated-form@4.0.2 build:main
8
8
  > tsc --module CommonJS --outDir ./build
9
9
 
package/README.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  A form library built for [remix](https://remix.run) to make validation easy.
4
4
 
5
- - Client-side, field-by-field validation (e.g. validate on blur) and form-level validation
6
- - Set default values for the entire form in one place
5
+ - Client-side, field-by-field and form-level validation
7
6
  - Re-use validation on the server
8
- - Show validation errors from the server even without JS
9
- - Detect if the current form is submitting when there are multiple forms on the page
7
+ - Set default values for the entire form in one place
10
8
  - Supports nested objects and arrays
9
+ - Easily detect if a specific form is being sumitted
11
10
  - Validation library agnostic
11
+ - Can work without JS
12
12
 
13
13
  # Docs
14
14
 
@@ -10,7 +10,7 @@ export declare type FormProps<DataType> = {
10
10
  * A submit callback that gets called when the form is submitted
11
11
  * after all validations have been run.
12
12
  */
13
- onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => Promise<void>;
13
+ onSubmit?: (data: DataType, event: React.FormEvent<HTMLFormElement>) => void | Promise<void>;
14
14
  /**
15
15
  * Allows you to provide a `fetcher` from remix's `useFetcher` hook.
16
16
  * The form will use the fetcher for loading states, action data, etc
@@ -47,4 +47,4 @@ export declare type FormProps<DataType> = {
47
47
  /**
48
48
  * The primary form component of `remix-validated-form`.
49
49
  */
50
- export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, disableFocusOnError, method, replace, ...rest }: FormProps<DataType>): JSX.Element;
50
+ export declare function ValidatedForm<DataType>({ validator, onSubmit, children, fetcher, action, defaultValues: providedDefaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, disableFocusOnError, method, replace, id, ...rest }: FormProps<DataType>): JSX.Element;
@@ -1,68 +1,17 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Form as RemixForm, useActionData, useSubmit, useTransition, } from "@remix-run/react";
2
+ import { Form as RemixForm, useSubmit } from "@remix-run/react";
3
3
  import uniq from "lodash/uniq";
4
- import React, { useEffect, useMemo, useRef, useState, } from "react";
4
+ import React, { useCallback, useEffect, useMemo, useRef, useState, } from "react";
5
5
  import invariant from "tiny-invariant";
6
- import { FormContext } from "./internal/formContext";
6
+ import { useIsSubmitting, useIsValid } from "./hooks";
7
+ import { FORM_ID_FIELD } from "./internal/constants";
8
+ import { InternalFormContext, } from "./internal/formContext";
9
+ import { useDefaultValuesFromLoader, useErrorResponseForForm, useFormUpdateAtom, useHasActiveFormSubmit, } from "./internal/hooks";
7
10
  import { useMultiValueMap } from "./internal/MultiValueMap";
11
+ import { addErrorAtom, clearErrorAtom, endSubmitAtom, formRegistry, resetAtom, setFieldErrorsAtom, startSubmitAtom, syncFormContextAtom, } from "./internal/state";
8
12
  import { useSubmitComplete } from "./internal/submissionCallbacks";
9
- import { omit, mergeRefs } from "./internal/util";
10
- function useErrorResponseForThisForm(fetcher, subaction) {
11
- var _a;
12
- const actionData = useActionData();
13
- if (fetcher) {
14
- if ((_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors)
15
- return fetcher.data;
16
- return null;
17
- }
18
- if (!(actionData === null || actionData === void 0 ? void 0 : actionData.fieldErrors))
19
- return null;
20
- if ((!subaction && !actionData.subaction) ||
21
- actionData.subaction === subaction)
22
- return actionData;
23
- return null;
24
- }
25
- function useFieldErrors(fieldErrorsFromBackend) {
26
- const [fieldErrors, setFieldErrors] = useState(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
27
- useEffect(() => {
28
- if (fieldErrorsFromBackend)
29
- setFieldErrors(fieldErrorsFromBackend);
30
- }, [fieldErrorsFromBackend]);
31
- return [fieldErrors, setFieldErrors];
32
- }
33
- const useIsSubmitting = (fetcher) => {
34
- const [isSubmitStarted, setSubmitStarted] = useState(false);
35
- const transition = useTransition();
36
- const hasActiveSubmission = fetcher
37
- ? fetcher.state === "submitting"
38
- : !!transition.submission;
39
- const startSubmit = () => setSubmitStarted(true);
40
- const endSubmit = () => setSubmitStarted(false);
41
- useSubmitComplete(hasActiveSubmission, () => {
42
- endSubmit();
43
- });
44
- return [isSubmitStarted, startSubmit, endSubmit];
45
- };
13
+ import { mergeRefs, useIsomorphicLayoutEffect as useLayoutEffect, } from "./internal/util";
46
14
  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(repopulateFieldsFromBackend, defaultValues) {
64
- return repopulateFieldsFromBackend !== null && repopulateFieldsFromBackend !== void 0 ? repopulateFieldsFromBackend : defaultValues;
65
- }
66
15
  function nonNull(value) {
67
16
  return value !== null;
68
17
  }
@@ -106,85 +55,122 @@ const focusFirstInvalidInput = (fieldErrors, customFocusHandlers, formElement) =
106
55
  }
107
56
  }
108
57
  };
58
+ const useFormId = (providedId) => {
59
+ // We can use a `Symbol` here because we only use it after hydration
60
+ const [symbolId] = useState(() => Symbol("remix-validated-form-id"));
61
+ return providedId !== null && providedId !== void 0 ? providedId : symbolId;
62
+ };
109
63
  /**
110
- * The primary form component of `remix-validated-form`.
64
+ * Use a component to access the state so we don't cause
65
+ * any extra rerenders of the whole form.
111
66
  */
112
- export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, disableFocusOnError, method, replace, ...rest }) {
113
- var _a;
114
- const backendError = useErrorResponseForThisForm(fetcher, subaction);
115
- const [fieldErrors, setFieldErrors] = useFieldErrors(backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors);
116
- const [isSubmitting, startSubmit, endSubmit] = useIsSubmitting(fetcher);
117
- const defaultsToUse = useDefaultValues(backendError === null || backendError === void 0 ? void 0 : backendError.repopulateFields, defaultValues);
118
- const [touchedFields, setTouchedFields] = useState({});
119
- const [hasBeenSubmitted, setHasBeenSubmitted] = useState(false);
120
- const submit = useSubmit();
121
- const formRef = useRef(null);
67
+ const FormResetter = ({ resetAfterSubmit, formRef, }) => {
68
+ const isSubmitting = useIsSubmitting();
69
+ const isValid = useIsValid();
122
70
  useSubmitComplete(isSubmitting, () => {
123
71
  var _a;
124
- endSubmit();
125
- if (!backendError && resetAfterSubmit) {
72
+ if (isValid && resetAfterSubmit) {
126
73
  (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
127
74
  }
128
75
  });
129
- const customFocusHandlers = useMultiValueMap();
130
- const contextValue = useMemo(() => ({
131
- fieldErrors,
132
- action,
133
- defaultValues: defaultsToUse,
134
- isSubmitting,
135
- isValid: Object.keys(fieldErrors).length === 0,
136
- touchedFields,
137
- setFieldTouched: (fieldName, touched) => setTouchedFields((prev) => ({
138
- ...prev,
139
- [fieldName]: touched,
140
- })),
141
- clearError: (fieldName) => {
142
- setFieldErrors((prev) => omit(prev, fieldName));
143
- },
144
- validateField: async (fieldName) => {
145
- invariant(formRef.current, "Cannot find reference to form");
146
- const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
147
- // By checking and returning `prev` here, we can avoid a re-render
148
- // if the validation state is the same.
149
- if (error) {
150
- setFieldErrors((prev) => {
151
- if (prev[fieldName] === error)
152
- return prev;
153
- return {
154
- ...prev,
155
- [fieldName]: error,
156
- };
157
- });
158
- return error;
76
+ return null;
77
+ };
78
+ function formEventProxy(event) {
79
+ let defaultPrevented = false;
80
+ return new Proxy(event, {
81
+ get: (target, prop) => {
82
+ if (prop === "preventDefault") {
83
+ return () => {
84
+ defaultPrevented = true;
85
+ };
159
86
  }
160
- else {
161
- setFieldErrors((prev) => {
162
- if (!(fieldName in prev))
163
- return prev;
164
- return omit(prev, fieldName);
165
- });
166
- return null;
87
+ if (prop === "defaultPrevented") {
88
+ return defaultPrevented;
167
89
  }
90
+ return target[prop];
168
91
  },
169
- registerReceiveFocus: (fieldName, handler) => {
170
- customFocusHandlers().add(fieldName, handler);
171
- return () => {
172
- customFocusHandlers().remove(fieldName, handler);
173
- };
174
- },
175
- hasBeenSubmitted,
176
- }), [
177
- fieldErrors,
92
+ });
93
+ }
94
+ const useFormAtom = (formId) => {
95
+ const formAtom = formRegistry(formId);
96
+ useEffect(() => () => formRegistry.remove(formId), [formId]);
97
+ return formAtom;
98
+ };
99
+ /**
100
+ * The primary form component of `remix-validated-form`.
101
+ */
102
+ export function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues: providedDefaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit = false, disableFocusOnError, method, replace, id, ...rest }) {
103
+ var _a;
104
+ const formId = useFormId(id);
105
+ const formAtom = useFormAtom(formId);
106
+ const contextValue = useMemo(() => ({
107
+ formId,
178
108
  action,
179
- defaultsToUse,
180
- isSubmitting,
181
- touchedFields,
182
- hasBeenSubmitted,
183
- setFieldErrors,
184
- validator,
185
- customFocusHandlers,
186
- ]);
109
+ subaction,
110
+ defaultValuesProp: providedDefaultValues,
111
+ fetcher,
112
+ }), [action, fetcher, formId, providedDefaultValues, subaction]);
113
+ const backendError = useErrorResponseForForm(contextValue);
114
+ const backendDefaultValues = useDefaultValuesFromLoader(contextValue);
115
+ const hasActiveSubmission = useHasActiveFormSubmit(contextValue);
116
+ const formRef = useRef(null);
187
117
  const Form = (_a = fetcher === null || fetcher === void 0 ? void 0 : fetcher.Form) !== null && _a !== void 0 ? _a : RemixForm;
118
+ const submit = useSubmit();
119
+ const clearError = useFormUpdateAtom(clearErrorAtom);
120
+ const addError = useFormUpdateAtom(addErrorAtom);
121
+ const setFieldErrors = useFormUpdateAtom(setFieldErrorsAtom);
122
+ const reset = useFormUpdateAtom(resetAtom);
123
+ const startSubmit = useFormUpdateAtom(startSubmitAtom);
124
+ const endSubmit = useFormUpdateAtom(endSubmitAtom);
125
+ const syncFormContext = useFormUpdateAtom(syncFormContextAtom);
126
+ const validateField = useCallback(async (fieldName) => {
127
+ invariant(formRef.current, "Cannot find reference to form");
128
+ const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
129
+ if (error) {
130
+ addError({ formAtom, name: fieldName, error });
131
+ return error;
132
+ }
133
+ else {
134
+ clearError({ name: fieldName, formAtom });
135
+ return null;
136
+ }
137
+ }, [addError, clearError, formAtom, validator]);
138
+ const customFocusHandlers = useMultiValueMap();
139
+ const registerReceiveFocus = useCallback((fieldName, handler) => {
140
+ customFocusHandlers().add(fieldName, handler);
141
+ return () => {
142
+ customFocusHandlers().remove(fieldName, handler);
143
+ };
144
+ }, [customFocusHandlers]);
145
+ useLayoutEffect(() => {
146
+ syncFormContext({
147
+ formAtom,
148
+ action,
149
+ defaultValues: providedDefaultValues !== null && providedDefaultValues !== void 0 ? providedDefaultValues : backendDefaultValues,
150
+ subaction,
151
+ validateField,
152
+ registerReceiveFocus,
153
+ });
154
+ }, [
155
+ action,
156
+ formAtom,
157
+ providedDefaultValues,
158
+ registerReceiveFocus,
159
+ subaction,
160
+ syncFormContext,
161
+ validateField,
162
+ backendDefaultValues,
163
+ ]);
164
+ useEffect(() => {
165
+ var _a;
166
+ setFieldErrors({
167
+ fieldErrors: (_a = backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors) !== null && _a !== void 0 ? _a : {},
168
+ formAtom,
169
+ });
170
+ }, [backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors, formAtom, setFieldErrors]);
171
+ useSubmitComplete(hasActiveSubmission, () => {
172
+ endSubmit({ formAtom });
173
+ });
188
174
  let clickedButtonRef = React.useRef();
189
175
  useEffect(() => {
190
176
  let form = formRef.current;
@@ -205,35 +191,40 @@ export function ValidatedForm({ validator, onSubmit, children, fetcher, action,
205
191
  window.removeEventListener("click", handleClick);
206
192
  };
207
193
  }, []);
208
- return (_jsx(Form, { ref: mergeRefs([formRef, formRefProp]), ...rest, action: action, method: method, replace: replace, onSubmit: async (e) => {
209
- e.preventDefault();
210
- setHasBeenSubmitted(true);
211
- startSubmit();
212
- const result = await validator.validate(getDataFromForm(e.currentTarget));
213
- if (result.error) {
214
- endSubmit();
215
- setFieldErrors(result.error.fieldErrors);
216
- if (!disableFocusOnError) {
217
- focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
218
- }
194
+ const handleSubmit = async (e) => {
195
+ startSubmit({ formAtom });
196
+ const result = await validator.validate(getDataFromForm(e.currentTarget));
197
+ if (result.error) {
198
+ endSubmit({ formAtom });
199
+ setFieldErrors({ fieldErrors: result.error.fieldErrors, formAtom });
200
+ if (!disableFocusOnError) {
201
+ focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
219
202
  }
220
- else {
221
- onSubmit && onSubmit(result.data, e);
222
- if (fetcher)
223
- fetcher.submit(clickedButtonRef.current || e.currentTarget);
224
- else
225
- submit(clickedButtonRef.current || e.currentTarget, {
226
- method,
227
- replace,
228
- });
229
- clickedButtonRef.current = null;
203
+ }
204
+ else {
205
+ const eventProxy = formEventProxy(e);
206
+ await (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, eventProxy));
207
+ if (eventProxy.defaultPrevented) {
208
+ endSubmit({ formAtom });
209
+ return;
230
210
  }
211
+ if (fetcher)
212
+ fetcher.submit(clickedButtonRef.current || e.currentTarget);
213
+ else
214
+ submit(clickedButtonRef.current || e.currentTarget, {
215
+ method,
216
+ replace,
217
+ });
218
+ clickedButtonRef.current = null;
219
+ }
220
+ };
221
+ return (_jsx(Form, { ref: mergeRefs([formRef, formRefProp]), ...rest, id: id, action: action, method: method, replace: replace, onSubmit: (e) => {
222
+ e.preventDefault();
223
+ handleSubmit(e);
231
224
  }, onReset: (event) => {
232
225
  onReset === null || onReset === void 0 ? void 0 : onReset(event);
233
226
  if (event.defaultPrevented)
234
227
  return;
235
- setFieldErrors({});
236
- setTouchedFields({});
237
- setHasBeenSubmitted(false);
238
- }, children: _jsxs(FormContext.Provider, { value: contextValue, children: [subaction && (_jsx("input", { type: "hidden", value: subaction, name: "subaction" }, void 0)), children] }, void 0) }, void 0));
228
+ reset({ formAtom });
229
+ }, children: _jsxs(InternalFormContext.Provider, { value: contextValue, children: [_jsx(FormResetter, { formRef: formRef, resetAfterSubmit: resetAfterSubmit }, void 0), subaction && (_jsx("input", { type: "hidden", value: subaction, name: "subaction" }, void 0)), id && _jsx("input", { type: "hidden", value: id, name: FORM_ID_FIELD }, void 0), children] }, void 0) }, void 0));
239
230
  }
@@ -1,10 +1,7 @@
1
1
  import { HTMLProps } from "react";
2
- declare type ValidatedInputProps = HTMLProps<HTMLInputElement> & {
3
- name: string;
4
- };
5
- export declare const ValidatedInput: ({ name, ...rest }: ValidatedInputProps) => JSX.Element;
6
- declare type ErrorMessageProps = {
7
- name: string;
8
- };
9
- export declare const ErrorMessage: ({ name }: ErrorMessageProps) => string | undefined;
2
+ declare type WithRequiredName<T extends {
3
+ name?: string;
4
+ }> = T & Required<Pick<T, "name">>;
5
+ export declare const ValidatedInput: ({ name, form, ...rest }: WithRequiredName<HTMLProps<HTMLInputElement>>) => JSX.Element;
6
+ export declare const ValidatedTextarea: ({ name, form, ...rest }: WithRequiredName<HTMLProps<HTMLTextAreaElement>>) => JSX.Element;
10
7
  export {};
@@ -1,10 +1,10 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { useField } from ".";
3
- export const ValidatedInput = ({ name, ...rest }) => {
4
- const { getInputProps } = useField(name);
3
+ export const ValidatedInput = ({ name, form, ...rest }) => {
4
+ const { getInputProps } = useField(name, { formId: form });
5
5
  return _jsx("input", { ...getInputProps(rest) }, void 0);
6
6
  };
7
- export const ErrorMessage = ({ name }) => {
8
- const { error } = useField(name);
9
- return error;
7
+ export const ValidatedTextarea = ({ name, form, ...rest }) => {
8
+ const { getInputProps } = useField(name, { formId: form });
9
+ return _jsx("textarea", { ...getInputProps(rest) }, void 0);
10
10
  };
@@ -1,4 +1,18 @@
1
1
  import { GetInputProps, ValidationBehaviorOptions } from "./internal/getInputProps";
2
+ /**
3
+ * Returns whether or not the parent form is currently being submitted.
4
+ * This is different from remix's `useTransition().submission` in that it
5
+ * is aware of what form it's in and when _that_ form is being submitted.
6
+ *
7
+ * @param formId
8
+ */
9
+ export declare const useIsSubmitting: (formId?: string | undefined) => boolean;
10
+ /**
11
+ * Returns whether or not the current form is valid.
12
+ *
13
+ * @param formId the id of the form. Only necessary if being used outside a ValidatedForm.
14
+ */
15
+ export declare const useIsValid: (formId?: string | undefined) => boolean;
2
16
  export declare type FieldProps = {
3
17
  /**
4
18
  * The validation error message if there is one.
@@ -43,18 +57,9 @@ export declare const useField: (name: string, options?: {
43
57
  * Allows you to specify when a field gets validated (when using getInputProps)
44
58
  */
45
59
  validationBehavior?: Partial<ValidationBehaviorOptions> | undefined;
60
+ /**
61
+ * The formId of the form you want to use.
62
+ * This is not necesary if the input is used inside a form.
63
+ */
64
+ formId?: string | undefined;
46
65
  } | undefined) => FieldProps;
47
- /**
48
- * Provides access to the entire form context.
49
- */
50
- export declare const useFormContext: () => import("./internal/formContext").FormContextValue;
51
- /**
52
- * Returns whether or not the parent form is currently being submitted.
53
- * This is different from remix's `useTransition().submission` in that it
54
- * is aware of what form it's in and when _that_ form is being submitted.
55
- */
56
- export declare const useIsSubmitting: () => boolean;
57
- /**
58
- * Returns whether or not the current form is valid.
59
- */
60
- export declare const useIsValid: () => boolean;
package/browser/hooks.js CHANGED
@@ -1,39 +1,55 @@
1
- import get from "lodash/get";
2
- import toPath from "lodash/toPath";
3
- import { useContext, useEffect, useMemo } from "react";
4
- import { FormContext } from "./internal/formContext";
1
+ import { useEffect, useMemo } from "react";
5
2
  import { createGetInputProps, } from "./internal/getInputProps";
6
- const useInternalFormContext = (hookName) => {
7
- const context = useContext(FormContext);
8
- if (!context)
9
- throw new Error(`${hookName} must be used within a ValidatedForm component`);
10
- return context;
3
+ import { useInternalFormContext, useFieldTouched, useFieldError, useFieldDefaultValue, useContextSelectAtom, useClearError, useSetTouched, } from "./internal/hooks";
4
+ import { hasBeenSubmittedAtom, isSubmittingAtom, isValidAtom, registerReceiveFocusAtom, validateFieldAtom, } from "./internal/state";
5
+ /**
6
+ * Returns whether or not the parent form is currently being submitted.
7
+ * This is different from remix's `useTransition().submission` in that it
8
+ * is aware of what form it's in and when _that_ form is being submitted.
9
+ *
10
+ * @param formId
11
+ */
12
+ export const useIsSubmitting = (formId) => {
13
+ const formContext = useInternalFormContext(formId, "useIsSubmitting");
14
+ return useContextSelectAtom(formContext.formId, isSubmittingAtom);
15
+ };
16
+ /**
17
+ * Returns whether or not the current form is valid.
18
+ *
19
+ * @param formId the id of the form. Only necessary if being used outside a ValidatedForm.
20
+ */
21
+ export const useIsValid = (formId) => {
22
+ const formContext = useInternalFormContext(formId, "useIsValid");
23
+ return useContextSelectAtom(formContext.formId, isValidAtom);
11
24
  };
12
25
  /**
13
26
  * Provides the data and helpers necessary to set up a field.
14
27
  */
15
28
  export const useField = (name, options) => {
16
- const { fieldErrors, clearError, validateField, defaultValues, registerReceiveFocus, touchedFields, setFieldTouched, hasBeenSubmitted, } = useInternalFormContext("useField");
17
- const isTouched = !!touchedFields[name];
18
- const { handleReceiveFocus } = options !== null && options !== void 0 ? options : {};
29
+ const { handleReceiveFocus, formId: providedFormId } = options !== null && options !== void 0 ? options : {};
30
+ const formContext = useInternalFormContext(providedFormId, "useField");
31
+ const defaultValue = useFieldDefaultValue(name, formContext);
32
+ const touched = useFieldTouched(name, formContext);
33
+ const error = useFieldError(name, formContext);
34
+ const clearError = useClearError(formContext);
35
+ const setTouched = useSetTouched(formContext);
36
+ const hasBeenSubmitted = useContextSelectAtom(formContext.formId, hasBeenSubmittedAtom);
37
+ const validateField = useContextSelectAtom(formContext.formId, validateFieldAtom);
38
+ const registerReceiveFocus = useContextSelectAtom(formContext.formId, registerReceiveFocusAtom);
19
39
  useEffect(() => {
20
40
  if (handleReceiveFocus)
21
41
  return registerReceiveFocus(name, handleReceiveFocus);
22
42
  }, [handleReceiveFocus, name, registerReceiveFocus]);
23
43
  const field = useMemo(() => {
24
44
  const helpers = {
25
- error: fieldErrors[name],
26
- clearError: () => {
27
- clearError(name);
28
- },
45
+ error,
46
+ clearError: () => clearError(name),
29
47
  validate: () => {
30
48
  validateField(name);
31
49
  },
32
- defaultValue: defaultValues
33
- ? get(defaultValues, toPath(name), undefined)
34
- : undefined,
35
- touched: isTouched,
36
- setTouched: (touched) => setFieldTouched(name, touched),
50
+ defaultValue,
51
+ touched,
52
+ setTouched: (touched) => setTouched(name, touched),
37
53
  };
38
54
  const getInputProps = createGetInputProps({
39
55
  ...helpers,
@@ -46,29 +62,15 @@ export const useField = (name, options) => {
46
62
  getInputProps,
47
63
  };
48
64
  }, [
49
- fieldErrors,
65
+ error,
66
+ defaultValue,
67
+ touched,
50
68
  name,
51
- defaultValues,
52
- isTouched,
53
69
  hasBeenSubmitted,
54
70
  options === null || options === void 0 ? void 0 : options.validationBehavior,
55
71
  clearError,
56
72
  validateField,
57
- setFieldTouched,
73
+ setTouched,
58
74
  ]);
59
75
  return field;
60
76
  };
61
- /**
62
- * Provides access to the entire form context.
63
- */
64
- export const useFormContext = () => useInternalFormContext("useFormContext");
65
- /**
66
- * Returns whether or not the parent form is currently being submitted.
67
- * This is different from remix's `useTransition().submission` in that it
68
- * is aware of what form it's in and when _that_ form is being submitted.
69
- */
70
- export const useIsSubmitting = () => useInternalFormContext("useIsSubmitting").isSubmitting;
71
- /**
72
- * Returns whether or not the current form is valid.
73
- */
74
- export const useIsValid = () => useInternalFormContext("useIsValid").isValid;
@@ -3,4 +3,4 @@ export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/createValidator";
6
- export type { FormContextValue } from "./internal/formContext";
6
+ export * from "./userFacingFormContext";
package/browser/index.js CHANGED
@@ -3,3 +3,4 @@ export * from "./server";
3
3
  export * from "./ValidatedForm";
4
4
  export * from "./validation/types";
5
5
  export * from "./validation/createValidator";
6
+ export * from "./userFacingFormContext";
@@ -0,0 +1,3 @@
1
+ export declare const FORM_ID_FIELD: "__rvfInternalFormId";
2
+ export declare const FORM_DEFAULTS_FIELD: "__rvfInternalFormDefaults";
3
+ export declare const formDefaultValuesKey: (formId: string) => string;
@@ -0,0 +1,3 @@
1
+ export const FORM_ID_FIELD = "__rvfInternalFormId";
2
+ export const FORM_DEFAULTS_FIELD = "__rvfInternalFormDefaults";
3
+ export const formDefaultValuesKey = (formId) => `${FORM_DEFAULTS_FIELD}_${formId}`;
@@ -1,54 +1,12 @@
1
1
  /// <reference types="react" />
2
- import { FieldErrors, TouchedFields } from "../validation/types";
3
- export declare type FormContextValue = {
4
- /**
5
- * All the errors in all the fields in the form.
6
- */
7
- fieldErrors: FieldErrors;
8
- /**
9
- * Clear the errors of the specified fields.
10
- */
11
- clearError: (...names: string[]) => void;
12
- /**
13
- * Validate the specified field.
14
- */
15
- validateField: (fieldName: string) => Promise<string | null>;
16
- /**
17
- * The `action` prop of the form.
18
- */
2
+ import { useFetcher } from "@remix-run/react";
3
+ export declare type InternalFormContextValue = {
4
+ formId: string | symbol;
19
5
  action?: string;
20
- /**
21
- * Whether or not the form is submitting.
22
- */
23
- isSubmitting: boolean;
24
- /**
25
- * Whether or not a submission has been attempted.
26
- * This is true once the form has been submitted, even if there were validation errors.
27
- * Resets to false when the form is reset.
28
- */
29
- hasBeenSubmitted: boolean;
30
- /**
31
- * Whether or not the form is valid.
32
- */
33
- isValid: boolean;
34
- /**
35
- * The default values of the form.
36
- */
37
- defaultValues?: {
6
+ subaction?: string;
7
+ defaultValuesProp?: {
38
8
  [fieldName: string]: any;
39
9
  };
40
- /**
41
- * Register a custom focus handler to be used when
42
- * the field needs to receive focus due to a validation error.
43
- */
44
- registerReceiveFocus: (fieldName: string, handler: () => void) => () => void;
45
- /**
46
- * Any fields that have been touched by the user.
47
- */
48
- touchedFields: TouchedFields;
49
- /**
50
- * Change the touched state of the specified field.
51
- */
52
- setFieldTouched: (fieldName: string, touched: boolean) => void;
10
+ fetcher?: ReturnType<typeof useFetcher>;
53
11
  };
54
- export declare const FormContext: import("react").Context<FormContextValue | null>;
12
+ export declare const InternalFormContext: import("react").Context<InternalFormContextValue | null>;
@@ -1,2 +1,2 @@
1
1
  import { createContext } from "react";
2
- export const FormContext = createContext(null);
2
+ export const InternalFormContext = createContext(null);