Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/hooks/useAccessibility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,25 @@ export default function useAccessibility({
return focused;
};

const handleKeyDown = (event) => {
const handleKeyDown = (event: KeyboardEvent) => {
switch (event.keyCode) {
case ESC:
case ESC: {
// Let a nested menu handle Escape before closing the outer popup.
const overlay = overlayRef?.current;
const overlayElement = overlay?.list || overlay;
const rootMenu = overlayElement?.matches?.('[role="menu"]')
? overlayElement
: overlayElement?.querySelector?.('[role="menu"]');
const targetMenu =
event.target instanceof Element
? event.target.closest('[role="menu"]')
: null;
if (rootMenu && targetMenu && targetMenu !== rootMenu) {
break;
}
handleCloseMenuAndReturnFocus();
break;
}
case TAB: {
let focusResult: boolean = false;
if (!focusMenuRef.current) {
Expand Down
48 changes: 48 additions & 0 deletions tests/useAccessibility.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,51 @@ it('closes without consuming Tab when the overlay ref is omitted', () => {
trigger.remove();
}
});

it.each([false, true])(
'leaves a portaled nested menu Escape to its owner (wrapped: %s)',
(wrapped) => {
const trigger = document.createElement('button');
const wrapper = document.createElement('div');
const root = document.createElement('ul');
const submenu = document.createElement('ul');
const child = document.createElement('li');
root.setAttribute('role', 'menu');
submenu.setAttribute('role', 'menu');
child.tabIndex = -1;
submenu.appendChild(child);
wrapper.appendChild(root);
document.body.append(trigger, wrapper, submenu);
const onOpenChange = jest.fn();
const { unmount } = renderHook(() =>
useAccessibility({
open: true,
triggerRef: { current: trigger },
onOpenChange,
overlayRef: { current: wrapped ? wrapper : { list: root } },
}),
);
try {
child.focus();
act(() =>
child.dispatchEvent(
new KeyboardEvent('keydown', { keyCode: 27, bubbles: true }),
),
);
expect(onOpenChange).not.toHaveBeenCalled();
expect(document.activeElement).toBe(child);
act(() =>
root.dispatchEvent(
new KeyboardEvent('keydown', { keyCode: 27, bubbles: true }),
),
);
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(document.activeElement).toBe(trigger);
} finally {
unmount();
trigger.remove();
wrapper.remove();
submenu.remove();
}
},
);
Loading