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(menu): render through portal to avoid z-index and overflow issues #8829

Merged
merged 8 commits into from
Jul 14, 2021
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,11 @@
}
}

// styles for "next" version
.#{$prefix}--overflow-menu__container {
display: inline-block;
}

// Windows HCM fix
/* stylelint-disable */
.#{$prefix}--overflow-menu:focus,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7653,6 +7653,9 @@ Map {
"children": Object {
"type": "node",
},
"id": Object {
"type": "string",
},
"level": Object {
"type": "number",
},
Expand Down
19 changes: 8 additions & 11 deletions packages/react/src/components/Menu/Menu-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,25 @@ import Menu, {
} from '../Menu';
import { mount } from 'enzyme';
import { settings } from 'carbon-components';
import { describe, expect } from 'window-or-global';

const { prefix } = settings;

describe('Menu', () => {
describe('renders as expected', () => {
describe('menu', () => {
it('receives the expected classes when closed', () => {
it("isn't rendered when closed", () => {
const wrapper = mount(<Menu />);
const container = wrapper.childAt(0).childAt(0);

expect(container.hasClass(`${prefix}--menu`)).toBe(true);
expect(container.hasClass(`${prefix}--menu--open`)).toBe(false);
expect(wrapper.getDOMNode()).toBe(null);
});

it('receives the expected classes when opened', () => {
const wrapper = mount(<Menu open />);
const container = wrapper.getDOMNode();

const container = wrapper.childAt(0).childAt(0);

expect(container.hasClass(`${prefix}--menu`)).toBe(true);
expect(container.hasClass(`${prefix}--menu--open`)).toBe(true);
expect(container.classList.contains(`${prefix}--menu`)).toBe(true);
expect(container.classList.contains(`${prefix}--menu--open`)).toBe(
true
);
});
});

Expand Down Expand Up @@ -90,7 +87,7 @@ describe('Menu', () => {

it('renders props.children as submenu', () => {
const wrapper = mount(
<Menu>
<Menu open>
<MenuItem label="Format">
<MenuItem label="Bold" />
<MenuItem label="Italic" />
Expand Down
35 changes: 33 additions & 2 deletions packages/react/src/components/Menu/Menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import React, { useEffect, useRef, useState } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { settings } from 'carbon-components';
Expand Down Expand Up @@ -36,8 +37,9 @@ const margin = 16; // distance to keep to body edges, in px
const Menu = function Menu({
autoclose = true,
children,
open,
id,
level = 1,
open,
x = 0,
y = 0,
onClose = () => {},
Expand All @@ -48,6 +50,7 @@ const Menu = function Menu({
const [position, setPosition] = useState([x, y]);
const [canBeClosed, setCanBeClosed] = useState(false);
const isRootMenu = level === 1;
const focusReturn = useRef(null);

function getContainerBoundaries() {
const { clientWidth: bodyWidth, clientHeight: bodyHeight } = document.body;
Expand Down Expand Up @@ -107,6 +110,16 @@ const Menu = function Menu({
}

function handleKeyDown(event) {
if (match(event, keys.Tab)) {
event.preventDefault();

if (focusReturn.current) {
focusReturn.current.focus();
}

onClose();
}

if (
event.target.tagName === 'LI' &&
(match(event, keys.Enter) || match(event, keys.Space))
Expand Down Expand Up @@ -187,10 +200,17 @@ const Menu = function Menu({
return correctedPosition;
}

function handleBlur(e) {
if (isRootMenu && !rootRef?.current?.element.contains(e.relatedTarget)) {
onClose();
}
}

useEffect(() => {
setCanBeClosed(false);

if (open) {
focusReturn.current = document.activeElement;
let localDirection = 1;

if (isRootMenu) {
Expand Down Expand Up @@ -235,9 +255,11 @@ const Menu = function Menu({
});

const ulAttributes = {
id,
className: classes,
onKeyDown: handleKeyDown,
onClick: handleClick,
onBlur: handleBlur,
role: 'menu',
tabIndex: -1,
'data-direction': direction,
Expand Down Expand Up @@ -274,11 +296,15 @@ const Menu = function Menu({
childrenToRender = React.Children.toArray(options[0].props.children);
}

return (
const menu = (
<ClickListener onClickOutside={handleClickOutside} ref={rootRef}>
<ul {...ulAttributes}>{childrenToRender}</ul>
</ClickListener>
);

return isRootMenu
? (open && ReactDOM.createPortal(menu, document.body)) || null
: menu;
};

Menu.propTypes = {
Expand All @@ -293,6 +319,11 @@ Menu.propTypes = {
*/
children: PropTypes.node,

/**
* Define an ID for this menu
*/
id: PropTypes.string,

/**
* Internal: keeps track of the nesting level of the menu
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,23 @@ export const Nested = () =>
},
{ type: 'item', label: 'Level 1' },
]);

export const InToolbar = () => (
<StoryFrame>
<div className="bx--table-toolbar" style={{ overflow: 'visible' }}>
<div className="bx--toolbar-content">
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
<div tabIndex={0}>Tab stop</div>
<OverflowMenu>
{buildMenu([
{ type: 'item', label: 'Option 1' },
{ type: 'item', label: 'Option 2' },
{ type: 'item', label: 'Option 3' },
])}
</OverflowMenu>
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
<div tabIndex={0}>Tab stop</div>
</div>
</div>
</StoryFrame>
);
24 changes: 21 additions & 3 deletions packages/react/src/components/OverflowMenu/next/OverflowMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import PropTypes from 'prop-types';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import { OverflowMenuVertical16 } from '@carbon/icons-react';
import { useId } from '../../../internal/useId';
import Menu from '../../Menu';

const { prefix } = settings;
Expand All @@ -19,6 +20,7 @@ function OverflowMenu({
renderIcon: IconElement = OverflowMenuVertical16,
...rest
}) {
const id = useId('overflowmenu');
const [open, setOpen] = useState(false);
const [position, setPosition] = useState([
[0, 0],
Expand Down Expand Up @@ -55,26 +57,42 @@ function OverflowMenu({
}
}

function handleMousedown(e) {
// prevent default for mousedown on trigger element to avoid
// the "blur" event from firing on the menu as this would close
// it and immediately re-open since "click" event is fired after
// "blur" event.
e.preventDefault();
}

const containerClasses = classNames(`${prefix}--overflow-menu__container`);

const triggerClasses = classNames(`${prefix}--overflow-menu`, {
[`${prefix}--overflow-menu--open`]: open,
});

return (
<>
<div className={containerClasses} aria-owns={id}>
<button
{...rest}
type="button"
aria-haspopup
aria-expanded={open}
className={triggerClasses}
onClick={handleClick}
onMouseDown={handleMousedown}
ref={triggerRef}>
<IconElement />
</button>
<Menu open={open} onClose={closeMenu} x={position[0]} y={position[1]}>
<Menu
id={id}
open={open}
onClose={closeMenu}
x={position[0]}
y={position[1]}>
{children}
</Menu>
</>
</div>
);
}

Expand Down