Command palette
패키지 네임스페이스가 아니라 레시피입니다. Dialog가 팔레트를 담고, useCombobox가 입력, 필터링, 활성 옵션, id를 맡습니다. CommandPalette.* export는 없습니다.
이 페이지의 내용
dialog 표시 방식을 쓰고 getDialogProps()를 Dialog.Root에 펼치세요. 팔레트가 열릴 때 훅이 입력을 비우고 첫 행을 활성으로 만들며, 팔레트가 닫히는 동안 고른 명령은 다시 실행되지 않습니다. value를 null로 두고 onValueChange에서 명령을 실행하면, 명령을 골라도 선택된 것이 남지 않습니다. filterOptions가 목록의 순서를 정합니다. 텍스트로 시작하는 명령이 먼저 오므로, Enter가 실행하는 첫 행이 가장 그럴듯한 명령이 됩니다.
import {
Button,
Dialog,
Field,
OptionList,
Stack,
Text,
useCombobox,
useHotkey,
type ComboboxFilterOptions,
type ComboboxOption,
} from '@tounsoo/todae';
import { useState } from 'react';
const COMMANDS: ComboboxOption[] = [
{ value: 'new-invoice', label: 'Create invoice' },
{ value: 'new-customer', label: 'Add customer' },
{ value: 'billing', label: 'Open billing settings' },
{ value: 'theme', label: 'Switch theme' },
{ value: 'sign-out', label: 'Sign out' },
];
/** Commands whose label starts with the text come first, then the others that hold it. */
const rankCommands: ComboboxFilterOptions = (options, query) => {
const needle = query.toLowerCase();
const holds = options.filter((option) => option.label.toLowerCase().includes(needle));
const starts = holds.filter((option) => option.label.toLowerCase().startsWith(needle));
return [...starts, ...holds.filter((option) => !starts.includes(option))];
};
/** `onRun` is called with the value of each command that runs. */
export default function CommandPalette({ onRun }: { onRun?: (value: string) => void } = {}) {
const [ran, setRan] = useState<string | null>(null);
const cb = useCombobox({
options: COMMANDS,
filterOptions: rankCommands,
presentation: 'dialog',
// Controlled at null, so running a command never leaves a selection behind.
value: null,
onValueChange: (value: string | null) => {
if (!value) return;
setRan(COMMANDS.find((command) => command.value === value)?.label ?? value);
onRun?.(value);
},
});
useHotkey(['Control+K', 'Meta+K'], () => {
if (!cb.open) cb.setOpen(true);
});
return (
<Stack.Root>
<Button.Root {...cb.getTriggerProps()} variant="secondary" aria-keyshortcuts="Control+K Meta+K">
Search commands
</Button.Root>
<Dialog.Root {...cb.getDialogProps()} aria-label="Commands">
<Field.Root id={cb.ids.input} aria-label="Command">
<Field.TextInput {...cb.getInputProps()} placeholder="Type a command" />
</Field.Root>
<OptionList.Root {...cb.getListboxProps({ 'aria-label': 'Commands' })} hidden={cb.isEmpty}>
{cb.items.map((item) => (
<OptionList.Option key={item.id} {...cb.getOptionProps(item)} />
))}
</OptionList.Root>
<Text.Root tone="muted" role="status">
{cb.isEmpty ? 'No matching commands.' : ''}
</Text.Root>
</Dialog.Root>
<Text.Root tone="muted" role="status">
{ran ? `Ran: ${ran}` : 'Press Ctrl+K or ⌘K, or use the button.'}
</Text.Root>
</Stack.Root>
);
}
Press Ctrl+K or ⌘K, or use the button.
단축키는 useHotkey로, Ctrl+K나 ⌘K에서 팔레트를 엽니다. 트리거의 aria-keyshortcuts가 보조 기술에 단축키를 알려 줍니다. Escape나 배경 클릭으로 대화 상자가 닫히고, 포커스는 팔레트가 열릴 때 포커스가 있던 요소로, 포커스가 없었다면 트리거로 돌아갑니다. 빈 결과 메시지는 role="status" 영역에 있어 스크린 리더가 읽어 줍니다.
접근성을 지키는 조합
Todae가 맡는 것: Dialog는 네이티브 모달 <dialog>이므로, 열려 있는 동안 뒤의 페이지는 inert 상태가 되고, 위에서 설명한 대로 닫히며 포커스를 돌려줍니다. useCombobox는 입력을 role="combobox"로 만들어 aria-activedescendant로 활성 명령을 가리키고, 화살표 키, Home, End로 옮기며, Enter로 고릅니다. getTriggerProps()는 트리거에 aria-haspopup="dialog", aria-expanded, aria-controls를 줍니다.
직접 제공할 것: 대화 상자에 이름을 주세요. getDialogProps()는 options 문자열(기본값 "Options")로 aria-label을 설정하므로, 위의 aria-label="Commands"처럼 스프레드 뒤에 직접 주세요. 입력에도 이름이 필요합니다. 여기서는 Field.Root의 aria-label입니다. getLabelProps()를 단 보이는 레이블이 없으므로 목록에도 이름을 주세요. 여기서는 getListboxProps()에 넘긴 aria-label입니다. 트리거에는 보이는 텍스트와 단축키를 알리는 aria-keyshortcuts를 주세요. 빈 결과 메시지는 마운트된 채로 남는 role="status" 요소에 두세요. 명령이 보이는 효과를 남기지 않는다면, 실행 뒤에 상태 메시지처럼 알아챌 수 있는 결과를 주세요.
주의할 점: aria-label을 {...cb.getDialogProps()}보다 앞에 두면 스프레드의 이름이 이깁니다. 일치하는 항목이 없을 때 목록을 마운트 해제하지 마세요. aria-controls가 계속 가리키도록 hidden으로 숨기세요. 단축키로만 팔레트를 열 수 있게 하지 마세요.
언제 쓰나요
언제: 앱 전체에서 동작을 찾아 실행하는 한 곳이 필요할 때.
쓰지 않을 때: 폼 필드의 값 고르기 → Combobox 레시피. 짧고 고정된 동작 목록 → Menu.