-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathinsert.js
44 lines (39 loc) · 1.27 KB
/
insert.js
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
// @flow
import type { MutableState, Mutator, Tools } from 'final-form'
import copyField from './copyField'
import { escapeRegexTokens } from './utils'
const insert: Mutator<any> = (
[name, index, value]: any[],
state: MutableState<any>,
{ changeValue, resetFieldState }: Tools<any>
) => {
changeValue(state, name, (array: ?(any[])): any[] => {
const copy = [...(array || [])]
copy.splice(index, 0, value)
return copy
})
// now we have increment any higher indexes
const pattern = new RegExp(`^${escapeRegexTokens(name)}\\[(\\d+)\\](.*)`)
const newFields = {}
Object.keys(state.fields).forEach(key => {
const tokens = pattern.exec(key)
if (tokens) {
const fieldIndex = Number(tokens[1])
if (fieldIndex >= index) {
// Shift all higher indices up
const incrementedKey = `${name}[${fieldIndex + 1}]${tokens[2]}`
copyField(state.fields, key, newFields, incrementedKey)
if (fieldIndex === index) {
newFields[key] = state.fields[key]
resetFieldState(key)
}
return
}
}
// Keep this field that does not match the name,
// or has index smaller than what is being inserted
newFields[key] = state.fields[key]
})
state.fields = newFields
}
export default insert