{"slug":"prompt-input","name":"Prompt Input","description":"An auto-growing agent composer with prompt actions, model selection, keyboard submission, and animated send and stop states.","category":"agents","source_url":"https://beui.dev/r/prompt-input/raw","detail_url":"https://beui.dev/r/prompt-input","raw_url":"https://beui.dev/r/prompt-input/raw","page_url":"https://beui.dev/components/agents/prompt-input","markdown_url":"https://beui.dev/components/agents/prompt-input.md","published_at":"2026-08-02","updated_at":"2026-11-28","dependencies":["@floating-ui/dom","clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["../magnetic","./base","./context","./dropdown-menu/context","./dropdown-menu/item-base","./dropdown-menu/menu-panel","./dropdown-menu/placement","./engine","./magnetic","./metallic","./placement","./stateful","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./use-position","@/components/agents/clip-resize-frame","@/components/agents/prompt-input","@/components/motion/button","@/components/motion/dropdown-menu","@/components/motion/menu/menu-item-highlight","@/components/motion/menu/use-menu-navigation","@/components/motion/popover-position","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/lib/audio-context","@/lib/ease","@/lib/favicon","@/lib/hooks/use-dismiss","@/lib/hooks/use-favicon","@/lib/hooks/use-hover-capable","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-row-cursor","@/lib/hooks/use-tap-gesture","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/presence-gate","@/lib/sound","@/lib/sounds/close","@/lib/sounds/engine","@/lib/sounds/open","@/lib/sounds/press","@/lib/sounds/select","@/lib/touch","@/lib/utils"],"install_slugs":["prompt-input"],"requires_theme":true,"props":[{"displayName":"PromptInput","props":[{"name":"value","type":"string","required":false,"defaultValue":null,"description":"The prompt text, for controlled use."},{"name":"defaultValue","type":"string","required":false,"defaultValue":"","description":"The initial prompt text when uncontrolled. Default: \"\""},{"name":"onValueChange","type":"((value: string) => void)","required":false,"defaultValue":null,"description":"Called with the new text on every edit."},{"name":"models","type":"PromptModel[]","required":false,"defaultValue":"[]","description":"Models listed in the model menu. Hidden when empty."},{"name":"model","type":"string","required":false,"defaultValue":null,"description":"The selected model's value, for controlled use."},{"name":"defaultModel","type":"string","required":false,"defaultValue":null,"description":"The initial model when uncontrolled. Default: the first model"},{"name":"onModelChange","type":"((model: string) => void)","required":false,"defaultValue":null,"description":"Called with the model's value when a model is picked."},{"name":"actions","type":"PromptAction[]","required":false,"defaultValue":"[]","description":"Items in the add menu next to the input. Hidden when empty."},{"name":"onAction","type":"((action: string) => void)","required":false,"defaultValue":null,"description":"Called with the action's value when an add menu item is chosen."},{"name":"commands","type":"PromptCommand[]","required":false,"defaultValue":"[]","description":"Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty."},{"name":"onCommand","type":"((command: string) => void)","required":false,"defaultValue":null,"description":"Called with the command's value when a slash command is picked."},{"name":"onSubmit","type":"((value: string, model?: string) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Called with the trimmed prompt and selected model on Enter or the send button."},{"name":"loading","type":"boolean","required":false,"defaultValue":"false","description":"Swaps send for a stop button and blocks new prompts. Default: false"},{"name":"onStop","type":"(() => void)","required":false,"defaultValue":null,"description":"Called when the stop button is pressed while loading."},{"name":"minRows","type":"number","required":false,"defaultValue":"2","description":"Height of the empty input, in text rows. Default: 2"},{"name":"maxRows","type":"number","required":false,"defaultValue":"8","description":"Rows the input grows to before it scrolls. Default: 8"},{"name":"leadingAction","type":"ReactNode","required":false,"defaultValue":null,"description":"Extra controls placed between the add menu and the model menu."},{"name":"labels","type":"Partial<{ placeholder: string; label: string; addToPrompt: string; chooseModel: string; send: string; stop: string; commands: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the form element."}]}],"types":[{"name":"PromptModel","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"Unique key, passed to `onModelChange` and `onSubmit`."},{"name":"label","type":"ReactNode","required":true,"description":"Name shown in the model menu and on its trigger when selected."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label in the menu and on the trigger."},{"name":"disabled","type":"boolean","required":false,"description":"Stops the model from being picked."}]},{"name":"PromptAction","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"Unique key, passed to `onAction` when the item is chosen."},{"name":"label","type":"ReactNode","required":true,"description":"Item text in the add menu."},{"name":"description","type":"ReactNode","required":false,"description":"Muted line under the label."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label."},{"name":"disabled","type":"boolean","required":false,"description":"Stops the item from being chosen."}]},{"name":"PromptCommand","file":"components/agents/prompt-input.tsx","fields":[{"name":"value","type":"string","required":true,"description":"What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt."},{"name":"label","type":"string","required":true,"description":"Name shown in the command list. Also matched while typing."},{"name":"description","type":"ReactNode","required":false,"description":"Muted line beside the label."},{"name":"icon","type":"ReactNode","required":false,"description":"Icon before the label."}]}],"files":[{"path":"components/agents/prompt-input.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/prompt-input\n\nimport { ArrowUp, ChevronDown, Plus, Square } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type FormEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type TextareaHTMLAttributes,\n  useCallback,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { ClipResizeFrame } from \"@/components/agents/clip-resize-frame\";\nimport { Button } from \"@/components/motion/button\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuItem,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuTrigger,\n} from \"@/components/motion/dropdown-menu\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\n\n/** One identity for the default, so the filtered list stays stable. */\nconst NO_COMMANDS: PromptCommand[] = [];\n\n// The slash list rises in and drops away faster; rows fade in and out as the\n// filter changes, and the rest slide into place.\nconst LIST_IN = { duration: 0.18, ease: EASE_OUT } as const;\nconst LIST_OUT = { duration: 0.12, ease: EASE_OUT } as const;\nconst ROW_OUT = { duration: 0.1, ease: EASE_OUT } as const;\nconst ROW_MOVE = { layout: SPRING_LAYOUT, opacity: { duration: 0.16, ease: EASE_OUT } } as const;\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const promptInputMessages = {\n  placeholder: \"Ask the agent to do something…\",\n  label: \"Prompt\",\n  addToPrompt: \"Add to prompt\",\n  chooseModel: \"Choose model\",\n  send: \"Send prompt\",\n  stop: \"Stop generating\",\n  commands: \"Commands\",\n};\n\nexport type PromptInputMessages = typeof promptInputMessages;\n\nexport interface PromptModel {\n  /** Unique key, passed to `onModelChange` and `onSubmit`. */\n  value: string;\n  /** Name shown in the model menu and on its trigger when selected. */\n  label: ReactNode;\n  /** Icon before the label in the menu and on the trigger. */\n  icon?: ReactNode;\n  /** Stops the model from being picked. */\n  disabled?: boolean;\n}\n\nexport interface PromptAction {\n  /** Unique key, passed to `onAction` when the item is chosen. */\n  value: string;\n  /** Item text in the add menu. */\n  label: ReactNode;\n  /** Muted line under the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n  /** Stops the item from being chosen. */\n  disabled?: boolean;\n}\n\nexport interface PromptCommand {\n  /** What follows the slash: typing `/value` finds it, and picking it writes `/value ` into the prompt. */\n  value: string;\n  /** Name shown in the command list. Also matched while typing. */\n  label: string;\n  /** Muted line beside the label. */\n  description?: ReactNode;\n  /** Icon before the label. */\n  icon?: ReactNode;\n}\n\nexport interface PromptInputProps extends Omit<\n  TextareaHTMLAttributes<HTMLTextAreaElement>,\n  \"value\" | \"defaultValue\" | \"onChange\" | \"onSubmit\" | \"children\"\n> {\n  /** The prompt text, for controlled use. */\n  value?: string;\n  /** The initial prompt text when uncontrolled. Default: \"\" */\n  defaultValue?: string;\n  /** Called with the new text on every edit. */\n  onValueChange?: (value: string) => void;\n  /** Models listed in the model menu. Hidden when empty. */\n  models?: PromptModel[];\n  /** The selected model's value, for controlled use. */\n  model?: string;\n  /** The initial model when uncontrolled. Default: the first model */\n  defaultModel?: string;\n  /** Called with the model's value when a model is picked. */\n  onModelChange?: (model: string) => void;\n  /** Items in the add menu next to the input. Hidden when empty. */\n  actions?: PromptAction[];\n  /** Called with the action's value when an add menu item is chosen. */\n  onAction?: (action: string) => void;\n  /** Slash commands. Typing `/` at the start of a word lists them above the input. Hidden when empty. */\n  commands?: PromptCommand[];\n  /** Called with the command's value when a slash command is picked. */\n  onCommand?: (command: string) => void;\n  /** Called with the trimmed prompt and selected model on Enter or the send button. */\n  onSubmit?: (value: string, model?: string) => void | Promise<void>;\n  /** Swaps send for a stop button and blocks new prompts. Default: false */\n  loading?: boolean;\n  /** Called when the stop button is pressed while loading. */\n  onStop?: () => void;\n  /** Height of the empty input, in text rows. Default: 2 */\n  minRows?: number;\n  /** Rows the input grows to before it scrolls. Default: 8 */\n  maxRows?: number;\n  /** Extra controls placed between the add menu and the model menu. */\n  leadingAction?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<PromptInputMessages>;\n  /** Classes merged onto the form element. */\n  className?: string;\n}\n\nexport function PromptInput({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  models = [],\n  model,\n  defaultModel,\n  onModelChange,\n  actions = [],\n  onAction,\n  commands = NO_COMMANDS,\n  onCommand,\n  onSubmit,\n  loading = false,\n  onStop,\n  minRows = 2,\n  maxRows = 8,\n  leadingAction,\n  labels,\n  className,\n  disabled,\n  placeholder,\n  \"aria-label\": ariaLabel,\n  onKeyDown,\n  ...textareaProps\n}: PromptInputProps) {\n  const t = useMessages(\"promptInput\", promptInputMessages, labels);\n  const reduce = useReducedMotion() ?? false;\n  const textareaRef = useRef<HTMLTextAreaElement>(null);\n  const measurementRef = useRef<HTMLDivElement>(null);\n  const [internalValue, setInternalValue] = useState(defaultValue);\n  const [internalModel, setInternalModel] = useState(\n    defaultModel ?? models[0]?.value,\n  );\n  const [actionsOpen, setActionsOpen] = useState(false);\n  const [modelsOpen, setModelsOpen] = useState(false);\n  const currentValue = value ?? internalValue;\n  const currentModelValue = model ?? internalModel;\n  const currentModel = models.find(\n    (option) => option.value === currentModelValue,\n  );\n  const canSubmit = Boolean(currentValue.trim()) && !disabled && !loading;\n\n  // Slash commands: the word before the caret, when it starts with `/`.\n  const [caret, setCaret] = useState(currentValue.length);\n  // Escape closes the list for the slash it was opened by, until another one.\n  const [dismissedAt, setDismissedAt] = useState(-1);\n  const baseId = useId();\n  const slash = commands.length\n    ? /(?:^|\\s)\\/([\\w-]*)$/.exec(currentValue.slice(0, caret))\n    : null;\n  const query = slash ? slash[1].toLowerCase() : \"\";\n  const slashAt = slash ? caret - slash[1].length - 1 : -1;\n  const matches = slash\n    ? commands.filter(\n        (command) =>\n          command.value.toLowerCase().includes(query) ||\n          command.label.toLowerCase().includes(query),\n      )\n    : NO_COMMANDS;\n  const slashOpen = matches.length > 0 && slashAt !== dismissedAt && !disabled;\n  const commandRows = matches.map((command) => ({ id: command.value }));\n  const { activeIndex, moveTo, moveActive } = useRowCursor(commandRows, query);\n  const activeCommand = slashOpen ? matches[activeIndex] : undefined;\n  const listId = `${baseId}-commands`;\n  const optionId = (value: string) => `${baseId}-command-${value}`;\n  // Pointer moves glide the highlight; arrow keys jump it, a spring would\n  // only trail behind fast arrowing.\n  const [glide, setGlide] = useState(false);\n\n  const pickCommand = (command: PromptCommand) => {\n    const inserted = `/${command.value} `;\n    const next =\n      currentValue.slice(0, slashAt) + inserted + currentValue.slice(caret);\n    const nextCaret = slashAt + inserted.length;\n    setValue(next);\n    setCaret(nextCaret);\n    onCommand?.(command.value);\n    requestAnimationFrame(() => {\n      textareaRef.current?.focus({ preventScroll: true });\n      textareaRef.current?.setSelectionRange(nextCaret, nextCaret);\n    });\n  };\n\n  const resizeTextarea = useCallback(() => {\n    const textarea = textareaRef.current;\n    const measurement = measurementRef.current;\n    if (!textarea || !measurement || textarea.value !== currentValue) return;\n\n    const lineHeight = 24;\n    const nextHeight = Math.min(\n      Math.max(measurement.scrollHeight, minRows * lineHeight),\n      maxRows * lineHeight,\n    );\n    const height = `${nextHeight}px`;\n    if (textarea.style.height !== height) textarea.style.height = height;\n  }, [currentValue, maxRows, minRows]);\n\n  useLayoutEffect(() => {\n    resizeTextarea();\n  }, [resizeTextarea]);\n\n  useEffect(() => {\n    const textarea = textareaRef.current;\n    if (!textarea || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(resizeTextarea);\n    observer.observe(textarea);\n    return () => observer.disconnect();\n  }, [resizeTextarea]);\n\n  const setValue = (next: string) => {\n    if (value === undefined) setInternalValue(next);\n    onValueChange?.(next);\n  };\n\n  const setModel = (next: string) => {\n    if (model === undefined) setInternalModel(next);\n    onModelChange?.(next);\n  };\n\n  const submit = (event?: FormEvent) => {\n    event?.preventDefault();\n    const prompt = currentValue.trim();\n    if (!prompt || disabled || loading) return;\n\n    onSubmit?.(prompt, currentModelValue);\n    if (value === undefined) setInternalValue(\"\");\n    textareaRef.current?.focus({ preventScroll: true });\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n    onKeyDown?.(event);\n    if (slashOpen && !event.defaultPrevented && !event.nativeEvent.isComposing) {\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        setGlide(false);\n        moveActive(event.key === \"ArrowDown\" ? 1 : -1);\n        return;\n      }\n      if ((event.key === \"Enter\" && !event.shiftKey) || event.key === \"Tab\") {\n        event.preventDefault();\n        if (activeCommand) pickCommand(activeCommand);\n        return;\n      }\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        setDismissedAt(slashAt);\n        return;\n      }\n    }\n    if (\n      event.defaultPrevented ||\n      event.key !== \"Enter\" ||\n      event.shiftKey ||\n      event.nativeEvent.isComposing\n    ) {\n      return;\n    }\n    event.preventDefault();\n    submit();\n  };\n\n  return (\n    <form\n      onSubmit={submit}\n      className={cn(\n        \"relative w-full rounded-3xl border border-border/80 bg-background p-2 transition-colors focus-within:border-foreground/25\",\n        disabled && \"opacity-60\",\n        className,\n      )}\n    >\n      <div\n        ref={measurementRef}\n        aria-hidden=\"true\"\n        className=\"pointer-events-none invisible absolute inset-x-2 top-0 whitespace-pre-wrap px-2 text-sm leading-6 [overflow-wrap:break-word]\"\n      >\n        {`${currentValue}\\u200b`}\n      </div>\n\n      {/* The list rises a few px out of the input as it fades in, and drops\n          back faster. Focus stays in the input, which drives it with the arrow\n          keys. As you filter, its top edge glides (the list is anchored at its\n          bottom, above the input), leaving rows fade and the rest slide into\n          place, instead of the edge and rows jumping. */}\n      <AnimatePresence>\n        {slashOpen ? (\n          <motion.div\n            key=\"commands\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 6, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={\n              reduce\n                ? { opacity: 0, pointerEvents: \"none\", transition: LIST_OUT }\n                : { opacity: 0, y: 4, pointerEvents: \"none\", transition: LIST_OUT }\n            }\n            transition={LIST_IN}\n            style={{ transformOrigin: \"bottom left\" }}\n            className=\"absolute inset-x-0 bottom-full z-20 mb-2\"\n          >\n            <ClipResizeFrame edge=\"top\" contentClassName=\"p-2\">\n              <div\n                id={listId}\n                role=\"listbox\"\n                aria-label={t(\"commands\")}\n                className=\"relative max-h-60 overflow-y-auto overscroll-contain\"\n              >\n                <AnimatePresence initial={false} mode=\"popLayout\">\n            {matches.map((command, index) => {\n              const active = index === activeIndex;\n              return (\n                <motion.button\n                  layout={reduce ? false : \"position\"}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0, transition: ROW_OUT }}\n                  transition={ROW_MOVE}\n                  key={command.value}\n                  id={optionId(command.value)}\n                  type=\"button\"\n                  role=\"option\"\n                  aria-selected={active}\n                  tabIndex={-1}\n                  onPointerMove={() => {\n                    if (active) return;\n                    setGlide(true);\n                    moveTo(command.value);\n                  }}\n                  onPointerDown={(event) => event.preventDefault()}\n                  onClick={() => pickCommand(command)}\n                  className={cn(MENU_ITEM_CLASS, \"cursor-default gap-2.5 text-foreground\")}\n                >\n                  {active ? (\n                    <MenuItemHighlight\n                      layoutId={`${baseId}-command-highlight`}\n                      reduce={reduce}\n                      instant={!glide}\n                    />\n                  ) : null}\n                  {command.icon ? (\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"flex shrink-0 text-muted-foreground [&_svg]:size-4\"\n                    >\n                      {command.icon}\n                    </span>\n                  ) : null}\n                  <span className=\"shrink-0\">{command.label}</span>\n                  {command.description ? (\n                    <span className=\"min-w-0 truncate text-xs text-muted-foreground\">\n                      {command.description}\n                    </span>\n                  ) : null}\n                  <span className=\"ml-auto shrink-0 font-mono text-xs text-muted-foreground/70\">\n                    /{command.value}\n                  </span>\n                </motion.button>\n              );\n            })}\n                </AnimatePresence>\n              </div>\n            </ClipResizeFrame>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n      <textarea\n        ref={textareaRef}\n        value={currentValue}\n        disabled={disabled}\n        placeholder={placeholder ?? t(\"placeholder\")}\n        aria-label={ariaLabel ?? t(\"label\")}\n        rows={minRows}\n        {...textareaProps}\n        aria-autocomplete={commands.length ? \"list\" : undefined}\n        aria-controls={slashOpen ? listId : undefined}\n        aria-activedescendant={activeCommand ? optionId(activeCommand.value) : undefined}\n        onChange={(event) => {\n          setValue(event.target.value);\n          setCaret(event.target.selectionStart);\n        }}\n        onSelect={(event) => setCaret(event.currentTarget.selectionStart)}\n        onKeyDown={handleKeyDown}\n        className=\"scrollbar-hide block w-full resize-none overflow-y-auto bg-transparent px-2 pt-1.5 text-sm leading-6 text-foreground outline-none placeholder:text-muted-foreground/55\"\n      />\n\n      <div className=\"mt-1 flex min-h-8 items-center gap-1\">\n        {actions.length ? (\n          // The library menu: arrow keys and typeahead, a highlight that\n          // glides between rows, and no animation when the keyboard opens it.\n          <DropdownMenu open={actionsOpen} onOpenChange={setActionsOpen}>\n            <Tooltip content={t(\"addToPrompt\")} side=\"top\">\n              <AddButton\n                open={actionsOpen}\n                reduce={reduce}\n                disabled={disabled || loading}\n                aria-label={t(\"addToPrompt\")}\n              />\n            </Tooltip>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-72\">\n              {actions.map((action) => (\n                <DropdownMenuItem\n                  key={action.value}\n                  disabled={action.disabled}\n                  onSelect={() => onAction?.(action.value)}\n                  textValue={typeof action.label === \"string\" ? action.label : undefined}\n                  className=\"items-start\"\n                >\n                  {action.icon ? (\n                    <span aria-hidden=\"true\" className=\"mt-0.5 flex shrink-0\">\n                      {action.icon}\n                    </span>\n                  ) : null}\n                  {/* One line each: a menu row is read at a glance. */}\n                  <span className=\"min-w-0 flex-1\">\n                    <span className=\"block truncate\">{action.label}</span>\n                    {action.description ? (\n                      <span className=\"block truncate text-xs leading-4 text-muted-foreground\">\n                        {action.description}\n                      </span>\n                    ) : null}\n                  </span>\n                </DropdownMenuItem>\n              ))}\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n        {leadingAction}\n        {models.length ? (\n          // The same menu as the plus: a model is a pick from a short list,\n          // with the check at the end of the chosen row.\n          <DropdownMenu open={modelsOpen} onOpenChange={setModelsOpen}>\n            <DropdownMenuTrigger disabled={disabled || loading}>\n              <button\n                type=\"button\"\n                disabled={disabled || loading}\n                className=\"inline-flex h-8 min-w-0 max-w-52 items-center gap-1.5 rounded-full px-3 text-xs text-muted-foreground outline-none transition-colors hover:bg-foreground/[0.06] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n              >\n                {currentModel?.icon ? (\n                  <span aria-hidden=\"true\" className=\"flex size-4 shrink-0 items-center justify-center [&_svg]:size-3.5\">\n                    {currentModel.icon}\n                  </span>\n                ) : null}\n                <span className=\"truncate\">{currentModel?.label ?? t(\"chooseModel\")}</span>\n                <motion.span\n                  aria-hidden=\"true\"\n                  animate={{ rotate: modelsOpen ? 180 : 0 }}\n                  transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                  className=\"flex shrink-0\"\n                >\n                  <ChevronDown className=\"size-3.5\" />\n                </motion.span>\n              </button>\n            </DropdownMenuTrigger>\n            <DropdownMenuContent side=\"top\" align=\"start\" sideOffset={8} className=\"w-56\">\n              <DropdownMenuRadioGroup value={currentModelValue ?? \"\"} onValueChange={setModel}>\n                {models.map((option) => (\n                  <DropdownMenuRadioItem\n                    key={option.value}\n                    value={option.value}\n                    disabled={option.disabled}\n                    closeOnSelect\n                    textValue={typeof option.label === \"string\" ? option.label : undefined}\n                  >\n                    {option.icon ? (\n                      <span aria-hidden=\"true\" className=\"flex shrink-0\">\n                        {option.icon}\n                      </span>\n                    ) : null}\n                    <span className=\"min-w-0 truncate\">{option.label}</span>\n                  </DropdownMenuRadioItem>\n                ))}\n              </DropdownMenuRadioGroup>\n            </DropdownMenuContent>\n          </DropdownMenu>\n        ) : null}\n\n        <span className=\"relative ml-auto flex\">\n          <Tooltip content={loading ? t(\"stop\") : t(\"send\")} side=\"top\">\n          <Button\n            type={loading ? \"button\" : \"submit\"}\n            size=\"icon\"\n            disabled={loading ? !onStop : !canSubmit}\n            aria-label={loading ? t(\"stop\") : t(\"send\")}\n            onClick={loading ? onStop : undefined}\n            className={cn(\n              \"size-8 rounded-full\",\n              // Nothing to send: a quiet gray chip, not a dimmed primary. It\n              // lights up the moment there is a prompt.\n              !loading && !canSubmit && \"bg-foreground/[0.06] text-muted-foreground disabled:opacity-100\",\n            )}\n          >\n            <AnimatePresence initial={false} mode=\"popLayout\">\n              <motion.span\n                key={loading ? \"stop\" : \"send\"}\n                // A little blur melts the arrow into the square, so the swap\n                // reads as one icon changing rather than two crossing.\n                initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3, scale: 0.8, filter: \"blur(2px)\" }}\n                animate={{ opacity: 1, y: 0, scale: 1, filter: \"blur(0px)\" }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, y: -3, scale: 0.8, filter: \"blur(2px)\" }}\n                transition={reduce ? { duration: 0 } : SPRING_SWAP}\n                className=\"grid place-items-center\"\n              >\n                {loading ? (\n                  <Square className=\"size-3 fill-current\" />\n                ) : (\n                  <ArrowUp className=\"size-4\" />\n                )}\n              </motion.span>\n            </AnimatePresence>\n          </Button>\n          </Tooltip>\n          {/* While the agent works, a thin arc circles the stop button. */}\n          <AnimatePresence>\n            {loading ? (\n              <motion.svg\n                key=\"working\"\n                aria-hidden=\"true\"\n                viewBox=\"0 0 40 40\"\n                initial={{ opacity: 0, scale: reduce ? 1 : 0.9 }}\n                animate={{ opacity: 1, scale: 1, rotate: reduce ? 0 : 360 }}\n                exit={{ opacity: 0, transition: { duration: 0.15, ease: EASE_OUT } }}\n                transition={{\n                  opacity: { duration: 0.2, ease: EASE_OUT },\n                  scale: { duration: 0.2, ease: EASE_OUT },\n                  rotate: { duration: 1, ease: \"linear\", repeat: Number.POSITIVE_INFINITY },\n                }}\n                className=\"pointer-events-none absolute -inset-1 size-10 text-primary\"\n              >\n                <circle cx=\"20\" cy=\"20\" r=\"19\" fill=\"none\" stroke=\"currentColor\" strokeOpacity={0.15} strokeWidth=\"1.5\" />\n                <circle\n                  cx=\"20\"\n                  cy=\"20\"\n                  r=\"19\"\n                  fill=\"none\"\n                  stroke=\"currentColor\"\n                  strokeWidth=\"1.5\"\n                  strokeLinecap=\"round\"\n                  strokeDasharray=\"30 90\"\n                />\n              </motion.svg>\n            ) : null}\n          </AnimatePresence>\n        </span>\n      </div>\n    </form>\n  );\n}\n\n/**\n * The plus that opens the add menu. Its own component so the tooltip around it\n * and the menu trigger inside both reach the button: the plus turns into a\n * cross while the menu is open.\n */\nfunction AddButton({\n  open,\n  reduce,\n  ...props\n}: ComponentProps<typeof Button> & { open: boolean; reduce: boolean }) {\n  return (\n    <DropdownMenuTrigger disabled={props.disabled}>\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon\"\n        {...props}\n        className=\"size-8 rounded-full data-[state=open]:bg-foreground/[0.06] data-[state=open]:text-foreground\"\n      >\n        <motion.span\n          aria-hidden=\"true\"\n          animate={{ rotate: open ? 45 : 0 }}\n          transition={reduce ? { duration: 0 } : SPRING_SWAP}\n          className=\"flex\"\n        >\n          <Plus className=\"size-4\" />\n        </motion.span>\n      </Button>\n    </DropdownMenuTrigger>\n  );\n}\n"},{"path":"components/agents/clip-resize-frame.tsx","type":"util","content":"\"use client\";\n\nimport {\n  type AnimationPlaybackControls,\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport { type CSSProperties, type ReactNode, useLayoutEffect, useRef } from \"react\";\nimport { EASE_OUT, SPRING_MORPH } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n// The bottom edge glides to the new size; a little quicker when shrinking,\n// since the content inside has already gone.\nconst GROW = { duration: 0.3, ease: EASE_OUT } as const;\nconst SHRINK = { duration: 0.24, ease: EASE_OUT } as const;\n\nexport interface ClipResizeFrameProps extends Omit<HTMLMotionProps<\"div\">, \"children\" | \"style\"> {\n  style?: CSSProperties;\n  /**\n   * Which size follows the content. \"y\": the bottom edge glides as the height\n   * changes. \"x\": both ends glide in or out from the centre as the width\n   * changes, on a morph spring, for pills and chips. Default: \"y\"\n   */\n  axis?: \"x\" | \"y\";\n  /**\n   * With axis \"y\", which edge moves. \"top\" is for a panel anchored at its\n   * bottom, such as a list opening above an input: its top edge glides and its\n   * content stays against the bottom. Default: \"bottom\"\n   */\n  edge?: \"top\" | \"bottom\";\n  /** Outer corner radius in px. The surface inside uses one less. */\n  radius?: number;\n  /** Classes for the content box (padding goes here). */\n  contentClassName?: string;\n  children: ReactNode;\n}\n\n/**\n * A bordered card whose bottom edge glides when its content grows or shrinks,\n * without animating height. The layout changes at once; a clip on the card\n * hides the difference and slides it away. The border is the 1px gap between\n * two clipped layers (the frame in the border colour, the surface inside it),\n * so the bottom line travels with the edge instead of being clipped off.\n */\nexport function ClipResizeFrame({\n  axis = \"y\",\n  edge = \"bottom\",\n  radius = 16,\n  className,\n  contentClassName,\n  style,\n  children,\n  ...props\n}: ClipResizeFrameProps) {\n  const reduce = useReducedMotion() ?? false;\n  const horizontal = axis === \"x\";\n  const fromTop = !horizontal && edge === \"top\";\n  const surfaceRef = useRef<HTMLDivElement>(null);\n  const contentRef = useRef<HTMLDivElement>(null);\n  // How much of the surface (px) is hidden right now: at the moving edge, or\n  // split evenly between the two ends.\n  const gap = useMotionValue(0);\n  const clip = (value: number, round: number) =>\n    horizontal\n      ? `inset(0 ${value / 2}px 0 ${value / 2}px round ${round}px)`\n      : fromTop\n        ? `inset(${value}px 0 0 0 round ${round}px)`\n        : `inset(0 0 ${value}px 0 round ${round}px)`;\n  const frameClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius) : \"none\",\n  );\n  const surfaceClip = useTransform(gap, (value) =>\n    Math.abs(value) > 0.5 ? clip(value, radius - 1) : \"none\",\n  );\n\n  useLayoutEffect(() => {\n    const surface = surfaceRef.current;\n    const content = contentRef.current;\n    if (!surface || !content || typeof ResizeObserver === \"undefined\") return;\n\n    const measure = () => (horizontal ? content.offsetWidth : content.offsetHeight);\n    const side = horizontal ? \"width\" : \"height\";\n    let last = measure();\n    // While shrinking, the surface keeps its old size so the edge has\n    // somewhere to glide from; null when the surface sizes to its content.\n    let held: number | null = null;\n    let controls: AnimationPlaybackControls | undefined;\n\n    const release = () => {\n      held = null;\n      surface.style[side] = \"\";\n      gap.set(0);\n    };\n\n    // Runs after layout and before paint, so the held size lands in the\n    // same frame as the content change: the edge never jumps.\n    const observer = new ResizeObserver(() => {\n      const next = measure();\n      if (next === last) return;\n      const visible = (held ?? last) - gap.get();\n      last = next;\n      controls?.stop();\n\n      if (reduce) {\n        release();\n        return;\n      }\n\n      const from = Math.max(next, visible);\n      held = from > next ? from : null;\n      surface.style[side] = held === null ? \"\" : `${held}px`;\n      gap.set(from - visible);\n      controls = animate(gap, from - next, {\n        ...(horizontal ? SPRING_MORPH : next < visible ? SHRINK : GROW),\n        // The edge has reached the content: hand the size back to layout.\n        onComplete: () => {\n          if (held !== null) release();\n        },\n      });\n    });\n    observer.observe(content);\n    return () => {\n      observer.disconnect();\n      controls?.stop();\n    };\n  }, [gap, reduce, horizontal]);\n\n  return (\n    <motion.div\n      {...props}\n      style={{ ...style, borderRadius: radius, clipPath: frameClip }}\n      className={cn(\"bg-border p-px\", horizontal && \"w-fit\", className)}\n    >\n      <motion.div\n        ref={surfaceRef}\n        style={{ borderRadius: radius - 1, clipPath: surfaceClip }}\n        // Held wider than its content while shrinking, the surface keeps the\n        // content centred, so the two ends close in on it evenly.\n        // Held taller than its content, a top-edge surface keeps the content\n        // against its anchored bottom.\n        className={cn(\n          \"overflow-hidden bg-background\",\n          horizontal && \"flex justify-center\",\n          fromTop && \"flex flex-col justify-end\",\n        )}\n      >\n        <div ref={contentRef} className={cn(horizontal && \"w-max shrink-0\", contentClassName)}>\n          {children}\n        </div>\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/button/index.tsx","type":"util","content":"export type {\n  ButtonLinkProps,\n  ButtonProps,\n  ButtonSize,\n  ButtonVariant,\n} from \"./base\";\nexport { Button, ButtonLink } from \"./base\";\nexport type { MagneticButtonProps } from \"./magnetic\";\nexport { MagneticButton } from \"./magnetic\";\nexport type { MetallicButtonProps } from \"./metallic\";\nexport { MetallicButton } from \"./metallic\";\nexport type {\n  ButtonState,\n  StatefulButtonMessages,\n  StatefulButtonProps,\n} from \"./stateful\";\nexport { StatefulButton, statefulButtonMessages } from \"./stateful\";\n"},{"path":"components/motion/dropdown-menu.tsx","type":"util","content":"\"use client\";\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type MutableRefObject,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { enabledItems } from \"@/components/motion/menu/use-menu-navigation\";\nimport { SPRING_PANEL } from \"@/lib/ease\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useSound } from \"@/lib/sound\";\nimport { closeSound } from \"@/lib/sounds/close\";\nimport { openSound } from \"@/lib/sounds/open\";\nimport { selectSound } from \"@/lib/sounds/select\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, RootContext, type RootContextValue, useLevel, useRoot } from \"./dropdown-menu/context\";\nimport { type DropdownMenuItemProps, ItemBase } from \"./dropdown-menu/item-base\";\nimport { MenuPanel } from \"./dropdown-menu/menu-panel\";\nimport type { Align } from \"./dropdown-menu/placement\";\n\nexport type { DropdownMenuItemProps } from \"./dropdown-menu/item-base\";\n\n// Long enough to skip the submenus a pointer crosses on its way somewhere else.\nconst SUB_OPEN_DELAY = 100;\n// How long a pointer heading for an open submenu may cross sibling rows.\nconst SUB_GRACE = 300;\n\ntype TriggerElementProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  \"data-state\"?: \"open\" | \"closed\";\n};\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Whether the menu is open, for controlled use. */\n  open?: boolean;\n  /** Whether the menu starts open when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the menu opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /**\n   * Play a soft sweep as the menu opens and closes, and a tick for checkbox\n   * and radio rows. Off by default; a `SoundProvider` can mute it app-wide.\n   */\n  sound?: boolean;\n}\n\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  sound = false,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [focusTarget, setFocusTarget] = useState<FocusTarget>(\"first\");\n  const [instant, setInstant] = useState(false);\n  const [mounted, setMounted] = useState(false);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const menuId = useId();\n  const triggerId = useId();\n  const reduce = useReducedMotion() ?? false;\n  const playOpen = useSound(openSound, { enabled: sound });\n  const playClose = useSound(closeSound, { enabled: sound });\n  const playSelect = useSound(selectSound, { enabled: sound });\n\n  useEffect(() => setMounted(true), []);\n\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"first\", now = false) => {\n      if (next !== open) {\n        if (next) playOpen();\n        else playClose();\n        setInstant(now);\n      }\n      if (next) setFocusTarget(focus);\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange, open, playOpen, playClose],\n  );\n\n  // Focus goes back to the trigger when the menu closes from inside it, or\n  // with nothing focused. A click elsewhere keeps the focus it landed on.\n  const wasOpen = useRef(open);\n  useEffect(() => {\n    if (wasOpen.current === open) return;\n    wasOpen.current = open;\n    if (open) return;\n    const active = document.activeElement;\n    if (\n      !active ||\n      active === document.body ||\n      active.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)\n    ) {\n      triggerRef.current?.focus({ preventScroll: true });\n    }\n  }, [open, menuId]);\n\n  const value = useMemo<RootContextValue>(\n    () => ({\n      open,\n      setOpen,\n      focusTarget,\n      instant,\n      menuId,\n      triggerId,\n      triggerRef,\n      reduce,\n      mounted,\n      playSelect,\n    }),\n    [open, setOpen, focusTarget, instant, menuId, triggerId, reduce, mounted, playSelect],\n  );\n\n  return <RootContext.Provider value={value}>{children}</RootContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuTriggerProps {\n  /** A single focusable element, usually a button. */\n  children: ReactElement<TriggerElementProps>;\n  /** Stops clicks and arrow keys from opening the menu. Default: false */\n  disabled?: boolean;\n}\n\nexport function DropdownMenuTrigger({ children, disabled = false }: DropdownMenuTriggerProps) {\n  const root = useRoot(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = children.props.ref;\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      root.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: childProps.id ?? root.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": root.open,\n    \"aria-controls\": root.open ? root.menuId : undefined,\n    \"data-state\": root.open ? \"open\" : \"closed\",\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented || disabled) return;\n      // `detail` is 0 for a click the keyboard synthesized from Enter or Space:\n      // that opener wants the first row and no animation, a pointer wants no\n      // row picked yet and the menu to grow out of the trigger.\n      const keyboard = event.detail === 0;\n      root.setOpen(!root.open, keyboard ? \"first\" : \"panel\", keyboard);\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented || disabled) return;\n      if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n        event.preventDefault();\n        root.setOpen(true, event.key === \"ArrowDown\" ? \"first\" : \"last\", true);\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Classes merged onto the menu panel. */\n  className?: string;\n  /** Preferred side. Flips when the viewport has no room. Default \"bottom\". */\n  side?: \"top\" | \"bottom\";\n  /** Default \"start\". */\n  align?: Align;\n  /** Gap between trigger and menu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuContent({\n  children,\n  className,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n}: DropdownMenuContentProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const panelRef = useRef<HTMLDivElement | null>(null);\n\n  const { setOpen, triggerRef, menuId } = root;\n  // Escape and Tab are keys, so the menu goes at once; a press outside lets it fold away.\n  const dismiss = useCallback(\n    (reason: DismissReason) => setOpen(false, \"first\", reason === \"escape\"),\n    [setOpen],\n  );\n  const closeFromKey = useCallback(() => setOpen(false, \"first\", true), [setOpen]);\n  const ignore = useCallback(\n    (target: Element) =>\n      Boolean(triggerRef.current?.contains(target)) ||\n      Boolean(target.closest(`[data-menu-root=\"${CSS.escape(menuId)}\"]`)),\n    [triggerRef, menuId],\n  );\n  useDismiss(root.open, dismiss, null, { ignore });\n\n  if (!root.mounted) return null;\n\n  return (\n    <AnimatePresence custom={root.instant}>\n      {root.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={root.menuId}\n              anchorRef={root.triggerRef}\n              panelRef={panelRef}\n              side={side}\n              align={align}\n              sideOffset={sideOffset}\n              focus={root.focusTarget}\n              instant={root.instant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={root.triggerRef.current?.id ?? root.triggerId}\n              onClose={closeFromKey}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Items                                                                      */\n/* -------------------------------------------------------------------------- */\n\nexport function DropdownMenuItem(props: DropdownMenuItemProps) {\n  return <ItemBase {...props} />;\n}\n\nexport interface DropdownMenuCheckboxItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** Whether the row is checked. */\n  checked: boolean;\n  /** Called with the new checked state when the row is toggled. */\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** Stays open after a toggle by default, so the check can be seen landing. */\nexport function DropdownMenuCheckboxItem({\n  checked,\n  onCheckedChange,\n  closeOnSelect = false,\n  children,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const root = useRoot(\"DropdownMenuCheckboxItem\");\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemcheckbox\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        if (!closeOnSelect) root.playSelect();\n        onCheckedChange?.(!checked);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <AnimatePresence initial={false}>\n          {checked ? (\n            <motion.span\n              key=\"check\"\n              initial={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              animate={{ opacity: 1, scale: 1 }}\n              exit={root.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n              transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n              className=\"flex\"\n            >\n              <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n            </motion.span>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string;\n  onValueChange?: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  /** The `value` of the checked radio row. */\n  value: string;\n  /** Called with the picked row's value when a radio row is selected. */\n  onValueChange?: (value: string) => void;\n  children: ReactNode;\n  /** Classes merged onto the group wrapper. */\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({ value, onValueChange, children, className }: DropdownMenuRadioGroupProps) {\n  const context = useMemo(() => ({ value, onValueChange }), [value, onValueChange]);\n  return (\n    <RadioGroupContext.Provider value={context}>\n      <div className={className}>{children}</div>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps extends Omit<DropdownMenuItemProps, \"onSelect\" | \"tone\" | \"inset\"> {\n  /** The row's value. Checked when it matches the group's `value`. */\n  value: string;\n}\n\n/** Stays open after a pick by default, so the check can be seen moving. */\nexport function DropdownMenuRadioItem({ value, closeOnSelect = false, children, ...props }: DropdownMenuRadioItemProps) {\n  const root = useRoot(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) throw new Error(\"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\");\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      role=\"menuitemradio\"\n      checked={checked}\n      closeOnSelect={closeOnSelect}\n      onSelect={() => {\n        // A pick that closes the menu sounds through the close sweep instead.\n        if (!closeOnSelect && !checked) root.playSelect();\n        group.onValueChange?.(value);\n      }}\n    >\n      {children}\n      {/* The mark sits at the end of the row, never before the label. */}\n      <span aria-hidden=\"true\" className=\"ml-auto flex size-4 shrink-0 items-center justify-center\">\n        <motion.span\n          initial={false}\n          animate={root.reduce ? { opacity: checked ? 1 : 0 } : { opacity: checked ? 1 : 0, scale: checked ? 1 : 0.6 }}\n          transition={root.reduce ? { duration: 0.1 } : SPRING_PANEL}\n          className=\"flex\"\n        >\n          <Check className=\"size-3.5 text-foreground\" strokeWidth={2.4} />\n        </motion.span>\n      </span>\n    </ItemBase>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Submenus                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  id: string;\n  contentId: string;\n  open: boolean;\n  focus: FocusTarget;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const context = useContext(SubContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return context;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const level = useLevel(\"DropdownMenuSub\");\n  const id = useId();\n  const contentId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const panelRef = useRef<HTMLDivElement | null>(null);\n  // Closes with its parent: an exiting menu takes its submenu out with it.\n  const open = level.openSub === id && level.present;\n  const { setOpenSub } = level;\n  const setOpen = useCallback(\n    (next: boolean, focus: FocusTarget = \"none\", instant?: boolean) =>\n      setOpenSub(next ? id : null, focus, instant),\n    [setOpenSub, id],\n  );\n  const value = useMemo(\n    () => ({ id, contentId, open, focus: level.subFocus, triggerRef, panelRef, setOpen }),\n    [id, contentId, open, level.subFocus, setOpen],\n  );\n  return <SubContext.Provider value={value}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  /** Stops hover, click and keys from opening the submenu. */\n  disabled?: boolean;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the trigger row. */\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({ children, disabled, inset, textValue, className }: DropdownMenuSubTriggerProps) {\n  const level = useLevel(\"DropdownMenuSubTrigger\");\n  const sub = useSub(\"DropdownMenuSubTrigger\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const clearTimer = useCallback(() => {\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = null;\n  }, []);\n  useEffect(() => clearTimer, [clearTimer]);\n\n  return (\n    <ItemBase\n      disabled={disabled}\n      inset={inset}\n      textValue={textValue}\n      className={className}\n      subTrigger={{\n        id: sub.id,\n        open: sub.open,\n        controls: sub.contentId,\n        ref: sub.triggerRef,\n        onPointerMove: (event) => {\n          if (document.activeElement !== event.currentTarget) {\n            event.currentTarget.focus({ preventScroll: true });\n          }\n          if (disabled || sub.open || timer.current) return;\n          // Another row's submenu closes as soon as the pointer settles here.\n          if (level.openSub) level.setOpenSub(null);\n          timer.current = setTimeout(() => {\n            timer.current = null;\n            sub.setOpen(true, \"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          clearTimer();\n          const panel = sub.panelRef.current;\n          if (!sub.open || !panel || event.pointerType === \"touch\") return;\n          // Leave a corridor from the pointer to the submenu's near edge, so a\n          // diagonal path across the rows below does not close it.\n          const rect = panel.getBoundingClientRect();\n          const right = rect.left >= event.clientX;\n          const edge = right ? rect.left : rect.right;\n          const back = right ? -5 : 5;\n          level.grace.current = {\n            polygon: [\n              { x: event.clientX + back, y: event.clientY },\n              { x: edge, y: rect.top },\n              { x: edge, y: rect.bottom },\n            ],\n            until: Date.now() + SUB_GRACE,\n          };\n        },\n        onKeyDown: (event) => {\n          if (disabled) return;\n          if (event.key === \"ArrowRight\" || event.key === \"Enter\" || event.key === \" \") {\n            event.preventDefault();\n            event.stopPropagation();\n            sub.setOpen(true, \"first\");\n            // Already open from a hover: the panel's focus effect will not run\n            // again, so hand focus in here.\n            if (sub.open) enabledItems(sub.panelRef.current)[0]?.focus();\n          }\n        },\n        // Keys open the submenu in onKeyDown, so a click here is a pointer or a tap.\n        onClick: () => {\n          if (!disabled) sub.setOpen(true, \"first\", false);\n        },\n      }}\n    >\n      {children}\n      <ChevronRight aria-hidden=\"true\" className=\"ml-auto size-4\" />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Classes merged onto the submenu panel. */\n  className?: string;\n  /** Gap between the menu's edge and the submenu in px. Default 6. */\n  sideOffset?: number;\n}\n\nexport function DropdownMenuSubContent({ children, className, sideOffset = 6 }: DropdownMenuSubContentProps) {\n  const root = useRoot(\"DropdownMenuSubContent\");\n  const level = useLevel(\"DropdownMenuSubContent\");\n  const sub = useSub(\"DropdownMenuSubContent\");\n\n  return (\n    <AnimatePresence custom={level.subInstant}>\n      {sub.open && (\n        <PresenceGate>\n          {({ isPresent, gate }) => (\n            <MenuPanel\n              id={sub.contentId}\n              anchorRef={sub.triggerRef}\n              panelRef={sub.panelRef}\n              side=\"right\"\n              align=\"start\"\n              sideOffset={sideOffset}\n              focus={sub.focus}\n              instant={level.subInstant}\n              present={isPresent}\n              gate={gate}\n              labelledBy={sub.id}\n              onClose={() => root.setOpen(false, \"first\", true)}\n              onPointerEnter={() => {\n                level.grace.current = null;\n              }}\n              onKeyDown={(event) => {\n                if (event.key !== \"ArrowLeft\") return false;\n                event.preventDefault();\n                sub.setOpen(false, \"none\", true);\n                sub.triggerRef.current?.focus({ preventScroll: true });\n                return true;\n              }}\n              className={className}\n            >\n              {children}\n            </MenuPanel>\n          )}\n        </PresenceGate>\n      )}\n    </AnimatePresence>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Decoration                                                                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Classes merged onto the label element. */\n  className?: string;\n}\n\nexport function DropdownMenuLabel({ children, inset, className }: DropdownMenuLabelProps) {\n  return (\n    <div className={cn(\"px-3 py-1.5 text-xs font-medium text-muted-foreground\", inset && \"pl-9\", className)}>\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuSeparatorProps {\n  /** Classes merged onto the separator line. */\n  className?: string;\n}\n\nexport function DropdownMenuSeparator({ className }: DropdownMenuSeparatorProps) {\n  return <hr className={cn(\"-mx-2 my-1 h-px border-0 bg-border\", className)} />;\n}\n\nexport interface DropdownMenuShortcutProps {\n  children: ReactNode;\n  /** Classes merged onto the shortcut text. */\n  className?: string;\n}\n\nexport function DropdownMenuShortcut({ children, className }: DropdownMenuShortcutProps) {\n  return (\n    <span aria-hidden=\"true\" className={cn(\"ml-auto pl-4 text-xs tracking-wide text-muted-foreground\", className)}>\n      {children}\n    </span>\n  );\n}\n"},{"path":"components/motion/menu/menu-item-highlight.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/** The row shape every menu item shares. Menus add their own gap and states. */\nexport const MENU_ITEM_CLASS =\n  \"relative isolate flex w-full select-none items-center rounded-lg px-3 py-1.5 text-left text-sm outline-none\";\n\nexport interface MenuItemHighlightProps {\n  /** Shared by every row of one panel, so the highlight glides between them. */\n  layoutId: string;\n  tone?: \"default\" | \"destructive\";\n  reduce: boolean;\n  /**\n   * Jump instead of gliding: the highlight was moved by the keyboard, where a\n   * spring only trails behind fast arrowing.\n   */\n  instant?: boolean;\n}\n\n/** The highlight behind the active row. Render it only inside the active row. */\nexport function MenuItemHighlight({\n  layoutId,\n  tone = \"default\",\n  reduce,\n  instant = false,\n}: MenuItemHighlightProps) {\n  return (\n    <motion.span\n      aria-hidden=\"true\"\n      layoutId={layoutId}\n      className={cn(\n        \"absolute inset-0 -z-10 rounded-lg\",\n        tone === \"destructive\" ? \"bg-destructive/10\" : \"bg-foreground/[0.07]\",\n      )}\n      transition={reduce || instant ? { duration: 0 } : SPRING_LAYOUT}\n    />\n  );\n}\n"},{"path":"components/motion/tooltip.tsx","type":"util","content":"\"use client\";\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type PointerEvent as ReactPointerEvent,\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { TooltipSurface } from \"@/components/motion/tooltip-surface\";\nimport { type DismissReason, useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { useHoverGesture } from \"@/lib/hooks/use-hover-gesture\";\nimport { useTapGesture } from \"@/lib/hooks/use-tap-gesture\";\nimport { assignRef } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\nimport { focusFromKeyboard, graceArea, inBox, inPolygon, watchModality } from \"./tooltip/grace\";\nimport { TooltipArrow, TooltipPositioner } from \"./tooltip/positioner\";\nimport {\n  type TooltipAlign,\n  type TooltipAnchor,\n  type TooltipPoint,\n  type TooltipSide,\n  useTooltipPointer,\n} from \"./tooltip/use-position\";\n\nexport type { TooltipAlign, TooltipSide };\n\n/* -------------------------------------------------------------------------- */\n/* Provider                                                                   */\n/* -------------------------------------------------------------------------- */\n\ninterface TooltipTiming {\n  /** Delay before a hover opens a tooltip (ms). */\n  delay: number;\n  /** Delay before a tooltip closes once the pointer has left it (ms). */\n  closeDelay: number;\n  /** After one tooltip closes, others open instantly for this long (ms). */\n  skipDelay: number;\n}\n\nconst TimingContext = createContext<TooltipTiming>({ delay: 120, closeDelay: 0, skipDelay: 300 });\n\nexport interface TooltipProviderProps extends Partial<TooltipTiming> {\n  children: ReactNode;\n}\n\n/** Shared timing for every tooltip inside it. Optional: tooltips work without one. */\nexport function TooltipProvider({ children, ...timing }: TooltipProviderProps) {\n  const parent = useContext(TimingContext);\n  const { delay = parent.delay, closeDelay = parent.closeDelay, skipDelay = parent.skipDelay } =\n    timing;\n  const value = useMemo(() => ({ delay, closeDelay, skipDelay }), [delay, closeDelay, skipDelay]);\n  return <TimingContext.Provider value={value}>{children}</TimingContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Root                                                                       */\n/* -------------------------------------------------------------------------- */\n\n// Moving along a toolbar should feel instant after the first label, and only\n// one label may show at a time: a keyboard-focused control and a hovered one\n// would otherwise both claim the screen.\nlet lastClosedAt = 0;\nlet current: { close: () => void } | null = null;\n\nfunction isEmpty(content: ReactNode) {\n  return content == null || content === false || content === \"\";\n}\n\ninterface TooltipContextValue {\n  open: boolean;\n  /** Show and hide without animating (keyboard focus, a warm toolbar, a replaced label). */\n  instant: boolean;\n  contentId: string;\n  labelId: string;\n  asLabel: boolean;\n  empty: boolean;\n  followCursor: boolean;\n  anchor: TooltipAnchor | null;\n  /** True when a TooltipTrigger owns the anchor; false for an external `anchorRef`. */\n  triggered: boolean;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  pointer: ReturnType<typeof useTooltipPointer>;\n  setTrigger: (element: TooltipAnchor | null) => void;\n  setEmpty: (empty: boolean) => void;\n  close: () => void;\n  onContentEnter: () => void;\n  onContentLeave: (event: ReactPointerEvent) => void;\n}\n\nconst TooltipContext = createContext<TooltipContextValue | null>(null);\n\nfunction useTooltipContext(part: string) {\n  const context = useContext(TooltipContext);\n  if (!context) throw new Error(`${part} must be used inside <Tooltip>`);\n  return context;\n}\n\nexport interface TooltipRootProps {\n  children?: ReactNode;\n  /** Whether the tooltip is shown, for controlled use. */\n  open?: boolean;\n  /** Whether the tooltip starts shown when uncontrolled. Default: false */\n  defaultOpen?: boolean;\n  /** Called with the new state when the tooltip shows or hides. */\n  onOpenChange?: (open: boolean) => void;\n  /** Delay before showing on hover (ms). Keyboard focus shows immediately. */\n  delay?: number;\n  /** Delay before hiding once the pointer has left (ms). */\n  closeDelay?: number;\n  /** Never show, e.g. while the label it carries is already visible. */\n  disabled?: boolean;\n  /**\n   * Use the tooltip as the trigger's accessible name rather than its\n   * description. For icon-only controls whose only label is the tooltip.\n   */\n  asLabel?: boolean;\n  /** Follow real pointer coordinates; keyboard focus still uses the anchor. */\n  followCursor?: boolean;\n  /** Existing anchor for controlled integrations such as chart cells. */\n  anchorRef?: RefObject<TooltipAnchor | null>;\n  /** Id of the tooltip surface, for anchors that reference it themselves. */\n  id?: string;\n}\n\nfunction TooltipRoot({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  delay: delayProp,\n  closeDelay: closeDelayProp,\n  disabled = false,\n  asLabel = false,\n  followCursor = false,\n  anchorRef,\n  id,\n  initialEmpty = false,\n}: TooltipRootProps & { initialEmpty?: boolean }) {\n  const timing = useContext(TimingContext);\n  const delay = delayProp ?? timing.delay;\n  const closeDelay = closeDelayProp ?? timing.closeDelay;\n  const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);\n  const open = controlledOpen ?? uncontrolledOpen;\n  // Keyboard focus and a warm toolbar show the label at once; animating\n  // something seen this often only makes it feel slow.\n  const [instant, setInstant] = useState(false);\n  const [empty, setEmpty] = useState(initialEmpty);\n  const [trigger, setTrigger] = useState<TooltipAnchor | null>(null);\n  const [external, setExternal] = useState<TooltipAnchor | null>(null);\n  const anchor = anchorRef ? external : trigger;\n  const generatedId = useId();\n  const contentId = id ?? `${generatedId}-content`;\n  const labelId = `${generatedId}-label`;\n  const floatingRef = useRef<HTMLSpanElement | null>(null);\n  const anchorObject = useRef<TooltipAnchor | null>(null);\n  const pointer = useTooltipPointer(anchor, followCursor);\n\n  // An external ref can attach after this component renders; read it once it has.\n  useLayoutEffect(() => {\n    if (!anchorRef) return;\n    const element = anchorRef.current ?? null;\n    if (element !== external) setExternal(element);\n  });\n\n  // Everything the event listeners read, current without re-binding them.\n  const latest = useRef({ open, delay, closeDelay, disabled, empty, onOpenChange, controlled: false });\n  useLayoutEffect(() => {\n    anchorObject.current = anchor;\n    latest.current = {\n      open,\n      delay,\n      closeDelay,\n      disabled,\n      empty,\n      onOpenChange,\n      controlled: controlledOpen !== undefined,\n    };\n  });\n\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const grace = useRef<(() => void) | null>(null);\n  const self = useRef<{ close: () => void }>({ close: () => {} });\n\n  const clearTimers = useCallback(() => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    if (closeTimer.current) clearTimeout(closeTimer.current);\n    openTimer.current = null;\n    closeTimer.current = null;\n  }, []);\n\n  const stopGrace = useCallback(() => {\n    grace.current?.();\n    grace.current = null;\n  }, []);\n\n  // Only a real change reaches the consumer: a pointer leaving a closed\n  // tooltip is not news.\n  const commit = useCallback((next: boolean) => {\n    if (latest.current.open === next) return;\n    if (!latest.current.controlled) setUncontrolledOpen(next);\n    latest.current.onOpenChange?.(next);\n  }, []);\n\n  const openNow = useCallback(\n    (now = false) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.disabled || latest.current.empty) return;\n      // The label being replaced leaves at once, so two never show together.\n      if (current && current !== self.current) current.close();\n      current = self.current;\n      setInstant(now);\n      commit(true);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n\n  const finish = useCallback(\n    (now: boolean) => {\n      clearTimers();\n      stopGrace();\n      if (latest.current.open) lastClosedAt = Date.now();\n      if (current === self.current) current = null;\n      if (latest.current.open) setInstant(now);\n      commit(false);\n    },\n    [clearTimers, stopGrace, commit],\n  );\n  // Also a listener (window blur, outside press), so it takes no arguments.\n  const close = useCallback(() => finish(false), [finish]);\n  useLayoutEffect(() => {\n    self.current.close = () => finish(true);\n  }, [finish]);\n\n  const requestOpen = useCallback(() => {\n    clearTimers();\n    if (latest.current.open || latest.current.disabled || latest.current.empty) return;\n    // Warm: another label is still showing (the pointer is crossing to this\n    // one), or one closed a moment ago. Either way, skip the delay and the fade.\n    const warm =\n      (current !== null && current !== self.current) ||\n      Date.now() - lastClosedAt < timing.skipDelay;\n    if (warm) openNow(true);\n    else if (latest.current.delay <= 0) openNow();\n    else openTimer.current = setTimeout(() => openNow(), latest.current.delay);\n  }, [clearTimers, openNow, timing.skipDelay]);\n\n  const requestClose = useCallback(() => {\n    clearTimers();\n    if (latest.current.closeDelay > 0) {\n      closeTimer.current = setTimeout(close, latest.current.closeDelay);\n    } else close();\n  }, [clearTimers, close]);\n\n  // Hold the label open while the pointer crosses from one box toward the other.\n  const startGrace = useCallback(\n    (exit: TooltipPoint, from: Element, to: Element | null) => {\n      stopGrace();\n      if (!to) return requestClose();\n      const target = to.getBoundingClientRect();\n      const origin = from.getBoundingClientRect();\n      const corridor = graceArea(exit, target);\n      const onMove = (event: PointerEvent) => {\n        const point = { x: event.clientX, y: event.clientY };\n        if (inBox(point, target) || inBox(point, origin)) return;\n        if (!inPolygon(point, corridor)) requestClose();\n      };\n      document.addEventListener(\"pointermove\", onMove);\n      grace.current = () => document.removeEventListener(\"pointermove\", onMove);\n    },\n    [stopGrace, requestClose],\n  );\n\n  const hover = useHoverGesture();\n  const tap = useTapGesture<boolean>();\n\n  // Listeners go on the trigger itself rather than on cloned props, so a\n  // component that owns its own handlers keeps them, and no wrapper element\n  // sits between the control and its layout.\n  useEffect(() => {\n    if (anchorRef || !trigger) return;\n    watchModality();\n    // A mouse press dismisses the label and keeps it away until the pointer\n    // leaves; hovering a control you just clicked should not bring it back.\n    let suppressed = false;\n    // Focus that came from the keyboard holds the label open on its own.\n    let keyboardFocus = false;\n\n    const onEnter = (event: PointerEvent) => {\n      if (!hover.enter(event)) return;\n      stopGrace();\n      if (closeTimer.current) clearTimeout(closeTimer.current);\n      if (!suppressed) requestOpen();\n    };\n    const onLeave = (event: PointerEvent) => {\n      if (!hover.leave(event)) return;\n      suppressed = false;\n      if (keyboardFocus) return;\n      if (openTimer.current) {\n        clearTimers();\n        return;\n      }\n      if (latest.current.open && !followCursor) {\n        startGrace({ x: event.clientX, y: event.clientY }, trigger, floatingRef.current);\n      } else requestClose();\n    };\n    const onDown = (event: PointerEvent) => {\n      tap.start(event, latest.current.open);\n      if (event.pointerType === \"mouse\") {\n        suppressed = true;\n        close();\n      }\n    };\n    // A finger never hovers, and Safari does not focus a button on tap either,\n    // so the label is only reachable if the tap itself toggles it. The click\n    // carries no pointerType; the pointerdown before it says whether it was a\n    // tap, and keyboard activation has none at all.\n    const onClick = () => {\n      const gesture = tap.take();\n      if (!gesture || gesture.pointerType === \"mouse\") return;\n      if (gesture.state) close();\n      else openNow();\n    };\n    const onKey = () => tap.drop();\n    const onFocusIn = () => {\n      if (!focusFromKeyboard()) return;\n      keyboardFocus = true;\n      openNow(true);\n    };\n    const onFocusOut = (event: FocusEvent) => {\n      if (trigger.contains(event.relatedTarget as Node | null)) return;\n      const fromKeyboard = keyboardFocus;\n      keyboardFocus = false;\n      finish(fromKeyboard);\n    };\n\n    // Both element kinds dispatch the same events; one type keeps the listeners typed.\n    const el = trigger as HTMLElement;\n    el.addEventListener(\"pointerenter\", onEnter);\n    el.addEventListener(\"pointerleave\", onLeave);\n    el.addEventListener(\"pointerdown\", onDown);\n    el.addEventListener(\"pointercancel\", tap.drop);\n    el.addEventListener(\"click\", onClick);\n    el.addEventListener(\"keydown\", onKey);\n    el.addEventListener(\"focusin\", onFocusIn);\n    el.addEventListener(\"focusout\", onFocusOut);\n    return () => {\n      el.removeEventListener(\"pointerenter\", onEnter);\n      el.removeEventListener(\"pointerleave\", onLeave);\n      el.removeEventListener(\"pointerdown\", onDown);\n      el.removeEventListener(\"pointercancel\", tap.drop);\n      el.removeEventListener(\"click\", onClick);\n      el.removeEventListener(\"keydown\", onKey);\n      el.removeEventListener(\"focusin\", onFocusIn);\n      el.removeEventListener(\"focusout\", onFocusOut);\n    };\n  }, [\n    anchorRef,\n    trigger,\n    followCursor,\n    hover,\n    tap,\n    requestOpen,\n    requestClose,\n    openNow,\n    close,\n    finish,\n    clearTimers,\n    stopGrace,\n    startGrace,\n  ]);\n\n  // While open, a trigger that turns disabled loses focus without a blur event,\n  // and a window that loses focus never reports the pointer leaving.\n  useEffect(() => {\n    if (!open || anchorRef || !trigger) return;\n    const observer = new MutationObserver(() => {\n      if (trigger.matches(\":disabled, [aria-disabled='true']\")) close();\n    });\n    observer.observe(trigger, { attributes: true, attributeFilter: [\"disabled\", \"aria-disabled\"] });\n    window.addEventListener(\"blur\", close);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"blur\", close);\n    };\n  }, [open, anchorRef, trigger, close]);\n\n  // A chart drives its own open state and swaps content as it goes; only a\n  // trigger-owned label closes itself for having nothing to say.\n  useEffect(() => {\n    if (disabled || (empty && !anchorRef)) close();\n  }, [disabled, empty, anchorRef, close]);\n\n  useEffect(\n    () => () => {\n      clearTimers();\n      stopGrace();\n      if (current === self.current) current = null;\n    },\n    [clearTimers, stopGrace],\n  );\n\n  const insideTooltip = useCallback(\n    (target: Element) => Boolean(floatingRef.current?.contains(target)),\n    [],\n  );\n  // ...and closed by the next tap that lands somewhere else, or Escape. The\n  // label covers nothing interactive, so that tap passes through to what it hit.\n  // Escape is a key press, so the label goes at once.\n  const dismiss = useCallback((reason: DismissReason) => finish(reason === \"escape\"), [finish]);\n  useDismiss(open, dismiss, anchorObject, { ignore: insideTooltip });\n\n  const onContentEnter = useCallback(() => {\n    stopGrace();\n    clearTimers();\n  }, [stopGrace, clearTimers]);\n\n  const onContentLeave = useCallback(\n    (event: ReactPointerEvent) => {\n      const floating = floatingRef.current;\n      if (!floating) return;\n      if (anchorRef) {\n        // Bridge the small gap back onto a chart; it reopens on its own terms.\n        clearTimers();\n        closeTimer.current = setTimeout(close, 100);\n        return;\n      }\n      startGrace({ x: event.clientX, y: event.clientY }, floating, anchorObject.current);\n    },\n    [anchorRef, clearTimers, close, startGrace],\n  );\n\n  const value = useMemo<TooltipContextValue>(\n    () => ({\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      triggered: !anchorRef,\n      floatingRef,\n      pointer,\n      setTrigger,\n      setEmpty,\n      close,\n      onContentEnter,\n      onContentLeave,\n    }),\n    [\n      open,\n      instant,\n      contentId,\n      labelId,\n      asLabel,\n      empty,\n      followCursor,\n      anchor,\n      anchorRef,\n      pointer,\n      close,\n      onContentEnter,\n      onContentLeave,\n    ],\n  );\n\n  return <TooltipContext.Provider value={value}>{children}</TooltipContext.Provider>;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Trigger                                                                    */\n/* -------------------------------------------------------------------------- */\n\nfunction mergeIds(...ids: unknown[]) {\n  return ids.filter((value) => typeof value === \"string\" && value).join(\" \") || undefined;\n}\n\nexport interface TooltipTriggerProps extends ComponentProps<\"button\"> {\n  /** Use the single child element as the trigger instead of rendering a button. */\n  asChild?: boolean;\n}\n\nexport function TooltipTrigger({ asChild = false, children, ref, ...props }: TooltipTriggerProps) {\n  const { open, contentId, labelId, asLabel, empty, setTrigger } =\n    useTooltipContext(\"TooltipTrigger\");\n  const child = asChild && isValidElement(children) ? children : null;\n  const childProps = (child?.props ?? props) as Record<string, unknown>;\n  const childRef = child ? (childProps.ref as Ref<TooltipAnchor> | undefined) : undefined;\n  const attached = useRef<TooltipAnchor | null>(null);\n\n  const setRef = useCallback(\n    (element: TooltipAnchor | null) => {\n      attached.current = element;\n      setTrigger(element);\n      assignRef(childRef ?? (ref as Ref<TooltipAnchor> | undefined), element);\n    },\n    [setTrigger, childRef, ref],\n  );\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== \"production\" && child && !attached.current) {\n      console.warn(\n        \"TooltipTrigger: the child did not attach a ref, so the tooltip has nothing to listen to. Render a DOM element or a component that passes `ref` through.\",\n      );\n    }\n  }, [child]);\n\n  const aria = asLabel\n    ? {\n        \"aria-labelledby\": empty\n          ? (childProps[\"aria-labelledby\"] as string | undefined)\n          : labelId,\n      }\n    : {\n        \"aria-describedby\": mergeIds(\n          childProps[\"aria-describedby\"],\n          open && !empty ? contentId : undefined,\n        ),\n      };\n\n  if (asChild) {\n    if (!child) return children;\n    return cloneElement(child as ReactElement<Record<string, unknown>>, { ref: setRef, ...aria });\n  }\n\n  return (\n    <button\n      type=\"button\"\n      data-state={open ? \"open\" : \"closed\"}\n      {...props}\n      ref={setRef as Ref<HTMLButtonElement>}\n      {...aria}\n    >\n      {children}\n    </button>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Content                                                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipContentProps {\n  children?: ReactNode;\n  /** Preferred side of the anchor. Flips when there is no room. Default: \"top\" */\n  side?: TooltipSide;\n  /** Alignment along the chosen side. Default: \"center\" */\n  align?: TooltipAlign;\n  /** Gap between anchor and tooltip (px). */\n  sideOffset?: number;\n  /** Draw an arrow pointing at the anchor. */\n  arrow?: boolean;\n  /** Point within the anchor, as fractions of its rendered width and height. */\n  anchorPoint?: TooltipPoint;\n  /** Classes merged onto the tooltip surface. */\n  className?: string;\n}\n\nexport function TooltipContent({\n  children,\n  side = \"top\",\n  align = \"center\",\n  sideOffset,\n  arrow = false,\n  anchorPoint,\n  className,\n}: TooltipContentProps) {\n  const {\n    open,\n    instant,\n    contentId,\n    labelId,\n    asLabel,\n    followCursor,\n    anchor,\n    floatingRef,\n    pointer,\n    setEmpty,\n    close,\n    onContentEnter,\n    onContentLeave,\n  } = useTooltipContext(\"TooltipContent\");\n  const empty = isEmpty(children);\n  const arrowRef = useRef<SVGSVGElement | null>(null);\n\n  useLayoutEffect(() => {\n    setEmpty(empty);\n  }, [empty, setEmpty]);\n\n  if (typeof document === \"undefined\") return null;\n\n  return createPortal(\n    <>\n      {/* The name has to exist while the label is closed, so it lives apart from the surface. */}\n      {asLabel && !empty ? (\n        <span id={labelId} hidden>\n          {children}\n        </span>\n      ) : null}\n      {/* `custom` reaches a surface that is already exiting, so a label closed\n          from the keyboard or replaced by a neighbour leaves without animating. */}\n      <AnimatePresence custom={instant}>\n        {open && !empty ? (\n          <TooltipPositioner\n            key=\"tooltip\"\n            anchor={anchor}\n            floatingRef={floatingRef}\n            arrowRef={arrow ? arrowRef : undefined}\n            anchorPoint={anchorPoint}\n            followCursor={followCursor}\n            side={side}\n            align={align}\n            sideOffset={sideOffset}\n            onDismiss={close}\n            pointer={pointer}\n          >\n            {(positioned, isPresent, placedSide) => (\n              <TooltipSurface\n                id={asLabel ? undefined : contentId}\n                aria-hidden={asLabel || undefined}\n                ready={positioned}\n                instant={instant}\n                onPointerEnter={onContentEnter}\n                onPointerLeave={onContentLeave}\n                style={{ pointerEvents: isPresent && !followCursor ? \"auto\" : \"none\" }}\n                className={cn(\n                  \"max-w-[min(20rem,calc(100vw-16px))] whitespace-normal break-words\",\n                  arrow && \"relative\",\n                  className,\n                )}\n              >\n                {children}\n                {arrow ? <TooltipArrow ref={arrowRef} side={placedSide} /> : null}\n              </TooltipSurface>\n            )}\n          </TooltipPositioner>\n        ) : null}\n      </AnimatePresence>\n    </>,\n    document.body,\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/* Tooltip (root, or one-line shorthand when given `content`)                 */\n/* -------------------------------------------------------------------------- */\n\nexport interface TooltipProps\n  extends TooltipRootProps,\n    Omit<TooltipContentProps, \"children\" | \"className\"> {\n  /**\n   * Shorthand: the tooltip's content. With it, `children` is the trigger\n   * element; without it, compose `TooltipTrigger` and `TooltipContent`.\n   */\n  content?: ReactNode;\n  /** Shorthand only: classes for the tooltip surface. */\n  className?: string;\n}\n\nexport function Tooltip(props: TooltipProps) {\n  if (!(\"content\" in props)) return <TooltipRoot {...props} />;\n  const {\n    content,\n    children,\n    side,\n    align,\n    sideOffset,\n    arrow,\n    anchorPoint,\n    className,\n    ...root\n  } = props;\n  if (!root.anchorRef && !isValidElement(children)) return children ?? null;\n  return (\n    <TooltipRoot {...root} initialEmpty={isEmpty(content)}>\n      {isValidElement(children) ? <TooltipTrigger asChild>{children}</TooltipTrigger> : null}\n      <TooltipContent\n        side={side}\n        align={align}\n        sideOffset={sideOffset}\n        arrow={arrow}\n        anchorPoint={anchorPoint}\n        className={className}\n      >\n        {content}\n      </TooltipContent>\n    </TooltipRoot>\n  );\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/button/base.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type MouseEvent,\n  type PointerEvent,\n  type ReactNode,\n  useCallback,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { useSound } from \"@/lib/sound\";\nimport { pressSound } from \"@/lib/sounds/press\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ButtonVariant = \"primary\" | \"secondary\" | \"ghost\" | \"outline\";\nexport type ButtonSize = \"sm\" | \"md\" | \"lg\" | \"icon\";\n\nexport interface ButtonProps extends Omit<\n  HTMLMotionProps<\"button\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only button. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97: subtle, so the press reads as feedback, not a squash. */\n  pressScale?: number;\n  /** Spawn a Material-style ripple from the press point. Off by default. */\n  ripple?: boolean;\n  /** Play a soft press sound. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n  children?: ReactNode;\n}\n\nexport interface ButtonLinkProps extends Omit<\n  HTMLMotionProps<\"a\">,\n  \"children\"\n> {\n  /** Visual style: filled, card, ghost or outline. Default: \"primary\" */\n  variant?: ButtonVariant;\n  /** Height and padding; \"icon\" is a square icon-only link. Default: \"md\" */\n  size?: ButtonSize;\n  /** Scale while pressed. Default 0.97. */\n  pressScale?: number;\n  children?: ReactNode;\n}\n\ntype Ripple = { id: number; x: number; y: number; size: number };\n\nconst VARIANT_CLASS: Record<ButtonVariant, string> = {\n  primary: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n  secondary: \"border border-border bg-card text-foreground hover:border-border\",\n  ghost: \"text-muted-foreground hover:text-foreground hover:bg-muted/60\",\n  outline:\n    \"border border-border bg-transparent text-foreground hover:bg-muted/60\",\n};\n\nconst SIZE_CLASS: Record<ButtonSize, string> = {\n  sm: \"h-8 px-3 text-xs gap-1.5 rounded-full\",\n  md: \"h-10 px-5 text-sm gap-2 rounded-full\",\n  lg: \"h-12 px-6 text-base gap-2 rounded-full\",\n  icon: \"h-8 w-8 rounded-full\",\n};\n\nexport const Button = forwardRef<HTMLButtonElement, ButtonProps>(\n  function Button(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      ripple = false,\n      sound = false,\n      className,\n      children,\n      onPointerDown,\n      onClick,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n    const [ripples, setRipples] = useState<Ripple[]>([]);\n    const nextId = useRef(0);\n    const play = useSound(pressSound, { enabled: sound });\n\n    const handleClick = useCallback(\n      (event: MouseEvent<HTMLButtonElement>) => {\n        // `detail` is 0 for a click the keyboard made; a pointer press already sounded.\n        if (event.detail === 0) play();\n        onClick?.(event);\n      },\n      [play, onClick],\n    );\n\n    const handlePointerDown = useCallback(\n      (event: PointerEvent<HTMLButtonElement>) => {\n        play();\n        if (ripple && !reduce) {\n          const rect = event.currentTarget.getBoundingClientRect();\n          const size = Math.max(rect.width, rect.height) * 2;\n          const id = nextId.current++;\n          setRipples((prev) => [\n            ...prev,\n            {\n              id,\n              x: event.clientX - rect.left,\n              y: event.clientY - rect.top,\n              size,\n            },\n          ]);\n        }\n        onPointerDown?.(event);\n      },\n      [ripple, reduce, onPointerDown, play],\n    );\n\n    return (\n      // Hover changes colour only: a hover scale blurs the label, and buttons\n      // are hovered far too often for movement to earn its place.\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        onPointerDown={handlePointerDown}\n        onClick={handleClick}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          ripple && \"relative overflow-hidden\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {ripple && !reduce ? (\n          <span className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-[inherit]\">\n            <AnimatePresence>\n              {ripples.map((r) => (\n                <motion.span\n                  key={r.id}\n                  className=\"absolute rounded-full bg-current\"\n                  style={{\n                    left: r.x,\n                    top: r.y,\n                    width: r.size,\n                    height: r.size,\n                    x: \"-50%\",\n                    y: \"-50%\",\n                  }}\n                  initial={{ scale: 0.05, opacity: 0.3 }}\n                  animate={{ scale: 1, opacity: 0 }}\n                  exit={{ opacity: 0 }}\n                  transition={{ duration: 0.8, ease: EASE_OUT }}\n                  onAnimationComplete={() =>\n                    setRipples((prev) => prev.filter((x) => x.id !== r.id))\n                  }\n                />\n              ))}\n            </AnimatePresence>\n          </span>\n        ) : null}\n        {children}\n      </motion.button>\n    );\n  },\n);\n\nexport const ButtonLink = forwardRef<HTMLAnchorElement, ButtonLinkProps>(\n  function ButtonLink(\n    {\n      variant = \"primary\",\n      size = \"md\",\n      pressScale = 0.97,\n      className,\n      children,\n      ...rest\n    },\n    ref,\n  ) {\n    const reduce = useReducedMotion();\n\n    return (\n      <motion.a\n        ref={ref}\n        whileTap={reduce ? undefined : { scale: pressScale }}\n        transition={SPRING_PRESS}\n        className={cn(\n          \"inline-flex items-center justify-center font-medium select-none\",\n          \"transition-colors\",\n          VARIANT_CLASS[variant],\n          SIZE_CLASS[size],\n          className,\n        )}\n        {...rest}\n      >\n        {children}\n      </motion.a>\n    );\n  },\n);\n"},{"path":"components/motion/button/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { forwardRef } from \"react\";\nimport { Magnetic } from \"../magnetic\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MagneticButtonProps extends ButtonProps {\n  /** Magnetic pull strength. Default 0.25. */\n  strength?: number;\n  /** Class applied to the magnetic wrapper. */\n  magneticClassName?: string;\n}\n\nexport const MagneticButton = forwardRef<HTMLButtonElement, MagneticButtonProps>(function MagneticButton(\n  { strength = 0.25, magneticClassName, children, ...rest },\n  ref,\n) {\n  return (\n    <Magnetic strength={strength} className={magneticClassName}>\n      <Button ref={ref} {...rest}>\n        {children}\n      </Button>\n    </Magnetic>\n  );\n});\n"},{"path":"components/motion/button/metallic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { forwardRef, useState } from \"react\";\nimport { EASE_IN_OUT, EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport interface MetallicButtonProps extends Omit<\n  ButtonProps,\n  \"ripple\" | \"variant\"\n> {\n  /** Stops the traveling reflection while preserving the chrome rim. */\n  paused?: boolean;\n}\n\n// The rim and highlight drift separately so the material stays quiet and reflective.\nconst SILVER_DRIFT = {\n  duration: 8,\n  ease: EASE_IN_OUT,\n  repeat: Infinity,\n};\n\n// One quick sweep on hover. Leaving resets it instantly: both ends sit outside\n// the button, so the jump is invisible and no reverse sweep plays.\nconst CHROME_SHIMMER = {\n  duration: 0.9,\n  ease: EASE_OUT,\n};\nconst CHROME_RESET = { duration: 0 };\n\nexport const MetallicButton = forwardRef<\n  HTMLButtonElement,\n  MetallicButtonProps\n>(function MetallicButton(\n  {\n    size = \"md\",\n    paused = false,\n    className,\n    children,\n    onHoverStart,\n    onHoverEnd,\n    ...rest\n  },\n  ref,\n) {\n  const reduce = useReducedMotion();\n  const still = paused || Boolean(reduce);\n  const [hovered, setHovered] = useState(false);\n\n  return (\n    <Button\n      ref={ref}\n      variant=\"ghost\"\n      size={size}\n      onHoverStart={(event, info) => {\n        setHovered(true);\n        onHoverStart?.(event, info);\n      }}\n      onHoverEnd={(event, info) => {\n        setHovered(false);\n        onHoverEnd?.(event, info);\n      }}\n      className={cn(\n        \"group relative isolate overflow-hidden border-0 bg-transparent text-foreground\",\n        \"hover:bg-transparent hover:text-foreground\",\n        \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2\",\n        \"shadow-[0_8px_22px_rgba(0,0,0,0.16)]\",\n        size === \"icon\" && \"rounded-full\",\n        className,\n      )}\n      {...rest}\n    >\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-18%] z-0 w-[136%] rounded-[inherit] bg-[linear-gradient(105deg,#111_0%,#737373_14%,#fafafa_26%,#525252_38%,#0a0a0a_50%,#a3a3a3_64%,#fff_75%,#404040_87%,#111_100%)]\"\n        animate={still ? undefined : { x: [\"0%\", \"13%\", \"0%\"] }}\n        transition={still ? undefined : SILVER_DRIFT}\n      />\n\n      <motion.span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-y-0 left-[-58%] z-[1] w-[52%] -skew-x-12 bg-[linear-gradient(90deg,transparent,rgba(255,255,255,0.5)_48%,transparent)] opacity-50 blur-[3px] mix-blend-screen\"\n        animate={still ? undefined : { x: hovered ? \"310%\" : \"0%\" }}\n        transition={still ? undefined : hovered ? CHROME_SHIMMER : CHROME_RESET}\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[2] rounded-[inherit] bg-background transition-colors group-hover:bg-muted/40\"\n      />\n\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute inset-[2px] z-[3] rounded-[inherit] shadow-[inset_0_1px_0_rgba(255,255,255,0.28),inset_0_-1px_0_rgba(0,0,0,0.16)]\"\n      />\n\n      <span className=\"relative z-10 inline-flex items-center justify-center gap-2\">\n        {children}\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/button/stateful.tsx","type":"util","content":"\"use client\";\n\nimport { Check, Loader2, X } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  forwardRef,\n  type ReactNode,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { EASE_OUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { Button, type ButtonProps } from \"./base\";\n\nexport type ButtonState = \"idle\" | \"loading\" | \"success\" | \"error\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const statefulButtonMessages = {\n  loading: \"Loading\",\n  success: \"Done\",\n  error: \"Try again\",\n};\n\nexport type StatefulButtonMessages = typeof statefulButtonMessages;\n\nexport interface StatefulButtonProps extends Omit<ButtonProps, \"children\"> {\n  /** Which state to show. Loading also disables the button. Default: \"idle\" */\n  state?: ButtonState;\n  children: ReactNode;\n  /** Text shown while loading. Default: \"Loading\" */\n  loadingText?: ReactNode;\n  /** Text shown on success. Default: \"Done\" */\n  successText?: ReactNode;\n  /** Text shown on error. Default: \"Try again\" */\n  errorText?: ReactNode;\n  /** Trailing icon shown only while idle. */\n  icon?: ReactNode;\n  /** Override any built-in string. */\n  labels?: Partial<StatefulButtonMessages>;\n}\n\nconst CASCADE_STAGGER = 0.025;\nconst ROLL_BLUR = \"blur(6px)\";\n\nconst CASCADE_LETTER_VARIANTS: Variants = {\n  initial: { opacity: 0, y: \"105%\", filter: ROLL_BLUR },\n  animate: (delay: number = 0) => ({\n    opacity: 1,\n    y: \"0%\",\n    filter: \"blur(0px)\",\n    transition: { ...SPRING_SWAP, delay },\n  }),\n  exit: (delay: number = 0) => ({\n    opacity: 0,\n    y: \"-105%\",\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT, delay: delay * 0.5 },\n  }),\n};\n\nconst ICON_VARIANTS: Variants = {\n  // Width collapses too, so the icon adds/removes its own space smoothly\n  // instead of popping the row width in a single frame.\n  initial: { opacity: 0, width: 0, scale: 0.7, filter: ROLL_BLUR },\n  animate: {\n    opacity: 1,\n    width: \"1.5rem\",\n    scale: 1,\n    filter: \"blur(0px)\",\n    transition: SPRING_SWAP,\n  },\n  exit: {\n    opacity: 0,\n    width: 0,\n    scale: 0.7,\n    filter: ROLL_BLUR,\n    transition: { duration: 0.16, ease: EASE_OUT },\n  },\n};\n\nfunction IconSlot({ keyId, children }: { keyId: string; children: ReactNode }) {\n  const reduce = useReducedMotion();\n  return (\n    <motion.span\n      key={keyId}\n      variants={ICON_VARIANTS}\n      initial={reduce ? { opacity: 0 } : \"initial\"}\n      animate={reduce ? { opacity: 1 } : \"animate\"}\n      exit={reduce ? { opacity: 0 } : \"exit\"}\n      transition={reduce ? { duration: 0.15 } : undefined}\n      className=\"inline-grid shrink-0 place-items-center overflow-hidden\"\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nfunction TextSlot({\n  value,\n  children,\n}: {\n  value: string;\n  children: ReactNode;\n}) {\n  const reduce = useReducedMotion();\n  const measureRef = useRef<HTMLSpanElement>(null);\n  const [width, setWidth] = useState<number>();\n  const label = typeof children === \"string\" ? children : null;\n  const cascade = label !== null && !reduce;\n\n  // Measure strings with the same per-letter layout as the cascade. Measuring\n  // the whole string preserves kerning, which can make it narrower than the\n  // inline-block letters and clip the final glyph during the width animation.\n  useLayoutEffect(() => {\n    const nextWidth = measureRef.current?.offsetWidth;\n    if (!nextWidth) return;\n    setWidth((current) => (current === nextWidth ? current : nextWidth));\n  });\n\n  return (\n    <motion.span\n      initial={false}\n      animate={{ width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className=\"relative inline-block overflow-hidden whitespace-nowrap align-bottom\"\n    >\n      <span\n        ref={measureRef}\n        aria-hidden\n        className=\"invisible inline-block whitespace-nowrap\"\n      >\n        {cascade\n          ? label.split(\"\").map((char, index) => (\n              <span\n                // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                key={index}\n                className=\"inline-block whitespace-pre\"\n              >\n                {char}\n              </span>\n            ))\n          : children}\n      </span>\n\n      {cascade ? (\n        <>\n          <span className=\"sr-only\">{label}</span>\n          <AnimatePresence initial={false}>\n            <motion.span\n              key={`cascade-${value}`}\n              aria-hidden\n              initial=\"initial\"\n              animate=\"animate\"\n              exit=\"exit\"\n              className=\"absolute left-0 top-0 inline-block whitespace-pre\"\n            >\n              {label.split(\"\").map((char, index) => (\n                <motion.span\n                  // biome-ignore lint/suspicious/noArrayIndexKey: position is the slot identity.\n                  key={index}\n                  custom={index * CASCADE_STAGGER}\n                  variants={CASCADE_LETTER_VARIANTS}\n                  // Own states: a label that swaps away and straight back\n                  // re-enters mid-exit, and only owned targets are restored.\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  className=\"inline-block whitespace-pre will-change-[opacity,filter,transform]\"\n                >\n                  {char}\n                </motion.span>\n              ))}\n            </motion.span>\n          </AnimatePresence>\n        </>\n      ) : (\n        <AnimatePresence initial={false}>\n          <motion.span\n            key={`text-${value}`}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: 14, filter: ROLL_BLUR }}\n            animate={reduce ? { opacity: 1 } : { opacity: 1, y: 0, filter: \"blur(0px)\" }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -14, filter: ROLL_BLUR }}\n            transition={reduce ? { duration: 0.15 } : SPRING_SWAP}\n            className=\"absolute left-0 top-0 inline-block will-change-[opacity,filter,transform]\"\n          >\n            {children}\n          </motion.span>\n        </AnimatePresence>\n      )}\n    </motion.span>\n  );\n}\n\nexport const StatefulButton = forwardRef<HTMLButtonElement, StatefulButtonProps>(function StatefulButton(\n  {\n    state = \"idle\",\n    children,\n    loadingText,\n    successText,\n    errorText,\n    icon,\n    labels,\n    disabled,\n    ...rest\n  },\n  ref,\n) {\n  const t = useMessages(\"statefulButton\", statefulButtonMessages, labels);\n  const isBusy = state === \"loading\";\n  const stateText =\n    state === \"loading\"\n      ? (loadingText ?? t(\"loading\"))\n      : state === \"success\"\n        ? (successText ?? t(\"success\"))\n        : state === \"error\"\n        ? (errorText ?? t(\"error\"))\n        : children;\n  const textKey =\n    typeof stateText === \"string\" ? `${state}-${stateText}` : state;\n\n  return (\n    <Button ref={ref} disabled={disabled || isBusy} aria-busy={isBusy} {...rest}>\n      <span\n        aria-live=\"polite\"\n        className=\"relative inline-flex items-center justify-center overflow-hidden\"\n      >\n        <AnimatePresence initial={false}>\n          {state === \"loading\" ? (\n            <IconSlot keyId=\"loading-icon\">\n              <Loader2 className=\"h-4 w-4 animate-spin\" />\n            </IconSlot>\n          ) : null}\n          {state === \"success\" ? (\n            <IconSlot keyId=\"success-icon\">\n              <Check className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n          {state === \"error\" ? (\n            <IconSlot keyId=\"error-icon\">\n              <X className=\"h-4 w-4\" />\n            </IconSlot>\n          ) : null}\n        </AnimatePresence>\n\n        <TextSlot value={textKey}>{stateText}</TextSlot>\n\n        <AnimatePresence initial={false}>\n          {state === \"idle\" && icon ? (\n            <IconSlot keyId=\"idle-icon\">{icon}</IconSlot>\n          ) : null}\n        </AnimatePresence>\n      </span>\n    </Button>\n  );\n});\n"},{"path":"components/motion/dropdown-menu/context.ts","type":"util","content":"\"use client\";\n\nimport { createContext, type MutableRefObject, useContext } from \"react\";\nimport type { Point } from \"./placement\";\n\nexport type FocusTarget = \"first\" | \"last\" | \"panel\" | \"none\";\n\nexport interface RootContextValue {\n  open: boolean;\n  /**\n   * `instant` skips the open or close animation: the keyboard asked for it,\n   * and keyboard users open and close menus far too often to wait on motion.\n   */\n  setOpen: (open: boolean, focus?: FocusTarget, instant?: boolean) => void;\n  focusTarget: FocusTarget;\n  /** Whether the latest open or close skips its animation. */\n  instant: boolean;\n  menuId: string;\n  triggerId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  reduce: boolean;\n  mounted: boolean;\n  /** Plays the select sound when the menu's `sound` prop is on. */\n  playSelect: () => void;\n}\n\nexport const RootContext = createContext<RootContextValue | null>(null);\n\nexport function useRoot(component: string) {\n  const context = useContext(RootContext);\n  if (!context) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return context;\n}\n\n/** One open panel: the root menu or a submenu. */\nexport interface LevelContextValue {\n  levelId: string;\n  present: boolean;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** The highlight glides after the pointer, and jumps after a key. */\n  glide: boolean;\n  openSub: string | null;\n  /** `instant` defaults to true when a focus target says the keyboard opened it. */\n  setOpenSub: (id: string | null, focus?: FocusTarget, instant?: boolean) => void;\n  subFocus: FocusTarget;\n  /** Whether the submenu's latest open or close skips its animation. */\n  subInstant: boolean;\n  /** A pointer on its way from a submenu trigger to the submenu it opened. */\n  grace: MutableRefObject<{ polygon: Point[]; until: number } | null>;\n}\n\nexport const LevelContext = createContext<LevelContextValue | null>(null);\n\nexport function useLevel(component: string) {\n  const context = useContext(LevelContext);\n  if (!context) {\n    throw new Error(`${component} must be used within <DropdownMenuContent>`);\n  }\n  return context;\n}\n"},{"path":"components/motion/dropdown-menu/item-base.tsx","type":"util","content":"\"use client\";\n\nimport { type MutableRefObject, type KeyboardEvent as ReactKeyboardEvent, type ReactNode, useId } from \"react\";\nimport { MENU_ITEM_CLASS, MenuItemHighlight } from \"@/components/motion/menu/menu-item-highlight\";\nimport { cn } from \"@/lib/utils\";\nimport { useLevel, useRoot } from \"./context\";\nimport { insidePolygon } from \"./placement\";\n\ntype ItemTone = \"default\" | \"destructive\";\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Called when the item is chosen by click, Enter or Space. */\n  onSelect?: () => void;\n  /** Dims the item and blocks selecting it. Default: false */\n  disabled?: boolean;\n  /** Close the whole menu after selecting. Default true. */\n  closeOnSelect?: boolean;\n  /** \"destructive\" tints the row for dangerous actions. Default: \"default\" */\n  tone?: ItemTone;\n  /** Indent to line up with rows that start with an icon. */\n  inset?: boolean;\n  /** Text matched by typeahead when the label is not plain text. */\n  textValue?: string;\n  /** Classes merged onto the item row. */\n  className?: string;\n}\n\ninterface ItemBaseProps extends DropdownMenuItemProps {\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  checked?: boolean;\n  subTrigger?: {\n    id: string;\n    open: boolean;\n    controls: string;\n    onPointerMove: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onPointerLeave: (event: React.PointerEvent<HTMLButtonElement>) => void;\n    onKeyDown: (event: ReactKeyboardEvent<HTMLButtonElement>) => void;\n    onClick: () => void;\n    ref: MutableRefObject<HTMLElement | null>;\n  };\n}\n\n/** The row every item kind renders: plain, checkbox, radio and submenu trigger. */\nexport function ItemBase({\n  children,\n  onSelect,\n  disabled = false,\n  closeOnSelect = true,\n  tone = \"default\",\n  inset = false,\n  textValue,\n  className,\n  role = \"menuitem\",\n  checked,\n  subTrigger,\n}: ItemBaseProps) {\n  const root = useRoot(\"DropdownMenuItem\");\n  const level = useLevel(\"DropdownMenuItem\");\n  const ownId = useId();\n  const id = subTrigger?.id ?? ownId;\n  const active = level.activeId === id;\n\n  return (\n    <button\n      type=\"button\"\n      ref={(node) => {\n        if (subTrigger) subTrigger.ref.current = node;\n      }}\n      id={id}\n      role={role}\n      {...(role === \"menuitem\" ? {} : { \"aria-checked\": checked })}\n      aria-haspopup={subTrigger ? \"menu\" : undefined}\n      aria-expanded={subTrigger ? subTrigger.open : undefined}\n      aria-controls={subTrigger?.open ? subTrigger.controls : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={-1}\n      data-menu-item=\"\"\n      data-level={level.levelId}\n      data-disabled={disabled ? \"\" : undefined}\n      data-highlighted={active ? \"\" : undefined}\n      data-text-value={textValue}\n      onFocus={() => {\n        level.setActiveId(id);\n        // Moving to another row of this menu closes a submenu it does not own.\n        if (level.openSub && level.openSub !== subTrigger?.id) level.setOpenSub(null);\n      }}\n      onPointerMove={(event) => {\n        if (event.pointerType === \"touch\") return;\n        // On the way to an open submenu, crossing this row changes nothing.\n        const grace = level.grace.current;\n        if (grace && Date.now() < grace.until && insidePolygon({ x: event.clientX, y: event.clientY }, grace.polygon)) {\n          return;\n        }\n        level.grace.current = null;\n        if (subTrigger) {\n          subTrigger.onPointerMove(event);\n          return;\n        }\n        if (level.openSub) level.setOpenSub(null);\n        if (disabled) {\n          if (level.panelRef.current?.contains(document.activeElement)) {\n            level.panelRef.current.focus({ preventScroll: true });\n          }\n          return;\n        }\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={subTrigger?.onPointerLeave}\n      onKeyDown={subTrigger?.onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        if (subTrigger) {\n          subTrigger.onClick();\n          return;\n        }\n        onSelect?.();\n        // `detail` is 0 when Enter or Space picked the row: close without animating.\n        if (closeOnSelect) root.setOpen(false, \"first\", event.detail === 0);\n      }}\n      className={cn(\n        MENU_ITEM_CLASS,\n        \"cursor-default gap-2\",\n        \"[&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-9\",\n        disabled && \"opacity-50\",\n        tone === \"destructive\" ? \"text-destructive [&_svg]:text-destructive\" : \"[&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {active && !disabled ? (\n        <MenuItemHighlight\n          layoutId={`${level.levelId}-highlight`}\n          tone={tone}\n          reduce={root.reduce}\n          instant={!level.glide}\n        />\n      ) : null}\n      {children}\n    </button>\n  );\n}\n"},{"path":"components/motion/dropdown-menu/menu-panel.tsx","type":"util","content":"\"use client\";\n\nimport { motion, type Variants } from \"motion/react\";\nimport {\n  type MutableRefObject,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { enabledItems, useMenuNavigation } from \"@/components/motion/menu/use-menu-navigation\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { type FocusTarget, LevelContext, type LevelContextValue, useRoot } from \"./context\";\nimport { type Align, type Placement, type Point, place, type Side } from \"./placement\";\n\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\n// The panel grows out of its trigger from this scale and distance.\nconst OPEN_SCALE = 0.94;\nconst OPEN_TRAVEL = 6;\nconst OPEN = { duration: 0.2, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\ninterface PanelProps {\n  children: ReactNode;\n  className?: string;\n  id: string;\n  anchorRef: MutableRefObject<HTMLElement | null>;\n  side: Side;\n  align: Align;\n  sideOffset: number;\n  focus: FocusTarget;\n  /** Show without animating; the AnimatePresence around it carries the same flag to the exit. */\n  instant: boolean;\n  present: boolean;\n  gate: { inert: boolean; style: { pointerEvents: \"auto\" | \"none\" } };\n  labelledBy: string;\n  onClose: () => void;\n  onKeyDown?: (event: ReactKeyboardEvent<HTMLDivElement>) => boolean;\n  onPointerEnter?: () => void;\n  panelRef: MutableRefObject<HTMLDivElement | null>;\n}\n\n/** One panel, shared by the menu and its submenus. */\nexport function MenuPanel({\n  children,\n  className,\n  id,\n  anchorRef,\n  side,\n  align,\n  sideOffset,\n  focus,\n  instant,\n  present,\n  gate,\n  labelledBy,\n  onClose,\n  onKeyDown,\n  onPointerEnter,\n  panelRef,\n}: PanelProps) {\n  const root = useRoot(\"DropdownMenuContent\");\n  const parent = useContext(LevelContext);\n  const levelId = useId();\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [glide, setGlide] = useState(true);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const [subFocus, setSubFocus] = useState<FocusTarget>(\"none\");\n  const [subInstant, setSubInstant] = useState(false);\n  const grace = useRef<{ polygon: Point[]; until: number } | null>(null);\n  const navigate = useMenuNavigation();\n\n  const layout = usePopoverPortalPosition(anchorRef, panelRef, true);\n  // Held once placed: an exiting panel stays where it was, even if the\n  // trigger scrolls away under it.\n  const [placement, setPlacement] = useState<Placement | null>(null);\n  useLayoutEffect(() => {\n    if (!layout || !present) return;\n    // A submenu measures its gap from the parent panel's edge, not from the\n    // row inside it, so the two panels never touch.\n    const edge = parent?.panelRef.current?.getBoundingClientRect();\n    const anchor = edge ? { ...layout.trigger, left: edge.left, width: edge.width } : layout.trigger;\n    setPlacement(place(anchor, layout.content, side, align, sideOffset));\n  }, [layout, present, side, align, sideOffset, parent]);\n\n  const setOpenSub = useCallback(\n    (next: string | null, nextFocus: FocusTarget = \"none\", now = nextFocus !== \"none\") => {\n      setSubFocus(nextFocus);\n      setSubInstant(now);\n      setOpenSubState(next);\n    },\n    [],\n  );\n\n  // Waits for the first placement: the panel is `visibility: hidden` until\n  // then, and the browser will not focus anything inside it.\n  const placed = placement !== null;\n  useEffect(() => {\n    const panel = panelRef.current;\n    // `present` too: reopening during the exit brings this same panel back.\n    if (!placed || !present || !panel || focus === \"none\") return;\n    if (focus === \"panel\") {\n      panel.focus({ preventScroll: true });\n      return;\n    }\n    const items = enabledItems(panel);\n    (focus === \"last\" ? items[items.length - 1] : items[0])?.focus({ preventScroll: true });\n  }, [placed, present, focus, panelRef]);\n\n  const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // Submenus render inside this panel's React tree, so their keys bubble\n    // here too. Each panel answers only for its own rows.\n    const panel = panelRef.current;\n    const target = event.target as HTMLElement;\n    if (!panel || target.closest(\"[data-menu-panel]\") !== panel) return;\n    // Set before the key moves focus, so the highlight it lands on jumps.\n    setGlide(false);\n    if (onKeyDown?.(event)) return;\n    if (event.key === \"Tab\") {\n      event.preventDefault();\n      onClose();\n      return;\n    }\n    navigate(event, panel);\n  };\n\n  const level = useMemo<LevelContextValue>(\n    () => ({\n      levelId,\n      present,\n      panelRef,\n      activeId,\n      setActiveId,\n      glide,\n      openSub,\n      setOpenSub,\n      subFocus,\n      subInstant,\n      grace,\n    }),\n    [levelId, present, panelRef, activeId, glide, openSub, setOpenSub, subFocus, subInstant],\n  );\n\n  // The panel starts tucked toward its trigger and springs out of it.\n  const used = placement?.side ?? side;\n  const toward = used === \"top\" || used === \"left\" ? 1 : -1;\n  const vertical = used === \"top\" || used === \"bottom\";\n  const offset = (distance: number) => (vertical ? { y: distance * toward } : { x: distance * toward });\n  // `custom` is the instant flag. An exiting panel reads it from its\n  // AnimatePresence, so Escape removes the menu at once even after it has\n  // already left the React tree.\n  const variants: Variants = root.reduce\n    ? {\n        hidden: { opacity: 0 },\n        shown: (now = false) => ({\n          opacity: 1,\n          transition: now ? INSTANT : { duration: 0.15, ease: EASE_OUT },\n        }),\n        gone: (now = false) => ({ opacity: 0, transition: now ? INSTANT : EXIT }),\n      }\n    : {\n        hidden: { opacity: 0, scale: OPEN_SCALE, ...offset(OPEN_TRAVEL) },\n        shown: (now = false) => ({\n          opacity: 1,\n          scale: 1,\n          x: 0,\n          y: 0,\n          transition: now\n            ? INSTANT\n            : {\n                ...OPEN,\n                opacity: { duration: 0.12, ease: EASE_OUT },\n              },\n        }),\n        gone: (now = false) => ({\n          opacity: 0,\n          scale: 0.97,\n          ...offset(OPEN_TRAVEL / 2),\n          transition: now ? INSTANT : EXIT,\n        }),\n      };\n\n  return createPortal(\n    <motion.div\n      {...gate}\n      ref={panelRef}\n      id={id}\n      role=\"menu\"\n      aria-labelledby={labelledBy}\n      aria-orientation=\"vertical\"\n      tabIndex={-1}\n      data-menu-panel=\"\"\n      data-menu-root={root.menuId}\n      data-level={levelId}\n      data-side={placement?.side ?? side}\n      custom={instant}\n      variants={variants}\n      initial=\"hidden\"\n      animate=\"shown\"\n      exit=\"gone\"\n      onKeyDown={handleKeyDown}\n      onPointerMove={(event) => {\n        if (event.pointerType !== \"touch\") setGlide(true);\n      }}\n      onFocus={(event) => {\n        if (event.target === event.currentTarget) setActiveId(null);\n      }}\n      onPointerEnter={onPointerEnter}\n      onPointerLeave={(event) => {\n        // Leaving the panel drops the highlight, unless the row it sits on\n        // owns the open submenu the pointer is heading into.\n        if (event.pointerType === \"touch\" || openSub) return;\n        const panel = panelRef.current;\n        if (panel?.contains(document.activeElement)) panel.focus({ preventScroll: true });\n      }}\n      style={{\n        ...gate.style,\n        left: placement?.left ?? 0,\n        top: placement?.top ?? 0,\n        transformOrigin: placement?.origin,\n        maxHeight: placement?.maxHeight,\n        visibility: placement ? undefined : \"hidden\",\n      }}\n      className={cn(\n        \"fixed z-[100] min-w-48 overflow-y-auto overscroll-contain rounded-2xl border border-border bg-background p-2 text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)] outline-none\",\n        parent && \"z-[101]\",\n        className,\n      )}\n    >\n      <LevelContext.Provider value={level}>{children}</LevelContext.Provider>\n    </motion.div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/dropdown-menu/placement.ts","type":"util","content":"export const VIEWPORT_PADDING = 8;\n// The panel's border and padding, so a submenu's first row lines up with the\n// row that opened it.\nexport const SUB_ALIGN_OFFSET = 9;\n// How far a submenu stacked under its row sits in, so it reads as nested.\nexport const SUB_STACK_INDENT = 16;\n\nexport type Side = \"top\" | \"bottom\" | \"left\" | \"right\";\nexport type Align = \"start\" | \"center\" | \"end\";\nexport type Point = { x: number; y: number };\n\nexport type Placement = {\n  left: number;\n  top: number;\n  side: Side;\n  origin: string;\n  /** The room on the chosen side; a taller menu scrolls inside it. */\n  maxHeight: number;\n};\n\nexport type Rect = { left: number; top: number; width: number; height: number };\n\nexport function clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\nexport function insidePolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\nexport function placeVertical(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: \"top\" | \"bottom\",\n  align: Align,\n  offset: number,\n): Placement {\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const below = trigger.top + trigger.height + offset;\n  const roomBelow = viewHeight - VIEWPORT_PADDING - below;\n  const roomAbove = trigger.top - offset - VIEWPORT_PADDING;\n  // The preferred side when the menu fits there, otherwise the roomier one.\n  const used =\n    side === \"bottom\"\n      ? size.height <= roomBelow || roomBelow >= roomAbove\n        ? \"bottom\"\n        : \"top\"\n      : size.height <= roomAbove || roomAbove >= roomBelow\n        ? \"top\"\n        : \"bottom\";\n  const maxHeight = Math.max(used === \"bottom\" ? roomBelow : roomAbove, 0);\n  const height = Math.min(size.height, maxHeight);\n  const start =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width - size.width\n        : trigger.left + trigger.width / 2 - size.width / 2;\n  const x = clamp(start, VIEWPORT_PADDING, viewWidth - size.width - VIEWPORT_PADDING);\n  const y = used === \"bottom\" ? below : trigger.top - offset - height;\n  // Grow from the aligned edge, so that edge holds still while the panel\n  // scales in instead of sliding sideways into place.\n  const anchorX =\n    align === \"start\"\n      ? trigger.left\n      : align === \"end\"\n        ? trigger.left + trigger.width\n        : trigger.left + trigger.width / 2;\n  const originX = clamp(anchorX - x, 0, size.width);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${originX}px ${used === \"bottom\" ? 0 : height}px`,\n    maxHeight,\n  };\n}\n\nexport function place(\n  trigger: Rect,\n  size: { width: number; height: number },\n  side: Side,\n  align: Align,\n  offset: number,\n): Placement {\n  if (side === \"top\" || side === \"bottom\") {\n    return placeVertical(trigger, size, side, align, offset);\n  }\n\n  const viewWidth = document.documentElement.clientWidth;\n  const viewHeight = window.innerHeight;\n  const right = trigger.left + trigger.width + offset;\n  const left = trigger.left - size.width - offset;\n  const fitsRight = right + size.width <= viewWidth - VIEWPORT_PADDING;\n  const fitsLeft = left >= VIEWPORT_PADDING;\n  // A narrow screen has room on neither side: drop below the row instead of\n  // covering it, the way a phone stacks a submenu.\n  if (!fitsRight && !fitsLeft) {\n    return placeVertical(\n      { ...trigger, left: trigger.left + SUB_STACK_INDENT, width: trigger.width - SUB_STACK_INDENT },\n      size,\n      \"bottom\",\n      \"start\",\n      2,\n    );\n  }\n  const used: Side = side === \"right\" ? (fitsRight ? \"right\" : \"left\") : fitsLeft ? \"left\" : \"right\";\n  const maxHeight = viewHeight - VIEWPORT_PADDING * 2;\n  const height = Math.min(size.height, maxHeight);\n  const x = used === \"right\" ? right : left;\n  const y = clamp(trigger.top - SUB_ALIGN_OFFSET, VIEWPORT_PADDING, viewHeight - height - VIEWPORT_PADDING);\n  const originY = clamp(trigger.top + trigger.height / 2 - y, 0, height);\n  return {\n    left: x,\n    top: y,\n    side: used,\n    origin: `${used === \"right\" ? 0 : size.width}px ${originY}px`,\n    maxHeight,\n  };\n}\n"},{"path":"components/motion/menu/use-menu-navigation.ts","type":"util","content":"\"use client\";\n\nimport { type KeyboardEvent, useCallback, useEffect, useRef } from \"react\";\n\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * The enabled rows of one menu panel, in order. Rows carry `data-menu-item`\n * and the panel's `data-level`, so a submenu rendered inside the panel keeps\n * its own rows to itself.\n */\nexport function enabledItems(panel: HTMLElement | null) {\n  if (!panel) return [];\n  return Array.from(\n    panel.querySelectorAll<HTMLElement>(\n      `[data-menu-item][data-level=\"${panel.dataset.level}\"]:not([data-disabled])`,\n    ),\n  );\n}\n\n/**\n * Arrow keys, Home, End and typeahead for a menu panel. The returned handler\n * moves focus between the panel's rows and says whether it used the key.\n * Typeahead matches a row's `data-text-value`, or its text.\n */\nexport function useMenuNavigation() {\n  const query = useRef(\"\");\n  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  useEffect(\n    () => () => {\n      if (timer.current) clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  return useCallback((event: KeyboardEvent<HTMLElement>, panel: HTMLElement | null) => {\n    const items = enabledItems(panel);\n    const index = items.indexOf(event.target as HTMLElement);\n    if (event.key === \"ArrowDown\" || event.key === \"ArrowUp\") {\n      event.preventDefault();\n      if (items.length === 0) return true;\n      const step = event.key === \"ArrowDown\" ? 1 : -1;\n      const next =\n        index < 0\n          ? step === 1\n            ? 0\n            : items.length - 1\n          : (index + step + items.length) % items.length;\n      items[next]?.focus();\n      return true;\n    }\n    if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      items[event.key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return true;\n    }\n    const typed = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A space with nothing typed yet presses the row instead.\n    if (!typed || (event.key === \" \" && query.current === \"\")) return false;\n    query.current += event.key.toLocaleLowerCase();\n    if (timer.current) clearTimeout(timer.current);\n    timer.current = setTimeout(() => {\n      query.current = \"\";\n    }, TYPEAHEAD_RESET);\n    // Start after the current row, so repeating a letter cycles its matches.\n    const ordered = [...items.slice(index + 1), ...items.slice(0, index + 1)];\n    const typedSoFar = query.current;\n    const repeated = typedSoFar.length > 1 && [...typedSoFar].every((char) => char === typedSoFar[0]);\n    const needle = repeated ? typedSoFar[0] : typedSoFar;\n    const match = ordered.find((item) =>\n      (item.dataset.textValue ?? item.textContent ?? \"\").trim().toLocaleLowerCase().startsWith(needle),\n    );\n    if (!match) return false;\n    event.preventDefault();\n    match.focus();\n    return true;\n  }, []);\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit - this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree - an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/sound.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/close.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** The open whoosh falling and a little quicker, settling with a soft low tap, for things closing. */\nexport const closeSound = defineSound({\n  name: \"Close\",\n  duration: 0.16,\n  room: 0.18,\n  build: (v) => {\n    v.noise({ freq: 2600, to: 700, q: 1.2, attack: 0.012, decay: 0.09, gain: 0.7 });\n    v.click({ freq: 1400, q: 1.2, at: 0.05, decay: 0.006, gain: 0.2 });\n    v.strike({ freq: 260, material: \"wood\", bend: 1.2, at: 0.05, decay: 0.045, gain: 0.3 });\n  },\n});\n"},{"path":"lib/sounds/open.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A soft rising whoosh that lands with a light glass touch, for menus, popovers and dialogs opening. */\nexport const openSound = defineSound({\n  name: \"Open\",\n  duration: 0.2,\n  room: 0.2,\n  build: (v) => {\n    v.noise({ freq: 600, to: 2600, q: 1.2, attack: 0.035, decay: 0.11, gain: 0.75 });\n    v.noise({ freq: 4500, to: 6000, q: 1, attack: 0.03, decay: 0.07, gain: 0.05 });\n    v.strike({ freq: 1320, material: \"glass\", at: 0.05, decay: 0.07, gain: 0.12 });\n  },\n});\n"},{"path":"lib/sounds/select.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A crisp detent, like a dial clicking into a notch, for tabs, segmented controls and menu choices. */\nexport const selectSound = defineSound({\n  name: \"Select\",\n  duration: 0.05,\n  room: 0.08,\n  build: (v) => {\n    v.click({ freq: 4500, q: 2.5, decay: 0.003, gain: 0.45 });\n    v.strike({ freq: 1700, material: \"metal\", decay: 0.028, gain: 0.3 });\n    v.strike({ freq: 520, material: \"wood\", bend: 1.15, decay: 0.012, gain: 0.25 });\n  },\n});\n"},{"path":"components/motion/tooltip/grace.ts","type":"util","content":"type Point = { x: number; y: number };\ntype Box = { left: number; top: number; right: number; bottom: number };\n\n/**\n * The corridor a pointer may cross between the trigger and the open tooltip\n * without closing it: the convex hull of where it left and the box it is\n * heading for. A fixed timeout either cuts a slow diagonal move short or keeps\n * the label alive after the pointer has plainly gone elsewhere; this follows\n * the path itself.\n */\nexport function graceArea(exit: Point, target: Box): Point[] {\n  // A few pixels either side of the exit point give the corridor some width at\n  // its narrow end, so a hand that drifts sideways while it moves stays inside.\n  const pad = 5;\n  return hull([\n    { x: exit.x - pad, y: exit.y - pad },\n    { x: exit.x + pad, y: exit.y - pad },\n    { x: exit.x - pad, y: exit.y + pad },\n    { x: exit.x + pad, y: exit.y + pad },\n    { x: target.left, y: target.top },\n    { x: target.right, y: target.top },\n    { x: target.right, y: target.bottom },\n    { x: target.left, y: target.bottom },\n  ]);\n}\n\nexport function inBox(point: Point, box: Box) {\n  return (\n    point.x >= box.left && point.x <= box.right && point.y >= box.top && point.y <= box.bottom\n  );\n}\n\nexport function inPolygon(point: Point, polygon: Point[]) {\n  let inside = false;\n  for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {\n    const a = polygon[i];\n    const b = polygon[j];\n    if (\n      a.y > point.y !== b.y > point.y &&\n      point.x < ((b.x - a.x) * (point.y - a.y)) / (b.y - a.y) + a.x\n    ) {\n      inside = !inside;\n    }\n  }\n  return inside;\n}\n\n// Monotone chain; the corridor is always convex, so a hull is all it needs.\nfunction hull(points: Point[]) {\n  const sorted = [...points].sort((a, b) => a.x - b.x || a.y - b.y);\n  const cross = (o: Point, a: Point, b: Point) =>\n    (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n  const lower: Point[] = [];\n  for (const p of sorted) {\n    while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) {\n      lower.pop();\n    }\n    lower.push(p);\n  }\n  const upper: Point[] = [];\n  for (let i = sorted.length - 1; i >= 0; i--) {\n    const p = sorted[i];\n    while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) {\n      upper.pop();\n    }\n    upper.push(p);\n  }\n  lower.pop();\n  upper.pop();\n  return lower.concat(upper);\n}\n\n/**\n * How the user last reached for the page. A focus that a mouse press caused is\n * not a request to read the label: the pointer is already on the control and\n * hovering showed it. A focus that followed a key - Tab, or a roving arrow key\n * moving focus in script - is the only way a keyboard user sees it at all.\n */\nlet modality: \"keyboard\" | \"pointer\" = \"keyboard\";\nlet listening = false;\n\nexport function watchModality() {\n  if (listening || typeof window === \"undefined\") return;\n  listening = true;\n  window.addEventListener(\"keydown\", () => (modality = \"keyboard\"), true);\n  window.addEventListener(\"pointerdown\", () => (modality = \"pointer\"), true);\n}\n\nexport function focusFromKeyboard() {\n  return modality === \"keyboard\";\n}\n"},{"path":"components/motion/tooltip/positioner.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport { type CSSProperties, type ReactNode, type Ref, useCallback, useState } from \"react\";\nimport { type TooltipSide, useTooltipPosition } from \"./use-position\";\n\ntype PositionProps = Parameters<typeof useTooltipPosition>[0];\n\n/** Readiness lives with the mounted overlay, not a trigger ref's attach/detach cycle. */\nexport function TooltipPositioner({\n  children,\n  ...position\n}: Omit<PositionProps, \"open\" | \"onPosition\"> & {\n  children: (ready: boolean, present: boolean, side: TooltipSide) => ReactNode;\n}) {\n  const present = useIsPresent();\n  const [ready, setReady] = useState(false);\n  const [side, setSide] = useState<TooltipSide>(position.side);\n  const onPosition = useCallback((placed: TooltipSide) => {\n    setReady(true);\n    setSide(placed);\n  }, []);\n  useTooltipPosition({ ...position, open: present, onPosition });\n  return (\n    <span\n      ref={position.floatingRef}\n      inert={!present}\n      aria-hidden={!present || undefined}\n      className=\"pointer-events-none fixed left-0 top-0 z-[9999] w-max\"\n      style={{ visibility: \"hidden\", maxWidth: \"calc(100vw - 16px)\" }}\n    >\n      {children(ready, present, side)}\n    </span>\n  );\n}\n\n// Each arrow is a 12px box whose base sits on the surface's inner border edge,\n// so its fill covers the border beneath it and only the two outer edges stroke.\nconst ARROW: Record<TooltipSide, { path: string; style: CSSProperties }> = {\n  top: { path: \"M0 6L6 12L12 6\", style: { top: \"calc(100% - 6px)\" } },\n  bottom: { path: \"M0 6L6 0L12 6\", style: { bottom: \"calc(100% - 6px)\" } },\n  left: { path: \"M6 0L12 6L6 12\", style: { left: \"calc(100% - 6px)\" } },\n  right: { path: \"M6 0L0 6L6 12\", style: { right: \"calc(100% - 6px)\" } },\n};\n\nexport function TooltipArrow({ side, ref }: { side: TooltipSide; ref: Ref<SVGSVGElement> }) {\n  const { path, style } = ARROW[side];\n  return (\n    <svg\n      ref={ref}\n      aria-hidden=\"true\"\n      width=\"12\"\n      height=\"12\"\n      viewBox=\"0 0 12 12\"\n      className=\"pointer-events-none absolute overflow-visible\"\n      style={style}\n    >\n      {/* Redrawn to fit the surface's edge once placed (see arrowShape). */}\n      <path data-arrow-fill=\"\" d={`${path}Z`} style={{ fill: \"var(--tooltip-arrow-fill, transparent)\" }} />\n      <path\n        data-arrow-stroke=\"\"\n        d={path}\n        fill=\"none\"\n        strokeWidth=\"1\"\n        style={{ stroke: \"var(--tooltip-arrow-stroke, transparent)\" }}\n      />\n    </svg>\n  );\n}\n"},{"path":"components/motion/tooltip/use-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  arrow as arrowMiddleware,\n  autoUpdate,\n  computePosition,\n  flip,\n  hide,\n  offset,\n  type Placement,\n  shift,\n  type VirtualElement,\n} from \"@floating-ui/dom\";\nimport { type RefObject, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\n\nexport type TooltipSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type TooltipAlign = \"start\" | \"center\" | \"end\";\nexport type TooltipPoint = {\n  /** Horizontal position; for `anchorPoint`, a 0 to 1 fraction of the anchor's width. */\n  x: number;\n  /** Vertical position; for `anchorPoint`, a 0 to 1 fraction of the anchor's height. */\n  y: number;\n};\nexport type TooltipAnchor = HTMLElement | SVGElement;\n\nconst ORIGIN: Record<TooltipSide, string> = {\n  top: \"center bottom\",\n  bottom: \"center top\",\n  left: \"right center\",\n  right: \"left center\",\n};\n\n/** `top` painted over `bottom`, as one opaque colour. Falls back to `top`. */\nfunction blend(top: string, bottom: string) {\n  const context = document.createElement(\"canvas\").getContext(\"2d\", { willReadFrequently: true });\n  if (!context) return top;\n  context.fillStyle = bottom;\n  context.fillRect(0, 0, 1, 1);\n  context.fillStyle = top;\n  context.fillRect(0, 0, 1, 1);\n  const [r, g, b, a] = context.getImageData(0, 0, 1, 1).data;\n  // A see-through background has nothing solid to blend onto.\n  return a === 255 ? `rgb(${r}, ${g}, ${b})` : top;\n}\n\n/** The arrow element's box, which the arrow middleware centres along the edge. */\nconst ARROW_SIZE = 12;\n/** How far the tip reaches past the border's inner edge. */\nconst ARROW_REACH = 6;\n\n/**\n * How far a rounded edge has curved in from its straight line at `position`\n * along an edge of `length`, with corners of `radius`. Zero on the straight\n * stretch between the corners.\n */\nfunction curveDepth(position: number, length: number, radius: number) {\n  const offset =\n    position < radius ? radius - position : position > length - radius ? position - (length - radius) : 0;\n  if (offset <= 0) return 0;\n  return radius - Math.sqrt(Math.max(radius * radius - offset * offset, 0));\n}\n\n/**\n * The arrow's two paths, in the surface's border-box coordinates. Each 45°\n * side runs from the tip until it meets the middle of the surface's border,\n * wherever that is: on a straight stretch, or partway round a pill's curved\n * end. The stroke covers only those two sides, so the border flows straight\n * into them. The fill closes a little inside the surface, hiding the stretch\n * of border the arrow sits on.\n */\nfunction arrowShape({\n  side,\n  center,\n  width,\n  height,\n  radius,\n  border,\n}: {\n  side: TooltipSide;\n  center: number;\n  width: number;\n  height: number;\n  radius: number;\n  border: number;\n}) {\n  const vertical = side === \"top\" || side === \"bottom\";\n  const length = vertical ? width : height;\n  // Work on one edge: `depth` runs inward from the edge's outer line, `along` runs down it.\n  const tip = { depth: border - ARROW_REACH, along: center };\n  // The border's centre line: the stroke meets it there, so the two line up.\n  const line = border / 2;\n  // Both sides follow the same rule, so an arrow a pixel off-centre stays symmetric.\n  const curved =\n    curveDepth(center - ARROW_SIZE / 2, length, radius) > 0 ||\n    curveDepth(center + ARROW_SIZE / 2, length, radius) > 0;\n  const meet = (direction: -1 | 1) => {\n    // On a straight stretch the 45° side meets the border directly.\n    if (!curved) {\n      for (let t = 0; t <= ARROW_SIZE; t += 0.05) {\n        const along = center + direction * t;\n        const depth = tip.depth + t;\n        if (depth >= line) return { depth, along };\n      }\n    }\n    // On a pill's round end a 45° side passes outside the curve, or meets it\n    // at a kink. Run the side tangent to the curve instead, so the border\n    // flows into it without a corner.\n    const curve = radius - line;\n    const centre = { depth: radius, along: direction < 0 ? radius : length - radius };\n    const dx = tip.depth - centre.depth;\n    const dy = tip.along - centre.along;\n    const distance = Math.hypot(dx, dy);\n    if (distance <= curve) return { depth: line, along: center + direction * ARROW_REACH };\n    const base = Math.atan2(dy, dx);\n    const spread = Math.acos(curve / distance);\n    const candidates = [base + spread, base - spread].map((angle) => ({\n      depth: centre.depth + curve * Math.cos(angle),\n      along: centre.along + curve * Math.sin(angle),\n    }));\n    // The tangent on this side of the tip.\n    return direction < 0\n      ? candidates[0].along < candidates[1].along\n        ? candidates[0]\n        : candidates[1]\n      : candidates[0].along > candidates[1].along\n        ? candidates[0]\n        : candidates[1];\n  };\n  const start = meet(-1);\n  const end = meet(1);\n  const inside = Math.max(start.depth, end.depth) + border + 1;\n  const point = ({ depth, along }: { depth: number; along: number }) => {\n    const [x, y] =\n      side === \"right\"\n        ? [depth, along]\n        : side === \"left\"\n          ? [width - depth, along]\n          : side === \"bottom\"\n            ? [along, depth]\n            : [along, height - depth];\n    return `${x.toFixed(2)} ${y.toFixed(2)}`;\n  };\n  return {\n    fill: `M${point(tip)}L${point(start)}L${point({ depth: inside, along: start.along })}L${point({ depth: inside, along: end.along })}L${point(end)}Z`,\n    stroke: `M${point(start)}L${point(tip)}L${point(end)}`,\n  };\n}\n\n/** Position is geometry, not animation. One write per frame, never a spring chasing a pointer. */\nexport function useTooltipPosition({\n  open,\n  anchor,\n  floatingRef,\n  arrowRef,\n  anchorPoint,\n  followCursor,\n  side,\n  align,\n  sideOffset,\n  onDismiss,\n  onPosition,\n  pointer,\n}: {\n  open: boolean;\n  anchor: TooltipAnchor | null;\n  floatingRef: RefObject<HTMLSpanElement | null>;\n  arrowRef?: RefObject<SVGSVGElement | null>;\n  anchorPoint?: TooltipPoint;\n  followCursor: boolean;\n  side: TooltipSide;\n  align: TooltipAlign;\n  sideOffset?: number;\n  onDismiss: () => void;\n  onPosition: (side: TooltipSide) => void;\n  pointer: ReturnType<typeof useTooltipPointer>;\n}) {\n  const { cursor, onMove } = pointer;\n  const preferred: Placement = align === \"center\" ? side : `${side}-${align}`;\n  const cursorSide = useRef<Placement | null>(null);\n  useLayoutEffect(() => {\n    cursorSide.current = open ? preferred : null;\n  }, [open, preferred]);\n  const frame = useRef<number | null>(null);\n  const version = useRef(0);\n  const update = useRef<() => void>(() => {});\n  const schedule = useCallback(() => {\n    // Invalidate older async calculations as soon as new geometry is requested.\n    version.current++;\n    if (frame.current !== null) return;\n    frame.current = requestAnimationFrame(() => {\n      frame.current = null;\n      update.current();\n    });\n  }, []);\n  useLayoutEffect(() => {\n    onMove.current = schedule;\n    return () => {\n      onMove.current = null;\n    };\n  }, [onMove, schedule]);\n  const pointX = anchorPoint?.x;\n  const pointY = anchorPoint?.y;\n\n  // Latest committed inputs are read without recreating observers for every period/content update.\n  useLayoutEffect(() => {\n    update.current = () => {\n      const floating = floatingRef.current;\n      if (!open || !anchor || !floating) return;\n      const revision = ++version.current;\n      const currentCursor = followCursor ? cursor.current : null;\n      const virtual = Boolean(currentCursor) || pointX !== undefined || pointY !== undefined;\n      const reference: Element | VirtualElement = virtual\n        ? {\n            contextElement: anchor,\n            getBoundingClientRect: () => {\n              const rect = anchor.getBoundingClientRect();\n              const x = currentCursor?.x ?? rect.left + rect.width * (pointX ?? 0.5);\n              const y = currentCursor?.y ?? rect.top + rect.height * (pointY ?? 0.5);\n              return { x, y, left: x, right: x, top: y, bottom: y, width: 0, height: 0 };\n            },\n          }\n        : anchor;\n      const arrowElement = arrowRef?.current ?? null;\n      void computePosition(reference, floating, {\n        strategy: \"fixed\",\n        placement: currentCursor ? (cursorSide.current ?? preferred) : preferred,\n        middleware: [\n          offset(sideOffset ?? (currentCursor ? 12 : 8)),\n          flip({ padding: 8 }),\n          shift({ padding: 8 }),\n          ...(arrowElement ? [arrowMiddleware({ element: arrowElement, padding: 10 })] : []),\n          // A label left floating over whatever scrolled into its trigger's place\n          // describes nothing there. Points inside a chart move with the chart.\n          ...(virtual ? [] : [hide({ strategy: \"referenceHidden\" })]),\n        ],\n      }).then(({ x, y, placement, middlewareData }) => {\n        if (version.current !== revision || !floating.isConnected) return;\n        // Hold the chosen side for this hover session. Crossing a flip threshold\n        // repeatedly must not bounce the surface above and below the pointer.\n        if (currentCursor) cursorSide.current = placement;\n        else cursorSide.current = null;\n        const placedSide = placement.split(\"-\")[0] as TooltipSide;\n        const dpr = window.devicePixelRatio || 1;\n        floating.style.transform = `translate3d(${Math.round(x * dpr) / dpr}px, ${Math.round(y * dpr) / dpr}px, 0)`;\n        floating.style.setProperty(\"--tooltip-origin\", ORIGIN[placedSide]);\n        // A box with no size has no clipped state to report, only a missing layout.\n        const box = anchor.getBoundingClientRect();\n        const clipped =\n          Boolean(middlewareData.hide?.referenceHidden) && (box.width > 0 || box.height > 0);\n        floating.style.visibility = clipped ? \"hidden\" : \"visible\";\n        floating.dataset.placement = placement;\n        const surface = arrowElement?.parentElement;\n        if (arrowElement && surface) {\n          // The middleware centres the 12px arrow box along the edge; its\n          // centre is where the tip points. The paths are drawn in the\n          // surface's border-box coordinates, so the svg sits at its corner.\n          const { x: ax, y: ay } = middlewareData.arrow ?? {};\n          const vertical = placedSide === \"top\" || placedSide === \"bottom\";\n          const width = surface.offsetWidth;\n          const height = surface.offsetHeight;\n          const along = (vertical ? ax : ay) ?? ((vertical ? width : height) - ARROW_SIZE) / 2;\n          const style = getComputedStyle(surface);\n          const shape = arrowShape({\n            side: placedSide,\n            center: along + ARROW_SIZE / 2,\n            width,\n            height,\n            // `rounded-full` resolves to a huge radius; the box clamps it to half its short side.\n            radius: Math.min(Number.parseFloat(style.borderTopLeftRadius) || 0, width / 2, height / 2),\n            border: surface.clientLeft,\n          });\n          Object.assign(arrowElement.style, {\n            left: `${-surface.clientLeft}px`,\n            top: `${-surface.clientTop}px`,\n            right: \"auto\",\n            bottom: \"auto\",\n          });\n          arrowElement.querySelector(\"[data-arrow-fill]\")?.setAttribute(\"d\", shape.fill);\n          arrowElement.querySelector(\"[data-arrow-stroke]\")?.setAttribute(\"d\", shape.stroke);\n          // Paint with whatever the surface resolved to, so a restyled tooltip\n          // keeps a matching arrow without a second set of classes. A\n          // see-through border is drawn over the surface's own background, so\n          // the stroke takes that blended colour: half of it sits over the\n          // page, and it overlaps the border where the two meet.\n          arrowElement.style.setProperty(\"--tooltip-arrow-fill\", style.backgroundColor);\n          arrowElement.style.setProperty(\n            \"--tooltip-arrow-stroke\",\n            blend(style.borderTopColor, style.backgroundColor),\n          );\n        }\n        onPosition(placedSide);\n      });\n    };\n    if (open) schedule();\n  }, [\n    open,\n    anchor,\n    floatingRef,\n    arrowRef,\n    followCursor,\n    pointX,\n    pointY,\n    preferred,\n    sideOffset,\n    schedule,\n    onPosition,\n    cursor,\n  ]);\n\n  useLayoutEffect(() => {\n    const floating = floatingRef.current;\n    if (!open || !anchor || !floating) return;\n    const stop = autoUpdate(anchor, floating, schedule);\n    const onScroll = () => {\n      // A stationary pointer no longer describes the same chart point after scrolling.\n      if (followCursor && cursor.current) onDismiss();\n    };\n    window.addEventListener(\"scroll\", onScroll, true);\n    return () => {\n      stop();\n      window.removeEventListener(\"scroll\", onScroll, true);\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n      frame.current = null;\n    };\n  }, [open, anchor, floatingRef, followCursor, onDismiss, schedule, cursor]);\n\n  useLayoutEffect(\n    () => () => {\n      version.current++;\n      if (frame.current !== null) cancelAnimationFrame(frame.current);\n    },\n    [],\n  );\n}\n\n/** Pointer lifetime belongs to the anchor, including the opening delay. */\nexport function useTooltipPointer(anchor: TooltipAnchor | null, followCursor: boolean) {\n  const cursor = useRef<TooltipPoint | null>(null);\n  const onMove = useRef<(() => void) | null>(null);\n  const pointerFocus = useRef(false);\n  useLayoutEffect(() => {\n    if (!anchor || !followCursor) return;\n    const point = (event: PointerEvent) => {\n      if (event.type === \"pointermove\" && event.pointerType === \"touch\" && !event.buttons) return;\n      cursor.current = { x: event.clientX, y: event.clientY };\n      if (event.type === \"pointerdown\") pointerFocus.current = true;\n      onMove.current?.();\n    };\n    const keyboard = () => {\n      cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const focus = () => {\n      if (!pointerFocus.current) cursor.current = null;\n      pointerFocus.current = false;\n      onMove.current?.();\n    };\n    const leave = () => {\n      cursor.current = null;\n    };\n    anchor.addEventListener(\"pointerenter\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointermove\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerdown\", point as EventListener, { passive: true });\n    anchor.addEventListener(\"pointerleave\", leave);\n    anchor.addEventListener(\"pointercancel\", leave);\n    anchor.addEventListener(\"keydown\", keyboard);\n    anchor.addEventListener(\"focusin\", focus);\n    return () => {\n      cursor.current = null;\n      anchor.removeEventListener(\"pointerenter\", point as EventListener);\n      anchor.removeEventListener(\"pointermove\", point as EventListener);\n      anchor.removeEventListener(\"pointerdown\", point as EventListener);\n      anchor.removeEventListener(\"pointerleave\", leave);\n      anchor.removeEventListener(\"pointercancel\", leave);\n      anchor.removeEventListener(\"keydown\", keyboard);\n      anchor.removeEventListener(\"focusin\", focus);\n    };\n  }, [anchor, followCursor]);\n\n  return useMemo(() => ({ cursor, onMove }), []);\n}\n"},{"path":"components/motion/tooltip-surface.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion, type Variants } from \"motion/react\";\nimport type { ComponentProps, ReactNode, Ref } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nconst ENTER = { duration: 0.18, ease: EASE_OUT };\nconst EXIT = { duration: 0.12, ease: EASE_OUT };\nconst INSTANT = { duration: 0 };\n\n/**\n * `custom` is the `instant` flag. An exiting surface reads it from its\n * `AnimatePresence`, so a tooltip replaced by a neighbour vanishes at once\n * even though it has already left the React tree.\n */\nconst variants = (reduce: boolean): Variants => ({\n  closed: (instant = false) => ({\n    opacity: 0,\n    scale: reduce ? 1 : 0.97,\n    transition: instant ? INSTANT : EXIT,\n  }),\n  open: (instant = false) => ({\n    opacity: 1,\n    scale: 1,\n    transition: instant ? INSTANT : ENTER,\n  }),\n});\n\n/** Presentation only: the unanimated parent owns measurement and positioning. */\nexport function TooltipSurface({\n  children,\n  className,\n  ref,\n  ready = true,\n  instant = false,\n  style,\n  ...props\n}: Omit<ComponentProps<typeof motion.span>, \"children\"> & {\n  children?: ReactNode;\n  /** Start the entrance only after the positioning layer has been measured. */\n  ready?: boolean;\n  /**\n   * Appear and disappear without animating: a label opened from the keyboard,\n   * or one of a row of tooltips the pointer is moving along.\n   */\n  instant?: boolean;\n  ref?: Ref<HTMLSpanElement>;\n}) {\n  const reduce = useReducedMotion() ?? false;\n  return (\n    <motion.span\n      ref={ref}\n      role=\"tooltip\"\n      custom={instant}\n      variants={variants(reduce)}\n      initial=\"closed\"\n      animate={ready ? \"open\" : \"closed\"}\n      exit=\"closed\"\n      style={{ transformOrigin: \"var(--tooltip-origin, center)\", ...style }}\n      className={cn(\n        \"block whitespace-nowrap rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-foreground shadow-[0_8px_24px_-8px_rgb(0_0_0/0.16)]\",\n        className,\n      )}\n      {...props}\n    >\n      {children}\n    </motion.span>\n  );\n}\n"},{"path":"lib/hooks/use-hover-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\nimport { isHoveringPointer } from \"@/lib/touch\";\n\ninterface BoundaryEvent {\n  pointerId: number;\n  pointerType: string;\n  buttons: number;\n}\n\nexport interface HoverGesture {\n  /** True when this enter starts a hover: the pointer arrived resting, not pressing. */\n  enter: (event: BoundaryEvent) => boolean;\n  /** True when this leave ends a hover that entered as one. */\n  leave: (event: BoundaryEvent) => boolean;\n}\n\n/**\n * Pairs a surface's enter with its leave, per pointer.\n *\n * `isHoveringPointer` answers the question the *enter* asks - is this pointer\n * resting on the surface or pressing it - and both boundary cases go wrong if\n * the leave is asked the same question again:\n *\n * - A pen with no hover never rests. It arrives in contact, taps, and the spec\n *   then requires its boundary events after `pointerup`, so the leave carries\n *   `buttons: 0` and reads as a mouse gliding off. Hover teardown then undid\n *   the tap - the panel the pen had just opened closed under it.\n * - A mouse pressed on the surface and dragged off leaves with `buttons: 1`.\n *   Skipping teardown there strands the surface open: the release happens\n *   outside, and no second leave ever comes.\n *\n * So the state a hover holds is released by the pointer that took it, whatever\n * the buttons say at the boundary, and a pointer that arrived in contact never\n * took it in the first place. Contact is the exception tracked here, not\n * hover: a leave from a pointer this surface never saw enter - mounted under\n * the cursor, say - still counts, since the alternative is state with no way\n * out.\n */\nexport function useHoverGesture(): HoverGesture {\n  const contact = useRef(new Set<number>());\n\n  return useMemo(\n    () => ({\n      enter: (event) => {\n        if (isHoveringPointer(event)) {\n          contact.current.delete(event.pointerId);\n          return true;\n        }\n        contact.current.add(event.pointerId);\n        return false;\n      },\n      leave: (event) => {\n        const arrivedInContact = contact.current.delete(event.pointerId);\n        return !arrivedInContact && event.pointerType !== \"touch\";\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/hooks/use-tap-gesture.ts","type":"util","content":"\"use client\";\n\nimport { useMemo, useRef } from \"react\";\n\n/** What a pointerdown recorded, read back by the click that ends its gesture. */\nexport interface TapRecord<S> {\n  /** Which input started the gesture. */\n  pointerType: string;\n  /** What the surface was showing when it started. */\n  state: S;\n}\n\nexport interface TapGesture<S> {\n  /** Record the gesture a pointerdown starts, with the state it starts in. */\n  start: (event: { pointerType: string }, state: S) => void;\n  /** Read the record and clear it. `null` when no pointer is behind this click. */\n  take: () => TapRecord<S> | null;\n  /** Drop the record: this gesture will never spend it on a click. */\n  drop: () => void;\n}\n\n/**\n * The pointer gesture behind a click, recorded where the click cannot report\n * it. A `click` carries no `pointerType` in the engines that matter, so the\n * `pointerdown` before it is the only thing that says which input activated\n * the control - and whether one did at all, since keyboard activation\n * synthesizes a click with no pointer behind it.\n *\n * State goes in with the record because a click reports that no better: a\n * browser that focuses a control on contact can open the very panel the tap\n * was meant to open, and reading \"is it open\" at click time then undoes it.\n * What the gesture started against is what it acts on.\n *\n * The record is spent by one click and dropped by everything else, because a\n * record that outlives its gesture is worse than none:\n *\n * - A scroll or an OS gesture takes the touch away - `pointercancel`, no click\n *   ever - and the finger would sit in the record until some later click.\n * - That later click is often `Enter` on a keyboard, which arrives with no\n *   pointerdown of its own and would inherit the abandoned finger. A keydown\n *   is the start of a keyboard activation and never part of a tap, so it drops\n *   the record too.\n *\n * Both ends have to be wired by the surface: `drop` on `onPointerCancel` and\n * on `onKeyDown`.\n */\nexport function useTapGesture<S>(): TapGesture<S> {\n  const record = useRef<TapRecord<S> | null>(null);\n\n  return useMemo(\n    () => ({\n      start: (event, state) => {\n        record.current = { pointerType: event.pointerType, state };\n      },\n      take: () => {\n        const spent = record.current;\n        record.current = null;\n        return spent;\n      },\n      drop: () => {\n        record.current = null;\n      },\n    }),\n    [],\n  );\n}\n"},{"path":"lib/sounds/press.ts","type":"util","content":"import { defineSound } from \"./engine\";\n\n/** A physical button: a switch click that settles twice over a soft thump and a little casing ring. */\nexport const pressSound = defineSound({\n  name: \"Press\",\n  duration: 0.1,\n  vary: 0.03,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 2800, q: 1.8, decay: 0.005, gain: 0.5 });\n    v.click({ freq: 4200, q: 2.5, at: 0.011, decay: 0.003, gain: 0.16 });\n    v.strike({ freq: 150, material: \"wood\", bend: 1.5, decay: 0.07, gain: 0.75 });\n    v.strike({ freq: 1250, material: \"plastic\", decay: 0.022, gain: 0.14 });\n  },\n});\n"},{"path":"components/motion/magnetic.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useMotionValue, useReducedMotion, useSpring } from \"motion/react\";\nimport { useRef, type ReactNode } from \"react\";\nimport { SPRING_MOUSE } from \"@/lib/ease\";\nimport { useHoverCapable } from \"@/lib/hooks/use-hover-capable\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface MagneticProps {\n  children: ReactNode;\n  strength?: number;\n  className?: string;\n}\n\nexport function Magnetic({ children, strength = 0.35, className }: MagneticProps) {\n  const ref = useRef<HTMLDivElement>(null);\n  const reduce = useReducedMotion();\n  const canHover = useHoverCapable();\n  // Decorative cursor-follow: skip on touch (phantom hover) and reduced motion.\n  const enabled = !reduce && canHover;\n  const x = useMotionValue(0);\n  const y = useMotionValue(0);\n  const sx = useSpring(x, SPRING_MOUSE);\n  const sy = useSpring(y, SPRING_MOUSE);\n\n  const onMove = (e: React.MouseEvent<HTMLDivElement>) => {\n    const el = ref.current;\n    if (!el || !enabled) return;\n    const rect = el.getBoundingClientRect();\n    x.set((e.clientX - rect.left - rect.width / 2) * strength);\n    y.set((e.clientY - rect.top - rect.height / 2) * strength);\n  };\n\n  const onLeave = () => {\n    x.set(0);\n    y.set(0);\n  };\n\n  return (\n    <motion.div\n      ref={ref}\n      onMouseMove={onMove}\n      onMouseLeave={onLeave}\n      style={{ x: sx, y: sy }}\n      className={cn(\"inline-block\", className)}\n    >\n      {children}\n    </motion.div>\n  );\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/audio-context.ts","type":"util","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"util","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"},{"path":"lib/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"lib/hooks/use-hover-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true only on devices that have a true hover (mouse / trackpad).\n * Touch devices fire phantom `:hover` on tap that sticks until tap-elsewhere\n * - gate hover-only effects (scale lifts, magnetic pulls) behind this.\n */\nexport function useHoverCapable() {\n  const [canHover, setCanHover] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\" || !window.matchMedia) return;\n    const mq = window.matchMedia(\"(hover: hover) and (pointer: fine)\");\n    const update = () => setCanHover(mq.matches);\n    update();\n    mq.addEventListener?.(\"change\", update);\n    return () => mq.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canHover;\n}\n"},{"path":"components/previews/agents/prompt-input.preview.tsx","type":"preview","content":"\"use client\";\n\nimport {\n  Bot,\n  Bug,\n  FileText,\n  ImagePlus,\n  ListChecks,\n  Puzzle,\n  ScanSearch,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { PromptInput } from \"@/components/agents/prompt-input\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useFavicon } from \"@/lib/hooks/use-favicon\";\n\n// Type \"/\" in the input to list these.\nconst COMMANDS = [\n  { value: \"review\", label: \"Review\", description: \"Check the open changes\", icon: <ScanSearch /> },\n  { value: \"fix\", label: \"Fix\", description: \"Repair a failing test\", icon: <Bug /> },\n  { value: \"plan\", label: \"Plan\", description: \"Break the task into steps\", icon: <ListChecks /> },\n  { value: \"summarize\", label: \"Summarize\", description: \"Shorten the thread\", icon: <FileText /> },\n];\n\nfunction ModelLogo({ url }: { url: string }) {\n  const favicon = useFavicon(url);\n\n  if (!favicon.src) return <Bot />;\n\n  return (\n    <img\n      ref={favicon.ref}\n      src={favicon.src}\n      alt=\"\"\n      width={16}\n      height={16}\n      referrerPolicy=\"no-referrer\"\n      className=\"size-4 rounded-sm object-contain\"\n    />\n  );\n}\n\nconst MODELS = [\n  {\n    value: \"gpt-5.2\",\n    label: \"GPT-5.2\",\n    icon: <ModelLogo url=\"https://openai.com\" />,\n  },\n  {\n    value: \"claude-sonnet-4\",\n    label: \"Claude Sonnet 4\",\n    icon: <ModelLogo url=\"https://www.anthropic.com\" />,\n  },\n  {\n    value: \"gemini-3.6-flash\",\n    label: \"Gemini 3.6 Flash\",\n    // gemini.google.com has no /favicon.ico; Google DeepMind ships Gemini.\n    icon: <ModelLogo url=\"https://deepmind.google\" />,\n  },\n  {\n    value: \"grok-4.5\",\n    label: \"Grok 4.5\",\n    icon: <ModelLogo url=\"https://x.ai\" />,\n  },\n  {\n    value: \"mistral-large-3\",\n    label: \"Mistral Large 3\",\n    icon: <ModelLogo url=\"https://mistral.ai\" />,\n  },\n];\n\nconst ACTIONS = [\n  {\n    value: \"image\",\n    label: \"Attach image\",\n    description: \"Add a screenshot or visual reference.\",\n    icon: <ImagePlus />,\n  },\n  {\n    value: \"skill\",\n    label: \"Use a skill\",\n    description: \"Give the agent a specialized workflow.\",\n    icon: <Puzzle />,\n  },\n  {\n    value: \"context\",\n    label: \"Add context\",\n    description: \"Include a file with supporting details.\",\n    icon: <FileText />,\n  },\n];\n\nexport function PromptInputPreview() {\n  const reduce = useReducedMotion() ?? false;\n  const timer = useRef<number | undefined>(undefined);\n  const [loading, setLoading] = useState(false);\n  const [sent, setSent] = useState<string>();\n  const [notice, setNotice] = useState<string>();\n\n  useEffect(\n    () => () => {\n      if (timer.current) window.clearTimeout(timer.current);\n    },\n    [],\n  );\n\n  const submit = (prompt: string) => {\n    setSent(undefined);\n    setNotice(undefined);\n    setLoading(true);\n    timer.current = window.setTimeout(() => {\n      setLoading(false);\n      setSent(prompt);\n    }, 900);\n  };\n\n  const stop = () => {\n    if (timer.current) window.clearTimeout(timer.current);\n    setLoading(false);\n  };\n\n  return (\n    <div className=\"flex h-[360px] w-full max-w-xl flex-col justify-center\">\n      <PromptInput\n        models={MODELS}\n        actions={ACTIONS}\n        defaultModel=\"gpt-5.2\"\n        defaultValue=\"Review the current implementation and suggest the next improvement.\"\n        loading={loading}\n        onSubmit={submit}\n        onStop={stop}\n        onAction={(action) => {\n          const selected = ACTIONS.find((item) => item.value === action);\n          setNotice(selected ? `${selected.label} selected.` : undefined);\n        }}\n        commands={COMMANDS}\n        onCommand={(command) => setNotice(`Command /${command} added.`)}\n      />\n      <div className=\"h-8 px-2 pt-2 text-xs text-muted-foreground\">\n        <AnimatePresence mode=\"wait\">\n          {sent || notice ? (\n            <motion.p\n              key={sent ?? notice}\n              initial={reduce ? { opacity: 1 } : { opacity: 0, y: 3 }}\n              animate={{ opacity: 1, y: 0 }}\n              exit={{ opacity: 0 }}\n              transition={{ duration: reduce ? 0 : 0.18, ease: EASE_OUT }}\n            >\n              {sent ? \"Prompt sent to the selected model.\" : notice}\n            </motion.p>\n          ) : null}\n        </AnimatePresence>\n      </div>\n    </div>\n  );\n}\n"},{"path":"lib/hooks/use-favicon.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useState } from \"react\";\nimport { getFaviconUrl } from \"@/lib/favicon\";\n\n/**\n * Resolves a site favicon and drops it once it is known to be unusable, so\n * callers can draw their own glyph instead of a broken image. Plenty of sites\n * answer `/favicon.ico` with a 403 or 404, and `onError` is not enough to catch\n * it: an image the browser starts loading from server-rendered HTML usually\n * fails before React attaches a handler, and that event is never replayed.\n * `decode()` settles on the image's final state instead of relying on an event\n * firing at the right moment.\n */\nexport function useFavicon(url?: string) {\n  const resolved = url ? getFaviconUrl(url) : null;\n  const [failedSrc, setFailedSrc] = useState<string | null>(null);\n  const src = resolved && resolved !== failedSrc ? resolved : null;\n\n  const ref = useCallback(\n    (img: HTMLImageElement | null) => {\n      if (!img || !src) return;\n\n      let released = false;\n      img.decode().catch(() => {\n        if (!released) setFailedSrc(src);\n      });\n\n      // The node is going away or the source changed; a late rejection then\n      // describes an image we are no longer showing.\n      return () => {\n        released = true;\n      };\n    },\n    [src],\n  );\n\n  return { src, ref };\n}\n"},{"path":"lib/favicon.ts","type":"util","content":"/** Resolve a website URL to its conventional root favicon location. */\nexport function getFaviconUrl(value: string) {\n  try {\n    return new URL(\"/favicon.ico\", value).toString();\n  } catch {\n    return null;\n  }\n}\n"}]}