-
Notifications
You must be signed in to change notification settings - Fork 8k
/
use_field.ts
692 lines (593 loc) · 21.4 KB
/
use_field.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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { useMemo, useState, useEffect, useRef, useCallback } from 'react';
import {
FormHook,
FieldHook,
FieldConfig,
FieldValidateResponse,
ValidationError,
FormData,
ValidationConfig,
FieldValidationData,
ValidationCancelablePromise,
} from '../types';
import { FIELD_TYPES, VALIDATION_TYPES } from '../constants';
export interface InternalFieldConfig<T> {
initialValue: T;
isIncludedInOutput?: boolean;
}
const errorsToString = (errors: ValidationError[]): string[] | null => {
return errors.length ? errors.map((error) => error.message) : null;
};
export const useField = <T, FormType = FormData, I = T>(
// @ts-expect-error upgrade typescript v4.9.5
form: FormHook<FormType>,
path: string,
// @ts-expect-error upgrade typescript v4.9.5
config: FieldConfig<T, FormType, I> & InternalFieldConfig<T>,
valueChangeListener?: (value: I) => void,
errorChangeListener?: (errors: string[] | null) => void,
{
validationData = null,
validationDataProvider = () => Promise.resolve(undefined),
}: FieldValidationData = {}
) => {
const {
type = FIELD_TYPES.TEXT,
defaultValue = '' as unknown as T, // The default value instead of "undefined" (when resetting the form this will be the field value)
initialValue, // The initial value of the field when rendering the form
isIncludedInOutput = true,
label = '',
labelAppend = '',
helpText = '',
validations,
formatters,
fieldsToValidateOnChange,
valueChangeDebounceTime = form.__options.valueChangeDebounceTime, // By default 500ms
serializer,
deserializer,
} = config;
const { getFormData, getFields, validateFields, __addField, __removeField, __getFormData$ } =
form;
const deserializeValue = useCallback(
(rawValue: T): I => {
if (typeof rawValue === 'function') {
return deserializer ? deserializer(rawValue()) : rawValue();
}
return deserializer ? deserializer(rawValue) : (rawValue as unknown as I);
},
[deserializer]
);
const initialValueDeserialized = useMemo(() => {
return deserializeValue(initialValue);
}, [deserializeValue, initialValue]);
const [value, setStateValue] = useState<I>(initialValueDeserialized);
const [errors, setStateErrors] = useState<ValidationError[]>([]);
const [isPristine, setPristine] = useState(true);
const [isModified, setIsModified] = useState(false);
const [isValidating, setValidating] = useState(false);
const [isChangingValue, setIsChangingValue] = useState(false);
const [isValidated, setIsValidated] = useState(false);
const isMounted = useRef<boolean>(false);
const validateCounter = useRef(0);
const changeCounter = useRef(0);
const inflightValidation = useRef<ValidationCancelablePromise | null>(null);
const debounceTimeout = useRef<NodeJS.Timeout | null>(null);
// Keep a ref of the last state (value and errors) notified to the consumer so they don't get
// loads of updates whenever they don't wrap the "onChange()" and "onError()" handlers with a useCallback
// e.g. <UseField onChange={() => { // inline code }}
const lastNotifiedState = useRef<{ value?: I; errors: string[] | null }>({
value: initialValueDeserialized,
errors: null,
});
const hasAsyncValidation = useMemo(
() =>
validations === undefined
? false
: validations.some((validation) => validation.isAsync === true),
[validations]
);
const valueHasChanged = value !== lastNotifiedState.current.value;
const errorsHaveChanged = lastNotifiedState.current.errors !== errorsToString(errors);
// ----------------------------------
// -- HELPERS
// ----------------------------------
/**
* Filter an array of errors for a specific validation type
*
* @param _errors The array of errors to filter
* @param validationType The validation type to filter out
*/
const filterErrors = (
_errors: ValidationError[],
validationTypeToFilterOut: string | string[] = VALIDATION_TYPES.FIELD
): ValidationError[] => {
const validationTypeToArray = Array.isArray(validationTypeToFilterOut)
? (validationTypeToFilterOut as string[])
: ([validationTypeToFilterOut] as string[]);
return _errors.filter((error) =>
validationTypeToArray.every((_type) => error.validationType !== _type)
);
};
/**
* If the field has some "formatters" defined in its config, run them in series and return
* the transformed value. This handler is called whenever the field value changes, right before
* updating the "value" state.
*/
const formatInputValue = useCallback(
(inputValue: unknown): I => {
const isEmptyString = typeof inputValue === 'string' && inputValue.trim() === '';
if (isEmptyString || !formatters) {
return inputValue as I;
}
const formData = __getFormData$().value;
return formatters.reduce((output, formatter) => formatter(output, formData), inputValue) as I;
},
[formatters, __getFormData$]
);
const runValidationsOnValueChange = useCallback(
async (done: () => void) => {
const changeIteration = ++changeCounter.current;
const startTime = Date.now();
// We call "validateFields" on the form which in turn will call
// our "validate()" function here below.
// The form is the coordinator and has access to all of the fields. We can
// this way validate multiple field whenever one field value changes.
await validateFields(fieldsToValidateOnChange ?? [path]);
if (!isMounted.current) {
return;
}
/**
* If we have set a delay to display possible validation error message after the field value has changed we
* 1. check that this is the last "change iteration" (--> the last keystroke from the user)
* 2. verify how long we've already waited for to run the validations (those can be async and make HTTP requests).
* 3. (if needed) add a timeout to set the "isChangingValue" state back to "false".
*/
if (changeIteration === changeCounter.current) {
if (valueChangeDebounceTime > 0) {
const timeElapsed = Date.now() - startTime;
if (timeElapsed < valueChangeDebounceTime) {
const timeLeftToWait = valueChangeDebounceTime - timeElapsed;
debounceTimeout.current = setTimeout(() => {
debounceTimeout.current = null;
done();
}, timeLeftToWait);
return;
}
}
done();
}
},
[path, valueChangeDebounceTime, fieldsToValidateOnChange, validateFields]
);
// Cancel any inflight validation (e.g an HTTP Request)
const cancelInflightValidation = useCallback(() => {
if (inflightValidation.current && typeof inflightValidation.current.cancel === 'function') {
inflightValidation.current.cancel();
inflightValidation.current = null;
}
}, []);
/**
* Run all the validations in sequence. If any of the validations is marked as asynchronous
* ("isAsync: true") this method will be asynchronous.
* The reason why we maintain both a "sync" and "async" option for field.validate() is because
* in some cases validating a field must be synchronous (e.g. when adding an item to the EuiCombobox,
* we want to first validate the value before adding it. The "onCreateOption" handler expects a boolean
* to be returned synchronously).
* Keeping both alternative (sync and async) is then a good thing to avoid refactoring dependencies (and
* the whole jungle with it!).
*/
const runValidations = useCallback(
(
{
formData,
value: valueToValidate,
onlyBlocking: runOnlyBlockingValidations,
validationTypeToValidate,
}: {
formData: any;
value: I;
onlyBlocking: boolean;
validationTypeToValidate: string;
},
clearFieldErrors: FieldHook['clearErrors']
): ValidationError[] | Promise<ValidationError[]> => {
if (!validations) {
return [];
}
// -- helpers
const doByPassValidation = ({
type: validationType,
isBlocking, // @ts-expect-error upgrade typescript v4.9.5
}: ValidationConfig<FormType, string, I>) => {
if (validationType !== undefined && validationType !== validationTypeToValidate) {
return true;
}
if (runOnlyBlockingValidations && isBlocking === false) {
return true;
}
return false;
};
const enhanceValidationError = (
validationError: ValidationError,
// @ts-expect-error upgrade typescript v4.9.5
validation: ValidationConfig<FormType, string, I>,
validationType: string
) => ({
...validationError,
// We add an "__isBlocking__" property to know if this error is a blocker or no.
// Most validation errors are blockers but in some cases a validation is more a warning than an error
// (e.g when adding an item to the EuiComboBox item. The item might be invalid and can't be added
// but the field (the array of items) is still valid).
__isBlocking__: validationError.__isBlocking__ ?? validation.isBlocking,
validationType,
});
const runAsync = async () => {
const validationErrors: ValidationError[] = [];
for (const validation of validations) {
const {
validator,
exitOnFail = true,
type: validationType = VALIDATION_TYPES.FIELD,
} = validation;
if (doByPassValidation(validation)) {
continue;
}
inflightValidation.current = validator({
value: valueToValidate,
errors: validationErrors,
// @ts-expect-error upgrade typescript v4.9.5
form: { getFormData, getFields },
formData,
path,
customData: { provider: validationDataProvider, value: validationData },
}) as ValidationCancelablePromise;
const validationResult = await inflightValidation.current;
inflightValidation.current = null;
if (!validationResult) {
continue;
}
validationErrors.push(
enhanceValidationError(validationResult, validation, validationType)
);
if (exitOnFail) {
break;
}
}
return validationErrors;
};
const runSync = () => {
const validationErrors: ValidationError[] = [];
for (const validation of validations) {
const {
validator,
exitOnFail = true,
type: validationType = VALIDATION_TYPES.FIELD,
} = validation;
if (doByPassValidation(validation)) {
continue;
}
const validationResult = validator({
value: valueToValidate,
errors: validationErrors,
// @ts-expect-error upgrade typescript v4.9.5
form: { getFormData, getFields },
formData,
path,
customData: { provider: validationDataProvider, value: validationData },
});
if (!validationResult) {
continue;
}
if (!!validationResult.then) {
// The validator returned a Promise: abort and run the validations asynchronously.
// This is a fallback mechansim, it is recommended to explicitly mark a validation
// as asynchronous with the "isAsync" flag to avoid runnning twice the same validation
// (and possible HTTP requests).
// We keep a reference to the inflight promise so we can cancel it.
inflightValidation.current = validationResult as ValidationCancelablePromise;
cancelInflightValidation();
return runAsync();
}
validationErrors.push(
enhanceValidationError(validationResult as ValidationError, validation, validationType)
);
if (exitOnFail) {
break;
}
}
return validationErrors;
};
// -- end helpers
clearFieldErrors([
validationTypeToValidate ?? VALIDATION_TYPES.FIELD,
VALIDATION_TYPES.ASYNC, // Immediately clear errors for "async" type validations.
]);
cancelInflightValidation();
if (hasAsyncValidation) {
return runAsync();
}
return runSync();
},
[
cancelInflightValidation,
validations,
hasAsyncValidation,
getFormData,
getFields,
path,
validationData,
validationDataProvider,
]
);
// ----------------------------------
// -- Internal API
// ----------------------------------
const serializeValue: FieldHook<T, I>['__serializeValue'] = useCallback(
(internalValue: I = value) => {
return serializer ? serializer(internalValue) : (internalValue as unknown as T);
},
[serializer, value]
);
// ----------------------------------
// -- Public API
// ----------------------------------
const clearErrors: FieldHook['clearErrors'] = useCallback(
(validationType = VALIDATION_TYPES.FIELD) => {
setStateErrors((previousErrors) => filterErrors(previousErrors, validationType));
},
[]
);
const validate: FieldHook<T, I>['validate'] = useCallback(
(validationConfig = {}) => {
const {
formData = __getFormData$().value,
value: valueToValidate = value,
validationType = VALIDATION_TYPES.FIELD,
onlyBlocking = false,
} = validationConfig;
setValidating(true);
// By the time our validate function has reached completion, it’s possible
// that we have called validate() again. If this is the case, we need
// to ignore the results of this invocation and only use the results of
// the most recent invocation to update the error state for a field
const validateIteration = ++validateCounter.current;
const onValidationResult = (_validationErrors: ValidationError[]): FieldValidateResponse => {
if (validateIteration === validateCounter.current && isMounted.current) {
// This is the most recent invocation
setValidating(false);
setIsValidated(true);
// Update the errors array
setStateErrors((prev) => {
const filteredErrors = filterErrors(prev, validationType);
return [...filteredErrors, ..._validationErrors];
});
}
return {
isValid: _validationErrors.length === 0,
errors: _validationErrors,
};
};
const validationErrors = runValidations(
{
formData,
value: valueToValidate,
validationTypeToValidate: validationType,
onlyBlocking,
},
clearErrors
);
if (Reflect.has(validationErrors, 'then')) {
return (validationErrors as Promise<ValidationError[]>).then(onValidationResult);
}
return onValidationResult(validationErrors as ValidationError[]);
},
[__getFormData$, value, runValidations, clearErrors]
);
const setValue: FieldHook<T, I>['setValue'] = useCallback(
(newValue) => {
setStateValue((prev) => {
let _newValue = newValue;
if (typeof _newValue === 'function') {
_newValue = (_newValue as Function)(prev);
}
return formatInputValue(_newValue);
});
},
[formatInputValue]
);
const setErrors: FieldHook<T, I>['setErrors'] = useCallback((_errors) => {
setStateErrors(
_errors.map((error) => ({
validationType: VALIDATION_TYPES.FIELD,
__isBlocking__: true,
...error,
}))
);
}, []);
const onChange: FieldHook<T, I>['onChange'] = useCallback(
(event) => {
const newValue = {}.hasOwnProperty.call(event!.target, 'checked')
? event.target.checked
: event.target.value;
setValue(newValue as unknown as I);
},
[setValue]
);
const getErrorsMessages: FieldHook<T, I>['getErrorsMessages'] = useCallback(
({ errorCode, validationType = VALIDATION_TYPES.FIELD } = {}) => {
const errorMessages = errors.reduce((messages, error) => {
const isSameErrorCode = errorCode && error.code === errorCode;
const isSamevalidationType =
error.validationType === validationType ||
(validationType === VALIDATION_TYPES.FIELD &&
!{}.hasOwnProperty.call(error, 'validationType'));
if (isSameErrorCode || (typeof errorCode === 'undefined' && isSamevalidationType)) {
return messages
? `${messages}, ${error.message}` // concatenate error message
: error.message;
}
return messages;
}, '');
return errorMessages ? errorMessages : null;
},
[errors]
);
const reset: FieldHook<T, I>['reset'] = useCallback(
(resetOptions = { resetValue: true }) => {
const { resetValue = true, defaultValue: updatedDefaultValue } = resetOptions;
setPristine(true);
if (isMounted.current) {
setIsModified(false);
setValidating(false);
setIsChangingValue(false);
setIsValidated(false);
setStateErrors([]);
if (resetValue) {
const newValue = deserializeValue(updatedDefaultValue ?? defaultValue);
lastNotifiedState.current.value = newValue;
setValue(newValue);
return newValue;
}
}
},
[deserializeValue, defaultValue, setValue, setStateErrors]
);
// Don't take into account non blocker validation. Some are just warning (like trying to add a wrong ComboBox item)
const isValid = errors.filter((e) => e.__isBlocking__ !== false).length === 0;
const field = useMemo<FieldHook<T, I>>(() => {
return {
path,
type,
label,
labelAppend,
helpText,
value,
errors,
isPristine,
isDirty: !isPristine,
isModified,
isValid,
isValidating,
isValidated,
isChangingValue,
onChange,
getErrorsMessages,
setValue,
setErrors,
clearErrors,
validate,
reset,
__isIncludedInOutput: isIncludedInOutput,
__serializeValue: serializeValue,
};
}, [
path,
type,
label,
labelAppend,
helpText,
value,
isPristine,
isModified,
errors,
isValid,
isValidating,
isValidated,
isChangingValue,
isIncludedInOutput,
onChange,
getErrorsMessages,
setValue,
setErrors,
clearErrors,
validate,
reset,
serializeValue,
]);
// ----------------------------------
// -- EFFECTS
// ----------------------------------
useEffect(() => {
// Add the fieldHook object to the form "fieldsRefs" map
__addField(field);
}, [field, __addField]);
useEffect(() => {
return () => {
// We only remove the field from the form "fieldsRefs" map when its path
// changes (which in practice never occurs) or whenever the <UseField /> unmounts
__removeField(path);
// We also have to trigger validation of dependant fields
const dependantFields = fieldsToValidateOnChange?.filter((f) => f !== path);
if (dependantFields?.length) {
validateFields(dependantFields);
}
};
}, [path, __removeField, fieldsToValidateOnChange, validateFields]);
// Value change: notify prop listener (<UseField onChange={() => {...}})
// We have a separate useEffect for this as the "onChange" handler pass through prop
// might not be wrapped inside a "useCallback" and that would trigger a possible infinite
// amount of effect executions.
useEffect(() => {
if (!isMounted.current || value === undefined) {
return;
}
if (valueChangeListener && valueHasChanged) {
valueChangeListener(value);
}
}, [value, valueHasChanged, valueChangeListener]);
// Value change: update state and run validations
useEffect(() => {
if (!isMounted.current || !valueHasChanged) {
return;
}
setPristine(false);
setIsChangingValue(true);
runValidationsOnValueChange(() => {
if (isMounted.current) {
setIsChangingValue(false);
}
});
}, [valueHasChanged, runValidationsOnValueChange]);
// Value change: set "isModified" state
useEffect(() => {
setIsModified(() => {
if (typeof value === 'object') {
return JSON.stringify(value) !== JSON.stringify(initialValueDeserialized);
}
return value !== initialValueDeserialized;
});
}, [value, initialValueDeserialized]);
// Errors change: notify prop listener (<UseField onError={() => {...}} />)
useEffect(() => {
if (!isMounted.current) {
return;
}
if (errorChangeListener && errorsHaveChanged) {
errorChangeListener(errorsToString(errors));
}
}, [errors, errorsHaveChanged, errorChangeListener]);
useEffect(() => {
lastNotifiedState.current.value = value;
}, [value]);
useEffect(() => {
lastNotifiedState.current.errors = errorsToString(errors);
}, [errors]);
useEffect(() => {
isMounted.current = true;
return () => {
isMounted.current = false;
if (debounceTimeout.current) {
clearTimeout(debounceTimeout.current);
debounceTimeout.current = null;
}
};
}, []);
return field;
};