/
useField.ts
510 lines (445 loc) · 12.2 KB
/
useField.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
import {
watch,
ref,
isRef,
reactive,
computed,
onMounted,
onBeforeUnmount,
unref,
WatchStopHandle,
provide,
Ref,
} from 'vue';
import { BaseSchema } from 'yup';
import isEqual from 'fast-deep-equal/es6';
import { validate as validateValue } from './validate';
import {
FormContext,
ValidationResult,
MaybeRef,
GenericValidateFunction,
FieldMeta,
YupValidator,
FieldComposable,
FieldState,
PrivateFieldComposite,
WritableRef,
} from './types';
import {
normalizeRules,
extractLocators,
normalizeEventValue,
hasCheckedAttr,
getFromPath,
injectWithSelf,
resolveNextCheckboxValue,
isYupValidator,
} from './utils';
import { isCallable } from '../../shared';
import { FieldContextSymbol, FormInitialValuesSymbol, FormContextSymbol } from './symbols';
interface FieldOptions<TValue = unknown> {
initialValue?: MaybeRef<TValue>;
validateOnValueUpdate: boolean;
validateOnMount?: boolean;
bails?: boolean;
type?: string;
valueProp?: MaybeRef<TValue>;
uncheckedValue?: MaybeRef<TValue>;
label?: MaybeRef<string>;
}
type RuleExpression<TValue> =
| string
| Record<string, unknown>
| GenericValidateFunction
| YupValidator
| BaseSchema<TValue>
| undefined;
let ID_COUNTER = 0;
/**
* Creates a field composite.
*/
export function useField<TValue = unknown>(
name: MaybeRef<string>,
rules?: MaybeRef<RuleExpression<TValue>>,
opts?: Partial<FieldOptions<TValue>>
): FieldComposable<TValue> {
const fid = ID_COUNTER >= Number.MAX_SAFE_INTEGER ? 0 : ++ID_COUNTER;
const {
initialValue,
validateOnMount,
bails,
type,
valueProp,
label,
validateOnValueUpdate,
uncheckedValue,
} = normalizeOptions(unref(name), opts);
const form = injectWithSelf(FormContextSymbol);
const {
meta,
errors,
errorMessage,
handleBlur,
handleInput,
resetValidationState,
setValidationState,
setErrors,
value,
checked,
} = useValidationState<TValue>({
name,
initValue: initialValue,
form,
type,
valueProp,
});
const normalizedRules = computed(() => {
let rulesValue = unref(rules);
const schema = unref(form?.schema);
if (schema && !isYupValidator(schema)) {
rulesValue = extractRuleFromSchema<TValue>(schema, unref(name)) || rulesValue;
}
if (isYupValidator(rulesValue) || isCallable(rulesValue)) {
return rulesValue;
}
return normalizeRules(rulesValue);
});
async function validateWithStateMutation(): Promise<ValidationResult> {
meta.pending = true;
let result: ValidationResult;
meta.validated = true;
if (!form || !form.validateSchema) {
result = await validateValue(value.value, normalizedRules.value, {
name: unref(label) || unref(name),
values: form?.values ?? {},
bails,
});
} else {
result = (await form.validateSchema('validated-only'))[unref(name)] ?? { valid: true, errors: [] };
}
meta.pending = false;
return setValidationState(result);
}
async function validateValidStateOnly(): Promise<void> {
let result: ValidationResult;
if (!form || !form.validateSchema) {
result = await validateValue(value.value, normalizedRules.value, {
name: unref(label) || unref(name),
values: form?.values ?? {},
bails,
});
} else {
result = (await form.validateSchema('silent'))?.[unref(name)] ?? { valid: true, errors: [] };
}
meta.valid = result.valid;
}
// Common input/change event handler
const handleChange = (e: unknown) => {
if (checked && checked.value === ((e as Event)?.target as HTMLInputElement)?.checked) {
return;
}
let newValue = normalizeEventValue(e) as TValue;
// Single checkbox field without a form to toggle it's value
if (checked && type === 'checkbox' && !form) {
newValue = resolveNextCheckboxValue(value.value, unref(valueProp), unref(uncheckedValue)) as TValue;
}
value.value = newValue;
if (!validateOnValueUpdate) {
return validateWithStateMutation();
}
};
// Runs the initial validation
onMounted(() => {
if (validateOnMount) {
return validateWithStateMutation();
}
// validate self initially if no form was handling this
// forms should have their own initial silent validation run to make things more efficient
if (!form || !form.validateSchema) {
validateValidStateOnly();
}
});
function setTouched(isTouched: boolean) {
meta.touched = isTouched;
}
let unwatchValue: WatchStopHandle;
function watchValue() {
unwatchValue = watch(value, validateOnValueUpdate ? validateWithStateMutation : validateValidStateOnly, {
deep: true,
});
}
watchValue();
function resetField(state?: Partial<FieldState<TValue>>) {
unwatchValue?.();
resetValidationState(state);
watchValue();
}
const field: PrivateFieldComposite<TValue> = {
idx: -1,
fid,
name,
value,
meta,
errors,
errorMessage,
type,
valueProp,
uncheckedValue,
checked,
resetField,
handleReset: () => resetField(),
validate: validateWithStateMutation,
handleChange,
handleBlur,
handleInput,
setValidationState,
setTouched,
setErrors,
};
provide(FieldContextSymbol, field);
if (isRef(rules) && typeof unref(rules) !== 'function') {
watch(
rules,
(value, oldValue) => {
if (isEqual(value, oldValue)) {
return;
}
return validateWithStateMutation();
},
{
deep: true,
}
);
}
// if no associated form return the field API immediately
if (!form) {
return field;
}
// associate the field with the given form
form.register(field);
onBeforeUnmount(() => {
form.unregister(field);
});
// extract cross-field dependencies in a computed prop
const dependencies = computed(() => {
const rulesVal = normalizedRules.value;
// is falsy, a function schema or a yup schema
if (!rulesVal || isCallable(rulesVal) || isYupValidator(rulesVal)) {
return {};
}
return Object.keys(rulesVal).reduce((acc, rule: string) => {
const deps = extractLocators(rulesVal[rule])
.map((dep: any) => dep.__locatorRef)
.reduce((depAcc, depName) => {
const depValue = getFromPath(form.values, depName) || form.values[depName];
if (depValue !== undefined) {
depAcc[depName] = depValue;
}
return depAcc;
}, {} as Record<string, unknown>);
Object.assign(acc, deps);
return acc;
}, {} as Record<string, unknown>);
});
// Adds a watcher that runs the validation whenever field dependencies change
watch(dependencies, (deps, oldDeps) => {
// Skip if no dependencies or if the field wasn't manipulated
if (!Object.keys(deps).length) {
return;
}
const shouldValidate = !isEqual(deps, oldDeps);
if (shouldValidate) {
meta.dirty ? validateWithStateMutation() : validateValidStateOnly();
}
});
return field;
}
/**
* Normalizes partial field options to include the full options
*/
function normalizeOptions<TValue>(name: string, opts: Partial<FieldOptions<TValue>> | undefined): FieldOptions<TValue> {
const defaults = () => ({
initialValue: undefined,
validateOnMount: false,
bails: true,
rules: '',
label: name,
validateOnValueUpdate: true,
});
if (!opts) {
return defaults();
}
return {
...defaults(),
...(opts || {}),
};
}
/**
* Manages the validation state of a field.
*/
function useValidationState<TValue>({
name,
initValue,
form,
type,
valueProp,
}: {
name: MaybeRef<string>;
valueProp?: MaybeRef<TValue>;
initValue?: MaybeRef<TValue>;
form?: FormContext;
type?: string;
}) {
const { errors, errorMessage, setErrors } = useErrorsSource(name, form);
const formInitialValues = injectWithSelf(FormInitialValuesSymbol, undefined);
// clones the ref value to a mutable version
const initialValueRef = ref(unref(initValue)) as Ref<TValue>;
const initialValue = computed(() => {
return (getFromPath<TValue>(unref(formInitialValues), unref(name)) ?? unref(initialValueRef)) as TValue;
});
const value = useFieldValue(initialValue, name, form);
const meta = useMeta(initialValue, value, errors);
const checked = hasCheckedAttr(type)
? computed(() => {
if (Array.isArray(value.value)) {
return value.value.includes(unref(valueProp));
}
return unref(valueProp) === value.value;
})
: undefined;
/**
* Handles common onBlur meta update
*/
const handleBlur = () => {
meta.touched = true;
};
/**
* Handles common on blur events
*/
const handleInput = (e: unknown) => {
// Checkboxes/Radio will emit a `change` event anyway, custom components will use `update:modelValue`
// so this is redundant
if (!hasCheckedAttr(type)) {
value.value = normalizeEventValue(e) as TValue;
}
};
// Updates the validation state with the validation result
function setValidationState(result: ValidationResult) {
setErrors(result.errors);
return result;
}
// Resets the validation state
function resetValidationState(state?: Partial<FieldState<TValue>>) {
const fieldPath = unref(name);
const newValue =
state && 'value' in state
? (state.value as TValue)
: ((getFromPath<TValue>(unref(formInitialValues), fieldPath) ?? unref(initValue)) as TValue);
if (form) {
form.setFieldValue(fieldPath, newValue, { force: true });
form.setFieldInitialValue(fieldPath, newValue);
} else {
value.value = newValue;
initialValueRef.value = newValue;
}
setErrors(state?.errors || []);
meta.touched = state?.touched ?? false;
meta.pending = false;
meta.validated = false;
}
return {
meta,
errors,
errorMessage,
setErrors,
setValidationState,
resetValidationState,
handleBlur,
handleInput,
value,
checked,
};
}
/**
* Exposes meta flags state and some associated actions with them.
*/
function useMeta<TValue>(initialValue: MaybeRef<TValue>, currentValue: Ref<TValue>, errors: Ref<string[]>) {
const meta = reactive({
touched: false,
pending: false,
valid: true,
validated: false,
initialValue: computed(() => unref(initialValue) as TValue | undefined),
dirty: computed(() => {
return !isEqual(unref(currentValue), unref(initialValue));
}),
}) as FieldMeta<TValue>;
watch(
errors,
value => {
meta.valid = !value.length;
},
{
immediate: true,
flush: 'sync',
}
);
return meta;
}
/**
* Extracts the validation rules from a schema
*/
function extractRuleFromSchema<TValue>(schema: Record<string, RuleExpression<TValue>> | undefined, fieldName: string) {
// no schema at all
if (!schema) {
return undefined;
}
// there is a key on the schema object for this field
return schema[fieldName];
}
/**
* Manages the field value
*/
function useFieldValue<TValue>(
initialValue: MaybeRef<TValue | undefined>,
path: MaybeRef<string>,
form?: FormContext
): WritableRef<TValue> {
// if no form is associated, use a regular ref.
if (!form) {
return ref(unref(initialValue)) as WritableRef<TValue>;
}
// set initial value
form.stageInitialValue(unref(path), unref(initialValue));
// otherwise use a computed setter that triggers the `setFieldValue`
const value = computed<TValue>({
get() {
return getFromPath<TValue>(form.values, unref(path)) as TValue;
},
set(newVal) {
form.setFieldValue(unref(path), newVal);
},
});
return value as WritableRef<TValue>;
}
function useErrorsSource(path: MaybeRef<string>, form?: FormContext) {
if (!form) {
const errors = ref<string[]>([]);
return {
errors: computed(() => errors.value),
errorMessage: computed<string | undefined>(() => errors.value[0]),
setErrors: (messages: string | string[]) => {
errors.value = Array.isArray(messages) ? messages : [messages];
},
};
}
const errors = computed(() => form.errorBag.value[unref(path)] || []);
return {
errors,
errorMessage: computed<string | undefined>(() => errors.value[0]),
setErrors: (messages: string | string[]) => {
form.setFieldErrorBag(unref(path), messages);
},
};
}