{"name":"overflow-toolbar","type":"registry:component","files":[{"path":"overflow-toolbar.tsx","type":"registry:component","target":"components/ui/overflow-toolbar/overflow-toolbar.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport { flushSync } from \"react-dom\"\n\nimport { ChevronDown as ChevronDownIcon } from \"honestui/icons\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Button } from \"@/components/ui/button\"\nimport {\n  Menu,\n  MenuGroup,\n  MenuGroupLabel,\n  MenuItem,\n  MenuPopup,\n  MenuSeparator,\n  MenuTrigger,\n} from \"@/components/ui/menu\"\nimport { Toolbar, ToolbarButton, ToolbarGroup } from \"@/components/ui/toolbar\"\nimport { Tooltip, TooltipPopup, TooltipTrigger } from \"@/components/ui/tooltip\"\n\nimport type {\n  OverflowMenuSection,\n  OverflowPriority,\n  OverflowToolbarItemStore,\n} from \"./overflow-toolbar-types\"\nimport {\n  createOverflowToolbarItemStore,\n  defaultOverflowPriority,\n  getCollapseOrder,\n  getOverflowMenuSections,\n  initialOverflowFitState,\n  stepOverflowFit,\n} from \"./overflow-toolbar-utils\"\n\nexport type { OverflowPriority } from \"./overflow-toolbar-types\"\n\nconst itemAttribute = \"data-overflow-toolbar-item\"\nconst moreAttribute = \"data-overflow-toolbar-more\"\n\nconst toolbarNavigationKeys = new Set([\"ArrowLeft\", \"ArrowRight\", \"ArrowUp\", \"ArrowDown\", \"Home\", \"End\"])\n\n/** Toolbar strips borders from its direct children only; these can sit one level down. */\nconst controlClassName = cn(\n  \"border-0 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-disabled:active:scale-100!\",\n  // One 32px control height, a 13px label, and 16px icons in the secondary colour.\n  \"shrink-0 rounded-[var(--hui-radius-1)] text-[var(--hui-color-foreground-base-primary)] [font-size:var(--hui-font-size-control,13px)] [letter-spacing:var(--hui-letter-spacing-control,-0.003em)] [line-height:16px] [font-weight:var(--hui-font-weight-medium)]\",\n  \"[&_svg]:size-4 [&_svg]:text-[var(--hui-color-foreground-base-secondary)] not-data-disabled:hover:[&_svg]:text-[var(--hui-color-foreground-base-primary)] data-popup-open:[&_svg]:text-[var(--hui-color-foreground-base-primary)]\"\n)\nconst labelledControl = \"min-h-8 gap-[6px] px-[10px]\"\nconst iconControl = \"size-8\"\n\ntype OverflowToolbarContextValue = {\n  store: OverflowToolbarItemStore\n  collapsedIds: ReadonlySet<string>\n  menuSections: readonly OverflowMenuSection[]\n  /** Called while a More button is mounted. Without one, nothing collapses. */\n  registerMore: () => () => void\n  setMenuOpen: (isOpen: boolean) => void\n}\n\nconst OverflowToolbarContext = React.createContext<OverflowToolbarContextValue | null>(null)\n\nfunction useOverflowToolbar(part: string) {\n  const context = React.useContext(OverflowToolbarContext)\n  if (!context) throw new Error(`${part} must be used inside OverflowToolbar.`)\n  return context\n}\n\nconst OverflowToolbarGroupContext = React.createContext<{ id: string; label: string } | null>(null)\n\n/* -------------------------------------------------------------------------- */\n/* Focus                                                                      */\n/* -------------------------------------------------------------------------- */\n\ntype FocusOrigin = { kind: \"item\"; id: string } | { kind: \"more\" }\n\nfunction findItemControl(root: HTMLElement, id: string) {\n  return root.querySelector<HTMLElement>(`[${itemAttribute}=\"${CSS.escape(id)}\"]:not([hidden])`)\n}\n\n/** Which of the toolbar's own controls has focus, if any. */\nfunction readFocusOrigin(root: HTMLElement): FocusOrigin | null {\n  const active = document.activeElement\n  if (!(active instanceof HTMLElement) || !root.contains(active)) return null\n  if (active.hasAttribute(moreAttribute)) return { kind: \"more\" }\n\n  const id = active.getAttribute(itemAttribute)\n  return id === null ? null : { kind: \"item\", id }\n}\n\n/**\n * Moving an action removes the control that showed it. If that control had\n * focus, the browser drops focus to the page; put it on the control that now\n * stands for the action instead.\n */\nfunction repairFocus(root: HTMLElement, origin: FocusOrigin, lastRestoredId: string | undefined) {\n  const active = document.activeElement\n  if (active !== null && active !== document.body) return\n\n  const more = root.querySelector<HTMLElement>(`[${moreAttribute}]`)\n  const target =\n    origin.kind === \"item\"\n      ? (findItemControl(root, origin.id) ?? more)\n      : (more ?? (lastRestoredId === undefined ? null : findItemControl(root, lastRestoredId)))\n\n  target?.focus()\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport type OverflowToolbarProps = Omit<\n  React.ComponentProps<typeof Toolbar>,\n  \"orientation\" | \"ref\"\n>\n\n/**\n * A horizontal toolbar that fills its container and moves actions into the\n * More menu when they stop fitting. It measures its own box, so it follows a\n * sidebar opening or a panel resizing as well as the window.\n */\nfunction OverflowToolbar({ className, children, ...props }: OverflowToolbarProps) {\n  const rootRef = React.useRef<HTMLDivElement>(null)\n  const [store] = React.useState(createOverflowToolbarItemStore)\n  const items = React.useSyncExternalStore(store.subscribe, store.getItems, store.getItems)\n  const [hasMore, setHasMore] = React.useState(false)\n  const [collapsedCount, setCollapsedCount] = React.useState(0)\n\n  const collapseOrder = React.useMemo(() => getCollapseOrder(items), [items])\n  const collapsibleCount = hasMore ? collapseOrder.length : 0\n  const collapsedIds = React.useMemo(\n    () => new Set(collapseOrder.slice(0, Math.min(collapsedCount, collapsibleCount))),\n    [collapseOrder, collapsedCount, collapsibleCount]\n  )\n  const menuSections = React.useMemo(\n    () => getOverflowMenuSections(items, collapsedIds),\n    [items, collapsedIds]\n  )\n\n  const fitState = React.useRef(initialOverflowFitState)\n  /** What the DOM currently shows; a step is only valid for the layout it measured. */\n  const rendered = React.useRef({ collapsedCount, collapsibleCount, collapseOrder })\n  const isMenuOpen = React.useRef(false)\n  const focusOrigin = React.useRef<FocusOrigin | null>(null)\n\n  const fit = React.useCallback(() => {\n    const root = rootRef.current\n    const current = fitState.current\n    if (!root || current.collapsedCount !== rendered.current.collapsedCount) return\n\n    const next = stepOverflowFit(current, {\n      width: root.clientWidth,\n      overflows: root.scrollWidth > root.clientWidth,\n      collapsibleCount: rendered.current.collapsibleCount,\n      canRestore: !isMenuOpen.current,\n    })\n    fitState.current = next\n\n    if (next.collapsedCount === current.collapsedCount) {\n      focusOrigin.current = null\n      return\n    }\n\n    focusOrigin.current ??= readFocusOrigin(root)\n    setCollapsedCount(next.collapsedCount)\n  }, [])\n\n  const forgetFailedCount = React.useCallback(() => {\n    fitState.current = { ...fitState.current, failedCount: null }\n  }, [])\n\n  const observation = React.useRef<{ observer: ResizeObserver; targets: Set<Element> } | null>(\n    null\n  )\n\n  React.useLayoutEffect(() => {\n    if (typeof ResizeObserver === \"undefined\") return\n\n    const widths = new WeakMap<Element, number>()\n    const observer = new ResizeObserver((entries) => {\n      for (const entry of entries) {\n        const width = entry.target.getBoundingClientRect().width\n        const previous = widths.get(entry.target)\n        widths.set(entry.target, width)\n        // An action changed size, so a count that overflowed before may fit now.\n        if (previous !== undefined && previous !== width && entry.target !== rootRef.current) {\n          forgetFailedCount()\n        }\n      }\n      // Render before the browser paints, so no frame shows the toolbar clipped.\n      flushSync(fit)\n    })\n    observation.current = { observer, targets: new Set() }\n\n    return () => {\n      observer.disconnect()\n      observation.current = null\n    }\n  }, [fit, forgetFailedCount])\n\n  React.useLayoutEffect(() => {\n    const root = rootRef.current\n    if (!root) return\n\n    const itemElements = Array.from(root.querySelectorAll<HTMLElement>(`[${itemAttribute}]`))\n    store.reorder(itemElements.map((element) => element.getAttribute(itemAttribute) ?? \"\"))\n\n    // The root reports the space it has; each action reports its own size.\n    if (observation.current) {\n      const { observer, targets: previousTargets } = observation.current\n      const targets = new Set<Element>([root, ...itemElements])\n      for (const element of previousTargets) {\n        if (!targets.has(element)) observer.unobserve(element)\n      }\n      for (const element of targets) {\n        if (!previousTargets.has(element)) observer.observe(element)\n      }\n      observation.current.targets = targets\n    }\n\n    if (rendered.current.collapseOrder.join(\"\\n\") !== collapseOrder.join(\"\\n\")) forgetFailedCount()\n    rendered.current = { collapsedCount, collapsibleCount, collapseOrder }\n\n    if (focusOrigin.current) repairFocus(root, focusOrigin.current, collapseOrder[0])\n    fit()\n  })\n\n  const registerMore = React.useCallback(() => {\n    setHasMore(true)\n    return () => setHasMore(false)\n  }, [])\n\n  const setMenuOpen = React.useCallback(\n    (isOpen: boolean) => {\n      isMenuOpen.current = isOpen\n      if (isOpen) return\n\n      // Focus is still in the closing menu and is about to return to the More\n      // button. If this fit removes the button first, the repair needs to know that.\n      if (!rootRef.current?.contains(document.activeElement)) focusOrigin.current = { kind: \"more\" }\n      fit()\n    },\n    [fit]\n  )\n\n  const context = React.useMemo(\n    () => ({ store, collapsedIds, menuSections, registerMore, setMenuOpen }),\n    [store, collapsedIds, menuSections, registerMore, setMenuOpen]\n  )\n\n  return (\n    <OverflowToolbarContext.Provider value={context}>\n      <Toolbar\n        ref={rootRef}\n        data-slot=\"overflow-toolbar\"\n        // If the pinned actions alone are too wide, they scroll instead of being cut off.\n        className={cn(\n          // A hairline surface around 32px controls: 4px inset, 2px between controls.\n          \"w-full min-w-0 gap-[2px] overflow-x-auto overflow-y-clip rounded-[var(--hui-radius-2)] border-[var(--hui-color-border-base-primary)] bg-[var(--hui-color-background-base-primary)] p-[var(--hui-space-2)]\",\n          className\n        )}\n        {...props}\n      >\n        {children}\n      </Toolbar>\n    </OverflowToolbarContext.Provider>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Group                                                                      */\n/* -------------------------------------------------------------------------- */\n\nexport type OverflowToolbarGroupProps = Omit<\n  React.ComponentProps<typeof ToolbarGroup>,\n  \"aria-label\" | \"aria-labelledby\"\n> & {\n  /** Names the group for assistive technology and heads its actions in the More menu. */\n  label: string\n}\n\n/**\n * Related actions that stay together in the toolbar and in the menu. A rule\n * divides the group from visible content before it, and the group disappears\n * with its rule once every action in it has collapsed.\n */\nfunction OverflowToolbarGroup({ label, className, ...props }: OverflowToolbarGroupProps) {\n  const id = React.useId()\n  const group = React.useMemo(() => ({ id, label }), [id, label])\n\n  return (\n    <OverflowToolbarGroupContext.Provider value={group}>\n      <ToolbarGroup\n        aria-label={label}\n        className={cn(\n          \"gap-[2px] [&:not(:has(>:not([hidden])))]:hidden\",\n          \"before:mx-[var(--hui-space-2)] before:hidden before:h-[var(--hui-space-5)] before:w-px before:shrink-0 before:bg-[var(--hui-color-border-base-primary)] before:content-[''] forced-colors:before:bg-[CanvasText]\",\n          \"[:is([data-overflow-toolbar-group]:has(>:not([hidden])),:not([hidden],[data-overflow-toolbar-group]))~&]:before:block\",\n          className\n        )}\n        {...props}\n        data-overflow-toolbar-group=\"\"\n      />\n    </OverflowToolbarGroupContext.Provider>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/* Item                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport type OverflowToolbarItemProps = {\n  /** The action's name, shown in the toolbar and in the More menu. */\n  label: string\n  /** Decorative; the label carries the name. */\n  icon?: React.ReactNode\n  /**\n   * `\"always\"` keeps the action in the toolbar. A number ranks it against the\n   * other actions: the lowest number moves into the menu first.\n   */\n  priority?: OverflowPriority\n  /** Shows only the icon in the toolbar. The label becomes the accessible name and a tooltip. */\n  iconOnly?: boolean\n  disabled?: boolean\n  onSelect?: () => void\n  /** Identifies the action. Set it when you need a stable value to target in tests. */\n  id?: string\n  /** Applied to the toolbar button, not to the menu item. */\n  className?: string\n}\n\n/** One action. It renders as a toolbar button while it fits and as a menu item when it does not. */\nfunction OverflowToolbarItem({\n  label,\n  icon,\n  priority = defaultOverflowPriority,\n  iconOnly = false,\n  disabled = false,\n  onSelect,\n  id: idProp,\n  className,\n}: OverflowToolbarItemProps) {\n  const { store, collapsedIds } = useOverflowToolbar(\"OverflowToolbarItem\")\n  const group = React.useContext(OverflowToolbarGroupContext)\n  const generatedId = React.useId()\n  const id = idProp ?? generatedId\n\n  // The handler is usually a new closure on each render; the menu calls the latest.\n  const onSelectRef = React.useRef(onSelect)\n  const select = React.useCallback(() => onSelectRef.current?.(), [])\n\n  React.useLayoutEffect(() => {\n    onSelectRef.current = onSelect\n    store.upsert({\n      id,\n      priority,\n      label,\n      icon,\n      disabled,\n      groupId: group?.id ?? null,\n      groupLabel: group?.label ?? null,\n      select,\n    })\n  })\n\n  React.useLayoutEffect(() => () => store.remove(id), [store, id])\n\n  if (collapsedIds.has(id)) {\n    // Keeps the action's place in the document order while it is in the menu.\n    return <span hidden data-overflow-toolbar-item={id} />\n  }\n\n  const showsLabel = !iconOnly || icon == null\n  const control = (\n    <ToolbarButton\n      render={<Button variant=\"link\" size={showsLabel ? \"sm\" : \"icon-sm\"} />}\n      aria-label={showsLabel ? undefined : label}\n      disabled={disabled}\n      // A disabled action stays reachable, so it can still be found and read out.\n      focusableWhenDisabled\n      className={cn(controlClassName, showsLabel ? labelledControl : iconControl, className)}\n      onClick={select}\n      data-overflow-toolbar-item={id}\n    >\n      {icon}\n      {showsLabel && label}\n    </ToolbarButton>\n  )\n\n  if (showsLabel) return control\n\n  return (\n    <Tooltip>\n      <TooltipTrigger render={control} />\n      <TooltipPopup sideOffset={8}>{label}</TooltipPopup>\n    </Tooltip>\n  )\n}\n\n/* -------------------------------------------------------------------------- */\n/* More                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport type OverflowToolbarMoreProps = {\n  /** The button's name. Shown as its text unless `children` replace it. */\n  label?: string\n  /** Replaces the visible text, for example with an icon. `label` stays as the accessible name. */\n  children?: React.ReactNode\n  /** Applied to the toolbar button. */\n  className?: string\n}\n\n/**\n * The menu that holds collapsed actions. Place it where the button should\n * appear, usually last. It renders nothing while every action fits.\n */\nfunction OverflowToolbarMore(props: OverflowToolbarMoreProps) {\n  const { menuSections, registerMore } = useOverflowToolbar(\"OverflowToolbarMore\")\n\n  React.useLayoutEffect(() => registerMore(), [registerMore])\n\n  return menuSections.length === 0 ? null : <OverflowToolbarMenu sections={menuSections} {...props} />\n}\n\nfunction OverflowToolbarMenu({\n  sections,\n  label = \"More\",\n  children,\n  className,\n}: OverflowToolbarMoreProps & { sections: readonly OverflowMenuSection[] }) {\n  const { setMenuOpen } = useOverflowToolbar(\"OverflowToolbarMore\")\n\n  // The button can leave while its menu is open; restoring must not stay paused.\n  React.useEffect(() => () => setMenuOpen(false), [setMenuOpen])\n\n  return (\n    <Menu\n      onOpenChange={(isOpen) => {\n        if (isOpen) setMenuOpen(true)\n      }}\n      // Restoring waits until the menu has closed and focus is back on the button.\n      onOpenChangeComplete={(isOpen) => {\n        if (!isOpen) setMenuOpen(false)\n      }}\n    >\n      <ToolbarButton\n        render={<MenuTrigger render={<Button variant=\"link\" size=\"sm\" />} />}\n        aria-label={children == null ? undefined : label}\n        className={cn(\n          controlClassName,\n          children == null ? cn(labelledControl, \"gap-[var(--hui-space-2)]\") : iconControl,\n          // Pushed to the end of the bar, wherever it sits in the markup.\n          \"ms-auto\",\n          className\n        )}\n        data-overflow-toolbar-more=\"\"\n      >\n        {children ?? (\n          <>\n            {label}\n            <ChevronDownIcon aria-hidden=\"true\" className=\"size-3.5!\" />\n          </>\n        )}\n      </ToolbarButton>\n      <MenuPopup\n        align=\"end\"\n        // The menu belongs to the toolbar's React tree, so its key presses reach\n        // the toolbar too, which would move focus along the toolbar and out of the menu.\n        onKeyDown={(event) => {\n          if (toolbarNavigationKeys.has(event.key)) event.stopPropagation()\n        }}\n      >\n        {sections.map((section, index) => (\n          <React.Fragment key={section.key}>\n            {index > 0 && <MenuSeparator />}\n            <MenuGroup>\n              {section.label !== null && <MenuGroupLabel>{section.label}</MenuGroupLabel>}\n              {section.items.map((item) => (\n                <MenuItem key={item.id} disabled={item.disabled} onClick={item.select}>\n                  {item.icon}\n                  {item.label}\n                </MenuItem>\n              ))}\n            </MenuGroup>\n          </React.Fragment>\n        ))}\n      </MenuPopup>\n    </Menu>\n  )\n}\n\nexport { OverflowToolbar, OverflowToolbarGroup, OverflowToolbarItem, OverflowToolbarMore }\n"},{"path":"overflow-toolbar-types.ts","type":"registry:component","target":"components/ui/overflow-toolbar/overflow-toolbar-types.ts","content":"import type * as React from \"react\"\n\n/**\n * `\"always\"` keeps the action in the toolbar. A number ranks it against the\n * other actions: the lowest number moves into the menu first.\n */\nexport type OverflowPriority = \"always\" | number\n\n/** What the toolbar knows about one action, wherever it is currently shown. */\nexport type OverflowToolbarItemRecord = {\n  id: string\n  priority: OverflowPriority\n  label: string\n  icon: React.ReactNode\n  disabled: boolean\n  /** The group the action sits in, or `null` when it is a direct child of the toolbar. */\n  groupId: string | null\n  groupLabel: string | null\n  select: () => void\n}\n\nexport type OverflowToolbarItemStore = {\n  /** Every registered action, in the order the actions appear in the document. */\n  getItems: () => readonly OverflowToolbarItemRecord[]\n  subscribe: (listener: () => void) => () => void\n  /** Adds the action, or replaces it when any of its fields changed. */\n  upsert: (record: OverflowToolbarItemRecord) => void\n  remove: (id: string) => void\n  /** Sorts the actions to match `ids`. Actions missing from `ids` go last. */\n  reorder: (ids: readonly string[]) => void\n}\n\nexport type OverflowFitState = {\n  /** How many actions, counted from the start of the collapse order, are in the menu. */\n  collapsedCount: number\n  /** A count that overflowed, and the toolbar width it overflowed at. */\n  failedCount: { collapsedCount: number; width: number } | null\n}\n\n/** One reading of the rendered toolbar. */\nexport type OverflowMeasurement = {\n  /** The toolbar's inner width in CSS pixels. */\n  width: number\n  /** The content is wider than the toolbar. */\n  overflows: boolean\n  /** How many actions are allowed to collapse. */\n  collapsibleCount: number\n  /** `false` holds actions in the menu, which keeps an open menu from changing under the pointer. */\n  canRestore: boolean\n}\n\n/** A run of collapsed actions that share a group, as the menu lists them. */\nexport type OverflowMenuSection = {\n  key: string\n  /** The group's label, or `null` for actions outside any group. */\n  label: string | null\n  items: readonly OverflowToolbarItemRecord[]\n}\n"},{"path":"overflow-toolbar-utils.ts","type":"registry:component","target":"components/ui/overflow-toolbar/overflow-toolbar-utils.ts","content":"import type {\n  OverflowFitState,\n  OverflowMeasurement,\n  OverflowMenuSection,\n  OverflowToolbarItemRecord,\n  OverflowToolbarItemStore,\n} from \"./overflow-toolbar-types\"\n\nexport const defaultOverflowPriority = 0\n\nexport const initialOverflowFitState: OverflowFitState = {\n  collapsedCount: 0,\n  failedCount: null,\n}\n\nconst comparedFields = [\n  \"priority\",\n  \"label\",\n  \"icon\",\n  \"disabled\",\n  \"groupId\",\n  \"groupLabel\",\n  \"select\",\n] as const satisfies readonly (keyof OverflowToolbarItemRecord)[]\n\n/**\n * Holds the actions outside React state, so an action can report its latest\n * props on every render without re-rendering the toolbar when nothing changed.\n */\nexport function createOverflowToolbarItemStore(): OverflowToolbarItemStore {\n  let items: readonly OverflowToolbarItemRecord[] = []\n  const listeners = new Set<() => void>()\n\n  function replaceItems(next: readonly OverflowToolbarItemRecord[]) {\n    items = next\n    listeners.forEach((listener) => listener())\n  }\n\n  return {\n    getItems: () => items,\n    subscribe(listener) {\n      listeners.add(listener)\n      return () => {\n        listeners.delete(listener)\n      }\n    },\n    upsert(record) {\n      const index = items.findIndex((item) => item.id === record.id)\n\n      if (index === -1) {\n        replaceItems([...items, record])\n        return\n      }\n\n      const current = items[index]\n      if (comparedFields.every((field) => Object.is(current[field], record[field]))) return\n\n      replaceItems(items.map((item) => (item.id === record.id ? record : item)))\n    },\n    remove(id) {\n      if (items.some((item) => item.id === id)) {\n        replaceItems(items.filter((item) => item.id !== id))\n      }\n    },\n    reorder(ids) {\n      const position = new Map(ids.map((id, index) => [id, index]))\n      const positionOf = (item: OverflowToolbarItemRecord) => position.get(item.id) ?? ids.length\n      // Array sorting is stable, so actions missing from `ids` keep their relative order.\n      const sorted = [...items].sort((a, b) => positionOf(a) - positionOf(b))\n\n      if (sorted.some((item, index) => item !== items[index])) replaceItems(sorted)\n    },\n  }\n}\n\n/**\n * The ids of the actions that may collapse, first to collapse first: lowest\n * priority, and among equals the one nearest the end of the toolbar.\n */\nexport function getCollapseOrder(items: readonly OverflowToolbarItemRecord[]): string[] {\n  return items\n    .flatMap((item, position) =>\n      item.priority === \"always\" ? [] : [{ id: item.id, priority: item.priority, position }]\n    )\n    .sort((a, b) => a.priority - b.priority || b.position - a.position)\n    .map((item) => item.id)\n}\n\n/**\n * Decides the next count from one reading of the toolbar. The toolbar renders\n * the result and measures again, until a reading returns the same count.\n *\n * An overflow collapses one more action. A fit tries one fewer, because only\n * rendering shows whether the action has room; `failedCount` remembers the\n * attempt that overflowed, so the same width is not tried twice.\n */\nexport function stepOverflowFit(\n  state: OverflowFitState,\n  measurement: OverflowMeasurement\n): OverflowFitState {\n  const collapsedCount = Math.min(state.collapsedCount, measurement.collapsibleCount)\n\n  if (measurement.overflows) {\n    return {\n      // Once only pinned actions are left there is nothing more to collapse.\n      collapsedCount: Math.min(collapsedCount + 1, measurement.collapsibleCount),\n      failedCount: { collapsedCount, width: measurement.width },\n    }\n  }\n\n  const restoredCount = collapsedCount - 1\n  const isKnownToOverflow =\n    state.failedCount !== null &&\n    state.failedCount.collapsedCount === restoredCount &&\n    measurement.width <= state.failedCount.width\n\n  if (collapsedCount === 0 || !measurement.canRestore || isKnownToOverflow) {\n    return { collapsedCount, failedCount: state.failedCount }\n  }\n\n  return { collapsedCount: restoredCount, failedCount: state.failedCount }\n}\n\n/**\n * The collapsed actions in document order, split where the group changes, so\n * the menu can repeat the toolbar's grouping.\n */\nexport function getOverflowMenuSections(\n  items: readonly OverflowToolbarItemRecord[],\n  collapsedIds: ReadonlySet<string>\n): OverflowMenuSection[] {\n  const sections: { key: string; label: string | null; items: OverflowToolbarItemRecord[] }[] = []\n  let lastGroupId: string | null | undefined\n\n  for (const item of items) {\n    if (!collapsedIds.has(item.id)) continue\n\n    const last = sections.at(-1)\n    if (last && item.groupId === lastGroupId) {\n      last.items.push(item)\n      continue\n    }\n\n    sections.push({ key: item.groupId ?? item.id, label: item.groupLabel, items: [item] })\n    lastGroupId = item.groupId\n  }\n\n  return sections\n}\n"}],"dependencies":["honestui","react-dom"],"registryDependencies":["https://www.honestui.com/r/button.json","https://www.honestui.com/r/menu.json","https://www.honestui.com/r/toolbar.json","https://www.honestui.com/r/tooltip.json"]}