-
-
Notifications
You must be signed in to change notification settings - Fork 267
/
Form.tsx
189 lines (167 loc) · 5.11 KB
/
Form.tsx
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
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';
type BaseFormProps = Omit<React.FormHTMLAttributes<HTMLFormElement>, 'onSubmit' | 'children'>;
type RenderProps = (values: Store, form: FormInstance) => JSX.Element | 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,
} = (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;
}
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>();
React.useEffect(() => {
if (!isSimilar(prevFieldsRef.current || [], fields || [])) {
formInstance.setFields(fields || []);
}
prevFieldsRef.current = fields;
}, [fields, formInstance]);
const formContextValue = React.useMemo(
() => ({
...(formInstance as InternalFormInstance),
validateTrigger,
}),
[formInstance, validateTrigger],
);
const wrapperNode = (
<ListContext.Provider value={null}>
<FieldContext.Provider value={formContextValue}>{childrenNode}</FieldContext.Provider>
</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;