-
-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathList.tsx
198 lines (176 loc) · 6.32 KB
/
List.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
import * as React from 'react';
import warning from '@rc-component/util/lib/warning';
import type { InternalNamePath, NamePath, StoreValue, ValidatorRule, Meta } from './interface';
import FieldContext from './FieldContext';
import Field from './Field';
import { move, getNamePath } from './utils/valueUtil';
import type { ListContextProps } from './ListContext';
import ListContext from './ListContext';
export interface ListField {
name: number;
key: number;
isListField: boolean;
}
export interface ListOperations {
add: (defaultValue?: StoreValue, index?: number) => void;
remove: (index: number | number[]) => void;
move: (from: number, to: number) => void;
}
export interface ListProps<Values = any> {
name: NamePath<Values>;
rules?: ValidatorRule[];
validateTrigger?: string | string[] | false;
initialValue?: any[];
children?: (fields: ListField[], operations: ListOperations, meta: Meta) => React.ReactNode;
/** @private Passed by Form.List props. Do not use since it will break by path check. */
isListField?: boolean;
}
function List<Values = any>({
name,
initialValue,
children,
rules,
validateTrigger,
isListField,
}: ListProps<Values>) {
const context = React.useContext(FieldContext);
const wrapperListContext = React.useContext(ListContext);
const keyRef = React.useRef({
keys: [],
id: 0,
});
const keyManager = keyRef.current;
const prefixName: InternalNamePath = React.useMemo(() => {
const parentPrefixName = getNamePath(context.prefixName) || [];
return [...parentPrefixName, ...getNamePath(name)];
}, [context.prefixName, name]);
const fieldContext = React.useMemo(() => ({ ...context, prefixName }), [context, prefixName]);
// List context
const listContext = React.useMemo<ListContextProps>(
() => ({
getKey: (namePath: InternalNamePath) => {
const len = prefixName.length;
const pathName = namePath[len];
return [keyManager.keys[pathName], namePath.slice(len + 1)];
},
}),
[prefixName],
);
// User should not pass `children` as other type.
if (typeof children !== 'function') {
warning(false, 'Form.List only accepts function as children.');
return null;
}
const shouldUpdate = (prevValue: StoreValue, nextValue: StoreValue, { source }) => {
if (source === 'internal') {
return false;
}
return prevValue !== nextValue;
};
return (
<ListContext.Provider value={listContext}>
<FieldContext.Provider value={fieldContext}>
<Field
name={[]}
shouldUpdate={shouldUpdate}
rules={rules}
validateTrigger={validateTrigger}
initialValue={initialValue}
isList
isListField={isListField ?? !!wrapperListContext}
>
{({ value = [], onChange }, meta) => {
const { getFieldValue } = context;
const getNewValue = () => {
const values = getFieldValue(prefixName || []) as StoreValue[];
return values || [];
};
/**
* Always get latest value in case user update fields by `form` api.
*/
const operations: ListOperations = {
add: (defaultValue, index?: number) => {
// Mapping keys
const newValue = getNewValue();
if (index >= 0 && index <= newValue.length) {
keyManager.keys = [
...keyManager.keys.slice(0, index),
keyManager.id,
...keyManager.keys.slice(index),
];
onChange([...newValue.slice(0, index), defaultValue, ...newValue.slice(index)]);
} else {
if (
process.env.NODE_ENV !== 'production' &&
(index < 0 || index > newValue.length)
) {
warning(
false,
'The second parameter of the add function should be a valid positive number.',
);
}
keyManager.keys = [...keyManager.keys, keyManager.id];
onChange([...newValue, defaultValue]);
}
keyManager.id += 1;
},
remove: (index: number | number[]) => {
const newValue = getNewValue();
const indexSet = new Set(Array.isArray(index) ? index : [index]);
if (indexSet.size <= 0) {
return;
}
keyManager.keys = keyManager.keys.filter(
(_, keysIndex) => !indexSet.has(keysIndex),
);
// Trigger store change
onChange(newValue.filter((_, valueIndex) => !indexSet.has(valueIndex)));
},
move(from: number, to: number) {
if (from === to) {
return;
}
const newValue = getNewValue();
// Do not handle out of range
if (from < 0 || from >= newValue.length || to < 0 || to >= newValue.length) {
return;
}
keyManager.keys = move(keyManager.keys, from, to);
// Trigger store change
onChange(move(newValue, from, to));
},
};
let listValue = value || [];
if (!Array.isArray(listValue)) {
listValue = [];
if (process.env.NODE_ENV !== 'production') {
warning(
false,
`Current value of '${prefixName.join(' > ')}' is not an array type.`,
);
}
}
return children(
(listValue as StoreValue[]).map((__, index): ListField => {
let key = keyManager.keys[index];
if (key === undefined) {
keyManager.keys[index] = keyManager.id;
key = keyManager.keys[index];
keyManager.id += 1;
}
return {
name: index,
key,
isListField: true,
};
}),
operations,
meta,
);
}}
</Field>
</FieldContext.Provider>
</ListContext.Provider>
);
}
export default List;