-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Form.tsx
176 lines (154 loc) · 5.26 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
import * as React from 'react';
import { emit } from './context/emitter';
import { deriveInitial } from './helpers/deriveInitial';
import { deriveKeys } from './helpers/deriveKeys';
import useState from './helpers/useState';
import { Errors, FormHookContext, InitialValues, Touched } from './types';
export const formContext = React.createContext<FormHookContext>(null as any, () => 0);
export interface SuccessBag {
resetForm: () => void;
}
export interface ErrorBag {
setErrors: (errors: Errors) => void;
setFormError: (error: string) => void;
}
export interface CallBag {
props?: object;
setErrors: (errors: Errors) => void;
setFormError: (error: string) => void;
}
export interface FormOptions<T> {
children?: any;
enableReinitialize?: boolean;
initialValues?: InitialValues;
mapPropsToValues?: (props: object) => InitialValues;
noForm?: boolean;
onError?: (error: object, callbag: ErrorBag) => void;
onSuccess?: (result: any, callbag: SuccessBag) => void;
onSubmit: (values: Partial<T>, callbag: CallBag) => Promise<any> | any;
shouldSubmitWhenInvalid?: boolean;
validate?: (values: Partial<T>) => object;
validateOnBlur?: boolean;
validateOnChange?: boolean;
}
export const EMPTY_OBJ = {};
const Form = <Values extends object>({
children,
enableReinitialize,
initialValues,
onSubmit,
noForm,
validate,
onError,
onSuccess,
shouldSubmitWhenInvalid,
validateOnBlur,
validateOnChange,
...formProps // used to inject className, onKeyDown and related on the <form>
}: FormOptions<Values>) => {
const { 0: values, 1: setFieldValue, 2: setValuesState } = useState(initialValues || EMPTY_OBJ);
const { 0: touched, 1: touch, 2: setTouchedState } = useState(EMPTY_OBJ);
const { 0: formErrors, 2: setErrorState } = useState(EMPTY_OBJ);
const { 0: isSubmitting, 1: setSubmitting } = React.useState(false);
const { 0: formError, 1: setFormError } = React.useState();
const isDirty = React.useRef(false);
// The validation step in our form, this memoization happens on values and touched.
const validateForm = React.useCallback(() => {
const validationErrors = validate ? validate(values) : EMPTY_OBJ;
setErrorState(validationErrors);
emit(deriveKeys(Object.assign({}, validationErrors, formErrors)));
return validationErrors;
}, [values]);
// Provide a way to reset the full form to the initialValues.
const resetForm = React.useCallback(() => {
isDirty.current = false;
emit(deriveKeys(Object.assign({}, initialValues, values)));
setValuesState(initialValues || EMPTY_OBJ);
setTouchedState(EMPTY_OBJ);
setErrorState(EMPTY_OBJ);
}, [initialValues]);
const handleSubmit = React.useCallback(
async (event?: React.FormEvent<HTMLFormElement>) => {
if (event && event.preventDefault) event.preventDefault();
const errors = validateForm();
setTouchedState(deriveInitial(errors, true));
if (!shouldSubmitWhenInvalid && Object.keys(errors).length > 0) {
setSubmitting(false);
return emit('submitting');
}
const setFormErr = (err: string) => {
setFormError(err);
emit('formError');
};
return new Promise(resolve => resolve(
onSubmit(values, { setErrors: setErrorState, setFormError: setFormErr })))
.then((result: any) => {
setSubmitting(false);
emit('submitting');
if (onSuccess) onSuccess(result, { resetForm });
})
.catch((e: any) => {
setSubmitting(false);
emit('submitting');
if (onError) onError(e, { setErrors: setErrorState, setFormError: setFormErr });
});
},
[values],
);
React.useEffect(() => {
if (isSubmitting) handleSubmit();
}, [isSubmitting]);
// Make our listener for the reinitialization when need be.
React.useEffect(() => {
if (enableReinitialize) resetForm();
}, [initialValues]);
// Run validations when needed.
React.useEffect(() => {
validateForm();
}, [validateOnBlur && touched, validateOnChange && values]);
// The onChange we can use for our Fields,
// should also be renewed context wise when our touched are altered.
const onChange = React.useCallback((fieldId: string, value: any) => {
isDirty.current = true;
setFieldValue(fieldId, value);
emit(fieldId);
}, []);
const submit = React.useCallback((e?: React.SyntheticEvent) => {
if (e && e.preventDefault) e.preventDefault();
setSubmitting(() => true);
emit('submitting');
}, []);
const providerValue = React.useMemo(
() => ({
errors: formErrors as Errors,
formError,
isDirty: isDirty.current,
isSubmitting,
resetForm,
setFieldTouched: (fieldId: string, value?: boolean) => {
emit(fieldId);
touch(fieldId, value == null ? true : value);
},
setFieldValue: onChange,
submit,
touched: touched as Touched,
validate: validateForm,
values,
}),
[
formErrors, formError, onChange, touched,
validateForm, values, resetForm, isSubmitting,
],
);
return (
<formContext.Provider value={providerValue}>
{noForm ?
children :
<form onSubmit={submit} {...formProps}>
{children}
</form>
}
</formContext.Provider>
);
};
export default Form;