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,3 +1,4 @@
1
+ import { FORM_ID_FIELD } from "../internal/constants";
1
2
  import { objectFromPathEntries } from "../internal/flatten";
2
3
  const preprocessFormData = (data) => {
3
4
  // A slightly janky way of determining if the data is a FormData object
@@ -22,14 +23,17 @@ export function createValidator(validator) {
22
23
  error: {
23
24
  fieldErrors: result.error,
24
25
  subaction: data.subaction,
26
+ formId: data[FORM_ID_FIELD],
25
27
  },
26
28
  submittedData: data,
29
+ formId: data[FORM_ID_FIELD],
27
30
  };
28
31
  }
29
32
  return {
30
33
  data: result.data,
31
34
  error: undefined,
32
35
  submittedData: data,
36
+ formId: data[FORM_ID_FIELD],
33
37
  };
34
38
  },
35
39
  validateField: (data, field) => validator.validateField(preprocessFormData(data), field),
@@ -5,15 +5,18 @@ export declare type GenericObject = {
5
5
  };
6
6
  export declare type ValidatorError = {
7
7
  subaction?: string;
8
+ formId?: string;
8
9
  fieldErrors: FieldErrors;
9
10
  };
10
11
  export declare type ValidationErrorResponseData = {
11
12
  subaction?: string;
13
+ formId?: string;
12
14
  fieldErrors: FieldErrors;
13
15
  repopulateFields?: unknown;
14
16
  };
15
17
  export declare type BaseResult = {
16
18
  submittedData: GenericObject;
19
+ formId?: string;
17
20
  };
18
21
  export declare type ErrorResult = BaseResult & {
19
22
  error: ValidatorError;
@@ -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;
@@ -28,66 +28,15 @@ const react_1 = require("@remix-run/react");
28
28
  const uniq_1 = __importDefault(require("lodash/uniq"));
29
29
  const react_2 = __importStar(require("react"));
30
30
  const tiny_invariant_1 = __importDefault(require("tiny-invariant"));
31
+ const hooks_1 = require("./hooks");
32
+ const constants_1 = require("./internal/constants");
31
33
  const formContext_1 = require("./internal/formContext");
34
+ const hooks_2 = require("./internal/hooks");
32
35
  const MultiValueMap_1 = require("./internal/MultiValueMap");
36
+ const state_1 = require("./internal/state");
33
37
  const submissionCallbacks_1 = require("./internal/submissionCallbacks");
34
38
  const util_1 = require("./internal/util");
35
- function useErrorResponseForThisForm(fetcher, subaction) {
36
- var _a;
37
- const actionData = (0, react_1.useActionData)();
38
- if (fetcher) {
39
- if ((_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors)
40
- return fetcher.data;
41
- return null;
42
- }
43
- if (!(actionData === null || actionData === void 0 ? void 0 : actionData.fieldErrors))
44
- return null;
45
- if ((!subaction && !actionData.subaction) ||
46
- actionData.subaction === subaction)
47
- return actionData;
48
- return null;
49
- }
50
- function useFieldErrors(fieldErrorsFromBackend) {
51
- const [fieldErrors, setFieldErrors] = (0, react_2.useState)(fieldErrorsFromBackend !== null && fieldErrorsFromBackend !== void 0 ? fieldErrorsFromBackend : {});
52
- (0, react_2.useEffect)(() => {
53
- if (fieldErrorsFromBackend)
54
- setFieldErrors(fieldErrorsFromBackend);
55
- }, [fieldErrorsFromBackend]);
56
- return [fieldErrors, setFieldErrors];
57
- }
58
- const useIsSubmitting = (fetcher) => {
59
- const [isSubmitStarted, setSubmitStarted] = (0, react_2.useState)(false);
60
- const transition = (0, react_1.useTransition)();
61
- const hasActiveSubmission = fetcher
62
- ? fetcher.state === "submitting"
63
- : !!transition.submission;
64
- const startSubmit = () => setSubmitStarted(true);
65
- const endSubmit = () => setSubmitStarted(false);
66
- (0, submissionCallbacks_1.useSubmitComplete)(hasActiveSubmission, () => {
67
- endSubmit();
68
- });
69
- return [isSubmitStarted, startSubmit, endSubmit];
70
- };
71
39
  const getDataFromForm = (el) => new FormData(el);
72
- /**
73
- * The purpose for this logic is to handle validation errors when javascript is disabled.
74
- * Normally (without js), when a form is submitted and the action returns the validation errors,
75
- * the form will be reset. The errors will be displayed on the correct fields,
76
- * but all the values in the form will be gone. This is not good UX.
77
- *
78
- * To get around this, we return the submitted form data from the server,
79
- * and use those to populate the form via `defaultValues`.
80
- * This results in a more seamless UX akin to what you would see when js is enabled.
81
- *
82
- * One potential downside is that resetting the form will reset the form
83
- * to the _new_ default values that were returned from the server with the validation errors.
84
- * However, this case is less of a problem than the janky UX caused by losing the form values.
85
- * It will only ever be a problem if the form includes a `<button type="reset" />`
86
- * and only if JS is disabled.
87
- */
88
- function useDefaultValues(repopulateFieldsFromBackend, defaultValues) {
89
- return repopulateFieldsFromBackend !== null && repopulateFieldsFromBackend !== void 0 ? repopulateFieldsFromBackend : defaultValues;
90
- }
91
40
  function nonNull(value) {
92
41
  return value !== null;
93
42
  }
@@ -131,85 +80,122 @@ const focusFirstInvalidInput = (fieldErrors, customFocusHandlers, formElement) =
131
80
  }
132
81
  }
133
82
  };
83
+ const useFormId = (providedId) => {
84
+ // We can use a `Symbol` here because we only use it after hydration
85
+ const [symbolId] = (0, react_2.useState)(() => Symbol("remix-validated-form-id"));
86
+ return providedId !== null && providedId !== void 0 ? providedId : symbolId;
87
+ };
134
88
  /**
135
- * The primary form component of `remix-validated-form`.
89
+ * Use a component to access the state so we don't cause
90
+ * any extra rerenders of the whole form.
136
91
  */
137
- function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, disableFocusOnError, method, replace, ...rest }) {
138
- var _a;
139
- const backendError = useErrorResponseForThisForm(fetcher, subaction);
140
- const [fieldErrors, setFieldErrors] = useFieldErrors(backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors);
141
- const [isSubmitting, startSubmit, endSubmit] = useIsSubmitting(fetcher);
142
- const defaultsToUse = useDefaultValues(backendError === null || backendError === void 0 ? void 0 : backendError.repopulateFields, defaultValues);
143
- const [touchedFields, setTouchedFields] = (0, react_2.useState)({});
144
- const [hasBeenSubmitted, setHasBeenSubmitted] = (0, react_2.useState)(false);
145
- const submit = (0, react_1.useSubmit)();
146
- const formRef = (0, react_2.useRef)(null);
92
+ const FormResetter = ({ resetAfterSubmit, formRef, }) => {
93
+ const isSubmitting = (0, hooks_1.useIsSubmitting)();
94
+ const isValid = (0, hooks_1.useIsValid)();
147
95
  (0, submissionCallbacks_1.useSubmitComplete)(isSubmitting, () => {
148
96
  var _a;
149
- endSubmit();
150
- if (!backendError && resetAfterSubmit) {
97
+ if (isValid && resetAfterSubmit) {
151
98
  (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
152
99
  }
153
100
  });
154
- const customFocusHandlers = (0, MultiValueMap_1.useMultiValueMap)();
155
- const contextValue = (0, react_2.useMemo)(() => ({
156
- fieldErrors,
157
- action,
158
- defaultValues: defaultsToUse,
159
- isSubmitting,
160
- isValid: Object.keys(fieldErrors).length === 0,
161
- touchedFields,
162
- setFieldTouched: (fieldName, touched) => setTouchedFields((prev) => ({
163
- ...prev,
164
- [fieldName]: touched,
165
- })),
166
- clearError: (fieldName) => {
167
- setFieldErrors((prev) => (0, util_1.omit)(prev, fieldName));
168
- },
169
- validateField: async (fieldName) => {
170
- (0, tiny_invariant_1.default)(formRef.current, "Cannot find reference to form");
171
- const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
172
- // By checking and returning `prev` here, we can avoid a re-render
173
- // if the validation state is the same.
174
- if (error) {
175
- setFieldErrors((prev) => {
176
- if (prev[fieldName] === error)
177
- return prev;
178
- return {
179
- ...prev,
180
- [fieldName]: error,
181
- };
182
- });
183
- return error;
101
+ return null;
102
+ };
103
+ function formEventProxy(event) {
104
+ let defaultPrevented = false;
105
+ return new Proxy(event, {
106
+ get: (target, prop) => {
107
+ if (prop === "preventDefault") {
108
+ return () => {
109
+ defaultPrevented = true;
110
+ };
184
111
  }
185
- else {
186
- setFieldErrors((prev) => {
187
- if (!(fieldName in prev))
188
- return prev;
189
- return (0, util_1.omit)(prev, fieldName);
190
- });
191
- return null;
112
+ if (prop === "defaultPrevented") {
113
+ return defaultPrevented;
192
114
  }
115
+ return target[prop];
193
116
  },
194
- registerReceiveFocus: (fieldName, handler) => {
195
- customFocusHandlers().add(fieldName, handler);
196
- return () => {
197
- customFocusHandlers().remove(fieldName, handler);
198
- };
199
- },
200
- hasBeenSubmitted,
201
- }), [
202
- fieldErrors,
117
+ });
118
+ }
119
+ const useFormAtom = (formId) => {
120
+ const formAtom = (0, state_1.formRegistry)(formId);
121
+ (0, react_2.useEffect)(() => () => state_1.formRegistry.remove(formId), [formId]);
122
+ return formAtom;
123
+ };
124
+ /**
125
+ * The primary form component of `remix-validated-form`.
126
+ */
127
+ function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues: providedDefaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit = false, disableFocusOnError, method, replace, id, ...rest }) {
128
+ var _a;
129
+ const formId = useFormId(id);
130
+ const formAtom = useFormAtom(formId);
131
+ const contextValue = (0, react_2.useMemo)(() => ({
132
+ formId,
203
133
  action,
204
- defaultsToUse,
205
- isSubmitting,
206
- touchedFields,
207
- hasBeenSubmitted,
208
- setFieldErrors,
209
- validator,
210
- customFocusHandlers,
211
- ]);
134
+ subaction,
135
+ defaultValuesProp: providedDefaultValues,
136
+ fetcher,
137
+ }), [action, fetcher, formId, providedDefaultValues, subaction]);
138
+ const backendError = (0, hooks_2.useErrorResponseForForm)(contextValue);
139
+ const backendDefaultValues = (0, hooks_2.useDefaultValuesFromLoader)(contextValue);
140
+ const hasActiveSubmission = (0, hooks_2.useHasActiveFormSubmit)(contextValue);
141
+ const formRef = (0, react_2.useRef)(null);
212
142
  const Form = (_a = fetcher === null || fetcher === void 0 ? void 0 : fetcher.Form) !== null && _a !== void 0 ? _a : react_1.Form;
143
+ const submit = (0, react_1.useSubmit)();
144
+ const clearError = (0, hooks_2.useFormUpdateAtom)(state_1.clearErrorAtom);
145
+ const addError = (0, hooks_2.useFormUpdateAtom)(state_1.addErrorAtom);
146
+ const setFieldErrors = (0, hooks_2.useFormUpdateAtom)(state_1.setFieldErrorsAtom);
147
+ const reset = (0, hooks_2.useFormUpdateAtom)(state_1.resetAtom);
148
+ const startSubmit = (0, hooks_2.useFormUpdateAtom)(state_1.startSubmitAtom);
149
+ const endSubmit = (0, hooks_2.useFormUpdateAtom)(state_1.endSubmitAtom);
150
+ const syncFormContext = (0, hooks_2.useFormUpdateAtom)(state_1.syncFormContextAtom);
151
+ const validateField = (0, react_2.useCallback)(async (fieldName) => {
152
+ (0, tiny_invariant_1.default)(formRef.current, "Cannot find reference to form");
153
+ const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
154
+ if (error) {
155
+ addError({ formAtom, name: fieldName, error });
156
+ return error;
157
+ }
158
+ else {
159
+ clearError({ name: fieldName, formAtom });
160
+ return null;
161
+ }
162
+ }, [addError, clearError, formAtom, validator]);
163
+ const customFocusHandlers = (0, MultiValueMap_1.useMultiValueMap)();
164
+ const registerReceiveFocus = (0, react_2.useCallback)((fieldName, handler) => {
165
+ customFocusHandlers().add(fieldName, handler);
166
+ return () => {
167
+ customFocusHandlers().remove(fieldName, handler);
168
+ };
169
+ }, [customFocusHandlers]);
170
+ (0, util_1.useIsomorphicLayoutEffect)(() => {
171
+ syncFormContext({
172
+ formAtom,
173
+ action,
174
+ defaultValues: providedDefaultValues !== null && providedDefaultValues !== void 0 ? providedDefaultValues : backendDefaultValues,
175
+ subaction,
176
+ validateField,
177
+ registerReceiveFocus,
178
+ });
179
+ }, [
180
+ action,
181
+ formAtom,
182
+ providedDefaultValues,
183
+ registerReceiveFocus,
184
+ subaction,
185
+ syncFormContext,
186
+ validateField,
187
+ backendDefaultValues,
188
+ ]);
189
+ (0, react_2.useEffect)(() => {
190
+ var _a;
191
+ setFieldErrors({
192
+ fieldErrors: (_a = backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors) !== null && _a !== void 0 ? _a : {},
193
+ formAtom,
194
+ });
195
+ }, [backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors, formAtom, setFieldErrors]);
196
+ (0, submissionCallbacks_1.useSubmitComplete)(hasActiveSubmission, () => {
197
+ endSubmit({ formAtom });
198
+ });
213
199
  let clickedButtonRef = react_2.default.useRef();
214
200
  (0, react_2.useEffect)(() => {
215
201
  let form = formRef.current;
@@ -230,36 +216,41 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
230
216
  window.removeEventListener("click", handleClick);
231
217
  };
232
218
  }, []);
233
- return ((0, jsx_runtime_1.jsx)(Form, { ref: (0, util_1.mergeRefs)([formRef, formRefProp]), ...rest, action: action, method: method, replace: replace, onSubmit: async (e) => {
234
- e.preventDefault();
235
- setHasBeenSubmitted(true);
236
- startSubmit();
237
- const result = await validator.validate(getDataFromForm(e.currentTarget));
238
- if (result.error) {
239
- endSubmit();
240
- setFieldErrors(result.error.fieldErrors);
241
- if (!disableFocusOnError) {
242
- focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
243
- }
219
+ const handleSubmit = async (e) => {
220
+ startSubmit({ formAtom });
221
+ const result = await validator.validate(getDataFromForm(e.currentTarget));
222
+ if (result.error) {
223
+ endSubmit({ formAtom });
224
+ setFieldErrors({ fieldErrors: result.error.fieldErrors, formAtom });
225
+ if (!disableFocusOnError) {
226
+ focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
244
227
  }
245
- else {
246
- onSubmit && onSubmit(result.data, e);
247
- if (fetcher)
248
- fetcher.submit(clickedButtonRef.current || e.currentTarget);
249
- else
250
- submit(clickedButtonRef.current || e.currentTarget, {
251
- method,
252
- replace,
253
- });
254
- clickedButtonRef.current = null;
228
+ }
229
+ else {
230
+ const eventProxy = formEventProxy(e);
231
+ await (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, eventProxy));
232
+ if (eventProxy.defaultPrevented) {
233
+ endSubmit({ formAtom });
234
+ return;
255
235
  }
236
+ if (fetcher)
237
+ fetcher.submit(clickedButtonRef.current || e.currentTarget);
238
+ else
239
+ submit(clickedButtonRef.current || e.currentTarget, {
240
+ method,
241
+ replace,
242
+ });
243
+ clickedButtonRef.current = null;
244
+ }
245
+ };
246
+ return ((0, jsx_runtime_1.jsx)(Form, { ref: (0, util_1.mergeRefs)([formRef, formRefProp]), ...rest, id: id, action: action, method: method, replace: replace, onSubmit: (e) => {
247
+ e.preventDefault();
248
+ handleSubmit(e);
256
249
  }, onReset: (event) => {
257
250
  onReset === null || onReset === void 0 ? void 0 : onReset(event);
258
251
  if (event.defaultPrevented)
259
252
  return;
260
- setFieldErrors({});
261
- setTouchedFields({});
262
- setHasBeenSubmitted(false);
263
- }, children: (0, jsx_runtime_1.jsxs)(formContext_1.FormContext.Provider, { value: contextValue, children: [subaction && ((0, jsx_runtime_1.jsx)("input", { type: "hidden", value: subaction, name: "subaction" }, void 0)), children] }, void 0) }, void 0));
253
+ reset({ formAtom });
254
+ }, children: (0, jsx_runtime_1.jsxs)(formContext_1.InternalFormContext.Provider, { value: contextValue, children: [(0, jsx_runtime_1.jsx)(FormResetter, { formRef: formRef, resetAfterSubmit: resetAfterSubmit }, void 0), subaction && ((0, jsx_runtime_1.jsx)("input", { type: "hidden", value: subaction, name: "subaction" }, void 0)), id && (0, jsx_runtime_1.jsx)("input", { type: "hidden", value: id, name: constants_1.FORM_ID_FIELD }, void 0), children] }, void 0) }, void 0));
264
255
  }
265
256
  exports.ValidatedForm = ValidatedForm;
package/build/hooks.d.ts CHANGED
@@ -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/build/hooks.js CHANGED
@@ -1,45 +1,60 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.useIsValid = exports.useIsSubmitting = exports.useFormContext = exports.useField = void 0;
7
- const get_1 = __importDefault(require("lodash/get"));
8
- const toPath_1 = __importDefault(require("lodash/toPath"));
3
+ exports.useField = exports.useIsValid = exports.useIsSubmitting = void 0;
9
4
  const react_1 = require("react");
10
- const formContext_1 = require("./internal/formContext");
11
5
  const getInputProps_1 = require("./internal/getInputProps");
12
- const useInternalFormContext = (hookName) => {
13
- const context = (0, react_1.useContext)(formContext_1.FormContext);
14
- if (!context)
15
- throw new Error(`${hookName} must be used within a ValidatedForm component`);
16
- return context;
6
+ const hooks_1 = require("./internal/hooks");
7
+ const state_1 = require("./internal/state");
8
+ /**
9
+ * Returns whether or not the parent form is currently being submitted.
10
+ * This is different from remix's `useTransition().submission` in that it
11
+ * is aware of what form it's in and when _that_ form is being submitted.
12
+ *
13
+ * @param formId
14
+ */
15
+ const useIsSubmitting = (formId) => {
16
+ const formContext = (0, hooks_1.useInternalFormContext)(formId, "useIsSubmitting");
17
+ return (0, hooks_1.useContextSelectAtom)(formContext.formId, state_1.isSubmittingAtom);
17
18
  };
19
+ exports.useIsSubmitting = useIsSubmitting;
20
+ /**
21
+ * Returns whether or not the current form is valid.
22
+ *
23
+ * @param formId the id of the form. Only necessary if being used outside a ValidatedForm.
24
+ */
25
+ const useIsValid = (formId) => {
26
+ const formContext = (0, hooks_1.useInternalFormContext)(formId, "useIsValid");
27
+ return (0, hooks_1.useContextSelectAtom)(formContext.formId, state_1.isValidAtom);
28
+ };
29
+ exports.useIsValid = useIsValid;
18
30
  /**
19
31
  * Provides the data and helpers necessary to set up a field.
20
32
  */
21
33
  const useField = (name, options) => {
22
- const { fieldErrors, clearError, validateField, defaultValues, registerReceiveFocus, touchedFields, setFieldTouched, hasBeenSubmitted, } = useInternalFormContext("useField");
23
- const isTouched = !!touchedFields[name];
24
- const { handleReceiveFocus } = options !== null && options !== void 0 ? options : {};
34
+ const { handleReceiveFocus, formId: providedFormId } = options !== null && options !== void 0 ? options : {};
35
+ const formContext = (0, hooks_1.useInternalFormContext)(providedFormId, "useField");
36
+ const defaultValue = (0, hooks_1.useFieldDefaultValue)(name, formContext);
37
+ const touched = (0, hooks_1.useFieldTouched)(name, formContext);
38
+ const error = (0, hooks_1.useFieldError)(name, formContext);
39
+ const clearError = (0, hooks_1.useClearError)(formContext);
40
+ const setTouched = (0, hooks_1.useSetTouched)(formContext);
41
+ const hasBeenSubmitted = (0, hooks_1.useContextSelectAtom)(formContext.formId, state_1.hasBeenSubmittedAtom);
42
+ const validateField = (0, hooks_1.useContextSelectAtom)(formContext.formId, state_1.validateFieldAtom);
43
+ const registerReceiveFocus = (0, hooks_1.useContextSelectAtom)(formContext.formId, state_1.registerReceiveFocusAtom);
25
44
  (0, react_1.useEffect)(() => {
26
45
  if (handleReceiveFocus)
27
46
  return registerReceiveFocus(name, handleReceiveFocus);
28
47
  }, [handleReceiveFocus, name, registerReceiveFocus]);
29
48
  const field = (0, react_1.useMemo)(() => {
30
49
  const helpers = {
31
- error: fieldErrors[name],
32
- clearError: () => {
33
- clearError(name);
34
- },
50
+ error,
51
+ clearError: () => clearError(name),
35
52
  validate: () => {
36
53
  validateField(name);
37
54
  },
38
- defaultValue: defaultValues
39
- ? (0, get_1.default)(defaultValues, (0, toPath_1.default)(name), undefined)
40
- : undefined,
41
- touched: isTouched,
42
- setTouched: (touched) => setFieldTouched(name, touched),
55
+ defaultValue,
56
+ touched,
57
+ setTouched: (touched) => setTouched(name, touched),
43
58
  };
44
59
  const getInputProps = (0, getInputProps_1.createGetInputProps)({
45
60
  ...helpers,
@@ -52,33 +67,16 @@ const useField = (name, options) => {
52
67
  getInputProps,
53
68
  };
54
69
  }, [
55
- fieldErrors,
70
+ error,
71
+ defaultValue,
72
+ touched,
56
73
  name,
57
- defaultValues,
58
- isTouched,
59
74
  hasBeenSubmitted,
60
75
  options === null || options === void 0 ? void 0 : options.validationBehavior,
61
76
  clearError,
62
77
  validateField,
63
- setFieldTouched,
78
+ setTouched,
64
79
  ]);
65
80
  return field;
66
81
  };
67
82
  exports.useField = useField;
68
- /**
69
- * Provides access to the entire form context.
70
- */
71
- const useFormContext = () => useInternalFormContext("useFormContext");
72
- exports.useFormContext = useFormContext;
73
- /**
74
- * Returns whether or not the parent form is currently being submitted.
75
- * This is different from remix's `useTransition().submission` in that it
76
- * is aware of what form it's in and when _that_ form is being submitted.
77
- */
78
- const useIsSubmitting = () => useInternalFormContext("useIsSubmitting").isSubmitting;
79
- exports.useIsSubmitting = useIsSubmitting;
80
- /**
81
- * Returns whether or not the current form is valid.
82
- */
83
- const useIsValid = () => useInternalFormContext("useIsValid").isValid;
84
- exports.useIsValid = useIsValid;
package/build/index.d.ts CHANGED
@@ -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/build/index.js CHANGED
@@ -15,3 +15,4 @@ __exportStar(require("./server"), exports);
15
15
  __exportStar(require("./ValidatedForm"), exports);
16
16
  __exportStar(require("./validation/types"), exports);
17
17
  __exportStar(require("./validation/createValidator"), exports);
18
+ __exportStar(require("./userFacingFormContext"), exports);
@@ -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,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formDefaultValuesKey = exports.FORM_DEFAULTS_FIELD = exports.FORM_ID_FIELD = void 0;
4
+ exports.FORM_ID_FIELD = "__rvfInternalFormId";
5
+ exports.FORM_DEFAULTS_FIELD = "__rvfInternalFormDefaults";
6
+ const formDefaultValuesKey = (formId) => `${exports.FORM_DEFAULTS_FIELD}_${formId}`;
7
+ exports.formDefaultValuesKey = formDefaultValuesKey;
@@ -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,5 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FormContext = void 0;
3
+ exports.InternalFormContext = void 0;
4
4
  const react_1 = require("react");
5
- exports.FormContext = (0, react_1.createContext)(null);
5
+ exports.InternalFormContext = (0, react_1.createContext)(null);