Command Palette

One search for every page, action and record, opened with Cmd+K (Ctrl+K off a Mac) and run by a person or an agent.

Source
$npx @dinachi/cli@latest add command-palette

label
recent
CommandPalettePreview
disabled

Usage

import { FileText, Receipt } from "lucide-react"
import {
  CommandPalette,
  CommandPaletteBody,
  CommandPaletteContent,
  CommandPaletteInput,
  CommandPaletteList,
  CommandPalettePreview,
  CommandPaletteTrigger,
  type CommandItem,
} from "@/components/ui/command-palette"

const commands: CommandItem[] = [
  { id: "orders", label: "Orders", group: "Pages", kind: "Page", icon: <FileText />, shortcut: "G O" },
  {
    id: "order-4821",
    label: "Order #4821",
    description: "Ada Okafor",
    group: "Orders",
    kind: "Order",
    icon: <Receipt />,
    actions: [
      { id: "open", label: "Open order" },
      { id: "refund", label: "Refund" },
    ],
  },
]

export function Search({ run }: { run: (id: string, action?: string) => void }) {
  return (
    <CommandPalette items={commands} recent={["order-4821"]} onRun={(item, action) => run(item.id, action?.id)}>
      <CommandPaletteTrigger />
      <CommandPaletteContent>
        <CommandPaletteInput />
        <CommandPaletteBody>
          <CommandPaletteList />
          <CommandPalettePreview placeholder="Type to search pages and orders." />
        </CommandPaletteBody>
      </CommandPaletteContent>
    </CommandPalette>
  )
}

Examples

A hotel back office: recent items, groups, a preview with each record's actions, and Switch property as a sub-list. On a phone it fills the screen with the search at the bottom.
import { BedDouble, FileText, Receipt, Zap } from 'lucide-react';
import {
  CommandPalette,
  CommandPaletteBody,
  CommandPaletteContent,
  CommandPaletteInput,
  CommandPaletteList,
  CommandPalettePreview,
  CommandPaletteTrigger,
  type CommandItem,
} from '@/components/ui/command-palette';

const commands: CommandItem[] = [
  { id: 'orders', label: 'Orders', group: 'Pages', kind: 'Page', icon: <FileText />, shortcut: 'G O' },
  { id: 'refund', label: 'Refund an order', group: 'Actions', kind: 'Action', icon: <Zap /> },
  {
    id: 'property', label: 'Switch property', group: 'Actions', icon: <Zap />, shortcut: '⌘ P',
    items: [
      { id: 'saltmarsh', label: 'Saltmarsh Hotel', description: 'Whitstable' },
      { id: 'harbour', label: 'Harbour House', description: 'Deal' },
    ],
  },
  {
    id: 'order-4821', label: 'Order #4821', description: 'Ada Okafor', group: 'Orders', kind: 'Order',
    icon: <Receipt />, meta: '£204.00',
    actions: [
      { id: 'open', label: 'Open order' },
      { id: 'refund', label: 'Refund' },
      { id: 'email', label: 'Email guest' },
    ],
  },
  { id: 'room-214', label: 'Room 214', description: 'Sea View Double', group: 'Rooms', kind: 'Room', icon: <BedDouble /> },
];

export function Search({ onRun }: { onRun: (item: CommandItem, actionId?: string) => void }) {
  return (
    <CommandPalette items={commands} recent={['order-4821']} onRun={(item, action) => onRun(item, action?.id)}>
      <CommandPaletteTrigger />
      <CommandPaletteContent>
        <CommandPaletteInput />
        <CommandPaletteBody>
          <CommandPaletteList />
          <CommandPalettePreview placeholder="Type to search pages, actions, orders and rooms.">
            {(item) => <p className="text-muted-foreground">{item.description}</p>}
          </CommandPalettePreview>
        </CommandPaletteBody>
      </CommandPaletteContent>
    </CommandPalette>
  );
}

Notes

The item shape

CommandItem, CommandAction, CommandRunDetails and filterCommands live in command-items, which dinachi add command-palette installs alongside, so other command surfaces can share them without the palette. An item has id, label, and optionally description, group, kind, icon, shortcut, meta, keywords, disabled, actions and items. All of it is plain data except icon and meta, which are React nodes: a list from a server or a model sends the rest and the app adds those two. The order of actions is part of the contract: actions[0] is what Enter runs, actions[1] what Mod+Enter runs, and the rest are reached from the preview. items makes it a sub-list that opens in place. Keep app logic in onRun rather than on the items.

What stays in your app

The palette lays out a record's name and actions. Its fields, such as an order's status and amount, come from CommandPalettePreview's children. What running does, and any toast after it, is onRun's job. shortcut on an item is a hint; binding it is up to you.

No motion

It is opened from the keyboard many times a day, so it never animates: no scale, fade or backdrop fade, and the highlight and sub-lists change at once. CommandPaletteContent uses Base UI's dialog parts directly, not the Dialog component, so it carries no transition. The phone screen appears at once too, as the keyboard already rises under it.

While the search is empty

With recent or suggested set, an empty search shows the recent items, then the suggested ones, up to idleLimit rows, rather than the whole list. Typing searches everything.

Long lists

Every search filters all the items, but at most limit rows render, 50 by default: about five screens of the list, and few enough that each keystroke stays quick with thousands of items. Past that, typing narrows faster than scrolling. The status says how many matched, such as 50 of 312 results, and the agent's search returns the same rows the list shows. Moving the highlight re-renders only the two rows it leaves and reaches, and the preview.

On a phone

Below 640px it fills the screen with the field at the bottom, above the keyboard, and the best match just above the field. The arrows move the way they point, so Up goes away from the field. A record with more than one action opens a detail screen with the keyboard down, focus on Back and the list hidden from assistive tech; Back returns focus to the field. Rows, the sub-list chip, Back and Cancel are 44px or taller.

In these docs

The site's search holds Cmd+K, so the demos here open from their button.

API

items
agent
CommandItem[]
Every command, in the order groups and rows are listed. The agent reads them while closed.
recentstring[]
Ids listed first, under Recent, while the search is empty.
recentLabelstring = "Recent"
The heading over recent items.
suggestedstring[]
Ids listed after the recent ones, under their own groups, while the search is empty.
idleLimitnumber = 8
How many rows show while the search is empty. Applies once recent or suggested is set; without either, the list shows up to limit.
limitnumber = 50
The most rows a search, a sub-list or the full list shows. Typing narrows it. Infinity lifts it.
onRun
agent
(item, action, details) => void
Runs a picked item with its first action, or the one asked for. details.reason is item-press, action-press or keyboard. details.cancel() keeps the palette open.
openboolean
Controlled open state.
defaultOpenboolean = false
Starts open when uncontrolled.
onOpenChange
agent
(open, details) => void
Runs for people and agents. details.cancel() refuses the change.
valuestring
Controlled search text.
defaultValuestring = ""
Starting search text.
onValueChange
agent
(value, details) => void
Runs as the search changes, from either side.
shortcutstring | false = "k"
The key that toggles it with Cmd on a Mac and Ctrl elsewhere. It matches the physical key on other layouts. false turns it off and hides the trigger's hint.
label
agent
string = "Command palette"
Names the dialog and the field. The agent finds the palette by it.
filter(item, query) => boolean = filterCommands
Decides what matches. The default needs every word in the label, description or keywords.
disabled
agent
boolean = false
Blocks the trigger, the shortcut and the agent.

Agent

Inside an AgentProvider, it appears in agent.snapshot() as combobox.

Reads

label

The palette's label.

open

True while the palette is showing.

value

The search text, while open.

items

Every command on the current level while closed, or the matches while open.

disabled

True when the palette is blocked.

Actions

open() / close()

Opens or closes the palette.

search("refund")

Opens it, types the text, returns the matches shown, up to limit, with their group and actions.

select("Order #4821", "Refund")

Runs a command, with its first action or the one named, and closes if open. A sub-list opens and returns its commands.

back()

Inside a sub-list, steps back out and returns the level above.

Opening and closing run through onOpenChange, the search through onValueChange and running through onRun. isAgentChange(details) is true for each; details.cancel() refuses it and the agent is told. disabled refuses everything. The agent sees a closed palette through its trigger, so render CommandPaletteTrigger for an agent to find it before it opens.

await agent.act({
  steps: [
    { ref: "Command palette", action: "search", args: ["4821"] },
    { ref: "Command palette", action: "select", args: ["Order #4821", "Refund"] },
  ],
})

Accessibility

  • The palette is a modal dialog named by label; focus moves to the search and returns to the trigger on close.
  • The search has role combobox and the results are a listbox of options; aria-activedescendant keeps focus in the field, and the highlighted option has aria-selected.
  • The listbox is named after the label, and a polite status counts the matches as you type, as 50 of 312 results when limit cuts the list.
  • Opening a sub-list names the search after it and announces it, as Switch property, 3 options.
  • On a phone, the detail screen's Back is named Back to search. Back and Cancel mix the info colour with the text colour so they pass 4.5:1 in both themes.
  • Groups are labelled by their headings. On a phone they are reversed visually only, so reading order stays best match first.
  • Matched words are marked with mark, and shortcuts are kbd.