remix-validated-form 4.3.0 → 4.3.1-beta.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 (137) hide show
  1. package/.turbo/turbo-build.log +15 -9
  2. package/README.md +1 -0
  3. package/browser/internal/logic/getRadioChecked.js +10 -0
  4. package/browser/internal/reset.d.ts +0 -0
  5. package/browser/internal/reset.js +0 -0
  6. package/browser/unreleased/formStateHooks.d.ts +0 -0
  7. package/browser/unreleased/formStateHooks.js +0 -0
  8. package/dist/remix-validated-form.cjs.js +1 -0
  9. package/dist/remix-validated-form.es.js +3535 -0
  10. package/dist/remix-validated-form.umd.js +1 -0
  11. package/{build → dist/types}/ValidatedForm.d.ts +0 -0
  12. package/{build → dist/types}/hooks.d.ts +0 -0
  13. package/{build → dist/types}/index.d.ts +0 -0
  14. package/{build → dist/types}/internal/MultiValueMap.d.ts +0 -0
  15. package/{build → dist/types}/internal/constants.d.ts +0 -0
  16. package/{build → dist/types}/internal/flatten.d.ts +0 -0
  17. package/{build → dist/types}/internal/formContext.d.ts +0 -0
  18. package/{build → dist/types}/internal/getInputProps.d.ts +0 -0
  19. package/{build → dist/types}/internal/hooks.d.ts +0 -0
  20. package/{build → dist/types}/internal/hydratable.d.ts +0 -0
  21. package/{build → dist/types}/internal/logic/getCheckboxChecked.d.ts +0 -0
  22. package/{build → dist/types}/internal/logic/getRadioChecked.d.ts +0 -0
  23. package/{build → dist/types}/internal/reset.d.ts +0 -0
  24. package/{build → dist/types}/internal/state/atomUtils.d.ts +0 -0
  25. package/{build → dist/types}/internal/state/controlledFields.d.ts +0 -0
  26. package/{build → dist/types}/internal/state.d.ts +0 -0
  27. package/{build → dist/types}/internal/submissionCallbacks.d.ts +0 -0
  28. package/{build → dist/types}/internal/util.d.ts +0 -0
  29. package/{build → dist/types}/server.d.ts +0 -0
  30. package/{build → dist/types}/unreleased/formStateHooks.d.ts +0 -0
  31. package/{build → dist/types}/userFacingFormContext.d.ts +0 -0
  32. package/{build → dist/types}/validation/createValidator.d.ts +0 -0
  33. package/{build → dist/types}/validation/types.d.ts +0 -0
  34. package/package.json +8 -7
  35. package/src/internal/getInputProps.test.ts +251 -0
  36. package/src/internal/logic/getRadioChecked.ts +11 -0
  37. package/src/validation/validation.test.ts +304 -0
  38. package/tsconfig.json +4 -1
  39. package/vite.config.ts +7 -0
  40. package/.turbo/turbo-test.log +0 -11
  41. package/browser/components.d.ts +0 -7
  42. package/browser/components.js +0 -10
  43. package/browser/internal/SingleTypeMultiValueMap.d.ts +0 -9
  44. package/browser/internal/SingleTypeMultiValueMap.js +0 -41
  45. package/browser/internal/customState.d.ts +0 -105
  46. package/browser/internal/customState.js +0 -46
  47. package/browser/internal/hooks-valtio.d.ts +0 -18
  48. package/browser/internal/hooks-valtio.js +0 -110
  49. package/browser/internal/hooks-zustand.d.ts +0 -16
  50. package/browser/internal/hooks-zustand.js +0 -100
  51. package/browser/internal/immerMiddleware.d.ts +0 -6
  52. package/browser/internal/immerMiddleware.js +0 -7
  53. package/browser/internal/logic/elementUtils.d.ts +0 -3
  54. package/browser/internal/logic/elementUtils.js +0 -3
  55. package/browser/internal/logic/getCheckboxChecked copy.d.ts +0 -1
  56. package/browser/internal/logic/getCheckboxChecked copy.js +0 -9
  57. package/browser/internal/logic/setFieldValue.d.ts +0 -1
  58. package/browser/internal/logic/setFieldValue.js +0 -40
  59. package/browser/internal/logic/setInputValueInForm.d.ts +0 -1
  60. package/browser/internal/logic/setInputValueInForm.js +0 -77
  61. package/browser/internal/setFieldValue.d.ts +0 -20
  62. package/browser/internal/setFieldValue.js +0 -83
  63. package/browser/internal/setFormValues.d.ts +0 -2
  64. package/browser/internal/setFormValues.js +0 -26
  65. package/browser/internal/state/setFieldValue.d.ts +0 -0
  66. package/browser/internal/state/setFieldValue.js +0 -1
  67. package/browser/internal/state-valtio.d.ts +0 -62
  68. package/browser/internal/state-valtio.js +0 -69
  69. package/browser/internal/state-zustand.d.ts +0 -47
  70. package/browser/internal/state-zustand.js +0 -85
  71. package/browser/internal/test.d.ts +0 -0
  72. package/browser/internal/test.js +0 -15
  73. package/browser/internal/useMultiValueMap.d.ts +0 -1
  74. package/browser/internal/useMultiValueMap.js +0 -11
  75. package/browser/internal/watch.d.ts +0 -18
  76. package/browser/internal/watch.js +0 -122
  77. package/browser/lowLevelHooks.d.ts +0 -0
  78. package/browser/lowLevelHooks.js +0 -1
  79. package/browser/test-data/testFormData.d.ts +0 -15
  80. package/browser/test-data/testFormData.js +0 -46
  81. package/browser/types.d.ts +0 -1
  82. package/browser/types.js +0 -1
  83. package/browser/validation/validation.test.d.ts +0 -1
  84. package/browser/validation/validation.test.js +0 -274
  85. package/browser/validation/withYup.d.ts +0 -6
  86. package/browser/validation/withYup.js +0 -40
  87. package/browser/validation/withZod.d.ts +0 -6
  88. package/browser/validation/withZod.js +0 -50
  89. package/build/ValidatedForm.js +0 -261
  90. package/build/hooks.js +0 -91
  91. package/build/index.js +0 -18
  92. package/build/internal/MultiValueMap.js +0 -48
  93. package/build/internal/SingleTypeMultiValueMap.d.ts +0 -8
  94. package/build/internal/SingleTypeMultiValueMap.js +0 -45
  95. package/build/internal/constants.js +0 -7
  96. package/build/internal/flatten.js +0 -14
  97. package/build/internal/formContext.js +0 -5
  98. package/build/internal/getInputProps.js +0 -58
  99. package/build/internal/hooks-valtio.d.ts +0 -18
  100. package/build/internal/hooks-valtio.js +0 -128
  101. package/build/internal/hooks-zustand.d.ts +0 -16
  102. package/build/internal/hooks-zustand.js +0 -117
  103. package/build/internal/hooks.js +0 -128
  104. package/build/internal/hydratable.js +0 -17
  105. package/build/internal/immerMiddleware.d.ts +0 -6
  106. package/build/internal/immerMiddleware.js +0 -14
  107. package/build/internal/logic/elementUtils.d.ts +0 -3
  108. package/build/internal/logic/elementUtils.js +0 -9
  109. package/build/internal/logic/getCheckboxChecked.js +0 -13
  110. package/build/internal/logic/getRadioChecked.js +0 -9
  111. package/build/internal/logic/setFieldValue.d.ts +0 -1
  112. package/build/internal/logic/setFieldValue.js +0 -47
  113. package/build/internal/logic/setInputValueInForm.d.ts +0 -1
  114. package/build/internal/logic/setInputValueInForm.js +0 -84
  115. package/build/internal/reset.js +0 -19
  116. package/build/internal/setFormValues.d.ts +0 -2
  117. package/build/internal/setFormValues.js +0 -33
  118. package/build/internal/state/atomUtils.js +0 -13
  119. package/build/internal/state/controlledFields.js +0 -103
  120. package/build/internal/state-valtio.d.ts +0 -62
  121. package/build/internal/state-valtio.js +0 -83
  122. package/build/internal/state-zustand.d.ts +0 -47
  123. package/build/internal/state-zustand.js +0 -91
  124. package/build/internal/state.js +0 -71
  125. package/build/internal/submissionCallbacks.js +0 -17
  126. package/build/internal/test.d.ts +0 -1
  127. package/build/internal/test.js +0 -12
  128. package/build/internal/util.js +0 -41
  129. package/build/internal/watch.d.ts +0 -20
  130. package/build/internal/watch.js +0 -126
  131. package/build/server.js +0 -32
  132. package/build/types.d.ts +0 -1
  133. package/build/types.js +0 -2
  134. package/build/unreleased/formStateHooks.js +0 -59
  135. package/build/userFacingFormContext.js +0 -30
  136. package/build/validation/createValidator.js +0 -45
  137. package/build/validation/types.js +0 -2
@@ -1,110 +0,0 @@
1
- import { useActionData, useMatches, useTransition } from "@remix-run/react";
2
- import { useUpdateAtom } from "jotai/utils";
3
- import lodashGet from "lodash/get";
4
- import { useCallback, useContext } from "react";
5
- import invariant from "tiny-invariant";
6
- import { formDefaultValuesKey } from "./constants";
7
- import { InternalFormContext } from "./formContext";
8
- import { hydratable } from "./hydratable";
9
- import { ATOM_SCOPE, clearErrorAtom, formRegistry, setTouchedAtom, } from "./state";
10
- import { useFormData } from "./state-valtio";
11
- export const useInternalFormContext = (formId, hookName) => {
12
- const formContext = useContext(InternalFormContext);
13
- if (formId)
14
- return { formId };
15
- if (formContext)
16
- return formContext;
17
- throw new Error(`Unable to determine form for ${hookName}. Please use it inside a form or pass a 'formId'.`);
18
- };
19
- export function useErrorResponseForForm({ fetcher, subaction, formId, }) {
20
- var _a;
21
- const actionData = useActionData();
22
- if (fetcher) {
23
- if ((_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors)
24
- return fetcher.data;
25
- return null;
26
- }
27
- if (!(actionData === null || actionData === void 0 ? void 0 : actionData.fieldErrors))
28
- return null;
29
- // If there's an explicit id, we should ignore data that has the wrong id
30
- if (typeof formId === "string" && actionData.formId)
31
- return actionData.formId === formId ? actionData : null;
32
- if ((!subaction && !actionData.subaction) ||
33
- actionData.subaction === subaction)
34
- return actionData;
35
- return null;
36
- }
37
- export const useFieldErrorsForForm = (context) => {
38
- const response = useErrorResponseForForm(context);
39
- const form = useFormData(context.formId);
40
- return hydratable.from(response === null || response === void 0 ? void 0 : response.fieldErrors, form.hydrated);
41
- };
42
- export const useDefaultValuesFromLoader = ({ formId, }) => {
43
- const matches = useMatches();
44
- if (typeof formId === "string") {
45
- const dataKey = formDefaultValuesKey(formId);
46
- // If multiple loaders declare the same default values,
47
- // we should use the data from the deepest route.
48
- const match = matches
49
- .reverse()
50
- .find((match) => match.data && dataKey in match.data);
51
- return match === null || match === void 0 ? void 0 : match.data[dataKey];
52
- }
53
- return null;
54
- };
55
- export const useDefaultValuesForForm = (context) => {
56
- const { formId, defaultValuesProp } = context;
57
- const form = useFormData(formId);
58
- const errorResponse = useErrorResponseForForm(context);
59
- const defaultValuesFromLoader = useDefaultValuesFromLoader(context);
60
- // Typical flow is:
61
- // - Default values only available from props or server
62
- // - Props have a higher priority than server
63
- // - State gets hydrated with default values
64
- // - After submit, we may need to use values from the error
65
- if (form.hydrated)
66
- return hydratable.hydratedData();
67
- if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.repopulateFields) {
68
- invariant(typeof errorResponse.repopulateFields === "object", "repopulateFields returned something other than an object");
69
- return hydratable.serverData(errorResponse.repopulateFields);
70
- }
71
- if (defaultValuesProp)
72
- return hydratable.serverData(defaultValuesProp);
73
- return hydratable.serverData(defaultValuesFromLoader);
74
- };
75
- export const useHasActiveFormSubmit = ({ fetcher, }) => {
76
- const transition = useTransition();
77
- const hasActiveSubmission = fetcher
78
- ? fetcher.state === "submitting"
79
- : !!transition.submission;
80
- return hasActiveSubmission;
81
- };
82
- export const useFieldTouched = (name, { formId }) => {
83
- const form = useFormData(formId);
84
- return form.touchedFields[name];
85
- };
86
- export const useFieldError = (name, context) => {
87
- const fieldErrors = useFieldErrorsForForm(context);
88
- const form = useFormData(context.formId);
89
- return fieldErrors
90
- .map((fieldErrors) => fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors[name])
91
- .hydrateTo(form.fieldErrors[name]);
92
- };
93
- export const useFieldDefaultValue = (name, context) => {
94
- const defaultValues = useDefaultValuesForForm(context);
95
- const state = useFormData(context.formId);
96
- return defaultValues.map((val) => lodashGet(val, name)).hydrateTo(state);
97
- };
98
- export const useFormUpdateAtom = (atom) => useUpdateAtom(atom, ATOM_SCOPE);
99
- export const useClearError = (context) => {
100
- const clearError = useFormUpdateAtom(clearErrorAtom);
101
- return useCallback((name) => {
102
- clearError({ name, formAtom: formRegistry(context.formId) });
103
- }, [clearError, context.formId]);
104
- };
105
- export const useSetTouched = (context) => {
106
- const setTouched = useFormUpdateAtom(setTouchedAtom);
107
- return useCallback((name, touched) => {
108
- setTouched({ name, formAtom: formRegistry(context.formId), touched });
109
- }, [setTouched, context.formId]);
110
- };
@@ -1,16 +0,0 @@
1
- import { FieldErrors, ValidationErrorResponseData } from "..";
2
- import { InternalFormContextValue } from "./formContext";
3
- import { Hydratable } from "./hydratable";
4
- export declare const useInternalFormContext: (formId?: string | symbol | undefined, hookName?: string | undefined) => InternalFormContextValue;
5
- export declare function useErrorResponseForForm({ fetcher, subaction, formId, }: InternalFormContextValue): ValidationErrorResponseData | null;
6
- export declare const useFieldErrorsForForm: (context: InternalFormContextValue) => Hydratable<FieldErrors | undefined>;
7
- export declare const useDefaultValuesFromLoader: ({ formId, }: InternalFormContextValue) => any;
8
- export declare const useDefaultValuesForForm: (context: InternalFormContextValue) => Hydratable<{
9
- [fieldName: string]: any;
10
- }>;
11
- export declare const useHasActiveFormSubmit: ({ fetcher, }: InternalFormContextValue) => boolean;
12
- export declare const useFieldTouched: (name: string, { formId }: InternalFormContextValue) => boolean;
13
- export declare const useFieldError: (name: string, context: InternalFormContextValue) => string | undefined;
14
- export declare const useFieldDefaultValue: (name: string, context: InternalFormContextValue) => any;
15
- export declare const useClearError: (context: InternalFormContextValue) => (name: string) => void;
16
- export declare const useSetTouched: (context: InternalFormContextValue) => (name: string, touched: boolean) => void;
@@ -1,100 +0,0 @@
1
- import { useActionData, useMatches, useTransition } from "@remix-run/react";
2
- import lodashGet from "lodash/get";
3
- import { useContext } from "react";
4
- import invariant from "tiny-invariant";
5
- import { formDefaultValuesKey } from "./constants";
6
- import { InternalFormContext } from "./formContext";
7
- import { hydratable } from "./hydratable";
8
- import { useStore } from "./state-zustand";
9
- export const useInternalFormContext = (formId, hookName) => {
10
- const formContext = useContext(InternalFormContext);
11
- if (formId)
12
- return { formId };
13
- if (formContext)
14
- return formContext;
15
- throw new Error(`Unable to determine form for ${hookName}. Please use it inside a form or pass a 'formId'.`);
16
- };
17
- export function useErrorResponseForForm({ fetcher, subaction, formId, }) {
18
- var _a;
19
- const actionData = useActionData();
20
- if (fetcher) {
21
- if ((_a = fetcher.data) === null || _a === void 0 ? void 0 : _a.fieldErrors)
22
- return fetcher.data;
23
- return null;
24
- }
25
- if (!(actionData === null || actionData === void 0 ? void 0 : actionData.fieldErrors))
26
- return null;
27
- // If there's an explicit id, we should ignore data that has the wrong id
28
- if (typeof formId === "string" && actionData.formId)
29
- return actionData.formId === formId ? actionData : null;
30
- if ((!subaction && !actionData.subaction) ||
31
- actionData.subaction === subaction)
32
- return actionData;
33
- return null;
34
- }
35
- export const useFieldErrorsForForm = (context) => {
36
- const response = useErrorResponseForForm(context);
37
- const hydrated = useStore((state) => state.form(context.formId).hydrated);
38
- return hydratable.from(response === null || response === void 0 ? void 0 : response.fieldErrors, hydrated);
39
- };
40
- export const useDefaultValuesFromLoader = ({ formId, }) => {
41
- const matches = useMatches();
42
- if (typeof formId === "string") {
43
- const dataKey = formDefaultValuesKey(formId);
44
- // If multiple loaders declare the same default values,
45
- // we should use the data from the deepest route.
46
- const match = matches
47
- .reverse()
48
- .find((match) => match.data && dataKey in match.data);
49
- return match === null || match === void 0 ? void 0 : match.data[dataKey];
50
- }
51
- return null;
52
- };
53
- export const useDefaultValuesForForm = (context) => {
54
- const { formId, defaultValuesProp } = context;
55
- const hydrated = useStore((state) => state.form(formId).hydrated);
56
- const errorResponse = useErrorResponseForForm(context);
57
- const defaultValuesFromLoader = useDefaultValuesFromLoader(context);
58
- // Typical flow is:
59
- // - Default values only available from props or server
60
- // - Props have a higher priority than server
61
- // - State gets hydrated with default values
62
- // - After submit, we may need to use values from the error
63
- if (hydrated)
64
- return hydratable.hydratedData();
65
- if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.repopulateFields) {
66
- invariant(typeof errorResponse.repopulateFields === "object", "repopulateFields returned something other than an object");
67
- return hydratable.serverData(errorResponse.repopulateFields);
68
- }
69
- if (defaultValuesProp)
70
- return hydratable.serverData(defaultValuesProp);
71
- return hydratable.serverData(defaultValuesFromLoader);
72
- };
73
- export const useHasActiveFormSubmit = ({ fetcher, }) => {
74
- const transition = useTransition();
75
- const hasActiveSubmission = fetcher
76
- ? fetcher.state === "submitting"
77
- : !!transition.submission;
78
- return hasActiveSubmission;
79
- };
80
- export const useFieldTouched = (name, { formId }) => {
81
- return useStore((state) => state.form(formId).touchedFields[name]);
82
- };
83
- export const useFieldError = (name, context) => {
84
- const state = useStore((state) => state.form(context.formId).fieldErrors[name]);
85
- return useFieldErrorsForForm(context)
86
- .map((fieldErrors) => fieldErrors === null || fieldErrors === void 0 ? void 0 : fieldErrors[name])
87
- .hydrateTo(state);
88
- };
89
- export const useFieldDefaultValue = (name, context) => {
90
- const state = useStore((state) => state.form(context.formId).defaultValues[name]);
91
- return useDefaultValuesForForm(context)
92
- .map((val) => lodashGet(val, name))
93
- .hydrateTo(state);
94
- };
95
- export const useClearError = (context) => {
96
- return useStore((state) => state.helpers(context.formId).clearError);
97
- };
98
- export const useSetTouched = (context) => {
99
- return useStore((state) => state.helpers(context.formId).setTouched);
100
- };
@@ -1,6 +0,0 @@
1
- import { Draft } from "immer";
2
- import { State, StateCreator } from "zustand";
3
- declare type TImmerConfigFn<T extends State> = (partial: ((draft: Draft<T>) => void) | T, replace?: boolean) => void;
4
- declare type TImmerConfig<T extends State> = StateCreator<T, TImmerConfigFn<T>>;
5
- export declare const immer: <T extends object>(config: TImmerConfig<T>) => StateCreator<T, import("zustand").SetState<T>, import("zustand").GetState<T>, import("zustand").StoreApi<T>>;
6
- export {};
@@ -1,7 +0,0 @@
1
- import produce from "immer";
2
- export const immer = (config) => (set, get, api) => config((partial, replace) => {
3
- const nextState = typeof partial === "function"
4
- ? produce(partial)
5
- : partial;
6
- return set(nextState, replace);
7
- }, get, api);
@@ -1,3 +0,0 @@
1
- export declare const isMultiselect: (node: Node) => node is HTMLSelectElement;
2
- export declare const isCheckbox: (node: Node | RadioNodeList) => node is HTMLInputElement;
3
- export declare const isRadio: (node: Node) => node is HTMLInputElement;
@@ -1,3 +0,0 @@
1
- export const isMultiselect = (node) => node instanceof HTMLSelectElement && node.multiple;
2
- export const isCheckbox = (node) => node instanceof HTMLInputElement && node.type === "checkbox";
3
- export const isRadio = (node) => node instanceof HTMLInputElement && node.type === "radio";
@@ -1 +0,0 @@
1
- export declare const getCheckboxChecked: (checkboxValue: string | undefined, newValue: unknown) => boolean | undefined;
@@ -1,9 +0,0 @@
1
- export const getCheckboxChecked = (checkboxValue = "on", newValue) => {
2
- if (Array.isArray(newValue))
3
- return newValue.includes(checkboxValue);
4
- if (typeof newValue === "boolean")
5
- return newValue;
6
- if (typeof newValue === "string")
7
- return newValue === checkboxValue;
8
- return undefined;
9
- };
@@ -1 +0,0 @@
1
- export declare const setFieldValue: (formElement: HTMLFormElement, name: string, value: unknown) => void;
@@ -1,40 +0,0 @@
1
- import invariant from "tiny-invariant";
2
- import { getCheckboxChecked } from "./getCheckboxChecked";
3
- import { getRadioChecked } from "./getRadioChecked";
4
- const setElementValue = (element, value, name) => {
5
- if (element instanceof HTMLSelectElement && element.multiple) {
6
- invariant(Array.isArray(value), "Must specify an array to set the value for a multi-select");
7
- for (const option of element.options) {
8
- option.selected = value.includes(option.value);
9
- }
10
- return;
11
- }
12
- if (element instanceof HTMLInputElement && element.type === "checkbox") {
13
- const newChecked = getCheckboxChecked(element.value, value);
14
- invariant(newChecked !== undefined, `Unable to determine if checkbox should be checked. Provided value was ${value} for checkbox ${name}.`);
15
- element.checked = newChecked;
16
- return;
17
- }
18
- if (element instanceof HTMLInputElement && element.type === "radio") {
19
- const newChecked = getRadioChecked(element.value, value);
20
- invariant(newChecked !== undefined, `Unable to determine if radio should be checked. Provided value was ${value} for radio ${name}.`);
21
- element.checked = newChecked;
22
- return;
23
- }
24
- invariant(typeof value === "string", `Invalid value for field "${name}" which is an ${element.constructor.name}. Expected string but received ${typeof value}`);
25
- const input = element;
26
- input.value = value;
27
- };
28
- export const setFieldValue = (formElement, name, value) => {
29
- const controlElement = formElement.elements.namedItem(name);
30
- if (!controlElement)
31
- return;
32
- if (controlElement instanceof RadioNodeList) {
33
- for (const element of controlElement) {
34
- setElementValue(element, value, name);
35
- }
36
- }
37
- else {
38
- setElementValue(controlElement, value, name);
39
- }
40
- };
@@ -1 +0,0 @@
1
- export declare const setInputValueInForm: (formElement: HTMLFormElement, name: string, value: unknown[]) => void;
@@ -1,77 +0,0 @@
1
- import invariant from "tiny-invariant";
2
- import { isCheckbox, isMultiselect, isRadio } from "./elementUtils";
3
- import { getCheckboxChecked } from "./getCheckboxChecked";
4
- /**
5
- * Helper class to track the values being set on uncontrolled fields.
6
- * HTML is super permissive with inputs that all share the same `name`.
7
- */
8
- class Values {
9
- constructor(values) {
10
- this.hasSetRadioValue = false;
11
- this.remove = (value) => {
12
- const index = this.values.indexOf(value);
13
- const deleted = this.values.splice(index, 1);
14
- return deleted.length > 0;
15
- };
16
- this.bool = (value) => {
17
- if (getCheckboxChecked(value, this.values)) {
18
- this.remove(value) || this.remove(true);
19
- return true;
20
- }
21
- return false;
22
- };
23
- this.radio = (value) => {
24
- if (this.hasSetRadioValue)
25
- return false;
26
- const result = this.bool(value);
27
- if (result)
28
- this.hasSetRadioValue = true;
29
- return result;
30
- };
31
- this.str = () => { var _a; return String((_a = this.values.pop()) !== null && _a !== void 0 ? _a : ""); };
32
- this.allValues = () => this.values;
33
- this.warnIfLeftovers = (field) => {
34
- if (this.values.length > 0) {
35
- console.warn(`Could not determine how to use the value for the field ${field}. ` +
36
- `Leftover values were: ${this.values.join(", ")}.`);
37
- }
38
- };
39
- const unknownValues = Array.isArray(values) ? values : [values];
40
- this.values = unknownValues;
41
- }
42
- }
43
- const setElementValue = (element, values, field) => {
44
- if (isMultiselect(element)) {
45
- for (const option of element.options) {
46
- option.selected = values.bool(option.value);
47
- }
48
- return;
49
- }
50
- if (isCheckbox(element)) {
51
- element.checked = values.bool(element.value);
52
- return;
53
- }
54
- if (isRadio(element)) {
55
- element.checked = values.radio(element.value);
56
- return;
57
- }
58
- const input = element;
59
- invariant(input.type !== "hidden", `Cannot set value on hidden input if it is not a controlled field. Field being updated was ${field}.`);
60
- input.value = values.str();
61
- };
62
- export const setInputValueInForm = (formElement, name, value) => {
63
- const controlElement = formElement.elements.namedItem(name);
64
- if (!controlElement)
65
- return;
66
- const values = new Values(value);
67
- if (controlElement instanceof RadioNodeList) {
68
- for (const element of controlElement) {
69
- setElementValue(element, values, name);
70
- }
71
- values.warnIfLeftovers(name);
72
- }
73
- else {
74
- setElementValue(controlElement, values, name);
75
- values.warnIfLeftovers(name);
76
- }
77
- };
@@ -1,20 +0,0 @@
1
- import { InternalFormId } from "./state/atomUtils";
2
- declare type ControlledDataItem = Record<string, unknown[]>;
3
- declare class ValidatedFormData {
4
- #private;
5
- constructor(formData: FormData, customData: ControlledDataItem);
6
- get: (fieldName: string) => any;
7
- getAll: (fieldName: string) => any[];
8
- has: (fieldName: string) => boolean;
9
- append: (fieldName: string, value: any) => void;
10
- delete: (fieldName: string) => void;
11
- set: (fieldName: string, value: any) => void;
12
- entries: () => IterableIterator<[string, any[]]>;
13
- values: () => IterableIterator<any[]>;
14
- [Symbol.iterator]: () => IterableIterator<[string, any[]]>;
15
- setRepeated: (fieldName: string, value: any[]) => void;
16
- changedFields(): Generator<readonly [string, any[]], void, unknown>;
17
- }
18
- export declare type FormValuesUpdater = (formData: ValidatedFormData) => void;
19
- export declare const useSetFormValues: (formId: InternalFormId) => (arg: FormValuesUpdater) => Promise<void>;
20
- export {};
@@ -1,83 +0,0 @@
1
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
- };
6
- var _ValidatedFormData_data, _ValidatedFormData_updates, _a;
7
- import { useAtomCallback } from "jotai/utils";
8
- import groupBy from "lodash/groupBy";
9
- import mapValues from "lodash/mapValues";
10
- import invariant from "tiny-invariant";
11
- import { setInputValueInForm } from "./logic/setInputValueInForm";
12
- import { MultiValueMap } from "./MultiValueMap";
13
- import { ATOM_SCOPE, formElementAtom } from "./state";
14
- import { controlledFieldsAtom, setControlledFieldValueAtom, } from "./state/controlledFields";
15
- class ValidatedFormData {
16
- constructor(formData, customData) {
17
- _ValidatedFormData_data.set(this, new MultiValueMap());
18
- _ValidatedFormData_updates.set(this, new Map());
19
- // API to mimic form data
20
- this.get = (fieldName) => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").getAll(fieldName)[0];
21
- this.getAll = (fieldName) => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").getAll(fieldName);
22
- this.has = (fieldName) => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").has(fieldName);
23
- this.append = (fieldName, value) => {
24
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").add(fieldName, value);
25
- };
26
- this.delete = (fieldName) => {
27
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").delete(fieldName);
28
- __classPrivateFieldGet(this, _ValidatedFormData_updates, "f").set(fieldName, true);
29
- };
30
- this.set = (fieldName, value) => {
31
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").delete(fieldName);
32
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").add(fieldName, value);
33
- __classPrivateFieldGet(this, _ValidatedFormData_updates, "f").set(fieldName, true);
34
- };
35
- this.entries = () => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").entries();
36
- this.values = () => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").values();
37
- this[_a] = () => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").entries();
38
- // Custom APIs
39
- this.setRepeated = (fieldName, value) => {
40
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").delete(fieldName);
41
- value.forEach((val) => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").add(fieldName, val));
42
- __classPrivateFieldGet(this, _ValidatedFormData_updates, "f").set(fieldName, true);
43
- };
44
- for (const [key, value] of formData.entries()) {
45
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").add(key, value);
46
- }
47
- Object.entries(customData).forEach(([name, values]) => {
48
- __classPrivateFieldGet(this, _ValidatedFormData_data, "f").delete(name);
49
- values.forEach((value) => __classPrivateFieldGet(this, _ValidatedFormData_data, "f").add(name, value));
50
- });
51
- }
52
- *changedFields() {
53
- for (const updatedField of __classPrivateFieldGet(this, _ValidatedFormData_updates, "f").keys()) {
54
- const value = this.getAll(updatedField);
55
- yield [updatedField, value];
56
- }
57
- }
58
- }
59
- _ValidatedFormData_data = new WeakMap(), _ValidatedFormData_updates = new WeakMap(), _a = Symbol.iterator;
60
- export const useSetFormValues = (formId) => useAtomCallback(async (get, set, update) => {
61
- var _b;
62
- const form = get(formElementAtom(formId));
63
- invariant(form, "Unable to access form element when setting field value. This is likely a bug in remix-validated-form.");
64
- const formData = new FormData(form);
65
- const controlledFields = get(controlledFieldsAtom(formId));
66
- const controlledData = mapValues(groupBy(controlledFields, (field) => field.name), (val) => val.map((field) => get(field.valueAtom)));
67
- const validatedFormData = new ValidatedFormData(formData, controlledData);
68
- update(validatedFormData);
69
- for (const [field, value] of validatedFormData.changedFields()) {
70
- const relevantFields = controlledFields.filter(({ name }) => name === field);
71
- if (relevantFields.length === 0) {
72
- setInputValueInForm(form, field, value);
73
- return;
74
- }
75
- for (const [index, field] of relevantFields.entries()) {
76
- const itemValue = (_b = value[index]) !== null && _b !== void 0 ? _b : "";
77
- await set(setControlledFieldValueAtom, {
78
- internalFieldId: field.internalId,
79
- value: itemValue,
80
- });
81
- }
82
- }
83
- }, ATOM_SCOPE);
@@ -1,2 +0,0 @@
1
- import { InternalFormId } from "./state/atomUtils";
2
- export declare const useSetFormValues: (formId: InternalFormId) => (arg: Record<string, unknown>) => Promise<void>;
@@ -1,26 +0,0 @@
1
- import { useAtomCallback } from "jotai/utils";
2
- import { useCallback } from "react";
3
- import invariant from "tiny-invariant";
4
- import { setInputValueInForm } from "./logic/setInputValueInForm";
5
- import { ATOM_SCOPE, formElementAtom } from "./state";
6
- import { controlledFieldsAtom, setControlledFieldValueAtom, } from "./state/controlledFields";
7
- export const useSetFormValues = (formId) => useAtomCallback(useCallback(async (get, set, updatedValues) => {
8
- const form = get(formElementAtom(formId));
9
- invariant(form, "Unable to access form element when setting field value. This is likely a bug in remix-validated-form.");
10
- const controlledFields = get(controlledFieldsAtom(formId));
11
- const updatePromises = [];
12
- for (const [field, value] of Object.entries(updatedValues)) {
13
- const isControlled = !!controlledFields[field];
14
- if (isControlled) {
15
- updatePromises.push(set(setControlledFieldValueAtom, {
16
- field,
17
- formId,
18
- value,
19
- }));
20
- }
21
- else {
22
- setInputValueInForm(form, field, Array.isArray(value) ? value : [value]);
23
- }
24
- }
25
- await Promise.all(updatePromises);
26
- }, [formId]), ATOM_SCOPE);
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,62 +0,0 @@
1
- import { FieldErrors, TouchedFields } from "..";
2
- export declare type InternalFormState = {
3
- hydrated: boolean;
4
- fieldErrors: FieldErrors;
5
- isSubmitting: boolean;
6
- hasBeenSubmitted: boolean;
7
- touchedFields: TouchedFields;
8
- action?: string;
9
- subaction?: string;
10
- defaultValues: {
11
- [fieldName: string]: any;
12
- };
13
- validateField: (fieldName: string) => Promise<string | null>;
14
- registerReceiveFocus: (fieldName: string, handler: () => void) => () => void;
15
- setFieldValue: (fieldName: string, value: unknown) => void;
16
- };
17
- declare type SyncFormArgs = {
18
- defaultValues?: {
19
- [fieldName: string]: any;
20
- };
21
- action?: string;
22
- subaction?: string;
23
- validateField: InternalFormState["validateField"];
24
- registerReceiveFocus: InternalFormState["registerReceiveFocus"];
25
- setFieldValueForForm: InternalFormState["setFieldValue"];
26
- };
27
- declare type StoreState = {
28
- forms: {
29
- [formId: string | symbol]: InternalFormState;
30
- };
31
- };
32
- export declare const state: StoreState;
33
- export declare const registerFormSlice: (formId: string | symbol, { registerReceiveFocus, setFieldValueForForm, validateField, action, defaultValues, subaction, }: SyncFormArgs) => void;
34
- export declare const unregisterFormSlice: (formId: string | symbol) => void;
35
- export declare const useFormData: (formId: string | symbol) => {
36
- readonly hydrated: boolean;
37
- readonly fieldErrors: {
38
- readonly [x: string]: string;
39
- };
40
- readonly isSubmitting: boolean;
41
- readonly hasBeenSubmitted: boolean;
42
- readonly touchedFields: {
43
- readonly [x: string]: boolean;
44
- };
45
- readonly action?: string | undefined;
46
- readonly subaction?: string | undefined;
47
- readonly defaultValues: {
48
- readonly [x: string]: any;
49
- };
50
- readonly validateField: (fieldName: string) => Promise<string | null>;
51
- readonly registerReceiveFocus: (fieldName: string, handler: () => void) => () => void;
52
- readonly setFieldValue: (fieldName: string, value: unknown) => void;
53
- };
54
- export declare const startSubmit: (formId: string | symbol) => void;
55
- export declare const endSubmit: (formId: string | symbol) => void;
56
- export declare const sync: (formId: string | symbol, { defaultValues, action, subaction, registerReceiveFocus, validateField, setFieldValueForForm, }: SyncFormArgs) => void;
57
- export declare const clearError: (formId: string | symbol, fieldName: string) => void;
58
- export declare const addError: (formId: string | symbol, fieldName: string, error: string) => void;
59
- export declare const setTouched: (formId: string | symbol, fieldName: string, touched: boolean) => void;
60
- export declare const reset: (formId: string | symbol) => void;
61
- export declare const setFieldErrors: (formId: string | symbol, fieldErrors: FieldErrors) => void;
62
- export {};