{"slug":"message-scroller","name":"Message Scroller","description":"A reader-aware conversation viewport that follows streamed output at the live edge and releases control when the reader moves away.","category":"agents","source_url":"https://beui.dev/r/message-scroller/raw","detail_url":"https://beui.dev/r/message-scroller","raw_url":"https://beui.dev/r/message-scroller/raw","page_url":"https://beui.dev/components/agents/message-scroller","markdown_url":"https://beui.dev/components/agents/message-scroller.md","published_at":"2026-08-02","updated_at":"2026-11-28","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["../magnetic","./base","./context","./dropdown-menu/context","./dropdown-menu/item-base","./dropdown-menu/menu-panel","./dropdown-menu/placement","./engine","./magnetic","./metallic","./placement","./stateful","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./use-position","@/components/agents/agent-disclosure","@/components/agents/citations","@/components/agents/clip-resize-frame","@/components/agents/icon-swap","@/components/agents/message","@/components/agents/message-bubble","@/components/agents/message-context","@/components/agents/message-scroller","@/components/agents/prompt-input","@/components/agents/streaming-response","@/components/motion/button","@/components/motion/dropdown-menu","@/components/motion/menu/menu-item-highlight","@/components/motion/menu/use-menu-navigation","@/components/motion/popover-position","@/components/motion/preview-rail","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/components/previews/agents/chat-preview","@/lib/audio-context","@/lib/ease","@/lib/favicon","@/lib/hooks/use-copy","@/lib/hooks/use-dismiss","@/lib/hooks/use-favicon","@/lib/hooks/use-hover-capable","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-row-cursor","@/lib/hooks/use-tap-gesture","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/presence-gate","@/lib/sound","@/lib/sounds/close","@/lib/sounds/engine","@/lib/sounds/open","@/lib/sounds/press","@/lib/sounds/select","@/lib/touch","@/lib/utils"],"install_slugs":["message-scroller"],"requires_theme":true,"props":[{"displayName":"MessageScroller","props":[{"name":"followOutput","type":"boolean","required":false,"defaultValue":"true","description":"Keep streamed output pinned while the reader remains near the end."},{"name":"followThreshold","type":"number","required":false,"defaultValue":"56","description":"Distance from the end that still counts as following the output."},{"name":"smooth","type":"boolean","required":false,"defaultValue":"true","description":"Smoothly follow growing content."},{"name":"onFollowChange","type":"((following: boolean) => void)","required":false,"defaultValue":null,"description":"Reports when the reader leaves or returns to the live edge."},{"name":"label","type":"string","required":false,"defaultValue":null,"description":"Accessible label for the scrollable transcript."},{"name":"busy","type":"boolean","required":false,"defaultValue":null,"description":"Marks the transcript as waiting for more streamed content."},{"name":"navigation","type":"\"rail\"","required":false,"defaultValue":null,"description":"Adds a compact rail for navigating between rendered Message rows."},{"name":"jumpButton","type":"boolean","required":false,"defaultValue":"true","description":"Shows a button back to the latest message once the reader scrolls up. Default true."},{"name":"navigationLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible label for the optional message navigation rail."},{"name":"viewportClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the scrolling viewport."},{"name":"contentClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the log element that wraps the messages."},{"name":"railClassName","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the navigation rail, used with `navigation=\"rail\"`."},{"name":"viewportRef","type":"Ref<HTMLElement>","required":false,"defaultValue":null,"description":"Ref to the scrolling viewport element."},{"name":"viewportProps","type":"Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, \"children\" | \"className\" | \"ref\">","required":false,"defaultValue":null,"description":"Extra props for the scrolling viewport. Its event handlers still run."},{"name":"contentProps","type":"Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"children\" | \"className\" | \"ref\">","required":false,"defaultValue":null,"description":"Extra props for the log element that wraps the messages."},{"name":"labels","type":"Partial<{ label: string; jumpToLatest: string; navigationLabel: string; preview: string; goToUser: string; goToAssistant: string; goToMessage: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the root element."}]}],"types":[],"files":[{"path":"components/agents/message-scroller.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/message-scroller\n\nimport { ArrowDown } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  type Ref,\n  useCallback,\n  useEffect,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  PreviewRail,\n  type PreviewRailItem,\n} from \"@/components/motion/preview-rail\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n// The jump button rises in from the bottom edge and drops back out, faster.\nconst JUMP_IN = { duration: 0.2, ease: EASE_OUT } as const;\nconst JUMP_OUT = { duration: 0.14, ease: EASE_OUT } as const;\n\nexport const messageScrollerMessages = {\n  label: \"Conversation\",\n  jumpToLatest: \"Jump to latest\",\n  navigationLabel: \"Message navigation\",\n  preview: \"Message\",\n  goToUser: \"Go to user message {index} of {total}\",\n  goToAssistant: \"Go to assistant message {index} of {total}\",\n  goToMessage: \"Go to conversation message {index} of {total}\",\n};\n\nexport type MessageScrollerMessages = typeof messageScrollerMessages;\n\nconst PREVIEW_TITLE_LENGTH = 56;\nconst PREVIEW_DESCRIPTION_LENGTH = 88;\n\nfunction truncateMessageText(text: string, limit: number) {\n  if (text.length <= limit) return text;\n  const excerpt = text.slice(0, limit);\n  const boundary = excerpt.lastIndexOf(\" \");\n  return `${excerpt.slice(0, boundary > limit * 0.65 ? boundary : limit).trim()}…`;\n}\n\nfunction getMessageText(message: HTMLElement) {\n  const surface =\n    message.querySelector<HTMLElement>('[data-slot=\"message-bubble-content\"]') ??\n    message.querySelector<HTMLElement>('[data-slot=\"message-content\"]') ??\n    message;\n  return (surface.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n}\n\nfunction getMessagePreview(\n  message: HTMLElement,\n  emptyLabel: string,\n  assistantResponse?: HTMLElement,\n) {\n  const text = getMessageText(message);\n  if (!text) {\n    return { label: emptyLabel, description: undefined };\n  }\n\n  if (text.length <= PREVIEW_TITLE_LENGTH) {\n    const responseText = assistantResponse\n      ? getMessageText(assistantResponse)\n      : \"\";\n    return {\n      label: text,\n      description: responseText\n        ? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)\n        : undefined,\n    };\n  }\n\n  const titleExcerpt = text.slice(0, PREVIEW_TITLE_LENGTH);\n  const titleBoundary = titleExcerpt.lastIndexOf(\" \");\n  const titleEnd =\n    titleBoundary > PREVIEW_TITLE_LENGTH * 0.65\n      ? titleBoundary\n      : PREVIEW_TITLE_LENGTH;\n  const label = `${text.slice(0, titleEnd).trim()}…`;\n  const responseText = assistantResponse\n    ? getMessageText(assistantResponse)\n    : text.slice(titleEnd).trim();\n  return {\n    label,\n    description: responseText\n      ? truncateMessageText(responseText, PREVIEW_DESCRIPTION_LENGTH)\n      : undefined,\n  };\n}\n\nexport interface MessageScrollerProps extends ComponentPropsWithRef<\"div\"> {\n  /** Keep streamed output pinned while the reader remains near the end. */\n  followOutput?: boolean;\n  /** Distance from the end that still counts as following the output. */\n  followThreshold?: number;\n  /** Smoothly follow growing content. */\n  smooth?: boolean;\n  /** Reports when the reader leaves or returns to the live edge. */\n  onFollowChange?: (following: boolean) => void;\n  /** Accessible label for the scrollable transcript. */\n  label?: string;\n  /** Marks the transcript as waiting for more streamed content. */\n  busy?: boolean;\n  /** Adds a compact rail for navigating between rendered Message rows. */\n  navigation?: \"rail\";\n  /** Shows a button back to the latest message once the reader scrolls up. Default true. */\n  jumpButton?: boolean;\n  /** Accessible label for the optional message navigation rail. */\n  navigationLabel?: string;\n  /** Classes merged onto the scrolling viewport. */\n  viewportClassName?: string;\n  /** Classes merged onto the log element that wraps the messages. */\n  contentClassName?: string;\n  /** Classes merged onto the navigation rail, used with `navigation=\"rail\"`. */\n  railClassName?: string;\n  /** Ref to the scrolling viewport element. */\n  viewportRef?: Ref<HTMLElement>;\n  /** Extra props for the scrolling viewport. Its event handlers still run. */\n  viewportProps?: Omit<\n    ComponentPropsWithRef<\"section\">,\n    \"children\" | \"className\" | \"ref\"\n  >;\n  /** Extra props for the log element that wraps the messages. */\n  contentProps?: Omit<\n    ComponentPropsWithRef<\"div\">,\n    \"children\" | \"className\" | \"ref\"\n  >;\n  /** Override any built-in string. */\n  labels?: Partial<MessageScrollerMessages>;\n}\n\nexport function MessageScroller({\n  followOutput = true,\n  followThreshold = 56,\n  smooth = true,\n  onFollowChange,\n  label,\n  busy,\n  navigation,\n  jumpButton = true,\n  navigationLabel,\n  viewportClassName,\n  contentClassName,\n  railClassName,\n  viewportRef: externalViewportRef,\n  viewportProps,\n  contentProps,\n  className,\n  children,\n  labels,\n  ...props\n}: MessageScrollerProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"messageScroller\", messageScrollerMessages, labels);\n  // Read by the stable rail sync so inline `labels` don't rebuild it each render.\n  const tRef = useRef(t);\n  const viewportRef = useRef<HTMLElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  const followingRef = useRef(followOutput);\n  const programmaticScrollRef = useRef(false);\n  const scrollTimerRef = useRef<number | undefined>(undefined);\n  const frameRef = useRef<number | undefined>(undefined);\n  const railFrameRef = useRef<number | undefined>(undefined);\n  const railIdRef = useRef(new WeakMap<HTMLElement, string>());\n  const railIdCounterRef = useRef(0);\n  const railTargetsRef = useRef(new Map<string, HTMLElement>());\n  const [railItems, setRailItems] = useState<PreviewRailItem[]>([]);\n  const [activeRailId, setActiveRailId] = useState(\"\");\n  const [railOverflowing, setRailOverflowing] = useState(false);\n  // Mirrors followingRef for rendering: the jump button shows while false.\n  const [atLiveEdge, setAtLiveEdge] = useState(true);\n  const {\n    onScroll: onViewportScroll,\n    onWheel: onViewportWheel,\n    onTouchStart: onViewportTouchStart,\n    onKeyDown: onViewportKeyDown,\n    ...restViewportProps\n  } = viewportProps ?? {};\n\n  const setViewportRef = useCallback(\n    (node: HTMLElement | null) => {\n      viewportRef.current = node;\n      if (typeof externalViewportRef === \"function\") {\n        externalViewportRef(node);\n      } else if (externalViewportRef) {\n        externalViewportRef.current = node;\n      }\n    },\n    [externalViewportRef],\n  );\n\n  const setFollowing = useCallback(\n    (next: boolean) => {\n      if (followingRef.current === next) return;\n      followingRef.current = next;\n      setAtLiveEdge(next);\n      onFollowChange?.(next);\n    },\n    [onFollowChange],\n  );\n\n  const updateActiveRailItem = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    const viewport = viewportRef.current;\n    const targets = [...railTargetsRef.current.entries()];\n    if (!viewport || targets.length === 0) return;\n\n    const viewportRect = viewport.getBoundingClientRect();\n    if (viewport.scrollTop <= followThreshold) {\n      const firstId = targets[0]?.[0] ?? \"\";\n      setActiveRailId((current) => (current === firstId ? current : firstId));\n      return;\n    }\n\n    const distanceFromEnd =\n      viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;\n    if (distanceFromEnd <= followThreshold) {\n      const lastId = targets.at(-1)?.[0] ?? \"\";\n      setActiveRailId((current) => (current === lastId ? current : lastId));\n      return;\n    }\n\n    const viewportCenter = viewportRect.top + viewportRect.height / 2;\n    let nearestId = targets[0]?.[0] ?? \"\";\n    let nearestDistance = Number.POSITIVE_INFINITY;\n\n    for (const [id, element] of targets) {\n      const rect = element.getBoundingClientRect();\n      const messageCenter = rect.top + rect.height / 2;\n      const distance = Math.abs(messageCenter - viewportCenter);\n      if (distance < nearestDistance) {\n        nearestDistance = distance;\n        nearestId = id;\n      }\n    }\n\n    setActiveRailId((current) =>\n      current === nearestId ? current : nearestId,\n    );\n  }, [followThreshold, navigation]);\n\n  const syncRailItems = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    const content = contentRef.current;\n    const viewport = viewportRef.current;\n    if (!content || !viewport) return;\n\n    const messages = Array.from(\n      content.querySelectorAll<HTMLElement>('[data-slot=\"message\"]'),\n    );\n    const targets = new Map<string, HTMLElement>();\n    const nextItems = messages.map((message, index) => {\n      let id = railIdRef.current.get(message);\n      if (!id) {\n        railIdCounterRef.current += 1;\n        id = `message-rail-${railIdCounterRef.current}`;\n        railIdRef.current.set(message, id);\n      }\n      targets.set(id, message);\n      const sender = message.dataset.from ?? \"conversation\";\n      const assistantResponse =\n        sender === \"user\"\n          ? messages\n              .slice(index + 1)\n              .find((candidate) => candidate.dataset.from === \"assistant\")\n          : undefined;\n      const preview = getMessagePreview(\n        message,\n        tRef.current(\"preview\"),\n        assistantResponse,\n      );\n\n      return {\n        id,\n        label: preview.label,\n        description: preview.description,\n        ariaLabel: tRef.current(\n          sender === \"user\"\n            ? \"goToUser\"\n            : sender === \"assistant\"\n              ? \"goToAssistant\"\n              : \"goToMessage\",\n          { index: index + 1, total: messages.length },\n        ),\n      };\n    });\n\n    railTargetsRef.current = targets;\n    setRailItems((current) => {\n      const unchanged =\n        current.length === nextItems.length &&\n        current.every(\n          (item, index) =>\n            item.id === nextItems[index]?.id &&\n            item.label === nextItems[index]?.label &&\n            item.description === nextItems[index]?.description &&\n            item.ariaLabel === nextItems[index]?.ariaLabel,\n        );\n      return unchanged ? current : nextItems;\n    });\n    setRailOverflowing(\n      viewport.scrollHeight > viewport.clientHeight + 1 && messages.length > 1,\n    );\n  }, [navigation]);\n\n  const scheduleRailSync = useCallback(() => {\n    if (navigation !== \"rail\") return;\n    if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);\n    railFrameRef.current = requestAnimationFrame(() => {\n      syncRailItems();\n      updateActiveRailItem();\n    });\n  }, [navigation, syncRailItems, updateActiveRailItem]);\n\n  useLayoutEffect(() => {\n    tRef.current = t;\n    scheduleRailSync();\n  }, [t, scheduleRailSync]);\n\n  // A scroll this component started must not read as the reader scrolling\n  // away. A smooth scroll can outlast any fixed guess, so the flag clears on\n  // `scrollend`; the timer is the fallback where that event doesn't exist.\n  const releaseAfterScroll = useCallback(\n    (viewport: HTMLElement, behavior: ScrollBehavior) => {\n      if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      const release = () => {\n        programmaticScrollRef.current = false;\n        viewport.removeEventListener(\"scrollend\", release);\n        if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      };\n      if (behavior !== \"smooth\") {\n        scrollTimerRef.current = window.setTimeout(release, 0);\n        return;\n      }\n      const hasScrollEnd = \"onscrollend\" in window;\n      if (hasScrollEnd) viewport.addEventListener(\"scrollend\", release);\n      scrollTimerRef.current = window.setTimeout(release, hasScrollEnd ? 1200 : 320);\n    },\n    [],\n  );\n\n  const scrollToEnd = useCallback(\n    (behavior: ScrollBehavior) => {\n      const viewport = viewportRef.current;\n      if (!viewport) return;\n\n      programmaticScrollRef.current = true;\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({ top: viewport.scrollHeight, behavior });\n      } else {\n        viewport.scrollTop = viewport.scrollHeight;\n      }\n      releaseAfterScroll(viewport, behavior);\n    },\n    [releaseAfterScroll],\n  );\n\n  const handleScroll = useCallback(() => {\n    const viewport = viewportRef.current;\n    if (!viewport || programmaticScrollRef.current) return;\n\n    const distance =\n      viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;\n    setFollowing(distance <= followThreshold);\n    updateActiveRailItem();\n  }, [followThreshold, setFollowing, updateActiveRailItem]);\n\n  const leaveLiveEdge = useCallback(() => {\n    programmaticScrollRef.current = false;\n  }, []);\n\n  useLayoutEffect(() => {\n    followingRef.current = followOutput;\n    if (!followOutput) return;\n\n    frameRef.current = requestAnimationFrame(() => scrollToEnd(\"auto\"));\n    return () => {\n      if (frameRef.current) cancelAnimationFrame(frameRef.current);\n    };\n  }, [followOutput, scrollToEnd]);\n\n  useEffect(() => {\n    const content = contentRef.current;\n    if (!content || typeof ResizeObserver === \"undefined\") return;\n\n    const observer = new ResizeObserver(() => {\n      scheduleRailSync();\n      if (!followOutput || !followingRef.current) return;\n      scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n    });\n    observer.observe(content);\n\n    return () => observer.disconnect();\n  }, [followOutput, reduce, scheduleRailSync, scrollToEnd, smooth]);\n\n  useEffect(() => {\n    if (navigation !== \"rail\") {\n      railTargetsRef.current.clear();\n      setRailItems([]);\n      setRailOverflowing(false);\n      return;\n    }\n\n    const content = contentRef.current;\n    const viewport = viewportRef.current;\n    if (!content || !viewport) return;\n\n    scheduleRailSync();\n    const mutationObserver =\n      typeof MutationObserver === \"undefined\"\n        ? null\n        : new MutationObserver(scheduleRailSync);\n    mutationObserver?.observe(content, {\n      childList: true,\n      characterData: true,\n      subtree: true,\n    });\n\n    const resizeObserver =\n      typeof ResizeObserver === \"undefined\"\n        ? null\n        : new ResizeObserver(scheduleRailSync);\n    resizeObserver?.observe(content);\n    resizeObserver?.observe(viewport);\n\n    return () => {\n      mutationObserver?.disconnect();\n      resizeObserver?.disconnect();\n    };\n  }, [navigation, scheduleRailSync]);\n\n  useEffect(\n    () => () => {\n      if (scrollTimerRef.current) window.clearTimeout(scrollTimerRef.current);\n      if (frameRef.current) cancelAnimationFrame(frameRef.current);\n      if (railFrameRef.current) cancelAnimationFrame(railFrameRef.current);\n    },\n    [],\n  );\n\n  const scrollToRailItem = useCallback(\n    (item: PreviewRailItem) => {\n      const viewport = viewportRef.current;\n      const target = railTargetsRef.current.get(item.id);\n      if (!viewport || !target) return;\n\n      const lastItem = railItems.at(-1)?.id === item.id;\n      setActiveRailId(item.id);\n      if (lastItem) {\n        setFollowing(true);\n        scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n        return;\n      }\n\n      setFollowing(false);\n      programmaticScrollRef.current = true;\n      const viewportRect = viewport.getBoundingClientRect();\n      const targetRect = target.getBoundingClientRect();\n      const top =\n        viewport.scrollTop +\n        targetRect.top -\n        viewportRect.top -\n        (viewport.clientHeight - targetRect.height) / 2;\n      const behavior = reduce || !smooth ? \"auto\" : \"smooth\";\n\n      if (typeof viewport.scrollTo === \"function\") {\n        viewport.scrollTo({ top, behavior });\n      } else {\n        viewport.scrollTop = top;\n      }\n      releaseAfterScroll(viewport, behavior);\n    },\n    [railItems, reduce, releaseAfterScroll, scrollToEnd, setFollowing, smooth],\n  );\n\n  const viewport = (\n    <section\n      ref={setViewportRef}\n      aria-label={label ?? t(\"label\")}\n      {...restViewportProps}\n      onScroll={(event) => {\n        handleScroll();\n        onViewportScroll?.(event);\n      }}\n      onWheel={(event) => {\n        leaveLiveEdge();\n        onViewportWheel?.(event);\n      }}\n      onTouchStart={(event) => {\n        leaveLiveEdge();\n        onViewportTouchStart?.(event);\n      }}\n      onKeyDown={(event) => {\n        if ([\"ArrowUp\", \"PageUp\", \"Home\"].includes(event.key)) {\n          leaveLiveEdge();\n        }\n        onViewportKeyDown?.(event);\n      }}\n      className={cn(\n        \"h-full overflow-y-auto overscroll-contain outline-none [overflow-anchor:none] focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n        navigation === \"rail\"\n          ? \"[-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n          : \"[scrollbar-gutter:stable]\",\n        viewportClassName,\n        navigation === \"rail\" && railOverflowing && \"pr-10\",\n      )}\n    >\n      <div\n        ref={contentRef}\n        role=\"log\"\n        aria-live=\"polite\"\n        aria-relevant=\"additions text\"\n        aria-busy={busy}\n        className={contentClassName}\n        {...contentProps}\n      >\n        {children}\n      </div>\n    </section>\n  );\n\n  const jumpToLatest = () => {\n    setFollowing(true);\n    scrollToEnd(reduce || !smooth ? \"auto\" : \"smooth\");\n  };\n  const showJump = jumpButton && followOutput && !atLiveEdge;\n\n  return (\n    <div\n      data-slot=\"message-scroller\"\n      className={cn(\"relative min-h-0\", className)}\n      {...props}\n    >\n      {navigation === \"rail\" ? (\n        <PreviewRail\n          items={railOverflowing ? railItems : []}\n          label={navigationLabel ?? t(\"navigationLabel\")}\n          activeId={activeRailId}\n          onItemSelect={scrollToRailItem}\n          previewSide=\"before\"\n          highlightActive\n          itemSize={14}\n          className=\"h-full min-h-0 overflow-hidden\"\n          previewContainerClassName=\"right-8 left-3\"\n          previewClassName=\"mr-1 w-64 max-w-full [&_[data-slot=preview-rail-card]]:h-20 [&_[data-slot=preview-rail-card]]:overflow-hidden [&_[data-slot=preview-rail-card]]:p-3 [&_[data-slot=preview-rail-title]]:line-clamp-1 [&_[data-slot=preview-rail-title]]:text-xs [&_[data-slot=preview-rail-title]]:leading-4 [&_[data-slot=preview-rail-description]]:line-clamp-2 [&_[data-slot=preview-rail-description]]:text-xs [&_[data-slot=preview-rail-description]]:leading-4\"\n          railClassName={cn(\n            \"absolute inset-y-3 right-1 w-7 content-center py-1 [&_[data-slot=preview-rail-item]]:w-7 [&_[data-slot=preview-rail-item]]:justify-end [&_[data-slot=preview-rail-tick]]:h-px [&_[data-slot=preview-rail-tick]]:w-4 [&_[data-slot=preview-rail-tick]]:origin-right\",\n            railOverflowing\n              ? \"pointer-events-auto opacity-100\"\n              : \"pointer-events-none opacity-0\",\n            railClassName,\n          )}\n        >\n          {viewport}\n        </PreviewRail>\n      ) : (\n        viewport\n      )}\n      {/* Back to the live edge, once the reader has scrolled away from it. */}\n      <AnimatePresence>\n        {showJump ? (\n          <motion.div\n            key=\"jump\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.95 }}\n            animate={{ opacity: 1, y: 0, scale: 1, transition: JUMP_IN }}\n            exit={reduce ? { opacity: 0, transition: JUMP_OUT } : { opacity: 0, y: 8, scale: 0.95, transition: JUMP_OUT }}\n            className=\"pointer-events-none absolute inset-x-0 bottom-3 flex justify-center\"\n          >\n            <Tooltip content={t(\"jumpToLatest\")} side=\"top\">\n              <button\n                type=\"button\"\n                onClick={jumpToLatest}\n                aria-label={t(\"jumpToLatest\")}\n                // Card fill and the strong border: it floats over messages\n                // that share the background, and must read as a control.\n                className=\"pointer-events-auto inline-flex size-8 items-center justify-center rounded-full border border-(--color-border-strong) bg-card text-muted-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.97]\"\n              >\n                <ArrowDown aria-hidden=\"true\" className=\"size-4\" />\n              </button>\n            </Tooltip>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n"},{"path":"components/motion/preview-rail.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type MouseEvent,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\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 previewRailMessages = {\n  label: \"Section navigation\",\n};\n\nexport type PreviewRailMessages = typeof previewRailMessages;\n\nexport interface PreviewRailItem {\n  /** Unique key, used for the active item and passed to `onActiveChange`. */\n  id: string;\n  /** Title of the preview card and the tick's accessible name. */\n  label: string;\n  /** Accessible name for the tick when it should differ from `label`. */\n  ariaLabel?: string;\n  /** Muted text under the title in the preview card. */\n  description?: ReactNode;\n  /** Makes the tick a link; on touch, the first tap shows the preview. */\n  href?: string;\n  /** Link target for `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link `rel`. Default: \"noreferrer noopener\" when `target` is \"_blank\" */\n  rel?: string;\n}\n\nexport interface PreviewRailProps {\n  /** Rail entries, each a tick with a preview card and an optional link. */\n  items: PreviewRailItem[];\n  /** Accessible name for the rail's nav element. Default: \"Section navigation\" */\n  label?: string;\n  /** Lay the ticks out in a column or a row. Default: \"vertical\" */\n  orientation?: \"vertical\" | \"horizontal\";\n  /** The selected item id, for controlled use. */\n  activeId?: string;\n  /** The initial selected item id when uncontrolled. Default: the first item. */\n  defaultActiveId?: string;\n  /** Called with the item id when an item is selected. */\n  onActiveChange?: (id: string) => void;\n  /** Called with the item when it is clicked or tapped. */\n  onItemSelect?: (item: PreviewRailItem) => void;\n  /** Custom content for the hover card. Default: the item's label and description. */\n  renderPreview?: (item: PreviewRailItem) => ReactNode;\n  /** Show a preview card beside the hovered or focused tick. Default: true */\n  showPreview?: boolean;\n  /** Which side of the rail the vertical preview card sits on. Default: \"after\" */\n  previewSide?: \"before\" | \"after\";\n  /** Keep the selected tick lit when nothing is hovered or focused. Default: false */\n  highlightActive?: boolean;\n  /** Length of each tick's slot along the rail (px). Default: 24 */\n  itemSize?: number;\n  children?: ReactNode;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the nav element that holds the ticks. */\n  railClassName?: string;\n  /** Classes merged onto the layer that positions the preview cards. */\n  previewContainerClassName?: string;\n  /** Classes merged onto the wrapper around the shown preview card. */\n  previewClassName?: string;\n  /** Override any built-in string. */\n  labels?: Partial<PreviewRailMessages>;\n}\n\nfunction DefaultPreview({ item }: { item: PreviewRailItem }) {\n  return (\n    <div\n      data-slot=\"preview-rail-card\"\n      className=\"rounded-2xl border border-border bg-card p-4 shadow-sm\"\n    >\n      <p\n        data-slot=\"preview-rail-title\"\n        className=\"font-medium text-card-foreground\"\n      >\n        {item.label}\n      </p>\n      {item.description ? (\n        <div\n          data-slot=\"preview-rail-description\"\n          className=\"mt-1 text-sm leading-6 text-muted-foreground\"\n        >\n          {item.description}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n\nexport function PreviewRail({\n  items,\n  label: labelProp,\n  orientation = \"vertical\",\n  activeId,\n  defaultActiveId,\n  onActiveChange,\n  onItemSelect,\n  renderPreview,\n  showPreview = true,\n  previewSide = \"after\",\n  highlightActive = false,\n  itemSize = 24,\n  children,\n  className,\n  railClassName,\n  previewContainerClassName,\n  previewClassName,\n  labels,\n}: PreviewRailProps) {\n  const t = useMessages(\"previewRail\", previewRailMessages, labels);\n  const label = labelProp ?? t(\"label\");\n  const uid = useId();\n  const reduce = useReducedMotion();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [internalActiveId, setInternalActiveId] = useState(\n    defaultActiveId ?? items[0]?.id ?? \"\",\n  );\n  const [hoveredId, setHoveredId] = useState<string | null>(null);\n  // A finger cannot hover, so a tap lights the tick instead. Kept apart from\n  // the hovered one: they end in different ways, and a stray mouse move must\n  // not clear a tick the keyboard or a tap chose.\n  const [pinnedId, setPinnedId] = useState<string | null>(null);\n  const [focusedId, setFocusedId] = useState<string | null>(null);\n  // A click carries no pointerType, so the pointerdown before it is what says\n  // whether the activation was a tap. Keyboard activation has none at all.\n  const tap = useTapGesture<boolean>();\n  const hover = useHoverGesture();\n\n  const clearPinned = useCallback(() => setPinnedId(null), []);\n\n  // The next tap outside the rail stands in for the pointer leaving it. The\n  // card is a preview, so that tap passes through to whatever it landed on.\n  useDismiss(pinnedId !== null, clearPinned, rootRef);\n\n  const requestedActiveId = activeId ?? internalActiveId;\n  const selectedId = items.some((item) => item.id === requestedActiveId)\n    ? requestedActiveId\n    : (items[0]?.id ?? \"\");\n  const displayedId = hoveredId ?? pinnedId ?? focusedId ?? \"\";\n  const highlightedId = displayedId || (highlightActive ? selectedId : \"\");\n  const displayedIndex = items.findIndex((item) => item.id === highlightedId);\n  const rowTemplate = items.length\n    ? `repeat(${items.length}, ${itemSize}px)`\n    : undefined;\n  const isHorizontal = orientation === \"horizontal\";\n\n  const selectItem = (id: string) => {\n    if (activeId === undefined) setInternalActiveId(id);\n    onActiveChange?.(id);\n  };\n\n  return (\n    <motion.div\n      layoutRoot\n      ref={rootRef}\n      onBlur={(event) => {\n        // Both tick sources leave with the focus: a tap does not always land\n        // focus, but when it does, tabbing away must not strand the card.\n        if (!event.currentTarget.contains(event.relatedTarget)) {\n          setFocusedId(null);\n          setPinnedId(null);\n        }\n      }}\n      className={cn(\n        \"isolate relative flex w-full overflow-visible\",\n        isHorizontal\n          ? \"min-h-64 flex-col items-center justify-center\"\n          : \"min-h-80\",\n        className,\n      )}\n    >\n      <nav\n        aria-label={label}\n        onPointerLeave={(event) => {\n          // A touch pointer leaves on lift, which would clear the tick the tap\n          // just chose - that one is cleared by the outside tap instead.\n          if (hover.leave(event)) setHoveredId(null);\n        }}\n        style={\n          isHorizontal\n            ? { gridTemplateColumns: rowTemplate }\n            : { gridTemplateRows: rowTemplate }\n        }\n        className={cn(\n          \"relative z-10 grid shrink-0\",\n          isHorizontal\n            ? \"h-12 w-fit max-w-full self-center justify-center\"\n            : \"w-12 content-center\",\n          railClassName,\n        )}\n      >\n        {items.map((item, index) => {\n          const selected = item.id === selectedId;\n          const highlighted = item.id === highlightedId;\n          const distance =\n            displayedIndex < 0 ? Number.POSITIVE_INFINITY : Math.abs(index - displayedIndex);\n          const scale = highlighted\n            ? 1\n            : distance === 1\n              ? 0.68\n              : distance === 2\n                ? 0.44\n                : 0.25;\n\n          const itemContent = (\n            <>\n              <motion.span\n                data-slot=\"preview-rail-tick\"\n                aria-hidden=\"true\"\n                animate={isHorizontal ? { scaleY: scale } : { scaleX: scale }}\n                transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                className={cn(\n                  \"block bg-current\",\n                  isHorizontal\n                    ? \"h-12 w-0.5 origin-bottom\"\n                    : \"h-0.5 w-12 origin-left\",\n                  highlighted ? \"text-foreground\" : undefined,\n                )}\n              />\n            </>\n          );\n\n          const sharedClassName = cn(\n            \"relative flex text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n            isHorizontal\n              ? \"h-12 w-6 items-end justify-center\"\n              : \"h-6 w-12 items-center\",\n          );\n          const sharedStyle = isHorizontal\n            ? { width: itemSize }\n            : { height: itemSize };\n          const handlePointerEnter = (event: PointerEvent<HTMLElement>) => {\n            if (hover.enter(event)) setHoveredId(item.id);\n          };\n          const handlePointerDown = (event: PointerEvent<HTMLElement>) => {\n            tap.start(event, pinnedId === item.id);\n            setFocusedId(null);\n          };\n          // A gesture the platform takes away sends no click, and a key press\n          // starts an activation that never had a pointer behind it: either\n          // one leaves a record the next click would read as a tap of its own.\n          const dropGesture = () => tap.drop();\n          const handleFocus = (currentTarget: HTMLElement) => {\n            if (currentTarget.matches(\":focus-visible\")) {\n              setFocusedId(item.id);\n            }\n          };\n          const handleSelect = (event: MouseEvent<HTMLElement>) => {\n            const gesture = tap.take();\n            const tapped =\n              gesture !== null && gesture.pointerType !== \"mouse\";\n\n            if (tapped) {\n              // A link would otherwise show its preview and leave the page in\n              // the same tap, so the card is never read: the first tap lights\n              // the tick, the second follows the link.\n              if (item.href && !gesture.state) {\n                event.preventDefault();\n                setPinnedId(item.id);\n                return;\n              }\n              setPinnedId(item.id);\n            }\n\n            selectItem(item.id);\n            onItemSelect?.(item);\n          };\n\n          return item.href ? (\n            <a\n              key={item.id}\n              data-slot=\"preview-rail-item\"\n              href={item.href}\n              target={item.target}\n              rel={\n                item.rel ??\n                (item.target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n              }\n              aria-label={item.ariaLabel ?? item.label}\n              aria-current={selected ? \"page\" : undefined}\n              onPointerEnter={handlePointerEnter}\n              onPointerDown={handlePointerDown}\n              onPointerCancel={dropGesture}\n              onKeyDown={dropGesture}\n              onFocus={(event) => handleFocus(event.currentTarget)}\n              onClick={handleSelect}\n              style={sharedStyle}\n              className={sharedClassName}\n            >\n              {itemContent}\n            </a>\n          ) : (\n            <button\n              key={item.id}\n              data-slot=\"preview-rail-item\"\n              type=\"button\"\n              aria-label={item.ariaLabel ?? item.label}\n              aria-current={selected ? \"location\" : undefined}\n              onPointerEnter={handlePointerEnter}\n              onPointerDown={handlePointerDown}\n              onPointerCancel={dropGesture}\n              onKeyDown={dropGesture}\n              onFocus={(event) => handleFocus(event.currentTarget)}\n              onClick={handleSelect}\n              style={sharedStyle}\n              className={sharedClassName}\n            >\n              {itemContent}\n            </button>\n          );\n        })}\n      </nav>\n\n      {showPreview ? (\n        <div\n          aria-hidden=\"true\"\n          style={\n            isHorizontal\n              ? { gridTemplateColumns: rowTemplate }\n              : { gridTemplateRows: rowTemplate }\n          }\n          className={cn(\n            \"pointer-events-none absolute z-50 grid\",\n            isHorizontal\n              ? \"top-1/2 left-1/2 h-5 w-fit max-w-full -translate-x-1/2 -translate-y-1/2 justify-center\"\n              : previewSide === \"before\"\n                ? \"inset-y-0 right-16 left-4 content-center\"\n                : \"inset-y-0 right-4 left-16 content-center\",\n            previewContainerClassName,\n          )}\n        >\n          {items.map((item) => (\n            <div\n              key={item.id}\n              style={\n                isHorizontal ? { width: itemSize } : { height: itemSize }\n              }\n              className={cn(\n                \"relative flex items-center\",\n                isHorizontal ? \"justify-center\" : undefined,\n              )}\n            >\n              {item.id === displayedId ? (\n                <div\n                  className={cn(\n                    isHorizontal\n                      ? \"absolute bottom-12 left-1/2 w-72 -translate-x-1/2\"\n                      : cn(\n                          \"w-full max-w-sm\",\n                          previewSide === \"before\" && \"ml-auto\",\n                        ),\n                    previewClassName,\n                  )}\n                >\n                  <motion.div\n                    layoutId={`preview-rail-card-${uid}`}\n                    transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                  >\n                    <AnimatePresence mode=\"wait\" initial={false}>\n                      <motion.div\n                        key={item.id}\n                        initial={\n                          reduce\n                            ? { opacity: 0 }\n                            : { opacity: 0, y: 4, filter: \"blur(6px)\" }\n                        }\n                        animate={\n                          reduce\n                            ? { opacity: 1 }\n                            : { opacity: 1, y: 0, filter: \"blur(0px)\" }\n                        }\n                        exit={\n                          reduce\n                            ? { opacity: 0 }\n                            : {\n                                opacity: 0,\n                                y: -2,\n                                filter: \"blur(4px)\",\n                                transition: {\n                                  duration: 0.12,\n                                  ease: EASE_OUT,\n                                },\n                              }\n                        }\n                        transition={{\n                          duration: reduce ? 0 : 0.18,\n                          ease: EASE_OUT,\n                        }}\n                      >\n                        {renderPreview ? (\n                          renderPreview(item)\n                        ) : (\n                          <DefaultPreview item={item} />\n                        )}\n                      </motion.div>\n                    </AnimatePresence>\n                  </motion.div>\n                </div>\n              ) : null}\n            </div>\n          ))}\n        </div>\n      ) : null}\n\n      {children ? (\n        <div className=\"min-h-0 min-w-0 flex-1\">{children}</div>\n      ) : null}\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\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 { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from \"./tooltip/grace\";\nimport { TooltipArrow, TooltipPositioner } from \"./tooltip/positioner\";\nimport {\n  type TooltipAlign,\n  type TooltipAnchor,\n  type TooltipPoint,\n  type TooltipSide,\n  useTooltipPointer,\n} from \"./tooltip/use-position\";\n\nexport type { TooltipAlign, TooltipSide };\n\n/* -------------------------------------------------------------------------- */\n/* Provider                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface TooltipTiming {\n  /** Delay before a hover opens a tooltip (ms). */\n  delay: number;\n  /** Delay before a tooltip closes once the pointer has left it (ms). */\n  closeDelay: number;\n  /** After one tooltip closes, others open instantly for this long (ms). */\n  skipDelay: number;\n}\n\nconst TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });\n\nexport interface TooltipProviderProps extends Partial<TooltipTiming> {\n  children: ReactNode;\n}\n\n/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */\nexport function TooltipProvider({ children, ...timing }: TooltipProviderProps) {\n  const parent = useContext(TimingContext);\n  const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =\n    timing;\n  const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);\n  return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\n// Moving along a toolbar should feel instant after the first label, and only\n// one label may show at a time: a keyboard-focused control and a hovered one\n// would otherwise both claim the screen.\nlet lastClosedAt = 0;\nlet current: { close: () => void } | null = null;\n\nfunction isEmpty(content: ReactNode) {\n  return content == null || content === false || content === \"\";\n}\n\ninterface TooltipContextValue {\n  open: boolean;\n  /** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */\n  instant: boolean;\n  contentId: string;\n  labelId: string;\n  asLabel: boolean;\n  empty: boolean;\n  followCursor: boolean;\n  anchor: TooltipAnchor | null;\n  /** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */\n  triggered: boolean;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  pointer: ReturnType<typeof useTooltipPointer>;\n  setTrigger: (element: TooltipAnchor | null) => void;\n  setEmpty: (empty: boolean) => void;\n  close: () => void;\n  onContentEnter: () => void;\n  onContentLeave: (event: ReactPointerEvent) => void;\n}\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nfunction useTooltipContext(part: string) {\n  const context = useContext(TooltipContext);\n  if (!context) throw new Error(`${part} must be used inside <Tooltip>`);\n  return context;\n}\n\nexport interface TooltipRootProps {\n  children?: ReactNode;\n  /** Whether the tooltip is shown, for controlled use. */\n  open?: boolean;\n  /** Whether the tooltip starts shown when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the tooltip shows or hides. */\n  onOpenChange?: (open: boolean) => void;\n  /** Delay before showing on hover (ms). Keyboard focus shows immediately. */\n  delay?: number;\n  /** Delay before hiding once the pointer has left (ms). */\n  closeDelay?: number;\n  /** Never show, e.g. while the label it carries is already visible. */\n  disabled?: boolean;\n  /**\n   * Use the tooltip as the trigger's accessible name rather than its\n   * description. For icon-only controls whose only label is the tooltip.\n   */\n  asLabel?: boolean;\n  /** Follow real pointer coordinates; keyboard focus still uses the anchor. */\n  followCursor?: boolean;\n  /** Existing anchor for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<TooltipAnchor | null>;\n  /** Id of the tooltip surface, for anchors that reference it themselves. */\n  id?: string;\n}\n\nfunction TooltipRoot({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  delay: delayProp,\n  closeDelay: closeDelayProp,\n  disabled = false,\n  asLabel = false,\n  followCursor = false,\n  anchorRef,\n  id,\n  initialEmpty = false,\n}: TooltipRootProps & { initialEmpty?: boolean }) {\n  const timing = useContext(TimingContext);\n  const delay = delayProp ?? timing.delay;\n  const closeDelay = closeDelayProp ?? timing.closeDelay;\n  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n  const open = controlledOpen ?? uncontrolledOpen;\n  // Keyboard focus and a warm toolbar show the label at once; animating\n  // something seen this often only makes it feel slow.\n  const [instant, setInstant] = useState(false);\n  const [empty, setEmpty] = useState(initialEmpty);\n  const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);\n  const [external, setExternal] = useState<TooltipAnchor | null>(null);\n  const anchor = anchorRef ? external : trigger;\n  const generatedId = useId();\n  const contentId = id ?? `${generatedId}-content`;\n  const labelId = `${generatedId}-label`;\n  const floatingRef = useRef<HTMLSpanElement | null>(null);\n  const anchorObject = useRef<TooltipAnchor | null>(null);\n  const pointer = useTooltipPointer(anchor, followCursor);\n\n  // An external ref can attach after this component renders; read it once it has.\n  useLayoutEffect(() => {\n    if (!anchorRef) return;\n    const element = anchorRef.current ?? null;\n    if (element !== external) setExternal(element);\n  });\n\n  // Everything the event listeners read, current without re-binding them.\n  const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });\n  useLayoutEffect(() => {\n    anchorObject.current = anchor;\n    latest.current = {\n      open,\n      delay,\n      closeDelay,\n      disabled,\n      empty,\n      onOpenChange,\n      controlled: controlledOpen !== undefined,\n    };\n  });\n\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const grace = useRef<(() => void) | null>(null);\n  const self = useRef<{ close: () => void }>({ close: () => {} });\n\n  const clearTimers = useCallback(() => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    if (closeTimer.current) clearTimeout(closeTimer.current);\n    openTimer.current = null;\n    closeTimer.current = null;\n  }, []);\n\n  const stopGrace = useCallback(() => {\n    grace.current?.();\n    grace.current = null;\n  }, []);\n\n  // Only a real change reaches the consumer: a pointer leaving a closed\n  // tooltip is not news.\n  const commit = useCallback((next: boolean) => {\n    if (latest.current.open === next) return;\n    if (!latest.current.controlled) setUncontrolledOpen(next);\n    latest.current.onOpenChange?.(next);\n  }, []);\n\n  const openNow = useCallback(\n    (now = false) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.disabled || latest.current.empty) return;\n      // The label being replaced leaves at once, so two never show together.\n      if (current && current !== self.current) current.close();\n      current = self.current;\n      setInstant(now);\n      commit(true);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n\n  const finish = useCallback(\n    (now: boolean) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.open) lastClosedAt = Date.now();\n      if (current === self.current) current = null;\n      if (latest.current.open) setInstant(now);\n      commit(false);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n  // Also a listener (window blur, outside press), so it takes no arguments.\n  const close = useCallback(() => finish(false), [finish]);\n  useLayoutEffect(() => {\n    self.current.close = () => finish(true);\n  }, [finish]);\n\n  const requestOpen = useCallback(() => {\n    clearTimers();\n    if (latest.current.open || latest.current.disabled || latest.current.empty) return;\n    // Warm: another label is still showing (the pointer is crossing to this\n    // one), or one closed a moment ago. Either way, skip the delay and the fade.\n    const warm =\n      (current !== null && current !== self.current) ||\n      Date.now() - lastClosedAt < timing.skipDelay;\n    if (warm) openNow(true);\n    else if (latest.current.delay <= 0) openNow();\n    else openTimer.current = setTimeout(() => openNow(), latest.current.delay);\n  }, [clearTimers, openNow, timing.skipDelay]);\n\n  const requestClose = useCallback(() => {\n    clearTimers();\n    if (latest.current.closeDelay > 0) {\n      closeTimer.current = setTimeout(close, latest.current.closeDelay);\n    } else close();\n  }, [clearTimers, close]);\n\n  // Hold the label open while the pointer crosses from one box toward the other.\n  const startGrace = useCallback(\n    (exit: TooltipPoint, from: Element, to: Element | null) => {\n      stopGrace();\n      if (!to) return requestClose();\n      const target = to.getBoundingClientRect();\n      const origin = from.getBoundingClientRect();\n      const corridor = graceArea(exit, target);\n      const onMove = (event: PointerEvent) => {\n        const point = { x: event.clientX, y: event.clientY };\n        if (inBox(point, target) || inBox(point, origin)) return;\n        if (!inPolygon(point, corridor)) requestClose();\n      };\n      document.addEventListener(\"pointermove\", onMove);\n      grace.current = () => document.removeEventListener(\"pointermove\", onMove);\n    },\n    [stopGrace, requestClose],\n  );\n\n  const hover = useHoverGesture();\n  const tap = useTapGesture<boolean>();\n\n  // Listeners go on the trigger itself rather than on cloned props, so a\n  // component that owns its own handlers keeps them, and no wrapper element\n  // sits between the control and its layout.\n  useEffect(() => {\n    if (anchorRef || !trigger) return;\n    watchModality();\n    // A mouse press dismisses the label and keeps it away until the pointer\n    // leaves; hovering a control you just clicked should not bring it back.\n    let suppressed = false;\n    // Focus that came from the keyboard holds the label open on its own.\n    let keyboardFocus = false;\n\n    const onEnter = (event: PointerEvent) => {\n      if (!hover.enter(event)) return;\n      stopGrace();\n      if (closeTimer.current) clearTimeout(closeTimer.current);\n      if (!suppressed) requestOpen();\n    };\n    const onLeave = (event: PointerEvent) => {\n      if (!hover.leave(event)) return;\n      suppressed = false;\n      if (keyboardFocus) return;\n      if (openTimer.current) {\n        clearTimers();\n        return;\n      }\n      if (latest.current.open && !followCursor) {\n        startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);\n      } else requestClose();\n    };\n    const onDown = (event: PointerEvent) => {\n      tap.start(event, latest.current.open);\n      if (event.pointerType === \"mouse\") {\n        suppressed = true;\n        close();\n      }\n    };\n    // A finger never hovers, and Safari does not focus a button on tap either,\n    // so the label is only reachable if the tap itself toggles it. The click\n    // carries no pointerType; the pointerdown before it says whether it was a\n    // tap, and keyboard activation has none at all.\n    const onClick = () => {\n      const gesture = tap.take();\n      if (!gesture || gesture.pointerType === \"mouse\") return;\n      if (gesture.state) close();\n      else openNow();\n    };\n    const onKey = () => tap.drop();\n    const onFocusIn = () => {\n      if (!focusFromKeyboard()) return;\n      keyboardFocus = true;\n      openNow(true);\n    };\n    const onFocusOut = (event: FocusEvent) => {\n      if (trigger.contains(event.relatedTarget as Node | null)) return;\n      const fromKeyboard = keyboardFocus;\n      keyboardFocus = false;\n      finish(fromKeyboard);\n    };\n\n    // Both element kinds dispatch the same events; one type keeps the listeners typed.\n    const el = trigger as HTMLElement;\n    el.addEventListener(\"pointerenter\", onEnter);\n    el.addEventListener(\"pointerleave\", onLeave);\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointercancel\", tap.drop);\n    el.addEventListener(\"click\", onClick);\n    el.addEventListener(\"keydown\", onKey);\n    el.addEventListener(\"focusin\", onFocusIn);\n    el.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      el.removeEventListener(\"pointerenter\", onEnter);\n      el.removeEventListener(\"pointerleave\", onLeave);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointercancel\", tap.drop);\n      el.removeEventListener(\"click\", onClick);\n      el.removeEventListener(\"keydown\", onKey);\n      el.removeEventListener(\"focusin\", onFocusIn);\n      el.removeEventListener(\"focusout\", onFocusOut);\n    };\n  }, [\n    anchorRef,\n    trigger,\n    followCursor,\n    hover,\n    tap,\n    requestOpen,\n    requestClose,\n    openNow,\n    close,\n    finish,\n    clearTimers,\n    stopGrace,\n    startGrace,\n  ]);\n\n  // While open, a trigger that turns disabled loses focus without a blur event,\n  // and a window that loses focus never reports the pointer leaving.\n  useEffect(() => {\n    if (!open || anchorRef || !trigger) return;\n    const observer = new MutationObserver(() => {\n      if (trigger.matches(\":disabled, [aria-disabled='true']\")) close();\n    });\n    observer.observe(trigger, { attributes: true, attributeFilter: [\"disabled\", \"aria-disabled\"] });\n    window.addEventListener(\"blur\", close);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"blur\", close);\n    };\n  }, [open, anchorRef, trigger, close]);\n\n  // A chart drives its own open state and swaps content as it goes; only a\n  // trigger-owned label closes itself for having nothing to say.\n  useEffect(() => {\n    if (disabled || (empty && !anchorRef)) close();\n  }, [disabled, empty, anchorRef, close]);\n\n  useEffect(\n    () => () => {\n      clearTimers();\n      stopGrace();\n      if (current === self.current) current = null;\n    },\n    [clearTimers, stopGrace],\n  );\n\n  const insideTooltip = useCallback(\n    (target: Element) => Boolean(floatingRef.current?.contains(target)),\n    [],\n  );\n  // ...and closed by the next tap that lands somewhere else, or Escape. The\n  // label covers nothing interactive, so that tap passes through to what it hit.\n  // Escape is a key press, so the label goes at once.\n  const dismiss = useCallback((reason: DismissReason) => finish(reason === \"escape\"), [finish]);\n  useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });\n\n  const onContentEnter = useCallback(() => {\n    stopGrace();\n    clearTimers();\n  }, [stopGrace, clearTimers]);\n\n  const onContentLeave = useCallback(\n    (event: ReactPointerEvent) => {\n      const floating = floatingRef.current;\n      if (!floating) return;\n      if (anchorRef) {\n        // Bridge the small gap back onto a chart; it reopens on its own terms.\n        clearTimers();\n        closeTimer.current = setTimeout(close, 100);\n        return;\n      }\n      startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);\n    },\n    [anchorRef, clearTimers, close, startGrace],\n  );\n\n  const value = useMemo<TooltipContextValue>(\n    () => ({\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      triggered: !anchorRef,\n      floatingRef,\n      pointer,\n      setTrigger,\n      setEmpty,\n      close,\n      onContentEnter,\n      onContentLeave,\n    }),\n    [\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      anchorRef,\n      pointer,\n      close,\n      onContentEnter,\n      onContentLeave,\n    ],\n  );\n\n  return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nfunction mergeIds(...ids: unknown[]) {\n  return ids.filter((value) => typeof value === \"string\" && value).join(\" \") || undefined;\n}\n\nexport interface TooltipTriggerProps extends ComponentProps<\"button\"> {\n  /** Use the single child element as the trigger instead of rendering a button. */\n  asChild?: boolean;\n}\n\nexport function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {\n  const { open, contentId, labelId, asLabel, empty, setTrigger } =\n    useTooltipContext(\"TooltipTrigger\");\n  const child = asChild && isValidElement(children) ? children : null;\n  const childProps = (child?.props ?? props) as Record<string, unknown>;\n  const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;\n  const attached = useRef<TooltipAnchor | null>(null);\n\n  const setRef = useCallback(\n    (element: TooltipAnchor | null) => {\n      attached.current = element;\n      setTrigger(element);\n      assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);\n    },\n    [setTrigger, childRef, ref],\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"production\" && child && !attached.current) {\n      console.warn(\n        \"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.\",\n      );\n    }\n  }, [child]);\n\n  const aria = asLabel\n    ? {\n        \"aria-labelledby\": empty\n          ? (childProps[\"aria-labelledby\"] as string | undefined)\n          : labelId,\n      }\n    : {\n        \"aria-describedby\": mergeIds(\n          childProps[\"aria-describedby\"],\n          open && !empty ? contentId : undefined,\n        ),\n      };\n\n  if (asChild) {\n    if (!child) return children;\n    return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });\n  }\n\n  return (\n    <button\n      type=\"button\"\n      data-state={open ? \"open\" : \"closed\"}\n      {...props}\n      ref={setRef as Ref<HTMLButtonElement>}\n      {...aria}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipContentProps {\n  children?: ReactNode;\n  /** Preferred side of the anchor. Flips when there is no room. Default: \"top\" */\n  side?: TooltipSide;\n  /** Alignment along the chosen side. Default: \"center\" */\n  align?: TooltipAlign;\n  /** Gap between anchor and tooltip (px). */\n  sideOffset?: number;\n  /** Draw an arrow pointing at the anchor. */\n  arrow?: boolean;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: TooltipPoint;\n  /** Classes merged onto the tooltip surface. */\n  className?: string;\n}\n\nexport function TooltipContent({\n  children,\n  side = \"top\",\n  align = \"center\",\n  sideOffset,\n  arrow = false,\n  anchorPoint,\n  className,\n}: TooltipContentProps) {\n  const {\n    open,\n    instant,\n    contentId,\n    labelId,\n    asLabel,\n    followCursor,\n    anchor,\n    floatingRef,\n    pointer,\n    setEmpty,\n    close,\n    onContentEnter,\n    onContentLeave,\n  } = useTooltipContext(\"TooltipContent\");\n  const empty = isEmpty(children);\n  const arrowRef = useRef<SVGSVGElement | null>(null);\n\n  useLayoutEffect(() => {\n    setEmpty(empty);\n  }, [empty, setEmpty]);\n\n  if (typeof document === \"undefined\") return null;\n\n  return createPortal(\n    <>\n      {/* The name has to exist while the label is closed, so it lives apart from the surface. */}\n      {asLabel && !empty ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {/* `custom` reaches a surface that is already exiting, so a label closed\n          from the keyboard or replaced by a neighbour leaves without animating. */}\n      <AnimatePresence custom={instant}>\n        {open && !empty ? (\n          <TooltipPositioner\n            key=\"tooltip\"\n            anchor={anchor}\n            floatingRef={floatingRef}\n            arrowRef={arrow ? arrowRef : undefined}\n            anchorPoint={anchorPoint}\n            followCursor={followCursor}\n            side={side}\n            align={align}\n            sideOffset={sideOffset}\n            onDismiss={close}\n            pointer={pointer}\n          >\n            {(positioned, isPresent, placedSide) => (\n              <TooltipSurface\n                id={asLabel ? undefined : contentId}\n                aria-hidden={asLabel || undefined}\n                ready={positioned}\n                instant={instant}\n                onPointerEnter={onContentEnter}\n                onPointerLeave={onContentLeave}\n                style={{ pointerEvents: isPresent && !followCursor ? \"auto\" : \"none\" }}\n                className={cn(\n                  \"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words\",\n                  arrow && \"relative\",\n                  className,\n                )}\n              >\n                {children}\n                {arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}\n              </TooltipSurface>\n            )}\n          </TooltipPositioner>\n        ) : null}\n      </AnimatePresence>\n    </>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tooltip (root, or one-line shorthand when given `content`)                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipProps\n  extends TooltipRootProps,\n    Omit<TooltipContentProps, \"children\" | \"className\"> {\n  /**\n   * Shorthand: the tooltip's content. With it, `children` is the trigger\n   * element; without it, compose `TooltipTrigger` and `TooltipContent`.\n   */\n  content?: ReactNode;\n  /** Shorthand only: classes for the tooltip surface. */\n  className?: string;\n}\n\nexport function Tooltip(props: TooltipProps) {\n  if (!(\"content\" in props)) return <TooltipRoot {...props} />;\n  const {\n    content,\n    children,\n    side,\n    align,\n    sideOffset,\n    arrow,\n    anchorPoint,\n    className,\n    ...root\n  } = props;\n  if (!root.anchorRef && !isValidElement(children)) return children ?? null;\n  return (\n    <TooltipRoot {...root} initialEmpty={isEmpty(content)}>\n      {isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}\n      <TooltipContent\n        side={side}\n        align={align}\n        sideOffset={sideOffset}\n        arrow={arrow}\n        anchorPoint={anchorPoint}\n        className={className}\n      >\n        {content}\n      </TooltipContent>\n    </TooltipRoot>\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/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":"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/hooks/use-hover-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\nimport { isHoveringPointer } from \"@/lib/touch\";\n\ninterface BoundaryEvent {\n  pointerId: number;\n  pointerType: string;\n  buttons: number;\n}\n\nexport interface HoverGesture {\n  /** True when this enter starts a hover: the pointer arrived resting, not pressing. */\n  enter: (event: BoundaryEvent) => boolean;\n  /** True when this leave ends a hover that entered as one. */\n  leave: (event: BoundaryEvent) => boolean;\n}\n\n/**\n * Pairs a surface's enter with its leave, per pointer.\n *\n * `isHoveringPointer` answers the question the *enter* asks - is this pointer\n * resting on the surface or pressing it - and both boundary cases go wrong if\n * the leave is asked the same question again:\n *\n * - A pen with no hover never rests. It arrives in contact, taps, and the spec\n *   then requires its boundary events after `pointerup`, so the leave carries\n *   `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid\n *   the tap - the panel the pen had just opened closed under it.\n * - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.\n *   Skipping teardown there strands the surface open: the release happens\n *   outside, and no second leave ever comes.\n *\n * So the state a hover holds is released by the pointer that took it, whatever\n * the buttons say at the boundary, and a pointer that arrived in contact never\n * took it in the first place. Contact is the exception tracked here, not\n * hover: a leave from a pointer this surface never saw enter - mounted under\n * the cursor, say - still counts, since the alternative is state with no way\n * out.\n */\nexport function useHoverGesture(): HoverGesture {\n  const contact = useRef(new Set<number>());\n\n  return useMemo(\n    () => ({\n      enter: (event) => {\n        if (isHoveringPointer(event)) {\n          contact.current.delete(event.pointerId);\n          return true;\n        }\n        contact.current.add(event.pointerId);\n        return false;\n      },\n      leave: (event) => {\n        const arrivedInContact = contact.current.delete(event.pointerId);\n        return !arrivedInContact && event.pointerType !== \"touch\";\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/hooks/use-tap-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\n\n/** What a pointerdown recorded, read back by the click that ends its gesture. */\nexport interface TapRecord<S> {\n  /** Which input started the gesture. */\n  pointerType: string;\n  /** What the surface was showing when it started. */\n  state: S;\n}\n\nexport interface TapGesture<S> {\n  /** Record the gesture a pointerdown starts, with the state it starts in. */\n  start: (event: { pointerType: string }, state: S) => void;\n  /** Read the record and clear it. `null` when no pointer is behind this click. */\n  take: () => TapRecord<S> | null;\n  /** Drop the record: this gesture will never spend it on a click. */\n  drop: () => void;\n}\n\n/**\n * The pointer gesture behind a click, recorded where the click cannot report\n * it. A `click` carries no `pointerType` in the engines that matter, so the\n * `pointerdown` before it is the only thing that says which input activated\n * the control - and whether one did at all, since keyboard activation\n * synthesizes a click with no pointer behind it.\n *\n * State goes in with the record because a click reports that no better: a\n * browser that focuses a control on contact can open the very panel the tap\n * was meant to open, and reading \"is it open\" at click time then undoes it.\n * What the gesture started against is what it acts on.\n *\n * The record is spent by one click and dropped by everything else, because a\n * record that outlives its gesture is worse than none:\n *\n * - A scroll or an OS gesture takes the touch away - `pointercancel`, no click\n *   ever - and the finger would sit in the record until some later click.\n * - That later click is often `Enter` on a keyboard, which arrives with no\n *   pointerdown of its own and would inherit the abandoned finger. A keydown\n *   is the start of a keyboard activation and never part of a tap, so it drops\n *   the record too.\n *\n * Both ends have to be wired by the surface: `drop` on `onPointerCancel` and\n * on `onKeyDown`.\n */\nexport function useTapGesture<S>(): TapGesture<S> {\n  const record = useRef<TapRecord<S> | null>(null);\n\n  return useMemo(\n    () => ({\n      start: (event, state) => {\n        record.current = { pointerType: event.pointerType, state };\n      },\n      take: () => {\n        const spent = record.current;\n        record.current = null;\n        return spent;\n      },\n      drop: () => {\n        record.current = null;\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"components/motion/tooltip/grace.ts","type":"util","content":"type Point = { x: number; y: number };\ntype Box = { left: number; top: number; right: number; bottom: number };\n\n/**\n * The corridor a pointer may cross between the trigger and the open tooltip\n * without closing it: the convex hull of where it left and the box it is\n * heading for. A fixed timeout either cuts a slow diagonal move short or keeps\n * the label alive after the pointer has plainly gone elsewhere; this follows\n * the path itself.\n */\nexport function graceArea(exit: Point, target: Box): Point[] {\n  // A few pixels either side of the exit point give the corridor some width at\n  // its narrow end, so a hand that drifts sideways while it moves stays inside.\n  const pad = 5;\n  return hull([\n    { x: exit.x - pad, y: exit.y - pad },\n    { x: exit.x + pad, y: exit.y - pad },\n    { x: exit.x - pad, y: exit.y + pad },\n    { x: exit.x + pad, y: exit.y + pad },\n    { x: target.left, y: target.top },\n    { x: target.right, y: target.top },\n    { x: target.right, y: target.bottom },\n    { x: target.left, y: target.bottom },\n  ]);\n}\n\nexport function inBox(point: Point, box: Box) {\n  return (\n    point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom\n  );\n}\n\nexport function inPolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\n// Monotone chain; the corridor is always convex, so a hull is all it needs.\nfunction hull(points: Point[]) {\n  const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n  const cross = (o: Point, a: Point, b: Point) =>\n    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n  const lower: Point[] = [];\n  for (const p of sorted) {\n    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {\n      lower.pop();\n    }\n    lower.push(p);\n  }\n  const upper: Point[] = [];\n  for (let i = sorted.length - 1; i >= 0; i--) {\n    const p = sorted[i];\n    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {\n      upper.pop();\n    }\n    upper.push(p);\n  }\n  lower.pop();\n  upper.pop();\n  return lower.concat(upper);\n}\n\n/**\n * How the user last reached for the page. A focus that a mouse press caused is\n * not a request to read the label: the pointer is already on the control and\n * hovering showed it. A focus that followed a key - Tab, or a roving arrow key\n * moving focus in script - is the only way a keyboard user sees it at all.\n */\nlet modality: \"keyboard\" | \"pointer\" = \"keyboard\";\nlet listening = false;\n\nexport function watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (modality = \"keyboard\"), true);\n  window.addEventListener(\"pointerdown\", () => (modality = \"pointer\"), true);\n}\n\nexport function focusFromKeyboard() {\n  return modality === \"keyboard\";\n}\n"},{"path":"components/motion/tooltip/positioner.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from \"react\";\nimport { type TooltipSide, useTooltipPosition } from \"./use-position\";\n\ntype PositionProps = Parameters<typeof useTooltipPosition>[0];\n\n/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */\nexport function TooltipPositioner({\n  children,\n  ...position\n}: Omit<PositionProps, \"open\" | \"onPosition\"> & {\n  children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;\n}) {\n  const present = useIsPresent();\n  const [ready, setReady] = useState(false);\n  const [side, setSide] = useState<TooltipSide>(position.side);\n  const onPosition = useCallback((placed: TooltipSide) => {\n    setReady(true);\n    setSide(placed);\n  }, []);\n  useTooltipPosition({ ...position, open: present, onPosition });\n  return (\n    <span\n      ref={position.floatingRef}\n      inert={!present}\n      aria-hidden={!present || undefined}\n      className=\"pointer-events-none fixed left-0 top-0 z-[9999] w-max\"\n      style={{ visibility: \"hidden\", maxWidth: \"calc(100vw - 16px)\" }}\n    >\n      {children(ready, present, side)}\n    </span>\n  );\n}\n\n// Each arrow is a 12px box whose base sits on the surface's inner border edge,\n// so its fill covers the border beneath it and only the two outer edges stroke.\nconst ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {\n  top: { path: \"M0 6L6 12L12 6\", style: { top: \"calc(100% - 6px)\" } },\n  bottom: { path: \"M0 6L6 0L12 6\", style: { bottom: \"calc(100% - 6px)\" } },\n  left: { path: \"M6 0L12 6L6 12\", style: { left: \"calc(100% - 6px)\" } },\n  right: { path: \"M6 0L0 6L6 12\", style: { right: \"calc(100% - 6px)\" } },\n};\n\nexport function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {\n  const { path, style } = ARROW[side];\n  return (\n    <svg\n      ref={ref}\n      aria-hidden=\"true\"\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 12 12\"\n      className=\"pointer-events-none absolute overflow-visible\"\n      style={style}\n    >\n      {/* Redrawn to fit the surface's edge once placed (see arrowShape). */}\n      <path data-arrow-fill=\"\" d={`${path}Z`} style={{ fill: \"var(--tooltip-arrow-fill, transparent)\" }} />\n      <path\n        data-arrow-stroke=\"\"\n        d={path}\n        fill=\"none\"\n        strokeWidth=\"1\"\n        style={{ stroke: \"var(--tooltip-arrow-stroke, transparent)\" }}\n      />\n    </svg>\n  );\n}\n"},{"path":"components/motion/tooltip/use-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  arrow as arrowMiddleware,\n  autoUpdate,\n  computePosition,\n  flip,\n  hide,\n  offset,\n  type Placement,\n  shift,\n  type VirtualElement,\n} from \"@floating-ui/dom\";\nimport { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\n\nexport type TooltipSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type TooltipAlign = \"start\" | \"center\" | \"end\";\nexport type TooltipPoint = {\n  /** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */\n  x: number;\n  /** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */\n  y: number;\n};\nexport type TooltipAnchor = HTMLElement | SVGElement;\n\nconst ORIGIN: Record<TooltipSide, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */\nfunction blend(top: string, bottom: string) {\n  const context = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!context) return top;\n  context.fillStyle = bottom;\n  context.fillRect(0, 0, 1, 1);\n  context.fillStyle = top;\n  context.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;\n  // A see-through background has nothing solid to blend onto.\n  return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;\n}\n\n/** The arrow element's box, which the arrow middleware centres along the edge. */\nconst ARROW_SIZE = 12;\n/** How far the tip reaches past the border's inner edge. */\nconst ARROW_REACH = 6;\n\n/**\n * How far a rounded edge has curved in from its straight line at `position`\n * along an edge of `length`, with corners of `radius`. Zero on the straight\n * stretch between the corners.\n */\nfunction curveDepth(position: number, length: number, radius: number) {\n  const offset =\n    position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;\n  if (offset <= 0) return 0;\n  return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));\n}\n\n/**\n * The arrow's two paths, in the surface's border-box coordinates. Each 45°\n * side runs from the tip until it meets the middle of the surface's border,\n * wherever that is: on a straight stretch, or partway round a pill's curved\n * end. The stroke covers only those two sides, so the border flows straight\n * into them. The fill closes a little inside the surface, hiding the stretch\n * of border the arrow sits on.\n */\nfunction arrowShape({\n  side,\n  center,\n  width,\n  height,\n  radius,\n  border,\n}: {\n  side: TooltipSide;\n  center: number;\n  width: number;\n  height: number;\n  radius: number;\n  border: number;\n}) {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const length = vertical ? width : height;\n  // Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.\n  const tip = { depth: border - ARROW_REACH, along: center };\n  // The border's centre line: the stroke meets it there, so the two line up.\n  const line = border / 2;\n  // Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.\n  const curved =\n    curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||\n    curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;\n  const meet = (direction: -1 | 1) => {\n    // On a straight stretch the 45° side meets the border directly.\n    if (!curved) {\n      for (let t = 0; t <= ARROW_SIZE; t += 0.05) {\n        const along = center + direction * t;\n        const depth = tip.depth + t;\n        if (depth >= line) return { depth, along };\n      }\n    }\n    // On a pill's round end a 45° side passes outside the curve, or meets it\n    // at a kink. Run the side tangent to the curve instead, so the border\n    // flows into it without a corner.\n    const curve = radius - line;\n    const centre = { depth: radius, along: direction < 0 ? radius : length - radius };\n    const dx = tip.depth - centre.depth;\n    const dy = tip.along - centre.along;\n    const distance = Math.hypot(dx, dy);\n    if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };\n    const base = Math.atan2(dy, dx);\n    const spread = Math.acos(curve / distance);\n    const candidates = [base + spread, base - spread].map((angle) => ({\n      depth: centre.depth + curve * Math.cos(angle),\n      along: centre.along + curve * Math.sin(angle),\n    }));\n    // The tangent on this side of the tip.\n    return direction < 0\n      ? candidates[0].along < candidates[1].along\n        ? candidates[0]\n        : candidates[1]\n      : candidates[0].along > candidates[1].along\n        ? candidates[0]\n        : candidates[1];\n  };\n  const start = meet(-1);\n  const end = meet(1);\n  const inside = Math.max(start.depth, end.depth) + border + 1;\n  const point = ({ depth, along }: { depth: number; along: number }) => {\n    const [x, y] =\n      side === \"right\"\n        ? [depth, along]\n        : side === \"left\"\n          ? [width - depth, along]\n          : side === \"bottom\"\n            ? [along, depth]\n            : [along, height - depth];\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  };\n  return {\n    fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,\n    stroke: `M${point(start)}L${point(tip)}L${point(end)}`,\n  };\n}\n\n/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */\nexport function useTooltipPosition({\n  open,\n  anchor,\n  floatingRef,\n  arrowRef,\n  anchorPoint,\n  followCursor,\n  side,\n  align,\n  sideOffset,\n  onDismiss,\n  onPosition,\n  pointer,\n}: {\n  open: boolean;\n  anchor: TooltipAnchor | null;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  arrowRef?: RefObject<SVGSVGElement | null>;\n  anchorPoint?: TooltipPoint;\n  followCursor: boolean;\n  side: TooltipSide;\n  align: TooltipAlign;\n  sideOffset?: number;\n  onDismiss: () => void;\n  onPosition: (side: TooltipSide) => void;\n  pointer: ReturnType<typeof useTooltipPointer>;\n}) {\n  const { cursor, onMove } = pointer;\n  const preferred: Placement = align === \"center\" ? side : `${side}-${align}`;\n  const cursorSide = useRef<Placement | null>(null);\n  useLayoutEffect(() => {\n    cursorSide.current = open ? preferred : null;\n  }, [open, preferred]);\n  const frame = useRef<number | null>(null);\n  const version = useRef(0);\n  const update = useRef<() => void>(() => {});\n  const schedule = useCallback(() => {\n    // Invalidate older async calculations as soon as new geometry is requested.\n    version.current++;\n    if (frame.current !== null) return;\n    frame.current = requestAnimationFrame(() => {\n      frame.current = null;\n      update.current();\n    });\n  }, []);\n  useLayoutEffect(() => {\n    onMove.current = schedule;\n    return () => {\n      onMove.current = null;\n    };\n  }, [onMove, schedule]);\n  const pointX = anchorPoint?.x;\n  const pointY = anchorPoint?.y;\n\n  // Latest committed inputs are read without recreating observers for every period/content update.\n  useLayoutEffect(() => {\n    update.current = () => {\n      const floating = floatingRef.current;\n      if (!open || !anchor || !floating) return;\n      const revision = ++version.current;\n      const currentCursor = followCursor ? cursor.current : null;\n      const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;\n      const reference: Element | VirtualElement = virtual\n        ? {\n            contextElement: anchor,\n            getBoundingClientRect: () => {\n              const rect = anchor.getBoundingClientRect();\n              const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);\n              const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);\n              return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };\n            },\n          }\n        : anchor;\n      const arrowElement = arrowRef?.current ?? null;\n      void computePosition(reference, floating, {\n        strategy: \"fixed\",\n        placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,\n        middleware: [\n          offset(sideOffset ?? (currentCursor ? 12 : 8)),\n          flip({ padding: 8 }),\n          shift({ padding: 8 }),\n          ...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),\n          // A label left floating over whatever scrolled into its trigger's place\n          // describes nothing there. Points inside a chart move with the chart.\n          ...(virtual ? [] : [hide({ strategy: \"referenceHidden\" })]),\n        ],\n      }).then(({ x, y, placement, middlewareData }) => {\n        if (version.current !== revision || !floating.isConnected) return;\n        // Hold the chosen side for this hover session. Crossing a flip threshold\n        // repeatedly must not bounce the surface above and below the pointer.\n        if (currentCursor) cursorSide.current = placement;\n        else cursorSide.current = null;\n        const placedSide = placement.split(\"-\")[0] as TooltipSide;\n        const dpr = window.devicePixelRatio || 1;\n        floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;\n        floating.style.setProperty(\"--tooltip-origin\", ORIGIN[placedSide]);\n        // A box with no size has no clipped state to report, only a missing layout.\n        const box = anchor.getBoundingClientRect();\n        const clipped =\n          Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);\n        floating.style.visibility = clipped ? \"hidden\" : \"visible\";\n        floating.dataset.placement = placement;\n        const surface = arrowElement?.parentElement;\n        if (arrowElement && surface) {\n          // The middleware centres the 12px arrow box along the edge; its\n          // centre is where the tip points. The paths are drawn in the\n          // surface's border-box coordinates, so the svg sits at its corner.\n          const { x: ax, y: ay } = middlewareData.arrow ?? {};\n          const vertical = placedSide === \"top\" || placedSide === \"bottom\";\n          const width = surface.offsetWidth;\n          const height = surface.offsetHeight;\n          const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;\n          const style = getComputedStyle(surface);\n          const shape = arrowShape({\n            side: placedSide,\n            center: along + ARROW_SIZE / 2,\n            width,\n            height,\n            // `rounded-full` resolves to a huge radius; the box clamps it to half its short side.\n            radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),\n            border: surface.clientLeft,\n          });\n          Object.assign(arrowElement.style, {\n            left: `${-surface.clientLeft}px`,\n            top: `${-surface.clientTop}px`,\n            right: \"auto\",\n            bottom: \"auto\",\n          });\n          arrowElement.querySelector(\"[data-arrow-fill]\")?.setAttribute(\"d\", shape.fill);\n          arrowElement.querySelector(\"[data-arrow-stroke]\")?.setAttribute(\"d\", shape.stroke);\n          // Paint with whatever the surface resolved to, so a restyled tooltip\n          // keeps a matching arrow without a second set of classes. A\n          // see-through border is drawn over the surface's own background, so\n          // the stroke takes that blended colour: half of it sits over the\n          // page, and it overlaps the border where the two meet.\n          arrowElement.style.setProperty(\"--tooltip-arrow-fill\", style.backgroundColor);\n          arrowElement.style.setProperty(\n            \"--tooltip-arrow-stroke\",\n            blend(style.borderTopColor, style.backgroundColor),\n          );\n        }\n        onPosition(placedSide);\n      });\n    };\n    if (open) schedule();\n  }, [\n    open,\n    anchor,\n    floatingRef,\n    arrowRef,\n    followCursor,\n    pointX,\n    pointY,\n    preferred,\n    sideOffset,\n    schedule,\n    onPosition,\n    cursor,\n  ]);\n\n  useLayoutEffect(() => {\n    const floating = floatingRef.current;\n    if (!open || !anchor || !floating) return;\n    const stop = autoUpdate(anchor, floating, schedule);\n    const onScroll = () => {\n      // A stationary pointer no longer describes the same chart point after scrolling.\n      if (followCursor && cursor.current) onDismiss();\n    };\n    window.addEventListener(\"scroll\", onScroll, true);\n    return () => {\n      stop();\n      window.removeEventListener(\"scroll\", onScroll, true);\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n    };\n  }, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);\n\n  useLayoutEffect(\n    () => () => {\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n}\n\n/** Pointer lifetime belongs to the anchor, including the opening delay. */\nexport function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {\n  const cursor = useRef<TooltipPoint | null>(null);\n  const onMove = useRef<(() => void) | null>(null);\n  const pointerFocus = useRef(false);\n  useLayoutEffect(() => {\n    if (!anchor || !followCursor) return;\n    const point = (event: PointerEvent) => {\n      if (event.type === \"pointermove\" && event.pointerType === \"touch\" && !event.buttons) return;\n      cursor.current = { x: event.clientX, y: event.clientY };\n      if (event.type === \"pointerdown\") pointerFocus.current = true;\n      onMove.current?.();\n    };\n    const keyboard = () => {\n      cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const focus = () => {\n      if (!pointerFocus.current) cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const leave = () => {\n      cursor.current = null;\n    };\n    anchor.addEventListener(\"pointerenter\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointermove\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerdown\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerleave\", leave);\n    anchor.addEventListener(\"pointercancel\", leave);\n    anchor.addEventListener(\"keydown\", keyboard);\n    anchor.addEventListener(\"focusin\", focus);\n    return () => {\n      cursor.current = null;\n      anchor.removeEventListener(\"pointerenter\", point as EventListener);\n      anchor.removeEventListener(\"pointermove\", point as EventListener);\n      anchor.removeEventListener(\"pointerdown\", point as EventListener);\n      anchor.removeEventListener(\"pointerleave\", leave);\n      anchor.removeEventListener(\"pointercancel\", leave);\n      anchor.removeEventListener(\"keydown\", keyboard);\n      anchor.removeEventListener(\"focusin\", focus);\n    };\n  }, [anchor, followCursor]);\n\n  return useMemo(() => ({ cursor, onMove }), []);\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ComponentProps, ReactNode, Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nconst ENTER = { duration: 0.18, ease: EASE_OUT };\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\n/**\n * `custom` is the `instant` flag. An exiting surface reads it from its\n * `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once\n * even though it has already left the React tree.\n */\nconst variants = (reduce: boolean): Variants => ({\n  closed: (instant = false) => ({\n    opacity: 0,\n    scale: reduce ? 1 : 0.97,\n    transition: instant ? INSTANT : EXIT,\n  }),\n  open: (instant = false) => ({\n    opacity: 1,\n    scale: 1,\n    transition: instant ? INSTANT : ENTER,\n  }),\n});\n\n/** Presentation only: the unanimated parent owns measurement and positioning. */\nexport function TooltipSurface({\n  children,\n  className,\n  ref,\n  ready = true,\n  instant = false,\n  style,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  /** Start the entrance only after the positioning layer has been measured. */\n  ready?: boolean;\n  /**\n   * Appear and disappear without animating: a label opened from the keyboard,\n   * or one of a row of tooltips the pointer is moving along.\n   */\n  instant?: boolean;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      custom={instant}\n      variants={variants(reduce)}\n      initial=\"closed\"\n      animate={ready ? \"open\" : \"closed\"}\n      exit=\"closed\"\n      style={{ transformOrigin: \"var(--tooltip-origin, center)\", ...style }}\n      className={cn(\n        \"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\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":"lib/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"components/previews/agents/message-scroller.preview.tsx","type":"preview","content":"\"use client\";\n\nimport {\n  ChatPreview,\n  type ChatPreviewMessage,\n} from \"@/components/previews/agents/chat-preview\";\n\nconst MESSAGES: ChatPreviewMessage[] = [\n  {\n    id: \"scope-question\",\n    from: \"user\",\n    content: \"What should the first release include?\",\n  },\n  {\n    id: \"scope-answer\",\n    from: \"assistant\",\n    content: \"Start with the smallest workflow that still feels complete.\",\n  },\n  {\n    id: \"states-question\",\n    from: \"user\",\n    content: \"Include streaming and recovery states too.\",\n  },\n  {\n    id: \"states-answer\",\n    from: \"assistant\",\n    content: \"Yes. Those states make the first version feel dependable.\",\n  },\n  {\n    id: \"evidence-question\",\n    from: \"user\",\n    content: \"How should we present tool results?\",\n  },\n  {\n    id: \"evidence-answer\",\n    from: \"assistant\",\n    content: \"Keep results close to the action that produced them.\",\n  },\n  {\n    id: \"approval-question\",\n    from: \"user\",\n    content: \"What about actions that need confirmation?\",\n  },\n  {\n    id: \"approval-answer\",\n    from: \"assistant\",\n    content: \"Pause the run, explain the impact, and ask before continuing.\",\n  },\n  {\n    id: \"summary-question\",\n    from: \"user\",\n    content: \"Can the transcript stay easy to navigate?\",\n  },\n  {\n    id: \"summary-answer\",\n    from: \"assistant\",\n    content: \"Use the rail to jump between turns without losing your place.\",\n  },\n];\n\nexport function MessageScrollerPreview() {\n  return (\n    <ChatPreview\n      initialMessages={MESSAGES}\n      showRail\n      reply=\"The viewport follows while you stay at the live edge. Scroll upward while this response streams and it will leave your reading position alone.\"\n      placeholder=\"Send another message…\"\n    />\n  );\n}\n"},{"path":"components/previews/agents/chat-preview.tsx","type":"util","content":"\"use client\";\n\nimport { Bot, User } from \"lucide-react\";\nimport { useReducedMotion } from \"motion/react\";\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport {\n  Message,\n  MessageAvatar,\n  MessageContent,\n  MessageFooter,\n  MessageGroup,\n  MessageHeader,\n  MessageTyping,\n} from \"@/components/agents/message\";\nimport {\n  MessageBubble,\n  MessageBubbleContent,\n  type MessageBubbleVariant,\n} from \"@/components/agents/message-bubble\";\nimport { MessageScroller } from \"@/components/agents/message-scroller\";\nimport { PromptInput } from \"@/components/agents/prompt-input\";\nimport { StreamingResponse } from \"@/components/agents/streaming-response\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface ChatPreviewMessage {\n  id: string;\n  from: \"user\" | \"assistant\";\n  content: string;\n}\n\ninterface RenderedChatMessage extends ChatPreviewMessage {\n  animateIn: boolean;\n  streaming?: boolean;\n}\n\nexport interface ChatPreviewProps {\n  initialMessages?: ChatPreviewMessage[];\n  reply?: string | ((prompt: string) => string);\n  showAvatars?: boolean;\n  showMetadata?: boolean;\n  showRail?: boolean;\n  assistantVariant?: MessageBubbleVariant;\n  userVariant?: MessageBubbleVariant;\n  placeholder?: string;\n  className?: string;\n  viewportClassName?: string;\n}\n\nconst DEFAULT_MESSAGES: ChatPreviewMessage[] = [\n  {\n    id: \"welcome-question\",\n    from: \"user\",\n    content: \"What should we include in the first release?\",\n  },\n  {\n    id: \"welcome-answer\",\n    from: \"assistant\",\n    content: \"Start with the smallest workflow that still feels complete.\",\n  },\n];\n\nconst DEFAULT_REPLY =\n  \"I’d include composing a prompt, following a streamed answer, recovering from an error, and returning to the latest response without losing the reader’s place.\";\nconst CHARACTERS_PER_SECOND = 96;\nconst STREAM_DELAY = 140;\n\nexport function ChatPreview({\n  initialMessages = DEFAULT_MESSAGES,\n  reply = DEFAULT_REPLY,\n  showAvatars = false,\n  showMetadata = false,\n  showRail = false,\n  assistantVariant = \"soft\",\n  userVariant = \"solid\",\n  placeholder = \"Send a message…\",\n  className,\n  viewportClassName,\n}: ChatPreviewProps) {\n  const reduce = useReducedMotion() ?? false;\n  const nextId = useRef(0);\n  const replyTimer = useRef<number | undefined>(undefined);\n  const [messages, setMessages] = useState<RenderedChatMessage[]>(() =>\n    initialMessages.map((message) => ({ ...message, animateIn: false })),\n  );\n  const [pending, setPending] = useState(false);\n  const [activeReply, setActiveReply] = useState<{\n    id: string;\n    content: string;\n  } | null>(null);\n  const loading = pending || activeReply !== null;\n\n  useEffect(() => {\n    if (!activeReply) return;\n\n    if (reduce) {\n      setMessages((current) =>\n        current.map((message) =>\n          message.id === activeReply.id\n            ? { ...message, content: activeReply.content, streaming: false }\n            : message,\n        ),\n      );\n      setActiveReply(null);\n      return;\n    }\n\n    const startedAt = performance.now() + STREAM_DELAY;\n    let frame = 0;\n    const stream = (now: number) => {\n      const cursor = Math.min(\n        activeReply.content.length,\n        Math.floor(\n          (Math.max(0, now - startedAt) / 1000) * CHARACTERS_PER_SECOND,\n        ),\n      );\n      const content = activeReply.content.slice(0, cursor);\n      setMessages((current) =>\n        current.map((message) =>\n          message.id === activeReply.id && message.content !== content\n            ? { ...message, content }\n            : message,\n        ),\n      );\n\n      if (cursor < activeReply.content.length) {\n        frame = requestAnimationFrame(stream);\n      } else {\n        setMessages((current) =>\n          current.map((message) =>\n            message.id === activeReply.id\n              ? { ...message, streaming: false }\n              : message,\n          ),\n        );\n        setActiveReply(null);\n      }\n    };\n\n    frame = requestAnimationFrame(stream);\n    return () => cancelAnimationFrame(frame);\n  }, [activeReply, reduce]);\n\n  useEffect(\n    () => () => {\n      if (replyTimer.current) window.clearTimeout(replyTimer.current);\n    },\n    [],\n  );\n\n  const submit = useCallback(\n    (prompt: string) => {\n      if (loading) return;\n\n      const run = nextId.current++;\n      const userId = `sent-user-${run}`;\n      const assistantId = `sent-assistant-${run}`;\n      const response = typeof reply === \"function\" ? reply(prompt) : reply;\n\n      // The reply's bubble opens with the typing dots in it and streams into\n      // the same bubble, so nothing swaps when the first words arrive.\n      setMessages((current) => [\n        ...current,\n        { id: userId, from: \"user\", content: prompt, animateIn: true },\n        {\n          id: assistantId,\n          from: \"assistant\",\n          content: \"\",\n          animateIn: true,\n          streaming: true,\n        },\n      ]);\n      setPending(true);\n\n      replyTimer.current = window.setTimeout(() => {\n        setPending(false);\n        setActiveReply({ id: assistantId, content: response });\n      }, reduce ? 0 : 420);\n    },\n    [loading, reduce, reply],\n  );\n\n  const stop = useCallback(() => {\n    if (replyTimer.current) window.clearTimeout(replyTimer.current);\n    replyTimer.current = undefined;\n    setPending(false);\n    // A reply stopped before its first word leaves no empty bubble behind.\n    setMessages((current) =>\n      current\n        .filter((message) => !(message.streaming && !message.content))\n        .map((message) =>\n          message.streaming ? { ...message, streaming: false } : message,\n        ),\n    );\n    setActiveReply(null);\n  }, []);\n\n  return (\n    <div\n      className={cn(\n        \"flex h-[440px] w-full max-w-xl flex-col overflow-hidden rounded-2xl border border-border/70 bg-background\",\n        className,\n      )}\n    >\n      <MessageScroller\n        busy={loading}\n        navigation={showRail ? \"rail\" : undefined}\n        className=\"min-h-0 flex-1\"\n        viewportClassName={cn(\"px-3 py-4\", viewportClassName)}\n        contentClassName=\"min-h-full\"\n      >\n        <MessageGroup spacing=\"default\">\n          {messages.map((message) => (\n            <Message\n              key={message.id}\n              id={message.id}\n              from={message.from}\n              animateIn={message.from === \"user\" && message.animateIn}\n            >\n              {showAvatars ? (\n                <MessageAvatar>\n                  {message.from === \"user\" ? <User /> : <Bot />}\n                </MessageAvatar>\n              ) : null}\n              <MessageContent>\n                {showMetadata ? (\n                  <MessageHeader>\n                    <span className=\"font-medium text-foreground/70\">\n                      {message.from === \"user\" ? \"You\" : \"Assistant\"}\n                    </span>\n                    <span>{message.streaming ? \"Responding\" : \"Now\"}</span>\n                  </MessageHeader>\n                ) : null}\n                <MessageBubble\n                  variant={\n                    message.from === \"user\" ? userVariant : assistantVariant\n                  }\n                  // The reply's bubble pops from its corner; a sent row\n                  // already rises as a whole.\n                  animateIn={message.from === \"assistant\" && message.animateIn}\n                >\n                  <MessageBubbleContent>\n                    {message.from === \"assistant\" ? (\n                      <StreamingResponse\n                        status={message.streaming ? \"streaming\" : \"complete\"}\n                        showActions={false}\n                        announce={false}\n                      >\n                        {message.content || <MessageTyping />}\n                      </StreamingResponse>\n                    ) : (\n                      message.content\n                    )}\n                  </MessageBubbleContent>\n                </MessageBubble>\n                {showMetadata && message.from === \"user\" ? (\n                  <MessageFooter>Sent</MessageFooter>\n                ) : null}\n              </MessageContent>\n            </Message>\n          ))}\n        </MessageGroup>\n      </MessageScroller>\n\n      <div className=\"shrink-0 border-t border-border/60 p-2\">\n        <PromptInput\n          minRows={1}\n          maxRows={1}\n          loading={loading}\n          onSubmit={submit}\n          onStop={stop}\n          placeholder={placeholder}\n          className=\"border-0 bg-muted shadow-none focus-within:border-transparent\"\n        />\n      </div>\n    </div>\n  );\n}\n"},{"path":"components/agents/message.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  createContext,\n  type ReactNode,\n  useContext,\n} from \"react\";\nimport { MessageSideContext } from \"@/components/agents/message-context\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport {\n  MessageBubble,\n  MessageBubbleCollapsible,\n  MessageBubbleContent,\n  MessageBubbleGroup,\n} from \"@/components/agents/message-bubble\";\nexport type { MessageScrollerProps } from \"@/components/agents/message-scroller\";\nexport { MessageScroller } from \"@/components/agents/message-scroller\";\n\nexport type MessageFrom = \"user\" | \"assistant\";\n\nexport const messageMessages = {\n  user: \"user message\",\n  assistant: \"assistant message\",\n  typing: \"Responding\",\n};\n\nexport type MessageMessages = typeof messageMessages;\n\ninterface MessageContextValue {\n  from: MessageFrom;\n}\n\nconst MessageContext = createContext<MessageContextValue>({\n  from: \"assistant\",\n});\n\nexport interface MessageProps\n  extends Omit<ComponentPropsWithRef<typeof motion.article>, \"children\"> {\n  /** Who sent it; \"user\" rows align to the end, \"assistant\" rows to the start. */\n  from: MessageFrom;\n  /** Plays a trailing-edge pop-up once when this message row mounts. */\n  animateIn?: boolean;\n  children: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<MessageMessages>;\n}\n\nexport interface MessageGroupProps extends ComponentPropsWithRef<\"div\"> {\n  /** Gap between messages: 6 px for \"compact\", 16 px for \"default\". Default: \"compact\" */\n  spacing?: \"compact\" | \"default\";\n}\n\nexport interface MessageAvatarProps extends ComponentPropsWithRef<\"div\"> {\n  /** Keep an empty avatar slot so grouped messages remain aligned. */\n  placeholder?: boolean;\n}\n\nexport type MessageContentProps = ComponentPropsWithRef<\"div\">;\nexport type MessageHeaderProps = ComponentPropsWithRef<\"div\">;\nexport type MessageFooterProps = ComponentPropsWithRef<\"div\">;\n\nexport type MessageMarkerProps = ComponentPropsWithRef<\"div\">;\n\nexport interface MessageTypingProps extends ComponentPropsWithRef<\"span\"> {\n  /** Screen reader text for the typing dots. Default: \"Responding\" */\n  label?: string;\n}\n\n// A sent row should rise from the live edge without changing measured layout.\nconst MESSAGE_POP_UP = {\n  type: \"spring\",\n  stiffness: 480,\n  damping: 32,\n  mass: 0.62,\n} as const;\n\nexport function Message({\n  from,\n  animateIn = false,\n  children,\n  className,\n  initial,\n  animate,\n  transition,\n  exit,\n  style,\n  labels,\n  ...props\n}: MessageProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"message\", messageMessages, labels);\n\n  return (\n    <MessageSideContext.Provider value={from === \"user\" ? \"end\" : \"start\"}>\n      <MessageContext.Provider value={{ from }}>\n        <motion.article\n          data-slot=\"message\"\n          data-from={from}\n          aria-label={props[\"aria-label\"] ?? t(from)}\n          initial={\n            initial ??\n            (animateIn && !reduce\n              ? {\n                  opacity: 0,\n                  transform: \"translateY(8px) scale(0.95)\",\n                }\n              : false)\n          }\n          animate={\n            animate ??\n            (animateIn && !reduce\n              ? {\n                  opacity: 1,\n                  transform: \"translateY(0px) scale(1)\",\n                }\n              : { opacity: 1 })\n          }\n          exit={\n            exit ??\n            (reduce\n              ? { opacity: 0 }\n              : {\n                  opacity: 0,\n                  transform: \"translateY(-3px) scale(0.99)\",\n                })\n          }\n          transition={\n            transition ?? (reduce ? { duration: 0.12 } : MESSAGE_POP_UP)\n          }\n          style={{\n            transformOrigin: from === \"user\" ? \"100% 100%\" : \"0% 100%\",\n            ...style,\n          }}\n          className={cn(\n            \"group/message flex w-full items-start gap-2\",\n            from === \"user\" ? \"flex-row-reverse\" : \"flex-row\",\n            className,\n          )}\n          {...props}\n        >\n          {children}\n        </motion.article>\n      </MessageContext.Provider>\n    </MessageSideContext.Provider>\n  );\n}\n\nexport function MessageGroup({\n  spacing = \"compact\",\n  className,\n  ...props\n}: MessageGroupProps) {\n  return (\n    <div\n      data-slot=\"message-group\"\n      className={cn(\n        \"flex w-full flex-col\",\n        spacing === \"compact\" ? \"gap-1.5\" : \"gap-4\",\n        // A message that follows one from the same speaker tightens its\n        // bubble's top corner on that side, so the run reads as one turn.\n        \"[&>[data-from=user]+[data-from=user]_[data-slot=message-bubble-content]]:rounded-se-md\",\n        \"[&>[data-from=assistant]+[data-from=assistant]_[data-slot=message-bubble-content]]:rounded-ss-md\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageAvatar({\n  placeholder = false,\n  children,\n  className,\n  ...props\n}: MessageAvatarProps) {\n  return (\n    <div\n      data-slot=\"message-avatar\"\n      aria-hidden={placeholder || undefined}\n      className={cn(\n        \"grid size-7 shrink-0 place-items-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground [&_img]:size-full [&_img]:object-cover [&_svg]:size-3.5\",\n        placeholder && \"invisible\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport function MessageContent({ className, ...props }: MessageContentProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-content\"\n      className={cn(\n        \"flex min-w-0 flex-1 flex-col gap-1.5\",\n        from === \"user\" ? \"items-end\" : \"items-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageHeader({ className, ...props }: MessageHeaderProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-header\"\n      className={cn(\n        // No inset: the label lines up with the edge of the bubble or text\n        // below it, whichever variant is used.\n        \"flex items-center gap-1.5 text-[11px] leading-none text-muted-foreground\",\n        from === \"user\" ? \"justify-end\" : \"justify-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageFooter({ className, ...props }: MessageFooterProps) {\n  const { from } = useContext(MessageContext);\n\n  return (\n    <div\n      data-slot=\"message-footer\"\n      className={cn(\n        \"flex min-h-5 items-center gap-1 text-[11px] text-muted-foreground\",\n        from === \"user\" ? \"justify-end\" : \"justify-start\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageMarker({ className, ...props }: MessageMarkerProps) {\n  return (\n    <div\n      data-slot=\"message-marker\"\n      className={cn(\n        \"mx-auto flex w-fit max-w-[88%] items-center gap-1.5 rounded-full bg-muted/70 px-2.5 py-1 text-center text-xs text-muted-foreground\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function MessageTyping({\n  label,\n  className,\n  ...props\n}: MessageTypingProps) {\n  const reduce = useReducedMotion() ?? false;\n  const t = useMessages(\"message\", messageMessages);\n\n  return (\n    <span\n      data-slot=\"message-typing\"\n      className={cn(\"inline-flex h-5 items-center gap-1\", className)}\n      {...props}\n    >\n      <span className=\"sr-only\">{label ?? t(\"typing\")}</span>\n      {[0, 1, 2].map((index) => (\n        <motion.span\n          key={index}\n          aria-hidden=\"true\"\n          className=\"size-1 rounded-full bg-current\"\n          animate={\n            reduce\n              ? { opacity: 0.45 }\n              : { opacity: [0.28, 0.85, 0.28], y: [0, -2, 0] }\n          }\n          transition={{\n            duration: 1.05,\n            ease: EASE_OUT,\n            repeat: Number.POSITIVE_INFINITY,\n            delay: index * 0.14,\n          }}\n        />\n      ))}\n    </span>\n  );\n}\n"},{"path":"components/agents/message-bubble.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronDown } from \"lucide-react\";\nimport {\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  cloneElement,\n  createContext,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { MessageSideContext } from \"@/components/agents/message-context\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\nexport type MessageBubbleVariant =\n  | \"solid\"\n  | \"soft\"\n  | \"tint\"\n  | \"outline\"\n  | \"ghost\"\n  | \"danger\";\nexport type MessageBubbleAlign = \"start\" | \"end\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const messageBubbleMessages = {\n  showMore: \"Show more\",\n  showLess: \"Show less\",\n};\n\nexport type MessageBubbleMessages = typeof messageBubbleMessages;\n\ninterface MessageBubbleContextValue {\n  align?: MessageBubbleAlign;\n  animateIn: boolean;\n  variant: MessageBubbleVariant;\n  labels?: Partial<MessageBubbleMessages>;\n}\n\nconst MessageBubbleContext = createContext<MessageBubbleContextValue>({\n  animateIn: true,\n  variant: \"soft\",\n});\n\nexport interface MessageBubbleProps\n  extends Omit<HTMLMotionProps<\"div\">, \"children\"> {\n  /** Fill and border style of the bubble. Default: \"soft\" */\n  variant?: MessageBubbleVariant;\n  /** Defaults to the surrounding Message alignment when omitted. */\n  align?: MessageBubbleAlign;\n  /** Plays the bubble entrance once when this component mounts. */\n  animateIn?: boolean;\n  /** Override any built-in string. */\n  labels?: Partial<MessageBubbleMessages>;\n  children?: ReactNode;\n}\n\nexport interface MessageBubbleContentProps\n  extends ComponentPropsWithRef<\"div\"> {\n  /** Replaces the content element while preserving bubble styling. */\n  render?: ReactElement;\n}\n\nexport interface MessageBubbleGroupProps extends ComponentPropsWithRef<\"div\"> {\n  /** Gap between bubbles. Default: \"compact\" */\n  spacing?: \"compact\" | \"default\";\n}\n\nexport interface MessageBubbleCollapsibleProps\n  extends ComponentPropsWithRef<\"div\"> {\n  /** Whether the full text shows, for controlled use. */\n  open?: boolean;\n  /** Whether the full text shows at first when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the text expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Lines shown while collapsed. Default: 4 */\n  collapsedLines?: 2 | 3 | 4 | 5 | 6;\n  /** Text of the expand button. Default: \"Show more\" */\n  moreLabel?: ReactNode;\n  /** Text of the collapse button. Default: \"Show less\" */\n  lessLabel?: ReactNode;\n  /** Classes merged onto the clamped text wrapper. */\n  contentClassName?: string;\n  /** Classes merged onto the show more button. */\n  triggerClassName?: string;\n  children?: ReactNode;\n}\n\nconst BUBBLE_CONTENT_REVEAL = {\n  duration: 0.12,\n  ease: EASE_OUT,\n  delay: 0.04,\n} as const;\n\n// Expanded text wipes in top to bottom, quick enough to read straight on.\nconst REVEAL = { duration: 0.32, ease: EASE_OUT } as const;\n// Clamped text stays solid to here (%), then fades out by the bottom.\nconst CLAMP_SOLID = 68;\n// How soft the moving edge of the wipe is, in % of the text's height.\nconst WIPE_EDGE = 12;\n\n// Sent bubbles should pop into place quickly with one restrained overshoot.\nconst BUBBLE_POP = {\n  type: \"spring\",\n  stiffness: 520,\n  damping: 27,\n  mass: 0.52,\n} as const;\n\nexport function MessageBubble({\n  variant = \"soft\",\n  align,\n  animateIn = false,\n  labels,\n  className,\n  children,\n  initial,\n  animate,\n  exit,\n  transition,\n  layout,\n  ...props\n}: MessageBubbleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const messageSide = useContext(MessageSideContext);\n  const resolvedAlign = align ?? messageSide ?? \"start\";\n\n  return (\n    <MessageBubbleContext.Provider\n      value={{ align: resolvedAlign, animateIn, variant, labels }}\n    >\n      <motion.div\n        data-slot=\"message-bubble\"\n        data-align={resolvedAlign}\n        data-variant={variant}\n        layout={layout}\n        initial={initial ?? false}\n        animate={animate}\n        exit={\n          exit ??\n          (reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.99 })\n        }\n        transition={transition ?? (reduce ? { duration: 0.12 } : SPRING_LAYOUT)}\n        className={cn(\n          \"group/bubble flex w-full flex-col\",\n          resolvedAlign === \"end\" ? \"items-end\" : \"items-start\",\n          className,\n        )}\n        {...props}\n      >\n        {children}\n      </motion.div>\n    </MessageBubbleContext.Provider>\n  );\n}\n\nfunction bubbleContentClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n  interactive: boolean,\n) {\n  return cn(\n    \"relative z-0 min-w-9 max-w-[82%] rounded-2xl px-3.5 py-2.5 text-sm leading-6 text-foreground\",\n    // The corner by the speaker is tighter, so a bubble points at who said it.\n    align === \"end\" ? \"rounded-ee-md\" : \"rounded-es-md\",\n    \"[&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-background/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5 [&_p+p]:mt-2 [&_pre]:my-2 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:bg-background/60 [&_pre]:p-3 [&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5\",\n    variant === \"solid\" &&\n      \"text-primary-foreground [&_code]:bg-primary-foreground/15 [&_pre]:bg-primary-foreground/15\",\n    variant === \"ghost\" && \"w-full max-w-none rounded-none px-0 py-0\",\n    variant === \"danger\" && \"text-destructive\",\n    interactive &&\n      \"cursor-pointer text-left outline-none transition-[background-color,color,transform] duration-150 hover:brightness-[0.98] focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.99]\",\n  );\n}\n\nfunction bubbleSurfaceClass(\n  variant: MessageBubbleVariant,\n  align: MessageBubbleAlign,\n) {\n  return cn(\n    \"pointer-events-none absolute inset-0 -z-10 rounded-[inherit]\",\n    align === \"end\" ? \"origin-bottom-right\" : \"origin-bottom-left\",\n    variant === \"solid\" && \"bg-primary\",\n    variant === \"soft\" && \"bg-muted\",\n    variant === \"tint\" && \"bg-muted\",\n    variant === \"outline\" && \"border border-border/70 bg-background\",\n    variant === \"danger\" && \"bg-destructive/10\",\n  );\n}\n\nexport function MessageBubbleContent({\n  render,\n  className,\n  children,\n  ref,\n  ...props\n}: MessageBubbleContentProps) {\n  const reduce = useReducedMotion() ?? false;\n  const { align = \"start\", animateIn, variant } =\n    useContext(MessageBubbleContext);\n  const interactive =\n    render?.type === \"button\" || render?.type === \"a\";\n  const classes = cn(\n    bubbleContentClass(variant, align, interactive),\n    className,\n  );\n  const composedChildren = (\n    <>\n      {/* The surface pops in once, then always matches its text: a surface\n          that springs after its content leaves streamed lines and expanded\n          text hanging outside the bubble. */}\n      {variant !== \"ghost\" ? (\n        <motion.span\n          aria-hidden=\"true\"\n          initial={\n            animateIn && !reduce\n              ? {\n                  opacity: 0,\n                  scale: 0.92,\n                }\n              : false\n          }\n          animate={{ opacity: 1, scale: 1 }}\n          transition={\n            reduce\n              ? { duration: 0 }\n              : {\n                  opacity: { duration: 0.12, ease: EASE_OUT },\n                  scale: BUBBLE_POP,\n                }\n          }\n          className={bubbleSurfaceClass(variant, align)}\n        />\n      ) : null}\n      <motion.div\n        initial={animateIn ? { opacity: 0 } : false}\n        animate={{ opacity: 1 }}\n        transition={\n          reduce ? { duration: 0.12, ease: EASE_OUT } : BUBBLE_CONTENT_REVEAL\n        }\n        className=\"relative\"\n      >\n        {children}\n      </motion.div>\n    </>\n  );\n\n  if (render) {\n    const child = render as ReactElement<\n      Record<string, unknown> & { className?: string; ref?: Ref<HTMLElement> }\n    >;\n\n    return cloneElement(child, {\n      ...props,\n      ref: mergeRefs(child.props.ref, ref as Ref<HTMLElement> | undefined),\n      className: cn(classes, child.props.className),\n      children: composedChildren,\n      \"data-slot\": \"message-bubble-content\",\n    });\n  }\n\n  return (\n    <div\n      ref={ref}\n      data-slot=\"message-bubble-content\"\n      className={classes}\n      {...props}\n    >\n      {composedChildren}\n    </div>\n  );\n}\n\nexport function MessageBubbleGroup({\n  spacing = \"compact\",\n  className,\n  ...props\n}: MessageBubbleGroupProps) {\n  return (\n    <div\n      data-slot=\"message-bubble-group\"\n      className={cn(\n        \"flex w-full flex-col\",\n        spacing === \"compact\" ? \"gap-1.5\" : \"gap-3\",\n        // A bubble that follows one from the same speaker tightens its top\n        // corner on that side too, so the run reads as one turn.\n        \"[&>[data-align=end]+[data-align=end]_[data-slot=message-bubble-content]]:rounded-se-md\",\n        \"[&>[data-align=start]+[data-align=start]_[data-slot=message-bubble-content]]:rounded-ss-md\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nconst LINE_CLAMP_CLASS = {\n  2: \"line-clamp-2\",\n  3: \"line-clamp-3\",\n  4: \"line-clamp-4\",\n  5: \"line-clamp-5\",\n  6: \"line-clamp-6\",\n} as const;\n\nexport function MessageBubbleCollapsible({\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  collapsedLines = 4,\n  moreLabel,\n  lessLabel,\n  contentClassName,\n  triggerClassName,\n  className,\n  children,\n  ...props\n}: MessageBubbleCollapsibleProps) {\n  const reduce = useReducedMotion() ?? false;\n  const contentId = useId();\n  const t = useMessages(\n    \"messageBubble\",\n    messageBubbleMessages,\n    useContext(MessageBubbleContext).labels,\n  );\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const contentRef = useRef<HTMLDivElement>(null);\n  // Where the clamped text ended, as a share of the full text: the reveal\n  // starts there, so the lines already on screen never blink.\n  const clampedHeight = useRef(0);\n  // The fade mask, from solid (`solid`%) to clear (`clear`%). Clamped, it\n  // softens the last lines; open, it wipes down until the text is all solid.\n  const solid = useMotionValue(currentOpen ? 100 : CLAMP_SOLID);\n  const clear = useMotionValue(currentOpen ? 100 + WIPE_EDGE : 100);\n  const mask = useMotionTemplate`linear-gradient(to bottom, #000 ${solid}%, transparent ${clear}%)`;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next) clampedHeight.current = contentRef.current?.offsetHeight ?? 0;\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  // Opening shows the whole text at once (no height animation) and wipes the\n  // new lines in from the top; closing clamps straight back.\n  useLayoutEffect(() => {\n    if (!currentOpen) {\n      solid.set(CLAMP_SOLID);\n      clear.set(100);\n      return;\n    }\n    const full = contentRef.current?.offsetHeight ?? 0;\n    const start =\n      reduce || !full || !clampedHeight.current\n        ? 100\n        : Math.min(100, (clampedHeight.current / full) * 100 - WIPE_EDGE);\n    solid.set(start);\n    clear.set(start + WIPE_EDGE);\n    if (start >= 100) return;\n    const toSolid = animate(solid, 100, REVEAL);\n    const toClear = animate(clear, 100 + WIPE_EDGE, REVEAL);\n    return () => {\n      toSolid.stop();\n      toClear.stop();\n    };\n  }, [currentOpen, reduce, solid, clear]);\n\n  return (\n    <div\n      data-slot=\"message-bubble-collapsible\"\n      data-state={currentOpen ? \"open\" : \"closed\"}\n      className={cn(\"w-full\", className)}\n      {...props}\n    >\n      <motion.div\n        ref={contentRef}\n        id={contentId}\n        style={{ maskImage: mask, WebkitMaskImage: mask }}\n        className={cn(\n          !currentOpen && LINE_CLAMP_CLASS[collapsedLines],\n          contentClassName,\n        )}\n      >\n        {children}\n      </motion.div>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className={cn(\n          \"mt-2 inline-flex h-7 items-center gap-1 rounded-full px-2 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n          triggerClassName,\n        )}\n      >\n        <span>{currentOpen\n            ? (lessLabel ?? t(\"showLess\"))\n            : (moreLabel ?? t(\"showMore\"))}</span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n    </div>\n  );\n}\n"},{"path":"components/agents/prompt-input.tsx","type":"util","content":"\"use client\";\n\nimport { ArrowUp, ChevronDown, Plus, Square } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type TextareaHTMLAttributes,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { ClipResizeFrame } from \"@/components/agents/clip-resize-frame\";\nimport { Button } from \"@/components/motion/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@/components/motion/dropdown-menu\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** One identity for the default, so the filtered list stays stable. */\nconst NO_COMMANDS: PromptCommand[] = [];\n\n// The slash list rises in and drops away faster; rows fade in and out as the\n// filter changes, and the rest slide into place.\nconst LIST_IN = { duration: 0.18, ease: EASE_OUT } as const;\nconst LIST_OUT = { duration: 0.12, ease: EASE_OUT } as const;\nconst ROW_OUT = { duration: 0.1, ease: EASE_OUT } as const;\nconst ROW_MOVE = { layout: SPRING_LAYOUT, opacity: { duration: 0.16, ease: EASE_OUT } } as const;\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const promptInputMessages = {\n  placeholder: \"Ask the agent to do something…\",\n  label: \"Prompt\",\n  addToPrompt: \"Add to prompt\",\n  chooseModel: \"Choose model\",\n  send: \"Send prompt\",\n  stop: \"Stop generating\",\n  commands: \"Commands\",\n};\n\nexport type PromptInputMessages = typeof promptInputMessages;\n\nexport interface PromptModel {\n  /** Unique key, passed to `onModelChange` and `onSubmit`. */\n  value: string;\n  /** Name shown in the model menu and on its trigger when selected. */\n  label: ReactNode;\n  /** Icon before the label in the menu and on the trigger. */\n  icon?: ReactNode;\n  /** Stops the model from being picked. */\n  disabled?: boolean;\n}\n\nexport interface PromptAction {\n  /** Unique key, passed to `onAction` when the item is chosen. */\n  value: string;\n  /** Item text in the add menu. */\n  label: ReactNode;\n  /** Muted line under the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n  /** Stops the item from being chosen. */\n  disabled?: boolean;\n}\n\nexport interface PromptCommand {\n  /** What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt. */\n  value: string;\n  /** Name shown in the command list. Also matched while typing. */\n  label: string;\n  /** Muted line beside the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n}\n\nexport interface PromptInputProps extends Omit<\n  TextareaHTMLAttributes<HTMLTextAreaElement>,\n  \"value\" | \"defaultValue\" | \"onChange\" | \"onSubmit\" | \"children\"\n> {\n  /** The prompt text, for controlled use. */\n  value?: string;\n  /** The initial prompt text when uncontrolled. Default: \"\" */\n  defaultValue?: string;\n  /** Called with the new text on every edit. */\n  onValueChange?: (value: string) => void;\n  /** Models listed in the model menu. Hidden when empty. */\n  models?: PromptModel[];\n  /** The selected model's value, for controlled use. */\n  model?: string;\n  /** The initial model when uncontrolled. Default: the first model */\n  defaultModel?: string;\n  /** Called with the model's value when a model is picked. */\n  onModelChange?: (model: string) => void;\n  /** Items in the add menu next to the input. Hidden when empty. */\n  actions?: PromptAction[];\n  /** Called with the action's value when an add menu item is chosen. */\n  onAction?: (action: string) => void;\n  /** Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty. */\n  commands?: PromptCommand[];\n  /** Called with the command's value when a slash command is picked. */\n  onCommand?: (command: string) => void;\n  /** Called with the trimmed prompt and selected model on Enter or the send button. */\n  onSubmit?: (value: string, model?: string) => void | Promise<void>;\n  /** Swaps send for a stop button and blocks new prompts. Default: false */\n  loading?: boolean;\n  /** Called when the stop button is pressed while loading. */\n  onStop?: () => void;\n  /** Height of the empty input, in text rows. Default: 2 */\n  minRows?: number;\n  /** Rows the input grows to before it scrolls. Default: 8 */\n  maxRows?: number;\n  /** Extra controls placed between the add menu and the model menu. */\n  leadingAction?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<PromptInputMessages>;\n  /** Classes merged onto the form element. */\n  className?: string;\n}\n\nexport function PromptInput({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  models = [],\n  model,\n  defaultModel,\n  onModelChange,\n  actions = [],\n  onAction,\n  commands = NO_COMMANDS,\n  onCommand,\n  onSubmit,\n  loading = false,\n  onStop,\n  minRows = 2,\n  maxRows = 8,\n  leadingAction,\n  labels,\n  className,\n  disabled,\n  placeholder,\n  \"aria-label\": ariaLabel,\n  onKeyDown,\n  ...textareaProps\n}: PromptInputProps) {\n  const t = useMessages(\"promptInput\", promptInputMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const measurementRef = useRef<HTMLDivElement>(null);\n  const [internalValue, setInternalValue] = useState(defaultValue);\n  const [internalModel, setInternalModel] = useState(\n    defaultModel ?? models[0]?.value,\n  );\n  const [actionsOpen, setActionsOpen] = useState(false);\n  const [modelsOpen, setModelsOpen] = useState(false);\n  const currentValue = value ?? internalValue;\n  const currentModelValue = model ?? internalModel;\n  const currentModel = models.find(\n    (option) => option.value === currentModelValue,\n  );\n  const canSubmit = Boolean(currentValue.trim()) && !disabled && !loading;\n\n  // Slash commands: the word before the caret, when it starts with `/`.\n  const [caret, setCaret] = useState(currentValue.length);\n  // Escape closes the list for the slash it was opened by, until another one.\n  const [dismissedAt, setDismissedAt] = useState(-1);\n  const baseId = useId();\n  const slash = commands.length\n    ? /(?:^|\\s)\\/([\\w-]*)$/.exec(currentValue.slice(0, caret))\n    : null;\n  const query = slash ? slash[1].toLowerCase() : \"\";\n  const slashAt = slash ? caret - slash[1].length - 1 : -1;\n  const matches = slash\n    ? commands.filter(\n        (command) =>\n          command.value.toLowerCase().includes(query) ||\n          command.label.toLowerCase().includes(query),\n      )\n    : NO_COMMANDS;\n  const slashOpen = matches.length > 0 && slashAt !== dismissedAt && !disabled;\n  const commandRows = matches.map((command) => ({ id: command.value }));\n  const { activeIndex, moveTo, moveActive } = useRowCursor(commandRows, query);\n  const activeCommand = slashOpen ? matches[activeIndex] : undefined;\n  const listId = `${baseId}-commands`;\n  const optionId = (value: string) => `${baseId}-command-${value}`;\n  // Pointer moves glide the highlight; arrow keys jump it, a spring would\n  // only trail behind fast arrowing.\n  const [glide, setGlide] = useState(false);\n\n  const pickCommand = (command: PromptCommand) => {\n    const inserted = `/${command.value} `;\n    const next =\n      currentValue.slice(0, slashAt) + inserted + currentValue.slice(caret);\n    const nextCaret = slashAt + inserted.length;\n    setValue(next);\n    setCaret(nextCaret);\n    onCommand?.(command.value);\n    requestAnimationFrame(() => {\n      textareaRef.current?.focus({ preventScroll: true });\n      textareaRef.current?.setSelectionRange(nextCaret, nextCaret);\n    });\n  };\n\n  const resizeTextarea = useCallback(() => {\n    const textarea = textareaRef.current;\n    const measurement = measurementRef.current;\n    if (!textarea || !measurement || textarea.value !== currentValue) return;\n\n    const lineHeight = 24;\n    const nextHeight = Math.min(\n      Math.max(measurement.scrollHeight, minRows * lineHeight),\n      maxRows * lineHeight,\n    );\n    const height = `${nextHeight}px`;\n    if (textarea.style.height !== height) textarea.style.height = height;\n  }, [currentValue, maxRows, minRows]);\n\n  useLayoutEffect(() => {\n    resizeTextarea();\n  }, [resizeTextarea]);\n\n  useEffect(() => {\n    const textarea = textareaRef.current;\n    if (!textarea || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(resizeTextarea);\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [resizeTextarea]);\n\n  const setValue = (next: string) => {\n    if (value === undefined) setInternalValue(next);\n    onValueChange?.(next);\n  };\n\n  const setModel = (next: string) => {\n    if (model === undefined) setInternalModel(next);\n    onModelChange?.(next);\n  };\n\n  const submit = (event?: FormEvent) => {\n    event?.preventDefault();\n    const prompt = currentValue.trim();\n    if (!prompt || disabled || loading) return;\n\n    onSubmit?.(prompt, currentModelValue);\n    if (value === undefined) setInternalValue(\"\");\n    textareaRef.current?.focus({ preventScroll: true });\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n    onKeyDown?.(event);\n    if (slashOpen && !event.defaultPrevented && !event.nativeEvent.isComposing) {\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        setGlide(false);\n        moveActive(event.key === \"ArrowDown\" ? 1 : -1);\n        return;\n      }\n      if ((event.key === \"Enter\" && !event.shiftKey) || event.key === \"Tab\") {\n        event.preventDefault();\n        if (activeCommand) pickCommand(activeCommand);\n        return;\n      }\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        setDismissedAt(slashAt);\n        return;\n      }\n    }\n    if (\n      event.defaultPrevented ||\n      event.key !== \"Enter\" ||\n      event.shiftKey ||\n      event.nativeEvent.isComposing\n    ) {\n      return;\n    }\n    event.preventDefault();\n    submit();\n  };\n\n  return (\n    <form\n      onSubmit={submit}\n      className={cn(\n        \"relative w-full rounded-3xl border border-border/80 bg-background p-2 transition-colors focus-within:border-foreground/25\",\n        disabled && \"opacity-60\",\n        className,\n      )}\n    >\n      <div\n        ref={measurementRef}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none invisible absolute inset-x-2 top-0 whitespace-pre-wrap px-2 text-sm leading-6 [overflow-wrap:break-word]\"\n      >\n        {`${currentValue}\\u200b`}\n      </div>\n\n      {/* The list rises a few px out of the input as it fades in, and drops\n          back faster. Focus stays in the input, which drives it with the arrow\n          keys. As you filter, its top edge glides (the list is anchored at its\n          bottom, above the input), leaving rows fade and the rest slide into\n          place, instead of the edge and rows jumping. */}\n      <AnimatePresence>\n        {slashOpen ? (\n          <motion.div\n            key=\"commands\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={\n              reduce\n                ? { opacity: 0, pointerEvents: \"none\", transition: LIST_OUT }\n                : { opacity: 0, y: 4, pointerEvents: \"none\", transition: LIST_OUT }\n            }\n            transition={LIST_IN}\n            style={{ transformOrigin: \"bottom left\" }}\n            className=\"absolute inset-x-0 bottom-full z-20 mb-2\"\n          >\n            <ClipResizeFrame edge=\"top\" contentClassName=\"p-2\">\n              <div\n                id={listId}\n                role=\"listbox\"\n                aria-label={t(\"commands\")}\n                className=\"relative max-h-60 overflow-y-auto overscroll-contain\"\n              >\n                <AnimatePresence initial={false} mode=\"popLayout\">\n            {matches.map((command, index) => {\n              const active = index === activeIndex;\n              return (\n                <motion.button\n                  layout={reduce ? false : \"position\"}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0, transition: ROW_OUT }}\n                  transition={ROW_MOVE}\n                  key={command.value}\n                  id={optionId(command.value)}\n                  type=\"button\"\n                  role=\"option\"\n                  aria-selected={active}\n                  tabIndex={-1}\n                  onPointerMove={() => {\n                    if (active) return;\n                    setGlide(true);\n                    moveTo(command.value);\n                  }}\n                  onPointerDown={(event) => event.preventDefault()}\n                  onClick={() => pickCommand(command)}\n                  className={cn(MENU_ITEM_CLASS, \"cursor-default gap-2.5 text-foreground\")}\n                >\n                  {active ? (\n                    <MenuItemHighlight\n                      layoutId={`${baseId}-command-highlight`}\n                      reduce={reduce}\n                      instant={!glide}\n                    />\n                  ) : null}\n                  {command.icon ? (\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"flex shrink-0 text-muted-foreground [&_svg]:size-4\"\n                    >\n                      {command.icon}\n                    </span>\n                  ) : null}\n                  <span className=\"shrink-0\">{command.label}</span>\n                  {command.description ? (\n                    <span className=\"min-w-0 truncate text-xs text-muted-foreground\">\n                      {command.description}\n                    </span>\n                  ) : null}\n                  <span className=\"ml-auto shrink-0 font-mono text-xs text-muted-foreground/70\">\n                    /{command.value}\n                  </span>\n                </motion.button>\n              );\n            })}\n                </AnimatePresence>\n              </div>\n            </ClipResizeFrame>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n      <textarea\n        ref={textareaRef}\n        value={currentValue}\n        disabled={disabled}\n        placeholder={placeholder ?? t(\"placeholder\")}\n        aria-label={ariaLabel ?? t(\"label\")}\n        rows={minRows}\n        {...textareaProps}\n        aria-autocomplete={commands.length ? \"list\" : undefined}\n        aria-controls={slashOpen ? listId : undefined}\n        aria-activedescendant={activeCommand ? optionId(activeCommand.value) : undefined}\n        onChange={(event) => {\n          setValue(event.target.value);\n          setCaret(event.target.selectionStart);\n        }}\n        onSelect={(event) => setCaret(event.currentTarget.selectionStart)}\n        onKeyDown={handleKeyDown}\n        className=\"scrollbar-hide block w-full resize-none overflow-y-auto bg-transparent px-2 pt-1.5 text-sm leading-6 text-foreground outline-none placeholder:text-muted-foreground/55\"\n      />\n\n      <div className=\"mt-1 flex min-h-8 items-center gap-1\">\n        {actions.length ? (\n          // The library menu: arrow keys and typeahead, a highlight that\n          // glides between rows, and no animation when the keyboard opens it.\n          <DropdownMenu open={actionsOpen} onOpenChange={setActionsOpen}>\n            <Tooltip content={t(\"addToPrompt\")} side=\"top\">\n              <AddButton\n                open={actionsOpen}\n                reduce={reduce}\n                disabled={disabled || loading}\n                aria-label={t(\"addToPrompt\")}\n              />\n            </Tooltip>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-72\">\n              {actions.map((action) => (\n                <DropdownMenuItem\n                  key={action.value}\n                  disabled={action.disabled}\n                  onSelect={() => onAction?.(action.value)}\n                  textValue={typeof action.label === \"string\" ? action.label : undefined}\n                  className=\"items-start\"\n                >\n                  {action.icon ? (\n                    <span aria-hidden=\"true\" className=\"mt-0.5 flex shrink-0\">\n                      {action.icon}\n                    </span>\n                  ) : null}\n                  {/* One line each: a menu row is read at a glance. */}\n                  <span className=\"min-w-0 flex-1\">\n                    <span className=\"block truncate\">{action.label}</span>\n                    {action.description ? (\n                      <span className=\"block truncate text-xs leading-4 text-muted-foreground\">\n                        {action.description}\n                      </span>\n                    ) : null}\n                  </span>\n                </DropdownMenuItem>\n              ))}\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n        {leadingAction}\n        {models.length ? (\n          // The same menu as the plus: a model is a pick from a short list,\n          // with the check at the end of the chosen row.\n          <DropdownMenu open={modelsOpen} onOpenChange={setModelsOpen}>\n            <DropdownMenuTrigger disabled={disabled || loading}>\n              <button\n                type=\"button\"\n                disabled={disabled || loading}\n                className=\"inline-flex h-8 min-w-0 max-w-52 items-center gap-1.5 rounded-full px-3 text-xs text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n              >\n                {currentModel?.icon ? (\n                  <span aria-hidden=\"true\" className=\"flex size-4 shrink-0 items-center justify-center [&_svg]:size-3.5\">\n                    {currentModel.icon}\n                  </span>\n                ) : null}\n                <span className=\"truncate\">{currentModel?.label ?? t(\"chooseModel\")}</span>\n                <motion.span\n                  aria-hidden=\"true\"\n                  animate={{ rotate: modelsOpen ? 180 : 0 }}\n                  transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                  className=\"flex shrink-0\"\n                >\n                  <ChevronDown className=\"size-3.5\" />\n                </motion.span>\n              </button>\n            </DropdownMenuTrigger>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-56\">\n              <DropdownMenuRadioGroup value={currentModelValue ?? \"\"} onValueChange={setModel}>\n                {models.map((option) => (\n                  <DropdownMenuRadioItem\n                    key={option.value}\n                    value={option.value}\n                    disabled={option.disabled}\n                    closeOnSelect\n                    textValue={typeof option.label === \"string\" ? option.label : undefined}\n                  >\n                    {option.icon ? (\n                      <span aria-hidden=\"true\" className=\"flex shrink-0\">\n                        {option.icon}\n                      </span>\n                    ) : null}\n                    <span className=\"min-w-0 truncate\">{option.label}</span>\n                  </DropdownMenuRadioItem>\n                ))}\n              </DropdownMenuRadioGroup>\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n\n        <span className=\"relative ml-auto flex\">\n          <Tooltip content={loading ? t(\"stop\") : t(\"send\")} side=\"top\">\n          <Button\n            type={loading ? \"button\" : \"submit\"}\n            size=\"icon\"\n            disabled={loading ? !onStop : !canSubmit}\n            aria-label={loading ? t(\"stop\") : t(\"send\")}\n            onClick={loading ? onStop : undefined}\n            className={cn(\n              \"size-8 rounded-full\",\n              // Nothing to send: a quiet gray chip, not a dimmed primary. It\n              // lights up the moment there is a prompt.\n              !loading && !canSubmit && \"bg-foreground/[0.06] text-muted-foreground disabled:opacity-100\",\n            )}\n          >\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              <motion.span\n                key={loading ? \"stop\" : \"send\"}\n                // A little blur melts the arrow into the square, so the swap\n                // reads as one icon changing rather than two crossing.\n                initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3, scale: 0.8, filter: \"blur(2px)\" }}\n                animate={{ opacity: 1, y: 0, scale: 1, filter: \"blur(0px)\" }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.8, filter: \"blur(2px)\" }}\n                transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                className=\"grid place-items-center\"\n              >\n                {loading ? (\n                  <Square className=\"size-3 fill-current\" />\n                ) : (\n                  <ArrowUp className=\"size-4\" />\n                )}\n              </motion.span>\n            </AnimatePresence>\n          </Button>\n          </Tooltip>\n          {/* While the agent works, a thin arc circles the stop button. */}\n          <AnimatePresence>\n            {loading ? (\n              <motion.svg\n                key=\"working\"\n                aria-hidden=\"true\"\n                viewBox=\"0 0 40 40\"\n                initial={{ opacity: 0, scale: reduce ? 1 : 0.9 }}\n                animate={{ opacity: 1, scale: 1, rotate: reduce ? 0 : 360 }}\n                exit={{ opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }}\n                transition={{\n                  opacity: { duration: 0.2, ease: EASE_OUT },\n                  scale: { duration: 0.2, ease: EASE_OUT },\n                  rotate: { duration: 1, ease: \"linear\", repeat: Number.POSITIVE_INFINITY },\n                }}\n                className=\"pointer-events-none absolute -inset-1 size-10 text-primary\"\n              >\n                <circle cx=\"20\" cy=\"20\" r=\"19\" fill=\"none\" stroke=\"currentColor\" strokeOpacity={0.15} strokeWidth=\"1.5\" />\n                <circle\n                  cx=\"20\"\n                  cy=\"20\"\n                  r=\"19\"\n                  fill=\"none\"\n                  stroke=\"currentColor\"\n                  strokeWidth=\"1.5\"\n                  strokeLinecap=\"round\"\n                  strokeDasharray=\"30 90\"\n                />\n              </motion.svg>\n            ) : null}\n          </AnimatePresence>\n        </span>\n      </div>\n    </form>\n  );\n}\n\n/**\n * The plus that opens the add menu. Its own component so the tooltip around it\n * and the menu trigger inside both reach the button: the plus turns into a\n * cross while the menu is open.\n */\nfunction AddButton({\n  open,\n  reduce,\n  ...props\n}: ComponentProps<typeof Button> & { open: boolean; reduce: boolean }) {\n  return (\n    <DropdownMenuTrigger disabled={props.disabled}>\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon\"\n        {...props}\n        className=\"size-8 rounded-full data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n      >\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: open ? 45 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"flex\"\n        >\n          <Plus className=\"size-4\" />\n        </motion.span>\n      </Button>\n    </DropdownMenuTrigger>\n  );\n}\n"},{"path":"components/agents/streaming-response.tsx","type":"util","content":"\"use client\";\n\nimport {\n  Check,\n  ChevronDown,\n  Copy,\n  RotateCcw,\n  ThumbsDown,\n  ThumbsUp,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { type ReactNode, useCallback, useId, useState } from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport {\n  type CitationItem,\n  CitationList,\n  CitationStack,\n} from \"@/components/agents/citations\";\nimport { IconSwap as ActionIcon } from \"@/components/agents/icon-swap\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { useCopy } from \"@/lib/hooks/use-copy\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport type StreamingResponseStatus = \"streaming\" | \"complete\" | \"error\";\nexport type StreamingResponseFeedback = \"up\" | \"down\" | null;\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const streamingResponseMessages = {\n  copy: \"Copy response\",\n  copied: \"Copied\",\n  retry: \"Retry response\",\n  helpful: \"Helpful\",\n  notHelpful: \"Not helpful\",\n  source: \"{count} source\",\n  sources: \"{count} sources\",\n};\n\nexport type StreamingResponseMessages = typeof streamingResponseMessages;\n\nexport interface StreamingResponseProps {\n  /** Rendered response content. Pass plain text or the output of a Markdown renderer. */\n  children: ReactNode;\n  /** Stream state; actions appear once it leaves \"streaming\". Default: \"streaming\" */\n  status?: StreamingResponseStatus;\n  /** Plain-text value copied by the built-in copy action. */\n  copyText?: string;\n  /** Overrides the built-in clipboard action. */\n  onCopy?: () => void | Promise<void>;\n  /** Called when the retry action is pressed. The action shows only when set. */\n  onRetry?: () => void;\n  /** Optional sources shown as a compact footer disclosure after streaming. */\n  sources?: CitationItem[];\n  /** Whether the sources list is expanded, for controlled use. */\n  sourcesOpen?: boolean;\n  /** Whether the sources list starts expanded when uncontrolled. Default: false */\n  defaultSourcesOpen?: boolean;\n  /** Called with the next state when the sources list expands or collapses. */\n  onSourcesOpenChange?: (open: boolean) => void;\n  /** Prefix for source row ids that `Citation` markers link to. Generated when omitted. */\n  sourceIdPrefix?: string;\n  /** The thumbs up or down rating, for controlled use. */\n  feedback?: StreamingResponseFeedback;\n  /** The initial rating when uncontrolled. Default: null */\n  defaultFeedback?: StreamingResponseFeedback;\n  /** Called with the new rating, or `null` when it is toggled off. */\n  onFeedbackChange?: (feedback: StreamingResponseFeedback) => void;\n  /** Set false when a surrounding conversation log announces streamed text. */\n  announce?: boolean;\n  /** Hides the built-in completion actions without changing response status. */\n  showActions?: boolean;\n  /** Override any built-in string. `{count}` fills `source` (one) and `sources` (many). */\n  labels?: Partial<StreamingResponseMessages>;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Classes merged onto the wrapper around the response content. */\n  contentClassName?: string;\n  /** Classes merged onto the row of completion actions. */\n  actionsClassName?: string;\n}\n\nfunction ResponseAction({\n  label,\n  active,\n  onClick,\n  children,\n}: {\n  label: string;\n  /** Set for toggle actions; exposed as `aria-pressed`. */\n  active?: boolean;\n  onClick: () => void;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion() ?? false;\n\n  return (\n    <Tooltip content={label} side=\"top\">\n      <motion.button\n        type=\"button\"\n        aria-label={label}\n        aria-pressed={active}\n        onClick={onClick}\n        whileTap={reduce ? undefined : { scale: 0.95 }}\n        transition={SPRING_PRESS}\n        className={cn(\n          // A foreground tint, not bg-muted: muted is the bubble colour, so a\n          // muted hover would vanish inside a soft bubble.\n          \"grid size-7 place-items-center rounded-full text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n          active && \"bg-foreground/[0.06] text-foreground\",\n        )}\n      >\n        {children}\n      </motion.button>\n    </Tooltip>\n  );\n}\n\nexport function StreamingResponse({\n  children,\n  status = \"streaming\",\n  copyText,\n  onCopy,\n  onRetry,\n  sources = [],\n  sourcesOpen,\n  defaultSourcesOpen = false,\n  onSourcesOpenChange,\n  sourceIdPrefix,\n  feedback,\n  defaultFeedback = null,\n  onFeedbackChange,\n  announce = true,\n  showActions = true,\n  labels,\n  className,\n  contentClassName,\n  actionsClassName,\n}: StreamingResponseProps) {\n  const t = useMessages(\"streamingResponse\", streamingResponseMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const { copied, copy: handleCopy } = useCopy({ text: copyText, onCopy });\n  const [internalFeedback, setInternalFeedback] =\n    useState<StreamingResponseFeedback>(defaultFeedback);\n  const [internalSourcesOpen, setInternalSourcesOpen] =\n    useState(defaultSourcesOpen);\n  const currentFeedback = feedback ?? internalFeedback;\n  const currentSourcesOpen = sourcesOpen ?? internalSourcesOpen;\n  const streaming = status === \"streaming\";\n  const complete = status === \"complete\";\n  const canCopy = Boolean(copyText || onCopy);\n  const hasSources = sources.length > 0;\n  const shouldShowActions =\n    showActions && !streaming && (canCopy || onRetry || complete || hasSources);\n  const sourcesContentId = `${baseId}-sources`;\n  const resolvedSourcePrefix =\n    sourceIdPrefix ?? `response-source-${baseId.replace(/:/g, \"\")}`;\n\n  const setFeedback = (next: Exclude<StreamingResponseFeedback, null>) => {\n    const value = currentFeedback === next ? null : next;\n    if (feedback === undefined) setInternalFeedback(value);\n    onFeedbackChange?.(value);\n  };\n\n  const setSourcesOpen = useCallback(\n    (next: boolean) => {\n      if (sourcesOpen === undefined) setInternalSourcesOpen(next);\n      onSourcesOpenChange?.(next);\n    },\n    [onSourcesOpenChange, sourcesOpen],\n  );\n\n  return (\n    <div\n      data-state={status}\n      aria-busy={streaming}\n      className={cn(\"w-full\", className)}\n    >\n      <div\n        aria-live={announce ? \"polite\" : \"off\"}\n        className={cn(\n          \"text-sm leading-6 text-foreground/90 [&_a]:font-medium [&_a]:underline [&_a]:underline-offset-4 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.9em] [&_ol]:my-3 [&_ol]:list-decimal [&_ol]:space-y-1 [&_ol]:pl-5 [&_p+p]:mt-3 [&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-xl [&_pre]:border [&_pre]:border-border [&_pre]:bg-muted/45 [&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_ul]:my-3 [&_ul]:list-disc [&_ul]:space-y-1 [&_ul]:pl-5\",\n          contentClassName,\n        )}\n      >\n        {children}\n      </div>\n\n      <AnimatePresence initial={false}>\n        {shouldShowActions ? (\n          <motion.div\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: reduce ? 0.12 : 0.22, ease: EASE_OUT }}\n            className=\"mt-3\"\n          >\n            <div className={cn(\"flex items-center gap-0.5\", actionsClassName)}>\n              {canCopy ? (\n                <ResponseAction\n                  label={copied ? t(\"copied\") : t(\"copy\")}\n                  onClick={handleCopy}\n                >\n                  <ActionIcon id={copied ? \"copied\" : \"copy\"}>\n                    {copied ? (\n                      <Check className=\"size-3.5\" />\n                    ) : (\n                      <Copy className=\"size-3.5\" />\n                    )}\n                  </ActionIcon>\n                </ResponseAction>\n              ) : null}\n              {onRetry ? (\n                <ResponseAction label={t(\"retry\")} onClick={onRetry}>\n                  <RotateCcw className=\"size-3.5\" />\n                </ResponseAction>\n              ) : null}\n              {complete ? (\n                <>\n                  <ResponseAction\n                    label={t(\"helpful\")}\n                    active={currentFeedback === \"up\"}\n                    onClick={() => setFeedback(\"up\")}\n                  >\n                    {/* A chosen rating fills in, so the choice reads at a glance. */}\n                    <ActionIcon id={currentFeedback === \"up\" ? \"up-on\" : \"up\"}>\n                      <ThumbsUp\n                        className={cn(\"size-3.5\", currentFeedback === \"up\" && \"fill-current\")}\n                      />\n                    </ActionIcon>\n                  </ResponseAction>\n                  <ResponseAction\n                    label={t(\"notHelpful\")}\n                    active={currentFeedback === \"down\"}\n                    onClick={() => setFeedback(\"down\")}\n                  >\n                    <ActionIcon id={currentFeedback === \"down\" ? \"down-on\" : \"down\"}>\n                      <ThumbsDown\n                        className={cn(\"size-3.5\", currentFeedback === \"down\" && \"fill-current\")}\n                      />\n                    </ActionIcon>\n                  </ResponseAction>\n                </>\n              ) : null}\n              {hasSources ? (\n                <button\n                  type=\"button\"\n                  aria-expanded={currentSourcesOpen}\n                  aria-controls={sourcesContentId}\n                  onClick={() => setSourcesOpen(!currentSourcesOpen)}\n                  className=\"group ml-1 inline-flex min-h-7 items-center gap-2 rounded-full px-1.5 text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                >\n                  <CitationStack citations={sources} />\n                  <span className=\"tabular-nums\">\n                    {t(sources.length === 1 ? \"source\" : \"sources\", {\n                      count: sources.length,\n                    })}\n                  </span>\n                  <motion.span\n                    aria-hidden=\"true\"\n                    animate={{ rotate: currentSourcesOpen ? 180 : 0 }}\n                    transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                    className=\"text-muted-foreground/50 group-hover:text-muted-foreground\"\n                  >\n                    <ChevronDown className=\"size-3\" />\n                  </motion.span>\n                </button>\n              ) : null}\n            </div>\n\n            {hasSources ? (\n              <AgentDisclosure\n                id={sourcesContentId}\n                open={currentSourcesOpen}\n              >\n                <CitationList\n                  citations={sources}\n                  idPrefix={resolvedSourcePrefix}\n                  className=\"mt-2 rounded-2xl border border-border p-2\"\n                />\n              </AgentDisclosure>\n            ) : null}\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n"},{"path":"components/agents/message-context.tsx","type":"util","content":"\"use client\";\n\nimport { createContext } from \"react\";\n\nexport type MessageSide = \"start\" | \"end\";\n\nexport const MessageSideContext = createContext<MessageSide | undefined>(\n  undefined,\n);\n"},{"path":"components/agents/clip-resize-frame.tsx","type":"util","content":"\"use client\";\n\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport { type CSSProperties, type ReactNode, useLayoutEffect, useRef } from \"react\";\nimport { EASE_OUT, SPRING_MORPH } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n// The bottom edge glides to the new size; a little quicker when shrinking,\n// since the content inside has already gone.\nconst GROW = { duration: 0.3, ease: EASE_OUT } as const;\nconst SHRINK = { duration: 0.24, ease: EASE_OUT } as const;\n\nexport interface ClipResizeFrameProps extends Omit<HTMLMotionProps<\"div\">, \"children\" | \"style\"> {\n  style?: CSSProperties;\n  /**\n   * Which size follows the content. \"y\": the bottom edge glides as the height\n   * changes. \"x\": both ends glide in or out from the centre as the width\n   * changes, on a morph spring, for pills and chips. Default: \"y\"\n   */\n  axis?: \"x\" | \"y\";\n  /**\n   * With axis \"y\", which edge moves. \"top\" is for a panel anchored at its\n   * bottom, such as a list opening above an input: its top edge glides and its\n   * content stays against the bottom. Default: \"bottom\"\n   */\n  edge?: \"top\" | \"bottom\";\n  /** Outer corner radius in px. The surface inside uses one less. */\n  radius?: number;\n  /** Classes for the content box (padding goes here). */\n  contentClassName?: string;\n  children: ReactNode;\n}\n\n/**\n * A bordered card whose bottom edge glides when its content grows or shrinks,\n * without animating height. The layout changes at once; a clip on the card\n * hides the difference and slides it away. The border is the 1px gap between\n * two clipped layers (the frame in the border colour, the surface inside it),\n * so the bottom line travels with the edge instead of being clipped off.\n */\nexport function ClipResizeFrame({\n  axis = \"y\",\n  edge = \"bottom\",\n  radius = 16,\n  className,\n  contentClassName,\n  style,\n  children,\n  ...props\n}: ClipResizeFrameProps) {\n  const reduce = useReducedMotion() ?? false;\n  const horizontal = axis === \"x\";\n  const fromTop = !horizontal && edge === \"top\";\n  const surfaceRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  // How much of the surface (px) is hidden right now: at the moving edge, or\n  // split evenly between the two ends.\n  const gap = useMotionValue(0);\n  const clip = (value: number, round: number) =>\n    horizontal\n      ? `inset(0 ${value / 2}px 0 ${value / 2}px round ${round}px)`\n      : fromTop\n        ? `inset(${value}px 0 0 0 round ${round}px)`\n        : `inset(0 0 ${value}px 0 round ${round}px)`;\n  const frameClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius) : \"none\",\n  );\n  const surfaceClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius - 1) : \"none\",\n  );\n\n  useLayoutEffect(() => {\n    const surface = surfaceRef.current;\n    const content = contentRef.current;\n    if (!surface || !content || typeof ResizeObserver === \"undefined\") return;\n\n    const measure = () => (horizontal ? content.offsetWidth : content.offsetHeight);\n    const side = horizontal ? \"width\" : \"height\";\n    let last = measure();\n    // While shrinking, the surface keeps its old size so the edge has\n    // somewhere to glide from; null when the surface sizes to its content.\n    let held: number | null = null;\n    let controls: AnimationPlaybackControls | undefined;\n\n    const release = () => {\n      held = null;\n      surface.style[side] = \"\";\n      gap.set(0);\n    };\n\n    // Runs after layout and before paint, so the held size lands in the\n    // same frame as the content change: the edge never jumps.\n    const observer = new ResizeObserver(() => {\n      const next = measure();\n      if (next === last) return;\n      const visible = (held ?? last) - gap.get();\n      last = next;\n      controls?.stop();\n\n      if (reduce) {\n        release();\n        return;\n      }\n\n      const from = Math.max(next, visible);\n      held = from > next ? from : null;\n      surface.style[side] = held === null ? \"\" : `${held}px`;\n      gap.set(from - visible);\n      controls = animate(gap, from - next, {\n        ...(horizontal ? SPRING_MORPH : next < visible ? SHRINK : GROW),\n        // The edge has reached the content: hand the size back to layout.\n        onComplete: () => {\n          if (held !== null) release();\n        },\n      });\n    });\n    observer.observe(content);\n    return () => {\n      observer.disconnect();\n      controls?.stop();\n    };\n  }, [gap, reduce, horizontal]);\n\n  return (\n    <motion.div\n      {...props}\n      style={{ ...style, borderRadius: radius, clipPath: frameClip }}\n      className={cn(\"bg-border p-px\", horizontal && \"w-fit\", className)}\n    >\n      <motion.div\n        ref={surfaceRef}\n        style={{ borderRadius: radius - 1, clipPath: surfaceClip }}\n        // Held wider than its content while shrinking, the surface keeps the\n        // content centred, so the two ends close in on it evenly.\n        // Held taller than its content, a top-edge surface keeps the content\n        // against its anchored bottom.\n        className={cn(\n          \"overflow-hidden bg-background\",\n          horizontal && \"flex justify-center\",\n          fromTop && \"flex flex-col justify-end\",\n        )}\n      >\n        <div ref={contentRef} className={cn(horizontal && \"w-max shrink-0\", contentClassName)}>\n          {children}\n        </div>\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/button/index.tsx","type":"util","content":"export type {\n  ButtonLinkProps,\n  ButtonProps,\n  ButtonSize,\n  ButtonVariant,\n} from \"./base\";\nexport { Button, ButtonLink } from \"./base\";\nexport type { MagneticButtonProps } from \"./magnetic\";\nexport { MagneticButton } from \"./magnetic\";\nexport type { MetallicButtonProps } from \"./metallic\";\nexport { MetallicButton } from \"./metallic\";\nexport type {\n  ButtonState,\n  StatefulButtonMessages,\n  StatefulButtonProps,\n} from \"./stateful\";\nexport { StatefulButton, statefulButtonMessages } from \"./stateful\";\n"},{"path":"components/motion/dropdown-menu.tsx","type":"util","content":"\"use client\";\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type MutableRefObject,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { enabledItems } from \"@/components/motion/menu/use-menu-navigation\";\nimport { SPRING_PANEL } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, RootContext, type RootContextValue, useLevel, useRoot } from \"./dropdown-menu/context\";\nimport { type DropdownMenuItemProps, ItemBase } from \"./dropdown-menu/item-base\";\nimport { MenuPanel } from \"./dropdown-menu/menu-panel\";\nimport type { Align } from \"./dropdown-menu/placement\";\n\nexport type { DropdownMenuItemProps } from \"./dropdown-menu/item-base\";\n\n// Long enough to skip the submenus a pointer crosses on its way somewhere else.\nconst SUB_OPEN_DELAY = 100;\n// How long a pointer heading for an open submenu may cross sibling rows.\nconst SUB_GRACE = 300;\n\ntype TriggerElementProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  \"data-state\"?: \"open\" | \"closed\";\n};\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Whether the menu is open, for controlled use. */\n  open?: boolean;\n  /** Whether the menu starts open when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the menu opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * Play a soft sweep as the menu opens and closes, and a tick for checkbox\n   * and radio rows. Off by default; a `SoundProvider` can mute it app-wide.\n   */\n  sound?: boolean;\n}\n\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  sound = false,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [focusTarget, setFocusTarget] = useState<FocusTarget>(\"first\");\n  const [instant, setInstant] = useState(false);\n  const [mounted, setMounted] = useState(false);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const menuId = useId();\n  const triggerId = useId();\n  const reduce = useReducedMotion() ?? false;\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playSelect = useSound(selectSound, { enabled: sound });\n\n  useEffect(() => setMounted(true), []);\n\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"first\", now = false) => {\n      if (next !== open) {\n        if (next) playOpen();\n        else playClose();\n        setInstant(now);\n      }\n      if (next) setFocusTarget(focus);\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange, open, playOpen, playClose],\n  );\n\n  // Focus goes back to the trigger when the menu closes from inside it, or\n  // with nothing focused. A click elsewhere keeps the focus it landed on.\n  const wasOpen = useRef(open);\n  useEffect(() => {\n    if (wasOpen.current === open) return;\n    wasOpen.current = open;\n    if (open) return;\n    const active = document.activeElement;\n    if (\n      !active ||\n      active === document.body ||\n      active.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)\n    ) {\n      triggerRef.current?.focus({ preventScroll: true });\n    }\n  }, [open, menuId]);\n\n  const value = useMemo<RootContextValue>(\n    () => ({\n      open,\n      setOpen,\n      focusTarget,\n      instant,\n      menuId,\n      triggerId,\n      triggerRef,\n      reduce,\n      mounted,\n      playSelect,\n    }),\n    [open, setOpen, focusTarget, instant, menuId, triggerId, reduce, mounted, playSelect],\n  );\n\n  return <RootContext.Provider value={value}>{children}</RootContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuTriggerProps {\n  /** A single focusable element, usually a button. */\n  children: ReactElement<TriggerElementProps>;\n  /** Stops clicks and arrow keys from opening the menu. Default: false */\n  disabled?: boolean;\n}\n\nexport function DropdownMenuTrigger({ children, disabled = false }: DropdownMenuTriggerProps) {\n  const root = useRoot(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = children.props.ref;\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      root.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: childProps.id ?? root.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": root.open,\n    \"aria-controls\": root.open ? root.menuId : undefined,\n    \"data-state\": root.open ? \"open\" : \"closed\",\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented || disabled) return;\n      // `detail` is 0 for a click the keyboard synthesized from Enter or Space:\n      // that opener wants the first row and no animation, a pointer wants no\n      // row picked yet and the menu to grow out of the trigger.\n      const keyboard = event.detail === 0;\n      root.setOpen(!root.open, keyboard ? \"first\" : \"panel\", keyboard);\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented || disabled) return;\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        root.setOpen(true, event.key === \"ArrowDown\" ? \"first\" : \"last\", true);\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Classes merged onto the menu panel. */\n  className?: string;\n  /** Preferred side. Flips when the viewport has no room. Default \"bottom\". */\n  side?: \"top\" | \"bottom\";\n  /** Default \"start\". */\n  align?: Align;\n  /** Gap between trigger and menu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuContent({\n  children,\n  className,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n}: DropdownMenuContentProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const panelRef = useRef<HTMLDivElement | null>(null);\n\n  const { setOpen, triggerRef, menuId } = root;\n  // Escape and Tab are keys, so the menu goes at once; a press outside lets it fold away.\n  const dismiss = useCallback(\n    (reason: DismissReason) => setOpen(false, \"first\", reason === \"escape\"),\n    [setOpen],\n  );\n  const closeFromKey = useCallback(() => setOpen(false, \"first\", true), [setOpen]);\n  const ignore = useCallback(\n    (target: Element) =>\n      Boolean(triggerRef.current?.contains(target)) ||\n      Boolean(target.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)),\n    [triggerRef, menuId],\n  );\n  useDismiss(root.open, dismiss, null, { ignore });\n\n  if (!root.mounted) return null;\n\n  return (\n    <AnimatePresence custom={root.instant}>\n      {root.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={root.menuId}\n              anchorRef={root.triggerRef}\n              panelRef={panelRef}\n              side={side}\n              align={align}\n              sideOffset={sideOffset}\n              focus={root.focusTarget}\n              instant={root.instant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={root.triggerRef.current?.id ?? root.triggerId}\n              onClose={closeFromKey}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Items                                                                      */\n/* -------------------------------------------------------------------------- */\n\nexport function DropdownMenuItem(props: DropdownMenuItemProps) {\n  return <ItemBase {...props} />;\n}\n\nexport interface DropdownMenuCheckboxItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** Whether the row is checked. */\n  checked: boolean;\n  /** Called with the new checked state when the row is toggled. */\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** Stays open after a toggle by default, so the check can be seen landing. */\nexport function DropdownMenuCheckboxItem({\n  checked,\n  onCheckedChange,\n  closeOnSelect = false,\n  children,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const root = useRoot(\"DropdownMenuCheckboxItem\");\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemcheckbox\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        if (!closeOnSelect) root.playSelect();\n        onCheckedChange?.(!checked);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <AnimatePresence initial={false}>\n          {checked ? (\n            <motion.span\n              key=\"check\"\n              initial={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n              className=\"flex\"\n            >\n              <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string;\n  onValueChange?: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  /** The `value` of the checked radio row. */\n  value: string;\n  /** Called with the picked row's value when a radio row is selected. */\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  /** Classes merged onto the group wrapper. */\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({ value, onValueChange, children, className }: DropdownMenuRadioGroupProps) {\n  const context = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);\n  return (\n    <RadioGroupContext.Provider value={context}>\n      <div className={className}>{children}</div>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** The row's value. Checked when it matches the group's `value`. */\n  value: string;\n}\n\n/** Stays open after a pick by default, so the check can be seen moving. */\nexport function DropdownMenuRadioItem({ value, closeOnSelect = false, children, ...props }: DropdownMenuRadioItemProps) {\n  const root = useRoot(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) throw new Error(\"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\");\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemradio\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        // A pick that closes the menu sounds through the close sweep instead.\n        if (!closeOnSelect && !checked) root.playSelect();\n        group.onValueChange?.(value);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <motion.span\n          initial={false}\n          animate={root.reduce ? { opacity: checked ? 1 : 0 } : { opacity: checked ? 1 : 0, scale: checked ? 1 : 0.6 }}\n          transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n          className=\"flex\"\n        >\n          <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n        </motion.span>\n      </span>\n    </ItemBase>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Submenus                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  id: string;\n  contentId: string;\n  open: boolean;\n  focus: FocusTarget;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const context = useContext(SubContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return context;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const level = useLevel(\"DropdownMenuSub\");\n  const id = useId();\n  const contentId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const panelRef = useRef<HTMLDivElement | null>(null);\n  // Closes with its parent: an exiting menu takes its submenu out with it.\n  const open = level.openSub === id && level.present;\n  const { setOpenSub } = level;\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"none\", instant?: boolean) =>\n      setOpenSub(next ? id : null, focus, instant),\n    [setOpenSub, id],\n  );\n  const value = useMemo(\n    () => ({ id, contentId, open, focus: level.subFocus, triggerRef, panelRef, setOpen }),\n    [id, contentId, open, level.subFocus, setOpen],\n  );\n  return <SubContext.Provider value={value}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  /** Stops hover, click and keys from opening the submenu. */\n  disabled?: boolean;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the trigger row. */\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({ children, disabled, inset, textValue, className }: DropdownMenuSubTriggerProps) {\n  const level = useLevel(\"DropdownMenuSubTrigger\");\n  const sub = useSub(\"DropdownMenuSubTrigger\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const clearTimer = useCallback(() => {\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = null;\n  }, []);\n  useEffect(() => clearTimer, [clearTimer]);\n\n  return (\n    <ItemBase\n      disabled={disabled}\n      inset={inset}\n      textValue={textValue}\n      className={className}\n      subTrigger={{\n        id: sub.id,\n        open: sub.open,\n        controls: sub.contentId,\n        ref: sub.triggerRef,\n        onPointerMove: (event) => {\n          if (document.activeElement !== event.currentTarget) {\n            event.currentTarget.focus({ preventScroll: true });\n          }\n          if (disabled || sub.open || timer.current) return;\n          // Another row's submenu closes as soon as the pointer settles here.\n          if (level.openSub) level.setOpenSub(null);\n          timer.current = setTimeout(() => {\n            timer.current = null;\n            sub.setOpen(true, \"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          clearTimer();\n          const panel = sub.panelRef.current;\n          if (!sub.open || !panel || event.pointerType === \"touch\") return;\n          // Leave a corridor from the pointer to the submenu's near edge, so a\n          // diagonal path across the rows below does not close it.\n          const rect = panel.getBoundingClientRect();\n          const right = rect.left >= event.clientX;\n          const edge = right ? rect.left : rect.right;\n          const back = right ? -5 : 5;\n          level.grace.current = {\n            polygon: [\n              { x: event.clientX + back, y: event.clientY },\n              { x: edge, y: rect.top },\n              { x: edge, y: rect.bottom },\n            ],\n            until: Date.now() + SUB_GRACE,\n          };\n        },\n        onKeyDown: (event) => {\n          if (disabled) return;\n          if (event.key === \"ArrowRight\" || event.key === \"Enter\" || event.key === \" \") {\n            event.preventDefault();\n            event.stopPropagation();\n            sub.setOpen(true, \"first\");\n            // Already open from a hover: the panel's focus effect will not run\n            // again, so hand focus in here.\n            if (sub.open) enabledItems(sub.panelRef.current)[0]?.focus();\n          }\n        },\n        // Keys open the submenu in onKeyDown, so a click here is a pointer or a tap.\n        onClick: () => {\n          if (!disabled) sub.setOpen(true, \"first\", false);\n        },\n      }}\n    >\n      {children}\n      <ChevronRight aria-hidden=\"true\" className=\"ml-auto size-4\" />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Classes merged onto the submenu panel. */\n  className?: string;\n  /** Gap between the menu's edge and the submenu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuSubContent({ children, className, sideOffset = 6 }: DropdownMenuSubContentProps) {\n  const root = useRoot(\"DropdownMenuSubContent\");\n  const level = useLevel(\"DropdownMenuSubContent\");\n  const sub = useSub(\"DropdownMenuSubContent\");\n\n  return (\n    <AnimatePresence custom={level.subInstant}>\n      {sub.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={sub.contentId}\n              anchorRef={sub.triggerRef}\n              panelRef={sub.panelRef}\n              side=\"right\"\n              align=\"start\"\n              sideOffset={sideOffset}\n              focus={sub.focus}\n              instant={level.subInstant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={sub.id}\n              onClose={() => root.setOpen(false, \"first\", true)}\n              onPointerEnter={() => {\n                level.grace.current = null;\n              }}\n              onKeyDown={(event) => {\n                if (event.key !== \"ArrowLeft\") return false;\n                event.preventDefault();\n                sub.setOpen(false, \"none\", true);\n                sub.triggerRef.current?.focus({ preventScroll: true });\n                return true;\n              }}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Decoration                                                                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Classes merged onto the label element. */\n  className?: string;\n}\n\nexport function DropdownMenuLabel({ children, inset, className }: DropdownMenuLabelProps) {\n  return (\n    <div className={cn(\"px-3 py-1.5 text-xs font-medium text-muted-foreground\", inset && \"pl-9\", className)}>\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuSeparatorProps {\n  /** Classes merged onto the separator line. */\n  className?: string;\n}\n\nexport function DropdownMenuSeparator({ className }: DropdownMenuSeparatorProps) {\n  return <hr className={cn(\"-mx-2 my-1 h-px border-0 bg-border\", className)} />;\n}\n\nexport interface DropdownMenuShortcutProps {\n  children: ReactNode;\n  /** Classes merged onto the shortcut text. */\n  className?: string;\n}\n\nexport function DropdownMenuShortcut({ children, className }: DropdownMenuShortcutProps) {\n  return (\n    <span aria-hidden=\"true\" className={cn(\"ml-auto pl-4 text-xs tracking-wide text-muted-foreground\", className)}>\n      {children}\n    </span>\n  );\n}\n"},{"path":"components/motion/menu/menu-item-highlight.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** The row shape every menu item shares. Menus add their own gap and states. */\nexport const MENU_ITEM_CLASS =\n  \"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none\";\n\nexport interface MenuItemHighlightProps {\n  /** Shared by every row of one panel, so the highlight glides between them. */\n  layoutId: string;\n  tone?: \"default\" | \"destructive\";\n  reduce: boolean;\n  /**\n   * Jump instead of gliding: the highlight was moved by the keyboard, where a\n   * spring only trails behind fast arrowing.\n   */\n  instant?: boolean;\n}\n\n/** The highlight behind the active row. Render it only inside the active row. */\nexport function MenuItemHighlight({\n  layoutId,\n  tone = \"default\",\n  reduce,\n  instant = false,\n}: MenuItemHighlightProps) {\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      layoutId={layoutId}\n      className={cn(\n        \"absolute inset-0 -z-10 rounded-lg\",\n        tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n      )}\n      transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}\n    />\n  );\n}\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\n}\n"},{"path":"components/agents/agent-disclosure.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type HTMLMotionProps, useReducedMotion } from \"motion/react\";\nimport { type CSSProperties, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface AgentDisclosureProps\n  extends Omit<HTMLMotionProps<\"div\">, \"animate\" | \"initial\"> {\n  open: boolean;\n  openHeight?: CSSProperties[\"height\"];\n}\n\n/**\n * Shared reveal for collapsible agent content: a clip, fade and short drop,\n * never an animated height. The box takes its height as soon as it opens and\n * gives it up only once the closing reveal has played, so the exit is seen\n * and mirrors the entrance.\n */\nexport function AgentDisclosure({\n  open,\n  openHeight = \"auto\",\n  className,\n  style,\n  transition,\n  onAnimationComplete,\n  ...props\n}: AgentDisclosureProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [collapsed, setCollapsed] = useState(!open);\n  if (open && collapsed) setCollapsed(false);\n\n  return (\n    <motion.div\n      {...props}\n      aria-hidden={!open}\n      inert={!open}\n      initial={false}\n      animate={\n        reduce\n          ? { opacity: open ? 1 : 0 }\n          : {\n              opacity: open ? 1 : 0,\n              clipPath: open ? \"inset(0 0 0% 0)\" : \"inset(0 0 100% 0)\",\n              y: open ? 0 : -4,\n            }\n      }\n      transition={\n        transition ?? {\n          duration: reduce ? 0 : open ? 0.22 : 0.14,\n          ease: EASE_OUT,\n        }\n      }\n      onAnimationComplete={(definition) => {\n        if (!open) setCollapsed(true);\n        onAnimationComplete?.(definition);\n      }}\n      className={cn(\"overflow-hidden\", className)}\n      style={{\n        ...style,\n        height: collapsed ? 0 : openHeight,\n        pointerEvents: open ? undefined : \"none\",\n        transformOrigin: \"top\",\n      }}\n    />\n  );\n}\n"},{"path":"components/agents/citations.tsx","type":"util","content":"\"use client\";\n\nimport { BookOpenText, ChevronDown, ExternalLink, Globe2 } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { AgentDisclosure } from \"@/components/agents/agent-disclosure\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useFavicon } from \"@/lib/hooks/use-favicon\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\nexport const citationsMessages = {\n  title: \"Sources\",\n  viewCitation: \"View citation {index}\",\n};\n\nexport type CitationsMessages = typeof citationsMessages;\n\nexport interface CitationItem {\n  /** Unique key for the source, matched by a `Citation` marker's `citationId`. */\n  id: string;\n  /** Source name shown as the row's main text. */\n  title: ReactNode;\n  /** Muted text after the title, such as the site's host. */\n  domain?: ReactNode;\n  /** Link opened in a new tab and the favicon source. Omit for a plain row. */\n  url?: string;\n  /**\n   * Replaces the URL favicon, e.g. a document icon for non-web sources. An svg\n   * child is sized to match the favicon; falsy values fall back to the favicon.\n   */\n  icon?: ReactNode;\n}\n\nexport interface CitationsProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Text of the toggle button. Default: \"Sources\" */\n  title?: ReactNode;\n  /** Whether the list is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the list starts expanded when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the list expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<CitationsMessages>;\n}\n\nexport interface CitationProps {\n  /** Id of the `CitationItem` this marker links to. */\n  citationId: string;\n  /** Number shown on the marker. */\n  index: number;\n  /** Must match the related Citations idPrefix. */\n  idPrefix: string;\n  /**\n   * Accessible name for the marker. Defaults to `View citation {index}`. Include\n   * the index so voice control users can say the number they see.\n   */\n  label?: string;\n  /** Classes merged onto the marker link. */\n  className?: string;\n}\n\nexport interface CitationListProps {\n  /** Sources listed in order, numbered from 1. */\n  citations: CitationItem[];\n  /** Prefix for row ids that `Citation` markers link to. Generated when omitted. */\n  idPrefix?: string;\n  /** The citation a marker just led to; its row is lit. */\n  highlightedId?: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nexport interface CitationStackProps {\n  /** Sources whose favicons are stacked. */\n  citations: CitationItem[];\n  /** Most favicons to show. Default: 3 */\n  limit?: number;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\nfunction citationTargetId(prefix: string, citationId: string) {\n  return `${prefix}-${citationId.replace(/[^a-zA-Z0-9_-]/g, \"-\")}`;\n}\n\nexport function Citation({\n  citationId,\n  index,\n  idPrefix,\n  label,\n  className,\n}: CitationProps) {\n  const t = useMessages(\"citations\", citationsMessages);\n  return (\n    <a\n      href={`#${citationTargetId(idPrefix, citationId)}`}\n      aria-label={label ?? t(\"viewCitation\", { index })}\n      className={cn(\n        // A foreground tint, not bg-muted: muted is the bubble colour, so a\n        // muted marker would vanish inside a soft bubble.\n        \"mx-0.5 inline-flex min-w-4 -translate-y-0.5 items-center justify-center rounded-full bg-foreground/[0.07] px-1 py-0.5 text-[11px] font-medium leading-none text-muted-foreground no-underline outline-none transition-colors hover:bg-foreground/[0.12] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    >\n      {index}\n    </a>\n  );\n}\n\nexport function CitationFavicon({\n  url,\n  icon,\n  className,\n}: {\n  /** Page whose site favicon is shown. A globe icon shows when absent or broken. */\n  url?: string;\n  /** Drawn instead of the favicon when truthy. */\n  icon?: ReactNode;\n  className?: string;\n}) {\n  const favicon = useFavicon(icon ? undefined : url);\n\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\n        \"grid size-5 shrink-0 place-items-center text-muted-foreground [&>svg]:size-3.5\",\n        className,\n      )}\n    >\n      {icon ? (\n        icon\n      ) : favicon.src ? (\n        <img\n          ref={favicon.ref}\n          src={favicon.src}\n          alt=\"\"\n          width={16}\n          height={16}\n          referrerPolicy=\"no-referrer\"\n          className=\"size-4 rounded-sm object-contain\"\n        />\n      ) : (\n        <Globe2 className=\"size-3.5\" />\n      )}\n    </span>\n  );\n}\n\nexport function CitationStack({\n  citations,\n  limit = 3,\n  className,\n}: CitationStackProps) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className={cn(\"flex -space-x-1.5\", className)}\n    >\n      {citations.slice(0, limit).map((citation) => (\n        <CitationFavicon\n          key={citation.id}\n          url={citation.url}\n          icon={citation.icon}\n          className=\"size-6 rounded-full bg-background ring-2 ring-background\"\n        />\n      ))}\n    </span>\n  );\n}\n\nfunction CitationRow({\n  citation,\n  index,\n  idPrefix,\n  highlighted,\n}: {\n  citation: CitationItem;\n  index: number;\n  idPrefix: string;\n  highlighted: boolean;\n}) {\n  const content = (\n    <>\n      <CitationFavicon url={citation.url} icon={citation.icon} />\n      <span className=\"flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n        <span className=\"truncate text-sm font-medium text-foreground/80 transition-colors group-hover/citation:text-foreground\">\n          {citation.title}\n        </span>\n        {citation.domain ? (\n          <span className=\"min-w-0 truncate text-xs text-muted-foreground/60\">\n            {citation.domain}\n          </span>\n        ) : null}\n      </span>\n      <span className=\"flex shrink-0 items-center gap-1.5\">\n        <span className=\"grid size-5 place-items-center rounded-full bg-foreground/[0.05] text-[11px] font-medium tabular-nums text-muted-foreground\">\n          {index}\n        </span>\n        {citation.url ? (\n          <ExternalLink className=\"size-3.5 text-muted-foreground/40 transition-colors group-hover/citation:text-muted-foreground\" />\n        ) : null}\n      </span>\n    </>\n  );\n  // The row a marker just led to is lit, so the reader sees which source they\n  // landed on: `highlighted` from Citations, or `:target` after a plain jump.\n  const className = cn(\n    \"group/citation flex scroll-my-3 items-center gap-2 rounded-lg px-1.5 py-1 outline-none transition-colors duration-200 hover:bg-foreground/[0.04] focus-visible:ring-2 focus-visible:ring-ring target:bg-foreground/[0.07]\",\n    highlighted && \"bg-foreground/[0.07] hover:bg-foreground/[0.07]\",\n  );\n  const id = citationTargetId(idPrefix, citation.id);\n\n  return citation.url ? (\n    <a\n      id={id}\n      href={citation.url}\n      target=\"_blank\"\n      rel=\"noreferrer noopener\"\n      className={className}\n    >\n      {content}\n    </a>\n  ) : (\n    <div id={id} className={className}>\n      {content}\n    </div>\n  );\n}\n\nexport function CitationList({\n  citations,\n  idPrefix,\n  highlightedId,\n  className,\n}: CitationListProps) {\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const resolvedPrefix =\n    idPrefix ?? `citation-list-${baseId.replace(/:/g, \"\")}`;\n\n  return (\n    <div className={cn(\"grid gap-0.5\", className)}>\n      <AnimatePresence mode=\"popLayout\">\n        {citations.map((citation, index) => (\n          <motion.div\n            layout=\"position\"\n            key={citation.id}\n            initial={reduce ? { opacity: 1 } : { opacity: 0, y: 6 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3 }}\n            transition={\n              reduce\n                ? { duration: 0 }\n                : {\n                    opacity: { duration: 0.18, ease: EASE_OUT },\n                    y: SPRING_LAYOUT,\n                    layout: SPRING_LAYOUT,\n                  }\n            }\n          >\n            <CitationRow\n              citation={citation}\n              index={index + 1}\n              idPrefix={resolvedPrefix}\n              highlighted={citation.id === highlightedId}\n            />\n          </motion.div>\n        ))}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nexport function Citations({\n  citations,\n  title,\n  open,\n  defaultOpen = false,\n  onOpenChange,\n  idPrefix,\n  className,\n  labels,\n}: CitationsProps) {\n  const t = useMessages(\"citations\", citationsMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const baseId = useId();\n  const contentId = `${baseId}-content`;\n  const resolvedPrefix =\n    idPrefix ?? `citation-${baseId.replace(/:/g, \"\")}`;\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const currentOpen = open ?? internalOpen;\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (open === undefined) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [onOpenChange, open],\n  );\n\n  // A marker links to its source row. While the list is folded that row is\n  // hidden, so the jump would land on nothing: open the list, then bring the\n  // row into view once it is shown.\n  const [highlightedId, setHighlightedId] = useState<string>();\n  const latest = useRef({ currentOpen, setOpen, citations, reduce });\n  useLayoutEffect(() => {\n    latest.current = { currentOpen, setOpen, citations, reduce };\n  });\n  useEffect(() => {\n    // Returns true when the hash names one of this list's sources.\n    const reveal = (hash: string) => {\n      const now = latest.current;\n      const citation = now.citations.find(\n        (item) => citationTargetId(resolvedPrefix, item.id) === hash,\n      );\n      if (!citation) return false;\n      if (!now.currentOpen) now.setOpen(true);\n      setHighlightedId(citation.id);\n      // After the list has opened, bring the row just into view: no jump to\n      // the top of the page, where a sticky header would cover it.\n      window.setTimeout(() => {\n        document.getElementById(hash)?.scrollIntoView({\n          block: \"nearest\",\n          behavior: now.reduce ? \"auto\" : \"smooth\",\n        });\n      }, 0);\n      return true;\n    };\n    const onHash = () => reveal(decodeURIComponent(window.location.hash.slice(1)));\n    // Marker clicks are handled here rather than as a plain jump, which\n    // lands on nothing while the list is folded and pins the row under the\n    // page header when it is open.\n    const onClick = (event: MouseEvent) => {\n      const link = (event.target as Element | null)?.closest?.(\"a[href^='#']\");\n      if (!link) return;\n      if (reveal(decodeURIComponent(link.getAttribute(\"href\")?.slice(1) ?? \"\"))) {\n        event.preventDefault();\n      }\n    };\n    window.addEventListener(\"hashchange\", onHash);\n    document.addEventListener(\"click\", onClick);\n    return () => {\n      window.removeEventListener(\"hashchange\", onHash);\n      document.removeEventListener(\"click\", onClick);\n    };\n  }, [resolvedPrefix]);\n\n  return (\n    <div className={cn(\"w-full text-sm\", className)}>\n      <button\n        type=\"button\"\n        aria-expanded={currentOpen}\n        aria-controls={contentId}\n        onClick={() => setOpen(!currentOpen)}\n        className=\"group -ml-1 flex min-h-8 items-center gap-2 rounded-full px-1 text-left text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n      >\n        <BookOpenText className=\"size-4\" />\n        <span className=\"font-medium\">{title ?? t(\"title\")}</span>\n        <span className=\"rounded-full bg-foreground/[0.06] px-1.5 py-0.5 text-[11px] font-medium tabular-nums\">\n          {citations.length}\n        </span>\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: currentOpen ? 180 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"text-muted-foreground/60\"\n        >\n          <ChevronDown className=\"size-3.5\" />\n        </motion.span>\n      </button>\n\n      <AgentDisclosure\n        id={contentId}\n        open={currentOpen}\n      >\n        <CitationList\n          citations={citations}\n          idPrefix={resolvedPrefix}\n          highlightedId={highlightedId}\n          className=\"mt-1\"\n        />\n      </AgentDisclosure>\n    </div>\n  );\n}\n"},{"path":"components/agents/icon-swap.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface IconSwapProps {\n  /** Changes whenever the icon should change (copy → copied, running → done). */\n  id: string;\n  children: ReactNode;\n  className?: string;\n}\n\n/**\n * Crossfades one status icon into the next with a little scale and a 2px\n * blur, so the change reads as one icon morphing rather than two crossing.\n * Reduced motion keeps the fade and drops the scale.\n */\nexport function IconSwap({ id, children, className }: IconSwapProps) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <AnimatePresence mode=\"popLayout\" initial={false}>\n      <motion.span\n        key={id}\n        initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n        exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(2px)\" }}\n        transition={reduce ? { duration: 0.12 } : SPRING_SWAP}\n        className={cn(\"grid place-items-center\", className)}\n      >\n        {children}\n      </motion.span>\n    </AnimatePresence>\n  );\n}\n"},{"path":"lib/hooks/use-copy.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** How long the copied state holds after a copy, in ms. */\nconst COPIED_MS = 1600;\n\n/**\n * A copy action and a `copied` flag that holds for a moment after it works.\n *\n * `copy` runs `onCopy` when given, else writes `text` to the clipboard. The\n * flag turns on only once that succeeded: no clipboard (an insecure origin),\n * a refused write or a throwing `onCopy` leave it off rather than claiming a\n * copy that never happened.\n */\nexport function useCopy({\n  text,\n  onCopy,\n}: {\n  text?: string;\n  onCopy?: () => void | Promise<void>;\n}) {\n  const [copied, setCopied] = useState(false);\n  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n  useEffect(() => () => clearTimeout(timer.current), []);\n\n  const copy = useCallback(async () => {\n    try {\n      if (onCopy) await onCopy();\n      else if (text !== undefined && navigator.clipboard) {\n        await navigator.clipboard.writeText(text);\n      } else return;\n    } catch {\n      return;\n    }\n    setCopied(true);\n    clearTimeout(timer.current);\n    timer.current = setTimeout(() => setCopied(false), COPIED_MS);\n  }, [onCopy, text]);\n\n  return { copied, copy };\n}\n"},{"path":"components/motion/button/base.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type MouseEvent,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useSound } from \"@/lib/sound\";\nimport { pressSound } from \"@/lib/sounds/press\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ButtonVariant = \"primary\" | \"secondary\" | \"ghost\" | \"outline\";\nexport type ButtonSize = \"sm\" | \"md\" | \"lg\" | \"icon\";\n\nexport interface ButtonProps extends Omit<\n  HTMLMotionProps<\"button\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only button. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */\n  pressScale?: number;\n  /** Spawn a Material-style ripple from the press point. Off by default. */\n  ripple?: boolean;\n  /** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  children?: ReactNode;\n}\n\nexport interface ButtonLinkProps extends Omit<\n  HTMLMotionProps<\"a\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only link. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97. */\n  pressScale?: number;\n  children?: ReactNode;\n}\n\ntype Ripple = { id: number; x: number; y: number; size: number };\n\nconst VARIANT_CLASS: Record<ButtonVariant, string> = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary: \"border border-border bg-card text-foreground hover:border-border\",\n  ghost: \"text-muted-foreground hover:text-foreground hover:bg-muted/60\",\n  outline:\n    \"border border-border bg-transparent text-foreground hover:bg-muted/60\",\n};\n\nconst SIZE_CLASS: Record<ButtonSize, string> = {\n  sm: \"h-8 px-3 text-xs gap-1.5 rounded-full\",\n  md: \"h-10 px-5 text-sm gap-2 rounded-full\",\n  lg: \"h-12 px-6 text-base gap-2 rounded-full\",\n  icon: \"h-8 w-8 rounded-full\",\n};\n\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n  function Button(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      ripple = false,\n      sound = false,\n      className,\n      children,\n      onPointerDown,\n      onClick,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n    const [ripples, setRipples] = useState<Ripple[]>([]);\n    const nextId = useRef(0);\n    const play = useSound(pressSound, { enabled: sound });\n\n    const handleClick = useCallback(\n      (event: MouseEvent<HTMLButtonElement>) => {\n        // `detail` is 0 for a click the keyboard made; a pointer press already sounded.\n        if (event.detail === 0) play();\n        onClick?.(event);\n      },\n      [play, onClick],\n    );\n\n    const handlePointerDown = useCallback(\n      (event: PointerEvent<HTMLButtonElement>) => {\n        play();\n        if (ripple && !reduce) {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const size = Math.max(rect.width, rect.height) * 2;\n          const id = nextId.current++;\n          setRipples((prev) => [\n            ...prev,\n            {\n              id,\n              x: event.clientX - rect.left,\n              y: event.clientY - rect.top,\n              size,\n            },\n          ]);\n        }\n        onPointerDown?.(event);\n      },\n      [ripple, reduce, onPointerDown, play],\n    );\n\n    return (\n      // Hover changes colour only: a hover scale blurs the label, and buttons\n      // are hovered far too often for movement to earn its place.\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        onPointerDown={handlePointerDown}\n        onClick={handleClick}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          ripple && \"relative overflow-hidden\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {ripple && !reduce ? (\n          <span className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]\">\n            <AnimatePresence>\n              {ripples.map((r) => (\n                <motion.span\n                  key={r.id}\n                  className=\"absolute rounded-full bg-current\"\n                  style={{\n                    left: r.x,\n                    top: r.y,\n                    width: r.size,\n                    height: r.size,\n                    x: \"-50%\",\n                    y: \"-50%\",\n                  }}\n                  initial={{ scale: 0.05, opacity: 0.3 }}\n                  animate={{ scale: 1, opacity: 0 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: 0.8, ease: EASE_OUT }}\n                  onAnimationComplete={() =>\n                    setRipples((prev) => prev.filter((x) => x.id !== r.id))\n                  }\n                />\n              ))}\n            </AnimatePresence>\n          </span>\n        ) : null}\n        {children}\n      </motion.button>\n    );\n  },\n);\n\nexport const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(\n  function ButtonLink(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      className,\n      children,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n\n    return (\n      <motion.a\n        ref={ref}\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {children}\n      </motion.a>\n    );\n  },\n);\n"},{"path":"components/motion/button/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Magnetic } from \"../magnetic\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MagneticButtonProps extends ButtonProps {\n  /** Magnetic pull strength. Default 0.25. */\n  strength?: number;\n  /** Class applied to the magnetic wrapper. */\n  magneticClassName?: string;\n}\n\nexport const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(\n  { strength = 0.25, magneticClassName, children, ...rest },\n  ref,\n) {\n  return (\n    <Magnetic strength={strength} className={magneticClassName}>\n      <Button ref={ref} {...rest}>\n        {children}\n      </Button>\n    </Magnetic>\n  );\n});\n"},{"path":"components/motion/button/metallic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { forwardRef, useState } from \"react\";\nimport { EASE_IN_OUT, EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MetallicButtonProps extends Omit<\n  ButtonProps,\n  \"ripple\" | \"variant\"\n> {\n  /** Stops the traveling reflection while preserving the chrome rim. */\n  paused?: boolean;\n}\n\n// The rim and highlight drift separately so the material stays quiet and reflective.\nconst SILVER_DRIFT = {\n  duration: 8,\n  ease: EASE_IN_OUT,\n  repeat: Infinity,\n};\n\n// One quick sweep on hover. Leaving resets it instantly: both ends sit outside\n// the button, so the jump is invisible and no reverse sweep plays.\nconst CHROME_SHIMMER = {\n  duration: 0.9,\n  ease: EASE_OUT,\n};\nconst CHROME_RESET = { duration: 0 };\n\nexport const MetallicButton = forwardRef<\n  HTMLButtonElement,\n  MetallicButtonProps\n>(function MetallicButton(\n  {\n    size = \"md\",\n    paused = false,\n    className,\n    children,\n    onHoverStart,\n    onHoverEnd,\n    ...rest\n  },\n  ref,\n) {\n  const reduce = useReducedMotion();\n  const still = paused || Boolean(reduce);\n  const [hovered, setHovered] = useState(false);\n\n  return (\n    <Button\n      ref={ref}\n      variant=\"ghost\"\n      size={size}\n      onHoverStart={(event, info) => {\n        setHovered(true);\n        onHoverStart?.(event, info);\n      }}\n      onHoverEnd={(event, info) => {\n        setHovered(false);\n        onHoverEnd?.(event, info);\n      }}\n      className={cn(\n        \"group relative isolate overflow-hidden border-0 bg-transparent text-foreground\",\n        \"hover:bg-transparent hover:text-foreground\",\n        \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\",\n        \"shadow-[0_8px_22px_rgba(0,0,0,0.16)]\",\n        size === \"icon\" && \"rounded-full\",\n        className,\n      )}\n      {...rest}\n    >\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]\"\n        animate={still ? undefined : { x: [\"0%\", \"13%\", \"0%\"] }}\n        transition={still ? undefined : SILVER_DRIFT}\n      />\n\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen\"\n        animate={still ? undefined : { x: hovered ? \"310%\" : \"0%\" }}\n        transition={still ? undefined : hovered ? CHROME_SHIMMER : CHROME_RESET}\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40\"\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]\"\n      />\n\n      <span className=\"relative z-10 inline-flex items-center justify-center gap-2\">\n        {children}\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/button/stateful.tsx","type":"util","content":"\"use client\";\n\nimport { Check, Loader2, X } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type ReactNode,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport type ButtonState = \"idle\" | \"loading\" | \"success\" | \"error\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const statefulButtonMessages = {\n  loading: \"Loading\",\n  success: \"Done\",\n  error: \"Try again\",\n};\n\nexport type StatefulButtonMessages = typeof statefulButtonMessages;\n\nexport interface StatefulButtonProps extends Omit<ButtonProps, \"children\"> {\n  /** Which state to show. Loading also disables the button. Default: \"idle\" */\n  state?: ButtonState;\n  children: ReactNode;\n  /** Text shown while loading. Default: \"Loading\" */\n  loadingText?: ReactNode;\n  /** Text shown on success. Default: \"Done\" */\n  successText?: ReactNode;\n  /** Text shown on error. Default: \"Try again\" */\n  errorText?: ReactNode;\n  /** Trailing icon shown only while idle. */\n  icon?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<StatefulButtonMessages>;\n}\n\nconst CASCADE_STAGGER = 0.025;\nconst ROLL_BLUR = \"blur(6px)\";\n\nconst CASCADE_LETTER_VARIANTS: Variants = {\n  initial: { opacity: 0, y: \"105%\", filter: ROLL_BLUR },\n  animate: (delay: number = 0) => ({\n    opacity: 1,\n    y: \"0%\",\n    filter: \"blur(0px)\",\n    transition: { ...SPRING_SWAP, delay },\n  }),\n  exit: (delay: number = 0) => ({\n    opacity: 0,\n    y: \"-105%\",\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },\n  }),\n};\n\nconst ICON_VARIANTS: Variants = {\n  // Width collapses too, so the icon adds/removes its own space smoothly\n  // instead of popping the row width in a single frame.\n  initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },\n  animate: {\n    opacity: 1,\n    width: \"1.5rem\",\n    scale: 1,\n    filter: \"blur(0px)\",\n    transition: SPRING_SWAP,\n  },\n  exit: {\n    opacity: 0,\n    width: 0,\n    scale: 0.7,\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT },\n  },\n};\n\nfunction IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {\n  const reduce = useReducedMotion();\n  return (\n    <motion.span\n      key={keyId}\n      variants={ICON_VARIANTS}\n      initial={reduce ? { opacity: 0 } : \"initial\"}\n      animate={reduce ? { opacity: 1 } : \"animate\"}\n      exit={reduce ? { opacity: 0 } : \"exit\"}\n      transition={reduce ? { duration: 0.15 } : undefined}\n      className=\"inline-grid shrink-0 place-items-center overflow-hidden\"\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nfunction TextSlot({\n  value,\n  children,\n}: {\n  value: string;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion();\n  const measureRef = useRef<HTMLSpanElement>(null);\n  const [width, setWidth] = useState<number>();\n  const label = typeof children === \"string\" ? children : null;\n  const cascade = label !== null && !reduce;\n\n  // Measure strings with the same per-letter layout as the cascade. Measuring\n  // the whole string preserves kerning, which can make it narrower than the\n  // inline-block letters and clip the final glyph during the width animation.\n  useLayoutEffect(() => {\n    const nextWidth = measureRef.current?.offsetWidth;\n    if (!nextWidth) return;\n    setWidth((current) => (current === nextWidth ? current : nextWidth));\n  });\n\n  return (\n    <motion.span\n      initial={false}\n      animate={{ width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className=\"relative inline-block overflow-hidden whitespace-nowrap align-bottom\"\n    >\n      <span\n        ref={measureRef}\n        aria-hidden\n        className=\"invisible inline-block whitespace-nowrap\"\n      >\n        {cascade\n          ? label.split(\"\").map((char, index) => (\n              <span\n                // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                key={index}\n                className=\"inline-block whitespace-pre\"\n              >\n                {char}\n              </span>\n            ))\n          : children}\n      </span>\n\n      {cascade ? (\n        <>\n          <span className=\"sr-only\">{label}</span>\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={`cascade-${value}`}\n              aria-hidden\n              initial=\"initial\"\n              animate=\"animate\"\n              exit=\"exit\"\n              className=\"absolute left-0 top-0 inline-block whitespace-pre\"\n            >\n              {label.split(\"\").map((char, index) => (\n                <motion.span\n                  // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                  key={index}\n                  custom={index * CASCADE_STAGGER}\n                  variants={CASCADE_LETTER_VARIANTS}\n                  // Own states: a label that swaps away and straight back\n                  // re-enters mid-exit, and only owned targets are restored.\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  className=\"inline-block whitespace-pre will-change-[opacity,filter,transform]\"\n                >\n                  {char}\n                </motion.span>\n              ))}\n            </motion.span>\n          </AnimatePresence>\n        </>\n      ) : (\n        <AnimatePresence initial={false}>\n          <motion.span\n            key={`text-${value}`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}\n            animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}\n            transition={reduce ? { duration: 0.15 } : SPRING_SWAP}\n            className=\"absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]\"\n          >\n            {children}\n          </motion.span>\n        </AnimatePresence>\n      )}\n    </motion.span>\n  );\n}\n\nexport const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(\n  {\n    state = \"idle\",\n    children,\n    loadingText,\n    successText,\n    errorText,\n    icon,\n    labels,\n    disabled,\n    ...rest\n  },\n  ref,\n) {\n  const t = useMessages(\"statefulButton\", statefulButtonMessages, labels);\n  const isBusy = state === \"loading\";\n  const stateText =\n    state === \"loading\"\n      ? (loadingText ?? t(\"loading\"))\n      : state === \"success\"\n        ? (successText ?? t(\"success\"))\n        : state === \"error\"\n        ? (errorText ?? t(\"error\"))\n        : children;\n  const textKey =\n    typeof stateText === \"string\" ? `${state}-${stateText}` : state;\n\n  return (\n    <Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...rest}>\n      <span\n        aria-live=\"polite\"\n        className=\"relative inline-flex items-center justify-center overflow-hidden\"\n      >\n        <AnimatePresence initial={false}>\n          {state === \"loading\" ? (\n            <IconSlot keyId=\"loading-icon\">\n              <Loader2 className=\"h-4 w-4 animate-spin\" />\n            </IconSlot>\n          ) : null}\n          {state === \"success\" ? (\n            <IconSlot keyId=\"success-icon\">\n              <Check className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n          {state === \"error\" ? (\n            <IconSlot keyId=\"error-icon\">\n              <X className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n        </AnimatePresence>\n\n        <TextSlot value={textKey}>{stateText}</TextSlot>\n\n        <AnimatePresence initial={false}>\n          {state === \"idle\" && icon ? (\n            <IconSlot keyId=\"idle-icon\">{icon}</IconSlot>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/dropdown-menu/context.ts","type":"util","content":"\"use client\";\n\nimport { createContext, type MutableRefObject, useContext } from \"react\";\nimport type { Point } from \"./placement\";\n\nexport type FocusTarget = \"first\" | \"last\" | \"panel\" | \"none\";\n\nexport interface RootContextValue {\n  open: boolean;\n  /**\n   * `instant` skips the open or close animation: the keyboard asked for it,\n   * and keyboard users open and close menus far too often to wait on motion.\n   */\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n  focusTarget: FocusTarget;\n  /** Whether the latest open or close skips its animation. */\n  instant: boolean;\n  menuId: string;\n  triggerId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  reduce: boolean;\n  mounted: boolean;\n  /** Plays the select sound when the menu's `sound` prop is on. */\n  playSelect: () => void;\n}\n\nexport const RootContext = createContext<RootContextValue | null>(null);\n\nexport function useRoot(component: string) {\n  const context = useContext(RootContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return context;\n}\n\n/** One open panel: the root menu or a submenu. */\nexport interface LevelContextValue {\n  levelId: string;\n  present: boolean;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** The highlight glides after the pointer, and jumps after a key. */\n  glide: boolean;\n  openSub: string | null;\n  /** `instant` defaults to true when a focus target says the keyboard opened it. */\n  setOpenSub: (id: string | null, focus?: FocusTarget, instant?: boolean) => void;\n  subFocus: FocusTarget;\n  /** Whether the submenu's latest open or close skips its animation. */\n  subInstant: boolean;\n  /** A pointer on its way from a submenu trigger to the submenu it opened. */\n  grace: MutableRefObject<{ polygon: Point[]; until: number } | null>;\n}\n\nexport const LevelContext = createContext<LevelContextValue | null>(null);\n\nexport function useLevel(component: string) {\n  const context = useContext(LevelContext);\n  if (!context) {\n    throw new Error(`${component} must be used within <DropdownMenuContent>`);\n  }\n  return context;\n}\n"},{"path":"components/motion/dropdown-menu/item-base.tsx","type":"util","content":"\"use client\";\n\nimport { type MutableRefObject, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useId } from \"react\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { cn } from \"@/lib/utils\";\nimport { useLevel, useRoot } from \"./context\";\nimport { insidePolygon } from \"./placement\";\n\ntype ItemTone = \"default\" | \"destructive\";\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Called when the item is chosen by click, Enter or Space. */\n  onSelect?: () => void;\n  /** Dims the item and blocks selecting it. Default: false */\n  disabled?: boolean;\n  /** Close the whole menu after selecting. Default true. */\n  closeOnSelect?: boolean;\n  /** \"destructive\" tints the row for dangerous actions. Default: \"default\" */\n  tone?: ItemTone;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the item row. */\n  className?: string;\n}\n\ninterface ItemBaseProps extends DropdownMenuItemProps {\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  checked?: boolean;\n  subTrigger?: {\n    id: string;\n    open: boolean;\n    controls: string;\n    onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onPointerLeave: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => void;\n    onClick: () => void;\n    ref: MutableRefObject<HTMLElement | null>;\n  };\n}\n\n/** The row every item kind renders: plain, checkbox, radio and submenu trigger. */\nexport function ItemBase({\n  children,\n  onSelect,\n  disabled = false,\n  closeOnSelect = true,\n  tone = \"default\",\n  inset = false,\n  textValue,\n  className,\n  role = \"menuitem\",\n  checked,\n  subTrigger,\n}: ItemBaseProps) {\n  const root = useRoot(\"DropdownMenuItem\");\n  const level = useLevel(\"DropdownMenuItem\");\n  const ownId = useId();\n  const id = subTrigger?.id ?? ownId;\n  const active = level.activeId === id;\n\n  return (\n    <button\n      type=\"button\"\n      ref={(node) => {\n        if (subTrigger) subTrigger.ref.current = node;\n      }}\n      id={id}\n      role={role}\n      {...(role === \"menuitem\" ? {} : { \"aria-checked\": checked })}\n      aria-haspopup={subTrigger ? \"menu\" : undefined}\n      aria-expanded={subTrigger ? subTrigger.open : undefined}\n      aria-controls={subTrigger?.open ? subTrigger.controls : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={-1}\n      data-menu-item=\"\"\n      data-level={level.levelId}\n      data-disabled={disabled ? \"\" : undefined}\n      data-highlighted={active ? \"\" : undefined}\n      data-text-value={textValue}\n      onFocus={() => {\n        level.setActiveId(id);\n        // Moving to another row of this menu closes a submenu it does not own.\n        if (level.openSub && level.openSub !== subTrigger?.id) level.setOpenSub(null);\n      }}\n      onPointerMove={(event) => {\n        if (event.pointerType === \"touch\") return;\n        // On the way to an open submenu, crossing this row changes nothing.\n        const grace = level.grace.current;\n        if (grace && Date.now() < grace.until && insidePolygon({ x: event.clientX, y: event.clientY }, grace.polygon)) {\n          return;\n        }\n        level.grace.current = null;\n        if (subTrigger) {\n          subTrigger.onPointerMove(event);\n          return;\n        }\n        if (level.openSub) level.setOpenSub(null);\n        if (disabled) {\n          if (level.panelRef.current?.contains(document.activeElement)) {\n            level.panelRef.current.focus({ preventScroll: true });\n          }\n          return;\n        }\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={subTrigger?.onPointerLeave}\n      onKeyDown={subTrigger?.onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        if (subTrigger) {\n          subTrigger.onClick();\n          return;\n        }\n        onSelect?.();\n        // `detail` is 0 when Enter or Space picked the row: close without animating.\n        if (closeOnSelect) root.setOpen(false, \"first\", event.detail === 0);\n      }}\n      className={cn(\n        MENU_ITEM_CLASS,\n        \"cursor-default gap-2\",\n        \"[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-9\",\n        disabled && \"opacity-50\",\n        tone === \"destructive\" ? \"text-destructive [&_svg]:text-destructive\" : \"[&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {active && !disabled ? (\n        <MenuItemHighlight\n          layoutId={`${level.levelId}-highlight`}\n          tone={tone}\n          reduce={root.reduce}\n          instant={!level.glide}\n        />\n      ) : null}\n      {children}\n    </button>\n  );\n}\n"},{"path":"components/motion/dropdown-menu/menu-panel.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type Variants } from \"motion/react\";\nimport {\n  type MutableRefObject,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\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 { enabledItems, useMenuNavigation } from \"@/components/motion/menu/use-menu-navigation\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, LevelContext, type LevelContextValue, useRoot } from \"./context\";\nimport { type Align, type Placement, type Point, place, type Side } from \"./placement\";\n\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\n// The panel grows out of its trigger from this scale and distance.\nconst OPEN_SCALE = 0.94;\nconst OPEN_TRAVEL = 6;\nconst OPEN = { duration: 0.2, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\ninterface PanelProps {\n  children: ReactNode;\n  className?: string;\n  id: string;\n  anchorRef: MutableRefObject<HTMLElement | null>;\n  side: Side;\n  align: Align;\n  sideOffset: number;\n  focus: FocusTarget;\n  /** Show without animating; the AnimatePresence around it carries the same flag to the exit. */\n  instant: boolean;\n  present: boolean;\n  gate: { inert: boolean; style: { pointerEvents: \"auto\" | \"none\" } };\n  labelledBy: string;\n  onClose: () => void;\n  onKeyDown?: (event: ReactKeyboardEvent<HTMLDivElement>) => boolean;\n  onPointerEnter?: () => void;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n}\n\n/** One panel, shared by the menu and its submenus. */\nexport function MenuPanel({\n  children,\n  className,\n  id,\n  anchorRef,\n  side,\n  align,\n  sideOffset,\n  focus,\n  instant,\n  present,\n  gate,\n  labelledBy,\n  onClose,\n  onKeyDown,\n  onPointerEnter,\n  panelRef,\n}: PanelProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const parent = useContext(LevelContext);\n  const levelId = useId();\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [glide, setGlide] = useState(true);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const [subFocus, setSubFocus] = useState<FocusTarget>(\"none\");\n  const [subInstant, setSubInstant] = useState(false);\n  const grace = useRef<{ polygon: Point[]; until: number } | null>(null);\n  const navigate = useMenuNavigation();\n\n  const layout = usePopoverPortalPosition(anchorRef, panelRef, true);\n  // Held once placed: an exiting panel stays where it was, even if the\n  // trigger scrolls away under it.\n  const [placement, setPlacement] = useState<Placement | null>(null);\n  useLayoutEffect(() => {\n    if (!layout || !present) return;\n    // A submenu measures its gap from the parent panel's edge, not from the\n    // row inside it, so the two panels never touch.\n    const edge = parent?.panelRef.current?.getBoundingClientRect();\n    const anchor = edge ? { ...layout.trigger, left: edge.left, width: edge.width } : layout.trigger;\n    setPlacement(place(anchor, layout.content, side, align, sideOffset));\n  }, [layout, present, side, align, sideOffset, parent]);\n\n  const setOpenSub = useCallback(\n    (next: string | null, nextFocus: FocusTarget = \"none\", now = nextFocus !== \"none\") => {\n      setSubFocus(nextFocus);\n      setSubInstant(now);\n      setOpenSubState(next);\n    },\n    [],\n  );\n\n  // Waits for the first placement: the panel is `visibility: hidden` until\n  // then, and the browser will not focus anything inside it.\n  const placed = placement !== null;\n  useEffect(() => {\n    const panel = panelRef.current;\n    // `present` too: reopening during the exit brings this same panel back.\n    if (!placed || !present || !panel || focus === \"none\") return;\n    if (focus === \"panel\") {\n      panel.focus({ preventScroll: true });\n      return;\n    }\n    const items = enabledItems(panel);\n    (focus === \"last\" ? items[items.length - 1] : items[0])?.focus({ preventScroll: true });\n  }, [placed, present, focus, panelRef]);\n\n  const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // Submenus render inside this panel's React tree, so their keys bubble\n    // here too. Each panel answers only for its own rows.\n    const panel = panelRef.current;\n    const target = event.target as HTMLElement;\n    if (!panel || target.closest(\"[data-menu-panel]\") !== panel) return;\n    // Set before the key moves focus, so the highlight it lands on jumps.\n    setGlide(false);\n    if (onKeyDown?.(event)) return;\n    if (event.key === \"Tab\") {\n      event.preventDefault();\n      onClose();\n      return;\n    }\n    navigate(event, panel);\n  };\n\n  const level = useMemo<LevelContextValue>(\n    () => ({\n      levelId,\n      present,\n      panelRef,\n      activeId,\n      setActiveId,\n      glide,\n      openSub,\n      setOpenSub,\n      subFocus,\n      subInstant,\n      grace,\n    }),\n    [levelId, present, panelRef, activeId, glide, openSub, setOpenSub, subFocus, subInstant],\n  );\n\n  // The panel starts tucked toward its trigger and springs out of it.\n  const used = placement?.side ?? side;\n  const toward = used === \"top\" || used === \"left\" ? 1 : -1;\n  const vertical = used === \"top\" || used === \"bottom\";\n  const offset = (distance: number) => (vertical ? { y: distance * toward } : { x: distance * toward });\n  // `custom` is the instant flag. An exiting panel reads it from its\n  // AnimatePresence, so Escape removes the menu at once even after it has\n  // already left the React tree.\n  const variants: Variants = root.reduce\n    ? {\n        hidden: { opacity: 0 },\n        shown: (now = false) => ({\n          opacity: 1,\n          transition: now ? INSTANT : { duration: 0.15, ease: EASE_OUT },\n        }),\n        gone: (now = false) => ({ opacity: 0, transition: now ? INSTANT : EXIT }),\n      }\n    : {\n        hidden: { opacity: 0, scale: OPEN_SCALE, ...offset(OPEN_TRAVEL) },\n        shown: (now = false) => ({\n          opacity: 1,\n          scale: 1,\n          x: 0,\n          y: 0,\n          transition: now\n            ? INSTANT\n            : {\n                ...OPEN,\n                opacity: { duration: 0.12, ease: EASE_OUT },\n              },\n        }),\n        gone: (now = false) => ({\n          opacity: 0,\n          scale: 0.97,\n          ...offset(OPEN_TRAVEL / 2),\n          transition: now ? INSTANT : EXIT,\n        }),\n      };\n\n  return createPortal(\n    <motion.div\n      {...gate}\n      ref={panelRef}\n      id={id}\n      role=\"menu\"\n      aria-labelledby={labelledBy}\n      aria-orientation=\"vertical\"\n      tabIndex={-1}\n      data-menu-panel=\"\"\n      data-menu-root={root.menuId}\n      data-level={levelId}\n      data-side={placement?.side ?? side}\n      custom={instant}\n      variants={variants}\n      initial=\"hidden\"\n      animate=\"shown\"\n      exit=\"gone\"\n      onKeyDown={handleKeyDown}\n      onPointerMove={(event) => {\n        if (event.pointerType !== \"touch\") setGlide(true);\n      }}\n      onFocus={(event) => {\n        if (event.target === event.currentTarget) setActiveId(null);\n      }}\n      onPointerEnter={onPointerEnter}\n      onPointerLeave={(event) => {\n        // Leaving the panel drops the highlight, unless the row it sits on\n        // owns the open submenu the pointer is heading into.\n        if (event.pointerType === \"touch\" || openSub) return;\n        const panel = panelRef.current;\n        if (panel?.contains(document.activeElement)) panel.focus({ preventScroll: true });\n      }}\n      style={{\n        ...gate.style,\n        left: placement?.left ?? 0,\n        top: placement?.top ?? 0,\n        transformOrigin: placement?.origin,\n        maxHeight: placement?.maxHeight,\n        visibility: placement ? undefined : \"hidden\",\n      }}\n      className={cn(\n        \"fixed z-[100] min-w-48 overflow-y-auto overscroll-contain rounded-2xl border border-border bg-background p-2 text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none\",\n        parent && \"z-[101]\",\n        className,\n      )}\n    >\n      <LevelContext.Provider value={level}>{children}</LevelContext.Provider>\n    </motion.div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/dropdown-menu/placement.ts","type":"util","content":"export const VIEWPORT_PADDING = 8;\n// The panel's border and padding, so a submenu's first row lines up with the\n// row that opened it.\nexport const SUB_ALIGN_OFFSET = 9;\n// How far a submenu stacked under its row sits in, so it reads as nested.\nexport const SUB_STACK_INDENT = 16;\n\nexport type Side = \"top\" | \"bottom\" | \"left\" | \"right\";\nexport type Align = \"start\" | \"center\" | \"end\";\nexport type Point = { x: number; y: number };\n\nexport type Placement = {\n  left: number;\n  top: number;\n  side: Side;\n  origin: string;\n  /** The room on the chosen side; a taller menu scrolls inside it. */\n  maxHeight: number;\n};\n\nexport type Rect = { left: number; top: number; width: number; height: number };\n\nexport function clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\nexport function insidePolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\nexport function placeVertical(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: \"top\" | \"bottom\",\n  align: Align,\n  offset: number,\n): Placement {\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const below = trigger.top + trigger.height + offset;\n  const roomBelow = viewHeight - VIEWPORT_PADDING - below;\n  const roomAbove = trigger.top - offset - VIEWPORT_PADDING;\n  // The preferred side when the menu fits there, otherwise the roomier one.\n  const used =\n    side === \"bottom\"\n      ? size.height <= roomBelow || roomBelow >= roomAbove\n        ? \"bottom\"\n        : \"top\"\n      : size.height <= roomAbove || roomAbove >= roomBelow\n        ? \"top\"\n        : \"bottom\";\n  const maxHeight = Math.max(used === \"bottom\" ? roomBelow : roomAbove, 0);\n  const height = Math.min(size.height, maxHeight);\n  const start =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width - size.width\n        : trigger.left + trigger.width / 2 - size.width / 2;\n  const x = clamp(start, VIEWPORT_PADDING, viewWidth - size.width - VIEWPORT_PADDING);\n  const y = used === \"bottom\" ? below : trigger.top - offset - height;\n  // Grow from the aligned edge, so that edge holds still while the panel\n  // scales in instead of sliding sideways into place.\n  const anchorX =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width\n        : trigger.left + trigger.width / 2;\n  const originX = clamp(anchorX - x, 0, size.width);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${originX}px ${used === \"bottom\" ? 0 : height}px`,\n    maxHeight,\n  };\n}\n\nexport function place(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: Side,\n  align: Align,\n  offset: number,\n): Placement {\n  if (side === \"top\" || side === \"bottom\") {\n    return placeVertical(trigger, size, side, align, offset);\n  }\n\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const right = trigger.left + trigger.width + offset;\n  const left = trigger.left - size.width - offset;\n  const fitsRight = right + size.width <= viewWidth - VIEWPORT_PADDING;\n  const fitsLeft = left >= VIEWPORT_PADDING;\n  // A narrow screen has room on neither side: drop below the row instead of\n  // covering it, the way a phone stacks a submenu.\n  if (!fitsRight && !fitsLeft) {\n    return placeVertical(\n      { ...trigger, left: trigger.left + SUB_STACK_INDENT, width: trigger.width - SUB_STACK_INDENT },\n      size,\n      \"bottom\",\n      \"start\",\n      2,\n    );\n  }\n  const used: Side = side === \"right\" ? (fitsRight ? \"right\" : \"left\") : fitsLeft ? \"left\" : \"right\";\n  const maxHeight = viewHeight - VIEWPORT_PADDING * 2;\n  const height = Math.min(size.height, maxHeight);\n  const x = used === \"right\" ? right : left;\n  const y = clamp(trigger.top - SUB_ALIGN_OFFSET, VIEWPORT_PADDING, viewHeight - height - VIEWPORT_PADDING);\n  const originY = clamp(trigger.top + trigger.height / 2 - y, 0, height);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${used === \"right\" ? 0 : size.width}px ${originY}px`,\n    maxHeight,\n  };\n}\n"},{"path":"components/motion/menu/use-menu-navigation.ts","type":"util","content":"\"use client\";\n\nimport { type KeyboardEvent, useCallback, useEffect, useRef } from \"react\";\n\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * The enabled rows of one menu panel, in order. Rows carry `data-menu-item`\n * and the panel's `data-level`, so a submenu rendered inside the panel keeps\n * its own rows to itself.\n */\nexport function enabledItems(panel: HTMLElement | null) {\n  if (!panel) return [];\n  return Array.from(\n    panel.querySelectorAll<HTMLElement>(\n      `[data-menu-item][data-level=\"${panel.dataset.level}\"]:not([data-disabled])`,\n    ),\n  );\n}\n\n/**\n * Arrow keys, Home, End and typeahead for a menu panel. The returned handler\n * moves focus between the panel's rows and says whether it used the key.\n * Typeahead matches a row's `data-text-value`, or its text.\n */\nexport function useMenuNavigation() {\n  const query = useRef(\"\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(\n    () => () => {\n      if (timer.current) clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  return useCallback((event: KeyboardEvent<HTMLElement>, panel: HTMLElement | null) => {\n    const items = enabledItems(panel);\n    const index = items.indexOf(event.target as HTMLElement);\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      if (items.length === 0) return true;\n      const step = event.key === \"ArrowDown\" ? 1 : -1;\n      const next =\n        index < 0\n          ? step === 1\n            ? 0\n            : items.length - 1\n          : (index + step + items.length) % items.length;\n      items[next]?.focus();\n      return true;\n    }\n    if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      items[event.key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return true;\n    }\n    const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A space with nothing typed yet presses the row instead.\n    if (!typed || (event.key === \" \" && query.current === \"\")) return false;\n    query.current += event.key.toLocaleLowerCase();\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = setTimeout(() => {\n      query.current = \"\";\n    }, TYPEAHEAD_RESET);\n    // Start after the current row, so repeating a letter cycles its matches.\n    const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];\n    const typedSoFar = query.current;\n    const repeated = typedSoFar.length > 1 && [...typedSoFar].every((char) => char === typedSoFar[0]);\n    const needle = repeated ? typedSoFar[0] : typedSoFar;\n    const match = ordered.find((item) =>\n      (item.dataset.textValue ?? item.textContent ?? \"\").trim().toLocaleLowerCase().startsWith(needle),\n    );\n    if (!match) return false;\n    event.preventDefault();\n    match.focus();\n    return true;\n  }, []);\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit - this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree - an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/close.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"lib/hooks/use-favicon.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { getFaviconUrl } from \"@/lib/favicon\";\n\n/**\n * Resolves a site favicon and drops it once it is known to be unusable, so\n * callers can draw their own glyph instead of a broken image. Plenty of sites\n * answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch\n * it: an image the browser starts loading from server-rendered HTML usually\n * fails before React attaches a handler, and that event is never replayed.\n * `decode()` settles on the image's final state instead of relying on an event\n * firing at the right moment.\n */\nexport function useFavicon(url?: string) {\n  const resolved = url ? getFaviconUrl(url) : null;\n  const [failedSrc, setFailedSrc] = useState<string | null>(null);\n  const src = resolved && resolved !== failedSrc ? resolved : null;\n\n  const ref = useCallback(\n    (img: HTMLImageElement | null) => {\n      if (!img || !src) return;\n\n      let released = false;\n      img.decode().catch(() => {\n        if (!released) setFailedSrc(src);\n      });\n\n      // The node is going away or the source changed; a late rejection then\n      // describes an image we are no longer showing.\n      return () => {\n        released = true;\n      };\n    },\n    [src],\n  );\n\n  return { src, ref };\n}\n"},{"path":"lib/sounds/press.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */\nexport const pressSound = defineSound({\n  name: \"Press\",\n  duration: 0.1,\n  vary: 0.03,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });\n    v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });\n    v.strike({ freq: 150, material: \"wood\", bend: 1.5, decay: 0.07, gain: 0.75 });\n    v.strike({ freq: 1250, material: \"plastic\", decay: 0.022, gain: 0.14 });\n  },\n});\n"},{"path":"components/motion/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useMotionValue, useReducedMotion, useSpring } from \"motion/react\";\nimport { useRef, type ReactNode } from \"react\";\nimport { SPRING_MOUSE } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface MagneticProps {\n  children: ReactNode;\n  strength?: number;\n  className?: string;\n}\n\nexport function Magnetic({ children, strength = 0.35, className }: MagneticProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const canHover = useHoverCapable();\n  // Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.\n  const enabled = !reduce && canHover;\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const sx = useSpring(x, SPRING_MOUSE);\n  const sy = useSpring(y, SPRING_MOUSE);\n\n  const onMove = (e: React.MouseEvent<HTMLDivElement>) => {\n    const el = ref.current;\n    if (!el || !enabled) return;\n    const rect = el.getBoundingClientRect();\n    x.set((e.clientX - rect.left - rect.width / 2) * strength);\n    y.set((e.clientY - rect.top - rect.height / 2) * strength);\n  };\n\n  const onLeave = () => {\n    x.set(0);\n    y.set(0);\n  };\n\n  return (\n    <motion.div\n      ref={ref}\n      onMouseMove={onMove}\n      onMouseLeave={onLeave}\n      style={{ x: sx, y: sy }}\n      className={cn(\"inline-block\", className)}\n    >\n      {children}\n    </motion.div>\n  );\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/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"lib/favicon.ts","type":"util","content":"/** Resolve a website URL to its conventional root favicon location. */\nexport function getFaviconUrl(value: string) {\n  try {\n    return new URL(\"/favicon.ico\", value).toString();\n  } catch {\n    return null;\n  }\n}\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"}]}