コマンドパレット
⌘K か Ctrl+K で開き、画面と操作を名前で探す部品です。このサイトの上の帯の検索も、この部品です。
見本で種類と状態を確かめる
幅は min(640, 画面の幅 − 32) で、画面の上から 12vh に開きます。検索の欄は高さ 52、結果の行は高さ 48 です。結果は種類ごとの見出しで分けます。実物は、このページで ⌘K(Windows では Ctrl+K)を押すと開きます。
選んだ状態
結果がない
コードを写す
HTML
<button class="mz-button" type="button" commandfor="pal-light" command="show-modal" aria-keyshortcuts="Meta+K Control+K" data-demo-open="palette"><svg class="mz-button__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg><span class="mz-button__label">画面と操作を探す</span><kbd class="mz-kbd" aria-hidden="true">⌘K</kbd></button>
<dialog class="mz-palette" id="pal-light" data-demo="palette" aria-label="画面と操作を探す">
<div class="mz-palette__search">
<svg class="mz-palette__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
<input class="mz-palette__input" type="text" role="combobox" aria-label="画面と操作を探す" aria-expanded="true" aria-controls="pal-light-list" aria-autocomplete="list" aria-activedescendant="pal-light-o-home" autocomplete="off" spellcheck="false" autofocus>
<kbd class="mz-kbd" aria-hidden="true">Esc</kbd>
</div>
<div class="mz-palette__results" role="listbox" id="pal-light-list" aria-label="結果">
<div class="mz-palette__group" role="group" aria-labelledby="pal-light-g-PAGES">
<div class="mz-palette__heading" id="pal-light-g-PAGES">PAGES</div>
<div class="mz-palette__option" role="option" id="pal-light-o-home" aria-selected="true"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"/><path d="M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg><span class="mz-palette__option-label">ホーム</span></div>
<div class="mz-palette__option" role="option" id="pal-light-o-outlook" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 3v16a2 2 0 0 0 2 2h16"/><path d="m19 9-5 5-4-4-3 3"/></svg><span class="mz-palette__option-label">11月の見通し</span></div>
<div class="mz-palette__option" role="option" id="pal-light-o-tx" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 12h.01"/><path d="M3 18h.01"/><path d="M3 6h.01"/><path d="M8 12h13"/><path d="M8 18h13"/><path d="M8 6h13"/></svg><span class="mz-palette__option-label">明細</span><span class="mz-palette__option-meta">11/20(金)更新</span></div>
<div class="mz-palette__option" role="option" id="pal-light-o-accounts" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"/><path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"/></svg><span class="mz-palette__option-label">口座と残高</span></div>
</div>
<div class="mz-palette__group" role="group" aria-labelledby="pal-light-g-ACTIONS">
<div class="mz-palette__heading" id="pal-light-g-ACTIONS">ACTIONS</div>
<div class="mz-palette__option" role="option" id="pal-light-o-import" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 15V3"/><path d="m7 10 5 5 5-5"/><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/></svg><span class="mz-palette__option-label">明細を取り込む</span></div>
<div class="mz-palette__option" role="option" id="pal-light-o-close" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect width="18" height="11" x="3" y="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg><span class="mz-palette__option-label">11月を締める</span></div>
<div class="mz-palette__option" role="option" id="pal-light-o-event" aria-selected="false"><svg class="mz-palette__option-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="M12 5v14"/></svg><span class="mz-palette__option-label">予定を足す</span></div>
</div>
</div>
<p class="mz-palette__empty" hidden>当てはまる画面と操作がありません。言葉を短くして探してください。</p>
</dialog>React の呼び出し方
const [open, setOpen] = useState(false);
usePaletteShortcut(() => setOpen(true));
return (
<Palette
open={open}
onClose={() => setOpen(false)}
items={items}
onSelect={(item) => console.log(item.id)}
label="画面と操作を探す"
emptyText="当てはまる画面と操作がありません。言葉を短くして探してください。"
searchIcon={<Search strokeWidth={1.5} aria-hidden="true" />}
/>
);実装を見る(react/Palette.tsx)
React の実装(react/Palette.tsx)
/**
* Palette — コマンドパレット(⌘K)(docs/spec/components.md「palette」)。見た目は css/components/palette.css だけが持つ。
* - <dialog> を showModal() で開く。Esc で閉じ、フォーカスは開く前の場所へ戻る(ネイティブの挙動)
* - 入力は role="combobox"、結果は role="listbox"。フォーカスは入力に置いたまま、aria-activedescendant で選ぶ
* - ↑↓ で選ぶ(端で折り返す)、Enter で開く。入力中は結果を絞るだけで、画面もフォーカスも動かさない
* - ⌘K/Ctrl+K と「/」(文字の入力中でないとき)で開くのは usePaletteShortcut
*/
import { forwardRef, useEffect, useId, useImperativeHandle, useMemo, useRef, useState, type DialogHTMLAttributes, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { useModalOpen } from './Dialog';
export interface PaletteItem {
id: string;
label: string;
/** 種類の見出し(caption。欧文の小さなラベル:PAGES・ACTIONS など) */
group: string;
/** 右に添える補足(例:「11/20(金)更新」) */
meta?: string;
icon?: ReactNode;
/** 絞り込みで label のほかに当てる語(読み・英字) */
keywords?: string[];
}
export interface PaletteProps extends Omit<DialogHTMLAttributes<HTMLDialogElement>, 'open' | 'onSelect'> {
open: boolean;
onClose: () => void;
items: PaletteItem[];
onSelect: (item: PaletteItem) => void;
/** パレットの名前(例:「画面と操作を探す」) */
label: string;
/** 結果がないときの文(何がなく、次に何をすればよいか) */
emptyText: string;
searchIcon?: ReactNode;
}
export const Palette = forwardRef<HTMLDialogElement, PaletteProps>(function Palette(
{ open, onClose, items, onSelect, label, emptyText, searchIcon, className, ...rest },
ref,
) {
const inner = useRef<HTMLDialogElement>(null);
useImperativeHandle(ref, () => inner.current as HTMLDialogElement);
const base = useId();
const [query, setQuery] = useState('');
const [active, setActive] = useState(0);
useModalOpen(inner, open, onClose);
// 言葉と選択は、閉じたときに空に戻す(開くときには消さない)。開いたときに useEffect で消すと、
// ⌘K の直後に間を置かずに打った文字が、その初期化で消えることがあった(demo/palette.html も閉じたときに戻す)
const [wasOpen, setWasOpen] = useState(open);
if (wasOpen !== open) {
setWasOpen(open);
if (!open) {
setQuery('');
setActive(0);
}
}
const results = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return items;
return items.filter((item) => [item.label, ...(item.keywords ?? [])].some((s) => s.toLowerCase().includes(q)));
}, [items, query]);
const groups = useMemo(() => {
const map = new Map<string, PaletteItem[]>();
for (const item of results) map.set(item.group, [...(map.get(item.group) ?? []), item]);
return [...map];
}, [results]);
const optionId = (item: PaletteItem) => `${base}-o-${item.id}`;
const current = results[Math.min(active, results.length - 1)];
const handleKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
// 日本語の変換中の Enter・矢印は変換の操作なので、選ばない
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
if (results.length === 0) return;
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
const step = event.key === 'ArrowDown' ? 1 : -1;
setActive((i) => (i + step + results.length) % results.length);
} else if (event.key === 'Enter' && current) {
event.preventDefault();
inner.current?.close();
onSelect(current);
}
};
return (
<dialog ref={inner} className={className ? `mz-palette ${className}` : 'mz-palette'} aria-label={label} {...rest}>
<div className="mz-palette__search">
{searchIcon ? (
<span className="mz-palette__icon" aria-hidden="true">
{searchIcon}
</span>
) : null}
<input
className="mz-palette__input"
type="text"
role="combobox"
aria-label={label}
aria-expanded={results.length > 0}
aria-controls={`${base}-list`}
aria-autocomplete="list"
aria-activedescendant={current ? optionId(current) : undefined}
autoComplete="off"
spellCheck={false}
autoFocus
value={query}
onChange={(event) => {
setQuery(event.target.value);
setActive(0);
}}
onKeyDown={handleKeyDown}
/>
</div>
<div className="mz-palette__results" role="listbox" id={`${base}-list`} aria-label="結果" hidden={results.length === 0}>
{groups.map(([group, list]) => (
<div className="mz-palette__group" role="group" aria-labelledby={`${base}-g-${group}`} key={group}>
<div className="mz-palette__heading" id={`${base}-g-${group}`}>
{group}
</div>
{list.map((item) => (
<div
className="mz-palette__option"
role="option"
id={optionId(item)}
aria-selected={item === current}
key={item.id}
onPointerMove={() => setActive(results.indexOf(item))}
onClick={() => {
inner.current?.close();
onSelect(item);
}}
>
{item.icon ? (
<span className="mz-palette__option-icon" aria-hidden="true">
{item.icon}
</span>
) : null}
<span className="mz-palette__option-label">{item.label}</span>
{item.meta ? <span className="mz-palette__option-meta">{item.meta}</span> : null}
</div>
))}
</div>
))}
</div>
{/* 結果がないときは一覧を隠し、一覧の外の文で伝える(listbox の中に option 以外を置かない) */}
{results.length === 0 ? <p className="mz-palette__empty">{emptyText}</p> : null}
</dialog>
);
});
/** ⌘K/Ctrl+K で開く。「/」は文字の入力中でないときだけ開く(入力欄の「/」を奪わない) */
export function usePaletteShortcut(onOpen: () => void): void {
const onOpenRef = useRef(onOpen);
onOpenRef.current = onOpen;
useEffect(() => {
const handle = (event: KeyboardEvent) => {
const typing = (event.target as HTMLElement | null)?.closest('input, textarea, select, [contenteditable=""], [contenteditable="true"]');
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
event.preventDefault();
onOpenRef.current();
} else if (event.key === '/' && !typing && !event.metaKey && !event.ctrlKey && !event.altKey) {
event.preventDefault();
onOpenRef.current();
}
};
document.addEventListener('keydown', handle);
return () => document.removeEventListener('keydown', handle);
}, []);
}絞り込み・↑↓ の選択・Enter で開く処理は JS が持ちます(React の Palette は持っています)。
いつ使うか
- 画面と操作の数が多く、メニューをたどるより名前で探すほうが早いアプリに置きます。
- 結果は「画面」「操作」のような種類ごとの見出しで分けます。見出しは caption・text-2 です。
- 当てはまらないときは、次にどうすればよいかを文で出します。
読み上げとキーボードにどう応えるか
- ⌘K か Ctrl+K で開き、
/で検索へ移り、↑↓ で選び、Enter で開き、Esc で閉じます。開くボタンにはaria-keyshortcuts="Meta+K Control+K"を付けます。 - 検索の欄は
role="combobox"で、結果はrole="listbox"、選んだ行はaria-activedescendantで伝えます。フォーカスは欄に置いたままです。 - ダイアログと同じく、閉じるとフォーカスは開いたボタンへ戻ります。
よい例と悪い例
当てはまる画面と操作がありません。言葉を短くして探してください。
該当なし
更新日