Command palette
A search box over the page that finds and runs commands: open it, type a few letters, press Enter. It suits apps with more commands than fit in menus, and people who keep their hands on the keyboard. It adds to menus and buttons; it should not be the only way to reach a command.
Install
npx shadcn@latest add https://thrumui.dev/r/command-palette.jsonAdds components/ui/command-palette.tsx and installs @base-ui/react@1.9.0. Nothing else in your project changes.
import { commandScore } from "@/components/ui/command-palette";Automatically installs icon search from the icon set.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
CommandPalette: open | boolean | – | Whether the palette is open, when the parent holds the state. Use it with onOpenChange. |
CommandPalette: defaultOpen | boolean | Default false | Whether the palette starts open, when it holds its own state. |
CommandPalette: onOpenChange | (open: boolean) => void | – | Called when the palette opens or closes: by the shortcut, Escape, a press outside, or a picked command. |
CommandPalette: shortcut | string | – | One key that opens and closes the palette from anywhere on the page when pressed with Ctrl or ⌘, as in "k". Off unless set. |
CommandPalette: label | string | Default "Command palette" | The name of the dialog for screen readers. |
CommandPalette: sound | boolean | Default true | Play a soft sound when the palette opens or closes and a click when a command is picked, if the visitor has sound on. |
CommandPalette: className | string | – | Extra classes for the window. It is 512 pixels wide at most and keeps 16 pixels clear of the screen's sides. |
CommandInput: placeholder | string | Default "Type a command or search…" | The hint shown while the input is empty. |
CommandInput: aria-label | string | Default "Search commands" | The name of the input for screen readers. |
CommandList | div props | – | The scrolling list. It holds groups, items and separators, and hides itself when nothing matches. |
CommandGroup: heading | ReactNode | – | The name of the group, shown above its commands. A group with no matching command is hidden. |
CommandItem: children | ReactNode | Required | The label. Plain text is also what the command is found by. |
CommandItem: onSelect | () => void | – | Runs when the command is picked with Enter or a press. |
CommandItem: keywords | readonly string[] | – | Other words the command should be found by, as in ["preferences"] for Settings. |
CommandItem: icon | ReactNode | – | An icon before the label, drawn at 16 pixels. Decorative: hide it from screen readers. |
CommandItem: shortcut | string | – | Key hint text at the end of the row. The palette does not listen for the keys. |
CommandItem: label | string | – | The text the command is found by, when its children are more than plain text. |
CommandItem: closeOnSelect | boolean | Default true | Close the palette after the command has run. Set false for a setting that may be followed by another. |
CommandItem: disabled | boolean | Default false | Dimmed, skipped by the arrow keys, and it cannot be picked. |
CommandEmpty: children | ReactNode | Default "No commands found." | What the palette says when nothing matches. Put it between the input and the list. |
CommandSeparator | div props | – | A line between groups. It is left out while text is typed. |
commandScore(query, label, keywords?) | number | – | The matching rule on its own: 3 when the label starts with the text, 2 when a later word or a keyword starts with it, 1 when it appears anywhere, 0 for no match. |
rankCommands(query, commands) | T[] | – | The commands that match, best first, for a list you filter yourself. Each needs a label and may have keywords. |
Motion and sound
Motion
- The window fades in and grows from 96% to full size from its top edge over 150 ms, and the veil behind it fades in with it. Both leave the same way.
- The list changes at once as text is typed: nothing slides while someone is reading it.
- Reduced motion: the window and the veil appear and leave at once.
Sound
- A soft rising tone when the palette opens and a falling one when it closes without a pick.
- A click when a command is picked. The palette then closes without a second sound.
Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works
Accessibility
- The palette is a modal dialog with a name. Focus moves into the input when it opens, stays inside while it is open, and returns to where it was when it closes.
- The input is a combobox that controls a listbox of options. Focus stays in the input, and the highlighted command is reported through aria-activedescendant.
- Commands whose label starts with the typed text come first, then those where a later word or a keyword starts with it, then those that only contain it.
- When nothing matches, the message appears in a polite status region, so a screen reader hears it.
- Give every command another home as well: a menu, a button, a settings page. A palette is found by people who already know it exists.
- The window is a floating surface. Under a glass material it is translucent, and its tint keeps the text at 4.5 to 1 over any page.
| Keys | Action |
|---|---|
| Ctrl / ⌘ + key | Open the palette, or close it, when a shortcut is set. |
| A to Z | Filter the commands. The best match is highlighted. |
| ↓ / ↑ | Move the highlight to the next or previous command. Past the end it wraps. |
| Home / End | Move the highlight to the first or last command. |
| Enter | Run the highlighted command. |
| Esc | Close the palette. Focus returns to where it was. |
Source
"use client";
import { Children, createContext, isValidElement, useContext, useEffect, useRef, useState, type ComponentProps, type ReactNode } from "react";
import { Autocomplete as AutocompletePrimitive } from "@base-ui/react/autocomplete";
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog";
import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { MENU_ITEM, MENU_LABEL, MENU_SEPARATOR, MENU_SHORTCUT } from "@/components/ui/dropdown-menu";
import { SearchIcon } from "@/components/icons/search";
/**
* How well a command matches what was typed: 3 when its label starts with the text, 2 when a later word of the label or a
* keyword starts with it, 1 when the text appears anywhere in the label or a keyword, 0 when it does not match.
* Case is ignored. Empty text matches every command alike.
*/
export function commandScore(query: string, label: string, keywords: readonly string[] = []): number {
// Matches the query as one contiguous phrase rather than independent out-of-order terms.
const text = query.trim().toLowerCase();
if (!text) return 1;
const name = label.toLowerCase();
const extra = keywords.map((keyword) => keyword.toLowerCase());
if (name.startsWith(text)) return 3;
if ([...name.split(/[\s\-_/.]+/), ...extra].some((word) => word.startsWith(text))) return 2;
return name.includes(text) || extra.some((word) => word.includes(text)) ? 1 : 0;
}
/** The commands that match the typed text, best match first. Commands that match equally well keep the order they were given in. */
export function rankCommands<T extends { label: string; keywords?: readonly string[] }>(query: string, commands: readonly T[]): T[] {
return commands
.map((command) => ({ command, score: commandScore(query, command.label, command.keywords) }))
.filter((entry) => entry.score > 0)
.sort((a, b) => b.score - a.score)
.map((entry) => entry.command);
}
const PaletteContext = createContext<{ query: string; found: boolean; pick: (run: (() => void) | undefined, close: boolean) => void }>({ query: "", found: true, pick: () => {} });
/** Whether any `CommandItem` in the tree matches the text, looking through lists, groups and fragments. */
function anyMatch(children: ReactNode, query: string): boolean {
return Children.toArray(children).some((child) => {
if (!isValidElement<CommandItemProps>(child)) return false;
if (child.type === CommandItem) return commandScore(query, textOf(child.props), child.props.keywords) > 0;
return anyMatch(child.props.children, query);
});
}
/** The text a command is matched by: its `label`, or its children when they are plain text. */
function textOf(props: Pick<CommandItemProps, "label" | "children">) {
return props.label ?? (typeof props.children === "string" ? props.children : "");
}
/** While text is typed, the commands among `children` best match first, then whatever else was there. Untouched while the input is empty. */
function ranked(children: ReactNode, query: string): ReactNode {
if (!query.trim()) return children;
const all = Children.toArray(children);
const commands = all.flatMap((child) => (isValidElement<CommandItemProps>(child) && child.type === CommandItem ? [{ child, label: textOf(child.props), keywords: child.props.keywords }] : []));
if (commands.length === 0) return children;
return [...rankCommands(query, commands).map((command) => command.child), ...all.filter((child) => !(isValidElement(child) && child.type === CommandItem))];
}
export type CommandPaletteProps = {
/** Whether the palette is open, when the parent holds the state. Use it with `onOpenChange`. */
open?: boolean;
/** Whether the palette starts open, when it holds its own state. */
defaultOpen?: boolean;
/** Called when the palette opens or closes: by the shortcut, Escape, a press outside, or a picked command. */
onOpenChange?: (open: boolean) => void;
/** One key that opens and closes the palette from anywhere on the page when pressed with Ctrl or ⌘, as in `"k"`. Off unless set. */
shortcut?: string;
/** The name of the dialog for screen readers. */
label?: string;
/** Play a soft sound when the palette opens or closes and a click when a command is picked, if the visitor has sound on. */
sound?: boolean;
/** Extra classes for the window. */
className?: string;
/** `CommandInput`, `CommandEmpty` and `CommandList`. */
children?: ReactNode;
};
/**
* A search box over the page that finds and runs commands: type a few letters, press Enter. Open it from a button of your
* own through `open`, or give it a `shortcut`. It is a floating surface, so it turns to glass when the page's material asks for it.
*/
export function CommandPalette({ open, defaultOpen = false, onOpenChange, shortcut, label = "Command palette", sound = true, className, children }: CommandPaletteProps) {
const [inner, setInner] = useState(defaultOpen);
const isOpen = open ?? inner;
const was = useRef(isOpen);
const picked = useRef(false);
function change(next: boolean) {
setInner(next);
onOpenChange?.(next);
}
// The palette can be opened by the parent, the shortcut, or a key inside it, so the sound follows the state and not one of the handlers.
useEffect(() => {
if (was.current === isOpen) return;
was.current = isOpen;
// A picked command has made its own click; a closing tone on top would be one sound too many.
if (sound && !picked.current) play(isOpen ? "open" : "close");
picked.current = false;
}, [isOpen, sound]);
useEffect(() => {
if (!shortcut) return;
const key = shortcut.toLowerCase();
function onKey(event: KeyboardEvent) {
if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === key) {
event.preventDefault();
change(!isOpen);
}
}
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
});
return (
<DialogPrimitive.Root open={isOpen} onOpenChange={(next) => change(next)}>
<DialogPrimitive.Portal>
<DialogPrimitive.Backdrop
data-slot="command-palette-backdrop"
className="fixed inset-0 z-50 bg-background/70 transition-opacity duration-150 ease-out data-ending-style:opacity-0 data-starting-style:opacity-0 motion-reduce:transition-none"
/>
<DialogPrimitive.Popup
data-slot="command-palette"
data-surface="floating"
aria-label={label}
className={cn(
"fixed top-[12dvh] left-1/2 z-50 flex max-h-[min(26rem,76dvh)] w-[calc(100%-2rem)] max-w-lg origin-top -translate-x-1/2 flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg outline-none",
"transition-[opacity,scale] duration-150 ease-out data-ending-style:scale-[0.96] data-ending-style:opacity-0 data-starting-style:scale-[0.96] data-starting-style:opacity-0 motion-reduce:transition-none",
className,
)}
>
<PaletteBody
pick={(run, close) => {
if (sound) play("select");
run?.();
if (close) {
picked.current = true;
change(false);
}
}}
>
{children}
</PaletteBody>
</DialogPrimitive.Popup>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
);
}
/** Holds the typed text. It lives only while the palette is open, so every opening starts with an empty input. */
function PaletteBody({ pick, children }: { pick: (run: (() => void) | undefined, close: boolean) => void; children: ReactNode }) {
const [query, setQuery] = useState("");
return (
<PaletteContext.Provider value={{ query, found: anyMatch(children, query), pick }}>
<AutocompletePrimitive.Root
inline
open
autoHighlight="always"
keepHighlight
value={query}
onValueChange={(value, details) => {
// Picking a command must not write its name into the input.
if (details.reason !== "item-press") setQuery(value);
}}
>
{children}
</AutocompletePrimitive.Root>
</PaletteContext.Provider>
);
}
/** The search box at the top of the palette. It keeps the focus while the arrow keys move the highlight through the list. */
export function CommandInput({ className, placeholder = "Type a command or search…", "aria-label": ariaLabel = "Search commands", ...props }: AutocompletePrimitive.Input.Props) {
const { found } = useContext(PaletteContext);
// With nothing listed, the input must not point at a highlighted option that is gone.
const none = found ? {} : { "aria-activedescendant": undefined };
return (
<div data-slot="command-input-row" className="flex flex-none items-center gap-2 border-b px-4">
<SearchIcon size={16} className="flex-none text-muted-foreground" />
<AutocompletePrimitive.Input
data-slot="command-input"
aria-label={ariaLabel}
placeholder={placeholder}
{...none}
className={cn("h-10 w-full min-w-0 bg-transparent text-sm outline-none placeholder:text-muted-foreground", className)}
{...props}
/>
</div>
);
}
export type CommandListProps = Omit<AutocompletePrimitive.List.Props, "children"> & { children?: ReactNode };
/** The scrolling list of commands. It holds `CommandGroup`, `CommandItem` and `CommandSeparator` parts, and hides itself when nothing matches. */
export function CommandList({ className, children, ...props }: CommandListProps) {
const { query } = useContext(PaletteContext);
return (
<AutocompletePrimitive.List
data-slot="command-list"
className={cn("min-h-0 flex-1 scroll-py-2 overflow-y-auto overscroll-contain p-2 outline-none [&:not(:has([data-slot=command-item]))]:hidden", className)}
{...props}
>
{ranked(children, query)}
</AutocompletePrimitive.List>
);
}
export type CommandGroupProps = Omit<AutocompletePrimitive.Group.Props, "children"> & {
/** The name of the group, shown above its commands and read with them. */
heading?: ReactNode;
children?: ReactNode;
};
/** Commands under one heading. While text is typed its commands are ordered best match first, and a group with no match is hidden. */
export function CommandGroup({ heading, className, children, ...props }: CommandGroupProps) {
const { query } = useContext(PaletteContext);
return (
<AutocompletePrimitive.Group data-slot="command-group" className={cn("[&:not(:has([data-slot=command-item]))]:hidden", className)} {...props}>
{heading != null && (
<AutocompletePrimitive.GroupLabel data-slot="command-group-heading" className={MENU_LABEL}>
{heading}
</AutocompletePrimitive.GroupLabel>
)}
{ranked(children, query)}
</AutocompletePrimitive.Group>
);
}
export type CommandItemProps = Omit<AutocompletePrimitive.Item.Props, "value" | "onSelect"> & {
/** An icon before the label, 16 pixels. Decorative: hide it from screen readers. */
icon?: ReactNode;
/** Key hint text at the end of the row, as in `"Ctrl+N"`. The palette does not listen for the keys. */
shortcut?: string;
/** Other words the command should be found by, as in `["preferences", "options"]` for Settings. */
keywords?: readonly string[];
/** The text the command is found by, when its children are more than plain text. */
label?: string;
/** Runs when the command is picked with Enter or a press. */
onSelect?: () => void;
/** Close the palette after the command has run. Set false for commands that change a setting and may be followed by another. */
closeOnSelect?: boolean;
};
/** One command. It is shown while its label or one of its `keywords` matches the typed text. */
export function CommandItem({ icon, shortcut, keywords, label, onSelect, closeOnSelect = true, className, children, onClick, ...props }: CommandItemProps) {
const { query, pick } = useContext(PaletteContext);
const text = textOf({ label, children });
if (!commandScore(query, text, keywords)) return null;
return (
<AutocompletePrimitive.Item
data-slot="command-item"
value={text}
className={cn(MENU_ITEM, "scroll-my-2", className)}
onClick={(event) => {
onClick?.(event);
pick(onSelect, closeOnSelect);
}}
{...props}
>
{icon}
<span className="min-w-0 flex-1 truncate">{children}</span>
{shortcut && <span className={MENU_SHORTCUT}>{shortcut}</span>}
</AutocompletePrimitive.Item>
);
}
/** What the palette says when nothing matches. Put it between `CommandInput` and `CommandList`. Screen readers announce it politely. */
export function CommandEmpty({ className, children = "No commands found.", ...props }: ComponentProps<"div">) {
return (
// The status region is always there, so the message is announced when it appears inside it.
<div data-slot="command-empty" role="status" {...props}>
<div className={cn("hidden px-4 py-8 text-center text-sm text-muted-foreground [[data-slot=command-palette]:not(:has([data-slot=command-item]))_&]:block", className)}>{children}</div>
</div>
);
}
/** A line between groups. It is left out while text is typed, when the groups it divides may be gone. */
export function CommandSeparator({ className, ...props }: AutocompletePrimitive.Separator.Props) {
const { query } = useContext(PaletteContext);
if (query.trim()) return null;
return <AutocompletePrimitive.Separator data-slot="command-separator" className={cn(MENU_SEPARATOR, className)} {...props} />;
}Files and dependencies
- Adds
components/ui/command-palette.tsx- Packages
@base-ui/react@1.9.0- Brings along
- Sound engineDropdown menu
- Icons
search
Changelog
- 1.0.0 · 2026-12-03First release.