-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathFormItem.tsx
More file actions
551 lines (480 loc) · 18 KB
/
FormItem.tsx
File metadata and controls
551 lines (480 loc) · 18 KB
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
import React, { forwardRef, ReactNode, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import {
CheckCircleFilledIcon as TdCheckCircleFilledIcon,
CloseCircleFilledIcon as TdCloseCircleFilledIcon,
ErrorCircleFilledIcon as TdErrorCircleFilledIcon,
} from 'tdesign-icons-react';
import { get, isEqual, isFunction, isObject, isString, set } from 'lodash-es';
import useConfig from '../hooks/useConfig';
import useDefaultProps from '../hooks/useDefaultProps';
import useGlobalIcon from '../hooks/useGlobalIcon';
import { useLocaleReceiver } from '../locale/LocalReceiver';
import { NATIVE_INPUT_COMP, TD_CTRL_PROP_MAP, ValidateStatus } from './const';
import { formItemDefaultProps } from './defaultProps';
import { useFormContext, useFormListContext } from './FormContext';
import { parseMessage, validate as validateModal } from './formModel';
import { HOOK_MARK } from './hooks/useForm';
import useFormItemInitialData from './hooks/useFormItemInitialData';
import useFormItemStyle from './hooks/useFormItemStyle';
import { calcFieldValue, concatName } from './utils';
import type { StyledProps } from '../common';
import type {
FieldData,
FormInstanceFunctions,
FormItemValidateMessage,
FormRule,
NamePath,
TdFormItemProps,
TdFormProps,
ValidateTriggerType,
ValueType,
} from './type';
export interface FormItemProps extends TdFormItemProps, StyledProps {
children?: React.ReactNode | React.ReactNode[] | ((form: FormInstanceFunctions) => React.ReactElement);
}
export interface FormItemInstance {
name?: NamePath;
fullPath?: NamePath[];
value?: any;
initialData?: any;
isFormList?: boolean;
formListMapRef?: React.MutableRefObject<Map<any, any>>;
getValue?: () => any;
setValue?: (newVal: any) => void;
setField?: (field: Omit<FieldData, 'name'>) => void;
validate?: (trigger?: ValidateTriggerType, showErrorMessage?: boolean) => Promise<Record<string, any>>;
validateOnly?: (trigger?: ValidateTriggerType) => Promise<Record<string, any>>;
resetField?: (type?: TdFormProps['resetType']) => void;
setValidateMessage?: (message: FormItemValidateMessage[]) => void;
getValidateMessage?: FormInstanceFunctions['getValidateMessage'];
resetValidate?: () => void;
}
const FormItem = forwardRef<FormItemInstance, FormItemProps>((originalProps, ref) => {
const [locale, t] = useLocaleReceiver('form');
const { classPrefix, form: globalFormConfig } = useConfig();
const { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } = useGlobalIcon({
CheckCircleFilledIcon: TdCheckCircleFilledIcon,
CloseCircleFilledIcon: TdCloseCircleFilledIcon,
ErrorCircleFilledIcon: TdErrorCircleFilledIcon,
});
const {
form,
colon,
layout,
requiredMark: requiredMarkFromContext,
requiredMarkPosition,
labelAlign: labelAlignFromContext,
labelWidth: labelWidthFromContext,
showErrorMessage: showErrorMessageFromContext,
disabled: disabledFromContext,
readOnly: readOnlyFromContext,
resetType: resetTypeFromContext,
rules: rulesFromContext,
statusIcon: statusIconFromContext,
errorMessage,
formMapRef,
onFormItemValueChange,
} = useFormContext();
const {
name: formListName,
fullPath: parentFullPath,
rules: formListRules,
formListMapRef,
form: formOfFormList,
} = useFormListContext();
const props = useDefaultProps<FormItemProps>(originalProps, formItemDefaultProps);
const {
children,
style,
label,
name,
status,
tips,
help,
valueFormat,
initialData,
className,
shouldUpdate,
successBorder,
statusIcon = statusIconFromContext,
rules: innerRules = getInnerRules(name, rulesFromContext, formListName, formListRules),
labelWidth = labelWidthFromContext,
labelAlign = labelAlignFromContext,
requiredMark = requiredMarkFromContext,
} = props;
/* 用于处理嵌套 Form 的情况 (例如 FormList 内有一个 Dialog + Form) */
const isSameForm = useMemo(() => isEqual(form, formOfFormList), [form, formOfFormList]);
const fullPath = useMemo(() => {
const validParentFullPath = formListName && isSameForm ? parentFullPath : undefined;
return concatName(validParentFullPath, name);
}, [formListName, parentFullPath, name, isSameForm]);
const { defaultInitialData } = useFormItemInitialData(name, fullPath, initialData, children);
const [, forceUpdate] = useState({}); // custom render state
const [freeShowErrorMessage, setFreeShowErrorMessage] = useState(undefined);
const [errorList, setErrorList] = useState([]);
const [successList, setSuccessList] = useState([]);
const [verifyStatus, setVerifyStatus] = useState('validating');
const [resetValidating, setResetValidating] = useState(false);
const [needResetField, setNeedResetField] = useState(false);
const [formValue, setFormValue] = useState(defaultInitialData);
const formItemRef = useRef<FormItemInstance>(null); // 当前 formItem 实例
const innerFormItemsRef = useRef([]);
const shouldEmitChangeRef = useRef(false); // onChange 冒泡开关
const shouldValidate = useRef(false); // 校验开关
const valueRef = useRef(formValue); // 当前最新值
const errorListMapRef = useRef(new Map());
const snakeName = []
.concat(isSameForm ? formListName : undefined, name)
.filter((item) => item !== undefined)
.toString(); // 转化 name
const errorMessages = useMemo(() => errorMessage ?? globalFormConfig.errorMessage, [errorMessage, globalFormConfig]);
const showErrorMessage = useMemo(() => {
if (typeof freeShowErrorMessage === 'boolean') return freeShowErrorMessage;
if (typeof props.showErrorMessage === 'boolean') return props.showErrorMessage;
return showErrorMessageFromContext;
}, [freeShowErrorMessage, props.showErrorMessage, showErrorMessageFromContext]);
const { formItemClass, formItemLabelClass, contentClass, labelStyle, contentStyle, helpNode, extraNode } =
useFormItemStyle({
className,
help,
tips,
snakeName,
status,
successBorder,
errorList,
successList,
layout,
verifyStatus,
label,
labelWidth,
labelAlign,
requiredMark,
requiredMarkPosition,
showErrorMessage,
innerRules,
});
// 更新 form 表单字段
const updateFormValue = (newVal: any, validate = true, shouldEmitChange = false) => {
const { setPrevStore } = form?.getInternalHooks?.(HOOK_MARK) || {};
setPrevStore?.(form?.getFieldsValue?.(true));
shouldEmitChangeRef.current = shouldEmitChange;
shouldValidate.current = validate;
valueRef.current = newVal;
const fieldValue = get(form?.store, fullPath);
if (isEqual(fieldValue, newVal)) return;
set(form?.store, fullPath, newVal);
setFormValue(newVal);
};
// 初始化 rules,最终以 formItem 上优先级最高
function getInnerRules(name, formRules, formListName, formListRules): FormRule[] {
if (Array.isArray(name)) {
return get(formRules?.[formListName], name) || get(formListRules, name) || get(formRules, name.join('.')) || [];
}
return formRules?.[name] || formListRules || [];
}
const renderSuffixIcon = () => {
if (statusIcon === false) return null;
const resultIcon = (iconSlot: ReactNode) => <span className={`${classPrefix}-form__status`}>{iconSlot}</span>;
const getDefaultIcon = () => {
const iconMap = {
success: <CheckCircleFilledIcon size="25px" />,
error: <CloseCircleFilledIcon size="25px" />,
warning: <ErrorCircleFilledIcon size="25px" />,
};
if (verifyStatus === ValidateStatus.SUCCESS) {
return resultIcon(iconMap[verifyStatus]);
}
if (errorList && errorList[0]) {
const type = errorList[0].type || 'error';
return resultIcon(iconMap[type]);
}
return null;
};
if (React.isValidElement(statusIcon)) {
// @ts-ignore
return resultIcon(React.cloneElement(statusIcon, { style: { color: 'unset' }, ...statusIcon.props }));
}
if (statusIcon === true) {
return getDefaultIcon();
}
return null;
};
async function analysisValidateResult(trigger: ValidateTriggerType) {
const result = {
successList: [],
errorList: [],
rules: [],
resultList: [],
allowSetValue: false,
};
result.rules = trigger === 'all' ? innerRules : innerRules.filter((item) => (item.trigger || 'change') === trigger);
if (!result.rules?.length) {
setResetValidating(false);
return result;
}
result.allowSetValue = true;
result.resultList = await validateModal(formValue, result.rules);
result.errorList = result.resultList
.filter((item) => item.result !== true)
.map((item) => {
Object.keys(item).forEach((key) => {
if (!item.message && errorMessages[key]) {
// eslint-disable-next-line
item.message = parseMessage(errorMessages[key], {
validate: item[key],
name: isString(label) ? label : String(name),
});
}
});
return item;
});
// 仅有自定义校验方法才会存在 successList
result.successList = result.resultList.filter(
(item) => item.result === true && item.message && item.type === 'success',
);
return result;
}
async function validate(trigger: ValidateTriggerType = 'all', showErrorMessage?: boolean) {
if (innerFormItemsRef.current.length) {
return innerFormItemsRef.current.map((innerFormItem) => innerFormItem?.validate(trigger, showErrorMessage));
}
setResetValidating(true);
// undefined | boolean
setFreeShowErrorMessage(showErrorMessage);
const {
successList: innerSuccessList,
errorList: innerErrorList,
rules: validateRules,
resultList,
allowSetValue,
} = await analysisValidateResult(trigger);
// 缓存不同 trigger 下的错误信息 all 包含了所有场景需过滤
if (innerErrorList.length && trigger !== 'all') {
errorListMapRef.current.set(trigger, innerErrorList);
} else {
errorListMapRef.current.delete(trigger);
}
// all 校验无错误信息时清空所有错误缓存
if (!innerErrorList.length && trigger === 'all') {
errorListMapRef.current.clear();
}
const cacheErrorList = [...errorListMapRef.current.values()].flat();
if (allowSetValue) {
setSuccessList(innerSuccessList);
setErrorList(cacheErrorList.length ? cacheErrorList : innerErrorList);
}
// 根据校验结果设置校验状态
if (validateRules.length) {
let status = ValidateStatus.SUCCESS;
if (innerErrorList.length || cacheErrorList.length) {
status = innerErrorList?.[0]?.type || cacheErrorList?.[0]?.type || ValidateStatus.ERROR;
}
setVerifyStatus(status);
} else {
setVerifyStatus(ValidateStatus.VALIDATING);
}
// 重置处理
if (needResetField) {
resetHandler();
}
setResetValidating(false);
return {
[snakeName]: innerErrorList.length === 0 ? true : resultList,
};
}
async function validateOnly(trigger: ValidateTriggerType = 'all') {
const { errorList: innerErrorList, resultList } = await analysisValidateResult(trigger);
return {
[snakeName]: innerErrorList.length === 0 ? true : resultList,
};
}
// blur 下触发校验
function handleItemBlur() {
const filterRules = innerRules.filter((item) => item.trigger === 'blur');
filterRules.length && validate('blur');
}
function getResetValue(resetType: TdFormProps['resetType']): ValueType {
if (resetType === 'initial') {
return defaultInitialData;
}
let emptyValue: ValueType;
if (Array.isArray(formValue)) {
emptyValue = [];
} else if (isObject(formValue)) {
emptyValue = {};
} else if (isString(formValue)) {
emptyValue = '';
}
return emptyValue;
}
function resetField(type: TdFormProps['resetType']) {
if (typeof name === 'undefined') return;
const resetType = type || resetTypeFromContext;
const resetValue = getResetValue(resetType);
// reset 不校验
updateFormValue(resetValue, false);
if (resetValidating) {
setNeedResetField(true);
} else {
resetHandler();
}
}
function resetHandler() {
setNeedResetField(false);
setErrorList([]);
setSuccessList([]);
setVerifyStatus(ValidateStatus.VALIDATING);
}
function setField(field: Omit<FieldData, 'name'>) {
const { value, status, validateMessage } = field;
if (typeof status !== 'undefined') {
setErrorList(validateMessage ? [validateMessage] : []);
setSuccessList(validateMessage ? [validateMessage] : []);
setNeedResetField(false);
setVerifyStatus(status);
}
if (typeof value !== 'undefined') {
// 手动设置 status 则不需要校验 交给用户判断
updateFormValue(value, typeof status === 'undefined' ? true : false, true);
}
}
function setValidateMessage(validateMessage: FormItemValidateMessage[]) {
if (!validateMessage || !Array.isArray(validateMessage)) return;
if (validateMessage.length === 0) {
setErrorList([]);
setVerifyStatus(ValidateStatus.SUCCESS);
return;
}
setErrorList(validateMessage);
const status = validateMessage?.[0]?.type || ValidateStatus.ERROR;
setVerifyStatus(status);
}
function getValidateMessage() {
return errorList;
}
useEffect(() => {
// 注册自定义更新回调
if (!shouldUpdate || !form) return;
const { getPrevStore, registerWatch } = form?.getInternalHooks?.(HOOK_MARK) || {};
const cancelRegister = registerWatch?.(() => {
const currStore = form?.getFieldsValue?.(true) || {};
let updateFlag = shouldUpdate as boolean;
if (isFunction(shouldUpdate)) updateFlag = shouldUpdate(getPrevStore?.(), currStore);
if (updateFlag) forceUpdate({});
});
return cancelRegister;
}, [shouldUpdate, form]);
useEffect(() => {
if (typeof name === 'undefined') return;
const isFormList = formListName && isSameForm;
const mapRef = isFormList ? formListMapRef : formMapRef;
if (!mapRef?.current) return;
// 注册实例
mapRef.current.set(fullPath, formItemRef);
// 初始化
set(form?.store, fullPath, defaultInitialData);
setFormValue(defaultInitialData);
return () => {
mapRef.current.delete(fullPath);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [snakeName, formListName]);
useEffect(() => {
// value 变化通知 watch 事件
form?.getInternalHooks?.(HOOK_MARK)?.notifyWatch?.(name);
// 控制是否需要校验
if (!shouldValidate.current) return;
if (typeof name !== 'undefined' && shouldEmitChangeRef.current) {
const fieldValue = calcFieldValue(fullPath, formValue);
onFormItemValueChange?.(fieldValue);
}
const filterRules = innerRules.filter((item) => (item.trigger || 'change') === 'change');
filterRules.length && validate('change');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formValue, snakeName]);
// 暴露 ref 实例方法
const instance: FormItemInstance = {
name,
fullPath,
value: formValue,
initialData,
isFormList: false,
getValue: () => valueRef.current,
setValue: (newVal: any) => updateFormValue(newVal, true, true),
setField,
validate,
validateOnly,
resetField,
setValidateMessage,
getValidateMessage,
resetValidate: resetHandler,
};
useImperativeHandle(ref, (): FormItemInstance => instance);
useImperativeHandle(formItemRef, (): FormItemInstance => instance);
// 传入 form 实例支持自定义渲染
if (isFunction(children)) return children(form);
return (
<div className={formItemClass} style={style}>
{label && (
<div className={formItemLabelClass} style={labelStyle}>
<label htmlFor={props?.for}>{label}</label>
{colon && t(locale.colonText)}
</div>
)}
<div className={contentClass()} style={contentStyle}>
<div className={`${classPrefix}-form__controls-content`}>
{React.Children.map(children, (child, index) => {
if (!child) return null;
if (!React.isValidElement(child)) return child;
const childType = child.type;
const isCustomComp = typeof childType === 'object' || typeof childType === 'function';
// @ts-ignore
const componentName = isCustomComp ? childType.displayName : childType;
if (componentName === 'FormItem') {
return React.cloneElement(child, {
// @ts-ignore
ref: (el) => {
if (!el) return;
innerFormItemsRef.current[index] = el;
},
});
}
const childProps = child.props as any;
const commonProps = {
disabled: disabledFromContext,
readOnly: readOnlyFromContext,
...childProps,
};
if (!isCustomComp && !NATIVE_INPUT_COMP.includes(componentName)) {
return React.cloneElement(child, commonProps);
}
let ctrlKey = 'value';
if (isCustomComp) {
ctrlKey = TD_CTRL_PROP_MAP.get(componentName) || 'value';
}
return React.cloneElement(child, {
disabled: disabledFromContext,
readOnly: readOnlyFromContext,
...childProps,
[ctrlKey]: formValue,
onChange: (value: any, ...args: any[]) => {
const newValue = valueFormat ? valueFormat(value) : value;
updateFormValue(newValue, true, true);
childProps?.onChange?.call?.(null, value, ...args);
},
onBlur: (value: any, ...args: any[]) => {
handleItemBlur();
childProps?.onBlur?.call?.(null, value, ...args);
},
});
})}
{renderSuffixIcon()}
</div>
{helpNode}
{extraNode}
</div>
</div>
);
});
FormItem.displayName = 'FormItem';
export default FormItem;