Skip to content

Commit e00e0c2

Browse files
committed
fix: consume Escape when returning from a submenu
1 parent 8dfdef4 commit e00e0c2

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

‎src/hooks/useAccessibility.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,11 @@ export function useAccessibility<T extends HTMLElement>(
302302

303303
const parentMenuElement = key2element.get(parentKey);
304304

305+
// A submenu consumes Escape; the surrounding popup handles root Escape.
306+
if (which === ESC && parentMenuElement) {
307+
e.stopPropagation();
308+
}
309+
305310
// Focus menu item
306311
triggerAccessibilityOpen(parentKey, false);
307312
tryFocus(parentMenuElement);

‎tests/Keyboard.spec.tsx‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,47 @@ describe('Menu.Keyboard', () => {
4444
});
4545
}
4646

47+
it.each([1, 2])('consumes submenu Escape at depth %s but lets root Escape bubble', depth => {
48+
const onOpenChange = jest.fn();
49+
const onWindowKeyDown = jest.fn();
50+
window.addEventListener('keydown', onWindowKeyDown);
51+
const { container, getByText, unmount } = render(
52+
<Menu defaultOpenKeys={depth === 2 ? ['sub', 'inner'] : ['sub']} onOpenChange={onOpenChange}>
53+
<SubMenu key="sub" title="Submenu">
54+
{depth === 2 ? (
55+
<SubMenu key="inner" title="Inner">
56+
<MenuItem key="child">Child</MenuItem>
57+
</SubMenu>
58+
) : (
59+
<MenuItem key="child">Child</MenuItem>
60+
)}
61+
</SubMenu>
62+
</Menu>,
63+
);
64+
for (let i = 0; i < 3; i += 1) {
65+
act(() => jest.runAllTimers());
66+
}
67+
try {
68+
const child = getByText('Child').closest<HTMLElement>('[role="menuitem"]');
69+
act(() => child.focus());
70+
fireEvent.keyDown(child, { which: KeyCode.ESC, keyCode: KeyCode.ESC });
71+
act(() => jest.runAllTimers());
72+
expect(onOpenChange).toHaveBeenLastCalledWith(depth === 2 ? ['sub'] : []);
73+
expect(document.activeElement).toBe(
74+
getByText(depth === 2 ? 'Inner' : 'Submenu').closest('[role="menuitem"]'),
75+
);
76+
expect(onWindowKeyDown).not.toHaveBeenCalled();
77+
78+
const rootItem = getByText('Submenu').closest<HTMLElement>('[role="menuitem"]');
79+
act(() => rootItem.focus());
80+
fireEvent.keyDown(rootItem, { which: KeyCode.ESC, keyCode: KeyCode.ESC });
81+
expect(onWindowKeyDown).toHaveBeenCalledTimes(1);
82+
} finally {
83+
window.removeEventListener('keydown', onWindowKeyDown);
84+
unmount();
85+
}
86+
});
87+
4788
it('no data-menu-id by init', () => {
4889
const { container } = render(
4990
<Menu mode="inline" openKeys={['light']}>

0 commit comments

Comments
 (0)