Command
The shadcn/ui Command menu (cmdk) with a result list that eases its height as you type, a clear selected row and keycap shortcuts — plus an animated React ⌘K command palette block built with Motion, with a gliding highlight, recent items and nested pages.
- Drop-in shadcn API
- cmdk filtering
- ⌘K palette
- Nested pages
- Motion block
Try “Change theme…”, then Backspace to go back.
"use client";
import {
Bell,
BookOpen,
CreditCard,
Globe,
LayoutDashboard,
Monitor,
Moon,
Palette,
Plus,
Search,
Settings,
Sparkles,
UserPlus,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { CommandPalette, type CommandPaletteGroup, type CommandPalettePage } from "@/components/dusk/command/command-palette";
const groups: CommandPaletteGroup[] = [
{
heading: "Actions",
items: [
{ id: "new-project", label: "New project", icon: <Plus />, shortcut: "⌘N", onSelect: () => toast.success("Project created") },
{ id: "invite", label: "Invite teammate", icon: <UserPlus />, keywords: ["team", "member"], onSelect: () => toast("Invite sent") },
{ id: "search-docs", label: "Search docs", icon: <BookOpen />, keywords: ["help"], onSelect: () => toast("Opening docs…") },
],
},
{
heading: "Navigation",
items: [
{ id: "dashboard", label: "Dashboard", icon: <LayoutDashboard />, onSelect: () => toast("Dashboard") },
{ id: "billing", label: "Billing", icon: <CreditCard />, description: "Plans, invoices and payment", onSelect: () => toast("Billing") },
{ id: "notifications", label: "Notifications", icon: <Bell />, onSelect: () => toast("Notifications") },
],
},
{
heading: "Preferences",
items: [
{ id: "theme", label: "Change theme…", icon: <Palette />, page: "theme", keywords: ["appearance", "dark"] },
{ id: "language", label: "Change language…", icon: <Globe />, page: "language" },
{ id: "settings", label: "Settings", icon: <Settings />, shortcut: "⌘,", onSelect: () => toast("Settings") },
],
},
];
const pages: CommandPalettePage[] = [
{
id: "theme",
title: "Theme",
placeholder: "Pick a theme…",
groups: [
{
heading: "Theme",
items: [
{ id: "theme-dusk", label: "Dusk mint", icon: <Sparkles />, onSelect: () => toast("Theme: Dusk mint") },
{ id: "theme-midnight", label: "Midnight", icon: <Moon />, onSelect: () => toast("Theme: Midnight") },
{ id: "theme-system", label: "Match system", icon: <Monitor />, onSelect: () => toast("Theme: System") },
],
},
],
},
{
id: "language",
title: "Language",
placeholder: "Search languages…",
groups: [
{
heading: "Language",
items: ["English", "Deutsch", "Español", "Français", "हिन्दी", "日本語"].map((label) => ({
id: `lang-${label}`,
label,
onSelect: () => toast(`Language: ${label}`),
})),
},
],
},
];
export default function CommandPaletteDemo() {
return (
<div className="flex flex-col items-center gap-3">
<CommandPalette
groups={groups}
pages={pages}
hotkey="j"
defaultRecent={["billing", "new-project"]}
trigger={
<Button variant="outline" className="w-64 justify-start text-muted-foreground">
<Search />
Search or run a command…
<kbd className="ml-auto rounded border border-white/10 bg-white/5 px-1.5 font-mono text-[0.7rem]">⌘J</kbd>
</Button>
}
/>
<p className="text-xs text-muted-foreground">Try “Change theme…”, then Backspace to go back.</p>
</div>
);
}Installation
$ npx shadcn@latest add https://duskui.com/r/command.json1. Install the dependencies.
npm install cmdk lucide-react2. Copy the source into
components/ui/command.tsx.command.tsx "use client" import * as React from "react" import { Command as CommandPrimitive } from "cmdk" import { SearchIcon } from "lucide-react" import { cn } from "@/lib/utils" import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog" /** * DuskUI Command — a drop-in upgrade of the shadcn/ui Command (cmdk). * * Same parts, props and data-slot attributes as shadcn, plus: * - The result list eases its height as results filter in and out (cmdk's * `--cmdk-list-height`), so the palette never jumps. * - The selected item eases its background in and its icon brightens. * - `CommandDialog` sits near the top of the screen like a real palette, and * its accessible title lives inside the dialog. * - Shortcuts render as small keycaps. * - Under `prefers-reduced-motion` the height and highlight changes are instant. * CSS only. cmdk handles filtering, sorting and keyboard navigation. */ function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) { return ( <CommandPrimitive data-slot="command" className={cn( "bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-xl", className )} {...props} /> ) } /** A Command inside a Dialog — the classic ⌘K palette. Wire the shortcut yourself. */ function CommandDialog({ title = "Command Palette", description = "Search for a command to run...", children, className, showCloseButton = true, ...props }: React.ComponentProps<typeof Dialog> & { /** Accessible title (visually hidden). */ title?: string /** Accessible description (visually hidden). */ description?: string className?: string showCloseButton?: boolean }) { return ( <Dialog {...props}> <DialogContent className={cn( "top-[max(1rem,12dvh)] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-xl", className )} showCloseButton={showCloseButton} > <DialogHeader className="sr-only"> <DialogTitle>{title}</DialogTitle> <DialogDescription>{description}</DialogDescription> </DialogHeader> <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 **:data-[slot=command-input-wrapper]:pr-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5 **:data-[slot=command-list]:max-h-[min(360px,60dvh)]"> {children} </Command> </DialogContent> </Dialog> ) } /** The search field. Filters items as you type. */ function CommandInput({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) { return ( <div data-slot="command-input-wrapper" className="group/command-input flex h-10 items-center gap-2 border-b px-3" > <SearchIcon className="size-4 shrink-0 text-muted-foreground" /> <CommandPrimitive.Input data-slot="command-input" className={cn( "placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50", className )} {...props} /> </div> ) } /** The scrollable result list. Its height eases as results change. */ function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) { return ( <CommandPrimitive.List data-slot="command-list" className={cn( "h-(--cmdk-list-height) max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto overscroll-contain", "transition-[height] duration-200 ease-out motion-reduce:transition-none", className )} {...props} /> ) } /** Shown when nothing matches the search. Fades in. */ function CommandEmpty({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) { return ( <CommandPrimitive.Empty data-slot="command-empty" className={cn( "text-muted-foreground animate-in fade-in-0 py-6 text-center text-sm duration-200", className )} {...props} /> ) } /** A titled group of items. Hidden automatically when none of its items match. */ function CommandGroup({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Group>) { return ( <CommandPrimitive.Group data-slot="command-group" className={cn( "text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium", className )} {...props} /> ) } /** A thin divider between groups. */ function CommandSeparator({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Separator>) { return ( <CommandPrimitive.Separator data-slot="command-separator" className={cn("bg-border -mx-1 h-px", className)} {...props} /> ) } /** A selectable row. `onSelect` fires on click or Enter. */ function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) { return ( <CommandPrimitive.Item data-slot="command-item" className={cn( "relative flex cursor-default items-center gap-2 rounded-md px-2 py-1.5 text-sm outline-hidden select-none", "transition-[color,background-color] duration-150 ease-out motion-reduce:transition-none", "data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground", "data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50", "[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground [&_svg:not([class*='text-'])]:transition-colors data-[selected=true]:[&_svg:not([class*='text-'])]:text-foreground", className )} {...props} /> ) } /** Right-aligned keyboard hint, e.g. ⌘K. Visual only; wire the shortcut yourself. */ function CommandShortcut({ className, ...props }: React.ComponentProps<"span">) { return ( <span data-slot="command-shortcut" className={cn( "text-muted-foreground ml-auto rounded border border-white/10 bg-white/[0.04] px-1.5 py-px font-mono text-[0.7rem] tracking-widest", className )} {...props} /> ) } export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator, }
Replaces components/ui/command.tsx with the same exports and props, including CommandDialog's title, description, className and showCloseButton. It uses the DuskUI Dialog, which the CLI installs for you. Animations are CSS, so the base needs no Motion.
Usage
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandShortcut,
} from "@/components/ui/command"
export function SearchMenu() {
return (
<Command className="rounded-xl border">
<CommandInput placeholder="Type a command or search…" />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem onSelect={() => console.log("calendar")}>Calendar</CommandItem>
<CommandItem>
Settings
<CommandShortcut>⌘S</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
)
}Examples
Default
An inline menu. Type to filter: the list eases to its new height instead of jumping, the selected row gets a neutral highlight and its icon brightens, and shortcuts render as small keycaps. Disabled items are skipped by the arrow keys.
"use client";
import { Calculator, Calendar, CreditCard, Settings, Smile, User } from "lucide-react";
import { toast } from "sonner";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command";
export default function CommandBasicDemo() {
return (
<Command className="w-full max-w-sm rounded-xl border shadow-md">
<CommandInput placeholder="Type a command or search…" />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem onSelect={() => toast("Opening calendar")}>
<Calendar />
Calendar
</CommandItem>
<CommandItem onSelect={() => toast("Searching emoji")}>
<Smile />
Search emoji
</CommandItem>
<CommandItem disabled>
<Calculator />
Calculator
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Settings">
<CommandItem onSelect={() => toast("Profile")}>
<User />
Profile
<CommandShortcut>⌘P</CommandShortcut>
</CommandItem>
<CommandItem onSelect={() => toast("Billing")}>
<CreditCard />
Billing
<CommandShortcut>⌘B</CommandShortcut>
</CommandItem>
<CommandItem onSelect={() => toast("Settings")}>
<Settings />
Settings
<CommandShortcut>⌘S</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
);
}Dialog
CommandDialog wraps the menu in the DuskUI Dialog and positions it near the top of the screen like a real palette. Its accessible title and description are visually hidden but announced. Bind a shortcut yourself with a keydown listener.
"use client";
import * as React from "react";
import { FileText, LayoutDashboard, Moon, Plus, Settings } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/components/ui/command";
export default function CommandDialogDemo() {
const [open, setOpen] = React.useState(false);
const run = (message: string) => () => {
setOpen(false);
toast(message);
};
return (
<>
<Button variant="outline" onClick={() => setOpen(true)}>
Open command dialog
</Button>
<CommandDialog open={open} onOpenChange={setOpen}>
<CommandInput placeholder="Search pages and actions…" />
<CommandList>
<CommandEmpty>Nothing matches that search.</CommandEmpty>
<CommandGroup heading="Pages">
<CommandItem onSelect={run("Dashboard")}>
<LayoutDashboard />
Dashboard
</CommandItem>
<CommandItem onSelect={run("Docs")}>
<FileText />
Documentation
</CommandItem>
<CommandItem onSelect={run("Settings")}>
<Settings />
Settings
<CommandShortcut>⌘,</CommandShortcut>
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Actions">
<CommandItem onSelect={run("New project created")}>
<Plus />
New project
<CommandShortcut>⌘N</CommandShortcut>
</CommandItem>
<CommandItem onSelect={run("Theme toggled")}>
<Moon />
Toggle theme
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</>
);
}Blocks
Ready-made variations composed from the base component with Motion. Each installs on its own and pulls in its dependencies automatically.
Command Palette
A data-driven ⌘K palette. It fades in from the top, a highlight glides between items as you arrow or hover (a shared Motion layoutId), and actions you run surface under Recent. Items with a page open a nested page: the list slides in from the side you're travelling, a breadcrumb shows where you are and the panel eases to the new height. Backspace on an empty search or Escape steps back. This demo uses ⌘J so it doesn't clash with the site search.
Try “Change theme…”, then Backspace to go back.
"use client";
import {
Bell,
BookOpen,
CreditCard,
Globe,
LayoutDashboard,
Monitor,
Moon,
Palette,
Plus,
Search,
Settings,
Sparkles,
UserPlus,
} from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { CommandPalette, type CommandPaletteGroup, type CommandPalettePage } from "@/components/dusk/command/command-palette";
const groups: CommandPaletteGroup[] = [
{
heading: "Actions",
items: [
{ id: "new-project", label: "New project", icon: <Plus />, shortcut: "⌘N", onSelect: () => toast.success("Project created") },
{ id: "invite", label: "Invite teammate", icon: <UserPlus />, keywords: ["team", "member"], onSelect: () => toast("Invite sent") },
{ id: "search-docs", label: "Search docs", icon: <BookOpen />, keywords: ["help"], onSelect: () => toast("Opening docs…") },
],
},
{
heading: "Navigation",
items: [
{ id: "dashboard", label: "Dashboard", icon: <LayoutDashboard />, onSelect: () => toast("Dashboard") },
{ id: "billing", label: "Billing", icon: <CreditCard />, description: "Plans, invoices and payment", onSelect: () => toast("Billing") },
{ id: "notifications", label: "Notifications", icon: <Bell />, onSelect: () => toast("Notifications") },
],
},
{
heading: "Preferences",
items: [
{ id: "theme", label: "Change theme…", icon: <Palette />, page: "theme", keywords: ["appearance", "dark"] },
{ id: "language", label: "Change language…", icon: <Globe />, page: "language" },
{ id: "settings", label: "Settings", icon: <Settings />, shortcut: "⌘,", onSelect: () => toast("Settings") },
],
},
];
const pages: CommandPalettePage[] = [
{
id: "theme",
title: "Theme",
placeholder: "Pick a theme…",
groups: [
{
heading: "Theme",
items: [
{ id: "theme-dusk", label: "Dusk mint", icon: <Sparkles />, onSelect: () => toast("Theme: Dusk mint") },
{ id: "theme-midnight", label: "Midnight", icon: <Moon />, onSelect: () => toast("Theme: Midnight") },
{ id: "theme-system", label: "Match system", icon: <Monitor />, onSelect: () => toast("Theme: System") },
],
},
],
},
{
id: "language",
title: "Language",
placeholder: "Search languages…",
groups: [
{
heading: "Language",
items: ["English", "Deutsch", "Español", "Français", "हिन्दी", "日本語"].map((label) => ({
id: `lang-${label}`,
label,
onSelect: () => toast(`Language: ${label}`),
})),
},
],
},
];
export default function CommandPaletteDemo() {
return (
<div className="flex flex-col items-center gap-3">
<CommandPalette
groups={groups}
pages={pages}
hotkey="j"
defaultRecent={["billing", "new-project"]}
trigger={
<Button variant="outline" className="w-64 justify-start text-muted-foreground">
<Search />
Search or run a command…
<kbd className="ml-auto rounded border border-white/10 bg-white/5 px-1.5 font-mono text-[0.7rem]">⌘J</kbd>
</Button>
}
/>
<p className="text-xs text-muted-foreground">Try “Change theme…”, then Backspace to go back.</p>
</div>
);
}$ npx shadcn@latest add https://duskui.com/r/command-palette.json1. Install the dependencies.
npm install motion cmdk @radix-ui/react-dialog lucide-react2. Copy the source into
components/dusk/command/command-palette.tsx.command-palette.tsx "use client"; import * as React from "react"; import * as DialogPrimitive from "@radix-ui/react-dialog"; import { Command as CommandPrimitive, defaultFilter } from "cmdk"; import { AnimatePresence, motion, useReducedMotion, type Transition, } from "motion/react"; import { ChevronLeft, ChevronRight, CornerDownLeft, History, Search } from "lucide-react"; import { Command, CommandEmpty, CommandGroup, CommandItem, CommandList, CommandShortcut, } from "@/components/ui/command"; import { cn } from "@/lib/utils"; export type CommandPaletteItem = { /** Unique within the palette. */ id: string; label: string; icon?: React.ReactNode; /** Secondary line under the label. */ description?: string; /** Keyboard hint, e.g. "⌘N". Visual only. */ shortcut?: string; /** Extra search terms. */ keywords?: string[]; disabled?: boolean; /** Open a nested page (by page id) instead of running an action. */ page?: string; /** Run the action. The palette closes afterwards unless `keepOpen` is set. */ onSelect?: () => void; keepOpen?: boolean; }; export type CommandPaletteGroup = { heading: string; items: CommandPaletteItem[]; }; export type CommandPalettePage = { id: string; /** Shown in the breadcrumb. */ title: string; placeholder?: string; groups: CommandPaletteGroup[]; }; export interface CommandPaletteProps { /** Groups on the home page. */ groups: CommandPaletteGroup[]; /** Nested pages, opened by items with a `page`. */ pages?: CommandPalettePage[]; open?: boolean; defaultOpen?: boolean; onOpenChange?: (open: boolean) => void; /** Element that opens the palette, usually a Button. */ trigger?: React.ReactElement; /** Key that toggles the palette with ⌘ / Ctrl. `null` disables the shortcut. */ hotkey?: string | null; placeholder?: string; emptyMessage?: React.ReactNode; /** Item ids shown under "Recent" before anything has been run. */ defaultRecent?: string[]; /** How many recent items to keep. 0 hides the group. */ recentLimit?: number; /** Accessible title (visually hidden). */ title?: string; /** Accessible description (visually hidden). */ description?: string; className?: string; } const highlightSpring: Transition = { type: "spring", stiffness: 560, damping: 40, mass: 0.6 }; const heightSpring: Transition = { type: "spring", bounce: 0, duration: 0.35 }; const surfaceSpring: Transition = { type: "spring", duration: 0.25, bounce: 0 }; /** Search labels, descriptions and keywords, never internal ids. */ const filter = (_value: string, search: string, keywords?: string[]) => defaultFilter("", search, keywords); /** * A ⌘K command palette. A highlight glides between items as you arrow or * hover, recently run actions surface at the top, and items can open nested * pages — the list slides in from the side you're travelling, a breadcrumb * shows where you are and the panel eases to the new height. Backspace on * an empty search or Escape goes back a page. Built on cmdk and Radix Dialog: * filtering, keyboard navigation, focus trap and focus return all work. */ export function CommandPalette({ groups, pages = [], open: openProp, defaultOpen = false, onOpenChange, trigger, hotkey = "k", placeholder = "Type a command or search…", emptyMessage = "No results found.", defaultRecent = [], recentLimit = 3, title = "Command palette", description = "Search for a command to run.", className, }: CommandPaletteProps) { const reduceMotion = useReducedMotion() ?? false; const layoutId = React.useId(); const [internalOpen, setInternalOpen] = React.useState(defaultOpen); const open = openProp ?? internalOpen; const [stack, setStack] = React.useState<string[]>([]); const [direction, setDirection] = React.useState(0); const [search, setSearch] = React.useState(""); const [selected, setSelected] = React.useState(""); const [recent, setRecent] = React.useState<string[]>(defaultRecent); const inputRef = React.useRef<HTMLInputElement>(null); // An action run as the palette closes is added to Recent once it has faded out. const pendingRecent = React.useRef<string | null>(null); const pageId = stack[stack.length - 1]; const page = pageId ? pages.find((p) => p.id === pageId) : undefined; const setOpen = React.useCallback( (next: boolean) => { if (openProp === undefined) setInternalOpen(next); onOpenChange?.(next); }, [openProp, onOpenChange] ); // ⌘K / Ctrl+K toggles the palette. const openRef = React.useRef(open); React.useEffect(() => { openRef.current = open; }, [open]); React.useEffect(() => { if (!hotkey) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key.toLowerCase() === hotkey.toLowerCase() && (event.metaKey || event.ctrlKey)) { event.preventDefault(); setOpen(!openRef.current); } }; document.addEventListener("keydown", onKeyDown); return () => document.removeEventListener("keydown", onKeyDown); }, [hotkey, setOpen]); const findItem = (id: string) => { for (const group of [...groups, ...pages.flatMap((p) => p.groups)]) { const item = group.items.find((i) => i.id === id); if (item) return item; } }; const go = (next: string[], dir: number) => { setDirection(dir); setStack(next); setSearch(""); // Let cmdk pick the first item of the new page. setSelected(""); inputRef.current?.focus(); }; const back = () => { if (stack.length) go(stack.slice(0, -1), -1); }; const run = (item: CommandPaletteItem) => { if (item.page) { go([...stack, item.page], 1); return; } item.onSelect?.(); if (item.keepOpen) { remember(item.id); } else { pendingRecent.current = item.id; setOpen(false); } }; const remember = (id: string) => { if (recentLimit > 0) setRecent((r) => [id, ...r.filter((x) => x !== id)].slice(0, recentLimit)); }; const recentItems = !page && !search && recentLimit > 0 ? recent .map(findItem) .filter((item): item is CommandPaletteItem => !!item && !item.page) .slice(0, recentLimit) : []; const visibleGroups = page ? page.groups : groups; const renderItem = (item: CommandPaletteItem, prefix: string) => { const value = `${prefix}:${item.id}`; const isSelected = selected === value; return ( <CommandItem key={value} value={value} keywords={[item.label, item.description ?? "", ...(item.keywords ?? [])]} disabled={item.disabled} onSelect={() => run(item)} className={cn( "group/item gap-3 rounded-lg px-2.5 py-2", // The gliding highlight replaces the static selected background and marker. "data-[selected=true]:bg-transparent before:hidden" )} > {isSelected && ( <motion.span aria-hidden // One highlight per page, so it glides within a page and simply appears on a new one. layoutId={`${layoutId}-${prefix === "recent" ? "home" : prefix}-highlight`} transition={reduceMotion ? { duration: 0 } : highlightSpring} className="absolute inset-0 rounded-lg bg-accent" /> )} {item.icon && ( <span aria-hidden className={cn( "relative flex size-7 shrink-0 items-center justify-center rounded-md border bg-white/[0.03] transition-colors duration-150 [&_svg]:size-4", isSelected ? "border-white/15 text-foreground [&_svg]:!text-foreground" : "text-muted-foreground" )} > {item.icon} </span> )} <span className="relative flex min-w-0 flex-1 flex-col"> <span className="truncate">{item.label}</span> {item.description && ( <span className="truncate text-xs text-muted-foreground">{item.description}</span> )} </span> {item.shortcut && <CommandShortcut className="relative">{item.shortcut}</CommandShortcut>} {item.page && ( <ChevronRight aria-hidden className={cn( "relative transition-transform duration-200", isSelected && !reduceMotion && "translate-x-0.5" )} /> )} </CommandItem> ); }; return ( <DialogPrimitive.Root open={open} onOpenChange={setOpen} > {trigger && <DialogPrimitive.Trigger asChild>{trigger}</DialogPrimitive.Trigger>} <AnimatePresence onExitComplete={() => { // Reset once fully closed so the palette reopens on its home page. if (pendingRecent.current) remember(pendingRecent.current); pendingRecent.current = null; setStack([]); setDirection(0); setSearch(""); setSelected(""); }} > {open && ( // forceMount hands mounting to AnimatePresence so the exit animation can play. <DialogPrimitive.Portal forceMount> <DialogPrimitive.Overlay forceMount asChild> <motion.div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-[2px]" initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0, transition: { duration: 0.15 } }} transition={{ duration: 0.2 }} /> </DialogPrimitive.Overlay> <DialogPrimitive.Content forceMount asChild onOpenAutoFocus={(event) => { event.preventDefault(); inputRef.current?.focus(); }} onEscapeKeyDown={(event) => { // Escape steps back out of nested pages before closing. if (stack.length) { event.preventDefault(); back(); } }} > <motion.div className={cn( "fixed top-[max(1rem,12dvh)] left-1/2 z-50 w-[calc(100%-2rem)] max-w-xl -translate-x-1/2 outline-none", className )} initial={reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.96, y: -8 }} animate={reduceMotion ? { opacity: 1 } : { opacity: 1, scale: 1, y: 0 }} exit={ reduceMotion ? { opacity: 0, transition: { duration: 0.1 } } : { opacity: 0, scale: 0.98, y: -4, transition: { duration: 0.12, ease: "easeIn" } } } transition={surfaceSpring} > <DialogPrimitive.Title className="sr-only">{title}</DialogPrimitive.Title> <DialogPrimitive.Description className="sr-only">{description}</DialogPrimitive.Description> <Command loop filter={filter} value={selected} onValueChange={setSelected} className="rounded-xl border shadow-lg" onKeyDown={(event) => { if (event.key === "Backspace" && !search && stack.length) { event.preventDefault(); back(); } }} > <div className="flex items-center gap-2 border-b px-3"> <Search aria-hidden className="size-4 shrink-0 text-muted-foreground" /> <AnimatePresence initial={false} mode="popLayout"> {stack.length > 0 && ( <motion.nav key="crumbs" aria-label="Breadcrumb" className="flex shrink-0 items-center gap-1" initial={reduceMotion ? { opacity: 0 } : { opacity: 0, x: -6 }} animate={{ opacity: 1, x: 0 }} exit={reduceMotion ? { opacity: 0 } : { opacity: 0, x: -6 }} transition={{ duration: 0.18 }} > <button type="button" onClick={back} aria-label="Back" className="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-[3px] focus-visible:ring-ring/50" > <ChevronLeft className="size-4" aria-hidden /> </button> {stack.map((id, i) => ( <span key={id} aria-current={i === stack.length - 1 ? "page" : undefined} className="rounded-md border border-white/10 bg-white/[0.06] px-1.5 py-0.5 text-xs font-medium text-foreground" > {pages.find((p) => p.id === id)?.title ?? id} </span> ))} </motion.nav> )} </AnimatePresence> <CommandPrimitive.Input ref={inputRef} value={search} onValueChange={setSearch} placeholder={page?.placeholder ?? placeholder} className="h-12 min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground" /> <kbd className="hidden shrink-0 rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 font-mono text-[0.65rem] text-muted-foreground sm:inline"> esc </kbd> </div> <AutoHeight transition={reduceMotion ? { duration: 0 } : heightSpring}> <CommandList className="h-auto max-h-[min(380px,55dvh)] scroll-py-2 transition-none"> {/* A fresh key per page replays the slide-in from the travel direction. */} <motion.div key={pageId ?? "home"} className="p-1.5" initial={ direction === 0 || reduceMotion ? false : { opacity: 0, x: direction * 8 } } animate={{ opacity: 1, x: 0 }} transition={{ type: "spring", bounce: 0, duration: 0.25 }} > <CommandEmpty>{emptyMessage}</CommandEmpty> {recentItems.length > 0 && ( <CommandGroup heading={ <span className="flex items-center gap-1.5"> <History className="size-3" aria-hidden /> Recent </span> } > {recentItems.map((item) => renderItem(item, "recent"))} </CommandGroup> )} {visibleGroups.map((group) => ( <CommandGroup key={group.heading} heading={group.heading}> {group.items.map((item) => renderItem(item, pageId ?? "home"))} </CommandGroup> ))} </motion.div> </CommandList> </AutoHeight> <div className="flex items-center gap-4 border-t px-3 py-2 text-[0.7rem] text-muted-foreground"> <span className="flex items-center gap-1.5"> <Kbd>↑</Kbd> <Kbd>↓</Kbd> navigate </span> <span className="flex items-center gap-1.5"> <Kbd> <CornerDownLeft className="size-3" aria-hidden /> </Kbd> select </span> <span className="ml-auto flex items-center gap-1.5"> <Kbd>{stack.length ? "⌫" : "esc"}</Kbd> {stack.length ? "back" : "close"} </span> </div> </Command> </motion.div> </DialogPrimitive.Content> </DialogPrimitive.Portal> )} </AnimatePresence> </DialogPrimitive.Root> ); } function Kbd({ children }: { children: React.ReactNode }) { return ( <kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded border border-white/10 bg-white/[0.04] px-1 font-mono text-[0.65rem]"> {children} </kbd> ); } /** Eases its height to its content, so the palette never jumps between pages or results. */ function AutoHeight({ children, transition }: { children: React.ReactNode; transition: Transition }) { const innerRef = React.useRef<HTMLDivElement>(null); const [height, setHeight] = React.useState<number | "auto">("auto"); React.useLayoutEffect(() => { const el = innerRef.current; if (!el) return; const observer = new ResizeObserver(([entry]) => setHeight(entry.borderBoxSize?.[0]?.blockSize ?? el.offsetHeight) ); observer.observe(el); return () => observer.disconnect(); }, []); return ( <motion.div initial={false} animate={{ height }} transition={transition} className="overflow-hidden"> <div ref={innerRef}>{children}</div> </motion.div> ); }
| Prop | Type | Default | Description |
|---|---|---|---|
| groups | CommandPaletteGroup[] | — | Groups on the home page: { heading, items }. |
| pages | CommandPalettePage[] | [] | Nested pages: { id, title, placeholder?, groups }. |
| items[] | { id, label, icon?, description?, shortcut?, keywords?, disabled?, page?, onSelect?, keepOpen? } | — | page opens a nested page; otherwise onSelect runs and the palette closes unless keepOpen. |
| open / defaultOpen / onOpenChange | boolean / boolean / (open: boolean) => void | — | Open state. |
| trigger | ReactElement | — | Element that opens the palette, usually a Button. |
| hotkey | string | null | "k" | Key that toggles the palette with ⌘ / Ctrl. null disables it. |
| defaultRecent / recentLimit | string[] / number | [] / 3 | Initial recent item ids and how many to keep. 0 hides Recent. |
| placeholder / emptyMessage | string / ReactNode | — | Search placeholder and the no-results message. |
| title / description | string | — | Accessible (visually hidden) dialog title and description. |
API Reference
Same parts as shadcn/ui: Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandSeparator and CommandShortcut. Each forwards the cmdk props.
| Prop | Type | Default | Description |
|---|---|---|---|
| value / onValueChange | string / (value: string) => void | — | Controlled selected item (on Command). |
| filter / shouldFilter / loop | (value, search, keywords) => number / boolean / boolean | — | Custom scoring, turn filtering off for async results, wrap arrow keys (on Command). |
| value / onValueChange | string / (search: string) => void | — | Controlled search text (on CommandInput). |
| onSelect / value / keywords / disabled | (value) => void / string / string[] / boolean | — | On CommandItem. keywords add search terms. |
| heading | ReactNode | — | Group title (on CommandGroup). |
| title / description / showCloseButton | string / string / boolean | "Command Palette" / … / true | On CommandDialog, plus all Dialog props. |
Accessibility
- cmdk renders a
comboboxinput that controls alistbox; the selected option is exposed witharia-selectedandaria-activedescendant, so focus stays in the input. - Arrow keys (and Ctrl+N/P, Ctrl+J/K) move the selection, Home/End jump, Enter runs the item. Disabled items are skipped.
- CommandDialog and the Command Palette are Radix Dialogs: focus is trapped, Escape closes (in the palette it first steps back out of nested pages) and focus returns to the trigger.
- The palette's breadcrumb is a labelled nav with aria-current on the current page and a real Back button.
- Under prefers-reduced-motion the list height and highlight change instantly, pages don't slide and the palette only fades.