/
useForm.ts
773 lines (667 loc) · 22.3 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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
import { computed, ref, Ref, provide, reactive, onMounted, isRef, watch, unref, nextTick, warn } from 'vue';
import isEqual from 'fast-deep-equal/es6';
import type { SchemaOf } from 'yup';
import { klona as deepCopy } from 'klona/lite';
import {
FieldMeta,
SubmissionHandler,
GenericValidateFunction,
ValidationResult,
MaybeRef,
FormState,
FormValidationResult,
PrivateFieldContext,
PrivateFormContext,
FormContext,
FormErrors,
FormErrorBag,
SchemaValidationMode,
RawFormSchema,
} from './types';
import {
applyFieldMutation,
getFromPath,
isYupValidator,
keysOf,
resolveNextCheckboxValue,
setInPath,
unsetPath,
isFormSubmitEvent,
normalizeField,
} from './utils';
import { FormErrorsKey, FormContextKey, FormInitialValuesKey } from './symbols';
import { validateYupSchema, validateObjectSchema } from './validate';
interface FormOptions<TValues extends Record<string, any>> {
validationSchema?: MaybeRef<
Record<keyof TValues, GenericValidateFunction | string | Record<string, any>> | SchemaOf<TValues> | undefined
>;
initialValues?: MaybeRef<TValues>;
initialErrors?: Record<keyof TValues, string | undefined>;
initialTouched?: Record<keyof TValues, boolean>;
validateOnMount?: boolean;
}
type RegisteredField = PrivateFieldContext | PrivateFieldContext[];
export function useForm<TValues extends Record<string, any> = Record<string, any>>(
opts?: FormOptions<TValues>
): FormContext<TValues> {
// A flat array containing field references
const fields: Ref<PrivateFieldContext[]> = ref([]);
// If the form is currently submitting
const isSubmitting = ref(false);
// a field map object useful for faster access of fields
const fieldsById = computed<Record<keyof TValues, RegisteredField>>(() => {
return fields.value.reduce((acc, field) => {
const fieldPath: keyof TValues = unref(field.name);
// if the field was not added before
if (!acc[fieldPath]) {
acc[fieldPath] = field;
field.idx = -1;
return acc;
}
// if the same name is detected
const existingField: RegisteredField = acc[fieldPath];
if (!Array.isArray(existingField)) {
existingField.idx = 0;
acc[fieldPath] = [existingField];
}
const fieldGroup = acc[fieldPath] as PrivateFieldContext[];
field.idx = fieldGroup.length;
fieldGroup.push(field);
return acc;
}, {} as Record<keyof TValues, RegisteredField>);
});
// The number of times the user tried to submit the form
const submitCount = ref(0);
// a private ref for all form values
const formValues = reactive(deepCopy(unref(opts?.initialValues) || {})) as TValues;
// a lookup to keep track of values by their field ids
// this is important because later we need it if fields swap names
const valuesByFid: Record<string, any> = {};
// the source of errors for the form fields
const { errorBag, setErrorBag, setFieldErrorBag } = useErrorBag(opts?.initialErrors);
// Gets the first error of each field
const errors = computed<FormErrors<TValues>>(() => {
return keysOf(errorBag.value).reduce((acc, key) => {
const bag = errorBag.value[key];
if (bag && bag.length) {
acc[key] = bag[0];
}
return acc;
}, {} as FormErrors<TValues>);
});
/**
* Holds a computed reference to all fields names and labels
*/
const fieldNames = computed(() => {
return keysOf(fieldsById.value).reduce((names, path) => {
const field = normalizeField(fieldsById.value[path]);
if (field) {
names[path as string] = unref(field.label || field.name) || '';
}
return names;
}, {} as Record<string, string>);
});
const fieldBailsMap = computed(() => {
return keysOf(fieldsById.value).reduce((map, path) => {
const field = normalizeField(fieldsById.value[path]);
if (field) {
map[path as string] = field.bails ?? true;
}
return map;
}, {} as Record<string, boolean>);
});
// mutable non-reactive reference to initial errors
// we need this to process initial errors then unset them
const initialErrors = { ...(opts?.initialErrors || {}) };
// initial form values
const { readonlyInitialValues, initialValues, setInitialValues } = useFormInitialValues<TValues>(
fieldsById,
formValues,
opts?.initialValues
);
// form meta aggregations
const meta = useFormMeta(fields, formValues, readonlyInitialValues, errors);
const schema = opts?.validationSchema;
const formCtx: PrivateFormContext<TValues> = {
fieldsById,
values: formValues,
errorBag,
schema,
submitCount,
meta,
isSubmitting,
validateSchema: unref(schema) ? validateSchema : undefined,
validate,
register: registerField,
unregister: unregisterField,
setFieldErrorBag,
validateField,
setFieldValue,
setValues,
setErrors,
setFieldError,
setFieldTouched,
setTouched,
resetForm,
handleSubmit,
stageInitialValue,
setFieldInitialValue,
};
/**
* Manually sets an error message on a specific field
*/
function setFieldError(field: keyof TValues, message: string | string[] | undefined) {
setFieldErrorBag(field, message);
}
/**
* Sets errors for the fields specified in the object
*/
function setErrors(fields: Partial<Record<keyof TValues, string | string[] | undefined>>) {
setErrorBag(fields);
}
/**
* Sets a single field value
*/
function setFieldValue<T extends keyof TValues = string>(
field: T,
value: TValues[T] | undefined,
{ force } = { force: false }
) {
const fieldInstance: RegisteredField | undefined = fieldsById.value[field];
const clonedValue = deepCopy(value);
// field wasn't found, create a virtual field as a placeholder
if (!fieldInstance) {
setInPath(formValues, field as string, clonedValue);
return;
}
// Multiple checkboxes, and only one of them got updated
if (Array.isArray(fieldInstance) && fieldInstance[0]?.type === 'checkbox' && !Array.isArray(value)) {
const newVal = deepCopy(
resolveNextCheckboxValue(getFromPath(formValues, field as string) || [], value, undefined)
);
setInPath(formValues, field as string, newVal);
fieldInstance.forEach(fieldItem => {
valuesByFid[fieldItem.fid] = newVal;
});
return;
}
let newValue = value;
// Single Checkbox: toggles the field value unless the field is being reset then force it
if (!Array.isArray(fieldInstance) && fieldInstance?.type === 'checkbox' && !force) {
newValue = deepCopy(
resolveNextCheckboxValue<TValues[T]>(
getFromPath<TValues[T]>(formValues, field as string) as TValues[T],
value as TValues[T],
unref(fieldInstance.uncheckedValue) as TValues[T]
)
);
}
setInPath(formValues, field as string, newValue);
// multiple radio fields
if (fieldInstance && Array.isArray(fieldInstance)) {
fieldInstance.forEach(fieldItem => {
valuesByFid[fieldItem.fid] = newValue;
});
return;
}
valuesByFid[fieldInstance.fid] = newValue;
}
/**
* Sets multiple fields values
*/
function setValues(fields: Partial<TValues>) {
// clean up old values
keysOf(formValues).forEach(key => {
delete formValues[key];
});
// set up new values
keysOf(fields).forEach(path => {
setFieldValue(path, fields[path]);
});
}
/**
* Sets the touched meta state on a field
*/
function setFieldTouched(field: keyof TValues, isTouched: boolean) {
const fieldInstance: RegisteredField | undefined = fieldsById.value[field];
if (!fieldInstance) {
return;
}
applyFieldMutation(fieldInstance, f => f.setTouched(isTouched));
}
/**
* Sets the touched meta state on multiple fields
*/
function setTouched(fields: Partial<Record<keyof TValues, boolean>>) {
keysOf(fields).forEach(field => {
setFieldTouched(field, !!fields[field]);
});
}
/**
* Resets all fields
*/
function resetForm(state?: Partial<FormState<TValues>>) {
// set initial values if provided
if (state?.values) {
setInitialValues(state.values);
setValues(state?.values);
} else {
// otherwise clean the current values
setValues(initialValues.value);
}
// Reset all fields state
fields.value.forEach(f => f.resetField());
if (state?.touched) {
setTouched(state.touched);
}
setErrors(state?.errors || {});
submitCount.value = state?.submitCount || 0;
}
function registerField(field: PrivateFieldContext) {
fields.value.push(field);
// TODO: Do this automatically on registration
// eslint-disable-next-line no-unused-expressions
fieldsById.value; // force computation of the fields ids to properly set their idx
if (isRef(field.name)) {
valuesByFid[field.fid] = field.value.value;
// ensures when a field's name was already taken that it preserves its same value
// necessary for fields generated by loops
watch(
field.name,
(newPath, oldPath) => {
setFieldValue(newPath, valuesByFid[field.fid]);
const isSharingName = fields.value.find(f => unref(f.name) === oldPath);
// clean up the old path if no other field is sharing that name
// #3325
if (!isSharingName) {
unsetPath(formValues, oldPath);
unsetPath(initialValues.value, oldPath);
}
},
{
flush: 'post',
}
);
}
// if field already had errors (initial errors) that's not user-set, validate it again to ensure state is correct
// the difference being that `initialErrors` will contain the error message while other errors (pre-validated schema) won't have them as initial errors
// #3342
const path = unref(field.name);
const initialErrorMessage = unref(field.errorMessage);
if (initialErrorMessage && initialErrors?.[path] !== initialErrorMessage) {
validateField(path);
}
// marks the initial error as "consumed" so it won't be matched later with same non-initial error
delete initialErrors[path];
}
function unregisterField(field: PrivateFieldContext<unknown>) {
const idx = fields.value.indexOf(field);
if (idx === -1) {
return;
}
fields.value.splice(idx, 1);
const fid = field.fid;
// cleans up the field value from fid lookup
nextTick(() => {
delete valuesByFid[fid];
// clears a field error on unmounted
// we wait till next tick to make sure if the field is completely removed and doesn't have any siblings like checkboxes
// #3384
if (!fieldsById.value[fieldName]) {
setFieldError(fieldName, undefined);
}
});
const fieldName = unref(field.name);
// in this case, this is a single field not a group (checkbox or radio)
// so remove the field value key immediately
if (field.idx === -1) {
// avoid un-setting the value if the field was switched with another that shares the same name
// they will be unset once the new field takes over the new name, look at `#registerField()`
// #3166
const isSharingName = fields.value.find(f => unref(f.name) === fieldName);
if (isSharingName) {
return;
}
unsetPath(formValues, fieldName);
unsetPath(initialValues.value, fieldName);
return;
}
// otherwise find the actual value in the current array of values and remove it
const valueIdx: number | undefined = getFromPath<unknown[] | undefined>(formValues, fieldName)?.indexOf?.(
unref(field.checkedValue)
);
if (valueIdx === undefined) {
unsetPath(formValues, fieldName);
return;
}
if (valueIdx === -1) {
return;
}
if (Array.isArray(formValues[fieldName])) {
unsetPath(formValues, `${fieldName}.${valueIdx}`);
return;
}
unsetPath(formValues, fieldName);
unsetPath(initialValues.value, fieldName);
}
async function validate(): Promise<FormValidationResult<TValues>> {
if (formCtx.validateSchema) {
return formCtx.validateSchema('force');
}
// No schema, each field is responsible to validate itself
const validations = await Promise.all(
fields.value.map(f => {
return f.validate().then((result: ValidationResult) => {
return {
key: unref(f.name),
valid: result.valid,
errors: result.errors,
};
});
})
);
const results: Partial<Record<keyof TValues, ValidationResult>> = {};
const errors: Partial<Record<keyof TValues, string>> = {};
for (const validation of validations) {
results[validation.key as keyof TValues] = {
valid: validation.valid,
errors: validation.errors,
};
if (validation.errors.length) {
errors[validation.key as keyof TValues] = validation.errors[0];
}
}
return {
valid: validations.every(r => r.valid),
results,
errors,
};
}
async function validateField(field: keyof TValues): Promise<ValidationResult> {
const fieldInstance: RegisteredField | undefined = fieldsById.value[field];
if (!fieldInstance) {
warn(`field with name ${field} was not found`);
return Promise.resolve({ errors: [], valid: true });
}
if (Array.isArray(fieldInstance)) {
return fieldInstance.map(f => f.validate())[0];
}
return fieldInstance.validate();
}
function handleSubmit(fn?: SubmissionHandler<TValues>) {
return function submissionHandler(e: unknown) {
if (e instanceof Event) {
e.preventDefault();
e.stopPropagation();
}
// Touch all fields
setTouched(
keysOf(fieldsById.value).reduce((acc, field) => {
acc[field] = true;
return acc;
}, {} as Record<keyof TValues, boolean>)
);
isSubmitting.value = true;
submitCount.value++;
return validate()
.then(result => {
if (result.valid && typeof fn === 'function') {
return fn(deepCopy(formValues), {
evt: e as Event,
setErrors,
setFieldError,
setTouched,
setFieldTouched,
setValues,
setFieldValue,
resetForm,
});
}
})
.then(
() => {
isSubmitting.value = false;
},
err => {
isSubmitting.value = false;
// re-throw the err so it doesn't go silent
throw err;
}
);
};
}
function setFieldInitialValue(path: string, value: unknown) {
setInPath(initialValues.value, path, deepCopy(value));
}
/**
* Sneaky function to set initial field values
*/
function stageInitialValue(path: string, value: unknown) {
setInPath(formValues, path, value);
setFieldInitialValue(path, value);
}
async function validateSchema(mode: SchemaValidationMode): Promise<FormValidationResult<TValues>> {
const schemaValue = unref(schema);
if (!schemaValue) {
return { valid: true, results: {}, errors: {} };
}
const formResult = isYupValidator(schemaValue)
? await validateYupSchema(schemaValue, formValues)
: await validateObjectSchema(schemaValue as RawFormSchema<TValues>, formValues, {
names: fieldNames.value,
bailsMap: fieldBailsMap.value,
});
// fields by id lookup
const fieldsById = formCtx.fieldsById.value || {};
// errors fields names, we need it to also check if custom errors are updated
const currentErrorsPaths = keysOf(formCtx.errorBag.value);
// collect all the keys from the schema and all fields
// this ensures we have a complete keymap of all the fields
const paths = [
...new Set([...keysOf(formResult.results), ...keysOf(fieldsById), ...currentErrorsPaths]),
] as string[];
// aggregates the paths into a single result object while applying the results on the fields
return paths.reduce(
(validation, path) => {
const field: RegisteredField | undefined = fieldsById[path];
const messages = (formResult.results[path] || { errors: [] as string[] }).errors;
const fieldResult = {
errors: messages,
valid: !messages.length,
};
validation.results[path as keyof TValues] = fieldResult;
if (!fieldResult.valid) {
validation.errors[path as keyof TValues] = fieldResult.errors[0];
}
// field not rendered
if (!field) {
setFieldError(path, messages);
return validation;
}
// always update the valid flag regardless of the mode
applyFieldMutation(field, f => (f.meta.valid = fieldResult.valid));
if (mode === 'silent') {
return validation;
}
const wasValidated = Array.isArray(field) ? field.some(f => f.meta.validated) : field.meta.validated;
if (mode === 'validated-only' && !wasValidated) {
return validation;
}
applyFieldMutation(field, f => f.setValidationState(fieldResult), true);
return validation;
},
{ valid: formResult.valid, results: {}, errors: {} } as FormValidationResult<TValues>
);
}
const submitForm = handleSubmit((_, { evt }) => {
if (isFormSubmitEvent(evt)) {
evt.target.submit();
}
});
// Trigger initial validation
onMounted(() => {
if (opts?.initialErrors) {
setErrors(opts.initialErrors);
}
if (opts?.initialTouched) {
setTouched(opts.initialTouched);
}
// if validate on mount was enabled
if (opts?.validateOnMount) {
validate();
return;
}
// otherwise run initial silent validation through schema if available
// the useField should skip their own silent validation if a yup schema is present
if (formCtx.validateSchema) {
formCtx.validateSchema('silent');
}
});
if (isRef(schema)) {
watch(schema, () => {
formCtx.validateSchema?.('validated-only');
});
}
// Provide injections
provide(FormContextKey, formCtx as PrivateFormContext);
provide(FormErrorsKey, errors);
return {
errors,
meta,
values: formValues,
isSubmitting,
submitCount,
validate,
validateField,
handleReset: () => resetForm(),
resetForm,
handleSubmit,
submitForm,
setFieldError,
setErrors,
setFieldValue,
setValues,
setFieldTouched,
setTouched,
};
}
/**
* Manages form meta aggregation
*/
function useFormMeta<TValues extends Record<string, unknown>>(
fields: Ref<PrivateFieldContext[]>,
currentValues: TValues,
initialValues: MaybeRef<TValues>,
errors: Ref<FormErrors<TValues>>
) {
const MERGE_STRATEGIES: Record<keyof Pick<FieldMeta<unknown>, 'touched' | 'pending' | 'valid'>, 'every' | 'some'> = {
touched: 'some',
pending: 'some',
valid: 'every',
};
const isDirty = computed(() => {
return !isEqual(currentValues, unref(initialValues));
});
const flags = computed(() => {
return keysOf(MERGE_STRATEGIES).reduce((acc, flag) => {
const mergeMethod = MERGE_STRATEGIES[flag];
acc[flag] = fields.value[mergeMethod](field => field.meta[flag]);
return acc;
}, {} as Record<keyof Omit<FieldMeta<unknown>, 'initialValue'>, boolean>);
});
return computed(() => {
return {
initialValues: unref(initialValues) as TValues,
...flags.value,
valid: flags.value.valid && !keysOf(errors.value as any).length,
dirty: isDirty.value,
};
});
}
/**
* Manages the initial values prop
*/
function useFormInitialValues<TValues extends Record<string, any>>(
fields: Ref<Record<keyof TValues, RegisteredField>>,
formValues: TValues,
providedValues?: MaybeRef<TValues>
) {
const initialValues = ref<TValues>((unref(providedValues) as TValues) || ({} as TValues));
// acts as a read only proxy of the initial values object
const computedInitials = computed<TValues>(() => {
return initialValues.value as TValues;
});
function setInitialValues(values: Partial<TValues>, updateFields = false) {
initialValues.value = deepCopy(values);
if (!updateFields) {
return;
}
// update the pristine non-touched fields
// those are excluded because it's unlikely you want to change the form values using initial values
// we mostly watch them for API population or newly inserted fields
// if the user API is taking too much time before user interaction they should consider disabling or hiding their inputs until the values are ready
const hadInteraction = (f: PrivateFieldContext) => f.meta.touched;
keysOf(fields.value).forEach(fieldPath => {
const field: RegisteredField = fields.value[fieldPath];
const touchedByUser = Array.isArray(field) ? field.some(hadInteraction) : hadInteraction(field);
if (touchedByUser) {
return;
}
const newValue = getFromPath(initialValues.value, fieldPath as string);
setInPath(formValues, fieldPath as string, newValue);
});
}
if (isRef(providedValues)) {
watch(
providedValues,
value => {
setInitialValues(value, true);
},
{
deep: true,
}
);
}
provide(FormInitialValuesKey, computedInitials);
return {
readonlyInitialValues: computedInitials,
initialValues,
setInitialValues,
};
}
function useErrorBag<TValues extends Record<string, any>>(initialErrors?: FormErrors<TValues>) {
const errorBag: Ref<FormErrorBag<TValues>> = ref({});
function normalizeErrorItem(message: string | string[]) {
return Array.isArray(message) ? message : message ? [message] : [];
}
/**
* Manually sets an error message on a specific field
*/
function setFieldErrorBag(field: keyof TValues, message: string | undefined | string[]) {
if (!message) {
delete errorBag.value[field];
return;
}
errorBag.value[field] = normalizeErrorItem(message);
}
/**
* Sets errors for the fields specified in the object
*/
function setErrorBag(fields: Partial<Record<keyof TValues, string | string[] | undefined>>) {
errorBag.value = keysOf(fields).reduce((acc, key) => {
const message = fields[key] as string | string[] | undefined;
if (message) {
acc[key] = normalizeErrorItem(message);
}
return acc;
}, {} as FormErrorBag<TValues>);
}
if (initialErrors) {
setErrorBag(initialErrors);
}
return {
errorBag,
setErrorBag,
setFieldErrorBag,
};
}