11// @flow
22import type { MutableState , Mutator , Tools } from 'final-form'
3- import moveFieldState from './moveFieldState '
3+ import copyField from './copyField '
44import { escapeRegexTokens } from './utils'
55
66const remove : Mutator < any > = (
77 [name, index]: any[],
88 state: MutableState< any > ,
9- { changeValue , renameField , getIn , setIn } : Tools< any >
9+ { changeValue , getIn , setIn } : Tools< any >
1010) => {
1111 let returnValue
1212 changeValue ( state , name , ( array : ?( any [ ] ) ) : any [ ] => {
@@ -19,14 +19,12 @@ const remove: Mutator<any> = (
1919 // now we have to remove any subfields for our index,
2020 // and decrement all higher indexes.
2121 const pattern = new RegExp ( `^${ escapeRegexTokens ( name ) } \\[(\\d+)\\](.*)` )
22- const backup = { ... state , fields : { ... state . fields } }
22+ const newFields = { }
2323 Object . keys ( state . fields ) . forEach ( key => {
2424 const tokens = pattern . exec ( key )
2525 if ( tokens ) {
2626 const fieldIndex = Number ( tokens [ 1 ] )
2727 if ( fieldIndex === index ) {
28- // delete any subfields for this array item
29- delete state . fields [ key ]
3028 // delete any submitErrors for this array item
3129 // if the root key of the delete index
3230 if ( key === `${ name } [${ index } ]` ) {
@@ -38,19 +36,24 @@ const remove: Mutator<any> = (
3836 state = setIn ( state , path , submitErrors )
3937 }
4038 }
41- } else if ( fieldIndex > index ) {
42- // shift all higher ones down
43- delete state . fields [ key ]
39+
40+ return
41+ }
42+
43+ if ( fieldIndex > index ) {
44+ // Shift all higher indices down
4445 const decrementedKey = `${ name } [${ fieldIndex - 1 } ]${ tokens [ 2 ] } `
45- if ( backup . fields [ decrementedKey ] ) {
46- moveFieldState ( state , backup . fields [ key ] , decrementedKey , backup )
47- } else {
48- // take care of setting the correct change, blur, focus, validators on new field
49- renameField ( state , key , decrementedKey )
50- }
46+ copyField ( state . fields , key , newFields , decrementedKey )
47+ return
5148 }
5249 }
50+
51+ // Keep this field that does not match the name,
52+ // or has index smaller than what is being removed
53+ newFields [ key ] = state . fields [ key ]
5354 } )
55+
56+ state . fields = newFields
5457 return returnValue
5558}
5659
0 commit comments