# Command Palette
*URL: https://www.grettech.com/components/command-palette*

⌘K search over pages, docs and actions, with groups, keyboard navigation, highlighted matches and recent items. Opens as a dialog or sits inline.

- ⌘K / Ctrl+K hotkey and a search button trigger
- Full combobox keyboard support: arrows, Home/End, Enter
- Matches labels, descriptions and keywords, and highlights them
- Remembers recent items; dialog or inline variant

## Install with the shadcn CLI
```bash
npx shadcn@latest add https://www.grettech.com/api/registry/command-palette
```
With its demo: `npx shadcn@latest add https://www.grettech.com/api/registry/command-palette-demo`

**Dependencies:** npm: clsx, tailwind-merge, lucide-react; shadcn/ui: dialog

## Manual installation
**Step 1: Install dependencies**
Install the packages this component uses and the shadcn/ui components it builds on. It also needs the `cn` helper in `lib/utils.ts`, which `npx shadcn@latest init` adds.

```bash
npm install clsx tailwind-merge lucide-react
npx shadcn@latest add dialog
```

**Step 2: Copy the source code**
Add these files to your project components directory.

File: `components/ui/command-palette.tsx`
```tsx
"use client"

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogTitle,
} from "@/components/ui/dialog"
import { cn } from "@/lib/utils"
import { CornerDownLeft, Search } from "lucide-react"
import * as React from "react"

export interface CommandItem {
  id: string
  label: string
  description?: string
  icon?: React.ReactNode
  /** Extra words that should match, e.g. ["billing", "invoice"] */
  keywords?: string[]
  /** Keys shown on the right, e.g. ["⌘", "B"] */
  shortcut?: string[]
  /** Navigates here when chosen (through onNavigate) */
  href?: string
  onSelect?: () => void
}

export interface CommandGroup {
  heading: string
  items: CommandItem[]
}

export interface CommandPaletteProps {
  groups: CommandGroup[]
  /** "dialog" opens over the page; "inline" renders the panel in place */
  variant?: "dialog" | "inline"
  open?: boolean
  onOpenChange?: (open: boolean) => void
  /** Key that opens the dialog together with ⌘ or Ctrl. null disables it. */
  hotkey?: string | null
  /** Called for items with an href. Defaults to a full page navigation. */
  onNavigate?: (href: string) => void
  placeholder?: string
  emptyMessage?: string
  /** localStorage key for recent items. null turns recents off. */
  recentKey?: string | null
  /** Hides the built-in search button that opens the dialog */
  hideTrigger?: boolean
  triggerLabel?: string
  className?: string
}

const MAX_RECENT = 4

const RECENT_EVENT = "gridtic-command-recent"

function subscribeRecent(callback: () => void) {
  window.addEventListener("storage", callback)
  window.addEventListener(RECENT_EVENT, callback)
  return () => {
    window.removeEventListener("storage", callback)
    window.removeEventListener(RECENT_EVENT, callback)
  }
}

function readRaw(key: string | null) {
  if (!key) return "[]"
  try {
    return localStorage.getItem(key) ?? "[]"
  } catch {
    return "[]"
  }
}

function parseRecent(raw: string): string[] {
  try {
    const value = JSON.parse(raw)
    return Array.isArray(value) ? value : []
  } catch {
    return []
  }
}

/** Every word of the query must appear in the label, description or keywords */
function matches(item: CommandItem, words: string[]) {
  const haystack = [item.label, item.description, ...(item.keywords ?? [])]
    .join(" ")
    .toLowerCase()
  return words.every((w) => haystack.includes(w))
}

function Highlight({ text, words }: { text: string; words: string[] }) {
  if (words.length === 0) return <>{text}</>
  const pattern = new RegExp(
    `(${words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`,
    "gi"
  )
  return (
    <>
      {text.split(pattern).map((part, i) =>
        i % 2 === 1 ? (
          <mark
            key={i}
            className="rounded-sm bg-transparent text-foreground underline decoration-foreground/40 underline-offset-2"
          >
            {part}
          </mark>
        ) : (
          part
        )
      )}
    </>
  )
}

function Kbd({ children }: { children: React.ReactNode }) {
  return (
    <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded border bg-muted px-1 font-sans text-[10px] font-medium text-muted-foreground">
      {children}
    </kbd>
  )
}

function Panel({
  groups,
  onDone,
  onNavigate,
  placeholder,
  emptyMessage,
  recentKey,
  autoFocus,
}: {
  groups: CommandGroup[]
  onDone: () => void
  onNavigate: (href: string) => void
  placeholder: string
  emptyMessage: string
  recentKey: string | null
  autoFocus: boolean
}) {
  const id = React.useId()
  const [query, setQuery] = React.useState("")
  const [active, setActive] = React.useState(0)
  const listRef = React.useRef<HTMLDivElement>(null)

  // Read from localStorage after hydration; the server renders no recents
  const recentRaw = React.useSyncExternalStore(
    subscribeRecent,
    () => readRaw(recentKey),
    () => "[]"
  )
  const recent = React.useMemo(() => parseRecent(recentRaw), [recentRaw])

  const words = query.toLowerCase().split(/\s+/).filter(Boolean)
  const allItems = groups.flatMap((g) => g.items)
  const visibleGroups: CommandGroup[] = React.useMemo(() => {
    const filtered = groups
      .map((g) => ({ ...g, items: g.items.filter((it) => matches(it, words)) }))
      .filter((g) => g.items.length > 0)
    if (words.length > 0 || recent.length === 0) return filtered
    const recentItems = recent
      .map((rid) => allItems.find((it) => it.id === rid))
      .filter((it): it is CommandItem => Boolean(it))
    return recentItems.length > 0
      ? [{ heading: "Recent", items: recentItems }, ...filtered]
      : filtered
    // words is derived from query
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [groups, query, recent])

  const flat = visibleGroups.flatMap((g) => g.items)
  const current = Math.min(active, Math.max(flat.length - 1, 0))

  const choose = (item: CommandItem) => {
    if (recentKey) {
      const next = [item.id, ...recent.filter((r) => r !== item.id)].slice(
        0,
        MAX_RECENT
      )
      try {
        localStorage.setItem(recentKey, JSON.stringify(next))
        window.dispatchEvent(new Event(RECENT_EVENT))
      } catch {}
    }
    item.onSelect?.()
    if (item.href) onNavigate(item.href)
    onDone()
  }

  // Keep the active result visible by scrolling the list only.
  // scrollIntoView would also scroll the page to the palette, e.g. jumping
  // to an inline palette further down the page as soon as it mounts.
  React.useEffect(() => {
    const list = listRef.current
    const option = list?.querySelector<HTMLElement>(`[data-index="${current}"]`)
    if (!list || !option) return
    // The list is the options' offset parent (it's position: relative)
    const top = option.offsetTop
    const bottom = top + option.offsetHeight
    if (top < list.scrollTop) list.scrollTop = top
    else if (bottom > list.scrollTop + list.clientHeight)
      list.scrollTop = bottom - list.clientHeight
  }, [current])

  const onKeyDown = (e: React.KeyboardEvent) => {
    const last = flat.length - 1
    if (e.key === "ArrowDown") setActive(current >= last ? 0 : current + 1)
    else if (e.key === "ArrowUp") setActive(current <= 0 ? last : current - 1)
    else if (e.key === "Home") setActive(0)
    else if (e.key === "End") setActive(last)
    else if (e.key === "Enter" && flat[current]) choose(flat[current])
    else return
    e.preventDefault()
  }

  // Index of each group's first item in the flat list
  const starts: number[] = []
  let count = 0
  for (const group of visibleGroups) {
    starts.push(count)
    count += group.items.length
  }

  return (
    <div className="flex flex-col">
      <div className="flex items-center gap-2 border-b px-4">
        <Search
          aria-hidden="true"
          className="size-4 shrink-0 text-muted-foreground"
        />
        <input
          role="combobox"
          aria-expanded="true"
          aria-controls={`${id}-list`}
          aria-activedescendant={flat[current] ? `${id}-${current}` : undefined}
          aria-autocomplete="list"
          aria-label={placeholder}
          autoFocus={autoFocus}
          value={query}
          onChange={(e) => {
            setQuery(e.target.value)
            setActive(0)
          }}
          onKeyDown={onKeyDown}
          placeholder={placeholder}
          className="h-12 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
        />
      </div>
      <div
        ref={listRef}
        id={`${id}-list`}
        role="listbox"
        aria-label="Results"
        className="relative max-h-80 overflow-y-auto p-2"
      >
        {flat.length === 0 && (
          <p className="py-10 text-center text-sm text-muted-foreground">
            {emptyMessage}
          </p>
        )}
        {visibleGroups.map((group, g) => (
          <div
            key={`${group.heading}-${g}`}
            role="group"
            aria-label={group.heading}
          >
            <p className="px-2 pt-2 pb-1 text-[11px] font-medium text-muted-foreground">
              {group.heading}
            </p>
            {group.items.map((item, n) => {
              const i = starts[g] + n
              const selected = i === current
              return (
                <div
                  key={`${group.heading}-${item.id}-${n}`}
                  id={`${id}-${i}`}
                  role="option"
                  aria-selected={selected}
                  data-index={i}
                  onPointerMove={() => setActive(i)}
                  onClick={() => choose(item)}
                  className={cn(
                    "flex cursor-pointer items-center gap-3 rounded-lg px-2 py-2 text-sm",
                    selected && "bg-muted"
                  )}
                >
                  {item.icon && (
                    <span
                      aria-hidden="true"
                      className="flex size-7 shrink-0 items-center justify-center rounded-md border bg-background text-muted-foreground [&_svg]:size-4"
                    >
                      {item.icon}
                    </span>
                  )}
                  <span className="min-w-0 flex-1">
                    <span className="block truncate">
                      <Highlight text={item.label} words={words} />
                    </span>
                    {item.description && (
                      <span className="block truncate text-xs text-muted-foreground">
                        {item.description}
                      </span>
                    )}
                  </span>
                  {item.shortcut ? (
                    <span className="flex gap-1">
                      {item.shortcut.map((k) => (
                        <Kbd key={k}>{k}</Kbd>
                      ))}
                    </span>
                  ) : (
                    selected && (
                      <CornerDownLeft
                        aria-hidden="true"
                        className="size-3.5 text-muted-foreground"
                      />
                    )
                  )}
                </div>
              )
            })}
          </div>
        ))}
      </div>
      <div className="flex items-center gap-3 border-t px-4 py-2 text-[11px] text-muted-foreground">
        <span className="flex items-center gap-1">
          <Kbd>↑</Kbd>
          <Kbd>↓</Kbd> to move
        </span>
        <span className="flex items-center gap-1">
          <Kbd>↵</Kbd> to open
        </span>
      </div>
    </div>
  )
}

export function CommandPalette({
  groups,
  variant = "dialog",
  open: controlledOpen,
  onOpenChange,
  hotkey = "k",
  onNavigate = (href) => window.location.assign(href),
  placeholder = "Search pages and actions…",
  emptyMessage = "No results.",
  recentKey = "gridtic-command-recent",
  hideTrigger = false,
  triggerLabel = "Search…",
  className,
}: CommandPaletteProps) {
  const [internalOpen, setInternalOpen] = React.useState(false)
  const open = controlledOpen ?? internalOpen
  const setOpen = React.useCallback(
    (next: boolean) => {
      setInternalOpen(next)
      onOpenChange?.(next)
    },
    [onOpenChange]
  )

  React.useEffect(() => {
    if (variant !== "dialog" || !hotkey) return
    const onKey = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === hotkey) {
        e.preventDefault()
        setOpen(!open)
      }
    }
    window.addEventListener("keydown", onKey)
    return () => window.removeEventListener("keydown", onKey)
  }, [variant, hotkey, open, setOpen])

  const panelProps = {
    groups,
    onNavigate,
    placeholder,
    emptyMessage,
    recentKey,
  }

  if (variant === "inline") {
    return (
      <div
        className={cn(
          "w-full max-w-lg overflow-hidden rounded-xl border bg-popover text-popover-foreground shadow-sm",
          className
        )}
      >
        <Panel {...panelProps} onDone={() => {}} autoFocus={false} />
      </div>
    )
  }

  return (
    <>
      {!hideTrigger && (
        <button
          type="button"
          onClick={() => setOpen(true)}
          aria-haspopup="dialog"
          className={cn(
            "inline-flex h-9 w-full max-w-64 items-center gap-2 rounded-lg border bg-background px-3 text-sm text-muted-foreground shadow-xs transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
            className
          )}
        >
          <Search aria-hidden="true" className="size-4" />
          <span className="flex-1 text-left">{triggerLabel}</span>
          {hotkey && (
            <span className="flex gap-1" aria-hidden="true">
              <Kbd>⌘</Kbd>
              <Kbd>{hotkey.toUpperCase()}</Kbd>
            </span>
          )}
        </button>
      )}
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="top-[20%] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-lg">
          <DialogTitle className="sr-only">Command palette</DialogTitle>
          <DialogDescription className="sr-only">
            Search, then press Enter to open a result.
          </DialogDescription>
          {/* Remounts on open, so each search starts empty */}
          {open && (
            <Panel {...panelProps} onDone={() => setOpen(false)} autoFocus />
          )}
        </DialogContent>
      </Dialog>
    </>
  )
}

```

**Step 3: Framework Adjustments (Optional)**
If you are manually copying this code into a Vite or Remix project (without using the CLI), make sure to remove the `"use client";` directive from the very top of the file.

## Props
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| `groups` | `CommandGroup[]` | - | Yes | Results, grouped under headings. |
| `groups.heading` | `string` | - | Yes | Group heading. |
| `groups.items` | `CommandItem[]` | - | Yes | { id, label, description?, icon?, keywords?, shortcut?, href?, onSelect? }. Every word of the search must appear in the label, description or keywords. href navigates through onNavigate; onSelect runs first. |
| `groups.items.id` | `string` | - | Yes | - |
| `groups.items.label` | `string` | - | Yes | - |
| `groups.items.description` | `string` | - | No | - |
| `groups.items.icon` | `React.ReactNode` | - | No | - |
| `groups.items.keywords` | `string[]` | - | No | Extra words that should match, e.g. ["billing", "invoice"] |
| `groups.items.shortcut` | `string[]` | - | No | Keys shown on the right, e.g. ["⌘", "B"] |
| `groups.items.href` | `string` | - | No | Navigates here when chosen (through onNavigate) |
| `groups.items.onSelect` | `() => void` | - | No | - |
| `variant` | `"dialog" \| "inline"` | `"dialog"` | No | Opens over the page, or renders the panel in place (e.g. a docs search page). |
| `open` | `boolean` | - | No | Controlled open state of the dialog. |
| `onOpenChange` | `(open: boolean) => void` | - | No | Called when the dialog opens or closes. |
| `hotkey` | `string \| null` | `"k"` | No | Key that opens the dialog with ⌘ or Ctrl. null disables it. |
| `onNavigate` | `(href: string) => void` | `window.location.assign` | No | Called for items with an href, e.g. router.push. Defaults to a full page navigation. |
| `placeholder` | `string` | `"Search pages and actions…"` | No | Search placeholder, also the input's accessible name. |
| `emptyMessage` | `string` | `"No results."` | No | Shown when nothing matches. |
| `recentKey` | `string \| null` | `"gridtic-command-recent"` | No | localStorage key for recent items. null turns recents off. |
| `hideTrigger` | `boolean` | `false` | No | Hides the built-in search button; open it with the hotkey or open. |
| `triggerLabel` | `string` | `"Search…"` | No | Text in the search button. |
| `className` | `string` | - | No | Extra classes for the search button, or the panel when inline. |

## Usage
```tsx
"use client"

import {
  BookOpen,
  CreditCard,
  FileText,
  Home,
  LifeBuoy,
  Mail,
  Moon,
  Settings,
} from "lucide-react"
import { CommandPalette, type CommandGroup } from "@/components/ui/command-palette"

const GROUPS: CommandGroup[] = [
  {
    heading: "Pages",
    items: [
      { id: "home", label: "Home", icon: <Home />, href: "#home" },
      {
        id: "docs",
        label: "Documentation",
        description: "Guides and API reference",
        icon: <BookOpen />,
        keywords: ["guide", "api"],
        href: "#docs",
      },
      {
        id: "pricing",
        label: "Pricing",
        icon: <CreditCard />,
        keywords: ["plans", "billing"],
        href: "#pricing",
      },
      { id: "blog", label: "Blog", icon: <FileText />, href: "#blog" },
    ],
  },
  {
    heading: "Actions",
    items: [
      {
        id: "theme",
        label: "Toggle dark mode",
        icon: <Moon />,
        keywords: ["theme", "light"],
        shortcut: ["D"],
        onSelect: () => document.documentElement.classList.toggle("dark"),
      },
      {
        id: "contact",
        label: "Contact sales",
        icon: <Mail />,
        keywords: ["email", "talk"],
        href: "#contact",
      },
      {
        id: "support",
        label: "Get support",
        icon: <LifeBuoy />,
        href: "#support",
      },
      {
        id: "settings",
        label: "Settings",
        icon: <Settings />,
        href: "#settings",
      },
    ],
  },
]

export default function CommandPaletteDemo() {
  return (
    <div className="flex w-full flex-col items-center gap-6 p-4">
      <CommandPalette groups={GROUPS} />
      <CommandPalette
        groups={GROUPS}
        variant="inline"
        recentKey={null}
      />
    </div>
  )
}

```
