Command palette

@yasinsensoy/web

Web · Components

CommandPalette

⌘K command palette: quick search, navigating to pages and running commands inside the app.

10 exports

Live example

Preview

Command palette

Open with ⌘K / Ctrl+K. Type "dark" (found in a subpage), type "ali" (server results), Mod+Shift+T opens the Theme page directly.

Code

import { CommandPalette, Button } from "@yasinsensoy/web";

<CommandPalette recentKey="commands"
  trigger={<Button variant="outline" icon="search">Search… ⌘K</Button>}
  items={[
    { group: "Pages", items: [{ label: "Home", icon: "home", href: "/" }] },
    {
      group: "Commands",
      items: [
        { label: "New document", icon: "plus", shortcut: "Mod+Alt+N", onSelect: newDocument },
        { label: "Export report", onSelect: async () => await exportReport() },
        {
          label: "Theme",
          items: [
            { label: "Light", onSelect: () => setTheme("light") },
            { label: "Dark", onSelect: () => setTheme("dark") },
          ],
        },
        { label: "Delete account", icon: "trash", tone: "danger", onSelect: remove },
      ],
    },
  ]}
  loadItems={async ({ query, signal }) => {
    const people = await fetch(`/api/people?q=${query}`, { signal }).then((r) => r.json());
    return [{ group: "People", items: people.map((p) => ({ label: p.name, href: `/people/${p.id}` })) }];
  }}
/>

Events

  1. Events appear here when you interact with the preview.

Import

import { CommandPalette } from "@yasinsensoy/web";

CommandPalette

componentClient component

⌘K command palette: quick search, navigating to pages and running commands inside the app. Commands are given with the items array; fuzzy search, groups, shortcuts, sub-pages, server-side search and recently used are built in.

  • Fuzzy search: no case, Turkish character or accent differences; the letters only need to appear in order ("gcm" → "Git commit"). Matches at word starts and contiguous matches rank higher, and matching letters are highlighted. keywords and description are searched too.
  • Shortcuts: shortcut (default ⌘K / Ctrl+K) opens the palette. Commands' own shortcuts ("Mod+Shift+L") work even while the palette is closed, so all of the app's shortcuts are defined in one place.
  • Sub-pages: when a command has items (or loadItems), selecting it switches the palette to that page; the path shows in the search box. Back: Backspace in an empty box, Esc or the phone's back button. Search at the root also finds sub-page commands (deepSearch).
  • Async: items can be a Promise/function; loadItems searches on the server (requested when typing stops; the old request is cancelled).
  • Commands: if onSelect returns a Promise the row shows loading and the palette closes when the work is done; href navigates without a page reload.
  • Smooth even with thousands of commands: the list is virtualized and filtering doesn't block typing.
  • Mobile: opens as a full-height sheet sliding from the bottom; rows are thumb-height, the list stays above the keyboard when it opens, and it closes by pulling down and with the back button (going back first when in a sub-page).

Built on the native <dialog> and shown in the top layer as a popover (opening doesn't stutter no matter how large the page is); focus stays inside and returns to the previous place on close.

CommandPalette({ items, loadItems, trigger, shortcut, shortcutScope, open: openProp, defaultOpen, onOpenChange, onSelect, placeholder, emptyMessage, recentKey, recentLimit, deepSearch, sort, filter, footer, mobileSheet, className, }: CommandPaletteProps): JSX.Element

Examples

<CommandPalette
  recentKey="commands"
  trigger={<Button variant="outline" icon="search">Search… ⌘K</Button>}
  items={[
    {
      group: "Pages",
      items: [
        { label: "Dashboard", icon: "home", href: "/dashboard" },
        { label: "Orders", icon: "box", href: "/orders", keywords: ["purchases"] },
      ],
    },
    {
      group: "Commands",
      items: [
        { label: "New order", icon: "plus", shortcut: "Mod+Shift+O", onSelect: newOrder },
        {
          label: "Theme",
          icon: "theme",
          items: [
            { label: "Light", onSelect: () => setTheme("light") },
            { label: "Dark", onSelect: () => setTheme("dark") },
          ],
        },
        { label: "Sign out", tone: "danger", onSelect: async () => await signOut() },
      ],
    },
  ]}
  // Server-side search:
  loadItems={async ({ query, signal }) => {
    if (!query) return [];
    const users = await fetch(`/api/users?q=${query}`, { signal }).then((r) => r.json());
    return [{ group: "Users", items: users.map((u) => ({ label: u.name, href: `/u/${u.id}` })) }];
  }}
/>

When command shortcuts work.

  • "global": whenever the palette is on the page (even when closed). This is the way to define all of the app's shortcuts in one place.
  • "open": only while the palette is open.
  • "none": shortcuts are only displayed, they don't work.
type CommandShortcutScope = "global" | "open" | "none"

Props of the CommandPalette component.

NameTypeDefaultDescription
items?CommandItemsSourceCommands and groups. An array, a Promise or a function called once when the palette opens; filtered fuzzily in the browser when searching. Give a command items for a sub-page. See CommandItem.
loadItems?CommandLoaderServer-side search (e.g. users, documents). Called when typing stops; the returned commands are shown unfiltered below items. Both can be used together: fixed commands + search results.
trigger?ReactElementElement that opens the palette (e.g. a button looking like "Search… ⌘K"). When omitted the palette opens only with the shortcut or open.
shortcut?string | readonly string[] | false"Mod+K"Shortcut(s) that toggle the palette. Turned off with false. Example: ["Mod+K", "/"] ("/" doesn't work inside a text field).
shortcutScope?CommandShortcutScope"global"When command shortcuts work. See CommandShortcutScope.
open?booleanWhether it is open in controlled use.
defaultOpen?booleanfalseOpen initially in uncontrolled use?
onOpenChange?(open: boolean) => voidCalled with the new state when it opens or closes.
onSelect?(item: CommandItem) => voidCalled when any command is selected (before the command's own onSelect).
placeholder?string"Komut ya da arama yazın…"Placeholder of the search box.
emptyMessage?ReactNode"Sonuç bulunamadı"Content shown when there are no results.
recentKey?stringlocalStorage key for "Recently used". When given, run commands are remembered and shown at the top while the search is empty.
recentLimit?number5Number of remembered commands.
deepSearch?booleantrueShould search also return commands from sub-pages given as arrays? For example typing "dark" at the root finds "Theme › Dark" and runs it directly.
sort?booleantrueSort search results by match score? With false they stay in the order defined.
filter?CommandFilterYour own matching function; used instead of the built-in fuzzy search. See CommandFilter.
footer?ReactNode | falseFooter. Defaults to keyboard hints on desktop (↑↓ navigate, ↵ select, esc); hidden with false. Not shown on touch screens.
mobileSheet?booleantrueTurn into a full-height sheet sliding from the bottom on small screens (below 640 px)?
className?stringClasses added to the dialog (e.g. max-w-2xl).

A command inside a CommandPalette. See CommandItem in the core.

type CommandItem = Core.CommandItem<ReactNode, IconProp>

Titled command group.

type CommandGroup = Core.CommandGroup<ReactNode, IconProp>

An element of the CommandPalette items array: a command or a { group, items } group.

type CommandEntry = Core.CommandEntry<ReactNode, IconProp>

Command source filtered in the browser: an array, a Promise or a function called once.

type CommandItemsSource = Core.CommandItemsSource<ReactNode, IconProp>

Loader that searches on the server.

type CommandLoader = Core.CommandLoader<ReactNode, IconProp>

Your own matching function.

type CommandFilter = Core.CommandFilter<ReactNode, IconProp>

Info given to a {@link CommandLoader<N, I>} function.

NameTypeDescription
querystringText in the search box (may be empty).
signalAbortSignalCancels the old request when a new search starts or the palette closes; pass it to fetch.