Command palette

@yasinsensoy/native

React Native · Components

CommandPalette

Command palette: quick search, navigating to pages and running commands inside the app.

10 exports

Live example

The preview runs in the browser with the web component; the native component takes the same props and looks the same on iOS and Android.

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/native";

<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/native";

Command palette: quick search, navigating to pages and running commands inside the app. Same data and behavior as CommandPalette on web; commands are given with the items array (the same array works on both platforms).

  • Fuzzy search: Ignores case, Turkish characters and accents; the letters only need to appear in order ("gcm" → "Git commit"). Matches at word starts and adjacent matches rank higher, matched letters are highlighted. keywords and description are searched too. The scoring lives in core and is the same as on web.
  • Sub pages: When a command has items (or loadItems), selecting it moves the palette to that page; the path shows in the search box. Back: the arrow in the header, backspace in an empty box, or the Android back button. Search at the root also finds commands in sub pages (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 opens with openLink.
  • Keyboard: The keyboard's "Go" key (or Enter on a hardware keyboard) runs the first result; the first result is highlighted while typing.
  • Phone: A full-height sheet sliding up from the bottom; when the keyboard opens the list stays above it, and it closes by pulling down and with the back button (on a sub page the back button first returns to the parent page). Tablet: Opens centered.
  • Smooth with thousands of commands: the list is virtualized and filtering does not block typing.

Command shortcuts (shortcut) and the palette shortcut are not available on native because touch devices have no such keys.

CommandPalette({ items, loadItems, trigger, open: openProp, defaultOpen, onOpenChange, onSelect, placeholder, emptyMessage, recentKey, recentLimit, storage, deepSearch, sort, filter, mobileSheet, styles: parts, testID, }: CommandPaletteProps): JSX.Element

Examples

<CommandPalette
  recentKey="commands"
  storage={storage}
  trigger={<Button variant="outline" icon="search">Search…</Button>}
  items={[
    {
      group: "Pages",
      items: [
        { label: "Dashboard", icon: "home", href: "/dashboard" },
        { label: "Orders", icon: "box", href: "/orders", keywords: ["purchase"] },
      ],
    },
    {
      group: "Commands",
      items: [
        {
          label: "Theme",
          items: [
            { label: "Light", onSelect: () => setColorScheme("light") },
            { label: "Dark", onSelect: () => setColorScheme("dark") },
          ],
        },
        { label: "Sign out", tone: "danger", onSelect: async () => await signOut() },
      ],
    },
  ]}
/>

Styles of the inner parts of CommandPalette.

NameTypeDescription
panel?ViewStyleWindow.
header?ViewStyleSearch row.
item?ViewStyleCommand row.
group?ViewStyleGroup heading.

Props of the CommandPalette component (same names as on web).

NameTypeDefaultDescription
items?CommandItemsSourceCommands and groups. Can be an array, a Promise or a function called once when the palette opens; filtered fuzzily on the device while 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 below items without filtering.
trigger?ReactElementElement that opens the palette (e.g. a button that looks like "Search…"). If omitted the palette opens only via open.
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?string"Recently used" key. When given, executed commands are remembered and shown at the top while the search is empty. Give storage to persist them.
recentLimit?number5Number of remembered commands.
storage?PreferenceStorageWhere recent items are stored (a @yasinsensoy/native/storage store can be passed directly). If omitted they are forgotten when the app closes.
deepSearch?booleantrueShould search also return commands of sub pages given as arrays? For example, typing "dark" at the root finds "Theme › Dark" and runs it directly.
sort?booleantrueShould search results be sorted by match score? With false they keep the order they were defined in.
filter?CommandFilterYour own matching function; used instead of the built-in fuzzy search. See CommandFilter.
mobileSheet?booleantrueTurn into a full-height sheet sliding up from the bottom on a phone (below 640 dp)? With false it opens centered on every screen.
styles?CommandPaletteStylesStyles of the inner parts. See CommandPaletteStyles.
testID?stringTest id (given to the window).

A command in CommandPalette (same fields as on web).

  • label, description, badge: text or an element.
  • icon: an icon name or an element.
  • href: navigated to with openLink when selected (a link registered with the Navigator opens inside the app).
  • onSelect: if it returns a Promise the row shows loading and the palette closes when the work is done (stays open with keepOpen).
  • items/loadItems: a sub page opens when selected.
  • shortcut: not shown and does nothing on native (accepted so the same data can be used as on web).
type CommandItem = Core.CommandItem<ReactNode, IconProp>

A command group with a heading: { group, items }.

type CommandGroup = Core.CommandGroup<ReactNode, IconProp>

An element of the items array: a command or a group.

type CommandEntry = Core.CommandEntry<ReactNode, IconProp>

A filtered command source: an array, a Promise or a function called once.

type CommandItemsSource = Core.CommandItemsSource<ReactNode, IconProp>

A loader that searches on the server.

type CommandLoader = Core.CommandLoader<ReactNode, IconProp>

Your own matching function: returns a score; 0 or less means no match.

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.