Aadi

Command Palette

Component

About

A command palette for AI apps: recent chats, actions with shortcuts and models in one ranked search, with matched letters in bold, keyboard navigation and mod+k from anywhere. Results narrow as you type.

Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Command Palette to your project and fits it to your theme.

Code

How Command Palette is used: the demo's code. The component's own source comes with a free account.

Usage.tsx

"use client"

import * as React from "react"
import { CommandPalette, CommandPaletteGroup, CommandPaletteItem, Icon, IconNode, SearchIcon, createIcon } from "@/components/ui/command-palette"

/** How long a choice holds a tour before it carries on. */
const RESUME_MS = 1800

/** True until `RESUME_MS` after the last `hold()`, for tours with their own state. */
function useHold() {
  const [held, setHeld] = React.useState(false)
  const timer = React.useRef(0)
  React.useEffect(() => () => window.clearTimeout(timer.current), [])
  const hold = React.useCallback(() => {
    setHeld(true)
    window.clearTimeout(timer.current)
    timer.current = window.setTimeout(() => setHeld(false), RESUME_MS)
  }, [])
  return [held, hold] as const
}

const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches

/** Searches the tour types, each narrowing the list to something different. Empty shows the groups. */
const QUERIES = ["", "checkout", "dark", "model", "rate"]

const REST_MS = 1300

const TYPE_MS = 80

const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"

/**
 * 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
 * phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
 * render white on dark pages. FitFrame fills the frame exactly instead.
 *
 * - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
 * - "crop": the content stays at full size from the top and fades out at the bottom. For text
 *   that streams in, where a changing scale would make the page breathe.
 *
 * `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
 * to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
 * shrinks evenly on both sides.
 *
 * Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
 * shorter than `hideBelow`, so a profile card shows the visual alone.
 */
function FitFrame({
  children,
  mode = "scale",
  hideBelow = 360,
  minWidth,
}: {
  children: React.ReactNode
  mode?: "scale" | "crop"
  hideBelow?: number
  minWidth?: string
}) {
  const content = React.useRef<HTMLDivElement>(null)
  const [cropped, setCropped] = React.useState(false)

  React.useLayoutEffect(() => {
    const el = content.current
    if (!el) return
    const measure = () => {
      const vw = window.innerWidth
      const vh = window.innerHeight
      el.toggleAttribute("data-fit-small", vh < hideBelow)
      // Layout sizes ignore the transform, so measuring never feeds back.
      const w = Math.max(el.offsetWidth, el.scrollWidth)
      const h = Math.max(el.offsetHeight, el.scrollHeight)
      const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
      el.style.transform = scale < 1 ? `scale(${scale})` : ""
      setCropped(mode === "crop" && h > vh + 1)
    }
    measure()
    const observer = new ResizeObserver(measure)
    observer.observe(el)
    // Content that changes inside a fixed width box (a headline that cycles words) never resizes
    // the box itself, so changes below it measure again on the next frame.
    let frame = 0
    const mutations = new MutationObserver(() => {
      cancelAnimationFrame(frame)
      frame = requestAnimationFrame(measure)
    })
    mutations.observe(el, { subtree: true, childList: true, characterData: true })
    window.addEventListener("resize", measure)
    return () => {
      observer.disconnect()
      mutations.disconnect()
      cancelAnimationFrame(frame)
      window.removeEventListener("resize", measure)
    }
  }, [mode, hideBelow])

  const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
  return (
    <div
      className="flex w-full justify-center overflow-hidden"
      style={{
        height: "100dvh",
        alignItems: mode === "crop" ? "flex-start" : "center",
        maskImage: cropped ? fade : undefined,
        WebkitMaskImage: cropped ? fade : undefined,
      }}
    >
      <style>{FIT_CSS}</style>
      <div
        ref={content}
        className="w-full shrink-0"
        style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
      >
        {children}
      </div>
    </div>
  )
}

const chats = [
  ["Fix the slow runs page", "Today"],
  ["Why does checkout fail on CI only", "Today"],
  ["Add rate limiting to the public API", "Yesterday"],
  ["Migrate auth to database sessions", "Monday"],
  ["Compare vector databases for search", "Sep 28"],
  ["Draft the September incident review", "Sep 21"],
]

const iconNode: IconNode = [
  ["path", {"d":"M6 3.5h12a3 3 0 0 1 3 3V14a3 3 0 0 1-3 3H8.53a1.5 1.5 0 0 0-.94.33l-2.56 2.05A1.25 1.25 0 0 1 3 18.4V6.5a3 3 0 0 1 3-3"}],
]

const MessageSquareIcon: Icon = /* @__PURE__ */ createIcon("message-square", iconNode)

const iconNode2: IconNode = [
  ["path", {"d":"M5 12h14"}],
  ["path", {"d":"M12 5v14"}],
]

const PlusIcon: Icon = /* @__PURE__ */ createIcon("plus", iconNode2)

const iconNode3: IconNode = [
  ["path", {"d":"M6 3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3"}],
  ["path", {"d":"M9 6.25v11.5"}],
]

const PanelLeftIcon: Icon = /* @__PURE__ */ createIcon("panel-left", iconNode3)

const iconNode4: IconNode = [
  ["path", {"d":"M11.5 9h7a2.5 2.5 0 0 1 2.5 2.5v7a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 9 18.5v-7A2.5 2.5 0 0 1 11.5 9"}],
  ["path", {"d":"M6 15h-.5A2.5 2.5 0 0 1 3 12.5v-7A2.5 2.5 0 0 1 5.5 3h7A2.5 2.5 0 0 1 15 5.5V6"}],
]

const CopyIcon: Icon = /* @__PURE__ */ createIcon("copy", iconNode4)

const iconNode5: IconNode = [
  ["path", {"d":"M11.47 3.27a8.75 8.75 0 1 0 9.26 9.26 6.75 6.75 0 0 1-9.26-9.26"}],
]

const MoonIcon: Icon = /* @__PURE__ */ createIcon("moon", iconNode5)

const iconNode6: IconNode = [
  ["path", {"d":"M5.5 5h13a3 3 0 0 1 3 3v8a3 3 0 0 1-3 3h-13a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3"}],
  ["path", {"d":"M6.5 9.25h.01"}],
  ["path", {"d":"M6.5 12.25h.01"}],
  ["path", {"d":"M10.17 9.25h.01"}],
  ["path", {"d":"M10.17 12.25h.01"}],
  ["path", {"d":"M13.83 9.25h.01"}],
  ["path", {"d":"M13.83 12.25h.01"}],
  ["path", {"d":"M17.5 9.25h.01"}],
  ["path", {"d":"M17.5 12.25h.01"}],
  ["path", {"d":"M8 15.5h8"}],
]

const KeyboardIcon: Icon = /* @__PURE__ */ createIcon("keyboard", iconNode6)

const iconNode7: IconNode = [
  ["path", {"d":"m9.17 5.26.2-.98a1.5 1.5 0 0 1 1.47-1.21h2.32a1.5 1.5 0 0 1 1.47 1.21l.2.98a1.5 1.5 0 0 0 .72 1.01l-.37-.21a1.5 1.5 0 0 0 1.24.12l.95-.32a1.5 1.5 0 0 1 1.79.67l1.16 2.01a1.5 1.5 0 0 1-.31 1.88l-.76.66a1.5 1.5 0 0 0-.52 1.13v-.42a1.5 1.5 0 0 0 .52 1.13l.76.66a1.5 1.5 0 0 1 .31 1.88l-1.16 2.01a1.5 1.5 0 0 1-1.79.67l-.95-.32a1.5 1.5 0 0 0-1.24.12l.37-.21a1.5 1.5 0 0 0-.72 1.01l-.2.98a1.5 1.5 0 0 1-1.47 1.21h-2.32a1.5 1.5 0 0 1-1.47-1.21l-.2-.98a1.5 1.5 0 0 0-.72-1.01l.37.21a1.5 1.5 0 0 0-1.24-.12l-.95.32a1.5 1.5 0 0 1-1.79-.67l-1.16-2.01a1.5 1.5 0 0 1 .31-1.88l.76-.66a1.5 1.5 0 0 0 .52-1.13v.42a1.5 1.5 0 0 0-.52-1.13l-.76-.66a1.5 1.5 0 0 1-.31-1.88l1.16-2.01a1.5 1.5 0 0 1 1.79-.67l.95.32a1.5 1.5 0 0 0 1.24-.12l-.37.21a1.5 1.5 0 0 0 .72-1.01"}],
  ["path", {"d":"M9.25 12a2.75 2.75 0 1 0 5.5 0 2.75 2.75 0 1 0-5.5 0"}],
]

const SettingsIcon: Icon = /* @__PURE__ */ createIcon("settings", iconNode7)

/** Generic tiers, not real products. */
const models = [
  ["Large model", "Current"],
  ["Fast model", ""],
  ["Reasoning model", ""],
]

const iconNode8: IconNode = [
  ["path", {"d":"M6 3h12a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3"}],
  ["path", {"d":"m12.88 7.88 3.24 3.24a1.25 1.25 0 0 1 0 1.76l-3.24 3.24a1.25 1.25 0 0 1-1.76 0l-3.24-3.24a1.25 1.25 0 0 1 0-1.76l3.24-3.24a1.25 1.25 0 0 1 1.76 0"}],
]

const ModelIcon: Icon = /* @__PURE__ */ createIcon("model", iconNode8)

const ITEMS: CommandPaletteItem[] = [
  ...chats.map(([label, hint]) => ({
    id: `chat-${label}`,
    label: label as string,
    group: "chats",
    hint,
    icon: <MessageSquareIcon />,
  })),
  { id: "new", label: "New chat", group: "actions", icon: <PlusIcon />, shortcut: "mod+shift+o" },
  { id: "sidebar", label: "Toggle sidebar", group: "actions", icon: <PanelLeftIcon />, shortcut: "mod+b" },
  {
    id: "search",
    label: "Search messages…",
    group: "actions",
    icon: <SearchIcon />,
    shortcut: "mod+shift+f",
    keywords: "find full text",
  },
  { id: "copy", label: "Copy last response", group: "actions", icon: <CopyIcon />, shortcut: "mod+shift+c" },
  { id: "theme", label: "Switch to dark theme", group: "actions", icon: <MoonIcon />, keywords: "appearance mode" },
  { id: "shortcuts", label: "Show keyboard shortcuts", group: "actions", icon: <KeyboardIcon />, shortcut: "mod+/" },
  { id: "settings", label: "Open settings", group: "actions", icon: <SettingsIcon />, shortcut: "mod+comma", keywords: "preferences" },
  ...models.map(([label, hint]) => ({
    id: `model-${label}`,
    label: label as string,
    group: "models",
    hint: hint || undefined,
    icon: <ModelIcon />,
    keywords: "model switch",
  })),
]

const groups: CommandPaletteGroup[] = [
  { id: "chats", label: "Chats", emptyLimit: 3 },
  { id: "actions", label: "Actions", emptyLimit: 3 },
  { id: "models", label: "Models", emptyLimit: 2 },
]

/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
  return (
    <p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
      {children}{" "}
      <a
        href={`https://chatcn.dev/docs/components/${slug}`}
        target="_blank"
        rel="noopener"
        className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
      >
        chatcn.dev
      </a>
    </p>
  )
}

/**
 * The palette open in an AI chat app: it starts on recent chats, actions and models, then
 * searches type in and the ranked results narrow, from a chat about checkout to the theme switch
 * and the models. Loops. Type or pick a result and the tour waits for you.
 */
export default function CommandPalettePreview() {
  const [step, setStep] = React.useState({ query: 1, typed: 3 })
  const [held, hold] = useHold()
  const [mine, setMine] = React.useState("")
  const [container, setContainer] = React.useState<HTMLDivElement | null>(null)

  React.useEffect(() => {
    if (reducedMotion() || held) return
    const full = QUERIES[step.query]!
    const done = step.typed >= full.length
    const id = window.setTimeout(
      () =>
        setStep((s) =>
          done ? { query: (s.query + 1) % QUERIES.length, typed: 0 } : { query: s.query, typed: s.typed + 1 },
        ),
      done ? REST_MS : TYPE_MS,
    )
    return () => window.clearTimeout(id)
  }, [step, held])

  const query = held ? mine : QUERIES[step.query]!.slice(0, step.typed)

  return (
    <FitFrame minWidth="40rem">
      <div className="flex w-full flex-col items-center justify-center gap-4 p-6">
        <div ref={setContainer} className="relative h-[20.5rem] w-full max-w-xl [transform:translateZ(0)] [&_[data-slot=command-palette-backdrop]]:hidden">
          {container ? (
            <CommandPalette
              items={ITEMS}
              groups={groups}
              open
              onOpenChange={() => hold()}
              query={query}
              onQueryChange={(q) => {
                hold()
                setMine(q)
              }}
              onSelect={() => hold()}
              hotkey={null}
              apple
              container={container}
              // The preview is scaled, so the screen based offsets would not fit it.
              className="top-0 max-h-[20.5rem] w-full"
            />
          ) : null}
        </div>
        <MoreOn slug="command-palette">Chats, actions and models in one ranked search. On</MoreOn>
      </div>
    </FitFrame>
  )
}

Dependencies

More by Aadi

View all
  • Dither Orb

    Dither Orb

    12
  • Audio Visualizer

    Audio Visualizer

    9
  • Voice Orb

    Voice Orb

    8
  • Agent Lanes

    Agent Lanes

    6
  • Computer View

    Computer View

    3
  • Waveform

    Waveform

    2
  • Reasoning

    Reasoning

    2
  • Voice Session

    Voice Session

    1