react-form-manage 1.0.5 → 1.0.6-beta.1

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 (60) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/components/Form/FormCleanUp.d.ts +2 -0
  3. package/dist/components/Form/FormCleanUp.js +46 -0
  4. package/dist/components/Form/FormItem.d.ts +18 -0
  5. package/dist/components/Form/FormItem.js +46 -0
  6. package/dist/components/Form/FormList.d.ts +8 -0
  7. package/dist/components/Form/FormList.js +11 -0
  8. package/dist/components/Form/InputWrapper.d.ts +6 -0
  9. package/dist/components/Form/InputWrapper.js +7 -0
  10. package/dist/components/Input.d.ts +5 -0
  11. package/dist/components/Input.js +8 -0
  12. package/dist/constants/validation.d.ts +31 -0
  13. package/dist/constants/validation.js +33 -0
  14. package/dist/contexts/FormContext.d.ts +2 -0
  15. package/dist/contexts/FormContext.js +2 -0
  16. package/dist/hooks/useFormItemControl.d.ts +22 -0
  17. package/dist/hooks/useFormItemControl.js +390 -0
  18. package/dist/hooks/useFormListControl.d.ts +26 -0
  19. package/dist/hooks/useFormListControl.js +280 -0
  20. package/dist/index.d.ts +8 -134
  21. package/dist/index.js +9 -0
  22. package/dist/providers/Form.d.ts +28 -0
  23. package/dist/providers/Form.js +322 -0
  24. package/dist/stores/formStore.d.ts +25 -0
  25. package/dist/stores/formStore.js +304 -0
  26. package/dist/types/index.d.ts +1 -0
  27. package/dist/types/index.js +1 -0
  28. package/dist/types/public.d.ts +51 -0
  29. package/dist/types/public.js +1 -0
  30. package/dist/utils/obj.util.d.ts +2 -0
  31. package/dist/utils/obj.util.js +24 -0
  32. package/package.json +30 -47
  33. package/src/App.css +49 -0
  34. package/src/App.tsx +36 -0
  35. package/src/assets/react.svg +1 -0
  36. package/src/components/Form/FormCleanUp.tsx +57 -0
  37. package/src/components/Form/FormItem.tsx +60 -0
  38. package/src/components/Form/FormList.tsx +13 -0
  39. package/src/components/Form/InputWrapper.tsx +17 -0
  40. package/src/components/Input.jsx +13 -0
  41. package/src/components/Input.tsx +21 -0
  42. package/src/constants/validation.ts +63 -0
  43. package/src/contexts/FormContext.ts +3 -0
  44. package/src/hooks/useFormItemControl.ts +558 -0
  45. package/src/hooks/useFormListControl.ts +378 -0
  46. package/src/index.css +68 -0
  47. package/src/index.ts +30 -0
  48. package/src/main.tsx +10 -0
  49. package/src/providers/Form.tsx +429 -0
  50. package/src/stores/formStore.ts +477 -0
  51. package/src/types/index.ts +1 -0
  52. package/src/types/public.ts +50 -0
  53. package/src/utils/obj.util.ts +42 -0
  54. package/dist/index.cjs +0 -1937
  55. package/dist/index.cjs.d.ts +0 -1
  56. package/dist/index.cjs.map +0 -1
  57. package/dist/index.esm.d.ts +0 -1
  58. package/dist/index.esm.js +0 -1926
  59. package/dist/index.esm.js.map +0 -1
  60. package/src/types/components.d.ts +0 -135
@@ -0,0 +1,429 @@
1
+ import { cloneDeep, get, isEqual, last, set, uniq } from "lodash";
2
+ import { useTask } from "minh-custom-hooks-release";
3
+ import { createContext, useContext, useEffect, useState } from "react";
4
+ import { flushSync } from "react-dom";
5
+ import { useShallow } from "zustand/react/shallow"; // Import useShallow
6
+ import FormCleanUp from "../components/Form/FormCleanUp";
7
+ import { useFormListeners, useFormStore } from "../stores/formStore";
8
+ import type { PublicFormInstance } from "../types/public";
9
+ import { getAllNoneObjStringPath } from "../utils/obj.util";
10
+
11
+ export const FormContext = createContext(null);
12
+
13
+ export default function Form({
14
+ children,
15
+ formName,
16
+ initialValues,
17
+ onFinish,
18
+ onReject,
19
+ onFinally,
20
+ FormElement,
21
+ ...props
22
+ }) {
23
+ const {
24
+ getFormItemValue,
25
+ setInitData,
26
+ setData,
27
+ getFormValues,
28
+ setFormState,
29
+ setFormInstance,
30
+ revokeFormInstance,
31
+ setSubmitHistory,
32
+ clearFormValues,
33
+ clearFormInitialValues,
34
+ clearFormState,
35
+ } = useFormStore(
36
+ useShallow((state) => ({
37
+ setInitData: state.setFormInitData,
38
+ getFormValues: state.getFormValues,
39
+ setFormState: state.setFormState,
40
+ setFormInstance: state.setFormInstance,
41
+ revokeFormInstance: state.revokeFormInstance,
42
+ setData: state.setData,
43
+ setSubmitHistory: state.setSubmitHistory,
44
+ getFormItemValue: state.getFormItemValue,
45
+ clearFormValues: state.clearFormValues,
46
+ clearFormInitialValues: state.clearFormInitialValues,
47
+ clearFormState: state.clearFormState,
48
+
49
+ // Test, nhớ xóa sau khi xong
50
+ formStates: state.formStates?.[formName],
51
+ })),
52
+ );
53
+
54
+ const { getListeners } = useFormListeners(
55
+ useShallow((state) => {
56
+ return {
57
+ getListeners: state.getListeners,
58
+ };
59
+ }),
60
+ );
61
+
62
+ const setFieldValue = (name, value, options) => {
63
+ const listener = getListeners().find(
64
+ (l) => l.name === name && l.formName === formName,
65
+ );
66
+ if (listener) {
67
+ listener.onChange(value, options);
68
+ } else {
69
+ setData(formName, name, value);
70
+ }
71
+ };
72
+
73
+ const setFieldValues = (values, options = { notTriggerDirty: false }) => {
74
+ const allStringPath = getAllNoneObjStringPath(values);
75
+
76
+ allStringPath.forEach((p) => {
77
+ const listener = getListeners().find(
78
+ (l) => l.name === p && l.formName === formName,
79
+ );
80
+ if (listener) {
81
+ listener.onChange(get(values, listener.name), options);
82
+ } else {
83
+ setData(formName, p, get(values, p));
84
+ }
85
+ });
86
+ };
87
+
88
+ const getFieldValue = (name) => {
89
+ return getFormItemValue(formName, name);
90
+ };
91
+
92
+ const getFieldValues = (names = []) => {
93
+ return names.map((name) => ({
94
+ name,
95
+ value: getFormItemValue(formName, name),
96
+ }));
97
+ };
98
+
99
+ const setFieldFocus = (name) => {
100
+ const listener = getListeners().find(
101
+ (l) => l.name === name && l.formName === formName,
102
+ );
103
+ if (listener && typeof listener.emitFocus === "function") {
104
+ listener.emitFocus();
105
+ }
106
+ };
107
+
108
+ const getFieldErrors = (names) => {
109
+ const listeners = getListeners().filter(
110
+ (l) => names.includes(l.name) && l.formName === formName,
111
+ );
112
+ return listeners.map((l) => ({
113
+ name: l.name,
114
+ errors: l.internalErrors || [],
115
+ }));
116
+ };
117
+
118
+ const getAllFieldErrors = () => {
119
+ return getListeners()
120
+ ?.filter((l) => {
121
+ return l.internalErrors?.length && l.formName === formName;
122
+ })
123
+ .map((l) => ({
124
+ name: l.name,
125
+ formName: l.formName,
126
+ formItemId: l.formItemId,
127
+ errors: l.internalErrors,
128
+ }));
129
+ };
130
+
131
+ // Submit data
132
+ const {
133
+ run: runSubmit,
134
+ runAsync: runSubmitAsync,
135
+ state: _,
136
+ reset,
137
+ } = useTask({
138
+ async task(props) {
139
+ try {
140
+ flushSync(setFormState({ formName, submitState: "submitting" }));
141
+ const errorFields = getAllFieldErrors();
142
+ const listeners = getListeners().filter((l) => l.formName === formName);
143
+ const formValues = getFormValues(formName);
144
+
145
+ const resultValues = cloneDeep(formValues);
146
+ const cleanValues = {};
147
+ uniq(listeners, (l) => l.name).forEach((l) => {
148
+ set(cleanValues, l.name, get(resultValues, l.name));
149
+ });
150
+
151
+ const handleIsolateCase = async () => {
152
+ if (!errorFields?.length) {
153
+ if (typeof props?.externalFinishCallback !== "function") {
154
+ onFinish && (await onFinish(cleanValues, resultValues));
155
+ } else {
156
+ if (props?.callBothFinish) {
157
+ onFinish && (await onFinish(cleanValues, resultValues));
158
+ await props?.externalFinishCallback(cleanValues, resultValues);
159
+ } else {
160
+ await props?.externalFinishCallback(cleanValues, resultValues);
161
+ }
162
+ }
163
+
164
+ // if (!isEqual(cleanValues, last(getSubmitHistory(formName)))) {
165
+ // setSubmitHistory(formName, cleanValues);
166
+ // }
167
+
168
+ setSubmitHistory(formName, cleanValues);
169
+
170
+ // if (
171
+ // !isEqual(
172
+ // resultValues,
173
+ // last(submitHistoryWithUnRegisteredValues.current)
174
+ // )
175
+ // ) {
176
+ // submitHistoryWithUnRegisteredValues.current = [
177
+ // ...submitHistoryWithUnRegisteredValues.current,
178
+ // resultValues,
179
+ // ].slice(-10, 10);
180
+ // }
181
+
182
+ // resultWatchQueue.current.forEach((l) => {
183
+ // l.emitSubmitTrigger(cleanValues);
184
+ // l.emitDataChange(cleanValues);
185
+ // l.emitDataWithUnRegisteredValuesChange(resultValues);
186
+ // l.emitSubmitTriggerWithUnRegisteredValues(resultValues);
187
+ // });
188
+ } else {
189
+ if (typeof props?.externalRejectCallback !== "function") {
190
+ onReject && (await onReject(errorFields));
191
+ } else {
192
+ if (props?.callBothReject) {
193
+ onReject && (await onReject(errorFields));
194
+ await props?.externalRejectCallback(errorFields);
195
+ } else {
196
+ await props?.externalRejectCallback(errorFields);
197
+ }
198
+ }
199
+ }
200
+ };
201
+
202
+ const handleFinallyCase = async () => {
203
+ if (typeof props?.externalFinallyCallback !== "function") {
204
+ onFinally &&
205
+ (await onFinally({
206
+ errorsField: errorFields,
207
+ values: cleanValues,
208
+ withUnRegisteredValues: resultValues,
209
+ }));
210
+ } else {
211
+ if (props?.callBothFinally) {
212
+ onFinally &&
213
+ (await onFinally({
214
+ errorsField: errorFields,
215
+ values: cleanValues,
216
+ withUnRegisteredValues: resultValues,
217
+ }));
218
+ await props?.externalFinallyCallback({
219
+ errorsField: errorFields,
220
+ values: cleanValues,
221
+ withUnRegisteredValues: resultValues,
222
+ });
223
+ } else {
224
+ await props?.externalFinallyCallback({
225
+ errorsField: errorFields,
226
+ values: cleanValues,
227
+ withUnRegisteredValues: resultValues,
228
+ });
229
+ }
230
+ }
231
+ };
232
+
233
+ await Promise.allSettled([handleIsolateCase(), handleFinallyCase()]);
234
+
235
+ if (errorFields?.length) {
236
+ setFormState({ formName, submitState: "rejected" });
237
+ } else {
238
+ setFormState({ formName, submitState: "submitted" });
239
+ }
240
+ } catch (error) {
241
+ console.error("Error in form submit: ", error);
242
+ setFormState({ formName, submitState: "rejected" });
243
+ }
244
+ },
245
+ });
246
+
247
+ const resetFields = (resetOptions) => {
248
+ reset();
249
+ flushSync(
250
+ setFormState({
251
+ formName,
252
+ isInitied: false,
253
+ }),
254
+ );
255
+ const totalListenerFields = getListeners();
256
+ if (Array.isArray(resetOptions)) {
257
+ totalListenerFields.forEach((l) => {
258
+ const findListenerByName = resetOptions.find((o) => o.name === l.name);
259
+
260
+ if (findListenerByName) {
261
+ l.onReset(findListenerByName?.value);
262
+ }
263
+ });
264
+
265
+ totalListenerFields
266
+ .filter((l) => resetOptions.find((o) => o.name !== l.name))
267
+ .forEach((l) => {
268
+ l?.onReset?.();
269
+ });
270
+ } else if (typeof resetOptions === "object") {
271
+ const allStringPath = getAllNoneObjStringPath(resetOptions);
272
+ allStringPath.forEach((p) => {
273
+ const listener = totalListenerFields.find(
274
+ (l) => l.name === p && l.formName === formName,
275
+ );
276
+ if (listener) {
277
+ listener.onChange(get(resetOptions, listener.name));
278
+ } else {
279
+ setData(formName, p, get(resetOptions, p));
280
+ }
281
+ });
282
+ } else {
283
+ totalListenerFields.forEach((l) => {
284
+ l?.onReset?.();
285
+ });
286
+ }
287
+
288
+ setFormState({
289
+ formName,
290
+ isInitied: true,
291
+ });
292
+ };
293
+
294
+ useEffect(() => {
295
+ setInitData(formName, initialValues);
296
+ setFormState({
297
+ formName,
298
+ isInitied: true,
299
+ submitState: "idle",
300
+ });
301
+ setFormInstance({
302
+ formName,
303
+ resetFields,
304
+ submit: runSubmit,
305
+ submitAsync: runSubmitAsync,
306
+ setFieldValue,
307
+ setFieldValues,
308
+ getFieldValue,
309
+ getFieldValues,
310
+ setFieldFocus,
311
+ getFieldErrors,
312
+ });
313
+
314
+ return () => {
315
+ revokeFormInstance({ formName });
316
+ clearFormInitialValues(formName);
317
+ clearFormValues(formName);
318
+ clearFormState(formName);
319
+ };
320
+ }, []);
321
+
322
+ return (
323
+ <FormContext.Provider
324
+ value={{
325
+ formName,
326
+ }}
327
+ >
328
+ {FormElement ? (
329
+ <FormElement
330
+ onSubmit={(e) => {
331
+ e.preventDefault();
332
+ e.stopPropagation();
333
+
334
+ runSubmit(undefined as any);
335
+ }}
336
+ {...props}
337
+ >
338
+ {children}
339
+ </FormElement>
340
+ ) : (
341
+ <form
342
+ onSubmit={(e) => {
343
+ e.preventDefault();
344
+ e.stopPropagation();
345
+
346
+ runSubmit(undefined as any);
347
+ }}
348
+ {...props}
349
+ >
350
+ {children}
351
+ </form>
352
+ )}
353
+ <FormCleanUp />
354
+ </FormContext.Provider>
355
+ );
356
+ }
357
+
358
+ export function useFormContext() {
359
+ const c = useContext(FormContext);
360
+
361
+ if (!c) throw new Error("Must be use inside FormProvider");
362
+
363
+ return c;
364
+ }
365
+
366
+ export function useForm<T = any>(formNameOrFormInstance?: string | PublicFormInstance<T>) {
367
+ const targetFormName =
368
+ typeof formNameOrFormInstance === "object" && formNameOrFormInstance !== null
369
+ ? (formNameOrFormInstance as PublicFormInstance<T>).formName
370
+ : (formNameOrFormInstance as string | undefined);
371
+
372
+ const formInstance = useFormStore((state) => {
373
+ return state.formInstances.find((i) => i.formName === targetFormName);
374
+ }) as PublicFormInstance<T> | undefined;
375
+
376
+ return [formInstance];
377
+ }
378
+
379
+ export function useWatch<T = any>(name: keyof T & string, formNameOrFormInstance?: string | PublicFormInstance<T>) {
380
+ const [formInstance] = useForm<T>(formNameOrFormInstance as any);
381
+
382
+ const value = useFormStore((state) => {
383
+ return state.getFormItemValue(
384
+ formInstance?.formName ?? (formNameOrFormInstance as any),
385
+ name as string,
386
+ );
387
+ });
388
+
389
+ return value as T[keyof T] | undefined;
390
+ }
391
+
392
+ export function useSubmitDataWatch<T = any>({
393
+ formNameOrFormInstance,
394
+ triggerWhenChange = false,
395
+ mapFn,
396
+ }: { formNameOrFormInstance?: string | PublicFormInstance<T>; triggerWhenChange?: boolean; mapFn?: (v: any, prev: any) => any } ) {
397
+ const [formInstance] = useForm<T>(formNameOrFormInstance as any);
398
+
399
+ const value = useFormStore((state) => {
400
+ return last(get(state.submitHistory, formInstance?.formName));
401
+ });
402
+
403
+ const [submitData, setSubmitData] = useState(
404
+ mapFn ? mapFn(value, null) : value,
405
+ );
406
+
407
+ useEffect(() => {
408
+ if (!triggerWhenChange || !isEqual(submitData, value)) {
409
+ setSubmitData(mapFn ? mapFn(value, submitData) : value);
410
+ }
411
+ }, [value, triggerWhenChange]);
412
+
413
+ return submitData as T | undefined;
414
+ }
415
+
416
+ export const useFormStateWatch = <T = any>(formNameOrFormInstance?: string | PublicFormInstance<T>) => {
417
+ const [formInstance] = useForm<T>(formNameOrFormInstance as any);
418
+
419
+ const formState = useFormStore((state) => {
420
+ return state.formStates?.[formInstance?.formName];
421
+ });
422
+
423
+ return formState as any;
424
+ };
425
+
426
+ Form.useForm = useForm;
427
+ Form.useWatch = useWatch;
428
+ Form.useSubmitDataWatch = useSubmitDataWatch;
429
+ Form.useFormStateWatch = useFormStateWatch;