-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathForm.tsx
More file actions
230 lines (201 loc) · 6.48 KB
/
Form.tsx
File metadata and controls
230 lines (201 loc) · 6.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
import * as React from 'react';
import type {
Store,
FormInstance,
FieldData,
ValidateMessages,
Callbacks,
InternalFormInstance,
FormRef,
} from './interface';
import useForm from './useForm';
import FieldContext, { HOOK_MARK } from './FieldContext';
import type { FormContextProps } from './FormContext';
import FormContext from './FormContext';
import { isSimilar } from './utils/valueUtil';
import ListContext from './ListContext';
import type { BatchTask, BatchUpdateRef } from './BatchUpdate';
import BatchUpdate from './BatchUpdate';
type BaseFormProps = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit' | 'children'>;
type RenderProps = (values: Store, form: FormInstance) => React.ReactNode;
export interface FormProps<Values = any> extends BaseFormProps {
initialValues?: Store;
form?: FormInstance<Values>;
children?: RenderProps | React.ReactNode;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
component?: false | string | React.FC<any> | React.ComponentClass<any>;
fields?: FieldData[];
name?: string;
validateMessages?: ValidateMessages;
onValuesChange?: Callbacks<Values>['onValuesChange'];
onFieldsChange?: Callbacks<Values>['onFieldsChange'];
onFinish?: Callbacks<Values>['onFinish'];
onFinishFailed?: Callbacks<Values>['onFinishFailed'];
validateTrigger?: string | string[] | false;
preserve?: boolean;
clearOnDestroy?: boolean;
}
const Form: React.ForwardRefRenderFunction<FormRef, FormProps> = (
{
name,
initialValues,
fields,
form,
preserve,
children,
component: Component = 'form',
validateMessages,
validateTrigger = 'onChange',
onValuesChange,
onFieldsChange,
onFinish,
onFinishFailed,
clearOnDestroy,
...restProps
}: FormProps,
ref,
) => {
const nativeElementRef = React.useRef<HTMLFormElement>(null);
const formContext: FormContextProps = React.useContext(FormContext);
// We customize handle event since Context will makes all the consumer re-render:
// https://reactjs.org/docs/context.html#contextprovider
const [formInstance] = useForm(form);
const {
useSubscribe,
setInitialValues,
setCallbacks,
setValidateMessages,
setPreserve,
destroyForm,
setBatchUpdate,
} = (formInstance as InternalFormInstance).getInternalHooks(HOOK_MARK);
// Pass ref with form instance
React.useImperativeHandle(ref, () => ({
...formInstance,
nativeElement: nativeElementRef.current,
}));
// Register form into Context
React.useEffect(() => {
formContext.registerForm(name, formInstance);
return () => {
formContext.unregisterForm(name);
};
}, [formContext, formInstance, name]);
// Pass props to store
setValidateMessages({
...formContext.validateMessages,
...validateMessages,
});
setCallbacks({
onValuesChange,
onFieldsChange: (changedFields: FieldData[], ...rest) => {
formContext.triggerFormChange(name, changedFields);
if (onFieldsChange) {
onFieldsChange(changedFields, ...rest);
}
},
onFinish: (values: Store) => {
formContext.triggerFormFinish(name, values);
if (onFinish) {
onFinish(values);
}
},
onFinishFailed,
});
setPreserve(preserve);
// Set initial value, init store value when first mount
const mountRef = React.useRef(null);
setInitialValues(initialValues, !mountRef.current);
if (!mountRef.current) {
mountRef.current = true;
}
// ======================== Batch Update ========================
// zombieJ:
// To avoid Form self re-render,
// We create a sub component `BatchUpdate` to handle batch update logic.
// When the call with do not change immediate, we will batch the update
// and flush it in `useLayoutEffect` for next tick.
// Set batch update ref
const batchUpdateRef = React.useRef<BatchUpdateRef>(null);
const batchUpdateTasksRef = React.useRef<[key: string, fn: VoidFunction][]>([]);
const tryFlushBatch = () => {
if (batchUpdateRef.current) {
batchUpdateTasksRef.current.forEach(([key, fn]) => {
batchUpdateRef.current.batch(key, fn);
});
batchUpdateTasksRef.current = [];
}
};
// Ref update
const setBatchUpdateRef = React.useCallback((batchUpdate: BatchUpdateRef | null) => {
batchUpdateRef.current = batchUpdate;
tryFlushBatch();
}, []);
// Task list
const batchUpdate: BatchTask = (key, callback) => {
batchUpdateTasksRef.current.push([key, callback]);
tryFlushBatch();
};
setBatchUpdate(batchUpdate);
// ========================== Unmount ===========================
React.useEffect(
() => () => destroyForm(clearOnDestroy),
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
// Prepare children by `children` type
let childrenNode: React.ReactNode;
const childrenRenderProps = typeof children === 'function';
if (childrenRenderProps) {
const values = formInstance.getFieldsValue(true);
childrenNode = (children as RenderProps)(values, formInstance);
} else {
childrenNode = children;
}
// Not use subscribe when using render props
useSubscribe(!childrenRenderProps);
// Listen if fields provided. We use ref to save prev data here to avoid additional render
const prevFieldsRef = React.useRef<FieldData[] | undefined>(null);
React.useEffect(() => {
if (!isSimilar(prevFieldsRef.current || [], fields || [])) {
formInstance.setFields(fields || []);
}
prevFieldsRef.current = fields;
}, [fields, formInstance]);
// =========================== Render ===========================
const formContextValue = React.useMemo<InternalFormInstance>(
() => ({
...(formInstance as InternalFormInstance),
validateTrigger,
}),
[formInstance, validateTrigger],
);
const wrapperNode = (
<ListContext.Provider value={null}>
<FieldContext.Provider value={formContextValue}>{childrenNode}</FieldContext.Provider>
<BatchUpdate ref={setBatchUpdateRef} />
</ListContext.Provider>
);
if (Component === false) {
return wrapperNode;
}
return (
<Component
{...restProps}
ref={nativeElementRef}
onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
event.stopPropagation();
formInstance.submit();
}}
onReset={(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
formInstance.resetFields();
restProps.onReset?.(event);
}}
>
{wrapperNode}
</Component>
);
};
export default Form;