# Menubar

The WAI-ARIA menubar: "File Edit View" in a row, each opening a menu, with the arrow keys moving between the menus. `Menubar` is one element, `<div role="menubar">`, around ordinary [Menu](menu.md) parts: every `Menu.Trigger` inside becomes an item of the bar, and every menu keeps its own open state, items, actions and pending state. A menubar is not site navigation; links in a header are a navigation menu.

## Anatomy

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

<Menubar aria-label="Application">                      {/* div[role=menubar] */}
  <Menu.Root>
    <Menu.Trigger>File</Menu.Trigger>                   {/* button[role=menuitem][popovertarget] */}
    <Menu.Popup>                                        {/* div[popover=auto][role=menu] */}
      <Menu.Item action={newFile}>New</Menu.Item>
      <Menu.Root>                                       {/* a submenu, as in any menu */}
        <Menu.SubmenuTrigger>Open recent</Menu.SubmenuTrigger>
        <Menu.Popup><RecentFiles /></Menu.Popup>
      </Menu.Root>
    </Menu.Popup>
  </Menu.Root>
  <Menu.Root>
    <Menu.Trigger>View</Menu.Trigger>
    <Menu.Popup>…</Menu.Popup>
  </Menu.Root>
</Menubar>
```

| Part | Element | Role |
| - | - | - |
| `Menubar` | `<div role="menubar" aria-orientation="horizontal">` | One Tab stop and the arrow keys between its Triggers; switches menus. Holds no open state. |
| `Menu.Trigger` in a bar | `<button role="menuitem" popovertarget aria-haspopup="menu">` | An item of the bar. `tabindex` is written by the bar. |
| every other `Menu` part | | Unchanged: see [Menu](menu.md). |

There is no `Menubar.Menu` or `Menubar.Trigger`: a top-level `Menu.Root` rendered inside a `Menubar` is a menu of the bar, and a menu moves into or out of a bar without renaming a part. A submenu is not a menu of the bar (the bar ends at each `Menu.Popup`). A vertical rule between menus is the standalone [Separator](separator.md) with `orientation="vertical"`, which is not focusable.

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

// An application menu: ordinary Menu.Roots inside a Menubar. Each menu keeps its own open state;
// the bar gives one Tab stop and the arrow keys between the menus. "Open recent" reads its list
// with use(): the submenu opens when the list has loaded. "Save" runs a fake server call with
// data-pending on the item; the menu closes when it settles.
let recentFiles: Promise<string[]> | null = null;
function loadRecentFiles(): Promise<string[]> {
  recentFiles ??= sleep(800).then(() => ["Quarterly report.txt", "Notes.md", "Budget.csv"]);
  return recentFiles;
}

function RecentFiles({ onOpen }: { onOpen: (name: string) => void }) {
  const files = use(loadRecentFiles());
  return files.map((name) => (
    <Menu.Item key={name} action={() => onOpen(name)}>
      {name}
    </Menu.Item>
  ));
}

export function MenubarApp() {
  const [log, setLog] = useState("Nothing yet");
  const [wrap, setWrap] = useState(true);
  const [zoom, setZoom] = useState("100");
  const did = (what: string) => setLog(what);
  return (
    <div className="demo-stack">
      <Menubar aria-label="Application" className="demo-menubar">
        <Menu.Root>
          <Menu.Trigger className="demo-menubar-trigger">File</Menu.Trigger>
          <Menu.Popup className="demo-menu">
            <Menu.Item action={() => did("New file")}>New</Menu.Item>
            <Menu.Root>
              <Menu.SubmenuTrigger>Open recent</Menu.SubmenuTrigger>
              <Menu.Popup className="demo-menu">
                <RecentFiles onOpen={(name) => did(`Opened ${name}`)} />
              </Menu.Popup>
            </Menu.Root>
            <Menu.Separator />
            <Menu.Item
              action={async () => {
                await fakeSave("the file", { ms: 1200 });
                startTransition(() => did("Saved"));
              }}
            >
              Save
            </Menu.Item>
          </Menu.Popup>
        </Menu.Root>
        <Menu.Root>
          <Menu.Trigger className="demo-menubar-trigger">Edit</Menu.Trigger>
          <Menu.Popup className="demo-menu">
            <Menu.Item action={() => did("Undo")}>Undo</Menu.Item>
            <Menu.Item action={() => did("Redo")}>Redo</Menu.Item>
            <Menu.Separator />
            <Menu.Item action={() => did("Cut")}>Cut</Menu.Item>
            <Menu.Item action={() => did("Copy")}>Copy</Menu.Item>
            <Menu.Item action={() => did("Paste")}>Paste</Menu.Item>
          </Menu.Popup>
        </Menu.Root>
        <Menu.Root>
          <Menu.Trigger className="demo-menubar-trigger">View</Menu.Trigger>
          <Menu.Popup className="demo-menu">
            <Menu.CheckboxItem checked={wrap} checkedChangeAction={(next) => setWrap(next)}>
              Word wrap
            </Menu.CheckboxItem>
            <Menu.Separator />
            <Menu.RadioGroup value={zoom} valueChangeAction={(next) => setZoom(next)}>
              <Menu.GroupLabel className="demo-menu-label">Zoom</Menu.GroupLabel>
              <Menu.RadioItem value="75">75%</Menu.RadioItem>
              <Menu.RadioItem value="100">100%</Menu.RadioItem>
              <Menu.RadioItem value="150">150%</Menu.RadioItem>
            </Menu.RadioGroup>
          </Menu.Popup>
        </Menu.Root>
        <Menu.Root>
          <Menu.Trigger className="demo-menubar-trigger" disabled>
            Help
          </Menu.Trigger>
          <Menu.Popup className="demo-menu">
            <Menu.Item>About</Menu.Item>
          </Menu.Popup>
        </Menu.Root>
      </Menubar>
      <p className="demo-readout">
        Last command: {log}. Word wrap: {wrap ? "on" : "off"}, zoom: {zoom}%.
      </p>
    </div>
  );
}
```

```css title="menubar.css"
/* Menubar: the bar is a <div role="menubar">; its items are the Menu.Triggers
   (`role="menuitem"`), with the popups between them. The popups use the Menu styles (menu.css).
   A Trigger carries `data-open` (optimistic: highlighted as soon as a switch asks for its menu),
   `data-pending` while its menu's items load, and `aria-disabled` when disabled. */
.demo-menubar {
  display: inline-flex;
  gap: 2px;
  padding: 2px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
}

.demo-menubar-trigger {
  padding: 4px 12px;
  border: 0;
  border-radius: 6px;
  background: none;
  color: var(--color-text);
  font: inherit;
  cursor: default;
}

.demo-menubar-trigger:hover,
.demo-menubar-trigger:focus-visible,
.demo-menubar-trigger[data-open] {
  outline: none;
  background: color-mix(in srgb, var(--color-primary) 15%, transparent);
}

.demo-menubar-trigger[data-pending] {
  cursor: progress;
}

.demo-menubar-trigger[aria-disabled="true"] {
  opacity: 0.45;
}

.demo-menubar-trigger[aria-disabled="true"]:hover {
  background: none;
}
```

Tab enters the bar on File (or on the menu used last). Left / Right move between the menus; ArrowDown, Enter or a click opens one. Inside a menu, Right moves on to the next menu and Left back to the previous one, first item focused (on "Open recent", Right opens the submenu instead). Once a menu is open, moving the pointer across the bar switches menus. Help is disabled: it is reached and announced, but never opens.

## How it works

### Switching menus

Every move from one menu of the bar to another runs the same three steps: the target Trigger is focused (with the focus ring from the keyboard, quietly from the pointer); every other menu of the bar closes at once; the target's open is requested. So:

- The menu you leave is **dismissed**, a fact: `onOpenChange(false, { reason: "dismiss" })` on its Root. A menu whose open was still pending is superseded instead: `openChangeAction(false, { reason: "dismiss" })`, and it never appears.
- The menu you go to is **requested**: `openChangeAction(true, { reason: "activate" })` in a transition, with `data-open` and `data-pending` on its Trigger until its items have rendered.
- Because the Trigger is focused before its menu shows, Escape or an item's activation in the new menu returns focus to the new Trigger.

## Props

### Menubar

| Prop | Type | Default | Description |
| - | - | - | - |
| `loop` | `boolean` | `true` | The arrow keys wrap from the last menu to the first and back: on the bar, and from inside its menus. |
| `className` | `string \| ((state: MenubarState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: MenubarState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: MenubarState) => ReactNode)` | – | The menus of the bar, or a function of the state. |
| `render` | `ReactElement \| ((props, state: MenubarState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `MenubarState` is `{ orientation }`, always `"horizontal"`: the bar holds no open state. Each menu's is on its `Menu.Root`.
- **Owned**: `role` (`"menubar"`), `aria-orientation` and `data-orientation` (both `"horizontal"`), `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown`, and the `tabindex` of its Triggers.

Name the bar with `aria-label` or `aria-labelledby`. `aria-orientation` is rendered although horizontal is the role's default, so a stylesheet has the same `[data-orientation]` hook as on a Toolbar or a tab list. There is no `disabled`: disable a menu on its `Menu.Trigger`.

### Menu.Trigger, Menu.Root and Menu.Popup in a bar

No new props. Inside a bar:

- `Menu.Trigger` renders `role="menuitem"` and no `tabindex` (the bar writes it; do not pass `tabIndex`). `disabled` renders `aria-disabled="true"` and `data-disabled` instead of the native attribute: the Trigger stays focusable and announced, and never opens its menu (it renders no `popovertarget`, and `aria-expanded="false"` instead). Owned keys add `role` and `onPointerMove` (the hover switch). A `render` element's own `onPointerMove` still runs, first.
- `Menu.Root` keeps `open`, `defaultOpen`, `openChangeAction` and `onOpenChange`. `delay` / `closeDelay` stay submenu-only: switching menus by hover has no delay.
- `Menu.Popup` keeps its defaults (`side="bottom"`, `align="start"`).

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-open` | `Menu.Trigger` | Its menu is open or opening (optimistic): set at once when a switch asks for it. |
| `data-pending` | `Menu.Trigger` | Its menu's open or close action is in flight. |
| `data-disabled` | `Menu.Trigger` | The `disabled` prop. |
| `data-orientation` | Menubar | Always `"horizontal"`. |

The popups and items carry Menu's own ([Menu data attributes](menu.md#data-attributes)).

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| Tab / Shift+Tab | outside the bar | Focus enters the bar on the Trigger focused last (the first one before any was). |
| ArrowRight / ArrowLeft | Trigger | Next / previous Trigger (swapped under `direction: rtl`; wraps with `loop`). If this Trigger's menu is open: that menu closes and the new Trigger's opens, focus left on the Trigger. |
| Home / End | Trigger | First / last Trigger; the same rule for an open menu. |
| ArrowRight / ArrowLeft / Home / End | a disabled Trigger a switch landed on | The bar stays in menu mode there: the Trigger reached opens its menu, with the first item focused if you came from inside a menu. |
| Escape | that disabled Trigger | Ends menu mode; focus stays. |
| ArrowDown / Enter / Space | Trigger | Opens its menu with the first item focused (as in Menu). |
| ArrowUp | Trigger | Opens its menu with the last item focused. |
| Any of these with Alt, Ctrl or Meta, or already default-prevented | anywhere | Not handled: the key is the browser's. |
| ArrowRight | an item that opens no submenu, at any depth | The next menu of the bar opens, first item focused. On a SubmenuTrigger it opens the submenu. (Swapped under `direction: rtl`.) |
| ArrowLeft | an item of a top-level menu | The previous menu of the bar opens, first item focused. In a submenu it closes the submenu. (Swapped under `direction: rtl`.) |
| Escape | item | Closes the innermost menu; focus returns to its Trigger. |
| Tab / Shift+Tab | item | Closes the menus; Tab moves past the bar, Shift+Tab lands on the menu's Trigger. |
| Tab / Shift+Tab | Trigger | Leaves the bar; a menu still shown (after a hover switch) is hidden. |

There is no typeahead between the Triggers. With every menu closed, the arrow keys only move focus, and hovering a Trigger does nothing: a click or the keyboard opens the first menu. Once one is open, moving the pointer onto another Trigger (mouse or pen, not touch) switches to it, with no delay; a click on the Trigger of the open menu closes it.

Right to left: the bar reads the computed `direction` of the Menubar element when a key is pressed. Under `direction: rtl` (`<html dir="rtl">`, or `dir` on the bar or an ancestor) ArrowLeft goes to the next Trigger or menu and ArrowRight to the previous one, both between Triggers and from an item. A SubmenuTrigger's key is Menu's: the inline-end arrow, ArrowLeft in RTL, opens its submenu ([What mirrors](../concepts/direction-and-locales.md#what-mirrors)).

| Element | Attributes |
| - | - |
| `Menubar` | `role="menubar"`; your `aria-label` / `aria-labelledby` |
| `Menu.Trigger` in a bar | `role="menuitem"`, `aria-haspopup="menu"`, `popovertarget`, `tabindex` (written by the bar), `aria-disabled="true"` when disabled. No `aria-expanded`: the browser exposes the expanded state from `popovertarget`. A disabled Trigger is the exception: no `popovertarget` (it must not open), and `aria-expanded="false"` instead. |
| Popups and items | As [Menu](menu.md#keyboard-and-aria). |

The popups are DOM children of the `menubar` element, each right after its Trigger, as in the APG example; Chromium and Firefox expose each open menu as a child of the bar named by its Trigger, and axe reports no violation for this structure.

> **Label the bar**
>
> A menubar needs a name: pass `aria-label` or `aria-labelledby`.

## Transition types

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

None of its own. Each menu's opens and closes are Menu's: `fsui-menu` plus `fsui-menu-open` or `fsui-menu-close`.

## Optimistic and pending

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

The bar holds no state. A switch sets the new Trigger's `data-open` at once (optimistic) and `data-pending` while its menu's `openChangeAction` runs or its items load; the menu that was left closes at once, with nothing pending.

An item's action that is still running when you switch away keeps running in its own transition; its menu has already closed, so the close it would run when it settles does nothing. The new menu opens at once when its Root has no `openChangeAction`. A controlled Root, or one with an `openChangeAction`, opens in a transition that React entangles with the pending action, so that menu opens when the action settles; its Trigger shows `data-open` and `data-pending` meanwhile.

## Suspense

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

As Menu, per menu: items that suspend hold the open. During a switch no menu is shown and focus stays on the new Trigger (`data-pending`) until the items are ready; then the menu shows with its first item focused.

Switching again before that supersedes the pending open: that menu never appears.

## Browser-owned state

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

Each menu is its own `popover="auto"`: the browser shows one at a time, and handles Escape and light dismiss. A switch closes the old menu with `hidePopover()`, a dismissal reported to its `onOpenChange`. A controlled `Menu.Root` in a bar needs `onOpenChange`, as every controlled menu does; one that keeps `open={true}` after the switch is shown again, which hides the menu the switch opened.

## Before hydration

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

The bar writes `tabindex` from an effect, so the server HTML has none: before hydration every Trigger is a Tab stop, and a click opens its (still empty) menu natively, one at a time. Hydration fills a menu found open (`reason: "platform"`) and leaves one Tab stop. There is no JS-free mode.

## Styling

```css
.menubar { display: flex; gap: 2px; }
.menubar > [role="menuitem"] { padding: 4px 10px; border: 0; background: none; }
.menubar > [role="menuitem"]:focus-visible,
.menubar > [role="menuitem"][data-open] { background: var(--accent-weak); outline: none; }
.menubar > [role="menuitem"][data-pending] { cursor: progress; }
.menubar > [role="menuitem"][aria-disabled="true"] { opacity: .4; }
```

Style the popups as any menu ([Menu styling](menu.md#styling)). `transition` on a `Menu.Popup` works as outside a bar, but for a bar the usual choice is no view transition between menus: a view transition blocks pointer input while it runs, and a user sweeping across the bar switches several times a second. The menu a switch closes leaves by its CSS exit.

## Not included

- A vertical menubar (`orientation`).
- `experimental_focusGroup` (`focusgroup="menubar"`).
- Typeahead between the Triggers.
- Items directly in the bar (a command or a link with no menu).
- Press, drag and release from a Trigger onto an item.
- A bar-level value naming the open menu: control each Root instead.
- Opening on hover while every menu is closed.
