Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: focus issue in menu #17047

Merged
8 changes: 5 additions & 3 deletions packages/react/src/components/Menu/Menu-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import React from 'react';
import { Menu, MenuItem, MenuItemSelectable, MenuItemRadioGroup } from './';
import { act, fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { waitForPosition } from '../ListBox/test-helpers';

describe('Menu', () => {
describe('renders as expected', () => {
Expand Down Expand Up @@ -83,7 +84,7 @@ describe('Menu', () => {
document.body.removeChild(el);
});

it('warns about nested menus in basic mode', () => {
it('warns about nested menus in basic mode', async () => {
const spy = jest.spyOn(console, 'warn').mockImplementation(() => {});

render(
Expand All @@ -93,14 +94,14 @@ describe('Menu', () => {
</MenuItem>
</Menu>
);

await waitForPosition();
expect(spy).toHaveBeenCalled();
spy.mockRestore();
});
});

describe('Submenu behavior', () => {
beforeEach(() => {
beforeEach(async () => {
jest.useFakeTimers();
render(
<Menu open>
Expand All @@ -109,6 +110,7 @@ describe('Menu', () => {
</MenuItem>
</Menu>
);
await waitForPosition();
});
afterEach(() => {
jest.useRealTimers();
Expand Down
53 changes: 52 additions & 1 deletion packages/react/src/components/Menu/Menu.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,59 @@ export const Playground = (args) => {
onChange={radioOnChange}
/>
</MenuItem>
<MenuItem label="Copy" shortcut="⌘C" onClick={itemOnClick} />
<MenuItem label="Paste" shortcut="⌘V" disabled onClick={itemOnClick} />
<MenuItemDivider />
<MenuItemGroup label="Font style">
<MenuItemSelectable
label="Bold"
defaultSelected
onChange={selectableOnChange}
/>
<MenuItemSelectable label="Italic" onChange={selectableOnChange} />
</MenuItemGroup>
<MenuItemDivider />
<MenuItemRadioGroup
label="Text decoration"
items={['None', 'Overline', 'Line-through', 'Underline']}
defaultSelectedItem="None"
onChange={radioOnChange}
/>
<MenuItemDivider />
<MenuItem label="Cut" shortcut="⌘X" onClick={itemOnClick} />
<MenuItem
label="Delete"
shortcut="⌫"
kind="danger"
onClick={itemOnClick}
/>
</Menu>
);
};

export const Test = (args) => {
const itemOnClick = action('onClick (MenuItem)');
const selectableOnChange = action('onChange (MenuItemSelectable)');
const radioOnChange = action('onChange (MenuItemRadioGroup)');

const target = document.getElementById('storybook-root');

return (
<Menu {...args} target={target} x={document?.dir === 'rtl' ? 250 : 0} open>
<MenuItem label="Copy" shortcut="⌘C" onClick={itemOnClick} />
<MenuItemDivider />
<MenuItem label="Cut" shortcut="⌘X" onClick={itemOnClick}>
<MenuItemSelectable label="Cut" onChange={selectableOnChange} />
<MenuItemSelectable label="Copy" onChange={selectableOnChange} />
<MenuItemSelectable label="Italic" onChange={selectableOnChange} />
</MenuItem>
<MenuItem label="Share with">
<MenuItemRadioGroup
label="Share with"
items={['None', 'Product team', 'Organization', 'Company']}
defaultSelectedItem="Product team"
onChange={radioOnChange}
/>
</MenuItem>
<MenuItem label="Copy" shortcut="⌘C" onClick={itemOnClick} />
<MenuItem label="Paste" shortcut="⌘V" disabled onClick={itemOnClick} />
<MenuItemDivider />
Expand Down
190 changes: 94 additions & 96 deletions packages/react/src/components/Menu/MenuItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,15 @@ import React, {
useRef,
useState,
} from 'react';

import {
useHover,
useFloating,
useInteractions,
safePolygon,
autoUpdate,
offset,
FloatingFocusManager,
} from '@floating-ui/react';
import { CaretRight, CaretLeft, Checkmark } from '@carbon/icons-react';
import { keys, match } from '../../internal/keyboard';
import { useControllableState } from '../../internal/useControllableState';
Expand Down Expand Up @@ -79,9 +87,6 @@ export interface MenuItemProps extends LiHTMLAttributes<HTMLLIElement> {
shortcut?: string;
}

const hoverIntentDelay = 150; // in ms
const leaveIntentDelay = 300; // in ms

export const MenuItem = forwardRef<HTMLLIElement, MenuItemProps>(
function MenuItem(
{
Expand All @@ -97,26 +102,41 @@ export const MenuItem = forwardRef<HTMLLIElement, MenuItemProps>(
},
forwardRef
) {
const [submenuOpen, setSubmenuOpen] = useState(false);
const [rtl, setRtl] = useState(false);

const {
refs,
floatingStyles,
context: floatingContext,
} = useFloating({
open: submenuOpen,
onOpenChange: setSubmenuOpen,
placement: rtl ? 'left-start' : 'right-start',
whileElementsMounted: autoUpdate,
middleware: [offset({ mainAxis: -6, crossAxis: -6 })],
});
const { getReferenceProps, getFloatingProps } = useInteractions([
useHover(floatingContext, {
delay: 100,
enabled: true,
handleClose: safePolygon({
requireIntent: false,
}),
}),
]);

const prefix = usePrefix();
const context = useContext(MenuContext);

const menuItem = useRef<HTMLLIElement>(null);
const ref = useMergedRefs<HTMLLIElement>([forwardRef, menuItem]);
const [boundaries, setBoundaries] = useState<{
x: number | [number, number];
y: number | [number, number];
}>({ x: -1, y: -1 });
const [rtl, setRtl] = useState(false);
const ref = useMergedRefs<HTMLLIElement>([
forwardRef,
menuItem,
refs.setReference,
]);

const hasChildren = Boolean(children);
const [submenuOpen, setSubmenuOpen] = useState(false);
const hoverIntentTimeout = useRef<ReturnType<typeof setTimeout> | null>(
null
);

const leaveIntentTimeout = useRef<ReturnType<typeof setTimeout> | null>(
null
);

const isDisabled = disabled && !hasChildren;
const isDanger = kind === 'danger' && !hasChildren;
Expand All @@ -136,25 +156,11 @@ export const MenuItem = forwardRef<HTMLLIElement, MenuItemProps>(
return;
}

const { x, y, width, height } = menuItem.current.getBoundingClientRect();
if (rtl) {
setBoundaries({
x: [-x, x - width],
y: [y, y + height],
});
} else {
setBoundaries({
x: [x, x + width],
y: [y, y + height],
});
}

setSubmenuOpen(true);
}

function closeSubmenu() {
setSubmenuOpen(false);
setBoundaries({ x: -1, y: -1 });
}

function handleClick(
Expand All @@ -173,29 +179,6 @@ export const MenuItem = forwardRef<HTMLLIElement, MenuItemProps>(
}
}

function handleMouseEnter() {
if (leaveIntentTimeout.current) {
// When mouse reenters before closing keep sub menu open
clearTimeout(leaveIntentTimeout.current);
leaveIntentTimeout.current = null;
}
hoverIntentTimeout.current = setTimeout(() => {
openSubmenu();
}, hoverIntentDelay);
}

function handleMouseLeave() {
if (hoverIntentTimeout.current) {
clearTimeout(hoverIntentTimeout.current);
// Avoid closing the sub menu as soon as mouse leaves
// prevents accidental closure due to scroll bar
leaveIntentTimeout.current = setTimeout(() => {
closeSubmenu();
menuItem.current?.focus();
}, leaveIntentDelay);
}
}

function handleKeyDown(e: React.KeyboardEvent<HTMLLIElement>) {
if (hasChildren && match(e, keys.ArrowRight)) {
openSubmenu();
Expand Down Expand Up @@ -245,48 +228,63 @@ export const MenuItem = forwardRef<HTMLLIElement, MenuItemProps>(
}
}, [iconsAllowed, IconElement, context.state.hasIcons, context]);

useEffect(() => {
Object.keys(floatingStyles).forEach((style) => {
if (refs.floating.current && style !== 'position') {
refs.floating.current.style[style] = floatingStyles[style];
}
});
}, [floatingStyles, refs.floating]);

return (
<li
role="menuitem"
{...rest}
ref={ref}
className={classNames}
tabIndex={-1}
aria-disabled={isDisabled ?? undefined}
aria-haspopup={hasChildren ?? undefined}
aria-expanded={hasChildren ? submenuOpen : undefined}
onClick={handleClick}
onMouseEnter={hasChildren ? handleMouseEnter : undefined}
onMouseLeave={hasChildren ? handleMouseLeave : undefined}
onKeyDown={handleKeyDown}>
<div className={`${prefix}--menu-item__icon`}>
{iconsAllowed && IconElement && <IconElement />}
</div>
<Text as="div" className={`${prefix}--menu-item__label`} title={label}>
{label}
</Text>
{shortcut && !hasChildren && (
<div className={`${prefix}--menu-item__shortcut`}>{shortcut}</div>
)}
{hasChildren && (
<>
<div className={`${prefix}--menu-item__shortcut`}>
{rtl ? <CaretLeft /> : <CaretRight />}
</div>
<Menu
label={label}
open={submenuOpen}
onClose={() => {
closeSubmenu();
menuItem.current?.focus();
}}
x={boundaries.x}
y={boundaries.y}>
{children}
</Menu>
</>
)}
</li>
<FloatingFocusManager
context={floatingContext}
order={['reference', 'floating']}
modal={false}>
<li
role="menuitem"
{...rest}
ref={ref}
className={classNames}
tabIndex={-1}
aria-disabled={isDisabled ?? undefined}
aria-haspopup={hasChildren ?? undefined}
aria-expanded={hasChildren ? submenuOpen : undefined}
onClick={handleClick}
onKeyDown={handleKeyDown}
{...getReferenceProps()}>
<div className={`${prefix}--menu-item__icon`}>
{iconsAllowed && IconElement && <IconElement />}
</div>
<Text
as="div"
className={`${prefix}--menu-item__label`}
title={label}>
{label}
</Text>
{shortcut && !hasChildren && (
<div className={`${prefix}--menu-item__shortcut`}>{shortcut}</div>
)}
{hasChildren && (
<>
<div className={`${prefix}--menu-item__shortcut`}>
{rtl ? <CaretLeft /> : <CaretRight />}
</div>
<Menu
label={label}
open={submenuOpen}
onClose={() => {
closeSubmenu();
menuItem.current?.focus();
}}
ref={refs.setFloating}
{...getFloatingProps()}>
{children}
</Menu>
</>
)}
</li>
</FloatingFocusManager>
);
}
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import React from 'react';
import React, { act } from 'react';
import { OverflowMenu } from '.';
import { MenuItem } from '../../Menu';
import { render, screen } from '@testing-library/react';
Expand Down Expand Up @@ -47,10 +47,8 @@ describe('OverflowMenu (enable-v12-overflowmenu)', () => {
</MenuItem>
</OverflowMenu>
);

await userEvent.type(screen.getByRole('button'), 'enter');
expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'true');

// eslint-disable-next-line testing-library/no-node-access
const ul = document.querySelector('ul');
expect(ul).toBeInTheDocument();
Expand Down Expand Up @@ -99,7 +97,11 @@ describe('OverflowMenu (enable-v12-overflowmenu)', () => {
);
await userEvent.type(screen.getByRole('button'), 'enter');
expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'true');
await userEvent.click(document.body);

await act(async () => {
await userEvent.click(document.body);
});
preetibansalui marked this conversation as resolved.
Show resolved Hide resolved

expect(screen.getByRole('button')).toHaveAttribute(
'aria-expanded',
'false'
Expand Down
Loading