# Menu
## Background
### Definition
This spec defines the default function of a `Menu` as an interactive component that displays a list of options that can be represented by a range possible states. Possible variants are defined in [the relevant section](#variants)
The `Menu` should be displayed on a temporary surface that interrupts the normal flow of content. The temporary surface should be triggered by an external user action such as (but not limited to) a click on a button or other UI control.
The interactions that result in the dismiss/removal of the `Menu` component should be configurable.
## Prior art
As a part of the spec definitions in Fluent UI, a research effort has been made through [Open UI](https://open-ui.org/). The current research proposal is available as an open source contribution undergoing review ([research proposal](https://github.com/WICG/open-ui/pull/249))
## Comparison of `@fluentui/react` and `@fluentui/react-northstar`
- All mentions of v7 or v8 == `@fluentui/react` ([docsite](https://developer.microsoft.com/en-us/fluentui#/))
- All mentions of v0 == `@fluentui/react-northstar` ([docsite](https://fluentsite.z22.web.core.windows.net/))
The most relevant comparison that can be achieved between the two libraries is between `ContextualMenu` in v7 and a combination of `Menu`, `Popup` and `ToolbarItem` in v0.
v0 suffers from a consistency issue that the control used in `Menu` and the menu variant of `ToolbarItem` are not actually the same component and have different behavior. However, semantically for the purposes of this spec, they representthe same control that will be implemented.
Note that the below code samples are not meant to be complete, but to highlight differences between the two libraries. Please refer to official docsites for actual API references.
### Positioning
Please refer to the `react-popover` spec for more detailled comparison of positionining between v9 and v0.
### Trigger vs target
The v7 `ContextualMenu` has a prop `target` which is intended to be a ref to the DOM element that the positioning logic anchors to. The usage of this prop requires the visibility state of the component to be controlled using React state by the consumer. The same prop exists on the v0 `Popup` component that is intended to perform the same function.
```tsx
const buttonRef = React.useRef()
// V7/8
// v0 - shorthand
```
The v0 `Popup` component has an alternative prop, `trigger`, which accepts a React component. This prop simplifies the creation of temporary content by autocontrolling the open/dismiss functionality.
```tsx
// v0 - shorthand trigger
}
content={...}
/>
// v0 - children trigger
} title="Show popup" />
```
### Layout variations
The v7 `ContextualMenu` only has one primary layout which is a vertical list of menu items.
The v0 `Menu` component differs clearly in this that the default layout is a horizontal menu. To achieve the same layout as `ContextualMenu` (and the layout defined in this spec) it's necessary to use the `vertical` prop which is `false` by default.
```tsx
```
### Open/Dismiss events
The v7 `ContextualMenu` is intended to be used as a controlled component. The visibiltiy of the menu is controlled using the `hidden` prop whose value should be React state of the cosumer. A separate `onDismiss` prop can also be used that will be invoked during events where the callout tries to close, i.e. click outside the content.
The v0 `Popup` should be compared here, since the v0 `Menu` does not handle open/dismiss events. `Popup` visibility can be controlled using the `open` prop. `Popup` provides a callback prop `onOpenChange` which can be used both to open and dismiss.
As mentioned above, `Popup` implements an autocontrolled pattern which allows both controlled an uncontrolled variants to be used in its API.
```tsx
// v7 controlled ContextualMenu
const [showContextualMenu, setShowContextualMenu] = React.useState(false);
const onShowContextualMenu = () => setShowContextualMenu(true);
const onHideContextualMenu = () => setShowContextualMenu(false);
;
// v0 uncontrolled Popup
const [open, setOpen] = React.useState(false);
{/*react on changes*/}}
trigger={} title="Open popup" />}
/>;
// v0 controlled Popup - used with trigger disables autocontrol
const [open, setOpen] = React.useState(false);
setOpen(!props.open)}
trigger={} title="Open popup" />}
/>;
```
### Keyboard navigation
Both v7 and v0 support arrow navigation in the menu, and home/end keys to jump to first and last items respectively.
One interesting difference is that the v7 `ContextualMenu` will also tab through items. The v0 `Menu` on the other hand uses tab to focus in/out of the entire component.
`ContextualMenu` will also allow disabled items to be focusable while navigating the list, while the v0 `Menu` does not permit this.
### Selection state
The v0 `Menu` component supports and `active` state and has a number of props to manage this state. However, this state only affects items visually and does not perform the same function as menu item checkboxes or radio items. The `active` state of menu items can both be controlled and autocontrolled
```tsx
// v0 autocontrolled active index with default
// v0 autocontrolled active index controlled
// shorthand variation
const items = [
{
key: 'editorials',
content: 'Editorials',
},
]
```
In order to obtain semantically meaningful selection state in v0, the only possible way is to use a `Toolbar` component. The menu that is rendered in this component is completely different but supports both checkbox and radio selection states through the use of an `active` prop and must be controlled.
```tsx
// Toolbar with one item that opens a selectable menu
const toolbarItems = [
{
icon: ,
title: 'More',
menu: [
{
active: true,
content: 'Bold',
kind: 'toggle',
// kind: 'radio', // for radio
onClick: handleToggleClick,
},
{
active: false,
content: 'Italic',
kind: 'toggle',
// kind: 'radio', // for radio
},
],
menuOpen,
onMenuOpenChange: (e, { menuOpen }) => setMenuOpen(menuOpen),
},
]
```
The v7 `ContextualMenu` on the other hand, only supports the checkbox selection state implicitly. This behavior must be controlled by consumers and uses `canCheck` and `isChecked` props:
```tsx
const menuProps = {
shouldFocusOnMount: true,
items: [
{
text: 'New',
canCheck: true,
isChecked: true,
onClick: onToggleSelect,
},
{
text: 'Share',
canCheck: true,
isChecked: false,
onClick: onToggleSelect,
},
],
};
// shorthand usage in a menu button
;
```
### DOM output
Below are some sample DOM outputs to compare for certain scenarios. Not all DOM attributes are reflected here, a subset have been chosen to provide easier reading and comparison.
#### Basic menu
Both the current v7 and v0 versions of this control use the `ul` and `li` combination along with content wrapper elements. This makes style overrides kind of complicated to target and also makes custom rendering difficult since there is the added complexity of targeting stricter DOM structures.
`ul`/`li` combinations are also very strict in markdown and might not play well with newer concepts like virtualization and custom scrollbars where arbitrary `div` elements can be inserted into the DOM.
In terms off A11y and narration there is effectively no difference in having a wrapping element or not. Would useful in the proposed new API to use a simpler DOM structure that provides more flexibility.
```html
```
### Menu divider
```html
```
### Custom rendering and data
v7 provides render callbacks that can be used to render either the entire menu list or specific slots of menut items. Each call back provides the props avaialble to that slot and a `defaultRender` which allows to easily extend the original render, if required.
```tsx
// v7 custom rendering
const menuProps = {
onRenderMenuList: (props: IContextualMenuListProps, defaultRenderer) => {},
onRenderSubMenu: (props: IContextualMenuProps, defaultRenderer) => {},
items: [
{
onRender: (
item: any,
dismissMenu: (ev?: any, dismissAll?: boolean) => void
) => React.ReactNode
}
{onRenderContent: (props: IContextualMenuItemProps, defaultRenderer) => {}},
{onRenderIcon: (props: IContextualMenuItemProps, defaultRenderer) => {}},
]
}
```
Custom data can also be associated with menu items
```tsx
const menuProps = {
items: [{
...
data: { foo: "bar" }
}]
}
```
v0 custom rendering through shorthand components is a consistent experience through all shorthand components, but provide a smaller API surface (whether this is simpler or less powerful can be subjective). Custom rendering in the case of the `Menu` component would be done through the use of `children` prop either through the standard React child component API or through shorthand as a callback function.
```tsx
// v0 shorthand children render callback
const items = [
{
key: 'editorials',
children: (El, props) => {props.key}
},
]
// v0 children API custom render
```
## Variants
### Nested menus
A `Menu` should be able to trigger an additional instance of itself as a part of one or more of its options. The nested `Menu` component should have the same functional capabilities as the root `Menu` component.
The actions that trigger the the nested `Menu` should be be consistent with the actions that can trigger any root `Menu` from a similar UI control.
We advise that no more than two nested `Menu` components be used, but this spec does not functionally apply that constrain to the implementation of the `Menu` component.
### Selection state
A `Menu` should be able to track and represent the selection state of all or some of its options if required.
When an options is associated with a selection state. The `Menu`, either root or nested, should control its dismiss behavior accordingly based on configuration.
### Sections
A `Menu` can be partitioned into sections using visible dividers in its list of options. Each section can contain a heading title that announces or briefly describes the options in the particular section
### Secondary label
An option of a `Menu` component should be able to declare additional secondary label that can provide additional context describing the option or its usage.
For example a secondary label can be a label that shows a keyboard shortcut that will perform an equivalent action of the option of the `Menu` component.
### Split option with nesting
An option of a `Menu` component can trigger a nested `Menu` component and also perform its default action by splitting the option into two interactable areas that handle each action separately.
### Disabled option(s)
All options in a `Menu` component can be disabled and should provide a visible indication for this purpose. User interaction should be defined for disabled options
### Scrollable
A `Menu` should display a vertical scrollbar when the number of options exceeds the height of the component
### Standalone/No surface
A `Menu` can be used without the temporary popup surface and its trigger. This will allow `Menu` components to be permanent page content or used in custom surfaces with a wider range of UI components.
### Custom content
```
This variant is still a work in progress and needs additional thought
```
Any custom content can be used in the rendering of the Menu, all interactions and accessibility is left to the discretion of the consumer.
## API
The `Menu` should implement a `children` based API as is the standard across all the surveyed alternatives as a part of Open UI research in [Prior Art](#prior-art). The component will leverage the use of `context` in the interaction and data flows of child components.
Sample usages will be give in the following section of this document [Sample code](#sample-code)
### Menu
The root level component serves as a simplified interface (sugar) for popup positioning and triggering.
```typescript
export type MenuProps = MenuListProps &
Pick'> & {
/**
* Explicitly require children
*/
children: React.ReactNode;
/**
* Whether the popup is open
*/
open?: boolean;
/**
* Call back when the component requests to change value
* The `open` value is used as a hint when directly controlling the component
*/
onOpenChange?: (e: MenuOpenEvents, data: MenuOpenChangeData) => void;
/**
* Whether the popup is open by default
*/
defaultOpen?: boolean;
/**
* Wrapper to style and add events for the popup
*/
menuPopup?: ShorthandProps>;
/*
* Opens the menu on hover
*/
openOnHover?: boolean;
/**
* Opens the menu on right click (context menu), removes all other menu open interactions
*/
openOnContext?: boolean;
/**
* Root menus are rendered out of DOM order on `document.body`, use this to render the menu in DOM order
* This option is disregarded for submenus
*/
inline?: boolean;
};
```
### MenuTrigger
A non-visual component that wraps its child and configures them to be the trigger that will open a menu. This component should only accept one child
```typescript
export type MenuTriggerProps = {
/**
* Explicitly require single child
*/
children: React.ReactElement;
};
```
### MenuList
This component is used internally by `Menu` and manages the context and layout its items.
`MenuList` can also be used separately as the standalone variant of the `Menu`, since it should not control popup positioning or triggers. It is the only component in the API that can be used standalone. Envisioned to be used with more complex popup or trigger scenarios where the `Menu` component does not provide enough control for these situations.
```typescript
export type MenuListProps = ComponentProps &
React.HTMLAttributes & {
/**
* Callback when checked items change for value with a name
*
* @param name - the name of the value
* @param checkedItems - the items for this value that are checked
*/
onCheckedValueChange?: (e: React.MouseEvent | React.KeyboardEvent, name: string, checkedItems: string[]) => void;
/**
* Map of all checked values
*/
checkedValues?: Record;
/**
* Default values to be checked on mount
*/
defaultCheckedValues?: Record;
/**
* States that menu items can contain icons and reserve slots for item alignment
*/
hasIcons?: boolean;
/**
* States that menu items can contain selectable items and reserve slots for item alignment
*/
hasCheckmarks?: boolean;
};
```
### MenuGroup
Creates a group inside a `MenuList`, setting up header layout and dividers between `MenuItems`.
The MenuGroup is also a useful component to declare different selection groups (checkbox/radio) in a `MenuList`.
> This component only accepts native DOM attributes as props.
### MenuGroupHeader
Creates a section header element with appropriate styling. Will set correct `aria-labelledby` relationship if it is instantiated within a [MenuGroup](#menugroup)
> This component only accepts native DOM attributes as props.
### MenuDivider
Creates a divider element in the `MenuList` with correct HTML and aria semantics for divider.
This divider is purely a visual cue. To ensure consistent narration experience across all screenreaders [MenuGroup](#menugroup) should be used
> This component only accepts native DOM attributes as props.
### MenuItem
```typescript
export type MenuItemProps = ComponentProps &
React.HTMLAttributes & {
/**
* Icon slot rendered before children content
*/
icon?: ShorthandProps>;
/**
* A helper slot for alignment when a menu item is used with selectable menuitems
* Avoid using this slot as a replacement for MenuItemCheckbox and MenuItemRadio components
*/
checkmark?: ShorthandProps>;
/**
* Icon slot that shows the indicator for a submenu
*/
submenuIndicator?: ShorthandProps>;
/**
* Component children are placed in this slot
* Avoid using the `children` property in this slot in favour of Component children whenever possible
*/
content?: ShorthandProps>;
/**
* Secondary content rendered opposite the primary content (e.g Shortcut text)
*/
secondaryContent?: ShorthandProps>;
/**
* If the menu item is a trigger for a submenu
*/
hasSubmenu?: boolean;
/**
* Applies disabled styles to menu item but remains focusable
*/
disabled?: boolean;
/**
* Clicking on the menu item will not dismiss an open menu
*/
persistOnClick?: boolean;
};
```
### MenuItemCheckbox/Radio
Variants of `MenuItem` that allows a single or multiple selection state based on the value that it represents. API is intended to mirror that of HTML inputs
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
```typescript
/**
* Props for selecatble menu items
*/
export type MenuItemSelectableProps = React.HTMLAttributes & {
/**
* Follows input convention
* https://www.w3schools.com/jsref/prop_checkbox_name.asp
*/
name: string;
/**
* Follows input convention
* https://www.w3schools.com/jsref/prop_checkbox_value.asp
*/
value: string;
/**
* Whether the selectable item is disabled
*/
disabled?: boolean;
};
export type MenuItemCheckboxProps = ComponentProps &
React.HTMLAttributes &
MenuItemProps &
MenuItemSelectableProps & {
/**
* Slot for the checkmark indicator
*/
checkmark?: ShorthandProps>;
};
export type MenuItemRadioProps = ComponentProps &
React.HTMLAttributes &
MenuItemProps &
MenuItemSelectableProps & {
checkmark?: ShorthandProps>;
};
```
## Sample code
The below samples do not represent the definitive props of the final implemented component, but represent the ideal final implementations. Can be subject to change during the implementation phase.
### Basic Menu
```tsx
const menu = (