{"slug":"breadcrumb","name":"Animated Breadcrumb","description":"Composable breadcrumb navigation with soft path transitions, a hoverable overflow dropdown for long trails, custom separators, and router-link support.","category":"motion","source_url":"https://beui.dev/r/breadcrumb/raw","detail_url":"https://beui.dev/r/breadcrumb","raw_url":"https://beui.dev/r/breadcrumb/raw","page_url":"https://beui.dev/components/motion/breadcrumb","markdown_url":"https://beui.dev/components/motion/breadcrumb.md","published_at":"2026-09-27","updated_at":"2026-11-28","dependencies":["clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["@/components/motion/breadcrumb","@/components/motion/popover-morph","@/components/motion/popover-position","@/lib/ease","@/lib/focusable","@/lib/hooks/use-dismiss","@/lib/hooks/use-hover-capable","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/utils"],"install_slugs":["breadcrumb"],"requires_theme":false,"props":[{"displayName":"Breadcrumb","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"BreadcrumbList","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"BreadcrumbLink","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"BreadcrumbPage","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"BreadcrumbSeparator","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]},{"displayName":"BreadcrumbEllipsis","props":[{"name":"children","type":"ReactNode","required":true,"defaultValue":null,"description":"Hidden BreadcrumbItems, in path order."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the wrapper around the ellipsis button."},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the ellipsis button. Default: \"Show hidden paths\""}]},{"displayName":"BreadcrumbItem","props":[{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]}],"types":[],"files":[{"path":"components/motion/breadcrumb.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/motion/breadcrumb\n\nimport { ChevronRight, Ellipsis } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  motion,\n  useIsPresent,\n  useReducedMotion,\n  type HTMLMotionProps,\n} from \"motion/react\";\nimport {\n  Children,\n  createContext,\n  useContext,\n  forwardRef,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type ReactNode,\n  useId,\n  type ComponentPropsWithRef,\n  type ReactElement,\n} from \"react\";\nimport { MorphPopover, MorphPopoverContent, MorphPopoverTrigger } from \"@/components/motion/popover-morph\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const breadcrumbMessages = {\n  label: \"Breadcrumb\",\n  showHidden: \"Show hidden paths\",\n};\n\nexport type BreadcrumbMessages = typeof breadcrumbMessages;\n\nconst BreadcrumbLabels = createContext<Partial<BreadcrumbMessages> | undefined>(undefined);\n\nfunction useBreadcrumbMessages() {\n  return useMessages(\"breadcrumb\", breadcrumbMessages, useContext(BreadcrumbLabels));\n}\n\nexport type BreadcrumbProps = ComponentPropsWithRef<\"nav\"> & {\n  /** Override any built-in string. */\n  labels?: Partial<BreadcrumbMessages>;\n};\n\n/** A navigation landmark. Keep it mounted while the route changes. */\nexport function Breadcrumb({ className, children, labels, ...props }: BreadcrumbProps) {\n  const id = useId();\n  const t = useMessages(\"breadcrumb\", breadcrumbMessages, labels);\n  return (\n    <nav aria-label={t(\"label\")} {...props} className={cn(\"min-w-0\", className)}>\n      <BreadcrumbLabels.Provider value={labels}>\n        <LayoutGroup id={id}>{children}</LayoutGroup>\n      </BreadcrumbLabels.Provider>\n    </nav>\n  );\n}\n\nexport type BreadcrumbListProps = ComponentPropsWithRef<\"ol\"> & {\n  /** Maximum visible slots, including the ellipsis. Minimum 3; Infinity disables collapsing. */\n  maxItems?: number;\n  /** Accessible label for the hidden ancestor disclosure. */\n  overflowLabel?: string;\n};\n\n/** Pass keyed BreadcrumbItems directly so entering and leaving routes animate. */\nexport function BreadcrumbList({ className, children, maxItems = 4, overflowLabel, ...props }: BreadcrumbListProps) {\n  const items = Children.toArray(children);\n  const limit = Number.isFinite(maxItems) ? Math.max(3, Math.floor(maxItems)) : 4;\n  const collapse = maxItems !== Infinity && items.length > limit;\n  const tailCount = limit - 2;\n  const visible = collapse ? [\n    items[0],\n    <BreadcrumbItem key=\"breadcrumb-overflow\">\n      <BreadcrumbSeparator />\n      <BreadcrumbEllipsis label={overflowLabel}>\n        {items.slice(1, -tailCount)}\n      </BreadcrumbEllipsis>\n    </BreadcrumbItem>,\n    ...items.slice(-tailCount),\n  ] : items;\n  return (\n    <ol\n      {...props}\n      className={cn(\"relative flex flex-wrap items-center gap-x-1 gap-y-1 text-sm\", className)}\n    >\n      <AnimatePresence initial={false} mode=\"popLayout\">{visible}</AnimatePresence>\n    </ol>\n  );\n}\n\nexport type BreadcrumbItemProps = HTMLMotionProps<\"li\">;\n\n/** Use a stable route key; put its optional separator inside this item. */\nexport const BreadcrumbItem = forwardRef<HTMLLIElement, BreadcrumbItemProps>(\n  function BreadcrumbItem({ className, style, children, ...props }, ref) {\n    const reduce = useReducedMotion();\n    const present = useIsPresent();\n    const itemRef = useRef<HTMLLIElement>(null);\n    useLayoutEffect(() => {\n      const item = itemRef.current;\n      if (!item || !present) return;\n      const measure = () => {\n        // popLayout snapshots offsetWidth (integer pixels). Retain the exact\n        // width so a fractional-pixel loss cannot wrap the final character.\n        item.style.setProperty(\"--breadcrumb-exit-width\", `${item.getBoundingClientRect().width}px`);\n      };\n      measure();\n      const observer = new ResizeObserver(measure);\n      observer.observe(item);\n      return () => observer.disconnect();\n    }, [present]);\n    const hidden = { opacity: 0, y: reduce ? 0 : 6 };\n    return (\n      <motion.li\n        ref={(node) => {\n          itemRef.current = node;\n          if (typeof ref === \"function\") return ref(node);\n          if (ref) ref.current = node;\n        }}\n        layout={reduce ? false : \"position\"}\n        initial={hidden}\n        animate={{ opacity: 1, y: 0 }}\n        exit={hidden}\n        transition={{ duration: 0.2, ease: EASE_OUT, layout: SPRING_LAYOUT }}\n        {...props}\n        inert={!present}\n        aria-hidden={!present || undefined}\n        style={{\n          ...style,\n          minWidth: present ? style?.minWidth : \"var(--breadcrumb-exit-width)\",\n          pointerEvents: present ? style?.pointerEvents : \"none\",\n        }}\n        className={cn(\"relative inline-flex min-w-0 max-w-full items-center gap-1\", className)}\n      >\n        {children}\n      </motion.li>\n    );\n  },\n);\n\nexport type BreadcrumbLinkProps = ComponentPropsWithRef<\"a\"> & {\n  /** Render your router's Link, spreading these props onto it. */\n  render?: (props: ComponentPropsWithRef<\"a\">) => ReactElement;\n};\n\nexport function BreadcrumbLink({ className, render, ...props }: BreadcrumbLinkProps) {\n  const linkProps = {\n    ...props,\n    className: cn(\n      \"inline-flex min-h-8 min-w-0 items-center gap-1.5 rounded-full px-3 font-medium text-muted-foreground transition-colors duration-150 hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 [&>svg]:size-3.5 [&>svg]:shrink-0\",\n      className,\n    ),\n  };\n  return render ? render(linkProps) : <a {...linkProps} />;\n}\n\nexport type BreadcrumbPageProps = ComponentPropsWithRef<\"span\">;\n\nexport function BreadcrumbPage({ className, children, ...props }: BreadcrumbPageProps) {\n  return (\n    <span\n      {...props}\n      aria-current=\"page\"\n      className={cn(\n        \"relative isolate inline-flex min-h-8 min-w-0 items-center gap-1.5 rounded-full px-3 font-medium text-foreground [overflow-wrap:anywhere] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring [&>svg]:size-3.5 [&>svg]:shrink-0\",\n        className,\n      )}\n    >\n      {children}\n    </span>\n  );\n}\n\nexport type BreadcrumbSeparatorProps = ComponentPropsWithRef<\"span\">;\n\n/** Decorative separator, placed inside the following BreadcrumbItem. */\nexport function BreadcrumbSeparator({ className, children, ...props }: BreadcrumbSeparatorProps) {\n  return (\n    <span\n      {...props}\n      aria-hidden=\"true\"\n      data-breadcrumb-separator=\"\"\n      className={cn(\"inline-flex shrink-0 items-center text-muted-foreground/50 [&>svg]:size-3.5 rtl:rotate-180\", className)}\n    >\n      {children ?? <ChevronRight />}\n    </span>\n  );\n}\n\n\nexport interface BreadcrumbEllipsisProps {\n  /** Hidden BreadcrumbItems, in path order. */\n  children: ReactNode;\n  /** Classes merged onto the wrapper around the ellipsis button. */\n  className?: string;\n  /** Accessible name for the ellipsis button. Default: \"Show hidden paths\" */\n  label?: string;\n}\n\n/** Hover disclosure with click/touch toggle and keyboard access to ancestor links. */\nexport function BreadcrumbEllipsis({ children, className, label }: BreadcrumbEllipsisProps) {\n  const t = useBreadcrumbMessages();\n  const [open, setOpen] = useState(false);\n  const [placement, setPlacement] = useState<{ align: \"start\" | \"end\"; side: \"top\" | \"bottom\"; width: number }>({ align: \"start\", side: \"bottom\", width: 224 });\n  const canHover = useHoverCapable();\n  const present = useIsPresent();\n  const trigger = useRef<HTMLButtonElement>(null);\n  const panel = useRef<HTMLOListElement>(null);\n  const focusOnOpen = useRef(false);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useLayoutEffect(() => {\n    if (!open) return;\n    const update = () => {\n      const rect = trigger.current?.getBoundingClientRect();\n      if (!rect) return;\n      const right = window.innerWidth - rect.left - 8;\n      const left = rect.right - 8;\n      const align = right < 224 && left > right ? \"end\" : \"start\";\n      const below = window.innerHeight - rect.bottom;\n      setPlacement({\n        align,\n        side: below < 280 && rect.top > below ? \"top\" : \"bottom\",\n        width: Math.max(32, Math.min(224, align === \"start\" ? right : left)),\n      });\n    };\n    update();\n    window.addEventListener(\"resize\", update);\n    return () => window.removeEventListener(\"resize\", update);\n  }, [open]);\n\n  const cancelClose = () => {\n    if (closeTimer.current !== null) clearTimeout(closeTimer.current);\n    closeTimer.current = null;\n  };\n  const leave = () => {\n    cancelClose();\n    // Allow the pointer to cross the gap between the trigger and portal.\n    closeTimer.current = setTimeout(() => {\n      if (!panel.current?.contains(document.activeElement) && document.activeElement !== trigger.current) setOpen(false);\n    }, 160);\n  };\n  useEffect(() => () => {\n    if (closeTimer.current !== null) clearTimeout(closeTimer.current);\n  }, []);\n\n  useEffect(() => {\n    if (!open) return;\n    const onFocus = (event: FocusEvent) => {\n      if (event.target instanceof Node && event.target !== trigger.current && !panel.current?.contains(event.target)) setOpen(false);\n    };\n    document.addEventListener(\"focusin\", onFocus);\n    return () => document.removeEventListener(\"focusin\", onFocus);\n  }, [open]);\n\n  return (\n    <MorphPopover open={open && present} onOpenChange={setOpen} className={cn(className)}>\n      <span\n        onPointerEnter={(event) => {\n          cancelClose();\n          if (canHover && event.pointerType === \"mouse\") {\n            focusOnOpen.current = false;\n            setOpen(true);\n          }\n        }}\n        onPointerLeave={leave}\n      >\n        <MorphPopoverTrigger>\n          <button\n            ref={trigger}\n            type=\"button\"\n            aria-label={label ?? t(\"showHidden\")}\n            className=\"inline-flex size-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n            // Enter and Space open through MorphPopoverTrigger, which moves\n            // focus to the first path itself. ArrowDown opens without a click.\n            onKeyDown={(event) => {\n              if (event.key === \"ArrowDown\") {\n                event.preventDefault();\n                focusOnOpen.current = true;\n                setOpen(true);\n                panel.current?.querySelector<HTMLElement>(\"a[href],button\")?.focus();\n              }\n            }}\n          >\n            <Ellipsis aria-hidden=\"true\" className=\"size-4\" />\n          </button>\n        </MorphPopoverTrigger>\n        <MorphPopoverContent align={placement.align} side={placement.side} sideOffset={6} className=\"p-2\">\n          <BreadcrumbOverflowPaths\n            ref={panel}\n            style={{ width: placement.width - 18 }}\n            focusOnOpen={focusOnOpen}\n            onPointerEnter={() => { cancelClose(); setOpen(true); }}\n            onPointerLeave={leave}\n            onClick={(event) => {\n              if ((event.target as Element).closest(\"a[href]\")) setOpen(false);\n            }}\n          >\n            {children}\n          </BreadcrumbOverflowPaths>\n        </MorphPopoverContent>\n      </span>\n    </MorphPopover>\n  );\n}\n\nfunction BreadcrumbOverflowPaths({ focusOnOpen, ref, ...props }: ComponentPropsWithRef<\"ol\"> & { focusOnOpen: { current: boolean } }) {\n  const localRef = useRef<HTMLOListElement>(null);\n  useLayoutEffect(() => {\n    if (!focusOnOpen.current) return;\n    const focus = () => localRef.current?.querySelector<HTMLElement>(\"a[href],button\")?.focus();\n    focus();\n    // The portal becomes visible after its parent's layout measurement.\n    const frame = requestAnimationFrame(() => {\n      focus();\n      focusOnOpen.current = false;\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [focusOnOpen]);\n  return (\n    <ol\n      {...props}\n      ref={(node) => {\n        localRef.current = node;\n        if (typeof ref === \"function\") return ref(node);\n        if (ref) ref.current = node;\n      }}\n      className=\"flex max-h-64 flex-col gap-0.5 overflow-y-auto [&>li]:w-full [&_a]:w-full [&_a]:py-1 [&_a]:[overflow-wrap:anywhere] [&_[data-breadcrumb-separator]]:hidden\"\n    />\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  usePresence,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { FOCUSABLE_SELECTOR } from \"@/lib/focusable\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against - see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n  /** Arms or disarms moving focus into the panel as it next appears. */\n  armFocusOnOpen: (armed: boolean) => void;\n  /** Reads and disarms the flag set by `armFocusOnOpen`. */\n  takeFocusOnOpen: () => boolean;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Classes merged onto the wrapper around the trigger. */\n  className?: string;\n}\n\n/**\n * A popover whose full-size panel reveals from the corner nearest the trigger\n * on one spring, then retraces the same clip on close. Content and surface\n * edges keep their size throughout. Closes on outside pointer / Escape.\n * Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A keyboard open arms focus for the panel to take as it appears. Any later\n  // key or pointer press disarms it, so an open the parent declined cannot\n  // leave it armed for a later open that nobody asked to focus.\n  const focusOnOpenRef = useRef(false);\n  const disarmRef = useRef<AbortController | null>(null);\n  const armFocusOnOpen = useCallback((armed: boolean) => {\n    disarmRef.current?.abort();\n    disarmRef.current = null;\n    focusOnOpenRef.current = armed;\n    if (!armed) return;\n    const controller = new AbortController();\n    const disarm = () => {\n      focusOnOpenRef.current = false;\n      controller.abort();\n    };\n    const options = { capture: true, signal: controller.signal };\n    document.addEventListener(\"keydown\", disarm, options);\n    document.addEventListener(\"pointerdown\", disarm, options);\n    disarmRef.current = controller;\n  }, []);\n  const takeFocusOnOpen = useCallback(() => {\n    const armed = focusOnOpenRef.current;\n    armFocusOnOpen(false);\n    return armed;\n  }, [armFocusOnOpen]);\n  useEffect(() => () => disarmRef.current?.abort(), []);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element - a Tooltip wrapping the\n  // button, say - and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable - this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  // Inside is the root anchor and the portaled panel. Until the root mounts\n  // there is nothing to measure \"outside\" against, so nothing dismisses.\n  const insidePopover = useCallback(\n    (target: Element) =>\n      !root || root.contains(target) || Boolean(contentRef.current?.contains(target)),\n    [root],\n  );\n  useDismiss(open, close, null, { ignore: insidePopover });\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n      armFocusOnOpen,\n      takeFocusOnOpen,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child?.props?.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnKeyDown = child?.props?.onKeyDown as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnPointerDown = child?.props?.onPointerDown as\n    | ((e: unknown) => void)\n    | undefined;\n  // Set by an Enter or Space keydown on the trigger, cleared by a pointer\n  // press, read by the click that follows.\n  const keyboardRef = useRef(false);\n  const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)\n    ?.ref;\n  // Register once per actual ref change, not once per open-state render.\n  const mergedRef = useMemo(\n    () => mergeRefs(childRef, ctx.registerTrigger),\n    [childRef, ctx.registerTrigger],\n  );\n  if (!isValidElement(children)) return children;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergedRef,\n    onKeyDown: (e: unknown) => {\n      childOnKeyDown?.(e);\n      const key = (e as { key?: string } | undefined)?.key;\n      keyboardRef.current = key === \"Enter\" || key === \" \";\n    },\n    onPointerDown: (e: unknown) => {\n      childOnPointerDown?.(e);\n      keyboardRef.current = false;\n    },\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      // Enter and Space reach here as a click with `detail` 0 after their\n      // keydown on this element. A pointer click counts at least 1, and a\n      // scripted click() has no keydown before it. Only a keyboard open\n      // moves focus into the panel.\n      const keyboard =\n        keyboardRef.current &&\n        (e as { detail?: number } | undefined)?.detail === 0;\n      keyboardRef.current = false;\n      ctx.armFocusOnOpen(!ctx.open && keyboard);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\n// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow\n// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.\nconst MORPH_ENTER = { type: \"spring\", duration: 0.26, bounce: 0 } as const;\nconst MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;\n\n// Keep the panel and content at their final size. An inset clip reveals the\n// nearest corner without scaling borders, shadows or keyboard-focus geometry.\n// A full-size clip keeps content at its final coordinates without box-to-box\n// scale correction. One progress value keeps clip and opacity synchronized;\n// clip-path and the shadow may paint, so this is not a compositor-only morph.\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n  return `inset(${side === \"top\" ? inset : 0}% ${align === \"start\" ? inset : 0}% ${side === \"bottom\" ? inset : 0}% ${align === \"end\" ? inset : 0}% round ${radius}px)`;\n}\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  /** Preferred side of the trigger. Flips when there is no room. Default: \"bottom\" */\n  side?: Side;\n  /** Lines the panel up with the trigger's start or end edge. Default: \"end\" */\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */\n  radius?: number;\n  /** Draw the surface shadow. Default true. */\n  shadow?: boolean;\n  /**\n   * Runs after the portalled surface is positioned and visible. Passing it\n   * hands focus to the caller: the panel then moves no focus on its own.\n   */\n  onOpenAutoFocus?: (content: HTMLDivElement) => void;\n  /**\n   * Element to focus when the trigger opens the panel by keyboard. Defaults\n   * to the first focusable element in the panel, or the panel itself. A\n   * pointer open does not move focus. Ignored with `onOpenAutoFocus`.\n   */\n  initialFocus?: RefObject<HTMLElement | null>;\n  /** Classes merged onto the panel surface. */\n  className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const [portalReady, setPortalReady] = useState(false);\n  useEffect(() => setPortalReady(true), []);\n  if (!portalReady) return null;\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open && <MorphPopoverSurface {...props} />}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  shadow = true,\n  onOpenAutoFocus,\n  initialFocus,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [isPresent, safeToRemove] = usePresence();\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    isPresent,\n  );\n\n  const preferredLeft = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  // Keep larger compositions, such as calendars, inside the viewport. Prefer\n  // the requested side, then use the roomier side when it cannot fit there.\n  const gutter = 12;\n  const below = layout\n    ? Math.max(\n        0,\n        window.innerHeight -\n          layout.trigger.top -\n          layout.trigger.height -\n          sideOffset -\n          gutter,\n      )\n    : 0;\n  const above = layout\n    ? Math.max(0, layout.trigger.top - sideOffset - gutter)\n    : 0;\n  const requestedSpace = side === \"bottom\" ? below : above;\n  const otherSpace = side === \"bottom\" ? above : below;\n  const resolvedSide =\n    layout &&\n    layout.content.height > requestedSpace &&\n    otherSpace > requestedSpace\n      ? side === \"bottom\"\n        ? \"top\"\n        : \"bottom\"\n      : side;\n  const availableHeight = resolvedSide === \"bottom\" ? below : above;\n  const left = layout\n    ? Math.max(\n        gutter,\n        Math.min(\n          preferredLeft,\n          window.innerWidth - layout.content.width - gutter,\n        ),\n      )\n    : 0;\n  const top = layout\n    ? resolvedSide === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : Math.max(\n          gutter,\n          layout.trigger.top - layout.content.height - sideOffset,\n        )\n    : 0;\n\n  const progress = useMotionValue(0);\n  const clipPath = useTransform(progress, (p) =>\n    clipAt(resolvedSide, align, radius, 92 * (1 - p)),\n  );\n  const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);\n  // Reduced motion has no travel, so a short fade carries the whole entrance\n  // and exit on its own.\n  const fade = useMotionValue(reduce ? 0 : 1);\n  const ready = layout !== null;\n  const focusedOnOpen = useRef(false);\n  useEffect(() => {\n    if (\n      !ready ||\n      !isPresent ||\n      focusedOnOpen.current ||\n      !ctx.contentRef.current\n    )\n      return;\n    focusedOnOpen.current = true;\n    onOpenAutoFocus?.(ctx.contentRef.current);\n  }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n  // `safeToRemove` is a new function on every render: AnimatePresence\n  // rebuilds its context each time its parent renders. Read it through a ref\n  // so a render during the exit (a consumer's state change, a list streaming\n  // in) does not restart the exit from where it got to - restarted every\n  // render, it would close in ever smaller steps and never report completion,\n  // leaving an inert, invisible panel mounted for good.\n  const safeToRemoveRef = useRef(safeToRemove);\n  useLayoutEffect(() => {\n    safeToRemoveRef.current = safeToRemove;\n  });\n  useEffect(() => {\n    if (!ready) {\n      if (!isPresent) safeToRemoveRef.current?.();\n      return;\n    }\n    const settle = () => {\n      if (!isPresent) safeToRemoveRef.current?.();\n    };\n    if (reduce) {\n      progress.jump(1);\n      const animation = animate(fade, isPresent ? 1 : 0, {\n        duration: 0.12,\n        onComplete: settle,\n      });\n      return () => animation.stop();\n    }\n    const animation = animate(progress, isPresent ? 1 : 0, {\n      ...(isPresent ? MORPH_ENTER : MORPH_EXIT),\n      onComplete: settle,\n    });\n    return () => animation.stop();\n  }, [fade, progress, ready, isPresent, reduce]);\n\n  // The wrapper stays `visibility: hidden` until the first measurement, and\n  // focus() inside a hidden subtree is silently ignored. So move focus in the\n  // commit that makes the panel visible, not when it mounts. A CSS transition\n  // on `visibility` can still hold the controls hidden for a moment after\n  // that commit (a reduced-motion reset that gives every element a short\n  // transition-duration does), so while focus rests on the panel or has not\n  // moved, each such transition that ends tries the candidates again, until\n  // the user presses a key or pointer. The effect runs once per open, so it\n  // reads the caller's props through refs: a new ref or callback passed\n  // mid-open must not tear down a pending retry.\n  const initialFocusRef = useRef(initialFocus);\n  const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);\n  useLayoutEffect(() => {\n    initialFocusRef.current = initialFocus;\n    callerFocusesRef.current = onOpenAutoFocus !== undefined;\n  });\n  const { contentRef, takeFocusOnOpen } = ctx;\n  useLayoutEffect(() => {\n    if (!ready || !isPresent) return;\n    if (!takeFocusOnOpen() || callerFocusesRef.current) return;\n    const panel = contentRef.current;\n    const wrapper = panel?.parentElement;\n    if (!panel || !wrapper) return;\n    const from = document.activeElement;\n    const unmoved = () =>\n      document.activeElement === from || document.activeElement === panel;\n    // The selector also matches elements focus() refuses: a hidden input, a\n    // disabled button that carries a tabindex, anything under display: none.\n    // Keep the first candidate that takes focus, else hold it on the panel.\n    const focusFirst = () => {\n      const candidates = [\n        initialFocusRef.current?.current,\n        ...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ];\n      for (const candidate of candidates) {\n        if (!candidate) continue;\n        candidate.focus({ preventScroll: true });\n        if (unmoved()) continue;\n        // preventScroll keeps the page still, but it also stops the panel's\n        // own scroll area from bringing a row below the fold into view.\n        candidate.scrollIntoView?.({ block: \"nearest\" });\n        return true;\n      }\n      panel.focus({ preventScroll: true });\n      return false;\n    };\n    if (focusFirst()) return;\n    const retry = (event: TransitionEvent) => {\n      if (event.propertyName !== \"visibility\") return;\n      if (!unmoved() || focusFirst()) stop();\n    };\n    const stop = () => {\n      wrapper.removeEventListener(\"transitionend\", retry);\n      document.removeEventListener(\"keydown\", stop, true);\n      document.removeEventListener(\"pointerdown\", stop, true);\n    };\n    wrapper.addEventListener(\"transitionend\", retry);\n    document.addEventListener(\"keydown\", stop, true);\n    document.addEventListener(\"pointerdown\", stop, true);\n    return stop;\n  }, [ready, isPresent, contentRef, takeFocusOnOpen]);\n\n  return (\n    <motion.div\n      data-morph-popover-portal=\"\"\n      inert={!isPresent}\n      style={{\n        left,\n        top,\n        opacity: reduce ? fade : surfaceOpacity,\n        pointerEvents: isPresent ? \"auto\" : \"none\",\n        visibility: layout ? \"visible\" : \"hidden\",\n      }}\n      // A drop-shadow follows the clipped surface; box-shadow would be cut\n      // off by its own clip. Caller surface classes retain their old target.\n      className={cn(\n        \"fixed z-[9999]\",\n        shadow && \"[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\",\n      )}\n    >\n      <motion.div\n        ref={ctx.contentRef}\n        id={ctx.contentId}\n        role=\"dialog\"\n        aria-labelledby={ctx.triggerId}\n        tabIndex={-1}\n        style={{\n          clipPath: reduce ? undefined : clipPath,\n          borderRadius: radius,\n          maxHeight: layout ? availableHeight : undefined,\n          overflowX: \"hidden\",\n          overflowY: \"auto\",\n        }}\n        className={cn(\n          // The panel holds focus when nothing inside it can. An inset ring\n          // stays inside the clip that would cut off an outline.\n          \"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n          className,\n        )}\n      >\n        {children}\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * - gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"components/previews/motion/breadcrumb.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { ArrowUpRight, Folder, Home } from \"lucide-react\";\nimport { useLayoutEffect, useRef, useState } from \"react\";\nimport {\n  Breadcrumb,\n  BreadcrumbItem,\n  BreadcrumbLink,\n  BreadcrumbList,\n  BreadcrumbPage,\n  BreadcrumbSeparator,\n} from \"@/components/motion/breadcrumb\";\n\nconst PATH = [\"Workspace\", \"Projects\", \"Website\", \"Design system\", \"Components\", \"Navigation\", \"Breadcrumb\"];\n\nexport function BreadcrumbPreview() {\n  const [depth, setDepth] = useState(5);\n  const currentRef = useRef<HTMLSpanElement>(null);\n  const restoreFocus = useRef<number | null>(null);\n\n  useLayoutEffect(() => {\n    if (restoreFocus.current === depth) {\n      currentRef.current?.focus();\n      restoreFocus.current = null;\n    }\n  }, [depth]);\n\n  return (\n    <div className=\"w-full max-w-lg space-y-8 px-4\">\n      <Breadcrumb className=\"min-h-[4.25rem] sm:min-h-8\">\n        <BreadcrumbList maxItems={3}>\n          {PATH.slice(0, depth + 1).map((label, index) => (\n            <BreadcrumbItem key={label}>\n              {index > 0 && <BreadcrumbSeparator />}\n              {index === depth ? (\n                <BreadcrumbPage ref={currentRef} tabIndex={-1}>\n                  {index === 0 && <Home aria-hidden=\"true\" />}\n                  {label}\n                </BreadcrumbPage>\n              ) : (\n                <BreadcrumbLink\n                  href={`#${label.toLowerCase()}`}\n                  onClick={(event) => {\n                    if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;\n                    event.preventDefault();\n                    restoreFocus.current = index;\n                    setDepth(index);\n                  }}\n                >\n                  {index === 0 && <Home aria-hidden=\"true\" />}\n                  {label}\n                </BreadcrumbLink>\n              )}\n            </BreadcrumbItem>\n          ))}\n        </BreadcrumbList>\n      </Breadcrumb>\n      <div className=\"min-h-20 border-t border-border/60 pt-5\">\n        {depth < PATH.length - 1 ? (\n          <button\n            type=\"button\"\n            onClick={() => {\n              restoreFocus.current = depth + 1;\n              setDepth((value) => Math.min(value + 1, PATH.length - 1));\n            }}\n            className=\"flex w-full items-center gap-3 rounded-full border border-border/60 px-4 py-3 text-start text-sm transition-colors hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n          >\n            <Folder aria-hidden=\"true\" className=\"size-4 text-muted-foreground\" />\n            <span className=\"flex-1\">{PATH[depth + 1]}</span>\n            <ArrowUpRight aria-hidden=\"true\" className=\"size-3.5 text-muted-foreground\" />\n          </button>\n        ) : (\n          <p className=\"py-3 text-center text-sm text-muted-foreground\">Choose a parent path to go back.</p>\n        )}\n      </div>\n    </div>\n  );\n}\n"}]}