Skip to content

Commit 6f0aa31

Browse files
Merge pull request #440 from eccenca/feature/improveMenuRoleSupport-CMEM-7707
Improve Menu role support (CMEM-7707)
2 parents 54e5ffa + 792f7b9 commit 6f0aa31

10 files changed

Lines changed: 950 additions & 23 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,19 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/) and this p
66

77
## [Unreleased]
88

9+
### Added
10+
11+
- `<Menu />`
12+
- `role` property: `menu` (default), `navigation`, `list`, `listbox`, `none` or `presentation` get special support, other ARIA roles are set as they are
13+
- `navigation` is rendered as `list`, the `nav` wrapper must be added by yourself
14+
- sets `roleStructure` of `<MenuItem />` children automatically according to the `role` if it is not given, otherwise a console warning is emitted if it does not fit
15+
- emits a console warning if an explicitly set `role` of a `<MenuItem />` child does not fit to its (explicitly or automatically set) `roleStructure`
16+
- sets `role="listitem"` (lists) or `role="none"` (listboxes) on `<MenuDivider />` children, and `aria-hidden` if the divider has no `title`; explicitly set values are kept, except `role="separator"`
17+
- `<MenuDivider />`
18+
- accepts all attributes of the `li` element, e.g. `role` and `aria-hidden`
19+
- `<ContextMenu />`
20+
- `role` property: `menu` (default) or `listbox`, forwarded to the included `<Menu />` and used for `aria-haspopup` of the toggler
21+
922
### Fixed
1023

1124
- Fix misused menu roles in selection popups and overlays

‎src/components/ContextOverlay/ContextMenu.stories.tsx‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,12 @@ const Template: StoryFn<typeof ContextMenu> = (args) => (
2323

2424
export const Default = Template.bind({});
2525
Default.args = {
26+
role: "menu",
2627
children: [
27-
<MenuItem key="m0" text={"First option"} />,
28-
<MenuItem key="m1" text={"Item two"}>
29-
<MenuItem key="m2" text={"First sub option"} />
30-
<MenuItem key="m3" text={"Sub item two"} />
28+
<MenuItem key="m0" roleStructure="menuitem" text={"First option"} />,
29+
<MenuItem key="m1" roleStructure="menuitem" text={"Item two"}>
30+
<MenuItem key="m2" roleStructure="menuitem" text={"First sub option"} />
31+
<MenuItem key="m3" roleStructure="menuitem" text={"Sub item two"} />
3132
</MenuItem>,
3233
],
3334
};

‎src/components/ContextOverlay/ContextMenu.tsx‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { CLASSPREFIX as eccgui } from "../../configuration/constants";
55
import { ValidIconName } from "../Icon/canonicalIconNames";
66
import { IconButton, IconButtonProps } from "../Icon/IconButton";
77
import { TestableComponent } from "../interfaces";
8-
import Menu from "../Menu/Menu";
8+
import Menu, { MenuProps } from "../Menu/Menu";
99

1010
import ContextOverlay, { ContextOverlayProps } from "./ContextOverlay";
1111

@@ -19,6 +19,12 @@ export interface ContextMenuProps extends TestableComponent {
1919
* They will be wrapped in a `Menu` element automatically.
2020
*/
2121
children?: React.JSX.Element | React.JSX.Element[];
22+
/**
23+
* Role of the included `Menu` element.
24+
* It defines the `roleStructure` of the `MenuItem` children, e.g. use `listbox` for selectable options.
25+
* It is also used for `aria-haspopup` of the toggler element.
26+
*/
27+
role?: "menu" | "listbox";
2228
/**
2329
* Toggler that need to be used to display menu.
2430
* If a valid icon name is used then the icon element is displayed.
@@ -46,6 +52,11 @@ export interface ContextMenuProps extends TestableComponent {
4652
* Props to spread to `ContextOverlay` that is used to display the dropdown.
4753
*/
4854
contextOverlayProps?: Partial<Omit<ContextOverlayProps, "content" | "children" | "className">>;
55+
/**
56+
* Props to spread to the included `Menu` element, e.g. additional `aria-*` attributes.
57+
* Use the `role` property of `ContextMenu` to set the role of the menu.
58+
*/
59+
menuProps?: Partial<Omit<MenuProps, "children" | "role">>;
4960
/**
5061
* Disables the button to open the menu.
5162
*/
@@ -63,9 +74,11 @@ export interface ContextMenuProps extends TestableComponent {
6374
export const ContextMenu = ({
6475
children,
6576
className = "",
77+
role = "menu",
6678
togglerElement = "item-moremenu",
6779
togglerText = "Show more options",
6880
contextOverlayProps,
81+
menuProps,
6982
disabled,
7083
togglerLarge = false,
7184
togglerSize,
@@ -94,11 +107,15 @@ export const ContextMenu = ({
94107

95108
return (
96109
<ContextOverlay
97-
popupKind={PopupKind.MENU}
98110
{...restProps}
99111
{...contextOverlayProps}
100112
className={`${eccgui}-contextmenu ` + className}
101-
content={<Menu>{children}</Menu>}
113+
content={
114+
<Menu {...menuProps} role={role}>
115+
{children}
116+
</Menu>
117+
}
118+
popupKind={role === "listbox" ? PopupKind.LISTBOX : PopupKind.MENU}
102119
disabled={!!disabled}
103120
usePlaceholder={!preventPlaceholder}
104121
>

‎src/components/ContextOverlay/tests/ContextMenu.test.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
44
import "@testing-library/jest-dom";
55

66
import { CLASSPREFIX as eccgui } from "../../../configuration/constants";
7+
import MenuItem from "../../Menu/MenuItem";
78

89
import ContextMenu from "./../ContextMenu";
910
import { Default as ContextMenuStory } from "./../ContextMenu.stories";
@@ -43,4 +44,49 @@ describe("ContextMenu", () => {
4344
expect(screen.getByRole("button")).toHaveAttribute("aria-haspopup", "menu");
4445
expect(screen.getByRole("menu")).toBeVisible();
4546
});
47+
it("should use role `menu` for the menu by default", async () => {
48+
const { container } = render(<ContextMenu {...ContextMenuStory.args} preventPlaceholder={true} />);
49+
fireEvent.click(container.getElementsByClassName(overlayWrapper)[0]);
50+
expect(await screen.findByRole("menu")).toBeInTheDocument();
51+
});
52+
it("should forward `role` to the menu", async () => {
53+
const { container } = render(
54+
<ContextMenu role="listbox" preventPlaceholder={true}>
55+
<MenuItem text="First option" />
56+
</ContextMenu>,
57+
);
58+
fireEvent.click(container.getElementsByClassName(overlayWrapper)[0]);
59+
expect(await screen.findByRole("listbox")).toBeInTheDocument();
60+
expect(screen.getByRole("option", { name: "First option" })).toBeInTheDocument();
61+
});
62+
it("should forward `menuProps` to the menu", async () => {
63+
const { container } = render(
64+
<ContextMenu
65+
role="listbox"
66+
preventPlaceholder={true}
67+
menuProps={{ "aria-multiselectable": true, "aria-label": "Options", className: "custom-menu" }}
68+
>
69+
<MenuItem text="First option" />
70+
</ContextMenu>,
71+
);
72+
fireEvent.click(container.getElementsByClassName(overlayWrapper)[0]);
73+
const listbox = await screen.findByRole("listbox");
74+
expect(listbox).toHaveAttribute("aria-multiselectable", "true");
75+
expect(listbox).toHaveAttribute("aria-label", "Options");
76+
expect(listbox).toHaveClass("custom-menu");
77+
});
78+
it.each([true, false])(
79+
"should set `aria-haspopup` according to role `listbox` (preventPlaceholder: %s)",
80+
async (preventPlaceholder) => {
81+
const { container } = render(
82+
<ContextMenu role="listbox" preventPlaceholder={preventPlaceholder}>
83+
<MenuItem text="First option" />
84+
</ContextMenu>,
85+
);
86+
expect(screen.getByRole("button")).toHaveAttribute("aria-haspopup", "listbox");
87+
fireEvent.click(container.getElementsByClassName(overlayWrapper)[0]);
88+
expect(await screen.findByRole("listbox")).toBeVisible();
89+
expect(screen.getByRole("button")).toHaveAttribute("aria-haspopup", "listbox");
90+
},
91+
);
4692
});

‎src/components/Menu/Menu.tsx‎

Lines changed: 152 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,160 @@
1-
import React from "react";
2-
import { Menu as BlueprintMenu, MenuProps as BlueprintMenuProps } from "@blueprintjs/core";
1+
import React, { AriaRole } from "react";
2+
import {
3+
Menu as BlueprintMenu,
4+
MenuItem as BlueprintMenuItem,
5+
MenuProps as BlueprintMenuProps,
6+
} from "@blueprintjs/core";
37

48
import { CLASSPREFIX as eccgui } from "../../configuration/constants";
59

6-
export type MenuProps = BlueprintMenuProps;
10+
import MenuDivider, { MenuDividerProps } from "./MenuDivider";
11+
import MenuItem, { MenuItemProps } from "./MenuItem";
12+
13+
/**
14+
* Roles that are supported by the automatic `roleStructure` handling of the `MenuItem` children.
15+
*/
16+
type SupportedMenuRole = "menu" | "navigation" | "list" | "listbox" | "none" | "presentation";
17+
18+
export interface MenuProps extends BlueprintMenuProps {
19+
/**
20+
* Sets the ARIA role of the menu.
21+
* It may become mandatory in a future version.
22+
* Setting a `role` checks whether `MenuItem` and `MenuDivider` children use a correct `roleStructure`, or sets it automatically.
23+
* The automatic checks only work if `MenuItem` and `MenuDivider` are used as direct children or inside a `Fragment`.
24+
* The checks only work for `menu`, `navigation`, `list`, `listbox`, `none` and `presentation`.
25+
* Other roles are applied as they are, and the children are not processed.
26+
*/
27+
role?: SupportedMenuRole | AriaRole;
28+
}
29+
30+
const roleMapping: Partial<Record<SupportedMenuRole, AriaRole>> = {
31+
navigation: "list",
32+
};
33+
34+
const allowedRoleStructure: Record<SupportedMenuRole, NonNullable<MenuItemProps["roleStructure"]>[]> = {
35+
menu: ["menuitem"],
36+
navigation: ["listitem"],
37+
list: ["listitem"],
38+
listbox: ["listoption"],
39+
none: ["none"],
40+
presentation: ["none"],
41+
};
42+
43+
/**
44+
* Allowed values for an explicitly set `role` on `MenuItem` children, regarding their (explicitly or automatically set) `roleStructure`.
45+
* Blueprint sets this `role` on the inner target element of the item, where it overwrites the role defined by `roleStructure`,
46+
* so it must fit to the role of the `li` element that is defined by `roleStructure`.
47+
* A `roleStructure` without entry does not restrict the item role.
48+
*/
49+
const allowedItemRole: Partial<Record<NonNullable<MenuItemProps["roleStructure"]>, AriaRole[]>> = {
50+
menuitem: ["menuitem", "menuitemcheckbox", "menuitemradio"],
51+
listitem: ["link", "button", "none", "presentation"],
52+
// the `li` element already has the `option` role, so the target element must not have an own role
53+
listoption: ["none", "presentation"],
54+
};
55+
56+
/**
57+
* `MenuDivider` children get this role if their `role="separator"` is not allowed inside the (mapped) menu role.
58+
*/
59+
const dividerRoleMapping: Partial<Record<AriaRole, AriaRole>> = {
60+
list: "listitem",
61+
listbox: "none",
62+
};
63+
64+
/**
65+
* Blueprint uses this `roleStructure` by default, so it does not need to be set explicitly.
66+
*/
67+
const defaultRoleStructure: MenuItemProps["roleStructure"] = "menuitem";
68+
69+
/**
70+
* Represents a list of items, used as menu, navigation, options, or only for presentation.
71+
* It sets automatically `roleStructure` for its direct `MenuItem` children (also inside fragments) regarding the set `role`,
72+
* or it emits a console warning if it does not fit to an already set `roleStructure`.
73+
* It also emits a console warning if an explicitly set `role` of a `MenuItem` does not fit to its `roleStructure`.
74+
* On `MenuDivider` children without role or with `role="separator"` it sets `role="listitem"` in lists
75+
* (`role="list"` or `role="navigation"`) and `role="none"` in listboxes, because `separator` is not allowed there.
76+
* It also sets `aria-hidden` then if the divider has no `title` and no own `aria-hidden` value.
77+
* It does not add a `nav` wrapper on `role="navigation"`, you need to do it on your own.
78+
*/
79+
export const Menu = ({ children, className = "", role = "menu", ...restProps }: MenuProps) => {
80+
const isSupportedRole = Object.prototype.hasOwnProperty.call(allowedRoleStructure, role);
81+
const roleMapped = (isSupportedRole && roleMapping[role as SupportedMenuRole]) || role;
82+
const subroles = isSupportedRole ? allowedRoleStructure[role as SupportedMenuRole] : undefined;
83+
const dividerRole = Object.prototype.hasOwnProperty.call(dividerRoleMapping, roleMapped)
84+
? dividerRoleMapping[roleMapped]
85+
: undefined;
86+
87+
// warnings are collected while rendering and emitted by an effect, so they are not repeated on each re-render
88+
const warnings: string[] = [];
89+
90+
const processItems = (
91+
nodes: React.ReactNode,
92+
subroles: NonNullable<MenuItemProps["roleStructure"]>[],
93+
): React.ReactNode =>
94+
React.Children.map(nodes, (child) => {
95+
if (React.isValidElement<{ children?: React.ReactNode }>(child) && child.type === React.Fragment) {
96+
return <React.Fragment key={child.key}>{processItems(child.props.children, subroles)}</React.Fragment>;
97+
}
98+
if (React.isValidElement<MenuDividerProps>(child) && child.type === MenuDivider) {
99+
if (!dividerRole) {
100+
return child;
101+
}
102+
const { role: ownRole, title, "aria-hidden": ariaHidden } = child.props;
103+
return React.cloneElement(child, {
104+
// `separator` is not allowed here, other explicitly set roles are kept
105+
...(!ownRole || ownRole === "separator" ? { role: dividerRole } : {}),
106+
...(!title && ariaHidden === undefined ? { "aria-hidden": true } : {}),
107+
});
108+
}
109+
if (
110+
!React.isValidElement<MenuItemProps>(child) ||
111+
(child.type !== MenuItem && child.type !== BlueprintMenuItem)
112+
) {
113+
return child;
114+
}
115+
const { roleStructure, role: itemRole } = child.props;
116+
const roleStructureUsed = roleStructure ?? subroles[0];
117+
const itemRoles = allowedItemRole[roleStructureUsed];
118+
if (itemRole && itemRoles && !itemRoles.includes(itemRole)) {
119+
warnings.push(
120+
`Menu: MenuItem with role="${itemRole}" does not fit to its roleStructure="${roleStructureUsed}"${
121+
roleStructure ? "" : ` (set automatically for Menu role="${role}")`
122+
}, allowed: ${itemRoles.map((allowedRole) => `"${allowedRole}"`).join(", ")}.`,
123+
);
124+
}
125+
if (!roleStructure) {
126+
// prevent unnecessary cloning if Blueprint's default is used anyway
127+
return subroles[0] === defaultRoleStructure
128+
? child
129+
: React.cloneElement(child, { roleStructure: subroles[0] });
130+
}
131+
if (!subroles.includes(roleStructure)) {
132+
warnings.push(
133+
`Menu: MenuItem with roleStructure="${roleStructure}" does not fit into Menu with role="${role}", allowed: ${subroles
134+
.map((subrole) => `"${subrole}"`)
135+
.join(", ")}.`,
136+
);
137+
}
138+
return child;
139+
});
140+
141+
const items = subroles ? processItems(children, subroles) : children;
142+
143+
// only emit warnings again if they changed
144+
const warningsKey = warnings.join("\n");
145+
React.useEffect(() => {
146+
if (!warningsKey) {
147+
return;
148+
}
149+
warningsKey.split("\n").forEach((warning) => {
150+
// eslint-disable-next-line no-console
151+
console.warn(warning);
152+
});
153+
}, [warningsKey]);
7154

8-
export const Menu = ({ children, className = "", ...restProps }: MenuProps) => {
9155
return (
10-
<BlueprintMenu {...restProps} className={`${eccgui}-menu__list ` + className}>
11-
{children}
156+
<BlueprintMenu role={roleMapped} {...restProps} className={`${eccgui}-menu__list ` + className}>
157+
{items}
12158
</BlueprintMenu>
13159
);
14160
};

‎src/components/Menu/MenuDivider.tsx‎

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,40 @@
11
import React from "react";
2-
import { MenuDivider as BlueprintMenuDivider, MenuDividerProps as BlueprintMenuDividerProps } from "@blueprintjs/core";
2+
import {
3+
Classes as BlueprintClasses,
4+
H6 as BlueprintSeparatorTitle,
5+
MenuDividerProps as BlueprintMenuDividerProps,
6+
} from "@blueprintjs/core";
7+
import classNames from "classnames";
38

49
import { CLASSPREFIX as eccgui } from "../../configuration/constants";
510

6-
export type MenuDividerProps = BlueprintMenuDividerProps;
11+
/**
12+
* Properties of the Blueprint `MenuDivider` and all attributes of the `li` element.
13+
* Use `role="listitem"` if the parent `Menu` is a list, because `separator` is not allowed there.
14+
* `Menu` sets it automatically, and `aria-hidden` for dividers without `title`.
15+
*/
16+
export interface MenuDividerProps
17+
extends
18+
BlueprintMenuDividerProps,
19+
Omit<React.LiHTMLAttributes<HTMLLIElement>, "title" | "children" | "className"> {}
720

8-
export const MenuDivider = ({ children, className = "", ...restProps }: MenuDividerProps) => {
21+
/**
22+
* Divider or section header inside `Menu`.
23+
* It uses the same markup and classes like the Blueprint `MenuDivider`, but supports other roles than `separator`.
24+
*/
25+
export const MenuDivider = ({ className, role = "separator", title, titleId, ...otherLiProps }: MenuDividerProps) => {
926
return (
10-
<BlueprintMenuDivider {...restProps} className={`${eccgui}-menu__divider ` + className}>
11-
{children}
12-
</BlueprintMenuDivider>
27+
<li
28+
{...otherLiProps}
29+
role={role}
30+
className={classNames(
31+
title ? BlueprintClasses.MENU_HEADER : BlueprintClasses.MENU_DIVIDER,
32+
`${eccgui}-menu__divider`,
33+
className,
34+
)}
35+
>
36+
{title && <BlueprintSeparatorTitle id={titleId}>{title}</BlueprintSeparatorTitle>}
37+
</li>
1338
);
1439
};
1540

‎src/components/Menu/MenuItem.tsx‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,18 @@ export interface MenuItemProps
3434
* Visual intent color to apply to element.
3535
*/
3636
intent?: BlueprintMenuItemProps["intent"] | "accent";
37+
/**
38+
* Defines the ARIA role structure that is used for the menu item element and its inner target element.
39+
* It is recommended to set it, even if it is optional right now.
40+
* The value is checked if a `role` is set on the parent `Menu`.
41+
* It may become mandatory in a future version.
42+
*/
43+
roleStructure?: BlueprintMenuItemProps["roleStructure"];
3744
}
3845

3946
/**
4047
* Single item, used as child inside `Menu`.
48+
* It is recommended to use it as a direct child and not to wrap it inside other elements, except `Fragment`.
4149
*/
4250
export const MenuItem = React.forwardRef<HTMLLIElement, MenuItemProps>(
4351
({ children, className = "", icon, onClick, href, text, tooltip, intent, ...restProps }, ref) => {

0 commit comments

Comments
 (0)