---
title: "Toolbar · Ark UI — StyleX Blocks"
description: "A row of buttons, links, inputs and toggle groups with a single Tab stop and arrow-key navigation."
url: "https://stylexblocks.com/components/ark-ui/toolbar/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Toolbar

A row of buttons, links, inputs and toggle groups with a single Tab stop and arrow-key navigation.

- Behavior engine: Ark UI
- Also available for: [Base UI](https://stylexblocks.com/components/base-ui/toolbar.md), [UI SDK](https://stylexblocks.com/components/ui-sdk/toolbar.md)
- Category: Display
- Variants: surface, plain
- Sizes: xs, sm, md, lg
- HTML page: https://stylexblocks.com/components/ark-ui/toolbar/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init
```

Then add the item as source you own:

```sh
npx stylexblocks add toolbar
```

Equivalent: `npx shadcn add @stylexblocks/toolbar`. Registry item JSON: https://stylexblocks.com/r/ark-ui/toolbar.json

## Usage

```tsx
import { Toolbar } from "#components/ui/ark-ui/toolbar.tsx";
import { ToggleGroup } from "#components/ui/ark-ui/toggle-group.tsx";

export function Example() {
  return (
    // one Tab stop; arrow keys rove across every item. Ark's ToggleGroup
    // has its own roving focus — turn it off so the toolbar owns the keys.
    <Toolbar.Root variant="surface" size="md" aria-label="Text formatting">
      <ToggleGroup.Root rovingFocus={false} multiple aria-label="Formatting">
        <ToggleGroup.Item value="bold" aria-label="Bold"><BoldIcon /></ToggleGroup.Item>
        <ToggleGroup.Item value="italic" aria-label="Italic"><ItalicIcon /></ToggleGroup.Item>
      </ToggleGroup.Root>
      <Toolbar.Separator />
      <Toolbar.Link href="/history">Edited 5m ago</Toolbar.Link>
      <Toolbar.Button>Share</Toolbar.Button>
    </Toolbar.Root>
  );
}
```

## Examples

### With an input

Toolbar.Input joins the arrow-key order; while it has focus the caret keys edit text until the caret reaches either end.

```tsx
import { Toolbar } from "#components/ui/ark-ui/toolbar.tsx";

export function Example() {
  return (
    <Toolbar.Root aria-label="Search">
      <Toolbar.Button>Filter</Toolbar.Button>
      <Toolbar.Input placeholder="Search…" aria-label="Search" />
      <Toolbar.Separator />
      <Toolbar.Button>Export</Toolbar.Button>
    </Toolbar.Root>
  );
}
```

### Vertical

orientation="vertical" stacks the items, turns separators horizontal and moves focus with Up and Down.

```tsx
import { Toolbar } from "#components/ui/ark-ui/toolbar.tsx";
import { ToggleGroup } from "#components/ui/ark-ui/toggle-group.tsx";

export function Example() {
  return (
    <Toolbar.Root orientation="vertical" aria-label="Alignment">
      <ToggleGroup.Root rovingFocus={false} orientation="vertical" defaultValue={["left"]} aria-label="Alignment">
        <ToggleGroup.Item value="left" aria-label="Align left"><AlignLeftIcon /></ToggleGroup.Item>
        <ToggleGroup.Item value="center" aria-label="Align center"><AlignCenterIcon /></ToggleGroup.Item>
        <ToggleGroup.Item value="right" aria-label="Align right"><AlignRightIcon /></ToggleGroup.Item>
      </ToggleGroup.Root>
      <Toolbar.Separator />
      <Toolbar.Button aria-label="Bold"><BoldIcon /></Toolbar.Button>
    </Toolbar.Root>
  );
}
```

### Plain

The plain variant drops the panel chrome so the toolbar can sit inside a header or card.

```tsx
<Toolbar.Root variant="plain" aria-label="Actions">
  <Toolbar.Button>Reply</Toolbar.Button>
  <Toolbar.Button>Forward</Toolbar.Button>
  <Toolbar.Separator />
  <Toolbar.Button disabled>Archive</Toolbar.Button>
</Toolbar.Root>
```

## Source

`components/ui/ark-ui/toolbar.tsx`

```tsx
import * as stylex from "@stylexjs/stylex";
import { createContext, useCallback, useContext, useEffect, useRef } from "react";
import { ark, type HTMLArkProps } from "@ark-ui/react/factory";
import { createSlotRecipeContext } from "#lib/ark-ui/create-slot-recipe-context.tsx";
import { defineSlotRecipe } from "#lib/recipe-props.ts";
import { colorPalette } from '@stylexblocks/ui/color-palette.stylex.ts'
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { semanticShadows } from '@stylexblocks/ui/semantic-tokens/shadows.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'

// A row (or column) of controls. Buttons and links (both the `button` slot)
// share the Toggle's ghost metrics so toggle groups sit flush beside them;
// orientation is read from the `data-orientation` attribute both engines
// emit.

const toolbarRoot = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    flexDirection: {
      default: 'row',
      ':is([data-orientation="vertical"])': 'column',
    },
    width: 'fit-content',
    gap: spacing._1,
  },
})

const toolbarRootVariants = stylex.create({
  surface: {
    backgroundColor: semanticColors.bgPanel,
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: semanticColors.border,
    borderRadius: semanticRadii.panel,
    boxShadow: semanticShadows.xs,
    padding: spacing._1,
  },
  plain: {},
})

const toolbarRootSizes = stylex.create({
  xs: {
    gap: spacing._0_5,
  },
  sm: {
    gap: spacing._1,
  },
  md: {
    gap: spacing._1,
  },
  lg: {
    gap: spacing._1_5,
  },
})

const toolbarGroup = stylex.create({
  base: {
    display: 'flex',
    alignItems: 'center',
    flexDirection: {
      default: 'row',
      ':is([data-orientation="vertical"])': 'column',
    },
    gap: spacing._1,
  },
})

const toolbarButton = stylex.create({
  base: {
    display: 'inline-flex',
    appearance: 'none',
    alignItems: 'center',
    justifyContent: 'center',
    userSelect: 'none',
    position: 'relative',
    whiteSpace: 'nowrap',
    flexShrink: 0,
    margin: 0,
    borderWidth: 0,
    fontFamily: 'inherit',
    fontWeight: fontWeights.medium,
    lineHeight: 1.2,
    textDecoration: 'none',
    outline: 'none',
    transitionProperty: 'background-color, border-color, color, box-shadow',
    transitionDuration: durations.moderate,
    outlineWidth: {
      default: null,
      ':focus-visible': '1px',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '2px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
    cursor: {
      default: 'pointer',
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
    color: {
      default: semanticColors.fgMuted,
      ':hover': semanticColors.fg,
      ':is([data-popup-open], [data-state="open"], [aria-expanded="true"])':
        semanticColors.fg,
    },
    backgroundColor: {
      default: 'transparent',
      ':hover': colorPalette.muted,
      ':is([data-popup-open], [data-state="open"], [aria-expanded="true"])':
        colorPalette.subtle,
    },
  },
})

const toolbarButtonSizes = stylex.create({
  xs: {
    gap: spacing._1,
    height: sizes.controlXs,
    minWidth: sizes.controlXs,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._1_5,
    fontSize: fontSizes.xs,
    lineHeight: lineHeights.xs,
  },
  sm: {
    gap: spacing._1_5,
    height: sizes.controlSm,
    minWidth: sizes.controlSm,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
  md: {
    gap: spacing._2,
    height: sizes.controlMd,
    minWidth: sizes.controlMd,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2_5,
    fontSize: fontSizes.sm,
    lineHeight: lineHeights.sm,
  },
  lg: {
    gap: spacing._2,
    height: sizes.controlLg,
    minWidth: sizes.controlLg,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._3,
    fontSize: fontSizes.md,
    lineHeight: lineHeights.md,
  },
})

const toolbarInput = stylex.create({
  base: {
    display: 'inline-flex',
    appearance: 'none',
    alignItems: 'center',
    flexShrink: 0,
    minWidth: 0,
    width: '10rem',
    margin: 0,
    fontFamily: 'inherit',
    fontWeight: fontWeights.normal,
    color: semanticColors.fg,
    backgroundColor: semanticColors.bg,
    borderWidth: '1px',
    borderStyle: 'solid',
    borderColor: {
      default: semanticColors.border,
      ':hover': semanticColors.borderEmphasized,
    },
    cursor: {
      default: 'text',
      ':is(:disabled, [disabled], [data-disabled])': 'not-allowed',
    },
    transitionProperty: 'border-color, box-shadow',
    transitionDuration: durations.moderate,
    outline: 'none',
    outlineWidth: {
      default: null,
      ':focus-visible': '1px',
    },
    outlineOffset: {
      default: null,
      ':focus-visible': '-1px',
    },
    outlineStyle: {
      default: null,
      ':focus-visible': 'solid',
    },
    outlineColor: {
      default: null,
      ':focus-visible': colorPalette.focusRing,
    },
    opacity: {
      default: null,
      ':is(:disabled, [disabled], [data-disabled])': 0.5,
    },
  },
})

const toolbarInputSizes = stylex.create({
  xs: {
    height: sizes.controlXs,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2,
    fontSize: fontSizes.xs,
  },
  sm: {
    height: sizes.controlSm,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2,
    fontSize: fontSizes.sm,
  },
  md: {
    height: sizes.controlMd,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._2_5,
    fontSize: fontSizes.sm,
  },
  lg: {
    height: sizes.controlLg,
    borderRadius: semanticRadii.control,
    paddingInline: spacing._3,
    fontSize: fontSizes.md,
  },
})

const toolbarSeparator = stylex.create({
  base: {
    flexShrink: 0,
    alignSelf: 'stretch',
    backgroundColor: semanticColors.border,
    width: {
      default: '1px',
      ':is([data-orientation="horizontal"])': 'auto',
    },
    height: {
      default: 'auto',
      ':is([data-orientation="horizontal"])': '1px',
    },
    marginInline: {
      default: spacing._1,
      ':is([data-orientation="horizontal"])': 0,
    },
    marginBlock: {
      default: spacing._1,
      ':is([data-orientation="horizontal"])': 0,
    },
  },
})

export type ToolbarVariant = keyof typeof toolbarRootVariants

export type ToolbarSize = keyof typeof toolbarRootSizes

const toolbarRecipe = defineSlotRecipe({
  slots: {
    root: { styles: toolbarRoot, variants: toolbarRootVariants, sizes: toolbarRootSizes },
    group: { styles: toolbarGroup },
    button: { styles: toolbarButton, sizes: toolbarButtonSizes },
    input: { styles: toolbarInput, sizes: toolbarInputSizes },
    separator: { styles: toolbarSeparator },
  },
  defaultVariants: { variant: "surface", size: "md" },
});

type Orientation = "horizontal" | "vertical";

interface ToolbarContextValue {
  orientation: Orientation;
  disabled: boolean;
}

const ToolbarContext = createContext<ToolbarContextValue>({
  orientation: "horizontal",
  disabled: false,
});

// Everything focusable inside the toolbar takes part in the roving tab stop.
const ITEM_SELECTOR =
  'button, a[href], input, select, textarea, [data-toolbar-item]';

function isDisabled(el: Element) {
  return (el as HTMLButtonElement).disabled === true || el.getAttribute("aria-disabled") === "true";
}

function isTextField(el: Element): el is HTMLInputElement | HTMLTextAreaElement {
  if (el instanceof HTMLTextAreaElement) return true;
  return (
    el instanceof HTMLInputElement &&
    !["button", "checkbox", "radio", "reset", "submit", "image", "range", "color"].includes(el.type)
  );
}

export interface ToolbarRootProps extends HTMLArkProps<"div"> {
  ref?: React.Ref<HTMLDivElement>;
  /** Arrow-key axis; also flips the separators. @default "horizontal" */
  orientation?: Orientation;
  /** Wrap focus from the last item to the first and back. @default true */
  loopFocus?: boolean;
  /** Disables every button, link and input in the toolbar. */
  disabled?: boolean;
}

/**
 * A WAI-ARIA toolbar: one Tab stop, arrow keys move between items (roving
 * tabindex), Home/End jump to the ends. Text inputs keep their caret keys
 * until the caret reaches an edge. The roving state is kept on the DOM, so
 * any focusable child (buttons, links, inputs, nested toggle groups) joins
 * the order.
 */
function RootNode({
  orientation = "horizontal",
  loopFocus = true,
  disabled = false,
  ref,
  onKeyDown,
  onFocus,
  ...props
}: ToolbarRootProps) {
  const rootRef = useRef<HTMLDivElement | null>(null);
  const activeRef = useRef<HTMLElement | null>(null);

  const getItems = useCallback(() => {
    const root = rootRef.current;
    if (!root) return [];
    return Array.from(root.querySelectorAll<HTMLElement>(ITEM_SELECTOR)).filter(
      (el) => !isDisabled(el) && el.closest('[role="toolbar"]') === root,
    );
  }, []);

  const sync = useCallback(() => {
    const root = rootRef.current;
    if (!root) return;
    const items = getItems();
    if (!activeRef.current || !items.includes(activeRef.current)) {
      activeRef.current = items[0] ?? null;
    }
    for (const el of root.querySelectorAll<HTMLElement>(`${ITEM_SELECTOR}, [tabindex]`)) {
      if (el.closest('[role="toolbar"]') !== root) continue;
      const next = el === activeRef.current ? "0" : "-1";
      if (el.getAttribute("tabindex") !== next) el.setAttribute("tabindex", next);
    }
  }, [getItems]);

  useEffect(() => {
    sync();
  });

  useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    // Children re-render on their own (a toggle flipping, an item appearing);
    // re-assert the single tab stop whenever the subtree changes. Writes are
    // idempotent, so observing `tabindex` cannot loop.
    const observer = new MutationObserver(sync);
    observer.observe(root, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ["tabindex", "disabled", "aria-disabled"],
    });
    return () => observer.disconnect();
  }, [sync]);

  const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    const target = event.target as HTMLElement;
    const items = getItems();
    const index = items.indexOf(target);
    if (index === -1) return;

    const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
    const prevKey =
      orientation === "vertical" ? "ArrowUp" : rtl ? "ArrowRight" : "ArrowLeft";
    const nextKey =
      orientation === "vertical" ? "ArrowDown" : rtl ? "ArrowLeft" : "ArrowRight";

    let nextIndex: number | null = null;
    if (event.key === prevKey || event.key === nextKey) {
      const forward = event.key === nextKey;
      if (isTextField(target)) {
        const atStart = target.selectionStart === 0 && target.selectionEnd === 0;
        const atEnd = target.selectionStart === target.value.length;
        if (forward ? !atEnd : !atStart) return;
      }
      nextIndex = index + (forward ? 1 : -1);
      if (nextIndex < 0) nextIndex = loopFocus ? items.length - 1 : 0;
      if (nextIndex >= items.length) nextIndex = loopFocus ? 0 : items.length - 1;
    } else if (event.key === "Home" && !isTextField(target)) {
      nextIndex = 0;
    } else if (event.key === "End" && !isTextField(target)) {
      nextIndex = items.length - 1;
    }
    if (nextIndex === null) return;
    event.preventDefault();
    const next = items[nextIndex];
    if (!next) return;
    activeRef.current = next;
    sync();
    next.focus();
  };

  const handleFocus = (event: React.FocusEvent<HTMLDivElement>) => {
    onFocus?.(event);
    const target = event.target as HTMLElement;
    if (getItems().includes(target) && activeRef.current !== target) {
      activeRef.current = target;
      sync();
    }
  };

  return (
    <ToolbarContext.Provider value={{ orientation, disabled }}>
      <ark.div
        role="toolbar"
        aria-orientation={orientation}
        data-orientation={orientation}
        data-disabled={disabled ? "" : undefined}
        {...props}
        ref={(node: HTMLDivElement | null) => {
          rootRef.current = node;
          if (typeof ref === "function") ref(node);
          else if (ref) ref.current = node;
        }}
        onKeyDown={handleKeyDown}
        onFocus={handleFocus}
      />
    </ToolbarContext.Provider>
  );
}

function GroupNode({ disabled, ...props }: HTMLArkProps<"div"> & { disabled?: boolean }) {
  const toolbar = useContext(ToolbarContext);
  const isDisabled = toolbar.disabled || !!disabled;
  return (
    <ToolbarContext.Provider value={{ orientation: toolbar.orientation, disabled: isDisabled }}>
      <ark.div
        role="group"
        data-orientation={toolbar.orientation}
        data-disabled={isDisabled ? "" : undefined}
        {...props}
      />
    </ToolbarContext.Provider>
  );
}

function ButtonNode({ disabled, ...props }: HTMLArkProps<"button">) {
  const toolbar = useContext(ToolbarContext);
  const isDisabled = toolbar.disabled || !!disabled;
  return (
    <ark.button
      type="button"
      data-orientation={toolbar.orientation}
      data-disabled={isDisabled ? "" : undefined}
      disabled={isDisabled}
      {...props}
    />
  );
}

function LinkNode(props: HTMLArkProps<"a">) {
  const toolbar = useContext(ToolbarContext);
  return <ark.a data-orientation={toolbar.orientation} {...props} />;
}

function InputNode({ disabled, ...props }: HTMLArkProps<"input">) {
  const toolbar = useContext(ToolbarContext);
  const isDisabled = toolbar.disabled || !!disabled;
  return (
    <ark.input
      data-orientation={toolbar.orientation}
      data-disabled={isDisabled ? "" : undefined}
      disabled={isDisabled}
      {...props}
    />
  );
}

function SeparatorNode(props: HTMLArkProps<"div">) {
  const toolbar = useContext(ToolbarContext);
  const orientation = toolbar.orientation === "vertical" ? "horizontal" : "vertical";
  return (
    <ark.div
      role="separator"
      aria-orientation={orientation}
      data-orientation={orientation}
      {...props}
    />
  );
}

const { withProvider, withContext } = createSlotRecipeContext(toolbarRecipe);

/**
 * Toolbar — hand-built on Ark's `ark` factory (Ark ships no toolbar
 * primitive), following the WAI-ARIA toolbar pattern: `role="toolbar"`, a
 * single Tab stop and roving focus with the arrow keys. `<Toolbar.Root
 * variant size>` resolves the recipe once; parts inherit it. Toggle groups
 * drop straight in — pass `rovingFocus={false}` to an Ark ToggleGroup so the
 * toolbar owns the arrow keys. Composition via `asChild`.
 */
export const Toolbar = {
  Root: withProvider(RootNode, "root", "ToolbarRoot"),
  Group: withContext(GroupNode, "group", "ToolbarGroup"),
  Button: withContext(ButtonNode, "button", "ToolbarButton"),
  Link: withContext(LinkNode, "button", "ToolbarLink"),
  Input: withContext(InputNode, "input", "ToolbarInput"),
  Separator: withContext(SeparatorNode, "separator", "ToolbarSeparator"),
};

export type ToolbarButtonProps = React.ComponentProps<typeof Toolbar.Button>;
export type ToolbarLinkProps = React.ComponentProps<typeof Toolbar.Link>;
export type ToolbarInputProps = React.ComponentProps<typeof Toolbar.Input>;
```
