remix-validated-form 4.0.1-beta.2 → 4.1.0-beta.2

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 +137 -149
  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 +133 -145
  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 +199 -200
  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,64 +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 isSubmitting = hasActiveSubmission && isSubmitStarted;
65
- const startSubmit = () => setSubmitStarted(true);
66
- const endSubmit = () => setSubmitStarted(false);
67
- return [isSubmitting, startSubmit, endSubmit];
68
- };
69
39
  const getDataFromForm = (el) => new FormData(el);
70
- /**
71
- * The purpose for this logic is to handle validation errors when javascript is disabled.
72
- * Normally (without js), when a form is submitted and the action returns the validation errors,
73
- * the form will be reset. The errors will be displayed on the correct fields,
74
- * but all the values in the form will be gone. This is not good UX.
75
- *
76
- * To get around this, we return the submitted form data from the server,
77
- * and use those to populate the form via `defaultValues`.
78
- * This results in a more seamless UX akin to what you would see when js is enabled.
79
- *
80
- * One potential downside is that resetting the form will reset the form
81
- * to the _new_ default values that were returned from the server with the validation errors.
82
- * However, this case is less of a problem than the janky UX caused by losing the form values.
83
- * It will only ever be a problem if the form includes a `<button type="reset" />`
84
- * and only if JS is disabled.
85
- */
86
- function useDefaultValues(repopulateFieldsFromBackend, defaultValues) {
87
- return repopulateFieldsFromBackend !== null && repopulateFieldsFromBackend !== void 0 ? repopulateFieldsFromBackend : defaultValues;
88
- }
89
40
  function nonNull(value) {
90
41
  return value !== null;
91
42
  }
@@ -129,85 +80,117 @@ const focusFirstInvalidInput = (fieldErrors, customFocusHandlers, formElement) =
129
80
  }
130
81
  }
131
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
+ };
132
88
  /**
133
- * 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.
134
91
  */
135
- function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit, disableFocusOnError, method, replace, ...rest }) {
136
- var _a;
137
- const backendError = useErrorResponseForThisForm(fetcher, subaction);
138
- const [fieldErrors, setFieldErrors] = useFieldErrors(backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors);
139
- const [isSubmitting, startSubmit, endSubmit] = useIsSubmitting(fetcher);
140
- const defaultsToUse = useDefaultValues(backendError === null || backendError === void 0 ? void 0 : backendError.repopulateFields, defaultValues);
141
- const [touchedFields, setTouchedFields] = (0, react_2.useState)({});
142
- const [hasBeenSubmitted, setHasBeenSubmitted] = (0, react_2.useState)(false);
143
- const submit = (0, react_1.useSubmit)();
144
- 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)();
145
95
  (0, submissionCallbacks_1.useSubmitComplete)(isSubmitting, () => {
146
96
  var _a;
147
- endSubmit();
148
- if (!backendError && resetAfterSubmit) {
97
+ if (isValid && resetAfterSubmit) {
149
98
  (_a = formRef.current) === null || _a === void 0 ? void 0 : _a.reset();
150
99
  }
151
100
  });
152
- const customFocusHandlers = (0, MultiValueMap_1.useMultiValueMap)();
153
- const contextValue = (0, react_2.useMemo)(() => ({
154
- fieldErrors,
155
- action,
156
- defaultValues: defaultsToUse,
157
- isSubmitting,
158
- isValid: Object.keys(fieldErrors).length === 0,
159
- touchedFields,
160
- setFieldTouched: (fieldName, touched) => setTouchedFields((prev) => ({
161
- ...prev,
162
- [fieldName]: touched,
163
- })),
164
- clearError: (fieldName) => {
165
- setFieldErrors((prev) => (0, util_1.omit)(prev, fieldName));
166
- },
167
- validateField: async (fieldName) => {
168
- (0, tiny_invariant_1.default)(formRef.current, "Cannot find reference to form");
169
- const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
170
- // By checking and returning `prev` here, we can avoid a re-render
171
- // if the validation state is the same.
172
- if (error) {
173
- setFieldErrors((prev) => {
174
- if (prev[fieldName] === error)
175
- return prev;
176
- return {
177
- ...prev,
178
- [fieldName]: error,
179
- };
180
- });
181
- 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
+ };
182
111
  }
183
- else {
184
- setFieldErrors((prev) => {
185
- if (!(fieldName in prev))
186
- return prev;
187
- return (0, util_1.omit)(prev, fieldName);
188
- });
189
- return null;
112
+ if (prop === "defaultPrevented") {
113
+ return defaultPrevented;
190
114
  }
115
+ return target[prop];
191
116
  },
192
- registerReceiveFocus: (fieldName, handler) => {
193
- customFocusHandlers().add(fieldName, handler);
194
- return () => {
195
- customFocusHandlers().remove(fieldName, handler);
196
- };
197
- },
198
- hasBeenSubmitted,
199
- }), [
200
- fieldErrors,
117
+ });
118
+ }
119
+ /**
120
+ * The primary form component of `remix-validated-form`.
121
+ */
122
+ function ValidatedForm({ validator, onSubmit, children, fetcher, action, defaultValues: providedDefaultValues, formRef: formRefProp, onReset, subaction, resetAfterSubmit = false, disableFocusOnError, method, replace, id, ...rest }) {
123
+ var _a;
124
+ const formId = useFormId(id);
125
+ const formAtom = (0, state_1.formRegistry)(formId);
126
+ const contextValue = (0, react_2.useMemo)(() => ({
127
+ formId,
201
128
  action,
202
- defaultsToUse,
203
- isSubmitting,
204
- touchedFields,
205
- hasBeenSubmitted,
206
- setFieldErrors,
207
- validator,
208
- customFocusHandlers,
209
- ]);
129
+ subaction,
130
+ defaultValuesProp: providedDefaultValues,
131
+ fetcher,
132
+ }), [action, fetcher, formId, providedDefaultValues, subaction]);
133
+ const backendError = (0, hooks_2.useErrorResponseForForm)(contextValue);
134
+ const backendDefaultValues = (0, hooks_2.useDefaultValuesFromLoader)(contextValue);
135
+ const hasActiveSubmission = (0, hooks_2.useHasActiveFormSubmit)(contextValue);
136
+ const formRef = (0, react_2.useRef)(null);
210
137
  const Form = (_a = fetcher === null || fetcher === void 0 ? void 0 : fetcher.Form) !== null && _a !== void 0 ? _a : react_1.Form;
138
+ const submit = (0, react_1.useSubmit)();
139
+ const clearError = (0, hooks_2.useFormUpdateAtom)(state_1.clearErrorAtom);
140
+ const addError = (0, hooks_2.useFormUpdateAtom)(state_1.addErrorAtom);
141
+ const setFieldErrors = (0, hooks_2.useFormUpdateAtom)(state_1.setFieldErrorsAtom);
142
+ const reset = (0, hooks_2.useFormUpdateAtom)(state_1.resetAtom);
143
+ const startSubmit = (0, hooks_2.useFormUpdateAtom)(state_1.startSubmitAtom);
144
+ const endSubmit = (0, hooks_2.useFormUpdateAtom)(state_1.endSubmitAtom);
145
+ const syncFormContext = (0, hooks_2.useFormUpdateAtom)(state_1.syncFormContextAtom);
146
+ const validateField = (0, react_2.useCallback)(async (fieldName) => {
147
+ (0, tiny_invariant_1.default)(formRef.current, "Cannot find reference to form");
148
+ const { error } = await validator.validateField(getDataFromForm(formRef.current), fieldName);
149
+ if (error) {
150
+ addError({ formAtom, name: fieldName, error });
151
+ return error;
152
+ }
153
+ else {
154
+ clearError({ name: fieldName, formAtom });
155
+ return null;
156
+ }
157
+ }, [addError, clearError, formAtom, validator]);
158
+ const customFocusHandlers = (0, MultiValueMap_1.useMultiValueMap)();
159
+ const registerReceiveFocus = (0, react_2.useCallback)((fieldName, handler) => {
160
+ customFocusHandlers().add(fieldName, handler);
161
+ return () => {
162
+ customFocusHandlers().remove(fieldName, handler);
163
+ };
164
+ }, [customFocusHandlers]);
165
+ (0, util_1.useIsomorphicLayoutEffect)(() => {
166
+ syncFormContext({
167
+ formAtom,
168
+ action,
169
+ defaultValues: providedDefaultValues !== null && providedDefaultValues !== void 0 ? providedDefaultValues : backendDefaultValues,
170
+ subaction,
171
+ validateField,
172
+ registerReceiveFocus,
173
+ });
174
+ }, [
175
+ action,
176
+ formAtom,
177
+ providedDefaultValues,
178
+ registerReceiveFocus,
179
+ subaction,
180
+ syncFormContext,
181
+ validateField,
182
+ backendDefaultValues,
183
+ ]);
184
+ (0, react_2.useEffect)(() => {
185
+ var _a;
186
+ setFieldErrors({
187
+ fieldErrors: (_a = backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors) !== null && _a !== void 0 ? _a : {},
188
+ formAtom,
189
+ });
190
+ }, [backendError === null || backendError === void 0 ? void 0 : backendError.fieldErrors, formAtom, setFieldErrors]);
191
+ (0, submissionCallbacks_1.useSubmitComplete)(hasActiveSubmission, () => {
192
+ endSubmit({ formAtom });
193
+ });
211
194
  let clickedButtonRef = react_2.default.useRef();
212
195
  (0, react_2.useEffect)(() => {
213
196
  let form = formRef.current;
@@ -228,36 +211,41 @@ function ValidatedForm({ validator, onSubmit, children, fetcher, action, default
228
211
  window.removeEventListener("click", handleClick);
229
212
  };
230
213
  }, []);
231
- return ((0, jsx_runtime_1.jsx)(Form, { ref: (0, util_1.mergeRefs)([formRef, formRefProp]), ...rest, action: action, method: method, replace: replace, onSubmit: async (e) => {
232
- e.preventDefault();
233
- setHasBeenSubmitted(true);
234
- startSubmit();
235
- const result = await validator.validate(getDataFromForm(e.currentTarget));
236
- if (result.error) {
237
- endSubmit();
238
- setFieldErrors(result.error.fieldErrors);
239
- if (!disableFocusOnError) {
240
- focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
241
- }
214
+ const handleSubmit = async (e) => {
215
+ startSubmit({ formAtom });
216
+ const result = await validator.validate(getDataFromForm(e.currentTarget));
217
+ if (result.error) {
218
+ endSubmit({ formAtom });
219
+ setFieldErrors({ fieldErrors: result.error.fieldErrors, formAtom });
220
+ if (!disableFocusOnError) {
221
+ focusFirstInvalidInput(result.error.fieldErrors, customFocusHandlers(), formRef.current);
242
222
  }
243
- else {
244
- onSubmit && onSubmit(result.data, e);
245
- if (fetcher)
246
- fetcher.submit(clickedButtonRef.current || e.currentTarget);
247
- else
248
- submit(clickedButtonRef.current || e.currentTarget, {
249
- method,
250
- replace,
251
- });
252
- clickedButtonRef.current = null;
223
+ }
224
+ else {
225
+ const eventProxy = formEventProxy(e);
226
+ await (onSubmit === null || onSubmit === void 0 ? void 0 : onSubmit(result.data, eventProxy));
227
+ if (eventProxy.defaultPrevented) {
228
+ endSubmit({ formAtom });
229
+ return;
253
230
  }
231
+ if (fetcher)
232
+ fetcher.submit(clickedButtonRef.current || e.currentTarget);
233
+ else
234
+ submit(clickedButtonRef.current || e.currentTarget, {
235
+ method,
236
+ replace,
237
+ });
238
+ clickedButtonRef.current = null;
239
+ }
240
+ };
241
+ 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) => {
242
+ e.preventDefault();
243
+ handleSubmit(e);
254
244
  }, onReset: (event) => {
255
245
  onReset === null || onReset === void 0 ? void 0 : onReset(event);
256
246
  if (event.defaultPrevented)
257
247
  return;
258
- setFieldErrors({});
259
- setTouchedFields({});
260
- setHasBeenSubmitted(false);
261
- }, 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));
248
+ reset({ formAtom });
249
+ }, 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));
262
250
  }
263
251
  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);