forked from final-form/final-form-arrays
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap.js
39 lines (32 loc) · 1.04 KB
/
swap.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
// @flow
import type { MutableState, Mutator, Tools } from 'final-form'
import moveFields from './moveFields'
import restoreFunctions from './restoreFunctions'
const TMP: string = 'tmp'
const swap: Mutator<any> = (
[name, indexA, indexB]: any[],
state: MutableState<any>,
{ changeValue }: Tools<any>
) => {
if (indexA === indexB) {
return
}
changeValue(state, name, (array: ?(any[])): any[] => {
const copy = [...(array || [])]
const a = copy[indexA]
copy[indexA] = copy[indexB]
copy[indexB] = a
return copy
})
//make a copy of a state for further functions restore
const backupState = { ...state, fields: { ...state.fields } }
// swap all field state that begin with "name[indexA]" with that under "name[indexB]"
const aPrefix = `${name}[${indexA}]`
const bPrefix = `${name}[${indexB}]`
const tmpPrefix = `${name}[${TMP}]`
moveFields(name, aPrefix, TMP, state)
moveFields(name, bPrefix, indexA, state)
moveFields(name, tmpPrefix, indexB, state)
restoreFunctions(state, backupState)
}
export default swap