Command palette
Search and run anything from the keyboard.
Installation
Run the CLI
Run
pnpm dlx asta-ui@latest initonce, then this. The file lands incomponents/astabyte/, installsradix-ui@base-ui/reactand the colour tokens go into your CSS. This is the Radix build. Drop --radix for Base UI.This is the Base UI build, the default. Want Radix? Add --radix.$ pnpm dlx asta-ui@latest add command-palette --radixOr install the package
Don’t want the file? Import from
asta-uiasta-ui/baseand update withpnpm update asta-ui. Add the stylesheet once. More.$ pnpm add asta-ui radix-ui @base-ui/reactimport { CommandPalette } from "asta-ui";import { CommandPalette } from "asta-ui/base";Or copy it by hand
Install
radix-ui@base-ui/react, then copy this file. Keep the paths, or fix the@/imports. Then add the tokens fromglobals.css."use client"; import { Dialog as D } from "radix-ui"; import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); export interface Command { id: string; label: string; group: string; icon?: ReactNode; /** Shortcut hint shown on the right, e.g. "⌘N". */ shortcut?: string; /** Extra words that match as a plain substring, e.g. synonyms or a description. */ keywords?: string; onSelect?: () => void; } /** * Fuzzy match: every query letter must appear in order. Returns the matched indexes (for highlighting) * and a score that prefers consecutive letters and word starts, or null when it doesn't match. */ export function fuzzy(text: string, query: string): { score: number; hits: number[] } | null { const t = text.toLowerCase(); const q = query.toLowerCase().replace(/\s+/g, ""); if (!q) return { score: 0, hits: [] }; const hits: number[] = []; let score = 0; let from = 0; for (const ch of q) { const at = t.indexOf(ch, from); if (at < 0) return null; if (hits.length && at === hits[hits.length - 1] + 1) score += 3; if (at === 0 || t[at - 1] === " ") score += 2; score -= (at - from) * 0.1; hits.push(at); from = at + 1; } return { score, hits }; } function Highlight({ text, hits }: { text: string; hits: number[] }) { if (!hits.length) return <>{text}</>; const set = new Set(hits); return ( <> {[...text].map((c, i) => set.has(i) ? ( <mark key={i} className="bg-transparent font-semibold text-ink"> {c} </mark> ) : ( <span key={i}>{c}</span> ), )} </> ); } export interface CommandPaletteProps { open: boolean; onOpenChange: (open: boolean) => void; commands: Command[]; /** Order of groups; groups not listed follow in the order they appear. */ groups?: string[]; placeholder?: string; /** `contained` positions it inside the nearest relative parent instead of over the whole page. */ contained?: boolean; className?: string; } /** * A command palette: grouped results, fuzzy filtering with matched letters highlighted, arrow keys and Enter. * The modal part is Radix Dialog: focus is trapped, Escape or a click outside closes it, the page behind is * hidden from screen readers and stops scrolling, and focus returns to whatever opened it. */ export function CommandPalette({ open, onOpenChange, commands, groups, placeholder = "Type a command or search…", contained = false, className }: CommandPaletteProps) { const [q, setQ] = useState(""); const [at, setAt] = useState(0); const input = useRef<HTMLInputElement>(null); const list = useRef<HTMLDivElement>(null); const back = useRef<HTMLElement | null>(null); const listId = useId(); // Filtered, scored and grouped. Without a query, keep the given order. const sections = useMemo(() => { const scored = commands .map((c) => { const m = fuzzy(c.label, q) ?? (c.keywords && q.trim() && c.keywords.toLowerCase().includes(q.trim().toLowerCase()) ? { score: -5, hits: [] } : null); return m && { c, ...m }; }) .filter((x): x is { c: Command; score: number; hits: number[] } => !!x); if (q) scored.sort((a, b) => b.score - a.score); const order = [...(groups ?? []), ...commands.map((c) => c.group)].filter((g, i, a) => a.indexOf(g) === i); return order.map((g) => ({ group: g, items: scored.filter((s) => s.c.group === g) })).filter((s) => s.items.length); }, [commands, groups, q]); const flat = sections.flatMap((s) => s.items); const active = Math.min(at, Math.max(0, flat.length - 1)); useEffect(() => { list.current?.querySelector<HTMLElement>(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]); const close = () => onOpenChange(false); const run = (c?: Command) => { if (!c) return; c.onSelect?.(); close(); }; let n = -1; const pos = contained ? "absolute" : "fixed"; const overlay = ( <D.Overlay className={cx( pos, "inset-0 z-50 bg-[color-mix(in_srgb,var(--color-ink)_24%,transparent)] will-change-[opacity]", "data-[state=open]:animate-[kit-cmd-fade_.12s_ease-out_both] data-[state=closed]:animate-[kit-cmd-fade-out_.1s_ease-out_both] motion-reduce:!animate-none", contained && "rounded-[inherit]", )} /> ); const content = ( <D.Content aria-describedby={undefined} onOpenAutoFocus={(e) => { // Focus hasn't moved yet: remember the opener, start fresh, focus the search box. e.preventDefault(); back.current = document.activeElement as HTMLElement | null; setQ(""); setAt(0); input.current?.focus(); }} onCloseAutoFocus={(e) => { e.preventDefault(); back.current?.focus?.({ preventScroll: true }); }} className={cx( pos, "left-1/2 top-[10%] z-50 flex will-change-[opacity] max-h-[min(440px,calc(100%-2rem))] w-[calc(100%-1.5rem)] max-w-[560px] -translate-x-1/2 flex-col overflow-hidden rounded-xl bg-paper outline-none", "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_12%,transparent),0_24px_60px_-20px_rgb(0_0_0/0.4)]", // Opened from the keyboard many times a day, so it appears at once: a 120ms fade, no movement. "data-[state=open]:animate-[kit-cmd-fade_.12s_ease-out_both] data-[state=closed]:animate-[kit-cmd-fade-out_.1s_ease-out_both] motion-reduce:!animate-none", className, )} onKeyDown={(e) => { if (e.key === "ArrowDown") setAt((active + 1) % Math.max(1, flat.length)); else if (e.key === "ArrowUp") setAt((active - 1 + flat.length) % Math.max(1, flat.length)); else if (e.key === "Home") setAt(0); else if (e.key === "End") setAt(flat.length - 1); else if (e.key === "Enter") run(flat[active]?.c); else return; e.preventDefault(); e.stopPropagation(); }} > <D.Title className="sr-only">Command palette</D.Title> <style href="asta-command-palette" precedence="asta">{` @keyframes kit-cmd-fade { from { opacity: 0 } } @keyframes kit-cmd-fade-out { to { opacity: 0 } } `}</style> <div className="flex items-center gap-2.5 px-4 shadow-[inset_0_-1px_0_color-mix(in_srgb,var(--color-ink)_8%,transparent)]"> <svg viewBox="0 0 24 24" className="h-4 w-4 shrink-0 text-mute" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="10.5" cy="10.5" r="6" /> <path d="m15 15 5 5" strokeLinecap="round" /> </svg> <input ref={input} value={q} onChange={(e) => { setQ(e.target.value); setAt(0); }} placeholder={placeholder} aria-label="Search commands" name="q" autoComplete="off" spellCheck={false} enterKeyHint="go" role="combobox" aria-expanded="true" aria-controls={listId} aria-activedescendant={flat[active] ? `${listId}-${flat[active].c.id}` : undefined} aria-autocomplete="list" className="h-12 min-w-0 flex-1 bg-transparent text-[16px] text-ink outline-none placeholder:text-mute sm:text-[15px]" /> <kbd className="rounded-md bg-paper-2 px-1.5 font-sans text-[11px] leading-5 text-mute">Esc</kbd> </div> <div ref={list} id={listId} role="listbox" aria-label="Results" className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-1.5"> {sections.map((s) => ( <div key={s.group} role="group" aria-label={s.group} className="mb-1 last:mb-0"> <p className="px-2.5 pb-1 pt-2 text-[11.5px] font-medium text-mute">{s.group}</p> {s.items.map(({ c, hits }) => { n += 1; const i = n; const on = i === active; return ( <div key={c.id} id={`${listId}-${c.id}`} role="option" aria-selected={on} data-index={i} onPointerMove={() => at !== i && setAt(i)} onClick={() => run(c)} className={cx( "relative flex h-10 cursor-pointer items-center gap-3 rounded-[10px] px-2.5 text-[14px] transition-colors duration-150", on ? "bg-paper-2 text-ink" : "text-ink-2", )} > {on && <span aria-hidden className="absolute inset-y-2.5 left-0 w-0.5 rounded-full bg-brand" />} {c.icon && ( <span className={cx( "flex h-6 w-6 shrink-0 items-center justify-center rounded-md [&_svg]:h-3.5 [&_svg]:w-3.5", on ? "bg-paper text-ink" : "bg-paper-2 text-mute", )} > {c.icon} </span> )} <span className="min-w-0 flex-1 truncate"> <Highlight text={c.label} hits={hits} /> </span> {c.shortcut && <kbd className="font-sans text-[11.5px] text-mute">{c.shortcut}</kbd>} {on && ( <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 text-mute" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden > <path d="M19 5v6.5a2.5 2.5 0 0 1-2.5 2.5H5" /> <path d="m9 10-4 4 4 4" /> </svg> )} </div> ); })} </div> ))} {flat.length === 0 && ( <div className="flex flex-col items-center px-4 py-10 text-center" role="status"> <span className="flex h-10 w-10 items-center justify-center rounded-full bg-paper-2 text-mute"> <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="10.5" cy="10.5" r="6" /> <path d="m15 15 5 5" /> <path d="M8 10.5h5" /> </svg> </span> <p className="mt-3 text-[14px] text-ink">No results for “{q}”</p> <p className="mt-1 text-[13px] text-mute">Try a shorter word, or fewer letters.</p> </div> )} </div> <div className="flex items-center gap-4 px-4 py-2.5 text-[12px] text-mute shadow-[inset_0_1px_0_color-mix(in_srgb,var(--color-ink)_8%,transparent)]"> {[ ["↑↓", "Navigate"], ["↵", "Open"], ["Esc", "Close"], ].map(([k, l]) => ( <span key={l} className="flex items-center gap-1.5"> <kbd className="min-w-5 rounded-md bg-paper-2 px-1 text-center font-sans text-[11px] leading-5 text-ink-2">{k}</kbd> {l} </span> ))} <span className="ml-auto hidden tabular-nums sm:inline"> {flat.length} {flat.length === 1 ? "result" : "results"} </span> </div> </D.Content> ); return ( <D.Root open={open} onOpenChange={onOpenChange}> {contained ? ( <> {overlay} {content} </> ) : ( <D.Portal> {overlay} {content} </D.Portal> )} </D.Root> ); } export default CommandPalette;"use client"; import { Dialog as D } from "@base-ui/react/dialog"; import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" "); export interface Command { id: string; label: string; group: string; icon?: ReactNode; /** Shortcut hint shown on the right, e.g. "⌘N". */ shortcut?: string; /** Extra words that match as a plain substring, e.g. synonyms or a description. */ keywords?: string; onSelect?: () => void; } /** * Fuzzy match: every query letter must appear in order. Returns the matched indexes (for highlighting) * and a score that prefers consecutive letters and word starts, or null when it doesn't match. */ export function fuzzy(text: string, query: string): { score: number; hits: number[] } | null { const t = text.toLowerCase(); const q = query.toLowerCase().replace(/\s+/g, ""); if (!q) return { score: 0, hits: [] }; const hits: number[] = []; let score = 0; let from = 0; for (const ch of q) { const at = t.indexOf(ch, from); if (at < 0) return null; if (hits.length && at === hits[hits.length - 1] + 1) score += 3; if (at === 0 || t[at - 1] === " ") score += 2; score -= (at - from) * 0.1; hits.push(at); from = at + 1; } return { score, hits }; } function Highlight({ text, hits }: { text: string; hits: number[] }) { if (!hits.length) return <>{text}</>; const set = new Set(hits); return ( <> {[...text].map((c, i) => set.has(i) ? ( <mark key={i} className="bg-transparent font-semibold text-ink"> {c} </mark> ) : ( <span key={i}>{c}</span> ), )} </> ); } export interface CommandPaletteProps { open: boolean; onOpenChange: (open: boolean) => void; commands: Command[]; /** Order of groups; groups not listed follow in the order they appear. */ groups?: string[]; placeholder?: string; /** `contained` positions it inside the nearest relative parent instead of over the whole page. */ contained?: boolean; className?: string; } /** * A command palette: grouped results, fuzzy filtering with matched letters highlighted, arrow keys and Enter. * The modal part is Base UI Dialog: focus is trapped, Escape or a click outside closes it, the page behind is * hidden from screen readers and stops scrolling, and focus returns to whatever opened it. */ export function CommandPalette({ open, onOpenChange, commands, groups, placeholder = "Type a command or search…", contained = false, className }: CommandPaletteProps) { const [q, setQ] = useState(""); const [at, setAt] = useState(0); const input = useRef<HTMLInputElement>(null); const list = useRef<HTMLDivElement>(null); const back = useRef<HTMLElement | null>(null); const listId = useId(); const host = useRef<HTMLSpanElement>(null); // Filtered, scored and grouped. Without a query, keep the given order. const sections = useMemo(() => { const scored = commands .map((c) => { const m = fuzzy(c.label, q) ?? (c.keywords && q.trim() && c.keywords.toLowerCase().includes(q.trim().toLowerCase()) ? { score: -5, hits: [] } : null); return m && { c, ...m }; }) .filter((x): x is { c: Command; score: number; hits: number[] } => !!x); if (q) scored.sort((a, b) => b.score - a.score); const order = [...(groups ?? []), ...commands.map((c) => c.group)].filter((g, i, a) => a.indexOf(g) === i); return order.map((g) => ({ group: g, items: scored.filter((s) => s.c.group === g) })).filter((s) => s.items.length); }, [commands, groups, q]); const flat = sections.flatMap((s) => s.items); const active = Math.min(at, Math.max(0, flat.length - 1)); useEffect(() => { list.current?.querySelector<HTMLElement>(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); }, [active]); // Remember the opener before Base UI moves focus into the palette. useLayoutEffect(() => { if (open && !list.current?.contains(document.activeElement)) back.current = document.activeElement as HTMLElement | null; }, [open]); const close = () => onOpenChange(false); const run = (c?: Command) => { if (!c) return; c.onSelect?.(); close(); }; let n = -1; const pos = contained ? "absolute" : "fixed"; const overlay = ( <D.Backdrop className={cx( pos, "inset-0 z-50 bg-[color-mix(in_srgb,var(--color-ink)_24%,transparent)] will-change-[opacity]", "transition-opacity duration-[120ms] ease-out data-[starting-style]:opacity-0 data-[ending-style]:opacity-0 data-[ending-style]:duration-100 motion-reduce:!transition-none", contained && "rounded-[inherit]", )} /> ); const content = ( <D.Popup initialFocus={() => { // Runs as it opens: start fresh and focus the search box. setQ(""); setAt(0); return input.current ?? true; }} finalFocus={() => (back.current?.isConnected ? back.current : true)} className={cx( pos, "left-1/2 top-[10%] z-50 flex will-change-[opacity] max-h-[min(440px,calc(100%-2rem))] w-[calc(100%-1.5rem)] max-w-[560px] -translate-x-1/2 flex-col overflow-hidden rounded-xl bg-paper outline-none", "shadow-[inset_0_0_0_1px_color-mix(in_srgb,var(--color-ink)_12%,transparent),0_24px_60px_-20px_rgb(0_0_0/0.4)]", // Opened from the keyboard many times a day, so it appears at once: a 120ms fade, no movement. "transition-opacity duration-[120ms] ease-out data-[starting-style]:opacity-0", "data-[ending-style]:opacity-0 data-[ending-style]:duration-100 motion-reduce:!transition-none", className, )} onKeyDown={(e) => { if (e.key === "ArrowDown") setAt((active + 1) % Math.max(1, flat.length)); else if (e.key === "ArrowUp") setAt((active - 1 + flat.length) % Math.max(1, flat.length)); else if (e.key === "Home") setAt(0); else if (e.key === "End") setAt(flat.length - 1); else if (e.key === "Enter") run(flat[active]?.c); else return; e.preventDefault(); e.stopPropagation(); }} > <D.Title className="sr-only">Command palette</D.Title> <div className="flex items-center gap-2.5 px-4 shadow-[inset_0_-1px_0_color-mix(in_srgb,var(--color-ink)_8%,transparent)]"> <svg viewBox="0 0 24 24" className="h-4 w-4 shrink-0 text-mute" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="10.5" cy="10.5" r="6" /> <path d="m15 15 5 5" strokeLinecap="round" /> </svg> <input ref={input} value={q} onChange={(e) => { setQ(e.target.value); setAt(0); }} placeholder={placeholder} aria-label="Search commands" name="q" autoComplete="off" spellCheck={false} enterKeyHint="go" role="combobox" aria-expanded="true" aria-controls={listId} aria-activedescendant={flat[active] ? `${listId}-${flat[active].c.id}` : undefined} aria-autocomplete="list" className="h-12 min-w-0 flex-1 bg-transparent text-[16px] text-ink outline-none placeholder:text-mute sm:text-[15px]" /> <kbd className="rounded-md bg-paper-2 px-1.5 font-sans text-[11px] leading-5 text-mute">Esc</kbd> </div> <div ref={list} id={listId} role="listbox" aria-label="Results" className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-1.5"> {sections.map((s) => ( <div key={s.group} role="group" aria-label={s.group} className="mb-1 last:mb-0"> <p className="px-2.5 pb-1 pt-2 text-[11.5px] font-medium text-mute">{s.group}</p> {s.items.map(({ c, hits }) => { n += 1; const i = n; const on = i === active; return ( <div key={c.id} id={`${listId}-${c.id}`} role="option" aria-selected={on} data-index={i} onPointerMove={() => at !== i && setAt(i)} onClick={() => run(c)} className={cx( "relative flex h-10 cursor-pointer items-center gap-3 rounded-[10px] px-2.5 text-[14px] transition-colors duration-150", on ? "bg-paper-2 text-ink" : "text-ink-2", )} > {on && <span aria-hidden className="absolute inset-y-2.5 left-0 w-0.5 rounded-full bg-brand" />} {c.icon && ( <span className={cx( "flex h-6 w-6 shrink-0 items-center justify-center rounded-md [&_svg]:h-3.5 [&_svg]:w-3.5", on ? "bg-paper text-ink" : "bg-paper-2 text-mute", )} > {c.icon} </span> )} <span className="min-w-0 flex-1 truncate"> <Highlight text={c.label} hits={hits} /> </span> {c.shortcut && <kbd className="font-sans text-[11.5px] text-mute">{c.shortcut}</kbd>} {on && ( <svg viewBox="0 0 24 24" className="h-3.5 w-3.5 text-mute" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden > <path d="M19 5v6.5a2.5 2.5 0 0 1-2.5 2.5H5" /> <path d="m9 10-4 4 4 4" /> </svg> )} </div> ); })} </div> ))} {flat.length === 0 && ( <div className="flex flex-col items-center px-4 py-10 text-center" role="status"> <span className="flex h-10 w-10 items-center justify-center rounded-full bg-paper-2 text-mute"> <svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden> <circle cx="10.5" cy="10.5" r="6" /> <path d="m15 15 5 5" /> <path d="M8 10.5h5" /> </svg> </span> <p className="mt-3 text-[14px] text-ink">No results for “{q}”</p> <p className="mt-1 text-[13px] text-mute">Try a shorter word, or fewer letters.</p> </div> )} </div> <div className="flex items-center gap-4 px-4 py-2.5 text-[12px] text-mute shadow-[inset_0_1px_0_color-mix(in_srgb,var(--color-ink)_8%,transparent)]"> {[ ["↑↓", "Navigate"], ["↵", "Open"], ["Esc", "Close"], ].map(([k, l]) => ( <span key={l} className="flex items-center gap-1.5"> <kbd className="min-w-5 rounded-md bg-paper-2 px-1 text-center font-sans text-[11px] leading-5 text-ink-2">{k}</kbd> {l} </span> ))} <span className="ml-auto hidden tabular-nums sm:inline"> {flat.length} {flat.length === 1 ? "result" : "results"} </span> </div> </D.Popup> ); return ( <> {contained && <span ref={host} className="contents" />} <D.Root open={open} onOpenChange={(next) => onOpenChange(next)}> <D.Portal container={contained ? host : undefined}> {overlay} {content} </D.Portal> </D.Root> </> ); } export default CommandPalette;Or ask your AI agent
Paste this into Claude Code, Cursor, Codex, v0 or Lovable. Fill in the last line. More in Prompts.
Add the Astabyte UI Command palette component to my project. Search and run anything from the keyboard. It includes: ⌘J, groups, filter, keys. Install it (Radix build): ```sh pnpm dlx asta-ui@latest add command-palette --radix ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/command-palette.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init --radix` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { CommandPalette, type Command } from "@/components/astabyte/command-palette"; ``` Usage example and props: https://ui.astabyte.com/command-palette Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Radix primitives from the radix-ui package). - Stay on Radix: install other Astabyte UI components with `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Add the Astabyte UI Command palette component to my project. Search and run anything from the keyboard. It includes: ⌘J, groups, filter, keys. Install it (Base UI build): ```sh pnpm dlx asta-ui@latest add command-palette ``` Or with the shadcn CLI: ```sh pnpm dlx shadcn@latest add https://ui.astabyte.com/r/base/command-palette.json ``` If the project isn't set up yet, run `pnpm dlx asta-ui@latest init` first: it runs `shadcn init` when needed and adds the @astabyte registry (Next.js, Vite, React Router, Astro, TanStack Start; Tailwind CSS v4). Import it like this: ```tsx import { Button } from "@/components/astabyte/button"; import { CommandPalette, type Command } from "@/components/astabyte/command-palette"; ``` Usage example and props: https://ui.astabyte.com/command-palette Full catalogue for context: https://ui.astabyte.com/llms.txt Rules: - Keep the colour tokens (paper, paper-2, ink, ink-2, mute, brand). Don't restyle with hard-coded colours; rebrand by changing the token values in the CSS. - Keep the motion as it is: transform and opacity only, and the prefers-reduced-motion fallback. - Keep keyboard, focus and ARIA behaviour (interactive pieces are built on Base UI primitives from the @base-ui/react package). - Stay on Base UI: install other Astabyte UI components without `--radix` so the project uses one primitive library. - Use fake data and fake brand names in examples. Use it to: [describe where it goes and what it should do]Or use plain HTML + CSS
Not on React? Use it from Django, Rails, Laravel, Go
html/template, htmx or a static page. Loadasta.cssandasta.jsonce (thehead.htmltab), then paste the markup. Theui.astabyte.com/cdnlink is temporary: pin a version from jsDelivr for production. More in HTML + CSS.<!-- Needs asta.js: data-asta-open or Cmd/Ctrl+K opens it; filtering, highlighting, the result count and arrow keys are scripted. --> <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center"> <button class="asta-btn asta-btn-outline" data-asta-open="ex-cmd-one"><span class="asta-btn-label">Search <kbd class="asta-btn-kbd">⌘K</kbd></span></button> <dialog id="ex-cmd-one" class="asta-dialog asta-cmd" data-asta-command data-hotkey="k" aria-label="Command palette"> <div class="asta-cmd-inner"> <div class="asta-cmd-search"> <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3" stroke-linecap="round"/></svg> <input type="text" name="q" class="asta-cmd-input" data-asta-command-input autocomplete="off" spellcheck="false" placeholder="Type a command or search…" aria-label="Search commands" enterkeyhint="go" role="combobox" aria-expanded="true" aria-controls="ex-cmd-one-list" aria-autocomplete="list"> <kbd class="asta-cmd-esc">Esc</kbd> </div> <div class="asta-cmd-scroll" data-asta-command-scroll> <div id="ex-cmd-one-list" role="listbox" aria-label="Results" data-asta-command-list> <div role="group" aria-label="Pages" data-asta-command-group class="asta-cmd-group"> <p aria-hidden="true" class="asta-cmd-heading">Pages</p> <div data-asta-command-items> <a role="option" aria-selected="false" href="#command-palette" data-asta-command-item data-keywords="" class="asta-cmd-item"><span class="asta-cmd-item-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 7 8 2.5 13.5 7v6.5h-11z"/></svg></span><span class="asta-cmd-item-label" data-asta-command-label>Home</span><svg class="asta-cmd-item-enter" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 4v4.5a1.5 1.5 0 0 1-1.5 1.5H3.5M6 7l-2.5 3L6 13"/></svg></a> <div role="option" aria-selected="false" data-asta-command-item data-keywords="mail messages" class="asta-cmd-item"><span class="asta-cmd-item-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 9.5h3l1 1.5h3l1-1.5h3M2.5 9.5 4 3.5h8l1.5 6v3h-11z"/></svg></span><span class="asta-cmd-item-label" data-asta-command-label>Inbox</span><kbd class="asta-cmd-item-kbd">G I</kbd><svg class="asta-cmd-item-enter" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 4v4.5a1.5 1.5 0 0 1-1.5 1.5H3.5M6 7l-2.5 3L6 13"/></svg></div> <div role="option" aria-selected="false" data-asta-command-item data-keywords="analytics" class="asta-cmd-item"><span class="asta-cmd-item-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M3 13V8M8 13V3M13 13V6"/></svg></span><span class="asta-cmd-item-label" data-asta-command-label>Reports</span><svg class="asta-cmd-item-enter" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 4v4.5a1.5 1.5 0 0 1-1.5 1.5H3.5M6 7l-2.5 3L6 13"/></svg></div> </div> </div> <div role="group" aria-label="Actions" data-asta-command-group class="asta-cmd-group"> <p aria-hidden="true" class="asta-cmd-heading">Actions</p> <div data-asta-command-items> <div role="option" aria-selected="false" data-asta-command-item data-keywords="" class="asta-cmd-item"><span class="asta-cmd-item-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><path d="M8 3.5v9M3.5 8h9"/></svg></span><span class="asta-cmd-item-label" data-asta-command-label>New project</span><kbd class="asta-cmd-item-kbd">⌘N</kbd><svg class="asta-cmd-item-enter" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 4v4.5a1.5 1.5 0 0 1-1.5 1.5H3.5M6 7l-2.5 3L6 13"/></svg></div> <div role="option" aria-selected="false" data-asta-command-item data-keywords="" data-asta-open="ex-drawer-right" class="asta-cmd-item"><span class="asta-cmd-item-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M8 8a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5zM3 13.5c.8-2.3 2.7-3.5 5-3.5s4.2 1.2 5 3.5"/></svg></span><span class="asta-cmd-item-label" data-asta-command-label>Invite people</span><svg class="asta-cmd-item-enter" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 4v4.5a1.5 1.5 0 0 1-1.5 1.5H3.5M6 7l-2.5 3L6 13"/></svg></div> </div> </div> </div> <div data-asta-command-empty hidden role="status" class="asta-cmd-empty"> <span class="asta-cmd-empty-icon"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" aria-hidden="true"><circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3M5.5 7h3"/></svg></span> <p class="asta-cmd-empty-title">No results for “<span data-asta-command-q></span>”</p> <p class="asta-cmd-empty-hint">Try a shorter word, or fewer letters.</p> </div> </div> <div class="asta-cmd-footer"> <span class="asta-cmd-hint"><kbd>↑↓</kbd>Navigate</span> <span class="asta-cmd-hint"><kbd>↵</kbd>Open</span> <span class="asta-cmd-hint"><kbd>Esc</kbd>Close</span> <span class="asta-cmd-count" data-asta-command-count></span> </div> </div> </dialog> </div>
Usage
The demo above, as code.
"use client";
import { useEffect, useRef, useState } from "react";
import { Button } from "@/components/astabyte/button";
import { CommandPalette, type Command } from "@/components/astabyte/command-palette";
const icon = (d: string) => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d={d} />
</svg>
);
const DOC = "M6 3.5h8l4.5 4.5v12.5H6ZM14 3.5V8h4.5";
const CLOCK = "M3.5 12a8.5 8.5 0 1 0 17 0a8.5 8.5 0 1 0-17 0M12 7.5V12l3 2";
export default function CommandPaletteDemo() {
const [open, setOpen] = useState(false);
const [last, setLast] = useState("");
const root = useRef<HTMLDivElement>(null);
const inside = useRef(false);
// ⌘J / Ctrl+J opens it, but only while the pointer or focus is inside this demo.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
const here = inside.current || root.current?.contains(document.activeElement);
if (here && (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "j") {
e.preventDefault();
setOpen((v) => !v);
}
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
const go = (label: string) => () => setLast(label);
const commands: Command[] = [
{ id: "r1", group: "Recent", label: "Pricing page", icon: icon(CLOCK), onSelect: go("Pricing page") },
{ id: "r2", group: "Recent", label: "Invite teammates", icon: icon(CLOCK), onSelect: go("Invite teammates") },
{ id: "p1", group: "Pages", label: "Dashboard", icon: icon(DOC), shortcut: "G D", onSelect: go("Dashboard") },
{ id: "p2", group: "Pages", label: "Projects", icon: icon(DOC), shortcut: "G P", onSelect: go("Projects") },
{ id: "p3", group: "Pages", label: "Billing and invoices", icon: icon(DOC), keywords: "payment plan", onSelect: go("Billing and invoices") },
{ id: "p4", group: "Pages", label: "Team settings", icon: icon(DOC), keywords: "members", onSelect: go("Team settings") },
{ id: "a1", group: "Actions", label: "Create new project", icon: icon("M12 5v14M5 12h14"), shortcut: "⌘N", onSelect: go("Create new project") },
{ id: "a2", group: "Actions", label: "Copy current link", icon: icon("M10 14a4 4 0 0 0 5.66 0l3-3a4 4 0 0 0-5.66-5.66l-1 1M14 10a4 4 0 0 0-5.66 0l-3 3a4 4 0 0 0 5.66 5.66l1-1"), shortcut: "⌘⇧C", onSelect: go("Copy current link") },
{ id: "a3", group: "Actions", label: "Switch theme", icon: icon("M19.5 14.5A7.5 7.5 0 0 1 9.5 4.5a7.5 7.5 0 1 0 10 10Z"), keywords: "dark light mode", onSelect: go("Switch theme") },
{ id: "a4", group: "Actions", label: "Log out", icon: icon("M10 4.5H6A1.5 1.5 0 0 0 4.5 6v12A1.5 1.5 0 0 0 6 19.5h4M10 12h10M16 8l4 4-4 4"), onSelect: go("Log out") },
];
return (
<div
ref={root}
onPointerEnter={() => (inside.current = true)}
onPointerLeave={() => (inside.current = false)}
className="relative flex min-h-[420px] w-full flex-col items-center justify-center gap-4 overflow-hidden p-4 sm:p-8"
>
<Button
variant="outline"
kbd="⌘J"
onClick={() => setOpen(true)}
className="w-full max-w-[300px] !justify-between font-normal text-mute"
iconLeft={icon("M4.5 10.5a6 6 0 1 0 12 0a6 6 0 1 0-12 0M15 15l5 5")}
>
<span className="mr-auto">Search or run a command…</span>
</Button>
<p className="text-[13px] text-mute" aria-live="polite">
{last ? (
<>
Ran <span className="text-ink">{last}</span>
</>
) : (
"Click it, or hover here and press ⌘J."
)}
</p>
<CommandPalette open={open} onOpenChange={setOpen} commands={commands} groups={["Recent", "Pages", "Actions"]} contained />
</div>
);
}