# Menu

The WAI-ARIA menu button. There is no native menu element, so the platform gives the popover half (`popover="auto"`: the top layer, light dismiss, Escape, nesting for submenus, placement next to the trigger, focus return) and the library gives the menu half: the current item, arrow keys, Home and End, typeahead, submenu keys and closing the menu when focus leaves it. And the asynchronous half: an item's `action` runs in a transition with `data-pending` on the item, and the menu closes in the commit that ends it, so a slow Server Function behind "Archive" shows its progress where the user clicked and the menu leaves with a view transition in every engine.

## Anatomy

```tsx
import { Menu } from "@funstack/ui/menu";

<Menu.Root>                                                {/* no DOM: ids, open state */}
  <Menu.Trigger>Actions</Menu.Trigger>                     {/* button[popovertarget][aria-haspopup=menu] */}
  <Menu.Popup>                                             {/* div[popover=auto][role=menu] */}
    <Menu.Item action={rename}>Rename</Menu.Item>          {/* button[role=menuitem] */}
    <Menu.Separator />                                     {/* hr role="separator" */}
    <Menu.Group>                                           {/* div[role=group] */}
      <Menu.GroupLabel>View</Menu.GroupLabel>
      <Menu.CheckboxItem checked={dense} checkedChangeAction={saveDense}>Dense</Menu.CheckboxItem>
      <Menu.RadioGroup value={sort} valueChangeAction={saveSort}>
        <Menu.RadioItem value="name">By name</Menu.RadioItem>
        <Menu.RadioItem value="date">By date</Menu.RadioItem>
      </Menu.RadioGroup>
    </Menu.Group>
    <Menu.Root>                                            {/* a Root inside a Popup: a submenu */}
      <Menu.SubmenuTrigger>Move to</Menu.SubmenuTrigger>   {/* button[role=menuitem][aria-haspopup=menu] */}
      <Menu.Popup>…</Menu.Popup>                           {/* opens to the right */}
    </Menu.Root>
  </Menu.Popup>
</Menu.Root>
```

- **Always [library mode](../concepts/browser-owned-state.md#js-free-mode).** A menu cannot follow the APG without JavaScript, so there is no JS-free mode. The Trigger still renders `popovertarget`: a click before hydration opens the (still empty) menu natively and the items fill in on hydration (`reason: "platform"`).
- **Items are buttons** with explicit roles, `tabindex="-1"` and `type="button"`. `render` can substitute a link (`render={<a href="/new" />}`): Enter clicks it, so it navigates and runs the item's action.
- **A submenu is a nested Root** whose trigger is a `Menu.SubmenuTrigger`, an item of the parent menu. Submenus are DOM descendants of their parent popup: nothing is portalled.
- No Portal, Positioner, Arrow or Close part. A "Cancel" item is an `Item` with no `action`: activating it only closes. The Trigger names the menu (`aria-labelledby`).

```tsx title="MenuRowActions.tsx"
"use client";
import { startTransition, useState } from "react";
import { Menu } from "@funstack/ui/menu";
import type { MenuOpenChangeDetails } from "@funstack/ui/menu";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

// Each item's `action` runs in the item's own transition: the item shows data-pending (here a
// "…" label) while the fake server call runs, and the whole menu closes when it settles, with a
// view transition (`transition` on the Popup). "Move to" is a submenu: hover it, or press
// ArrowRight. A rejection reaches the Error Boundary inside the Popup and the menu stays open.
export function MenuRowActions() {
  const [status, setStatus] = useState("Report.pdf");
  const [last, setLast] = useState("(none yet)");
  const [fail, setFail] = useState(false);
  const record = (open: boolean, { reason }: MenuOpenChangeDetails) => {
    setLast(`openChangeAction(${open}, "${reason}")`);
  };
  // Escape, a click outside, Tab: facts, reported synchronously and not awaited.
  const recordFact = (open: boolean, { reason }: MenuOpenChangeDetails) => {
    setLast(`onOpenChange(${open}, "${reason}")`);
  };
  const done = (text: string) => () => setStatus(text);

  return (
    <div className="demo-stack">
      <div className="demo-row">
        <span>{status}</span>
        <Menu.Root openChangeAction={record} onOpenChange={recordFact}>
          <Menu.Trigger className="demo-button" aria-label="Actions for Report.pdf">
            {({ pending }) => (pending ? <span className="demo-spinner" aria-hidden /> : "⋯")}
          </Menu.Trigger>
          <Menu.Popup
            className="demo-menu"
            transition={{
              "fsui-menu-open": "menu-in",
              "fsui-menu-close": "menu-out",
              default: "none",
            }}
          >
            <DemoErrorBoundary>
              <Menu.Item action={done("Report.pdf (renamed)")}>Rename</Menu.Item>
              <Menu.Item
                action={async () => {
                  await fakeSave("the archive", { ms: 1200, fail });
                  // After an await: wrap the update in startTransition (React limitation).
                  startTransition(done("Report.pdf (archived)"));
                }}
              >
                {({ pending }) => (pending ? "Archiving…" : "Archive")}
              </Menu.Item>
              <Menu.Item disabled>Share</Menu.Item>
              <Menu.Separator />
              <Menu.Root>
                <Menu.SubmenuTrigger>Move to</Menu.SubmenuTrigger>
                <Menu.Popup className="demo-menu">
                  <Menu.Item action={done("Report.pdf (in Inbox)")}>Inbox</Menu.Item>
                  <Menu.Item action={done("Report.pdf (in Later)")}>Later</Menu.Item>
                </Menu.Popup>
              </Menu.Root>
              <Menu.Separator />
              <Menu.Item className="demo-menu-danger" action={done("(deleted)")}>
                Delete
              </Menu.Item>
            </DemoErrorBoundary>
          </Menu.Popup>
        </Menu.Root>
      </div>
      <label className="demo-row">
        <input type="checkbox" checked={fail} onChange={(e) => setFail(e.target.checked)} />
        Make Archive fail
      </label>
      <p className="demo-readout">Last call: {last}</p>
    </div>
  );
}
```

```css title="menu.css"
/* Menu: the Popup is a <div popover="auto" role="menu">. Open state is `:popover-open` on it;
   items carry `data-pending`, `data-checked` and `aria-disabled`; the Trigger and SubmenuTrigger
   carry `data-open` / `data-pending`. Hovering an item focuses it, so `:focus` is the hover
   style too. */

.demo-menu {
  /* The popover UA stylesheet sets `inset: 0; margin: auto`: reset both for anchored placement. */
  margin: 0;
  inset: auto;
  min-inline-size: 12rem;
  padding: 4px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  background: var(--color-bg);
  color: var(--color-text);
  box-shadow: 0 12px 40px rgb(0 0 0 / 0.25);
  /* CSS enter / exit, used by dismissals (Escape, a click outside, Tab). */
  opacity: 0;
  transition:
    opacity 120ms,
    display 120ms allow-discrete,
    overlay 120ms allow-discrete;
}
.demo-menu:popover-open {
  opacity: 1;
}
@starting-style {
  .demo-menu:popover-open {
    opacity: 0;
  }
}
/* The gaps. `data-side` is where the browser placed the menu (a submenu: right in LTR, left in
   RTL, either after a flip). A flip swaps the popup's margins, so each gap goes on both sides of
   its axis. A submenu carries `inline-end` until it is shown: keyed too, so its first layout
   already has the gap. */
.demo-menu[data-side="bottom"],
.demo-menu[data-side="top"] {
  margin-block: 4px;
}
.demo-menu[data-side="right"],
.demo-menu[data-side="left"],
.demo-menu[data-side="inline-start"],
.demo-menu[data-side="inline-end"] {
  margin-inline: 2px;
}

.demo-menu [role^="menuitem"] {
  display: flex;
  align-items: center;
  gap: 8px;
  inline-size: 100%;
  padding: 6px 10px;
  border: 0;
  border-radius: 4px;
  background: none;
  color: inherit;
  font: inherit;
  text-align: start;
  cursor: pointer;
}
.demo-menu [role^="menuitem"]:focus {
  outline: none;
  background: color-mix(in srgb, var(--color-primary) 15%, transparent);
}
/* Not while pending: an item that ignores activation while its action runs is aria-disabled too
   (`whilePending="ignore"`), and its pending look is [data-pending] below. */
.demo-menu [aria-disabled="true"]:not([data-pending]) {
  opacity: 0.45;
  cursor: default;
}
.demo-menu [data-pending] {
  cursor: progress;
}
/* A check column for checkbox and radio items. */
.demo-menu [role="menuitemcheckbox"]::before,
.demo-menu [role="menuitemradio"]::before {
  content: "";
  inline-size: 1em;
}
/* Generated text is part of the item's accessible name ("✓Serif" in Chromium). The empty alternative text
   after "/" keeps these marks out of it: `aria-checked` already exposes the state. */
.demo-menu [role="menuitemcheckbox"][data-checked]::before,
.demo-menu [role="menuitemradio"][data-checked]::before {
  content: "✓" / "";
}
.demo-menu [role="menuitemcheckbox"][data-pending]::after,
.demo-menu [role="menuitemradio"][data-pending]::after {
  content: "…" / "";
  margin-inline-start: auto;
}
/* A submenu arrow; flipped by the writing direction. */
.demo-menu [aria-haspopup="menu"]::after {
  content: "›" / "";
  margin-inline-start: auto;
}
.demo-menu hr {
  margin: 4px 0;
  border: 0;
  border-block-start: 1px solid var(--color-border);
}
.demo-menu-label {
  padding: 4px 10px;
  font-size: 0.8rem;
  color: var(--color-text-muted, inherit);
}
.demo-menu-danger {
  color: #dc2626;
}

/* Library-driven opens and closes (an item's activation): `transition` on the Popup. */
::view-transition-new(.menu-in) {
  animation: 120ms ease-out both menu-in;
}
::view-transition-old(.menu-out) {
  animation: 120ms ease-in both menu-out;
}
@keyframes menu-in {
  from {
    opacity: 0;
    translate: 0 -4px;
  }
}
@keyframes menu-out {
  to {
    opacity: 0;
    translate: 0 -4px;
  }
}
@media (prefers-reduced-motion: reduce) {
  .demo-menu {
    transition: none;
  }
  ::view-transition-new(.menu-in),
  ::view-transition-old(.menu-out) {
    animation: none;
  }
}
```

## How it works

### Items, actions and closing

Click, Enter or Space on an `Item` runs its `action` in the item's own transition. The menu **stays open while the action runs**, with `data-pending` on the item, and closes once it settles, through the top-level Root (`openChangeAction(false, { reason: "activate" })`, then `hidePopover()` in the commit, with a view transition if the Popup has `transition`). A synchronous action closes in the same tick. A rejection leaves the menu open and reaches the nearest Error Boundary above the item; an action that shows its own message and calls [`details.reject()`](../concepts/action-props.md#reject) leaves it open with no boundary (a CheckboxItem or RadioItem also rolls its check back). A second click, Enter or Space while the action is pending is ignored (and cancelled), and the item is `aria-disabled="true"` meanwhile: the first activation already ends in the menu's close. A `closeOnActivate={false}` item is different: nothing of the library's follows its action, so it runs every activation (a "Zoom in" item counts each press), with `data-pending` until the last run settles and no `aria-disabled`. `whilePending` overrides either default. A pending item is an ordinary item for navigation; only the open focus skips items with the `disabled` prop (`data-disabled`). For "close now, work in the background" do not return the promise: `action={() => { void archive(id); }}`.

- `closeOnActivate={false}` keeps the menu open (a "Refresh" item).
- An item that opens a dialog sets its state from a click handler, not from `action`: see [Open a dialog or navigate from an item](#open-from-item).
- A [Button](button.md) inside a `Menu.Popup` is not a menu item: no `role="menuitem"`, not in the arrow-key set, and it does not close the menu. Use `Menu.Item` for actions in a menu.
- Activating an item in a submenu closes the whole stack: the top-level Root gets `"activate"`, each submenu Root `"dismiss"`. The submenu disappears at once (it is hidden as a nested popover); the top-level menu animates.
- **A menu closes its submenus.** Whatever closes a menu (an item, the Trigger, a controlled `open={false}`, Tab, a click or right-click outside), each open submenu Root gets exactly one `onOpenChange(false, { reason: "dismiss" })`, also when `transition` on the Popup hid the content first (its `details.event` is then `undefined`). A menu reopens at its first level, focus on its first item. A menu that is only hidden with what is around it (a `keepMounted` Dialog that closes, a tab switched away) keeps its submenus and shows them again with it. Any other popup open inside a `Menu.Popup` follows the Popover rule ([Popups inside a popup](popover.md#nested-popups)).
- If the menu was dismissed and opened again while an action ran, that action's close is dropped: it belonged to the previous opening. A Root with no `openChangeAction` re-opens at once. A controlled Root, or one with an `openChangeAction`, does not show the re-open until that action settles: React holds transitions started while an async action is pending, so meanwhile the Trigger shows `data-open` and `data-pending` without a menu (it stays exposed as collapsed: no menu is shown). A slow Server Function behind an item makes this visible (Popover's `Close` behaves the same).
- Keyboard activation goes through the item's `click()`, so `details.event` is a `click` event for pointer and keyboard alike, and an item composed with another trigger (`<Dialog.Trigger render={<Menu.Item closeOnActivate={false} />}>`) runs its command.

### Checkbox and radio items

```tsx title="MenuViewOptions.tsx"
"use client";
import { startTransition, useState } from "react";
import { Menu } from "@funstack/ui/menu";
import { sleep } from "./fake-api.js";

// Checkbox and radio items are state owners with useOptimistic: aria-checked flips at once,
// data-pending shows while the (fake) save runs, and the menu stays open so several options can
// be changed in a row. Controlled here, following "update on success": the setState after the
// await is wrapped in startTransition.
export function MenuViewOptions() {
  const [dense, setDense] = useState(false);
  const [archived, setArchived] = useState(true);
  const [sort, setSort] = useState("name");
  return (
    <div className="demo-stack">
      <Menu.Root>
        <Menu.Trigger className="demo-button">View</Menu.Trigger>
        <Menu.Popup className="demo-menu" experimental_focusGroup>
          <Menu.CheckboxItem
            checked={dense}
            checkedChangeAction={async (next) => {
              await sleep(600);
              startTransition(() => setDense(next));
            }}
          >
            Dense rows
          </Menu.CheckboxItem>
          <Menu.CheckboxItem
            checked={archived}
            checkedChangeAction={async (next) => {
              await sleep(600);
              startTransition(() => setArchived(next));
            }}
          >
            Show archived
          </Menu.CheckboxItem>
          <Menu.Separator />
          <Menu.RadioGroup
            value={sort}
            valueChangeAction={async (next) => {
              await sleep(600);
              startTransition(() => setSort(next));
            }}
          >
            <Menu.GroupLabel className="demo-menu-label">Sort by</Menu.GroupLabel>
            <Menu.RadioItem value="name">Name</Menu.RadioItem>
            <Menu.RadioItem value="modified">Last modified</Menu.RadioItem>
            <Menu.RadioItem value="size">Size</Menu.RadioItem>
          </Menu.RadioGroup>
        </Menu.Popup>
      </Menu.Root>
      <p className="demo-readout">
        dense: {String(dense)}, show archived: {String(archived)}, sort: {sort}
      </p>
    </div>
  );
}
```

`menu.css`: the same file as above.

`CheckboxItem` and `RadioGroup` are [state owners](../concepts/pending-and-optimistic.md#state-owner) like [Checkbox](checkbox.md) and [RadioGroup](radio-group.md): `aria-checked` and `data-checked` flip at once, `data-pending` shows while the change action runs (on the item and on the `RadioGroup`), and a rejection rolls the check back. They **keep the menu open** by default (the APG's Space rule, and toggling several options is the point); `closeOnActivate` closes the menu after the change settles. Re-activating the selected radio item dispatches nothing; with `closeOnActivate` it still closes the menu.

> **Coming from Radix**
>
> Radix closes the menu when a checkbox or radio item is selected, unless its `onSelect` calls `preventDefault()`. Here the default is the reverse: `closeOnActivate` is `false` for `CheckboxItem` and `RadioItem`. Pass `closeOnActivate` to close the menu after the change.

> **Uncontrolled state lives with the items**
>
> By default the items unmount when the menu closes, and uncontrolled checkbox and radio state goes with them. Control them (as above), or give the Popup `keepMounted`.

### Context menus

A `Menu.ContextTrigger` in the Root opens the same Popup at the pointer from a right-click, Shift+F10 or a touch long-press, next to (or instead of) the Trigger: see [Context menu](context-menu.md). Two behaviours apply to every menu, context-opened or not: a right- or middle-click outside closes it at once (`"dismiss"`), as native menus do; Chromium's light dismiss alone would leave it open under the browser's own menu. And a wheel over the menu never scrolls the page under it: the library prevents it unless the menu itself can scroll that way (Ctrl+wheel and a trackpad pinch still zoom).

## Props

### `Menu.Root`

| Prop | Type | Default | Description |
| - | - | - | - |
| `open` | `boolean` | – | Controlled open state. undefined means uncontrolled. Pass `onOpenChange` too: the browser closes the menu without asking (development warns). A parent that keeps `true` after a dismissal gets the menu shown again at once, with focus left where the dismissal put it (no initial focus). |
| `defaultOpen` | `boolean` | – | Initial open state when uncontrolled. Shown after hydration. |
| `openChangeAction` | `ChangeAction<boolean, MenuOpenChangeDetails>` | – | Requests only. Awaited for `true` (the menu opens when it resolves and the items have rendered) and for the closes a part asks for (the Trigger, an item's activation, ArrowLeft in a submenu, the pointer leaving a hover-opened submenu); the menu stays shown until the action settles, with `data-pending` on the Trigger meanwhile. Never called for a dismissal (`onOpenChange`). Runs in the Root's transition; may be a Server Function. `details.reason`: `"activate"`, `"dismiss"` (the hover close of a submenu) or `"platform"` (found open on hydration; `event` is `undefined`). |
| `onOpenChange` | `UrgentChangeHandler<boolean, MenuOpenChangeDetails>` | – | Facts only: the menu was closed without the library closing it on request. Always `false`. `details.reason`: `"dismiss"` (Escape, a click outside, Tab or focus leaving the menu, a right- or middle-click outside, the parent menu closing a submenu, a scroll or a release outside under a [context menu](context-menu.md), script) or `"activate"` (a [foreign invoker](../concepts/browser-owned-state.md#foreign-invoker), whose press does not move focus out of the menu; a Trigger rendered as another element, pressed while open). Called synchronously in the browser's `toggle` event, outside any transition, and not awaited: nothing is pending and no view transition runs. In controlled mode set state directly here (`onOpenChange={setOpen}`), never in `startTransition` or after an `await`; a parent that keeps `open` gets the menu shown again at once. Each submenu's Root has its own. May return a promise (a Server Function); a rejection or a throw goes to `reportError`. On a controlled Root with no `openChangeAction`, also a part's close (an item, the Trigger while open): the library performs it at once and calls this with `"activate"` ([nothing waits](../concepts/action-props.md#urgent-open)). |
| `loop` | `boolean` | `true` | ArrowDown / ArrowUp wrap from the last item to the first and back. |
| `delay` | `number` | `100` | Submenu only: milliseconds from hovering the SubmenuTrigger to the open. A development warning on a top-level Root. |
| `closeDelay` | `number` | `150` | Submenu only: milliseconds from the pointer leaving the SubmenuTrigger and the submenu to the close. |
| `children` | `ReactNode \| ((state: MenuRootState) => ReactNode)` | – | The parts. The function form receives the optimistic state and must not suspend. |

- **State**: `MenuRootState` is `{ open, pending, submenu, context }`; `open` is optimistic; `submenu` is true for a Root rendered inside a `Menu.Popup`; `context` is true while the open came from a [\`Menu.ContextTrigger\`](context-menu.md).
- **Owned**: none: the Root renders no element (no `ref`, `className` or `style`).

### `Menu.Trigger`

A `<button popovertarget>`: see [Triggers of a popup](../concepts/browser-owned-state.md#popup-triggers) for what that gives it, and for a Trigger rendered as another element. One per Root: it is the menu's anchor and focus-return target, and a press on a second Trigger while open counts as outside.

| Prop | Type | Default | Description |
| - | - | - | - |
| `disabled` | `boolean` | `false` | Native `disabled`. Owned, so a `render` element cannot re-enable it. With a link or component `render`, and inside a `Menubar` or a [\`Toolbar.Root\`](toolbar.md), `aria-disabled="true"` instead (the element stays focusable and, in a Toolbar, in the arrow-key sequence); a click, Enter and the arrow keys do not open. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `className` | `string \| ((state: MenuTriggerState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuTriggerState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuTriggerState) => ReactNode)` | – | Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: MenuTriggerState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `MenuTriggerState` is `{ open, pending, disabled }`.
- **Owned**: `type` (only on a `<button>`), `id`, `disabled`, `aria-disabled` (link or component `render`, in a Menubar or a Toolbar), `popoverTarget` (only on an invoker), `aria-haspopup`, `aria-expanded` (only on a Trigger that is no invoker), `role` (in a Menubar), `onClick`, `onKeyDown`, `onMouseDown`, `onPointerMove` (the hover switch, in a Menubar), `data-open`, `data-pending`, `data-disabled`. Owned and never written: `popoverTargetAction`, `commandfor`, `command`.

Use it in a top-level Root only. A primary-button press on it while the menu is open keeps focus on the current item; the click then closes the menu.

### `Menu.Popup`

| Prop | Type | Default | Description |
| - | - | - | - |
| `side` | `"top" \| "bottom" \| "left" \| "right" \| "inline-start" \| "inline-end" \| null` | `"bottom" ("inline-end" in a submenu)` | Placement through inline `position-area`, with `position-try-fallbacks` flipping it (a submenu flips inline only). `inline-start` / `inline-end` follow the popup's direction: a submenu opens on the right of its item in LTR and on the left in RTL, the side the arrow keys point to. `left` / `right` stay physical. `null` emits no inline placement and no `data-side` / `data-align`. Ignored for an open from a [Menu.ContextTrigger](context-menu.md), which is placed at the pointer; there `null` opts out of the inline point placement too. |
| `align` | `"start" \| "center" \| "end"` | `"start"` | Alignment along the side. On a top / bottom side `start` / `end` are inline-relative (`start` lines up the inline-start edges: the left in LTR, the right in RTL); on the other sides the top / bottom edges. |
| `keepMounted` | `boolean` | `false` | false: the items render only while open (items that suspend hold the open, with `data-pending` on the Trigger). true: they stay mounted in `<Activity mode="hidden">`; an item action that rejects while the menu is closed goes to `reportError`, not to an Error Boundary. |
| `experimental_focusGroup` | `boolean` | `false` | Renders `focusgroup="menu wrap\|nowrap"`. Where the engine implements it (Chromium 150+), the browser moves focus for ArrowUp / ArrowDown / Home / End and items render no `tabindex`; elsewhere nothing changes. Typeahead, activation, submenu keys and Tab stay in JS. |
| `transition` | `ViewTransitionClass` | – | The class of the `<ViewTransition>` around the popup element; without it no boundary is rendered. A string animates this menu's own open and its library-driven closes (an item's activation, the Trigger, ArrowLeft, a hover close) and its own mount and unmount ([only as the top of what is inserted or removed](../concepts/transitions.md#mount-unmount)), in all engines; nothing else (not another menu, not an unrelated transition, not content that changes inside). A submenu is its own menu: its open does not animate the parent's string, while a map keyed on `fsui-menu-open` on the parent plays when a submenu opens, so use the string on menus with submenus. A controlled `open` you change in your own transition needs a map keyed on `fsui-menu-open` / `fsui-menu-close` plus `addTransitionType` ([recipe](../concepts/transitions.md#controlled)). A type map is React's: it names every menu that has it and that a commit with its types reaches, and each plays the class; end it with `default: "none"` ([Type maps](../concepts/transitions.md#type-maps)). Dismissals animate with CSS only. Keep it static: changing it remounts the popup. Any value, `"none"` included, makes a mount of the Popup while it is open, or a second reveal of a mounted Popup by `<Suspense>` or `<Activity>`, inside a transition run the page cross-fade; a plain open does not, and neither does the mount of a closed Popup: it renders its element one commit after its mount, before paint, so its `ref` is still empty in the mount effects of the component that renders it ([two-step mount](../concepts/transitions.md#closed-popups)). While a view transition runs, the popup's CSS transitions are cut for the library's own show or hide (a `@keyframes` animation is not, and a dismissal keeps its CSS exit). |
| `className` | `string \| ((state: MenuPopupState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuPopupState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuPopupState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MenuPopupState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MenuPopupState` is `{ open, side, align, submenu, context }`; `open` is committed; `submenu` (`data-submenu`) is true on a submenu's popup; `context` is true and `side` is `null` for an open from a `Menu.ContextTrigger`. While the menu is shown, `side` / `align` are where the browser placed it (a physical side, after any flip: a submenu reads `right` in LTR and `left` in RTL); otherwise your props.
- **Owned**: `id`, `popover`, `role` (`"menu"`), `aria-labelledby` (the Trigger or SubmenuTrigger while one is mounted, token-merged with yours), `tabIndex` (`-1`), `focusgroup` (the token list with the flag, removed otherwise), `onKeyDown`, `onBlur`, `onMouseDown` (a press outside the items keeps focus on the current item), `onContextMenu` (no browser menu over this one), `onPointerEnter`, `onPointerLeave`, `data-side` / `data-align` (unless `side` is `null`), `data-context`, `data-submenu`, and for a context open the inline `--menu-point-x` / `--menu-point-y` / `--menu-point-gap`, the inline `top` and `left` (`right` in RTL) and the hoisted `@position-try` stylesheet.

A menu shown on the physical side you asked for costs no render for the placement; a logical side (every submenu, by default `inline-end`) costs one render on show and one on hide, since `data-side` turns physical while shown. Style it with `:popover-open`; it emits no `data-open`. Render a `<div>`, not a `<dialog>`.

### `Menu.Item`

| Prop | Type | Default | Description |
| - | - | - | - |
| `action` | `Action<[details: MenuItemActionDetails & Rejectable]>` | – | Runs in the item's own transition (`data-pending` on the item); the menu closes when it settles. A second activation while it is pending is ignored, and the item is `aria-disabled="true"` meanwhile, unless `whilePending` is `"run"` (the default with `closeOnActivate={false}`). May be a Server Function (`details.event` is virtual). A rejection keeps the menu open and reaches the nearest Error Boundary above the item; `details.reject()` keeps it open with no boundary (a handled failure). |
| `closeOnActivate` | `boolean` | `true` | Close the whole menu once `action` settles. |
| `disabled` | `boolean` | `false` | Renders `aria-disabled="true"` and `data-disabled`, never the native attribute: a disabled item stays focusable (the APG) and is reached by the arrow keys and typeahead, but never activates. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `label` | `string` | – | Text that typeahead matches when the item's text content is not representative (an icon). Rendered as `data-fsui-typeahead`, the library's internal marker: do not select on it. |
| `className` | `string \| ((state: MenuItemState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuItemState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuItemState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MenuItemState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |
| `whilePending` | `"run" \| "ignore"` | `"ignore", or "run" with closeOnActivate={false}` | What a click, Enter or Space does while this item's `action` is pending. `"ignore"`: nothing (the event is cancelled, `aria-disabled="true"` meanwhile). `"run"`: the action runs again (`data-pending` until every run has settled, no `aria-disabled`); a closing item closes the menu once the last run has settled, and only if the latest run resolved: a rejection keeps the menu open in both modes. No effect without `action`: the item then shows `data-pending` while the menu's close waits, never `aria-disabled`. See [A second click while pending](../concepts/pending-and-optimistic.md#second-click). |

- **State**: `MenuItemState` is `{ pending, disabled }`.
- **Owned**: `type` (on a `<button>`), `role`, `tabIndex`, `disabled` (always absent), `aria-disabled` (the `disabled` prop, or while pending with `whilePending="ignore"`), `onClick`, `onKeyDown`, `onPointerMove`, `data-pending`, `data-disabled`, `data-fsui-typeahead`.

### `Menu.CheckboxItem`

| Prop | Type | Default | Description |
| - | - | - | - |
| `checked` | `boolean` | – | Controlled checked state. undefined means uncontrolled. |
| `defaultChecked` | `boolean` | `false` | Initial checked state when uncontrolled. |
| `checkedChangeAction` | `ChangeAction<boolean, MenuCheckboxItemCheckedChangeDetails>` | – | Awaited in the item's transition; `aria-checked` flips at once and rolls back on rejection. `details.reason` is `"activate"`. May be a Server Function. |
| `closeOnActivate` | `boolean` | `false` | Close the whole menu once the change settles. |
| `disabled` | `boolean` | `false` | Renders `aria-disabled="true"` and `data-disabled`, never the native attribute: a disabled item stays focusable (the APG) and is reached by the arrow keys and typeahead, but never activates. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `label` | `string` | – | Text that typeahead matches when the item's text content is not representative (an icon). Rendered as `data-fsui-typeahead`, the library's internal marker: do not select on it. |
| `className` | `string \| ((state: MenuCheckboxItemState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuCheckboxItemState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuCheckboxItemState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MenuCheckboxItemState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `MenuCheckboxItemState` is `{ checked, pending, disabled }`; `checked` is optimistic.
- **Owned**: those of `Menu.Item`, plus `role` (`"menuitemcheckbox"`), `aria-checked`, `data-checked`.

Transition types `fsui-menu` with `fsui-menu-check` or `fsui-menu-uncheck`.

### `Menu.RadioGroup`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V \| null` | – | Controlled value; null selects nothing, undefined means uncontrolled. `V` is the item value type: a declared union you pass is kept, a literal is `string` ([Typed values](../concepts/action-props.md#typed-values)). |
| `defaultValue` | `V \| null` | `null` | Initial value when uncontrolled. |
| `valueChangeAction` | `ChangeAction<V, MenuRadioGroupValueChangeDetails>` | – | Receives the chosen item's value, awaited in the group's transition. `details.reason` is `"activate"`. May be a Server Function. |
| `className` | `string \| ((state: MenuRadioGroupState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuRadioGroupState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuRadioGroupState) => ReactNode)` | – | The RadioItems and a GroupLabel. |
| `render` | `ReactElement \| ((props, state: MenuRadioGroupState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MenuRadioGroupState` is `{ value, pending }`.
- **Owned**: `role` (`"group"`), `aria-labelledby` (token-merged: the `GroupLabel` inside it, while one is mounted), `data-pending`.

Transition types `fsui-menu`, `fsui-menu-select`.

### `Menu.RadioItem`

| Prop | Type | Default | Description |
| - | - | - | - |
| `value` | `V` | – | Required. The value this item selects. `V` is `string` unless you pass a type argument, which checks the value ([Typed values](../concepts/action-props.md#typed-values)). |
| `closeOnActivate` | `boolean` | `false` | Close the whole menu once the change settles (also when the item was already selected). |
| `disabled` | `boolean` | `false` | Renders `aria-disabled="true"` and `data-disabled`, never the native attribute: a disabled item stays focusable (the APG) and is reached by the arrow keys and typeahead, but never activates. A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `label` | `string` | – | Text that typeahead matches when the item's text content is not representative (an icon). Rendered as `data-fsui-typeahead`, the library's internal marker: do not select on it. |
| `className` | `string \| ((state: MenuRadioItemState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuRadioItemState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuRadioItemState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: MenuRadioItemState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `MenuRadioItemState` is `{ value, checked, pending, disabled }`; `value` is the item's own `value` prop; `pending` is true on the item being selected.
- **Owned**: those of `Menu.Item`, plus `role` (`"menuitemradio"`), `aria-checked`, `data-checked`, and `value` (not rendered: a menu item is not a form control).

A `RadioItem` outside a `RadioGroup` throws.

### `Menu.Group`, `Menu.GroupLabel`, `Menu.Separator`

`Group` is a `<div role="group">` labelled by its `GroupLabel` (a `<div>` with the owned `id`), which also names a `RadioGroup`. `Separator` is an `<hr role="separator">`: it owns `role`, so a `render` element of another tag is a separator too. All take `className`, `style`, `render` and (except `Separator`) `children`; they have no state.

### `Menu.SubmenuTrigger`

| Prop | Type | Default | Description |
| - | - | - | - |
| `disabled` | `boolean` | `false` | `aria-disabled`: focusable, never opens. Not the native attribute (it is an item). A click runs no `onClick`, a `render` element's included, and is cancelled; a `render` element's `disabled` disables the part too ([unavailable parts](../concepts/render.md#unavailable)). |
| `label` | `string` | – | Typeahead text, as on `Menu.Item`. |
| `className` | `string \| ((state: MenuSubmenuTriggerState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenuSubmenuTriggerState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenuSubmenuTriggerState) => ReactNode)` | – | Rendered from optimistic state; must not suspend. |
| `render` | `ReactElement \| ((props, state: MenuSubmenuTriggerState) => ReactNode)` | – | Replace the default \<button> (element form) or take over rendering (function form). |

- **State**: `MenuSubmenuTriggerState` is `{ open, pending, disabled }`, as the Trigger.
- **Owned**: the Trigger's (`type`, `id`, `popoverTarget` (only on an invoker: not while disabled), `aria-haspopup`, `aria-expanded` (only when it is no invoker, so also while disabled), `data-open`, `data-pending`; owned and never written: `popoverTargetAction`, `commandfor`, `command`) and the item's (`role`, `tabIndex`, `disabled` (absent), `aria-disabled`, `data-disabled`, `data-fsui-typeahead`, `onClick`, `onKeyDown`, `onPointerMove`, `onPointerEnter`, `onPointerLeave`).

Both an item of the parent menu (roving `tabindex`, typeahead) and the Trigger of its Root; `data-pending` while items that suspend load. A disabled SubmenuTrigger stays focusable (`aria-disabled`), so it is no invoker while disabled and renders `aria-expanded` from the shown submenu. Use it in a submenu Root only.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-open` | Trigger, SubmenuTrigger | Optimistic open state of the Root. |
| `aria-expanded` | Trigger, SubmenuTrigger, only when it is no [invoker](../concepts/browser-owned-state.md#popup-triggers): a link or other non-button element, a disabled component `render`, or a disabled SubmenuTrigger | Whether the menu is shown (mirrored from its `toggle` event, not optimistic). A `<button>` has none: the browser exposes the state. |
| `data-open` | ContextTrigger | Optimistic open state of the Root (no `aria-expanded`: the region has no role). |
| `data-pending` | Trigger, SubmenuTrigger, ContextTrigger | An open or close of the Root is in flight (items that suspend hold the open). |
| `data-pending` | Item, CheckboxItem, RadioItem, RadioGroup | The item's `action` or change action is in flight, then (a closing Item, with or without `action`) until the menu's close has committed; on the RadioGroup while a selection is. |
| `aria-disabled` | Item, CheckboxItem, RadioItem, SubmenuTrigger | `"true"` for the `disabled` prop (items are never natively disabled), and on an Item while its `action` is pending and it ignores a second activation (`whilePending="ignore"`, the default unless `closeOnActivate={false}`). |
| `data-disabled` | Trigger, items, ContextTrigger | The `disabled` prop. |
| `aria-checked`, `data-checked` | CheckboxItem, RadioItem | Optimistic checked state. |
| `data-fsui-typeahead` | Item, CheckboxItem, RadioItem, SubmenuTrigger | The `label` prop: the text typeahead matches. An internal marker (the `data-fsui-` prefix), not a styling hook. |
| `data-submenu` | Popup | The popup belongs to a submenu (`state.submenu`). |
| `:popover-open` | Popup | The menu is shown. Browser-owned: the Popup emits no `data-open`. |
| `data-side`, `data-align` | Popup | While shown, where the browser placed the popup (after any flip); otherwise the requested placement. Absent for an open from a `Menu.ContextTrigger`. |
| `data-context` | Popup | The current open came from a `Menu.ContextTrigger` and is placed at a point (see [Context menu](context-menu.md)). |

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| Enter / Space / ArrowDown | Trigger | Opens with the first enabled item focused (ArrowDown on an open menu focuses it). |
| ArrowUp | Trigger | Opens with the last enabled item focused. |
| ArrowDown / ArrowUp | item | Next / previous item, disabled ones included; wraps if `loop`. |
| Home / End | item | First / last item. |
| A printable character | item | Typeahead: the next item starting with it; repeat to cycle; type a prefix within 500 ms. |
| Enter / Space | item | Activates it (Space is a character while typeahead is active). |
| ArrowRight | SubmenuTrigger | Opens the submenu with its first item focused (ArrowLeft under `direction: rtl`). |
| ArrowLeft | item in a submenu | Closes the submenu; focus returns to its SubmenuTrigger (ArrowRight under `direction: rtl`). |
| Escape | anywhere | Closes the innermost menu; focus returns to its Trigger or SubmenuTrigger (the library does it for a submenu). |
| Tab / Shift+Tab | item | Closes the whole menu at once and moves on (Shift+Tab lands on the Trigger). |

- Under `direction: rtl` ArrowLeft opens and ArrowRight closes a submenu, and the submenu opens on the left of its item (the default `side="inline-end"`); the top-level menu's `align="start"` lines up the right edges. Both follow the popup's inherited direction through `self-*` `position-area` keywords, so an RTL container works as well as an RTL page. Firefox misplaces popups inside a direction island ([#89](https://github.com/uhyo/funstack-ui/issues/89); see [Tooltip](tooltip.md#browser-notes)).
- **Focus is real DOM focus** on items (no `aria-activedescendant`). Every open focuses the first item, pointer opens included (no focus ring then, through `focus({ focusVisible: false })`; Safari may still show a ring on the first item after a click); a submenu opened by hover keeps focus on its trigger. **Moving the pointer over an item focuses it**, so keyboard and pointer always agree on the current item: style `:focus` as the hover state. A press on the menu's own space (padding, a `Separator`, a `GroupLabel`) keeps focus on the current item, so the arrow keys keep working. So does a press on a `<button>` Trigger while the menu is open: the click then closes it like an item's activation, on every browser (a Trigger rendered as another element is light-dismissed first: see [Triggers of a popup](../concepts/browser-owned-state.md#popup-triggers)).
- **Hover intent** for submenus: the submenu opens `delay` ms (100) after the pointer enters its trigger and closes `closeDelay` ms (150) after the pointer leaves both, unless keyboard focus is inside it. Touch never opens on hover.
- **Tab closes immediately**, without asking `openChangeAction`: a menu must not linger once focus has moved on. It is a fact, reported to `onOpenChange` as `"dismiss"`.
- **ARIA:** the Trigger and SubmenuTrigger have `aria-haspopup="menu"`; as invokers, the browser exposes their expanded state ([Triggers of a popup](../concepts/browser-owned-state.md#popup-triggers)); the Popup `role="menu"` and `aria-labelledby` pointing at its trigger; items their roles and `aria-checked` / `aria-disabled`.

### Inside a Toolbar

A `Menu.Trigger` inside a [Toolbar](toolbar.md) opens on the arrow key perpendicular to the toolbar's, leaving the toolbar's own arrows to it. Enter and Space open it in every case. In a vertical toolbar, put the popup beside it on the inline-end side: `side="inline-end"` (the right in LTR, the left under `direction: rtl`).

| Context | Opens with the first item | Opens with the last item | Left to the Toolbar |
| - | - | - | - |
| No toolbar | ArrowDown | ArrowUp | – |
| Horizontal Toolbar | ArrowDown | ArrowUp | ArrowLeft / ArrowRight |
| Vertical Toolbar | ArrowRight (ArrowLeft under `direction: rtl`) | – | ArrowDown / ArrowUp |

## Transition types

Concept: [Transitions & ViewTransition](../concepts/transitions.md#transition-types)

Opens and closes: `fsui-menu` plus `fsui-menu-open` or `fsui-menu-close` (a submenu's too). A CheckboxItem: `fsui-menu` plus `fsui-menu-check` or `fsui-menu-uncheck`. A RadioGroup: `fsui-menu` plus `fsui-menu-select`. These types are public API: key a `transition` map on them, and add them with `addTransitionType` for a controlled change ([Transitions](../concepts/transitions.md#controlled)). A string `transition` is keyed on an internal per-instance type instead, which this component's own dispatch adds.

## Optimistic and pending

Concept: [Pending & optimistic state](../concepts/pending-and-optimistic.md)

The Trigger's `data-open` and CheckboxItem and RadioItem `data-checked` are optimistic; the state the browser exposes on the Trigger follows the shown menu. Items render from the committed open state. An Item is a [pure trigger](../concepts/pending-and-optimistic.md#pure-trigger): `data-pending` while its action runs and until the menu's close it asked for has committed (also without `action`, then never `aria-disabled`); a second activation is ignored, or with `closeOnActivate={false}` runs again (`whilePending`).

### A slow `openChangeAction`

A submenu's `Menu.Root` has its own `openChangeAction` and `onOpenChange`. Here both actions take 2 seconds, like a server call, and the handlers log the dismissals. Each trigger is exposed as expanded exactly while its menu is shown:

```tsx title="MenuSlowOpen.tsx"
"use client";
import { startTransition, useState } from "react";
import { Menu } from "@funstack/ui/menu";
import type { MenuOpenChangeDetails } from "@funstack/ui/menu";
import { sleep } from "./fake-api.js";

// A slow `openChangeAction` on the menu and on its submenu (a nested Root has its own): a
// pretend server call of 2 seconds for every request. Opening: the Trigger (or SubmenuTrigger)
// gets data-open and data-pending at once, the menu is shown when the action settles. Choosing an
// item closes the menu when the close's action settles. Escape and a click outside are the
// browser's, a fact: the menu hides at once, nothing is pending and the action is not called;
// `onOpenChange` reports it (also for a submenu closed with its parent). The browser exposes each
// trigger as expanded exactly while its menu is shown. The readout is plain text, not a live
// region.
export function MenuSlowOpen() {
  const [log, setLog] = useState("(none yet)");
  const [view, setView] = useState("List");
  const slow =
    (menu: string) =>
    async (open: boolean, { reason }: MenuOpenChangeDetails) => {
      const call = `${menu} openChangeAction(${open}, "${reason}")`;
      setLog(`${call}: running…`);
      await sleep(2000);
      // After an await: wrap the update in startTransition (React limitation).
      startTransition(() => setLog(`${call}: settled`));
    };
  // A fact: called in the browser's event, not awaited. A plain setState here is urgent.
  const dismissed =
    (menu: string) =>
    (open: boolean, { reason }: MenuOpenChangeDetails) => {
      setLog(`${menu} onOpenChange(${open}, "${reason}")`);
    };
  const choose = (next: string) => () => setView(next);

  return (
    <div className="demo-stack">
      <div className="demo-row">
        <span>View: {view}</span>
        <Menu.Root openChangeAction={slow("menu")} onOpenChange={dismissed("menu")}>
          <Menu.Trigger className="demo-button">
            {({ pending }) => (
              <>Options{pending && <span className="demo-spinner" aria-hidden />}</>
            )}
          </Menu.Trigger>
          <Menu.Popup className="demo-menu">
            <Menu.Item action={choose("List")}>List</Menu.Item>
            <Menu.Item action={choose("Grid")}>Grid</Menu.Item>
            <Menu.Separator />
            <Menu.Root openChangeAction={slow("submenu")} onOpenChange={dismissed("submenu")}>
              <Menu.SubmenuTrigger>
                {({ pending }) => (
                  <>Sort by{pending && <span className="demo-spinner" aria-hidden />}</>
                )}
              </Menu.SubmenuTrigger>
              <Menu.Popup className="demo-menu">
                <Menu.Item action={choose("List, by name")}>Name</Menu.Item>
                <Menu.Item action={choose("List, by date")}>Date</Menu.Item>
              </Menu.Popup>
            </Menu.Root>
          </Menu.Popup>
        </Menu.Root>
      </div>
      <p className="demo-readout">
        Last: <code>{log}</code>
      </p>
    </div>
  );
}
```

`menu.css`: the same file as above.

- Open the menu (click, Enter) or the "Sort by" submenu (hover, ArrowRight): the trigger gets `data-open` and `data-pending` at once and stays collapsed; the menu is shown, focus moves into it and the trigger is expanded when the action settles.
- Choose an item, or click the Trigger again: the menu stays shown and the Trigger expanded until the close's action settles.
- Escape or a click outside: a fact. The menu hides and the Trigger is collapsed at once; nothing is pending and the slow action is not called; `onOpenChange` is (each open submenu's too, when the whole stack closes).

The readout under the example is plain text, not a live region, so it does not interrupt a screen reader.

An open of a Root that is controlled or has an `openChangeAction`, as here, also waits for any other action pending in the app: the Trigger shows `data-open` and `data-pending`, and the menu is shown when that action settles. An uncontrolled Root with no `openChangeAction` opens at once. See [Pending actions hold other transitions](../concepts/action-props.md#pending-actions-hold-transitions).

## Suspense

Concept: [Suspense](../concepts/suspense.md)

Items that suspend hold the open: the menu (or submenu) stays closed with `data-pending` on its Trigger, then opens once, complete, with the first item focused.

The items render from committed state, so a submenu read with `use()`:

```tsx
<Menu.Root>
  <Menu.SubmenuTrigger>Open recent</Menu.SubmenuTrigger>
  <Menu.Popup>
    <RecentFiles />   {/* use(recentFiles): the submenu opens when ready */}
  </Menu.Popup>
</Menu.Root>
```

## Browser-owned state

Concept: [Browser-owned state](../concepts/browser-owned-state.md)

The popup is a `popover="auto"`: the top layer, light dismiss and Escape are the browser's. A dismissal closes the menu at once, a fact: `onOpenChange(false)` is called with `reason: "dismiss"`, nothing is pending, and it animates with CSS only.

## Before hydration

Concept: [Server Components](../concepts/server-components.md#before-hydration)

The Trigger carries `popovertarget`: a click before hydration opens the (still empty) menu natively, and the items fill in on hydration (`reason: "platform"`).

The empty popup still has your border, padding and shadow, so on a slow page it looks broken. Hide a menu popup that has no item yet:

```css
.menu:not(:has([role^="menuitem"])) { display: none; }
```

The menu is still open, only not drawn: it appears with its items when the page hydrates, and a click outside or Escape closes it before that. The rule cannot tell hydration apart: after hydration it also hides an open menu that renders no item (all of them filtered out, say), so give such a menu an empty-state element of its own or leave the rule out. `.menu` is your Popup's class; the same rule covers the menus of a [Menubar](menubar.md).

## Styling

Style the popup with `:popover-open` and the items with `[role^="menuitem"]`, `:focus`, `[aria-disabled="true"]`, `[data-pending]` and `[data-checked]`. Dismissals animate with CSS (`@starting-style` and `transition-behavior: allow-discrete`; Firefox hides a popover instantly). Library-driven opens and closes animate with `transition` on the Popup in every engine, transition types `fsui-menu` plus `fsui-menu-open` or `fsui-menu-close`. Keep them short: the page takes no pointer events during a view transition.

```tsx
<Menu.Popup transition="menu-pop">
```

The string animates this menu's own opens and closes; a submenu is a menu of its own, so its open does not animate the parent. Tell the open from the close in CSS with `:active-view-transition-type(fsui-menu-open)`. A map keyed on `fsui-menu-open` instead names every menu that has it in every menu's open, a submenu's included, and the parent plays its class when a submenu opens.

Keep the CSS exit next to `transition`: it animates the dismissals. The library turns the popup's CSS transitions off for the moment of its own show and hide while a view transition runs, so its show or hide never runs a CSS transition and you need no extra rule ([A popup with a CSS exit and a view transition](../concepts/transitions.md#css-exit)).

Text generated with `content` on `::before` or `::after` is part of the item's accessible name. A check mark drawn that way is read out by a screen reader, and a test that looks for the radio item named exactly "Serif" does not find it. Give a decorative mark empty alternative text after a slash; `aria-checked` already exposes the state:

```css
[role="menuitemradio"][data-checked]::before { content: "✓" / ""; }
```

## Recipes

### Keyboard shortcuts

The library does not bind shortcuts: an item runs its action only when it is activated. Showing a shortcut in an item is markup, and running it is your own `keydown` listener.

```tsx
<Menu.Item action={() => save()} label="Save" aria-keyshortcuts="Control+S">
  Save <kbd aria-hidden="true">Ctrl+S</kbd>
</Menu.Item>

useEffect(() => {
  const onKeyDown = (event: KeyboardEvent) => {
    if (event.key === "s" && event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey) {
      event.preventDefault(); // not the browser's "Save page"
      void save(); // the same function; the item is not involved
    }
  };
  document.addEventListener("keydown", onKeyDown);
  return () => document.removeEventListener("keydown", onKeyDown);
}, []);
```

- `aria-hidden="true"` on the hint keeps it out of the item's accessible name, so a screen reader says "Save", not "Save Ctrl+S".
- `aria-keyshortcuts` passes through to the item's element and exposes the shortcut instead. Its value is [modifier and key names joined with `+`](https://w3c.github.io/aria/#aria-keyshortcuts), modifiers first (`Control`, `Alt`, `Shift`, `Meta`); several shortcuts are separated by spaces (`"Control+S Meta+S"`).
- Typeahead matches an item's text content, which includes the hint. It matches a prefix, so typing "s" still finds Save, but `label` makes the matched text exactly the label.
- The menu leaves keys pressed with Ctrl, Alt or Meta alone, so your listener also receives the shortcut while the menu is open.

### Close now, save in the background

An item whose action returns a promise keeps its menu open until the promise settles, with `data-pending` on the item ([Items, actions and closing](#how-it-works)). That is right when the user should see the outcome in the menu, such as a Delete that can fail with a message. For a save the user does not need to wait for (a "Move to" item), start the promise and return nothing ([Return the promise only when the UI must wait for it](../concepts/action-props.md#await-only)). The menu then closes at once, also while another action is pending, unless the Root is controlled or has an `openChangeAction` ([Pending actions hold other transitions](../concepts/action-props.md#pending-actions-hold-transitions)):

```tsx
<Menu.Item
  action={() => {
    void moveIssue(issue.id, "done").catch(() => {
      toast({ title: `Could not move ${issue.id}`, priority: "high" });
    });
  }}
>
  Move to Done
</Menu.Item>
```

- The library never sees the promise: the item shows no `data-pending`, nothing rolls back, and a rejection reaches no Error Boundary. Show progress on the content being saved (an attribute of your own) and report a failure yourself, as the `.catch` above does with a [toast](toast.md).
- An item that moves or removes the element focus returns to when the menu closes (a Trigger inside the card it moves) leaves focus on `<body>`. Focus the content in its new place yourself once the change is committed, but only if focus is still on `<body>` or inside the moved content: the save can finish a second after the menu closed, when the user is typing somewhere else. The menu does not take focus back from an element outside it.
- If the save's result moves content while the user may be typing elsewhere, see [Background updates while the user types](../concepts/transitions.md#background-updates).

### <a id="open-from-item"></a>Open a dialog or navigate from an item

State you set in an item's `action` is a transition update, so it waits for every action pending in the app ([State that other UI reads at once](../concepts/action-props.md#held-local-state)). An uncontrolled menu with no `openChangeAction` still closes at once, but a dialog opened from the action appears only when a save pending elsewhere has settled. For an item that opens something, set the state in a click handler on the item's `render` element instead, and give the item no `action`. For an item that navigates, render the router's link, with no `action` either:

```tsx
// Urgent: the dialog opens while a save is pending elsewhere.
<Menu.Item render={<button onClick={() => setConfirming(true)} />}>Delete…</Menu.Item>

// A router's link: the link's own click navigates, outside any action.
<Menu.Item render={<Link to="/settings" />}>Settings</Menu.Item>
```

- The element's handler runs before the item's own ([merge rules](../concepts/render.md)). Keyboard activation is the element's click ([above](#how-it-works)), so the handler runs for Enter and Space too. With no `action`, the item then closes the menu, and a Root that is uncontrolled with no `openChangeAction` closes in the same event.
- A `disabled` item runs no click handler: not the element's, not its own `action`, for a pointer, Enter and Space alike, and the click is cancelled ([an unavailable part](../concepts/render.md#unavailable)). So `disabled={!canDelete}` is all a conditional item needs.
- The link takes the navigation out of the item's action, not out of the router's own transition. A router that renders the new route in a transition still waits for a pending save: React Router 8 does unless it has `useTransitions={false}` ([React Router](../concepts/react-router.md#use-transitions)).
- Keep an `action` when the menu should stay open until the work is done, with `data-pending` on the item ([Items, actions and closing](#how-it-works)).

Measured with a 1.5 s save pending elsewhere: an AlertDialog opened from the item's `action` appeared after about 1.4 s, and from the click handler within 20 ms (Chromium and Firefox).

## Browser notes

- `experimental_focusGroup` takes the native path in Chromium only; other engines keep the JS arrow keys (identical behaviour).
- Safari: a nested popover with `position-try-fallbacks` can hang (WebKit bug 302008). If a submenu hits it, give its Popup `side={null}` and place it in CSS.
- A row of menus with arrow keys between them is a [Menubar](menubar.md), around ordinary `Menu.Root`s.
