Popover menu
A button that opens a menu beside it, walked with the arrow keys and closed with Escape or a press outside.
Goal
An actions menu on a row, a card or a toolbar. Opening moves focus into the menu, the arrow keys move between items, and every way of closing it ends with focus back on the button that opened it when the user did not choose to go elsewhere.
Primitives
- PopoverController shows the panel beside the button and keeps it positioned. With
onDismissset, it also reports an outside press, focus leaving and Escape through a DismissController it owns, so the recipe does not add a second one.portal: falsekeeps the panel where it is. - RovingController gives the menu items one tab stop and moves it with the arrows, Home and End.
Left to the recipe: the open flag, moving focus into the menu on open, and returning focus to the button. The popover reports why it was dismissed and does not restore focus, because that depends on the reason: after Escape or choosing an item the button gets focus, after a press elsewhere the press already moved it.
Example
Open the menu with the button, move with the arrow keys, choose with Enter, or press Escape to close it. Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.
The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.
Menu closed
import { RadiantElement, customElement, onEvent, query, queryAll } from '@ecopages/radiant';
import { createPopoverController, createRovingController } from '@ecopages/radiant-ui/controllers';
@customElement('popover-menu-element')
export class PopoverMenuElement extends RadiantElement {
@query('button') private trigger!: HTMLElement;
@query('[role="menu"]') private menu!: HTMLElement;
@queryAll('[role="menuitem"]') private items!: HTMLElement[];
@query('[data-status]') private status!: HTMLElement;
private open = false;
private readonly menuPopover = createPopoverController(this, {
getAnchor: () => this.trigger,
getFloating: () => this.menu,
getOpen: () => this.open,
getPlacement: () => 'bottom-start',
portal: false,
onDismiss: (reason) => this.setOpen(false, reason === 'escape'),
});
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.menu,
orientation: 'vertical',
});
override onConnected(): void {
this.roving.sync();
}
private setOpen(next: boolean, restoreFocus = false): void {
this.open = next;
this.menuPopover.sync();
this.trigger.setAttribute('aria-expanded', String(next));
this.status.textContent = next ? 'Menu open' : 'Menu closed';
if (next) {
this.roving.sync();
this.roving.focus(this.items[0]);
} else if (restoreFocus) {
this.trigger.focus();
}
}
@onEvent({ selector: 'button[aria-haspopup]', type: 'click' })
toggle(): void {
this.setOpen(!this.open, true);
}
@onEvent({ selector: '[role="menuitem"]', type: 'click' })
choose(event: Event): void {
this.setOpen(false, true);
this.status.textContent = `Chose ${(event.target as HTMLElement).textContent}`;
}
}<popover-menu-element>
<button type="button" aria-haspopup="menu" aria-expanded="false">Actions</button>
<div role="menu" aria-label="Actions" hidden>
<button type="button" role="menuitem">Rename</button>
<button type="button" role="menuitem">Duplicate</button>
<button type="button" role="menuitem">Delete</button>
</div>
<p data-status aria-live="polite">Menu closed</p>
</popover-menu-element>.primitive-example:has(
> popover-menu-element,
> popover-menu-app,
> [data-controller='popover-menu'],
> [data-example='popover-menu']
) {
flex-direction: column;
align-items: flex-start;
min-height: 13rem;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'] {
display: flex;
flex-direction: column;
align-items: stretch;
min-width: 10rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
box-shadow: var(--shadow-overlay);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'][hidden] {
display: none;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem'] {
padding: var(--space-2) var(--space-3);
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--on-surface-container);
font: inherit;
text-align: left;
cursor: pointer;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:hover {
background: var(--surface-container-high);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:focus-visible {
background: var(--primary);
color: var(--on-primary);
outline-offset: -2px;
}createPopoverController(this, ...) and createRovingController(this, ...) are held in fields because the element calls them when the menu opens; both attach when the element connects and are destroyed when it disconnects, as are the @onEvent listeners. The popover still reports the dismissal reason, so the element decides whether focus returns to the button. sync() goes in onConnected because the items exist only after the element has its children.
What the Radiant form removes: the mount function and its registration, the cleanup to return and call, and the re-run after a client-side navigation.
The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.
Menu closed
import { RadiantElement, customElement, onEvent, query, queryAll } from '@ecopages/radiant';
import { createPopoverController, createRovingController } from '@ecopages/radiant-ui/controllers';
@customElement('popover-menu-element')
export class PopoverMenuElement extends RadiantElement {
@query('button') private trigger!: HTMLElement;
@query('[role="menu"]') private menu!: HTMLElement;
@queryAll('[role="menuitem"]') private items!: HTMLElement[];
@query('[data-status]') private status!: HTMLElement;
private open = false;
private readonly menuPopover = createPopoverController(this, {
getAnchor: () => this.trigger,
getFloating: () => this.menu,
getOpen: () => this.open,
getPlacement: () => 'bottom-start',
portal: false,
onDismiss: (reason) => this.setOpen(false, reason === 'escape'),
});
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.menu,
orientation: 'vertical',
});
override onConnected(): void {
this.roving.sync();
}
private setOpen(next: boolean, restoreFocus = false): void {
this.open = next;
this.menuPopover.sync();
this.trigger.setAttribute('aria-expanded', String(next));
this.status.textContent = next ? 'Menu open' : 'Menu closed';
if (next) {
this.roving.sync();
this.roving.focus(this.items[0]);
} else if (restoreFocus) {
this.trigger.focus();
}
}
@onEvent({ selector: 'button[aria-haspopup]', type: 'click' })
toggle(): void {
this.setOpen(!this.open, true);
}
@onEvent({ selector: '[role="menuitem"]', type: 'click' })
choose(event: Event): void {
this.setOpen(false, true);
this.status.textContent = `Chose ${(event.target as HTMLElement).textContent}`;
}
}<popover-menu-element>
<button type="button" aria-haspopup="menu" aria-expanded="false">Actions</button>
<div role="menu" aria-label="Actions" hidden>
<button type="button" role="menuitem">Rename</button>
<button type="button" role="menuitem">Duplicate</button>
<button type="button" role="menuitem">Delete</button>
</div>
<p data-status aria-live="polite">Menu closed</p>
</popover-menu-element>.primitive-example:has(
> popover-menu-element,
> popover-menu-app,
> [data-controller='popover-menu'],
> [data-example='popover-menu']
) {
flex-direction: column;
align-items: flex-start;
min-height: 13rem;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'] {
display: flex;
flex-direction: column;
align-items: stretch;
min-width: 10rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
box-shadow: var(--shadow-overlay);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'][hidden] {
display: none;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem'] {
padding: var(--space-2) var(--space-3);
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--on-surface-container);
font: inherit;
text-align: left;
cursor: pointer;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:hover {
background: var(--surface-container-high);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:focus-visible {
background: var(--primary);
color: var(--on-primary);
outline-offset: -2px;
}createPopoverController(this, ...) and createRovingController(this, ...) are held in fields because the element calls them when the menu opens; both attach when the element connects and are destroyed when it disconnects, as are the @onEvent listeners. The popover still reports the dismissal reason, so the element decides whether focus returns to the button. sync() goes in onConnected because the items exist only after the element has its children.
What the Radiant form removes: the mount function and its registration, the cleanup to return and call, and the re-run after a client-side navigation.
The same menu as one self-contained tag. The element owns its markup: it keeps the open flag and the status as state and draws the button, the menu and the status line with render(), so there is no markup to author or copy and the page holds only the tag.
import { RadiantElement, customElement, onEvent, state } from '@ecopages/radiant';
import { createPopoverController, createRovingController } from '@ecopages/radiant-ui/controllers';
const actions = ['Rename', 'Duplicate', 'Delete'];
@customElement('popover-menu-app')
export class PopoverMenuApp extends RadiantElement<{ status: string }> {
@state open = false;
@state status = 'Menu closed';
private readonly menuPopover = createPopoverController(this, {
getAnchor: () => this.querySelector<HTMLElement>('button[aria-haspopup]'),
getFloating: () => this.querySelector<HTMLElement>('[role="menu"]'),
getOpen: () => this.open,
getPlacement: () => 'bottom-start',
portal: false,
onDismiss: (reason) => this.setOpen(false, reason === 'escape'),
});
private readonly roving = createRovingController(this, {
getItems: () => [...this.querySelectorAll<HTMLElement>('[role="menuitem"]')],
getTarget: () => this.querySelector<HTMLElement>('[role="menu"]'),
orientation: 'vertical',
});
/**
* Attaches the roving controller to the menu the render produced.
*
* @remarks
* The controllers attach when the element connects, before the first render, when no menu exists yet; a later
* `attach()` and `sync()` resolve the menu and its items again.
*/
protected override updated(): void {
this.roving.attach();
this.roving.sync();
}
private setOpen(next: boolean, restoreFocus = false): void {
this.open = next;
this.menuPopover.sync();
this.status = next ? 'Menu open' : 'Menu closed';
if (next) {
this.roving.sync();
this.roving.focus(this.querySelector<HTMLElement>('[role="menuitem"]')!);
} else if (restoreFocus) {
this.querySelector<HTMLElement>('button[aria-haspopup]')!.focus();
}
}
@onEvent({ selector: 'button[aria-haspopup]', type: 'click' })
toggle(): void {
this.setOpen(!this.open, true);
}
@onEvent({ selector: '[role="menuitem"]', type: 'click' })
choose(event: Event): void {
this.setOpen(false, true);
this.status = `Chose ${(event.target as HTMLElement).textContent}`;
}
override render() {
return (
<>
<button type="button" aria-haspopup="menu" aria-expanded={this.open ? 'true' : 'false'}>
Actions
</button>
<div role="menu" aria-label="Actions" hidden={!this.open}>
{actions.map((action) => (
<button key={action} type="button" role="menuitem">
{action}
</button>
))}
</div>
<p data-status aria-live="polite">
{this.$.status}
</p>
</>
);
}
}.primitive-example:has(
> popover-menu-element,
> popover-menu-app,
> [data-controller='popover-menu'],
> [data-example='popover-menu']
) {
flex-direction: column;
align-items: flex-start;
min-height: 13rem;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'] {
display: flex;
flex-direction: column;
align-items: stretch;
min-width: 10rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
box-shadow: var(--shadow-overlay);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'][hidden] {
display: none;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem'] {
padding: var(--space-2) var(--space-3);
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--on-surface-container);
font: inherit;
text-align: left;
cursor: pointer;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:hover {
background: var(--surface-container-high);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:focus-visible {
background: var(--primary);
color: var(--on-primary);
outline-offset: -2px;
}open and status are @state, so aria-expanded, hidden and the status text follow from render() and setOpen no longer writes them. The controllers still read the live DOM, so they look the button, the menu and the items up with querySelector in their getters instead of holding @query fields. The popover shows the menu in sync(), ahead of the render, so focus can move into it at once; updated(), which runs after each commit, attaches and syncs the roving controller to the menu the render produced. The status line is bound with this.$.status, so announcing patches one text node.
Compared with the Radiant element above, the markup lives inside the element, so there is nothing to keep in step with the page and the labels are data you can change, but restyling the structure means editing the class. It also needs the render path on the server to have content before the script runs: this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads, which a page of authored children does not.
The same behavior as a RadiantController attached to markup that already exists. There is no custom element tag: the root is a plain div carrying data-controller="popover-menu", and the class finds its parts with @query just as the element does.
Menu closed
import { RadiantController, controller, onEvent, query, queryAll } from '@ecopages/radiant';
import { createPopoverController, createRovingController } from '@ecopages/radiant-ui/controllers';
/**
* @remarks
* `RadiantController` has the two registration methods a radiant-ui `ControllerHost` needs, so the `createX(this, ...)`
* factories bind to it as they do to an element: attached on `connect()`, destroyed on `disconnect()`.
*/
@controller('popover-menu')
export class PopoverMenuController extends RadiantController {
@query('button') private trigger!: HTMLElement;
@query('[role="menu"]') private menu!: HTMLElement;
@queryAll('[role="menuitem"]') private items!: HTMLElement[];
@query('[data-status]') private status!: HTMLElement;
private open = false;
private readonly menuPopover = createPopoverController(this, {
getAnchor: () => this.trigger,
getFloating: () => this.menu,
getOpen: () => this.open,
getPlacement: () => 'bottom-start',
portal: false,
onDismiss: (reason) => this.setOpen(false, reason === 'escape'),
});
private readonly roving = createRovingController(this, {
getItems: () => this.items,
getTarget: () => this.menu,
orientation: 'vertical',
});
override connect(): void {
super.connect();
this.roving.sync();
}
private setOpen(next: boolean, restoreFocus = false): void {
this.open = next;
this.menuPopover.sync();
this.trigger.setAttribute('aria-expanded', String(next));
this.status.textContent = next ? 'Menu open' : 'Menu closed';
if (next) {
this.roving.sync();
this.roving.focus(this.items[0]);
} else if (restoreFocus) {
this.trigger.focus();
}
}
@onEvent({ selector: 'button[aria-haspopup]', type: 'click' })
toggle(): void {
this.setOpen(!this.open, true);
}
@onEvent({ selector: '[role="menuitem"]', type: 'click' })
choose(event: Event): void {
this.setOpen(false, true);
this.status.textContent = `Chose ${(event.target as HTMLElement).textContent}`;
}
}<div data-controller="popover-menu">
<button type="button" aria-haspopup="menu" aria-expanded="false">Actions</button>
<div role="menu" aria-label="Actions" hidden>
<button type="button" role="menuitem">Rename</button>
<button type="button" role="menuitem">Duplicate</button>
<button type="button" role="menuitem">Delete</button>
</div>
<p data-status aria-live="polite">Menu closed</p>
</div>.primitive-example:has(
> popover-menu-element,
> popover-menu-app,
> [data-controller='popover-menu'],
> [data-example='popover-menu']
) {
flex-direction: column;
align-items: flex-start;
min-height: 13rem;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'] {
display: flex;
flex-direction: column;
align-items: stretch;
min-width: 10rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
box-shadow: var(--shadow-overlay);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'][hidden] {
display: none;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem'] {
padding: var(--space-2) var(--space-3);
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--on-surface-container);
font: inherit;
text-align: left;
cursor: pointer;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:hover {
background: var(--surface-container-high);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:focus-visible {
background: var(--primary);
color: var(--on-primary);
outline-offset: -2px;
}The class is registered with @controller('popover-menu') and nothing in the file starts it: one registry the docs site starts over the document attaches it to every data-controller="popover-menu" element, including markup inserted later, and disconnects it when the element is removed. createPopoverController(this, ...) and createRovingController(this, ...) accept the controller as their host, so they attach on connect and are destroyed on disconnect, as are the @onEvent listeners.
Compared with the Radiant element, there is no tag to define, so the markup can come from a server or a CMS and only needs the attribute. The differences are small: the controller has no onConnected, so the first roving.sync() goes in a connected callback registered in the constructor, and something outside the class has to start the registry.
A mount function wires the controllers to one element and returns the cleanup that undoes it.
Menu closed
import { PopoverController, RovingController } from '@ecopages/radiant-ui/controllers';
export function mount(root: HTMLElement): () => void {
const trigger = root.querySelector('button')!;
const menu = root.querySelector<HTMLElement>('[role="menu"]')!;
const status = root.querySelector('[data-status]')!;
const items = [...menu.querySelectorAll<HTMLElement>('[role="menuitem"]')];
let open = false;
const popover = new PopoverController({
getAnchor: () => trigger,
getFloating: () => menu,
getOpen: () => open,
getPlacement: () => 'bottom-start',
portal: false,
onDismiss: (reason) => setOpen(false, reason === 'escape'),
});
const roving = new RovingController({
getItems: () => items,
getTarget: () => menu,
orientation: 'vertical',
});
function setOpen(next: boolean, restoreFocus = false): void {
open = next;
popover.sync();
trigger.setAttribute('aria-expanded', String(open));
status.textContent = open ? 'Menu open' : 'Menu closed';
if (open) {
roving.sync();
roving.focus(items[0]);
} else if (restoreFocus) {
trigger.focus();
}
}
popover.attach();
roving.attach();
roving.sync();
trigger.addEventListener('click', () => setOpen(!open, true));
for (const item of items) {
item.addEventListener('click', () => {
setOpen(false, true);
status.textContent = `Chose ${item.textContent}`;
});
}
return () => {
popover.destroy();
roving.destroy();
};
}<div data-example="popover-menu">
<button type="button" aria-haspopup="menu" aria-expanded="false">Actions</button>
<div role="menu" aria-label="Actions" hidden>
<button type="button" role="menuitem">Rename</button>
<button type="button" role="menuitem">Duplicate</button>
<button type="button" role="menuitem">Delete</button>
</div>
<p data-status aria-live="polite">Menu closed</p>
</div>.primitive-example:has(
> popover-menu-element,
> popover-menu-app,
> [data-controller='popover-menu'],
> [data-example='popover-menu']
) {
flex-direction: column;
align-items: flex-start;
min-height: 13rem;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'] {
display: flex;
flex-direction: column;
align-items: stretch;
min-width: 10rem;
margin: 0;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
box-shadow: var(--shadow-overlay);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menu'][hidden] {
display: none;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem'] {
padding: var(--space-2) var(--space-3);
border: 0;
border-radius: var(--radius-control);
background: transparent;
color: var(--on-surface-container);
font: inherit;
text-align: left;
cursor: pointer;
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:hover {
background: var(--surface-container-high);
}
:is([data-example='popover-menu'], popover-menu-element, popover-menu-app, div[data-controller='popover-menu'])
[role='menuitem']:focus-visible {
background: var(--primary);
color: var(--on-primary);
outline-offset: -2px;
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.
Styles
The menu hides with hidden and sits in the flow under the button; add position: absolute to float it over what follows. The stylesheet is the popover-menu.css tab in the files above.