-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathuseFieldArray.ts
More file actions
285 lines (241 loc) · 8.39 KB
/
useFieldArray.ts
File metadata and controls
285 lines (241 loc) · 8.39 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
import { Ref, unref, ref, onBeforeUnmount, watch, MaybeRefOrGetter, toValue } from 'vue';
import { isNullOrUndefined } from '../../shared';
import { FormContextKey } from './symbols';
import { FieldArrayContext, FieldEntry, PrivateFieldArrayContext, PrivateFormContext } from './types';
import { deepCopy, computedDeep, getFromPath, injectWithSelf, warn, isEqual, setInPath } from './utils';
export function useFieldArray<TValue = unknown>(arrayPath: MaybeRefOrGetter<string>): FieldArrayContext<TValue> {
const form = injectWithSelf(FormContextKey, undefined) as PrivateFormContext;
const fields: Ref<FieldEntry<TValue>[]> = ref([]);
const noOp = () => {};
const noOpApi: FieldArrayContext<TValue> = {
fields,
remove: noOp,
push: noOp,
swap: noOp,
insert: noOp,
update: noOp,
replace: noOp,
prepend: noOp,
move: noOp,
};
if (!form) {
if (__DEV__) {
warn(
'FieldArray requires being a child of `<Form/>` or `useForm` being called before it. Array fields may not work correctly',
);
}
return noOpApi;
}
if (!unref(arrayPath)) {
if (__DEV__) {
warn('FieldArray requires a field path to be provided, did you forget to pass the `name` prop?');
}
return noOpApi;
}
const alreadyExists = form.fieldArrays.find(a => unref(a.path) === unref(arrayPath));
if (alreadyExists) {
return alreadyExists as PrivateFieldArrayContext<TValue>;
}
let entryCounter = 0;
function getCurrentValues() {
return getFromPath<TValue[]>(form?.values, toValue(arrayPath), []) || [];
}
function initFields() {
const currentValues = getCurrentValues();
if (!Array.isArray(currentValues)) {
return;
}
fields.value = currentValues.map((v, idx) => createEntry(v, idx, fields.value));
updateEntryFlags();
}
initFields();
function updateEntryFlags() {
const fieldsLength = fields.value.length;
for (let i = 0; i < fieldsLength; i++) {
const entry = fields.value[i];
entry.isFirst = i === 0;
entry.isLast = i === fieldsLength - 1;
}
}
function createEntry(value: TValue, idx?: number, currentFields?: FieldEntry<TValue>[]): FieldEntry<TValue> {
// Skips the work by returning the current entry if it already exists
// This should make the `key` prop stable and doesn't cause more re-renders than needed
// The value is computed and should update anyways
if (currentFields && !isNullOrUndefined(idx) && currentFields[idx]) {
return currentFields[idx];
}
const key = entryCounter++;
const entry: FieldEntry<TValue> = {
key,
value: computedDeep<TValue>({
get() {
const currentValues = getFromPath<TValue[]>(form?.values, toValue(arrayPath), []) || [];
const idx = fields.value.findIndex(e => e.key === key);
return idx === -1 ? value : currentValues[idx];
},
set(value: TValue) {
const idx = fields.value.findIndex(e => e.key === key);
if (idx === -1) {
if (__DEV__) {
warn(`Attempting to update a non-existent array item`);
}
return;
}
update(idx, value);
},
}) as TValue, // will be auto unwrapped
isFirst: false,
isLast: false,
};
return entry;
}
function afterMutation() {
updateEntryFlags();
// Should trigger a silent validation since a field may not do that #4096
form?.validate({ mode: 'silent' });
}
function remove(idx: number) {
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
if (!pathValue || !Array.isArray(pathValue)) {
return;
}
const newValue = [...pathValue];
newValue.splice(idx, 1);
const fieldPath = pathName + `[${idx}]`;
form.destroyPath(fieldPath);
form.unsetInitialValue(fieldPath);
setInPath(form.values, pathName, newValue);
fields.value.splice(idx, 1);
afterMutation();
}
function push(initialValue: TValue) {
const value = deepCopy(initialValue);
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
const normalizedPathValue = isNullOrUndefined(pathValue) ? [] : pathValue;
if (!Array.isArray(normalizedPathValue)) {
return;
}
const newValue = [...normalizedPathValue];
newValue.push(value);
form.stageInitialValue(pathName + `[${newValue.length - 1}]`, value);
setInPath(form.values, pathName, newValue);
fields.value.push(createEntry(value));
afterMutation();
}
function swap(indexA: number, indexB: number) {
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
if (!Array.isArray(pathValue) || !(indexA in pathValue) || !(indexB in pathValue)) {
return;
}
const newValue = [...pathValue];
const newFields = [...fields.value];
// the old switcheroo
const temp = newValue[indexA];
newValue[indexA] = newValue[indexB];
newValue[indexB] = temp;
const tempEntry = newFields[indexA];
newFields[indexA] = newFields[indexB];
newFields[indexB] = tempEntry;
setInPath(form.values, pathName, newValue);
fields.value = newFields;
updateEntryFlags();
}
function insert(idx: number, initialValue: TValue) {
const value = deepCopy(initialValue);
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
if (!Array.isArray(pathValue) || pathValue.length < idx) {
return;
}
const newValue = [...pathValue];
const newFields = [...fields.value];
newValue.splice(idx, 0, value);
newFields.splice(idx, 0, createEntry(value));
setInPath(form.values, pathName, newValue);
fields.value = newFields;
afterMutation();
}
function replace(arr: TValue[]) {
const pathName = toValue(arrayPath);
form.stageInitialValue(pathName, arr);
setInPath(form.values, pathName, arr);
initFields();
afterMutation();
}
function update(idx: number, value: TValue) {
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
if (!Array.isArray(pathValue) || pathValue.length - 1 < idx) {
return;
}
setInPath(form.values, `${pathName}[${idx}]`, value);
form?.validate({ mode: 'validated-only' });
}
function prepend(initialValue: TValue) {
const value = deepCopy(initialValue);
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
const normalizedPathValue = isNullOrUndefined(pathValue) ? [] : pathValue;
if (!Array.isArray(normalizedPathValue)) {
return;
}
const newValue = [value, ...normalizedPathValue];
setInPath(form.values, pathName, newValue);
form.stageInitialValue(pathName + `[0]`, value);
fields.value.unshift(createEntry(value));
afterMutation();
}
function move(oldIdx: number, newIdx: number) {
const pathName = toValue(arrayPath);
const pathValue = getFromPath<TValue[]>(form?.values, pathName);
const newValue = isNullOrUndefined(pathValue) ? [] : [...pathValue];
if (!Array.isArray(pathValue) || !(oldIdx in pathValue) || !(newIdx in pathValue)) {
return;
}
const newFields = [...fields.value];
const movedItem = newFields[oldIdx];
newFields.splice(oldIdx, 1);
newFields.splice(newIdx, 0, movedItem);
const movedValue = newValue[oldIdx];
newValue.splice(oldIdx, 1);
newValue.splice(newIdx, 0, movedValue);
setInPath(form.values, pathName, newValue);
fields.value = newFields;
afterMutation();
}
const fieldArrayCtx: FieldArrayContext<TValue> = {
fields,
remove,
push,
swap,
insert,
update,
replace,
prepend,
move,
};
form.fieldArrays.push({
path: arrayPath,
reset: initFields,
...fieldArrayCtx,
});
onBeforeUnmount(() => {
const idx = form.fieldArrays.findIndex(i => toValue(i.path) === toValue(arrayPath));
if (idx >= 0) {
form.fieldArrays.splice(idx, 1);
}
});
// Makes sure to sync the form values with the array value if they go out of sync
// #4153
watch(getCurrentValues, formValues => {
const fieldsValues = fields.value.map(f => f.value);
// If form values are not the same as the current values then something overrode them.
if (!isEqual(formValues, fieldsValues)) {
initFields();
}
});
return fieldArrayCtx;
}