diff --git a/demo/src/app.tsx b/demo/src/app.tsx index f9cb191..ac4085a 100644 --- a/demo/src/app.tsx +++ b/demo/src/app.tsx @@ -48,7 +48,10 @@ const App: React.FC = () => {
  • The up / down arrow keys allow for navigation through the menu items
  • Pressing tab will close the menu and move the focus to the next focusable element
  • Pressing escape will close the menu and return the focus to the button
  • -
  • Pressing enter will trigger that item (whether itʼs a link or has a click handler attached)
  • +
  • + Pressing enter will activate that item and close the menu (whether itʼs a link or has a click handler + attached) +
  • diff --git a/src/use-dropdown-menu.ts b/src/use-dropdown-menu.ts index 98cb9cb..c682052 100644 --- a/src/use-dropdown-menu.ts +++ b/src/use-dropdown-menu.ts @@ -112,8 +112,12 @@ export default function useDropdownMenu(itemCount: number) { } else if (key === 'Tab') { setIsOpen(false); return; - } else if (key === 'Enter' && !e.currentTarget.href) { - e.currentTarget.click(); + } else if (key === 'Enter') { + if (!e.currentTarget.href) { + e.currentTarget.click(); + } + + setIsOpen(false); return; } diff --git a/test/puppeteer/demo.test.ts b/test/puppeteer/demo.test.ts index f39089f..e736575 100644 --- a/test/puppeteer/demo.test.ts +++ b/test/puppeteer/demo.test.ts @@ -83,3 +83,21 @@ it('leaves the menu open if you click inside of it', async () => { expect(true).toBe(true); }); + +it('reroutes enter presses on menu items as clicks', async () => { + let alertAppeared = false; + + await page.click('#menu-button'); + await menuOpen(); + + // eslint-disable-next-line @typescript-eslint/no-misused-promises + page.on('dialog', async dialog => { + alertAppeared = true; + await dialog.dismiss(); + }); + + await page.focus('#menu-item-3'); + await keyboard.down('Enter'); + + expect(alertAppeared).toBe(true); +}); diff --git a/test/test-component.tsx b/test/test-component.tsx index 8818b2a..2592fff 100644 --- a/test/test-component.tsx +++ b/test/test-component.tsx @@ -8,27 +8,25 @@ const TestComponent: React.FC = () => { return ( - -