From 552149394fa06e2d4dd79f559752fa71c3722095 Mon Sep 17 00:00:00 2001 From: Cindy Nguyen <126883846+cintnguyen@users.noreply.github.com> Date: Thu, 12 Oct 2023 14:18:36 -0400 Subject: [PATCH] fix: run leave control logic when tabbing out of autosuggest (#2663) --- src/Form/FormAutosuggest.jsx | 26 ++++++++++++++++--------- src/Form/tests/FormAutosuggest.test.jsx | 17 ++++++++++++++++ 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/src/Form/FormAutosuggest.jsx b/src/Form/FormAutosuggest.jsx index 499f8444ab..813e02bcd9 100644 --- a/src/Form/FormAutosuggest.jsx +++ b/src/Form/FormAutosuggest.jsx @@ -112,6 +112,7 @@ function FormAutosuggest({ ); - const handleDocumentClick = (e) => { - if (parentRef.current && !parentRef.current.contains(e.target) && isActive) { - setIsActive(false); + const leaveControl = () => { + setIsActive(false); - setState(prevState => ({ - ...prevState, - dropDownItems: [], - errorMessage: !state.displayValue ? errorMessageText : '', - })); + setState(prevState => ({ + ...prevState, + dropDownItems: [], + errorMessage: !state.displayValue ? errorMessageText : '', + })); - setIsMenuClosed(true); + setIsMenuClosed(true); + }; + + const handleDocumentClick = (e) => { + if (parentRef.current && !parentRef.current.contains(e.target) && isActive) { + leaveControl(); } }; @@ -148,6 +153,9 @@ function FormAutosuggest({ setIsMenuClosed(true); } + if (e.key === 'Tab' && isActive) { + leaveControl(); + } }; useEffect(() => { diff --git a/src/Form/tests/FormAutosuggest.test.jsx b/src/Form/tests/FormAutosuggest.test.jsx index 27548704a3..4365cac38e 100644 --- a/src/Form/tests/FormAutosuggest.test.jsx +++ b/src/Form/tests/FormAutosuggest.test.jsx @@ -240,4 +240,21 @@ describe('controlled behavior', () => { expect(getByText('2 options found')).toBeInTheDocument(); }); + + it('closes options list when tabbed out and the input is no longer active', () => { + const { getByTestId, queryAllByTestId } = render(); + const input = getByTestId('autosuggest-textbox-input'); + + userEvent.click(input); + expect(document.activeElement).toBe(getByTestId('autosuggest-textbox-input')); + + const list = queryAllByTestId('autosuggest-optionitem'); + expect(list.length).toBe(3); + + userEvent.tab(); + expect(document.activeElement).not.toBe(getByTestId('autosuggest-textbox-input')); + + const updatedList = queryAllByTestId('autosuggest-optionitem'); + expect(updatedList.length).toBe(0); + }); });