{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"file-manager","type":"registry:block","title":"File Manager","description":"File browser with breadcrumb navigation, folders that slide in from the side you travel, grid/list views, click / Cmd-Ctrl-click / Shift-click range selection with arrow-key movement, kind-tinted file icons, a sort menu, a storage usage meter, and a drop overlay that adds dragged-in files to the open folder.","author":"kara <ztzyrant@gmail.com>","dependencies":["clsx","lucide-react","motion","tailwind-merge"],"registryDependencies":[],"files":[{"path":"components/motion/file-manager.tsx","type":"registry:component","target":"@components/motion/file-manager.tsx","content":"\"use client\";\n// karaui.kamisama-v0.my.id/components/blocks/file-manager\n\nimport {\n  ArrowDownWideNarrow,\n  ArrowUpNarrowWide,\n  File,\n  FileArchive,\n  FileAudio,\n  FileCode,\n  FileImage,\n  FileSpreadsheet,\n  FileText,\n  FileVideo,\n  Folder,\n  HardDrive,\n  LayoutGrid,\n  List,\n  Upload,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  type DragEvent,\n  type KeyboardEvent,\n  type MouseEvent,\n  type ReactNode,\n  useCallback,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  Breadcrumb,\n  BreadcrumbItem,\n  BreadcrumbLink,\n  BreadcrumbList,\n  BreadcrumbPage,\n  BreadcrumbSeparator,\n} from \"@/components/motion/breadcrumb\";\nimport {\n  DropdownMenu,\n  DropdownMenuContent,\n  DropdownMenuLabel,\n  DropdownMenuRadioGroup,\n  DropdownMenuRadioItem,\n  DropdownMenuSeparator,\n  DropdownMenuTrigger,\n} from \"@/components/motion/dropdown-menu\";\nimport { Progress } from \"@/components/motion/progress\";\nimport { ToggleGroup, ToggleGroupItem } from \"@/components/motion/toggle-group\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type FileKind =\n  | \"folder\"\n  | \"image\"\n  | \"video\"\n  | \"audio\"\n  | \"document\"\n  | \"code\"\n  | \"archive\"\n  | \"spreadsheet\"\n  | \"other\";\n\nexport interface FileNode {\n  id: string;\n  name: string;\n  kind: FileKind;\n  /** Bytes. Folders show their item count instead. */\n  size?: number;\n  /** ISO date string, formatted with `locale` in UTC. */\n  modified?: string;\n  children?: FileNode[];\n}\n\nexport type FileView = \"grid\" | \"list\";\nexport type FileSortKey = \"name\" | \"modified\" | \"size\" | \"kind\";\nexport type FileSort = { key: FileSortKey; direction: \"asc\" | \"desc\" };\n\nexport interface FileManagerProps {\n  /** The root folder. Dropped files are added to the internal copy. */\n  root: FileNode;\n  /** Controlled path: ids from the root's child down to the open folder. */\n  path?: string[];\n  defaultPath?: string[];\n  onPathChange?: (path: string[]) => void;\n  view?: FileView;\n  defaultView?: FileView;\n  onViewChange?: (view: FileView) => void;\n  /** Controlled selection (ids in the open folder). */\n  selection?: string[];\n  defaultSelection?: string[];\n  onSelectionChange?: (ids: string[]) => void;\n  defaultSort?: FileSort;\n  /** Fires when a file (not a folder) is opened by double-click or Enter. */\n  onOpenFile?: (file: FileNode, path: string[]) => void;\n  /** Fires with dropped files and the folder they landed in. */\n  onUpload?: (files: File[], folderId: string) => void;\n  /** Storage meter in bytes. Omit to hide the footer meter. */\n  storage?: { used: number; total: number };\n  /** Default \"en-US\" so server and client agree. */\n  locale?: string;\n  className?: string;\n}\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange: ((next: T) => void) | undefined,\n) {\n  const [internal, setInternal] = useState(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const set = useCallback(\n    (next: T) => {\n      if (!controlled) setInternal(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\nconst KIND_ICON: Record<FileKind, typeof File> = {\n  folder: Folder,\n  image: FileImage,\n  video: FileVideo,\n  audio: FileAudio,\n  document: FileText,\n  code: FileCode,\n  archive: FileArchive,\n  spreadsheet: FileSpreadsheet,\n  other: File,\n};\n\n// Each kind tints its icon with one chart token so types read at a glance.\nconst KIND_TINT: Record<FileKind, string> = {\n  folder: \"text-chart-1\",\n  image: \"text-chart-5\",\n  video: \"text-chart-2\",\n  audio: \"text-chart-3\",\n  document: \"text-muted-foreground\",\n  code: \"text-chart-3\",\n  archive: \"text-chart-4\",\n  spreadsheet: \"text-chart-3\",\n  other: \"text-muted-foreground\",\n};\n\nconst EXT_KIND: Record<string, FileKind> = {\n  png: \"image\", jpg: \"image\", jpeg: \"image\", gif: \"image\", webp: \"image\", svg: \"image\",\n  mp4: \"video\", mov: \"video\", webm: \"video\",\n  mp3: \"audio\", wav: \"audio\", flac: \"audio\",\n  pdf: \"document\", doc: \"document\", docx: \"document\", txt: \"document\", md: \"document\",\n  ts: \"code\", tsx: \"code\", js: \"code\", json: \"code\", css: \"code\", html: \"code\", py: \"code\",\n  zip: \"archive\", gz: \"archive\", tar: \"archive\", rar: \"archive\",\n  csv: \"spreadsheet\", xls: \"spreadsheet\", xlsx: \"spreadsheet\",\n};\n\n/** Best-guess kind from a file name's extension. */\nexport function fileKindFromName(name: string): FileKind {\n  const ext = name.split(\".\").pop()?.toLowerCase() ?? \"\";\n  return EXT_KIND[ext] ?? \"other\";\n}\n\n/** \"1.2 MB\"-style size, en-US digits. */\nexport function formatBytes(bytes: number) {\n  if (bytes < 1024) return `${bytes} B`;\n  const units = [\"KB\", \"MB\", \"GB\", \"TB\"];\n  let value = bytes / 1024;\n  let unit = 0;\n  while (value >= 1024 && unit < units.length - 1) {\n    value /= 1024;\n    unit++;\n  }\n  return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`;\n}\n\nfunction findFolder(root: FileNode, path: string[]) {\n  const trail: FileNode[] = [root];\n  let node = root;\n  for (const id of path) {\n    const next = node.children?.find((c) => c.id === id && c.kind === \"folder\");\n    if (!next) break;\n    trail.push(next);\n    node = next;\n  }\n  return trail;\n}\n\nfunction addToFolder(node: FileNode, folderId: string, files: FileNode[]): FileNode {\n  if (node.id === folderId) return { ...node, children: [...(node.children ?? []), ...files] };\n  if (!node.children) return node;\n  return { ...node, children: node.children.map((c) => addToFolder(c, folderId, files)) };\n}\n\nconst SORT_LABEL: Record<FileSortKey, string> = {\n  name: \"Name\",\n  modified: \"Date modified\",\n  size: \"Size\",\n  kind: \"Type\",\n};\n\n/**\n * File browser block: breadcrumb path, grid/list toggle, sort menu, folders\n * that slide in from the side you travel (deeper from the right, up from the\n * left), click / Cmd-Ctrl-click / Shift-click range selection, kind icons,\n * a storage meter, and a drop overlay that adds dragged-in files to the open\n * folder.\n */\nexport function FileManager({\n  root,\n  path: pathProp,\n  defaultPath = [],\n  onPathChange,\n  view: viewProp,\n  defaultView = \"grid\",\n  onViewChange,\n  selection: selectionProp,\n  defaultSelection = [],\n  onSelectionChange,\n  defaultSort = { key: \"name\", direction: \"asc\" },\n  onOpenFile,\n  onUpload,\n  storage,\n  locale = \"en-US\",\n  className,\n}: FileManagerProps) {\n  const reduce = useReducedMotion();\n  const [tree, setTree] = useState(root);\n  const [path, setPathState] = useControllable(pathProp, defaultPath, onPathChange);\n  const [view, setView] = useControllable(viewProp, defaultView, onViewChange);\n  const [selection, setSelection] = useControllable(\n    selectionProp,\n    defaultSelection,\n    onSelectionChange,\n  );\n  const [sort, setSort] = useState<FileSort>(defaultSort);\n  const [dir, setDir] = useState<1 | -1>(1);\n  const [dragging, setDragging] = useState(false);\n  const dragDepth = useRef(0);\n  const anchor = useRef<string | null>(null);\n  const gridRef = useRef<HTMLDivElement>(null);\n\n  const trail = findFolder(tree, path);\n  const folder = trail[trail.length - 1];\n  const folderKey = trail.map((n) => n.id).join(\"/\");\n\n  const dateFormat = useMemo(\n    () =>\n      new Intl.DateTimeFormat(locale, {\n        month: \"short\",\n        day: \"numeric\",\n        year: \"numeric\",\n        timeZone: \"UTC\",\n      }),\n    [locale],\n  );\n\n  const items = useMemo(() => {\n    const list = [...(folder.children ?? [])];\n    const sign = sort.direction === \"asc\" ? 1 : -1;\n    list.sort((a, b) => {\n      // Folders always first, like every desktop file manager.\n      if ((a.kind === \"folder\") !== (b.kind === \"folder\")) return a.kind === \"folder\" ? -1 : 1;\n      let cmp = 0;\n      if (sort.key === \"name\") cmp = a.name.localeCompare(b.name, locale);\n      else if (sort.key === \"modified\") cmp = (a.modified ?? \"\").localeCompare(b.modified ?? \"\");\n      else if (sort.key === \"size\") cmp = (a.size ?? 0) - (b.size ?? 0);\n      else cmp = a.kind.localeCompare(b.kind) || a.name.localeCompare(b.name, locale);\n      return cmp * sign;\n    });\n    return list;\n  }, [folder, sort, locale]);\n\n  const selected = new Set(selection);\n\n  const navigate = (next: string[]) => {\n    setDir(next.length >= path.length ? 1 : -1);\n    setPathState(next);\n    setSelection([]);\n    anchor.current = null;\n  };\n\n  const open = (item: FileNode) => {\n    if (item.kind === \"folder\") navigate([...trail.slice(1).map((n) => n.id), item.id]);\n    else onOpenFile?.(item, path);\n  };\n\n  const select = (item: FileNode, event: MouseEvent | KeyboardEvent) => {\n    const ids = items.map((i) => i.id);\n    if (event.shiftKey && anchor.current && ids.includes(anchor.current)) {\n      const a = ids.indexOf(anchor.current);\n      const b = ids.indexOf(item.id);\n      const range = ids.slice(Math.min(a, b), Math.max(a, b) + 1);\n      const base = event.metaKey || event.ctrlKey ? selection : [];\n      setSelection(Array.from(new Set([...base, ...range])));\n      return;\n    }\n    anchor.current = item.id;\n    if (event.metaKey || event.ctrlKey) {\n      setSelection(\n        selected.has(item.id) ? selection.filter((id) => id !== item.id) : [...selection, item.id],\n      );\n    } else setSelection([item.id]);\n  };\n\n  const onContainerKey = (event: KeyboardEvent<HTMLDivElement>) => {\n    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"a\") {\n      event.preventDefault();\n      setSelection(items.map((i) => i.id));\n    } else if (event.key === \"Escape\") setSelection([]);\n    else if (event.key === \"Backspace\" && event.altKey && path.length > 0) {\n      navigate(path.slice(0, -1));\n    }\n  };\n\n  const onItemKey = (event: KeyboardEvent<HTMLButtonElement>, item: FileNode, i: number) => {\n    if (event.key === \"Enter\") {\n      event.preventDefault();\n      open(item);\n      return;\n    }\n    if (event.key === \" \") {\n      event.preventDefault();\n      select(item, event);\n      return;\n    }\n    const columns =\n      view === \"grid\" && gridRef.current\n        ? getComputedStyle(gridRef.current).gridTemplateColumns.split(\" \").length\n        : 1;\n    const delta: Record<string, number> = {\n      ArrowRight: view === \"grid\" ? 1 : 0,\n      ArrowLeft: view === \"grid\" ? -1 : 0,\n      ArrowDown: columns,\n      ArrowUp: -columns,\n    };\n    const move = delta[event.key];\n    if (!move) return;\n    event.preventDefault();\n    const target = items[Math.min(items.length - 1, Math.max(0, i + move))];\n    const buttons = gridRef.current?.querySelectorAll<HTMLButtonElement>(\"[data-file-item]\");\n    buttons?.[items.indexOf(target)]?.focus();\n    if (event.shiftKey) select(target, event);\n  };\n\n  // Drop zone: only react to real file drags (not text or links).\n  const hasFiles = (event: DragEvent) => Array.from(event.dataTransfer.types).includes(\"Files\");\n  const dropHandlers = {\n    onDragEnter: (event: DragEvent<HTMLDivElement>) => {\n      if (!hasFiles(event)) return;\n      event.preventDefault();\n      dragDepth.current += 1;\n      setDragging(true);\n    },\n    onDragOver: (event: DragEvent<HTMLDivElement>) => {\n      if (!hasFiles(event)) return;\n      event.preventDefault();\n      event.dataTransfer.dropEffect = \"copy\";\n    },\n    onDragLeave: (event: DragEvent<HTMLDivElement>) => {\n      if (!hasFiles(event)) return;\n      dragDepth.current = Math.max(0, dragDepth.current - 1);\n      if (dragDepth.current === 0) setDragging(false);\n    },\n    onDrop: (event: DragEvent<HTMLDivElement>) => {\n      if (!hasFiles(event)) return;\n      event.preventDefault();\n      dragDepth.current = 0;\n      setDragging(false);\n      const files = Array.from(event.dataTransfer.files);\n      if (files.length === 0) return;\n      // \"Now\" is read inside the event handler, never during render.\n      const stamp = new Date().toISOString();\n      const nodes: FileNode[] = files.map((f, i) => ({\n        id: `upload-${stamp}-${i}-${f.name}`,\n        name: f.name,\n        kind: fileKindFromName(f.name),\n        size: f.size,\n        modified: stamp,\n      }));\n      setTree((t) => addToFolder(t, folder.id, nodes));\n      setSelection(nodes.map((n) => n.id));\n      onUpload?.(files, folder.id);\n    },\n  };\n\n  const slide = {\n    enter: (d: number) => (reduce ? { opacity: 0 } : { opacity: 0, x: d * 32 }),\n    center: { opacity: 1, x: 0 },\n    exit: (d: number) => (reduce ? { opacity: 0 } : { opacity: 0, x: d * -32 }),\n  };\n\n  return (\n    <div\n      {...dropHandlers}\n      className={cn(\n        \"@container relative flex h-[26rem] w-full flex-col overflow-hidden rounded-2xl border border-border bg-card text-card-foreground shadow-sm\",\n        className,\n      )}\n    >\n      {/* Toolbar */}\n      <div className=\"flex items-center gap-2 border-b border-border px-3 py-2\">\n        <Breadcrumb className=\"min-w-0 flex-1 text-xs\">\n          <BreadcrumbList className=\"flex-nowrap overflow-hidden\">\n            {trail.map((node, i) => {\n              const last = i === trail.length - 1;\n              const target = trail.slice(1, i + 1).map((n) => n.id);\n              return (\n                <BreadcrumbCrumb key={node.id} first={i === 0}>\n                  {last ? (\n                    <BreadcrumbPage className=\"truncate\">{node.name}</BreadcrumbPage>\n                  ) : (\n                    <BreadcrumbLink\n                      href=\"#\"\n                      render={({ className: linkClass, children }) => (\n                        <button\n                          type=\"button\"\n                          className={cn(linkClass, \"truncate\")}\n                          onClick={() => navigate(target)}\n                        >\n                          {children}\n                        </button>\n                      )}\n                    >\n                      {node.name}\n                    </BreadcrumbLink>\n                  )}\n                </BreadcrumbCrumb>\n              );\n            })}\n          </BreadcrumbList>\n        </Breadcrumb>\n\n        <DropdownMenu>\n          <DropdownMenuTrigger>\n            <button\n              type=\"button\"\n              aria-label={`Sort by ${SORT_LABEL[sort.key]}`}\n              className=\"inline-flex h-7 items-center gap-1.5 rounded-md border border-border px-2 text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-primary\"\n            >\n              {sort.direction === \"asc\" ? (\n                <ArrowUpNarrowWide aria-hidden className=\"size-3.5\" />\n              ) : (\n                <ArrowDownWideNarrow aria-hidden className=\"size-3.5\" />\n              )}\n              <span className=\"hidden @md:inline\">{SORT_LABEL[sort.key]}</span>\n            </button>\n          </DropdownMenuTrigger>\n          <DropdownMenuContent align=\"end\" className=\"w-44\">\n            <DropdownMenuLabel>Sort by</DropdownMenuLabel>\n            <DropdownMenuRadioGroup\n              ariaLabel=\"Sort by\"\n              value={sort.key}\n              onValueChange={(key) => setSort({ ...sort, key: key as FileSortKey })}\n            >\n              {(Object.keys(SORT_LABEL) as FileSortKey[]).map((key) => (\n                <DropdownMenuRadioItem key={key} value={key}>\n                  {SORT_LABEL[key]}\n                </DropdownMenuRadioItem>\n              ))}\n            </DropdownMenuRadioGroup>\n            <DropdownMenuSeparator />\n            <DropdownMenuRadioGroup\n              ariaLabel=\"Order\"\n              value={sort.direction}\n              onValueChange={(direction) =>\n                setSort({ ...sort, direction: direction as FileSort[\"direction\"] })\n              }\n            >\n              <DropdownMenuRadioItem value=\"asc\">Ascending</DropdownMenuRadioItem>\n              <DropdownMenuRadioItem value=\"desc\">Descending</DropdownMenuRadioItem>\n            </DropdownMenuRadioGroup>\n          </DropdownMenuContent>\n        </DropdownMenu>\n\n        <ToggleGroup\n          type=\"single\"\n          required\n          size=\"sm\"\n          variant=\"outline\"\n          value={view}\n          onValueChange={(v) => v && setView(v as FileView)}\n          aria-label=\"View\"\n        >\n          <ToggleGroupItem value=\"grid\" aria-label=\"Grid view\">\n            <LayoutGrid aria-hidden />\n          </ToggleGroupItem>\n          <ToggleGroupItem value=\"list\" aria-label=\"List view\">\n            <List aria-hidden />\n          </ToggleGroupItem>\n        </ToggleGroup>\n      </div>\n\n      {/* Items */}\n      {/* biome-ignore lint/a11y/noStaticElementInteractions: keyboard shortcuts (select all, clear, up) for the item grid; items are real buttons. */}\n      <div\n        onKeyDown={onContainerKey}\n        className=\"relative min-h-0 flex-1 overflow-y-auto overflow-x-hidden [scrollbar-color:var(--border-strong)_transparent] [scrollbar-width:thin]\"\n      >\n        <AnimatePresence initial={false} mode=\"popLayout\" custom={dir}>\n          <motion.div\n            key={`${folderKey}:${view}`}\n            custom={dir}\n            variants={slide}\n            initial=\"enter\"\n            animate=\"center\"\n            exit=\"exit\"\n            transition={{ duration: 0.22, ease: EASE_OUT }}\n            className=\"p-2\"\n          >\n            {items.length === 0 ? (\n              <div className=\"flex h-60 flex-col items-center justify-center gap-2 text-xs text-muted-foreground\">\n                <Upload aria-hidden className=\"size-5\" />\n                This folder is empty — drop files here\n              </div>\n            ) : view === \"grid\" ? (\n              <div\n                ref={gridRef}\n                className=\"grid grid-cols-3 gap-1 @md:grid-cols-4 @xl:grid-cols-5\"\n              >\n                {items.map((item, i) => (\n                  <ItemButton\n                    key={item.id}\n                    item={item}\n                    view=\"grid\"\n                    selected={selected.has(item.id)}\n                    meta={meta(item, dateFormat)}\n                    index={i}\n                    reduce={Boolean(reduce)}\n                    onClick={(e) => select(item, e)}\n                    onDoubleClick={() => open(item)}\n                    onKeyDown={(e) => onItemKey(e, item, i)}\n                  />\n                ))}\n              </div>\n            ) : (\n              <div ref={gridRef} className=\"flex flex-col\">\n                <div className=\"grid grid-cols-[1fr_5rem] gap-3 px-2 pb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground @md:grid-cols-[1fr_7rem_5rem]\">\n                  <span>Name</span>\n                  <span className=\"hidden @md:block\">Modified</span>\n                  <span className=\"text-right\">Size</span>\n                </div>\n                {items.map((item, i) => (\n                  <ItemButton\n                    key={item.id}\n                    item={item}\n                    view=\"list\"\n                    selected={selected.has(item.id)}\n                    meta={meta(item, dateFormat)}\n                    index={i}\n                    reduce={Boolean(reduce)}\n                    onClick={(e) => select(item, e)}\n                    onDoubleClick={() => open(item)}\n                    onKeyDown={(e) => onItemKey(e, item, i)}\n                  />\n                ))}\n              </div>\n            )}\n          </motion.div>\n        </AnimatePresence>\n      </div>\n\n      {/* Footer */}\n      <div className=\"flex items-center gap-3 border-t border-border px-3 py-2 text-[11px] text-muted-foreground\">\n        <span aria-live=\"polite\" className=\"shrink-0 tabular-nums\">\n          {selection.length > 0\n            ? `${selection.length} of ${items.length} selected`\n            : `${items.length} ${items.length === 1 ? \"item\" : \"items\"}`}\n        </span>\n        {storage ? (\n          <div className=\"ml-auto flex w-40 items-center gap-2 @md:w-56\">\n            <HardDrive aria-hidden className=\"size-3.5 shrink-0\" />\n            <Progress\n              value={storage.used}\n              max={storage.total}\n              size=\"sm\"\n              trackClassName=\"bg-foreground/10\"\n              aria-label=\"Storage used\"\n              className=\"flex-1\"\n            />\n            <span className=\"shrink-0 tabular-nums\">\n              {formatBytes(storage.used)} / {formatBytes(storage.total)}\n            </span>\n          </div>\n        ) : null}\n      </div>\n\n      {/* Drop overlay */}\n      <AnimatePresence>\n        {dragging ? (\n          <motion.div\n            key=\"drop\"\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            exit={{ opacity: 0, transition: { duration: 0.12 } }}\n            transition={{ duration: 0.18, ease: EASE_OUT }}\n            className=\"pointer-events-none absolute inset-2 z-20 flex flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-primary bg-background/85 backdrop-blur-sm\"\n          >\n            <motion.span\n              initial={reduce ? false : { y: 8, scale: 0.9 }}\n              animate={reduce ? undefined : { y: [0, -4, 0], scale: 1 }}\n              transition={\n                reduce\n                  ? undefined\n                  : { y: { duration: 1.2, repeat: Number.POSITIVE_INFINITY, ease: EASE_OUT } }\n              }\n              className=\"grid size-11 place-items-center rounded-full bg-primary text-primary-foreground shadow-md\"\n            >\n              <Upload aria-hidden className=\"size-5\" />\n            </motion.span>\n            <p className=\"text-sm font-medium\">Drop to upload to {folder.name}</p>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction BreadcrumbCrumb({ first, children }: { first: boolean; children: ReactNode }) {\n  return (\n    <>\n      {first ? null : <BreadcrumbSeparator />}\n      <BreadcrumbItem className=\"min-w-0\">{children}</BreadcrumbItem>\n    </>\n  );\n}\n\nfunction meta(item: FileNode, dateFormat: Intl.DateTimeFormat) {\n  const size =\n    item.kind === \"folder\"\n      ? `${item.children?.length ?? 0} ${item.children?.length === 1 ? \"item\" : \"items\"}`\n      : item.size !== undefined\n        ? formatBytes(item.size)\n        : \"—\";\n  const modified = item.modified ? dateFormat.format(new Date(item.modified)) : \"—\";\n  return { size, modified };\n}\n\nfunction ItemButton({\n  item,\n  view,\n  selected,\n  meta: info,\n  index,\n  reduce,\n  onClick,\n  onDoubleClick,\n  onKeyDown,\n}: {\n  item: FileNode;\n  view: FileView;\n  selected: boolean;\n  meta: { size: string; modified: string };\n  index: number;\n  reduce: boolean;\n  onClick: (event: MouseEvent<HTMLButtonElement>) => void;\n  onDoubleClick: () => void;\n  onKeyDown: (event: KeyboardEvent<HTMLButtonElement>) => void;\n}) {\n  const Icon = KIND_ICON[item.kind];\n  const tint = KIND_TINT[item.kind];\n  const label = `${item.name}, ${item.kind === \"folder\" ? \"folder\" : item.kind}, ${info.size}`;\n\n  return (\n    <motion.button\n      type=\"button\"\n      data-file-item=\"\"\n      aria-pressed={selected}\n      aria-label={label}\n      onClick={onClick}\n      onDoubleClick={onDoubleClick}\n      onKeyDown={onKeyDown}\n      // Shift-click must not select page text.\n      onMouseDown={(e) => e.shiftKey && e.preventDefault()}\n      initial={reduce ? false : { opacity: 0, y: 6 }}\n      animate={{ opacity: 1, y: 0 }}\n      transition={{ duration: 0.2, ease: EASE_OUT, delay: reduce ? 0 : Math.min(index, 12) * 0.02 }}\n      className={cn(\n        \"group relative rounded-lg text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-primary\",\n        view === \"grid\"\n          ? \"flex flex-col items-center gap-1.5 px-2 pt-3 pb-2\"\n          : \"grid grid-cols-[1fr_5rem] items-center gap-3 px-2 py-1.5 @md:grid-cols-[1fr_7rem_5rem]\",\n        selected ? \"bg-primary/10 ring-1 ring-primary/40\" : \"hover:bg-muted\",\n      )}\n    >\n      {view === \"grid\" ? (\n        <>\n          <span\n            className={cn(\n              \"grid size-12 place-items-center rounded-xl bg-muted transition-transform group-hover:-translate-y-0.5\",\n              selected && \"bg-primary/15\",\n            )}\n          >\n            <Icon aria-hidden className={cn(\"size-6\", tint)} />\n          </span>\n          <span className=\"w-full truncate text-center text-xs font-medium\">{item.name}</span>\n          <span className=\"text-[10px] text-muted-foreground\">{info.size}</span>\n        </>\n      ) : (\n        <>\n          <span className=\"flex min-w-0 items-center gap-2\">\n            <Icon aria-hidden className={cn(\"size-4 shrink-0\", tint)} />\n            <span className=\"truncate text-xs font-medium\">{item.name}</span>\n          </span>\n          <span className=\"hidden truncate text-[11px] text-muted-foreground @md:block\">\n            {info.modified}\n          </span>\n          <span className=\"text-right text-[11px] tabular-nums text-muted-foreground\">\n            {info.size}\n          </span>\n        </>\n      )}\n    </motion.button>\n  );\n}\n"},{"path":"components/motion/breadcrumb.tsx","type":"registry:component","target":"@components/motion/breadcrumb.tsx","content":"\"use client\";\n\nimport { ChevronRight, Ellipsis } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  LayoutGroup,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  useEffect,\n  useId,\n  useRef,\n  useState,\n  type ComponentProps,\n  type ComponentPropsWithoutRef,\n  type KeyboardEvent,\n  type ReactElement,\n  type ReactNode,\n} from \"react\";\nimport { EASE_OUT_CSS, SPRING_LAYOUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\n/* ------------------------------------------------------------------------ */\n/* Composable primitives                                                     */\n/* ------------------------------------------------------------------------ */\n\nexport type BreadcrumbDataItem = {\n  label: ReactNode;\n  href?: string;\n  icon?: ReactNode;\n  /** Render the link through your router, e.g. `(p) => <Link {...p} />`. */\n  render?: (props: BreadcrumbLinkRenderProps) => ReactElement;\n};\n\ntype BreadcrumbNavProps = ComponentPropsWithoutRef<\"nav\">;\n\nexport type BreadcrumbProps = BreadcrumbNavProps & {\n  /** Data-driven mode. Omit to compose `BreadcrumbList` children yourself. */\n  items?: BreadcrumbDataItem[];\n  /** Collapse middle items into \"…\" when there are more than this many. */\n  maxItems?: number;\n  /** \"expand\" reveals hidden items inline; \"menu\" lists them in a dropdown. */\n  collapse?: \"expand\" | \"menu\";\n  separator?: ReactNode;\n};\n\nexport function Breadcrumb({\n  items,\n  maxItems = 4,\n  collapse = \"expand\",\n  separator,\n  className,\n  children,\n  ...props\n}: BreadcrumbProps) {\n  return (\n    <nav aria-label=\"Breadcrumb\" className={cn(\"min-w-0\", className)} {...props}>\n      {items ? (\n        <BreadcrumbTrail\n          items={items}\n          maxItems={maxItems}\n          collapse={collapse}\n          separator={separator}\n        />\n      ) : (\n        children\n      )}\n    </nav>\n  );\n}\n\nexport function BreadcrumbList({ className, ...props }: ComponentPropsWithoutRef<\"ol\">) {\n  return (\n    <ol\n      className={cn(\n        \"flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2\",\n        className,\n      )}\n      {...props}\n    />\n  );\n}\n\nexport function BreadcrumbItem({ className, ...props }: ComponentPropsWithoutRef<\"li\">) {\n  return <li className={cn(\"inline-flex min-w-0 items-center gap-1.5\", className)} {...props} />;\n}\n\nexport type BreadcrumbLinkRenderProps = {\n  href: string;\n  className: string;\n  children: ReactNode;\n};\n\nexport type BreadcrumbLinkProps = Omit<ComponentPropsWithoutRef<\"a\">, \"href\" | \"children\"> & {\n  href: string;\n  children: ReactNode;\n  /** Swap the `<a>` for a router link: `render={(p) => <Link {...p} />}`. */\n  render?: (props: BreadcrumbLinkRenderProps) => ReactElement;\n};\n\nconst linkClass =\n  \"group/crumb relative inline-flex min-w-0 items-center gap-1.5 rounded-sm text-muted-foreground outline-none transition-colors duration-200 hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background\";\n\nfunction LinkContent({ children }: { children: ReactNode }) {\n  return (\n    <>\n      {children}\n      {/* Underline slides in from the left and leaves to the right: the origin\n          flips on hover, so scaleX grows and shrinks in the travel direction. */}\n      <span\n        aria-hidden\n        style={{ transitionTimingFunction: EASE_OUT_CSS }}\n        className=\"pointer-events-none absolute inset-x-0 -bottom-0.5 h-px origin-right scale-x-0 bg-current transition-transform duration-300 group-hover/crumb:origin-left group-hover/crumb:scale-x-100 group-focus-visible/crumb:origin-left group-focus-visible/crumb:scale-x-100 motion-reduce:transition-none\"\n      />\n    </>\n  );\n}\n\nexport function BreadcrumbLink({\n  href,\n  render,\n  className,\n  children,\n  ...props\n}: BreadcrumbLinkProps) {\n  const merged = cn(linkClass, className);\n  if (render) {\n    return render({ href, className: merged, children: <LinkContent>{children}</LinkContent> });\n  }\n  return (\n    <a href={href} className={merged} {...props}>\n      <LinkContent>{children}</LinkContent>\n    </a>\n  );\n}\n\nexport function BreadcrumbPage({ className, ...props }: ComponentPropsWithoutRef<\"span\">) {\n  return (\n    <span\n      aria-current=\"page\"\n      className={cn(\"inline-flex min-w-0 items-center gap-1.5 truncate font-medium text-foreground\", className)}\n      {...props}\n    />\n  );\n}\n\nexport function BreadcrumbSeparator({\n  className,\n  children,\n  ...props\n}: ComponentPropsWithoutRef<\"li\">) {\n  return (\n    <li\n      aria-hidden=\"true\"\n      className={cn(\"inline-flex items-center text-muted-foreground/60 [&>svg]:size-3.5\", className)}\n      {...props}\n    >\n      {children ?? <ChevronRight />}\n    </li>\n  );\n}\n\nexport function BreadcrumbEllipsis({ className, ...props }: ComponentProps<\"button\">) {\n  return (\n    <button\n      type=\"button\"\n      className={cn(\n        \"inline-flex h-6 w-7 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\",\n        className,\n      )}\n      {...props}\n    >\n      <Ellipsis className=\"size-4\" aria-hidden />\n    </button>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Data-driven trail                                                         */\n/* ------------------------------------------------------------------------ */\n\nfunction CrumbBody({ item, current }: { item: BreadcrumbDataItem; current: boolean }) {\n  const content = (\n    <>\n      {item.icon ? (\n        <span aria-hidden className=\"inline-flex shrink-0 [&>svg]:size-3.5\">\n          {item.icon}\n        </span>\n      ) : null}\n      <span className=\"max-w-[12rem] truncate\">{item.label}</span>\n    </>\n  );\n  if (current || !item.href) return <BreadcrumbPage aria-current={current ? \"page\" : undefined}>{content}</BreadcrumbPage>;\n  return (\n    <BreadcrumbLink href={item.href} render={item.render}>\n      {content}\n    </BreadcrumbLink>\n  );\n}\n\ntype Entry =\n  | { kind: \"item\"; item: BreadcrumbDataItem; index: number }\n  | { kind: \"ellipsis\"; hidden: { item: BreadcrumbDataItem; index: number }[] };\n\nfunction BreadcrumbTrail({\n  items,\n  maxItems,\n  collapse,\n  separator,\n}: {\n  items: BreadcrumbDataItem[];\n  maxItems: number;\n  collapse: \"expand\" | \"menu\";\n  separator?: ReactNode;\n}) {\n  const reduce = useReducedMotion();\n  const [expanded, setExpanded] = useState(false);\n  const firstRevealed = useRef<HTMLLIElement>(null);\n  const focusRevealed = useRef(false);\n\n  const indexed = items.map((item, index) => ({ item, index }));\n  const shouldCollapse = !expanded && items.length > Math.max(maxItems, 2);\n  const tail = Math.max(1, maxItems - 2);\n  const hidden = shouldCollapse ? indexed.slice(1, items.length - tail) : [];\n\n  const entries: Entry[] = shouldCollapse\n    ? [\n        { kind: \"item\", ...indexed[0] },\n        { kind: \"ellipsis\", hidden },\n        ...indexed.slice(items.length - tail).map((e) => ({ kind: \"item\" as const, ...e })),\n      ]\n    : indexed.map((e) => ({ kind: \"item\" as const, ...e }));\n\n  // The \"…\" button unmounts on expand; hand focus to the first revealed link\n  // so keyboard users are not dropped back on <body>.\n  useEffect(() => {\n    if (expanded && focusRevealed.current) {\n      focusRevealed.current = false;\n      firstRevealed.current?.querySelector<HTMLElement>(\"a,[tabindex]\")?.focus();\n    }\n  }, [expanded]);\n\n  const layoutTransition = reduce ? { duration: 0 } : SPRING_LAYOUT;\n\n  return (\n    <LayoutGroup>\n      {/* relative: popLayout takes exiting crumbs out of flow, absolutely. */}\n      <BreadcrumbList className=\"relative\">\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          {entries.flatMap((entry, i) => {\n            const key = entry.kind === \"item\" ? `item-${entry.index}` : \"ellipsis\";\n            const last = entry.kind === \"item\" && entry.index === items.length - 1;\n            const isFirstRevealed = expanded && entry.kind === \"item\" && entry.index === 1;\n            // Flat keyed <li>s (no Fragment) so AnimatePresence tracks each\n            // separator and crumb on its own and plays their exits.\n            const nodes: ReactElement[] = [];\n            if (i > 0) {\n              nodes.push(\n                <motion.li\n                  key={`sep-${key}`}\n                  layout=\"position\"\n                  aria-hidden=\"true\"\n                  transition={layoutTransition}\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1 }}\n                  exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                  className=\"inline-flex items-center text-muted-foreground/60 [&>svg]:size-3.5\"\n                >\n                  {separator ?? <ChevronRight />}\n                </motion.li>,\n              );\n            }\n            nodes.push(\n                <motion.li\n                  key={key}\n                  ref={isFirstRevealed ? firstRevealed : undefined}\n                  layout=\"position\"\n                  transition={layoutTransition}\n                  initial={reduce ? { opacity: 0 } : { opacity: 0, x: -6, filter: \"blur(4px)\" }}\n                  animate={{ opacity: 1, x: 0, filter: \"blur(0px)\" }}\n                  exit={{ opacity: 0, transition: { duration: 0.1 } }}\n                  className=\"inline-flex min-w-0 items-center gap-1.5\"\n                >\n                  {entry.kind === \"item\" ? (\n                    <CrumbBody item={entry.item} current={last} />\n                  ) : collapse === \"menu\" ? (\n                    <CollapsedMenu hidden={entry.hidden} />\n                  ) : (\n                    <BreadcrumbEllipsis\n                      aria-label={`Show ${entry.hidden.length} more`}\n                      onClick={() => {\n                        focusRevealed.current = true;\n                        setExpanded(true);\n                      }}\n                    />\n                  )}\n                </motion.li>,\n            );\n            return nodes;\n          })}\n        </AnimatePresence>\n      </BreadcrumbList>\n    </LayoutGroup>\n  );\n}\n\nfunction CollapsedMenu({ hidden }: { hidden: { item: BreadcrumbDataItem; index: number }[] }) {\n  const reduce = useReducedMotion();\n  const [open, setOpen] = useState(false);\n  const menuId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const listRef = useRef<HTMLUListElement>(null);\n\n  useEffect(() => {\n    if (!open) return;\n    const onPointer = (event: PointerEvent) => {\n      if (!rootRef.current?.contains(event.target as Node)) setOpen(false);\n    };\n    document.addEventListener(\"pointerdown\", onPointer);\n    listRef.current?.querySelector<HTMLElement>(\"a\")?.focus();\n    return () => document.removeEventListener(\"pointerdown\", onPointer);\n  }, [open]);\n\n  const close = (refocus: boolean) => {\n    setOpen(false);\n    if (refocus) triggerRef.current?.focus();\n  };\n\n  const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    if (!open) return;\n    const links = Array.from(listRef.current?.querySelectorAll<HTMLElement>(\"a\") ?? []);\n    const at = links.indexOf(document.activeElement as HTMLElement);\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      close(true);\n    } else if (event.key === \"ArrowDown\") {\n      event.preventDefault();\n      links[(at + 1) % links.length]?.focus();\n    } else if (event.key === \"ArrowUp\") {\n      event.preventDefault();\n      links[(at - 1 + links.length) % links.length]?.focus();\n    } else if (event.key === \"Tab\") {\n      setOpen(false);\n    }\n  };\n\n  return (\n    // biome-ignore lint/a11y/noStaticElementInteractions: delegates Escape/arrow keys for the popup's links\n    <div ref={rootRef} className=\"relative\" onKeyDown={onKeyDown}>\n      <BreadcrumbEllipsis\n        ref={triggerRef}\n        aria-label={`Show ${hidden.length} more`}\n        aria-expanded={open}\n        aria-controls={open ? menuId : undefined}\n        onClick={() => setOpen((o) => !o)}\n        className={cn(open && \"bg-muted text-foreground\")}\n      />\n      <AnimatePresence>\n        {open ? (\n          <motion.div\n            id={menuId}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94, y: -4 }}\n            animate={{ opacity: 1, scale: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: -2, transition: { duration: 0.12 } }}\n            transition={SPRING_PANEL}\n            className=\"absolute left-0 top-full z-50 mt-2 min-w-44 origin-top-left rounded-xl border border-border bg-popover p-1 text-popover-foreground shadow-lg\"\n          >\n            <ul ref={listRef} className=\"flex flex-col\">\n              {hidden.map(({ item, index }) => (\n                <li key={index}>\n                  {item.href ? (\n                    (item.render ?? defaultMenuLink)({\n                      href: item.href,\n                      className:\n                        \"flex items-center gap-2 rounded-lg px-2.5 py-1.5 text-sm text-muted-foreground outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:bg-muted focus-visible:text-foreground [&_svg]:size-3.5\",\n                      children: (\n                        <>\n                          {item.icon ? <span aria-hidden className=\"inline-flex\">{item.icon}</span> : null}\n                          <span className=\"truncate\">{item.label}</span>\n                        </>\n                      ),\n                    })\n                  ) : (\n                    <span className=\"flex items-center gap-2 px-2.5 py-1.5 text-sm text-muted-foreground\">\n                      {item.label}\n                    </span>\n                  )}\n                </li>\n              ))}\n            </ul>\n          </motion.div>\n        ) : null}\n      </AnimatePresence>\n    </div>\n  );\n}\n\nfunction defaultMenuLink({ href, className, children }: BreadcrumbLinkRenderProps) {\n  return (\n    <a href={href} className={className}>\n      {children}\n    </a>\n  );\n}\n"},{"path":"components/motion/dropdown-menu.tsx","type":"registry:component","target":"@components/motion/dropdown-menu.tsx","content":"\"use client\";\n\nimport { Check, ChevronRight } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport {\n  cloneElement,\n  createContext,\n  isValidElement,\n  type MutableRefObject,\n  type ReactElement,\n  type FocusEvent as ReactFocusEvent,\n  type KeyboardEvent as ReactKeyboardEvent,\n  type MouseEvent as ReactMouseEvent,\n  type ReactNode,\n  type PointerEvent as ReactPointerEvent,\n  type Ref,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport {\n  type PlacementAlign,\n  type PlacementSide,\n  resolvePlacement,\n} from \"@/components/motion/anchored-placement\";\nimport { usePopoverPortalPosition } from \"@/components/motion/popover-position\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_PANEL } from \"@/lib/ease\";\nimport { useDismiss } from \"@/lib/hooks/use-dismiss\";\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------- */\n/*                                   Levels                                   */\n/* -------------------------------------------------------------------------- */\n\n/** Where focus lands when a panel opens. */\ntype FocusIntent = \"first\" | \"last\" | \"content\" | \"none\";\n\n// Hovering a sub trigger waits this long before opening, so a pointer just\n// passing over the row on its way down the list doesn't flash a submenu.\nconst SUB_OPEN_DELAY = 100;\n// Leaving the sub trigger (or hovering a sibling) closes the submenu only\n// after this grace, so a diagonal move toward the submenu that clips a\n// neighbouring row doesn't snap it shut.\nconst SUB_CLOSE_DELAY = 220;\nconst TYPEAHEAD_RESET = 500;\n\n/**\n * One open panel: the root menu or a submenu. Items, the active-row\n * highlight and keyboard navigation all read the nearest level, so a submenu\n * is the same machinery one step down.\n */\ninterface MenuLevel {\n  /** Shared by every panel and the trigger of one menu tree (dismissal scope). */\n  rootId: string;\n  /** Scope for this panel's layoutId highlight. */\n  levelId: string;\n  open: boolean;\n  isSub: boolean;\n  triggerId: string;\n  contentId: string;\n  triggerRef: MutableRefObject<HTMLElement | null>;\n  contentRef: MutableRefObject<HTMLDivElement | null>;\n  focusIntent: MutableRefObject<FocusIntent>;\n  activeId: string | null;\n  setActiveId: (id: string | null) => void;\n  /** Id of the child submenu currently open from this panel. */\n  openSub: string | null;\n  setOpenSub: (id: string | null) => void;\n  scheduleSubClose: () => void;\n  cancelSubClose: () => void;\n  /** Close this panel only (root: the whole menu). */\n  close: (restoreFocus: boolean) => void;\n  /** Close the whole menu tree. */\n  closeAll: (restoreFocus: boolean) => void;\n  /** Open the root menu (used by the trigger). */\n  openRoot: () => void;\n  reduce: boolean;\n}\n\nconst MenuLevelContext = createContext<MenuLevel | null>(null);\n\nfunction useMenuLevel(component: string) {\n  const level = useContext(MenuLevelContext);\n  if (!level) throw new Error(`${component} must be used within <DropdownMenu>`);\n  return level;\n}\n\n/** Per-panel state shared by the root and every submenu. */\nfunction useLevelCore(open: boolean) {\n  const [activeId, setActiveId] = useState<string | null>(null);\n  const [openSub, setOpenSubState] = useState<string | null>(null);\n  const subCloseTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const cancelSubClose = useCallback(() => {\n    if (subCloseTimer.current) clearTimeout(subCloseTimer.current);\n    subCloseTimer.current = null;\n  }, []);\n\n  const setOpenSub = useCallback(\n    (id: string | null) => {\n      cancelSubClose();\n      setOpenSubState(id);\n    },\n    [cancelSubClose],\n  );\n\n  const scheduleSubClose = useCallback(() => {\n    cancelSubClose();\n    subCloseTimer.current = setTimeout(() => {\n      subCloseTimer.current = null;\n      setOpenSubState(null);\n    }, SUB_CLOSE_DELAY);\n  }, [cancelSubClose]);\n\n  // Reset the highlight when the panel opens, not when it closes: removing\n  // the layoutId highlight while the panel is still animating out leaves\n  // motion waiting on it forever, so the closed panel never unmounts.\n  useEffect(() => {\n    if (open) {\n      setActiveId(null);\n      return;\n    }\n    cancelSubClose();\n    setOpenSubState(null);\n  }, [open, cancelSubClose]);\n\n  useEffect(() => cancelSubClose, [cancelSubClose]);\n\n  return useMemo(\n    () => ({\n      activeId,\n      setActiveId,\n      openSub,\n      setOpenSub,\n      scheduleSubClose,\n      cancelSubClose,\n    }),\n    [activeId, openSub, setOpenSub, scheduleSubClose, cancelSubClose],\n  );\n}\n\nfunction getItems(container: HTMLElement | null) {\n  if (!container) return [];\n  return Array.from(\n    container.querySelectorAll<HTMLElement>(\n      '[data-dropdown-menu-item]:not([data-disabled=\"true\"])',\n    ),\n  );\n}\n\nfunction focusByIntent(container: HTMLElement | null, intent: FocusIntent) {\n  if (!container || intent === \"none\") return;\n  const items = getItems(container);\n  const target =\n    intent === \"first\"\n      ? items[0]\n      : intent === \"last\"\n        ? items[items.length - 1]\n        : container;\n  (target ?? container).focus({ preventScroll: true });\n}\n\nfunction assignRef<T>(ref: Ref<T> | undefined, value: T | null) {\n  if (typeof ref === \"function\") ref(value);\n  else if (ref) (ref as MutableRefObject<T | null>).current = value;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                    Root                                    */\n/* -------------------------------------------------------------------------- */\n\nexport interface DropdownMenuProps {\n  children: ReactNode;\n  /** Controlled open state. */\n  open?: boolean;\n  /** Uncontrolled initial open state. */\n  defaultOpen?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}\n\n/**\n * Composable dropdown menu following the WAI-ARIA menu button pattern. The\n * panel scales out of the trigger side, an active-row highlight glides\n * between items, and submenus open on hover intent or ArrowRight.\n */\nexport function DropdownMenu({\n  children,\n  open: controlledOpen,\n  defaultOpen = false,\n  onOpenChange,\n  className,\n}: DropdownMenuProps) {\n  const [internalOpen, setInternalOpen] = useState(defaultOpen);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const baseId = useId();\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"content\");\n  const reduce = useReducedMotion() ?? false;\n  const core = useLevelCore(open);\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (!controlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [controlled, onOpenChange],\n  );\n\n  const closeAll = useCallback(\n    (restoreFocus: boolean) => {\n      setOpen(false);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpen],\n  );\n\n  const dismiss = useCallback(() => setOpen(false), [setOpen]);\n  const openRoot = useCallback(() => setOpen(true), [setOpen]);\n  const insideTree = useCallback(\n    (target: Element) =>\n      Boolean(target.closest(`[data-dropdown-menu=\"${baseId}\"]`)),\n    [baseId],\n  );\n  // Escape is handled by the focused panel, which knows whether it is a\n  // submenu (close one level) or the root (close and refocus the trigger).\n  useDismiss(open, dismiss, null, { escape: false, ignore: insideTree });\n\n  // Focus moves into the panel on open: the first/last item for keyboard\n  // opens, the panel itself for pointer opens so arrows work immediately.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: baseId,\n      levelId: `${baseId}-root`,\n      open,\n      isSub: false,\n      triggerId: `${baseId}-trigger`,\n      contentId: `${baseId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close: closeAll,\n      closeAll,\n      openRoot,\n      reduce,\n    }),\n    [baseId, open, core, closeAll, openRoot, reduce],\n  );\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <div className={cn(\"relative inline-flex\", className)}>{children}</div>\n    </MenuLevelContext.Provider>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Trigger                                   */\n/* -------------------------------------------------------------------------- */\n\ntype TriggerChildProps = React.HTMLAttributes<HTMLElement> & {\n  ref?: Ref<HTMLElement>;\n  [key: `data-${string}`]: string | undefined;\n};\n\nexport interface DropdownMenuTriggerProps {\n  /** A single element, normally a `<button>`. Its own handlers still run. */\n  children: ReactElement<TriggerChildProps>;\n  className?: string;\n}\n\nexport function DropdownMenuTrigger({\n  children,\n  className,\n}: DropdownMenuTriggerProps) {\n  const level = useMenuLevel(\"DropdownMenuTrigger\");\n  if (!isValidElement(children)) {\n    throw new Error(\"<DropdownMenuTrigger> requires a single React element\");\n  }\n  const childProps = children.props;\n  const childRef = childProps.ref;\n\n  const openWith = (intent: FocusIntent) => {\n    level.focusIntent.current = intent;\n    if (!level.open) {\n      level.openRoot();\n    } else {\n      focusByIntent(level.contentRef.current, intent);\n    }\n  };\n\n  return cloneElement(children, {\n    ref: (node: HTMLElement | null) => {\n      level.triggerRef.current = node;\n      assignRef(childRef, node);\n    },\n    id: level.triggerId,\n    \"aria-haspopup\": \"menu\",\n    \"aria-expanded\": level.open,\n    \"aria-controls\": level.open ? level.contentId : undefined,\n    \"data-state\": level.open ? \"open\" : \"closed\",\n    \"data-dropdown-menu\": level.rootId,\n    className: cn(childProps.className, className),\n    onClick: (event: ReactMouseEvent<HTMLElement>) => {\n      childProps.onClick?.(event);\n      if (event.defaultPrevented) return;\n      if (level.open) {\n        level.closeAll(false);\n        return;\n      }\n      // `detail` is 0 for a click synthesized by the keyboard.\n      openWith(event.detail === 0 ? \"first\" : \"content\");\n    },\n    onKeyDown: (event: ReactKeyboardEvent<HTMLElement>) => {\n      childProps.onKeyDown?.(event);\n      if (event.defaultPrevented) return;\n      if (\n        event.key === \"ArrowDown\" ||\n        event.key === \"Enter\" ||\n        event.key === \" \"\n      ) {\n        event.preventDefault();\n        openWith(\"first\");\n      } else if (event.key === \"ArrowUp\") {\n        event.preventDefault();\n        openWith(\"last\");\n      }\n    },\n  });\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Panel                                    */\n/* -------------------------------------------------------------------------- */\n\ninterface MenuPanelProps {\n  level: MenuLevel;\n  children: ReactNode;\n  side: PlacementSide;\n  align: PlacementAlign;\n  sideOffset: number;\n  alignOffset: number;\n  className?: string;\n  ariaLabel?: string;\n  onPanelEnter?: () => void;\n}\n\nfunction MenuPanel({\n  level,\n  children,\n  side,\n  align,\n  sideOffset,\n  alignOffset,\n  className,\n  ariaLabel,\n  onPanelEnter,\n}: MenuPanelProps) {\n  const [portalReady, setPortalReady] = useState(false);\n  const typeahead = useRef(\"\");\n  const typeaheadTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const layout = usePopoverPortalPosition(\n    level.triggerRef,\n    level.contentRef,\n    portalReady && level.open,\n  );\n\n  useEffect(() => setPortalReady(true), []);\n  useEffect(\n    () => () => {\n      if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    },\n    [],\n  );\n\n  const moveFocus = (direction: 1 | -1) => {\n    const items = getItems(level.contentRef.current);\n    if (items.length === 0) return;\n    const current = items.indexOf(document.activeElement as HTMLElement);\n    const next =\n      current < 0\n        ? direction === 1\n          ? 0\n          : items.length - 1\n        : (current + direction + items.length) % items.length;\n    items[next]?.focus();\n  };\n\n  const onKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {\n    // React bubbles events through portals: a submenu's keys would reach its\n    // parent panel too. Only answer keys pressed inside this panel's DOM.\n    if (!event.currentTarget.contains(event.target as Node)) return;\n    if (event.defaultPrevented) return;\n    const { key } = event;\n\n    if (key === \"Escape\") {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"ArrowLeft\" && level.isSub) {\n      event.preventDefault();\n      level.close(true);\n      return;\n    }\n    if (key === \"Tab\") {\n      event.preventDefault();\n      level.closeAll(true);\n      return;\n    }\n    if (key === \"ArrowDown\" || key === \"ArrowUp\") {\n      event.preventDefault();\n      moveFocus(key === \"ArrowDown\" ? 1 : -1);\n      return;\n    }\n    if (key === \"Home\" || key === \"End\") {\n      event.preventDefault();\n      const items = getItems(level.contentRef.current);\n      items[key === \"Home\" ? 0 : items.length - 1]?.focus();\n      return;\n    }\n    const printable =\n      key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey;\n    // A leading space is activation, not a search character.\n    if (!printable || (key === \" \" && typeahead.current === \"\")) return;\n    event.preventDefault();\n    typeahead.current += key.toLocaleLowerCase();\n    if (typeaheadTimer.current) clearTimeout(typeaheadTimer.current);\n    typeaheadTimer.current = setTimeout(() => {\n      typeahead.current = \"\";\n    }, TYPEAHEAD_RESET);\n    const items = getItems(level.contentRef.current);\n    const start = items.indexOf(document.activeElement as HTMLElement);\n    // Search from the row after the current one so repeating a letter cycles.\n    const ordered =\n      typeahead.current.length === 1 && start >= 0\n        ? [...items.slice(start + 1), ...items.slice(0, start + 1)]\n        : items;\n    const match = ordered.find((item) =>\n      (item.dataset.label ?? item.textContent ?? \"\")\n        .trim()\n        .toLocaleLowerCase()\n        .startsWith(typeahead.current),\n    );\n    match?.focus();\n  };\n\n  if (!portalReady) return null;\n\n  const placement = layout\n    ? resolvePlacement(layout, { side, align, sideOffset, alignOffset })\n    : null;\n\n  return createPortal(\n    <AnimatePresence>\n      {level.open ? (\n        <motion.div\n          ref={level.contentRef}\n          id={level.contentId}\n          role=\"menu\"\n          aria-label={ariaLabel}\n          aria-labelledby={ariaLabel ? undefined : level.triggerId}\n          aria-orientation=\"vertical\"\n          tabIndex={-1}\n          data-dropdown-menu={level.rootId}\n          data-side={placement?.side ?? side}\n          initial={level.reduce ? { opacity: 0 } : { opacity: 0, scale: 0.94 }}\n          animate={{ opacity: 1, scale: 1 }}\n          // pointerEvents flips at the start of the exit, so a closing panel\n          // can never be hovered or clicked through.\n          exit={\n            level.reduce\n              ? { opacity: 0, pointerEvents: \"none\", transition: { duration: 0.1 } }\n              : {\n                  opacity: 0,\n                  scale: 0.96,\n                  pointerEvents: \"none\",\n                  transition: { duration: 0.12, ease: EASE_OUT },\n                }\n          }\n          transition={\n            level.reduce\n              ? { duration: 0.12, ease: EASE_OUT }\n              : { ...SPRING_PANEL, opacity: { duration: 0.16, ease: EASE_OUT } }\n          }\n          style={{\n            left: placement?.left ?? 0,\n            top: placement?.top ?? 0,\n            // The panel grows out of the trigger's side — transform-origin on\n            // an HTML element is safe for motion's scale.\n            transformOrigin: placement?.origin ?? \"50% 0%\",\n            visibility: placement ? \"visible\" : \"hidden\",\n          }}\n          onKeyDown={onKeyDown}\n          onFocus={(event: ReactFocusEvent<HTMLDivElement>) => {\n            if (event.target === event.currentTarget) level.setActiveId(null);\n            else onPanelEnter?.();\n          }}\n          onPointerEnter={onPanelEnter}\n          className={cn(\n            \"fixed z-[100] min-w-52 rounded-xl border border-border bg-card p-1.5 text-foreground shadow-[0_18px_40px_-12px_rgba(0,0,0,0.28)] outline-none\",\n            className,\n          )}\n        >\n          {children}\n        </motion.div>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n\nexport interface DropdownMenuContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"bottom\". */\n  side?: \"bottom\" | \"top\";\n  /** Alignment against the trigger. Default \"start\". */\n  align?: PlacementAlign;\n  /** Gap between trigger and panel, in px. Default 6. */\n  sideOffset?: number;\n  alignOffset?: number;\n  /** Accessible name; defaults to the trigger's text via aria-labelledby. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuContent({\n  children,\n  side = \"bottom\",\n  align = \"start\",\n  sideOffset = 6,\n  alignOffset = 0,\n  ariaLabel,\n  className,\n}: DropdownMenuContentProps) {\n  const level = useMenuLevel(\"DropdownMenuContent\");\n  return (\n    <MenuPanel\n      level={level}\n      side={side}\n      align={align}\n      sideOffset={sideOffset}\n      alignOffset={alignOffset}\n      ariaLabel={ariaLabel}\n      className={className}\n    >\n      {children}\n    </MenuPanel>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                   Items                                    */\n/* -------------------------------------------------------------------------- */\n\ntype ItemVariant = \"default\" | \"destructive\";\n\ninterface ItemBaseProps {\n  children: ReactNode;\n  itemId?: string;\n  role?: \"menuitem\" | \"menuitemcheckbox\" | \"menuitemradio\";\n  ariaChecked?: boolean;\n  disabled?: boolean;\n  variant?: ItemVariant;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n  closeOnSelect: boolean;\n  onActivate?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  isSubTrigger?: boolean;\n  extraProps?: React.ButtonHTMLAttributes<HTMLButtonElement> & {\n    ref?: Ref<HTMLButtonElement>;\n    [key: `data-${string}`]: string | undefined;\n  };\n}\n\nfunction ItemBase({\n  children,\n  itemId,\n  role = \"menuitem\",\n  ariaChecked,\n  disabled = false,\n  variant = \"default\",\n  inset = false,\n  textValue,\n  className,\n  closeOnSelect,\n  onActivate,\n  isSubTrigger = false,\n  extraProps,\n}: ItemBaseProps) {\n  const level = useMenuLevel(\"DropdownMenuItem\");\n  const autoId = useId();\n  const id = itemId ?? autoId;\n  const highlighted = level.activeId === id;\n  const checkedProps =\n    role === \"menuitem\" ? {} : { \"aria-checked\": ariaChecked ?? false };\n  const { onPointerEnter, onPointerLeave, onKeyDown, ref, ...rest } =\n    extraProps ?? {};\n\n  return (\n    <button\n      {...rest}\n      ref={ref}\n      type=\"button\"\n      id={id}\n      role={role}\n      {...checkedProps}\n      disabled={disabled}\n      tabIndex={-1}\n      data-dropdown-menu-item=\"\"\n      data-disabled={disabled ? \"true\" : undefined}\n      data-highlighted={highlighted ? \"\" : undefined}\n      data-label={textValue}\n      onFocus={() => level.setActiveId(id)}\n      onPointerEnter={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerEnter?.(event);\n        if (!isSubTrigger && event.pointerType !== \"touch\") {\n          level.scheduleSubClose();\n        }\n      }}\n      onPointerMove={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        if (disabled || event.pointerType === \"touch\") return;\n        if (document.activeElement !== event.currentTarget) {\n          event.currentTarget.focus({ preventScroll: true });\n        }\n      }}\n      onPointerLeave={(event: ReactPointerEvent<HTMLButtonElement>) => {\n        onPointerLeave?.(event);\n        if (event.pointerType === \"touch\" || isSubTrigger) return;\n        // Clearing focus to the panel drops the highlight when the pointer\n        // leaves the rows, the way native menus behave.\n        if (document.activeElement === event.currentTarget) {\n          level.contentRef.current?.focus({ preventScroll: true });\n        }\n      }}\n      onKeyDown={onKeyDown}\n      onClick={(event) => {\n        if (disabled) return;\n        onActivate?.(event);\n        if (closeOnSelect && !event.defaultPrevented) level.closeAll(true);\n      }}\n      className={cn(\n        \"relative isolate flex w-full select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-[13px] outline-none\",\n        \"disabled:pointer-events-none disabled:opacity-40\",\n        \"[&_svg]:size-4 [&_svg]:shrink-0\",\n        inset && \"pl-8\",\n        variant === \"destructive\"\n          ? \"text-destructive [&_svg]:text-destructive\"\n          : \"text-foreground [&_svg]:text-muted-foreground\",\n        className,\n      )}\n    >\n      {/* Its own presence boundary: a layoutId element registers with the\n          nearest AnimatePresence, and the panel's exit would otherwise wait\n          on the highlight's layout animation and never unmount. */}\n      <AnimatePresence initial={false}>\n        {highlighted ? (\n          <motion.span\n            aria-hidden=\"true\"\n            layoutId={`${level.levelId}-highlight`}\n            className={cn(\n              \"absolute inset-0 -z-10 rounded-lg\",\n              variant === \"destructive\"\n                ? \"bg-destructive/10\"\n                : \"bg-foreground/[0.07]\",\n            )}\n            transition={level.reduce ? { duration: 0 } : SPRING_LAYOUT}\n          />\n        ) : null}\n      </AnimatePresence>\n      {children}\n    </button>\n  );\n}\n\nfunction Shortcut({ children }: { children: ReactNode }) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"ml-auto pl-4 font-mono text-[11px] tracking-wide text-muted-foreground\"\n    >\n      {children}\n    </span>\n  );\n}\n\nexport interface DropdownMenuItemProps {\n  children: ReactNode;\n  /** Leading icon (sized to 16px). */\n  icon?: ReactNode;\n  /** Trailing shortcut hint, e.g. \"⌘K\" or a `KbdCombo`. Decorative. */\n  shortcut?: ReactNode;\n  variant?: ItemVariant;\n  disabled?: boolean;\n  /** Indent to line up with checkbox/radio rows. */\n  inset?: boolean;\n  /** Text used by typeahead when children aren't plain text. */\n  textValue?: string;\n  /** Call `event.preventDefault()` to keep the menu open. */\n  onSelect?: (event: ReactMouseEvent<HTMLButtonElement>) => void;\n  /** Default true. */\n  closeOnSelect?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuItem({\n  children,\n  icon,\n  shortcut,\n  onSelect,\n  closeOnSelect = true,\n  ...props\n}: DropdownMenuItemProps) {\n  return (\n    <ItemBase {...props} closeOnSelect={closeOnSelect} onActivate={onSelect}>\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nfunction Indicator({\n  checked,\n  kind,\n  reduce,\n}: {\n  checked: boolean;\n  kind: \"check\" | \"dot\";\n  reduce: boolean;\n}) {\n  return (\n    <span\n      aria-hidden=\"true\"\n      className=\"absolute left-2.5 flex size-4 items-center justify-center\"\n    >\n      <AnimatePresence initial={false}>\n        {checked ? (\n          <motion.span\n            key={kind}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            animate={{ opacity: 1, scale: 1 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n            transition={reduce ? { duration: 0.08 } : SPRING_PANEL}\n            className=\"flex items-center justify-center text-foreground\"\n          >\n            {kind === \"check\" ? (\n              <Check className=\"size-3.5! text-foreground!\" strokeWidth={2.6} />\n            ) : (\n              <span className=\"size-1.5 rounded-full bg-current\" />\n            )}\n          </motion.span>\n        ) : null}\n      </AnimatePresence>\n    </span>\n  );\n}\n\nexport interface DropdownMenuCheckboxItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  checked?: boolean;\n  defaultChecked?: boolean;\n  onCheckedChange?: (checked: boolean) => void;\n}\n\n/** A toggle row. Stays open on select by default so several can be flipped. */\nexport function DropdownMenuCheckboxItem({\n  children,\n  checked: controlledChecked,\n  defaultChecked = false,\n  onCheckedChange,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuCheckboxItemProps) {\n  const level = useMenuLevel(\"DropdownMenuCheckboxItem\");\n  const [internal, setInternal] = useState(defaultChecked);\n  const checked = controlledChecked ?? internal;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemcheckbox\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => {\n        if (controlledChecked === undefined) setInternal(!checked);\n        onCheckedChange?.(!checked);\n      }}\n    >\n      <Indicator checked={checked} kind=\"check\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\ninterface RadioGroupContextValue {\n  value: string | undefined;\n  select: (value: string) => void;\n}\n\nconst RadioGroupContext = createContext<RadioGroupContextValue | null>(null);\n\nexport interface DropdownMenuRadioGroupProps {\n  children: ReactNode;\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Accessible name for the group. */\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuRadioGroup({\n  children,\n  value: controlledValue,\n  defaultValue,\n  onValueChange,\n  ariaLabel,\n  className,\n}: DropdownMenuRadioGroupProps) {\n  const [internal, setInternal] = useState(defaultValue);\n  const value = controlledValue ?? internal;\n  const ctx = useMemo<RadioGroupContextValue>(\n    () => ({\n      value,\n      select: (next) => {\n        if (controlledValue === undefined) setInternal(next);\n        onValueChange?.(next);\n      },\n    }),\n    [value, controlledValue, onValueChange],\n  );\n  return (\n    <RadioGroupContext.Provider value={ctx}>\n      <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n        {children}\n      </fieldset>\n    </RadioGroupContext.Provider>\n  );\n}\n\nexport interface DropdownMenuRadioItemProps\n  extends Omit<DropdownMenuItemProps, \"onSelect\" | \"inset\" | \"icon\"> {\n  value: string;\n}\n\nexport function DropdownMenuRadioItem({\n  children,\n  value,\n  shortcut,\n  closeOnSelect = false,\n  ...props\n}: DropdownMenuRadioItemProps) {\n  const level = useMenuLevel(\"DropdownMenuRadioItem\");\n  const group = useContext(RadioGroupContext);\n  if (!group) {\n    throw new Error(\n      \"DropdownMenuRadioItem must be used within <DropdownMenuRadioGroup>\",\n    );\n  }\n  const checked = group.value === value;\n  return (\n    <ItemBase\n      {...props}\n      inset\n      role=\"menuitemradio\"\n      ariaChecked={checked}\n      closeOnSelect={closeOnSelect}\n      onActivate={() => group.select(value)}\n    >\n      <Indicator checked={checked} kind=\"dot\" reduce={level.reduce} />\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      {shortcut ? <Shortcut>{shortcut}</Shortcut> : null}\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuLabelProps {\n  children: ReactNode;\n  inset?: boolean;\n  className?: string;\n}\n\nexport function DropdownMenuLabel({\n  children,\n  inset = false,\n  className,\n}: DropdownMenuLabelProps) {\n  return (\n    <div\n      className={cn(\n        \"px-2.5 pb-1 pt-1.5 text-[11px] font-medium text-muted-foreground\",\n        inset && \"pl-8\",\n        className,\n      )}\n    >\n      {children}\n    </div>\n  );\n}\n\nexport interface DropdownMenuGroupProps {\n  children: ReactNode;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuGroup({\n  children,\n  ariaLabel,\n  className,\n}: DropdownMenuGroupProps) {\n  return (\n    <fieldset\n        aria-label={ariaLabel}\n        className={cn(\"m-0 min-w-0 border-0 p-0\", className)}\n      >\n      {children}\n    </fieldset>\n  );\n}\n\nexport function DropdownMenuSeparator({ className }: { className?: string }) {\n  return <hr className={cn(\"-mx-1.5 my-1.5 h-px border-0 bg-border\", className)} />;\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Submenus                                  */\n/* -------------------------------------------------------------------------- */\n\ninterface SubContextValue {\n  level: MenuLevel;\n  parent: MenuLevel;\n  triggerItemId: string;\n  openTimer: MutableRefObject<ReturnType<typeof setTimeout> | null>;\n  openWith: (intent: FocusIntent) => void;\n}\n\nconst SubContext = createContext<SubContextValue | null>(null);\n\nfunction useSub(component: string) {\n  const sub = useContext(SubContext);\n  if (!sub) throw new Error(`${component} must be used within <DropdownMenuSub>`);\n  return sub;\n}\n\nexport interface DropdownMenuSubProps {\n  children: ReactNode;\n}\n\n/** A nested menu opened from a `DropdownMenuSubTrigger` row. */\nexport function DropdownMenuSub({ children }: DropdownMenuSubProps) {\n  const parent = useMenuLevel(\"DropdownMenuSub\");\n  const subId = useId();\n  const open = parent.open && parent.openSub === subId;\n  const triggerRef = useRef<HTMLElement | null>(null);\n  const contentRef = useRef<HTMLDivElement | null>(null);\n  const focusIntent = useRef<FocusIntent>(\"none\");\n  const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n  const core = useLevelCore(open);\n  const triggerItemId = `${subId}-trigger`;\n\n  useEffect(\n    () => () => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n    },\n    [],\n  );\n\n  // Open submenus take focus only when asked to (keyboard); a hover open\n  // leaves it on the trigger row.\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() =>\n      focusByIntent(contentRef.current, focusIntent.current),\n    );\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const { setOpenSub } = parent;\n  const close = useCallback(\n    (restoreFocus: boolean) => {\n      setOpenSub(null);\n      if (restoreFocus) triggerRef.current?.focus({ preventScroll: true });\n    },\n    [setOpenSub],\n  );\n\n  const openWith = useCallback(\n    (intent: FocusIntent) => {\n      if (openTimer.current) clearTimeout(openTimer.current);\n      openTimer.current = null;\n      focusIntent.current = intent;\n      if (open) focusByIntent(contentRef.current, intent);\n      else setOpenSub(subId);\n    },\n    [open, setOpenSub, subId],\n  );\n\n  const level = useMemo<MenuLevel>(\n    () => ({\n      rootId: parent.rootId,\n      levelId: `${subId}-level`,\n      open,\n      isSub: true,\n      triggerId: triggerItemId,\n      contentId: `${subId}-content`,\n      triggerRef,\n      contentRef,\n      focusIntent,\n      ...core,\n      close,\n      closeAll: parent.closeAll,\n      openRoot: parent.openRoot,\n      reduce: parent.reduce,\n    }),\n    [\n      parent.rootId,\n      parent.closeAll,\n      parent.openRoot,\n      parent.reduce,\n      subId,\n      open,\n      triggerItemId,\n      core,\n      close,\n    ],\n  );\n\n  const ctx = useMemo<SubContextValue>(\n    () => ({ level, parent, triggerItemId, openTimer, openWith }),\n    [level, parent, triggerItemId, openWith],\n  );\n\n  return <SubContext.Provider value={ctx}>{children}</SubContext.Provider>;\n}\n\nexport interface DropdownMenuSubTriggerProps {\n  children: ReactNode;\n  icon?: ReactNode;\n  disabled?: boolean;\n  inset?: boolean;\n  textValue?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubTrigger({\n  children,\n  icon,\n  ...props\n}: DropdownMenuSubTriggerProps) {\n  const { level, parent, triggerItemId, openTimer, openWith } = useSub(\n    \"DropdownMenuSubTrigger\",\n  );\n\n  const clearOpenTimer = () => {\n    if (openTimer.current) clearTimeout(openTimer.current);\n    openTimer.current = null;\n  };\n\n  return (\n    <ItemBase\n      {...props}\n      itemId={triggerItemId}\n      isSubTrigger\n      closeOnSelect={false}\n      onActivate={(event) => openWith(event.detail === 0 ? \"first\" : \"none\")}\n      extraProps={{\n        ref: (node: HTMLButtonElement | null) => {\n          level.triggerRef.current = node;\n        },\n        \"aria-haspopup\": \"menu\",\n        \"aria-expanded\": level.open,\n        \"aria-controls\": level.open ? level.contentId : undefined,\n        \"data-state\": level.open ? \"open\" : \"closed\",\n        onPointerEnter: (event) => {\n          if (event.pointerType === \"touch\" || props.disabled) return;\n          parent.cancelSubClose();\n          if (level.open) return;\n          clearOpenTimer();\n          openTimer.current = setTimeout(() => {\n            openTimer.current = null;\n            openWith(\"none\");\n          }, SUB_OPEN_DELAY);\n        },\n        onPointerLeave: (event) => {\n          if (event.pointerType === \"touch\") return;\n          clearOpenTimer();\n          parent.scheduleSubClose();\n        },\n        onKeyDown: (event) => {\n          if (event.key === \"ArrowRight\") {\n            event.preventDefault();\n            openWith(\"first\");\n          }\n        },\n      }}\n    >\n      {icon}\n      <span className=\"min-w-0 flex-1 truncate\">{children}</span>\n      <ChevronRight\n        aria-hidden=\"true\"\n        className=\"-mr-1 ml-auto size-3.5! text-muted-foreground\"\n      />\n    </ItemBase>\n  );\n}\n\nexport interface DropdownMenuSubContentProps {\n  children: ReactNode;\n  /** Preferred side; flips when the viewport lacks room. Default \"right\". */\n  side?: \"right\" | \"left\";\n  /** Gap from the parent panel, in px. Default 8. */\n  sideOffset?: number;\n  /** Shift so the first row lines up with the trigger row. Default -7. */\n  alignOffset?: number;\n  ariaLabel?: string;\n  className?: string;\n}\n\nexport function DropdownMenuSubContent({\n  children,\n  side = \"right\",\n  sideOffset = 8,\n  alignOffset = -7,\n  ariaLabel,\n  className,\n}: DropdownMenuSubContentProps) {\n  const { level, parent, triggerItemId } = useSub(\"DropdownMenuSubContent\");\n  const { cancelSubClose, setActiveId } = parent;\n  // While the pointer or focus is in the submenu, its trigger row keeps the\n  // parent's highlight and the pending close is called off.\n  const onPanelEnter = useCallback(() => {\n    cancelSubClose();\n    setActiveId(triggerItemId);\n  }, [cancelSubClose, setActiveId, triggerItemId]);\n\n  return (\n    <MenuLevelContext.Provider value={level}>\n      <MenuPanel\n        level={level}\n        side={side}\n        align=\"start\"\n        sideOffset={sideOffset}\n        alignOffset={alignOffset}\n        ariaLabel={ariaLabel}\n        className={cn(\"min-w-44\", className)}\n        onPanelEnter={onPanelEnter}\n      >\n        {children}\n      </MenuPanel>\n    </MenuLevelContext.Provider>\n  );\n}\n"},{"path":"components/motion/progress.tsx","type":"registry:component","target":"@components/motion/progress.tsx","content":"\"use client\";\n\nimport {\n  motion,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport { type ReactNode, useEffect, useId, useRef } from \"react\";\nimport { NumberTicker } from \"@/components/motion/number-ticker\";\nimport { EASE_IN_OUT, EASE_OUT, SPRING_GLIDE } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport type ProgressSize = \"sm\" | \"md\" | \"lg\";\n\n// Reduced motion: indeterminate states drop every transform and keep a calm\n// opacity pulse (same rhythm as Loader's reduced variant).\nconst REDUCED_PULSE = {\n  animate: { opacity: [0.35, 0.85, 0.35] },\n  transition: { duration: 1.4, ease: EASE_IN_OUT, repeat: Infinity },\n};\n\nconst clamp01 = (n: number) => (Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : 0);\n\n/**\n * A spring-smoothed 0..1 fraction. Uses SPRING_GLIDE (critically damped) so\n * the fill never rebounds past the true value. Reduced motion jumps instead.\n */\nfunction useFraction(fraction: number) {\n  const reduce = useReducedMotion();\n  const spring = useSpring(0, SPRING_GLIDE);\n  useEffect(() => {\n    if (reduce) spring.jump(fraction);\n    else spring.set(fraction);\n  }, [fraction, reduce, spring]);\n  return spring;\n}\n\nfunction defaultValueText(percent: number) {\n  return `${percent}%`;\n}\n\ninterface ProgressCommonProps {\n  /** Current value. Omit (or pass `null`) together with `indeterminate`. */\n  value?: number | null;\n  /** Upper bound. Defaults to 100. */\n  max?: number;\n  /** Unknown-duration mode: a sliding segment (bar) or a spinning arc (circle). */\n  indeterminate?: boolean;\n  /** Visible label. When it is not a string, also pass `aria-label`. */\n  label?: ReactNode;\n  /** Show the rolling percentage. */\n  showValue?: boolean;\n  /** Screen-reader value text. Defaults to \"42%\". */\n  getValueText?: (percent: number, value: number, max: number) => string;\n  \"aria-label\"?: string;\n  className?: string;\n}\n\nfunction useProgressState(\n  value: number | null | undefined,\n  max: number,\n  indeterminate: boolean,\n) {\n  const safeMax = max > 0 ? max : 100;\n  const isIndeterminate = indeterminate || value == null;\n  const current = isIndeterminate ? 0 : Math.min(safeMax, Math.max(0, value ?? 0));\n  const fraction = clamp01(current / safeMax);\n  const percent = Math.round(fraction * 100);\n  return { safeMax, isIndeterminate, current, fraction, percent };\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                  Progress                                  */\n/* -------------------------------------------------------------------------- */\n\nconst TRACK_SIZE: Record<ProgressSize, string> = {\n  sm: \"h-1\",\n  md: \"h-2\",\n  lg: \"h-3\",\n};\n\nexport interface ProgressProps extends ProgressCommonProps {\n  size?: ProgressSize;\n  /** Classes for the fill (e.g. `bg-emerald-500`). */\n  indicatorClassName?: string;\n  /** Classes for the track. */\n  trackClassName?: string;\n}\n\n/**\n * Linear progress bar. The fill is an HTML element scaled on X from its left\n * edge (transform only), smoothed by a critically damped spring.\n */\nexport function Progress({\n  value,\n  max = 100,\n  indeterminate = false,\n  label,\n  showValue = false,\n  size = \"md\",\n  getValueText = defaultValueText,\n  indicatorClassName,\n  trackClassName,\n  className,\n  \"aria-label\": ariaLabel,\n}: ProgressProps) {\n  const reduce = useReducedMotion();\n  const labelId = useId();\n  const { safeMax, isIndeterminate, current, fraction, percent } =\n    useProgressState(value, max, indeterminate);\n  const scaleX = useFraction(fraction);\n  const hasHeader = label != null || (showValue && !isIndeterminate);\n\n  return (\n    <div\n      role=\"progressbar\"\n      aria-label={ariaLabel ?? (typeof label === \"string\" ? label : undefined)}\n      aria-labelledby={ariaLabel == null && label != null && typeof label !== \"string\" ? labelId : undefined}\n      aria-valuemin={0}\n      aria-valuemax={safeMax}\n      aria-valuenow={isIndeterminate ? undefined : current}\n      aria-valuetext={\n        isIndeterminate ? undefined : getValueText(percent, current, safeMax)\n      }\n      className={cn(\"flex w-full flex-col gap-2\", className)}\n    >\n      {hasHeader ? (\n        <div className=\"flex items-baseline justify-between gap-3 text-sm\">\n          {label != null ? (\n            <span id={labelId} className=\"min-w-0 truncate font-medium text-foreground\">\n              {label}\n            </span>\n          ) : (\n            <span />\n          )}\n          {showValue && !isIndeterminate ? (\n            <span aria-hidden=\"true\" className=\"shrink-0 text-muted-foreground\">\n              <NumberTicker\n                value={percent}\n                suffix=\"%\"\n                startOnView={false}\n                duration={0.45}\n                stagger={0}\n              />\n            </span>\n          ) : null}\n        </div>\n      ) : null}\n      <div\n        className={cn(\n          \"relative w-full overflow-hidden rounded-full bg-foreground/10\",\n          TRACK_SIZE[size],\n          trackClassName,\n        )}\n      >\n        {isIndeterminate ? (\n          reduce ? (\n            <motion.div\n              className={cn(\"absolute inset-0 rounded-full bg-primary\", indicatorClassName)}\n              animate={REDUCED_PULSE.animate}\n              transition={REDUCED_PULSE.transition}\n            />\n          ) : (\n            // A 40%-wide segment travels from fully off the left edge\n            // (-100% of itself) to fully off the right (250% of itself).\n            <motion.div\n              className={cn(\n                \"absolute inset-y-0 left-0 w-2/5 rounded-full bg-primary\",\n                indicatorClassName,\n              )}\n              initial={{ x: \"-100%\" }}\n              animate={{ x: \"250%\" }}\n              transition={{ duration: 1.4, ease: EASE_IN_OUT, repeat: Infinity }}\n            />\n          )\n        ) : (\n          <motion.div\n            className={cn(\n              \"absolute inset-0 origin-left rounded-full bg-primary\",\n              indicatorClassName,\n            )}\n            style={{ scaleX }}\n          />\n        )}\n      </div>\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                               ProgressCircle                               */\n/* -------------------------------------------------------------------------- */\n\nexport interface ProgressCircleProps extends ProgressCommonProps {\n  /** Diameter in px. */\n  size?: number;\n  /** Stroke width in px. */\n  thickness?: number;\n  /** Replace the centered percentage with custom content. */\n  children?: ReactNode;\n  /** Classes for the progress arc (stroke via `text-*`). */\n  indicatorClassName?: string;\n}\n\n/**\n * Ring progress. The arc draws with `pathLength`; the 12 o'clock start and\n * the indeterminate spin rotate whole HTML/SVG boxes with CSS transforms, so\n * no transform-origin is ever set on an inner SVG shape.\n */\nexport function ProgressCircle({\n  value,\n  max = 100,\n  indeterminate = false,\n  label,\n  showValue = true,\n  size = 64,\n  thickness,\n  getValueText = defaultValueText,\n  children,\n  indicatorClassName,\n  className,\n  \"aria-label\": ariaLabel,\n}: ProgressCircleProps) {\n  const reduce = useReducedMotion();\n  const labelId = useId();\n  const { safeMax, isIndeterminate, current, fraction, percent } =\n    useProgressState(value, max, indeterminate);\n  const stroke = thickness ?? Math.max(3, Math.round(size * 0.09));\n  const r = (size - stroke) / 2;\n  const c = size / 2;\n  const pathLength = useFraction(fraction);\n  // A round cap on a zero-length path still paints a dot; hide it at 0.\n  const arcOpacity = useTransform(pathLength, (v) => (v > 0.002 ? 1 : 0));\n  const fontSize = Math.max(10, Math.round(size * 0.22));\n\n  const center =\n    children ??\n    (showValue && !isIndeterminate ? (\n      <NumberTicker\n        value={percent}\n        suffix=\"%\"\n        startOnView={false}\n        duration={0.45}\n        stagger={0}\n        className=\"font-semibold text-foreground\"\n      />\n    ) : null);\n\n  const ring = (\n    <svg\n      width={size}\n      height={size}\n      viewBox={`0 0 ${size} ${size}`}\n      aria-hidden=\"true\"\n      focusable=\"false\"\n      // Start at 12 o'clock: rotate the whole <svg> box with CSS.\n      className=\"-rotate-90\"\n    >\n      <circle\n        cx={c}\n        cy={c}\n        r={r}\n        fill=\"none\"\n        strokeWidth={stroke}\n        className=\"stroke-foreground/10\"\n      />\n      {isIndeterminate ? (\n        <motion.circle\n          cx={c}\n          cy={c}\n          r={r}\n          fill=\"none\"\n          strokeWidth={stroke}\n          strokeLinecap=\"round\"\n          className={cn(\"stroke-current text-primary\", indicatorClassName)}\n          initial={false}\n          animate={{ pathLength: 0.28 }}\n          transition={{ duration: 0 }}\n        />\n      ) : (\n        <motion.circle\n          cx={c}\n          cy={c}\n          r={r}\n          fill=\"none\"\n          strokeWidth={stroke}\n          strokeLinecap=\"round\"\n          className={cn(\"stroke-current text-primary\", indicatorClassName)}\n          style={{ pathLength, opacity: arcOpacity }}\n        />\n      )}\n    </svg>\n  );\n\n  return (\n    <div\n      role=\"progressbar\"\n      aria-label={ariaLabel ?? (typeof label === \"string\" ? label : undefined)}\n      aria-labelledby={ariaLabel == null && label != null && typeof label !== \"string\" ? labelId : undefined}\n      aria-valuemin={0}\n      aria-valuemax={safeMax}\n      aria-valuenow={isIndeterminate ? undefined : current}\n      aria-valuetext={\n        isIndeterminate ? undefined : getValueText(percent, current, safeMax)\n      }\n      className={cn(\"inline-flex flex-col items-center gap-2\", className)}\n    >\n      <div className=\"relative\" style={{ width: size, height: size }}>\n        {isIndeterminate ? (\n          // The spin lives on an HTML wrapper, never on an SVG child.\n          <motion.div\n            className=\"size-full\"\n            animate={reduce ? REDUCED_PULSE.animate : { rotate: 360 }}\n            transition={\n              reduce\n                ? REDUCED_PULSE.transition\n                : { duration: 1, ease: \"linear\", repeat: Infinity }\n            }\n          >\n            {ring}\n          </motion.div>\n        ) : (\n          ring\n        )}\n        {center != null ? (\n          <div\n            aria-hidden=\"true\"\n            className=\"absolute inset-0 flex items-center justify-center tabular-nums\"\n            style={{ fontSize }}\n          >\n            {center}\n          </div>\n        ) : null}\n      </div>\n      {label != null ? (\n        <span id={labelId} className=\"text-xs text-muted-foreground\">\n          {label}\n        </span>\n      ) : null}\n    </div>\n  );\n}\n\n/* -------------------------------------------------------------------------- */\n/*                                ProgressSteps                               */\n/* -------------------------------------------------------------------------- */\n\nexport type ProgressStep = { label: string };\n\nexport interface ProgressStepsProps {\n  /** Number of segments, or labelled steps (labels render under segments). */\n  steps: number | ProgressStep[];\n  /**\n   * Completed steps. Fractions partially fill the next segment, e.g. `2.5`\n   * fills two segments and half of the third.\n   */\n  value: number;\n  size?: ProgressSize;\n  /** Hide the step labels even when `steps` carries them. */\n  hideLabels?: boolean;\n  \"aria-label\"?: string;\n  indicatorClassName?: string;\n  className?: string;\n}\n\n// Delay between neighbouring segments so a jump of several steps reads as a\n// sequence (stage 1 completes, then stage 2…) instead of all at once.\nconst SEGMENT_STAGGER = 0.14;\n\n/**\n * Segmented progress: N tracks that fill one after another, e.g. upload\n * stages or onboarding steps. Increases fill left→right; decreases unwind\n * right→left.\n */\nexport function ProgressSteps({\n  steps,\n  value,\n  size = \"md\",\n  hideLabels = false,\n  indicatorClassName,\n  className,\n  \"aria-label\": ariaLabel = \"Progress\",\n}: ProgressStepsProps) {\n  const reduce = useReducedMotion();\n  const list: ProgressStep[] =\n    typeof steps === \"number\"\n      ? Array.from({ length: Math.max(1, steps) }, (_, i) => ({ label: `Step ${i + 1}` }))\n      : steps;\n  const count = list.length;\n  const current = Math.min(count, Math.max(0, Number.isFinite(value) ? value : 0));\n  const showLabels = !hideLabels && typeof steps !== \"number\";\n\n  // Previous value decides the sequence direction and where it starts.\n  const prevRef = useRef(current);\n  const from = prevRef.current;\n  useEffect(() => {\n    prevRef.current = current;\n  }, [current]);\n  const growing = current >= from;\n\n  const activeIndex = Math.min(count - 1, Math.floor(current));\n  const valueText =\n    current >= count\n      ? `All ${count} steps complete`\n      : `Step ${activeIndex + 1} of ${count}: ${list[activeIndex]?.label ?? \"\"}`;\n\n  return (\n    <div\n      role=\"progressbar\"\n      aria-label={ariaLabel}\n      aria-valuemin={0}\n      aria-valuemax={count}\n      aria-valuenow={current}\n      aria-valuetext={valueText}\n      className={cn(\"flex w-full flex-col gap-2\", className)}\n    >\n      <div className=\"flex w-full gap-1.5\">\n        {list.map((_step, i) => {\n          const fill = clamp01(current - i);\n          const order = growing\n            ? Math.max(0, i - Math.floor(from))\n            : Math.max(0, Math.ceil(from) - 1 - i);\n          return (\n            <div\n              // biome-ignore lint/suspicious/noArrayIndexKey: segments are positional and never reorder\n              key={i}\n              className={cn(\n                \"relative flex-1 overflow-hidden rounded-full bg-foreground/10\",\n                TRACK_SIZE[size],\n              )}\n            >\n              <motion.div\n                className={cn(\n                  \"absolute inset-0 origin-left rounded-full bg-primary\",\n                  indicatorClassName,\n                )}\n                initial={false}\n                animate={{ scaleX: fill }}\n                transition={\n                  reduce\n                    ? { duration: 0 }\n                    : { duration: 0.32, ease: EASE_OUT, delay: order * SEGMENT_STAGGER }\n                }\n              />\n            </div>\n          );\n        })}\n      </div>\n      {showLabels ? (\n        <div aria-hidden=\"true\" className=\"flex w-full gap-1.5\">\n          {list.map((step, i) => (\n            <span\n              // biome-ignore lint/suspicious/noArrayIndexKey: segments are positional and never reorder\n              key={i}\n              className={cn(\n                \"min-w-0 flex-1 truncate text-xs transition-colors duration-200\",\n                i < current ? \"text-foreground\" : \"text-muted-foreground\",\n              )}\n            >\n              {step.label}\n            </span>\n          ))}\n        </div>\n      ) : null}\n    </div>\n  );\n}\n"},{"path":"components/motion/toggle-group.tsx","type":"registry:component","target":"@components/motion/toggle-group.tsx","content":"\"use client\";\n\nimport {\n  AnimatePresence,\n  type HTMLMotionProps,\n  motion,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  createContext,\n  forwardRef,\n  type KeyboardEvent,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from \"react\";\nimport { SPRING_LAYOUT, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { TOUCH_TARGET_CLASS } from \"@/lib/touch\";\nimport { cn } from \"@/lib/utils\";\n\n// Toggle / ToggleGroup vs SegmentedControl: `SegmentedControl`\n// (segmented-control.tsx) is a radiogroup form control that always holds one\n// value and ships a data-driven `ToggleGroup` for quick `items` arrays. This\n// file is the composable, shadcn-shaped toolbar primitive: a standalone\n// `Toggle`, and a `ToggleGroup` you fill with `ToggleGroupItem` children\n// (icons, labels, tooltips, anything), with `default`/`outline` variants. In\n// single mode one pressed surface glides between items; in multiple mode each\n// item pops its own surface in and out.\n\nexport type ToggleVariant = \"default\" | \"outline\";\nexport type ToggleSize = \"sm\" | \"md\" | \"lg\";\n\nconst sizeClass: Record<ToggleSize, string> = {\n  sm: \"h-7 min-w-7 gap-1.5 px-2 text-xs [&_svg]:size-3.5\",\n  md: \"h-9 min-w-9 gap-2 px-2.5 text-sm [&_svg]:size-4\",\n  lg: \"h-11 min-w-11 gap-2 px-3.5 text-sm [&_svg]:size-[18px]\",\n};\n\nconst surfaceClass: Record<ToggleVariant, string> = {\n  default: \"bg-muted ring-1 ring-border-strong\",\n  outline: \"bg-muted\",\n};\n\nconst itemBase =\n  \"relative isolate inline-flex shrink-0 select-none items-center justify-center whitespace-nowrap font-medium outline-none transition-colors duration-200 focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50\";\n\nfunction useControllable<T>(\n  value: T | undefined,\n  defaultValue: T,\n  onChange: ((next: T) => void) | undefined,\n) {\n  const [internal, setInternal] = useState<T>(defaultValue);\n  const controlled = value !== undefined;\n  const current = controlled ? value : internal;\n  const set = useCallback(\n    (next: T) => {\n      if (!controlled) setInternal(next);\n      onChange?.(next);\n    },\n    [controlled, onChange],\n  );\n  return [current, set] as const;\n}\n\ntype ButtonBaseProps = Omit<HTMLMotionProps<\"button\">, \"children\" | \"value\" | \"type\">;\n\n/** The pressed surface that pops in and out behind a standalone toggle or a multiple-mode item. */\nfunction PopSurface({ show, variant }: { show: boolean; variant: ToggleVariant }) {\n  const reduce = useReducedMotion();\n  return (\n    <AnimatePresence initial={false}>\n      {show ? (\n        <motion.span\n          key=\"on\"\n          aria-hidden\n          initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6 }}\n          animate={{ opacity: 1, scale: 1 }}\n          exit={\n            reduce\n              ? { opacity: 0 }\n              : { opacity: 0, scale: 0.75, transition: { duration: 0.12 } }\n          }\n          transition={SPRING_SWAP}\n          className={cn(\"absolute inset-0 -z-10 rounded-[inherit]\", surfaceClass[variant])}\n        />\n      ) : null}\n    </AnimatePresence>\n  );\n}\n\n/* ------------------------------------------------------------------------ */\n/* Toggle                                                                    */\n/* ------------------------------------------------------------------------ */\n\nexport interface ToggleProps extends ButtonBaseProps {\n  pressed?: boolean;\n  defaultPressed?: boolean;\n  onPressedChange?: (pressed: boolean) => void;\n  variant?: ToggleVariant;\n  size?: ToggleSize;\n  children?: ReactNode;\n}\n\n/** A two-state button (`aria-pressed`) whose pressed surface springs in and out. */\nexport const Toggle = forwardRef<HTMLButtonElement, ToggleProps>(function Toggle(\n  {\n    pressed,\n    defaultPressed = false,\n    onPressedChange,\n    variant = \"default\",\n    size = \"md\",\n    disabled,\n    className,\n    children,\n    onClick,\n    ...rest\n  },\n  ref,\n) {\n  const reduce = useReducedMotion();\n  const [on, setOn] = useControllable(pressed, defaultPressed, onPressedChange);\n  return (\n    <motion.button\n      ref={ref}\n      type=\"button\"\n      aria-pressed={on}\n      data-state={on ? \"on\" : \"off\"}\n      disabled={disabled}\n      whileTap={reduce || disabled ? undefined : { scale: 0.9 }}\n      transition={SPRING_PRESS}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) setOn(!on);\n      }}\n      className={cn(\n        itemBase,\n        TOUCH_TARGET_CLASS,\n        \"rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-background\",\n        sizeClass[size],\n        variant === \"outline\" && \"border border-border\",\n        on\n          ? \"text-foreground\"\n          : \"text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground\",\n        className,\n      )}\n      {...rest}\n    >\n      <PopSurface show={on} variant={variant} />\n      {children}\n    </motion.button>\n  );\n});\n\n/* ------------------------------------------------------------------------ */\n/* ToggleGroup                                                               */\n/* ------------------------------------------------------------------------ */\n\ninterface ToggleGroupContextValue {\n  type: \"single\" | \"multiple\";\n  pressed: string[];\n  toggle: (value: string) => void;\n  variant: ToggleVariant;\n  size: ToggleSize;\n  disabled: boolean;\n  layoutId: string;\n  tabStop: string | null;\n  setTabStop: (value: string) => void;\n}\n\nconst ToggleGroupContext = createContext<ToggleGroupContextValue | null>(null);\n\ntype ToggleGroupBase = Omit<\n  HTMLMotionProps<\"div\">,\n  \"children\" | \"defaultValue\" | \"onChange\" | \"dir\"\n> & {\n  variant?: ToggleVariant;\n  size?: ToggleSize;\n  disabled?: boolean;\n  /** Arrow-key axis for roving focus. Default \"horizontal\" (both axes still work). */\n  orientation?: \"horizontal\" | \"vertical\";\n  children?: ReactNode;\n};\n\nexport type ToggleGroupSingleProps = ToggleGroupBase & {\n  type: \"single\";\n  /** The pressed item, or `\"\"` when none is pressed. */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** Disallow un-pressing the active item, so one is always pressed. */\n  required?: boolean;\n};\n\nexport type ToggleGroupMultipleProps = ToggleGroupBase & {\n  type: \"multiple\";\n  value?: string[];\n  defaultValue?: string[];\n  onValueChange?: (value: string[]) => void;\n};\n\nexport type ToggleGroupProps = ToggleGroupSingleProps | ToggleGroupMultipleProps;\n\nconst ITEM_SELECTOR = \"[data-toggle-group-item]\";\n\nfunction enabledItems(root: HTMLElement | null) {\n  if (!root) return [];\n  return Array.from(root.querySelectorAll<HTMLButtonElement>(ITEM_SELECTOR)).filter(\n    (el) => !el.disabled && el.closest(\"[data-toggle-group]\") === root,\n  );\n}\n\n/**\n * Toolbar-style group of `ToggleGroupItem`s. `type=\"single\"` behaves like a\n * set of mutually exclusive toggles (deselectable unless `required`) whose\n * pressed surface glides between items; `type=\"multiple\"` presses any subset.\n * One tab stop, arrow keys / Home / End rove between items, Space/Enter press.\n */\nexport function ToggleGroup(props: ToggleGroupProps) {\n  const {\n    type,\n    value: _value,\n    defaultValue: _defaultValue,\n    onValueChange: _onValueChange,\n    variant = \"default\",\n    size = \"md\",\n    disabled = false,\n    orientation = \"horizontal\",\n    className,\n    children,\n    onKeyDown,\n    ...rest\n  } = props;\n  // `required` only exists on the single variant; keep it off the DOM.\n  const { required: _required, ...domProps } = rest as typeof rest & { required?: boolean };\n  const single = props.type === \"single\";\n  const required = props.type === \"single\" && Boolean(props.required);\n\n  const [pressed, setPressed] = useControllable<string[]>(\n    props.value === undefined\n      ? undefined\n      : props.type === \"single\"\n        ? props.value\n          ? [props.value]\n          : []\n        : props.value,\n    props.type === \"single\"\n      ? props.defaultValue\n        ? [props.defaultValue]\n        : []\n      : (props.defaultValue ?? []),\n    (next) => {\n      if (props.type === \"single\") props.onValueChange?.(next[0] ?? \"\");\n      else props.onValueChange?.(next);\n    },\n  );\n\n  const layoutId = useId();\n  const rootRef = useRef<HTMLDivElement>(null);\n  const [tabStop, setTabStop] = useState<string | null>(pressed[0] ?? null);\n\n  // Keep exactly one reachable tab stop: if the remembered item vanished or\n  // got disabled, fall back to the first pressed item, then the first enabled.\n  useEffect(() => {\n    const items = enabledItems(rootRef.current);\n    if (items.some((el) => el.dataset.value === tabStop)) return;\n    const fallback =\n      items.find((el) => pressed.includes(el.dataset.value ?? \"\")) ?? items[0];\n    const next = fallback?.dataset.value ?? null;\n    if (next !== tabStop) setTabStop(next);\n  });\n\n  const toggle = (itemValue: string) => {\n    const isOn = pressed.includes(itemValue);\n    if (single) {\n      if (isOn && required) return;\n      setPressed(isOn ? [] : [itemValue]);\n    } else {\n      setPressed(isOn ? pressed.filter((v) => v !== itemValue) : [...pressed, itemValue]);\n    }\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented) return;\n    const items = enabledItems(rootRef.current);\n    const index = items.indexOf(document.activeElement as HTMLButtonElement);\n    if (index < 0) return;\n    const forward = orientation === \"vertical\" ? \"ArrowDown\" : \"ArrowRight\";\n    const backward = orientation === \"vertical\" ? \"ArrowUp\" : \"ArrowLeft\";\n    let next: number;\n    if (event.key === forward || event.key === \"ArrowDown\" || event.key === \"ArrowRight\")\n      next = (index + 1) % items.length;\n    else if (event.key === backward || event.key === \"ArrowUp\" || event.key === \"ArrowLeft\")\n      next = (index - 1 + items.length) % items.length;\n    else if (event.key === \"Home\") next = 0;\n    else if (event.key === \"End\") next = items.length - 1;\n    else return;\n    event.preventDefault();\n    // Focus moves; pressing stays on Space/Enter — these are toggles, not radios.\n    items[next].focus();\n  };\n\n  return (\n    <ToggleGroupContext.Provider\n      value={{\n        type,\n        pressed,\n        toggle,\n        variant,\n        size,\n        disabled,\n        layoutId,\n        tabStop,\n        setTabStop,\n      }}\n    >\n      {/* layoutRoot keeps the gliding surface's projection local to the group,\n          so scrolled or transformed ancestors never skew the glide. */}\n      <motion.div\n        ref={rootRef}\n        layoutRoot\n        role=\"group\"\n        data-toggle-group=\"\"\n        data-orientation={orientation}\n        aria-disabled={disabled || undefined}\n        onKeyDown={handleKeyDown}\n        className={cn(\n          \"inline-flex w-fit items-center\",\n          orientation === \"vertical\" && \"flex-col items-stretch\",\n          variant === \"default\"\n            ? \"gap-0.5 rounded-xl border border-border bg-card p-1\"\n            : \"rounded-lg\",\n          disabled && \"opacity-60\",\n          className,\n        )}\n        {...domProps}\n      >\n        {children}\n      </motion.div>\n    </ToggleGroupContext.Provider>\n  );\n}\n\nexport interface ToggleGroupItemProps extends ButtonBaseProps {\n  value: string;\n  children?: ReactNode;\n}\n\nexport const ToggleGroupItem = forwardRef<HTMLButtonElement, ToggleGroupItemProps>(\n  function ToggleGroupItem(\n    { value, disabled: itemDisabled, className, children, onClick, onFocus, ...rest },\n    ref,\n  ) {\n    const ctx = useContext(ToggleGroupContext);\n    if (!ctx) throw new Error(\"ToggleGroupItem must be used inside <ToggleGroup>.\");\n    const reduce = useReducedMotion();\n    const disabled = ctx.disabled || Boolean(itemDisabled);\n    const on = ctx.pressed.includes(value);\n    const outline = ctx.variant === \"outline\";\n\n    return (\n      <motion.button\n        ref={ref}\n        type=\"button\"\n        data-toggle-group-item=\"\"\n        data-value={value}\n        data-state={on ? \"on\" : \"off\"}\n        aria-pressed={on}\n        disabled={disabled}\n        tabIndex={ctx.tabStop === value ? 0 : -1}\n        whileTap={reduce || disabled ? undefined : { scale: 0.88 }}\n        transition={SPRING_PRESS}\n        onFocus={(event) => {\n          ctx.setTabStop(value);\n          onFocus?.(event);\n        }}\n        onClick={(event) => {\n          onClick?.(event);\n          if (event.defaultPrevented) return;\n          ctx.setTabStop(value);\n          ctx.toggle(value);\n        }}\n        className={cn(\n          itemBase,\n          TOUCH_TARGET_CLASS,\n          sizeClass[ctx.size],\n          outline\n            ? // Joined segments: neighbours overlap their shared border.\n              \"rounded-none border border-border bg-card -ml-px first:ml-0 first:rounded-l-lg last:rounded-r-lg in-data-[orientation=vertical]:-mt-px in-data-[orientation=vertical]:ml-0 in-data-[orientation=vertical]:first:mt-0 in-data-[orientation=vertical]:first:rounded-l-none in-data-[orientation=vertical]:first:rounded-t-lg in-data-[orientation=vertical]:last:rounded-r-none in-data-[orientation=vertical]:last:rounded-b-lg\"\n            : \"rounded-lg focus-visible:ring-offset-1 focus-visible:ring-offset-card\",\n          on\n            ? \"text-foreground\"\n            : \"text-muted-foreground enabled:hover:bg-muted/60 enabled:hover:text-foreground\",\n          className,\n        )}\n        {...rest}\n      >\n        {ctx.type === \"single\" ? (\n          on ? (\n            <motion.span\n              layoutId={ctx.layoutId}\n              aria-hidden\n              transition={reduce ? { duration: 0 } : SPRING_LAYOUT}\n              className={cn(\n                \"absolute inset-0 -z-10 rounded-[inherit]\",\n                surfaceClass[ctx.variant],\n              )}\n            />\n          ) : null\n        ) : (\n          <PopSurface show={on} variant={ctx.variant} />\n        )}\n        {children}\n      </motion.button>\n    );\n  },\n);\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"components/motion/anchored-placement.ts","type":"registry:component","target":"@components/motion/anchored-placement.ts","content":"import type { PortalLayout } from \"@/components/motion/popover-position\";\n\nexport type PlacementSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport type PlacementAlign = \"start\" | \"center\" | \"end\";\n\nexport interface PlacementOptions {\n  side: PlacementSide;\n  align: PlacementAlign;\n  /** Gap between trigger and panel along the side axis, in px. */\n  sideOffset?: number;\n  /** Shift along the align axis, in px. */\n  alignOffset?: number;\n  /** Minimum distance kept from the viewport edges, in px. */\n  padding?: number;\n}\n\nexport interface Placement {\n  left: number;\n  top: number;\n  /** The side actually used — differs from the requested one after a flip. */\n  side: PlacementSide;\n  /** Trigger-facing point of the panel, as a CSS transform-origin (px). */\n  origin: string;\n}\n\nconst OPPOSITE: Record<PlacementSide, PlacementSide> = {\n  top: \"bottom\",\n  bottom: \"top\",\n  left: \"right\",\n  right: \"left\",\n};\n\nfunction clamp(value: number, min: number, max: number) {\n  return Math.min(Math.max(value, min), Math.max(min, max));\n}\n\n/**\n * Places a portalled panel against its trigger in viewport coordinates\n * (pair with `usePopoverPortalPosition`). Flips to the opposite side when the\n * requested one lacks room and the other has more, then clamps the panel into\n * the viewport on both axes. The returned origin is the trigger's center\n * projected onto the panel's facing edge, so a scale entrance grows out of the\n * trigger even after a flip or a clamp.\n */\nexport function resolvePlacement(\n  layout: PortalLayout,\n  {\n    side: requested,\n    align,\n    sideOffset = 6,\n    alignOffset = 0,\n    padding = 8,\n  }: PlacementOptions,\n): Placement {\n  const { trigger, content } = layout;\n  const vw = window.innerWidth;\n  const vh = window.innerHeight;\n  const space: Record<PlacementSide, number> = {\n    top: trigger.top - sideOffset - padding,\n    bottom: vh - (trigger.top + trigger.height) - sideOffset - padding,\n    left: trigger.left - sideOffset - padding,\n    right: vw - (trigger.left + trigger.width) - sideOffset - padding,\n  };\n  const vertical = requested === \"top\" || requested === \"bottom\";\n  const need = vertical ? content.height : content.width;\n  const opposite = OPPOSITE[requested];\n  const side =\n    space[requested] < need && space[opposite] > space[requested]\n      ? opposite\n      : requested;\n\n  let left: number;\n  let top: number;\n  if (vertical) {\n    top =\n      side === \"bottom\"\n        ? trigger.top + trigger.height + sideOffset\n        : trigger.top - content.height - sideOffset;\n    left =\n      align === \"start\"\n        ? trigger.left\n        : align === \"end\"\n          ? trigger.left + trigger.width - content.width\n          : trigger.left + trigger.width / 2 - content.width / 2;\n    left = clamp(left + alignOffset, padding, vw - content.width - padding);\n    top = clamp(top, padding, vh - content.height - padding);\n  } else {\n    left =\n      side === \"right\"\n        ? trigger.left + trigger.width + sideOffset\n        : trigger.left - content.width - sideOffset;\n    top =\n      align === \"start\"\n        ? trigger.top\n        : align === \"end\"\n          ? trigger.top + trigger.height - content.height\n          : trigger.top + trigger.height / 2 - content.height / 2;\n    top = clamp(top + alignOffset, padding, vh - content.height - padding);\n    left = clamp(left, padding, vw - content.width - padding);\n  }\n\n  const cx = clamp(trigger.left + trigger.width / 2 - left, 0, content.width);\n  const cy = clamp(trigger.top + trigger.height / 2 - top, 0, content.height);\n  const origin =\n    side === \"bottom\"\n      ? `${cx}px 0px`\n      : side === \"top\"\n        ? `${cx}px ${content.height}px`\n        : side === \"right\"\n          ? `0px ${cy}px`\n          : `${content.width}px ${cy}px`;\n\n  return { left, top, side, origin };\n}\n"},{"path":"components/motion/popover-position.ts","type":"registry:component","target":"@components/motion/popover-position.ts","content":"\"use client\";\n\nimport {\n  type MutableRefObject,\n  useCallback,\n  useLayoutEffect,\n  useState,\n} from \"react\";\n\nexport type PortalLayout = {\n  trigger: {\n    left: number;\n    top: number;\n    width: number;\n    height: number;\n  };\n  content: {\n    width: number;\n    height: number;\n  };\n};\n\nfunction sameLayout(a: PortalLayout | null, b: PortalLayout) {\n  return (\n    a?.trigger.left === b.trigger.left &&\n    a.trigger.top === b.trigger.top &&\n    a.trigger.width === b.trigger.width &&\n    a.trigger.height === b.trigger.height &&\n    a.content.width === b.content.width &&\n    a.content.height === b.content.height\n  );\n}\n\n/** Measures a trigger and portalled panel in viewport coordinates. */\nexport function usePopoverPortalPosition<\n  TriggerElement extends HTMLElement,\n  ContentElement extends HTMLElement,\n>(\n  triggerRef: MutableRefObject<TriggerElement | null>,\n  contentRef: MutableRefObject<ContentElement | null>,\n  active: boolean,\n) {\n  const [layout, setLayout] = useState<PortalLayout | null>(null);\n\n  const update = useCallback(() => {\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    if (!trigger || !content) return;\n\n    const rect = trigger.getBoundingClientRect();\n    const next: PortalLayout = {\n      trigger: {\n        left: rect.left,\n        top: rect.top,\n        width: rect.width,\n        height: rect.height,\n      },\n      content: {\n        width: content.offsetWidth,\n        height: content.offsetHeight,\n      },\n    };\n    setLayout((current) => (sameLayout(current, next) ? current : next));\n  }, [contentRef, triggerRef]);\n\n  useLayoutEffect(() => {\n    update();\n    if (!active) return;\n\n    const trigger = triggerRef.current;\n    const content = contentRef.current;\n    const observer = new ResizeObserver(update);\n    if (trigger) observer.observe(trigger);\n    if (content) observer.observe(content);\n\n    window.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      observer.disconnect();\n      window.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [active, contentRef, triggerRef, update]);\n\n  return layout;\n}\n"},{"path":"lib/hooks/use-dismiss.ts","type":"registry:hook","target":"@lib/hooks/use-dismiss.ts","content":"\"use client\";\n\nimport { type RefObject, useEffect } from \"react\";\n\n/**\n * What the dismissing gesture does to the control it landed on.\n *\n * `\"pass-through\"` is the platform norm (native popover light-dismiss): the\n * tap closes the overlay *and* activates whatever was under it. Use\n * `\"consume\"` where the open overlay sits over or beside controls that would\n * be costly to trigger by accident — the dismissal then swallows the\n * activation too, so the gesture only closes.\n */\nexport type DismissBehavior = \"pass-through\" | \"consume\";\n\nexport interface DismissOptions {\n  /** Default `\"pass-through\"`. */\n  behavior?: DismissBehavior;\n  /** Dismiss on Escape as well. Default true. */\n  escape?: boolean;\n  /** Return true for an outside target that should *not* dismiss. Must be stable. */\n  ignore?: (target: Element) => boolean;\n}\n\n/**\n * What every currently open dismiss scope counts as inside itself. A consumed\n * dismissal reads this to tell a stray gesture from one that belongs to an\n * overlay in front of it: overlays have no shared z-order to consult, but the\n * one the gesture landed in has said as much by registering it.\n */\nconst openScopes = new Set<(target: Element) => boolean>();\n\nfunction claimedByAnotherScope(\n  self: (target: Element) => boolean,\n  target: Element,\n) {\n  for (const scope of openScopes) {\n    if (scope !== self && scope(target)) return true;\n  }\n  return false;\n}\n\n// preventDefault on pointerdown does not suppress the click that follows, so\n// consuming a gesture means swallowing that click itself. The swallower\n// deliberately outlives the effect that installed it — the dismissal it\n// belongs to has already unmounted or re-rendered by the time the click lands.\n// It releases on that click, or on the next gesture if the pointer is dragged\n// away and no click ever arrives, so it can never eat a later one. A keydown\n// releases it too: a gesture that ends with neither a click nor a cancel would\n// otherwise leave it armed, and the click Enter synthesizes on some focused\n// control is not the one this dismissal was owed.\nfunction consumeActivation(source: Event) {\n  const swallow = (event: MouseEvent) => {\n    event.preventDefault();\n    event.stopPropagation();\n    release();\n  };\n  const restart = (event: Event) => {\n    if (event !== source) release();\n  };\n  const release = () => {\n    window.removeEventListener(\"click\", swallow, true);\n    window.removeEventListener(\"pointerdown\", restart, true);\n    window.removeEventListener(\"pointercancel\", restart, true);\n    window.removeEventListener(\"keydown\", release, true);\n  };\n  window.addEventListener(\"click\", swallow, true);\n  window.addEventListener(\"pointerdown\", restart, true);\n  window.addEventListener(\"pointercancel\", restart, true);\n  window.addEventListener(\"keydown\", release, true);\n}\n\n/**\n * Close an open overlay on Escape or a pointerdown outside `ref`. Pass `null`\n * for `ref` when what counts as inside isn't one element, and say so with\n * `ignore` instead.\n *\n * The pointerdown listener is capture-phase: a bubble-phase one is blinded by\n * any handler in between that stops propagation, and an overlay cannot know\n * what it is layered over. `onDismiss` and `ignore` must be stable (wrap in\n * useCallback) so the listeners aren't re-bound every render while open.\n */\nexport function useDismiss(\n  open: boolean,\n  onDismiss: () => void,\n  ref: RefObject<HTMLElement | null> | null,\n  {\n    behavior = \"pass-through\",\n    escape: dismissOnEscape = true,\n    ignore,\n  }: DismissOptions = {},\n) {\n  useEffect(() => {\n    if (!open) return;\n    const inside = (target: Element) =>\n      Boolean(ref?.current?.contains(target)) || Boolean(ignore?.(target));\n    const onKey = (event: KeyboardEvent) => {\n      if (dismissOnEscape && event.key === \"Escape\") onDismiss();\n    };\n    const onPointer = (event: PointerEvent) => {\n      const target = event.target as Element | null;\n      if (!target || inside(target)) return;\n      // Outside this overlay, but inside one that is also open: the gesture is\n      // that overlay's to answer, and swallowing its click from behind would\n      // cost the user the control they actually aimed at.\n      if (behavior === \"consume\" && !claimedByAnotherScope(inside, target)) {\n        consumeActivation(event);\n      }\n      onDismiss();\n    };\n    openScopes.add(inside);\n    window.addEventListener(\"keydown\", onKey);\n    window.addEventListener(\"pointerdown\", onPointer, true);\n    return () => {\n      openScopes.delete(inside);\n      window.removeEventListener(\"keydown\", onKey);\n      window.removeEventListener(\"pointerdown\", onPointer, true);\n    };\n  }, [open, onDismiss, ref, behavior, dismissOnEscape, ignore]);\n}\n"},{"path":"components/motion/number-ticker.tsx","type":"registry:component","target":"@components/motion/number-ticker.tsx","content":"\"use client\";\n\nimport { animate, motion, useInView, useReducedMotion } from \"motion/react\";\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface NumberTickerProps {\n  value: number;\n  /** Digits to pad to (left). */\n  pad?: number;\n  /** Per-digit roll duration in seconds. */\n  duration?: number;\n  /** Stagger between digits. */\n  stagger?: number;\n  /** Render only after the element enters the viewport. */\n  startOnView?: boolean;\n  prefix?: string;\n  suffix?: string;\n  /** Add a small blur during digit rolls. */\n  blur?: boolean;\n  className?: string;\n  digitClassName?: string;\n  /** Insert en-US group separators (commas); fixed so server and client match. Server-component safe. */\n  locale?: boolean;\n  /** Custom formatter. Client-only — server components must use `locale` instead. */\n  format?: (value: number) => string;\n}\n\nconst DIGIT_HEIGHT_EM = 1.1;\nconst DIGITS = Array.from({ length: 10 }, (_, n) => n);\n\nexport function NumberTicker({\n  value,\n  pad,\n  duration = 0.9,\n  stagger = 0.04,\n  startOnView = true,\n  prefix,\n  suffix,\n  blur = false,\n  className,\n  digitClassName,\n  locale,\n  format,\n}: NumberTickerProps) {\n  const containerRef = useRef<HTMLSpanElement>(null);\n  const inView = useInView(containerRef, { once: true, amount: 0.6 });\n  const [armed, setArmed] = useState(!startOnView);\n\n  useEffect(() => {\n    if (startOnView && inView) setArmed(true);\n  }, [startOnView, inView]);\n\n  const text = useMemo(() => {\n    const rounded = Math.round(value);\n    const formatted = format\n      ? format(rounded)\n      : locale\n        ? rounded.toLocaleString(\"en-US\")\n        : rounded.toString();\n    return pad ? formatted.padStart(pad, \"0\") : formatted;\n  }, [value, pad, format, locale]);\n  const glyphs = useMemo(() => {\n    const chars = text.split(\"\");\n    // Key by place value (position from the right): a changing digit keeps its\n    // identity and rolls to the new value instead of remounting and replaying\n    // from 0. Growing numbers add glyphs on the left without re-keying the\n    // ones, tens, hundreds already on screen.\n    return chars.map((char, i) => ({ char, id: `g-${chars.length - 1 - i}` }));\n  }, [text]);\n  const readableText = `${prefix ?? \"\"}${text}${suffix ?? \"\"}`;\n\n  // Stagger is an entrance flourish. Once the reveal has played, value\n  // changes roll every digit immediately — a per-digit delay on live updates\n  // reads as lag.\n  const [entered, setEntered] = useState(false);\n  useEffect(() => {\n    if (!armed || entered) return;\n    const total = (duration + glyphs.length * stagger) * 1000;\n    const t = window.setTimeout(() => setEntered(true), total);\n    return () => window.clearTimeout(t);\n  }, [armed, entered, duration, stagger, glyphs.length]);\n\n  return (\n    <span\n      ref={containerRef}\n      className={cn(\"inline-flex items-center tabular-nums\", className)}\n    >\n      <span className=\"sr-only\">{readableText}</span>\n      <span aria-hidden=\"true\" className=\"inline-flex items-center\">\n        {prefix ? <span>{prefix}</span> : null}\n        {glyphs.map(({ char, id }, i) => {\n          const isDigit = /\\d/.test(char);\n          if (!isDigit) {\n            return (\n              <span key={id} className=\"inline-block\">\n                {char}\n              </span>\n            );\n          }\n          const digit = Number(char);\n          return (\n            <Digit\n              key={id}\n              digit={armed ? digit : 0}\n              delay={entered ? 0 : i * stagger}\n              duration={duration}\n              blur={blur}\n              className={digitClassName}\n            />\n          );\n        })}\n        {suffix ? <span>{suffix}</span> : null}\n      </span>\n    </span>\n  );\n}\n\nfunction Digit({\n  digit,\n  delay,\n  duration,\n  blur,\n  className,\n}: {\n  digit: number;\n  delay: number;\n  duration: number;\n  blur: boolean;\n  className?: string;\n}) {\n  const reduce = useReducedMotion();\n  const columnRef = useRef<HTMLSpanElement>(null);\n\n  useEffect(() => {\n    if (reduce || !blur || !columnRef.current || !Number.isFinite(digit)) {\n      return;\n    }\n\n    const node = columnRef.current;\n    const controls = animate(\n      node,\n      { filter: [\"blur(10px)\", \"blur(0px)\"] },\n      {\n        duration: Math.min(duration * 0.75, 0.32),\n        delay,\n        ease: EASE_OUT,\n      },\n    );\n\n    return () => {\n      controls.stop();\n      node.style.filter = \"blur(0px)\";\n    };\n  }, [blur, delay, digit, duration, reduce]);\n\n  return (\n    <span\n      className={cn(\"relative inline-block overflow-hidden\", className)}\n      style={{ height: `${DIGIT_HEIGHT_EM}em`, width: \"1ch\" }}\n    >\n      <motion.span\n        ref={columnRef}\n        initial={{ y: 0 }}\n        animate={{ y: `-${digit * DIGIT_HEIGHT_EM}em` }}\n        transition={\n          reduce\n            ? { duration: 0 }\n            : { duration, delay, ease: EASE_OUT }\n        }\n        className=\"absolute inset-x-0 top-0 flex flex-col items-center will-change-[transform,filter]\"\n      >\n        {DIGITS.map((n) => (\n          <span\n            key={n}\n            className=\"flex h-[1.1em] items-center justify-center leading-none\"\n          >\n            {n}\n          </span>\n        ))}\n      </motion.span>\n    </span>\n  );\n}\n"},{"path":"lib/touch.ts","type":"registry:lib","target":"@lib/touch.ts","content":"// Shared touch primitives. iOS and iPadOS run their own gestures on top of the\n// page — the long-press selection callout and the selection it drags in with\n// it — and they win: once the platform claims a touch it cancels ours\n// mid-gesture, so a press-and-hold or a drag simply dies. Surfaces that own\n// their gesture have to opt out.\n//\n// What the two classes below cover, precisely:\n// - `-webkit-touch-callout: none` stops iOS's long-press callout. WebKit-only:\n//   it is not a property other engines have, so it is inert everywhere else.\n// - `user-select: none` stops the long-press selection on every engine,\n//   Android included, and stops a drag from painting a selection under the\n//   cursor. It is inherited, so it reaches every descendant — which is why the\n//   two classes differ only in whether they apply it unconditionally.\n// What neither covers:\n// - Chrome for Android's long-press menu on a link or an image. No CSS\n//   suppresses it; a gesture surface that wraps one needs its own\n//   `onContextMenu` with `preventDefault()`.\n// - The native drag of an `<img>` or `<a>` descendant. `-webkit-user-drag` is\n//   not inherited and plain divs and buttons are not drag sources, so setting\n//   it on the surface does nothing — the child itself needs `draggable={false}`.\n\n/**\n * Classes for a surface that *is* the control: a thumb, a drum, a stage, a\n * handle, a hold button. Selection is suppressed on every input, because a\n * drag that highlights the control's own label is wrong on a mouse too.\n * Compose with `touch-none` when the surface also owns the scroll axis — leave\n * it off when the page must still scroll from there.\n */\nexport const TOUCH_GESTURE_CLASS = \"select-none [-webkit-touch-callout:none]\";\n\n/**\n * The same opt-out for a gesture surface that wraps content the consumer owns:\n * a scroller, a context-menu trigger, a sheet header, a list row. Selection is\n * suppressed only where the platform runs its own press gestures — a coarse\n * pointer — so a mouse user can still select and copy that content. If the\n * gesture itself would paint a selection under the cursor, add `select-none`\n * for the duration of the gesture rather than reaching for\n * `TOUCH_GESTURE_CLASS`.\n *\n * `pointer: coarse` describes the *primary* pointer and nothing else, so a\n * hybrid machine reads it wrong in both directions: a tablet with a mouse\n * plugged in keeps touch as primary and loses mouse selection, and a laptop\n * with a touchscreen keeps the mouse as primary and leaves selection live\n * under a finger. No media query can answer per interaction — the query is\n * about the device, and the question is about the gesture in progress. The\n * default stays here because it is right on the machines that are one thing or\n * the other, and losing a selection is a nuisance; where the miss costs a\n * *gesture* instead, the surface pairs it with `holdSelection` on the press.\n */\nexport const TOUCH_GESTURE_CONTENT_CLASS =\n  \"[-webkit-touch-callout:none] pointer-coarse:select-none\";\n\n/**\n * Grow a small control's *hit area* to at least 44×44px (WCAG 2.5.5, Apple\n * HIG) on a coarse pointer, without changing what it looks like or the space\n * it takes in layout. An invisible `::after` box, centered on the control and\n * `max(100%, 2.75rem)` on each axis, catches the taps: a 32px icon button\n * reaches 6px past each edge, a wide 40px button only grows vertically, and a\n * control already 44px or larger is left as it is. Hit-testing a pseudo\n * element lands on its owner, so handlers, focus and `:active` all behave.\n *\n * Mouse and trackpad rendering is untouched — nothing here applies outside\n * `pointer: coarse`. Requirements on the element it goes on:\n * - It must be the containing block: add `relative` (and keep it mergeable, so\n *   a consumer's `absolute` still wins through `cn`).\n * - It must not clip itself (`overflow-hidden`), or the overhang is clipped\n *   away along with its hit area.\n * - It must render children: `<input>` and other void elements have no\n *   `::after`. Put it on the wrapper or label instead.\n * - It must not already use `::after` for something visible.\n *\n * Centered 44px means two 32px buttons with a 4px gap overlap by 8px; the\n * later one wins that strip, which still ends well short of the earlier\n * button's visual center. Below a ~32px pitch the later neighbour starts\n * eating into that center — use `TOUCH_TARGET_Y_CLASS` for such dense rows.\n *\n * The overhang is real geometry: inside a scroll container it counts as\n * scrollable overflow, so a control flush against a scroller's edge can add a\n * few pixels of scroll on touch screens. Give such a scroller a little padding\n * on that side.\n */\nexport const TOUCH_TARGET_CLASS =\n  \"pointer-coarse:after:absolute pointer-coarse:after:top-1/2 pointer-coarse:after:left-1/2 pointer-coarse:after:size-[max(100%,2.75rem)] pointer-coarse:after:-translate-x-1/2 pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']\";\n\n/**\n * `TOUCH_TARGET_CLASS` on the vertical axis only, for controls packed tighter\n * than ~32px apart in a row (pagination dots, dense swatches), where growing\n * sideways would hand most of each control to its neighbour. Same rules.\n */\nexport const TOUCH_TARGET_Y_CLASS =\n  \"pointer-coarse:after:absolute pointer-coarse:after:inset-x-0 pointer-coarse:after:top-1/2 pointer-coarse:after:h-[max(100%,2.75rem)] pointer-coarse:after:-translate-y-1/2 pointer-coarse:after:content-['']\";\n\n/**\n * Suppress selection on `element` for as long as a gesture is running on it,\n * whatever the primary pointer of the machine happens to be. Returns the\n * release. Inline, so it wins over the class above and is gone again the\n * moment the gesture ends.\n *\n * For the press gestures a native selection would otherwise steal — a\n * long-press that opens a menu. Elsewhere prefer the classes: a surface that\n * takes selection away for the whole session is a surface whose text nobody\n * can copy.\n */\nexport function holdSelection(element: HTMLElement) {\n  element.style.setProperty(\"user-select\", \"none\");\n  element.style.setProperty(\"-webkit-user-select\", \"none\");\n  return () => {\n    element.style.removeProperty(\"user-select\");\n    element.style.removeProperty(\"-webkit-user-select\");\n  };\n}\n\n/**\n * Pointer capture, best effort. WebKit throws `NotFoundError` when the pointer\n * is already gone by the time the handler runs — routine on iOS, where the\n * system can claim the touch first — and an uncaught throw takes the rest of\n * the handler, the gesture included, down with it. Touch pointers carry\n * implicit capture anyway, so losing it is never fatal.\n */\nexport function capturePointer(element: Element, pointerId: number) {\n  try {\n    element.setPointerCapture(pointerId);\n  } catch {\n    // Pointer is no longer active — implicit capture still applies on touch.\n  }\n}\n\n/** Release a capture taken with `capturePointer`, ignoring a stale pointer. */\nexport function releasePointer(element: Element, pointerId: number) {\n  try {\n    if (element.hasPointerCapture(pointerId)) {\n      element.releasePointerCapture(pointerId);\n    }\n  } catch {\n    // Capture was already dropped by the browser.\n  }\n}\n\n/**\n * Whether this event came from a pointer that is *hovering*: not a touch, and\n * not currently pressed. Which input the user is holding right now is not\n * something a device capability can answer — a touchscreen laptop hovers and\n * taps, and iPadOS reports a fine hovering pointer for a finger — so both\n * paths stay live and each handler branches on the event it was given.\n *\n * A pen resting on the glass is making contact, not hovering: `buttons` is the\n * tell, and it sends a pen tap down the same route a finger takes.\n *\n * This answers what an *enter* asks. A leave is the other half of a pair and\n * has to be read against the enter that started it — `useHoverGesture` in\n * `lib/hooks/use-hover-gesture` does that, and hover surfaces should use it\n * rather than asking this question twice.\n */\nexport const isHoveringPointer = (event: {\n  pointerType: string;\n  buttons: number;\n}) => event.pointerType !== \"touch\" && event.buttons === 0;\n"}]}