{"slug":"ai-sidebar","name":"AI Sidebar","description":"A collapsible AI workspace sidebar for folders, projects, files, and bookmarks with keyboard navigation, optimistic moves, inline rename, and overflow-aware labels.","category":"agents","source_url":"https://beui.dev/r/ai-sidebar/raw","detail_url":"https://beui.dev/r/ai-sidebar","raw_url":"https://beui.dev/r/ai-sidebar/raw","page_url":"https://beui.dev/components/agents/ai-sidebar","markdown_url":"https://beui.dev/components/agents/ai-sidebar.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":["./ai-sidebar/messages","./ai-sidebar/resource-row","./ai-sidebar/tree","./ai-sidebar/types","./animated-sidebar/context","./animated-sidebar/menu-button","./animated-sidebar/menu-sub-button","./animated-sidebar/mobile-sidebar","./animated-sidebar/motion","./animated-sidebar/use-is-mobile","./context","./marquee-label","./messages","./motion","./resource-menu-action","./tooltip/grace","./tooltip/positioner","./tooltip/use-position","./tree","./types","./use-position","@/components/agents/ai-sidebar","@/components/motion/animated-sidebar","@/components/motion/popover-morph","@/components/motion/popover-position","@/components/motion/shared-layout-bg","@/components/motion/tooltip","@/components/motion/tooltip-surface","@/lib/ease","@/lib/focusable","@/lib/hooks/use-dismiss","@/lib/hooks/use-focus-trap","@/lib/hooks/use-hover-gesture","@/lib/hooks/use-tap-gesture","@/lib/hooks/use-touch-capable","@/lib/i18n","@/lib/layers","@/lib/merge-refs","@/lib/scroll-lock","@/lib/touch","@/lib/utils"],"install_slugs":["ai-sidebar"],"requires_theme":true,"props":[{"displayName":"AISidebar","props":[{"name":"items","type":"SidebarResource[]","required":false,"defaultValue":null,"description":"The resource tree, for controlled use."},{"name":"defaultItems","type":"SidebarResource[]","required":false,"defaultValue":"[]","description":"The initial resource tree when uncontrolled."},{"name":"onItemsChange","type":"((items: SidebarResource[]) => void)","required":false,"defaultValue":null,"description":"Called with the new tree after a move, rename or rollback."},{"name":"onMove","type":"((move: SidebarResourceMove) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Reject the promise to roll the optimistic move back."},{"name":"onMoveError","type":"((error: unknown, move: SidebarResourceMove) => void)","required":false,"defaultValue":null,"description":"Called with the error and the move when `onMove` rejects."},{"name":"onRename","type":"((item: SidebarResource, label: string) => void | Promise<void>)","required":false,"defaultValue":null,"description":"Called with the item and trimmed new label. Reject to roll it back."},{"name":"activeId","type":"string | null","required":false,"defaultValue":null,"description":"Id of the selected row, for controlled use."},{"name":"defaultActiveId","type":"string | null","required":false,"defaultValue":"null","description":"Id of the initially selected row when uncontrolled. Default: null"},{"name":"onActiveChange","type":"((id: string) => void)","required":false,"defaultValue":null,"description":"Called with the row's id when a row is selected."},{"name":"defaultExpandedIds","type":"string[]","required":false,"defaultValue":"[]","description":"Ids of folders and projects that start expanded."},{"name":"renderIcon","type":"((item: SidebarResource) => ReactNode)","required":false,"defaultValue":null,"description":"Renders a row's icon in place of the built-in kind icon."},{"name":"renderMenu","type":"((item: SidebarResource, controls: SidebarResourceMenuControls) => ReactNode)","required":false,"defaultValue":null,"description":"Renders a row's actions menu, with controls to close, rename and move."},{"name":"ariaLabel","type":"string","required":false,"defaultValue":null,"description":"Accessible name for the tree. Default: \"Resources\""},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes merged onto the tree element."},{"name":"labels","type":"Partial<{ label: string; rename: string; renameItem: string; actions: string; moveUp: string; moveDown: string; moveInto: string; moveOut: string; moveToTop: string; movePending: string; movedBefore: string; ... 5 more ...; unnamedItem: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string."}]}],"types":[{"name":"SidebarResource","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the row, used for selection, expansion and moves."},{"name":"label","type":"string","required":true,"description":"Name shown in the row and edited on rename."},{"name":"kind","type":"SidebarResourceKind","required":true,"description":"Picks the row icon; folders and projects can hold children."},{"name":"children","type":"SidebarResource[]","required":false,"description":"Nested rows shown when a folder or project is expanded."},{"name":"disabled","type":"boolean","required":false,"description":"Dims the row and blocks selecting, renaming, dragging and dropping into it."}]},{"name":"SidebarResourceMove","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"itemId","type":"string","required":true,"description":"Id of the row being moved."},{"name":"targetId","type":"string | null","required":true,"description":"Id of the row it lands next to or inside, or null for the end of the root."},{"name":"position","type":"SidebarResourceDropPosition","required":true,"description":"Where the row lands relative to the target."}]},{"name":"SidebarResourceMenuControls","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"close","type":"() => void","required":true,"description":"Closes the row menu."},{"name":"rename","type":"() => void","required":true,"description":"Closes the menu and starts renaming the row in place."},{"name":"moves","type":"SidebarResourceMoveCommands","required":true,"description":"The moves this row can make right now."}]},{"name":"SidebarResourceMoveCommands","file":"components/agents/ai-sidebar/types.ts","fields":[{"name":"up","type":"() => void","required":false,"description":"Moves the row above the row before it."},{"name":"down","type":"() => void","required":false,"description":"Moves the row below the row after it."},{"name":"into","type":"{ label: string; run: () => void }","required":false,"description":"Moves the row into the folder or project above it, named by `label`."},{"name":"out","type":"() => void","required":false,"description":"Moves the row out of its parent, just after it."}]}],"files":[{"path":"components/agents/ai-sidebar.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/agents/ai-sidebar\n\nimport { AnimatePresence } from \"motion/react\";\nimport {\n  type KeyboardEvent,\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport { type AISidebarMessages, aiSidebarMessages } from \"./ai-sidebar/messages\";\nimport { ResourceRow } from \"./ai-sidebar/resource-row\";\nimport {\n  canContain,\n  containsResource,\n  findResource,\n  flattenResources,\n  moveResource,\n  renameResource,\n} from \"./ai-sidebar/tree\";\nimport type {\n  AISidebarProps,\n  DropTarget,\n  FlatResource,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceMove,\n  SidebarResourceMoveCommands,\n} from \"./ai-sidebar/types\";\n\nexport { type AISidebarMessages, aiSidebarMessages } from \"./ai-sidebar/messages\";\nexport type {\n  AISidebarProps,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceKind,\n  SidebarResourceMenuControls,\n  SidebarResourceMove,\n  SidebarResourceMoveCommands,\n} from \"./ai-sidebar/types\";\n\nconst MOVED_MESSAGE = {\n  before: \"movedBefore\",\n  inside: \"movedInside\",\n  after: \"movedAfter\",\n} as const satisfies Record<SidebarResourceDropPosition, keyof AISidebarMessages>;\n\nexport function AISidebar({\n  items,\n  defaultItems = [],\n  onItemsChange,\n  onMove,\n  onMoveError,\n  onRename,\n  activeId,\n  defaultActiveId = null,\n  onActiveChange,\n  defaultExpandedIds = [],\n  renderIcon,\n  renderMenu,\n  ariaLabel,\n  className,\n  labels,\n}: AISidebarProps) {\n  const t = useMessages(\"aiSidebar\", aiSidebarMessages, labels);\n  const [internalItems, setInternalItems] = useState(defaultItems);\n  // A move shows at once. When `items` is controlled, it shows on top of the\n  // items it was made from until the parent passes new ones.\n  const [optimistic, setOptimistic] = useState<{\n    base: SidebarResource[];\n    items: SidebarResource[];\n  } | null>(null);\n  const [internalActiveId, setInternalActiveId] = useState(defaultActiveId);\n  const [expandedIds, setExpandedIds] = useState(\n    () => new Set(defaultExpandedIds),\n  );\n  const [focusedId, setFocusedId] = useState<string | null>(\n    activeId ?? defaultActiveId,\n  );\n  const [draggingId, setDraggingId] = useState<string | null>(null);\n  const [dropTarget, setDropTarget] = useState<DropTarget | null>(null);\n  const [menuOpenId, setMenuOpenId] = useState<string | null>(null);\n  const [renamingId, setRenamingId] = useState<string | null>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const rowRefs = useRef(new Map<string, HTMLDivElement>());\n  const movePendingRef = useRef(false);\n  if (optimistic && optimistic.base !== items) setOptimistic(null);\n  const renderedItems =\n    items === undefined\n      ? internalItems\n      : optimistic?.base === items\n        ? optimistic.items\n        : items;\n  const selectedId = activeId !== undefined ? activeId : internalActiveId;\n\n  const flat = useMemo(\n    () => flattenResources(renderedItems, expandedIds),\n    [expandedIds, renderedItems],\n  );\n\n  // Which row carries the roving tabindex is resolved during render, never in\n  // a passive effect: an effect lands after the browser paints, so the first\n  // commit - and, on a server-rendered page, the markup itself - would have no\n  // tabbable row and Tab would skip the whole tree. The same hole opens again\n  // whenever a collapse or a rolled-back move takes the focused row out of it.\n  const focusedRow =\n    focusedId !== null && flat.some((row) => row.item.id === focusedId)\n      ? focusedId\n      : (flat[0]?.item.id ?? null);\n  if (focusedId !== focusedRow) setFocusedId(focusedRow);\n\n  useEffect(() => {\n    if (!menuOpenId) return;\n    const frame = requestAnimationFrame(() => {\n      const menus = Array.from(\n        document.querySelectorAll<HTMLElement>(\"[data-sidebar-resource-menu]\"),\n      );\n      menus\n        .find((menu) => menu.dataset.sidebarResourceMenu === menuOpenId)\n        ?.querySelector<HTMLElement>(\"button, a[href]\")\n        ?.focus();\n    });\n    return () => cancelAnimationFrame(frame);\n  }, [menuOpenId]);\n\n  const updateItems = useCallback(\n    (next: SidebarResource[]) => {\n      if (items === undefined) setInternalItems(next);\n      else setOptimistic(next === items ? null : { base: items, items: next });\n      onItemsChange?.(next);\n    },\n    [items, onItemsChange],\n  );\n\n  const performMove = useCallback(\n    async (move: SidebarResourceMove) => {\n      if (movePendingRef.current) {\n        setAnnouncement(t(\"movePending\"));\n        return;\n      }\n      const before = renderedItems;\n      const next = moveResource(before, move);\n      if (!next || next === before) return;\n\n      movePendingRef.current = true;\n      updateItems(next);\n      setDropTarget(null);\n      setDraggingId(null);\n      const moved = findResource(before, move.itemId);\n      const target = move.targetId ? findResource(before, move.targetId) : null;\n      const item = moved?.label ?? t(\"unnamedItem\");\n      setAnnouncement(\n        target\n          ? t(MOVED_MESSAGE[move.position], { item, target: target.label })\n          : t(\"movedToTop\", { item }),\n      );\n\n      try {\n        await onMove?.(move);\n      } catch (error) {\n        updateItems(before);\n        setAnnouncement(t(\"moveFailed\", { item }));\n        onMoveError?.(error, move);\n      } finally {\n        movePendingRef.current = false;\n      }\n    },\n    [onMove, onMoveError, renderedItems, t, updateItems],\n  );\n\n  const focusRow = useCallback((id: string) => {\n    setFocusedId(id);\n    requestAnimationFrame(() => rowRefs.current.get(id)?.focus());\n  }, []);\n\n  const select = useCallback(\n    (id: string) => {\n      if (activeId === undefined) setInternalActiveId(id);\n      onActiveChange?.(id);\n    },\n    [activeId, onActiveChange],\n  );\n\n  const toggle = useCallback((id: string) => {\n    setExpandedIds((current) => {\n      const next = new Set(current);\n      if (next.has(id)) next.delete(id);\n      else next.add(id);\n      return next;\n    });\n  }, []);\n\n  // The same four moves `Alt+Shift+Arrow` performs, handed to the row menu so\n  // they survive on a device with no drag and no modifier keys.\n  const moveCommands = useCallback(\n    (row: FlatResource): SidebarResourceMoveCommands => {\n      if (row.item.disabled) return {};\n      const index = flat.findIndex(({ item }) => item.id === row.item.id);\n      const previous = flat[index - 1];\n      const next = flat[index + 1];\n      const parentId = row.parentId;\n      const commands: SidebarResourceMoveCommands = {};\n\n      if (previous) {\n        commands.up = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: previous.item.id,\n            position: \"before\",\n          });\n      }\n      if (next) {\n        commands.down = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: next.item.id,\n            position: \"after\",\n          });\n      }\n      // Only offer the reparent when it lands somewhere new - the row above a\n      // folder's first child is the folder it already lives in.\n      if (previous && canContain(previous.item) && previous.item.id !== parentId) {\n        commands.into = {\n          label: previous.item.label,\n          run: () => {\n            setExpandedIds((current) => new Set(current).add(previous.item.id));\n            void performMove({\n              itemId: row.item.id,\n              targetId: previous.item.id,\n              position: \"inside\",\n            });\n          },\n        };\n      }\n      if (parentId) {\n        commands.out = () =>\n          void performMove({\n            itemId: row.item.id,\n            targetId: parentId,\n            position: \"after\",\n          });\n      }\n\n      return commands;\n    },\n    [flat, performMove],\n  );\n\n  const handleKeyDown = useCallback(\n    (event: KeyboardEvent<HTMLDivElement>, row: FlatResource) => {\n      const index = flat.findIndex(({ item }) => item.id === row.item.id);\n      const previous = flat[index - 1];\n      const next = flat[index + 1];\n      const moveModifier = event.altKey && event.shiftKey;\n\n      if (event.key === \"ArrowDown\" && !moveModifier && next) {\n        event.preventDefault();\n        focusRow(next.item.id);\n        return;\n      }\n      if (event.key === \"ArrowUp\" && !moveModifier && previous) {\n        event.preventDefault();\n        focusRow(previous.item.id);\n        return;\n      }\n      if (event.key === \"Home\" && flat[0]) {\n        event.preventDefault();\n        focusRow(flat[0].item.id);\n        return;\n      }\n      if (event.key === \"End\" && flat.at(-1)) {\n        event.preventDefault();\n        focusRow(flat.at(-1)?.item.id ?? row.item.id);\n        return;\n      }\n\n      if (row.item.disabled) {\n        if (event.key === \"ArrowLeft\" && row.parentId) {\n          event.preventDefault();\n          focusRow(row.parentId);\n        } else if (\n          moveModifier ||\n          [\"ArrowRight\", \"Enter\", \" \", \"F2\", \"ContextMenu\"].includes(\n            event.key,\n          ) ||\n          (event.shiftKey && event.key === \"F10\")\n        ) {\n          event.preventDefault();\n        }\n        return;\n      }\n\n      if (moveModifier && event.key === \"ArrowUp\" && previous) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: previous.item.id, position: \"before\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowDown\" && next) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: next.item.id, position: \"after\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowRight\" && previous && canContain(previous.item)) {\n        event.preventDefault();\n        setExpandedIds((current) => new Set(current).add(previous.item.id));\n        void performMove({ itemId: row.item.id, targetId: previous.item.id, position: \"inside\" });\n        return;\n      }\n      if (moveModifier && event.key === \"ArrowLeft\" && row.parentId) {\n        event.preventDefault();\n        void performMove({ itemId: row.item.id, targetId: row.parentId, position: \"after\" });\n        return;\n      }\n\n      if (event.key === \"ArrowRight\" && canContain(row.item)) {\n        event.preventDefault();\n        if (!expandedIds.has(row.item.id)) toggle(row.item.id);\n        else if (next?.parentId === row.item.id) focusRow(next.item.id);\n      } else if (event.key === \"ArrowLeft\") {\n        event.preventDefault();\n        if (expandedIds.has(row.item.id)) toggle(row.item.id);\n        else if (row.parentId) focusRow(row.parentId);\n      } else if (event.key === \"Enter\" || event.key === \" \") {\n        event.preventDefault();\n        if (canContain(row.item)) toggle(row.item.id);\n        else select(row.item.id);\n      } else if (event.key === \"F2\") {\n        event.preventDefault();\n        setRenamingId(row.item.id);\n      } else if (event.key === \"ContextMenu\" || (event.shiftKey && event.key === \"F10\")) {\n        event.preventDefault();\n        setMenuOpenId(row.item.id);\n      }\n    },\n    [expandedIds, flat, focusRow, performMove, select, toggle],\n  );\n\n  return (\n    <>\n      <div\n      role=\"tree\"\n      aria-label={ariaLabel ?? t(\"label\")}\n      aria-multiselectable=\"false\"\n      onDragOver={(event) => {\n        if (!draggingId || event.target !== event.currentTarget) return;\n        event.preventDefault();\n        setDropTarget({ id: null, position: \"after\" });\n      }}\n      onDrop={(event) => {\n        event.preventDefault();\n        if (draggingId && dropTarget) {\n          void performMove({\n            itemId: draggingId,\n            targetId: dropTarget.id,\n            position: dropTarget.position,\n          });\n        }\n      }}\n      className={cn(\n        \"relative flex min-w-0 flex-col gap-0.5 [overflow-anchor:none] group-data-[state=collapsed]/sidebar:hidden\",\n        draggingId && \"select-none pb-9\",\n        className,\n      )}\n    >\n      <AnimatePresence initial={false}>\n        {flat.map((row) => (\n          <ResourceRow\n            key={row.item.id}\n            row={row}\n            active={selectedId === row.item.id}\n            expanded={expandedIds.has(row.item.id)}\n            focused={focusedRow === row.item.id}\n            draggingId={draggingId}\n            dropTarget={dropTarget}\n            menuOpen={menuOpenId === row.item.id}\n            moves={moveCommands(row)}\n            renaming={renamingId === row.item.id}\n            onFocus={() => setFocusedId(row.item.id)}\n            onSelect={() => select(row.item.id)}\n            onToggle={() => toggle(row.item.id)}\n            onKeyDown={(event) => handleKeyDown(event, row)}\n            onRenameStart={() => setRenamingId(row.item.id)}\n            onRenameCancel={() => setRenamingId(null)}\n            onRenameCommit={(label) => {\n              const trimmed = label.trim();\n              setRenamingId(null);\n              if (!trimmed || trimmed === row.item.label) return;\n              const before = renderedItems;\n              updateItems(renameResource(before, row.item.id, trimmed));\n              void Promise.resolve(onRename?.(row.item, trimmed)).catch(() => {\n                updateItems(before);\n                setAnnouncement(\n                  t(\"renameFailed\", { item: row.item.label }),\n                );\n              });\n            }}\n            onMenuOpenChange={(open) => {\n              setMenuOpenId(open ? row.item.id : null);\n              if (!open) focusRow(row.item.id);\n            }}\n            onDragStart={(event, id) => {\n              setDraggingId(id);\n              event.dataTransfer.effectAllowed = \"move\";\n              event.dataTransfer.setData(\"text/plain\", id);\n            }}\n            onDragEnd={() => {\n              setDraggingId(null);\n              setDropTarget(null);\n            }}\n            onDragOver={(event, targetRow) => {\n              if (!draggingId || draggingId === targetRow.item.id) return;\n              const source = findResource(renderedItems, draggingId);\n              if (source && containsResource(source, targetRow.item.id)) return;\n              event.preventDefault();\n              event.stopPropagation();\n              const rect = event.currentTarget.getBoundingClientRect();\n              const ratio = (event.clientY - rect.top) / rect.height;\n              const position =\n                !targetRow.item.disabled &&\n                canContain(targetRow.item) &&\n                ratio >= 0.25 &&\n                ratio <= 0.75\n                  ? \"inside\"\n                  : ratio < 0.5\n                    ? \"before\"\n                    : \"after\";\n              setDropTarget({ id: targetRow.item.id, position });\n            }}\n            onDrop={(event) => {\n              event.preventDefault();\n              event.stopPropagation();\n              if (draggingId && dropTarget) {\n                void performMove({\n                  itemId: draggingId,\n                  targetId: dropTarget.id,\n                  position: dropTarget.position,\n                });\n              }\n            }}\n            renderIcon={renderIcon}\n            renderMenu={renderMenu}\n            t={t}\n            setRef={(node) => {\n              if (node) rowRefs.current.set(row.item.id, node);\n              else rowRefs.current.delete(row.item.id);\n            }}\n          />\n        ))}\n      </AnimatePresence>\n\n      {draggingId ? (\n        <div\n          aria-hidden=\"true\"\n          data-active={dropTarget?.id === null || undefined}\n          className=\"absolute inset-x-1 bottom-0 flex h-8 items-center justify-center rounded-lg border border-dashed border-border text-[11px] text-muted-foreground data-[active=true]:border-primary/50 data-[active=true]:bg-muted data-[active=true]:text-foreground\"\n        >\n          {t(\"moveToTop\")}\n        </div>\n      ) : null}\n\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </>\n  );\n}\n"},{"path":"components/agents/ai-sidebar/messages.ts","type":"util","content":"export const aiSidebarMessages = {\n  label: \"Resources\",\n  rename: \"Rename\",\n  renameItem: \"Rename {item}\",\n  actions: \"Actions for {item}\",\n  moveUp: \"Move up\",\n  moveDown: \"Move down\",\n  moveInto: \"Move into {target}\",\n  moveOut: \"Move out\",\n  moveToTop: \"Move to top level\",\n  movePending: \"Wait for the current move to finish.\",\n  movedBefore: \"Moved {item} before {target}.\",\n  movedInside: \"Moved {item} inside {target}.\",\n  movedAfter: \"Moved {item} after {target}.\",\n  movedToTop: \"Moved {item} to the top level.\",\n  moveFailed: \"Move failed. {item} was restored.\",\n  renameFailed: \"Rename failed. {item} was restored.\",\n  unnamedItem: \"item\",\n};\n\nexport type AISidebarMessages = typeof aiSidebarMessages;\n\nexport type Translate = (\n  key: keyof AISidebarMessages,\n  values?: Record<string, string | number>,\n) => string;\n"},{"path":"components/agents/ai-sidebar/resource-row.tsx","type":"util","content":"\"use client\";\n\nimport {\n  ArrowDown,\n  ArrowUp,\n  Bookmark,\n  FileText,\n  Folder,\n  FolderInput,\n  FolderOpen,\n  MoreHorizontal,\n  Pencil,\n  Undo2,\n} from \"lucide-react\";\nimport { motion, useReducedMotion } from \"motion/react\";\nimport {\n  type ComponentProps,\n  type DragEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  MorphPopover,\n  MorphPopoverContent,\n  MorphPopoverTrigger,\n} from \"@/components/motion/popover-morph\";\nimport { Tooltip } from \"@/components/motion/tooltip\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useTouchCapable } from \"@/lib/hooks/use-touch-capable\";\nimport { cn } from \"@/lib/utils\";\nimport { MarqueeLabel } from \"./marquee-label\";\nimport type { Translate } from \"./messages\";\nimport { ResourceMenuAction } from \"./resource-menu-action\";\nimport { canContain } from \"./tree\";\nimport type {\n  AISidebarProps,\n  DropTarget,\n  FlatResource,\n  SidebarResource,\n  SidebarResourceMoveCommands,\n} from \"./types\";\n\nfunction defaultIcon(item: SidebarResource, expanded: boolean) {\n  const Icon =\n    item.kind === \"folder\" || item.kind === \"project\"\n      ? expanded\n        ? FolderOpen\n        : Folder\n      : item.kind === \"bookmark\"\n          ? Bookmark\n          : FileText;\n  return <Icon className=\"size-4\" />;\n}\n\ninterface ResourceRowProps {\n  row: FlatResource;\n  active: boolean;\n  expanded: boolean;\n  focused: boolean;\n  draggingId: string | null;\n  dropTarget: DropTarget | null;\n  menuOpen: boolean;\n  moves: SidebarResourceMoveCommands;\n  renaming: boolean;\n  onDragEnd: () => void;\n  onDragOver: (event: DragEvent<HTMLDivElement>, row: FlatResource) => void;\n  onDragStart: (event: DragEvent<HTMLDivElement>, id: string) => void;\n  onDrop: (event: DragEvent<HTMLDivElement>) => void;\n  onFocus: () => void;\n  onKeyDown: (event: KeyboardEvent<HTMLDivElement>) => void;\n  onMenuOpenChange: (open: boolean) => void;\n  onRenameCancel: () => void;\n  onRenameCommit: (label: string) => void;\n  onRenameStart: () => void;\n  onSelect: () => void;\n  onToggle: () => void;\n  renderIcon?: (item: SidebarResource) => ReactNode;\n  renderMenu?: AISidebarProps[\"renderMenu\"];\n  setRef: (node: HTMLDivElement | null) => void;\n  t: Translate;\n}\n\nexport function ResourceRow({\n  row,\n  active,\n  expanded,\n  focused,\n  draggingId,\n  dropTarget,\n  menuOpen,\n  moves,\n  renaming,\n  onDragEnd,\n  onDragOver,\n  onDragStart,\n  onDrop,\n  onFocus,\n  onKeyDown,\n  onMenuOpenChange,\n  onRenameCancel,\n  onRenameCommit,\n  onRenameStart,\n  onSelect,\n  onToggle,\n  renderIcon,\n  renderMenu,\n  setRef,\n  t,\n}: ResourceRowProps) {\n  const reduce = useReducedMotion() ?? false;\n  const canTouch = useTouchCapable();\n  const [hovered, setHovered] = useState(false);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const skipRenameBlurRef = useRef(false);\n  const draggedRef = useRef(false);\n  const [draft, setDraft] = useState(row.item.label);\n  const acceptsChildren = canContain(row.item);\n  const isDragging = draggingId === row.item.id;\n  const dropPosition = dropTarget?.id === row.item.id ? dropTarget.position : null;\n\n  useEffect(() => {\n    if (!renaming) return;\n    skipRenameBlurRef.current = false;\n    setDraft(row.item.label);\n    requestAnimationFrame(() => {\n      inputRef.current?.focus();\n      inputRef.current?.select();\n    });\n  }, [renaming, row.item.label]);\n\n  const runFromMenu = (action: () => void) => () => {\n    onMenuOpenChange(false);\n    action();\n  };\n\n  const menu = renderMenu?.(row.item, {\n    close: () => onMenuOpenChange(false),\n    rename: () => {\n      onMenuOpenChange(false);\n      onRenameStart();\n    },\n    moves,\n  }) ?? (\n    <>\n      <ResourceMenuAction icon={Pencil} onSelect={runFromMenu(onRenameStart)}>\n        {t(\"rename\")}\n      </ResourceMenuAction>\n      {moves.up || moves.down || moves.into || moves.out ? (\n        <div aria-hidden=\"true\" className=\"my-1 h-px bg-border\" />\n      ) : null}\n      {moves.up ? (\n        <ResourceMenuAction icon={ArrowUp} onSelect={runFromMenu(moves.up)}>\n          {t(\"moveUp\")}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.down ? (\n        <ResourceMenuAction icon={ArrowDown} onSelect={runFromMenu(moves.down)}>\n          {t(\"moveDown\")}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.into ? (\n        <ResourceMenuAction\n          icon={FolderInput}\n          onSelect={runFromMenu(moves.into.run)}\n        >\n          {t(\"moveInto\", { target: moves.into.label })}\n        </ResourceMenuAction>\n      ) : null}\n      {moves.out ? (\n        <ResourceMenuAction icon={Undo2} onSelect={runFromMenu(moves.out)}>\n          {t(\"moveOut\")}\n        </ResourceMenuAction>\n      ) : null}\n    </>\n  );\n\n  return (\n    <motion.div\n      ref={setRef}\n      layout=\"position\"\n      transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n      role=\"treeitem\"\n      aria-level={row.depth + 1}\n      aria-selected={acceptsChildren ? undefined : active}\n      aria-expanded={acceptsChildren ? expanded : undefined}\n      aria-disabled={row.item.disabled || undefined}\n      tabIndex={focused ? 0 : -1}\n      draggable={!row.item.disabled && !renaming}\n      data-menu-open={menuOpen || undefined}\n      data-drop={dropPosition ?? undefined}\n      data-dragging={isDragging || undefined}\n      onFocus={onFocus}\n      onKeyDown={onKeyDown}\n      onClick={(event) => {\n        if (\n          event.defaultPrevented ||\n          draggedRef.current ||\n          renaming ||\n          row.item.disabled\n        )\n          return;\n        if (acceptsChildren) onToggle();\n        else onSelect();\n      }}\n      onDoubleClick={(event) => {\n        if (acceptsChildren || row.item.disabled) return;\n        event.preventDefault();\n        onRenameStart();\n      }}\n      onMouseEnter={() => setHovered(true)}\n      onMouseLeave={() => setHovered(false)}\n      onDragStartCapture={(event) => {\n        draggedRef.current = true;\n        onDragStart(event, row.item.id);\n      }}\n      onDragEndCapture={() => {\n        onDragEnd();\n        requestAnimationFrame(() => {\n          draggedRef.current = false;\n        });\n      }}\n      onDragOver={(event) => onDragOver(event, row)}\n      onDrop={onDrop}\n      className={cn(\n        \"group/resource relative flex min-h-9 min-w-0 cursor-pointer items-center gap-2.5 rounded-xl pr-3 text-sm outline-none\",\n        \"text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\",\n        \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset\",\n        \"data-[menu-open=true]:bg-muted data-[menu-open=true]:text-foreground\",\n        \"data-[dragging=true]:opacity-40\",\n        \"data-[drop=inside]:bg-muted data-[drop=inside]:ring-1 data-[drop=inside]:ring-primary/45\",\n        \"data-[drop=before]:before:absolute data-[drop=before]:before:-top-0.5 data-[drop=before]:before:right-2 data-[drop=before]:before:left-2 data-[drop=before]:before:h-0.5 data-[drop=before]:before:rounded-full data-[drop=before]:before:bg-primary\",\n        \"data-[drop=after]:after:absolute data-[drop=after]:after:-bottom-0.5 data-[drop=after]:after:right-2 data-[drop=after]:after:left-2 data-[drop=after]:after:h-0.5 data-[drop=after]:after:rounded-full data-[drop=after]:after:bg-primary\",\n        !acceptsChildren && active && \"bg-muted text-foreground\",\n        row.item.disabled && \"cursor-not-allowed opacity-45\",\n      )}\n      style={{ paddingLeft: `${12 + row.depth * 16}px` }}\n    >\n      <span aria-hidden=\"true\" className=\"grid size-5 shrink-0 place-items-center\">\n        {renderIcon?.(row.item) ?? defaultIcon(row.item, expanded)}\n      </span>\n\n      {renaming ? (\n        <input\n          ref={inputRef}\n          value={draft}\n          aria-label={t(\"renameItem\", { item: row.item.label })}\n          onChange={(event) => setDraft(event.target.value)}\n          draggable={false}\n          onClick={(event) => event.stopPropagation()}\n          onDoubleClick={(event) => event.stopPropagation()}\n          onBlur={() => {\n            if (!skipRenameBlurRef.current) onRenameCommit(draft);\n          }}\n          onKeyDown={(event) => {\n            event.stopPropagation();\n            if (event.key === \"Enter\") {\n              skipRenameBlurRef.current = true;\n              onRenameCommit(draft);\n            }\n            if (event.key === \"Escape\") {\n              skipRenameBlurRef.current = true;\n              onRenameCancel();\n            }\n          }}\n          className=\"mx-1 h-7 min-w-0 flex-1 rounded-full border border-border bg-background px-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n        />\n      ) : (\n        <MarqueeLabel active={hovered || menuOpen}>{row.item.label}</MarqueeLabel>\n      )}\n\n      {!renaming && !row.item.disabled ? (\n        <MorphPopover\n          open={menuOpen}\n          onOpenChange={onMenuOpenChange}\n        >\n          <Tooltip content={menuOpen ? null : t(\"actions\", { item: row.item.label })} side=\"top\">\n            <ActionsTrigger\n              aria-label={t(\"actions\", { item: row.item.label })}\n              className={cn(\n                // A finger never hovers, and this menu is the only path to\n                // rename and move without a drag - keep it on screen there.\n                canTouch ? \"opacity-100\" : \"opacity-0\",\n              )}\n            />\n          </Tooltip>\n          <MorphPopoverContent\n            side=\"bottom\"\n            align=\"end\"\n            sideOffset={8}\n            className=\"w-40 p-2\"\n          >\n            <div data-sidebar-resource-menu={row.item.id}>{menu}</div>\n          </MorphPopoverContent>\n        </MorphPopover>\n      ) : null}\n    </motion.div>\n  );\n}\n\n/**\n * The row's \"…\" button. Its own component so the tooltip around it and the\n * popover trigger inside both reach the button.\n */\nfunction ActionsTrigger({ className, ...props }: ComponentProps<\"button\">) {\n  return (\n    <MorphPopoverTrigger>\n      <button\n        type=\"button\"\n        draggable={false}\n        tabIndex={-1}\n        {...props}\n        onClick={(event) => {\n          props.onClick?.(event);\n          event.stopPropagation();\n        }}\n        className={cn(\n          \"grid size-7 shrink-0 place-items-center rounded-full outline-none transition-opacity hover:bg-foreground/5 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring group-hover/resource:opacity-100 group-data-[menu-open=true]/resource:opacity-100\",\n          className,\n        )}\n      >\n        <MoreHorizontal aria-hidden=\"true\" className=\"size-4\" />\n      </button>\n    </MorphPopoverTrigger>\n  );\n}\n"},{"path":"components/agents/ai-sidebar/tree.ts","type":"util","content":"import type {\n  FlatResource,\n  SidebarResource,\n  SidebarResourceDropPosition,\n  SidebarResourceMove,\n} from \"./types\";\n\nexport function canContain(item: SidebarResource) {\n  return item.kind === \"folder\" || item.kind === \"project\";\n}\n\nexport function flattenResources(\n  items: SidebarResource[],\n  expanded: Set<string>,\n  depth = 0,\n  parentId: string | null = null,\n): FlatResource[] {\n  return items.flatMap((item) => {\n    const row = { item, depth, parentId };\n    if (!item.children?.length || !expanded.has(item.id)) return [row];\n    return [\n      row,\n      ...flattenResources(item.children, expanded, depth + 1, item.id),\n    ];\n  });\n}\n\nexport function findResource(\n  items: SidebarResource[],\n  id: string,\n): SidebarResource | undefined {\n  for (const item of items) {\n    if (item.id === id) return item;\n    const child = item.children ? findResource(item.children, id) : undefined;\n    if (child) return child;\n  }\n}\n\nexport function containsResource(item: SidebarResource, id: string): boolean {\n  return (\n    item.id === id ||\n    item.children?.some((child) => containsResource(child, id)) === true\n  );\n}\n\nfunction removeResource(\n  items: SidebarResource[],\n  id: string,\n): { items: SidebarResource[]; removed?: SidebarResource } {\n  let removed: SidebarResource | undefined;\n  const next: SidebarResource[] = [];\n\n  for (const item of items) {\n    if (item.id === id) {\n      removed = item;\n      continue;\n    }\n\n    if (item.children?.length) {\n      const childResult = removeResource(item.children, id);\n      if (childResult.removed) {\n        removed = childResult.removed;\n        next.push({ ...item, children: childResult.items });\n        continue;\n      }\n    }\n\n    next.push(item);\n  }\n\n  return { items: next, removed };\n}\n\nfunction insertResource(\n  items: SidebarResource[],\n  resource: SidebarResource,\n  targetId: string | null,\n  position: SidebarResourceDropPosition,\n): SidebarResource[] {\n  if (targetId === null) return [...items, resource];\n\n  const next: SidebarResource[] = [];\n  for (const item of items) {\n    if (item.id === targetId) {\n      if (position === \"before\") next.push(resource, item);\n      else if (position === \"after\") next.push(item, resource);\n      else next.push({ ...item, children: [...(item.children ?? []), resource] });\n      continue;\n    }\n\n    if (item.children?.length) {\n      next.push({\n        ...item,\n        children: insertResource(item.children, resource, targetId, position),\n      });\n    } else {\n      next.push(item);\n    }\n  }\n  return next;\n}\n\nexport function moveResource(\n  items: SidebarResource[],\n  move: SidebarResourceMove,\n): SidebarResource[] | null {\n  const source = findResource(items, move.itemId);\n  if (!source || source.disabled) return null;\n  if (move.targetId && containsResource(source, move.targetId)) return null;\n\n  const target = move.targetId ? findResource(items, move.targetId) : undefined;\n  if (\n    move.position === \"inside\" &&\n    (!target || target.disabled || !canContain(target))\n  )\n    return null;\n\n  const removed = removeResource(items, move.itemId);\n  if (!removed.removed) return null;\n  return insertResource(\n    removed.items,\n    removed.removed,\n    move.targetId,\n    move.position,\n  );\n}\n\nexport function renameResource(\n  items: SidebarResource[],\n  id: string,\n  label: string,\n): SidebarResource[] {\n  return items.map((item) => ({\n    ...item,\n    label: item.id === id ? label : item.label,\n    children: item.children\n      ? renameResource(item.children, id, label)\n      : undefined,\n  }));\n}\n"},{"path":"components/agents/ai-sidebar/types.ts","type":"util","content":"import type { ReactNode } from \"react\";\nimport type { AISidebarMessages } from \"./messages\";\n\nexport type SidebarResourceKind =\n  | \"folder\"\n  | \"project\"\n  | \"file\"\n  | \"bookmark\";\n\nexport interface SidebarResource {\n  /** Unique key for the row, used for selection, expansion and moves. */\n  id: string;\n  /** Name shown in the row and edited on rename. */\n  label: string;\n  /** Picks the row icon; folders and projects can hold children. */\n  kind: SidebarResourceKind;\n  /** Nested rows shown when a folder or project is expanded. */\n  children?: SidebarResource[];\n  /** Dims the row and blocks selecting, renaming, dragging and dropping into it. */\n  disabled?: boolean;\n}\n\nexport type SidebarResourceDropPosition = \"before\" | \"inside\" | \"after\";\n\nexport interface SidebarResourceMove {\n  /** Id of the row being moved. */\n  itemId: string;\n  /** Id of the row it lands next to or inside, or null for the end of the root. */\n  targetId: string | null;\n  /** Where the row lands relative to the target. */\n  position: SidebarResourceDropPosition;\n}\n\n/**\n * The moves this row can make right now, the same four the keyboard offers on\n * `Alt+Shift+Arrow`. A pointer drag is the fast path for them; a finger has no\n * drag to give, so the row menu carries them too. Absent keys are moves this\n * row cannot make from where it sits.\n */\nexport interface SidebarResourceMoveCommands {\n  /** Moves the row above the row before it. */\n  up?: () => void;\n  /** Moves the row below the row after it. */\n  down?: () => void;\n  /** Moves the row into the folder or project above it, named by `label`. */\n  into?: { label: string; run: () => void };\n  /** Moves the row out of its parent, just after it. */\n  out?: () => void;\n}\n\nexport interface SidebarResourceMenuControls {\n  /** Closes the row menu. */\n  close: () => void;\n  /** Closes the menu and starts renaming the row in place. */\n  rename: () => void;\n  /** The moves this row can make right now. */\n  moves: SidebarResourceMoveCommands;\n}\n\nexport interface AISidebarProps {\n  /** The resource tree, for controlled use. */\n  items?: SidebarResource[];\n  /** The initial resource tree when uncontrolled. */\n  defaultItems?: SidebarResource[];\n  /** Called with the new tree after a move, rename or rollback. */\n  onItemsChange?: (items: SidebarResource[]) => void;\n  /** Reject the promise to roll the optimistic move back. */\n  onMove?: (move: SidebarResourceMove) => void | Promise<void>;\n  /** Called with the error and the move when `onMove` rejects. */\n  onMoveError?: (error: unknown, move: SidebarResourceMove) => void;\n  /** Called with the item and trimmed new label. Reject to roll it back. */\n  onRename?: (item: SidebarResource, label: string) => void | Promise<void>;\n  /** Id of the selected row, for controlled use. */\n  activeId?: string | null;\n  /** Id of the initially selected row when uncontrolled. Default: null */\n  defaultActiveId?: string | null;\n  /** Called with the row's id when a row is selected. */\n  onActiveChange?: (id: string) => void;\n  /** Ids of folders and projects that start expanded. */\n  defaultExpandedIds?: string[];\n  /** Renders a row's icon in place of the built-in kind icon. */\n  renderIcon?: (item: SidebarResource) => ReactNode;\n  /** Renders a row's actions menu, with controls to close, rename and move. */\n  renderMenu?: (\n    item: SidebarResource,\n    controls: SidebarResourceMenuControls,\n  ) => ReactNode;\n  /** Accessible name for the tree. Default: \"Resources\" */\n  ariaLabel?: string;\n  /** Classes merged onto the tree element. */\n  className?: string;\n  /** Override any built-in string. */\n  labels?: Partial<AISidebarMessages>;\n}\n\nexport interface FlatResource {\n  item: SidebarResource;\n  depth: number;\n  parentId: string | null;\n}\n\nexport interface DropTarget {\n  id: string | null;\n  position: SidebarResourceDropPosition;\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/agents/ai-sidebar/marquee-label.tsx","type":"util","content":"\"use client\";\n\nimport { motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\n\nconst ROW_REVEAL = {\n  duration: 0.16,\n  ease: EASE_OUT,\n} as const;\n\n/** A row label that scrolls its overflow into view while the row is active. */\nexport function MarqueeLabel({ active, children }: { active: boolean; children: string }) {\n  const reduce = useReducedMotion() ?? false;\n  const viewportRef = useRef<HTMLSpanElement>(null);\n  const labelRef = useRef<HTMLSpanElement>(null);\n  const [distance, setDistance] = useState(0);\n\n  useEffect(() => {\n    const measure = () => {\n      const viewport = viewportRef.current;\n      const label = labelRef.current;\n      if (!viewport || !label) return;\n      setDistance(label.scrollWidth > viewport.clientWidth ? label.scrollWidth + 24 : 0);\n    };\n    measure();\n    const observer = new ResizeObserver(measure);\n    if (viewportRef.current) observer.observe(viewportRef.current);\n    if (labelRef.current) observer.observe(labelRef.current);\n    return () => observer.disconnect();\n  }, []);\n\n  const running = active && distance > 0 && !reduce;\n\n  return (\n    <span ref={viewportRef} className=\"block min-w-0 flex-1 overflow-hidden\">\n      <motion.span\n        className=\"flex w-max items-center gap-6 whitespace-nowrap\"\n        animate={{ x: running ? [0, -distance] : 0 }}\n        transition={\n          running\n            ? {\n                duration: Math.max(2.4, distance / 34),\n                ease: \"linear\",\n                repeat: Number.POSITIVE_INFINITY,\n                repeatDelay: 2,\n              }\n            : ROW_REVEAL\n        }\n      >\n        <span ref={labelRef}>{children}</span>\n        {running ? <span aria-hidden=\"true\">{children}</span> : null}\n      </motion.span>\n    </span>\n  );\n}\n"},{"path":"components/agents/ai-sidebar/resource-menu-action.tsx","type":"util","content":"\"use client\";\n\nimport type { LucideIcon } from \"lucide-react\";\nimport type { ReactNode } from \"react\";\n\nexport function ResourceMenuAction({\n  icon: Icon,\n  onSelect,\n  children,\n}: {\n  icon: LucideIcon;\n  onSelect: () => void;\n  children: ReactNode;\n}) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onSelect}\n      // The same row shape as every library menu: rounded-lg inside the\n      // panel's p-2 (16 − 8), and a foreground tint for hover and focus.\n      className=\"flex h-8 w-full items-center gap-2 rounded-lg px-3 text-left text-xs text-foreground outline-none transition-colors hover:bg-foreground/[0.07] focus-visible:bg-foreground/[0.07] focus-visible:ring-2 focus-visible:ring-ring\"\n    >\n      <Icon aria-hidden=\"true\" className=\"size-3.5 shrink-0\" />\n      <span className=\"min-w-0 truncate\">{children}</span>\n    </button>\n  );\n}\n"},{"path":"components/motion/popover-morph.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  usePresence,\n  useReducedMotion,\n  useTransform,\n} from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  type RefObject,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { FOCUSABLE_SELECTOR } from \"@/lib/focusable\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { mergeRefs } from \"@/lib/merge-refs\";\nimport { cn } from \"@/lib/utils\";\n\ntype Side = \"top\" | \"bottom\";\ntype Align = \"start\" | \"end\";\n\ntype MorphContextValue = {\n  open: boolean;\n  setOpen: (open: boolean) => void;\n  toggle: () => void;\n  triggerId: string;\n  contentId: string;\n  /** The element the panel measures against - see `registerTrigger`. */\n  triggerRef: React.MutableRefObject<HTMLElement | null>;\n  registerTrigger: (node: HTMLElement | null) => void;\n  contentRef: React.MutableRefObject<HTMLDivElement | null>;\n  /** Arms or disarms moving focus into the panel as it next appears. */\n  armFocusOnOpen: (armed: boolean) => void;\n  /** Reads and disarms the flag set by `armFocusOnOpen`. */\n  takeFocusOnOpen: () => boolean;\n};\n\nconst MorphContext = createContext<MorphContextValue | null>(null);\n\nfunction useMorphContext(component: string) {\n  const ctx = useContext(MorphContext);\n  if (!ctx) throw new Error(`${component} must be used within <MorphPopover>`);\n  return ctx;\n}\n\nexport interface MorphPopoverProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  /** Called with the new open state when the panel opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Classes merged onto the wrapper around the trigger. */\n  className?: string;\n}\n\n/**\n * A popover whose full-size panel reveals from the corner nearest the trigger\n * on one spring, then retraces the same clip on close. Content and surface\n * edges keep their size throughout. Closes on outside pointer / Escape.\n * Controlled or uncontrolled.\n */\nexport function MorphPopover({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: MorphPopoverProps) {\n  const baseId = useId();\n  const [root, setRoot] = useState<HTMLDivElement | null>(null);\n  const [trigger, setTrigger] = useState<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n  const toggle = useCallback(() => setOpen(!open), [setOpen, open]);\n\n  // A keyboard open arms focus for the panel to take as it appears. Any later\n  // key or pointer press disarms it, so an open the parent declined cannot\n  // leave it armed for a later open that nobody asked to focus.\n  const focusOnOpenRef = useRef(false);\n  const disarmRef = useRef<AbortController | null>(null);\n  const armFocusOnOpen = useCallback((armed: boolean) => {\n    disarmRef.current?.abort();\n    disarmRef.current = null;\n    focusOnOpenRef.current = armed;\n    if (!armed) return;\n    const controller = new AbortController();\n    const disarm = () => {\n      focusOnOpenRef.current = false;\n      controller.abort();\n    };\n    const options = { capture: true, signal: controller.signal };\n    document.addEventListener(\"keydown\", disarm, options);\n    document.addEventListener(\"pointerdown\", disarm, options);\n    disarmRef.current = controller;\n  }, []);\n  const takeFocusOnOpen = useCallback(() => {\n    const armed = focusOnOpenRef.current;\n    armFocusOnOpen(false);\n    return armed;\n  }, [armFocusOnOpen]);\n  useEffect(() => () => disarmRef.current?.abort(), []);\n\n  // A trigger normally registers itself through MorphPopoverTrigger. It can't\n  // when something else already clones the element - a Tooltip wrapping the\n  // button, say - and an unregistered trigger leaves the panel with nothing to\n  // measure against, so it renders permanently invisible. The root boxes the\n  // trigger exactly (the content portals out of it), so it stands in until a\n  // real trigger registers, and stands in again if that one unmounts. Both are\n  // state, so a trigger arriving while the panel is open re-anchors it.\n  const anchorRef = useMemo<React.MutableRefObject<HTMLElement | null>>(\n    () => ({ current: trigger ?? root }),\n    [root, trigger],\n  );\n\n  // The panel is a `role=\"dialog\"` and goes inert the moment it closes, so\n  // focus cannot be left sitting inside it: a dismissal hands it back to the\n  // trigger, the way the ARIA dialog pattern asks. A pointer dismissal takes\n  // the focus onward itself when it lands on something focusable - this only\n  // catches the case where it would otherwise be stranded. When no trigger has\n  // registered, the root anchor stands in only if it can actually hold focus;\n  // there is nowhere better than where the keyboard already is, so leave it.\n  const close = useCallback(() => {\n    setOpen(false);\n    const focused = document.activeElement;\n    const inPanel =\n      focused instanceof HTMLElement && contentRef.current?.contains(focused);\n    if (!inPanel) return;\n    const restore = trigger ?? (root && root.tabIndex >= 0 ? root : null);\n    restore?.focus();\n  }, [root, setOpen, trigger]);\n\n  // Inside is the root anchor and the portaled panel. Until the root mounts\n  // there is nothing to measure \"outside\" against, so nothing dismisses.\n  const insidePopover = useCallback(\n    (target: Element) =>\n      !root || root.contains(target) || Boolean(contentRef.current?.contains(target)),\n    [root],\n  );\n  useDismiss(open, close, null, { ignore: insidePopover });\n\n  const ctx = useMemo<MorphContextValue>(\n    () => ({\n      open,\n      setOpen,\n      toggle,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef: anchorRef,\n      registerTrigger: setTrigger,\n      contentRef,\n      armFocusOnOpen,\n      takeFocusOnOpen,\n    }),\n    [open, setOpen, toggle, baseId, anchorRef, armFocusOnOpen, takeFocusOnOpen],\n  );\n\n  return (\n    <MorphContext.Provider value={ctx}>\n      <div ref={setRoot} className={cn(\"relative inline-flex\", className)}>\n        {children}\n      </div>\n    </MorphContext.Provider>\n  );\n}\n\nexport interface MorphPopoverTriggerProps {\n  children: ReactElement;\n}\n\n/** Wraps a single element, toggling the popover on click. */\nexport function MorphPopoverTrigger({ children }: MorphPopoverTriggerProps) {\n  const ctx = useMorphContext(\"MorphPopoverTrigger\");\n  const child = children as ReactElement<Record<string, unknown>>;\n  const childOnClick = child?.props?.onClick as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnKeyDown = child?.props?.onKeyDown as\n    | ((e: unknown) => void)\n    | undefined;\n  const childOnPointerDown = child?.props?.onPointerDown as\n    | ((e: unknown) => void)\n    | undefined;\n  // Set by an Enter or Space keydown on the trigger, cleared by a pointer\n  // press, read by the click that follows.\n  const keyboardRef = useRef(false);\n  const childRef = (child?.props as { ref?: Ref<HTMLElement> } | undefined)\n    ?.ref;\n  // Register once per actual ref change, not once per open-state render.\n  const mergedRef = useMemo(\n    () => mergeRefs(childRef, ctx.registerTrigger),\n    [childRef, ctx.registerTrigger],\n  );\n  if (!isValidElement(children)) return children;\n\n  return cloneElement(child, {\n    id: ctx.triggerId,\n    ref: mergedRef,\n    onKeyDown: (e: unknown) => {\n      childOnKeyDown?.(e);\n      const key = (e as { key?: string } | undefined)?.key;\n      keyboardRef.current = key === \"Enter\" || key === \" \";\n    },\n    onPointerDown: (e: unknown) => {\n      childOnPointerDown?.(e);\n      keyboardRef.current = false;\n    },\n    onClick: (e: unknown) => {\n      childOnClick?.(e);\n      // Enter and Space reach here as a click with `detail` 0 after their\n      // keydown on this element. A pointer click counts at least 1, and a\n      // scripted click() has no keydown before it. Only a keyboard open\n      // moves focus into the panel.\n      const keyboard =\n        keyboardRef.current &&\n        (e as { detail?: number } | undefined)?.detail === 0;\n      keyboardRef.current = false;\n      ctx.armFocusOnOpen(!ctx.open && keyboard);\n      ctx.toggle();\n    },\n    \"aria-haspopup\": \"dialog\",\n    \"aria-expanded\": ctx.open,\n    \"aria-controls\": ctx.open ? ctx.contentId : undefined,\n  });\n}\n\n// Full-distance clip travel needs a shorter curve than SPRING_PANEL's slow\n// overdamped tail. A non-bouncing spring reaches its rest within 260 ms.\nconst MORPH_ENTER = { type: \"spring\", duration: 0.26, bounce: 0 } as const;\nconst MORPH_EXIT = { duration: 0.2, ease: EASE_OUT } as const;\n\n// Keep the panel and content at their final size. An inset clip reveals the\n// nearest corner without scaling borders, shadows or keyboard-focus geometry.\n// A full-size clip keeps content at its final coordinates without box-to-box\n// scale correction. One progress value keeps clip and opacity synchronized;\n// clip-path and the shadow may paint, so this is not a compositor-only morph.\nfunction clipAt(side: Side, align: Align, radius: number, inset: number) {\n  return `inset(${side === \"top\" ? inset : 0}% ${align === \"start\" ? inset : 0}% ${side === \"bottom\" ? inset : 0}% ${align === \"end\" ? inset : 0}% round ${radius}px)`;\n}\n\nexport interface MorphPopoverContentProps {\n  children: ReactNode;\n  /** Preferred side of the trigger. Flips when there is no room. Default: \"bottom\" */\n  side?: Side;\n  /** Lines the panel up with the trigger's start or end edge. Default: \"end\" */\n  align?: Align;\n  /** Gap between trigger and panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Panel corner radius, in px. Default 16 (rounded-2xl), like every floating panel. */\n  radius?: number;\n  /** Draw the surface shadow. Default true. */\n  shadow?: boolean;\n  /**\n   * Runs after the portalled surface is positioned and visible. Passing it\n   * hands focus to the caller: the panel then moves no focus on its own.\n   */\n  onOpenAutoFocus?: (content: HTMLDivElement) => void;\n  /**\n   * Element to focus when the trigger opens the panel by keyboard. Defaults\n   * to the first focusable element in the panel, or the panel itself. A\n   * pointer open does not move focus. Ignored with `onOpenAutoFocus`.\n   */\n  initialFocus?: RefObject<HTMLElement | null>;\n  /** Classes merged onto the panel surface. */\n  className?: string;\n}\n\nexport function MorphPopoverContent(props: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const [portalReady, setPortalReady] = useState(false);\n  useEffect(() => setPortalReady(true), []);\n  if (!portalReady) return null;\n  return createPortal(\n    <AnimatePresence>\n      {ctx.open && <MorphPopoverSurface {...props} />}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\n// Measurement belongs to the mounted portal session: reopening must not start\n// an entrance at the previous session's coordinates before measuring this one.\nfunction MorphPopoverSurface({\n  children,\n  side = \"bottom\",\n  align = \"end\",\n  sideOffset = 8,\n  radius = 16,\n  shadow = true,\n  onOpenAutoFocus,\n  initialFocus,\n  className,\n}: MorphPopoverContentProps) {\n  const ctx = useMorphContext(\"MorphPopoverContent\");\n  const reduce = useReducedMotion() ?? false;\n  const [isPresent, safeToRemove] = usePresence();\n  const layout = usePopoverPortalPosition(\n    ctx.triggerRef,\n    ctx.contentRef,\n    isPresent,\n  );\n\n  const preferredLeft = layout\n    ? align === \"end\"\n      ? layout.trigger.left + layout.trigger.width - layout.content.width\n      : layout.trigger.left\n    : 0;\n  // Keep larger compositions, such as calendars, inside the viewport. Prefer\n  // the requested side, then use the roomier side when it cannot fit there.\n  const gutter = 12;\n  const below = layout\n    ? Math.max(\n        0,\n        window.innerHeight -\n          layout.trigger.top -\n          layout.trigger.height -\n          sideOffset -\n          gutter,\n      )\n    : 0;\n  const above = layout\n    ? Math.max(0, layout.trigger.top - sideOffset - gutter)\n    : 0;\n  const requestedSpace = side === \"bottom\" ? below : above;\n  const otherSpace = side === \"bottom\" ? above : below;\n  const resolvedSide =\n    layout &&\n    layout.content.height > requestedSpace &&\n    otherSpace > requestedSpace\n      ? side === \"bottom\"\n        ? \"top\"\n        : \"bottom\"\n      : side;\n  const availableHeight = resolvedSide === \"bottom\" ? below : above;\n  const left = layout\n    ? Math.max(\n        gutter,\n        Math.min(\n          preferredLeft,\n          window.innerWidth - layout.content.width - gutter,\n        ),\n      )\n    : 0;\n  const top = layout\n    ? resolvedSide === \"bottom\"\n      ? layout.trigger.top + layout.trigger.height + sideOffset\n      : Math.max(\n          gutter,\n          layout.trigger.top - layout.content.height - sideOffset,\n        )\n    : 0;\n\n  const progress = useMotionValue(0);\n  const clipPath = useTransform(progress, (p) =>\n    clipAt(resolvedSide, align, radius, 92 * (1 - p)),\n  );\n  const surfaceOpacity = useTransform(progress, [0, 0.15], [0, 1]);\n  // Reduced motion has no travel, so a short fade carries the whole entrance\n  // and exit on its own.\n  const fade = useMotionValue(reduce ? 0 : 1);\n  const ready = layout !== null;\n  const focusedOnOpen = useRef(false);\n  useEffect(() => {\n    if (\n      !ready ||\n      !isPresent ||\n      focusedOnOpen.current ||\n      !ctx.contentRef.current\n    )\n      return;\n    focusedOnOpen.current = true;\n    onOpenAutoFocus?.(ctx.contentRef.current);\n  }, [ready, isPresent, ctx.contentRef, onOpenAutoFocus]);\n  // `safeToRemove` is a new function on every render: AnimatePresence\n  // rebuilds its context each time its parent renders. Read it through a ref\n  // so a render during the exit (a consumer's state change, a list streaming\n  // in) does not restart the exit from where it got to - restarted every\n  // render, it would close in ever smaller steps and never report completion,\n  // leaving an inert, invisible panel mounted for good.\n  const safeToRemoveRef = useRef(safeToRemove);\n  useLayoutEffect(() => {\n    safeToRemoveRef.current = safeToRemove;\n  });\n  useEffect(() => {\n    if (!ready) {\n      if (!isPresent) safeToRemoveRef.current?.();\n      return;\n    }\n    const settle = () => {\n      if (!isPresent) safeToRemoveRef.current?.();\n    };\n    if (reduce) {\n      progress.jump(1);\n      const animation = animate(fade, isPresent ? 1 : 0, {\n        duration: 0.12,\n        onComplete: settle,\n      });\n      return () => animation.stop();\n    }\n    const animation = animate(progress, isPresent ? 1 : 0, {\n      ...(isPresent ? MORPH_ENTER : MORPH_EXIT),\n      onComplete: settle,\n    });\n    return () => animation.stop();\n  }, [fade, progress, ready, isPresent, reduce]);\n\n  // The wrapper stays `visibility: hidden` until the first measurement, and\n  // focus() inside a hidden subtree is silently ignored. So move focus in the\n  // commit that makes the panel visible, not when it mounts. A CSS transition\n  // on `visibility` can still hold the controls hidden for a moment after\n  // that commit (a reduced-motion reset that gives every element a short\n  // transition-duration does), so while focus rests on the panel or has not\n  // moved, each such transition that ends tries the candidates again, until\n  // the user presses a key or pointer. The effect runs once per open, so it\n  // reads the caller's props through refs: a new ref or callback passed\n  // mid-open must not tear down a pending retry.\n  const initialFocusRef = useRef(initialFocus);\n  const callerFocusesRef = useRef(onOpenAutoFocus !== undefined);\n  useLayoutEffect(() => {\n    initialFocusRef.current = initialFocus;\n    callerFocusesRef.current = onOpenAutoFocus !== undefined;\n  });\n  const { contentRef, takeFocusOnOpen } = ctx;\n  useLayoutEffect(() => {\n    if (!ready || !isPresent) return;\n    if (!takeFocusOnOpen() || callerFocusesRef.current) return;\n    const panel = contentRef.current;\n    const wrapper = panel?.parentElement;\n    if (!panel || !wrapper) return;\n    const from = document.activeElement;\n    const unmoved = () =>\n      document.activeElement === from || document.activeElement === panel;\n    // The selector also matches elements focus() refuses: a hidden input, a\n    // disabled button that carries a tabindex, anything under display: none.\n    // Keep the first candidate that takes focus, else hold it on the panel.\n    const focusFirst = () => {\n      const candidates = [\n        initialFocusRef.current?.current,\n        ...panel.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),\n      ];\n      for (const candidate of candidates) {\n        if (!candidate) continue;\n        candidate.focus({ preventScroll: true });\n        if (unmoved()) continue;\n        // preventScroll keeps the page still, but it also stops the panel's\n        // own scroll area from bringing a row below the fold into view.\n        candidate.scrollIntoView?.({ block: \"nearest\" });\n        return true;\n      }\n      panel.focus({ preventScroll: true });\n      return false;\n    };\n    if (focusFirst()) return;\n    const retry = (event: TransitionEvent) => {\n      if (event.propertyName !== \"visibility\") return;\n      if (!unmoved() || focusFirst()) stop();\n    };\n    const stop = () => {\n      wrapper.removeEventListener(\"transitionend\", retry);\n      document.removeEventListener(\"keydown\", stop, true);\n      document.removeEventListener(\"pointerdown\", stop, true);\n    };\n    wrapper.addEventListener(\"transitionend\", retry);\n    document.addEventListener(\"keydown\", stop, true);\n    document.addEventListener(\"pointerdown\", stop, true);\n    return stop;\n  }, [ready, isPresent, contentRef, takeFocusOnOpen]);\n\n  return (\n    <motion.div\n      data-morph-popover-portal=\"\"\n      inert={!isPresent}\n      style={{\n        left,\n        top,\n        opacity: reduce ? fade : surfaceOpacity,\n        pointerEvents: isPresent ? \"auto\" : \"none\",\n        visibility: layout ? \"visible\" : \"hidden\",\n      }}\n      // A drop-shadow follows the clipped surface; box-shadow would be cut\n      // off by its own clip. Caller surface classes retain their old target.\n      className={cn(\n        \"fixed z-[9999]\",\n        shadow && \"[filter:drop-shadow(0_10px_18px_rgba(0,0,0,0.14))]\",\n      )}\n    >\n      <motion.div\n        ref={ctx.contentRef}\n        id={ctx.contentId}\n        role=\"dialog\"\n        aria-labelledby={ctx.triggerId}\n        tabIndex={-1}\n        style={{\n          clipPath: reduce ? undefined : clipPath,\n          borderRadius: radius,\n          maxHeight: layout ? availableHeight : undefined,\n          overflowX: \"hidden\",\n          overflowY: \"auto\",\n        }}\n        className={cn(\n          // The panel holds focus when nothing inside it can. An inset ring\n          // stays inside the clip that would cut off an outline.\n          \"border border-border bg-background outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring\",\n          className,\n        )}\n      >\n        {children}\n      </motion.div>\n    </motion.div>\n  );\n}\n"},{"path":"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-touch-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true on devices that can be touched, whatever else they claim.\n *\n * This is not the inverse of `useHoverCapable`: iPadOS Safari browses\n * desktop-class and answers `(hover: hover) and (pointer: fine)` with true\n * while a finger is the only input there is, so anything that treats\n * hover-capable as \"no touch here\" strands every iPad. Gate the *touch path*\n * of an interaction on this hook and leave hover-only polish on\n * `useHoverCapable`, so a component that opens on hover also opens on tap.\n */\nexport function useTouchCapable() {\n  const [canTouch, setCanTouch] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n    const mq = window.matchMedia?.(\"(any-pointer: coarse)\");\n    // iPadOS disguises its pointer media queries; maxTouchPoints it reports\n    // honestly, which is what makes it the standard iPad tell.\n    const update = () =>\n      setCanTouch(Boolean(mq?.matches) || navigator.maxTouchPoints > 0);\n    update();\n    mq?.addEventListener?.(\"change\", update);\n    return () => mq?.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canTouch;\n}\n"},{"path":"components/motion/popover-position.ts","type":"util","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport {\n  inLayerAbove,\n  inOtherLayer,\n  type Layer,\n  openLayer,\n  ownsEscape,\n} from \"@/lib/layers\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident - the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\n/** What closed the overlay: Escape, a pointerdown outside it, or focus leaving it. */\nexport type DismissReason = \"escape\" | \"pointer\" | \"focus\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Dismiss when focus moves outside, as a combobox does on Tab. Default false. */\n  focusOutside?: boolean;\n  /**\n   * Dismiss on a pointerdown outside. Default true. Turn it off for an overlay\n   * whose own backdrop handles presses and only needs Escape and layering.\n   */\n  outsidePress?: boolean;\n  /** Return true for an outside target that should *not* dismiss. */\n  ignore?: (target: Element) => boolean;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it - the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over.\n *\n * Each open dismissal is a layer in `lib/layers.ts`, so only the innermost\n * open overlay answers Escape (a menu inside a drawer closes, the drawer\n * stays), and a drawer's focus trap leaves focus in a menu it portaled out.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: (reason: DismissReason) => void,\n  ref: RefObject<HTMLElement | SVGElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    focusOutside = false,\n    outsidePress = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  // Read through refs, so a callback rebuilt each render neither re-binds the\n  // listeners nor moves this layer to the top of the stack.\n  const dismissRef = useRef(onDismiss);\n  const ignoreRef = useRef(ignore);\n  useLayoutEffect(() => {\n    dismissRef.current = onDismiss;\n    ignoreRef.current = ignore;\n  });\n\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Node) =>\n      Boolean(ref?.current?.contains(target)) ||\n      (target instanceof Element && Boolean(ignoreRef.current?.(target)));\n    const layer: Layer = { contains: inside, escape: dismissOnEscape };\n    const closeLayer = openLayer(layer);\n    const onKey = (event: KeyboardEvent) => {\n      if (!dismissOnEscape || event.key !== \"Escape\" || !ownsEscape(layer, event)) return;\n      event.preventDefault();\n      dismissRef.current(\"escape\");\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // A press in an overlay opened on top of this one (a tooltip or menu\n      // portaled to the body) belongs to that overlay, not outside this one.\n      if (inLayerAbove(layer, target)) return;\n      // Outside this overlay, but inside another open one: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !inOtherLayer(layer, target, { traps: false })) {\n        consumeActivation(event);\n      }\n      dismissRef.current(\"pointer\");\n    };\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (target instanceof Node && !inside(target)) dismissRef.current(\"focus\");\n    };\n    window.addEventListener(\"keydown\", onKey);\n    if (outsidePress) window.addEventListener(\"pointerdown\", onPointer, true);\n    if (focusOutside) window.addEventListener(\"focusin\", onFocus);\n    return () => {\n      closeLayer();\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n      window.removeEventListener(\"focusin\", onFocus);\n    };\n  }, [open, ref, behavior, dismissOnEscape, focusOutside, outsidePress]);\n}\n"},{"path":"lib/merge-refs.ts","type":"util","content":"import type { Ref } from \"react\";\n\n/** Points a callback or object ref at `value`. */\nexport function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) ref.current = value;\n}\n\n/** One callback ref that sets every ref it is given. */\nexport function mergeRefs<T>(...refs: Array<Ref<T> | undefined>) {\n  return (node: T | null) => {\n    for (const ref of refs) assignRef(ref, node);\n  };\n}\n"},{"path":"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/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"lib/touch.ts","type":"util","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page - the long-press selection callout and the selection it drags in with\n// it - and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant - which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing - the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis - leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures - a coarse\n * pointer - so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction - the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal - a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs - routine on iOS, where the\n * system can claim the touch first - and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active - implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer - a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger - so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it - `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"},{"path":"components/previews/agents/ai-sidebar.preview.tsx","type":"preview","content":"\"use client\";\n\nimport {\n  Clock3,\n  GitPullRequest,\n  LayoutGrid,\n  PanelLeft,\n  Plug,\n  SquarePen,\n} from \"lucide-react\";\nimport { useState } from \"react\";\nimport {\n  AnimatedSidebar,\n  AnimatedSidebarContent,\n  AnimatedSidebarGroup,\n  AnimatedSidebarGroupContent,\n  AnimatedSidebarGroupLabel,\n  AnimatedSidebarInset,\n  AnimatedSidebarMenu,\n  AnimatedSidebarMenuButton,\n  AnimatedSidebarMenuItem,\n  AnimatedSidebarProvider,\n  AnimatedSidebarRail,\n  AnimatedSidebarTrigger,\n} from \"@/components/motion/animated-sidebar\";\nimport {\n  AISidebar,\n  type SidebarResource,\n  type SidebarResourceMove,\n} from \"@/components/agents/ai-sidebar\";\n\nconst resources: SidebarResource[] = [\n  {\n    id: \"design-system\",\n    label: \"Design system\",\n    kind: \"project\",\n  },\n  {\n    id: \"client-portal\",\n    label: \"Client portal\",\n    kind: \"project\",\n  },\n  {\n    id: \"marketing-site\",\n    label: \"Marketing website\",\n    kind: \"project\",\n  },\n  {\n    id: \"platform\",\n    label: \"Platform\",\n    kind: \"project\",\n    children: [\n      { id: \"api\", label: \"API migration\", kind: \"file\" },\n      { id: \"billing\", label: \"Billing states\", kind: \"file\" },\n      { id: \"docs\", label: \"Read platform docs\", kind: \"bookmark\" },\n    ],\n  },\n  {\n    id: \"mobile-app\",\n    label: \"Mobile app\",\n    kind: \"project\",\n  },\n  {\n    id: \"research-lab\",\n    label: \"Research lab\",\n    kind: \"folder\",\n  },\n  {\n    id: \"agent-workspace\",\n    label: \"Agent workspace\",\n    kind: \"project\",\n    children: [\n      {\n        id: \"resource-review\",\n        label: \"Review resource sidebar interaction details\",\n        kind: \"file\",\n      },\n      {\n        id: \"release-offer\",\n        label: \"Prepare release announcement\",\n        kind: \"file\",\n      },\n      {\n        id: \"haptics\",\n        label: \"Explore interaction feedback\",\n        kind: \"bookmark\",\n      },\n      {\n        id: \"promotion\",\n        label: \"Plan launch distribution\",\n        kind: \"file\",\n      },\n      {\n        id: \"motion-research\",\n        label: \"Research motion implementation patterns\",\n        kind: \"bookmark\",\n      },\n    ],\n  },\n  {\n    id: \"release-notes\",\n    label: \"Release notes\",\n    kind: \"file\",\n  },\n];\n\nconst actions = [\n  { label: \"New workspace\", icon: SquarePen },\n  { label: \"Pull requests\", icon: GitPullRequest },\n  { label: \"Sites\", icon: LayoutGrid },\n  { label: \"Scheduled\", icon: Clock3 },\n  { label: \"Extensions\", icon: Plug },\n] as const;\n\nfunction findLabel(items: SidebarResource[], id: string): string | undefined {\n  for (const item of items) {\n    if (item.id === id) return item.label;\n    const child = item.children ? findLabel(item.children, id) : undefined;\n    if (child) return child;\n  }\n}\n\nexport function AISidebarPreview() {\n  const [active, setActive] = useState(\"resource-review\");\n  const [items, setItems] = useState(resources);\n  const activeLabel = findLabel(items, active) ?? active;\n\n  const move = async (_event: SidebarResourceMove) => {\n    await new Promise((resolve) => window.setTimeout(resolve, 450));\n  };\n\n  return (\n    <div className=\"w-full px-0 py-2 sm:p-3\">\n      <AnimatedSidebarProvider\n        style={{ \"--sidebar-width\": \"16rem\" }}\n        className=\"h-[720px] min-h-0 w-full overflow-hidden rounded-2xl border border-foreground/[0.08] bg-background\"\n      >\n        <AnimatedSidebar\n          ariaLabel=\"Workspace resources\"\n          collapsible=\"offcanvas\"\n          className=\"min-h-0 w-full\"\n          panelClassName=\"h-full bg-background\"\n        >\n          <AnimatedSidebarContent className=\"gap-4 overflow-hidden px-2 py-4\">\n            <AnimatedSidebarGroup className=\"shrink-0 px-1 py-0\">\n              <AnimatedSidebarGroupContent>\n                <AnimatedSidebarMenu className=\"gap-1\">\n                  {actions.map(({ label, icon: Icon }) => (\n                    <AnimatedSidebarMenuItem key={label}>\n                      <AnimatedSidebarMenuButton\n                        icon={<Icon className=\"size-4\" />}\n                        onSelect={() => {}}\n                        className=\"font-normal text-foreground\"\n                      >\n                        {label}\n                      </AnimatedSidebarMenuButton>\n                    </AnimatedSidebarMenuItem>\n                  ))}\n                </AnimatedSidebarMenu>\n              </AnimatedSidebarGroupContent>\n            </AnimatedSidebarGroup>\n\n            <AnimatedSidebarGroup className=\"min-h-0 flex-1 px-1 py-0\">\n              <AnimatedSidebarGroupLabel className=\"mb-1 h-8 px-2 text-xs font-medium normal-case tracking-normal\">\n                Projects\n              </AnimatedSidebarGroupLabel>\n              <AnimatedSidebarGroupContent className=\"relative min-h-0 flex-1 overflow-hidden\">\n                <div className=\"h-full overflow-y-auto overscroll-contain pb-8 [overflow-anchor:none] [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\">\n                  <AISidebar\n                    items={items}\n                    activeId={active}\n                    defaultExpandedIds={[\"platform\", \"agent-workspace\"]}\n                    onActiveChange={setActive}\n                    onItemsChange={setItems}\n                    onMove={move}\n                  />\n                </div>\n                <div\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute inset-x-0 bottom-0 z-20 h-8 bg-gradient-to-t from-background via-background/80 to-transparent\"\n                />\n              </AnimatedSidebarGroupContent>\n            </AnimatedSidebarGroup>\n          </AnimatedSidebarContent>\n          <AnimatedSidebarRail />\n        </AnimatedSidebar>\n\n        <AnimatedSidebarInset className=\"min-h-0 bg-background\">\n          <header className=\"flex h-14 shrink-0 items-center justify-between gap-4 border-border border-b px-5\">\n            <div className=\"flex min-w-0 items-center gap-3\">\n              <AnimatedSidebarTrigger className=\"-ml-2 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground\">\n                <PanelLeft aria-hidden=\"true\" className=\"size-4\" />\n              </AnimatedSidebarTrigger>\n              <div className=\"min-w-0\">\n                <p className=\"text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground\">\n                  Workspace\n                </p>\n                <p className=\"truncate text-sm font-medium text-foreground\">\n                  Agent workspace\n                </p>\n              </div>\n            </div>\n            <span className=\"shrink-0 rounded-full bg-muted px-2.5 py-1 text-[11px] font-medium text-muted-foreground\">\n              Draft\n            </span>\n          </header>\n\n          <div className=\"min-h-0 flex-1 overflow-y-auto p-6 sm:p-8\">\n            <div className=\"mx-auto max-w-xl\">\n              <p className=\"text-xs text-muted-foreground\">Selected resource</p>\n              <h3 className=\"mt-2 text-xl font-medium tracking-tight text-foreground sm:text-2xl\">\n                {activeLabel}\n              </h3>\n              <p className=\"mt-3 max-w-lg text-sm leading-6 text-muted-foreground\">\n                Keep the resource tree predictable while files move between\n                projects, labels overflow, and folders expand around the\n                current selection.\n              </p>\n\n              <div className=\"mt-8 border-border border-t pt-6\">\n                <p className=\"text-sm font-medium text-foreground\">\n                  Interaction notes\n                </p>\n                <ul className=\"mt-3 space-y-3 text-sm leading-6 text-muted-foreground\">\n                  <li>Folders only reveal their contents.</li>\n                  <li>Files can be selected, moved, or renamed.</li>\n                  <li>Rejected moves return to their previous location.</li>\n                </ul>\n              </div>\n            </div>\n          </div>\n        </AnimatedSidebarInset>\n      </AnimatedSidebarProvider>\n    </div>\n  );\n}\n"},{"path":"components/motion/animated-sidebar.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type ButtonHTMLAttributes,\n  type CSSProperties,\n  forwardRef,\n  type HTMLAttributes,\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SharedLayoutBg } from \"@/components/motion/shared-layout-bg\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  AnimatedSidebarContext,\n  AnimatedSidebarPanelContext,\n  type AnimatedSidebarMessages,\n  animatedSidebarMessages,\n  type SidebarCollapsible,\n  type SidebarSide,\n  type SidebarVariant,\n  useAnimatedSidebar,\n  useAnimatedSidebarPanel,\n} from \"./animated-sidebar/context\";\nimport { MobileSidebar } from \"./animated-sidebar/mobile-sidebar\";\nimport {\n  PANEL_TRANSITION,\n  REDUCED_TRANSITION,\n  SIDEBAR_MORPH_TRANSITION,\n  SUBMENU_ITEM_VARIANTS,\n  SUBMENU_VARIANTS,\n} from \"./animated-sidebar/motion\";\nimport { useIsMobile } from \"./animated-sidebar/use-is-mobile\";\n\nexport {\n  AnimatedSidebarMenuSubButton,\n  type AnimatedSidebarMenuSubButtonProps,\n} from \"./animated-sidebar/menu-sub-button\";\nexport {\n  AnimatedSidebarMenuButton,\n  type AnimatedSidebarMenuButtonProps,\n} from \"./animated-sidebar/menu-button\";\nexport {\n  type AnimatedSidebarMessages,\n  animatedSidebarMessages,\n  useAnimatedSidebar,\n} from \"./animated-sidebar/context\";\n\nconst SIDEBAR_KEYBOARD_SHORTCUT = \"b\";\n\ntype SidebarProviderStyle = CSSProperties & {\n  \"--sidebar-width\"?: string;\n  \"--sidebar-width-icon\"?: string;\n  \"--sidebar-width-mobile\"?: string;\n};\n\nexport interface AnimatedSidebarProviderProps\n  extends HTMLAttributes<HTMLDivElement> {\n  /** Whether the desktop sidebar is expanded, for controlled use. */\n  open?: boolean;\n  /** Whether the desktop sidebar starts expanded when uncontrolled. Default: true */\n  defaultOpen?: boolean;\n  /** Called with the next state when the desktop sidebar expands or collapses. */\n  onOpenChange?: (open: boolean) => void;\n  /** Whether the mobile drawer is open, for controlled use. */\n  openMobile?: boolean;\n  /** Whether the mobile drawer starts open when uncontrolled. Default: false */\n  defaultOpenMobile?: boolean;\n  /** Called with the next state when the mobile drawer opens or closes. */\n  onOpenMobileChange?: (open: boolean) => void;\n  /** Inline styles; set `--sidebar-width`, `--sidebar-width-icon` or `--sidebar-width-mobile` here. */\n  style?: SidebarProviderStyle;\n  /** Override any built-in string. */\n  labels?: Partial<AnimatedSidebarMessages>;\n}\n\nexport function AnimatedSidebarProvider({\n  children,\n  open,\n  defaultOpen = true,\n  onOpenChange,\n  openMobile,\n  defaultOpenMobile = false,\n  onOpenMobileChange,\n  className,\n  style,\n  labels,\n  ...props\n}: AnimatedSidebarProviderProps) {\n  const t = useMessages(\"animatedSidebar\", animatedSidebarMessages, labels);\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const [internalOpenMobile, setInternalOpenMobile] =\n    useState(defaultOpenMobile);\n  const isMobile = useIsMobile();\n  const reduce = useReducedMotion() ?? false;\n  const generatedId = useId();\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const desktopOpen = open ?? internalOpen;\n  const mobileOpen = openMobile ?? internalOpenMobile;\n\n  const setOpen = useCallback(\n    (nextOpen: boolean) => {\n      if (open === undefined) setInternalOpen(nextOpen);\n      onOpenChange?.(nextOpen);\n    },\n    [onOpenChange, open],\n  );\n\n  const setOpenMobile = useCallback(\n    (nextOpen: boolean) => {\n      if (openMobile === undefined) setInternalOpenMobile(nextOpen);\n      onOpenMobileChange?.(nextOpen);\n    },\n    [onOpenMobileChange, openMobile],\n  );\n\n  const toggleSidebar = useCallback(() => {\n    if (isMobile) setOpenMobile(!mobileOpen);\n    else setOpen(!desktopOpen);\n  }, [desktopOpen, isMobile, mobileOpen, setOpen, setOpenMobile]);\n\n  useEffect(() => {\n    const handleShortcut = (event: KeyboardEvent) => {\n      if (\n        event.key.toLowerCase() === SIDEBAR_KEYBOARD_SHORTCUT &&\n        (event.metaKey || event.ctrlKey)\n      ) {\n        event.preventDefault();\n        toggleSidebar();\n      }\n    };\n\n    window.addEventListener(\"keydown\", handleShortcut);\n    return () => window.removeEventListener(\"keydown\", handleShortcut);\n  }, [toggleSidebar]);\n\n  return (\n    <AnimatedSidebarContext.Provider\n      value={{\n        isMobile,\n        layoutId: `${generatedId}-active`,\n        open: desktopOpen,\n        openMobile: mobileOpen,\n        reduce,\n        setOpen,\n        setOpenMobile,\n        state: desktopOpen ? \"expanded\" : \"collapsed\",\n        toggleSidebar,\n        triggerRef,\n        t,\n      }}\n    >\n      <div\n        {...props}\n        data-slot=\"sidebar-wrapper\"\n        data-state={desktopOpen ? \"expanded\" : \"collapsed\"}\n        style={{\n          \"--sidebar-width\": \"16rem\",\n          \"--sidebar-width-icon\": \"4.25rem\",\n          \"--sidebar-width-mobile\": \"18rem\",\n          ...style,\n        }}\n        className={cn(\n          \"group/sidebar-wrapper flex min-h-svh w-full min-w-0\",\n          className,\n        )}\n      >\n        {children}\n      </div>\n    </AnimatedSidebarContext.Provider>\n  );\n}\n\nexport interface AnimatedSidebarProps\n  extends Omit<HTMLMotionProps<\"aside\">, \"children\"> {\n  children?: ReactNode;\n  /** Which edge of the layout the sidebar sits on. Default: \"left\" */\n  side?: SidebarSide;\n  /** Panel style: bordered edge, floating card, or inset card. Default: \"sidebar\" */\n  variant?: SidebarVariant;\n  /** How it collapses: to an icon rail, fully off canvas, or never. Default: \"icon\" */\n  collapsible?: SidebarCollapsible;\n  /** Accessible name for the sidebar landmark. Default: \"Sidebar\" */\n  ariaLabel?: string;\n  /** Classes merged onto the inner panel that holds the content. */\n  panelClassName?: string;\n}\n\nexport const AnimatedSidebar = forwardRef<HTMLElement, AnimatedSidebarProps>(\n  function AnimatedSidebar(\n    {\n      side = \"left\",\n      variant = \"sidebar\",\n      collapsible = \"icon\",\n      ariaLabel: ariaLabelProp,\n      children,\n      className,\n      panelClassName,\n      style,\n      ...props\n    },\n    forwardedRef,\n  ) {\n    const context = useAnimatedSidebar();\n    const ariaLabel = ariaLabelProp ?? context.t(\"label\");\n    const collapsed = collapsible !== \"none\" && !context.open;\n    const offcanvas = collapsed && collapsible === \"offcanvas\";\n    const width = offcanvas\n      ? \"0px\"\n      : collapsed\n        ? \"var(--sidebar-width-icon)\"\n        : \"var(--sidebar-width)\";\n\n    if (context.isMobile) {\n      return (\n        <MobileSidebar\n          ariaLabel={ariaLabel}\n          className={className}\n          side={side}\n        >\n          {children}\n        </MobileSidebar>\n      );\n    }\n\n    return (\n      <motion.aside\n        {...props}\n        ref={forwardedRef}\n        initial={false}\n        aria-label={ariaLabel}\n        data-slot=\"sidebar\"\n        data-state={collapsed ? \"collapsed\" : \"expanded\"}\n        data-collapsible={collapsible}\n        data-variant={variant}\n        data-side={side}\n        animate={{ width }}\n        transition={\n          context.reduce ? { duration: 0 } : SIDEBAR_MORPH_TRANSITION\n        }\n        style={style}\n        className={cn(\n          \"group/sidebar relative hidden h-auto shrink-0 md:block will-change-[width]\",\n          \"peer\",\n          side === \"right\" && \"order-last\",\n          className,\n        )}\n      >\n        <motion.div\n          initial={false}\n          animate={{\n            opacity: offcanvas ? 0 : 1,\n            x: offcanvas ? (side === \"left\" ? \"-100%\" : \"100%\") : \"0%\",\n          }}\n          transition={\n            context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n          }\n          className={cn(\n            \"sticky top-0 flex h-svh w-full flex-col overflow-hidden bg-background\",\n            collapsible === \"offcanvas\" && \"w-[var(--sidebar-width)]\",\n            variant === \"sidebar\" &&\n              (side === \"left\" ? \"border-border border-r\" : \"border-border border-l\"),\n            variant === \"floating\" &&\n              \"m-2 h-[calc(100svh-1rem)] rounded-2xl border border-border shadow-sm\",\n            variant === \"inset\" && \"m-2 h-[calc(100svh-1rem)] rounded-2xl\",\n            panelClassName,\n          )}\n        >\n          <AnimatedSidebarPanelContext.Provider\n            value={{ collapsed, collapsible, side }}\n          >\n            {children}\n          </AnimatedSidebarPanelContext.Provider>\n        </motion.div>\n      </motion.aside>\n    );\n  },\n);\n\nexport interface AnimatedSidebarTriggerProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarTrigger = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarTriggerProps\n>(function AnimatedSidebarTrigger(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const expanded = context.isMobile ? context.openMobile : context.open;\n\n  return (\n    <button\n      {...props}\n      ref={(node) => {\n        context.triggerRef.current = node;\n        if (typeof forwardedRef === \"function\") forwardedRef(node);\n        else if (forwardedRef) forwardedRef.current = node;\n      }}\n      type={type}\n      aria-label={props[\"aria-label\"] ?? context.t(\"toggle\")}\n      aria-expanded={expanded}\n      data-slot=\"sidebar-trigger\"\n      data-state={expanded ? \"expanded\" : \"collapsed\"}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.toggleSidebar();\n      }}\n      className={cn(\n        \"inline-flex size-10 shrink-0 items-center justify-center rounded-full outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarCloseProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarClose = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarCloseProps\n>(function AnimatedSidebarClose(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n\n  return (\n    <button\n      {...props}\n      ref={forwardedRef}\n      type={type}\n      aria-label={props[\"aria-label\"] ?? context.t(\"close\")}\n      onClick={(event) => {\n        onClick?.(event);\n        if (event.defaultPrevented) return;\n        if (context.isMobile) context.setOpenMobile(false);\n        else context.setOpen(false);\n      }}\n      className={cn(\n        \"inline-flex size-10 shrink-0 items-center justify-center rounded-full outline-none\",\n        \"focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarRailProps\n  extends ButtonHTMLAttributes<HTMLButtonElement> {}\n\nexport const AnimatedSidebarRail = forwardRef<\n  HTMLButtonElement,\n  AnimatedSidebarRailProps\n>(function AnimatedSidebarRail(\n  { className, onClick, type = \"button\", ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n\n  return (\n    <button\n      {...props}\n      ref={forwardedRef}\n      type={type}\n      data-side={panel.side}\n      aria-label={props[\"aria-label\"] ?? context.t(\"toggle\")}\n      title={context.t(\"toggle\")}\n      tabIndex={-1}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) context.toggleSidebar();\n      }}\n      className={cn(\n        \"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 outline-none md:block\",\n        \"after:absolute after:inset-y-0 after:left-1/2 after:w-px after:bg-transparent after:transition-colors hover:after:bg-border\",\n        \"data-[side=right]:right-0 data-[side=right]:translate-x-1/2 data-[side=left]:left-full\",\n        className,\n      )}\n    />\n  );\n});\n\nexport interface AnimatedSidebarInsetProps\n  extends HTMLMotionProps<\"main\"> {}\n\nexport const AnimatedSidebarInset = forwardRef<\n  HTMLElement,\n  AnimatedSidebarInsetProps\n>(function AnimatedSidebarInset({ className, ...props }, forwardedRef) {\n  return (\n    <motion.main\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-inset\"\n      className={cn(\n        \"relative flex min-h-svh min-w-0 flex-1 flex-col bg-background\",\n        \"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-2xl md:peer-data-[variant=inset]:shadow-sm\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarHeader = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarHeader({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-header\"\n      className={cn(\"flex shrink-0 flex-col gap-2 p-3\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarContent = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarContent({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-content\"\n      className={cn(\n        \"flex min-h-0 flex-1 flex-col gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-2 py-2\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarFooter = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarFooter({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-footer\"\n      className={cn(\n        \"flex shrink-0 flex-col gap-2 border-border border-t p-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\",\n        className,\n      )}\n    />\n  );\n});\n\nexport const AnimatedSidebarGroup = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroup({ className, ...props }, forwardedRef) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-group\"\n      className={cn(\"flex w-full min-w-0 flex-col px-1 py-1.5\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarGroupLabel = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroupLabel(\n  { children, className, ...props },\n  forwardedRef,\n) {\n  const { collapsed } = useAnimatedSidebarPanel();\n\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      aria-hidden={collapsed}\n      data-slot=\"sidebar-group-label\"\n      className={cn(\n        \"mb-1 h-7 overflow-hidden px-2 text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground transition-opacity\",\n        collapsed ? \"opacity-0\" : \"opacity-100\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n});\n\nexport const AnimatedSidebarGroupContent = forwardRef<\n  HTMLDivElement,\n  HTMLAttributes<HTMLDivElement>\n>(function AnimatedSidebarGroupContent(\n  { className, ...props },\n  forwardedRef,\n) {\n  return (\n    <div\n      {...props}\n      ref={forwardedRef}\n      data-slot=\"sidebar-group-content\"\n      className={cn(\"w-full min-w-0\", className)}\n    />\n  );\n});\n\nexport const AnimatedSidebarMenu = forwardRef<\n  HTMLUListElement,\n  HTMLAttributes<HTMLUListElement>\n>(function AnimatedSidebarMenu(\n  { children, className, ...props },\n  forwardedRef,\n) {\n  return (\n    <SharedLayoutBg\n      {...props}\n      ref={forwardedRef as React.Ref<HTMLElement>}\n      as=\"ul\"\n      inset={0}\n      pillClassName=\"rounded-full bg-muted/70\"\n      pillContainerClassName=\"inset-y-auto top-0 h-9\"\n      data-slot=\"sidebar-menu\"\n      className={cn(\"flex w-full min-w-0 list-none flex-col gap-0.5\", className)}\n    >\n      {children}\n    </SharedLayoutBg>\n  );\n});\n\nexport const AnimatedSidebarMenuItem = forwardRef<\n  HTMLLIElement,\n  HTMLMotionProps<\"li\">\n>(function AnimatedSidebarMenuItem({ className, ...props }, forwardedRef) {\n  return (\n    <motion.li\n      {...props}\n      ref={forwardedRef}\n      layout=\"position\"\n      transition={SPRING_LAYOUT}\n      data-slot=\"sidebar-menu-item\"\n      className={cn(\"relative\", className)}\n    />\n  );\n});\n\nexport interface AnimatedSidebarMenuSubProps\n  extends Omit<HTMLMotionProps<\"ul\">, \"children\"> {\n  /** Shows the submenu. It stays hidden while the sidebar is collapsed. */\n  open: boolean;\n  children?: ReactNode;\n}\n\nexport const AnimatedSidebarMenuSub = forwardRef<\n  HTMLUListElement,\n  AnimatedSidebarMenuSubProps\n>(function AnimatedSidebarMenuSub(\n  { open, children, className, ...props },\n  forwardedRef,\n) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n\n  return (\n    <AnimatePresence initial={false} mode=\"popLayout\">\n      {open && !panel.collapsed ? (\n        <motion.ul\n          {...props}\n          ref={forwardedRef}\n          key=\"sidebar-submenu\"\n          variants={context.reduce ? undefined : SUBMENU_VARIANTS}\n          initial={context.reduce ? false : \"closed\"}\n          animate={context.reduce ? { opacity: 1 } : \"open\"}\n          exit={context.reduce ? { opacity: 0 } : \"closed\"}\n          transition={context.reduce ? { duration: 0.12 } : undefined}\n          data-slot=\"sidebar-menu-sub\"\n          className={cn(\n            \"relative mt-1 ml-5 flex min-w-0 flex-col gap-0.5 border-border border-l pl-3\",\n            className,\n          )}\n        >\n          {children}\n        </motion.ul>\n      ) : null}\n    </AnimatePresence>\n  );\n});\n\nexport const AnimatedSidebarMenuSubItem = forwardRef<\n  HTMLLIElement,\n  HTMLMotionProps<\"li\">\n>(function AnimatedSidebarMenuSubItem(\n  { className, ...props },\n  forwardedRef,\n) {\n  return (\n    <motion.li\n      {...props}\n      ref={forwardedRef}\n      variants={SUBMENU_ITEM_VARIANTS}\n      data-slot=\"sidebar-menu-sub-item\"\n      className={cn(\"relative min-w-0\", className)}\n    />\n  );\n});\n"},{"path":"components/motion/animated-sidebar/context.ts","type":"util","content":"\"use client\";\n\nimport { createContext, useContext } from \"react\";\nimport type { useMessages } from \"@/lib/i18n\";\n\nexport type SidebarState = \"expanded\" | \"collapsed\";\nexport type SidebarSide = \"left\" | \"right\";\nexport type SidebarVariant = \"sidebar\" | \"floating\" | \"inset\";\nexport type SidebarCollapsible = \"offcanvas\" | \"icon\" | \"none\";\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const animatedSidebarMessages = {\n  label: \"Sidebar\",\n  toggle: \"Toggle sidebar\",\n  close: \"Close sidebar\",\n};\n\nexport type AnimatedSidebarMessages = typeof animatedSidebarMessages;\n\ninterface AnimatedSidebarContextValue {\n  isMobile: boolean;\n  layoutId: string;\n  open: boolean;\n  openMobile: boolean;\n  reduce: boolean;\n  setOpen: (open: boolean) => void;\n  setOpenMobile: (open: boolean) => void;\n  state: SidebarState;\n  toggleSidebar: () => void;\n  triggerRef: React.RefObject<HTMLButtonElement | null>;\n  t: ReturnType<typeof useMessages<AnimatedSidebarMessages>>;\n}\n\nexport const AnimatedSidebarContext =\n  createContext<AnimatedSidebarContextValue | null>(null);\n\ninterface AnimatedSidebarPanelContextValue {\n  collapsed: boolean;\n  collapsible: SidebarCollapsible;\n  side: SidebarSide;\n}\n\nexport const AnimatedSidebarPanelContext =\n  createContext<AnimatedSidebarPanelContextValue | null>(null);\n\nexport function useAnimatedSidebar() {\n  const context = useContext(AnimatedSidebarContext);\n  if (!context) {\n    throw new Error(\n      \"useAnimatedSidebar must be used inside AnimatedSidebarProvider.\",\n    );\n  }\n  return context;\n}\n\nexport function useAnimatedSidebarPanel() {\n  const context = useContext(AnimatedSidebarPanelContext);\n  if (!context) {\n    throw new Error(\n      \"Animated Sidebar parts must be used inside AnimatedSidebar.\",\n    );\n  }\n  return context;\n}\n"},{"path":"components/motion/animated-sidebar/menu-button.tsx","type":"util","content":"\"use client\";\n\nimport { ChevronRight } from \"lucide-react\";\nimport { motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_LAYOUT, SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { useAnimatedSidebar, useAnimatedSidebarPanel } from \"./context\";\nimport {\n  LABEL_ENTER_TRANSITION,\n  LABEL_EXIT_TRANSITION,\n  REDUCED_TRANSITION,\n} from \"./motion\";\n\nexport interface AnimatedSidebarMenuButtonProps {\n  children: ReactNode;\n  /** Icon shown before the label; stays visible in the collapsed rail. */\n  icon?: ReactNode;\n  /** Trailing content such as a count, hidden while collapsed. */\n  badge?: ReactNode;\n  /** Renders a link to this URL instead of a button. */\n  href?: string;\n  /** Marks the current page and moves the shared highlight here. Default: false */\n  isActive?: boolean;\n  /** Expanded state of a submenu this button toggles; also shows a chevron. */\n  ariaExpanded?: boolean;\n  /** Disables the item. Default: false */\n  disabled?: boolean;\n  /** Close the mobile drawer on select. Defaults to true unless `ariaExpanded` is set. */\n  closeOnSelect?: boolean;\n  /** Link target, used with `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link rel, used with `href`. Defaults to \"noreferrer noopener\" for `_blank`. */\n  rel?: string;\n  /** Called when the item is clicked. */\n  onSelect?: () => void;\n  /** Classes merged onto the button or link element. */\n  className?: string;\n}\n\nexport function AnimatedSidebarMenuButton({\n  children,\n  icon,\n  badge,\n  href,\n  isActive = false,\n  ariaExpanded,\n  disabled = false,\n  closeOnSelect,\n  target,\n  rel,\n  onSelect,\n  className,\n}: AnimatedSidebarMenuButtonProps) {\n  const context = useAnimatedSidebar();\n  const panel = useAnimatedSidebarPanel();\n  const textLabel = typeof children === \"string\" ? children : undefined;\n\n  const select = (\n    event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>,\n  ) => {\n    if (disabled) {\n      event.preventDefault();\n      return;\n    }\n    onSelect?.();\n    const shouldCloseOnSelect =\n      closeOnSelect ?? ariaExpanded === undefined;\n    if (context.isMobile && shouldCloseOnSelect) {\n      context.setOpenMobile(false);\n    }\n    // A submenu cannot render in the icon rail, so opening one from there\n    // leaves its children unreachable - a pointer can still fall back to the\n    // rail or the shortcut, a finger has nothing. Selecting a group unfolds\n    // the panel that is about to hold it.\n    if (ariaExpanded !== undefined && panel.collapsed && !context.isMobile) {\n      context.setOpen(true);\n    }\n  };\n\n  const content = (\n    <>\n      {isActive ? (\n        <motion.span\n          layoutId={context.layoutId}\n          transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          className=\"absolute inset-0 rounded-full bg-muted\"\n        />\n      ) : null}\n      {icon ? (\n        <span\n          aria-hidden=\"true\"\n          className=\"relative z-10 grid size-5 shrink-0 place-items-center\"\n        >\n          {icon}\n        </span>\n      ) : null}\n      <motion.span\n        initial={false}\n        animate={{\n          opacity: panel.collapsed ? 0 : 1,\n          x: panel.collapsed ? -4 : 0,\n        }}\n        transition={\n          context.reduce\n            ? REDUCED_TRANSITION\n            : panel.collapsed\n              ? LABEL_EXIT_TRANSITION\n              : LABEL_ENTER_TRANSITION\n        }\n        aria-hidden={panel.collapsed}\n        className={cn(\n          \"relative z-10 min-w-0 flex-1 truncate\",\n          panel.collapsed && \"pointer-events-none\",\n        )}\n      >\n        {children}\n      </motion.span>\n      {badge && !panel.collapsed ? (\n        <span className=\"relative z-10 shrink-0 text-xs text-muted-foreground\">\n          {badge}\n        </span>\n      ) : null}\n      {ariaExpanded !== undefined ? (\n        <motion.span\n          aria-hidden=\"true\"\n          initial={false}\n          animate={{\n            opacity: panel.collapsed ? 0 : 1,\n            rotate: ariaExpanded ? 90 : 0,\n            x: panel.collapsed ? 4 : 0,\n          }}\n          transition={context.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          className=\"relative z-10 grid size-4 shrink-0 place-items-center text-muted-foreground\"\n        >\n          <ChevronRight className=\"size-3.5\" />\n        </motion.span>\n      ) : null}\n    </>\n  );\n\n  const interactiveClassName = cn(\n    \"relative flex min-h-9 w-full min-w-0 items-center gap-2.5 overflow-hidden rounded-full px-3 text-left text-sm font-medium outline-none\",\n    \"text-muted-foreground transition-colors hover:text-foreground\",\n    \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring\",\n    isActive && \"text-foreground\",\n    disabled && \"cursor-not-allowed opacity-40\",\n    className,\n  );\n\n  return href ? (\n    <motion.a\n      href={href}\n      target={target}\n      rel={\n        rel ??\n        (target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n      }\n      aria-current={isActive ? \"page\" : undefined}\n      aria-expanded={ariaExpanded}\n      aria-disabled={disabled || undefined}\n      aria-label={panel.collapsed ? textLabel : undefined}\n      title={panel.collapsed ? textLabel : undefined}\n      tabIndex={disabled ? -1 : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.a>\n  ) : (\n    <motion.button\n      type=\"button\"\n      disabled={disabled}\n      aria-current={isActive ? \"page\" : undefined}\n      aria-expanded={ariaExpanded}\n      aria-label={panel.collapsed ? textLabel : undefined}\n      title={panel.collapsed ? textLabel : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/animated-sidebar/menu-sub-button.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport type { ReactNode } from \"react\";\nimport { SPRING_PRESS } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\nimport { useAnimatedSidebar } from \"./context\";\n\nexport interface AnimatedSidebarMenuSubButtonProps {\n  children: ReactNode;\n  /** Leading icon. Defaults to a small dot. */\n  icon?: ReactNode;\n  /** Renders a link to this URL instead of a button. */\n  href?: string;\n  /** Marks the row as the current page. Default: false */\n  isActive?: boolean;\n  /** Dims the row and blocks selection. Default: false */\n  disabled?: boolean;\n  /** Closes the mobile sidebar after selecting. Default: true */\n  closeOnSelect?: boolean;\n  /** Link target, used with `href`. */\n  target?: \"_blank\" | \"_self\" | \"_parent\" | \"_top\";\n  /** Link rel, used with `href`. Defaults to \"noreferrer noopener\" for \"_blank\". */\n  rel?: string;\n  /** Called when the row is clicked and not disabled. */\n  onSelect?: () => void;\n  /** Classes merged onto the button or link. */\n  className?: string;\n}\n\nexport function AnimatedSidebarMenuSubButton({\n  children,\n  icon,\n  href,\n  isActive = false,\n  disabled = false,\n  closeOnSelect = true,\n  target,\n  rel,\n  onSelect,\n  className,\n}: AnimatedSidebarMenuSubButtonProps) {\n  const context = useAnimatedSidebar();\n\n  const select = (\n    event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>,\n  ) => {\n    if (disabled) {\n      event.preventDefault();\n      return;\n    }\n    onSelect?.();\n    if (context.isMobile && closeOnSelect) context.setOpenMobile(false);\n  };\n\n  const content = (\n    <>\n      <span\n        aria-hidden=\"true\"\n        className=\"grid size-4 shrink-0 place-items-center\"\n      >\n        {icon ?? <span className=\"size-1 rounded-full bg-current\" />}\n      </span>\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n    </>\n  );\n\n  const interactiveClassName = cn(\n    \"flex min-h-8 w-full min-w-0 items-center gap-2 rounded-full px-3 text-left text-xs outline-none\",\n    \"text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground\",\n    \"focus-visible:bg-muted/70 focus-visible:ring-2 focus-visible:ring-ring\",\n    isActive && \"bg-muted/70 text-foreground\",\n    disabled && \"cursor-not-allowed opacity-40\",\n    className,\n  );\n\n  return href ? (\n    <motion.a\n      href={href}\n      target={target}\n      rel={\n        rel ??\n        (target === \"_blank\" ? \"noreferrer noopener\" : undefined)\n      }\n      aria-current={isActive ? \"page\" : undefined}\n      aria-disabled={disabled || undefined}\n      tabIndex={disabled ? -1 : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.a>\n  ) : (\n    <motion.button\n      type=\"button\"\n      disabled={disabled}\n      aria-current={isActive ? \"page\" : undefined}\n      onClick={select}\n      whileTap={context.reduce || disabled ? undefined : { scale: 0.98 }}\n      transition={SPRING_PRESS}\n      className={interactiveClassName}\n    >\n      {content}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/animated-sidebar/mobile-sidebar.tsx","type":"util","content":"\"use client\";\n\nimport { motion } from \"motion/react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { useFocusTrap } from \"@/lib/hooks/use-focus-trap\";\nimport { useScrollLock } from \"@/lib/scroll-lock\";\nimport { cn } from \"@/lib/utils\";\nimport {\n  AnimatedSidebarPanelContext,\n  type SidebarSide,\n  useAnimatedSidebar,\n} from \"./context\";\nimport { PANEL_TRANSITION, REDUCED_TRANSITION } from \"./motion\";\n\nexport function MobileSidebar({\n  ariaLabel,\n  children,\n  className,\n  side,\n}: {\n  ariaLabel: string;\n  children: ReactNode;\n  className?: string;\n  side: SidebarSide;\n}) {\n  const context = useAnimatedSidebar();\n  const panelRef = useRef<HTMLDivElement>(null);\n  const [mounted, setMounted] = useState(false);\n  // The sheet is mounted for as long as the viewport is mobile, so it hides\n  // itself while closed rather than sitting there transparent and interactive.\n  // Opening shows it in the same commit that starts the slide - a delayed show\n  // would run the focus effect below against a still-hidden panel, and focus()\n  // on a hidden element is ignored. Closing waits for the slide to finish, and\n  // the panel's own exit tells us when that is: no duration to keep in sync.\n  const [hidden, setHidden] = useState(!context.openMobile);\n  // The completion callback fires for the open slide too, and it reads state\n  // from whenever motion settles: a ref keeps it on the current one.\n  const openMobileRef = useRef(context.openMobile);\n\n  useEffect(() => setMounted(true), []);\n\n  useEffect(() => {\n    openMobileRef.current = context.openMobile;\n    if (context.openMobile) setHidden(false);\n  }, [context.openMobile]);\n\n  // A modal sheet: focus moves in, Tab stays inside, Escape closes, and focus\n  // returns to the opener. The fixed body lock holds on iOS Safari too.\n  const { openMobile, setOpenMobile } = context;\n  const closeMobile = useCallback(() => setOpenMobile(false), [setOpenMobile]);\n  useFocusTrap(openMobile && mounted, panelRef, { onEscape: closeMobile });\n  useScrollLock(openMobile, { fixed: true });\n\n  if (!mounted) return null;\n\n  // This container groups the sheet for hiding and the z-index and carries no\n  // box: both children are `fixed` and resolve against the viewport themselves.\n  // The scrim spans the viewport edges but paints a colour, and the panel is\n  // inset off one side and paints its own surface, so no layer here is a\n  // transparent edge-spanning one.\n  return createPortal(\n    <div\n      className={cn(\n        \"pointer-events-none fixed left-0 top-0 z-50 size-0 md:hidden\",\n        hidden && !context.openMobile ? \"invisible\" : \"visible\",\n      )}\n    >\n      <motion.button\n        type=\"button\"\n        aria-label={context.t(\"close\")}\n        tabIndex={context.openMobile ? 0 : -1}\n        initial={false}\n        animate={{ opacity: context.openMobile ? 1 : 0 }}\n        transition={\n          context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n        }\n        onClick={() => context.setOpenMobile(false)}\n        className={cn(\n          \"fixed inset-0 bg-black/40\",\n          context.openMobile\n            ? \"pointer-events-auto\"\n            : \"pointer-events-none\",\n        )}\n      />\n\n      <motion.div\n        ref={panelRef}\n        role=\"dialog\"\n        aria-modal=\"true\"\n        aria-label={ariaLabel}\n        aria-hidden={!context.openMobile}\n        inert={!context.openMobile}\n        tabIndex={-1}\n        data-mobile=\"true\"\n        data-state={context.openMobile ? \"expanded\" : \"collapsed\"}\n        data-side={side}\n        initial={false}\n        animate={{\n          opacity: context.reduce\n            ? context.openMobile\n              ? 1\n              : 0\n            : 1,\n          x: context.reduce\n            ? 0\n            : context.openMobile\n              ? \"0%\"\n              : side === \"left\"\n                ? \"-100%\"\n                : \"100%\",\n        }}\n        transition={\n          context.reduce ? REDUCED_TRANSITION : PANEL_TRANSITION\n        }\n        onAnimationComplete={() => {\n          if (!openMobileRef.current) setHidden(true);\n        }}\n        className={cn(\n          \"pointer-events-auto fixed inset-y-0 flex h-dvh w-(--sidebar-width-mobile) max-w-[88vw] flex-col overflow-hidden\",\n          \"border-border bg-background shadow-2xl will-change-transform\",\n          side === \"left\" ? \"left-0 border-r\" : \"right-0 border-l\",\n          !context.openMobile && \"pointer-events-none\",\n          className,\n        )}\n      >\n        <AnimatedSidebarPanelContext.Provider\n          value={{ collapsed: false, collapsible: \"none\", side }}\n        >\n          {children}\n        </AnimatedSidebarPanelContext.Provider>\n      </motion.div>\n    </div>,\n    document.body,\n  );\n}\n"},{"path":"components/motion/animated-sidebar/motion.ts","type":"util","content":"import type { Variants } from \"motion/react\";\nimport { EASE_DRAWER, EASE_OUT } from \"@/lib/ease\";\n\nexport const PANEL_TRANSITION = {\n  duration: 0.36,\n  ease: EASE_DRAWER,\n} as const;\n\n// The desktop rail settles at a hard zero-width boundary. Keep the spring\n// critically damped so it cannot overshoot, pause against that boundary, and\n// then snap back during the final frame.\nexport const SIDEBAR_MORPH_TRANSITION = {\n  type: \"spring\",\n  stiffness: 380,\n  damping: 35,\n  mass: 0.75,\n} as const;\n\nexport const LABEL_ENTER_TRANSITION = {\n  duration: 0.2,\n  delay: 0.08,\n  ease: EASE_OUT,\n} as const;\n\nexport const LABEL_EXIT_TRANSITION = {\n  duration: 0.12,\n  ease: EASE_OUT,\n} as const;\n\nconst SUBMENU_TRANSITION = {\n  duration: 0.18,\n  ease: EASE_OUT,\n} as const;\n\nexport const SUBMENU_VARIANTS: Variants = {\n  closed: {\n    opacity: 0,\n    clipPath: \"inset(0 0 100% 0 round 8px)\",\n    transition: {\n      duration: 0.14,\n      ease: EASE_OUT,\n      staggerChildren: 0.025,\n      staggerDirection: -1,\n    },\n  },\n  open: {\n    opacity: 1,\n    clipPath: \"inset(0 0 0% 0 round 8px)\",\n    transition: {\n      duration: 0.2,\n      delayChildren: 0.035,\n      ease: EASE_OUT,\n      staggerChildren: 0.045,\n    },\n  },\n};\n\nexport const SUBMENU_ITEM_VARIANTS: Variants = {\n  closed: {\n    opacity: 0,\n    y: -6,\n    filter: \"blur(3px)\",\n  },\n  open: {\n    opacity: 1,\n    y: 0,\n    filter: \"blur(0px)\",\n    transition: SUBMENU_TRANSITION,\n  },\n};\n\nexport const REDUCED_TRANSITION = {\n  duration: 0.16,\n  ease: EASE_OUT,\n} as const;\n"},{"path":"components/motion/animated-sidebar/use-is-mobile.ts","type":"util","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\nconst MOBILE_QUERY = \"(max-width: 767px)\";\n\nfunction subscribeToMobileQuery(callback: () => void) {\n  const query = window.matchMedia(MOBILE_QUERY);\n  query.addEventListener(\"change\", callback);\n  return () => query.removeEventListener(\"change\", callback);\n}\n\nfunction getMobileSnapshot() {\n  return window.matchMedia(MOBILE_QUERY).matches;\n}\n\nfunction getServerMobileSnapshot() {\n  return false;\n}\n\nexport function useIsMobile() {\n  return useSyncExternalStore(\n    subscribeToMobileQuery,\n    getMobileSnapshot,\n    getServerMobileSnapshot,\n  );\n}\n"},{"path":"components/motion/shared-layout-bg.tsx","type":"util","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n  type Variants,\n} from \"motion/react\";\nimport {\n  Children,\n  cloneElement,\n  forwardRef,\n  type HTMLAttributes,\n  type FocusEvent,\n  isValidElement,\n  type MouseEvent,\n  type ReactElement,\n  type ReactNode,\n  type Ref,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SPRING_LAYOUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SharedLayoutBgProps\n  extends Omit<HTMLAttributes<HTMLElement>, \"children\"> {\n  children: ReactNode;\n  /** Semantic container used for the children. */\n  as?: \"div\" | \"ul\";\n  /** Tailwind class applied to the moving pill. Defaults to a subtle foreground tint. */\n  pillClassName?: string;\n  /** Horizontal inset of the pill relative to each row (px). Default 20. */\n  inset?: number;\n  /** Optional positioning override for the pill wrapper inside each item. */\n  pillContainerClassName?: string;\n}\n\nconst variants: Variants = {\n  initial: { opacity: 0, filter: \"blur(6px)\" },\n  animate: { opacity: 1, filter: \"blur(0px)\" },\n  exit: (isActive: boolean) =>\n    !isActive ? { opacity: 0, filter: \"blur(6px)\" } : {},\n};\n\nconst reducedVariants: Variants = {\n  initial: { opacity: 0 },\n  animate: { opacity: 1 },\n  exit: (isActive: boolean) => (!isActive ? { opacity: 0 } : {}),\n};\n\nexport const SharedLayoutBg = forwardRef<HTMLElement, SharedLayoutBgProps>(\n  function SharedLayoutBg(\n    {\n      children,\n      as = \"div\",\n      className,\n      onMouseLeave,\n      onBlur,\n      pillClassName,\n      pillContainerClassName,\n      inset = 20,\n      ...props\n    },\n    forwardedRef,\n  ) {\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const uid = useId();\n  const reduce = useReducedMotion();\n  // Focus leaving the list only clears the pill when the pointer is not\n  // still resting on an item.\n  const hovering = useRef(false);\n\n    const renderedChildren = Children.toArray(children)\n      .filter(isValidElement)\n      .map((child, index) => {\n        const el = child as ReactElement<{\n          className?: string;\n          onMouseEnter?: (event: MouseEvent<HTMLElement>) => void;\n          onFocus?: (event: FocusEvent<HTMLElement>) => void;\n          children?: ReactNode;\n        }>;\n        const childKey = el.key ? String(el.key) : `item-${index}`;\n        return cloneElement(\n          el,\n          {\n            key: childKey,\n            className: cn(\"relative\", el.props.className),\n            onMouseEnter: (event: MouseEvent<HTMLElement>) => {\n              el.props.onMouseEnter?.(event);\n              hovering.current = true;\n              setActiveId(childKey);\n            },\n            // Focus bubbles in React, so a link or button anywhere inside the\n            // item brings the pill to it for keyboard users too.\n            onFocus: (event: FocusEvent<HTMLElement>) => {\n              el.props.onFocus?.(event);\n              setActiveId(childKey);\n            },\n          },\n          <>\n            <AnimatePresence custom={activeId !== null}>\n              {activeId !== null ? (\n                <motion.div\n                  variants={reduce ? reducedVariants : variants}\n                  initial=\"initial\"\n                  animate=\"animate\"\n                  exit=\"exit\"\n                  custom={activeId !== null}\n                  className={cn(\n                    \"pointer-events-none absolute inset-y-0\",\n                    pillContainerClassName,\n                  )}\n                  style={{ left: -inset, right: -inset }}\n                >\n                  {activeId === childKey ? (\n                    <motion.div\n                      layoutId={`shared-bg-${uid}`}\n                      transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n                      className={cn(\n                        \"pointer-events-none h-full w-full rounded-2xl bg-muted/80\",\n                        pillClassName,\n                      )}\n                    />\n                  ) : null}\n                </motion.div>\n              ) : null}\n            </AnimatePresence>\n            <div className=\"relative z-10\">{el.props.children}</div>\n          </>,\n        );\n      });\n\n    const handleMouseLeave = (event: MouseEvent<HTMLElement>) => {\n      hovering.current = false;\n      // Keep the pill on a focused item so keyboard position stays visible.\n      if (!event.currentTarget.contains(document.activeElement))\n        setActiveId(null);\n      onMouseLeave?.(event);\n    };\n\n    const handleBlur = (event: FocusEvent<HTMLElement>) => {\n      const next = event.relatedTarget;\n      if (\n        !hovering.current &&\n        !(next instanceof Node && event.currentTarget.contains(next))\n      )\n        setActiveId(null);\n      onBlur?.(event);\n    };\n\n    // layoutRoot scopes the pill's layout projection to this list, so fixed or\n    // scrolled ancestors can't smear scroll offsets into its movement.\n    return as === \"ul\" ? (\n      <motion.ul\n        {...(props as HTMLMotionProps<\"ul\">)}\n        ref={forwardedRef as Ref<HTMLUListElement>}\n        layoutRoot\n        onMouseLeave={handleMouseLeave}\n        onBlur={handleBlur}\n        className={cn(\"flex w-full flex-col\", className)}\n      >\n        {renderedChildren}\n      </motion.ul>\n    ) : (\n      <motion.div\n        {...(props as HTMLMotionProps<\"div\">)}\n        ref={forwardedRef as Ref<HTMLDivElement>}\n        layoutRoot\n        onMouseLeave={handleMouseLeave}\n        onBlur={handleBlur}\n        className={cn(\"flex w-full flex-col\", className)}\n      >\n        {renderedChildren}\n      </motion.div>\n    );\n  },\n);\n"},{"path":"lib/hooks/use-focus-trap.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { cycleTab, focusFirstIn } from \"@/lib/focusable\";\nimport { inLayerAbove, type Layer, openLayer, ownsEscape, trapAbove } from \"@/lib/layers\";\n\nexport interface FocusTrapOptions {\n  /** Called on Escape while this is the innermost open layer. */\n  onEscape?: () => void;\n}\n\n/**\n * Moves focus into `panel` when `open` turns true, keeps Tab cycling inside it,\n * pulls focus back if it lands outside, and returns focus to whatever held it\n * before opening once `open` turns false.\n *\n * Layers opened on top (a menu portaled out of a drawer, a sheet opened from\n * it) keep focus and Escape until they close: see `lib/layers.ts`.\n *\n * For overlays rendered in place, where `useModalScope` cannot inert the rest\n * of the page. Pass `open` rather than presence: an exiting panel is already\n * inert through `PresenceGate`, so the trap releases with the same commit.\n * Give the panel `tabIndex={-1}` so it can take focus when it holds nothing\n * focusable.\n */\nexport function useFocusTrap(\n  open: boolean,\n  panel: RefObject<HTMLElement | null>,\n  { onEscape }: FocusTrapOptions = {},\n) {\n  const escapeRef = useRef(onEscape);\n  useLayoutEffect(() => {\n    escapeRef.current = onEscape;\n  });\n\n  useEffect(() => {\n    if (!open || !panel.current) return;\n    const layer: Layer = {\n      contains: (target) => Boolean(panel.current?.contains(target)),\n      traps: true,\n      get escape() {\n        return Boolean(escapeRef.current);\n      },\n    };\n    const closeLayer = openLayer(layer);\n    const returnFocus =\n      document.activeElement instanceof HTMLElement\n        ? document.activeElement\n        : null;\n    if (!panel.current.contains(document.activeElement)) focusFirstIn(panel.current);\n\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (!(target instanceof Node) || !panel.current) return;\n      if (panel.current.closest(\"[inert]\") || panel.current.contains(target)) return;\n      if (inLayerAbove(layer, target) || trapAbove(layer)) return;\n      focusFirstIn(panel.current);\n    };\n    const onKey = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") {\n        if (!escapeRef.current || !ownsEscape(layer, event)) return;\n        event.preventDefault();\n        escapeRef.current();\n        return;\n      }\n      const active = document.activeElement;\n      if (event.defaultPrevented || (active && inLayerAbove(layer, active))) return;\n      cycleTab(event, panel.current);\n    };\n    document.addEventListener(\"focusin\", onFocus);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"focusin\", onFocus);\n      document.removeEventListener(\"keydown\", onKey);\n      closeLayer();\n      if (returnFocus?.isConnected && !returnFocus.closest(\"[inert]\"))\n        returnFocus.focus({ preventScroll: true });\n    };\n  }, [open, panel]);\n}\n"},{"path":"lib/scroll-lock.ts","type":"util","content":"\"use client\";\n\nimport { useEffect } from \"react\";\n\nexport interface ScrollLockOptions {\n  /**\n   * Pin the body with `position: fixed` and restore the scroll offset on\n   * release. iOS Safari still scrolls an `overflow: hidden` body under a\n   * touch drag, so full-screen sheets that take touch gestures need this.\n   */\n  fixed?: boolean;\n}\n\n// Reference-counted, so overlays that close out of order never unlock the\n// page under one that is still open. The first lock picks the technique.\nlet owners = 0;\nlet restore: (() => void) | null = null;\n\nfunction apply({ fixed = false }: ScrollLockOptions) {\n  const root = document.documentElement;\n  const body = document.body;\n  const scrollY = window.scrollY;\n  const previous = {\n    rootOverflow: root.style.overflow,\n    overflow: body.style.overflow,\n    position: body.style.position,\n    top: body.style.top,\n    left: body.style.left,\n    right: body.style.right,\n  };\n  root.style.overflow = \"hidden\";\n  body.style.overflow = \"hidden\";\n  if (fixed) {\n    body.style.position = \"fixed\";\n    body.style.top = `-${scrollY}px`;\n    body.style.left = \"0\";\n    body.style.right = \"0\";\n  }\n  return () => {\n    root.style.overflow = previous.rootOverflow;\n    body.style.overflow = previous.overflow;\n    if (!fixed) return;\n    body.style.position = previous.position;\n    body.style.top = previous.top;\n    body.style.left = previous.left;\n    body.style.right = previous.right;\n    window.scrollTo(0, scrollY);\n  };\n}\n\n/** Locks page scroll. Call the returned function to release this lock. */\nexport function lockScroll(options: ScrollLockOptions = {}) {\n  if (owners++ === 0) restore = apply(options);\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    if (--owners === 0) {\n      restore?.();\n      restore = null;\n    }\n  };\n}\n\n/** Locks page scroll while `locked` is true. */\nexport function useScrollLock(locked: boolean, { fixed = false }: ScrollLockOptions = {}) {\n  useEffect(() => {\n    if (!locked) return;\n    return lockScroll({ fixed });\n  }, [locked, fixed]);\n}\n"}]}