diff --git a/package.json b/package.json index 3d9b05d..b458fc6 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/use-dropdown-menu.test.tsx b/src/use-dropdown-menu.test.tsx index de56266..8a52842 100644 --- a/src/use-dropdown-menu.test.tsx +++ b/src/use-dropdown-menu.test.tsx @@ -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(); + + 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(); diff --git a/src/use-dropdown-menu.ts b/src/use-dropdown-menu.ts index 9199d1c..512f10f 100644 --- a/src/use-dropdown-menu.ts +++ b/src/use-dropdown-menu.ts @@ -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); diff --git a/website/src/pages/demo.tsx b/website/src/pages/demo.tsx index 8aceac5..e0a0ddc 100644 --- a/website/src/pages/demo.tsx +++ b/website/src/pages/demo.tsx @@ -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 +
  • If the menu is revealed with the mouse, the menu can be be closed by pressing escape
  • Once focus is in the menu…