Navigation
Command palette
Search and run commands with ⌘K. Results slide into place as you filter; one pill follows the arrow keys; running an item pops it.
Examples and variants
Dialog
Open with the button or ⌘K / Ctrl+K.
Or press ⌘K.
function CommandPalette() {
const [open, setOpen] = useState(false)
const [last, setLast] = useState("")
const items: CommandItem[] = [
{ id: "new", label: "New project", group: "Projects", shortcut: "N", icon: <PlusIcon />, onRun: () => setLast("New project") },
{ id: "open", label: "Open file", group: "Projects", icon: <FileIcon />, onRun: () => setLast("Open file") },
{ id: "dup", label: "Duplicate", group: "Projects", icon: <CopyIcon />, onRun: () => setLast("Duplicate") },
{ id: "theme", label: "Toggle dark mode", group: "Settings", icon: <MoonIcon />, onRun: () => setLast("Toggle dark mode") },
{ id: "prefs", label: "Preferences", group: "Settings", shortcut: ",", icon: <SettingsIcon />, onRun: () => setLast("Preferences") },
]
return (
<div className="flex flex-col items-center gap-2">
<Button variant="secondary" onClick={() => setOpen(true)}>
Open command palette
<KbdGroup>
<Kbd>⌘</Kbd>
<Kbd>K</Kbd>
</KbdGroup>
</Button>
<p className="text-sm text-muted-foreground">{last ? `Ran: ${last}` : "Or press ⌘K."}</p>
<CommandDialog items={items} open={open} onOpenChange={setOpen} />
</div>
)
}Spec drawing
Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.
Install
With the CLI
The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/command.json
npx shadcn@latest add https://isotopi.com/r/dialog.json
npx shadcn@latest add https://isotopi.com/r/kbd.jsonBy hand
No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.
Install the packages it uses.
Terminalnpm install @base-ui/react class-variance-authority cn lucide-reactCopy these 6 files to the same paths in your project. Imports use the
@/alias for your project root.components/ui/dialog.tsxdialog
components/ui/dialog.tsx"use client" import * as React from "react" import { Dialog as DialogPrimitive } from "@base-ui/react/dialog" import { cn } from "cn" import { motionLevel, usePortalMotion } from "@/lib/overlay" type Point = { x: number; y: number } const PointContext = React.createContext<{ point: Point | null setPoint: (point: Point) => void } | null>(null) function Dialog(props: DialogPrimitive.Root.Props) { const [point, setPoint] = React.useState<Point | null>(null) return ( <PointContext.Provider value={{ point, setPoint }}> <DialogPrimitive.Root {...props} /> </PointContext.Provider> ) } function DialogTrigger({ onClick, ...props }: DialogPrimitive.Trigger.Props) { const context = React.useContext(PointContext) return ( <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} onClick={(event) => { const rect = event.currentTarget.getBoundingClientRect() context?.setPoint({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }) onClick?.(event) }} /> ) } function DialogClose({ ref, ...props }: DialogPrimitive.Close.Props & { ref?: React.Ref<HTMLButtonElement> }) { return <DialogPrimitive.Close ref={ref} data-slot="dialog-close" {...props} /> } function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) { return <DialogPrimitive.Title className={cn("text-title", className)} {...props} /> } function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { return <div data-slot="dialog-header" className={cn("flex flex-col gap-1", className)} {...props} /> } function DialogFooter({ className, ...props }: React.ComponentProps<"div">) { return ( <div data-slot="dialog-footer" className={cn("flex flex-wrap justify-end gap-inline-sm pt-1", className)} {...props} /> ) } function DialogDescription({ className, ...props }: DialogPrimitive.Description.Props) { return ( <DialogPrimitive.Description className={cn("text-sm text-muted-foreground", className)} {...props} /> ) } function DialogContent({ className, children, firm = false, shake = false, size = "sm", ...props }: DialogPrimitive.Popup.Props & { firm?: boolean shake?: boolean /** sm 400 · md 520 · lg 720 · full (phones: always near full width). */ size?: "sm" | "md" | "lg" | "full" }) { const ref = React.useRef<HTMLDivElement>(null) const context = React.useContext(PointContext) usePortalMotion(ref) const level = typeof window === "undefined" ? "liquid" : motionLevel() const point = context?.point const onScreen = point && point.x >= 0 && point.y >= 0 && point.x <= window.innerWidth && point.y <= window.innerHeight const fly = level === "liquid" && onScreen return ( <DialogPrimitive.Portal> <DialogPrimitive.Backdrop className={cn("overlay-scrim fixed inset-0 z-modal", firm && "overlay-scrim-firm")} onMouseDown={() => { if (!shake || !ref.current) return ref.current.classList.remove("alert-shake") void ref.current.offsetWidth ref.current.classList.add("alert-shake") }} /> <DialogPrimitive.Popup ref={ref} data-slot="dialog-content" className={cn( "overlay-surface overlay-grow dialog-fly fixed top-1/2 left-1/2 z-modal max-w-[calc(100vw-var(--space-6))] -translate-x-1/2 -translate-y-1/2 rounded-(--dialog-corner) p-(--dialog-padding) text-foreground", size === "sm" && "w-(--dialog-width-sm)", size === "md" && "w-(--dialog-width-md)", size === "lg" && "w-(--dialog-width-lg)", size === "full" && "h-[calc(100vh-var(--space-6))] w-[calc(100vw-var(--space-6))]", firm && "dialog-firm", className )} style={ fly ? ({ "--from-x": `${point.x - window.innerWidth / 2}px`, "--from-y": `${point.y - window.innerHeight / 2}px`, } as React.CSSProperties) : undefined } {...props} > <div className="dialog-copy flex flex-col gap-stack-md">{children}</div> </DialogPrimitive.Popup> </DialogPrimitive.Portal> ) } export { Dialog, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogFooter, DialogTitle, DialogDescription, }components/ui/kbd.tsxkbd
components/ui/kbd.tsx"use client" import * as React from "react" import { cn } from "cn" /* Kbd: shows a key. With `live`, it squashes like the real key when that key is pressed on the page. Pass `keyName` for the KeyboardEvent.key to match ("k", "Enter", "Meta"); it defaults to the text when that's one character. */ function Kbd({ className, live = false, keyName, children, ...props }: React.ComponentProps<"kbd"> & { live?: boolean; keyName?: string }) { const [down, setDown] = React.useState(false) const match = (keyName ?? (typeof children === "string" && children.length === 1 ? children : "")).toLowerCase() React.useEffect(() => { if (!live || !match) return const onDown = (event: KeyboardEvent) => { if (event.key.toLowerCase() === match) setDown(true) } const onUp = (event: KeyboardEvent) => { if (event.key.toLowerCase() === match) setDown(false) } const reset = () => setDown(false) window.addEventListener("keydown", onDown) window.addEventListener("keyup", onUp) window.addEventListener("blur", reset) return () => { window.removeEventListener("keydown", onDown) window.removeEventListener("keyup", onUp) window.removeEventListener("blur", reset) } }, [live, match]) return ( <kbd data-slot="kbd" data-down={down || undefined} className={cn( "kbd inline-flex h-(--kbd-height) min-w-(--kbd-height) items-center justify-center rounded-(--kbd-corner) bg-(--kbd-container) px-1 font-sans text-xs font-medium text-muted-foreground shadow-1 select-none", className )} {...props} > {children} </kbd> ) } function KbdGroup({ className, ...props }: React.ComponentProps<"span">) { return <span data-slot="kbd-group" className={cn("inline-flex items-center gap-1", className)} {...props} /> } export { Kbd, KbdGroup }components/ui/chip.tsxchip
components/ui/chip.tsx"use client" import * as React from "react" import { XIcon } from "lucide-react" import { cva, type VariantProps } from "class-variance-authority" import { cn } from "cn" /* One Chip for every compact, interactive token (component-model.md §3): - kind="input": a value someone entered or picked (Combobox multiple, tag fields). Removable. - kind="filter": a toggle that narrows a list. Pressed state. - kind="suggestion": a one-tap suggestion that runs an action. Badge stays static (status and counts) and is not a Chip. */ const chipVariants = cva( "chip-land inline-flex h-(--chip-height) shrink-0 items-center gap-1 rounded-(--chip-corner) px-(--chip-padding-x) text-xs whitespace-nowrap outline-none select-none focus-visible:shadow-(--focus-ring)", { variants: { kind: { input: "bg-(--chip-container) text-(--chip-label)", filter: "liquid-press bg-(--chip-filter-container) text-(--chip-label) hover:bg-(--chip-filter-container-hover) active:bg-(--chip-filter-container-pressed) data-[pressed]:bg-(--chip-container-selected) data-[pressed]:text-(--chip-label-selected) data-[pressed]:hover:bg-(--chip-container-selected-hover) disabled:bg-(--chip-container-disabled) disabled:text-(--chip-label-disabled)", suggestion: "liquid-press bg-(--chip-suggestion-container) text-(--chip-label) shadow-1 hover:bg-(--chip-suggestion-container-hover) disabled:bg-(--chip-container-disabled) disabled:text-(--chip-label-disabled) disabled:shadow-none", }, tone: { neutral: "", danger: "bg-(--color-danger-subtle) text-(--color-danger-fg)", success: "bg-(--color-success-subtle) text-(--color-success-fg)", }, }, defaultVariants: { kind: "input", tone: "neutral" }, } ) type ChipProps = React.ComponentProps<"span"> & VariantProps<typeof chipVariants> & { /** Plays the melt-away animation (set by the parent while the chip is being removed). */ melting?: boolean } function Chip({ className, kind, tone, melting, ...props }: ChipProps) { return ( <span data-slot="chip" data-kind={kind ?? "input"} className={cn(chipVariants({ kind, tone }), melting && "chip-melt", className)} {...props} /> ) } function ChipRemove({ className, children, ...props }: React.ComponentProps<"button">) { return ( <button type="button" data-slot="chip-remove" aria-label="Remove" className={cn( "hit-target liquid-press -mr-1 inline-flex size-4 items-center justify-center rounded-(--radius-pill) text-muted-foreground outline-none hover:bg-(--chip-remove-container-hover) hover:text-foreground active:bg-(--chip-remove-container-pressed) focus-visible:shadow-(--focus-ring) [&_svg]:size-3", className )} {...props} > {children ?? <XIcon aria-hidden />} </button> ) } export { Chip, ChipRemove, chipVariants }components/ui/combobox.tsxcombobox
components/ui/combobox.tsx"use client" import * as React from "react" import { createPortal } from "react-dom" import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox" import { cn } from "cn" import { tokenMs } from "@/lib/motion/token-ms" import { motionLevel } from "@/lib/overlay" import { Chip, ChipRemove } from "@/components/ui/chip" function ComboboxValue(props: ComboboxPrimitive.Value.Props) { return <ComboboxPrimitive.Value {...props} /> } type Bud = { id: number; x: number; y: number; dx: number; dy: number } /* Per-instance state (no window events or document lookups), so two comboboxes on one page never animate each other: - anchor: the visible field shape (ComboboxChips). The list anchors to it, not to the bare text input, so it never overlaps the field's focus halo. - bud: the droplet that flies from a picked row into the field, or from a removed chip back into the input. - melting: the chip being removed; it melts before the value updates. */ type ComboboxState = { anchor: HTMLElement | null setAnchor: (node: HTMLElement | null) => void input: React.RefObject<HTMLInputElement | null> bud: Bud | null sendBud: (from: { x: number; y: number }, to?: { x: number; y: number }) => void clearBud: () => void melting: unknown } const ComboboxContext = React.createContext<ComboboxState | null>(null) function useComboboxState() { const state = React.useContext(ComboboxContext) if (!state) throw new Error("Combobox parts must be inside <Combobox>") return state } function Combobox<Value, Multiple extends boolean | undefined = false>({ onValueChange, value, ...props }: ComboboxPrimitive.Root.Props<Value, Multiple>) { const [anchor, setAnchor] = React.useState<HTMLElement | null>(null) const [bud, setBud] = React.useState<Bud | null>(null) const [melting, setMelting] = React.useState<unknown>(null) const input = React.useRef<HTMLInputElement | null>(null) const current = React.useRef<unknown>(value) React.useEffect(() => { if (value !== undefined) current.current = value }, [value]) const sendBud = React.useCallback( (from: { x: number; y: number }, to?: { x: number; y: number }) => { if (!anchor || motionLevel(anchor) !== "liquid") return const box = anchor.getBoundingClientRect() const target = to ?? { x: box.left + box.width / 2, y: box.top + box.height / 2 } setBud({ id: Date.now(), x: from.x, y: from.y, dx: target.x - from.x, dy: target.y - from.y }) }, [anchor] ) // Multiple: a removed value melts first, then the change is reported. const handleChange = React.useCallback( (next: unknown, details: unknown) => { const report = () => { current.current = next ;(onValueChange as ((v: unknown, d: unknown) => void) | undefined)?.(next, details) } const before = Array.isArray(current.current) ? current.current : [] const after = Array.isArray(next) ? next : [] const removed = before.find((item) => !after.includes(item)) if (removed === undefined || !anchor || motionLevel(anchor) !== "liquid") { setMelting(null) report() return } setMelting(removed) window.setTimeout(() => { setMelting(null) report() }, tokenMs("--duration-fast", anchor)) }, [anchor, onValueChange] ) const state = React.useMemo( () => ({ anchor, setAnchor, input, bud, sendBud, clearBud: () => setBud(null), melting }), [anchor, bud, sendBud, melting] ) return ( <ComboboxContext.Provider value={state}> <ComboboxPrimitive.Root<Value, Multiple> {...props} value={value} onValueChange={handleChange as ComboboxPrimitive.Root.Props<Value, Multiple>["onValueChange"]} /> </ComboboxContext.Provider> ) } function ComboboxInput({ className, ...props }: ComboboxPrimitive.Input.Props) { const { input } = useComboboxState() return ( <ComboboxPrimitive.Input ref={input} data-slot="combobox-input" className={cn( "h-(--field-height-md) w-full min-w-48 rounded-(--field-corner) border-solid border-(length:--field-stroke-width) border-(--field-stroke-color) bg-(--field-container) px-(--field-padding-x) text-sm text-(--field-label) shadow-(--field-elevation) outline-none transition-[background-color,box-shadow] duration-(--duration-fast) ease-(--ease-out) placeholder:text-(--field-placeholder) focus-visible:bg-(--field-container-focus) focus-visible:shadow-(--field-focus-shadow)", className )} {...props} /> ) } function ComboboxContent({ className, children, ...props }: ComboboxPrimitive.Popup.Props) { const { anchor } = useComboboxState() return ( <ComboboxPrimitive.Portal> <ComboboxPrimitive.Positioner anchor={anchor ?? undefined} sideOffset={8} className="z-(--z-dropdown)" > <ComboboxPrimitive.Popup data-slot="combobox-content" className={cn( "grow-from-origin min-w-(--anchor-width) overflow-hidden rounded-(--menu-corner) bg-(--menu-container) p-1 text-foreground shadow-(--menu-elevation) outline-none", className )} {...props} > {children} </ComboboxPrimitive.Popup> </ComboboxPrimitive.Positioner> </ComboboxPrimitive.Portal> ) } function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) { const ref = React.useRef<HTMLDivElement>(null) const places = React.useRef(new Map<string, number>()) React.useLayoutEffect(() => { const root = ref.current if (!root) return const rows = [...root.querySelectorAll<HTMLElement>(".combo-row:not(.combo-row-out)")] const next = new Map<string, number>() const duration = tokenMs("--duration-fast", root) const easing = getComputedStyle(root).getPropertyValue("--ease-sheet").trim() || "ease" for (const row of rows) { const key = row.textContent ?? "" const top = row.getBoundingClientRect().top const before = places.current.get(key) next.set(key, top) if (before === undefined || duration === 0) continue const dy = before - top if (Math.abs(dy) < 1) continue row.animate([{ transform: `translateY(${dy}px)` }, { transform: "none" }], { duration, easing }) } places.current = next }) return ( <ComboboxPrimitive.List ref={ref} data-slot="combobox-list" className={cn("max-h-60 overflow-y-auto", className)} {...props} /> ) } function ComboboxItem({ className, onClick, ...props }: ComboboxPrimitive.Item.Props) { const { sendBud } = useComboboxState() return ( <ComboboxPrimitive.Item data-slot="combobox-item" className={cn( "flex cursor-default items-center rounded-(--menu-item-corner) text-sm outline-none data-highlighted:bg-(--menu-item-highlight)", className )} {...props} onClick={(event) => { onClick?.(event) const rect = event.currentTarget.getBoundingClientRect() sendBud({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }) }} /> ) } function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) { return ( <ComboboxPrimitive.Empty data-slot="combobox-empty" className={cn( "isotope-rise px-2 py-3 text-center text-sm text-muted-foreground", className )} {...props} /> ) } /** A plain field wrapper that anchors the list (single-value comboboxes with icons). */ function ComboboxField({ className, ...props }: React.ComponentProps<"div">) { const ref = React.useRef<HTMLDivElement>(null) const { setAnchor } = useComboboxState() React.useLayoutEffect(() => { setAnchor(ref.current) return () => setAnchor(null) }, [setAnchor]) return <div ref={ref} data-slot="combobox-field" className={cn("relative flex w-full items-center", className)} {...props} /> } function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) { return ( <ComboboxPrimitive.Clear data-slot="combobox-clear" aria-label="Clear" className={cn( "liquid-press inline-flex size-6 items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)", className )} {...props} /> ) } function ComboboxChips({ className, children, ...props }: ComboboxPrimitive.Chips.Props) { const chipsRef = React.useRef<HTMLDivElement>(null) const { setAnchor, bud, clearBud } = useComboboxState() const places = React.useRef(new Map<string, number>()) React.useLayoutEffect(() => { setAnchor(chipsRef.current) return () => setAnchor(null) }, [setAnchor]) // Neighbours slide over when a chip arrives or leaves (FLIP). React.useLayoutEffect(() => { const root = chipsRef.current if (!root) return const chips = [...root.querySelectorAll<HTMLElement>("[data-slot=chip]")] const next = new Map<string, number>() const easing = getComputedStyle(root).getPropertyValue("--ease-sheet").trim() || "ease" const duration = tokenMs("--duration-fast", root) for (const chip of chips) { const key = chip.textContent ?? "" const left = chip.getBoundingClientRect().left const before = places.current.get(key) next.set(key, left) if (before === undefined || duration === 0) continue const dx = before - left if (Math.abs(dx) < 1) continue chip.animate([{ transform: `translateX(${dx}px)` }, { transform: "none" }], { duration, easing }) } places.current = next }) return ( <ComboboxPrimitive.Chips ref={chipsRef} data-slot="combobox-chips" className={cn( "flex min-h-(--field-height-md) w-full min-w-48 flex-wrap items-center gap-(--space-gap-inline-xs) rounded-(--combobox-chips-corner) bg-(--field-container) px-2 py-1 shadow-(--field-elevation) transition-[background-color,box-shadow] duration-(--duration-fast) ease-(--ease-out) focus-within:bg-(--field-container-focus) focus-within:shadow-(--field-focus-shadow)", "**:data-[slot=combobox-input]:h-auto **:data-[slot=combobox-input]:min-w-0 **:data-[slot=combobox-input]:flex-1 **:data-[slot=combobox-input]:rounded-none **:data-[slot=combobox-input]:bg-transparent **:data-[slot=combobox-input]:px-1 **:data-[slot=combobox-input]:shadow-none **:data-[slot=combobox-input]:focus-visible:bg-transparent **:data-[slot=combobox-input]:focus-visible:shadow-none", className )} {...props} > {children} {/* Portalled: a fixed element inside a blurred surface (Glass) would be positioned against that surface. */} {bud ? createPortal( <span key={bud.id} aria-hidden className="chip-bud pointer-events-none fixed z-(--z-tooltip) size-(--size-icon-sm) -translate-1/2 rounded-full bg-muted" style={{ left: bud.x, top: bud.y, "--bud-x": `${bud.dx}px`, "--bud-y": `${bud.dy}px`, } as React.CSSProperties} onAnimationEnd={clearBud} />, document.body ) : null} </ComboboxPrimitive.Chips> ) } /** A chosen value in a multiple Combobox. Pass `value` so it knows when it's being removed. */ function ComboboxChip({ className, value, children, ...props }: ComboboxPrimitive.Chip.Props & { value?: unknown }) { const ref = React.useRef<HTMLDivElement>(null) const { melting, input, sendBud } = useComboboxState() const isMelting = melting !== null && melting === value React.useEffect(() => { if (!isMelting || !ref.current || !input.current) return const chip = ref.current.getBoundingClientRect() const field = input.current.getBoundingClientRect() sendBud( { x: chip.left + chip.width / 2, y: chip.top + chip.height / 2 }, { x: field.left + field.width / 2, y: field.top + field.height / 2 } ) }, [isMelting, input, sendBud]) return ( <ComboboxPrimitive.Chip ref={ref} render={<Chip kind="input" melting={isMelting} />} className={className} {...props} > {children} </ComboboxPrimitive.Chip> ) } function ComboboxChipRemove(props: ComboboxPrimitive.ChipRemove.Props) { return <ComboboxPrimitive.ChipRemove render={<ChipRemove />} {...props} /> } export { Combobox, ComboboxField, ComboboxClear, ComboboxChip, ComboboxChipRemove, ComboboxChips, ComboboxValue, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, }components/ui/search.tsxsearch
components/ui/search.tsx"use client" import * as React from "react" import { SearchIcon, XIcon } from "lucide-react" import { cn } from "cn" import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxField, ComboboxInput, ComboboxItem, ComboboxList, } from "@/components/ui/combobox" /* Search (Material 3 "Search"): a search field whose suggestions grow out of it. Matching characters turn bold as they match; the highlight slides between suggestions. Picking one calls onSelect. For free text, listen to onQueryChange and run your own search. */ function SearchHighlight({ text, query }: { text: string; query: string }) { const needle = query.trim().toLowerCase() const at = needle ? text.toLowerCase().indexOf(needle) : -1 if (at === -1) return <>{text}</> return ( <> {text.slice(0, at)} <mark className="search-match bg-transparent font-semibold text-foreground">{text.slice(at, at + needle.length)}</mark> {text.slice(at + needle.length)} </> ) } function Search({ items, placeholder = "Search", label = "Search", onSelect, onQueryChange, empty = "No results", className, }: { items: string[] placeholder?: string label?: string onSelect?: (item: string) => void onQueryChange?: (query: string) => void empty?: React.ReactNode className?: string }) { const [query, setQuery] = React.useState("") return ( <div data-slot="search" className={cn("w-full", className)}> <Combobox items={items} inputValue={query} onInputValueChange={(next) => { setQuery(next) onQueryChange?.(next) }} onValueChange={(next) => { if (typeof next === "string") onSelect?.(next) }} > <ComboboxField> <SearchIcon aria-hidden className="pointer-events-none absolute start-(--field-padding-x) size-(--size-icon-md) text-(--field-placeholder)" /> <ComboboxInput aria-label={label} placeholder={placeholder} className="ps-(--search-padding-start) pe-(--search-padding-end)" /> {query ? ( <button type="button" aria-label="Clear search" onClick={() => { setQuery("") onQueryChange?.("") }} className="search-clear liquid-press absolute end-2 inline-flex size-6 items-center justify-center rounded-(--shape-full) text-(--field-action-label) outline-none hover:bg-(--field-action-container-hover) hover:text-(--field-action-label-hover) active:bg-(--field-action-container-pressed) focus-visible:shadow-(--focus-ring)" > <XIcon className="size-(--size-icon-sm)" /> </button> ) : null} </ComboboxField> <ComboboxContent> <ComboboxEmpty>{empty}</ComboboxEmpty> <ComboboxList> {(item: string) => ( <ComboboxItem key={item} value={item} className="search-suggestion"> <SearchIcon aria-hidden className="me-2 size-(--size-icon-sm) shrink-0 text-ink-subtle" /> <span className="truncate text-muted-foreground"> <SearchHighlight text={item} query={query} /> </span> </ComboboxItem> )} </ComboboxList> </ComboboxContent> </Combobox> </div> ) } export { Search, SearchHighlight }components/ui/command.tsxcommand
components/ui/command.tsx"use client" import * as React from "react" import { SearchIcon } from "lucide-react" import { cn } from "cn" import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog" import { Kbd } from "@/components/ui/kbd" import { SearchHighlight } from "@/components/ui/search" import { tokenMs } from "@/lib/motion/token-ms" import { motionLevel } from "@/lib/overlay" /* Command palette (⌘K): search and run commands. Results filter as you type and the remaining rows slide into place (FLIP); one highlight pill moves with the arrow keys. Running an item pops it, then the palette closes. CommandDialog wraps it in a Dialog and binds ⌘K / Ctrl+K. */ type CommandItem = { id: string; label: string; group?: string; shortcut?: string; icon?: React.ReactNode; onRun: () => void } function Command({ items, placeholder = "Type a command or search…", onDone, className, }: { items: CommandItem[] placeholder?: string onDone?: () => void className?: string }) { const [query, setQuery] = React.useState("") const [active, setActive] = React.useState(0) const listRef = React.useRef<HTMLDivElement>(null) const places = React.useRef(new Map<string, number>()) const pillRef = React.useRef<HTMLSpanElement>(null) const id = React.useId() const results = items.filter((item) => item.label.toLowerCase().includes(query.trim().toLowerCase())) const groups = [...new Set(results.map((item) => item.group ?? ""))] const ordered = groups.flatMap((group) => results.filter((item) => (item.group ?? "") === group)) const current = ordered[Math.min(active, ordered.length - 1)] // FLIP: rows slide to their new place when the results change. React.useLayoutEffect(() => { const list = listRef.current if (!list) return const rows = [...list.querySelectorAll<HTMLElement>("[data-slot=command-item]")] const next = new Map<string, number>() const level = motionLevel(list) for (const row of rows) { const key = row.dataset.id ?? "" const top = row.offsetTop const before = places.current.get(key) next.set(key, top) if (level === "still" || before === undefined || Math.abs(before - top) < 1) continue row.animate([{ transform: `translateY(${before - top}px)` }, { transform: "none" }], { duration: tokenMs("--duration-fast", list), easing: getComputedStyle(list).getPropertyValue("--ease-sheet").trim() || "ease", }) } places.current = next const pill = pillRef.current const row = current ? list.querySelector<HTMLElement>(`[data-id="${current.id}"]`) : null if (pill && row) { pill.style.top = `${row.offsetTop}px` pill.style.height = `${row.offsetHeight}px` pill.style.opacity = "1" row.scrollIntoView({ block: "nearest" }) } else if (pill) pill.style.opacity = "0" }) function run(item: CommandItem) { const row = listRef.current?.querySelector<HTMLElement>(`[data-id="${item.id}"]`) row?.classList.add("command-run") window.setTimeout(() => { item.onRun() onDone?.() }, motionLevel(row ?? null) === "still" ? 0 : tokenMs("--duration-fast")) } return ( <div data-slot="command" className={cn("flex flex-col", className)}> <div className="flex items-center gap-2 px-3"> <SearchIcon aria-hidden className="size-(--size-icon-md) text-(--field-placeholder)" /> <input autoFocus role="combobox" aria-expanded aria-controls={`${id}-list`} aria-activedescendant={current ? `${id}-${current.id}` : undefined} aria-label="Command" value={query} placeholder={placeholder} onChange={(event) => { setQuery(event.target.value) setActive(0) }} onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault() setActive((i) => Math.min(ordered.length - 1, i + 1)) } else if (event.key === "ArrowUp") { event.preventDefault() setActive((i) => Math.max(0, i - 1)) } else if (event.key === "Enter" && current) { event.preventDefault() run(current) } }} className="h-(--command-input-height) flex-1 bg-transparent text-sm outline-none placeholder:text-(--field-placeholder)" /> </div> <div ref={listRef} id={`${id}-list`} role="listbox" aria-label="Results" className="relative max-h-(--command-list-height) overflow-y-auto p-(--menu-padding)"> <span ref={pillRef} aria-hidden className="command-pill pointer-events-none absolute inset-x-(--menu-padding) rounded-(--menu-item-corner) bg-(--menu-item-highlight) opacity-0" /> {ordered.length === 0 ? <p className="isotope-rise py-6 text-center text-sm text-muted-foreground">No results.</p> : null} {groups.map((group) => ( <div key={group || "none"} role="group" aria-label={group || undefined}> {group ? <p className="px-2 pt-2 pb-1 text-caption text-ink-subtle">{group}</p> : null} {results .filter((item) => (item.group ?? "") === group) .map((item) => ( <div key={item.id} id={`${id}-${item.id}`} data-id={item.id} data-slot="command-item" role="option" aria-selected={current?.id === item.id} onPointerMove={() => setActive(ordered.indexOf(item))} onClick={() => run(item)} className="relative z-[1] flex h-(--menu-item-height) cursor-default items-center gap-inline-sm rounded-(--menu-item-corner) px-(--menu-item-padding-x) text-sm [&_svg]:size-(--size-icon-sm) [&_svg]:text-ink-subtle" > {item.icon} <span className="flex-1 truncate"> <SearchHighlight text={item.label} query={query} /> </span> {item.shortcut ? <Kbd>{item.shortcut}</Kbd> : null} </div> ))} </div> ))} </div> </div> ) } function CommandDialog({ items, open, onOpenChange, hotkey = "k", }: { items: CommandItem[] open: boolean onOpenChange: (open: boolean) => void hotkey?: string }) { React.useEffect(() => { const onKey = (event: KeyboardEvent) => { if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === hotkey) { event.preventDefault() onOpenChange(!open) } } window.addEventListener("keydown", onKey) return () => window.removeEventListener("keydown", onKey) }, [open, onOpenChange, hotkey]) return ( <Dialog open={open} onOpenChange={onOpenChange}> <DialogContent size="md" className="p-0 pt-2"> <DialogTitle className="sr-only">Command palette</DialogTitle> <Command items={items} onDone={() => onOpenChange(false)} /> </DialogContent> </Dialog> ) } export { Command, CommandDialog } export type { CommandItem }
Imports
What the examples on this page import:
import { CopyIcon, FileIcon, MoonIcon, PlusIcon, SettingsIcon, TrashIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Calendar, type CalendarRange } from "@/components/ui/calendar"
import { Carousel } from "@/components/ui/carousel"
import { CommandDialog, type CommandItem } from "@/components/ui/command"
import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from "@/components/ui/context-menu"
import { DatePicker } from "@/components/ui/date-picker"
import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut } from "@/components/ui/dropdown-menu"
import { Kbd, KbdGroup } from "@/components/ui/kbd"
import { Menubar, MenubarMenu, MenubarTrigger } from "@/components/ui/menubar"
import { Search } from "@/components/ui/search"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { TimePicker } from "@/components/ui/time-picker"Anatomy
- 1Input · --command-input-height.
- 2Groups · Optional headings.
- 3Item · Menu item tokens; icon, label, shortcut.
- 4Highlight · Menu highlight pill.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
items | { id, label, group?, shortcut?, icon?, onRun }[] | — | Commands. |
CommandDialog open / onOpenChange | boolean | — | Controlled dialog. |
hotkey | string | "k" | With ⌘ or Ctrl. |
Tokens
Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.
| Token | Points to | Light | Dark |
|---|---|---|---|
--menu-container | var(--surface-container-raised) | oklch(1 0 0) | oklch(0.22 0 0) |
--menu-corner | var(--shape-md) | 14px | same |
--menu-padding | var(--space-inset-overlay) | 8px | same |
--menu-elevation | var(--elevation-2) | 0 1px 1px -0.5px oklch(0.22 0.01 260 / 6%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 6%), 0 6px 6px -3px oklch(0.22 0.01 260 / 6%), 0 12px 12px -6px oklch(0.22 0.01 260 / 6%), 0 24px 24px -12px oklch(0.22 0.01 260 / 6%) | 0 4px 12px oklch(0 0 0 / 40%), 0 12px 28px oklch(0 0 0 / 35%) |
--menu-item-height | var(--size-row-sm) | 32px | same |
--menu-item-padding-x | var(--space-inset-control-x-sm) | 8px | same |
--menu-item-corner | var(--shape-sm) | 8px | same |
--menu-item-highlight | var(--color-bg-hover) | oklch(0.965 0.005 95) | oklch(0.22 0 0) |
--menu-item-label-disabled | var(--color-fg-disabled) | oklch(0.62 0.01 95) | oklch(0.53 0 0) |
--menu-item-danger | var(--color-danger-fg) | oklch(0.48 0.18 25) | oklch(0.78 0.14 22) |
--menu-min-width | var(--layout-menu-min) | 180px | same |
--command-input-height | var(--size-control-lg) | 48px | same |
--command-list-height | calc(var(--menu-item-height) * 9) | calc(var(--menu-item-height) * 9) | same |
Motion
| Trigger | What happens | Tokens |
|---|---|---|
| Filter | Remaining rows slide to their new place (FLIP). | --duration-fast, --ease-sheet |
| Run | The item pops, then the palette closes. | --duration-fast |
Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.
Accessibility
- Combobox input with aria-activedescendant on a listbox.
- Arrows move, Enter runs, Escape closes.
Usage
Do
- Use for power users and quick switching.
Don’t
- Don't make it the only way to reach an action.
Code
"use client"
import * as React from "react"
import { SearchIcon } from "lucide-react"
import { cn } from "cn"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Kbd } from "@/components/ui/kbd"
import { SearchHighlight } from "@/components/ui/search"
import { tokenMs } from "@/lib/motion/token-ms"
import { motionLevel } from "@/lib/overlay"
/*
Command palette (⌘K): search and run commands. Results filter as you type
and the remaining rows slide into place (FLIP); one highlight pill moves
with the arrow keys. Running an item pops it, then the palette closes.
CommandDialog wraps it in a Dialog and binds ⌘K / Ctrl+K.
*/
type CommandItem = { id: string; label: string; group?: string; shortcut?: string; icon?: React.ReactNode; onRun: () => void }
function Command({
items,
placeholder = "Type a command or search…",
onDone,
className,
}: {
items: CommandItem[]
placeholder?: string
onDone?: () => void
className?: string
}) {
const [query, setQuery] = React.useState("")
const [active, setActive] = React.useState(0)
const listRef = React.useRef<HTMLDivElement>(null)
const places = React.useRef(new Map<string, number>())
const pillRef = React.useRef<HTMLSpanElement>(null)
const id = React.useId()
const results = items.filter((item) => item.label.toLowerCase().includes(query.trim().toLowerCase()))
const groups = [...new Set(results.map((item) => item.group ?? ""))]
const ordered = groups.flatMap((group) => results.filter((item) => (item.group ?? "") === group))
const current = ordered[Math.min(active, ordered.length - 1)]
// FLIP: rows slide to their new place when the results change.
React.useLayoutEffect(() => {
const list = listRef.current
if (!list) return
const rows = [...list.querySelectorAll<HTMLElement>("[data-slot=command-item]")]
const next = new Map<string, number>()
const level = motionLevel(list)
for (const row of rows) {
const key = row.dataset.id ?? ""
const top = row.offsetTop
const before = places.current.get(key)
next.set(key, top)
if (level === "still" || before === undefined || Math.abs(before - top) < 1) continue
row.animate([{ transform: `translateY(${before - top}px)` }, { transform: "none" }], {
duration: tokenMs("--duration-fast", list),
easing: getComputedStyle(list).getPropertyValue("--ease-sheet").trim() || "ease",
})
}
places.current = next
const pill = pillRef.current
const row = current ? list.querySelector<HTMLElement>(`[data-id="${current.id}"]`) : null
if (pill && row) {
pill.style.top = `${row.offsetTop}px`
pill.style.height = `${row.offsetHeight}px`
pill.style.opacity = "1"
row.scrollIntoView({ block: "nearest" })
} else if (pill) pill.style.opacity = "0"
})
function run(item: CommandItem) {
const row = listRef.current?.querySelector<HTMLElement>(`[data-id="${item.id}"]`)
row?.classList.add("command-run")
window.setTimeout(() => {
item.onRun()
onDone?.()
}, motionLevel(row ?? null) === "still" ? 0 : tokenMs("--duration-fast"))
}
return (
<div data-slot="command" className={cn("flex flex-col", className)}>
<div className="flex items-center gap-2 px-3">
<SearchIcon aria-hidden className="size-(--size-icon-md) text-(--field-placeholder)" />
<input
autoFocus
role="combobox"
aria-expanded
aria-controls={`${id}-list`}
aria-activedescendant={current ? `${id}-${current.id}` : undefined}
aria-label="Command"
value={query}
placeholder={placeholder}
onChange={(event) => {
setQuery(event.target.value)
setActive(0)
}}
onKeyDown={(event) => {
if (event.key === "ArrowDown") {
event.preventDefault()
setActive((i) => Math.min(ordered.length - 1, i + 1))
} else if (event.key === "ArrowUp") {
event.preventDefault()
setActive((i) => Math.max(0, i - 1))
} else if (event.key === "Enter" && current) {
event.preventDefault()
run(current)
}
}}
className="h-(--command-input-height) flex-1 bg-transparent text-sm outline-none placeholder:text-(--field-placeholder)"
/>
</div>
<div ref={listRef} id={`${id}-list`} role="listbox" aria-label="Results" className="relative max-h-(--command-list-height) overflow-y-auto p-(--menu-padding)">
<span ref={pillRef} aria-hidden className="command-pill pointer-events-none absolute inset-x-(--menu-padding) rounded-(--menu-item-corner) bg-(--menu-item-highlight) opacity-0" />
{ordered.length === 0 ? <p className="isotope-rise py-6 text-center text-sm text-muted-foreground">No results.</p> : null}
{groups.map((group) => (
<div key={group || "none"} role="group" aria-label={group || undefined}>
{group ? <p className="px-2 pt-2 pb-1 text-caption text-ink-subtle">{group}</p> : null}
{results
.filter((item) => (item.group ?? "") === group)
.map((item) => (
<div
key={item.id}
id={`${id}-${item.id}`}
data-id={item.id}
data-slot="command-item"
role="option"
aria-selected={current?.id === item.id}
onPointerMove={() => setActive(ordered.indexOf(item))}
onClick={() => run(item)}
className="relative z-[1] flex h-(--menu-item-height) cursor-default items-center gap-inline-sm rounded-(--menu-item-corner) px-(--menu-item-padding-x) text-sm [&_svg]:size-(--size-icon-sm) [&_svg]:text-ink-subtle"
>
{item.icon}
<span className="flex-1 truncate">
<SearchHighlight text={item.label} query={query} />
</span>
{item.shortcut ? <Kbd>{item.shortcut}</Kbd> : null}
</div>
))}
</div>
))}
</div>
</div>
)
}
function CommandDialog({
items,
open,
onOpenChange,
hotkey = "k",
}: {
items: CommandItem[]
open: boolean
onOpenChange: (open: boolean) => void
hotkey?: string
}) {
React.useEffect(() => {
const onKey = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === hotkey) {
event.preventDefault()
onOpenChange(!open)
}
}
window.addEventListener("keydown", onKey)
return () => window.removeEventListener("keydown", onKey)
}, [open, onOpenChange, hotkey])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent size="md" className="p-0 pt-2">
<DialogTitle className="sr-only">Command palette</DialogTitle>
<Command items={items} onDone={() => onOpenChange(false)} />
</DialogContent>
</Dialog>
)
}
export { Command, CommandDialog }
export type { CommandItem }