Skip to content

Commit

Permalink
Merge pull request #277 from sparksuite/close-menu-on-escape
Browse files Browse the repository at this point in the history
Close menu when the escape key is pressed while menu button holds focus
  • Loading branch information
WesCossick authored Jul 28, 2021
2 parents 7fb956b + ea6c128 commit 70926e6
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "react-accessible-dropdown-menu-hook",
"version": "2.3.0",
"version": "2.3.1",
"description": "A simple Hook for creating fully accessible dropdown menus in React",
"main": "dist/use-dropdown-menu.js",
"types": "dist/use-dropdown-menu.d.ts",
Expand Down
12 changes: 12 additions & 0 deletions src/use-dropdown-menu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,18 @@ it('Sets isOpen to true after pressing enter while focused on the menu button',
expect(screen.getByTestId('is-open-indicator')).toHaveTextContent('true');
});

it('Sets isOpen to false after pressing escape while focused on the menu button', () => {
render(<TestComponent />);

userEvent.click(screen.getByText('Primary'));

userEvent.type(screen.getByText('Primary'), '{esc}', {
skipClick: true,
});

expect(screen.getByTestId('is-open-indicator')).toHaveTextContent('false');
});

it('Sets isOpen to true after pressing space while focused on the menu button', () => {
render(<TestComponent />);

Expand Down
11 changes: 9 additions & 2 deletions src/use-dropdown-menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,17 +118,24 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
if (isKeyboardEvent(e)) {
const { key } = e;

if (!['Enter', ' ', 'Tab', 'ArrowDown'].includes(key)) {
if (!['Enter', ' ', 'Tab', 'ArrowDown', 'Escape'].includes(key)) {
return;
}

if ((key === 'Tab' || key === 'ArrowDown') && clickedOpen.current && isOpen) {
e.preventDefault();
moveFocus(0);
} else if (key !== 'Tab') {
}

if (key === 'Enter' || key === ' ') {
e.preventDefault();
setIsOpen(true);
}

if (key === 'Escape') {
e.preventDefault();
setIsOpen(false);
}
} else {
clickedOpen.current = !isOpen;
setIsOpen(!isOpen);
Expand Down
1 change: 1 addition & 0 deletions website/src/pages/demo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ const Demo: React.FC = () => {
If the menu is revealed with the mouse, the first menu item can be focused by pressing tab / arrow
down
</li>
<li>If the menu is revealed with the mouse, the menu can be be closed by pressing escape</li>
<li>
<em>Once focus is in the menu…</em>

Expand Down

0 comments on commit 70926e6

Please sign in to comment.