/
useForm.ts
1044 lines (866 loc) · 30.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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { merge } from 'rc-util/lib/utils/set';
import warning from 'rc-util/lib/warning';
import * as React from 'react';
import { HOOK_MARK } from './FieldContext';
import type {
Callbacks,
FieldData,
FieldEntity,
FieldError,
FilterFunc,
FormInstance,
GetFieldsValueConfig,
InternalFieldData,
InternalFormInstance,
InternalHooks,
InternalNamePath,
InternalValidateFields,
InternalValidateOptions,
Meta,
NamePath,
NotifyInfo,
RuleError,
Store,
StoreValue,
ValidateErrorEntity,
ValidateMessages,
ValuedNotifyInfo,
WatchCallBack,
} from './interface';
import { allPromiseFinish } from './utils/asyncUtil';
import { defaultValidateMessages } from './utils/messages';
import NameMap from './utils/NameMap';
import {
cloneByNamePathList,
containsNamePath,
getNamePath,
getValue,
matchNamePath,
setValue,
} from './utils/valueUtil';
type InvalidateFieldEntity = { INVALIDATE_NAME_PATH: InternalNamePath };
interface UpdateAction {
type: 'updateValue';
namePath: InternalNamePath;
value: StoreValue;
}
interface ValidateAction {
type: 'validateField';
namePath: InternalNamePath;
triggerName: string;
}
export type ReducerAction = UpdateAction | ValidateAction;
export class FormStore {
private formHooked: boolean = false;
private forceRootUpdate: () => void;
private subscribable: boolean = true;
private store: Store = {};
private fieldEntities: FieldEntity[] = [];
private initialValues: Store = {};
private callbacks: Callbacks = {};
private validateMessages: ValidateMessages = null;
private preserve?: boolean = null;
private lastValidatePromise: Promise<FieldError[]> = null;
constructor(forceRootUpdate: () => void) {
this.forceRootUpdate = forceRootUpdate;
}
public getForm = (): InternalFormInstance => ({
getFieldValue: this.getFieldValue,
getFieldsValue: this.getFieldsValue,
getFieldError: this.getFieldError,
getFieldWarning: this.getFieldWarning,
getFieldsError: this.getFieldsError,
isFieldsTouched: this.isFieldsTouched,
isFieldTouched: this.isFieldTouched,
isFieldValidating: this.isFieldValidating,
isFieldsValidating: this.isFieldsValidating,
resetFields: this.resetFields,
setFields: this.setFields,
setFieldValue: this.setFieldValue,
setFieldsValue: this.setFieldsValue,
validateFields: this.validateFields,
submit: this.submit,
_init: true,
getInternalHooks: this.getInternalHooks,
});
// ======================== Internal Hooks ========================
private getInternalHooks = (key: string): InternalHooks | null => {
if (key === HOOK_MARK) {
this.formHooked = true;
return {
dispatch: this.dispatch,
initEntityValue: this.initEntityValue,
registerField: this.registerField,
useSubscribe: this.useSubscribe,
setInitialValues: this.setInitialValues,
destroyForm: this.destroyForm,
setCallbacks: this.setCallbacks,
setValidateMessages: this.setValidateMessages,
getFields: this.getFields,
setPreserve: this.setPreserve,
getInitialValue: this.getInitialValue,
registerWatch: this.registerWatch,
};
}
warning(false, '`getInternalHooks` is internal usage. Should not call directly.');
return null;
};
private useSubscribe = (subscribable: boolean) => {
this.subscribable = subscribable;
};
/**
* Record prev Form unmount fieldEntities which config preserve false.
* This need to be refill with initialValues instead of store value.
*/
private prevWithoutPreserves: NameMap<boolean> | null = null;
/**
* First time `setInitialValues` should update store with initial value
*/
private setInitialValues = (initialValues: Store, init: boolean) => {
this.initialValues = initialValues || {};
if (init) {
let nextStore = merge(initialValues, this.store);
// We will take consider prev form unmount fields.
// When the field is not `preserve`, we need fill this with initialValues instead of store.
// eslint-disable-next-line array-callback-return
this.prevWithoutPreserves?.map(({ key: namePath }) => {
nextStore = setValue(nextStore, namePath, getValue(initialValues, namePath));
});
this.prevWithoutPreserves = null;
this.updateStore(nextStore);
}
};
private destroyForm = () => {
const prevWithoutPreserves = new NameMap<boolean>();
this.getFieldEntities(true).forEach(entity => {
if (!this.isMergedPreserve(entity.isPreserve())) {
prevWithoutPreserves.set(entity.getNamePath(), true);
}
});
this.prevWithoutPreserves = prevWithoutPreserves;
};
private getInitialValue = (namePath: InternalNamePath) => {
const initValue = getValue(this.initialValues, namePath);
// Not cloneDeep when without `namePath`
return namePath.length ? merge(initValue) : initValue;
};
private setCallbacks = (callbacks: Callbacks) => {
this.callbacks = callbacks;
};
private setValidateMessages = (validateMessages: ValidateMessages) => {
this.validateMessages = validateMessages;
};
private setPreserve = (preserve?: boolean) => {
this.preserve = preserve;
};
// ============================= Watch ============================
private watchList: WatchCallBack[] = [];
private registerWatch: InternalHooks['registerWatch'] = callback => {
this.watchList.push(callback);
return () => {
this.watchList = this.watchList.filter(fn => fn !== callback);
};
};
private notifyWatch = (namePath: InternalNamePath[] = []) => {
// No need to cost perf when nothing need to watch
if (this.watchList.length) {
const values = this.getFieldsValue();
const allValues = this.getFieldsValue(true);
this.watchList.forEach(callback => {
callback(values, allValues, namePath);
});
}
};
// ========================== Dev Warning =========================
private timeoutId: any = null;
private warningUnhooked = () => {
if (process.env.NODE_ENV !== 'production' && !this.timeoutId && typeof window !== 'undefined') {
this.timeoutId = setTimeout(() => {
this.timeoutId = null;
if (!this.formHooked) {
warning(
false,
'Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?',
);
}
});
}
};
// ============================ Store =============================
private updateStore = (nextStore: Store) => {
this.store = nextStore;
};
// ============================ Fields ============================
/**
* Get registered field entities.
* @param pure Only return field which has a `name`. Default: false
*/
private getFieldEntities = (pure: boolean = false) => {
if (!pure) {
return this.fieldEntities;
}
return this.fieldEntities.filter(field => field.getNamePath().length);
};
private getFieldsMap = (pure: boolean = false) => {
const cache: NameMap<FieldEntity> = new NameMap();
this.getFieldEntities(pure).forEach(field => {
const namePath = field.getNamePath();
cache.set(namePath, field);
});
return cache;
};
private getFieldEntitiesForNamePathList = (
nameList?: NamePath[],
): (FieldEntity | InvalidateFieldEntity)[] => {
if (!nameList) {
return this.getFieldEntities(true);
}
const cache = this.getFieldsMap(true);
return nameList.map(name => {
const namePath = getNamePath(name);
return cache.get(namePath) || { INVALIDATE_NAME_PATH: getNamePath(name) };
});
};
private getFieldsValue = (
nameList?: NamePath[] | true | GetFieldsValueConfig,
filterFunc?: FilterFunc,
) => {
this.warningUnhooked();
// Fill args
let mergedNameList: NamePath[] | true;
let mergedFilterFunc: FilterFunc;
let mergedStrict: boolean;
if (nameList === true || Array.isArray(nameList)) {
mergedNameList = nameList;
mergedFilterFunc = filterFunc;
} else if (nameList && typeof nameList === 'object') {
mergedStrict = nameList.strict;
mergedFilterFunc = nameList.filter;
}
if (mergedNameList === true && !mergedFilterFunc) {
return this.store;
}
const fieldEntities = this.getFieldEntitiesForNamePathList(
Array.isArray(mergedNameList) ? mergedNameList : null,
);
const filteredNameList: NamePath[] = [];
fieldEntities.forEach((entity: FieldEntity | InvalidateFieldEntity) => {
const namePath =
'INVALIDATE_NAME_PATH' in entity ? entity.INVALIDATE_NAME_PATH : entity.getNamePath();
// Ignore when it's a list item and not specific the namePath,
// since parent field is already take in count
if (mergedStrict) {
if ((entity as FieldEntity).isList?.()) {
return;
}
} else if (!mergedNameList && (entity as FieldEntity).isListField?.()) {
return;
}
if (!mergedFilterFunc) {
filteredNameList.push(namePath);
} else {
const meta: Meta = 'getMeta' in entity ? entity.getMeta() : null;
if (mergedFilterFunc(meta)) {
filteredNameList.push(namePath);
}
}
});
return cloneByNamePathList(this.store, filteredNameList.map(getNamePath));
};
private getFieldValue = (name: NamePath) => {
this.warningUnhooked();
const namePath: InternalNamePath = getNamePath(name);
return getValue(this.store, namePath);
};
private getFieldsError = (nameList?: NamePath[]) => {
this.warningUnhooked();
const fieldEntities = this.getFieldEntitiesForNamePathList(nameList);
return fieldEntities.map((entity, index) => {
if (entity && !('INVALIDATE_NAME_PATH' in entity)) {
return {
name: entity.getNamePath(),
errors: entity.getErrors(),
warnings: entity.getWarnings(),
};
}
return {
name: getNamePath(nameList[index]),
errors: [],
warnings: [],
};
});
};
private getFieldError = (name: NamePath): string[] => {
this.warningUnhooked();
const namePath = getNamePath(name);
const fieldError = this.getFieldsError([namePath])[0];
return fieldError.errors;
};
private getFieldWarning = (name: NamePath): string[] => {
this.warningUnhooked();
const namePath = getNamePath(name);
const fieldError = this.getFieldsError([namePath])[0];
return fieldError.warnings;
};
private isFieldsTouched = (...args) => {
this.warningUnhooked();
const [arg0, arg1] = args;
let namePathList: InternalNamePath[] | null;
let isAllFieldsTouched = false;
if (args.length === 0) {
namePathList = null;
} else if (args.length === 1) {
if (Array.isArray(arg0)) {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = false;
} else {
namePathList = null;
isAllFieldsTouched = arg0;
}
} else {
namePathList = arg0.map(getNamePath);
isAllFieldsTouched = arg1;
}
const fieldEntities = this.getFieldEntities(true);
const isFieldTouched = (field: FieldEntity) => field.isFieldTouched();
// ===== Will get fully compare when not config namePathList =====
if (!namePathList) {
return isAllFieldsTouched
? fieldEntities.every(entity => isFieldTouched(entity) || entity.isList())
: fieldEntities.some(isFieldTouched);
}
// Generate a nest tree for validate
const map = new NameMap<FieldEntity[]>();
namePathList.forEach(shortNamePath => {
map.set(shortNamePath, []);
});
fieldEntities.forEach(field => {
const fieldNamePath = field.getNamePath();
// Find matched entity and put into list
namePathList.forEach(shortNamePath => {
if (shortNamePath.every((nameUnit, i) => fieldNamePath[i] === nameUnit)) {
map.update(shortNamePath, list => [...list, field]);
}
});
});
// Check if NameMap value is touched
const isNamePathListTouched = (entities: FieldEntity[]) => entities.some(isFieldTouched);
const namePathListEntities = map.map(({ value }) => value);
return isAllFieldsTouched
? namePathListEntities.every(isNamePathListTouched)
: namePathListEntities.some(isNamePathListTouched);
};
private isFieldTouched = (name: NamePath) => {
this.warningUnhooked();
return this.isFieldsTouched([name]);
};
private isFieldsValidating = (nameList?: NamePath[]) => {
this.warningUnhooked();
const fieldEntities = this.getFieldEntities();
if (!nameList) {
return fieldEntities.some(testField => testField.isFieldValidating());
}
const namePathList: InternalNamePath[] = nameList.map(getNamePath);
return fieldEntities.some(testField => {
const fieldNamePath = testField.getNamePath();
return containsNamePath(namePathList, fieldNamePath) && testField.isFieldValidating();
});
};
private isFieldValidating = (name: NamePath) => {
this.warningUnhooked();
return this.isFieldsValidating([name]);
};
/**
* Reset Field with field `initialValue` prop.
* Can pass `entities` or `namePathList` or just nothing.
*/
private resetWithFieldInitialValue = (
info: {
entities?: FieldEntity[];
namePathList?: InternalNamePath[];
/** Skip reset if store exist value. This is only used for field register reset */
skipExist?: boolean;
} = {},
) => {
// Create cache
const cache: NameMap<Set<{ entity: FieldEntity; value: any }>> = new NameMap();
const fieldEntities = this.getFieldEntities(true);
fieldEntities.forEach(field => {
const { initialValue } = field.props;
const namePath = field.getNamePath();
// Record only if has `initialValue`
if (initialValue !== undefined) {
const records = cache.get(namePath) || new Set();
records.add({ entity: field, value: initialValue });
cache.set(namePath, records);
}
});
// Reset
const resetWithFields = (entities: FieldEntity[]) => {
entities.forEach(field => {
const { initialValue } = field.props;
if (initialValue !== undefined) {
const namePath = field.getNamePath();
const formInitialValue = this.getInitialValue(namePath);
if (formInitialValue !== undefined) {
// Warning if conflict with form initialValues and do not modify value
warning(
false,
`Form already set 'initialValues' with path '${namePath.join(
'.',
)}'. Field can not overwrite it.`,
);
} else {
const records = cache.get(namePath);
if (records && records.size > 1) {
// Warning if multiple field set `initialValue`and do not modify value
warning(
false,
`Multiple Field with path '${namePath.join(
'.',
)}' set 'initialValue'. Can not decide which one to pick.`,
);
} else if (records) {
const originValue = this.getFieldValue(namePath);
const isListField = field.isListField();
// Set `initialValue`
if (!isListField && (!info.skipExist || originValue === undefined)) {
this.updateStore(setValue(this.store, namePath, [...records][0].value));
}
}
}
}
});
};
let requiredFieldEntities: FieldEntity[];
if (info.entities) {
requiredFieldEntities = info.entities;
} else if (info.namePathList) {
requiredFieldEntities = [];
info.namePathList.forEach(namePath => {
const records = cache.get(namePath);
if (records) {
requiredFieldEntities.push(...[...records].map(r => r.entity));
}
});
} else {
requiredFieldEntities = fieldEntities;
}
resetWithFields(requiredFieldEntities);
};
private resetFields = (nameList?: NamePath[]) => {
this.warningUnhooked();
const prevStore = this.store;
if (!nameList) {
this.updateStore(merge(this.initialValues));
this.resetWithFieldInitialValue();
this.notifyObservers(prevStore, null, { type: 'reset' });
this.notifyWatch();
return;
}
// Reset by `nameList`
const namePathList: InternalNamePath[] = nameList.map(getNamePath);
namePathList.forEach(namePath => {
const initialValue = this.getInitialValue(namePath);
this.updateStore(setValue(this.store, namePath, initialValue));
});
this.resetWithFieldInitialValue({ namePathList });
this.notifyObservers(prevStore, namePathList, { type: 'reset' });
this.notifyWatch(namePathList);
};
private setFields = (fields: FieldData[]) => {
this.warningUnhooked();
const prevStore = this.store;
const namePathList: InternalNamePath[] = [];
fields.forEach((fieldData: FieldData) => {
const { name, ...data } = fieldData;
const namePath = getNamePath(name);
namePathList.push(namePath);
// Value
if ('value' in data) {
this.updateStore(setValue(this.store, namePath, data.value));
}
this.notifyObservers(prevStore, [namePath], {
type: 'setField',
data: fieldData,
});
});
this.notifyWatch(namePathList);
};
private getFields = (): InternalFieldData[] => {
const entities = this.getFieldEntities(true);
const fields = entities.map((field: FieldEntity): InternalFieldData => {
const namePath = field.getNamePath();
const meta = field.getMeta();
const fieldData = {
...meta,
name: namePath,
value: this.getFieldValue(namePath),
};
Object.defineProperty(fieldData, 'originRCField', {
value: true,
});
return fieldData;
});
return fields;
};
// =========================== Observer ===========================
/**
* This only trigger when a field is on constructor to avoid we get initialValue too late
*/
private initEntityValue = (entity: FieldEntity) => {
const { initialValue } = entity.props;
if (initialValue !== undefined) {
const namePath = entity.getNamePath();
const prevValue = getValue(this.store, namePath);
if (prevValue === undefined) {
this.updateStore(setValue(this.store, namePath, initialValue));
}
}
};
private isMergedPreserve = (fieldPreserve?: boolean) => {
const mergedPreserve = fieldPreserve !== undefined ? fieldPreserve : this.preserve;
return mergedPreserve ?? true;
};
private registerField = (entity: FieldEntity) => {
this.fieldEntities.push(entity);
const namePath = entity.getNamePath();
this.notifyWatch([namePath]);
// Set initial values
if (entity.props.initialValue !== undefined) {
const prevStore = this.store;
this.resetWithFieldInitialValue({ entities: [entity], skipExist: true });
this.notifyObservers(prevStore, [entity.getNamePath()], {
type: 'valueUpdate',
source: 'internal',
});
}
// un-register field callback
return (isListField?: boolean, preserve?: boolean, subNamePath: InternalNamePath = []) => {
this.fieldEntities = this.fieldEntities.filter(item => item !== entity);
// Clean up store value if not preserve
if (!this.isMergedPreserve(preserve) && (!isListField || subNamePath.length > 1)) {
const defaultValue = isListField ? undefined : this.getInitialValue(namePath);
if (
namePath.length &&
this.getFieldValue(namePath) !== defaultValue &&
this.fieldEntities.every(
field =>
// Only reset when no namePath exist
!matchNamePath(field.getNamePath(), namePath),
)
) {
const prevStore = this.store;
this.updateStore(setValue(prevStore, namePath, defaultValue, true));
// Notify that field is unmount
this.notifyObservers(prevStore, [namePath], { type: 'remove' });
// Dependencies update
this.triggerDependenciesUpdate(prevStore, namePath);
}
}
this.notifyWatch([namePath]);
};
};
private dispatch = (action: ReducerAction) => {
switch (action.type) {
case 'updateValue': {
const { namePath, value } = action;
this.updateValue(namePath, value);
break;
}
case 'validateField': {
const { namePath, triggerName } = action;
this.validateFields([namePath], { triggerName });
break;
}
default:
// Currently we don't have other action. Do nothing.
}
};
private notifyObservers = (
prevStore: Store,
namePathList: InternalNamePath[] | null,
info: NotifyInfo,
) => {
if (this.subscribable) {
const mergedInfo: ValuedNotifyInfo = {
...info,
store: this.getFieldsValue(true),
};
this.getFieldEntities().forEach(({ onStoreChange }) => {
onStoreChange(prevStore, namePathList, mergedInfo);
});
} else {
this.forceRootUpdate();
}
};
/**
* Notify dependencies children with parent update
* We need delay to trigger validate in case Field is under render props
*/
private triggerDependenciesUpdate = (prevStore: Store, namePath: InternalNamePath) => {
const childrenFields = this.getDependencyChildrenFields(namePath);
if (childrenFields.length) {
this.validateFields(childrenFields);
}
this.notifyObservers(prevStore, childrenFields, {
type: 'dependenciesUpdate',
relatedFields: [namePath, ...childrenFields],
});
return childrenFields;
};
private updateValue = (name: NamePath, value: StoreValue) => {
const namePath = getNamePath(name);
const prevStore = this.store;
this.updateStore(setValue(this.store, namePath, value));
this.notifyObservers(prevStore, [namePath], {
type: 'valueUpdate',
source: 'internal',
});
this.notifyWatch([namePath]);
// Dependencies update
const childrenFields = this.triggerDependenciesUpdate(prevStore, namePath);
// trigger callback function
const { onValuesChange } = this.callbacks;
if (onValuesChange) {
const changedValues = cloneByNamePathList(this.store, [namePath]);
onValuesChange(changedValues, this.getFieldsValue());
}
this.triggerOnFieldsChange([namePath, ...childrenFields]);
};
// Let all child Field get update.
private setFieldsValue = (store: Store) => {
this.warningUnhooked();
const prevStore = this.store;
if (store) {
const nextStore = merge(this.store, store);
this.updateStore(nextStore);
}
this.notifyObservers(prevStore, null, {
type: 'valueUpdate',
source: 'external',
});
this.notifyWatch();
};
private setFieldValue = (name: NamePath, value: any) => {
this.setFields([
{
name,
value,
},
]);
};
private getDependencyChildrenFields = (rootNamePath: InternalNamePath): InternalNamePath[] => {
const children: Set<FieldEntity> = new Set();
const childrenFields: InternalNamePath[] = [];
const dependencies2fields: NameMap<Set<FieldEntity>> = new NameMap();
/**
* Generate maps
* Can use cache to save perf if user report performance issue with this
*/
this.getFieldEntities().forEach(field => {
const { dependencies } = field.props;
(dependencies || []).forEach(dependency => {
const dependencyNamePath = getNamePath(dependency);
dependencies2fields.update(dependencyNamePath, (fields = new Set()) => {
fields.add(field);
return fields;
});
});
});
const fillChildren = (namePath: InternalNamePath) => {
const fields = dependencies2fields.get(namePath) || new Set();
fields.forEach(field => {
if (!children.has(field)) {
children.add(field);
const fieldNamePath = field.getNamePath();
if (field.isFieldDirty() && fieldNamePath.length) {
childrenFields.push(fieldNamePath);
fillChildren(fieldNamePath);
}
}
});
};
fillChildren(rootNamePath);
return childrenFields;
};
private triggerOnFieldsChange = (
namePathList: InternalNamePath[],
filedErrors?: FieldError[],
) => {
const { onFieldsChange } = this.callbacks;
if (onFieldsChange) {
const fields = this.getFields();
/**
* Fill errors since `fields` may be replaced by controlled fields
*/
if (filedErrors) {
const cache = new NameMap<string[]>();
filedErrors.forEach(({ name, errors }) => {
cache.set(name, errors);
});
fields.forEach(field => {
// eslint-disable-next-line no-param-reassign
field.errors = cache.get(field.name) || field.errors;
});
}
const changedFields = fields.filter(({ name: fieldName }) =>
containsNamePath(namePathList, fieldName as InternalNamePath),
);
if (changedFields.length) {
onFieldsChange(changedFields, fields);
}
}
};
// =========================== Validate ===========================
private validateFields: InternalValidateFields = (arg1?: any, arg2?: any) => {
this.warningUnhooked();
let nameList: NamePath[];
let options: InternalValidateOptions;
if (Array.isArray(arg1) || typeof arg1 === 'string' || typeof arg2 === 'string') {
nameList = arg1;
options = arg2;
} else {
options = arg1;
}
const provideNameList = !!nameList;
const namePathList: InternalNamePath[] | undefined = provideNameList
? nameList.map(getNamePath)
: [];
// Collect result in promise list
const promiseList: Promise<FieldError>[] = [];
// We temp save the path which need trigger for `onFieldsChange`
const TMP_SPLIT = String(Date.now());
const validateNamePathList = new Set<string>();
const { recursive, dirty } = options || {};
this.getFieldEntities(true).forEach((field: FieldEntity) => {
// Add field if not provide `nameList`
if (!provideNameList) {
namePathList.push(field.getNamePath());
}
// Skip if without rule
if (!field.props.rules || !field.props.rules.length) {
return;
}
// Skip if only validate dirty field
if (dirty && !field.isFieldDirty()) {
return;
}
const fieldNamePath = field.getNamePath();
validateNamePathList.add(fieldNamePath.join(TMP_SPLIT));
// Add field validate rule in to promise list
if (!provideNameList || containsNamePath(namePathList, fieldNamePath, recursive)) {
const promise = field.validateRules({
validateMessages: {
...defaultValidateMessages,
...this.validateMessages,
},
...options,
});
// Wrap promise with field
promiseList.push(
promise
.then<any, RuleError>(() => ({ name: fieldNamePath, errors: [], warnings: [] }))
.catch((ruleErrors: RuleError[]) => {
const mergedErrors: string[] = [];
const mergedWarnings: string[] = [];
ruleErrors.forEach?.(({ rule: { warningOnly }, errors }) => {
if (warningOnly) {
mergedWarnings.push(...errors);
} else {
mergedErrors.push(...errors);
}
});
if (mergedErrors.length) {
return Promise.reject({
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings,
});
}
return {
name: fieldNamePath,
errors: mergedErrors,
warnings: mergedWarnings,
};
}),
);
}
});
const summaryPromise = allPromiseFinish(promiseList);
this.lastValidatePromise = summaryPromise;
// Notify fields with rule that validate has finished and need update
summaryPromise
.catch(results => results)
.then((results: FieldError[]) => {
const resultNamePathList: InternalNamePath[] = results.map(({ name }) => name);
this.notifyObservers(this.store, resultNamePathList, {
type: 'validateFinish',
});
this.triggerOnFieldsChange(resultNamePathList, results);
});
const returnPromise: Promise<Store | ValidateErrorEntity | string[]> = summaryPromise
.then((): Promise<Store | string[]> => {
if (this.lastValidatePromise === summaryPromise) {
return Promise.resolve(this.getFieldsValue(namePathList));
}
return Promise.reject<string[]>([]);
})
.catch((results: { name: InternalNamePath; errors: string[] }[]) => {
const errorList = results.filter(result => result && result.errors.length);
return Promise.reject({
values: this.getFieldsValue(namePathList),
errorFields: errorList,
outOfDate: this.lastValidatePromise !== summaryPromise,
});
});
// Do not throw in console
returnPromise.catch<ValidateErrorEntity>(e => e);
// `validating` changed. Trigger `onFieldsChange`
const triggerNamePathList = namePathList.filter(namePath =>
validateNamePathList.has(namePath.join(TMP_SPLIT)),
);
this.triggerOnFieldsChange(triggerNamePathList);
return returnPromise as Promise<Store>;
};
// ============================ Submit ============================
private submit = () => {
this.warningUnhooked();