Skip to content

Commit

Permalink
fix: run leave control logic when tabbing out of autosuggest (#2663)
Browse files Browse the repository at this point in the history
  • Loading branch information
cintnguyen authored Oct 12, 2023
1 parent 8efc53e commit 5521493
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/Form/FormAutosuggest.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ function FormAutosuggest({
<IconButton
className="pgn__form-autosuggest__icon-button"
data-testid="autosuggest-iconbutton"
tabindex="-1"
src={isMenuClosed ? KeyboardArrowDown : KeyboardArrowUp}
iconAs={Icon}
size="sm"
Expand All @@ -123,17 +124,21 @@ 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();
}
};

Expand All @@ -148,6 +153,9 @@ function FormAutosuggest({

setIsMenuClosed(true);
}
if (e.key === 'Tab' && isActive) {
leaveControl();
}
};

useEffect(() => {
Expand Down
17 changes: 17 additions & 0 deletions src/Form/tests/FormAutosuggest.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<FormAutosuggestTestComponent />);
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);
});
});

0 comments on commit 5521493

Please sign in to comment.