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