{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"message-actions","type":"registry:component","title":"Message Actions","description":"Assistant message action row (`MessageActions`) with copy that morphs into a drawn check, regenerate that spins (continuously while its promise runs), exclusive thumbs up/down that pop in filled, a thumbs-down reason popover with toggle chips and comment, share and a more menu; reveals on message hover or focus and stays visible on touch or with `visibility=\"always\"` for the last message — a standalone, richer counterpart to StreamingResponse's built-in actions.","author":"kara <ztzyrant@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/agents/message-actions.tsx","type":"registry:component","target":"@components/agents/message-actions.tsx","content":"\"use client\";\n// karaui.kamisama-v0.my.id/components/agents/message-actions\n\nimport {\n  Copy,\n  MoreHorizontal,\n  RotateCw,\n  Share,\n  ThumbsDown,\n  ThumbsUp,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentPropsWithRef,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { Button } from \"@/components/motion/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuTrigger,\n} from \"@/components/motion/dropdown-menu\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n} from \"@/components/motion/popover-morph\";\nimport { Textarea } from \"@/components/motion/textarea\";\nimport { ToggleGroup, ToggleGroupItem } from \"@/components/motion/toggle-group\";\nimport { EASE_OUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type MessageFeedback = \"up\" | \"down\" | null;\n\nexport interface MessageFeedbackReason {\n  value: string;\n  label: string;\n}\n\nexport interface MessageFeedbackDetails {\n  reasons: string[];\n  comment: string;\n}\n\nexport interface MessageMoreAction {\n  value: string;\n  label: string;\n  icon?: ReactNode;\n  destructive?: boolean;\n  disabled?: boolean;\n}\n\nexport interface MessageActionsProps\n  extends Omit<ComponentPropsWithRef<\"div\">, \"children\"> {\n  /** Plain text copied by the copy action. */\n  copyText?: string;\n  /** Overrides the built-in clipboard write. */\n  onCopy?: () => void | Promise<void>;\n  /** Shows the regenerate action. A returned promise keeps the icon spinning. */\n  onRegenerate?: () => void | Promise<void>;\n  feedback?: MessageFeedback;\n  defaultFeedback?: MessageFeedback;\n  onFeedbackChange?: (feedback: MessageFeedback) => void;\n  /** Reasons offered after a thumbs-down. Pass `[]` to skip the popover. */\n  feedbackReasons?: MessageFeedbackReason[];\n  onFeedbackSubmit?: (details: MessageFeedbackDetails) => void;\n  onShare?: () => void;\n  moreActions?: MessageMoreAction[];\n  onMoreAction?: (value: string) => void;\n  /**\n   * `hover` reveals the row while the surrounding `Message` / message group is\n   * hovered or focused (always visible on touch); `always` keeps it shown —\n   * use it for the last message.\n   */\n  visibility?: \"hover\" | \"always\";\n}\n\nexport const DEFAULT_FEEDBACK_REASONS: MessageFeedbackReason[] = [\n  { value: \"incorrect\", label: \"Incorrect\" },\n  { value: \"unhelpful\", label: \"Not helpful\" },\n  { value: \"incomplete\", label: \"Incomplete\" },\n  { value: \"instructions\", label: \"Ignored instructions\" },\n  { value: \"unsafe\", label: \"Harmful\" },\n];\n\nfunction ActionButton({\n  label,\n  pressed,\n  onClick,\n  children,\n  className,\n}: {\n  label: string;\n  pressed?: boolean;\n  onClick?: () => void;\n  children: ReactNode;\n  className?: string;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.button\n      type=\"button\"\n      aria-label={label}\n      title={label}\n      aria-pressed={pressed}\n      onClick={onClick}\n      whileTap={reduce ? undefined : { scale: 0.88 }}\n      transition={SPRING_PRESS}\n      className={cn(\n        \"relative grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        pressed && \"text-foreground\",\n        className,\n      )}\n    >\n      {children}\n    </motion.button>\n  );\n}\n\nfunction DrawnCheck({ reduce }: { reduce: boolean }) {\n  return (\n    <svg\n      aria-hidden=\"true\"\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth=\"2.25\"\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className=\"size-3.5\"\n    >\n      <motion.path\n        d=\"M5 12.5l4.5 4.5L19 7.5\"\n        initial={{ pathLength: reduce ? 1 : 0 }}\n        animate={{ pathLength: 1 }}\n        transition={{ duration: reduce ? 0 : 0.28, ease: EASE_OUT, delay: 0.04 }}\n      />\n    </svg>\n  );\n}\n\n/** Outline thumb with a filled twin that pops in over it when active. */\nfunction Thumb({\n  direction,\n  active,\n  reduce,\n}: {\n  direction: \"up\" | \"down\";\n  active: boolean;\n  reduce: boolean;\n}) {\n  const Icon = direction === \"up\" ? ThumbsUp : ThumbsDown;\n  return (\n    <span className=\"relative grid size-3.5 place-items-center\">\n      <Icon aria-hidden=\"true\" className=\"size-3.5\" />\n      <AnimatePresence initial={false}>\n        {active ? (\n          <motion.span\n            key=\"fill\"\n            aria-hidden=\"true\"\n            className=\"absolute inset-0 grid place-items-center\"\n            initial={\n              reduce ? { opacity: 0 } : { opacity: 0, scale: 0.4, rotate: 0 }\n            }\n            animate={\n              reduce\n                ? { opacity: 1 }\n                : {\n                    opacity: 1,\n                    scale: [0.4, 1.28, 1],\n                    rotate: [0, direction === \"up\" ? -14 : 14, 0],\n                  }\n            }\n            exit={{ opacity: 0, scale: reduce ? 1 : 0.6, transition: { duration: 0.12 } }}\n            transition={\n              reduce ? { duration: 0.12 } : { duration: 0.42, ease: EASE_OUT }\n            }\n          >\n            <Icon className=\"size-3.5 fill-current\" />\n          </motion.span>\n        ) : null}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport function MessageActions({\n  copyText,\n  onCopy,\n  onRegenerate,\n  feedback,\n  defaultFeedback = null,\n  onFeedbackChange,\n  feedbackReasons = DEFAULT_FEEDBACK_REASONS,\n  onFeedbackSubmit,\n  onShare,\n  moreActions = [],\n  onMoreAction,\n  visibility = \"hover\",\n  className,\n  ...props\n}: MessageActionsProps) {\n  const reduce = useReducedMotion() ?? false;\n  const [copied, setCopied] = useState(false);\n  const [spins, setSpins] = useState(0);\n  const [regenerating, setRegenerating] = useState(false);\n  const [internalFeedback, setInternalFeedback] =\n    useState<MessageFeedback>(defaultFeedback);\n  const [popoverOpen, setPopoverOpen] = useState(false);\n  const [menuOpen, setMenuOpen] = useState(false);\n  const [reasons, setReasons] = useState<string[]>([]);\n  const [comment, setComment] = useState(\"\");\n  const [thanked, setThanked] = useState(false);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const copyTimer = useRef<number | undefined>(undefined);\n  const thanksTimer = useRef<number | undefined>(undefined);\n  const downRef = useRef<HTMLSpanElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n  const current = feedback ?? internalFeedback;\n  const canCopy = Boolean(copyText || onCopy);\n\n  useEffect(\n    () => () => {\n      window.clearTimeout(copyTimer.current);\n      window.clearTimeout(thanksTimer.current);\n    },\n    [],\n  );\n\n  const copy = async () => {\n    try {\n      if (onCopy) await onCopy();\n      else if (copyText) await navigator.clipboard?.writeText(copyText);\n    } catch {\n      setAnnouncement(\"Copy failed\");\n      return;\n    }\n    setCopied(true);\n    setAnnouncement(\"Copied to clipboard\");\n    window.clearTimeout(copyTimer.current);\n    copyTimer.current = window.setTimeout(() => setCopied(false), 1600);\n  };\n\n  const regenerate = async () => {\n    if (!onRegenerate || regenerating) return;\n    setSpins((count) => count + 1);\n    const result = onRegenerate();\n    if (result && typeof result.then === \"function\") {\n      setRegenerating(true);\n      try {\n        await result;\n      } finally {\n        setRegenerating(false);\n      }\n    }\n  };\n\n  const setFeedback = (next: MessageFeedback) => {\n    if (feedback === undefined) setInternalFeedback(next);\n    onFeedbackChange?.(next);\n  };\n\n  const openPopover = (next: boolean) => {\n    if (!next && panelRef.current?.contains(document.activeElement)) {\n      downRef.current?.querySelector(\"button\")?.focus({ preventScroll: true });\n    }\n    setPopoverOpen(next);\n    if (next) {\n      setReasons([]);\n      setComment(\"\");\n      setThanked(false);\n    }\n  };\n\n  const toggleUp = () => {\n    openPopover(false);\n    setFeedback(current === \"up\" ? null : \"up\");\n  };\n\n  const toggleDown = () => {\n    if (current === \"down\") {\n      setFeedback(null);\n      openPopover(false);\n      return;\n    }\n    setFeedback(\"down\");\n    if (feedbackReasons.length) openPopover(true);\n  };\n\n  const submit = () => {\n    onFeedbackSubmit?.({ reasons, comment: comment.trim() });\n    setThanked(true);\n    setAnnouncement(\"Thanks for the feedback\");\n    window.clearTimeout(thanksTimer.current);\n    thanksTimer.current = window.setTimeout(() => openPopover(false), 1100);\n  };\n\n  // Move focus into the panel once it has mounted and been measured.\n  useEffect(() => {\n    if (!popoverOpen) return;\n    const frame = requestAnimationFrame(() =>\n      panelRef.current\n        ?.querySelector<HTMLElement>(\"[aria-pressed], textarea\")\n        ?.focus({ preventScroll: true }),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [popoverOpen]);\n\n  const pinned = visibility === \"always\" || popoverOpen || menuOpen;\n\n  return (\n    <div\n      data-slot=\"message-actions\"\n      data-visible={pinned || undefined}\n      className={cn(\n        \"flex items-center gap-0.5 transition-[opacity,translate] duration-200 ease-out motion-reduce:translate-y-0\",\n        pinned\n          ? \"translate-y-0 opacity-100\"\n          : \"translate-y-0.5 opacity-0 focus-within:translate-y-0 focus-within:opacity-100 group-hover/message:translate-y-0 group-hover/message:opacity-100 group-hover/message-group:translate-y-0 group-hover/message-group:opacity-100 [@media(hover:none)]:translate-y-0 [@media(hover:none)]:opacity-100\",\n        className,\n      )}\n      {...props}\n    >\n      {canCopy ? (\n        <ActionButton label={copied ? \"Copied\" : \"Copy\"} onClick={copy}>\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            <motion.span\n              key={copied ? \"check\" : \"copy\"}\n              className=\"grid place-items-center\"\n              initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={\n                reduce\n                  ? { opacity: 0, transition: { duration: 0.1 } }\n                  : { opacity: 0, scale: 0.6, transition: { duration: 0.1 } }\n              }\n              transition={reduce ? { duration: 0.12 } : SPRING_SWAP}\n            >\n              {copied ? (\n                <DrawnCheck reduce={reduce} />\n              ) : (\n                <Copy aria-hidden=\"true\" className=\"size-3.5\" />\n              )}\n            </motion.span>\n          </AnimatePresence>\n        </ActionButton>\n      ) : null}\n\n      {onRegenerate ? (\n        <ActionButton\n          label={regenerating ? \"Regenerating\" : \"Regenerate\"}\n          onClick={regenerate}\n        >\n          <motion.span\n            aria-hidden=\"true\"\n            className=\"grid place-items-center\"\n            animate={\n              reduce\n                ? undefined\n                : regenerating\n                  ? { rotate: [spins * 360, spins * 360 + 360] }\n                  : { rotate: spins * 360 }\n            }\n            transition={\n              regenerating\n                ? {\n                    duration: 0.8,\n                    ease: \"linear\",\n                    repeat: Number.POSITIVE_INFINITY,\n                  }\n                : { duration: 0.55, ease: EASE_OUT }\n            }\n          >\n            <RotateCw className=\"size-3.5\" />\n          </motion.span>\n        </ActionButton>\n      ) : null}\n\n      <ActionButton label=\"Good response\" pressed={current === \"up\"} onClick={toggleUp}>\n        <Thumb direction=\"up\" active={current === \"up\"} reduce={reduce} />\n      </ActionButton>\n\n      <MorphPopover open={popoverOpen} onOpenChange={openPopover}>\n        <span ref={downRef} className=\"inline-flex\">\n          <ActionButton\n            label=\"Bad response\"\n            pressed={current === \"down\"}\n            onClick={toggleDown}\n          >\n            <Thumb direction=\"down\" active={current === \"down\"} reduce={reduce} />\n          </ActionButton>\n        </span>\n        <MorphPopoverContent side=\"bottom\" align=\"start\" radius={14} className=\"w-72\">\n          <div ref={panelRef} className=\"p-3\">\n            <AnimatePresence mode=\"popLayout\" initial={false}>\n              {thanked ? (\n                <motion.div\n                  key=\"thanks\"\n                  initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6 }}\n                  animate={{ opacity: 1, y: 0 }}\n                  transition={reduce ? { duration: 0.12 } : SPRING_SWAP}\n                  className=\"flex items-center gap-2 py-6 text-sm text-foreground\"\n                >\n                  <span className=\"mx-auto flex items-center gap-2\">\n                    <span className=\"grid size-6 place-items-center rounded-full bg-muted\">\n                      <DrawnCheck reduce={reduce} />\n                    </span>\n                    Thanks for the feedback\n                  </span>\n                </motion.div>\n              ) : (\n                <motion.div\n                  key=\"form\"\n                  exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                >\n                  <p className=\"text-sm font-medium text-foreground\">\n                    What went wrong?\n                  </p>\n                  <p className=\"mt-0.5 text-xs text-muted-foreground\">\n                    Pick any that apply.\n                  </p>\n                  <ToggleGroup\n                    type=\"multiple\"\n                    size=\"sm\"\n                    variant=\"default\"\n                    value={reasons}\n                    onValueChange={setReasons}\n                    aria-label=\"Feedback reasons\"\n                    className=\"mt-2.5 flex w-full flex-wrap gap-1.5 rounded-none border-0 bg-transparent p-0\"\n                  >\n                    {feedbackReasons.map((reason) => (\n                      <ToggleGroupItem\n                        key={reason.value}\n                        value={reason.value}\n                        className=\"rounded-full border border-border px-2.5\"\n                      >\n                        {reason.label}\n                      </ToggleGroupItem>\n                    ))}\n                  </ToggleGroup>\n                  <Textarea\n                    value={comment}\n                    onChange={setComment}\n                    placeholder=\"Tell us more (optional)\"\n                    aria-label=\"Additional feedback\"\n                    minRows={2}\n                    maxRows={4}\n                    className=\"mt-2.5\"\n                  />\n                  <div className=\"mt-2.5 flex justify-end gap-1.5\">\n                    <Button\n                      type=\"button\"\n                      size=\"sm\"\n                      variant=\"ghost\"\n                      onClick={() => openPopover(false)}\n                    >\n                      Cancel\n                    </Button>\n                    <Button\n                      type=\"button\"\n                      size=\"sm\"\n                      disabled={!reasons.length && !comment.trim()}\n                      onClick={submit}\n                    >\n                      Submit\n                    </Button>\n                  </div>\n                </motion.div>\n              )}\n            </AnimatePresence>\n          </div>\n        </MorphPopoverContent>\n      </MorphPopover>\n\n      {onShare ? (\n        <ActionButton label=\"Share\" onClick={onShare}>\n          <Share aria-hidden=\"true\" className=\"size-3.5\" />\n        </ActionButton>\n      ) : null}\n\n      {moreActions.length ? (\n        <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>\n          <DropdownMenuTrigger>\n            <button\n              type=\"button\"\n              aria-label=\"More actions\"\n              title=\"More actions\"\n              className=\"grid size-7 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:bg-muted data-[state=open]:text-foreground\"\n            >\n              <MoreHorizontal aria-hidden=\"true\" className=\"size-3.5\" />\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent align=\"start\" className=\"w-48\">\n            {moreActions.map((action) => (\n              <DropdownMenuItem\n                key={action.value}\n                icon={action.icon}\n                variant={action.destructive ? \"destructive\" : \"default\"}\n                disabled={action.disabled}\n                onSelect={() => onMoreAction?.(action.value)}\n              >\n                {action.label}\n              </DropdownMenuItem>\n            ))}\n          </DropdownMenuContent>\n        </DropdownMenu>\n      ) : null}\n\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n"},{"path":"components/motion/button/index.tsx","type":"registry:component","target":"@components/motion/button/index.tsx","content":"export type {\n  ButtonLinkProps,\n  ButtonProps,\n  ButtonSize,\n  ButtonVariant,\n} from \"./base\";\nexport { Button, ButtonLink } from \"./base\";\nexport type { MagneticButtonProps } from \"./magnetic\";\nexport { MagneticButton } from \"./magnetic\";\nexport type { ButtonState, StatefulButtonProps } from \"./stateful\";\nexport { StatefulButton } from \"./stateful\";\n"},{"path":"components/motion/dropdown-menu.tsx","type":"registry:component","target":"@components/motion/dropdown-menu.tsx","content":"\"use client\";\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type MutableRefObject,\n  type ReactElement,\n  type FocusEvent as ReactFocusEvent,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type ReactNode,\n  type PointerEvent as ReactPointerEvent,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  type PlacementAlign,\n  type PlacementSide,\n  resolvePlacement,\n} from \"@/components/motion/anchored-placement\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------- */\n/*                                   Levels                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Where focus lands when a panel opens. */\ntype FocusIntent = \"first\" | \"last\" | \"content\" | \"none\";\n\n// Hovering a sub trigger waits this long before opening, so a pointer just\n// passing over the row on its way down the list doesn't flash a submenu.\nconst SUB_OPEN_DELAY = 100;\n// Leaving the sub trigger (or hovering a sibling) closes the submenu only\n// after this grace, so a diagonal move toward the submenu that clips a\n// neighbouring row doesn't snap it shut.\nconst SUB_CLOSE_DELAY = 220;\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * One open panel: the root menu or a submenu. Items, the active-row\n * highlight and keyboard navigation all read the nearest level, so a submenu\n * is the same machinery one step down.\n */\ninterface MenuLevel {\n  /** Shared by every panel and the trigger of one menu tree (dismissal scope). */\n  rootId: string;\n  /** Scope for this panel's layoutId highlight. */\n  levelId: string;\n  open: boolean;\n  isSub: boolean;\n  triggerId: string;\n  contentId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  contentRef: MutableRefObject<HTMLDivElement | null>;\n  focusIntent: MutableRefObject<FocusIntent>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** Id of the child submenu currently open from this panel. */\n  openSub: string | null;\n  setOpenSub: (id: string | null) => void;\n  scheduleSubClose: () => void;\n  cancelSubClose: () => void;\n  /** Close this panel only (root: the whole menu). */\n  close: (restoreFocus: boolean) => void;\n  /** Close the whole menu tree. */\n  closeAll: (restoreFocus: boolean) => void;\n  /** Open the root menu (used by the trigger). */\n  openRoot: () => void;\n  reduce: boolean;\n}\n\nconst MenuLevelContext = createContext<MenuLevel | null>(null);\n\nfunction useMenuLevel(component: string) {\n  const level = useContext(MenuLevelContext);\n  if (!level) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return level;\n}\n\n/** Per-panel state shared by the root and every submenu. */\nfunction useLevelCore(open: boolean) {\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const subCloseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const cancelSubClose = useCallback(() => {\n    if (subCloseTimer.current) clearTimeout(subCloseTimer.current);\n    subCloseTimer.current = null;\n  }, []);\n\n  const setOpenSub = useCallback(\n    (id: string | null) => {\n      cancelSubClose();\n      setOpenSubState(id);\n    },\n    [cancelSubClose],\n  );\n\n  const scheduleSubClose = useCallback(() => {\n    cancelSubClose();\n    subCloseTimer.current = setTimeout(() => {\n      subCloseTimer.current = null;\n      setOpenSubState(null);\n    }, SUB_CLOSE_DELAY);\n  }, [cancelSubClose]);\n\n  // Reset the highlight when the panel opens, not when it closes: removing\n  // the layoutId highlight while the panel is still animating out leaves\n  // motion waiting on it forever, so the closed panel never unmounts.\n  useEffect(() => {\n    if (open) {\n      setActiveId(null);\n      return;\n    }\n    cancelSubClose();\n    setOpenSubState(null);\n  }, [open, cancelSubClose]);\n\n  useEffect(() => cancelSubClose, [cancelSubClose]);\n\n  return useMemo(\n    () => ({\n      activeId,\n      setActiveId,\n      openSub,\n      setOpenSub,\n      scheduleSubClose,\n      cancelSubClose,\n    }),\n    [activeId, openSub, setOpenSub, scheduleSubClose, cancelSubClose],\n  );\n}\n\nfunction getItems(container: HTMLElement | null) {\n  if (!container) return [];\n  return Array.from(\n    container.querySelectorAll<HTMLElement>(\n      '[data-dropdown-menu-item]:not([data-disabled=\"true\"])',\n    ),\n  );\n}\n\nfunction focusByIntent(container: HTMLElement | null, intent: FocusIntent) {\n  if (!container || intent === \"none\") return;\n  const items = getItems(container);\n  const target =\n    intent === \"first\"\n      ? items[0]\n      : intent === \"last\"\n        ? items[items.length - 1]\n        : container;\n  (target ?? container).focus({ preventScroll: true });\n}\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) (ref as MutableRefObject<T | null>).current = value;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Root                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * Composable dropdown menu following the WAI-ARIA menu button pattern. The\n * panel scales out of the trigger side, an active-row highlight glides\n * between items, and submenus open on hover intent or ArrowRight.\n */\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const baseId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"content\");\n  const reduce = useReducedMotion() ?? false;\n  const core = useLevelCore(open);\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n\n  const closeAll = useCallback(\n    (restoreFocus: boolean) => {\n      setOpen(false);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpen],\n  );\n\n  const dismiss = useCallback(() => setOpen(false), [setOpen]);\n  const openRoot = useCallback(() => setOpen(true), [setOpen]);\n  const insideTree = useCallback(\n    (target: Element) =>\n      Boolean(target.closest(`[data-dropdown-menu=\"${baseId}\"]`)),\n    [baseId],\n  );\n  // Escape is handled by the focused panel, which knows whether it is a\n  // submenu (close one level) or the root (close and refocus the trigger).\n  useDismiss(open, dismiss, null, { escape: false, ignore: insideTree });\n\n  // Focus moves into the panel on open: the first/last item for keyboard\n  // opens, the panel itself for pointer opens so arrows work immediately.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: baseId,\n      levelId: `${baseId}-root`,\n      open,\n      isSub: false,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close: closeAll,\n      closeAll,\n      openRoot,\n      reduce,\n    }),\n    [baseId, open, core, closeAll, openRoot, reduce],\n  );\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <div className={cn(\"relative inline-flex\", className)}>{children}</div>\n    </MenuLevelContext.Provider>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Trigger                                   */\n/* -------------------------------------------------------------------------- */\n\ntype TriggerChildProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  [key: `data-${string}`]: string | undefined;\n};\n\nexport interface DropdownMenuTriggerProps {\n  /** A single element, normally a `<button>`. Its own handlers still run. */\n  children: ReactElement<TriggerChildProps>;\n  className?: string;\n}\n\nexport function DropdownMenuTrigger({\n  children,\n  className,\n}: DropdownMenuTriggerProps) {\n  const level = useMenuLevel(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = childProps.ref;\n\n  const openWith = (intent: FocusIntent) => {\n    level.focusIntent.current = intent;\n    if (!level.open) {\n      level.openRoot();\n    } else {\n      focusByIntent(level.contentRef.current, intent);\n    }\n  };\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      level.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: level.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": level.open,\n    \"aria-controls\": level.open ? level.contentId : undefined,\n    \"data-state\": level.open ? \"open\" : \"closed\",\n    \"data-dropdown-menu\": level.rootId,\n    className: cn(childProps.className, className),\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented) return;\n      if (level.open) {\n        level.closeAll(false);\n        return;\n      }\n      // `detail` is 0 for a click synthesized by the keyboard.\n      openWith(event.detail === 0 ? \"first\" : \"content\");\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented) return;\n      if (\n        event.key === \"ArrowDown\" ||\n        event.key === \"Enter\" ||\n        event.key === \" \"\n      ) {\n        event.preventDefault();\n        openWith(\"first\");\n      } else if (event.key === \"ArrowUp\") {\n        event.preventDefault();\n        openWith(\"last\");\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Panel                                    */\n/* -------------------------------------------------------------------------- */\n\ninterface MenuPanelProps {\n  level: MenuLevel;\n  children: ReactNode;\n  side: PlacementSide;\n  align: PlacementAlign;\n  sideOffset: number;\n  alignOffset: number;\n  className?: string;\n  ariaLabel?: string;\n  onPanelEnter?: () => void;\n}\n\nfunction MenuPanel({\n  level,\n  children,\n  side,\n  align,\n  sideOffset,\n  alignOffset,\n  className,\n  ariaLabel,\n  onPanelEnter,\n}: MenuPanelProps) {\n  const [portalReady, setPortalReady] = useState(false);\n  const typeahead = useRef(\"\");\n  const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const layout = usePopoverPortalPosition(\n    level.triggerRef,\n    level.contentRef,\n    portalReady && level.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  useEffect(\n    () => () => {\n      if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    },\n    [],\n  );\n\n  const moveFocus = (direction: 1 | -1) => {\n    const items = getItems(level.contentRef.current);\n    if (items.length === 0) return;\n    const current = items.indexOf(document.activeElement as HTMLElement);\n    const next =\n      current < 0\n        ? direction === 1\n          ? 0\n          : items.length - 1\n        : (current + direction + items.length) % items.length;\n    items[next]?.focus();\n  };\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // React bubbles events through portals: a submenu's keys would reach its\n    // parent panel too. Only answer keys pressed inside this panel's DOM.\n    if (!event.currentTarget.contains(event.target as Node)) return;\n    if (event.defaultPrevented) return;\n    const { key } = event;\n\n    if (key === \"Escape\") {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"ArrowLeft\" && level.isSub) {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"Tab\") {\n      event.preventDefault();\n      level.closeAll(true);\n      return;\n    }\n    if (key === \"ArrowDown\" || key === \"ArrowUp\") {\n      event.preventDefault();\n      moveFocus(key === \"ArrowDown\" ? 1 : -1);\n      return;\n    }\n    if (key === \"Home\" || key === \"End\") {\n      event.preventDefault();\n      const items = getItems(level.contentRef.current);\n      items[key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return;\n    }\n    const printable =\n      key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A leading space is activation, not a search character.\n    if (!printable || (key === \" \" && typeahead.current === \"\")) return;\n    event.preventDefault();\n    typeahead.current += key.toLocaleLowerCase();\n    if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    typeaheadTimer.current = setTimeout(() => {\n      typeahead.current = \"\";\n    }, TYPEAHEAD_RESET);\n    const items = getItems(level.contentRef.current);\n    const start = items.indexOf(document.activeElement as HTMLElement);\n    // Search from the row after the current one so repeating a letter cycles.\n    const ordered =\n      typeahead.current.length === 1 && start >= 0\n        ? [...items.slice(start + 1), ...items.slice(0, start + 1)]\n        : items;\n    const match = ordered.find((item) =>\n      (item.dataset.label ?? item.textContent ?? \"\")\n        .trim()\n        .toLocaleLowerCase()\n        .startsWith(typeahead.current),\n    );\n    match?.focus();\n  };\n\n  if (!portalReady) return null;\n\n  const placement = layout\n    ? resolvePlacement(layout, { side, align, sideOffset, alignOffset })\n    : null;\n\n  return createPortal(\n    <AnimatePresence>\n      {level.open ? (\n        <motion.div\n          ref={level.contentRef}\n          id={level.contentId}\n          role=\"menu\"\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabel ? undefined : level.triggerId}\n          aria-orientation=\"vertical\"\n          tabIndex={-1}\n          data-dropdown-menu={level.rootId}\n          data-side={placement?.side ?? side}\n          initial={level.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94 }}\n          animate={{ opacity: 1, scale: 1 }}\n          // pointerEvents flips at the start of the exit, so a closing panel\n          // can never be hovered or clicked through.\n          exit={\n            level.reduce\n              ? { opacity: 0, pointerEvents: \"none\", transition: { duration: 0.1 } }\n              : {\n                  opacity: 0,\n                  scale: 0.96,\n                  pointerEvents: \"none\",\n                  transition: { duration: 0.12, ease: EASE_OUT },\n                }\n          }\n          transition={\n            level.reduce\n              ? { duration: 0.12, ease: EASE_OUT }\n              : { ...SPRING_PANEL, opacity: { duration: 0.16, ease: EASE_OUT } }\n          }\n          style={{\n            left: placement?.left ?? 0,\n            top: placement?.top ?? 0,\n            // The panel grows out of the trigger's side — transform-origin on\n            // an HTML element is safe for motion's scale.\n            transformOrigin: placement?.origin ?? \"50% 0%\",\n            visibility: placement ? \"visible\" : \"hidden\",\n          }}\n          onKeyDown={onKeyDown}\n          onFocus={(event: ReactFocusEvent<HTMLDivElement>) => {\n            if (event.target === event.currentTarget) level.setActiveId(null);\n            else onPanelEnter?.();\n          }}\n          onPointerEnter={onPanelEnter}\n          className={cn(\n            \"fixed z-[100] min-w-52 rounded-xl border border-border bg-card p-1.5 text-foreground shadow-[0_18px_40px_-12px_rgba(0,0,0,0.28)] outline-none\",\n            className,\n          )}\n        >\n          {children}\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"bottom\". */\n  side?: \"bottom\" | \"top\";\n  /** Alignment against the trigger. Default \"start\". */\n  align?: PlacementAlign;\n  /** Gap between trigger and panel, in px. Default 6. */\n  sideOffset?: number;\n  alignOffset?: number;\n  /** Accessible name; defaults to the trigger's text via aria-labelledby. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuContent({\n  children,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n  alignOffset = 0,\n  ariaLabel,\n  className,\n}: DropdownMenuContentProps) {\n  const level = useMenuLevel(\"DropdownMenuContent\");\n  return (\n    <MenuPanel\n      level={level}\n      side={side}\n      align={align}\n      sideOffset={sideOffset}\n      alignOffset={alignOffset}\n      ariaLabel={ariaLabel}\n      className={className}\n    >\n      {children}\n    </MenuPanel>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Items                                    */\n/* -------------------------------------------------------------------------- */\n\ntype ItemVariant = \"default\" | \"destructive\";\n\ninterface ItemBaseProps {\n  children: ReactNode;\n  itemId?: string;\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  ariaChecked?: boolean;\n  disabled?: boolean;\n  variant?: ItemVariant;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n  closeOnSelect: boolean;\n  onActivate?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  isSubTrigger?: boolean;\n  extraProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {\n    ref?: Ref<HTMLButtonElement>;\n    [key: `data-${string}`]: string | undefined;\n  };\n}\n\nfunction ItemBase({\n  children,\n  itemId,\n  role = \"menuitem\",\n  ariaChecked,\n  disabled = false,\n  variant = \"default\",\n  inset = false,\n  textValue,\n  className,\n  closeOnSelect,\n  onActivate,\n  isSubTrigger = false,\n  extraProps,\n}: ItemBaseProps) {\n  const level = useMenuLevel(\"DropdownMenuItem\");\n  const autoId = useId();\n  const id = itemId ?? autoId;\n  const highlighted = level.activeId === id;\n  const checkedProps =\n    role === \"menuitem\" ? {} : { \"aria-checked\": ariaChecked ?? false };\n  const { onPointerEnter, onPointerLeave, onKeyDown, ref, ...rest } =\n    extraProps ?? {};\n\n  return (\n    <button\n      {...rest}\n      ref={ref}\n      type=\"button\"\n      id={id}\n      role={role}\n      {...checkedProps}\n      disabled={disabled}\n      tabIndex={-1}\n      data-dropdown-menu-item=\"\"\n      data-disabled={disabled ? \"true\" : undefined}\n      data-highlighted={highlighted ? \"\" : undefined}\n      data-label={textValue}\n      onFocus={() => level.setActiveId(id)}\n      onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerEnter?.(event);\n        if (!isSubTrigger && event.pointerType !== \"touch\") {\n          level.scheduleSubClose();\n        }\n      }}\n      onPointerMove={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        if (disabled || event.pointerType === \"touch\") return;\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerLeave?.(event);\n        if (event.pointerType === \"touch\" || isSubTrigger) return;\n        // Clearing focus to the panel drops the highlight when the pointer\n        // leaves the rows, the way native menus behave.\n        if (document.activeElement === event.currentTarget) {\n          level.contentRef.current?.focus({ preventScroll: true });\n        }\n      }}\n      onKeyDown={onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        onActivate?.(event);\n        if (closeOnSelect && !event.defaultPrevented) level.closeAll(true);\n      }}\n      className={cn(\n        \"relative isolate flex w-full select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n        \"[&_svg]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-8\",\n        variant === \"destructive\"\n          ? \"text-destructive [&_svg]:text-destructive\"\n          : \"text-foreground [&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {/* Its own presence boundary: a layoutId element registers with the\n          nearest AnimatePresence, and the panel's exit would otherwise wait\n          on the highlight's layout animation and never unmount. */}\n      <AnimatePresence initial={false}>\n        {highlighted ? (\n          <motion.span\n            aria-hidden=\"true\"\n            layoutId={`${level.levelId}-highlight`}\n            className={cn(\n              \"absolute inset-0 -z-10 rounded-lg\",\n              variant === \"destructive\"\n                ? \"bg-destructive/10\"\n                : \"bg-foreground/[0.07]\",\n            )}\n            transition={level.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          />\n        ) : null}\n      </AnimatePresence>\n      {children}\n    </button>\n  );\n}\n\nfunction Shortcut({ children }: { children: ReactNode }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"ml-auto pl-4 font-mono text-[11px] tracking-wide text-muted-foreground\"\n    >\n      {children}\n    </span>\n  );\n}\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Leading icon (sized to 16px). */\n  icon?: ReactNode;\n  /** Trailing shortcut hint, e.g. \"⌘K\" or a `KbdCombo`. Decorative. */\n  shortcut?: ReactNode;\n  variant?: ItemVariant;\n  disabled?: boolean;\n  /** Indent to line up with checkbox/radio rows. */\n  inset?: boolean;\n  /** Text used by typeahead when children aren't plain text. */\n  textValue?: string;\n  /** Call `event.preventDefault()` to keep the menu open. */\n  onSelect?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  /** Default true. */\n  closeOnSelect?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuItem({\n  children,\n  icon,\n  shortcut,\n  onSelect,\n  closeOnSelect = true,\n  ...props\n}: DropdownMenuItemProps) {\n  return (\n    <ItemBase {...props} closeOnSelect={closeOnSelect} onActivate={onSelect}>\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nfunction Indicator({\n  checked,\n  kind,\n  reduce,\n}: {\n  checked: boolean;\n  kind: \"check\" | \"dot\";\n  reduce: boolean;\n}) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"absolute left-2.5 flex size-4 items-center justify-center\"\n    >\n      <AnimatePresence initial={false}>\n        {checked ? (\n          <motion.span\n            key={kind}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            transition={reduce ? { duration: 0.08 } : SPRING_PANEL}\n            className=\"flex items-center justify-center text-foreground\"\n          >\n            {kind === \"check\" ? (\n              <Check className=\"size-3.5! text-foreground!\" strokeWidth={2.6} />\n            ) : (\n              <span className=\"size-1.5 rounded-full bg-current\" />\n            )}\n          </motion.span>\n        ) : null}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport interface DropdownMenuCheckboxItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** A toggle row. Stays open on select by default so several can be flipped. */\nexport function DropdownMenuCheckboxItem({\n  children,\n  checked: controlledChecked,\n  defaultChecked = false,\n  onCheckedChange,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const level = useMenuLevel(\"DropdownMenuCheckboxItem\");\n  const [internal, setInternal] = useState(defaultChecked);\n  const checked = controlledChecked ?? internal;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemcheckbox\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => {\n        if (controlledChecked === undefined) setInternal(!checked);\n        onCheckedChange?.(!checked);\n      }}\n    >\n      <Indicator checked={checked} kind=\"check\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string | undefined;\n  select: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  children: ReactNode;\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Accessible name for the group. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({\n  children,\n  value: controlledValue,\n  defaultValue,\n  onValueChange,\n  ariaLabel,\n  className,\n}: DropdownMenuRadioGroupProps) {\n  const [internal, setInternal] = useState(defaultValue);\n  const value = controlledValue ?? internal;\n  const ctx = useMemo<RadioGroupContextValue>(\n    () => ({\n      value,\n      select: (next) => {\n        if (controlledValue === undefined) setInternal(next);\n        onValueChange?.(next);\n      },\n    }),\n    [value, controlledValue, onValueChange],\n  );\n  return (\n    <RadioGroupContext.Provider value={ctx}>\n      <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n        {children}\n      </fieldset>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  value: string;\n}\n\nexport function DropdownMenuRadioItem({\n  children,\n  value,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuRadioItemProps) {\n  const level = useMenuLevel(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) {\n    throw new Error(\n      \"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\",\n    );\n  }\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemradio\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => group.select(value)}\n    >\n      <Indicator checked={checked} kind=\"dot\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  inset?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuLabel({\n  children,\n  inset = false,\n  className,\n}: DropdownMenuLabelProps) {\n  return (\n    <div\n      className={cn(\n        \"px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground\",\n        inset && \"pl-8\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuGroupProps {\n  children: ReactNode;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuGroup({\n  children,\n  ariaLabel,\n  className,\n}: DropdownMenuGroupProps) {\n  return (\n    <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n      {children}\n    </fieldset>\n  );\n}\n\nexport function DropdownMenuSeparator({ className }: { className?: string }) {\n  return <hr className={cn(\"-mx-1.5 my-1.5 h-px border-0 bg-border\", className)} />;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Submenus                                  */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  level: MenuLevel;\n  parent: MenuLevel;\n  triggerItemId: string;\n  openTimer: MutableRefObject<ReturnType<typeof setTimeout> | null>;\n  openWith: (intent: FocusIntent) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const sub = useContext(SubContext);\n  if (!sub) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return sub;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\n/** A nested menu opened from a `DropdownMenuSubTrigger` row. */\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const parent = useMenuLevel(\"DropdownMenuSub\");\n  const subId = useId();\n  const open = parent.open && parent.openSub === subId;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"none\");\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const core = useLevelCore(open);\n  const triggerItemId = `${subId}-trigger`;\n\n  useEffect(\n    () => () => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n    },\n    [],\n  );\n\n  // Open submenus take focus only when asked to (keyboard); a hover open\n  // leaves it on the trigger row.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const { setOpenSub } = parent;\n  const close = useCallback(\n    (restoreFocus: boolean) => {\n      setOpenSub(null);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpenSub],\n  );\n\n  const openWith = useCallback(\n    (intent: FocusIntent) => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n      openTimer.current = null;\n      focusIntent.current = intent;\n      if (open) focusByIntent(contentRef.current, intent);\n      else setOpenSub(subId);\n    },\n    [open, setOpenSub, subId],\n  );\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: parent.rootId,\n      levelId: `${subId}-level`,\n      open,\n      isSub: true,\n      triggerId: triggerItemId,\n      contentId: `${subId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close,\n      closeAll: parent.closeAll,\n      openRoot: parent.openRoot,\n      reduce: parent.reduce,\n    }),\n    [\n      parent.rootId,\n      parent.closeAll,\n      parent.openRoot,\n      parent.reduce,\n      subId,\n      open,\n      triggerItemId,\n      core,\n      close,\n    ],\n  );\n\n  const ctx = useMemo<SubContextValue>(\n    () => ({ level, parent, triggerItemId, openTimer, openWith }),\n    [level, parent, triggerItemId, openWith],\n  );\n\n  return <SubContext.Provider value={ctx}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  icon?: ReactNode;\n  disabled?: boolean;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({\n  children,\n  icon,\n  ...props\n}: DropdownMenuSubTriggerProps) {\n  const { level, parent, triggerItemId, openTimer, openWith } = useSub(\n    \"DropdownMenuSubTrigger\",\n  );\n\n  const clearOpenTimer = () => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    openTimer.current = null;\n  };\n\n  return (\n    <ItemBase\n      {...props}\n      itemId={triggerItemId}\n      isSubTrigger\n      closeOnSelect={false}\n      onActivate={(event) => openWith(event.detail === 0 ? \"first\" : \"none\")}\n      extraProps={{\n        ref: (node: HTMLButtonElement | null) => {\n          level.triggerRef.current = node;\n        },\n        \"aria-haspopup\": \"menu\",\n        \"aria-expanded\": level.open,\n        \"aria-controls\": level.open ? level.contentId : undefined,\n        \"data-state\": level.open ? \"open\" : \"closed\",\n        onPointerEnter: (event) => {\n          if (event.pointerType === \"touch\" || props.disabled) return;\n          parent.cancelSubClose();\n          if (level.open) return;\n          clearOpenTimer();\n          openTimer.current = setTimeout(() => {\n            openTimer.current = null;\n            openWith(\"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          if (event.pointerType === \"touch\") return;\n          clearOpenTimer();\n          parent.scheduleSubClose();\n        },\n        onKeyDown: (event) => {\n          if (event.key === \"ArrowRight\") {\n            event.preventDefault();\n            openWith(\"first\");\n          }\n        },\n      }}\n    >\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      <ChevronRight\n        aria-hidden=\"true\"\n        className=\"-mr-1 ml-auto size-3.5! text-muted-foreground\"\n      />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"right\". */\n  side?: \"right\" | \"left\";\n  /** Gap from the parent panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Shift so the first row lines up with the trigger row. Default -7. */\n  alignOffset?: number;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubContent({\n  children,\n  side = \"right\",\n  sideOffset = 8,\n  alignOffset = -7,\n  ariaLabel,\n  className,\n}: DropdownMenuSubContentProps) {\n  const { level, parent, triggerItemId } = useSub(\"DropdownMenuSubContent\");\n  const { cancelSubClose, setActiveId } = parent;\n  // While the pointer or focus is in the submenu, its trigger row keeps the\n  // parent's highlight and the pending close is called off.\n  const onPanelEnter = useCallback(() => {\n    cancelSubClose();\n    setActiveId(triggerItemId);\n  }, [cancelSubClose, setActiveId, triggerItemId]);\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <MenuPanel\n        level={level}\n        side={side}\n        align=\"start\"\n        sideOffset={sideOffset}\n        alignOffset={alignOffset}\n        ariaLabel={ariaLabel}\n        className={cn(\"min-w-44\", className)}\n        onPanelEnter={onPanelEnter}\n      >\n        {children}\n      </MenuPanel>\n    </MenuLevelContext.Provider>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"registry:component","target":"@components/motion/popover-morph.tsx","content":"\"use client\";\n\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against — see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * A popover whose panel morphs open from the trigger corner: it's laid out at\n * full size but clipped to the corner nearest the trigger, then unclips as one\n * piece. Closes on outside pointer / Escape. Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element — a Tooltip wrapping the\n  // button, say — and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable — this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  useEffect(() => {\n    if (!open) return;\n    const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && close();\n    const onPointer = (e: PointerEvent) => {\n      const target = e.target as Node;\n      if (\n        root &&\n        !root.contains(target) &&\n        !contentRef.current?.contains(target)\n      )\n        close();\n    };\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer);\n    return () => {\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer);\n    };\n  }, [open, root, close]);\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\nfunction mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) {\n      if (typeof ref === \"function\") ref(node);\n      else if (ref && typeof ref === \"object\")\n        (ref as React.MutableRefObject<T | null>).current = node;\n    }\n  };\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  if (!isValidElement(children)) return children;\n\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child.props.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childRef = (child.props as { ref?: Ref<HTMLElement> }).ref;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergeRefs(childRef, ctx.registerTrigger),\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\nconst originFor = (side: Side, align: Align) =>\n  `${side === \"bottom\" ? \"top\" : \"bottom\"} ${align === \"end\" ? \"right\" : \"left\"}`;\n\n// A clip that hides everything but the corner nearest the trigger, so the\n// panel appears to grow out of it. inset(top right bottom left).\nfunction clipHidden(side: Side, align: Align, radius: number) {\n  const top = side === \"bottom\" ? \"0%\" : \"92%\";\n  const bottom = side === \"bottom\" ? \"92%\" : \"0%\";\n  const right = align === \"end\" ? \"0%\" : \"92%\";\n  const left = align === \"end\" ? \"92%\" : \"0%\";\n  return `inset(${top} ${right} ${bottom} ${left} round ${radius}px)`;\n}\nconst clipShown = (radius: number) => `inset(0% 0% 0% 0% round ${radius}px)`;\n\n// Preserve the original spring character on the wrapper, but tween the complex\n// clip-path so it cannot snap when the spring resolves its final distance.\nconst MORPH_CLIP_TRANSITION = { duration: 0.32, ease: EASE_OUT } as const;\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  side?: Side;\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16. */\n  radius?: number;\n  className?: string;\n}\n\nexport function MorphPopoverContent({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [portalReady, setPortalReady] = useState(false);\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    portalReady && ctx.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  const left = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  const top = layout\n    ? side === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : layout.trigger.top - layout.content.height - sideOffset\n    : 0;\n\n  // Both directions travel between the exact same hidden/show states. Exit\n  // targets \"hidden\" directly instead of introducing separate choreography.\n  const wrap = reduce\n    ? undefined\n    : {\n        hidden: { opacity: 0, scale: 0.96, transition: SPRING_PANEL },\n        show: { opacity: 1, scale: 1, transition: SPRING_PANEL },\n      };\n  const clip = reduce\n    ? undefined\n    : {\n        hidden: {\n          clipPath: clipHidden(side, align, radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n        show: {\n          clipPath: clipShown(radius),\n          transition: MORPH_CLIP_TRANSITION,\n        },\n      };\n\n  // Keep the server and first client render identical, then mount the portal.\n  if (!portalReady) return null;\n\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open ? (\n        <motion.div\n          data-morph-popover-portal=\"\"\n          // Wrapper carries the shadow as a drop-shadow filter, which hugs the\n          // clipped shape below (box-shadow would just get clipped away).\n          variants={wrap}\n          initial={reduce ? { opacity: 0 } : \"hidden\"}\n          animate={reduce ? { opacity: 1 } : \"show\"}\n          exit={reduce ? { opacity: 0 } : \"hidden\"}\n          transition={reduce ? { duration: 0.12 } : undefined}\n          style={{\n            left,\n            top,\n            visibility: layout ? \"visible\" : \"hidden\",\n            transformOrigin: originFor(side, align),\n          }}\n          className=\"fixed z-[9999] [filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\"\n        >\n          <motion.div\n            ref={ctx.contentRef}\n            id={ctx.contentId}\n            role=\"dialog\"\n            aria-labelledby={ctx.triggerId}\n            variants={clip}\n            style={{ borderRadius: radius }}\n            className={cn(\n              \"overflow-hidden border border-border bg-background\",\n              className,\n            )}\n          >\n            {children}\n          </motion.div>\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/textarea.tsx","type":"registry:component","target":"@components/motion/textarea.tsx","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n  type TextareaHTMLAttributes,\n} from \"react\";\nimport { EASE_OUT_CSS, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type TextareaClassNames = {\n  root?: string;\n  label?: string;\n  description?: string;\n  field?: string;\n  textarea?: string;\n  counter?: string;\n  errorMessage?: string;\n};\n\nexport interface TextareaProps\n  extends Omit<\n    TextareaHTMLAttributes<HTMLTextAreaElement>,\n    \"value\" | \"defaultValue\" | \"onChange\" | \"rows\"\n  > {\n  label?: string;\n  /** Helper text under the label, linked through aria-describedby. */\n  description?: string;\n  value?: string;\n  defaultValue?: string;\n  onChange?: (value: string) => void;\n  /** Truthy error triggers a shake, red border and (if a string) a message. */\n  error?: string | boolean;\n  /** Rows shown when empty; the field never shrinks below this. */\n  minRows?: number;\n  /** Rows the field grows to before it starts scrolling. */\n  maxRows?: number;\n  /** Shows the character counter. Defaults to true when `maxLength` is set. */\n  showCount?: boolean;\n  /** Fraction of `maxLength` at which the counter turns to the warning color. */\n  warnAt?: number;\n  className?: string;\n  classNames?: TextareaClassNames;\n}\n\nconst SHAKE = { x: [0, -6, 6, -4, 4, -2, 0] };\n\nexport const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(\n  function Textarea(\n    {\n      label,\n      description,\n      value: valueProp,\n      defaultValue,\n      onChange,\n      onFocus,\n      onBlur,\n      error,\n      minRows = 3,\n      maxRows = 8,\n      maxLength,\n      showCount,\n      warnAt = 0.9,\n      placeholder,\n      className,\n      classNames,\n      disabled,\n      id: idProp,\n      ...rest\n    },\n    forwardedRef,\n  ) {\n    const reactId = useId();\n    const id = idProp ?? reactId;\n    const reduce = useReducedMotion();\n\n    const controlled = valueProp !== undefined;\n    const [internal, setInternal] = useState(defaultValue ?? \"\");\n    const value = controlled ? (valueProp ?? \"\") : internal;\n\n    const [focused, setFocused] = useState(false);\n    const [height, setHeight] = useState<number | null>(null);\n    const [scrolls, setScrolls] = useState(false);\n\n    const fieldRef = useRef<HTMLDivElement>(null);\n    const counterRef = useRef<HTMLSpanElement>(null);\n    const mirrorRef = useRef<HTMLTextAreaElement>(null);\n    const innerRef = useRef<HTMLTextAreaElement | null>(null);\n\n    const setRefs = useCallback(\n      (node: HTMLTextAreaElement | null) => {\n        innerRef.current = node;\n        if (typeof forwardedRef === \"function\") forwardedRef(node);\n        else if (forwardedRef) forwardedRef.current = node;\n      },\n      [forwardedRef],\n    );\n\n    const hasError = Boolean(error);\n    const errorMessage = typeof error === \"string\" ? error : null;\n    const countVisible = showCount ?? maxLength !== undefined;\n    const count = value.length;\n    const ratio = maxLength ? count / maxLength : 0;\n    const atLimit = maxLength !== undefined && count >= maxLength;\n    const nearLimit = maxLength !== undefined && ratio >= warnAt && !atLimit;\n\n    // Measure the content with an invisible twin so the real field can\n    // transition between pixel heights (resetting it to `auto` would kill the\n    // transition). Height is this component's purpose, so it animates layout.\n    const measure = useCallback(() => {\n      const mirror = mirrorRef.current;\n      if (!mirror) return;\n      const style = getComputedStyle(mirror);\n      const lineHeight = Number.parseFloat(style.lineHeight) || 24;\n      const padY =\n        Number.parseFloat(style.paddingTop) +\n        Number.parseFloat(style.paddingBottom);\n      const min = lineHeight * minRows + padY;\n      const max = lineHeight * Math.max(minRows, maxRows) + padY;\n      const content = mirror.scrollHeight;\n      setHeight(Math.min(max, Math.max(min, content)));\n      setScrolls(content > max + 1);\n    }, [minRows, maxRows]);\n\n    useLayoutEffect(() => {\n      if (mirrorRef.current) mirrorRef.current.value = value || \" \";\n      measure();\n    }, [value, measure]);\n\n    // Width changes rewrap the text, so re-measure on resize.\n    useEffect(() => {\n      const field = fieldRef.current;\n      if (!field || typeof ResizeObserver === \"undefined\") return;\n      const observer = new ResizeObserver(() => measure());\n      observer.observe(field);\n      return () => observer.disconnect();\n    }, [measure]);\n\n    // Shake the field when an error appears.\n    useEffect(() => {\n      if (!fieldRef.current || reduce || !hasError) return;\n      animate(fieldRef.current, SHAKE, { duration: 0.45 });\n    }, [hasError, reduce]);\n\n    const nudgeCounter = useCallback(() => {\n      if (!counterRef.current || reduce) return;\n      animate(\n        counterRef.current,\n        { x: [0, -4, 4, -3, 3, 0] },\n        { duration: 0.35 },\n      );\n    }, [reduce]);\n\n    // Typing or pasting past `maxLength` is blocked natively; catch the\n    // attempt first so the counter can shake. Native listener because React's\n    // onBeforeInput misses paste and line breaks.\n    useEffect(() => {\n      const el = innerRef.current;\n      if (!el || maxLength === undefined) return;\n      const onBeforeInput = (event: InputEvent) => {\n        if (!event.inputType.startsWith(\"insert\")) return;\n        const data =\n          event.data ??\n          event.dataTransfer?.getData(\"text/plain\") ??\n          (event.inputType === \"insertLineBreak\" ? \"\\n\" : \"\");\n        const selected = el.selectionEnd - el.selectionStart;\n        if (el.value.length - selected + data.length > maxLength) {\n          nudgeCounter();\n        }\n      };\n      el.addEventListener(\"beforeinput\", onBeforeInput);\n      return () => el.removeEventListener(\"beforeinput\", onBeforeInput);\n    }, [maxLength, nudgeCounter]);\n\n    const handleChange = (next: string) => {\n      if (!controlled) setInternal(next);\n      onChange?.(next);\n    };\n\n    const describedBy =\n      [\n        description ? `${id}-description` : null,\n        countVisible ? `${id}-count` : null,\n        errorMessage ? `${id}-error` : null,\n      ]\n        .filter(Boolean)\n        .join(\" \") || undefined;\n\n    const sharedText =\n      \"block w-full resize-none bg-transparent px-3.5 py-2.5 text-base leading-6\";\n\n    return (\n      <div\n        className={cn(\"flex flex-col gap-1.5\", className, classNames?.root)}\n      >\n        {label || description ? (\n          <div className=\"flex flex-col gap-0.5 px-1\">\n            {label ? (\n              <label\n                htmlFor={id}\n                className={cn(\n                  \"text-sm font-medium text-foreground\",\n                  classNames?.label,\n                )}\n              >\n                {label}\n              </label>\n            ) : null}\n            {description ? (\n              <p\n                id={`${id}-description`}\n                className={cn(\n                  \"text-xs text-muted-foreground\",\n                  classNames?.description,\n                )}\n              >\n                {description}\n              </p>\n            ) : null}\n          </div>\n        ) : null}\n\n        <div\n          ref={fieldRef}\n          data-state={hasError ? \"error\" : focused ? \"focused\" : \"idle\"}\n          className={cn(\n            \"relative overflow-hidden rounded-2xl border transition-colors duration-200\",\n            \"border-border\",\n            focused && !hasError && \"border-foreground/40 ring-2 ring-ring/40\",\n            hasError && \"border-destructive ring-2 ring-destructive/25\",\n            disabled && \"opacity-60\",\n            classNames?.field,\n          )}\n        >\n          <textarea\n            ref={mirrorRef}\n            aria-hidden=\"true\"\n            tabIndex={-1}\n            readOnly\n            rows={1}\n            className={cn(\n              sharedText,\n              \"pointer-events-none invisible absolute inset-x-0 top-0 h-0 overflow-hidden\",\n              classNames?.textarea,\n            )}\n          />\n          <textarea\n            ref={setRefs}\n            id={id}\n            rows={minRows}\n            value={value}\n            disabled={disabled}\n            maxLength={maxLength}\n            placeholder={placeholder}\n            aria-invalid={hasError || undefined}\n            aria-describedby={describedBy}\n            {...rest}\n            onChange={(e) => handleChange(e.target.value)}\n            onFocus={(event) => {\n              setFocused(true);\n              onFocus?.(event);\n            }}\n            onBlur={(event) => {\n              setFocused(false);\n              onBlur?.(event);\n            }}\n            style={{\n              height: height ?? undefined,\n              transition: reduce ? undefined : `height 160ms ${EASE_OUT_CSS}`,\n              ...rest.style,\n            }}\n            className={cn(\n              sharedText,\n              \"text-foreground caret-foreground outline-none\",\n              \"placeholder:text-muted-foreground/60\",\n              scrolls\n                ? \"overflow-y-auto [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]\"\n                : \"overflow-y-hidden\",\n              disabled && \"cursor-not-allowed\",\n              classNames?.textarea,\n            )}\n          />\n\n          {countVisible ? (\n            <div className=\"flex justify-end px-3.5 pb-2\">\n              <span\n                ref={counterRef}\n                id={`${id}-count`}\n                className={cn(\n                  \"inline-block text-xs tabular-nums text-muted-foreground transition-colors duration-200\",\n                  nearLimit && \"text-warning\",\n                  atLimit && \"text-destructive\",\n                  classNames?.counter,\n                )}\n              >\n                <motion.span\n                  key={atLimit ? \"limit\" : \"count\"}\n                  className=\"inline-block\"\n                  initial={reduce || !atLimit ? false : { scale: 1.2 }}\n                  animate={{ scale: 1 }}\n                  transition={SPRING_PRESS}\n                >\n                  {maxLength !== undefined ? `${count}/${maxLength}` : count}\n                </motion.span>\n                <span className=\"sr-only\">\n                  {maxLength !== undefined\n                    ? ` characters used, ${maxLength - count} remaining`\n                    : \" characters\"}\n                </span>\n              </span>\n            </div>\n          ) : null}\n        </div>\n\n        <AnimatePresence initial={false}>\n          {errorMessage ? (\n            <motion.p\n              id={`${id}-error`}\n              role=\"alert\"\n              initial={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, y: -4, filter: \"blur(4px)\" }\n              }\n              animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n              exit={\n                reduce\n                  ? { opacity: 0 }\n                  : { opacity: 0, y: -4, filter: \"blur(4px)\" }\n              }\n              transition={{ duration: 0.2 }}\n              className={cn(\n                \"px-1 text-xs text-destructive\",\n                classNames?.errorMessage,\n              )}\n            >\n              {errorMessage}\n            </motion.p>\n          ) : null}\n        </AnimatePresence>\n      </div>\n    );\n  },\n);\n"},{"path":"components/motion/toggle-group.tsx","type":"registry:component","target":"@components/motion/toggle-group.tsx","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  createContext,\n  forwardRef,\n  type KeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { TOUCH_TARGET_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\n// Toggle / ToggleGroup vs SegmentedControl: `SegmentedControl`\n// (segmented-control.tsx) is a radiogroup form control that always holds one\n// value and ships a data-driven `ToggleGroup` for quick `items` arrays. This\n// file is the composable, shadcn-shaped toolbar primitive: a standalone\n// `Toggle`, and a `ToggleGroup` you fill with `ToggleGroupItem` children\n// (icons, labels, tooltips, anything), with `default`/`outline` variants. In\n// single mode one pressed surface glides between items; in multiple mode each\n// item pops its own surface in and out.\n\nexport type ToggleVariant = \"default\" | \"outline\";\nexport type ToggleSize = \"sm\" | \"md\" | \"lg\";\n\nconst sizeClass: Record<ToggleSize, string> = {\n  sm: \"h-7 min-w-7 gap-1.5 px-2 text-xs [&_svg]:size-3.5\",\n  md: \"h-9 min-w-9 gap-2 px-2.5 text-sm [&_svg]:size-4\",\n  lg: \"h-11 min-w-11 gap-2 px-3.5 text-sm [&_svg]:size-[18px]\",\n};\n\nconst surfaceClass: Record<ToggleVariant, string> = {\n  default: \"bg-muted ring-1 ring-border-strong\",\n  outline: \"bg-muted\",\n};\n\nconst itemBase =\n  \"relative isolate inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap font-medium outline-none transition-colors duration-200 focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50\";\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange: ((next: T) => void) | undefined,\n) {\n  const [internal, setInternal] = useState<T>(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const set = useCallback(\n    (next: T) => {\n      if (!controlled) setInternal(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\ntype ButtonBaseProps = Omit<HTMLMotionProps<\"button\">, \"children\" | \"value\" | \"type\">;\n\n/** The pressed surface that pops in and out behind a standalone toggle or a multiple-mode item. */\nfunction PopSurface({ show, variant }: { show: boolean; variant: ToggleVariant }) {\n  const reduce = useReducedMotion();\n  return (\n    <AnimatePresence initial={false}>\n      {show ? (\n        <motion.span\n          key=\"on\"\n          aria-hidden\n          initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n          animate={{ opacity: 1, scale: 1 }}\n          exit={\n            reduce\n              ? { opacity: 0 }\n              : { opacity: 0, scale: 0.75, transition: { duration: 0.12 } }\n          }\n          transition={SPRING_SWAP}\n          className={cn(\"absolute inset-0 -z-10 rounded-[inherit]\", surfaceClass[variant])}\n        />\n      ) : null}\n    </AnimatePresence>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Toggle                                                                    */\n/* ------------------------------------------------------------------------ */\n\nexport interface ToggleProps extends ButtonBaseProps {\n  pressed?: boolean;\n  defaultPressed?: boolean;\n  onPressedChange?: (pressed: boolean) => void;\n  variant?: ToggleVariant;\n  size?: ToggleSize;\n  children?: ReactNode;\n}\n\n/** A two-state button (`aria-pressed`) whose pressed surface springs in and out. */\nexport const Toggle = forwardRef<HTMLButtonElement, ToggleProps>(function Toggle(\n  {\n    pressed,\n    defaultPressed = false,\n    onPressedChange,\n    variant = \"default\",\n    size = \"md\",\n    disabled,\n    className,\n    children,\n    onClick,\n    ...rest\n  },\n  ref,\n) {\n  const reduce = useReducedMotion();\n  const [on, setOn] = useControllable(pressed, defaultPressed, onPressedChange);\n  return (\n    <motion.button\n      ref={ref}\n      type=\"button\"\n      aria-pressed={on}\n      data-state={on ? \"on\" : \"off\"}\n      disabled={disabled}\n      whileTap={reduce || disabled ? undefined : { scale: 0.9 }}\n      transition={SPRING_PRESS}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) setOn(!on);\n      }}\n      className={cn(\n        itemBase,\n        TOUCH_TARGET_CLASS,\n        \"rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-background\",\n        sizeClass[size],\n        variant === \"outline\" && \"border border-border\",\n        on\n          ? \"text-foreground\"\n          : \"text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground\",\n        className,\n      )}\n      {...rest}\n    >\n      <PopSurface show={on} variant={variant} />\n      {children}\n    </motion.button>\n  );\n});\n\n/* ------------------------------------------------------------------------ */\n/* ToggleGroup                                                               */\n/* ------------------------------------------------------------------------ */\n\ninterface ToggleGroupContextValue {\n  type: \"single\" | \"multiple\";\n  pressed: string[];\n  toggle: (value: string) => void;\n  variant: ToggleVariant;\n  size: ToggleSize;\n  disabled: boolean;\n  layoutId: string;\n  tabStop: string | null;\n  setTabStop: (value: string) => void;\n}\n\nconst ToggleGroupContext = createContext<ToggleGroupContextValue | null>(null);\n\ntype ToggleGroupBase = Omit<\n  HTMLMotionProps<\"div\">,\n  \"children\" | \"defaultValue\" | \"onChange\" | \"dir\"\n> & {\n  variant?: ToggleVariant;\n  size?: ToggleSize;\n  disabled?: boolean;\n  /** Arrow-key axis for roving focus. Default \"horizontal\" (both axes still work). */\n  orientation?: \"horizontal\" | \"vertical\";\n  children?: ReactNode;\n};\n\nexport type ToggleGroupSingleProps = ToggleGroupBase & {\n  type: \"single\";\n  /** The pressed item, or `\"\"` when none is pressed. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Disallow un-pressing the active item, so one is always pressed. */\n  required?: boolean;\n};\n\nexport type ToggleGroupMultipleProps = ToggleGroupBase & {\n  type: \"multiple\";\n  value?: string[];\n  defaultValue?: string[];\n  onValueChange?: (value: string[]) => void;\n};\n\nexport type ToggleGroupProps = ToggleGroupSingleProps | ToggleGroupMultipleProps;\n\nconst ITEM_SELECTOR = \"[data-toggle-group-item]\";\n\nfunction enabledItems(root: HTMLElement | null) {\n  if (!root) return [];\n  return Array.from(root.querySelectorAll<HTMLButtonElement>(ITEM_SELECTOR)).filter(\n    (el) => !el.disabled && el.closest(\"[data-toggle-group]\") === root,\n  );\n}\n\n/**\n * Toolbar-style group of `ToggleGroupItem`s. `type=\"single\"` behaves like a\n * set of mutually exclusive toggles (deselectable unless `required`) whose\n * pressed surface glides between items; `type=\"multiple\"` presses any subset.\n * One tab stop, arrow keys / Home / End rove between items, Space/Enter press.\n */\nexport function ToggleGroup(props: ToggleGroupProps) {\n  const {\n    type,\n    value: _value,\n    defaultValue: _defaultValue,\n    onValueChange: _onValueChange,\n    variant = \"default\",\n    size = \"md\",\n    disabled = false,\n    orientation = \"horizontal\",\n    className,\n    children,\n    onKeyDown,\n    ...rest\n  } = props;\n  // `required` only exists on the single variant; keep it off the DOM.\n  const { required: _required, ...domProps } = rest as typeof rest & { required?: boolean };\n  const single = props.type === \"single\";\n  const required = props.type === \"single\" && Boolean(props.required);\n\n  const [pressed, setPressed] = useControllable<string[]>(\n    props.value === undefined\n      ? undefined\n      : props.type === \"single\"\n        ? props.value\n          ? [props.value]\n          : []\n        : props.value,\n    props.type === \"single\"\n      ? props.defaultValue\n        ? [props.defaultValue]\n        : []\n      : (props.defaultValue ?? []),\n    (next) => {\n      if (props.type === \"single\") props.onValueChange?.(next[0] ?? \"\");\n      else props.onValueChange?.(next);\n    },\n  );\n\n  const layoutId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [tabStop, setTabStop] = useState<string | null>(pressed[0] ?? null);\n\n  // Keep exactly one reachable tab stop: if the remembered item vanished or\n  // got disabled, fall back to the first pressed item, then the first enabled.\n  useEffect(() => {\n    const items = enabledItems(rootRef.current);\n    if (items.some((el) => el.dataset.value === tabStop)) return;\n    const fallback =\n      items.find((el) => pressed.includes(el.dataset.value ?? \"\")) ?? items[0];\n    const next = fallback?.dataset.value ?? null;\n    if (next !== tabStop) setTabStop(next);\n  });\n\n  const toggle = (itemValue: string) => {\n    const isOn = pressed.includes(itemValue);\n    if (single) {\n      if (isOn && required) return;\n      setPressed(isOn ? [] : [itemValue]);\n    } else {\n      setPressed(isOn ? pressed.filter((v) => v !== itemValue) : [...pressed, itemValue]);\n    }\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    const items = enabledItems(rootRef.current);\n    const index = items.indexOf(document.activeElement as HTMLButtonElement);\n    if (index < 0) return;\n    const forward = orientation === \"vertical\" ? \"ArrowDown\" : \"ArrowRight\";\n    const backward = orientation === \"vertical\" ? \"ArrowUp\" : \"ArrowLeft\";\n    let next: number;\n    if (event.key === forward || event.key === \"ArrowDown\" || event.key === \"ArrowRight\")\n      next = (index + 1) % items.length;\n    else if (event.key === backward || event.key === \"ArrowUp\" || event.key === \"ArrowLeft\")\n      next = (index - 1 + items.length) % items.length;\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = items.length - 1;\n    else return;\n    event.preventDefault();\n    // Focus moves; pressing stays on Space/Enter — these are toggles, not radios.\n    items[next].focus();\n  };\n\n  return (\n    <ToggleGroupContext.Provider\n      value={{\n        type,\n        pressed,\n        toggle,\n        variant,\n        size,\n        disabled,\n        layoutId,\n        tabStop,\n        setTabStop,\n      }}\n    >\n      {/* layoutRoot keeps the gliding surface's projection local to the group,\n          so scrolled or transformed ancestors never skew the glide. */}\n      <motion.div\n        ref={rootRef}\n        layoutRoot\n        role=\"group\"\n        data-toggle-group=\"\"\n        data-orientation={orientation}\n        aria-disabled={disabled || undefined}\n        onKeyDown={handleKeyDown}\n        className={cn(\n          \"inline-flex w-fit items-center\",\n          orientation === \"vertical\" && \"flex-col items-stretch\",\n          variant === \"default\"\n            ? \"gap-0.5 rounded-xl border border-border bg-card p-1\"\n            : \"rounded-lg\",\n          disabled && \"opacity-60\",\n          className,\n        )}\n        {...domProps}\n      >\n        {children}\n      </motion.div>\n    </ToggleGroupContext.Provider>\n  );\n}\n\nexport interface ToggleGroupItemProps extends ButtonBaseProps {\n  value: string;\n  children?: ReactNode;\n}\n\nexport const ToggleGroupItem = forwardRef<HTMLButtonElement, ToggleGroupItemProps>(\n  function ToggleGroupItem(\n    { value, disabled: itemDisabled, className, children, onClick, onFocus, ...rest },\n    ref,\n  ) {\n    const ctx = useContext(ToggleGroupContext);\n    if (!ctx) throw new Error(\"ToggleGroupItem must be used inside <ToggleGroup>.\");\n    const reduce = useReducedMotion();\n    const disabled = ctx.disabled || Boolean(itemDisabled);\n    const on = ctx.pressed.includes(value);\n    const outline = ctx.variant === \"outline\";\n\n    return (\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        data-toggle-group-item=\"\"\n        data-value={value}\n        data-state={on ? \"on\" : \"off\"}\n        aria-pressed={on}\n        disabled={disabled}\n        tabIndex={ctx.tabStop === value ? 0 : -1}\n        whileTap={reduce || disabled ? undefined : { scale: 0.88 }}\n        transition={SPRING_PRESS}\n        onFocus={(event) => {\n          ctx.setTabStop(value);\n          onFocus?.(event);\n        }}\n        onClick={(event) => {\n          onClick?.(event);\n          if (event.defaultPrevented) return;\n          ctx.setTabStop(value);\n          ctx.toggle(value);\n        }}\n        className={cn(\n          itemBase,\n          TOUCH_TARGET_CLASS,\n          sizeClass[ctx.size],\n          outline\n            ? // Joined segments: neighbours overlap their shared border.\n              \"rounded-none border border-border bg-card -ml-px first:ml-0 first:rounded-l-lg last:rounded-r-lg in-data-[orientation=vertical]:-mt-px in-data-[orientation=vertical]:ml-0 in-data-[orientation=vertical]:first:mt-0 in-data-[orientation=vertical]:first:rounded-l-none in-data-[orientation=vertical]:first:rounded-t-lg in-data-[orientation=vertical]:last:rounded-r-none in-data-[orientation=vertical]:last:rounded-b-lg\"\n            : \"rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-card\",\n          on\n            ? \"text-foreground\"\n            : \"text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground\",\n          className,\n        )}\n        {...rest}\n      >\n        {ctx.type === \"single\" ? (\n          on ? (\n            <motion.span\n              layoutId={ctx.layoutId}\n              aria-hidden\n              transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n              className={cn(\n                \"absolute inset-0 -z-10 rounded-[inherit]\",\n                surfaceClass[ctx.variant],\n              )}\n            />\n          ) : null\n        ) : (\n          <PopSurface show={on} variant={ctx.variant} />\n        )}\n        {children}\n      </motion.button>\n    );\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;\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"},{"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":"components/motion/button/base.tsx","type":"registry:component","target":"@components/motion/button/base.tsx","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { TOUCH_TARGET_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ButtonVariant = \"primary\" | \"secondary\" | \"ghost\" | \"outline\";\nexport type ButtonSize = \"sm\" | \"md\" | \"lg\" | \"icon\";\n\nexport interface ButtonProps extends Omit<\n  HTMLMotionProps<\"button\">,\n  \"children\"\n> {\n  variant?: ButtonVariant;\n  size?: ButtonSize;\n  pressScale?: number;\n  /** Spawn a Material-style ripple from the press point. Off by default. */\n  ripple?: boolean;\n  children?: ReactNode;\n}\n\nexport interface ButtonLinkProps extends Omit<\n  HTMLMotionProps<\"a\">,\n  \"children\"\n> {\n  variant?: ButtonVariant;\n  size?: ButtonSize;\n  pressScale?: number;\n  children?: ReactNode;\n}\n\ntype Ripple = { id: number; x: number; y: number; size: number };\n\nconst VARIANT_CLASS: Record<ButtonVariant, string> = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary: \"border border-border bg-card text-foreground hover:border-border\",\n  ghost: \"text-muted-foreground hover:text-foreground hover:bg-primary/5\",\n  outline:\n    \"border border-border bg-transparent text-foreground hover:bg-primary/5\",\n};\n\nconst SIZE_CLASS: Record<ButtonSize, string> = {\n  sm: \"h-8 px-3 text-xs gap-1.5 rounded-full\",\n  md: \"h-10 px-5 text-sm gap-2 rounded-full\",\n  lg: \"h-12 px-6 text-base gap-2 rounded-full\",\n  icon: \"h-8 w-8 rounded-lg\",\n};\n\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n  function Button(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.93,\n      ripple = false,\n      className,\n      children,\n      onPointerDown,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n    const canHover = useHoverCapable();\n    const [ripples, setRipples] = useState<Ripple[]>([]);\n    const nextId = useRef(0);\n\n    const handlePointerDown = useCallback(\n      (event: PointerEvent<HTMLButtonElement>) => {\n        if (ripple && !reduce) {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const size = Math.max(rect.width, rect.height) * 2;\n          const id = nextId.current++;\n          setRipples((prev) => [\n            ...prev,\n            {\n              id,\n              x: event.clientX - rect.left,\n              y: event.clientY - rect.top,\n              size,\n            },\n          ]);\n        }\n        onPointerDown?.(event);\n      },\n      [ripple, reduce, onPointerDown],\n    );\n\n    return (\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}\n        transition={SPRING_PRESS}\n        onPointerDown={handlePointerDown}\n        className={cn(\n          \"relative inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          // The ripple layer clips itself, so on a touch screen the button can\n          // stop clipping and let its enlarged hit area overhang.\n          ripple && \"overflow-hidden pointer-coarse:overflow-visible\",\n          TOUCH_TARGET_CLASS,\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {ripple && !reduce ? (\n          <span className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]\">\n            <AnimatePresence>\n              {ripples.map((r) => (\n                <motion.span\n                  key={r.id}\n                  className=\"absolute rounded-full bg-current\"\n                  style={{\n                    left: r.x,\n                    top: r.y,\n                    width: r.size,\n                    height: r.size,\n                    x: \"-50%\",\n                    y: \"-50%\",\n                  }}\n                  initial={{ scale: 0.05, opacity: 0.3 }}\n                  animate={{ scale: 1, opacity: 0 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: 1.6, ease: EASE_OUT }}\n                  onAnimationComplete={() =>\n                    setRipples((prev) => prev.filter((x) => x.id !== r.id))\n                  }\n                />\n              ))}\n            </AnimatePresence>\n          </span>\n        ) : null}\n        {children}\n      </motion.button>\n    );\n  },\n);\n\nexport const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(\n  function ButtonLink(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.93,\n      className,\n      children,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n    const canHover = useHoverCapable();\n\n    return (\n      <motion.a\n        ref={ref}\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        whileHover={reduce || !canHover ? undefined : { scale: 1.02 }}\n        transition={SPRING_PRESS}\n        className={cn(\n          \"relative inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          TOUCH_TARGET_CLASS,\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {children}\n      </motion.a>\n    );\n  },\n);\n"},{"path":"components/motion/button/magnetic.tsx","type":"registry:component","target":"@components/motion/button/magnetic.tsx","content":"\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Magnetic } from \"../magnetic\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MagneticButtonProps extends ButtonProps {\n  /** Magnetic pull strength. Default 0.25. */\n  strength?: number;\n  /** Class applied to the magnetic wrapper. */\n  magneticClassName?: string;\n}\n\nexport const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(\n  { strength = 0.25, magneticClassName, children, ...rest },\n  ref,\n) {\n  return (\n    <Magnetic strength={strength} className={magneticClassName}>\n      <Button ref={ref} {...rest}>\n        {children}\n      </Button>\n    </Magnetic>\n  );\n});\n"},{"path":"components/motion/button/stateful.tsx","type":"registry:component","target":"@components/motion/button/stateful.tsx","content":"\"use client\";\n\nimport { Check, Loader2, X } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type ReactNode,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport type ButtonState = \"idle\" | \"loading\" | \"success\" | \"error\";\n\nexport interface StatefulButtonProps extends Omit<ButtonProps, \"children\"> {\n  state?: ButtonState;\n  children: ReactNode;\n  loadingText?: ReactNode;\n  successText?: ReactNode;\n  errorText?: ReactNode;\n  icon?: ReactNode;\n}\n\nconst CASCADE_STAGGER = 0.025;\nconst ROLL_BLUR = \"blur(6px)\";\n\nconst CASCADE_LETTER_VARIANTS: Variants = {\n  initial: { opacity: 0, y: \"105%\", filter: ROLL_BLUR },\n  animate: (delay: number = 0) => ({\n    opacity: 1,\n    y: \"0%\",\n    filter: \"blur(0px)\",\n    transition: { ...SPRING_SWAP, delay },\n  }),\n  exit: (delay: number = 0) => ({\n    opacity: 0,\n    y: \"-105%\",\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },\n  }),\n};\n\nconst ICON_VARIANTS: Variants = {\n  // Width collapses too, so the icon adds/removes its own space smoothly\n  // instead of popping the row width in a single frame.\n  initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },\n  animate: {\n    opacity: 1,\n    width: \"1.5rem\",\n    scale: 1,\n    filter: \"blur(0px)\",\n    transition: SPRING_SWAP,\n  },\n  exit: {\n    opacity: 0,\n    width: 0,\n    scale: 0.7,\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT },\n  },\n};\n\nfunction IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {\n  const reduce = useReducedMotion();\n  return (\n    <motion.span\n      key={keyId}\n      variants={ICON_VARIANTS}\n      initial={reduce ? { opacity: 0 } : \"initial\"}\n      animate={reduce ? { opacity: 1 } : \"animate\"}\n      exit={reduce ? { opacity: 0 } : \"exit\"}\n      transition={reduce ? { duration: 0.15 } : undefined}\n      className=\"inline-grid shrink-0 place-items-center overflow-hidden\"\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nfunction TextSlot({\n  value,\n  children,\n}: {\n  value: string;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion();\n  const measureRef = useRef<HTMLSpanElement>(null);\n  const [width, setWidth] = useState<number>();\n  const label = typeof children === \"string\" ? children : null;\n  const cascade = label !== null && !reduce;\n\n  // Measure strings with the same per-letter layout as the cascade. Measuring\n  // the whole string preserves kerning, which can make it narrower than the\n  // inline-block letters and clip the final glyph during the width animation.\n  useLayoutEffect(() => {\n    const nextWidth = measureRef.current?.offsetWidth;\n    if (!nextWidth) return;\n    setWidth((current) => (current === nextWidth ? current : nextWidth));\n  });\n\n  return (\n    <motion.span\n      initial={false}\n      animate={{ width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className=\"relative inline-block overflow-hidden whitespace-nowrap align-bottom\"\n    >\n      <span\n        ref={measureRef}\n        aria-hidden\n        className=\"invisible inline-block whitespace-nowrap\"\n      >\n        {cascade\n          ? label.split(\"\").map((char, index) => (\n              <span\n                // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                key={index}\n                className=\"inline-block whitespace-pre\"\n              >\n                {char}\n              </span>\n            ))\n          : children}\n      </span>\n\n      {cascade ? (\n        <>\n          <span className=\"sr-only\">{label}</span>\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={`cascade-${value}`}\n              aria-hidden\n              initial=\"initial\"\n              animate=\"animate\"\n              exit=\"exit\"\n              className=\"absolute left-0 top-0 inline-block whitespace-pre\"\n            >\n              {label.split(\"\").map((char, index) => (\n                <motion.span\n                  // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                  key={index}\n                  custom={index * CASCADE_STAGGER}\n                  variants={CASCADE_LETTER_VARIANTS}\n                  className=\"inline-block whitespace-pre will-change-[opacity,filter,transform]\"\n                >\n                  {char}\n                </motion.span>\n              ))}\n            </motion.span>\n          </AnimatePresence>\n        </>\n      ) : (\n        <AnimatePresence initial={false}>\n          <motion.span\n            key={`text-${value}`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}\n            animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}\n            transition={reduce ? { duration: 0.15 } : SPRING_SWAP}\n            className=\"absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]\"\n          >\n            {children}\n          </motion.span>\n        </AnimatePresence>\n      )}\n    </motion.span>\n  );\n}\n\nexport const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(\n  {\n    state = \"idle\",\n    children,\n    loadingText = \"Loading\",\n    successText = \"Done\",\n    errorText = \"Try again\",\n    icon,\n    disabled,\n    ...rest\n  },\n  ref,\n) {\n  const isBusy = state === \"loading\";\n  const stateText =\n    state === \"loading\"\n      ? loadingText\n      : state === \"success\"\n        ? successText\n        : state === \"error\"\n        ? errorText\n        : children;\n  const textKey =\n    typeof stateText === \"string\" ? `${state}-${stateText}` : state;\n\n  return (\n    <Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} whileHover={undefined} {...rest}>\n      <span\n        aria-live=\"polite\"\n        className=\"relative inline-flex items-center justify-center overflow-hidden\"\n      >\n        <AnimatePresence initial={false}>\n          {state === \"loading\" ? (\n            <IconSlot keyId=\"loading-icon\">\n              <Loader2 className=\"h-4 w-4 animate-spin\" />\n            </IconSlot>\n          ) : null}\n          {state === \"success\" ? (\n            <IconSlot keyId=\"success-icon\">\n              <Check className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n          {state === \"error\" ? (\n            <IconSlot keyId=\"error-icon\">\n              <X className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n        </AnimatePresence>\n\n        <TextSlot value={textKey}>{stateText}</TextSlot>\n\n        <AnimatePresence initial={false}>\n          {state === \"idle\" && icon ? (\n            <IconSlot keyId=\"idle-icon\">{icon}</IconSlot>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/anchored-placement.ts","type":"registry:component","target":"@components/motion/anchored-placement.ts","content":"import type { PortalLayout } from \"@/components/motion/popover-position\";\n\nexport type PlacementSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type PlacementAlign = \"start\" | \"center\" | \"end\";\n\nexport interface PlacementOptions {\n  side: PlacementSide;\n  align: PlacementAlign;\n  /** Gap between trigger and panel along the side axis, in px. */\n  sideOffset?: number;\n  /** Shift along the align axis, in px. */\n  alignOffset?: number;\n  /** Minimum distance kept from the viewport edges, in px. */\n  padding?: number;\n}\n\nexport interface Placement {\n  left: number;\n  top: number;\n  /** The side actually used — differs from the requested one after a flip. */\n  side: PlacementSide;\n  /** Trigger-facing point of the panel, as a CSS transform-origin (px). */\n  origin: string;\n}\n\nconst OPPOSITE: Record<PlacementSide, PlacementSide> = {\n  top: \"bottom\",\n  bottom: \"top\",\n  left: \"right\",\n  right: \"left\",\n};\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\n/**\n * Places a portalled panel against its trigger in viewport coordinates\n * (pair with `usePopoverPortalPosition`). Flips to the opposite side when the\n * requested one lacks room and the other has more, then clamps the panel into\n * the viewport on both axes. The returned origin is the trigger's center\n * projected onto the panel's facing edge, so a scale entrance grows out of the\n * trigger even after a flip or a clamp.\n */\nexport function resolvePlacement(\n  layout: PortalLayout,\n  {\n    side: requested,\n    align,\n    sideOffset = 6,\n    alignOffset = 0,\n    padding = 8,\n  }: PlacementOptions,\n): Placement {\n  const { trigger, content } = layout;\n  const vw = window.innerWidth;\n  const vh = window.innerHeight;\n  const space: Record<PlacementSide, number> = {\n    top: trigger.top - sideOffset - padding,\n    bottom: vh - (trigger.top + trigger.height) - sideOffset - padding,\n    left: trigger.left - sideOffset - padding,\n    right: vw - (trigger.left + trigger.width) - sideOffset - padding,\n  };\n  const vertical = requested === \"top\" || requested === \"bottom\";\n  const need = vertical ? content.height : content.width;\n  const opposite = OPPOSITE[requested];\n  const side =\n    space[requested] < need && space[opposite] > space[requested]\n      ? opposite\n      : requested;\n\n  let left: number;\n  let top: number;\n  if (vertical) {\n    top =\n      side === \"bottom\"\n        ? trigger.top + trigger.height + sideOffset\n        : trigger.top - content.height - sideOffset;\n    left =\n      align === \"start\"\n        ? trigger.left\n        : align === \"end\"\n          ? trigger.left + trigger.width - content.width\n          : trigger.left + trigger.width / 2 - content.width / 2;\n    left = clamp(left + alignOffset, padding, vw - content.width - padding);\n    top = clamp(top, padding, vh - content.height - padding);\n  } else {\n    left =\n      side === \"right\"\n        ? trigger.left + trigger.width + sideOffset\n        : trigger.left - content.width - sideOffset;\n    top =\n      align === \"start\"\n        ? trigger.top\n        : align === \"end\"\n          ? trigger.top + trigger.height - content.height\n          : trigger.top + trigger.height / 2 - content.height / 2;\n    top = clamp(top + alignOffset, padding, vh - content.height - padding);\n    left = clamp(left, padding, vw - content.width - padding);\n  }\n\n  const cx = clamp(trigger.left + trigger.width / 2 - left, 0, content.width);\n  const cy = clamp(trigger.top + trigger.height / 2 - top, 0, content.height);\n  const origin =\n    side === \"bottom\"\n      ? `${cx}px 0px`\n      : side === \"top\"\n        ? `${cx}px ${content.height}px`\n        : side === \"right\"\n          ? `0px ${cy}px`\n          : `${content.width}px ${cy}px`;\n\n  return { left, top, side, origin };\n}\n"},{"path":"components/motion/popover-position.ts","type":"registry:component","target":"@components/motion/popover-position.ts","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\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\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Return true for an outside target that should *not* dismiss. Must be stable. */\n  ignore?: (target: Element) => boolean;\n}\n\n/**\n * What every currently open dismiss scope counts as inside itself. A consumed\n * dismissal reads this to tell a stray gesture from one that belongs to an\n * overlay in front of it: overlays have no shared z-order to consult, but the\n * one the gesture landed in has said as much by registering it.\n */\nconst openScopes = new Set<(target: Element) => boolean>();\n\nfunction claimedByAnotherScope(\n  self: (target: Element) => boolean,\n  target: Element,\n) {\n  for (const scope of openScopes) {\n    if (scope !== self && scope(target)) return true;\n  }\n  return false;\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. `onDismiss` and `ignore` must be stable (wrap in\n * useCallback) so the listeners aren't re-bound every render while open.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: () => void,\n  ref: RefObject<HTMLElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Element) =>\n      Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));\n    const onKey = (event: KeyboardEvent) => {\n      if (dismissOnEscape && event.key === \"Escape\") onDismiss();\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 one that is also open: 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\" && !claimedByAnotherScope(inside, target)) {\n        consumeActivation(event);\n      }\n      onDismiss();\n    };\n    openScopes.add(inside);\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer, true);\n    return () => {\n      openScopes.delete(inside);\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n    };\n  }, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);\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 * Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple\n * HIG) on a coarse pointer, without changing what it looks like or the space\n * it takes in layout. An invisible `::after` box, centered on the control and\n * `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button\n * reaches 6px past each edge, a wide 40px button only grows vertically, and a\n * control already 44px or larger is left as it is. Hit-testing a pseudo\n * element lands on its owner, so handlers, focus and `:active` all behave.\n *\n * Mouse and trackpad rendering is untouched — nothing here applies outside\n * `pointer: coarse`. Requirements on the element it goes on:\n * - It must be the containing block: add `relative` (and keep it mergeable, so\n *   a consumer's `absolute` still wins through `cn`).\n * - It must not clip itself (`overflow-hidden`), or the overhang is clipped\n *   away along with its hit area.\n * - It must render children: `<input>` and other void elements have no\n *   `::after`. Put it on the wrapper or label instead.\n * - It must not already use `::after` for something visible.\n *\n * Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the\n * later one wins that strip, which still ends well short of the earlier\n * button's visual center. Below a ~32px pitch the later neighbour starts\n * eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.\n *\n * The overhang is real geometry: inside a scroll container it counts as\n * scrollable overflow, so a control flush against a scroller's edge can add a\n * few pixels of scroll on touch screens. Give such a scroller a little padding\n * on that side.\n */\nexport const TOUCH_TARGET_CLASS =\n  \"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']\";\n\n/**\n * `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter\n * than ~32px apart in a row (pagination dots, dense swatches), where growing\n * sideways would hand most of each control to its neighbour. Same rules.\n */\nexport const TOUCH_TARGET_Y_CLASS =\n  \"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal — a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs — routine on iOS, where the\n * system can claim the touch first — and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active — implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer — a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger — so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it — `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"registry:hook","target":"@lib/hooks/use-hover-capable.ts","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * — gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"components/motion/magnetic.tsx","type":"registry:component","target":"@components/motion/magnetic.tsx","content":"\"use client\";\n\nimport { motion, useMotionValue, useReducedMotion, useSpring } from \"motion/react\";\nimport { useRef, type ReactNode } from \"react\";\nimport { SPRING_MOUSE } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface MagneticProps {\n  children: ReactNode;\n  strength?: number;\n  className?: string;\n}\n\nexport function Magnetic({ children, strength = 0.35, className }: MagneticProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const canHover = useHoverCapable();\n  // Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.\n  const enabled = !reduce && canHover;\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const sx = useSpring(x, SPRING_MOUSE);\n  const sy = useSpring(y, SPRING_MOUSE);\n\n  const onMove = (e: React.MouseEvent<HTMLDivElement>) => {\n    const el = ref.current;\n    if (!el || !enabled) return;\n    const rect = el.getBoundingClientRect();\n    x.set((e.clientX - rect.left - rect.width / 2) * strength);\n    y.set((e.clientY - rect.top - rect.height / 2) * strength);\n  };\n\n  const onLeave = () => {\n    x.set(0);\n    y.set(0);\n  };\n\n  return (\n    <motion.div\n      ref={ref}\n      onMouseMove={onMove}\n      onMouseLeave={onLeave}\n      style={{ x: sx, y: sy }}\n      className={cn(\"inline-block\", className)}\n    >\n      {children}\n    </motion.div>\n  );\n}\n"}]}