CommandPalette
Search and run commands from the keyboard. Ctrl+K or ⌘K opens it; the search ignores case, accents and Arabic letter forms. A command can have a description (one line under the label; the search reads it too), a badge (short text at the end of the row) and disabled (the reason the command cannot run now). A disabled row shows its reason and stays in the list: the arrow keys pass over it, but Enter and a click do nothing. Server results: onSearchChange gets the typed text, loading shows a searching row, and the results are commands (put the matched text in keywords). description can be a node, for example an amount with the Riyal sign; a node is not searched. anchor opens the palette next to an element, and as a bottom sheet below 768 px. The anchor element must have aria-haspopup and aria-expanded. A command that moves the focus must do it after the palette closes, for example in a useEffect of the new element: the dialog and the bottom sheet keep the focus inside until they close.
import { CommandPalette, useCommandShortcut } from "@percentsa/ui";Examples
Code
export function CommandPaletteExample() {
const t = useT();
const [open, setOpen] = useState(false);
useCommandShortcut(() => setOpen((o) => !o));
return (
<>
<Button variant="secondary" onClick={() => setOpen(true)}>
<Search aria-hidden />
{t("Search commands", "ابحث في الأوامر")}
<Kbd>Ctrl K</Kbd>
</Button>
<CommandPalette open={open} onOpenChange={setOpen} commands={useCommands()} />
</>
);
}
const CUSTOMERS = [
{ en: "Noura Ali", ar: "نورة علي" },
{ en: "Noura Hassan", ar: "نورة حسن" },
{ en: "Khalid Noura", ar: "خالد نورة" },
];
/** Type 2 or more letters, for example "noura" or "نورة": after 400 ms the server rows join the list. */Code
export function CommandPaletteServerExample() {
const t = useT();
const [open, setOpen] = useState(false);
const [text, setText] = useState("");
// The server's answer: the names it found. The rows are built below, where `t` is at hand.
const [found, setFound] = useState<typeof CUSTOMERS | null>(null);
const q = text.trim().toLowerCase();
const loading = q.length >= 2 && found === null;
useEffect(() => {
setFound(null);
if (q.length < 2) return;
// A real app asks its server here.
const timer = setTimeout(() => setFound(CUSTOMERS.filter((c) => c.en.toLowerCase().includes(q) || c.ar.includes(q))), 400);
return () => clearTimeout(timer);
}, [q]);
const rows: Command[] = found
? [
...found.map((c) => ({ id: `c-${c.en}`, label: t(c.en, c.ar), group: t("Customers", "العملاء"), keywords: [q], onSelect: () => toast({ title: t(c.en, c.ar) }) })),
{
id: "pay",
label: t("Payment 1042", "الدفعة 1042"),
group: t("Payments", "الدفعات"),
description: (
<>
<Money amount={120} /> · [email protected]
</>
),
keywords: [q],
onSelect: () => toast({ title: t("Payment 1042", "الدفعة 1042") }),
},
]
: [];
return (
<>
<Button variant="secondary" onClick={() => setOpen(true)}>
<Search aria-hidden />
{t("Search customers", "ابحث في العملاء")}
</Button>
<CommandPalette open={open} onOpenChange={setOpen} commands={rows} onSearchChange={setText} loading={loading} />
</>
);
}
/** The palette opens under the button, and as a bottom sheet below 768 px. */Code
export function CommandPaletteAnchorExample() {
const t = useT();
const [open, setOpen] = useState(false);
const button = useRef<HTMLButtonElement>(null);
const commands: Command[] = [
{ id: "text", label: t("Text field", "حقل نص"), onSelect: () => toast({ title: t("Text field", "حقل نص") }) },
{ id: "number", label: t("Number field", "حقل رقم"), onSelect: () => toast({ title: t("Number field", "حقل رقم") }) },
{ id: "file", label: t("File field", "حقل ملف"), disabled: t("Needs a storage plan", "يحتاج إلى خطة تخزين"), onSelect: () => {} },
];
return (
<>
<Button ref={button} variant="secondary" aria-haspopup="dialog" aria-expanded={open} onClick={() => setOpen((o) => !o)}>
<Plus aria-hidden />
{t("Add option", "إضافة خيار")}
</Button>
<CommandPalette open={open} onOpenChange={setOpen} commands={commands} anchor={button} />
</>
);
}
function useAttentionItems(): AttentionItem[] {
const t = useT();
const ago = (minutes: number) => new Date(Date.now() - minutes * 60_000);
return [
{
id: "a",
level: "critical",
title: t("Site down", "الموقع متوقف"),
href: "#a",
detail: t("No answer for 5 minutes", "لا توجد استجابة منذ 5 دقائق"),
area: t("Main website", "الموقع الرئيسي"),
context: <a href="#client">Al Noor</a>,
openedAt: ago(6),
action: <Button size="sm" variant="secondary">{t("Restart", "إعادة التشغيل")}</Button>,
},
{ id: "b", level: "important", title: t("Deploy failed", "فشل النشر"), href: "#b", area: "shop.example.com", openedAt: ago(95), menu: [{ label: t("Dismiss", "تجاهل") }, { label: t("Open log", "فتح السجل") }] },
{ id: "c", level: "important", title: t("Disk almost full", "القرص شبه ممتلئ"), href: "#c", area: t("Main website", "الموقع الرئيسي"), openedAt: ago(300) },
{ id: "d", level: "other", title: t("Update ready", "تحديث جاهز"), area: "203.0.113.10", openedAt: ago(2000) },
];
}
/** Four items, one for each level; the app sorts them. The second has a "⋯" menu. The last has no `href`: its title is plain text. */