import { useEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react' import { ChevronRight } from 'lucide-react' import { cn } from '../lib/cn' import { focusRing } from '../lib/styles' export type BreadcrumbItem = { label: ReactNode /** Link target. The last item is the current page and never a link. */ href?: string /** Icon before the label. */ icon?: ReactNode } export type BreadcrumbProps = Omit, 'children'> & { items: BreadcrumbItem[] /** Replaces the chevron between items. */ separator?: ReactNode /** Collapse the middle items into "…" when there are more than this. */ maxItems?: number /** Items kept before the "…" when collapsed. */ itemsBeforeCollapse?: number /** Items kept after the "…" when collapsed. */ itemsAfterCollapse?: number } const linkClass = 'inline-flex items-center gap-1.5 rounded-sm text-fg-muted underline-offset-4 transition-colors hover:text-fg hover:underline [&_svg]:size-4 [&_svg]:shrink-0' /** Shows where the current page sits in the site hierarchy. */ export function Breadcrumb({ items, separator, maxItems, itemsBeforeCollapse = 1, itemsAfterCollapse = 2, className, 'aria-label': ariaLabel = 'Breadcrumb', ...props }: BreadcrumbProps) { const [expanded, setExpanded] = useState(false) const listRef = useRef(null) // After expanding, move focus to the first revealed item so it isn't lost with the "…" button. useEffect(() => { if (!expanded) return const revealed = listRef.current?.children[itemsBeforeCollapse] revealed?.querySelector('a, [aria-current]')?.focus() }, [expanded, itemsBeforeCollapse]) const collapse = !expanded && maxItems != null && items.length > maxItems && itemsBeforeCollapse + itemsAfterCollapse < items.length type Entry = { item: BreadcrumbItem; index: number } | 'ellipsis' const entries: Entry[] = items.map((item, index) => ({ item, index })) const visible: Entry[] = collapse ? [...entries.slice(0, itemsBeforeCollapse), 'ellipsis', ...entries.slice(items.length - itemsAfterCollapse)] : entries const sep = ( ) return ( ) }