Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
25 changes: 24 additions & 1 deletion packages/menu/src/MenuContainer.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -241,16 +241,39 @@ describe('MenuContainer', () => {
expect(menu).not.toBeVisible();
});

it('closes menu on blur', async () => {
it('closes menu on blur and restores focus to trigger if focus was moved to non-focusabe element', async () => {
const { getByTestId } = render(<TestMenu items={ITEMS} />);
const trigger = getByTestId('trigger');
const menu = getByTestId('menu');

await waitFor(async () => {
await user.click(trigger);
});
expect(menu).toBeVisible();

await waitFor(async () => {
await user.click(document.body);
});
expect(trigger).toHaveFocus();
expect(menu).not.toBeVisible();
});

it('closes menu on blur and moves focus focus to focusabe element', async () => {
const { getByTestId } = render(
<>
<TestMenu items={ITEMS} />
<button data-test-id="focusable">Click me</button>
</>
);
const trigger = getByTestId('trigger');
const menu = getByTestId('menu');
const button = getByTestId('focusable');

await waitFor(async () => {
await user.click(trigger);
await user.click(button);
});
expect(button).toHaveFocus();
expect(menu).not.toBeVisible();
});

Expand Down
70 changes: 53 additions & 17 deletions packages/menu/src/useMenu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -375,16 +375,38 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
[closeMenu, returnFocusToTrigger]
);

/**
* 1. When an element loses focus (on blur) and focus shifts to the `body` or
* a non-focusable element, `event.relatedTarget` should be `null`.
* However, jsdom incorrectly sets it to `Document`.
* This bug was fixed in [email protected]. Currently, `jest-environment-jsdom` (v29.7.0)
* depends on [email protected], which still contains the issue.
* Until a newer version is released, this simple workaround
* is necessary to accurately test the "focus return" behavior.
* @see https://github.com/jsdom/jsdom/pull/3767
* @see https://github.com/jsdom/jsdom/releases/tag/24.1.2
* @see https://github.com/jestjs/jest/blob/v29.7.0/packages/jest-environment-jsdom/package.json
*/
const handleMenuBlur = useCallback(
(event: MouseEvent) => {
const path = event.composedPath();

if (!path.includes(menuRef.current!) && !path.includes(triggerRef.current!)) {
returnFocusToTrigger();
closeMenu(StateChangeTypes.MenuBlur);
}
(event: React.FocusEvent) => {
const win = environment || window;

setTimeout(() => {
// Timeout is required to ensure blur is handled after focus
const activeElement = win.document.activeElement;

if (
!menuRef.current?.contains(activeElement) &&
!triggerRef.current?.contains(activeElement)
) {
// Only return focus to trigger if focus moved to a non-focusable element
if (!event.relatedTarget || event.relatedTarget?.nodeName === '#document' /* [1] */)
returnFocusToTrigger();
closeMenu(StateChangeTypes.MenuBlur);
}
});
},
[closeMenu, menuRef, returnFocusToTrigger, triggerRef]
[environment, menuRef, triggerRef, returnFocusToTrigger, closeMenu]
);

const handleMenuMouseLeave = useCallback(() => {
Expand Down Expand Up @@ -602,15 +624,12 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
const win = environment || window;

if (controlledIsExpanded) {
win.document.addEventListener('click', handleMenuBlur, true);
win.document.addEventListener('keydown', handleMenuKeyDown, true);
} else if (!controlledIsExpanded) {
win.document.removeEventListener('click', handleMenuBlur, true);
win.document.removeEventListener('keydown', handleMenuKeyDown, true);
}

return () => {
win.document.removeEventListener('click', handleMenuBlur, true);
win.document.removeEventListener('keydown', handleMenuKeyDown, true);
};
}, [controlledIsExpanded, handleMenuBlur, handleMenuKeyDown, environment]);
Expand Down Expand Up @@ -690,7 +709,15 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
*/

const getTriggerProps = useCallback<IUseMenuReturnValue['getTriggerProps']>(
({ onClick, onKeyDown, type = 'button', role = 'button', disabled, ...other } = {}) => ({
({
onClick,
onKeyDown,
onBlur,
type = 'button',
role = 'button',
disabled,
...other
} = {}) => ({
...other,
'data-garden-container-id': 'containers.menu.trigger',
'data-garden-container-version': PACKAGE_VERSION,
Expand All @@ -703,13 +730,21 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
type: type === null ? undefined : type,
role: role === null ? undefined : role,
onKeyDown: composeEventHandlers(onKeyDown, handleTriggerKeyDown),
onClick: composeEventHandlers(onClick, handleTriggerClick)
onClick: composeEventHandlers(onClick, handleTriggerClick),
onBlur: composeEventHandlers(onBlur, handleMenuBlur)
}),
[triggerRef, controlledIsExpanded, handleTriggerClick, handleTriggerKeyDown, triggerId]
[
triggerRef,
triggerId,
controlledIsExpanded,
handleTriggerKeyDown,
handleTriggerClick,
handleMenuBlur
]
);

const getMenuProps = useCallback<IUseMenuReturnValue['getMenuProps']>(
({ role = 'menu', onMouseLeave, ...other } = {}) => ({
({ role = 'menu', onBlur, onMouseLeave, ...other } = {}) => ({
...other,
...getGroupProps({
onMouseLeave: composeEventHandlers(onMouseLeave, handleMenuMouseLeave)
Expand All @@ -719,9 +754,10 @@ export const useMenu = <T extends HTMLElement = HTMLElement, M extends HTMLEleme
'aria-labelledby': triggerId,
tabIndex: -1,
role: role === null ? undefined : role,
ref: menuRef as any
ref: menuRef as any,
onBlur: composeEventHandlers(onBlur, handleMenuBlur)
}),
[triggerId, menuRef, getGroupProps, handleMenuMouseLeave]
[getGroupProps, handleMenuMouseLeave, triggerId, menuRef, handleMenuBlur]
);

const getSeparatorProps = useCallback<IUseMenuReturnValue['getSeparatorProps']>(
Expand Down