{"$schema":"https:\/\/ui.shadcn.com\/schema\/registry-item.json","name":"message","type":"registry:component","title":"Message","description":"Composable conversation primitives for message rows, grouped bubbles, avatars, metadata, live markers, and a mount-only trailing-edge pop-up for newly sent rows.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["@floating-ui\/dom","clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":["https:\/\/beui.dev\/r\/theme.json"],"docs":"Message: usage, props and types at https:\/\/beui.dev\/components\/agents\/message.md It uses beUI's theme tokens, added with this install.","files":[{"path":"components\/agents\/message.tsx","type":"registry:component","target":"@components\/agents\/message.tsx","content":"\"use client\";\n\/\/ beui.dev\/components\/agents\/message\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":"registry:component","target":"@components\/agents\/message-bubble.tsx","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\/message-context.tsx","type":"registry:component","target":"@components\/agents\/message-context.tsx","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\/message-scroller.tsx","type":"registry:component","target":"@components\/agents\/message-scroller.tsx","content":"\"use client\";\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()}\u2026`;\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()}\u2026`;\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":"lib\/ease.ts","type":"registry:lib","target":"@lib\/ease.ts","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":"registry:lib","target":"@lib\/i18n.tsx","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 \u2192 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 \u2192 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={{ \u2026 }}` 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":"registry:lib","target":"@lib\/utils.ts","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\/merge-refs.ts","type":"registry:lib","target":"@lib\/merge-refs.ts","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":"components\/motion\/preview-rail.tsx","type":"registry:component","target":"@components\/motion\/preview-rail.tsx","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":"registry:component","target":"@components\/motion\/tooltip.tsx","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\/hooks\/use-dismiss.ts","type":"registry:hook","target":"@lib\/hooks\/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { inOtherLayer, type Layer, openLayer, ownsEscape } 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      \/\/ 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":"registry:hook","target":"@lib\/hooks\/use-hover-gesture.ts","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":"registry:hook","target":"@lib\/hooks\/use-tap-gesture.ts","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":"registry:component","target":"@components\/motion\/tooltip\/grace.ts","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":"registry:component","target":"@components\/motion\/tooltip\/positioner.tsx","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":"registry:component","target":"@components\/motion\/tooltip\/use-position.ts","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\u00b0\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\u00b0 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\u00b0 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":"registry:component","target":"@components\/motion\/tooltip-surface.tsx","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\/layers.ts","type":"registry:lib","target":"@lib\/layers.ts","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":"registry:lib","target":"@lib\/touch.ts","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"}]}