{"slug":"command-palette","name":"Command Palette","description":"⌘K palette with fuzzy filter, a gliding active row, key hints and a height that holds while you type.","category":"blocks","source_url":"https://beui.dev/r/command-palette/raw","detail_url":"https://beui.dev/r/command-palette","raw_url":"https://beui.dev/r/command-palette/raw","page_url":"https://beui.dev/components/blocks/command-palette","markdown_url":"https://beui.dev/components/blocks/command-palette.md","published_at":"2026-05-17","updated_at":"2026-11-25","dependencies":["@tanstack/react-virtual","clsx","lucide-react","motion","react","react-dom","tailwind-merge"],"internal":["@/components/motion/command-palette","@/lib/command-search","@/lib/ease","@/lib/focusable","@/lib/hooks/use-focus-trap","@/lib/hooks/use-on-open","@/lib/hooks/use-row-cursor","@/lib/hooks/use-touch-capable","@/lib/i18n","@/lib/layers","@/lib/presence-gate","@/lib/scroll-lock","@/lib/utils"],"install_slugs":["command-palette"],"requires_theme":false,"props":[{"displayName":"CommandPalette","props":[{"name":"items","type":"CommandItem[]","required":true,"defaultValue":null,"description":"Commands to search, each with a label, optional group and an `onSelect` action."},{"name":"shortcut","type":"string","required":false,"defaultValue":"k","description":"Opens with Cmd/Ctrl + this key. Default: \"k\""},{"name":"placeholder","type":"string","required":false,"defaultValue":null,"description":"Hint text in the search field. Default: \"Type a command or search…\""},{"name":"emptyMessage","type":"string","required":false,"defaultValue":null,"description":"Text shown when no command matches. Default: \"No results found.\""},{"name":"open","type":"boolean","required":false,"defaultValue":null,"description":"Whether the palette is open, for controlled use."},{"name":"onOpenChange","type":"((open: boolean) => void)","required":false,"defaultValue":null,"description":"Called with the new open state when the palette opens or closes."},{"name":"labels","type":"Partial<{ placeholder: string; empty: string; close: string; dialog: string; list: string; results: string; navigate: string; select: string; dismiss: string; recent: string; clearRecent: string; }>","required":false,"defaultValue":null,"description":"Override any built-in string. `results` names items without a `group`."},{"name":"recent","type":"string | boolean","required":false,"defaultValue":"false","description":"Remember the commands people pick and list them first, under \"Recent\",\nwhile the search is empty. Saved in localStorage; pass a string to choose\nthe storage key. Default: off"},{"name":"recentLimit","type":"number","required":false,"defaultValue":"5","description":"How many recent commands to keep. Default: 5"},{"name":"className","type":"string","required":false,"defaultValue":null,"description":"Classes for the dialog panel."}]}],"types":[{"name":"CommandItem","file":"components/motion/command-palette.tsx","fields":[{"name":"id","type":"string","required":true,"description":"Unique key for the command, also stored in the recent list."},{"name":"label","type":"string","required":true,"description":"Name shown in the row and matched by search."},{"name":"group","type":"string","required":false,"description":"Heading the command is listed under; also searched. Default: \"Results\""},{"name":"hint","type":"string","required":false,"description":"Shortcut text shown as a key at the row end, such as \"⌘K\"."},{"name":"keywords","type":"string[]","required":false,"description":"Extra search terms, such as aliases, that match this command."},{"name":"icon","type":"LucideIcon","required":false,"description":"Lucide icon shown before the label."},{"name":"badge","type":"ReactNode","required":false,"description":"Content shown after the label, such as a status tag."},{"name":"onSelect","type":"() => void","required":true,"description":"Called when the command is chosen, before the palette closes."}]}],"files":[{"path":"components/motion/command-palette.tsx","type":"component","content":"\"use client\";\n// beui.dev/components/blocks/command-palette\n\nimport { observeElementRect, useVirtualizer } from \"@tanstack/react-virtual\";\nimport { AnimatePresence, LayoutGroup, motion, useReducedMotion } from \"motion/react\";\nimport { Search, type LucideIcon } from \"lucide-react\";\nimport {\n  type ReactNode,\n  useCallback,\n  useEffect,\n  useId,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { EASE_OUT } from \"@/lib/ease\";\nimport { useFocusTrap } from \"@/lib/hooks/use-focus-trap\";\nimport { useOnOpen } from \"@/lib/hooks/use-on-open\";\nimport { useRowCursor } from \"@/lib/hooks/use-row-cursor\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { useTouchCapable } from \"@/lib/hooks/use-touch-capable\";\nimport { PresenceGate } from \"@/lib/presence-gate\";\nimport { useScrollLock } from \"@/lib/scroll-lock\";\nimport { cn } from \"@/lib/utils\";\nimport { searchCommands } from \"@/lib/command-search\";\n\nexport type CommandItem = {\n  /** Unique key for the command, also stored in the recent list. */\n  id: string;\n  /** Name shown in the row and matched by search. */\n  label: string;\n  /** Heading the command is listed under; also searched. Default: \"Results\" */\n  group?: string;\n  /** Shortcut text shown as a key at the row end, such as \"⌘K\". */\n  hint?: string;\n  /** Extra search terms, such as aliases, that match this command. */\n  keywords?: string[];\n  /** Lucide icon shown before the label. */\n  icon?: LucideIcon;\n  /** Content shown after the label, such as a status tag. */\n  badge?: ReactNode;\n  /** Called when the command is chosen, before the palette closes. */\n  onSelect: () => void;\n};\n\n/** English defaults. Override per instance with `labels`, or app-wide with `LocaleProvider`. */\nexport const commandPaletteMessages = {\n  placeholder: \"Type a command or search…\",\n  empty: \"No results found.\",\n  close: \"Close command palette\",\n  dialog: \"Command palette\",\n  list: \"Commands\",\n  results: \"Results\",\n  navigate: \"Navigate\",\n  select: \"Select\",\n  dismiss: \"Close\",\n  recent: \"Recent\",\n  clearRecent: \"Clear recent\",\n};\n\nexport type CommandPaletteMessages = typeof commandPaletteMessages;\n\nexport interface CommandPaletteProps {\n  /** Commands to search, each with a label, optional group and an `onSelect` action. */\n  items: CommandItem[];\n  /** Opens with Cmd/Ctrl + this key. Default: \"k\" */\n  shortcut?: string;\n  /** Hint text in the search field. Default: \"Type a command or search…\" */\n  placeholder?: string;\n  /** Text shown when no command matches. Default: \"No results found.\" */\n  emptyMessage?: string;\n  /** Whether the palette is open, for controlled use. */\n  open?: boolean;\n  /** Called with the new open state when the palette opens or closes. */\n  onOpenChange?: (open: boolean) => void;\n  /** Override any built-in string. `results` names items without a `group`. */\n  labels?: Partial<CommandPaletteMessages>;\n  /**\n   * Remember the commands people pick and list them first, under \"Recent\",\n   * while the search is empty. Saved in localStorage; pass a string to choose\n   * the storage key. Default: off\n   */\n  recent?: boolean | string;\n  /** How many recent commands to keep. Default: 5 */\n  recentLimit?: number;\n  /** Classes for the dialog panel. */\n  className?: string;\n}\n\nconst RECENT_KEY = \"beui-command-palette-recent\";\n\n/** Recent command ids, newest first. Storage can be blocked or hold junk. */\nfunction readRecent(key: string): string[] {\n  try {\n    const value: unknown = JSON.parse(localStorage.getItem(key) ?? \"[]\");\n    return Array.isArray(value) ? value.filter((id): id is string => typeof id === \"string\") : [];\n  } catch {\n    return [];\n  }\n}\n\nfunction writeRecent(key: string, ids: string[]) {\n  try {\n    if (ids.length) localStorage.setItem(key, JSON.stringify(ids));\n    else localStorage.removeItem(key);\n  } catch {\n    // Storage blocked (private mode, quota): recents just don't persist.\n  }\n}\n\n// Opened by a shortcut many times a day, so it must read as instant: a short\n// fade and drop, no scale, and an exit that mirrors it a little faster.\nconst PANEL_IN = { duration: 0.18, ease: EASE_OUT } as const;\nconst PANEL_OUT = { duration: 0.14, ease: EASE_OUT } as const;\nconst DROP_PX = 8;\n// The active row's tint follows arrow keys; a short tween keeps it on the row\n// without lag or overshoot.\nconst HIGHLIGHT = { duration: 0.15, ease: EASE_OUT } as const;\n\n// Fixed sizes the list height is computed from; keep in step with the\n// classes below (p-2, label pt-1.5 pb-1 with a 16px line, mb-2, h-9 rows).\nconst LIST_PAD = 16;\nconst GROUP_LABEL = 26;\nconst GROUP_GAP = 8;\nconst ROW = 36;\n// Room for the empty state when nothing matches a short list.\nconst LIST_MIN = 160;\n// The list's tallest size (22rem); it may be shorter on short screens.\nconst LIST_MAX = 352;\n\ntype Entry =\n  | { kind: \"label\"; key: string; group: string; size: number }\n  | { kind: \"row\"; key: string; item: CommandItem; index: number; size: number };\n\nconst KEY =\n  \"inline-flex h-5 min-w-5 items-center justify-center rounded-md border border-border px-1 font-sans text-[11px] text-muted-foreground\";\n\nexport function CommandPalette({\n  items,\n  shortcut = \"k\",\n  placeholder: placeholderProp,\n  emptyMessage: emptyMessageProp,\n  open: controlledOpen,\n  onOpenChange,\n  labels,\n  recent = false,\n  recentLimit = 5,\n  className,\n}: CommandPaletteProps) {\n  const t = useMessages(\"commandPalette\", commandPaletteMessages, labels);\n  const placeholder = placeholderProp ?? t(\"placeholder\");\n  const emptyMessage = emptyMessageProp ?? t(\"empty\");\n  const [internalOpen, setInternalOpen] = useState(false);\n  const controlled = controlledOpen !== undefined;\n  const open = controlled ? controlledOpen : internalOpen;\n  const setOpen = useCallback(\n    (v: boolean) => {\n      if (!controlled) setInternalOpen(v);\n      onOpenChange?.(v);\n    },\n    [controlled, onOpenChange],\n  );\n\n  const [query, setQuery] = useState(\"\");\n  // Portal target only exists client-side; render nothing during SSR/hydration.\n  const [mounted, setMounted] = useState(false);\n  useEffect(() => setMounted(true), []);\n  const uid = useId();\n  const reduce = useReducedMotion();\n  const canTouch = useTouchCapable();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const panelRef = useRef<HTMLDivElement>(null);\n\n  useEffect(() => {\n    const onKey = (e: KeyboardEvent) => {\n      if (\n        (e.metaKey || e.ctrlKey) &&\n        e.key.toLowerCase() === shortcut.toLowerCase()\n      ) {\n        e.preventDefault();\n        setOpen(!open);\n      }\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [open, shortcut, setOpen]);\n\n  // A modal dialog: Tab stays inside, Escape closes, and focus goes back to\n  // whatever opened it.\n  const close = useCallback(() => setOpen(false), [setOpen]);\n  useFocusTrap(open && mounted, panelRef, { onEscape: close });\n  useScrollLock(open);\n\n  const filtered = useMemo(() => searchCommands(items, query), [items, query]);\n\n  const recentKey = recent ? (typeof recent === \"string\" ? recent : RECENT_KEY) : null;\n  // A palette rendered already open has no opening render for `useOnOpen` to\n  // catch, so the first state reads storage too. On the server the read finds\n  // no storage and returns nothing; the palette renders nothing there anyway.\n  const [recentIds, setRecentIds] = useState<string[]>(() =>\n    open && recentKey ? readRecent(recentKey) : [],\n  );\n  // Recent ids that still name an item, newest first. Ids of commands that\n  // have since gone are dropped rather than shown as blanks.\n  const recentItems = useMemo(\n    () =>\n      recentIds\n        .map((id) => items.find((it) => it.id === id))\n        .filter((it): it is CommandItem => Boolean(it))\n        .slice(0, recentLimit),\n    [recentIds, items, recentLimit],\n  );\n  // Recents show only while the search is empty; typing searches everything.\n  const showRecent = recentItems.length > 0 && query.trim() === \"\";\n\n  // Reserve the icon column only when at least one item brings an icon, so\n  // icon-less lists don't render a dead gap before every label.\n  const hasIcons = useMemo(() => items.some((it) => it.icon), [items]);\n\n  // The list is as tall as the unfiltered items need (rows and group labels\n  // have fixed heights), capped, and keeps that height while results filter,\n  // so the panel never jumps as you type and a short list leaves no void.\n  // Recents move rows into their own group, so they add one label.\n  const listHeight = useMemo(() => {\n    const groups = new Set(items.map((it) => it.group ?? \"\")).size + (recentItems.length ? 1 : 0);\n    return LIST_PAD + groups * GROUP_LABEL + Math.max(0, groups - 1) * GROUP_GAP + items.length * ROW;\n  }, [items, recentItems.length]);\n\n  const fallbackGroup = t(\"results\");\n  const recentLabel = t(\"recent\");\n  const grouped = useMemo(() => {\n    const map = new Map<string, CommandItem[]>();\n    // A recent command is listed once, at the top, not again in its group.\n    const listed = new Set(showRecent ? recentItems : []);\n    filtered.forEach((it) => {\n      if (listed.has(it)) return;\n      const g = it.group ?? fallbackGroup;\n      const groupItems = map.get(g) ?? [];\n      groupItems.push(it);\n      map.set(g, groupItems);\n    });\n    const groups = Array.from(map.entries());\n    return showRecent ? [[recentLabel, recentItems] as [string, CommandItem[]], ...groups] : groups;\n  }, [filtered, fallbackGroup, showRecent, recentItems, recentLabel]);\n\n  // Grouping reorders the list, so the rendered order is not the filtered\n  // order whenever two groups interleave. Everything that has to agree on\n  // \"which row\" - the highlight, the ids, Enter, the scroll - reads this one\n  // array, so they cannot drift apart.\n  const rows = useMemo(() => grouped.flatMap(([, list]) => list), [grouped]);\n\n  const { activeIndex: active, moveTo, moveActive } = useRowCursor(rows, query);\n\n  // The list is virtualized: group labels and rows become one flat list of\n  // fixed heights, and only the slice in view (plus a little overscan) is\n  // drawn. Opening or typing over hundreds of commands then renders a dozen\n  // rows, not all of them. `rows` stays whole, so the cursor, Enter and the\n  // ids still see every result.\n  const entries = useMemo(() => {\n    const out: Entry[] = [];\n    let index = 0;\n    grouped.forEach(([group, list], groupIndex) => {\n      out.push({\n        kind: \"label\",\n        key: `group:${group}`,\n        group,\n        size: GROUP_LABEL + (groupIndex > 0 ? GROUP_GAP : 0),\n      });\n      for (const item of list) out.push({ kind: \"row\", key: item.id, item, index: index++, size: ROW });\n    });\n    return out;\n  }, [grouped]);\n  // Entry index of each row, so the cursor can scroll its row into view.\n  const rowEntry = useMemo(\n    () => entries.flatMap((entry, i) => (entry.kind === \"row\" ? [i] : [])),\n    [entries],\n  );\n\n  const visibleHeight = Math.min(Math.max(listHeight, LIST_MIN), LIST_MAX);\n  const virtualizer = useVirtualizer({\n    count: entries.length,\n    getScrollElement: () => listRef.current,\n    estimateSize: (i) => entries[i]?.size ?? ROW,\n    getItemKey: (i) => entries[i]?.key ?? i,\n    paddingStart: LIST_PAD / 2,\n    paddingEnd: LIST_PAD / 2,\n    overscan: 6,\n    // The list's size before it is measured, so the opening render already\n    // holds the rows in view instead of an empty frame.\n    initialRect: { width: 0, height: visibleHeight },\n    // A list that measures 0 tall (no layout yet, or a test DOM) keeps its\n    // known height, so its rows still render and the active row exists.\n    observeElementRect: (instance, cb) =>\n      observeElementRect(instance, (rect) =>\n        cb(rect.height > 0 ? rect : { width: rect.width, height: visibleHeight }),\n      ),\n    enabled: open,\n  });\n  // Rows drawn right now. The field names the active row only when it is\n  // one of them, so the reference never points at a missing element.\n  const drawnRows = new Set(\n    virtualizer.getVirtualItems().flatMap((virtual) => {\n      const entry = entries[virtual.index];\n      return entry?.kind === \"row\" ? [entry.index] : [];\n    }),\n  );\n\n  // Clearing the query would drop the cursor on its own, but only if it had\n  // changed; `moveTo(null)` covers reopening on an already-empty query.\n  useOnOpen(open, () => {\n    setQuery(\"\");\n    moveTo(null);\n    if (recentKey) setRecentIds(readRecent(recentKey));\n  });\n\n  const select = (it: CommandItem) => {\n    if (recentKey) {\n      const next = [it.id, ...readRecent(recentKey).filter((id) => id !== it.id)].slice(\n        0,\n        recentLimit,\n      );\n      writeRecent(recentKey, next);\n      setRecentIds(next);\n    }\n    it.onSelect();\n    setOpen(false);\n  };\n\n  const clearRecent = () => {\n    if (recentKey) writeRecent(recentKey, []);\n    setRecentIds([]);\n    // The button goes away with the recents; keep focus in the palette.\n    inputRef.current?.focus();\n  };\n\n  useEffect(() => {\n    if (!open) return;\n    const frame = requestAnimationFrame(() => inputRef.current?.focus());\n    return () => cancelAnimationFrame(frame);\n  }, [open]);\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      moveActive(1);\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      moveActive(-1);\n    } else if (e.key === \"Enter\") {\n      if (e.nativeEvent.isComposing || e.keyCode === 229) return;\n      // Enter on a focused button (a row, Clear recent) presses that button.\n      if (e.target !== inputRef.current) return;\n      e.preventDefault();\n      const it = rows[active];\n      if (it) select(it);\n    }\n  };\n\n  // Keep the cursor's row in view. Its row may not be drawn yet, so this\n  // scrolls by index rather than to an element. The first row also brings\n  // its group label along, which is where a new query lands: the cursor\n  // returns to it and `rowEntry` changes, so this runs for every query.\n  useEffect(() => {\n    if (!open || rows.length === 0) return;\n    if (active === 0) virtualizer.scrollToOffset(0);\n    else {\n      const entry = rowEntry[active];\n      if (entry !== undefined) virtualizer.scrollToIndex(entry, { align: \"auto\" });\n    }\n  }, [active, open, rows.length, rowEntry, virtualizer]);\n\n  if (!mounted) return null;\n\n  // Portaled to <body> so ancestors with transforms, filters, or fixed\n  // positioning can't trap the overlay in their stacking context, and mounted\n  // only while open. The chrome is two fixed siblings rather than one wrapper:\n  // the backdrop spans the viewport edges but carries the scrim colour, and the\n  // layer positioning the panel is inset off every edge. Both hang off\n  // `PresenceGate`, so interaction releases in the same commit that starts the\n  // exit rather than when it ends - `open` is already false for those frames.\n  return createPortal(\n    <AnimatePresence initial={false}>\n      {open ? (\n        <PresenceGate key=\"backdrop\">\n          {({ gate }) => (\n            <motion.button\n              type=\"button\"\n              aria-label={t(\"close\")}\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0, transition: PANEL_OUT }}\n              transition={PANEL_IN}\n              {...gate}\n              onClick={() => setOpen(false)}\n              // A plain dim, no full-viewport blur: it keeps the page legible\n              // behind the panel and costs nothing to paint on mobile.\n              className=\"pointer-events-auto fixed inset-0 z-[100] bg-black/25 dark:bg-black/50\"\n            />\n          )}\n        </PresenceGate>\n      ) : null}\n\n      {open ? (\n        <PresenceGate key=\"panel-layer\">\n          {({ isPresent, gate }) => (\n            // The layer itself never takes pointer events, so it carries\n            // `inert` alone rather than the gate's pointer-events value.\n            <div\n              inert={!isPresent}\n              className=\"pointer-events-none fixed inset-x-4 bottom-4 top-[18vh] z-[100] flex items-start justify-center\"\n            >\n              <motion.div\n                ref={panelRef}\n                tabIndex={-1}\n                role=\"dialog\"\n                aria-modal=\"true\"\n                aria-label={t(\"dialog\")}\n                initial={{ opacity: 0, y: reduce ? 0 : -DROP_PX }}\n                animate={{ opacity: 1, y: 0 }}\n                exit={{ opacity: 0, y: reduce ? 0 : -DROP_PX, transition: PANEL_OUT }}\n                transition={PANEL_IN}\n                {...gate}\n                onKeyDown={onKeyDown}\n                className={cn(\n                  \"pointer-events-auto flex w-full max-w-xl flex-col overflow-hidden rounded-2xl border border-border bg-background shadow-[0_16px_48px_-12px_rgb(0_0_0/0.25)] outline-none\",\n                  className,\n                )}\n              >\n                <div className=\"flex items-center gap-3 border-b border-border px-4\">\n                  <Search aria-hidden=\"true\" className=\"size-4 shrink-0 text-muted-foreground\" />\n                  <input\n                    ref={inputRef}\n                    value={query}\n                    onChange={(e) => setQuery(e.target.value)}\n                    placeholder={placeholder}\n                    role=\"combobox\"\n                    // The field only exists while the palette is open.\n                    aria-expanded=\"true\"\n                    aria-controls={`${uid}-list`}\n                    aria-activedescendant={\n                      drawnRows.has(active) ? `${uid}-opt-${active}` : undefined\n                    }\n                    aria-autocomplete=\"list\"\n                    className={cn(\n                      \"h-12 flex-1 bg-transparent text-sm text-foreground placeholder:text-muted-foreground outline-none\",\n                      // The palette focuses this field the moment it opens, and iOS\n                      // zooms the page in on a focused field under 16px: the fixed\n                      // overlay is magnified off-center - clipped leading edge, half\n                      // an icon column - and the zoom outlives the palette. 16px on\n                      // touch keeps the page at scale 1; pointer devices keep 14px.\n                      canTouch && \"text-base\",\n                    )}\n                  />\n                </div>\n                <div\n                  ref={listRef}\n                  id={`${uid}-list`}\n                  role=\"listbox\"\n                  aria-label={t(\"list\")}\n                  style={{ height: `min(${visibleHeight}px, 55vh)` }}\n                  // Vertical padding lives in the virtualizer (paddingStart and\n                  // paddingEnd), so its offsets match the scroll position.\n                  className=\"overflow-y-auto overscroll-contain px-2 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n                >\n                  {rows.length === 0 ? (\n                    <div className=\"flex h-full flex-col items-center justify-center gap-3 text-sm text-muted-foreground\">\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"flex size-10 items-center justify-center rounded-full border border-border\"\n                      >\n                        <Search className=\"size-4\" />\n                      </span>\n                      {emptyMessage}\n                    </div>\n                  ) : (\n                    // One namespace per query: the highlight glides between\n                    // rows while you arrow through them, but never flies across\n                    // a list that just re-filtered under it.\n                    <LayoutGroup id={`${uid}-${query}`}>\n                    <div className=\"relative w-full\" style={{ height: virtualizer.getTotalSize() }}>\n                    {virtualizer.getVirtualItems().map((virtual) => {\n                      const entry = entries[virtual.index];\n                      if (!entry) return null;\n                      const place = {\n                        height: virtual.size,\n                        transform: `translateY(${virtual.start}px)`,\n                      };\n                      if (entry.kind === \"label\") {\n                        return (\n                          <div\n                            key={virtual.key}\n                            aria-hidden\n                            style={place}\n                            className=\"absolute top-0 left-0 flex w-full items-end px-3 pb-1 text-xs font-medium text-muted-foreground\"\n                          >\n                            {entry.group}\n                          </div>\n                        );\n                      }\n                      const { item: it, index: idx } = entry;\n                      const isActive = idx === active;\n                      const Icon = it.icon;\n                      return (\n                            <button\n                              key={virtual.key}\n                              type=\"button\"\n                              id={`${uid}-opt-${idx}`}\n                              role=\"option\"\n                              aria-selected={isActive}\n                              // Not every option is in the DOM, so each says\n                              // where it sits in the whole list.\n                              aria-setsize={rows.length}\n                              aria-posinset={idx + 1}\n                              data-index={idx}\n                              style={place}\n                              onMouseEnter={() => moveTo(it.id)}\n                              onClick={() => select(it)}\n                              className={cn(\n                                \"absolute top-0 left-0 isolate flex w-full items-center gap-3 rounded-lg px-3 text-left text-sm transition-colors duration-150\",\n                                isActive\n                                  ? \"text-foreground\"\n                                  : \"text-muted-foreground\",\n                              )}\n                            >\n                              {isActive ? (\n                                <motion.span\n                                  layoutId=\"active\"\n                                  // A light tint of the text colour, not a gray fill.\n                                  className=\"absolute inset-0 z-0 rounded-lg bg-foreground/[0.06]\"\n                                  transition={reduce ? { duration: 0 } : HIGHLIGHT}\n                                />\n                              ) : null}\n                              {Icon ? (\n                                <Icon aria-hidden=\"true\" className=\"relative z-10 size-4 shrink-0\" />\n                              ) : hasIcons ? (\n                                <span className=\"relative z-10 size-4 shrink-0\" />\n                              ) : null}\n                              <span className=\"relative z-10 flex-1 truncate\">\n                                {it.label}\n                              </span>\n                              {it.badge ? (\n                                <span className=\"relative z-10 shrink-0\">\n                                  {it.badge}\n                                </span>\n                              ) : null}\n                              {it.hint ? (\n                                <kbd className={cn(KEY, \"relative z-10 shrink-0 bg-background\")}>\n                                  {it.hint}\n                                </kbd>\n                              ) : null}\n                            </button>\n                      );\n                    })}\n                    </div>\n                    </LayoutGroup>\n                  )}\n                </div>\n                {/* Key hints for keyboards, and Clear recent. The button sits\n                    here rather than in the list, which may only hold options.\n                    It stays while you type, so the footer never comes and\n                    goes under a touch keyboard. */}\n                {canTouch && recentItems.length === 0 ? null : (\n                  <div className=\"flex h-10 shrink-0 items-center gap-4 border-t border-border px-4 text-xs text-muted-foreground\">\n                    {canTouch ? null : (\n                      <>\n                        <span aria-hidden=\"true\" className=\"inline-flex items-center gap-1.5\">\n                          <kbd className={KEY}>↑</kbd>\n                          <kbd className={KEY}>↓</kbd>\n                          {t(\"navigate\")}\n                        </span>\n                        <span aria-hidden=\"true\" className=\"inline-flex items-center gap-1.5\">\n                          <kbd className={KEY}>↵</kbd>\n                          {t(\"select\")}\n                        </span>\n                      </>\n                    )}\n                    <span className=\"ml-auto inline-flex items-center gap-4\">\n                      {recentItems.length ? (\n                        <button\n                          type=\"button\"\n                          onClick={clearRecent}\n                          className=\"-mx-2 rounded-full px-2 py-1 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring\"\n                        >\n                          {t(\"clearRecent\")}\n                        </button>\n                      ) : null}\n                      {canTouch ? null : (\n                        <span aria-hidden=\"true\" className=\"inline-flex items-center gap-1.5\">\n                          <kbd className={KEY}>Esc</kbd>\n                          {t(\"dismiss\")}\n                        </span>\n                      )}\n                    </span>\n                  </div>\n                )}\n              </motion.div>\n            </div>\n          )}\n        </PresenceGate>\n      ) : null}\n    </AnimatePresence>,\n    document.body,\n  );\n}\n"},{"path":"lib/command-search.ts","type":"util","content":"export type SearchableCommand = {\n  label: string;\n  group?: string;\n  keywords?: string[];\n};\n\nfunction normalize(value: string) {\n  return value\n    .replace(/([a-z])([A-Z])/g, \"$1 $2\")\n    .normalize(\"NFKD\")\n    .replace(/\\p{M}/gu, \"\")\n    .toLowerCase()\n    .replace(/[^\\p{L}\\p{N}]+/gu, \" \")\n    .trim();\n}\n\n// A keyword longer than this many words is prose (a description), not an\n// alias, and only ever matches as a fallback.\nconst PROSE_WORDS = 3;\n\n/** The label: whole words, word starts, then abbreviations. Never the middle\n * of a word: \"tab\" finds Tabs and Table, not Sortable List. */\nfunction labelScore(token: string, label: string) {\n  const words = label.split(\" \");\n  if (words.includes(token)) return 100;\n  if (words.some((word) => word.startsWith(token))) return 80;\n  // Keep short queries precise; fuzzy abbreviations may skip at most two\n  // letters within a word, rather than matching across a whole name.\n  if (token.length < 3) return 0;\n  for (const word of words) {\n    if (word.length - token.length > 2) continue;\n    let matched = 0;\n    for (const char of word) {\n      if (char === token[matched]) matched++;\n    }\n    if (matched === token.length) return 20;\n  }\n  return 0;\n}\n\n/** Groups, aliases and prose: whole words and word starts only, so \"tab\"\n * never matches inside \"stable\". */\nfunction wordScore(token: string, field: string, exact: number, prefix: number) {\n  const words = field.split(\" \");\n  if (words.includes(token)) return exact;\n  if (token.length >= 2 && words.some((word) => word.startsWith(token))) return prefix;\n  return 0;\n}\n\n/**\n * Match every query word and rank direct name matches first. A command\n * whose every word matched its name, group or a short keyword is a strong\n * match; one that needed a long keyword (a description) is weak, and weak\n * matches show only when nothing matched strongly. Typing \"swap\" lists the\n * swap components, not everything whose description mentions swapping.\n */\nexport function searchCommands<T extends SearchableCommand>(items: T[], query: string): T[] {\n  const normalized = normalize(query);\n  if (!normalized) return items;\n  const tokens = normalized.split(/\\s+/);\n\n  const scored = items.map((item) => {\n    const label = normalize(item.label);\n    const group = normalize(item.group ?? \"\");\n    const keywords = (item.keywords ?? []).map(normalize).filter(Boolean);\n    const aliases = keywords.filter((k) => k.split(\" \").length <= PROSE_WORDS);\n    const prose = keywords.filter((k) => k.split(\" \").length > PROSE_WORDS);\n\n    let score = label === normalized ? 10000 : label.startsWith(normalized) ? 2000 : 0;\n    let strong = true;\n    for (const token of tokens) {\n      const best = Math.max(\n        labelScore(token, label) + 40,\n        wordScore(token, group, 90, 70),\n        ...aliases.map((alias) => wordScore(token, alias, 90, 70)),\n      );\n      if (best > 40) {\n        score += best;\n        continue;\n      }\n      // Prose needs at least three letters; shorter words are everywhere.\n      const fallback =\n        token.length >= 3 ? Math.max(0, ...prose.map((text) => wordScore(token, text, 30, 20))) : 0;\n      if (!fallback) return { item, score: 0, strong: false };\n      score += fallback;\n      strong = false;\n    }\n    return { item, score, strong };\n  });\n\n  const matches = scored.filter(({ score }) => score > 0);\n  const anyStrong = matches.some(({ strong }) => strong);\n  return matches\n    .filter(({ strong }) => strong || !anyStrong)\n    .sort((a, b) => b.score - a.score)\n    .map(({ item }) => item);\n}\n"},{"path":"lib/ease.ts","type":"util","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants - defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps - label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances - modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides - pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) - critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/hooks/use-focus-trap.ts","type":"util","content":"\"use client\";\n\nimport { type RefObject, useEffect, useLayoutEffect, useRef } from \"react\";\nimport { cycleTab, focusFirstIn } from \"@/lib/focusable\";\nimport { inLayerAbove, type Layer, openLayer, ownsEscape, trapAbove } from \"@/lib/layers\";\n\nexport interface FocusTrapOptions {\n  /** Called on Escape while this is the innermost open layer. */\n  onEscape?: () => void;\n}\n\n/**\n * Moves focus into `panel` when `open` turns true, keeps Tab cycling inside it,\n * pulls focus back if it lands outside, and returns focus to whatever held it\n * before opening once `open` turns false.\n *\n * Layers opened on top (a menu portaled out of a drawer, a sheet opened from\n * it) keep focus and Escape until they close: see `lib/layers.ts`.\n *\n * For overlays rendered in place, where `useModalScope` cannot inert the rest\n * of the page. Pass `open` rather than presence: an exiting panel is already\n * inert through `PresenceGate`, so the trap releases with the same commit.\n * Give the panel `tabIndex={-1}` so it can take focus when it holds nothing\n * focusable.\n */\nexport function useFocusTrap(\n  open: boolean,\n  panel: RefObject<HTMLElement | null>,\n  { onEscape }: FocusTrapOptions = {},\n) {\n  const escapeRef = useRef(onEscape);\n  useLayoutEffect(() => {\n    escapeRef.current = onEscape;\n  });\n\n  useEffect(() => {\n    if (!open || !panel.current) return;\n    const layer: Layer = {\n      contains: (target) => Boolean(panel.current?.contains(target)),\n      traps: true,\n      get escape() {\n        return Boolean(escapeRef.current);\n      },\n    };\n    const closeLayer = openLayer(layer);\n    const returnFocus =\n      document.activeElement instanceof HTMLElement\n        ? document.activeElement\n        : null;\n    if (!panel.current.contains(document.activeElement)) focusFirstIn(panel.current);\n\n    const onFocus = (event: FocusEvent) => {\n      const target = event.target;\n      if (!(target instanceof Node) || !panel.current) return;\n      if (panel.current.closest(\"[inert]\") || panel.current.contains(target)) return;\n      if (inLayerAbove(layer, target) || trapAbove(layer)) return;\n      focusFirstIn(panel.current);\n    };\n    const onKey = (event: KeyboardEvent) => {\n      if (event.key === \"Escape\") {\n        if (!escapeRef.current || !ownsEscape(layer, event)) return;\n        event.preventDefault();\n        escapeRef.current();\n        return;\n      }\n      const active = document.activeElement;\n      if (event.defaultPrevented || (active && inLayerAbove(layer, active))) return;\n      cycleTab(event, panel.current);\n    };\n    document.addEventListener(\"focusin\", onFocus);\n    document.addEventListener(\"keydown\", onKey);\n    return () => {\n      document.removeEventListener(\"focusin\", onFocus);\n      document.removeEventListener(\"keydown\", onKey);\n      closeLayer();\n      if (returnFocus?.isConnected && !returnFocus.closest(\"[inert]\"))\n        returnFocus.focus({ preventScroll: true });\n    };\n  }, [open, panel]);\n}\n"},{"path":"lib/hooks/use-on-open.ts","type":"util","content":"\"use client\";\n\nimport { useState } from \"react\";\n\n/**\n * Runs `start` during the render in which `open` becomes true.\n *\n * Opening a list starts a fresh session - an empty query, the highlight back at\n * the top - and that is a resolution, not a side effect: a passive effect runs\n * after the commit, so the new session would carry the last one's state for a\n * window in which a key press can land.\n *\n * `start` may only set state belonging to the calling component. Anything that\n * reaches outside it - a consumer's callback, a DOM write, moving focus - is a\n * side effect, and React rejects a callback that sets another component's state\n * during this one's render. Put those in an effect keyed to `open`.\n */\nexport function useOnOpen(open: boolean, start: () => void) {\n  const [wasOpen, setWasOpen] = useState(open);\n  if (open !== wasOpen) {\n    setWasOpen(open);\n    if (open) start();\n  }\n}\n"},{"path":"lib/hooks/use-row-cursor.ts","type":"util","content":"\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\n\n/**\n * Where the keyboard or the pointer last moved to: the row's id, stamped with\n * the query it was placed under.\n */\ntype RowCursor = { id: string; query: string };\n\n/** The cursor's row, or -1 once the query has moved on or the row has left. */\nfunction indexOfCursor(\n  rows: readonly { id: string }[],\n  query: string,\n  cursor: RowCursor | null,\n) {\n  if (cursor === null || cursor.query !== query) return -1;\n  return rows.findIndex((row) => row.id === cursor.id);\n}\n\n/**\n * The highlighted row of a list whose rows can change under it.\n *\n * Which row is highlighted is resolved during render, never in a passive\n * effect: a passive effect runs after the commit, so a list that had just\n * changed would carry an `aria-activedescendant` naming a row that has left it,\n * and a key pressed in that window would commit the wrong row or nothing at\n * all.\n *\n * The cursor holds the row's id, not its position. A position alone cannot tell\n * a list that shrank from one that swapped its rows for a different set of the\n * same length, and the second case is the one that silently hands Enter to a\n * row the user never chose. A cursor whose row has left the list returns the\n * highlight to the first row rather than to the nearest surviving one: the row\n * the user aimed at is gone, and the first row is where a new query already\n * puts the highlight.\n *\n * Pass the query the list is filtered by. The cursor is stamped with it and\n * dropped when it changes, so a caller cannot forget to clear it - including a\n * caller whose query arrives as a prop and so never runs its own handler. Rows\n * that come back under a query that has moved on cannot revive it either.\n * `moveTo(null)` is for deliberate resets, such as reopening the list.\n *\n * Both callbacks keep one identity for the life of the component, and read the\n * rows and the query through a ref to do it. A caller will put them in an\n * effect's dependencies - the exhaustive-deps rule makes it - and a `moveTo`\n * rebuilt on every keystroke would re-run that effect on every keystroke.\n */\nexport function useRowCursor(rows: readonly { id: string }[], query: string) {\n  const [cursor, setCursor] = useState<RowCursor | null>(null);\n  // Written after commit, not during render: a render React discards or has not\n  // finished still runs the component body, and an event handler that read this\n  // in that window would stamp the cursor with a query the committed tree does\n  // not have.\n  const latest = useRef({ rows, query });\n  useLayoutEffect(() => {\n    latest.current = { rows, query };\n  });\n\n  const cursorRow = indexOfCursor(rows, query, cursor);\n  // Cleared rather than ignored: React re-runs this render with the cursor\n  // already gone, so rows that come back cannot revive a highlight the user has\n  // stopped aiming at.\n  if (cursor !== null && cursorRow < 0) setCursor(null);\n\n  const moveTo = useCallback(\n    (id: string | null) =>\n      setCursor(id === null ? null : { id, query: latest.current.query }),\n    [],\n  );\n\n  const moveActive = useCallback((direction: 1 | -1) => {\n    const { rows: live, query: liveQuery } = latest.current;\n    const last = live.length - 1;\n    if (last < 0) return;\n    // Steps from the row the cursor is really on, inside the update, so that\n    // two keys landing in one batch move two rows rather than one.\n    setCursor((current) => {\n      const at = Math.max(indexOfCursor(live, liveQuery, current), 0);\n      const next = Math.min(Math.max(at + direction, 0), last);\n      return { id: live[next].id, query: liveQuery };\n    });\n  }, []);\n\n  return { activeIndex: cursorRow < 0 ? 0 : cursorRow, moveTo, moveActive };\n}\n"},{"path":"lib/hooks/use-touch-capable.ts","type":"util","content":"\"use client\";\n\nimport { useEffect, useState } from \"react\";\n\n/**\n * Returns true on devices that can be touched, whatever else they claim.\n *\n * This is not the inverse of `useHoverCapable`: iPadOS Safari browses\n * desktop-class and answers `(hover: hover) and (pointer: fine)` with true\n * while a finger is the only input there is, so anything that treats\n * hover-capable as \"no touch here\" strands every iPad. Gate the *touch path*\n * of an interaction on this hook and leave hover-only polish on\n * `useHoverCapable`, so a component that opens on hover also opens on tap.\n */\nexport function useTouchCapable() {\n  const [canTouch, setCanTouch] = useState(false);\n\n  useEffect(() => {\n    if (typeof window === \"undefined\") return;\n    const mq = window.matchMedia?.(\"(any-pointer: coarse)\");\n    // iPadOS disguises its pointer media queries; maxTouchPoints it reports\n    // honestly, which is what makes it the standard iPad tell.\n    const update = () =>\n      setCanTouch(Boolean(mq?.matches) || navigator.maxTouchPoints > 0);\n    update();\n    mq?.addEventListener?.(\"change\", update);\n    return () => mq?.removeEventListener?.(\"change\", update);\n  }, []);\n\n  return canTouch;\n}\n"},{"path":"lib/i18n.tsx","type":"util","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/presence-gate.tsx","type":"util","content":"\"use client\";\n\nimport { useIsPresent } from \"motion/react\";\nimport type { ReactNode } from \"react\";\n\nexport interface PresenceGateRenderProps {\n  /**\n   * False from the render that starts the exit animation onward. An overlay\n   * kept in the tree by `AnimatePresence` is still the topmost thing on the\n   * page, so anything it decides from `open` alone stays true for the whole\n   * exit - this is the boolean that already knows the overlay is leaving.\n   */\n  isPresent: boolean;\n  /**\n   * Spread onto every layer that takes pointer events while the overlay is\n   * open. Interaction releases in the same commit that starts the exit while\n   * the visual exit keeps playing: pointer events stop landing, and `inert`\n   * drops the subtree from focus order, from tab order and from the\n   * accessibility tree - an exiting dialog is not a dialog you can still type\n   * into. A layer that never takes pointer events (a wrapper that only centres\n   * the panel) takes `inert={!isPresent}` alone, so its own\n   * `pointer-events-none` is not overwritten.\n   */\n  gate: {\n    inert: boolean;\n    style: { pointerEvents: \"auto\" | \"none\" };\n  };\n}\n\nexport interface PresenceGateProps {\n  children: (props: PresenceGateRenderProps) => ReactNode;\n}\n\n/**\n * Reads the presence of the subtree it renders and hands it down.\n *\n * `useIsPresent` only answers inside the `AnimatePresence` subtree, and the\n * components that own an overlay render the `AnimatePresence` themselves, so\n * the boolean has to be read one component further down: this is that\n * component, and the render prop is how it reaches the layers.\n */\nexport function PresenceGate({ children }: PresenceGateProps) {\n  const isPresent = useIsPresent();\n\n  return children({\n    isPresent,\n    gate: {\n      inert: !isPresent,\n      style: { pointerEvents: isPresent ? \"auto\" : \"none\" },\n    },\n  });\n}\n"},{"path":"lib/scroll-lock.ts","type":"util","content":"\"use client\";\n\nimport { useEffect } from \"react\";\n\nexport interface ScrollLockOptions {\n  /**\n   * Pin the body with `position: fixed` and restore the scroll offset on\n   * release. iOS Safari still scrolls an `overflow: hidden` body under a\n   * touch drag, so full-screen sheets that take touch gestures need this.\n   */\n  fixed?: boolean;\n}\n\n// Reference-counted, so overlays that close out of order never unlock the\n// page under one that is still open. The first lock picks the technique.\nlet owners = 0;\nlet restore: (() => void) | null = null;\n\nfunction apply({ fixed = false }: ScrollLockOptions) {\n  const root = document.documentElement;\n  const body = document.body;\n  const scrollY = window.scrollY;\n  const previous = {\n    rootOverflow: root.style.overflow,\n    overflow: body.style.overflow,\n    position: body.style.position,\n    top: body.style.top,\n    left: body.style.left,\n    right: body.style.right,\n  };\n  root.style.overflow = \"hidden\";\n  body.style.overflow = \"hidden\";\n  if (fixed) {\n    body.style.position = \"fixed\";\n    body.style.top = `-${scrollY}px`;\n    body.style.left = \"0\";\n    body.style.right = \"0\";\n  }\n  return () => {\n    root.style.overflow = previous.rootOverflow;\n    body.style.overflow = previous.overflow;\n    if (!fixed) return;\n    body.style.position = previous.position;\n    body.style.top = previous.top;\n    body.style.left = previous.left;\n    body.style.right = previous.right;\n    window.scrollTo(0, scrollY);\n  };\n}\n\n/** Locks page scroll. Call the returned function to release this lock. */\nexport function lockScroll(options: ScrollLockOptions = {}) {\n  if (owners++ === 0) restore = apply(options);\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    if (--owners === 0) {\n      restore?.();\n      restore = null;\n    }\n  };\n}\n\n/** Locks page scroll while `locked` is true. */\nexport function useScrollLock(locked: boolean, { fixed = false }: ScrollLockOptions = {}) {\n  useEffect(() => {\n    if (!locked) return;\n    return lockScroll({ fixed });\n  }, [locked, fixed]);\n}\n"},{"path":"lib/utils.ts","type":"util","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/focusable.ts","type":"util","content":"/**\n * Elements that can usually take keyboard focus. The selector cannot see\n * everything focus() checks (an element under `display: none`, say), so a\n * caller that needs certainty tries focus() and checks where it landed.\n */\nexport const FOCUSABLE_SELECTOR = [\n  \"a[href]\",\n  \"button:not(:disabled)\",\n  \"input:not(:disabled):not([type='hidden'])\",\n  \"select:not(:disabled)\",\n  \"textarea:not(:disabled)\",\n  \"[tabindex]:not([tabindex='-1'])\",\n].join(\",\");\n\n/** Elements inside `container` that Tab can reach, in DOM order. */\nexport function focusablesIn(container: Element | null | undefined) {\n  return Array.from(\n    container?.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR) ?? [],\n  ).filter((element) => element.tabIndex >= 0 && !element.closest(\"[inert]\"));\n}\n\n/** Focuses the first tabbable element in `panel`, or the panel itself. */\nexport function focusFirstIn(panel: HTMLElement | null | undefined) {\n  (focusablesIn(panel)[0] ?? panel)?.focus({ preventScroll: true });\n}\n\n/**\n * Keeps a Tab keypress inside `panel`, wrapping from the last tabbable element\n * to the first and back. Give the panel `tabIndex={-1}` so it can hold focus\n * when it has nothing tabbable.\n */\nexport function cycleTab(event: KeyboardEvent, panel: HTMLElement | null) {\n  if (event.key !== \"Tab\" || !panel) return;\n  const elements = focusablesIn(panel);\n  const first = elements[0];\n  const last = elements[elements.length - 1];\n  const active = document.activeElement;\n  if (!first || !last) {\n    event.preventDefault();\n    panel.focus({ preventScroll: true });\n  } else if (event.shiftKey && (active === first || active === panel)) {\n    event.preventDefault();\n    last.focus();\n  } else if (!event.shiftKey && active === last) {\n    event.preventDefault();\n    first.focus();\n  }\n}\n"},{"path":"lib/layers.ts","type":"util","content":"/**\n * Every open overlay on the page, innermost last: focus traps, modal scopes\n * and dismissable menus all register here. Overlays have no shared z-order to\n * consult, and a menu inside a drawer portals out of it, so this stack is how\n * they agree on who answers Escape and where focus may go.\n */\n\nexport interface Layer {\n  /** Whether `target` belongs to this layer (its panel, portals, trigger). */\n  contains: (target: Node) => boolean;\n  /** True for focus traps and modal scopes, which pull stray focus back. */\n  traps?: boolean;\n  /** False for a layer that ignores Escape, so the key reaches the one below. */\n  escape?: boolean;\n}\n\nconst stack: Layer[] = [];\n// The innermost layer when each Escape began, read before any handler runs,\n// so a layer that closes itself mid-event can't hand the key to the one below.\nconst escapeOwners = new WeakMap<Event, Layer | undefined>();\nlet listening = false;\n\nfunction innermostEscapeLayer() {\n  for (let index = stack.length - 1; index >= 0; index--) {\n    if (stack[index].escape !== false) return stack[index];\n  }\n  return undefined;\n}\n\nfunction recordEscapeOwner(event: KeyboardEvent) {\n  if (event.key === \"Escape\") escapeOwners.set(event, innermostEscapeLayer());\n}\n\n/** Registers an open layer. Call the returned function when it closes. */\nexport function openLayer(layer: Layer) {\n  if (!listening) {\n    document.addEventListener(\"keydown\", recordEscapeOwner, true);\n    listening = true;\n  }\n  stack.push(layer);\n  return () => {\n    const index = stack.indexOf(layer);\n    if (index !== -1) stack.splice(index, 1);\n  };\n}\n\n/** Whether this Escape is `layer`'s to answer: it was innermost when the key went down. */\nexport function ownsEscape(layer: Layer, event: KeyboardEvent) {\n  if (event.defaultPrevented) return false;\n  const owner = escapeOwners.has(event)\n    ? escapeOwners.get(event)\n    : innermostEscapeLayer();\n  return owner === layer;\n}\n\n/** Whether `target` sits in a layer opened on top of `layer`. */\nexport function inLayerAbove(layer: Layer, target: Node) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.contains(target));\n}\n\n/** Whether a focus trap is open on top of `layer`; stray focus is that one's to pull back. */\nexport function trapAbove(layer: Layer) {\n  const index = stack.indexOf(layer);\n  return stack.slice(index + 1).some((above) => above.traps);\n}\n\n/**\n * Whether `target` belongs to any open layer other than `layer`. Pass\n * `traps: false` to count only dismissable overlays, not the traps under them.\n */\nexport function inOtherLayer(layer: Layer, target: Node, { traps = true } = {}) {\n  return stack.some(\n    (other) => other !== layer && (traps || !other.traps) && other.contains(target),\n  );\n}\n"},{"path":"components/previews/blocks/command-palette.preview.tsx","type":"preview","content":"\"use client\";\n\nimport { FileText, Home, Plus, Settings, User } from \"lucide-react\";\nimport { useState } from \"react\";\nimport { CommandPalette } from \"@/components/motion/command-palette\";\n\nexport function CommandPalettePreview() {\n  const [open, setOpen] = useState(false);\n\n  return (\n    <div className=\"flex flex-col items-start gap-3\">\n      <button\n        type=\"button\"\n        onClick={() => setOpen(true)}\n        className=\"inline-flex h-10 items-center rounded-full border border-border bg-card px-5 text-sm font-medium text-foreground press hover:border-(--color-border-strong)\"\n      >\n        Open command palette\n      </button>\n      <p className=\"text-sm text-muted-foreground\">\n        Press{\" \"}\n        <kbd className=\"rounded border border-border bg-card px-1.5 py-0.5 text-xs text-foreground\">\n          ⌘ J\n        </kbd>{\" \"}\n        (or <kbd className=\"rounded border border-border bg-card px-1.5 py-0.5 text-xs text-foreground\">Ctrl J</kbd>) to open.\n      </p>\n      <CommandPalette\n        open={open}\n        onOpenChange={setOpen}\n        shortcut=\"j\"\n        recent\n        items={[\n          { id: \"home\", label: \"Go to Home\", group: \"Navigation\", icon: Home, hint: \"G H\", onSelect: () => {} },\n          { id: \"profile\", label: \"Open profile\", group: \"Navigation\", icon: User, hint: \"G P\", onSelect: () => {} },\n          { id: \"settings\", label: \"Settings\", group: \"Navigation\", icon: Settings, onSelect: () => {} },\n          { id: \"new-doc\", label: \"Create document\", group: \"Actions\", icon: FileText, hint: \"⌘ N\", onSelect: () => {} },\n          { id: \"new-project\", label: \"New project\", group: \"Actions\", icon: Plus, hint: \"⌘ ⇧ N\", onSelect: () => {} },\n        ]}\n      />\n    </div>\n  );\n}\n"}]}