{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "command-palette",
  "type": "registry:ui",
  "title": "Command Palette",
  "description": "A keyboard-first ⌘K palette with grouped actions, drill-down pages, recent items, and directional motion, built on cmdk inside a self-contained dialog shell.",
  "author": "Aditya Ojha <https://akoder.xyz>",
  "categories": [
    "navigation",
    "search",
    "dialog",
    "keyboard"
  ],
  "dependencies": [
    "cmdk",
    "lucide-react",
    "motion",
    "radix-ui"
  ],
  "registryDependencies": [
    "kbd"
  ],
  "meta": {
    "docs": "https://akoder.xyz/components/command-palette",
    "source": "https://github.com/AdityaKodez/adityaojha/blob/main/components/ui/command-palette.tsx"
  },
  "files": [
    {
      "path": "components/ui/command-palette.tsx",
      "content": "\"use client\";\n\nimport { Command as CommandPrimitive } from \"cmdk\";\nimport { ArrowLeft, ArrowUp, ChevronRight, CornerDownLeft, Search, X, ArrowDown } from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { Dialog as DialogPrimitive } from \"radix-ui\";\nimport { Kbd } from \"./kbd\";\nimport React, {\n  useCallback,\n  useEffect,\n  useMemo,\n  useRef,\n  useState,\n} from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\n/* -------------------------------------------------------------------------- */\n/*  Types                                                                     */\n/* -------------------------------------------------------------------------- */\n\nexport interface CommandPaletteItem {\n  /** Unique id — also the key used to persist recents. */\n  id: string;\n  /** Row label. Search matches this plus `keywords`. */\n  label: string;\n  /** Optional leading icon (a sized lucide element works well). */\n  icon?: React.ReactNode;\n  /** Right-aligned display-only shortcut hint, e.g. \"⌘D\". */\n  shortcut?: string;\n  /** Small right-aligned tag, e.g. \"new\" or \"external\". */\n  badge?: string;\n  /** Extra search terms beyond the label. */\n  keywords?: string[];\n  /** Id of a page (from `pages`) to drill into instead of running an action. */\n  page?: string;\n  /** Called when the item is picked. The palette closes after non-page items. */\n  onSelect?: () => void;\n}\n\nexport interface CommandPaletteGroup {\n  label: string;\n  items: CommandPaletteItem[];\n}\n\nexport interface CommandPalettePage {\n  /** Referenced by `CommandPaletteItem.page`. */\n  id: string;\n  /** Shown as the group heading while the page is open. */\n  label: string;\n  /** Overrides the search placeholder while the page is open. */\n  placeholder?: string;\n  items: CommandPaletteItem[];\n}\n\nexport interface CommandPaletteProps {\n  /** Top-level groups, rendered in order when no page is open. */\n  groups?: CommandPaletteGroup[];\n  /** Drill-down pages reachable from items with a matching `page` id. */\n  pages?: CommandPalettePage[];\n  /** Controlled open state. Omit to let the palette manage itself. */\n  open?: boolean;\n  onOpenChange?: (open: boolean) => void;\n  /** Global hotkey key combined with ⌘/Ctrl. `false` disables the listener. */\n  hotkey?: string | false;\n  placeholder?: string;\n  emptyLabel?: string;\n  /** Remember recently picked items (localStorage) and offer them on top. */\n  recents?: boolean;\n  storageKey?: string;\n  maxRecents?: number;\n  /** Prevent the palette from opening on small viewports (< 640px). */\n  disableOnMobile?: boolean;\n  className?: string;\n}\n\n/* -------------------------------------------------------------------------- */\n/*  Constants + helpers                                                       */\n/* -------------------------------------------------------------------------- */\n\nconst EASE: [number, number, number, number] = [0.22, 1, 0.36, 1];\n\nconst DEFAULT_PLACEHOLDER = \"Type a command or search…\";\nconst DEFAULT_EMPTY = \"No matching commands\";\nconst DEFAULT_STORAGE_KEY = \"command-palette:recents\";\n\nfunction readRecents(storageKey: string, max: number): string[] {\n  if (typeof window === \"undefined\") return [];\n  try {\n    const raw = window.localStorage.getItem(storageKey);\n    if (!raw) return [];\n    const parsed: unknown = JSON.parse(raw);\n    if (!Array.isArray(parsed)) return [];\n    return parsed\n      .filter((entry): entry is string => typeof entry === \"string\")\n      .slice(0, max);\n  } catch {\n    return [];\n  }\n}\n\nfunction writeRecents(storageKey: string, ids: string[]) {\n  try {\n    window.localStorage.setItem(storageKey, JSON.stringify(ids));\n  } catch {\n    // Ignore localStorage access issues\n  }\n}\n\n/** Shared kbd chip style for the static hints (esc key, footer legend). */\nconst kbdClass =\n  \"inline-flex h-5 min-w-5 items-center justify-center rounded-sm bg-popover px-1 font-sans text-[11px] font-medium text-muted-foreground\";\n\n/** Group heading typography — one source for the root list and drill pages. */\nconst groupHeadingClass =\n  \"[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:pt-2 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground\";\n\n/* -------------------------------------------------------------------------- */\n/*  Row                                                                       */\n/* -------------------------------------------------------------------------- */\n\nconst PaletteRow = React.memo(function PaletteRow({\n  item,\n  scope,\n  onRun,\n}: {\n  item: CommandPaletteItem;\n  scope: string;\n  onRun: (item: CommandPaletteItem) => void;\n}) {\n  return (\n    <CommandPrimitive.Item\n      value={`${scope}:${item.id}`}\n      keywords={[item.label, ...(item.keywords ?? [])]}\n      onSelect={() => onRun(item)}\n      className=\"group/row flex h-9 cursor-pointer select-none items-center gap-2.5 rounded-md px-2.5 text-sm outline-none transition-colors data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground\"\n    >\n      {item.icon && (\n        <span className=\"flex size-4 shrink-0 items-center justify-center opacity-70 [&_svg]:size-4\">\n          {item.icon}\n        </span>\n      )}\n      <span className=\"flex-1 truncate\">{item.label}</span>\n      {item.badge && (\n        <span className=\"shrink-0 rounded-sm bg-muted px-1.5 py-0.5 font-sans text-[11px] text-muted-foreground\">\n          {item.badge}\n        </span>\n      )}\n      {item.shortcut && (\n        <Kbd>{item.shortcut}</Kbd>\n      )}\n      {item.page && (\n        <ChevronRight\n          aria-hidden\n          className=\"size-3.5 shrink-0 text-muted-foreground opacity-0 transition-opacity group-data-[selected=true]/row:opacity-100\"\n        />\n      )}\n    </CommandPrimitive.Item>\n  );\n});\n\n/* -------------------------------------------------------------------------- */\n/*  Command palette                                                           */\n/* -------------------------------------------------------------------------- */\n\nexport function CommandPalette({\n  groups = [],\n  pages = [],\n  open: openProp,\n  onOpenChange,\n  hotkey = \"k\",\n  placeholder = DEFAULT_PLACEHOLDER,\n  emptyLabel = DEFAULT_EMPTY,\n  recents = false,\n  storageKey = DEFAULT_STORAGE_KEY,\n  maxRecents = 3,\n  disableOnMobile = false,\n  className,\n}: CommandPaletteProps) {\n  const prefersReducedMotion = useReducedMotion();\n\n  /* -- small-viewport gate (disableOnMobile) ------------------------------- */\n  const [isMobile, setIsMobile] = useState(false);\n  const isMobileRef = useRef(false);\n\n  useEffect(() => {\n    const mql = window.matchMedia(\"(max-width: 639px)\");\n    const update = () => {\n      isMobileRef.current = mql.matches;\n      setIsMobile(mql.matches);\n    };\n    update();\n    mql.addEventListener(\"change\", update);\n    return () => mql.removeEventListener(\"change\", update);\n  }, []);\n\n  /* -- open state (controlled or internal) -------------------------------- */\n  const [internalOpen, setInternalOpen] = useState(false);\n  const isControlled = openProp !== undefined;\n  const openRef = useRef(false);\n  const open = isControlled ? openProp : internalOpen;\n\n  useEffect(() => {\n    openRef.current = open;\n  }, [open]);\n\n  const setOpen = useCallback(\n    (next: boolean) => {\n      if (next && disableOnMobile && isMobileRef.current) return;\n      if (!isControlled) setInternalOpen(next);\n      onOpenChange?.(next);\n    },\n    [isControlled, onOpenChange, disableOnMobile],\n  );\n\n  const toggleOpen = useCallback(() => {\n    setOpen(!openRef.current);\n  }, [setOpen]);\n\n  /* -- page stack + search ------------------------------------------------ */\n  const [stack, setStack] = useState<string[]>([]);\n  const [query, setQuery] = useState<string>(\"\");\n  const dirRef = useRef<1 | -1>(1);\n  /** true = the next list mount appears instantly (open), false = it slides (page change). */\n  const skipListAnimRef = useRef(true);\n  const inputRef = useRef<HTMLInputElement | null>(null);\n  const listRef = useRef<HTMLDivElement | null>(null);\n\n  const pagesById = useMemo(() => {\n    const map = new Map<string, CommandPalettePage>();\n    for (const page of pages) map.set(page.id, page);\n    return map;\n  }, [pages]);\n\n  const currentPage = stack.length\n    ? pagesById.get(stack[stack.length - 1])\n    : undefined;\n  const commandKey = currentPage?.id ?? \"root\";\n\n  /** Every terminal item, for resolving recents. */\n  const itemsById = useMemo(() => {\n    const map = new Map<string, CommandPaletteItem>();\n    for (const group of groups) {\n      for (const item of group.items) {\n        if (!item.page) map.set(item.id, item);\n      }\n    }\n    for (const page of pages) {\n      for (const item of page.items) {\n        if (!item.page) map.set(item.id, item);\n      }\n    }\n    return map;\n  }, [groups, pages]);\n\n  /* -- recents ------------------------------------------------------------ */\n  const [recentIds, setRecentIds] = useState<string[]>([]);\n\n  const recordRecent = useCallback(\n    (id: string) => {\n      if (!recents) return;\n      setRecentIds((prev) => {\n        const next = [id, ...prev.filter((entry) => entry !== id)].slice(\n          0,\n          Math.max(1, maxRecents),\n        );\n        writeRecents(storageKey, next);\n        return next;\n      });\n    },\n    [recents, maxRecents, storageKey],\n  );\n\n  /* -- global hotkey (⌘K / Ctrl+K) ---------------------------------------- */\n  useEffect(() => {\n    if (!hotkey) return;\n    const key = typeof hotkey === \"string\" ? hotkey.toLowerCase() : \"\";\n    if (!key) return;\n    const onKeyDown = (event: KeyboardEvent) => {\n      if (event.repeat) return;\n      if (\n        event.key.toLowerCase() === key &&\n        (event.metaKey || event.ctrlKey)\n      ) {\n        event.preventDefault();\n        toggleOpen();\n      }\n    };\n    window.addEventListener(\"keydown\", onKeyDown);\n    return () => window.removeEventListener(\"keydown\", onKeyDown);\n  }, [hotkey, toggleOpen]);\n\n  /* -- reset the stack + refresh recents on every open --------------------- */\n  useEffect(() => {\n    if (!open) return;\n    dirRef.current = 1;\n    setStack([]);\n    setQuery(\"\");\n    if (recents) setRecentIds(readRecents(storageKey, maxRecents));\n  }, [open, recents, storageKey, maxRecents]);\n\n  /* -- keep focus in the input across page changes ------------------------- */\n  useEffect(() => {\n    inputRef.current?.focus({ preventScroll: true });\n  }, [commandKey]);\n\n  /* -- re-arm the list slide after page changes ---------------------------- */\n  useEffect(() => {\n    skipListAnimRef.current = true;\n  }, [commandKey]);\n\n  /* -- keep the active row visible while arrowing through long lists ------- */\n  const handleActiveChange = useCallback(() => {\n    requestAnimationFrame(() => {\n      const list = listRef.current;\n      if (!list) return;\n      const selected = list.querySelector<HTMLElement>(\n        '[cmdk-item][data-selected=\"true\"]',\n      );\n      if (!selected) return;\n\n      const listRect = list.getBoundingClientRect();\n      const itemRect = selected.getBoundingClientRect();\n\n      if (itemRect.bottom > listRect.bottom) {\n        list.scrollTop += itemRect.bottom - listRect.bottom + 4;\n      } else if (itemRect.top < listRect.top) {\n        list.scrollTop -= listRect.top - itemRect.top + 4;\n      }\n    });\n  }, []);\n\n  /* -- item selection ------------------------------------------------------ */\n  const goBack = useCallback(() => {\n    dirRef.current = -1;\n    skipListAnimRef.current = false;\n    setStack((prev) => prev.slice(0, -1));\n    setQuery(\"\");\n  }, []);\n\n  const runItem = useCallback(\n    (item: CommandPaletteItem) => {\n      if (item.page && pagesById.has(item.page)) {\n        dirRef.current = 1;\n        skipListAnimRef.current = false;\n        setStack((prev) => [...prev, item.page as string]);\n        setQuery(\"\");\n        return;\n      }\n      item.onSelect?.();\n      recordRecent(item.id);\n      setOpen(false);\n    },\n    [pagesById, recordRecent, setOpen],\n  );\n\n  /* -- filtering: multi-token substring match over label + keywords --------- */\n  const filter = useCallback(\n    (value: string, search: string, keywords?: string[]) => {\n      const cleanSearch = search.trim().toLowerCase();\n      if (!cleanSearch) return 1;\n      const tokens = cleanSearch.split(/\\s+/);\n      const haystack = (keywords ?? []).join(\" \").toLowerCase();\n      return tokens.every((token) => haystack.includes(token)) ? 1 : 0;\n    },\n    [],\n  );\n\n  const showRecents =\n    recents && !currentPage && query.trim() === \"\" && recentIds.length > 0;\n  const recentItems = showRecents\n    ? recentIds\n        .map((id) => itemsById.get(id))\n        .filter((item): item is CommandPaletteItem => item !== undefined)\n    : [];\n\n  const topGroups = currentPage\n    ? [\n        {\n          label: currentPage.label,\n          items: currentPage.items,\n        },\n      ]\n    : groups;\n\n  const rowScope = currentPage ? `page:${currentPage.id}` : \"root\";\n  const mobileBlocked = disableOnMobile && isMobile;\n\n  return (\n    <DialogPrimitive.Root open={open} onOpenChange={setOpen}>\n      <AnimatePresence>\n        {open && !mobileBlocked && (\n          <DialogPrimitive.Portal forceMount>\n            <DialogPrimitive.Overlay forceMount asChild>\n              <motion.div\n                initial={{ opacity: 0 }}\n                animate={{ opacity: 1 }}\n                exit={{ opacity: 0 }}\n                transition={{\n                  duration: prefersReducedMotion ? 0 : 0.12,\n                  ease: EASE,\n                }}\n                // Fallback for the non-modal case, where Radix leaves the\n                // positioner's `pointer-events: none` intact and backdrop\n                // clicks reach the overlay instead of the positioner.\n                onClick={() => setOpen(false)}\n                className=\"fixed inset-0 z-50 bg-black/10 supports-backdrop-filter:backdrop-blur-xs\"\n              />\n            </DialogPrimitive.Overlay>\n\n            <DialogPrimitive.Content\n              forceMount\n              asChild\n              onPointerDownOutside={() => setOpen(false)}\n              onEscapeKeyDown={(event) => {\n                // first escape clears the search, second backs out of page, third closes\n                if (query) {\n                  event.preventDefault();\n                  setQuery(\"\");\n                } else if (currentPage) {\n                  event.preventDefault();\n                  goBack();\n                }\n              }}\n            >\n              {/* full-viewport positioner — centers the panel. This node *is*\n                  Radix's Content, and for a modal dialog DismissableLayer sets\n                  an inline `pointer-events: auto` on it, which overrides the\n                  `pointer-events-none` class below. So backdrop presses land\n                  here (not on the overlay) and count as \"inside\" Content, which\n                  is why onPointerDownOutside never fires. Close when the press\n                  hits the positioner itself rather than the panel. */}\n              <div\n                onPointerDown={(event) => {\n                  if (event.target === event.currentTarget) setOpen(false);\n                }}\n                className=\"pointer-events-none fixed inset-0 z-50 grid place-items-center p-4 max-sm:place-items-end max-sm:p-0\"\n              >\n              <motion.div\n                initial={{ opacity: 0, scale: 0.98, y: 4 }}\n                animate={{ opacity: 1, scale: 1, y: 0 }}\n                exit={{ opacity: 0, scale: 0.98, y: 2 }}\n                transition={{\n                  duration: prefersReducedMotion ? 0 : 0.15,\n                  ease: EASE,\n                }}\n                className={cn(\n                  \"pointer-events-auto flex max-h-[min(56vh,432px)] w-full max-w-[27.5rem] flex-col overflow-hidden rounded-xl bg-muted text-foreground shadow-xl ring-1 ring-inset ring-border\",\n                  \"max-sm:rounded-b-none max-sm:rounded-t-xl\",\n                  className,\n                )}\n              >\n                <DialogPrimitive.Title className=\"sr-only\">\n                  Command palette\n                </DialogPrimitive.Title>\n                <DialogPrimitive.Description className=\"sr-only\">\n                  Search actions and navigate\n                </DialogPrimitive.Description>\n\n                {/* the command root is the flex column the height cap flows\n                    through — without it the list never constrains and the\n                    footer gets clipped instead of the list scrolling */}\n                <CommandPrimitive\n                  key={commandKey}\n                  loop\n                  filter={filter}\n                  onValueChange={handleActiveChange}\n                  className=\"flex min-h-0 flex-col\"\n                >\n                {/* header — part of the muted container, no rule */}\n                <div className=\"flex shrink-0 items-center gap-2 px-3.5\">\n                  {currentPage ? (\n                    <button\n                      type=\"button\"\n                      onClick={goBack}\n                      aria-label=\"Back to all commands\"\n                      className=\"-ml-1.5 flex size-7 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\"\n                    >\n                      <ArrowLeft className=\"size-4\" />\n                    </button>\n                  ) : (\n                    <Search\n                      aria-hidden\n                      className=\"size-4 shrink-0 text-muted-foreground/60\"\n                    />\n                  )}\n                  <CommandPrimitive.Input\n                    ref={inputRef}\n                    value={query}\n                    onValueChange={setQuery}\n                    onKeyDown={(event) => {\n                      if (event.key === \"Backspace\" && !query && currentPage) {\n                        event.preventDefault();\n                        goBack();\n                      }\n                    }}\n                    placeholder={currentPage?.placeholder ?? placeholder}\n                    className=\"h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground/60\"\n                  />\n                  {query ? (\n                    <button\n                      type=\"button\"\n                      onClick={() => setQuery(\"\")}\n                      aria-label=\"Clear search\"\n                      className=\"-mr-1 flex size-6 shrink-0 items-center justify-center rounded-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\"\n                    >\n                      <X className=\"size-3.5\" />\n                    </button>\n                  ) : (\n                    <span\n                      aria-hidden\n                      className={cn(kbdClass, \"shrink-0 text-[10px]\")}\n                    >\n                      Esc\n                    </span>\n                  )}\n                </div>\n\n                {/* list — an inset card so the content reads apart from the chrome;\n                    the panel caps its height and this list scrolls, scrollbar hidden\n                    (inline scrollbar-width beats the site's unlayered `*` rule) */}\n                <CommandPrimitive.List\n                  ref={listRef}\n                  style={{ scrollbarWidth: \"none\" }}\n                  className=\"mx-1.5 mb-1.5 mt-1 min-h-0 flex-initial overflow-y-auto overscroll-contain rounded-lg bg-card p-1.5 ring-1 ring-inset ring-border [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\"\n                >\n                  <motion.div\n                    key={commandKey}\n                    initial={\n                      // eslint-disable-next-line react-hooks/refs\n                      skipListAnimRef.current\n                        ? false\n                        : // eslint-disable-next-line react-hooks/refs\n                          { opacity: 0, x: 6 * dirRef.current }\n                    }\n                    animate={{ opacity: 1, x: 0 }}\n                    transition={{\n                      duration: prefersReducedMotion ? 0 : 0.16,\n                      ease: EASE,\n                    }}\n                  >\n                    {recentItems.length > 0 && (\n                      <CommandPrimitive.Group\n                        heading=\"Recent\"\n                        className={groupHeadingClass}\n                      >\n                        {recentItems.map((item) => (\n                          <PaletteRow\n                            key={`recent:${item.id}`}\n                            item={item}\n                            scope=\"recent\"\n                            onRun={runItem}\n                          />\n                        ))}\n                      </CommandPrimitive.Group>\n                    )}\n\n                    {topGroups.map((group, groupIndex) => (\n                      <CommandPrimitive.Group\n                        key={`${rowScope}:${group.label}:${groupIndex}`}\n                        heading={group.label}\n                        className={groupHeadingClass}\n                      >\n                        {group.items.map((item) => (\n                          <PaletteRow\n                            key={item.id}\n                            item={item}\n                            scope={rowScope}\n                            onRun={runItem}\n                          />\n                        ))}\n                      </CommandPrimitive.Group>\n                    ))}\n\n                    <CommandPrimitive.Empty className=\"py-8 text-center text-sm text-muted-foreground\">\n                      {query.trim() ? (\n                        <>\n                          No results for{\" \"}\n                          <span className=\"font-medium text-foreground\">“{query.trim()}”</span>\n                        </>\n                      ) : (\n                        emptyLabel\n                      )}\n                    </CommandPrimitive.Empty>\n                  </motion.div>\n                </CommandPrimitive.List>\n\n                {/* footer — part of the muted container, no rule */}\n                <div className=\"flex shrink-0 items-center gap-4 px-3.5 py-2.5 text-xs text-muted-foreground\">\n                  <span className=\"flex items-center gap-1.5\">\n                    <span className={cn(kbdClass, \"h-4 px-1 [&_svg]:size-2.5\")}>\n                      <ArrowUp aria-hidden />\n                    </span>\n                    <span className={cn(kbdClass, \"h-4 px-1 [&_svg]:size-2.5\")}>\n                      <ArrowDown aria-hidden />\n                    </span>\n                    Navigate\n                  </span>\n                  <span className=\"flex items-center gap-1.5\">\n                    <span className={cn(kbdClass, \"h-4 px-1 [&_svg]:size-2.5\")}>\n                      <CornerDownLeft aria-hidden />\n                    </span>\n                    Select\n                  </span>\n                  <span className=\"ml-auto flex items-center gap-1.5\">\n                    <span className={cn(kbdClass, \"h-4 px-1 text-[10px]\")}>\n                      Esc\n                    </span>\n                    Close\n                  </span>\n                </div>\n                </CommandPrimitive>\n              </motion.div>\n              </div>\n            </DialogPrimitive.Content>\n          </DialogPrimitive.Portal>\n        \n        )}\n      </AnimatePresence>\n    </DialogPrimitive.Root>\n  );\n}\n",
      "type": "registry:ui"
    }
  ],
  "docs": "## Installation\n\n```bash\nnpx shadcn@latest add @akoder/command-palette\n```\n\n## Usage\n\n```tsx\nimport { CommandPalette } from \"@/components/ui/command-palette\";\n\nexport function AppShell() {\n  const [open, setOpen] = useState(false);\n\n  return (\n    <>\n      <button onClick={() => setOpen(true)}>open palette</button>\n      <CommandPalette open={open} onOpenChange={setOpen} recents />\n    </>\n  );\n}\n```\n\nPass `groups` for top-level actions, `pages` plus `page` ids on items for drill-down navigation, and ⌘K / Ctrl+K toggles the palette by default. Recents persist per `storageKey` when `recents` is on."
}