Skip to content
Nacre
Color palette
中文

CommandPalette

experimentalCommandPalette · CommandTriggerOpen in playground
CommandPalette
Runs the real component in your browser.

A modal search field over grouped commands, opened with ⌘K: it filters by label and keywords, shows each command’s shortcut at the end of its row and says so when nothing matches; CommandTrigger is the entry point that looks like a search field. Where the commands come from and what they do stay in the app.

Status: experimental · Components: CommandPalette, CommandTrigger

import { CommandPalette, CommandTrigger } from 'nacre'

Put CommandTrigger in the middle of the title bar; pressing it opens the palette. CommandPalette is controlled (open + onClose); items carry an id, label, group, keywords and shortcut, and onSelect gets the chosen item back (the app can carry its run function on it). Choosing closes it and returns focus first, then calls back.

import { Text, View, signal } from 'nsh'
import type { ViewRef } from 'nsh'
import { CommandPalette, CommandTrigger, TEXT_SIZE } from 'nacre'
import type { CommandPaletteItem } from 'nacre'
const COMMANDS = (): CommandPaletteItem[] => [
{ id: 'go.chat', label: 'Chats', group: 'Go to', shortcut: 'mod+1' },
{ id: 'go.dashboard', label: 'Dashboard', group: 'Go to', shortcut: 'mod+2' },
{ id: 'cmd.status', label: 'Change status', group: 'Commands', keywords: ['online', 'status'], shortcut: 'mod+shift+s' },
{ id: 'cmd.refresh', label: 'Refresh chat list', group: 'Commands', keywords: ['reload'] },
{ id: 'cmd.export', label: 'Export history (no permission)', group: 'Commands', disabled: true },
]
export function CommandPaletteUsage() {
const open = signal(false)
const last = signal('')
let trigger: ViewRef | undefined
return (
<View class="flex-row flex-wrap items-center gap-3">
<CommandTrigger
testID="demo-cmdp-trigger"
label="Search"
accessibilityLabel="Command palette"
shortcut="mod+k"
viewRef={(node) => (trigger = node)}
onPress={() => open.set(true)}
/>
<Text testID="demo-cmdp-last" class={`${TEXT_SIZE.small} text-muted-foreground`}>{`$Last run: ${last() || '—'}`}</Text>
<CommandPalette
testID="demo-cmdp"
open={open()}
onClose={() => open.set(false)}
returnFocus={() => trigger}
placeholder="Search chats and commands…"
accessibilityLabel="Command palette"
items={COMMANDS()}
onSelect={(item) => last.set(item.id)}
/>
</View>
)
}

The list is capped at 360pt and scrolls inside the palette; while it scrolls, rows leave 10pt at the end for the overlay scrollbar so the shortcuts stay clear of it.

import { Text, View, signal } from 'nsh'
import { CommandPalette, CommandTrigger, TEXT_SIZE } from 'nacre'
import type { CommandPaletteItem } from 'nacre'
export function CommandPaletteLong() {
const open = signal(false)
const last = signal('')
const items: CommandPaletteItem[] = Array.from({ length: 18 }, (_, i) => ({
id: `cmd.${i + 1}`,
label: `$Command ${i + 1}`,
group: i < 9 ? 'Frequent' : 'More',
shortcut: i < 9 ? `mod+shift+${i + 1}` : `mod+alt+${i - 8}`,
}))
return (
<View class="flex-row flex-wrap items-center gap-3">
<CommandTrigger testID="demo-cmdp-long-trigger" label="All commands" onPress={() => open.set(true)} width={200} />
<Text class={`${TEXT_SIZE.small} text-muted-foreground`}>{`$Last run: ${last() || '—'}`}</Text>
<CommandPalette
testID="demo-cmdp-long"
open={open()}
onClose={() => open.set(false)}
items={items}
placeholder="Search commands…"
accessibilityLabel="All commands"
onSelect={(item) => last.set(item.id)}
/>
</View>
)
}

Type C001 to find Lin Jiayi by ID and preview the highlighted result. As in cmdk, shouldFilter={false} leaves matching and ordering to the source. Instead of cmdk’s composable list, NSH handles keyboard navigation; renderItem customizes rows and renderPreview supplies a read-only preview. Use loading while fetching; resolveSelection can return a final item or null to stay open. A query change discards pending selections. Reference: https://github.com/dip/cmdk#parts-and-styling

import { Text, View, computed, signal } from 'nsh'
import { CommandPalette, CommandTrigger, TEXT_SIZE } from 'nacre'
import type { CommandPaletteItem } from 'nacre'
const COMMANDS = (): CommandPaletteItem[] => [
{ id: 'go.chat', label: 'Chats', group: 'Go to', shortcut: 'mod+1' },
{ id: 'go.dashboard', label: 'Dashboard', group: 'Go to', shortcut: 'mod+2' },
{ id: 'cmd.status', label: 'Change status', group: 'Commands', keywords: ['online', 'status'], shortcut: 'mod+shift+s' },
{ id: 'cmd.refresh', label: 'Refresh chat list', group: 'Commands', keywords: ['reload'] },
{ id: 'cmd.export', label: 'Export history (no permission)', group: 'Commands', disabled: true },
]
export function CommandPaletteQuery() {
const open = signal(false)
const query = signal('')
const last = signal('')
const chats = [
{ id: 'C001', name: 'Lin Jiayi' },
{ id: 'C002', name: 'Chen Zhiyuan' },
]
const items = computed<CommandPaletteItem[]>(() => {
const q = query().trim().toLowerCase()
const hits = q ? chats.filter((chat) => `${chat.name} ${chat.id}`.toLowerCase().includes(q)).map((chat) => ({ id: chat.id, label: chat.name, group: 'Chats' })) : []
return [...hits, ...COMMANDS().filter((item) => [item.label, ...(item.keywords ?? [])].some((text) => text.toLowerCase().includes(q)))]
})
return (
<View class="flex-row flex-wrap items-center gap-3">
<CommandTrigger testID="demo-cmdp-query-trigger" label="Search chats" onPress={() => open.set(true)} width={200} />
<Text class={`${TEXT_SIZE.small} text-muted-foreground`}>{`$Last run: ${last() || '—'}`}</Text>
<CommandPalette
testID="demo-cmdp-query"
open={open()}
onClose={() => {
open.set(false)
query.set('')
}}
query={query()}
onQueryChange={(q) => query.set(q)}
items={items()}
shouldFilter={false}
renderPreview={(item) => chats.some((chat) => chat.id === item.id) ? <Text class={`p-3 ${TEXT_SIZE.body} text-popover-foreground`}>{`${item.label} · ${item.id}`}</Text> : null}
placeholder="Type a name or ID"
accessibilityLabel="Search chats"
emptyText="No chats with this customer"
onSelect={(item) => last.set(item.id)}
/>
</View>
)
}
Key Action
↑ ↓ Move the current row between commands, skipping disabled ones and wrapping at the ends
Return Run the current row: closes first, then calls onSelect
Esc Clears the query first; with an empty query closes and returns focus to where it was before opening (or returnFocus)
Tab Stays inside the palette (modal)
  • The palette is a modal dialog: while open, screen readers and Tab stay inside it, and on close focus returns to the view focused before opening, or to returnFocus when given.
  • The list reads as a listbox, announcing the current row as the arrow keys move it; accessibilityLabel names both the palette and its search field.
  • CommandTrigger is a button, not a text field: its screen reader name defaults to label; in the title bar, name it “Command palette”.

Do

  • Write each command’s shortcut in items (shown only; the app binds it)
  • Add synonyms and English names as keywords
  • Use CommandTrigger as the entry point, with the shortcut on its keycap
  • Pass returnFocus when focus should go back to the entry point

Don’t

  • Put forms or multi-step flows in the palette (use Dialog)
  • Use it to pick a form value from fixed options (use Combobox)
  • Put the command logic in the component (onSelect gets the chosen item to run)

Property descriptions follow the Chinese source comments.

Prop Type Default Description
open * boolean — 开着吗(受控):关时整块卸载
query string — 搜索词(受控);不给时面板自己管,每次打开都是空的
onQueryChange (query: string) => void — 输入或 Esc 清空搜索词时回调;受控时在这里改 query
items * readonly T[] — 全部可选项,按显示顺序;面板按标签与 keywords 过滤(不分大小写),没有命中的组整组不显示
shouldFilter boolean — false:按调用方给的顺序展示全部结果,不再按搜索词过滤
loading boolean — 搜索进行中,搜索框末尾显示加载提示
renderItem (item: T) => JSX.Element | null — 自定义行内容;返回 null 时仍用默认的标签、快捷键
renderPreview (item: T) => JSX.Element | null — 高亮项的只读预览;返回 null 时不占用预览面
resolveSelection (item: T) => T | null | Promise<T | null> — 执行前决定最终选项;返回 null 保持打开。换词、另选或关闭会作废先前的等待
onSelect * (item: T) => void — 选了一项(回车、点按):回传 items 里的那一项本身(应用可以在项上带执行函数)。 面板在当拍取出这一项,再收起(onClose)、焦点归位,最后回调:命令自己挪焦点不会被抢回去,应用也不必在面板卸载后再查条目
onClose * () => void — 要关:Esc(搜索词为空时;有词时 Esc 先清空)、点面板外、选完
returnFocus () => ViewRef | undefined — 收起后把键盘焦点交给谁;不给时交还打开前有焦点的视图(平台的模态层自己还)
placeholder string — 搜索框的占位
accessibilityLabel string — 读屏对面板(也是对搜索框)的称呼
emptyText string — 没有命中时的一句话,默认「没有匹配的结果」
width number — 宽度(pt),默认 520
testID string — 面板的 testID(app.type 打字落到面板里的搜索框)

* required

Prop Type Default Description
label * string — 框里的提示字(「全局搜索」),也是默认读屏名
shortcut string — 右侧键帽显示的快捷键,按 keymap 的写法("mod+k")
onPress * () => void — 按下(点按、空格、回车):打开命令面板
width number 264 宽度(pt),默认 264
accessibilityLabel string — 读屏名,默认 label;它其实是打开命令面板的按钮,可以写「命令面板」
testID string — 按钮的 testID
viewRef (node: ViewRef) => void — 关闭命令面板后焦点要回到这里时,把 ref 交给 CommandPalette 的 returnFocus

* required