{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "toolbar",
  "title": "Toolbar",
  "description": "A row of controls for one surface, such as an editor's formatting: Button commands and Toggle states, in groups with separators.",
  "registryDependencies": [
    "@ouro/button",
    "@ouro/kbd",
    "@ouro/lib-class-name-check",
    "@ouro/lib-cn",
    "@ouro/lib-dev",
    "@ouro/lib-env",
    "@ouro/lib-key-shortcuts",
    "@ouro/lib-platform",
    "@ouro/lib-portal-container",
    "@ouro/lib-refs",
    "@ouro/lib-use-dev-messages",
    "@ouro/lib-use-platform",
    "@ouro/menu",
    "@ouro/toggle",
    "@ouro/tooltip"
  ],
  "files": [
    {
      "path": "registry/ouro/components/ouro/toolbar/toolbar-styles.ts",
      "content": "export { fitCount, splitEntries, toolbarSizes };\nexport type { ToolbarSize };\n\n// Value lists and the overflow arithmetic Toolbar uses, apart from the component so its file\n// exports only components and types (React Fast Refresh).\n\n/**\n * The control sizes, as Button's and Toggle's.\n *\n * @internal\n */\nconst toolbarSizes = { sm: \"sm\", md: \"md\", lg: \"lg\" } as const;\n\n/**\n * A toolbar size.\n *\n * @internal\n */\ntype ToolbarSize = keyof typeof toolbarSizes;\n\n/**\n * How many entries fit in `width`: all of them when their widths and the gaps between them\n * do, or else as many as fit beside the More button (`more` wide, one gap before it).\n *\n * @internal\n * @claim \"How many entries fit in `width`\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow arithmetic > fits every entry when they and their gaps fit, with half a pixel of slack)\n * @claim \"How many entries fit in `width`\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow arithmetic > fits as many as leave room for More and its gap)\n */\nfunction fitCount(widths: readonly number[], more: number, gap: number, width: number): number {\n  const total = widths.reduce((sum, entry, index) => sum + entry + (index > 0 ? gap : 0), 0);\n  // Half a pixel of slack: rounded widths can add up a fraction over the space they came from.\n  if (total <= width + 0.5) return widths.length;\n  const budget = width - more - gap + 0.5;\n  let used = 0;\n  let count = 0;\n  for (const entry of widths) {\n    const next = used + (count > 0 ? gap : 0) + entry;\n    if (next > budget) break;\n    used = next;\n    count += 1;\n  }\n  return count;\n}\n\n/**\n * The first `count` entries to show and the rest for the More menu, with no separator at the\n * end of the row or the start of the menu.\n *\n * @internal\n * @claim \"The first `count` entries to show\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow arithmetic > drops a separator at the end of the row and at the start of the menu)\n */\nfunction splitEntries<T extends { type?: string | undefined }>(entries: readonly T[], count: number): { visible: T[]; overflow: T[] } {\n  const visible = entries.slice(0, count);\n  const overflow = entries.slice(count);\n  while (visible.length > 0 && visible.at(-1)!.type === \"separator\") visible.pop();\n  while (overflow.length > 0 && overflow[0]!.type === \"separator\") overflow.shift();\n  return { visible, overflow };\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/toolbar/toolbar-styles.ts"
    },
    {
      "path": "registry/ouro/components/ouro/toolbar/toolbar.tsx",
      "content": "\"use client\";\n\nimport { flushSync } from \"react-dom\";\nimport { Fragment, useEffect, useLayoutEffect, useRef, useState, type ComponentType, type FocusEvent as ReactFocusEvent, type JSX, type KeyboardEvent, type MouseEvent, type Ref, type RefObject, type SVGProps } from \"react\";\nimport { Button } from \"@/registry/ouro/components/ouro/button/button\";\nimport { Kbd } from \"@/registry/ouro/components/ouro/kbd/kbd\";\nimport { Menu, type MenuEntry } from \"@/registry/ouro/components/ouro/menu/menu\";\nimport { Toggle } from \"@/registry/ouro/components/ouro/toggle/toggle\";\nimport { Tooltip } from \"@/registry/ouro/components/ouro/tooltip/tooltip\";\nimport { useAppearanceClassNameCheck } from \"@/registry/ouro/lib/ouro/class-name-check\";\nimport { cn } from \"@/registry/ouro/lib/ouro/cn\";\nimport { TooltipsHidden } from \"@/registry/ouro/lib/ouro/portal-container\";\nimport { devThrow } from \"@/registry/ouro/lib/ouro/dev\";\nimport { ariaKeyShortcuts } from \"@/registry/ouro/lib/ouro/key-shortcuts\";\nimport type { Platform } from \"@/registry/ouro/lib/ouro/platform\";\nimport { useMergedRef } from \"@/registry/ouro/lib/ouro/refs\";\nimport { usePlatform } from \"@/registry/ouro/lib/ouro/use-platform\";\nimport { useDevWarnings, type DevWarning } from \"@/registry/ouro/lib/ouro/use-dev-messages\";\nimport { fitCount, splitEntries, toolbarSizes, type ToolbarSize } from \"@/registry/ouro/components/ouro/toolbar/toolbar-styles\";\n\n/** An icon component, such as one from `lucide-react` or `@heroicons/react`: `icon: BoldIcon`. */\nexport type ToolbarIcon = ComponentType<SVGProps<SVGSVGElement>>;\n\n/** Keys for a shortcut, as `Kbd` takes them: `[\"mod\", \"b\"]` shows ⌘B on Apple platforms and Ctrl+B elsewhere. */\nexport type ToolbarShortcut = readonly string[] | (string & { 'Use an array: shortcut={[\"mod\", \"b\"]}': never });\n\n/** What a toolbar control takes: a name, an icon and a shortcut to show. */\ninterface ToolbarControlEntry {\n  /** The control's name, shown unless `hideLabel` is set, and its text in the overflow menu. Unique within the toolbar. */\n  label: string;\n  /** Icon before the label, or alone with `hideLabel`. Pass the component: `icon: BoldIcon`. */\n  icon?: ToolbarIcon | undefined;\n  /** Shows only the icon; the label stays the control's name, and shows in its tooltip. */\n  hideLabel?: boolean | undefined;\n  /**\n   * The keys of the control's shortcut, shown in its tooltip and in the overflow menu, and set as\n   * `aria-keyshortcuts`: `[\"mod\", \"b\"]`. It does not bind them; your app handles the keys.\n   */\n  shortcut?: ToolbarShortcut | undefined;\n  /** Shown, and still reachable with the arrow keys, but cannot be pressed. */\n  disabled?: boolean | undefined;\n  /**\n   * The id of the agent action this control performs, set as `data-ax-action` on the control and\n   * on its item in the More menu, so the component that holds the bar and declares the action\n   * finds its control wherever it shows: `axAction: \"mute\"`.\n   */\n  axAction?: string | undefined;\n}\n\n/** A toolbar entry: a command, such as Insert link. The default `type`. */\nexport interface ToolbarButtonEntry extends ToolbarControlEntry {\n  type?: \"button\" | undefined;\n  /** Runs when the control is pressed, or chosen from the overflow menu. */\n  onClick?: (() => void) | undefined;\n}\n\n/** A toolbar entry: an on/off state, such as Bold, drawn as a `Toggle` (`aria-pressed`). */\nexport interface ToolbarToggleEntry extends ToolbarControlEntry {\n  type: \"toggle\";\n  /** Whether it is on, when you control it. Pair it with `onPressedChange`. */\n  pressed?: boolean | undefined;\n  /** Whether it starts on, when the toolbar keeps its state. @default false */\n  defaultPressed?: boolean | undefined;\n  /** Called with the new state when it is pressed, or chosen from the overflow menu. */\n  onPressedChange?: ((pressed: boolean) => void) | undefined;\n}\n\n/** A toolbar entry: related controls under a name screen readers hear (\"Lists\"). */\nexport interface ToolbarGroupEntry {\n  type: \"group\";\n  /** Names the group for screen readers, and labels it in the overflow menu. */\n  label: string;\n  items: readonly (ToolbarButtonEntry | ToolbarToggleEntry)[];\n}\n\n/** One entry in a Toolbar's `items`: a button (the default `type`), a toggle, a group or a separator. */\nexport type ToolbarEntry = ToolbarButtonEntry | ToolbarToggleEntry | ToolbarGroupEntry | { type: \"separator\" };\n\n/** Props for {@link Toolbar}. */\nexport interface ToolbarProps {\n  /** Names the toolbar for screen readers (\"Formatting\"). It is not shown. */\n  label: string;\n  /** The controls, in order: buttons, toggles, groups of them and separators. */\n  items: readonly ToolbarEntry[];\n  /**\n   * Every control's size, as Button's and Toggle's. @default \"md\"\n   * @claim \"Every control's size, as Button's and\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar > takes the size of every control)\n   */\n  size?: ToolbarSize | (string & { 'default is \"md\"; use \"sm\", \"md\" or \"lg\"': never }) | undefined;\n  /**\n   * A press with a mouse or a finger leaves focus where it was, so a text editor beside the\n   * toolbar keeps its caret and selection. With nothing focused, the control takes focus as\n   * usual. The keyboard still reaches the toolbar with Tab.\n   */\n  keepFocus?: boolean | undefined;\n  /** The name of the button that opens the controls that do not fit, and its tooltip. @default \"More\" */\n  moreLabel?: string | undefined;\n  /**\n   * Disables every control. They stay reachable with the arrow keys.\n   * @claim \"Disables every control\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar > disables every control with disabled)\n   */\n  disabled?: boolean | undefined;\n  /**\n   * Draws the bar as glass that floats over content, as a calling app's controls float over\n   * video: a translucent surface that blurs what is behind it, with a hairline edge, a soft\n   * shadow and rounded corners, all from the theme. It turns solid, with no blur, when the\n   * system asks for reduced transparency, and solid with a defined edge when it asks for more\n   * contrast. It is the look only: where the bar floats stays your layout, such as an\n   * absolutely placed wrapper over the stage.\n   * @claim \"a translucent surface that blurs what is behind it\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar floating > is translucent glass from the theme, with a blur, a hairline, a shadow and rounded corners, and stays in the flow)\n   * @claim \"It turns solid, with no blur\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar floating > turns solid with no blur when the system asks for reduced transparency)\n   * @claim \"solid with a defined edge when it asks for more\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar floating > turns solid with a defined edge with prefers-contrast: more, at the same size)\n   */\n  floating?: boolean | undefined;\n  /**\n   * Fades the bar out after this many milliseconds of pointer rest, as a calling app's controls\n   * fade over video (`3000` is usual). It fades with opacity alone, over the theme's base\n   * duration with its ease-out, the same with reduced motion, and its tooltips close as it goes.\n   * A pointer move over its area (`autoHideArea`) brings it back, and so do focus entering it,\n   * from Tab, a screen reader or Voice Control, and a key pressed in it. Keys pressed elsewhere,\n   * such as typing in a chat or holding Space to talk, leave it as it is; to show it for your\n   * app's own shortcuts, control it with `hidden`.\n   *\n   * It never fades while the pointer is over it, while its More menu is open, while a dialog,\n   * popover or other top-layer element that one of its controls opened is open, such as a share\n   * picker, or while keyboard focus is inside it, until the pointer moves on its area. A\n   * control's tooltip holds it only as the pointer or keyboard focus does, so a tooltip that Tab\n   * showed lets it go once the pointer moves. A control pressed with the mouse keeps no hold, so\n   * the bar still fades after a click on Mute.\n   *\n   * While faded it stays in the accessibility tree and focusable, so assistive technology still\n   * reaches every control; it only takes no pointer presses, drops its blur, and has\n   * `data-hidden` on the root.\n   * @claim \"Fades the bar out after this many milliseconds\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > fades out with opacity after the pointer rests, and a pointer move over its area brings it back)\n   * @claim \"It fades with opacity alone\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > fades with opacity alone, also with reduced motion)\n   * @claim \"its tooltips close as it goes\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > lets a tooltip that Tab showed go once the pointer moves, and closes it as it fades)\n   * @claim \"and so do focus entering it\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > comes back when focus enters it, from Tab or a screen reader)\n   * @claim \"and a key pressed in it\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > comes back for a key in it, but not for a bare modifier or a held key's repeats)\n   * @claim \"Keys pressed elsewhere\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays faded while someone types in a field elsewhere or presses keys on the page)\n   * @claim \"to show it for your app's own shortcuts\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > shows when the app sets hidden to false for its own shortcut, and fades after a new rest)\n   * @claim \"It never fades while the pointer is over it\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays while the pointer rests on it, and fades once the pointer leaves)\n   * @claim \"while its More menu is open\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays while its More menu is open)\n   * @claim \"while a dialog, popover or other top-layer element\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays behind a modal dialog one of its controls opened, and takes focus back when it closes)\n   * @claim \"while a dialog, popover or other top-layer element\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays while a popover anchored to one of its controls is open)\n   * @claim \"while a dialog, popover or other top-layer element\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > holds only while a dialog or top-layer element one of its controls opened is open)\n   * @claim \"while keyboard focus is inside it\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays while keyboard focus is inside it, until the pointer moves on its area)\n   * @claim \"A control's tooltip holds it only as the pointer\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays while the pointer rests on an icon-only control with its tooltip, and fades once it leaves)\n   * @claim \"so a tooltip that Tab\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > lets a tooltip that Tab showed go once the pointer moves, and closes it as it fades)\n   * @claim \"A control pressed with the mouse keeps no hold\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > fades after a click on a control once the pointer rests on the stage)\n   * @claim \"While faded it stays in the accessibility tree and focusable\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays in the accessibility tree and focusable while faded, and takes no pointer presses)\n   * @claim \"drops its blur\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > drops the glass's blur once it has faded, and has it back as soon as it shows)\n   */\n  autoHide?: number | (boolean & { 'Pass the milliseconds of rest: autoHide={3000}': never }) | undefined;\n  /**\n   * With `autoHide`: the element whose pointer moves bring the bar back, such as the call's\n   * stage, as an element or a ref. Without it, the bar finds the element it floats over from the\n   * layout: its offset parent (its nearest positioned ancestor), or, when that is an absolutely\n   * placed or fixed wrapper around the bar, the wrapper's own, and so on up. That default needs\n   * nothing wired up for a bar in a wrapper on a `relative` stage, but a stage that is itself\n   * absolutely placed (`absolute inset-0`) widens it past the stage, and a bar in a `relative`\n   * wrapper narrows it to the wrapper: pass the stage then. A bar with no positioned ancestor,\n   * or in a fixed wrapper, listens to the whole page.\n   * @claim \"the element whose pointer moves bring the bar back\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > takes its area from autoHideArea, an element or a ref, in either layout)\n   * @claim \"its offset parent (its nearest positioned ancestor)\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > comes back for a pointer move over its offset parent only, or anywhere when it has none)\n   * @claim \"its offset parent (its nearest positioned ancestor)\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > looks past an absolutely placed or fixed wrapper to the stage it floats over)\n   * @claim \"a stage that is itself absolutely placed\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > takes its area from autoHideArea, an element or a ref, in either layout)\n   * @claim \"A bar with no positioned ancestor, or in a fixed wrapper\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > comes back for a pointer move over its offset parent only, or anywhere when it has none)\n   */\n  autoHideArea?: Element | RefObject<Element | null> | null | undefined;\n  /**\n   * With `autoHide`: whether the bar is faded, when your app controls it. Pair it with\n   * `onHiddenChange={setHidden}`, which asks for each fade and return, so the bar still fades\n   * after a rest and comes back on a pointer move. Set it to `false` yourself to show the bar for\n   * something only your app knows about, such as the person using your app's call shortcuts; a\n   * new rest starts then. Keys anywhere else, such as typing in a chat, still never show it.\n   * Without it, the bar keeps its own state.\n   * @claim \"Pair it with `onHiddenChange={setHidden}`\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > fades and comes back through onHiddenChange, and shows only what the app sets)\n   * @claim \"Set it to `false` yourself to show the bar\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > shows when the app sets hidden to false for its own shortcut, and fades after a new rest)\n   * @claim \"Keys anywhere else, such as typing in a chat\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > shows when the app sets hidden to false for its own shortcut, and fades after a new rest)\n   */\n  hidden?: boolean | undefined;\n  /**\n   * With `autoHide`: called with `true` as the bar starts to fade out and `false` as it starts to\n   * come back, so your layout can move into its space and back. With `hidden`, it is how the bar\n   * asks, and it fades or comes back once you pass the new value.\n   * @claim \"called with `true` as the bar starts to fade out\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > reports each fade and return to onHiddenChange, once each)\n   * @claim \"With `hidden`, it is how the bar\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > fades and comes back through onHiddenChange, and shows only what the app sets)\n   */\n  onHiddenChange?: ((hidden: boolean) => void) | undefined;\n  /** Layout only: margins, width, flex and grid placement (`flex-1`, `mt-2`). Appearance classes warn in development. */\n  className?: string | undefined;\n  /** The toolbar element (`role=\"toolbar\"`). */\n  ref?: Ref<HTMLDivElement> | undefined;\n\n  /** Not a prop. The controls come from `items`: `<Toolbar items={[{ label: \"Bold\", type: \"toggle\" }]}>`. */\n  children?: { 'Use <Toolbar items={[{ label: \"Bold\", type: \"toggle\" }]}>': never };\n  /** Not a prop. A Toolbar is a row; controls that do not fit move into its More menu. */\n  orientation?: { 'A Toolbar is a row; what does not fit moves into its More menu': never };\n  /** Not a prop. Ouro UI uses `items`: `<Toolbar items={[...]}>`. */\n  actions?: { 'Use <Toolbar items={[...]}>': never };\n  /** Not a prop. Use `floating` for the glass look: `<Toolbar floating>`. */\n  glass?: { 'Use <Toolbar floating>': never };\n  /** Not a prop. `autoHide` takes the milliseconds: `<Toolbar autoHide={3000}>`. */\n  autoHideDuration?: { 'Use <Toolbar autoHide={3000}>': never };\n  /** Not a prop. The element whose pointer moves bring the bar back is `autoHideArea`: `<Toolbar autoHide={3000} autoHideArea={stageRef}>`. */\n  area?: { 'Use <Toolbar autoHideArea={stageRef}>': never };\n  /** Not a prop. To control whether the bar shows, pass `hidden` with `onHiddenChange`: `<Toolbar autoHide={3000} hidden={hidden} onHiddenChange={setHidden}>`. */\n  visible?: { 'Use <Toolbar autoHide={3000} hidden={hidden} onHiddenChange={setHidden}>': never };\n}\n\n/** With `keepFocus`: a press leaves focus on whatever has it. With nothing focused, the control takes focus as usual. */\nconst keepFocusOnPress = (event: MouseEvent<HTMLElement>) => {\n  const active = event.currentTarget.ownerDocument.activeElement;\n  if (active && active !== event.currentTarget.ownerDocument.body) event.preventDefault();\n};\n\nfunction MoreIcon(props: SVGProps<SVGSVGElement>): JSX.Element {\n  return (\n    <svg viewBox=\"0 0 24 24\" fill=\"currentColor\" {...props}>\n      <circle cx=\"5\" cy=\"12\" r=\"1.75\" />\n      <circle cx=\"12\" cy=\"12\" r=\"1.75\" />\n      <circle cx=\"19\" cy=\"12\" r=\"1.75\" />\n    </svg>\n  );\n}\n\n/** The controls, groups' included, in order. */\nfunction controlsOf(items: readonly ToolbarEntry[]): Array<ToolbarButtonEntry | ToolbarToggleEntry> {\n  return items.flatMap((entry) => (entry.type === \"group\" ? entry.items : entry.type === \"separator\" ? [] : [entry]));\n}\n\n/** A label that more than one control has, or undefined. */\nfunction duplicateLabel(items: readonly ToolbarEntry[]): string | undefined {\n  const seen = new Set<string>();\n  for (const { label } of controlsOf(items)) {\n    if (seen.has(label)) return label;\n    seen.add(label);\n  }\n  return undefined;\n}\n\n/** A control's shortcut keys, or undefined when it has a string (a type error) or an empty list. */\nfunction keysOf(entry: ToolbarButtonEntry | ToolbarToggleEntry): readonly string[] | undefined {\n  return Array.isArray(entry.shortcut) && entry.shortcut.length > 0 ? (entry.shortcut as readonly string[]) : undefined;\n}\n\n/**\n * A row of controls for one surface, such as an editor's formatting: Button commands and\n * Toggle states, in groups with separators. It is one tab stop, and the arrow keys, Home and\n * End move between its controls (the WAI-ARIA toolbar pattern). Icon-only controls show their\n * label, and any shortcut as `Kbd`, in a tooltip. When the row is too narrow, the controls\n * that do not fit move into a More menu at its end, toggles as checkbox items.\n *\n * `keepFocus` leaves focus in a text editor when a control is pressed with a mouse or a\n * finger, so its selection stays.\n *\n * `floating` draws the bar as glass over content, such as a calling app's controls over video,\n * and `autoHide` fades it out while the pointer rests, until the pointer moves over the stage or\n * focus enters it: `<Toolbar label=\"Call controls\" floating autoHide={3000} items={controls} />`,\n * in a wrapper your layout places over the video (`pointer-events-none absolute inset-x-0\n * bottom-4 flex justify-center` inside the `relative` stage, so the wrapper does not take presses\n * meant for the pictures beside the bar; a floating bar takes its own). `autoHideArea` names the\n * stage when the layout cannot, and `onHiddenChange` tells your layout when the bar fades and\n * comes back. Keys pressed outside the bar leave it faded, so typing in a chat leaves it faded\n * too; to show it when the person uses your app's own call shortcuts, control it with `hidden`, as\n * the second example does.\n *\n * Its agent side is its controls'. Toolbar is a container with nothing of its own for an agent\n * to read or do, so it declares no agent side; the controls inside declare their own, and a\n * calling app declares its call controls once, in the component that holds them, not in the bar.\n * Give each control the id of its action with `axAction`, which the control and its More-menu\n * item carry as `data-ax-action`, so that component's declaration finds its controls.\n *\n * Use `ToggleGroup` instead for toggles that share one value (text alignment), `ButtonGroup`\n * for a few joined buttons that are one control, and `Menu` with `MenuBar` for an\n * application's menus.\n *\n * @group Actions\n * @see https://ui.ouroboros.bot/docs/toolbar\n *\n * @example\n * <Toolbar\n *   label=\"Formatting\"\n *   keepFocus\n *   items={[\n *     { type: \"toggle\", label: \"Bold\", icon: BoldIcon, hideLabel: true, shortcut: [\"mod\", \"b\"], pressed: bold, onPressedChange: setBold },\n *     { type: \"toggle\", label: \"Italic\", icon: ItalicIcon, hideLabel: true, shortcut: [\"mod\", \"i\"], pressed: italic, onPressedChange: setItalic },\n *     { type: \"separator\" },\n *     { label: \"Insert link\", icon: LinkIcon, hideLabel: true, shortcut: [\"mod\", \"k\"], onClick: insertLink },\n *   ]}\n * />\n * @example\n * // Show the bar when the person uses the app's call shortcuts (⇧⌘M mutes, Ctrl+Shift+M off\n * // Apple platforms), and never for other keys, such as typing in the chat.\n * const [hidden, setHidden] = useState(false);\n * useEffect(() => {\n *   const onKey = (event: KeyboardEvent) => {\n *     if (!((event.metaKey || event.ctrlKey) && event.shiftKey && event.key.toLowerCase() === \"m\")) return;\n *     toggleMute();\n *     setHidden(false);\n *   };\n *   addEventListener(\"keydown\", onKey);\n *   return () => removeEventListener(\"keydown\", onKey);\n * }, []);\n * <Toolbar\n *   label=\"Call controls\"\n *   floating\n *   autoHide={3000}\n *   hidden={hidden}\n *   onHiddenChange={setHidden}\n *   items={[{ type: \"toggle\", label: \"Mute\", icon: MicOffIcon, hideLabel: true, shortcut: [\"shift\", \"mod\", \"m\"], pressed: muted, onPressedChange: toggleMute }]}\n * />\n * @claim \"Keys pressed outside the bar leave it faded\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar autoHide > stays faded while someone types in a field elsewhere or presses keys on the page)\n * @claim \"control it with `hidden`, as\" registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.floating.test.tsx::Toolbar hidden > shows when the app sets hidden to false for its own shortcut, and fades after a new rest)\n * @claim \"Give each control the id of its action with `axAction`\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow > sets each control's axAction as data-ax-action on the control in the row and on its More-menu item)\n * @claim \"Toolbar is a container with nothing of its own\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar > exports no agent side of its own)\n */\nexport function Toolbar(props: ToolbarProps): JSX.Element {\n  const { label, items, size: sizeProp = \"md\", keepFocus, moreLabel = \"More\", disabled, floating, autoHide, autoHideArea, hidden: hiddenProp, onHiddenChange, className, ref } = props;\n  const size = Object.hasOwn(toolbarSizes, sizeProp) ? (sizeProp as ToolbarSize) : \"md\";\n  const delay = Number.isFinite(autoHide) && (autoHide as number) > 0 ? (autoHide as number) : undefined;\n  useToolbarChecks(props, sizeProp, size, delay);\n  const toggles = useToggles();\n  const platform = usePlatform();\n  const { rootRef, setRef, probe, shown } = useOverflow(ref, items, size);\n  const { hidden, faded } = useAutoHide(rootRef, delay, autoHideArea, hiddenProp, onHiddenChange);\n  const { visible, overflow } = splitEntries(items, shown);\n  const withMore = probe || overflow.length > 0;\n  const stop = useTabStop(visible, withMore);\n  const context: ControlContext = { size, keepFocus, disabled, toggles, stop: stop.key, platform };\n  const more = moreButton(moreLabel, size, disabled, stop.key === MORE);\n\n  return (\n    <div\n      ref={setRef}\n      role=\"toolbar\"\n      aria-label={label}\n      aria-orientation=\"horizontal\"\n      data-ouro=\"toolbar\"\n      data-size={size}\n      data-disabled={disabled ? \"\" : undefined}\n      data-hidden={hidden ? \"\" : undefined}\n      onFocus={stop.follow}\n      onKeyDown={onKeys}\n      className={cn(\n        \"box-border flex min-w-0 flex-nowrap items-center gap-0.5\",\n        floating && floatingClass,\n        hidden && faded && \"backdrop-blur-none\",\n        delay !== undefined && fadeClass,\n        className,\n      )}\n    >\n      <TooltipsHidden value={hidden}>\n      {visible.map((entry, index) => {\n        if (entry.type === \"separator\") return <div key={index} role=\"separator\" aria-orientation=\"vertical\" data-ouro-toolbar-entry={index} className={separatorClass} />;\n        if (entry.type === \"group\") {\n          return (\n            <div key={index} role=\"group\" aria-label={entry.label} data-ouro-toolbar-entry={index} className=\"flex items-center gap-0.5\">\n              {entry.items.map((item) => control(item, context, item.label))}\n            </div>\n          );\n        }\n        return control(entry, context, index, index);\n      })}\n      {withMore && (disabled ? more : <Menu items={overflow.map((entry) => asMenuEntry(entry, toggles))} align=\"end\" trigger={more} />)}\n      </TooltipsHidden>\n    </div>\n  );\n}\n\n/** Throws on a shared label, and warns in development about a class, a size or a prop that does nothing. */\nfunction useToolbarChecks(props: ToolbarProps, sizeProp: string, size: ToolbarSize, delay: number | undefined): void {\n  const duplicate = duplicateLabel(props.items);\n  if (duplicate !== undefined) {\n    devThrow(\n      \"Toolbar\",\n      `two controls are labeled \"${duplicate}\"`,\n      process.env.NODE_ENV !== \"production\"\n        ? \"give each control its own label\"\n        : // Stryker disable next-line StringLiteral: production only; the check never runs there.\n          /* istanbul ignore next @preserve -- production only */ \"\",\n    );\n  }\n  useAppearanceClassNameCheck(\n    \"Toolbar\",\n    props.className,\n    process.env.NODE_ENV !== \"production\"\n      ? (token: string) => `remove \"${token}\"; Toolbar takes its colors from the theme`\n      : // Stryker disable next-line StringLiteral: production only; the check never runs there.\n        /* istanbul ignore next @preserve -- production only */ \"\",\n  );\n  useDevWarnings(\n    \"Toolbar\",\n    process.env.NODE_ENV !== \"production\"\n      ? () => [...propWarnings(props, sizeProp, size), ...floatWarnings(props, delay), ...entryWarnings(props.items)]\n      : /* istanbul ignore next @preserve -- production only */ undefined,\n  );\n}\n\n/** The development warnings for a toolbar's own props, with their fixes. */\nfunction propWarnings(props: ToolbarProps, sizeProp: string, size: ToolbarSize): DevWarning[] {\n  const { label, children, orientation, actions } = props;\n  return [\n    size !== sizeProp && [`size=\"${sizeProp}\" is not a size`, '<Toolbar size=\"md\">'],\n    !label && [\"label is empty, so the toolbar has no name\", '<Toolbar label=\"Formatting\">'],\n    children !== undefined && [\"children is not a prop; the controls come from items\", '<Toolbar items={[{ label: \"Bold\", type: \"toggle\" }]}>'],\n    orientation !== undefined && [\"orientation is not a prop; a Toolbar is a row\", `<Toolbar label=\"${label}\" items={…}>`],\n    actions !== undefined && [\"actions is not a prop\", \"<Toolbar items={[…]}>\"],\n  ];\n}\n\n/** The development warnings for `floating` and `autoHide`, and the names agents guess for them, with their fixes. */\nfunction floatWarnings(props: ToolbarProps, delay: number | undefined): DevWarning[] {\n  const { autoHide, autoHideArea, hidden, onHiddenChange, glass, autoHideDuration, area, visible } = props;\n  return [\n    autoHide !== undefined && delay === undefined && [`autoHide={${String(autoHide)}} is not a time in milliseconds`, \"<Toolbar autoHide={3000}>\"],\n    onHiddenChange !== undefined && delay === undefined && [\"onHiddenChange is never called without autoHide\", \"<Toolbar autoHide={3000} onHiddenChange={…}>\"],\n    autoHideArea !== undefined && delay === undefined && [\"autoHideArea does nothing without autoHide\", \"<Toolbar autoHide={3000} autoHideArea={stageRef}>\"],\n    hidden !== undefined && delay === undefined && [\"hidden does nothing without autoHide\", \"<Toolbar autoHide={3000} hidden={hidden} onHiddenChange={setHidden}>\"],\n    hidden !== undefined && delay !== undefined && onHiddenChange === undefined && [\n      \"hidden without onHiddenChange never fades or comes back on its own\",\n      \"<Toolbar autoHide={3000} hidden={hidden} onHiddenChange={setHidden}>\",\n    ],\n    visible !== undefined && [\"visible is not a prop; control the bar with hidden\", \"<Toolbar autoHide={3000} hidden={hidden} onHiddenChange={setHidden}>\"],\n    area !== undefined && [\"area is not a prop\", \"<Toolbar autoHide={3000} autoHideArea={stageRef}>\"],\n    glass !== undefined && [\"glass is not a prop\", \"<Toolbar floating>\"],\n    autoHideDuration !== undefined && [\"autoHideDuration is not a prop; autoHide takes the milliseconds\", \"<Toolbar autoHide={3000}>\"],\n  ];\n}\n\n/** The development warnings for a toolbar's items, with their fixes. */\nfunction entryWarnings(items: readonly ToolbarEntry[]): DevWarning[] {\n  const controls = controlsOf(items);\n  const bare = controls.find((entry) => entry.hideLabel && !entry.icon);\n  const stringShortcut = controls.find((entry) => typeof entry.shortcut === \"string\");\n  const unnamedGroup = items.some((entry) => entry.type === \"group\" && !entry.label);\n  return [\n    bare && [`\"${bare.label}\" hides its label without an icon`, `{ label: \"${bare.label}\", icon: ${bare.label.replace(/\\W/g, \"\")}Icon, hideLabel: true }`],\n    stringShortcut && [\n      `\"${stringShortcut.label}\" has shortcut=\"${String(stringShortcut.shortcut)}\", a string; shortcut takes an array`,\n      '{ shortcut: [\"mod\", \"b\"] }',\n    ],\n    unnamedGroup && [\"a group's label is empty, so screen readers cannot name it\", '{ type: \"group\", label: \"Lists\", items: […] }'],\n  ];\n}\n\n// Toggles keep their state here too, so an uncontrolled one survives a move into the More menu.\ninterface Toggles {\n  pressedOf: (entry: ToolbarToggleEntry) => boolean;\n  press: (entry: ToolbarToggleEntry, next: boolean) => void;\n}\n\nfunction useToggles(): Toggles {\n  const [own, setOwn] = useState<Readonly<Record<string, boolean>>>({});\n  return {\n    pressedOf: (entry) => entry.pressed ?? own[entry.label] ?? entry.defaultPressed ?? false,\n    press: (entry, next) => {\n      setOwn((state) => ({ ...state, [entry.label]: next }));\n      entry.onPressedChange?.(next);\n    },\n  };\n}\n\n/**\n * How many entries fit in the root now. When the focused control is about to move into the\n * menu, it sets `refocus`, so focus follows it to More once the row has updated.\n */\nfunction countFits(root: HTMLElement, widths: readonly number[], moreWidth: number, refocus: { current: boolean }): number {\n  const style = getComputedStyle(root);\n  // The root's own classes set its gap, so the computed value is always a length.\n  const gap = parseFloat(style.columnGap);\n  const width = root.clientWidth - parseFloat(style.paddingInlineStart) - parseFloat(style.paddingInlineEnd);\n  const fits = fitCount(widths, moreWidth, gap, width);\n  const entry = root.querySelector(\":scope > [data-ouro-toolbar-entry]:focus-within\");\n  if (entry && Number(entry.getAttribute(\"data-ouro-toolbar-entry\")) >= fits) refocus.current = true;\n  return fits;\n}\n\n/**\n * Whether every entry fits in the root with no More.\n *\n * @claim \"Whether every entry fits in the root with no More.\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow > fits a row that narrows, widens and narrows again exactly as one drawn at that width from the start)\n */\nfunction rowFits(root: HTMLElement, widths: readonly number[]): boolean {\n  const style = getComputedStyle(root);\n  const width = root.clientWidth - parseFloat(style.paddingInlineStart) - parseFloat(style.paddingInlineEnd);\n  return fitCount(widths, 0, parseFloat(style.columnGap), width) === widths.length;\n}\n\n/**\n * What decides an entry's width: its type, label, whether it shows its label and has an icon, and a group's\n * controls. Handlers, pressed states and shortcuts change none of it, nor does an app rendering the same items anew.\n * @claim \"Handlers, pressed states and shortcuts change none\" registry/ouro/components/ouro/toolbar/toolbar.test.tsx verify:testExists(registry/ouro/components/ouro/toolbar/toolbar.test.tsx::Toolbar overflow > lays nothing out when it renders again with new items that look the same, and measures again when a label changes)\n */\nfunction widthInputs(items: readonly ToolbarEntry[]): string {\n  const shape = (entry: ToolbarEntry): unknown =>\n    // Stryker disable next-line ConditionalExpression,StringLiteral,EqualityOperator: equivalent; each part only has to tell its kinds apart in the key, and a separator's string, a flipped test of a boolean and an empty name all still do, since every other entry is an array.\n    entry.type === \"separator\" ? \"separator\" : entry.type === \"group\" ? [entry.label, entry.items.map(shape)] : [entry.type, entry.label, entry.hideLabel === true, entry.icon !== undefined];\n  return JSON.stringify(items.map(shape));\n}\n\n// Overflow: with new widths or a new `size`, every entry is shown and measured before paint; then\n// as many as fit stay in the row and the rest move into the More menu. The widths measured\n// then serve every later resize, which the resize observer reports once the page is laid out, where\n// reads are free. A render of the same entries measures nothing: a read inside a commit lays the page out at once.\nfunction useOverflow(ref: Ref<HTMLDivElement> | undefined, items: readonly ToolbarEntry[], size: ToolbarSize) {\n  const rootRef = useRef<HTMLDivElement>(null);\n  const setRef = useMergedRef(ref, rootRef);\n  const widths = useRef<readonly number[] | null>(null);\n  const moreWidth = useRef(0);\n  const inputs = widthInputs(items);\n  // Counts the times the entries' text changed under them (a font loading, a zoom), which measures them again.\n  const [epoch, setEpoch] = useState(0);\n  // `probe` is set while More is drawn only to read its width, once a measure finds the row too narrow.\n  const [layout, setLayout] = useState<{ inputs: string; size: ToolbarSize; epoch: number; shown: number; probe?: true } | null>(null);\n  const measuring = layout?.inputs !== inputs || layout.size !== size || layout.epoch !== epoch;\n  const probe = !measuring && layout.probe === true;\n  const entries = useRef<ResizeObserver | null>(null);\n  const refocus = useRef(false);\n\n  // A row is measured with every entry and no More, so a row that fits is its final row from the first frame:\n  // More is drawn only once a measure finds the row too narrow. The first measure waits for the observer's\n  // first report, which comes once the page is laid out and before it paints, where the reads are free. Later\n  // measures (new items, a size, a font) run in the commit that asks for them, as the page is laid out by then.\n  // Stryker disable next-line BooleanLiteral: equivalent; the measure's effect sets it before any observer reports.\n  const pending = useRef(true);\n  const measured = useRef(false);\n  useLayoutEffect(() => {\n    const root = rootRef.current!;\n    const settle = (shown: number) => setLayout({ inputs, size, epoch, shown });\n    const toProbe = () => setLayout({ inputs, size, epoch, shown: widths.current!.length, probe: true });\n    // Whether every entry fits; when not, More is drawn next to read its width.\n    const plan = (): boolean => {\n      pending.current = false;\n      widths.current = [...root.querySelectorAll<HTMLElement>(\":scope > [data-ouro-toolbar-entry]\")].map((element) => element.getBoundingClientRect().width);\n      return rowFits(root, widths.current);\n    };\n    if (probe) {\n      moreWidth.current = root.querySelector<HTMLElement>(\":scope > [data-ouro-toolbar-more]\")!.getBoundingClientRect().width;\n      settle(countFits(root, widths.current!, moreWidth.current, refocus));\n      return;\n    }\n    if (!measuring) return;\n    if (measured.current) {\n      if (plan()) settle(widths.current!.length);\n      else toProbe();\n      return;\n    }\n    // Stryker disable next-line BooleanLiteral: equivalent; only a measure clears pending, and it also sets measured, so pending is still true here.\n    pending.current = true;\n    const measure = new ResizeObserver(() => {\n      measure.disconnect();\n      measured.current = true;\n      const fits = plan();\n      flushSync(() => (fits ? settle(widths.current!.length) : toProbe()));\n    });\n    measure.observe(root);\n    // Stryker disable next-line ArrowFunction: equivalent; an observer left on reports once, and a newer one made after it reports after it in the same delivery and sets the row it measures, while React drops a state set after unmount.\n    return () => measure.disconnect();\n  }, [inputs, size, epoch, probe, measuring]);\n\n  // A shown entry that is wider or narrower than measured means its text changed without the root resizing.\n  useLayoutEffect(() => {\n    const root = rootRef.current!;\n    const stale = new ResizeObserver(() => {\n      // The measure about to run reads every entry anew.\n      if (pending.current) return;\n      const measured = widths.current!;\n      const changed = [...root.querySelectorAll<HTMLElement>(\":scope > [data-ouro-toolbar-entry]\")].some(\n        (element) => !(Math.abs(element.getBoundingClientRect().width - measured[Number(element.getAttribute(\"data-ouro-toolbar-entry\"))]!) <= 0.5),\n      );\n      // Stryker disable next-line ArithmeticOperator: equivalent; the epoch is only compared for difference, so count - 1 forces a measure just as count + 1 does.\n      if (changed) setEpoch((count) => count + 1);\n    });\n    entries.current = stale;\n    // A font that loads changes the labels' widths, and maybe nothing the observers see, so the entries are measured\n    // again once the fonts are ready. (WebKit sends no loadingdone for a face it finds at once, only loading.)\n    const fonts = root.ownerDocument.fonts;\n    // Stryker disable next-line ArithmeticOperator: equivalent; the epoch is only compared for difference, so count - 1 forces a measure just as count + 1 does.\n    const loading = () => void fonts.ready.then(() => setEpoch((count) => count + 1));\n    fonts.addEventListener(\"loading\", loading);\n    return () => {\n      stale.disconnect();\n      fonts.removeEventListener(\"loading\", loading);\n    };\n  },\n  // Stryker disable next-line ArrayDeclaration: equivalent; a constant dependency list runs the effect once on mount and cleans up on unmount, exactly as an empty one does.\n  []);\n  useLayoutEffect(() => {\n    for (const element of rootRef.current!.querySelectorAll(\":scope > [data-ouro-toolbar-entry]\")) entries.current!.observe(element);\n  });\n\n  const shown = measuring ? items.length : layout.shown;\n  useLayoutEffect(() => {\n    if (!refocus.current) return;\n    refocus.current = false;\n    rootRef.current!.querySelector<HTMLElement>(\":scope > [data-ouro-toolbar-more]\")!.focus();\n  }, [shown]);\n\n  // Made in the mounting commit, as the first measure's is: made in a passive effect, it could start during the\n  // frame's first resize delivery (the measure's flushSync runs pending passive effects), after the row's depth was\n  // delivered, and the browser would report a \"ResizeObserver loop\" error.\n  useLayoutEffect(\n    () => {\n      const root = rootRef.current!;\n      const observer = new ResizeObserver(() => {\n        // Until the first measure has read the entries there is nothing to fit; it fits them itself.\n        if (pending.current) return;\n        const fits = rowFits(root, widths.current!);\n        // Too narrow: draw More to read its width and fit the row to it, before the frame paints.\n        flushSync(() => setLayout((current) => ({ inputs: current!.inputs, size: current!.size, epoch: current!.epoch, shown: widths.current!.length, ...(fits ? {} : { probe: true as const }) })));\n      });\n      observer.observe(root);\n      // Stryker disable next-line ArrowFunction: React ignores a state set after unmount, so disconnecting only tidies.\n      return () => observer.disconnect();\n    },\n    // The observer reads refs only, so the one set up once stays current.\n    // Stryker disable next-line ArrayDeclaration: any list that never changes runs it once, as this one does.\n    [],\n  );\n\n  return { rootRef, setRef, probe, shown };\n}\n\n/**\n * The element whose pointer moves bring an auto-hiding bar back: `autoHideArea` when it names\n * one, or else the bar's offset parent, or, when that is an absolutely placed or fixed wrapper\n * around the bar, the wrapper's own, and so on up. Null, for the whole page, when that runs out\n * or reaches the body.\n */\nfunction areaOf(root: HTMLElement, given: Element | RefObject<Element | null> | null | undefined): Element | null {\n  const named = given && \"current\" in given ? given.current : given;\n  if (named) return named;\n  let area = root.offsetParent as HTMLElement | null;\n  while (area !== null && [\"absolute\", \"fixed\"].includes(getComputedStyle(area).position)) area = area.offsetParent as HTMLElement | null;\n  return area === root.ownerDocument.body ? null : area;\n}\n\n/** The layers a control can open: dialogs, popovers and other top-layer elements. */\nconst LAYER = 'dialog, [role=\"dialog\"], [role=\"alertdialog\"], [popover]';\n\n/** Whether a layer is open: in the page, and not a `<dialog>` without `open` or a popover not shown. */\nconst isOpen = (layer: Element) => layer.isConnected && !layer.matches(\"dialog:not([open]), [popover]:not(:popover-open)\");\n\n/**\n * With `autoHide`: whether the bar has faded out, and whether that fade has finished, so the\n * glass drops its blur only once nothing shows. A pointer move or press over its area\n * (`areaOf`), focus entering it, or a key in it shows it and starts the rest again. With\n * `hidden`, the bar asks through `onHiddenChange` instead, and the app showing it starts a rest\n * too. When the rest ends while the pointer is over the bar, its More menu is open, a layer one\n * of its controls opened is open, or keyboard focus has been in it since the pointer last moved,\n * it waits another rest.\n */\nfunction useAutoHide(\n  rootRef: RefObject<HTMLDivElement | null>,\n  delay: number | undefined,\n  given: Element | RefObject<Element | null> | null | undefined,\n  controlled: boolean | undefined,\n  onHiddenChange: ((hidden: boolean) => void) | undefined,\n): { hidden: boolean; faded: boolean } {\n  const [own, setOwn] = useState(false);\n  const hidden = delay !== undefined && (controlled ?? own);\n  // Stryker disable next-line BooleanLiteral: every fade resets it before it is read, so where it starts changes nothing.\n  const [faded, setFaded] = useState(false);\n  // What the bar last asked for, or the app last set, and whom to tell, for the listeners set up\n  // once per delay. An ask counts at once, so a move right after a fade, before React renders\n  // it, still brings the bar back.\n  const latest = useRef({ wish: hidden, onHiddenChange });\n  useLayoutEffect(() => {\n    latest.current.onHiddenChange = onHiddenChange;\n  });\n  // Starts the rest again, for an app that shows the bar itself.\n  const restart = useRef<(() => void) | null>(null);\n\n  useEffect(() => {\n    if (delay === undefined) return;\n    const root = rootRef.current!;\n    const doc = root.ownerDocument;\n    const stop = new AbortController();\n    // Capture, so a player or a menu that stops an event inside the area still counts.\n    const listen = { capture: true, signal: stop.signal };\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    let at: string | undefined;\n    // A touch leaves :hover on what it tapped, so only a mouse or pen over the bar holds it.\n    let touch: boolean | undefined;\n    // Keys or focus in the bar since the pointer last moved on the area: focus already in it counts.\n    let keyed = root.contains(doc.activeElement);\n    // The control the last press or key went to, until the bar next rests, and the layers open\n    // then: a layer that opens after it and takes focus is the one that control opened, and it\n    // lends the bar a hold while it stays open, so the bar is in place to take focus back.\n    let opener: Element | null = null;\n    // Stryker disable next-line ArrayDeclaration: every press or key sets it with opener, and it is read only while opener is set.\n    let open: Element[] = [];\n    let lent: Element | null = null;\n    const held = () => {\n      // A layer that has closed lends nothing again, even if it opens later on its own.\n      if (lent !== null && !isOpen(lent)) lent = null;\n      return (\n        (!touch && root.matches(\":hover\")) ||\n        root.querySelector(\"[aria-expanded='true']\") !== null ||\n        lent !== null ||\n        // Keyboard focus only: Chromium focuses a button a mouse clicks, and that holds nothing.\n        // A tooltip that focus showed holds no more than the focus does.\n        (keyed && root.querySelector(\":focus-visible\") !== null)\n      );\n    };\n    const ask = (next: boolean) => {\n      if (latest.current.wish === next) return;\n      latest.current.wish = next;\n      setOwn(next);\n      latest.current.onHiddenChange?.(next);\n    };\n    let area = areaOf(root, given);\n    const rest = () => {\n      clearTimeout(timer);\n      timer = setTimeout(() => {\n        opener = null;\n        if (held()) return rest();\n        // Measured again as the bar goes, so a layout that changed since is the one that counts.\n        area = areaOf(root, given);\n        ask(true);\n        // Each fade keeps the blur until it has finished, whatever an earlier one left.\n        setFaded(false);\n      }, delay);\n    };\n    restart.current = rest;\n    const show = () => {\n      ask(false);\n      rest();\n    };\n    const press = (target: EventTarget | null) => {\n      opener = root.contains(target as Node) ? (target as Element).closest('[data-ouro-control=\"toolbar\"]') : null;\n      open = [...doc.querySelectorAll(LAYER)].filter(isOpen);\n    };\n    const inArea = (target: EventTarget | null) => area === null || area.contains(target as Node);\n    const onPointer = (event: PointerEvent) => {\n      if (event.type === \"pointerdown\") press(event.target);\n      const where = `${event.clientX} ${event.clientY}`;\n      // A move event that did not move (a browser's own, after layout) is no movement.\n      if ((event.type === \"pointermove\" && where === at) || !inArea(event.target)) return;\n      at = where;\n      touch = event.pointerType === \"touch\";\n      keyed = false;\n      show();\n    };\n    // Only keys in the bar show it; a bare modifier or a held key's repeats are no use of it.\n    const onKey = (event: globalThis.KeyboardEvent) => {\n      press(event.target);\n      if (!root.contains(event.target as Node) || event.repeat || [\"Alt\", \"Control\", \"Meta\", \"Shift\"].includes(event.key)) return;\n      keyed = true;\n      show();\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target as Element;\n      if (root.contains(target)) {\n        keyed = true;\n        show();\n        return;\n      }\n      const layer = target.closest(LAYER);\n      if (opener !== null && layer !== null && !open.includes(layer)) lent = layer;\n    };\n    doc.addEventListener(\"pointermove\", onPointer, listen);\n    doc.addEventListener(\"pointerdown\", onPointer, listen);\n    doc.addEventListener(\"keydown\", onKey, listen);\n    doc.addEventListener(\"focusin\", onFocus, listen);\n    rest();\n    return () => {\n      stop.abort();\n      clearTimeout(timer);\n      restart.current = null;\n      // So the bar shows when autoHide is turned off or changed.\n      ask(false);\n    };\n  }, [delay, given, rootRef]);\n\n  // The app's value is what the bar has now. When the app shows the bar, as for its own call\n  // shortcuts, it fades again after a new rest. The app passing back what the bar asked for is no\n  // new return: the bar started its rest as it asked, and that render can come after time has moved on.\n  useEffect(() => {\n    if (controlled === undefined) return;\n    const asked = latest.current.wish === controlled;\n    latest.current.wish = controlled;\n    // Stryker disable next-line ConditionalExpression: a rest that ends while the bar is hidden asks for what it has, so starting one then changes nothing.\n    if (!controlled && !asked) restart.current?.();\n  }, [controlled]);\n\n  // The blur goes once the fade has finished (at once with no transition); it is read only while\n  // the bar is hidden, so it comes back as soon as the bar shows.\n  useEffect(() => {\n    // Stryker disable next-line ConditionalExpression: waiting while shown only sets faded, which is read only while hidden and reset by every fade.\n    if (!hidden) return;\n    void Promise.allSettled(rootRef.current!.getAnimations().map((animation) => animation.finished)).then(() => setFaded(true));\n  }, [hidden, rootRef]);\n\n  return { hidden, faded };\n}\n\n/** The key that stands for the More button in the row's roving focus. */\n// Stryker disable next-line StringLiteral: equivalent; any string no control's label takes keeps More apart.\nconst MORE = \"\\u0000more\";\n\n/**\n * The row's one tab stop: the control focus was last in, or the first control while that one is in\n * More. Focus moving to a control makes it the stop, as the WAI-ARIA toolbar pattern's roving\n * tabindex does. Kept by label, which is unique, so it survives a control moving into More and back.\n */\nfunction useTabStop(visible: readonly ToolbarEntry[], withMore: boolean) {\n  const [focused, setFocused] = useState<string | null>(null);\n  const keys = visible.flatMap((entry) => (entry.type === \"separator\" ? [] : entry.type === \"group\" ? entry.items.map((item) => item.label) : [entry.label]));\n  if (withMore) keys.push(MORE);\n  // Stryker disable next-line ConditionalExpression: equivalent; the keys never hold null, so the check only narrows the type.\n  const key = focused !== null && keys.includes(focused) ? focused : keys[0];\n  const follow = (event: ReactFocusEvent<HTMLDivElement>) => {\n    const next = (event.target as HTMLElement).getAttribute(\"data-ouro-toolbar-stop\");\n    // Stryker disable next-line ConditionalExpression: equivalent; the only other focus in the row's tree is in the More menu, which gives focus back to More as it closes.\n    if (next !== null) setFocused(next);\n  };\n  return { key, follow };\n}\n\n/**\n * The toolbar's keys, as the WAI-ARIA toolbar pattern has them: the arrow keys move between its\n * controls and wrap at either end, the way the text runs (the page's direction, read at the press),\n * and Home and End reach the first and the last control. Disabled controls stay reachable. Keys\n * pressed in the More menu, which renders in a portal, are the menu's.\n */\nfunction onKeys(event: KeyboardEvent<HTMLDivElement>): void {\n  const controls = [...event.currentTarget.querySelectorAll<HTMLElement>('[data-ouro-control=\"toolbar\"]')];\n  const at = controls.indexOf(event.target as HTMLElement);\n  if (at === -1) return;\n  let next: number;\n  if (event.key === \"Home\" || event.key === \"End\") next = event.key === \"Home\" ? 0 : controls.length - 1;\n  else if ((event.key === \"ArrowRight\" || event.key === \"ArrowLeft\") && !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey)) {\n    const forward = (event.key === \"ArrowRight\") !== (getComputedStyle(event.currentTarget).direction === \"rtl\");\n    next = (at + (forward ? 1 : controls.length - 1)) % controls.length;\n  } else return;\n  event.preventDefault();\n  controls[next]!.focus();\n}\n\n/** What the row's controls share. */\ninterface ControlContext {\n  size: ToolbarSize;\n  keepFocus: boolean | undefined;\n  disabled: boolean | undefined;\n  toggles: Toggles;\n  /** The label of the control that is the row's tab stop. */\n  stop: string | undefined;\n  /** The platform the row's shortcuts are shown in, once the page knows it. */\n  platform: Platform;\n}\n\n/** A control in the row: a Toggle or a Button, with a tooltip when it hides its label or has a shortcut. */\nfunction control(entry: ToolbarButtonEntry | ToolbarToggleEntry, context: ControlContext, key: string | number, index?: number): JSX.Element {\n  const { size, keepFocus, disabled, toggles, stop, platform } = context;\n  const Icon = entry.icon;\n  const iconOnly = Boolean(entry.hideLabel && Icon);\n  const shortcut = keysOf(entry);\n  const off = Boolean(disabled || entry.disabled);\n  const shared = {\n    ...rowStop(entry.label, stop === entry.label, off),\n    \"data-ouro-toolbar-entry\": index,\n    \"aria-keyshortcuts\": shortcut && ariaKeyShortcuts(shortcut, platform),\n    \"data-ax-action\": entry.axAction,\n    onMouseDown: keepFocus ? keepFocusOnPress : undefined,\n    className: \"aria-disabled:cursor-not-allowed aria-disabled:opacity-50\",\n  };\n  const element =\n    entry.type === \"toggle\" ? (\n      <Toggle\n        {...shared}\n        data-ouro-control=\"toolbar\"\n        data-ouro-part=\"toggle\"\n        label={entry.label}\n        icon={Icon}\n        hideLabel={entry.hideLabel}\n        size={size}\n        pressed={toggles.pressedOf(entry)}\n        onPressedChange={(next) => {\n          if (!off) toggles.press(entry, next);\n        }}\n      />\n    ) : (\n      <Button\n        {...shared}\n        data-ouro-control=\"toolbar\"\n        data-ouro-part=\"button\"\n        variant=\"plain\"\n        tone=\"secondary\"\n        size={size}\n        aria-label={iconOnly ? entry.label : undefined}\n        startIcon={iconOnly ? undefined : Icon}\n        onClick={off ? undefined : entry.onClick}\n        className={cn(shared.className, iconOnly && \"aspect-square px-0\")}\n      >\n        {iconOnly && Icon ? <Icon aria-hidden=\"true\" className=\"size-[1.25em] shrink-0\" /> : entry.label}\n      </Button>\n    );\n  if (!iconOnly && !shortcut) return <Fragment key={key}>{element}</Fragment>;\n  return (\n    <Tooltip key={key} content={tip(entry.label, shortcut)}>\n      {element}\n    </Tooltip>\n  );\n}\n\n/**\n * What puts a control in the row's roving focus: its tab stop (only the stop is in the Tab order),\n * and, while disabled, `aria-disabled` and `data-disabled` rather than the `disabled` attribute, so\n * it stays reachable from the arrow keys and is read as unavailable, and its press does nothing.\n */\nfunction rowStop(key: string, isStop: boolean, off: boolean) {\n  return {\n    \"data-ouro-toolbar-stop\": key,\n    tabIndex: isStop ? 0 : -1,\n    \"aria-disabled\": off || undefined,\n    \"data-disabled\": off ? \"\" : undefined,\n  };\n}\n\n// An entry as the More menu shows it. A disabled toolbar has no menu, so only a control's own `disabled` reaches here.\nfunction asMenuEntry(entry: ToolbarEntry, toggles: Toggles): MenuEntry {\n  if (entry.type === \"separator\") return entry;\n  if (entry.type === \"group\") return { type: \"group\", label: entry.label, items: entry.items.map((item) => asMenuEntry(item, toggles)) };\n  const shortcut = keysOf(entry);\n  if (entry.type === \"toggle\") {\n    return {\n      type: \"checkbox\",\n      label: entry.label,\n      checked: toggles.pressedOf(entry),\n      onCheckedChange: (next) => toggles.press(entry, next),\n      shortcut,\n      disabled: entry.disabled,\n      axAction: entry.axAction,\n    };\n  }\n  return { label: entry.label, onClick: entry.onClick, shortcut, disabled: entry.disabled, axAction: entry.axAction };\n}\n\n// The button that opens what does not fit. A disabled toolbar has no menu to open.\nfunction moreButton(moreLabel: string, size: ToolbarSize, disabled: boolean | undefined, isStop: boolean): JSX.Element {\n  return (\n    <Tooltip content={moreLabel}>\n      <Button\n        {...rowStop(MORE, isStop, Boolean(disabled))}\n        data-ouro-toolbar-more=\"\"\n        data-ouro-control=\"toolbar\"\n        data-ouro-part=\"more\"\n        variant=\"plain\"\n        tone=\"secondary\"\n        size={size}\n        aria-label={moreLabel}\n        className=\"aspect-square px-0 aria-disabled:cursor-not-allowed aria-disabled:opacity-50\"\n      >\n        <MoreIcon aria-hidden=\"true\" className=\"size-[1.25em] shrink-0\" />\n      </Button>\n    </Tooltip>\n  );\n}\n\n// Glass over content: translucent card with a blur, a hairline, a soft shadow and the theme's\n// corners; solid where the system asks for less transparency, and with a defined edge for more\n// contrast, a ring so the box keeps its size. It takes presses inside a wrapper that passes them\n// through. Forced colours drop rings, so the bar keeps an edge as a border there.\nconst floatingClass =\n  \"rounded-ouro-xl bg-card/75 p-1 text-card-foreground shadow-(--shadow-lg) ring-1 ring-border/60 backdrop-blur-xl \" +\n  \"[@media(prefers-reduced-transparency:reduce)]:bg-card [@media(prefers-reduced-transparency:reduce)]:backdrop-blur-none \" +\n  \"pointer-events-auto contrast-more:bg-card contrast-more:ring-2 contrast-more:ring-current contrast-more:backdrop-blur-none \" +\n  \"forced-colors:border forced-colors:border-solid\";\n\n// The auto-hide fade: opacity alone, so it is the same with reduced motion. Faded, it takes no\n// presses, so an invisible control is never pressed by mistake; focus still reaches it.\nconst fadeClass = \"transition-opacity duration-(--ouro-duration-base) ease-(--ouro-ease-out) data-hidden:pointer-events-none data-hidden:opacity-0\";\n\n/** A vertical rule between controls, in the border color. */\nconst separatorClass = \"mx-1 h-5 w-px shrink-0 self-center bg-border forced-colors:bg-[CanvasText]\";\n\n/** A control's tooltip: its label, then its shortcut. */\nfunction tip(label: string, shortcut: readonly string[] | undefined): JSX.Element {\n  return (\n    <span className=\"inline-flex items-center gap-2\">\n      {label}\n      {shortcut && <Kbd keys={shortcut} />}\n    </span>\n  );\n}\n",
      "type": "registry:ui",
      "target": "@components/ouro/toolbar/toolbar.tsx"
    }
  ],
  "docs": "A row of controls for one surface, such as an editor's formatting: Button commands and Toggle states, in groups with separators. Import: import { Toolbar } from \"@/components/ouro/toolbar/toolbar\", with @/components replaced by your components alias (aliases.components in components.json, such as ~/components). Also installed: button, kbd, menu, toggle, tooltip, the helpers they import in lib/ouro. Needs ouro-base in your stylesheet: add that item once per app, from the same place as this one, if you have not. Docs: https://ui.ouroboros.bot/docs/toolbar.md Ouro UI v1.3.257.",
  "type": "registry:ui"
}