Skip to content

Commit 70926e6

Browse files
authored
Merge pull request #277 from sparksuite/close-menu-on-escape
Close menu when the escape key is pressed while menu button holds focus
2 parents 7fb956b + ea6c128 commit 70926e6

File tree

4 files changed

+23
-3
lines changed

4 files changed

+23
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-accessible-dropdown-menu-hook",
3-
"version": "2.3.0",
3+
"version": "2.3.1",
44
"description": "A simple Hook for creating fully accessible dropdown menus in React",
55
"main": "dist/use-dropdown-menu.js",
66
"types": "dist/use-dropdown-menu.d.ts",

src/use-dropdown-menu.test.tsx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,18 @@ it('Sets isOpen to true after pressing enter while focused on the menu button',
126126
expect(screen.getByTestId('is-open-indicator')).toHaveTextContent('true');
127127
});
128128

129+
it('Sets isOpen to false after pressing escape while focused on the menu button', () => {
130+
render(<TestComponent />);
131+
132+
userEvent.click(screen.getByText('Primary'));
133+
134+
userEvent.type(screen.getByText('Primary'), '{esc}', {
135+
skipClick: true,
136+
});
137+
138+
expect(screen.getByTestId('is-open-indicator')).toHaveTextContent('false');
139+
});
140+
129141
it('Sets isOpen to true after pressing space while focused on the menu button', () => {
130142
render(<TestComponent />);
131143

src/use-dropdown-menu.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,17 +118,24 @@ export default function useDropdownMenu(itemCount: number): DropdownMenuResponse
118118
if (isKeyboardEvent(e)) {
119119
const { key } = e;
120120

121-
if (!['Enter', ' ', 'Tab', 'ArrowDown'].includes(key)) {
121+
if (!['Enter', ' ', 'Tab', 'ArrowDown', 'Escape'].includes(key)) {
122122
return;
123123
}
124124

125125
if ((key === 'Tab' || key === 'ArrowDown') && clickedOpen.current && isOpen) {
126126
e.preventDefault();
127127
moveFocus(0);
128-
} else if (key !== 'Tab') {
128+
}
129+
130+
if (key === 'Enter' || key === ' ') {
129131
e.preventDefault();
130132
setIsOpen(true);
131133
}
134+
135+
if (key === 'Escape') {
136+
e.preventDefault();
137+
setIsOpen(false);
138+
}
132139
} else {
133140
clickedOpen.current = !isOpen;
134141
setIsOpen(!isOpen);

website/src/pages/demo.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ const Demo: React.FC = () => {
7070
If the menu is revealed with the mouse, the first menu item can be focused by pressing tab / arrow
7171
down
7272
</li>
73+
<li>If the menu is revealed with the mouse, the menu can be be closed by pressing escape</li>
7374
<li>
7475
<em>Once focus is in the menu…</em>
7576

0 commit comments

Comments
 (0)