Command Palette.
A searchable list of commands that opens with ⌘K or Ctrl+K. It filters as you type, groups results, and runs the highlighted command on Enter.
Add className="my-command-palette" to your component.
Make a change to create your CSS.
Installation
In a project with React and shadcn configured, run:
npx shadcn@latest add https://aduneer.github.io/opalframe/r/command-palette.jsonCopies the component and its stylesheet into components/ui. No additional runtime dependencies. Tailwind classes work through className.
For manual installation, copy both files from Source below. Keep the CSS import alongside the component.
Usage
"use client";
import { useState } from "react";
import { CommandPalette } from "@/components/ui/command-palette";
export default function Example() {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>
Search <kbd>⌘K</kbd>
</button>
<CommandPalette
open={open}
onOpenChange={setOpen}
items={[
{ id: "home", label: "Go to Dashboard", group: "Navigate" },
{ id: "invoice", label: "New invoice", group: "Create", shortcut: ["N"] },
]}
onSelect={(item) => console.log(item.id)}
/>
</>
);
}Customize
Colors and sizes are scoped CSS variables. Override them on your own class.
<CommandPalette items={items} onSelect={run} className="your-palette" />
.your-palette {
--command-accent: #a6cfff;
--command-surface: #1e2530;
--command-active: #293449;
--command-line: #3f4f64;
--command-list-height: 400px;
}Props
| Prop | Type | What it does |
|---|---|---|
items | CommandItem[] | Unique id and label, plus optional group, keywords, shortcut, icon, and disabled flag. Search matches the label, group, and keywords. |
onSelect | (item: CommandItem) => void | Called with the chosen item. In dialog mode the palette then closes. |
mode | "dialog" | "inline" | dialog (the default) opens a native modal dialog. inline renders the panel in place and keeps it open. |
open / defaultOpen | boolean | Controlled or initial dialog state. |
onOpenChange | (open: boolean) => void | Called when the hotkey, Escape, a backdrop click, or a selection opens or closes the dialog. |
hotkey | string | false | Key pressed with Cmd or Ctrl to toggle the dialog. Defaults to k; false turns it off. |
query / defaultQuery | string | Controlled or initial search text. Use onQueryChange to follow it. |
label / placeholder / emptyMessage | string | Accessible name for the dialog and search field, the field's placeholder, and the text shown when nothing matches. |
className / reducedMotion | string / boolean | Customization of the panel, and turning off the opening animation in addition to the OS preference. |
Accessibility & motion
The search field is an ARIA combobox that controls a listbox. Arrow Up and Down move the highlighted option without leaving the field, Enter runs it, and the highlighted option is exposed through aria-activedescendant. The number of results is announced politely. In dialog mode, the native dialog element makes the rest of the page inert, closes on Escape or a backdrop click, and returns focus to where it was. Escape clears a search before it closes the dialog. Groups are labelled for screen readers; shortcut hints are visual only. Reduced motion removes the opening animation.
Dependencies
React only. Styles live in a plain CSS file next to the component, and Tailwind utilities work through className.
Source
command-palette.tsx
"use client";
import {
useEffect,
useId,
useRef,
useState,
type KeyboardEvent,
type ReactNode,
} from "react";
import "./command-palette.css";
export interface CommandItem {
id: string;
label: string;
/** Items with the same group render under one heading, in first-seen order. */
group?: string;
/** Extra words that match a search, such as synonyms. */
keywords?: string[];
/** Displayed next to the label. The palette doesn't bind these keys. */
shortcut?: string[];
icon?: ReactNode;
disabled?: boolean;
}
export interface CommandPaletteProps {
items: CommandItem[];
onSelect: (item: CommandItem) => void;
/** "dialog" opens over the page; "inline" renders in place and stays open. */
mode?: "dialog" | "inline";
open?: boolean;
defaultOpen?: boolean;
onOpenChange?: (open: boolean) => void;
/** Pressed with Cmd or Ctrl to toggle the dialog. false disables it. */
hotkey?: string | false;
query?: string;
defaultQuery?: string;
onQueryChange?: (query: string) => void;
placeholder?: string;
label?: string;
emptyMessage?: string;
className?: string;
reducedMotion?: boolean;
}
function matches(item: CommandItem, query: string) {
const text = [item.label, item.group, ...(item.keywords ?? [])]
.join(" ")
.toLowerCase();
return query
.toLowerCase()
.split(/\s+/)
.every((term) => text.includes(term));
}
function highlight(label: string, query: string) {
const term = query.trim().toLowerCase();
const start = term ? label.toLowerCase().indexOf(term) : -1;
if (start < 0) return label;
return (
<>
{label.slice(0, start)}
<mark>{label.slice(start, start + term.length)}</mark>
{label.slice(start + term.length)}
</>
);
}
/** A searchable command list built on the ARIA combobox pattern. */
export function CommandPalette({
items,
onSelect,
mode = "dialog",
open,
defaultOpen = false,
onOpenChange,
hotkey = "k",
query,
defaultQuery = "",
onQueryChange,
placeholder = "Type a command or search…",
label = "Command palette",
emptyMessage = "No matching commands.",
className = "",
reducedMotion = false,
}: CommandPaletteProps) {
const uid = useId();
const dialog = useRef<HTMLDialogElement>(null);
const input = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const [internalQuery, setInternalQuery] = useState(defaultQuery);
const [activeId, setActiveId] = useState<string>();
const isOpen = mode === "inline" || (open ?? internalOpen);
const search = query ?? internalQuery;
const results = search.trim()
? items.filter((item) => matches(item, search.trim()))
: items;
const enabled = results.filter((item) => !item.disabled);
const active = enabled.find((item) => item.id === activeId) ?? enabled[0];
const groups: { name: string; items: CommandItem[] }[] = [];
for (const item of results) {
const name = item.group ?? "";
const group = groups.find((entry) => entry.name === name);
if (group) group.items.push(item);
else groups.push({ name, items: [item] });
}
function setOpen(next: boolean) {
if (mode === "inline") return;
if (open === undefined) setInternalOpen(next);
onOpenChange?.(next);
if (!next) setSearch("");
}
function setSearch(next: string) {
if (query === undefined) setInternalQuery(next);
onQueryChange?.(next);
setActiveId(undefined);
}
function choose(item: CommandItem | undefined) {
if (!item || item.disabled) return;
onSelect(item);
setOpen(false);
}
// The latest values for the global hotkey without re-binding it each render.
const toggle = useRef(() => setOpen(!isOpen));
useEffect(() => {
toggle.current = () => setOpen(!isOpen);
});
useEffect(() => {
if (mode !== "dialog" || !hotkey) return;
const listener = (event: globalThis.KeyboardEvent) => {
if (
(event.metaKey || event.ctrlKey) &&
!event.altKey &&
event.key.toLowerCase() === hotkey.toLowerCase()
) {
event.preventDefault();
toggle.current();
}
};
window.addEventListener("keydown", listener);
return () => window.removeEventListener("keydown", listener);
}, [mode, hotkey]);
useEffect(() => {
const element = dialog.current;
if (mode !== "dialog" || !element) return;
if (isOpen && !element.open) {
element.showModal();
input.current?.focus();
} else if (!isOpen && element.open) element.close();
}, [mode, isOpen]);
const activeOption = active?.id;
useEffect(() => {
const container = list.current;
const option = activeOption
? document.getElementById(`${uid}-option-${activeOption}`)
: null;
if (!container || !option) return;
// Scroll only the list; scrollIntoView could also move the page.
const top = option.offsetTop - container.offsetTop;
const bottom = top + option.offsetHeight;
if (top < container.scrollTop) container.scrollTop = top - 6;
else if (bottom > container.scrollTop + container.clientHeight)
container.scrollTop = bottom - container.clientHeight + 6;
}, [activeOption, uid]);
function navigate(event: KeyboardEvent<HTMLInputElement>) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
if (!enabled.length) return;
const index = active ? enabled.indexOf(active) : -1;
const step = event.key === "ArrowDown" ? 1 : -1;
setActiveId(enabled[(index + step + enabled.length) % enabled.length].id);
} else if (event.key === "Enter") {
event.preventDefault();
choose(active);
} else if (event.key === "Escape" && search) {
// Clear the search first; a second Escape closes the dialog.
event.preventDefault();
event.stopPropagation();
setSearch("");
}
}
const panel = (
<div
className={`is-command ${className}`}
data-mode={mode}
data-reduced-motion={reducedMotion || undefined}
>
<div className="is-command-search">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="11" cy="11" r="6.5" />
<path d="m16 16 4 4" />
</svg>
<input
ref={input}
role="combobox"
aria-label={label}
aria-expanded={isOpen}
aria-controls={`${uid}-list`}
aria-autocomplete="list"
aria-activedescendant={
active ? `${uid}-option-${active.id}` : undefined
}
autoComplete="off"
spellCheck={false}
placeholder={placeholder}
value={search}
onChange={(event) => setSearch(event.target.value)}
onKeyDown={navigate}
/>
{mode === "dialog" && (
<kbd className="is-command-escape" aria-hidden="true">
Esc
</kbd>
)}
</div>
<div
className="is-command-list"
id={`${uid}-list`}
role="listbox"
aria-label={`${label} results`}
ref={list}
>
{groups.map((group, groupIndex) => {
const options = group.items.map((item) => (
<div
key={item.id}
id={`${uid}-option-${item.id}`}
className="is-command-option"
role="option"
aria-selected={item.id === active?.id}
aria-disabled={item.disabled || undefined}
onPointerMove={() => {
if (!item.disabled && item.id !== active?.id)
setActiveId(item.id);
}}
onPointerDown={(event) => event.preventDefault()}
onClick={() => choose(item)}
>
{item.icon && (
<span className="is-command-icon" aria-hidden="true">
{item.icon}
</span>
)}
<span className="is-command-label">
{highlight(item.label, search)}
</span>
{item.shortcut && (
<span className="is-command-shortcut" aria-hidden="true">
{item.shortcut.map((key) => (
<kbd key={key}>{key}</kbd>
))}
</span>
)}
</div>
));
if (!group.name) return options;
const heading = `${uid}-group-${groupIndex}`;
return (
<div
key={group.name}
className="is-command-section"
role="presentation"
>
<div className="is-command-heading" id={heading} aria-hidden>
{group.name}
</div>
<div role="group" aria-labelledby={heading}>
{options}
</div>
</div>
);
})}
</div>
{!results.length && <p className="is-command-empty">{emptyMessage}</p>}
<div className="is-command-footer" aria-hidden="true">
<span>
<kbd>↑</kbd>
<kbd>↓</kbd> to move
</span>
<span>
<kbd>↵</kbd> to select
</span>
{mode === "dialog" && (
<span>
<kbd>Esc</kbd> to close
</span>
)}
</div>
<p className="is-command-sr" role="status">
{isOpen
? results.length
? `${results.length} ${results.length === 1 ? "command" : "commands"}`
: emptyMessage
: ""}
</p>
</div>
);
if (mode === "inline") return panel;
return (
<dialog
ref={dialog}
className="is-command-dialog"
aria-label={label}
data-reduced-motion={reducedMotion || undefined}
onCancel={(event) => {
event.preventDefault();
setOpen(false);
}}
onClick={(event) => {
// The dialog element itself is only hit outside the panel, on the backdrop.
if (event.target === event.currentTarget) setOpen(false);
}}
>
{panel}
</dialog>
);
}
command-palette.css
.is-command {
--command-surface: var(--surface, #181d25);
--command-text: var(--text, #f0f3f8);
--command-muted: var(--muted, #adb7c6);
--command-line: var(--line, #343d4a);
--command-active: var(--raised, #242a33);
--command-accent: var(--accent, #b2cfff);
--command-list-height: 320px;
box-sizing: border-box;
width: 100%;
max-width: 640px;
overflow: hidden;
border: 1px solid var(--command-line);
border-radius: 14px;
background: var(--command-surface);
color: var(--command-text);
box-shadow:
0 2px 4px #00000010,
0 28px 60px -28px #00000070;
font-size: 14px;
}
.is-command *,
.is-command *::before,
.is-command *::after {
box-sizing: border-box;
}
.is-command kbd {
display: inline-grid;
place-items: center;
min-width: 20px;
height: 20px;
padding: 0 5px;
border: 1px solid var(--command-line);
border-radius: 5px;
color: var(--command-muted);
background: color-mix(in srgb, var(--command-text) 4%, transparent);
font:
10px ui-monospace,
monospace;
}
.is-command-search {
display: flex;
align-items: center;
gap: 10px;
padding: 0 16px;
border-bottom: 1px solid var(--command-line);
}
.is-command-search > svg {
flex: 0 0 18px;
width: 18px;
height: 18px;
fill: none;
stroke: var(--command-muted);
stroke-width: 1.7;
stroke-linecap: round;
}
.is-command-search input {
flex: 1;
min-width: 0;
height: 54px;
border: 0;
outline: 0;
background: transparent;
color: var(--command-text);
font: inherit;
font-size: 15px;
}
.is-command-search input::placeholder {
color: var(--command-muted);
}
.is-command:has(input:focus-visible) {
border-color: color-mix(in srgb, var(--command-accent) 60%, transparent);
}
.is-command-list {
position: relative;
max-height: var(--command-list-height);
overflow-y: auto;
overscroll-behavior: contain;
padding: 6px;
}
.is-command-list:empty {
display: none;
}
.is-command-section + .is-command-section,
.is-command-option + .is-command-section {
margin-top: 6px;
}
.is-command-heading {
padding: 10px 10px 6px;
color: var(--command-muted);
font:
10px ui-monospace,
monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.is-command-option {
display: flex;
align-items: center;
gap: 12px;
min-height: 42px;
padding: 0 10px;
border-radius: 9px;
color: var(--command-muted);
cursor: pointer;
user-select: none;
-webkit-tap-highlight-color: transparent;
transition:
background 120ms,
color 120ms;
}
.is-command-option[aria-selected="true"] {
background: var(--command-active);
color: var(--command-text);
box-shadow: inset 2px 0 0 var(--command-accent);
}
.is-command-option[aria-disabled="true"] {
opacity: 0.45;
cursor: not-allowed;
}
.is-command-icon {
display: grid;
place-items: center;
flex: 0 0 18px;
width: 18px;
height: 18px;
}
.is-command-icon > svg {
width: 17px;
height: 17px;
}
.is-command-label {
flex: 1;
min-width: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.is-command-label mark {
background: none;
color: var(--command-accent);
font-weight: 600;
}
.is-command-shortcut {
display: flex;
gap: 4px;
}
.is-command-empty {
margin: 0;
padding: 36px 16px;
color: var(--command-muted);
text-align: center;
}
.is-command-footer {
display: flex;
flex-wrap: wrap;
gap: 6px 16px;
padding: 10px 16px;
border-top: 1px solid var(--command-line);
color: var(--command-muted);
font-size: 11px;
}
.is-command-footer > span {
display: inline-flex;
align-items: center;
gap: 4px;
}
.is-command-footer kbd {
margin-right: 2px;
}
.is-command-sr {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
overflow: hidden;
clip-path: inset(50%);
white-space: nowrap;
}
.is-command-dialog {
position: fixed;
inset: 12vh 0 auto;
width: min(640px, calc(100vw - 32px));
max-height: 76vh;
margin: 0 auto;
padding: 0;
border: 0;
background: transparent;
overflow: visible;
}
.is-command-dialog::backdrop {
background: #0b0d12a8;
backdrop-filter: blur(3px);
}
.is-command-dialog .is-command {
max-width: none;
}
.is-command-dialog[open] .is-command {
animation: is-command-in 180ms cubic-bezier(0.22, 1, 0.36, 1);
}
.is-command-dialog[open]::backdrop {
animation: is-command-fade 180ms ease-out;
}
@keyframes is-command-in {
from {
opacity: 0;
transform: translateY(-8px) scale(0.98);
}
}
@keyframes is-command-fade {
from {
opacity: 0;
}
}
.is-command[data-reduced-motion] .is-command-option,
.is-command-dialog[data-reduced-motion][open] .is-command,
.is-command-dialog[data-reduced-motion][open]::backdrop {
transition: none;
animation: none;
}
@media (prefers-reduced-motion: reduce) {
.is-command .is-command-option,
.is-command-dialog[open] .is-command,
.is-command-dialog[open]::backdrop {
transition: none;
animation: none;
}
}
@media (max-width: 480px) {
.is-command-dialog {
inset-block-start: 16px;
}
.is-command-shortcut {
display: none;
}
}