From 4ff13853df24803e9d07b0c90438e28b7c00a778 Mon Sep 17 00:00:00 2001 From: Alice Hendicott Date: Tue, 14 Mar 2023 18:46:19 +1100 Subject: [PATCH] fix(useCombobox): Ensure highlighted index is not selected on browser tab change (#1484) Related issue - #1471 Co-authored-by: Alice Hendicott --- .../__tests__/getInputProps.test.js | 32 +++++++++++++++++++ src/hooks/useCombobox/index.js | 4 +-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/hooks/useCombobox/__tests__/getInputProps.test.js b/src/hooks/useCombobox/__tests__/getInputProps.test.js index 6e591109..3bdce869 100644 --- a/src/hooks/useCombobox/__tests__/getInputProps.test.js +++ b/src/hooks/useCombobox/__tests__/getInputProps.test.js @@ -1460,6 +1460,38 @@ describe('getInputProps', () => { }), ) }) + + test('the open menu will be closed and highlighted item will not be selected if the blur event related target is null', () => { + const stateReducer = jest.fn().mockImplementation(s => s) + const {container} = renderCombobox({ + isOpen: true, + highlightedIndex: 0, + stateReducer, + }) + const input = getInput() + document.body.appendChild(container) + + fireEvent.blur(input, {relatedTarget: null}) + + expect(stateReducer).toHaveBeenCalledTimes(1) + expect(stateReducer).toHaveBeenCalledWith( + { + highlightedIndex: 0, + inputValue: '', + isOpen: true, + selectedItem: null, + }, + expect.objectContaining({ + type: stateChangeTypes.InputBlur, + changes: { + highlightedIndex: -1, + inputValue: '', + isOpen: false, + selectedItem: null, + }, + }), + ) + }) }) describe('on focus', () => { diff --git a/src/hooks/useCombobox/index.js b/src/hooks/useCombobox/index.js index cbb7c44c..6ad7034f 100644 --- a/src/hooks/useCombobox/index.js +++ b/src/hooks/useCombobox/index.js @@ -416,7 +416,7 @@ function useCombobox(userProps = {}) { : event.target.value, }) } - const inputHandleBlur = () => { + const inputHandleBlur = event => { /* istanbul ignore else */ if ( latestState.isOpen && @@ -424,7 +424,7 @@ function useCombobox(userProps = {}) { ) { dispatch({ type: stateChangeTypes.InputBlur, - selectItem: true, + selectItem: event.relatedTarget !== null, }) } }