-
Notifications
You must be signed in to change notification settings - Fork 358
Expand file tree
/
Copy pathFormList.tsx
More file actions
269 lines (243 loc) · 9.12 KB
/
FormList.tsx
File metadata and controls
269 lines (243 loc) · 9.12 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
import React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { castArray, cloneDeep, get, isEqual, merge, set, unset } from 'lodash-es';
import log from '@tdesign/common-js/log/index';
import { FormListContext, useFormContext, useFormListContext } from './FormContext';
import { HOOK_MARK } from './hooks/useForm';
import { calcFieldValue, concatName, convertNameToArray, swap } from './utils';
import type { FormItemInstance } from './FormItem';
import type { FormListField, FormListFieldOperation, NamePath, TdFormListProps } from './type';
let globalKey = 0;
const FormList: React.FC<TdFormListProps> = (props) => {
const { name, rules, children } = props;
const {
formMapRef,
form,
onFormItemValueChange,
initialData: initialDataFromForm,
resetType: resetTypeFromContext,
} = useFormContext();
const { fullPath: parentFullPath, initialData: parentInitialData } = useFormListContext();
const fullPath = concatName(parentFullPath, name);
const initialData = useMemo(() => {
let propsInitialData;
if (props.initialData) {
propsInitialData = props.initialData;
} else if (parentFullPath && parentInitialData) {
const relativePath = fullPath.slice(convertNameToArray(parentFullPath).length);
propsInitialData = get(parentInitialData, relativePath);
} else {
propsInitialData = get(initialDataFromForm, fullPath);
}
return cloneDeep(propsInitialData || []);
}, [props.initialData, fullPath, parentFullPath, parentInitialData, initialDataFromForm]);
const [formListValue, setFormListValue] = useState(() => get(form?.store, fullPath) || initialData);
const [fields, setFields] = useState<FormListField[]>(() =>
formListValue.map((data, index) => ({
data: { ...data },
key: (globalKey += 1),
name: index,
isListField: true,
})),
);
// 暴露给 Form 的当前 FormList 实例
const formListRef = useRef<FormItemInstance>(null);
// 存储当前 FormList 下所有的 FormItem 实例
const formListMapRef = useRef<Map<NamePath, React.RefObject<FormItemInstance>>>(new Map());
const snakeName = []
.concat(name)
.filter((item) => item !== undefined)
.toString(); // 转化 name
const updateFormList = (newFields: any, newFormListValue: any) => {
setFields(newFields);
setFormListValue(newFormListValue);
set(form?.store, fullPath, newFormListValue);
const changeValue = calcFieldValue(fullPath, newFormListValue);
onFormItemValueChange?.(changeValue);
};
const operation: FormListFieldOperation = {
add(defaultValue?: any, insertIndex?: number) {
const newFields = [...fields];
const index = insertIndex ?? newFields.length;
newFields.splice(index, 0, {
key: (globalKey += 1),
name: index,
isListField: true,
});
// 重新计算插入位置之后所有元素的 name 索引
newFields.forEach((field, index) => Object.assign(field, { name: index }));
const newFormListValue = [...formListValue];
newFormListValue.splice(index, 0, cloneDeep(defaultValue));
updateFormList(newFields, newFormListValue);
},
remove(index: number | number[]) {
const indices = castArray(index);
const newFields = [...fields].filter((f) => !indices.includes(f.name)).map((field, i) => ({ ...field, name: i }));
const newFormListValue = [...formListValue].filter((_, i) => !indices.includes(i));
unset(form?.store, fullPath);
updateFormList(newFields, newFormListValue);
},
move(from: number, to: number) {
const newFields = [...fields];
const newFormListValue = [...formListValue];
swap(newFields, from, to);
swap(newFormListValue, from, to);
newFields[from].name = from;
newFields[to].name = to;
updateFormList(newFields, newFormListValue);
},
};
function setListFields(fieldData: any[], callback: Function) {
if (isEqual(formListValue, fieldData)) return;
const newFields = fieldData.map((_, index) => {
const currField = fields[index];
const oldItem = formListValue[index];
const newItem = fieldData[index];
const noChange = currField && isEqual(oldItem, newItem);
return {
key: noChange ? currField.key : (globalKey += 1),
name: index,
isListField: true,
};
});
Array.from(formListMapRef.current.values()).forEach((formItemRef) => {
if (!formItemRef.current) return;
const { name: childName } = formItemRef.current;
const data = get(fieldData, childName);
if (data !== undefined) callback(formItemRef, data);
});
updateFormList(newFields, cloneDeep(fieldData));
}
useEffect(() => {
if (!name || !formMapRef) return;
// 初始化
formMapRef.current.set(fullPath, formListRef);
set(form?.store, fullPath, formListValue);
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
formMapRef.current.delete(fullPath);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [snakeName]);
useEffect(() => {
// fields 变化通知 watch 事件
form?.getInternalHooks?.(HOOK_MARK)?.notifyWatch?.(name);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [form, snakeName, fields]);
useImperativeHandle(
formListRef,
(): FormItemInstance => ({
name,
fullPath,
value: formListValue,
initialData,
isFormList: true,
formListMapRef,
getValue: () => get(form?.store, fullPath),
validate: (trigger = 'all') => {
const resultList = [];
const validates = [...formListMapRef.current.values()].map((formItemRef) =>
formItemRef?.current?.validate?.(trigger),
);
return new Promise((resolve) => {
Promise.all(validates).then((validateResult) => {
validateResult.forEach((result) => {
if (typeof result !== 'object') return;
const errorValue = Object.values(result)[0];
merge(resultList, errorValue);
});
const errorItems = validateResult.filter((item) => {
if (typeof item !== 'object') return;
return Object.values(item)[0] !== true;
});
if (errorItems.length) {
resolve({ [snakeName]: resultList });
} else {
resolve({ [snakeName]: true });
}
});
});
},
setValue: (fieldData) => {
// 支持局部更新数据: { [index]: value }
if (fieldData !== null && typeof fieldData === 'object' && !Array.isArray(fieldData)) {
const currentValue = cloneDeep(get(form?.store, fullPath) || []);
Object.keys(fieldData).forEach((key) => {
const index = Number(key);
if (!Number.isNaN(index)) {
currentValue[index] = merge({}, currentValue[index], fieldData[key]);
}
});
setListFields(currentValue, (formItemRef, data) => {
formItemRef?.current?.setValue?.(data);
});
return;
}
setListFields(fieldData, (formItemRef, data) => {
formItemRef?.current?.setValue?.(data);
});
},
setField: (fieldData) => {
const { value, status } = fieldData;
const currentValue = get(form?.store, fullPath) || [];
if (isEqual(currentValue, value)) return;
setListFields(value, (formItemRef, data) => {
formItemRef?.current?.setField?.({ value: data, status });
});
},
resetField: (type) => {
const resetType = type || resetTypeFromContext;
if (resetType === 'initial') {
const currentData = get(form?.store, fullPath);
if (isEqual(currentData, initialData)) return;
setFormListValue(initialData);
const newFields = initialData?.map((data, index) => ({
data: { ...data },
key: (globalKey += 1),
name: index,
isListField: true,
}));
setFields(newFields);
set(form?.store, fullPath, initialData);
} else {
// 重置为空
setFormListValue([]);
setFields([]);
unset(form?.store, fullPath);
}
},
setValidateMessage: (fieldData) => {
[...formListMapRef.current.values()].forEach((formItemRef) => {
if (!formItemRef.current) return;
const { name } = formItemRef.current;
const data = get(fieldData, name);
formItemRef?.current?.setValidateMessage?.(data);
});
},
resetValidate: () => {
[...formListMapRef.current.values()].forEach((formItemRef) => {
formItemRef?.current?.resetValidate?.();
});
},
}),
);
if (typeof children !== 'function') {
log.error('Form', `FormList's children must be a function!`);
return null;
}
return (
<FormListContext.Provider
value={{
name,
fullPath,
rules,
formListMapRef,
initialData,
form,
}}
>
{children(fields, operation)}
</FormListContext.Provider>
);
};
FormList.displayName = 'FormList';
export default FormList;