Skip to content

Commit

Permalink
fix: allows focus to return to input after hitting esc
Browse files Browse the repository at this point in the history
  • Loading branch information
cintnguyen committed Sep 12, 2023
1 parent 23b83c5 commit a122e04
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Form/FormAutosuggest.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, {
useEffect, useState,
useEffect, useState, useRef,
} from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
Expand Down Expand Up @@ -27,6 +27,7 @@ function FormAutosuggest({
...props
}) {
const intl = useIntl();
const formControlRef = useRef();
const parentRef = useArrowKeyNavigation({
selectors: arrowKeyNavigationSelector,
ignoredKeys: ignoredArrowKeysNames,
Expand Down Expand Up @@ -132,6 +133,10 @@ function FormAutosuggest({
if (e.key === 'Escape' && isActive) {
e.preventDefault();

if (formControlRef) {
formControlRef.current.focus();
}

setState(prevState => ({
...prevState,
dropDownItems: [],
Expand Down Expand Up @@ -221,6 +226,7 @@ function FormAutosuggest({
<div className="pgn__form-autosuggest__wrapper" ref={parentRef}>
<FormGroup isInvalid={!!state.errorMessage}>
<FormControl
ref={formControlRef}
aria-expanded={(state.dropDownItems.length > 0).toString()}
aria-owns="pgn__form-autosuggest__dropdown-box"
role="combobox"
Expand Down
11 changes: 11 additions & 0 deletions src/Form/tests/FormAutosuggest.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,15 @@ describe('controlled behavior', () => {
const updatedList = queryAllByTestId('autosuggest_optionitem');
expect(updatedList.length).toBe(0);
});

it('check focus on input after esc', () => {
const { getByTestId } = render(<FormAutosuggestTestComponent />);
const input = getByTestId('autosuggest_textbox_input');
const dropdownBtn = getByTestId('autosuggest_iconbutton');
userEvent.click(dropdownBtn);

userEvent.keyboard('{esc}');

expect(input.matches(':focus')).toBe(true);
});
});

0 comments on commit a122e04

Please sign in to comment.