PatternsNavigation
CommandPalette
@mox-hub/patterns 模式 · Navigation · canonical
command-palette@mox-hub/patternsNavigationcanonicalsrc/components/command-palette.tsx变体演示command-palette
Props API
| Prop | 类型 | 默认值 | 说明 |
|---|---|---|---|
| open* | boolean | — | — |
| onOpenChange* | (open: boolean) => void | — | — |
| items* | CommandItem[] | — | — |
| onSelect* | (item: CommandItem) => void | — | — |
| recentIds* | string[] | — | — |
| placeholder* | string | — | — |
| emptyLabel* | string | — | — |
| labels* | Partial<CommandPaletteLabels> | — | — |
源码
/**
* CommandPalette —— 受控的全局命令面板(搜索 / 分组 / 最近使用 / 快捷键)。
*
* 搜索、过滤与键盘导航全部交给 ui/command(base-ui Autocomplete),
* 弹层语义与 Esc / 遮罩关闭交给 ui/dialog;本组件只做数据分组与渲染。
*
* 不做什么:
* - 不注册全局快捷键、不监听 Cmd/Ctrl+K,也不自行打开/关闭:open 完全受控;
* - 不取数、不发请求、不依赖 router,命令列表与最近项由消费方注入;
* - 不重写键盘模型,不内置选中态之外的业务副作用。
*/
import type { ReactNode } from 'react';
import { Dialog, DialogContent, DialogTitle } from '@mox-hub/ui/components/dialog';
import {
Command,
CommandCollection,
CommandEmpty,
CommandGroup,
CommandGroupLabel,
CommandInput,
CommandItem as CommandItemRow,
CommandList,
CommandShortcut,
} from '@mox-hub/ui/components/command';
import { usePatternLabels } from '../lib/i18n';
export interface CommandItem {
id: string;
label: string;
description?: string;
icon?: ReactNode;
shortcut?: string;
group?: string;
keywords?: string[];
disabled?: boolean;
}
/** 组件内文案缺省(中文常量;消费方经 labels 覆写接入 i18n)。 */
export interface CommandPaletteLabels {
title: string;
placeholder: string;
empty: string;
defaultGroup: string;
recentGroup: string;
}
export const COMMAND_PALETTE_DEFAULT_LABELS: CommandPaletteLabels = {
title: '命令面板',
placeholder: '搜索命令…',
empty: '没有匹配的命令',
defaultGroup: '命令',
recentGroup: '最近使用',
};
export interface CommandPaletteProps {
open: boolean;
onOpenChange: (open: boolean) => void;
items: CommandItem[];
onSelect: (item: CommandItem) => void;
recentIds?: string[];
placeholder?: string;
emptyLabel?: string;
labels?: Partial<CommandPaletteLabels>;
}
/**
* ui/command 的内部条目:额外带 value/label 供 base-ui 做过滤与输入框回显,
* `item` 保留消费方传入的原始对象(onSelect 原样回传)。
*/
interface PaletteEntry {
value: string;
label: string;
item: CommandItem;
}
interface PaletteGroup {
value: string;
label: string;
items: PaletteEntry[];
}
function matchesEntry(entry: PaletteEntry, query: string): boolean {
const needle = query.trim().toLocaleLowerCase();
if (needle === '') return true;
const item = entry.item;
const haystack = [
item.label,
item.description,
item.group,
...(item.keywords ?? []),
];
return haystack.some(
(value) =>
typeof value === 'string' &&
value.toLocaleLowerCase().includes(needle),
);
}
/**
* 「最近使用」置顶,其余按 item.group 首次出现顺序分组;
* 未声明 group 的条目归入默认「命令」组。空组不渲染。
*/
function buildGroups(
items: CommandItem[],
recentIds: string[] | undefined,
labels: CommandPaletteLabels,
): PaletteGroup[] {
const groups = new Map<string, PaletteEntry[]>();
groups.set(labels.defaultGroup, []);
for (const item of items) {
const groupName = item.group?.trim() || labels.defaultGroup;
const entries = groups.get(groupName) ?? [];
if (!groups.has(groupName)) groups.set(groupName, entries);
entries.push({
value: `group:${groupName}:${item.id}`,
label: item.label,
item,
});
}
const result: PaletteGroup[] = [];
if (recentIds && recentIds.length > 0) {
const byId = new Map(items.map((item) => [item.id, item]));
const seen = new Set<string>();
const recentEntries: PaletteEntry[] = [];
for (const id of recentIds) {
if (seen.has(id)) continue;
const item = byId.get(id);
if (!item) continue;
seen.add(id);
recentEntries.push({
value: `recent:${item.id}`,
label: item.label,
item,
});
}
if (recentEntries.length > 0) {
result.push({
value: 'recent',
label: labels.recentGroup,
items: recentEntries,
});
}
}
for (const [groupName, entries] of groups) {
if (entries.length === 0) continue;
result.push({
value: `group:${groupName}`,
label: groupName,
items: entries,
});
}
return result;
}
export function CommandPalette({
open,
onOpenChange,
items,
onSelect,
recentIds,
placeholder,
emptyLabel,
labels,
}: CommandPaletteProps) {
const D = usePatternLabels(
'commandPalette',
COMMAND_PALETTE_DEFAULT_LABELS,
);
const text: CommandPaletteLabels = {
title: labels?.title ?? D.title,
placeholder: labels?.placeholder ?? D.placeholder,
empty: labels?.empty ?? D.empty,
defaultGroup: labels?.defaultGroup ?? D.defaultGroup,
recentGroup: labels?.recentGroup ?? D.recentGroup,
};
const groups = buildGroups(items, recentIds, text);
const handleSelect = (item: CommandItem) => {
if (item.disabled) return;
onSelect(item);
onOpenChange(false);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
showCloseButton={false}
className="top-[20%] translate-y-0 gap-0 overflow-hidden p-0 sm:max-w-xl"
>
<DialogTitle className="sr-only">{text.title}</DialogTitle>
<Command
items={groups}
filter={(entry: PaletteEntry, query: string) =>
matchesEntry(entry, query)
}
>
<CommandInput placeholder={placeholder ?? text.placeholder} />
<CommandList scrollAreaClassName="max-h-[60vh]">
{(group: PaletteGroup) => (
<CommandGroup key={group.value} items={group.items}>
<CommandGroupLabel>{group.label}</CommandGroupLabel>
<CommandCollection>
{(entry: PaletteEntry) => {
const item = entry.item;
return (
<CommandItemRow
key={entry.value}
value={entry}
disabled={item.disabled}
onClick={() => handleSelect(item)}
className="gap-2"
>
{item.icon ? (
<span
aria-hidden="true"
className="flex size-4 shrink-0 items-center justify-center text-content-text-muted [&_svg]:size-4"
>
{item.icon}
</span>
) : null}
<span className="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>
) : null}
</span>
{item.shortcut ? (
<CommandShortcut>{item.shortcut}</CommandShortcut>
) : null}
</CommandItemRow>
);
}}
</CommandCollection>
</CommandGroup>
)}
</CommandList>
<CommandEmpty>{emptyLabel ?? text.empty}</CommandEmpty>
</Command>
</DialogContent>
</Dialog>
);
}
可访问性与 RTL
- 键盘:交互件保留
:focus-visible焦点环;浮层支持 Escape 关闭与焦点归还,菜单 / 页签按 Base UI 约定支持方向键。 筛选菜单、拖拽排序、执行树与模型 listbox 等关键键盘流由 Playwright 断言覆盖,见规范示例 · 交互与可访问性。 - RTL:间距、对齐与方向性图标使用逻辑属性 (
ms-*/text-start/rtl:-scale-x-100);通过ThemeProvider或I18nProvider的direction="rtl"驱动,`lint:rtl` 会拦截新增物理类。 - 文案:优先用组件
labels/translate/translatorprops,其次用I18nProvider目录;内置 zh-CN 默认值,en-US 为参考翻译。见Theming · i18n 与 RTL。 - 对比度:高对比度 token、2px 控件边框与 3px 焦点环由主题层统一提供,见Foundations · Contrast。
用法说明
全局命令面板:ui/dialog + ui/command、分组、最近使用、快捷键展示、空态;选择后回调并关闭。