# Toolbar

A `role="toolbar"` container (WAI-ARIA APG Toolbar pattern) with one Tab stop and arrow keys between its controls. Its items are its focusable descendants, found in the DOM: a [ToggleGroup](toggle-group.md), a [Menu.Trigger](menu.md), a [Toggle](toggle.md), a plain `<button>`, a link or an input all join the sequence without a wrapper. A command button is a [Button](button.md). Every library button inside a toolbar stays focusable when disabled.

## Anatomy

```tsx
import { Button } from "@funstack/ui/button";
import { Toolbar } from "@funstack/ui/toolbar";

<Toolbar.Root aria-label="Formatting">
  <Button action={cut}>Cut</Button>
  <Toolbar.Separator />
  <ToggleGroup.Root aria-label="Text style">…</ToggleGroup.Root>
  <Menu.Root>…</Menu.Root>
</Toolbar.Root>
```

| Part | Element | Role |
| - | - | - |
| `Toolbar.Root` | `<div role="toolbar" aria-orientation>` | Finds its items in the DOM and moves focus between them. |
| `Toolbar.Separator` | `<hr role="separator" aria-orientation>` | A divider, perpendicular to the toolbar. Not focusable. |

There are no `Toolbar.Link`, `Toolbar.Group` or `Toolbar.ToggleGroup` parts: put the element itself in the toolbar. A command is a [Button](button.md); inside a toolbar its `disabled` renders `aria-disabled="true"` (it implies `focusableWhenDisabled`), so it stays focusable and is announced. Do not pass `tabIndex` to toolbar items; the toolbar writes `tabindex` itself. An element with its own `tabIndex={-1}` stays out of the sequence.

```tsx title="ToolbarEditor.tsx"
"use client";
import { startTransition, useState } from "react";
import { Button } from "@funstack/ui/button";
import { Menu } from "@funstack/ui/menu";
import { ToggleGroup } from "@funstack/ui/toggle-group";
import { Toolbar } from "@funstack/ui/toolbar";
import { DemoErrorBoundary } from "./DemoErrorBoundary.js";
import { fakeSave } from "./fake-api.js";

// An editor toolbar: one Tab stop over two ToggleGroups, separators, a menu button, three
// Buttons (Copy is disabled but stays focusable) and a text input placed last. Left /
// Right walk every control; ArrowDown on Insert opens the menu.
export function ToolbarEditor() {
  const [styles, setStyles] = useState<string[]>(["bold"]);
  const [align, setAlign] = useState<string | null>("left");
  const [log, setLog] = useState("Nothing yet.");
  const note = (line: string) => setLog(line);

  return (
    <DemoErrorBoundary>
      <div className="demo-stack">
        <Toolbar.Root aria-label="Formatting" className="demo-toolbar">
          <ToggleGroup.Root
            aria-label="Text style"
            className="demo-toggle-group"
            value={styles}
            valueChangeAction={async (_next, { added, removed }) => {
              await fakeSave("styles");
              // Functional update: overlapping saves that settle out of order lose nothing.
              startTransition(() =>
                setStyles((prev) => [
                  ...prev.filter((v) => !removed.includes(v)),
                  ...added.filter((v) => !prev.includes(v)),
                ]),
              );
            }}
          >
            <ToggleGroup.Item value="bold" className="demo-toggle-item" aria-label="Bold">
              <b aria-hidden>B</b>
            </ToggleGroup.Item>
            <ToggleGroup.Item value="italic" className="demo-toggle-item" aria-label="Italic">
              <i aria-hidden>I</i>
            </ToggleGroup.Item>
          </ToggleGroup.Root>
          <Toolbar.Separator className="demo-toolbar-separator" />
          <ToggleGroup.Root
            exclusive
            aria-label="Text alignment"
            className="demo-toggle-group"
            value={align}
            valueChangeAction={async (next) => {
              await fakeSave(`alignment=${next}`);
              startTransition(() => setAlign(next));
            }}
          >
            <ToggleGroup.Item value="left" className="demo-toggle-item">
              Left
            </ToggleGroup.Item>
            <ToggleGroup.Item value="center" className="demo-toggle-item">
              Center
            </ToggleGroup.Item>
          </ToggleGroup.Root>
          <Toolbar.Separator className="demo-toolbar-separator" />
          <Menu.Root>
            <Menu.Trigger className="demo-toolbar-button">Insert</Menu.Trigger>
            <Menu.Popup className="demo-menu">
              <Menu.Item action={() => note("Inserted an image.")}>Image</Menu.Item>
              <Menu.Item action={() => note("Inserted a table.")}>Table</Menu.Item>
            </Menu.Popup>
          </Menu.Root>
          <Button
            className="demo-toolbar-button"
            action={async () => {
              await fakeSave("cut");
              // After an await: wrap the update in startTransition (React limitation).
              startTransition(() => note("Cut."));
            }}
          >
            {({ pending }) => (
              <>
                {pending && <span className="demo-spinner" aria-hidden />}
                Cut
              </>
            )}
          </Button>
          <Button className="demo-toolbar-button" disabled>
            Copy
          </Button>
          <Button className="demo-toolbar-button" action={() => note("Pasted.")}>
            Paste
          </Button>
          {/* A text-entry control owns its arrow keys: at most one, and last (APG). */}
          <input
            type="text"
            aria-label="Font size"
            inputMode="numeric"
            defaultValue="16"
            size={3}
            className="demo-toolbar-input"
          />
        </Toolbar.Root>
        <p>
          Styles: <output>{styles.join(", ") || "none"}</output>. Alignment:{" "}
          <output>{align ?? "none"}</output>. Last command: <output>{log}</output>
        </p>
      </div>
    </DemoErrorBoundary>
  );
}
```

```css title="toolbar.css"
/* Toolbar: the toolbar is a flex row (a column when vertical); the separator is an <hr>. */
.demo-toolbar {
  display: inline-flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.25rem;
  padding: 0.25rem;
  border: 1px solid var(--color-border);
  border-radius: 10px;
}

.demo-toolbar[data-orientation="vertical"] {
  flex-direction: column;
  align-items: stretch;
}

.demo-toolbar-button {
  display: inline-flex;
  align-items: center;
  gap: 0.4em;
  padding: 0.3em 0.8em;
  border: 0;
  border-radius: 6px;
  background: transparent;
  color: var(--color-text);
  font: inherit;
  cursor: pointer;
}

.demo-toolbar-button:hover {
  background: color-mix(in srgb, var(--color-text) 8%, transparent);
}

/* [data-disabled], not [aria-disabled]: a pending Button with whilePending="ignore" is
   aria-disabled too. */
.demo-toolbar-button[data-disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}

.demo-toolbar-button[data-pending] {
  cursor: progress;
}

.demo-toolbar-button:focus-visible,
.demo-toolbar-input:focus-visible {
  outline: 2px solid var(--color-primary);
  outline-offset: 2px;
}

.demo-toolbar-input {
  padding: 0.25em 0.4em;
  border: 1px solid var(--color-border);
  border-radius: 6px;
  background: var(--color-bg);
  color: var(--color-text);
  font: inherit;
}

/* <hr> is a block; in a horizontal toolbar it is a vertical rule. */
.demo-toolbar-separator {
  margin: 0;
  border: 0;
  background: var(--color-border);
}

.demo-toolbar-separator[data-orientation="vertical"] {
  inline-size: 1px;
  align-self: stretch;
}

.demo-toolbar-separator[data-orientation="horizontal"] {
  block-size: 1px;
}
```

Tab enters on the last focused control (Bold the first time). Left / Right walk every control in document order: both groups, the menu button, the three commands, the input. ArrowDown on Insert opens the menu. Copy is disabled but stays focusable, so it is announced. In the input, Left / Right move the caret and Tab leaves the toolbar (it is last).

## Props

### Toolbar.Root

| Prop | Type | Default | Description |
| - | - | - | - |
| `orientation` | `"horizontal" \| "vertical"` | `"horizontal"` | Axis of the arrow keys; also `aria-orientation`. |
| `loop` | `boolean` | `true` | Arrows wrap from the last item to the first. |
| `experimental_focusGroup` | `boolean` | `false` | Renders `focusgroup="toolbar inline\|block wrap\|nowrap"`; where the browser implements it (Chromium 150+), the browser owns the single Tab stop (with memory of the last focused item), the arrows, Home and End, and the library writes no `tabindex`. See [Experimental features](../concepts/experimental.md). |
| `className` | `string \| ((state: ToolbarRootState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ToolbarRootState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `children` | `ReactNode \| ((state: ToolbarRootState) => ReactNode)` | – | Content, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: ToolbarRootState) => ReactNode)` | – | Replace the default \<div> (element form) or take over rendering (function form). |

- **State**: `ToolbarRootState` is `{ orientation }`.
- **Owned**: `role` (`"toolbar"`), `aria-orientation`, `data-orientation`, `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown`, `focusgroup` (the token list with the flag, removed otherwise), and the `tabindex` of its items.

There is no `disabled`: disable items individually, or wrap the toolbar in a `<fieldset disabled>`.

### Toolbar.Separator

| Prop | Type | Default | Description |
| - | - | - | - |
| `className` | `string \| ((state: ToolbarSeparatorState) => string \| undefined)` | – | A class name, or a function of the part's state. |
| `style` | `CSSProperties \| ((state: ToolbarSeparatorState) => CSSProperties \| undefined)` | – | Inline style, or a function of the part's state. |
| `render` | `ReactElement \| ((props, state: ToolbarSeparatorState) => ReactNode)` | – | Replace the default \<hr> (element form) or take over rendering (function form). |

- **State**: `ToolbarSeparatorState` is `{ orientation }`: the separator's own orientation, `"vertical"` in a horizontal toolbar.
- **Owned**: `role` (`"separator"`, rendered explicitly so a `render` element of another tag is one too), `aria-orientation`, `data-orientation`.

## Data attributes

| Attribute | On | Meaning |
| - | - | - |
| `data-orientation` | Root | The toolbar's orientation. |
| `data-orientation` | Separator | The separator's own (perpendicular) orientation. |

## Keyboard and ARIA

| Key | Where | Behaviour |
| - | - | - |
| ArrowRight / ArrowLeft | item, horizontal toolbar | Next / previous item (swapped under `direction: rtl`); wraps if `loop`. |
| ArrowDown / ArrowUp | item, vertical toolbar | Next / previous item; wraps if `loop`. |
| Home / End | item | First / last item. |
| Any of these with Alt, Ctrl or Meta, or already default-prevented | item | Not handled: the key is the browser's. |
| Any arrow key / Home / End | a native radio | The radio group's own: checks the next / previous radio, staying within the group (it wraps, except in Safari). |
| Tab / Shift+Tab | a native radio | The checked radio of its group if focus is on another one; else the next / previous toolbar item while one exists. |
| Any arrow key / Home / End | a text-entry item | Not handled: the item keeps its caret. |
| Tab / Shift+Tab | a text-entry item | Next / previous toolbar item while one exists; otherwise leaves the toolbar. |
| Tab / Shift+Tab | any other item | Leaves the toolbar; re-entry lands on the last focused item. |
| Enter / Space | `Button` | Runs `action`, unless disabled, or pending with `whilePending="ignore"`. |
| A key the item handled itself | item | Ignored by the toolbar (a `Menu.Trigger`'s ArrowDown opens its menu). |

Natively `disabled` controls are skipped; `aria-disabled` ones are reached, also by Home and End. A popup rendered inside the toolbar (a `Menu.Popup`) is not part of the sequence: its items are the menu's.

### Disabled controls

Inside a toolbar every library button-like part stays focusable when disabled, so a screen-reader user still finds it (APG Toolbar): it renders `aria-disabled="true"` instead of native `disabled`, stays in the arrow sequence, and its click, Enter and Space do nothing. Outside a toolbar a disabled Toggle or ToggleGroup Item is natively disabled.

| Part | Disabled inside a Toolbar | Disabled outside one |
| - | - | - |
| `Button` | `aria-disabled="true"`, in the sequence | native `disabled` |
| `Toggle` | `aria-disabled="true"`, in the sequence | native `disabled` |
| `ToggleGroup.Item` (own `disabled` or the group's) | `aria-disabled="true"`, in the sequence | native `disabled`, skipped by the group's arrows |
| `Menu.Trigger`, `Popover.Trigger`, `Dialog.Trigger`, `AlertDialog.Trigger`, `Drawer.Trigger` | `aria-disabled="true"`, in the sequence; the invoker attributes are removed | native `disabled` |
| Your own `<button disabled>` | native `disabled`, skipped (your choice) | native `disabled` |

Style a disabled control inside a toolbar with `[data-disabled]`, not `:disabled`.

### A ToggleGroup inside a Toolbar

The group joins the toolbar's single sequence: Left / Right (or Up / Down when vertical) flow through its Items like any other items, and the other axis does nothing on them. The group's own `orientation`, `loop` and `experimental_focusGroup` are ignored there (with a development warning); it still renders `role="group"`, its label and its pending state.

### A Menu.Trigger inside a Toolbar

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

> **Label the toolbar**
>
> A toolbar must have a name: pass `aria-label` or `aria-labelledby`. Name each ToggleGroup inside it too.

> **One text-entry control, last**
>
> An input, textarea, select, contenteditable or a control with role `textbox`, `combobox`, `spinbutton` or `slider` keeps its arrow keys, Home and End. From it, Tab and Shift+Tab move to the next and previous toolbar item while one exists (as Chromium's native `focusgroup` does). Following the APG, put at most one such control in a toolbar, and put it last.

> **Radios inside a toolbar trap the arrow keys**
>
> A group of native radios with one `name` (a [RadioGroup](radio-group.md) too) is one toolbar item. The toolbar's arrows land on its checked radio, or on its first radio when none is checked. On a radio, every arrow key is the radio group's: it checks as it moves and stays within the group (wrapping, except in Safari), so in a horizontal toolbar ArrowLeft / ArrowRight never leave the group (ArrowUp / ArrowDown in a vertical one). Leave it with Tab or Shift+Tab, which move to the next or previous toolbar item; from an unchecked radio they visit the checked one first. Both the JS path and Chromium's native `focusgroup` behave this way. Radios that share a `name` but belong to different forms (`form=`) are not told apart.
>
> For a one-of-several choice that is transparent to the toolbar's arrows (text alignment), use an `exclusive` [ToggleGroup](toggle-group.md). For Up / Down within the group and Left / Right through the toolbar, as in the APG Toolbar example, build the group from `button[role="radio"]` elements with your own key handlers: custom radios are ordinary toolbar items.

## Transition types

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

None: the Toolbar has no state of its own.

## Optimistic and pending

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

None of its own: controls inside keep their own optimistic and pending state.

## Suspense

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

Nothing specific: the Toolbar renders no content region.

## Browser-owned state

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

None.

## Before hydration

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

The toolbar writes `tabindex` from an effect, so the server HTML has none: before hydration every control is its own Tab stop, reachable and working with its native behaviour. After hydration there is one Tab stop.

## Styling

```css
.toolbar { display: flex; gap: .25rem; }
.toolbar[data-orientation="vertical"] { flex-direction: column; }
/* <hr> is a block; in a horizontal toolbar it is a vertical rule. */
.toolbar-separator { margin: 0; border: 0; background: var(--line); }
.toolbar-separator[data-orientation="vertical"] { inline-size: 1px; align-self: stretch; }
.toolbar-separator[data-orientation="horizontal"] { block-size: 1px; }
.toolbar-button[data-disabled] { opacity: .5; }
.toolbar-button[data-pending] { cursor: progress; }

@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(*),
  ::view-transition-old(*),
  ::view-transition-new(*) {
    animation: none !important;
  }
}
```

A `Button`'s `transition` animates the commit that ends its action with a view transition; keep the reduced-motion block above in your stylesheet. The Toolbar adds no view transition types of its own.

## Recipes

### Vertical toolbar

```tsx title="ToolbarVertical.tsx"
"use client";
import { useState } from "react";
import { Button } from "@funstack/ui/button";
import { Menu } from "@funstack/ui/menu";
import { Toolbar } from "@funstack/ui/toolbar";

// A vertical toolbar. Up / Down walk the tools; on Shapes, ArrowRight opens the menu with its
// first item focused (ArrowLeft under direction: rtl) and ArrowDown moves on to the next tool.
// The popup sits on the inline-end side; a right-to-left page would use side="left".
export function ToolbarVertical() {
  const [tool, setTool] = useState("select");
  return (
    <div className="demo-row">
      <Toolbar.Root orientation="vertical" aria-label="Tools" className="demo-toolbar">
        <Button className="demo-toolbar-button" action={() => setTool("select")}>
          Select
        </Button>
        <Button className="demo-toolbar-button" action={() => setTool("draw")}>
          Draw
        </Button>
        <Toolbar.Separator className="demo-toolbar-separator" />
        <Menu.Root>
          <Menu.Trigger className="demo-toolbar-button">Shapes</Menu.Trigger>
          <Menu.Popup className="demo-menu" side="inline-end">
            <Menu.Item action={() => setTool("rectangle")}>Rectangle</Menu.Item>
            <Menu.Item action={() => setTool("ellipse")}>Ellipse</Menu.Item>
          </Menu.Popup>
        </Menu.Root>
      </Toolbar.Root>
      <p>
        Tool: <output>{tool}</output>
      </p>
    </div>
  );
}
```

Up / Down walk the tools. A `Menu.Trigger` in a vertical toolbar opens on the inline-end arrow: ArrowRight, or ArrowLeft under `direction: rtl`. Put its popup on that side: `side="inline-end"`, the right in LTR and the left in a right-to-left page or container. ArrowDown moves on to the next tool.
