{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "breadcrumb",
  "title": "Breadcrumb",
  "description": "The trail of pages that leads to this one, with the Navigation menu's highlight gliding between its links. When it runs out of room, the crumbs after the first fold into a Menu behind “…”, the earliest first, and unfold as room comes back.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/menu.json",
    "https://kinoui.com/r/highlight.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/breadcrumb.tsx",
      "content": "'use client'\n\nimport { Menu, MenuContent, MenuItem, MenuTrigger } from '@/registry/components/kino/menu'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport { followPointer, highlightClassName, itemMatching } from '@/registry/lib/highlight'\nimport { flattenChildren } from '@/registry/lib/swap'\nimport { mergeProps, type PartProps, renderElement } from '@ui-sdk/react/primitive'\nimport {\n  cloneElement,\n  type ComponentProps,\n  isValidElement,\n  type MouseEvent,\n  type ReactElement,\n  useCallback,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * The trail of pages that leads to this one. The crumbs are the Navigation\n * menu's links, smaller: one highlight glides between them. When the trail\n * runs out of room, the crumbs after the first fold into a menu behind \"…\",\n * the earliest first, so the first page and the pages nearest this one stay.\n */\n\n/**\n * The trail's landmark. It is as wide as the trail would be whole, and no\n * wider than its container, so the trail has room to unfold as it grows.\n */\nfunction Breadcrumb({\n  className,\n  'aria-label': label = 'Breadcrumb',\n  ...props\n}: ComponentProps<'nav'>) {\n  return (\n    <nav\n      data-slot='breadcrumb'\n      aria-label={label}\n      className={cn('w-(--breadcrumb-width) max-w-full min-w-0', className)}\n      {...props}\n    />\n  )\n}\n\n/**\n * The crumbs and their separators, in order. It puts \"…\" after the first\n * crumb and folds the ones that don't fit into its menu. Crumbs are its own\n * children, or in fragments or arrays, so it can find them. `overflowLabel`\n * names \"…\" for a screen reader.\n */\nfunction BreadcrumbList({\n  className,\n  children,\n  overflowLabel = 'Show hidden pages',\n  ...props\n}: ComponentProps<'ol'> & { overflowLabel?: string }) {\n  const track = useCallback((list: HTMLOListElement | null) => {\n    if (!list) return\n    return fitTrail(list)\n  }, [])\n  const highlight = useCallback((layer: HTMLLIElement | null) => {\n    const list = layer?.parentElement\n    if (!layer || !list) return\n    return followPointer(list, layer, {\n      itemOf: itemMatching(list, CRUMB_TARGETS),\n      current: '[data-breadcrumb-ellipsis][data-open]',\n      focus: true,\n    })\n  }, [])\n  return (\n    <ol\n      ref={track}\n      data-slot='breadcrumb-list'\n      className={cn(\n        'group/breadcrumb text-muted-foreground relative isolate flex min-w-0 list-none flex-nowrap items-center gap-0.5 text-sm font-medium',\n        className,\n      )}\n      {...props}\n    >\n      <li\n        ref={highlight}\n        aria-hidden\n        data-slot='breadcrumb-highlight'\n        className={cn(\n          highlightClassName,\n          'bg-muted -z-10 forced-colors:bg-[Highlight] forced-colors:forced-color-adjust-none',\n        )}\n      />\n      {withOverflow(children, overflowLabel)}\n    </ol>\n  )\n}\n\nfunction BreadcrumbItem({ className, ...props }: ComponentProps<'li'>) {\n  return (\n    <li\n      data-slot='breadcrumb-item'\n      // The page you're on gives way first; the crumbs before it keep their names.\n      // Before the trail is first measured, as the page loads, every crumb gives\n      // way, so a long trail never spills out of its container.\n      className={cn(\n        'inline-flex shrink-0 items-center group-not-data-fitted/breadcrumb:min-w-0 group-not-data-fitted/breadcrumb:shrink group-not-data-fitted/breadcrumb:overflow-hidden data-collapsed:hidden [&:has(>[aria-current=page])]:min-w-0 [&:has(>[aria-current=page])]:shrink',\n        className,\n      )}\n      {...props}\n    />\n  )\n}\n\n/*\n * A crumb's box: the xs control's height and sides, as an xs Button's, so the\n * highlight under it is the shape of a small control at every density.\n */\nconst crumbClassName =\n  \"inline-flex h-(--control-height-xs) max-w-full min-w-0 items-center gap-1 rounded-(--control-radius-xs) px-[calc(var(--control-padding)*0.8)] whitespace-nowrap [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n\nconst crumbLinkClassName =\n  'transition-colors duration-(--motion-press-duration) ease-(--motion-press-fade-easing) select-none hover:text-foreground focus-visible:ring-3 focus-visible:ring-ring/50 focus-visible:outline-hidden data-glided:text-foreground forced-colors:data-glided:text-[HighlightText] forced-colors:data-glided:forced-color-adjust-none forced-colors:data-glided:**:text-[HighlightText]'\n\n/** A page on the way here. It renders an `<a>`; `render` swaps it for a router's link. */\nfunction BreadcrumbLink({\n  className,\n  render,\n  ...props\n}: Omit<PartProps<'a'>, 'className'> & { className?: string }) {\n  return renderElement(\n    'a',\n    mergeProps(\n      {\n        'data-slot': 'breadcrumb-link',\n        className: cn(crumbClassName, crumbLinkClassName, className),\n      },\n      props,\n    ),\n    render,\n  )\n}\n\n/**\n * The page you're on: not a link, and `aria-current='page'`. A long name\n * truncates, and shows whole in a tooltip under the pointer.\n */\nfunction BreadcrumbPage({ className, children, ...props }: ComponentProps<'span'>) {\n  return (\n    <CutTooltip\n      render={\n        <span\n          data-slot='breadcrumb-page'\n          aria-current='page'\n          className={cn(crumbClassName, 'text-foreground', className)}\n          {...props}\n        >\n          <span data-cut className='truncate'>\n            {children}\n          </span>\n        </span>\n      }\n    />\n  )\n}\n\n/** The mark between two crumbs: a chevron that points along the trail, or your own children. */\nfunction BreadcrumbSeparator({ className, children, ...props }: ComponentProps<'li'>) {\n  return (\n    <li\n      data-slot='breadcrumb-separator'\n      role='presentation'\n      aria-hidden\n      className={cn(\n        \"text-muted-foreground/70 inline-flex shrink-0 items-center data-collapsed:hidden [&_svg:not([class*='size-'])]:size-4 rtl:[&>svg]:rotate-180\",\n        className,\n      )}\n      {...props}\n    >\n      {children ?? (\n        <IconPlaceholder\n          lucide='ChevronRightIcon'\n          tabler='IconChevronRight'\n          hugeicons='ArrowRight01Icon'\n          phosphor='CaretRightIcon'\n          remixicon='RiArrowRightSLine'\n          aria-hidden\n        />\n      )}\n    </li>\n  )\n}\n\n/** What the highlight glides between: the links and \"…\". */\nconst CRUMB_TARGETS = '[data-slot=breadcrumb-link],[data-breadcrumb-ellipsis]'\n\n/** A folded crumb, as its row in the menu: its name, and the link or button it stands for. */\ninterface FoldedCrumb {\n  readonly label: string\n  readonly href: string | null\n  readonly link: HTMLElement | null\n}\n\n/** Whether a click opens a link somewhere else: a new tab or window, or a download. */\nfunction opensElsewhere(event: MouseEvent) {\n  return (\n    event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey\n  )\n}\n\n/*\n * \"…\" and the separator after it. Its menu lists the folded crumbs, read when\n * it opens. A row is a link to the same page; a plain click goes through the\n * crumb's own link, so a router's link still handles it.\n */\nfunction BreadcrumbOverflow({\n  label,\n  separator,\n}: {\n  label: string\n  separator: ReactElement<ComponentProps<'li'>>\n}) {\n  const [folded, setFolded] = useState<readonly FoldedCrumb[]>([])\n  const item = useRef<HTMLLIElement>(null)\n  return (\n    <>\n      {/* Folded until the trail needs it, so it never shows before the trail is measured. */}\n      <li\n        ref={item}\n        data-slot='breadcrumb-overflow'\n        data-collapsed=''\n        className='inline-flex shrink-0 items-center data-collapsed:hidden'\n      >\n        <Menu\n          onOpenChange={(open) => {\n            const list = item.current?.parentElement\n            if (!open || !list) return\n            item.current?.setAttribute('data-menu', '')\n            setFolded(foldedCrumbs(list))\n          }}\n          onOpenChangeComplete={(open) => {\n            // The menu hands focus back to \"…\" once it has gone: refit after that.\n            if (!open)\n              requestAnimationFrame(() => item.current?.removeAttribute('data-menu'))\n          }}\n        >\n          <MenuTrigger\n            data-breadcrumb-ellipsis=''\n            aria-label={label}\n            className={cn(\n              crumbClassName,\n              crumbLinkClassName,\n              'data-open:text-foreground',\n            )}\n          >\n            <IconPlaceholder\n              lucide='EllipsisIcon'\n              tabler='IconDots'\n              hugeicons='MoreHorizontalIcon'\n              phosphor='DotsThreeIcon'\n              remixicon='RiMoreLine'\n              aria-hidden\n            />\n          </MenuTrigger>\n          <MenuContent>\n            {folded.map((crumb, index) =>\n              crumb.href === null ? (\n                // A crumb that is a button, such as a chart's way back out, is a row that presses it.\n                <MenuItem\n                  // oxlint-disable-next-line react/no-array-index-key -- the folded crumbs keep their order\n                  key={index}\n                  disabled={!crumb.link}\n                  onSelect={() => crumb.link?.click()}\n                >\n                  {crumb.label}\n                </MenuItem>\n              ) : (\n                <MenuItem\n                  // oxlint-disable-next-line react/no-array-index-key -- the folded crumbs keep their order\n                  key={index}\n                  render={\n                    // The row gives the link its content.\n                    // oxlint-disable-next-line jsx-a11y/control-has-associated-label, jsx-a11y/anchor-has-content\n                    <a\n                      href={crumb.href}\n                      onClick={(event) => {\n                        if (!crumb.link || opensElsewhere(event)) return\n                        event.preventDefault()\n                        crumb.link.click()\n                      }}\n                    />\n                  }\n                >\n                  {crumb.label}\n                </MenuItem>\n              ),\n            )}\n          </MenuContent>\n        </Menu>\n      </li>\n      {cloneElement(separator, {\n        'data-collapsed': '',\n      } as ComponentProps<'li'>)}\n    </>\n  )\n}\n\n/**\n * The children with \"…\" and a copy of the first separator after the first\n * crumb's separator; unchanged when there is no first separator.\n */\nfunction withOverflow(children: ComponentProps<'ol'>['children'], label: string) {\n  const parts = flattenChildren(children)\n  const first = parts.findIndex(\n    (part) => isValidElement(part) && part.type === BreadcrumbItem,\n  )\n  const separator = parts[first + 1]\n  if (\n    first === -1 ||\n    !isValidElement<ComponentProps<'li'>>(separator) ||\n    separator.type !== BreadcrumbSeparator\n  ) {\n    return parts\n  }\n  return [\n    ...parts.slice(0, first + 2),\n    <BreadcrumbOverflow key='breadcrumb-overflow' label={label} separator={separator} />,\n    ...parts.slice(first + 2),\n  ]\n}\n\n/** The crumbs folded now, in order, read from the list. */\nfunction foldedCrumbs(list: Element): FoldedCrumb[] {\n  return Array.from(\n    list.querySelectorAll<HTMLElement>(\n      ':scope > [data-slot=breadcrumb-item][data-collapsed]',\n    ),\n    (crumb) => {\n      const link = crumb.querySelector<HTMLElement>('[data-slot=breadcrumb-link]')\n      return {\n        label: (link?.getAttribute('aria-label') ?? crumb.textContent ?? '').trim(),\n        href: link?.getAttribute('href') ?? null,\n        link,\n      }\n    },\n  )\n}\n\n/*\n * Folds the crumbs that don't fit and unfolds them as room comes back, and\n * gives the trail the width it would take whole, as `--breadcrumb-width`, so\n * a row that sizes to its content still offers it the room to unfold. It\n * folds in the frame the room changes, before it paints. Kept outside any\n * component: it writes attributes React doesn't own.\n */\nfunction fitTrail(list: HTMLOListElement) {\n  const nav = list.parentElement\n  let frame = 0\n  const fit = () => {\n    cancelAnimationFrame(frame)\n    const overflow = list.querySelector<HTMLElement>(\n      ':scope > [data-slot=breadcrumb-overflow]',\n    )\n    const trigger = overflow?.querySelector<HTMLElement>('[data-breadcrumb-ellipsis]')\n    // While \"…\" has its menu open or closing, what it lists stays folded, so\n    // focus has \"…\" to come back to; the menu settling refits.\n    if (overflow?.hasAttribute('data-menu')) return\n    // Everything shows while it is measured, in one task, so nothing paints\n    // in between and every width is current.\n    for (const part of list.querySelectorAll(':scope > [data-collapsed]')) {\n      part.removeAttribute('data-collapsed')\n    }\n    list.dataset.fitted = ''\n    const crumbs = Array.from(\n      list.querySelectorAll<HTMLElement>(':scope > [data-slot=breadcrumb-item]'),\n    )\n    // Each crumb is measured at its whole width, the page's name untruncated,\n    // with nothing allowed to shrink for the moment.\n    for (const crumb of crumbs) crumb.style.flexShrink = '0'\n    const widths = crumbs.map((crumb) => crumb.getBoundingClientRect().width)\n    for (const crumb of crumbs) crumb.style.removeProperty('flex-shrink')\n    const separator = list.querySelector<HTMLElement>(\n      ':scope > [data-slot=breadcrumb-separator]',\n    )\n    const trail = {\n      crumbs: widths,\n      separator: separator ? separator.getBoundingClientRect().width : 0,\n      overflow: overflow ? overflow.getBoundingClientRect().width : 0,\n      gap: Number.parseFloat(getComputedStyle(list).columnGap) || 0,\n    }\n    nav?.style.setProperty('--breadcrumb-width', `${Math.ceil(trailWidth(trail, 0))}px`)\n    const folded = overflow ? foldedCount({ ...trail, room: list.clientWidth }) : 0\n    const focused = document.activeElement\n    let lostFocus = false\n    crumbs.forEach((crumb, index) => {\n      if (index < 1 || index > folded) return\n      crumb.setAttribute('data-collapsed', '')\n      const after = crumb.nextElementSibling\n      if (after?.matches('[data-slot=breadcrumb-separator]')) {\n        after.setAttribute('data-collapsed', '')\n      }\n      if (focused && crumb.contains(focused)) lostFocus = true\n    })\n    if (overflow && folded === 0) {\n      overflow.setAttribute('data-collapsed', '')\n      overflow.nextElementSibling?.setAttribute('data-collapsed', '')\n    }\n    // A crumb that folds with focus in it hands focus to \"…\", where it went;\n    // \"…\" folding away with focus hands it to the first crumb it gave back.\n    if (lostFocus) trigger?.focus({ preventScroll: true })\n    else if (folded === 0 && focused && overflow?.contains(focused)) {\n      crumbs[1]\n        ?.querySelector<HTMLElement>('a, button, [tabindex]')\n        ?.focus({ preventScroll: true })\n    }\n  }\n  // The room changing refits at once, before the frame paints. A crumb that\n  // changes size refits a frame later: its fit may resize the trail, which\n  // the observer can't report back within the same frame.\n  const room = new ResizeObserver(fit)\n  const sizes = new ResizeObserver(() => {\n    cancelAnimationFrame(frame)\n    frame = requestAnimationFrame(fit)\n  })\n  const watch = () => {\n    sizes.disconnect()\n    for (const child of list.children) sizes.observe(child)\n  }\n  const changes = new MutationObserver(() => {\n    watch()\n    fit()\n  })\n  changes.observe(list, {\n    childList: true,\n    subtree: true,\n    characterData: true,\n    attributeFilter: ['data-menu'],\n  })\n  if (nav) room.observe(nav)\n  watch()\n  fit()\n  return () => {\n    cancelAnimationFrame(frame)\n    room.disconnect()\n    sizes.disconnect()\n    changes.disconnect()\n  }\n}\n\n/** The crumbs' widths, a separator's, \"…\"'s and the gap between any two, in px. */\ninterface Trail {\n  readonly crumbs: readonly number[]\n  readonly separator: number\n  readonly overflow: number\n  readonly gap: number\n}\n\n/**\n * How wide the trail is with `folded` crumbs after the first folded into\n * \"…\": the crumbs left, a separator after each but the last, \"…\" and its own\n * separator when anything is folded, and a gap between every two of those.\n */\nexport function trailWidth({ crumbs, separator, overflow, gap }: Trail, folded: number) {\n  const shown = crumbs.filter((_, index) => index < 1 || index > folded)\n  const marks = shown.length - 1 + (folded > 0 ? 1 : 0)\n  const parts = shown.length + marks + (folded > 0 ? 1 : 0)\n  const widths = shown.reduce((sum, width) => sum + width, 0)\n  return (\n    widths +\n    marks * separator +\n    (folded > 0 ? overflow : 0) +\n    Math.max(0, parts - 1) * gap\n  )\n}\n\n/**\n * How many crumbs after the first fold into \"…\" for the trail to fit in\n * `room`: none when it fits whole, and never the first or the last. With too\n * little room even then, the fold that leaves the trail narrowest, and the\n * last crumb truncates; a fold that would only widen it, as a crumb no wider\n * than \"…\" would, never happens. Half a pixel of slack absorbs rounding.\n */\nexport function foldedCount(trail: Trail & { readonly room: number }) {\n  const most = Math.max(0, trail.crumbs.length - 2)\n  let narrowest = 0\n  for (let folded = 0; folded <= most; folded++) {\n    const width = trailWidth(trail, folded)\n    if (width <= trail.room + 0.5) return folded\n    if (width < trailWidth(trail, narrowest)) narrowest = folded\n  }\n  return narrowest\n}\n\nexport {\n  Breadcrumb,\n  BreadcrumbItem,\n  BreadcrumbLink,\n  BreadcrumbList,\n  BreadcrumbPage,\n  BreadcrumbSeparator,\n}\n",
      "type": "registry:component",
      "target": "@components/kino/breadcrumb.tsx"
    }
  ],
  "type": "registry:component"
}