From 572f5fe2c1abca8baa0190b77c17787e758c94c8 Mon Sep 17 00:00:00 2001 From: Julian Grinblat Date: Fri, 30 Aug 2019 15:14:35 +0900 Subject: [PATCH] When removing fields, rename new ones --- src/remove.js | 9 +++++-- src/remove.test.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/src/remove.js b/src/remove.js index 98ef5fc..a293d9b 100644 --- a/src/remove.js +++ b/src/remove.js @@ -5,7 +5,7 @@ import moveFieldState from './moveFieldState' const remove: Mutator = ( [name, index]: any[], state: MutableState, - { changeValue }: Tools + { changeValue, renameField }: Tools ) => { let returnValue changeValue(state, name, (array: ?(any[])): any[] => { @@ -30,7 +30,12 @@ const remove: Mutator = ( // shift all higher ones down delete state.fields[key] const decrementedKey = `${name}[${fieldIndex - 1}]${tokens[2]}` - moveFieldState(state, backup.fields[key], decrementedKey, backup) + if (backup.fields[decrementedKey]) { + moveFieldState(state, backup.fields[key], decrementedKey, backup) + } else { + // take care of setting the correct change, blur, focus, validators on new field + renameField(state, key, decrementedKey) + } } } }) diff --git a/src/remove.test.js b/src/remove.test.js index 4a22ad4..4b92adc 100644 --- a/src/remove.test.js +++ b/src/remove.test.js @@ -160,4 +160,63 @@ describe('remove', () => { } }) }) + + it('should remove value from the specified index, and handle new fields', () => { + const array = ['a', { key: 'val' }] + const changeValue = jest.fn() + const renameField = jest.fn() + function blur0() {} + function change0() {} + function focus0() {} + function blur1() {} + function change1() {} + function focus1() {} + function blur2() {} + function change2() {} + function focus2() {} + const state = { + formState: { + values: { + foo: array, + anotherField: 42 + } + }, + fields: { + 'foo[0]': { + name: 'foo[0]', + blur: blur0, + change: change0, + focus: focus0, + touched: true, + error: 'A Error' + }, + 'foo[1]': { + name: 'foo[1]', + blur: blur1, + change: change1, + focus: focus1, + touched: false, + error: 'B Error' + }, + 'foo[1].key': { + name: 'foo[1].key', + blur: blur2, + change: change2, + focus: focus2, + touched: false, + error: 'B Error' + }, + anotherField: { + name: 'anotherField', + touched: false + } + } + } + const returnValue = remove(['foo', 0], state, { renameField, changeValue }) + expect(returnValue).toBeUndefined() + expect(renameField).toHaveBeenCalledTimes(1) + expect(renameField.mock.calls[0][0]).toEqual(state) + expect(renameField.mock.calls[0][1]).toEqual('foo[1].key') + expect(renameField.mock.calls[0][2]).toEqual('foo[0].key') + }) })