All components
Toolbar
A row of buttons, links, inputs and toggle groups with a single Tab stop and arrow-key navigation.
123456789101112131415161718import { 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> );}Variants
surface
plain
Sizes
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.
123456789101112import { 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.
12345678910111213141516import { 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.
123456<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>Install
1npx stylexblocks add toolbarSource
components/ui/ark-ui/toolbar.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535import * 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>;