{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "toolbar",
  "title": "Toolbar",
  "description": "A row of commands that is one Tab stop (Base UI Toolbar): item cells on shared seams, groups on a 2px keyline, toggles that flood, an exclusive group whose ink band stretches, menus docked to the frame, a text input cell; horizontal or vertical.",
  "dependencies": [
    "@base-ui/react@1.9.0",
    "class-variance-authority"
  ],
  "registryDependencies": [
    "@keyline-ui/keyline",
    "utils",
    "@keyline-ui/keyline-motion",
    "@keyline-ui/keyline-scope",
    "@keyline-ui/scroll-edges",
    "@keyline-ui/menu",
    "@keyline-ui/keyline-render",
    "@keyline-ui/toolbar-overflow"
  ],
  "files": [
    {
      "path": "src/registry/keyline/ui/toolbar.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { Toolbar as ToolbarPrimitive } from \"@base-ui/react/toolbar\";\nimport { Toggle } from \"@base-ui/react/toggle\";\nimport { ToggleGroup as ToggleGroupPrimitive } from \"@base-ui/react/toggle-group\";\nimport { Menu as MenuPrimitive } from \"@base-ui/react/menu\";\nimport { DirectionProvider } from \"@base-ui/react/direction-provider\";\nimport { mergeProps } from \"@base-ui/react/merge-props\";\nimport { useRender } from \"@base-ui/react/use-render\";\nimport { cva } from \"class-variance-authority\";\n\nimport { cn } from \"@/lib/utils\";\nimport { floodHandlers, useStretch } from \"../lib/keyline-motion\";\nimport { scopeProps, useDomDirection, useKeylineScope, useMergedRef } from \"../lib/keyline-scope\";\nimport { useScrollEdges } from \"../lib/scroll-edges\";\nimport { resolveClassName, resolveStyle, type PartProps } from \"../lib/keyline-render\";\nimport { fitStep, fold, isGroup, kindOf, splits, type Blocked, type RowItem } from \"../lib/toolbar-overflow\";\nimport {\n  Menu,\n  MenuItem,\n  MenuCheckboxItem,\n  MenuRadioGroup,\n  MenuRadioItem,\n  MenuSeparator,\n  MenuGroup,\n  MenuGroupLabel,\n  MenuSubmenuRoot,\n  MenuSubmenuTrigger,\n  MenuPopup,\n  MenuSurface,\n} from \"./menu\";\n\ntype Layout = \"control\" | \"cell\";\ntype Orientation = \"horizontal\" | \"vertical\";\nconst ToolbarCtx = React.createContext<{ layout: Layout; orientation: Orientation; inToolbar: boolean }>({\n  layout: \"control\",\n  orientation: \"horizontal\",\n  inToolbar: false,\n});\n/** True inside a Toolbar: parts written for a plain row (a filter token) render as toolbar items there. */\nconst useInToolbar = () => React.useContext(ToolbarCtx).inToolbar;\n\ntype Signal = \"idle\" | \"pending\" | \"done\" | \"failed\";\n\n/* ------------------------------------------------------------------ *\n * CLASSES\n * The row is one control frame of item cells. Every rule over the row's children keys on data-slot and sits on\n * the root, so a wrapped or custom item (a Tooltip's trigger, a caller's component rendering a ToolbarGroup) is\n * drawn like any other. --kl-tb-h is the inner height, so glyph-only items are square at every density.\n * ------------------------------------------------------------------ */\n\nconst rootVariants = cva(\n  [\n    \"kl-ctl group/toolbar flex min-h-(--kl-ctl) w-max max-w-full min-w-0 items-stretch overflow-x-auto overflow-y-hidden text-kl-ink\",\n    \"[--kl-tb-h:calc(var(--kl-ctl)-2*var(--kl-k2))] [overscroll-behavior-inline:contain]\",\n    \"[scrollbar-width:thin] [scrollbar-color:var(--kl-ink-3)_transparent]\",\n    // with a spacer the toolbar spans its container\n    \"has-[>[data-slot=toolbar-spacer]]:w-auto\",\n    // seams: every item after the first draws its start edge, 1px; after a group (in the row) the edge is the\n    // group's, 2px; a separator owns its own 2px edge and the item after it draws none. Folded items stay in the\n    // DOM (hidden), so a hidden group is not a neighbour.\n    \"data-[orientation=horizontal]:[&>:not([data-slot=toolbar-separator])+:not([data-slot=toolbar-separator])]:border-s-(length:--kl-k1)\",\n    \"data-[orientation=horizontal]:[&>:not([data-slot=toolbar-separator])+:not([data-slot=toolbar-separator])]:border-s-kl-seam\",\n    \"data-[orientation=horizontal]:[&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group]):not([hidden])+:not([data-slot=toolbar-separator])]:border-s-(length:--kl-k2)\",\n    \"data-[orientation=horizontal]:[&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group]):not([hidden])+:not([data-slot=toolbar-separator])]:border-s-kl-line\",\n    \"data-[orientation=vertical]:[&>:not([data-slot=toolbar-separator])+:not([data-slot=toolbar-separator])]:border-t-(length:--kl-k1)\",\n    \"data-[orientation=vertical]:[&>:not([data-slot=toolbar-separator])+:not([data-slot=toolbar-separator])]:border-t-kl-seam\",\n    \"data-[orientation=vertical]:[&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group]):not([hidden])+:not([data-slot=toolbar-separator])]:border-t-(length:--kl-k2)\",\n    \"data-[orientation=vertical]:[&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group]):not([hidden])+:not([data-slot=toolbar-separator])]:border-t-kl-line\",\n    // the first item (of the row, and of each group in it) clears the cut's corner: it never collapses into the bevel\n    \"data-[kl-layout=control]:data-[orientation=horizontal]:[&>:nth-child(1_of_[data-kl-tb-item]),&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group])>:nth-child(1_of_[data-kl-tb-item])]:ps-[calc(var(--kl-c,0px)*0.35)]\",\n    \"data-[kl-layout=control]:data-[orientation=vertical]:[&>:nth-child(1_of_[data-kl-tb-item]),&>:is([data-slot=toolbar-group],[data-slot=toolbar-toggle-group])>:nth-child(1_of_[data-kl-tb-item])]:pt-[calc(var(--kl-c,0px)*0.35)]\",\n    // a cell toolbar, or one with overflow=\"menu\", that doesn't fill its line closes its last item with an empty\n    // cell, so the item's end edge is drawn (by the filler's seam) and the frame's own edge is never doubled. The\n    // seam lies over the last item's end pixel, so a filler squeezed to nothing never stacks it on the frame.\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:relative\",\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:flex-[1_0_0]\",\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:content-['']\",\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-s-(length:--kl-k1)\",\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-s-kl-seam\",\n    \"[&:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:-ms-(--kl-k1)\",\n    // in a palette the filler sits below the last item: its seam is the block-start edge, never a side\n    \"[&[data-orientation=vertical]:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-s-0\",\n    \"[&[data-orientation=vertical]:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:ms-0\",\n    \"[&[data-orientation=vertical]:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-t-(length:--kl-k1)\",\n    \"[&[data-orientation=vertical]:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-t-kl-seam\",\n    \"[&[data-orientation=vertical]:is([data-kl-layout=cell],[data-kl-overflow=menu]):not(:has(>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:-mt-(--kl-k1)\",\n    // a palette holding every tool is sized by them: its filler is only the fit's 2px headroom, not a cell, so it\n    // draws no seam (a seam 2px inside the frame reads as a doubled bottom edge). With More it is a real cell.\n    \"[&[data-orientation=vertical][data-kl-overflow=menu][data-kl-overflow=menu]:not(:has(>[data-slot=toolbar-more],>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:border-t-0\",\n    \"[&[data-orientation=vertical][data-kl-overflow=menu][data-kl-overflow=menu]:not(:has(>[data-slot=toolbar-more],>[data-slot=toolbar-spacer])):not([data-kl-more])]:after:mt-0\",\n  ],\n  {\n    variants: {\n      /** control: its own frame. cell: a row of an enclosing frame; the foundation's layout=\"cell\" drops the frame and\n       * the background. */\n      layout: {\n        control: \"bg-kl-cell\",\n        cell: \"min-h-(--kl-row) w-auto flex-auto [--kl-tb-h:var(--kl-row)]\",\n      },\n      /** vertical: a column of cells (a tool palette). */\n      orientation: { horizontal: \"\", vertical: \"w-max flex-col overflow-x-hidden overflow-y-auto\" },\n      /** menu: the toolbar spans its line (the space it may use is measured), never scrolls unless even the kept\n       * items don't fit; a palette takes the height its container gives it (min 0 so a flex column can shrink it). */\n      overflow: { scroll: \"\", menu: \"\" },\n    },\n    compoundVariants: [\n      { overflow: \"menu\", orientation: \"horizontal\", className: \"w-auto\" },\n      { overflow: \"menu\", orientation: \"vertical\", className: \"max-h-full min-h-0 overflow-y-hidden\" },\n    ],\n    defaultVariants: { layout: \"control\", orientation: \"horizontal\", overflow: \"scroll\" },\n  },\n);\n\n/*\n * An item cell. It holds no padding of its own: the label carries it, so the signal cells sit on its edges. Its\n * hover tint gives way to any state that fills it (pressed, an open menu, covered by the band, the primary), and a\n * press outranks the hover. An open tooltip is not a held state: only an open menu (aria-expanded) fills the cell.\n */\nconst itemVariants = cva(\n  [\n    \"group/toolbar-item relative box-border flex flex-none cursor-pointer appearance-none items-stretch no-underline select-none\",\n    \"font-(family-name:--kl-font) text-[14px]/[1.2] font-(--kl-weight-strong) whitespace-nowrap\",\n    \"[-webkit-tap-highlight-color:transparent] [&_svg]:flex-none\",\n    \"hover:[&:not([data-pressed],[aria-expanded=true],[data-disabled],[data-kl-covered],[data-kl-primary])]:bg-kl-tint\",\n    \"active:not-data-disabled:not-data-pressed:not-data-kl-covered:bg-kl-press\",\n    \"focus-visible:outline-(length:--kl-ring) focus-visible:outline-offset-(--kl-ring-in) focus-visible:outline-kl-focus focus-visible:outline-solid\",\n    // busy is not out of service: a pending item keeps its look and runs the segment\n    \"aria-busy:cursor-progress\",\n    \"data-disabled:not-aria-busy:cursor-not-allowed data-disabled:not-aria-busy:bg-(image:--kl-hatch) data-disabled:not-aria-busy:text-kl-dis\",\n    // a menu title, open: the inverse cell (Select's open caret, Menubar's open title)\n    \"aria-expanded:bg-kl-inverse aria-expanded:text-kl-on-inverse aria-expanded:focus-visible:outline-current\",\n    \"forced-colors:data-pressed:outline-3 forced-colors:data-pressed:outline-offset-[-4px] forced-colors:data-pressed:outline-[Highlight] forced-colors:data-pressed:outline-solid\",\n    \"forced-colors:aria-expanded:outline-3 forced-colors:aria-expanded:outline-offset-[-4px] forced-colors:aria-expanded:outline-[Highlight] forced-colors:aria-expanded:outline-solid\",\n  ],\n  {\n    variants: {\n      orientation: { horizontal: \"\", vertical: \"min-h-(--kl-tb-h)\" },\n      icon: { true: \"min-w-(--kl-tb-h)\", false: \"\" },\n      /** the row's one commit action: the cobalt cell. Pressed it goes deeper cobalt, as Button does; disabled it is\n       * out of service like any item (the dis label on the hatch). */\n      primary: {\n        true: [\n          \"bg-kl-cobalt text-kl-on-cobalt hover:not-data-disabled:bg-kl-cobalt-hi\",\n          \"active:not-data-disabled:not-data-pressed:not-data-kl-covered:bg-kl-cobalt-lo\",\n          \"focus-visible:outline-current\",\n          \"data-disabled:not-aria-busy:bg-kl-cell data-disabled:not-aria-busy:text-kl-dis\",\n          \"forced-colors:bg-[ButtonText] forced-colors:text-[ButtonFace] forced-colors:forced-color-adjust-none\",\n        ],\n        false: \"\",\n      },\n    },\n    defaultVariants: { orientation: \"horizontal\", icon: false, primary: false },\n  },\n);\n\n/* A toggle on its own or in a multiple group floods (its own state); in an exclusive group it is a choice the ink band\n * covers. A flood owns its filled state: the ring on the fill takes the fill's text colour. */\nconst floodToggle = \"kl-flood data-pressed:focus-visible:outline-(color:--kl-fg)\";\nconst choiceToggle = cn(\n  \"data-kl-covered:text-kl-on-inverse data-kl-covered:focus-visible:outline-current\",\n  \"forced-colors:data-kl-covered:text-[HighlightText] forced-colors:data-kl-covered:forced-color-adjust-none\",\n);\n\nconst labelVariants = cva(\"flex min-w-0 flex-1 items-center justify-center gap-2 px-[calc(var(--kl-inset)+2px)]\", {\n  variants: {\n    orientation: { horizontal: \"\", vertical: \"justify-start\" },\n    icon: { true: \"justify-center px-0\", false: \"\" },\n    // a menu title: the caret sits close to the label it follows, never across a divider\n    caret: { true: \"pe-[6px]\", false: \"\" },\n    link: { true: \"underline decoration-1 underline-offset-4 group-hover/toolbar-item:decoration-2\", false: \"\" },\n  },\n  defaultVariants: { orientation: \"horizontal\", icon: false, caret: false, link: false },\n});\n\n/* affix: a count or a shortcut, divided inside the item as ButtonAffix is. On a filled cell (open, primary) its divider\n * takes the cell's text colour, so it stays visible; a key (kbd) or a code is mono, in the item's colour. */\nconst affixVariants = cva(\n  [\n    \"flex min-w-(--kl-tb-h) items-center justify-center px-2 font-(--kl-weight-display) tabular-nums\",\n    \"border-s-(length:--kl-k1) border-s-kl-seam\",\n    \"group-aria-expanded/toolbar-item:border-s-current group-data-kl-primary/toolbar-item:border-s-current\",\n    \"has-[kbd]:font-(family-name:--kl-font-mono) has-[kbd]:text-[11px] has-[kbd]:font-medium has-[kbd]:text-inherit\",\n    \"[&_.kl-code]:text-inherit [&_kbd]:[font:inherit]\",\n  ],\n  {\n    variants: {\n      // in a menu title the affix (a count) sits close to the caret\n      caret: { true: \"min-w-0 ps-[calc(var(--kl-inset)-2px)] pe-[6px]\", false: \"\" },\n    },\n    defaultVariants: { caret: false },\n  },\n);\n\n/* signal cells (Button's): done inserts a ✓ cell at the end, failed a ! cell at the start; both unfold (kl-slot) */\nconst signalCell = cn(\n  \"grid h-full w-(--kl-tb-h) place-items-center\",\n  \"forced-colors:bg-[Highlight] forced-colors:text-[HighlightText] forced-colors:forced-color-adjust-none\",\n);\n\n/* ---------------- overflow registration ---------------- */\n\ntype RowData =\n  | { type: \"button\"; label: React.ReactNode; affix: React.ReactNode; disabled: boolean }\n  | { type: \"toggle\"; label: React.ReactNode; affix: React.ReactNode; disabled: boolean; pressed: boolean }\n  | {\n      type: \"link\";\n      label: React.ReactNode;\n      disabled: boolean;\n      href?: string | undefined;\n      target?: string | undefined;\n      rel?: string | undefined;\n      onClick?: React.MouseEventHandler<HTMLAnchorElement> | undefined;\n    }\n  | { type: \"menu\"; label: React.ReactNode; disabled: boolean }\n  | { type: \"group\"; label: string | null }\n  | { type: \"toggle-group\"; label: string | null; multiple: boolean; value: string[]; disabled: boolean }\n  | { type: \"option\"; value: string; label: React.ReactNode; affix: React.ReactNode; disabled: boolean }\n  | { type: \"separator\" };\n\ntype Entry = { el: HTMLElement | null; slot: number; row: RowData };\ntype MenuContentEntry = { anchor: HTMLElement | null; children: React.ReactNode; container: unknown };\n\n/**\n * The toolbar's items, registered by the parts themselves (with the element they render, the top-level child they are\n * in, and what they become as a row of More). The fit reads the DOM; the registry gives each element its row.\n */\nclass Registry {\n  entries = new Map<string, Entry>();\n  contents = new Map<string, MenuContentEntry>();\n  private version = 0;\n  private listeners = new Set<() => void>();\n  /** structure changed: an item came, went, or moved (the fit re-measures) */\n  onStructure: (() => void) | null = null;\n  subscribe = (l: () => void) => {\n    this.listeners.add(l);\n    return () => void this.listeners.delete(l);\n  };\n  getVersion = () => this.version;\n  private emit() {\n    this.version++;\n    this.listeners.forEach((l) => l());\n  }\n  set(id: string, e: Entry) {\n    const prev = this.entries.get(id);\n    this.entries.set(id, e);\n    if (!prev || prev.el !== e.el || prev.slot !== e.slot) this.onStructure?.();\n    if (!prev || !sameRow(prev.row, e.row)) this.emit();\n  }\n  delete(id: string) {\n    if (this.entries.delete(id)) {\n      this.onStructure?.();\n      this.emit();\n    }\n  }\n  setContent(id: string, c: MenuContentEntry) {\n    const prev = this.contents.get(id);\n    this.contents.set(id, c);\n    if (!prev || prev.anchor !== c.anchor || prev.children !== c.children || prev.container !== c.container)\n      this.emit();\n  }\n  deleteContent(id: string) {\n    if (this.contents.delete(id)) this.emit();\n  }\n  byEl(el: Element): [string, Entry] | undefined {\n    for (const kv of this.entries) if (kv[1].el === el) return kv;\n    return undefined;\n  }\n}\n\nconst sameRow = (a: RowData, b: RowData) => {\n  const ka = Object.keys(a) as (keyof RowData)[];\n  if (ka.length !== Object.keys(b).length) return false;\n  return ka.every((k) => {\n    const x = a[k] as unknown;\n    const y = b[k] as unknown;\n    return Array.isArray(x) && Array.isArray(y) ? x.length === y.length && x.every((v, i) => v === y[i]) : x === y;\n  });\n};\n\ntype FoldState = { registry: Registry; folded: ReadonlySet<string> };\n/** Present inside a Toolbar with overflow=\"menu\" (and not inside its More menu). */\nconst FoldCtx = React.createContext<FoldState | null>(null);\n/** The index of the toolbar's top-level child an item renders in: where More goes is a position among them. */\nconst SlotCtx = React.createContext(-1);\n\n/** Registers an item (when its toolbar folds), and says whether it is folded: then it stays mounted, hidden. */\nfunction useFoldItem(row: RowData): { ref: React.RefObject<HTMLElement | null>; hidden: boolean } {\n  const ctx = React.useContext(FoldCtx);\n  const slot = React.useContext(SlotCtx);\n  const id = React.useId();\n  const ref = React.useRef<HTMLElement | null>(null);\n  React.useLayoutEffect(() => {\n    ctx?.registry.set(id, { el: ref.current, slot, row });\n  });\n  const registry = ctx?.registry;\n  React.useLayoutEffect(() => () => registry?.delete(id), [registry, id]);\n  return { ref, hidden: !!ctx?.folded.has(id) };\n}\n\ntype El = React.ReactElement<Record<string, unknown>>;\nconst isEl = (c: unknown): c is El => React.isValidElement(c);\nconst textOf = (n: unknown): string =>\n  typeof n === \"string\" || typeof n === \"number\"\n    ? String(n)\n    : Array.isArray(n)\n      ? n.map(textOf).join(\"\")\n      : isEl(n)\n        ? textOf(n.props[\"children\"])\n        : \"\";\n\n/** The name an item carries into the More menu: overflowLabel, else aria-label (glyph items), else its text. */\nfunction labelOf(p: {\n  overflowLabel?: React.ReactNode;\n  icon?: boolean | undefined;\n  children?: React.ReactNode;\n  \"aria-label\"?: string | undefined;\n}): React.ReactNode {\n  if (p.overflowLabel != null) return p.overflowLabel;\n  if (p.icon || p.children == null || textOf(p.children).trim() === \"\") return p[\"aria-label\"] ?? p.children;\n  return p.children;\n}\n\n/** An affix in the menu: a key (a <kbd>) goes in the shortcut cell; a count or a code follows the label. */\nconst isKey = (a: unknown) =>\n  isEl(a) &&\n  (a.type === \"kbd\" ||\n    React.Children.toArray(a.props[\"children\"] as React.ReactNode).some((c) => isEl(c) && c.type === \"kbd\"));\nfunction withAffix(label: React.ReactNode, affix: unknown): { label: React.ReactNode; shortcut?: React.ReactNode } {\n  if (affix == null || affix === false) return { label };\n  if (isKey(affix)) return { label, shortcut: affix as React.ReactNode };\n  return {\n    label: (\n      <>\n        {label}\n        <span\n          data-slot=\"toolbar-menu-count\"\n          className=\"ms-2 font-(family-name:--kl-font-mono) text-[12px] text-kl-ink-2 tabular-nums group-data-highlighted/menu-item:text-inherit\"\n        >\n          {affix as React.ReactNode}\n        </span>\n      </>\n    ),\n  };\n}\n\n/* ---------------- Toolbar (Root) ---------------- */\n\ntype ToolbarProps = ToolbarPrimitive.Root.Props & {\n  /** control (default): its own 2px frame and the cut. cell: a row of an enclosing frame (a panel's top cell, a shell header). */\n  layout?: Layout;\n  /**\n   * What a toolbar does when its items don't fit. scroll (default): it scrolls inside its frame and fades\n   * the hidden edge. menu: items that don't fit leave, last first, and a \"More\" item takes their place; its\n   * menu holds them as rows (a button is an item, a toggle a checkbox item, an exclusive group radio items,\n   * a menu a submenu), with their state. A ToolbarGroup gives up its items one at a time (they appear under\n   * its label); `keepTogether` makes it leave whole. Horizontal, the toolbar then spans its line; vertical\n   * (a palette), it takes the height its container gives it and More sits at its foot, opening to the side.\n   */\n  overflow?: \"scroll\" | \"menu\";\n  /** Accessible name of the overflow item (\"More\"); its menu says how many items it holds. */\n  overflowLabel?: string;\n  /** icon (default): the overflow item is a square ⋯ cell named by overflowLabel. label: it shows overflowLabel as text with a caret, for a row whose items may all move into it. */\n  overflowTrigger?: \"icon\" | \"label\";\n};\n\n/**\n * A row of commands that is ONE Tab stop (Base UI Toolbar): arrow keys move between items and wrap at the\n * ends (`loopFocus`, default true). Home and End are left to the focused item, as Base UI 1.9 does (the APG\n * lists them as optional for toolbars), so a text input cell keeps them. Every item is a cell of one frame.\n *\n *   ┌──────┬──────┲━━━━┳━━━━┳━━━━┱─────────────────┬──────────┬────┐\n *   │ Undo │ Redo ┃ B  │ I  │ U  ┃                 │ Insert ▾ │ ⋯  │\n *   └──────┴──────┺━━━━┻━━━━┻━━━━┹─────────────────┴──────────┴────┘\n *   items share 1px seams · a group meets its neighbours on a 2px keyline · a spacer is an empty cell\n *\n * - Give it `aria-label` (or `aria-labelledby`): a toolbar is a named landmark of controls.\n * - Groups (ToolbarGroup, ToolbarToggleGroup) are units: their outer edges are control weight (2px), so\n *   a group reads as one control inside the row without a gap (C1). ToolbarSeparator draws the same 2px\n *   keyline between ungrouped items and is announced as a separator.\n * - Disabled items stay focusable (Base UI's default), so a keyboard user still finds them and hears why.\n * - Narrow: a horizontal toolbar scrolls inside its frame and fades the edge where items are hidden\n *   (scroll edges); focus scrolls the focused item into view. With overflow=\"menu\" the items that don't\n *   fit move into a \"More\" menu instead (the primary item and text inputs never move), in either\n *   orientation. Items are found by their data-slot, so an item wrapped in a Tooltip, or rendered by a\n *   component of yours, moves like any other; a folded item stays mounted (hidden), so its state stays.\n * - Arrow keys follow the DOM `dir` (an RTL subtree reverses Left/Right), not only a DirectionProvider.\n */\nfunction Toolbar({\n  className,\n  layout = \"control\",\n  orientation = \"horizontal\",\n  overflow = \"scroll\",\n  overflowLabel = \"More\",\n  overflowTrigger = \"icon\",\n  ref: refProp,\n  children,\n  ...props\n}: ToolbarProps): React.ReactElement {\n  const ref = React.useRef<HTMLDivElement>(null);\n  useScrollEdges(ref);\n  const [dir, refreshDir] = useDomDirection(ref);\n  const setRef = useMergedRef(ref, refProp);\n  const ctx = React.useMemo(() => ({ layout, orientation, inToolbar: true }), [layout, orientation]);\n  const menuMode = overflow === \"menu\";\n  const content = useOverflow(ref, menuMode, orientation === \"vertical\", children, overflowLabel, overflowTrigger);\n  useKeepFocus(ref);\n  return (\n    <ToolbarCtx.Provider value={ctx}>\n      <DirectionProvider direction={dir}>\n        <ToolbarPrimitive.Root\n          ref={setRef}\n          data-kl-layout={layout}\n          data-kl-overflow={menuMode ? \"menu\" : undefined}\n          orientation={orientation}\n          onFocusCapture={refreshDir}\n          // one Tab stop: Firefox makes an overflowing scroller a Tab stop of its own, even around focusable items\n          tabIndex={-1}\n          className={resolveClassName(cn(rootVariants({ layout, orientation, overflow })), className)}\n          {...props}\n          data-slot=\"toolbar\"\n        >\n          {content}\n        </ToolbarPrimitive.Root>\n      </DirectionProvider>\n    </ToolbarCtx.Provider>\n  );\n}\n\n/**\n * Removing the focused item (a filter token's ×, a command that disables itself away) must not drop focus\n * to the page: when the item that had focus leaves the DOM, focus goes to the item now in its place, or\n * the one before it.\n */\nfunction useKeepFocus(ref: React.RefObject<HTMLDivElement | null>) {\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el || typeof MutationObserver === \"undefined\") return;\n    const items = () =>\n      Array.from(el.querySelectorAll<HTMLElement>(\"button, a[href], input\")).filter((x) => !x.closest(\"[hidden]\"));\n    let last: { node: HTMLElement; index: number } | null = null;\n    const onFocus = (e: FocusEvent) => {\n      const t = e.target as HTMLElement;\n      last = { node: t, index: items().indexOf(t) };\n    };\n    const mo = new MutationObserver(() => {\n      if (!last || last.node.isConnected) return;\n      const a = document.activeElement;\n      if (a && a !== document.body && a !== document.documentElement) return;\n      const list = items();\n      const next = list[Math.min(last.index, list.length - 1)];\n      last = null;\n      next?.focus();\n    });\n    el.addEventListener(\"focusin\", onFocus);\n    mo.observe(el, { childList: true, subtree: true });\n    return () => {\n      el.removeEventListener(\"focusin\", onFocus);\n      mo.disconnect();\n    };\n  }, [ref]);\n}\n\n/* ---------------- overflow (\"More\") ---------------- */\n\ntype Placed = { folded: ReadonlySet<string>; more: { slot: number; after: boolean } | null; count: number };\nconst NONE: Placed = { folded: new Set(), more: null, count: 0 };\n\n/** The row's elements the fit works with: in flow (not the edge fades or Base UI's focus guards), not More. */\nconst inFlow = (c: Element): c is HTMLElement => {\n  if (!(c instanceof HTMLElement)) return false;\n  const pos = getComputedStyle(c).position;\n  return pos !== \"fixed\" && pos !== \"absolute\";\n};\n\n/**\n * Fits a toolbar's items to its size along its axis: folds units from the end while the row overflows, and brings\n * the next one back when the free space (empty fill, slack in the spacer and input cells) holds its last measured\n * size. The arithmetic and the rules are lib/toolbar-overflow; this measures and renders. Runs in layout effects,\n * so nothing paints in between.\n */\nfunction useOverflow(\n  ref: React.RefObject<HTMLDivElement | null>,\n  on: boolean,\n  vertical: boolean,\n  children: React.ReactNode,\n  label: string,\n  trigger: \"icon\" | \"label\",\n): React.ReactNode {\n  // the axis the items run along: width in a row, height in a column (a tool palette)\n  const size = (e: Element) => (vertical ? e.getBoundingClientRect().height : e.getBoundingClientRect().width);\n  const inner = (e: HTMLElement) => (vertical ? e.clientHeight : e.clientWidth);\n  const outer = (e: HTMLElement) => (vertical ? e.offsetHeight : e.offsetWidth);\n  const minOf = (cs: CSSStyleDeclaration) => parseFloat(vertical ? cs.minHeight : cs.minWidth) || 0;\n  const [registry] = React.useState(() => new Registry());\n  const [placed, setPlaced] = React.useState<Placed>(NONE);\n  const widths = React.useRef(new Map<Element, number>());\n  const blocked = React.useRef<Blocked | null>(null);\n  const refocus = React.useRef(false);\n  const moreRef = React.useRef<HTMLButtonElement>(null);\n  const [, remeasure] = React.useReducer((x: number) => x + 1, 0);\n  const foldState = React.useMemo<FoldState>(() => ({ registry, folded: placed.folded }), [registry, placed.folded]);\n\n  // Measures after every render on purpose: items, fonts and the parent can all change the fit without a prop\n  // changing. Each pass moves the folded count one step toward the fit and `blocked` stops a step that would\n  // undo the last, so the passes settle.\n  // oxlint-disable-next-line react-hooks/exhaustive-deps -- re-measures each render; see above\n  React.useLayoutEffect(() => {\n    if (!on) return;\n    const el = ref.current;\n    if (!el) return;\n    // the row as the lib sees it: each element classified by its data-slot (registered items only: an element\n    // that no part registered has no row to become, so it stays)\n    const registered = (c: Element) => !!registry.byEl(c);\n    const kindIn = (c: Element) => (registered(c) ? kindOf(c) : \"keep\");\n    const kids = Array.from(el.children).filter(inFlow);\n    const items: RowItem<HTMLElement>[] = kids\n      .filter((c) => c !== moreRef.current)\n      .map((c) => {\n        const kind = kindIn(c);\n        if (kind !== \"unit\" || !isGroup(c)) return { el: c, kind, members: null };\n        const members = Array.from(c.children).filter(\n          (m): m is HTMLElement =>\n            inFlow(m) && !m.hasAttribute(\"data-kl-band\") && !m.hasAttribute(\"data-kl-scope\") && registered(m),\n        );\n        const all = Array.from(c.children).filter(\n          (m) => inFlow(m) && !m.hasAttribute(\"data-kl-band\") && !m.hasAttribute(\"data-kl-scope\"),\n        );\n        return { el: c, kind, members: members.length === all.length && splits(c, members) ? members : null };\n      });\n    const place = (count: number): Placed => {\n      const f = fold(items, count);\n      const ids = new Set<string>();\n      f.folded.forEach((e) => {\n        const hit = registry.byEl(e);\n        if (hit) ids.add(hit[0]);\n      });\n      let more: Placed[\"more\"] = null;\n      if (f.more) {\n        const at = \"before\" in f.more ? f.more.before : f.more.after;\n        const slot = registry.byEl(at)?.[1].slot ?? -1;\n        more = slot < 0 ? null : { slot, after: \"after\" in f.more };\n      }\n      return { folded: ids, more, count: Math.min(count, f.units.length) };\n    };\n    const samePlace = (a: Placed, b: Placed) =>\n      a.count === b.count &&\n      a.folded.size === b.folded.size &&\n      [...a.folded].every((x) => b.folded.has(x)) &&\n      a.more?.slot === b.more?.slot &&\n      a.more?.after === b.more?.after;\n    // the rendered row must be the fold of the current count (an item came or went since): render that first\n    const now = place(placed.count);\n    if (!samePlace(now, placed)) {\n      setPlaced(now);\n      return;\n    }\n    const f = fold(items, placed.count);\n    const units = f.units;\n    const count = now.count;\n    // remember each unit's size while it is in the row\n    for (const u of units) if (!f.folded.has(u) && !u.hidden) widths.current.set(u, size(u));\n    // the size the row asks for with every item in it: its flex basis, so a toolbar sized by its content (in a flex\n    // row) shrinks under pressure, and grows back, instead of fitting its current items forever\n    let full = outer(el) - inner(el) + 2;\n    for (const k of kids) {\n      if (k === moreRef.current || k.hidden) continue;\n      const cs = getComputedStyle(k);\n      const flexible = parseFloat(cs.flexGrow) > 0 || parseFloat(cs.flexShrink) > 0;\n      full += flexible ? minOf(cs) : size(k);\n    }\n    units.slice(units.length - count).forEach((u) => (full += widths.current.get(u) ?? 0));\n    // only a parent laid out along the same axis sizes it by its basis (a row for a row, a column for a palette)\n    const ps = el.parentElement ? getComputedStyle(el.parentElement) : null;\n    const inRow = !!ps && ps.display.includes(\"flex\") && ps.flexDirection.startsWith(\"column\") === vertical;\n    const basis = inRow ? `${Math.ceil(full)}px` : \"\";\n    if (el.style.flexBasis !== basis) el.style.flexBasis = basis;\n    // fractional sizes on both sides (lib: overflows): the content box from the rect, less the integer borders\n    const available = size(el) - (outer(el) - inner(el));\n    // overflow is the items' own extent (the scroll size also counts the edge-fade overlays)\n    const extent = kids.reduce((sum, k) => sum + size(k), 0);\n    let used = 0;\n    let slack = 0;\n    for (const k of kids) {\n      const r = size(k);\n      used += r;\n      const cs = getComputedStyle(k);\n      if (parseFloat(cs.flexGrow) > 0 || parseFloat(cs.flexShrink) > 0) slack += Math.max(0, r - minOf(cs));\n    }\n    const next = units[units.length - count];\n    // the first item back into a group that had left whole brings the group's own 2px edges with it\n    const group = next?.parentElement;\n    const edges = next && group && group !== el && f.folded.has(group) ? 4 : 0;\n    const need =\n      next === undefined\n        ? Infinity\n        : (widths.current.get(next) ?? Infinity) + edges - (count === 1 && moreRef.current ? size(moreRef.current) : 0);\n    const step = fitStep({\n      count,\n      total: units.length,\n      available,\n      extent,\n      free: available - used + slack,\n      need,\n      blocked: blocked.current,\n    });\n    blocked.current = step.blocked;\n    if (step.count !== count) {\n      if (step.count > count && el.contains(document.activeElement) && document.activeElement !== moreRef.current)\n        refocus.current = true;\n      setPlaced(place(step.count));\n      return;\n    }\n    if (refocus.current) {\n      refocus.current = false;\n      const a = document.activeElement as HTMLElement | null;\n      if (!a || !el.contains(a) || a.closest(\"[hidden]\")) moreRef.current?.focus({ preventScroll: true });\n    }\n  });\n\n  React.useLayoutEffect(() => {\n    const el = ref.current;\n    if (!on || !el || typeof ResizeObserver === \"undefined\") return;\n    const inner = (e: HTMLElement) => (vertical ? e.clientHeight : e.clientWidth);\n    let last = inner(el);\n    let raf = 0;\n    const refit = () => {\n      blocked.current = null;\n      cancelAnimationFrame(raf);\n      raf = requestAnimationFrame(() => flushSync(remeasure));\n    };\n    // the fit runs in the next frame, not inside the observer's callback: fitting changes the toolbar's own\n    // size (its flex basis), which inside the callback is a ResizeObserver loop error (seen in WebKit)\n    const ro = new ResizeObserver(() => {\n      if (inner(el) === last) return;\n      last = inner(el);\n      refit();\n    });\n    ro.observe(el);\n    // a web font arriving changes every item's width while the toolbar, held at its old basis, may keep its\n    // size: the basis measured with the fallback font would stay (a stray filler, or items left in More)\n    const fonts = typeof document !== \"undefined\" ? document.fonts : undefined;\n    fonts?.addEventListener(\"loadingdone\", refit);\n    // an item added, removed or moved (a filter token appearing) changes the fit without a toolbar render\n    registry.onStructure = () => {\n      cancelAnimationFrame(raf);\n      raf = requestAnimationFrame(() => flushSync(remeasure));\n    };\n    return () => {\n      ro.disconnect();\n      fonts?.removeEventListener(\"loadingdone\", refit);\n      cancelAnimationFrame(raf);\n      registry.onStructure = null;\n    };\n  }, [on, ref, vertical, registry]);\n\n  if (!on) return children;\n\n  const more = (\n    <FoldCtx.Provider value={null} key=\"kl-tb-more\">\n      <Menu>\n        <MenuTitle\n          ref={moreRef}\n          icon={trigger === \"icon\"}\n          aria-label={trigger === \"icon\" ? label : undefined}\n          data-kl-count={placed.count}\n          data-slot=\"toolbar-more\"\n          caret={trigger === \"label\"}\n        >\n          {trigger === \"label\" ? (\n            label\n          ) : (\n            <svg viewBox=\"0 0 16 16\" width=\"16\" height=\"16\" fill=\"currentColor\" aria-hidden>\n              <rect x=\"2\" y=\"7\" width=\"2.5\" height=\"2.5\" />\n              <rect x=\"6.75\" y=\"7\" width=\"2.5\" height=\"2.5\" />\n              <rect x=\"11.5\" y=\"7\" width=\"2.5\" height=\"2.5\" />\n            </svg>\n          )}\n        </MenuTitle>\n        <ToolbarMenuContent\n          align=\"end\"\n          aria-label={`${label}: ${placed.count} ${placed.count === 1 ? \"item\" : \"items\"}`}\n        >\n          <OverflowRows registry={registry} folded={placed.folded} />\n        </ToolbarMenuContent>\n      </Menu>\n    </FoldCtx.Provider>\n  );\n  const out: React.ReactNode[] = [];\n  React.Children.toArray(children).forEach((c, i) => {\n    const at = placed.more && placed.count > 0 && placed.more.slot === i ? placed.more : null;\n    if (at && !at.after) out.push(more);\n    out.push(\n      <SlotCtx.Provider key={isEl(c) && c.key != null ? c.key : i} value={i}>\n        {c}\n      </SlotCtx.Provider>,\n    );\n    if (at && at.after) out.push(more);\n  });\n  return <FoldCtx.Provider value={foldState}>{out}</FoldCtx.Provider>;\n}\n\n/** The More menu's rows: the folded items, in the row's order, with their current state (from the registry). */\nfunction OverflowRows({ registry, folded }: { registry: Registry; folded: ReadonlySet<string> }) {\n  React.useSyncExternalStore(registry.subscribe, registry.getVersion, registry.getVersion);\n  const all = [...registry.entries].filter(([, e]) => e.el?.isConnected);\n  const order = (a: [string, Entry], b: [string, Entry]) =>\n    a[1].el!.compareDocumentPosition(b[1].el!) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;\n  all.sort(order);\n  const within = (g: HTMLElement) => all.filter(([, e]) => e.el !== g && e.el!.parentElement === g);\n  // a folded menu's content: the ToolbarMenuContent whose scope marker follows its trigger (they share a Menu root)\n  const contentOf = (trigger: HTMLElement) => {\n    let best: MenuContentEntry | null = null;\n    for (const c of registry.contents.values()) {\n      if (!c.anchor || !(trigger.compareDocumentPosition(c.anchor) & Node.DOCUMENT_POSITION_FOLLOWING)) continue;\n      const between = all.some(\n        ([, e]) =>\n          e.row.type === \"menu\" &&\n          e.el !== trigger &&\n          trigger.compareDocumentPosition(e.el!) & Node.DOCUMENT_POSITION_FOLLOWING &&\n          c.anchor!.compareDocumentPosition(e.el!) & Node.DOCUMENT_POSITION_PRECEDING,\n      );\n      if (between) continue;\n      if (!best || c.anchor.compareDocumentPosition(best.anchor!) & Node.DOCUMENT_POSITION_FOLLOWING) best = c;\n    }\n    return best;\n  };\n  const click = (el: HTMLElement | null) => () => el?.click();\n\n  const rowOf = (id: string, e: Entry, only?: Set<string>): React.ReactNode => {\n    const r = e.row;\n    switch (r.type) {\n      case \"button\": {\n        const a = withAffix(r.label, r.affix);\n        return (\n          <MenuItem key={id} disabled={r.disabled} onClick={click(e.el)} shortcut={a.shortcut}>\n            {a.label}\n          </MenuItem>\n        );\n      }\n      case \"link\":\n        return (\n          <MenuItem\n            key={id}\n            disabled={r.disabled}\n            render={<a href={r.href} target={r.target} rel={r.rel} />}\n            onClick={r.onClick as never}\n          >\n            {r.label}\n          </MenuItem>\n        );\n      case \"toggle\": {\n        const a = withAffix(r.label, r.affix);\n        return (\n          <MenuCheckboxItem\n            key={id}\n            disabled={r.disabled}\n            checked={r.pressed}\n            onCheckedChange={click(e.el)}\n            shortcut={a.shortcut}\n          >\n            {a.label}\n          </MenuCheckboxItem>\n        );\n      }\n      case \"toggle-group\": {\n        const opts = within(e.el!).filter(([, o]) => o.row.type === \"option\");\n        const opt = (o: Entry) => o.row as Extract<RowData, { type: \"option\" }>;\n        return (\n          <MenuGroup key={id}>\n            {r.label ? <MenuGroupLabel>{r.label}</MenuGroupLabel> : null}\n            {!r.multiple ? (\n              <MenuRadioGroup\n                value={r.value[0] ?? null}\n                onValueChange={(v) => opts.find(([, o]) => opt(o).value === v)?.[1].el?.click()}\n                disabled={r.disabled}\n              >\n                {opts.map(([oid, o]) => {\n                  const a = withAffix(opt(o).label, opt(o).affix);\n                  return (\n                    <MenuRadioItem key={oid} value={opt(o).value} disabled={opt(o).disabled} shortcut={a.shortcut}>\n                      {a.label}\n                    </MenuRadioItem>\n                  );\n                })}\n              </MenuRadioGroup>\n            ) : (\n              opts.map(([oid, o]) => {\n                const a = withAffix(opt(o).label, opt(o).affix);\n                return (\n                  <MenuCheckboxItem\n                    key={oid}\n                    disabled={r.disabled || opt(o).disabled}\n                    checked={r.value.includes(opt(o).value)}\n                    onCheckedChange={click(o.el)}\n                    shortcut={a.shortcut}\n                  >\n                    {a.label}\n                  </MenuCheckboxItem>\n                );\n              })\n            )}\n          </MenuGroup>\n        );\n      }\n      case \"group\":\n        return (\n          <MenuGroup key={id}>\n            {r.label ? <MenuGroupLabel>{r.label}</MenuGroupLabel> : null}\n            {within(e.el!)\n              .filter(([mid]) => !only || only.has(mid))\n              .map(([mid, m]) => rowOf(mid, m))}\n          </MenuGroup>\n        );\n      case \"menu\": {\n        const content = contentOf(e.el!);\n        if (!content) return null;\n        return (\n          <MenuSubmenuRoot key={id}>\n            <MenuSubmenuTrigger disabled={r.disabled}>{r.label}</MenuSubmenuTrigger>\n            <MenuPopup container={content.container as never}>{content.children}</MenuPopup>\n          </MenuSubmenuRoot>\n        );\n      }\n      default:\n        return null;\n    }\n  };\n\n  // the row's top-level folded items (and a group folded in part, with only its folded items), in order\n  const rows: React.ReactNode[] = [];\n  let prevGroup = false;\n  for (const [id, e] of all) {\n    const top = e.el!.parentElement?.getAttribute(\"data-slot\") === \"toolbar\";\n    if (!top || e.row.type === \"separator\") continue;\n    const groupish = e.row.type === \"group\" || e.row.type === \"toggle-group\";\n    let only: Set<string> | undefined;\n    if (!folded.has(id)) {\n      if (e.row.type !== \"group\") continue;\n      only = new Set(within(e.el!).flatMap(([mid]) => (folded.has(mid) ? [mid] : [])));\n      if (!only.size) continue;\n    }\n    if (rows.length && (groupish || prevGroup)) rows.push(<MenuSeparator key={`s${id}`} />);\n    rows.push(rowOf(id, e, only));\n    prevGroup = groupish;\n  }\n  return <>{rows}</>;\n}\n\n/* ---------------- items ---------------- */\n\n/* The signal slots exist only on an item that takes a signal (so they can unfold); others carry just the label. */\nfunction ItemLabel({\n  affix,\n  signal,\n  icon,\n  caret,\n  link,\n  children,\n}: {\n  affix?: React.ReactNode;\n  signal?: Signal | undefined;\n  icon?: boolean | undefined;\n  caret?: boolean;\n  link?: boolean;\n  children?: React.ReactNode;\n}) {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const label = (\n    <span\n      data-slot=\"toolbar-label\"\n      className={cn(\n        labelVariants({ orientation, icon: !!icon, caret: !!caret && affix == null && signal == null, link: !!link }),\n      )}\n    >\n      {children}\n    </span>\n  );\n  const affixCell =\n    affix != null ? (\n      <span data-slot=\"toolbar-affix\" className={cn(affixVariants({ caret: !!caret && signal !== \"pending\" }))}>\n        {affix}\n      </span>\n    ) : null;\n  if (signal == null) {\n    return (\n      <>\n        {label}\n        {affixCell}\n      </>\n    );\n  }\n  return (\n    <>\n      <span className=\"kl-slot\" data-open={signal === \"failed\" ? \"\" : undefined} data-slot=\"toolbar-fail\" aria-hidden>\n        <span className=\"flex h-full\">\n          <span\n            className={cn(\n              signalCell,\n              \"border-e-(length:--kl-k1) border-e-kl-seam bg-kl-red text-[15px] font-(--kl-weight-display) text-kl-on-red\",\n            )}\n          >\n            !\n          </span>\n        </span>\n      </span>\n      {label}\n      {affixCell}\n      <span className=\"kl-slot\" data-open={signal === \"done\" ? \"\" : undefined} data-slot=\"toolbar-done\" aria-hidden>\n        <span className=\"flex h-full\">\n          <span\n            className={cn(\n              signalCell,\n              \"border-s-(length:--kl-k1) border-s-current bg-kl-yellow text-kl-on-yellow\",\n              \"group-data-kl-primary/toolbar-item:border-s-kl-on-cobalt\",\n            )}\n          >\n            <svg\n              className=\"kl-tick\"\n              viewBox=\"0 0 16 16\"\n              width=\"14\"\n              height=\"14\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth=\"2.25\"\n              strokeLinecap=\"square\"\n            >\n              <path pathLength={1} d=\"m3.5 8.5 3 3 6-7\" />\n            </svg>\n          </span>\n        </span>\n      </span>\n      {signal === \"pending\" ? <span className=\"kl-pending bottom-0 [--kl-bw:3px]\" aria-hidden /> : null}\n    </>\n  );\n}\n\ntype ToolbarButtonProps = ToolbarPrimitive.Button.Props & {\n  /** A trailing cell inside the item: a count or a shortcut (mono when it is a <kbd> or a code). */\n  affix?: React.ReactNode;\n  /** Square cell for a glyph-only item. Give it aria-label; pair with a Tooltip for sighted users. */\n  icon?: boolean;\n  /** The one primary action of the row: the cobalt cell (commit signal). At most one per toolbar. It never moves into the overflow menu. */\n  primary?: boolean;\n  /** Button's signal: pending runs a segment along the bottom keyline (busy, still focusable); done inserts a ✓ cell; failed a ! cell at the start. */\n  signal?: Signal;\n  /** The item's name as a row of the overflow menu, when its text is not enough (a glyph item uses aria-label). */\n  overflowLabel?: React.ReactNode;\n};\n\n/** A command cell (Base UI Toolbar.Button). Contents travel 1px on press (Key); the cell never floods: an action holds no state. */\nfunction ToolbarButton({\n  className,\n  affix,\n  icon,\n  primary,\n  signal,\n  overflowLabel,\n  disabled,\n  hidden,\n  children,\n  ref: refProp,\n  ...props\n}: ToolbarButtonProps): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const pending = signal === \"pending\";\n  const fold = useFoldItem({\n    type: \"button\",\n    label: labelOf({ overflowLabel, icon, children, \"aria-label\": props[\"aria-label\"] }),\n    affix,\n    disabled: !!disabled || pending,\n  });\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLButtonElement | null>, refProp);\n  return (\n    <ToolbarPrimitive.Button\n      ref={setRef}\n      data-kl-tb-item=\"\"\n      data-kl-icon={icon ? \"\" : undefined}\n      data-kl-primary={primary ? \"\" : undefined}\n      data-signal={signal == null || signal === \"idle\" ? undefined : signal}\n      aria-busy={pending || undefined}\n      disabled={disabled || pending}\n      hidden={fold.hidden || hidden}\n      className={resolveClassName(\n        cn(\"kl-key\", itemVariants({ orientation, icon: !!icon, primary: !!primary })),\n        className,\n      )}\n      {...props}\n      data-slot=\"toolbar-button\"\n    >\n      <ItemLabel affix={affix} signal={signal} icon={icon}>\n        {children}\n      </ItemLabel>\n    </ToolbarPrimitive.Button>\n  );\n}\n\n/** In a toggle group: whether it is exclusive (a choice the band covers) or multiple (independent toggles). */\nconst ToggleGroupCtx = React.createContext<{ exclusive: boolean } | null>(null);\n\ntype ToolbarToggleProps = Toggle.Props & {\n  icon?: boolean;\n  affix?: React.ReactNode;\n  disabled?: boolean;\n  /** The toggle's name as a checkbox row of the overflow menu, when its text is not enough. */\n  overflowLabel?: React.ReactNode;\n};\n\n/**\n * A toggle cell: Base UI Toggle rendered as a toolbar item, so it joins the row's arrow-key order.\n * On its own or in a multiple ToolbarToggleGroup it is independent state: it floods yellow from the press\n * point and carries a lamp (as ToggleGroup's cells do). In an exclusive group (multiple={false}) it is a\n * choice among options: no lamp, and the group's ink band stretches to it (as Segmented's does).\n */\nfunction ToolbarToggle({\n  className,\n  icon,\n  affix,\n  children,\n  disabled,\n  overflowLabel,\n  pressed: pressedProp,\n  defaultPressed,\n  onPressedChange,\n  hidden,\n  render,\n  ref: refProp,\n  ...props\n}: ToolbarToggleProps): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const group = React.useContext(ToggleGroupCtx);\n  const exclusive = !!group?.exclusive;\n  // on its own, its state is kept here (controlled or not), so the overflow menu's checkbox row can show it\n  const [own, setOwn] = React.useState(!!defaultPressed);\n  const pressed = pressedProp ?? own;\n  const label = labelOf({ overflowLabel, icon, children, \"aria-label\": props[\"aria-label\"] });\n  const fold = useFoldItem(\n    group\n      ? { type: \"option\", value: String(props.value ?? \"\"), label, affix, disabled: !!disabled }\n      : { type: \"toggle\", label, affix, disabled: !!disabled, pressed },\n  );\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLButtonElement | null>, refProp);\n  const own_ = group\n    ? {}\n    : {\n        pressed,\n        onPressedChange: (v: boolean, d: Toggle.ChangeEventDetails) => {\n          setOwn(v);\n          onPressedChange?.(v, d);\n        },\n      };\n  return (\n    <ToolbarPrimitive.Button\n      disabled={disabled}\n      render={\n        <Toggle\n          ref={setRef}\n          render={render}\n          data-kl-tb-item=\"\"\n          data-kl-icon={icon ? \"\" : undefined}\n          data-kl-item={exclusive ? \"\" : undefined}\n          hidden={fold.hidden || hidden}\n          className={resolveClassName(\n            cn(\"kl-key\", itemVariants({ orientation, icon: !!icon }), exclusive ? choiceToggle : floodToggle),\n            className,\n          )}\n          {...(exclusive ? null : floodHandlers)}\n          {...(group ? { onPressedChange } : null)}\n          {...own_}\n          {...props}\n          data-slot=\"toolbar-toggle\"\n        />\n      }\n    >\n      {exclusive ? (\n        <ItemLabel affix={affix} icon={icon}>\n          {children}\n        </ItemLabel>\n      ) : (\n        <ItemLabel affix={affix} icon={icon}>\n          {icon ? null : (\n            <span\n              className=\"kl-lamp group-data-pressed/toolbar-item:border-[5px]\"\n              data-slot=\"toolbar-lamp\"\n              aria-hidden\n            />\n          )}\n          {children}\n        </ItemLabel>\n      )}\n    </ToolbarPrimitive.Button>\n  );\n}\n\ntype ToolbarToggleGroupProps = Omit<ToggleGroupPrimitive.Props, \"value\" | \"defaultValue\" | \"onValueChange\"> & {\n  value?: string[];\n  defaultValue?: string[];\n  onValueChange?: (value: string[], eventDetails: ToggleGroupPrimitive.ChangeEventDetails) => void;\n};\n\n/**\n * Toggles that belong together (Base UI ToggleGroup inside the toolbar's focus order). `multiple` (default\n * true): independent toggles, each floods. multiple={false}: an exclusive choice (alignment, view), the ink\n * band stretches between cells, leading edge first, zero bounce.\n */\nfunction ToolbarToggleGroup({\n  className,\n  multiple = true,\n  value,\n  defaultValue,\n  onValueChange,\n  children,\n  disabled,\n  hidden,\n  ref: refProp,\n  ...props\n}: ToolbarToggleGroupProps): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const ref = React.useRef<HTMLDivElement>(null);\n  const [inner, setInner] = React.useState<string[]>(defaultValue ?? []);\n  const current = value ?? inner;\n  const fold = useFoldItem({\n    type: \"toggle-group\",\n    label: props[\"aria-label\"] ?? null,\n    multiple,\n    value: current,\n    disabled: !!disabled,\n  });\n  const setRef = useMergedRef(ref, refProp);\n  const setBoth = React.useCallback(\n    (n: HTMLDivElement | null) => {\n      setRef(n);\n      fold.ref.current = n;\n    },\n    [setRef, fold.ref],\n  );\n  const values = React.Children.toArray(children)\n    .filter(React.isValidElement)\n    .map((c) => (c.props as { value?: string }).value);\n  useStretch(ref, multiple ? -1 : values.indexOf(current[0]), { axis: orientation === \"vertical\" ? \"y\" : \"x\" });\n  const groupCtx = React.useMemo(() => ({ exclusive: !multiple }), [multiple]);\n  return (\n    <ToggleGroupCtx.Provider value={groupCtx}>\n      <ToggleGroupPrimitive\n        ref={setBoth}\n        data-kl-stretch={multiple ? undefined : \"\"}\n        multiple={multiple}\n        value={current}\n        disabled={disabled}\n        hidden={fold.hidden || hidden}\n        onValueChange={(v, d) => {\n          setInner(v as string[]);\n          onValueChange?.(v as string[], d);\n        }}\n        className={resolveClassName(cn(groupVariants({ orientation }), !multiple && \"relative isolate\"), className)}\n        {...props}\n        data-slot=\"toolbar-toggle-group\"\n      >\n        {multiple ? null : (\n          <span\n            data-kl-band=\"\"\n            data-slot=\"toolbar-band\"\n            className=\"pointer-events-none absolute -z-1 bg-kl-inverse forced-colors:bg-[Highlight] forced-colors:forced-color-adjust-none\"\n            aria-hidden\n            hidden\n          />\n        )}\n        {children}\n      </ToggleGroupPrimitive>\n    </ToggleGroupCtx.Provider>\n  );\n}\n\n/* A group: one control in the row (its outer edges are the row's 2px seams); its items share 1px seams. */\nconst groupVariants = cva(\"flex min-w-0 flex-none items-stretch\", {\n  variants: {\n    orientation: {\n      horizontal: \"[&>:not([data-kl-band])+*]:border-s-(length:--kl-k1) [&>:not([data-kl-band])+*]:border-s-kl-seam\",\n      vertical:\n        \"flex-col [&>:not([data-kl-band])+*]:border-t-(length:--kl-k1) [&>:not([data-kl-band])+*]:border-t-kl-seam\",\n    },\n  },\n  defaultVariants: { orientation: \"horizontal\" },\n});\n\n/**\n * Items that belong together, drawn as one control (2px outer edges). With overflow=\"menu\" its items move\n * into More one at a time, from the end, and appear there under the group's label; `keepTogether` moves\n * the group only as a whole (an alignment set, a pair that means nothing apart).\n */\nfunction ToolbarGroup({\n  className,\n  keepTogether,\n  hidden,\n  ref: refProp,\n  ...props\n}: ToolbarPrimitive.Group.Props & { keepTogether?: boolean }): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const fold = useFoldItem({ type: \"group\", label: props[\"aria-label\"] ?? null });\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLDivElement | null>, refProp);\n  return (\n    <ToolbarPrimitive.Group\n      ref={setRef}\n      data-kl-keep-together={keepTogether ? \"\" : undefined}\n      hidden={fold.hidden || hidden}\n      className={resolveClassName(cn(groupVariants({ orientation })), className)}\n      {...props}\n      data-slot=\"toolbar-group\"\n    />\n  );\n}\n\n/** A 2px keyline between items, announced as a separator. Not needed between groups (they draw their own). */\nfunction ToolbarSeparator({\n  className,\n  hidden,\n  ref: refProp,\n  ...props\n}: ToolbarPrimitive.Separator.Props): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const fold = useFoldItem({ type: \"separator\" });\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLDivElement | null>, refProp);\n  return (\n    <ToolbarPrimitive.Separator\n      ref={setRef}\n      orientation={orientation === \"vertical\" ? \"horizontal\" : \"vertical\"}\n      hidden={fold.hidden || hidden}\n      className={resolveClassName(\n        orientation === \"vertical\"\n          ? \"h-0 flex-none self-stretch border-t-(length:--kl-k2) border-t-kl-line\"\n          : \"w-0 flex-none self-stretch border-s-(length:--kl-k2) border-s-kl-line\",\n        className,\n      )}\n      {...props}\n      data-slot=\"toolbar-separator\"\n    />\n  );\n}\n\n/** An empty cell that takes the free space, pushing what follows to the end. Not focusable, not announced. */\nfunction ToolbarSpacer({ render, className, style, ...props }: PartProps<\"div\", Record<string, never>>) {\n  const state = {};\n  return useRender({\n    defaultTagName: \"div\",\n    render,\n    state,\n    props: mergeProps<\"div\">(\n      { \"aria-hidden\": true, className: resolveClassName(\"min-w-(--kl-gutter) flex-[1_1_0]\", className)(state) },\n      { style: resolveStyle(undefined, style)(state) },\n      props,\n      { \"data-slot\": \"toolbar-spacer\" } as React.ComponentProps<\"div\">,\n    ),\n  });\n}\n\n/** A link cell (Base UI Toolbar.Link): navigation, not a command. Underlined like a quiet button. */\nfunction ToolbarLink({\n  className,\n  children,\n  overflowLabel,\n  hidden,\n  ref: refProp,\n  ...props\n}: ToolbarPrimitive.Link.Props & { overflowLabel?: React.ReactNode }): React.ReactElement {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const fold = useFoldItem({\n    type: \"link\",\n    label: labelOf({ overflowLabel, children, \"aria-label\": props[\"aria-label\"] }),\n    disabled: false,\n    href: props.href,\n    target: props.target,\n    rel: props.rel,\n    onClick: props.onClick as React.MouseEventHandler<HTMLAnchorElement> | undefined,\n  });\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLAnchorElement | null>, refProp);\n  return (\n    <ToolbarPrimitive.Link\n      ref={setRef}\n      data-kl-tb-item=\"\"\n      hidden={fold.hidden || hidden}\n      className={resolveClassName(cn(itemVariants({ orientation })), className)}\n      {...props}\n      data-slot=\"toolbar-link\"\n    >\n      <ItemLabel link>{children}</ItemLabel>\n    </ToolbarPrimitive.Link>\n  );\n}\n\ntype ToolbarInputProps = ToolbarPrimitive.Input.Props & {\n  /** Names the input for assistive technology. */\n  label: string;\n  /** A glyph leading the cell. */\n  glyph?: React.ReactNode;\n  /** Classes for the cell (the label element that holds the glyph and the input). `className`, `style` and `render`\n   * are the input's (Base UI Toolbar.Input), as for every part. */\n  cellClassName?: string;\n};\n\n/**\n * A text input cell (Base UI Toolbar.Input). Arrow keys move the caret; they leave the input for the\n * neighbouring item only at the text's ends. Its edge is the cell's (`kl-edge`, a 2px band on the\n * keylines), as the table search's is. `label` names it for assistive technology; `glyph` leads it.\n */\nfunction ToolbarInput({ className, cellClassName, label, glyph, ...props }: ToolbarInputProps) {\n  return (\n    <label\n      data-slot=\"toolbar-input-cell\"\n      className={cn(\n        \"kl-cell kl-edge min-h-0 min-w-32 flex-[1_1_12rem] text-kl-ink-2\",\n        \"has-[input:disabled]:bg-(image:--kl-hatch) has-[input:disabled]:text-kl-dis\",\n        cellClassName,\n      )}\n    >\n      {glyph ?? null}\n      <span className=\"kl-sr\">{label}</span>\n      <ToolbarPrimitive.Input\n        className={resolveClassName(\n          cn(\n            \"m-0 min-w-0 flex-1 self-stretch border-0 bg-transparent p-0 text-kl-ink [outline:0]\",\n            \"font-(family-name:--kl-font) text-[14px] placeholder:text-kl-ink-3\",\n          ),\n          className,\n        )}\n        {...props}\n        data-slot=\"toolbar-input\"\n      />\n    </label>\n  );\n}\n\ntype MenuTitleProps = MenuPrimitive.Trigger.Props & {\n  icon?: boolean;\n  affix?: React.ReactNode;\n  primary?: boolean;\n  signal?: Signal;\n  caret?: boolean;\n  \"data-slot\"?: string;\n};\n\n/* A menu title in the row (ToolbarMenuTrigger, and the More item): Base UI Menu.Trigger as a toolbar item. */\nfunction MenuTitle({\n  className,\n  children,\n  icon,\n  disabled,\n  affix,\n  primary,\n  signal,\n  caret = !icon,\n  \"data-slot\": slot = \"toolbar-menu-trigger\",\n  render,\n  ...props\n}: MenuTitleProps) {\n  const { orientation } = React.useContext(ToolbarCtx);\n  const pending = signal === \"pending\";\n  return (\n    <ToolbarPrimitive.Button\n      disabled={disabled || pending}\n      render={\n        <MenuPrimitive.Trigger\n          render={render}\n          data-kl-tb-item=\"\"\n          data-kl-icon={icon ? \"\" : undefined}\n          data-kl-primary={primary ? \"\" : undefined}\n          data-signal={signal == null || signal === \"idle\" ? undefined : signal}\n          aria-busy={pending || undefined}\n          className={resolveClassName(\n            cn(\"kl-key\", itemVariants({ orientation, icon: !!icon, primary: !!primary })),\n            className,\n          )}\n          {...props}\n          data-slot={slot}\n        />\n      }\n    >\n      <ItemLabel affix={affix} signal={signal} icon={icon} caret={caret}>\n        {children}\n      </ItemLabel>\n      {caret ? (\n        <span data-slot=\"toolbar-caret\" className=\"flex items-center pe-[calc(var(--kl-inset)-2px)]\" aria-hidden>\n          <svg\n            viewBox=\"0 0 16 16\"\n            width=\"12\"\n            height=\"12\"\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinecap=\"square\"\n          >\n            <path d=\"m4 6 4 4 4-4\" />\n          </svg>\n        </span>\n      ) : null}\n    </ToolbarPrimitive.Button>\n  );\n}\n\n/**\n * A menu title in the row: Base UI Menu.Trigger rendered as a toolbar item, with a caret cell. Open, it is\n * the inverse cell; its menu docks to the toolbar's keyline under it (ToolbarMenuContent).\n * The toolbar's own Menu root is Base UI's: <ToolbarMenu><ToolbarMenuTrigger>…</ToolbarMenuTrigger><ToolbarMenuContent>…\n */\nfunction ToolbarMenuTrigger({\n  overflowLabel,\n  hidden,\n  ref: refProp,\n  ...props\n}: Omit<MenuTitleProps, \"caret\" | \"data-slot\"> & {\n  /** A trailing cell before the caret: a count (\"7/7\") or a shortcut. */\n  affix?: React.ReactNode;\n  /** The row's one commit action opens a menu (Assign ▾): the cobalt cell. It never moves into the overflow menu. */\n  primary?: boolean;\n  overflowLabel?: React.ReactNode;\n}): React.ReactElement {\n  const fold = useFoldItem({\n    type: \"menu\",\n    label: labelOf({ overflowLabel, icon: props.icon, children: props.children, \"aria-label\": props[\"aria-label\"] }),\n    disabled: !!props.disabled,\n  });\n  const setRef = useMergedRef(fold.ref as React.RefObject<HTMLButtonElement | null>, refProp);\n  return <MenuTitle ref={setRef} hidden={fold.hidden || hidden} {...props} />;\n}\n\n/**\n * The menu of a ToolbarMenuTrigger. Menu's surface and rows (MenuItem, MenuCheckboxItem, MenuRadioItem,\n * submenus from ./menu); its top border lies on the toolbar's bottom keyline at the toolbar's weight (2px\n * framed, 1px as a cell), so trigger and menu read as one shape. No cut. Carries the configuration of the\n * place it is written (cut, theme, density, motion, dir) into the portal.\n */\nfunction ToolbarMenuContent({\n  className,\n  container,\n  style,\n  align = \"start\",\n  children,\n  ...props\n}: React.ComponentProps<typeof MenuSurface> & {\n  container?: MenuPrimitive.Portal.Props[\"container\"];\n  align?: \"start\" | \"end\";\n}): React.ReactElement {\n  const { layout, orientation } = React.useContext(ToolbarCtx);\n  const [marker, scope, probe] = useKeylineScope(false, container);\n  const weight = layout === \"cell\" ? 1 : 2;\n  // in a folding toolbar the content registers what it holds, so a folded menu becomes a submenu of More. Its\n  // scope marker sits beside the trigger in the row: that is how the two are paired.\n  const ctx = React.useContext(FoldCtx);\n  const id = React.useId();\n  const anchor = React.useRef<HTMLSpanElement | null>(null);\n  const markerRef = (marker.props as { ref: React.RefObject<HTMLSpanElement | null> }).ref;\n  const setMarker = useMergedRef(anchor, markerRef);\n  React.useLayoutEffect(() => {\n    ctx?.registry.setContent(id, { anchor: anchor.current, children, container });\n  });\n  const registry = ctx?.registry;\n  React.useLayoutEffect(() => () => registry?.deleteContent(id), [registry, id]);\n  return (\n    <>\n      {React.cloneElement(marker as React.ReactElement<{ ref: React.Ref<HTMLSpanElement> }>, { ref: setMarker })}\n      <MenuPrimitive.Portal container={container}>\n        {probe}\n        <MenuPrimitive.Positioner\n          side={orientation === \"vertical\" ? (scope.dir === \"rtl\" ? \"left\" : \"right\") : \"bottom\"}\n          align={align}\n          sideOffset={0}\n          collisionPadding={12}\n          {...scopeProps(scope, { className: \"kl-positioner\" })}\n        >\n          <MenuSurface\n            attachWeight={weight}\n            className={resolveClassName(\"min-w-[max(13rem,var(--anchor-width))]\", className)}\n            style={style}\n            {...props}\n          >\n            {children}\n          </MenuSurface>\n        </MenuPrimitive.Positioner>\n      </MenuPrimitive.Portal>\n    </>\n  );\n}\n\n/** Base UI's part names: the toolbar is its Root. */\nconst ToolbarRoot = Toolbar;\n\nexport {\n  Toolbar,\n  ToolbarRoot,\n  ToolbarButton,\n  ToolbarToggle,\n  ToolbarToggleGroup,\n  ToolbarGroup,\n  ToolbarSeparator,\n  ToolbarSpacer,\n  ToolbarLink,\n  ToolbarInput,\n  ToolbarMenuTrigger,\n  ToolbarMenuContent,\n  useInToolbar,\n  type ToolbarProps,\n  type ToolbarButtonProps,\n  type ToolbarToggleProps,\n  type ToolbarToggleGroupProps,\n  type ToolbarInputProps,\n};\n// A toolbar menu is a Menu (its root, and its rows): re-exported so one import covers the toolbar's menus\nexport {\n  Menu as ToolbarMenu,\n  MenuItem as ToolbarMenuItem,\n  MenuCheckboxItem as ToolbarMenuCheckboxItem,\n  MenuRadioGroup as ToolbarMenuRadioGroup,\n  MenuRadioItem as ToolbarMenuRadioItem,\n  MenuSeparator as ToolbarMenuSeparator,\n  MenuGroup as ToolbarMenuGroup,\n  MenuGroupLabel as ToolbarMenuGroupLabel,\n} from \"./menu\";\n",
      "type": "registry:ui",
      "target": "components/keyline/ui/toolbar.tsx"
    }
  ],
  "type": "registry:ui"
}