-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathuseForm.ts
634 lines (558 loc) · 16.7 KB
/
useForm.ts
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
import deepmerge from 'deepmerge';
import isEqual from 'fast-deep-equal/es6';
import { klona as deepClone } from 'klona/full';
import { computed, onMounted, provide, reactive, ref, unref } from 'vue';
import { FormContextKey } from './useFormContext';
import useFormStore from './useFormStore';
import { InternalContextKey } from './useInternalContext';
import get from '../utils/get';
import isFunction from '../utils/isFunction';
import isPromise from '../utils/isPromise';
import isString from '../utils/isString';
import keysOf from '../utils/keysOf';
import set from '../utils/set';
import type { Reducer } from './useFormStore';
import type {
FieldAttrs,
FieldMeta,
FormErrors,
FormEventHandler,
FormResetState,
FormState,
FormTouched,
FormValues,
MaybeRef,
ResetForm,
SetFieldArrayValue,
UseFormRegister,
UseFormReturn,
ValidateField,
} from '../types';
interface FieldRegistry {
[field: string]: {
validate: (value: any) => string | Promise<string> | boolean | undefined;
};
}
interface FieldArrayRegistry {
[field: string]: {
reset: () => void;
};
}
export interface FormSubmitHelper<Values extends FormValues> {
setSubmitting: (isSubmitting: boolean) => void;
readonly initialValues: Values;
}
export type ValidateMode = 'blur' | 'input' | 'change' | 'submit';
export interface UseFormOptions<Values extends FormValues> {
initialValues: Values;
initialErrors?: FormErrors<Values>;
initialTouched?: FormTouched<Values>;
validateMode?: ValidateMode;
reValidateMode?: ValidateMode;
validateOnMounted?: boolean;
onSubmit: (
values: Values,
helper: FormSubmitHelper<Values>,
) => void | Promise<any>;
onInvalid?: (errors: FormErrors<Values>) => void;
validate?: (values: Values) => void | object | Promise<FormErrors<Values>>;
}
const enum ACTION_TYPE {
SUBMIT_ATTEMPT,
SUBMIT_SUCCESS,
SUBMIT_FAILURE,
SET_VALUES,
SET_FIELD_VALUE,
SET_TOUCHED,
SET_ERRORS,
SET_FIELD_ERROR,
SET_ISSUBMITTING,
SET_ISVALIDATING,
RESET_FORM,
}
type FormMessage<Values extends FormValues> =
| { type: ACTION_TYPE.SUBMIT_ATTEMPT }
| { type: ACTION_TYPE.SUBMIT_SUCCESS }
| { type: ACTION_TYPE.SUBMIT_FAILURE }
| { type: ACTION_TYPE.SET_VALUES; payload: Values }
| { type: ACTION_TYPE.SET_FIELD_VALUE; payload: { path: string; value: any } }
| {
type: ACTION_TYPE.SET_TOUCHED;
payload: { path: string; touched?: boolean };
}
| { type: ACTION_TYPE.SET_ERRORS; payload: FormErrors<Values> }
| {
type: ACTION_TYPE.SET_FIELD_ERROR;
payload: { path: string; error: string };
}
| { type: ACTION_TYPE.SET_ISSUBMITTING; payload: boolean }
| { type: ACTION_TYPE.SET_ISVALIDATING; payload: boolean }
| { type: ACTION_TYPE.RESET_FORM; payload: FormResetState<Values> };
function reducer<Values extends FormValues>(
state: FormState<Values>,
message: FormMessage<Values>,
) {
switch (message.type) {
case ACTION_TYPE.SUBMIT_ATTEMPT:
state.isSubmitting.value = true;
state.submitCount.value = state.submitCount.value + 1;
return;
case ACTION_TYPE.SUBMIT_SUCCESS:
state.isSubmitting.value = false;
return;
case ACTION_TYPE.SUBMIT_FAILURE:
state.isSubmitting.value = false;
return;
case ACTION_TYPE.SET_VALUES:
keysOf(state.values).forEach((key) => {
delete state.values[key];
});
keysOf(message.payload).forEach((path) => {
(state.values as Values)[path] = message.payload[path];
});
return;
case ACTION_TYPE.SET_FIELD_VALUE:
set(state.values, message.payload.path, deepClone(message.payload.value));
return;
case ACTION_TYPE.SET_TOUCHED:
set(state.touched.value, message.payload.path, message.payload.touched);
return;
case ACTION_TYPE.SET_ERRORS:
state.errors.value = message.payload;
return;
case ACTION_TYPE.SET_FIELD_ERROR:
set(state.errors.value, message.payload.path, message.payload.error);
return;
case ACTION_TYPE.SET_ISSUBMITTING:
state.isSubmitting.value = message.payload;
return;
case ACTION_TYPE.SET_ISVALIDATING:
state.isValidating.value = message.payload;
return;
case ACTION_TYPE.RESET_FORM:
reducer(state, {
type: ACTION_TYPE.SET_VALUES,
payload: message.payload.values,
});
state.touched.value = message.payload.touched;
state.errors.value = message.payload.errors;
state.submitCount.value = message.payload.submitCount;
}
}
const emptyErrors: FormErrors<unknown> = {};
const emptyTouched: FormTouched<unknown> = {};
/**
* Custom composition API to mange the entire form.
*
* @param options - form configuration and validation parameters. {@link UseFormOptions}
*
* @returns methods and state of this form. {@link UseFormReturn}
*
* @example
* ```vue
* <script setup lang="ts">
* const { register, handleSubmit } = useForm({
* initialValues: {
* name: 'Alex',
* age: 18,
* },
* onSubmit (values) {
* console.log({ values })
* },
* });
*
* const { value: name, attrs: nameAttrs } = register('name')
* const { value: age, attrs: ageAttrs } = register('name')
* </script>
*
* <template>
* <form v-on:submit="handleSubmit">
* <input v-model="name" type="text" v-bind="nameAttrs" />
* <input v-model.number="age" type="text" v-bind="ageAttrs" />
* <input type="submit" />
* </form>
* </template>
* ```
*/
export function useForm<Values extends FormValues = FormValues>(
options: UseFormOptions<Values>,
): UseFormReturn<Values> {
const {
validateOnMounted = false,
validateMode = 'submit',
reValidateMode = 'change',
onSubmit,
onInvalid,
} = options;
let initialValues = deepClone(options.initialValues);
let initialErrors = deepClone(options.initialErrors || emptyErrors);
let initialTouched = deepClone(options.initialTouched || emptyTouched);
const [state, dispatch] = useFormStore<
Reducer<FormState<Values>, FormMessage<Values>>
>(reducer, {
values: reactive(deepClone(initialValues)),
errors: ref(deepClone(initialErrors)),
touched: ref(deepClone(initialTouched)),
submitCount: ref(0),
isSubmitting: ref(false),
isValidating: ref(false),
});
const fieldRegistry: FieldRegistry = {};
const fieldArrayRegistry: FieldArrayRegistry = {};
const dirty = computed(() => !isEqual(state.values, initialValues));
const validateTiming = computed(() =>
state.submitCount.value === 0 ? validateMode : reValidateMode,
);
const registerField = (name: MaybeRef<string>, { validate }: any = {}) => {
fieldRegistry[unref(name)] = {
validate,
};
};
const registerFieldArray = (name: MaybeRef<string>, options: any) => {
registerField(name, options);
fieldArrayRegistry[unref(name)] = {
reset: options.reset,
};
};
const setFieldTouched = (name: string, touched = true) => {
dispatch({
type: ACTION_TYPE.SET_TOUCHED,
payload: {
path: name,
touched,
},
});
return validateTiming.value === 'blur'
? runAllValidateHandler(state.values)
: Promise.resolve();
};
const setValues = (values: Values, shouldValidate?: boolean) => {
dispatch({
type: ACTION_TYPE.SET_VALUES,
payload: values,
});
const willValidate =
shouldValidate == null
? validateTiming.value === 'change'
: shouldValidate;
return willValidate
? runAllValidateHandler(state.values)
: Promise.resolve();
};
const setFieldValue = (
name: string,
value: any,
shouldValidate?: boolean,
) => {
dispatch({
type: ACTION_TYPE.SET_FIELD_VALUE,
payload: {
path: name,
value,
},
});
return shouldValidate
? runAllValidateHandler(state.values)
: Promise.resolve();
};
const setFieldArrayValue: SetFieldArrayValue = (
name,
value,
method,
args,
shouldSetValue = true,
) => {
if (method && args) {
if (
keysOf(state.errors.value).length &&
Array.isArray(get(state.errors.value, name))
) {
const error = method(
get(state.errors.value, name),
args.argA,
args.argB,
);
if (shouldSetValue) {
dispatch({
type: ACTION_TYPE.SET_FIELD_ERROR,
payload: {
path: name,
error,
},
});
}
}
if (
keysOf(state.touched.value).length &&
Array.isArray(get(state.touched.value, name))
) {
const touched = method(
get(state.touched.value, name),
args.argA,
args.argB,
);
if (shouldSetValue) {
dispatch({
type: ACTION_TYPE.SET_TOUCHED,
payload: {
path: name,
touched,
},
});
}
}
}
return setFieldValue(name, value);
};
const handleBlur: FormEventHandler['handleBlur'] = (
eventOrName: Event | string,
path?: string,
): void | (() => void) => {
if (isString(eventOrName)) {
return () => setFieldTouched(eventOrName, true);
}
const { name, id } = eventOrName.target as HTMLInputElement;
const field = path ?? (name || id);
if (field) {
setFieldTouched(field, true);
}
};
const handleChange: FormEventHandler['handleChange'] = () => {
if (validateTiming.value === 'change') {
runAllValidateHandler(state.values);
}
};
const handleInput: FormEventHandler['handleInput'] = () => {
if (validateTiming.value === 'input') {
runAllValidateHandler(state.values);
}
};
const setSubmitting = (isSubmitting: boolean) => {
dispatch({ type: ACTION_TYPE.SET_ISSUBMITTING, payload: isSubmitting });
};
const getFieldValue = (name: MaybeRef<string>) => {
return computed<any>({
get() {
return get(state.values, unref(name));
},
set(value) {
setFieldValue(unref(name), value);
},
});
};
const getFieldMeta = (name: MaybeRef<string>): FieldMeta => {
const error = computed(() => getFieldError(unref(name)) as any as string);
const touched = computed(() => getFieldTouched(unref(name)));
const dirty = computed(() => getFieldDirty(unref(name)));
return {
dirty,
error,
touched,
};
};
const getFieldAttrs = (name: MaybeRef<string>) => {
return computed<FieldAttrs>(() => ({
name: unref(name),
onBlur: handleBlur,
onChange: handleChange,
onInput: handleInput,
}));
};
const getFieldError = (name: string): FormErrors<any> => {
return get(state.errors.value, name);
};
const getFieldTouched = (name: string): FormTouched<boolean> => {
return get(state.touched.value, name, false);
};
const getFieldDirty = (name: string): boolean => {
return !isEqual(get(initialValues, name), get(state.values, name));
};
const submitHelper: FormSubmitHelper<Values> = {
setSubmitting,
get initialValues() {
return deepClone(initialValues);
},
};
const runSingleFieldValidateHandler = (name: string, value: unknown) => {
return new Promise<string>((resolve) =>
resolve(fieldRegistry[name].validate(value) as string),
);
};
const runFieldValidateHandler = (values: Values) => {
const fieldKeysWithValidation = keysOf(fieldRegistry).filter((field) =>
isFunction(fieldRegistry[field].validate),
) as string[];
const fieldValidatePromise = fieldKeysWithValidation.map((field) =>
runSingleFieldValidateHandler(field, get(values, field)),
);
return Promise.all(fieldValidatePromise).then((errors) =>
errors.reduce((prev, curr, index) => {
if (curr) {
set(prev, fieldKeysWithValidation[index], curr);
}
return prev;
}, {} as FormErrors<Values>),
);
};
const runValidateHandler = (values: Values) => {
return new Promise<FormErrors<Values>>((resolve) => {
const maybePromise = options.validate?.(values);
if (maybePromise == null) {
resolve({});
} else if (isPromise(maybePromise)) {
maybePromise.then((error) => {
resolve(error || {});
});
} else {
resolve(maybePromise);
}
});
};
const runAllValidateHandler = (values: Values = state.values) => {
dispatch({ type: ACTION_TYPE.SET_ISVALIDATING, payload: true });
return Promise.all([
runFieldValidateHandler(values),
options.validate ? runValidateHandler(values) : {},
])
.then(([fieldErrors, validateErrors]) => {
const errors = deepmerge.all<FormErrors<Values>>(
[fieldErrors, validateErrors],
{
arrayMerge,
},
);
dispatch({ type: ACTION_TYPE.SET_ERRORS, payload: errors });
return errors;
})
.finally(() => {
dispatch({ type: ACTION_TYPE.SET_ISVALIDATING, payload: false });
});
};
const handleSubmit = (event?: Event) => {
event?.preventDefault();
dispatch({ type: ACTION_TYPE.SUBMIT_ATTEMPT });
runAllValidateHandler().then((errors) => {
const isValid = keysOf(errors).length === 0;
if (isValid) {
const maybePromise = onSubmit(deepClone(state.values), submitHelper);
if (maybePromise == null) {
return;
}
maybePromise
.then((result) => {
dispatch({ type: ACTION_TYPE.SUBMIT_SUCCESS });
return result;
})
.catch(() => {
dispatch({ type: ACTION_TYPE.SUBMIT_FAILURE });
});
} else {
dispatch({ type: ACTION_TYPE.SUBMIT_FAILURE });
onInvalid?.(errors);
}
});
};
const resetForm: ResetForm<Values> = (nextState) => {
const values = deepClone(nextState?.values || initialValues);
const errors = deepClone(nextState?.errors || initialErrors);
const touched = deepClone(nextState?.touched || initialTouched);
initialValues = deepClone(values);
initialErrors = deepClone(errors);
initialTouched = deepClone(touched);
dispatch({
type: ACTION_TYPE.RESET_FORM,
payload: {
values,
touched,
errors,
submitCount:
typeof nextState?.submitCount === 'number'
? nextState.submitCount
: 0,
},
});
// reset `fields` of `useFieldArray`
Object.values(fieldArrayRegistry).forEach((field) => {
field.reset();
});
};
const handleReset = (event?: Event) => {
event?.preventDefault();
resetForm();
};
const register: UseFormRegister<Values> = (name, options) => {
registerField(name, options);
return {
value: getFieldValue(name),
attrs: getFieldAttrs(name),
...getFieldMeta(name),
};
};
const validateField: ValidateField<Values> = (name) => {
if (fieldRegistry[name] && isFunction(fieldRegistry[name].validate)) {
dispatch({ type: ACTION_TYPE.SET_ISVALIDATING, payload: true });
return runSingleFieldValidateHandler(name, get(state.values, name))
.then((error) => {
dispatch({
type: ACTION_TYPE.SET_FIELD_ERROR,
payload: { path: name, error },
});
})
.finally(() => {
dispatch({ type: ACTION_TYPE.SET_ISVALIDATING, payload: false });
});
}
return Promise.resolve();
};
const context = {
values: state.values,
touched: computed(() => state.touched.value),
errors: computed(() => state.errors.value),
submitCount: computed(() => state.submitCount.value),
isSubmitting: state.isSubmitting,
isValidating: computed(() => state.isValidating.value),
dirty,
register,
setValues,
setFieldValue,
handleSubmit,
handleReset,
resetForm,
validateForm: runAllValidateHandler,
validateField,
};
provide(InternalContextKey, {
getFieldValue,
setFieldValue,
getFieldError,
getFieldTouched,
getFieldDirty,
getFieldAttrs,
registerFieldArray,
setFieldArrayValue,
register,
});
provide<UseFormReturn<Values>>(FormContextKey, context);
onMounted(() => {
if (!validateOnMounted) return;
runAllValidateHandler(initialValues);
});
return context;
}
/**
* deepmerge array merging algorithm
* https://github.com/TehShrike/deepmerge#arraymerge-example-combine-arrays
*/
function arrayMerge<T extends any[]>(target: T, source: T, options: any) {
const destination = [...target];
source.forEach((item, index) => {
if (typeof destination[index] === 'undefined') {
destination[index] = options.cloneUnlessOtherwiseSpecified(item, options);
} else if (options.isMergeableObject(item)) {
destination[index] = deepmerge(target[index], item, options);
} else if (target.indexOf(item) === -1) {
destination.push(item);
}
});
return destination;
}