-
-
Notifications
You must be signed in to change notification settings - Fork 266
/
Field.tsx
709 lines (592 loc) · 20.4 KB
/
Field.tsx
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
import toChildrenArray from 'rc-util/lib/Children/toArray';
import isEqual from 'rc-util/lib/isEqual';
import warning from 'rc-util/lib/warning';
import * as React from 'react';
import FieldContext, { HOOK_MARK } from './FieldContext';
import type {
EventArgs,
FieldEntity,
FormInstance,
InternalFormInstance,
InternalNamePath,
InternalValidateOptions,
Meta,
NamePath,
NotifyInfo,
Rule,
RuleError,
RuleObject,
Store,
StoreValue,
} from './interface';
import ListContext from './ListContext';
import { toArray } from './utils/typeUtil';
import { validateRules } from './utils/validateUtil';
import {
containsNamePath,
defaultGetValueFromEvent,
getNamePath,
getValue,
} from './utils/valueUtil';
const EMPTY_ERRORS: any[] = [];
export type ShouldUpdate<Values = any> =
| boolean
| ((prevValues: Values, nextValues: Values, info: { source?: string }) => boolean);
function requireUpdate(
shouldUpdate: ShouldUpdate,
prev: StoreValue,
next: StoreValue,
prevValue: StoreValue,
nextValue: StoreValue,
info: NotifyInfo,
): boolean {
if (typeof shouldUpdate === 'function') {
return shouldUpdate(prev, next, 'source' in info ? { source: info.source } : {});
}
return prevValue !== nextValue;
}
// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style
interface ChildProps {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[name: string]: any;
}
export type MetaEvent = Meta & { destroy?: boolean };
export interface InternalFieldProps<Values = any> {
children?:
| React.ReactElement
| ((control: ChildProps, meta: Meta, form: FormInstance<Values>) => React.ReactNode);
/**
* Set up `dependencies` field.
* When dependencies field update and current field is touched,
* will trigger validate rules and render.
*/
dependencies?: NamePath[];
getValueFromEvent?: (...args: EventArgs) => StoreValue;
name?: InternalNamePath;
normalize?: (value: StoreValue, prevValue: StoreValue, allValues: Store) => StoreValue;
rules?: Rule[];
shouldUpdate?: ShouldUpdate<Values>;
trigger?: string;
validateTrigger?: string | string[] | false;
/**
* Trigger will after configured milliseconds.
*/
validateDebounce?: number;
validateFirst?: boolean | 'parallel';
valuePropName?: string;
getValueProps?: (value: StoreValue) => Record<string, unknown>;
messageVariables?: Record<string, string>;
initialValue?: any;
onReset?: () => void;
onMetaChange?: (meta: MetaEvent) => void;
preserve?: boolean;
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isListField?: boolean;
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isList?: boolean;
/** @private Pass context as prop instead of context api
* since class component can not get context in constructor */
fieldContext?: InternalFormInstance;
}
export interface FieldProps<Values = any>
extends Omit<InternalFieldProps<Values>, 'name' | 'fieldContext'> {
name?: NamePath<Values>;
}
export interface FieldState {
resetCount: number;
}
// We use Class instead of Hooks here since it will cost much code by using Hooks.
class Field extends React.Component<InternalFieldProps, FieldState> implements FieldEntity {
public static contextType = FieldContext;
public static defaultProps = {
trigger: 'onChange',
valuePropName: 'value',
};
public state = {
resetCount: 0,
};
private cancelRegisterFunc: (
isListField?: boolean,
preserve?: boolean,
namePath?: InternalNamePath,
) => void | null = null;
private mounted = false;
/**
* Follow state should not management in State since it will async update by React.
* This makes first render of form can not get correct state value.
*/
private touched: boolean = false;
/**
* Mark when touched & validated. Currently only used for `dependencies`.
* Note that we do not think field with `initialValue` is dirty
* but this will be by `isFieldDirty` func.
*/
private dirty: boolean = false;
private validatePromise: Promise<string[]> | null;
private prevValidating: boolean;
private errors: string[] = EMPTY_ERRORS;
private warnings: string[] = EMPTY_ERRORS;
// ============================== Subscriptions ==============================
constructor(props: InternalFieldProps) {
super(props);
// Register on init
if (props.fieldContext) {
const { getInternalHooks }: InternalFormInstance = props.fieldContext;
const { initEntityValue } = getInternalHooks(HOOK_MARK);
initEntityValue(this);
}
}
public componentDidMount() {
const { shouldUpdate, fieldContext } = this.props;
this.mounted = true;
// Register on init
if (fieldContext) {
const { getInternalHooks }: InternalFormInstance = fieldContext;
const { registerField } = getInternalHooks(HOOK_MARK);
this.cancelRegisterFunc = registerField(this);
}
// One more render for component in case fields not ready
if (shouldUpdate === true) {
this.reRender();
}
}
public componentWillUnmount() {
this.cancelRegister();
this.triggerMetaEvent(true);
this.mounted = false;
}
public cancelRegister = () => {
const { preserve, isListField, name } = this.props;
if (this.cancelRegisterFunc) {
this.cancelRegisterFunc(isListField, preserve, getNamePath(name));
}
this.cancelRegisterFunc = null;
};
// ================================== Utils ==================================
public getNamePath = (): InternalNamePath => {
const { name, fieldContext } = this.props;
const { prefixName = [] }: InternalFormInstance = fieldContext;
return name !== undefined ? [...prefixName, ...name] : [];
};
public getRules = (): RuleObject[] => {
const { rules = [], fieldContext } = this.props;
return rules.map((rule: Rule): RuleObject => {
if (typeof rule === 'function') {
return rule(fieldContext);
}
return rule;
});
};
public reRender() {
if (!this.mounted) return;
this.forceUpdate();
}
public refresh = () => {
if (!this.mounted) return;
/**
* Clean up current node.
*/
this.setState(({ resetCount }) => ({
resetCount: resetCount + 1,
}));
};
// Event should only trigger when meta changed
private metaCache: MetaEvent = null;
public triggerMetaEvent = (destroy?: boolean) => {
const { onMetaChange } = this.props;
if (onMetaChange) {
const meta = { ...this.getMeta(), destroy };
if (!isEqual(this.metaCache, meta)) {
onMetaChange(meta);
}
this.metaCache = meta;
} else {
this.metaCache = null;
}
};
// ========================= Field Entity Interfaces =========================
// Trigger by store update. Check if need update the component
public onStoreChange: FieldEntity['onStoreChange'] = (prevStore, namePathList, info) => {
const { shouldUpdate, dependencies = [], onReset } = this.props;
const { store } = info;
const namePath = this.getNamePath();
const prevValue = this.getValue(prevStore);
const curValue = this.getValue(store);
const namePathMatch = namePathList && containsNamePath(namePathList, namePath);
// `setFieldsValue` is a quick access to update related status
if (info.type === 'valueUpdate' && info.source === 'external' && prevValue !== curValue) {
this.touched = true;
this.dirty = true;
this.validatePromise = null;
this.errors = EMPTY_ERRORS;
this.warnings = EMPTY_ERRORS;
this.triggerMetaEvent();
}
switch (info.type) {
case 'reset':
if (!namePathList || namePathMatch) {
// Clean up state
this.touched = false;
this.dirty = false;
this.validatePromise = undefined;
this.errors = EMPTY_ERRORS;
this.warnings = EMPTY_ERRORS;
this.triggerMetaEvent();
onReset?.();
this.refresh();
return;
}
break;
/**
* In case field with `preserve = false` nest deps like:
* - A = 1 => show B
* - B = 1 => show C
* - Reset A, need clean B, C
*/
case 'remove': {
if (shouldUpdate) {
this.reRender();
return;
}
break;
}
case 'setField': {
const { data } = info;
if (namePathMatch) {
if ('touched' in data) {
this.touched = data.touched;
}
if ('validating' in data && !('originRCField' in data)) {
this.validatePromise = data.validating ? Promise.resolve([]) : null;
}
if ('errors' in data) {
this.errors = data.errors || EMPTY_ERRORS;
}
if ('warnings' in data) {
this.warnings = data.warnings || EMPTY_ERRORS;
}
this.dirty = true;
this.triggerMetaEvent();
this.reRender();
return;
} else if ('value' in data && containsNamePath(namePathList, namePath, true)) {
// Contains path with value should also check
this.reRender();
return;
}
// Handle update by `setField` with `shouldUpdate`
if (
shouldUpdate &&
!namePath.length &&
requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info)
) {
this.reRender();
return;
}
break;
}
case 'dependenciesUpdate': {
/**
* Trigger when marked `dependencies` updated. Related fields will all update
*/
const dependencyList = dependencies.map(getNamePath);
// No need for `namePathMath` check and `shouldUpdate` check, since `valueUpdate` will be
// emitted earlier and they will work there
// If set it may cause unnecessary twice rerendering
if (dependencyList.some(dependency => containsNamePath(info.relatedFields, dependency))) {
this.reRender();
return;
}
break;
}
default:
// 1. If `namePath` exists in `namePathList`, means it's related value and should update
// For example <List name="list"><Field name={['list', 0]}></List>
// If `namePathList` is [['list']] (List value update), Field should be updated
// If `namePathList` is [['list', 0]] (Field value update), List shouldn't be updated
// 2.
// 2.1 If `dependencies` is set, `name` is not set and `shouldUpdate` is not set,
// don't use `shouldUpdate`. `dependencies` is view as a shortcut if `shouldUpdate`
// is not provided
// 2.2 If `shouldUpdate` provided, use customize logic to update the field
// else to check if value changed
if (
namePathMatch ||
((!dependencies.length || namePath.length || shouldUpdate) &&
requireUpdate(shouldUpdate, prevStore, store, prevValue, curValue, info))
) {
this.reRender();
return;
}
break;
}
if (shouldUpdate === true) {
this.reRender();
}
};
public validateRules = (options?: InternalValidateOptions): Promise<RuleError[]> => {
// We should fixed namePath & value to avoid developer change then by form function
const namePath = this.getNamePath();
const currentValue = this.getValue();
const { triggerName, validateOnly = false } = options || {};
// Force change to async to avoid rule OOD under renderProps field
const rootPromise = Promise.resolve().then(async (): Promise<any[]> => {
if (!this.mounted) {
return [];
}
const { validateFirst = false, messageVariables, validateDebounce } = this.props;
// Start validate
let filteredRules = this.getRules();
if (triggerName) {
filteredRules = filteredRules
.filter(rule => rule)
.filter((rule: RuleObject) => {
const { validateTrigger } = rule;
if (!validateTrigger) {
return true;
}
const triggerList = toArray(validateTrigger);
return triggerList.includes(triggerName);
});
}
// Wait for debounce. Skip if no `triggerName` since its from `validateFields / submit`
if (validateDebounce && triggerName) {
await new Promise(resolve => {
setTimeout(resolve, validateDebounce);
});
// Skip since out of date
if (this.validatePromise !== rootPromise) {
return [];
}
}
const promise = validateRules(
namePath,
currentValue,
filteredRules,
options,
validateFirst,
messageVariables,
);
promise
.catch(e => e)
.then((ruleErrors: RuleError[] = EMPTY_ERRORS) => {
if (this.validatePromise === rootPromise) {
this.validatePromise = null;
// Get errors & warnings
const nextErrors: string[] = [];
const nextWarnings: string[] = [];
ruleErrors.forEach?.(({ rule: { warningOnly }, errors = EMPTY_ERRORS }) => {
if (warningOnly) {
nextWarnings.push(...errors);
} else {
nextErrors.push(...errors);
}
});
this.errors = nextErrors;
this.warnings = nextWarnings;
this.triggerMetaEvent();
this.reRender();
}
});
return promise;
});
if (validateOnly) {
return rootPromise;
}
this.validatePromise = rootPromise;
this.dirty = true;
this.errors = EMPTY_ERRORS;
this.warnings = EMPTY_ERRORS;
this.triggerMetaEvent();
// Force trigger re-render since we need sync renderProps with new meta
this.reRender();
return rootPromise;
};
public isFieldValidating = () => !!this.validatePromise;
public isFieldTouched = () => this.touched;
public isFieldDirty = () => {
// Touched or validate or has initialValue
if (this.dirty || this.props.initialValue !== undefined) {
return true;
}
// Form set initialValue
const { fieldContext } = this.props;
const { getInitialValue } = fieldContext.getInternalHooks(HOOK_MARK);
if (getInitialValue(this.getNamePath()) !== undefined) {
return true;
}
return false;
};
public getErrors = () => this.errors;
public getWarnings = () => this.warnings;
public isListField = () => this.props.isListField;
public isList = () => this.props.isList;
public isPreserve = () => this.props.preserve;
// ============================= Child Component =============================
public getMeta = (): Meta => {
// Make error & validating in cache to save perf
this.prevValidating = this.isFieldValidating();
const meta: Meta = {
touched: this.isFieldTouched(),
validating: this.prevValidating,
errors: this.errors,
warnings: this.warnings,
name: this.getNamePath(),
validated: this.validatePromise === null,
};
return meta;
};
// Only return validate child node. If invalidate, will do nothing about field.
public getOnlyChild = (
children:
| React.ReactNode
| ((control: ChildProps, meta: Meta, context: FormInstance) => React.ReactNode),
): { child: React.ReactNode | null; isFunction: boolean } => {
// Support render props
if (typeof children === 'function') {
const meta = this.getMeta();
return {
...this.getOnlyChild(children(this.getControlled(), meta, this.props.fieldContext)),
isFunction: true,
};
}
// Filed element only
const childList = toChildrenArray(children);
if (childList.length !== 1 || !React.isValidElement(childList[0])) {
return { child: childList, isFunction: false };
}
return { child: childList[0], isFunction: false };
};
// ============================== Field Control ==============================
public getValue = (store?: Store) => {
const { getFieldsValue }: FormInstance = this.props.fieldContext;
const namePath = this.getNamePath();
return getValue(store || getFieldsValue(true), namePath);
};
public getControlled = (childProps: ChildProps = {}) => {
const {
trigger,
validateTrigger,
getValueFromEvent,
normalize,
valuePropName,
getValueProps,
fieldContext,
} = this.props;
const mergedValidateTrigger =
validateTrigger !== undefined ? validateTrigger : fieldContext.validateTrigger;
const namePath = this.getNamePath();
const { getInternalHooks, getFieldsValue }: InternalFormInstance = fieldContext;
const { dispatch } = getInternalHooks(HOOK_MARK);
const value = this.getValue();
const mergedGetValueProps = getValueProps || ((val: StoreValue) => ({ [valuePropName]: val }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const originTriggerFunc: any = childProps[trigger];
const valueProps = mergedGetValueProps(value);
// warning when prop value is function
if (process.env.NODE_ENV !== 'production') {
Object.keys(valueProps).forEach(key => {
warning(typeof valueProps[key] !== 'function', `It's not recommended to generate dynamic function prop by \`getValueProps\`. Please pass it to child component directly (prop: ${key})`)
})
}
const control = {
...childProps,
...valueProps,
};
// Add trigger
control[trigger] = (...args: EventArgs) => {
// Mark as touched
this.touched = true;
this.dirty = true;
this.triggerMetaEvent();
let newValue: StoreValue;
if (getValueFromEvent) {
newValue = getValueFromEvent(...args);
} else {
newValue = defaultGetValueFromEvent(valuePropName, ...args);
}
if (normalize) {
newValue = normalize(newValue, value, getFieldsValue(true));
}
dispatch({
type: 'updateValue',
namePath,
value: newValue,
});
if (originTriggerFunc) {
originTriggerFunc(...args);
}
};
// Add validateTrigger
const validateTriggerList: string[] = toArray(mergedValidateTrigger || []);
validateTriggerList.forEach((triggerName: string) => {
// Wrap additional function of component, so that we can get latest value from store
const originTrigger = control[triggerName];
control[triggerName] = (...args: EventArgs) => {
if (originTrigger) {
originTrigger(...args);
}
// Always use latest rules
const { rules } = this.props;
if (rules && rules.length) {
// We dispatch validate to root,
// since it will update related data with other field with same name
dispatch({
type: 'validateField',
namePath,
triggerName,
});
}
};
});
return control;
};
public render() {
const { resetCount } = this.state;
const { children } = this.props;
const { child, isFunction } = this.getOnlyChild(children);
// Not need to `cloneElement` since user can handle this in render function self
let returnChildNode: React.ReactNode;
if (isFunction) {
returnChildNode = child;
} else if (React.isValidElement(child)) {
returnChildNode = React.cloneElement(
child as React.ReactElement,
this.getControlled((child as React.ReactElement).props),
);
} else {
warning(!child, '`children` of Field is not validate ReactElement.');
returnChildNode = child;
}
return <React.Fragment key={resetCount}>{returnChildNode}</React.Fragment>;
}
}
function WrapperField<Values = any>({ name, ...restProps }: FieldProps<Values>) {
const fieldContext = React.useContext(FieldContext);
const listContext = React.useContext(ListContext);
const namePath = name !== undefined ? getNamePath(name) : undefined;
let key: string = 'keep';
if (!restProps.isListField) {
key = `_${(namePath || []).join('_')}`;
}
// Warning if it's a directly list field.
// We can still support multiple level field preserve.
if (
process.env.NODE_ENV !== 'production' &&
restProps.preserve === false &&
restProps.isListField &&
namePath.length <= 1
) {
warning(false, '`preserve` should not apply on Form.List fields.');
}
return (
<Field
key={key}
name={namePath}
isListField={!!listContext}
{...restProps}
fieldContext={fieldContext}
/>
);
}
export default WrapperField;