# React Native Command Palette (⌘K) (Pro)

> A ⌘K command palette for React Native, Expo and the web: fuzzy search with the matched letters bold, groups with Recent first, pages for nested commands (Change theme → Dark), shortcuts drawn as keys, results from your server as you type with loading and error states, full keyboard control, and a sheet on phones. Wires into AppShell with one prop. Part of Patine Pro.

# Command palette Pro

`CommandPalette` is the ⌘K menu of Linear, Vercel and Raycast: one search that jumps to any screen, runs any action and finds any record. Fuzzy search lights the letters that matched ("nwi" finds **N**e**w** **i**nvoice), results are grouped with **Recent** first, a command with `children` opens a page of its own, shortcuts show as keys, and a `source` adds results from your server as you type. It sits near the top of the screen on wide layouts and opens as a tall sheet on phones. `CommandMenu` is the same thing in place, for a launcher or a settings search.

```tsx
import { CommandPalette, CommandMenu } from '@patine-ui/pro';
```

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { Button, Kbd, Text } from 'patine-ui';
import { CommandPalette } from '@patine-ui/pro';

export default function Example() {
  const [open, setOpen] = useState(false);
  const [last, setLast] = useState('Nothing yet');
  const run = (what) => () => setLast(what);
  return (
    <View style={{ gap: 12, alignItems: 'flex-start' }}>
      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
        <Button variant="outline" onPress={() => setOpen(true)}>
          Search…
        </Button>
        <Kbd keys={['⌘', 'K']} size="sm" />
      </View>
      <Text color="textSecondary">Ran: {last}</Text>
      <CommandPalette
        open={open}
        onClose={() => setOpen(false)}
        defaultRecent={['invoices']}
        commands={[
          { id: 'overview', label: 'Overview', group: 'Navigation', icon: 'dashboard', shortcut: ['G', 'O'], onSelect: run('Overview') },
          { id: 'invoices', label: 'Invoices', group: 'Navigation', icon: 'fileText', description: 'Billing', shortcut: ['G', 'I'], onSelect: run('Invoices') },
          { id: 'customers', label: 'Customers', group: 'Navigation', icon: 'users', shortcut: ['G', 'C'], onSelect: run('Customers') },
          { id: 'new-invoice', label: 'New invoice', group: 'Actions', icon: 'plus', keywords: 'bill create', shortcut: ['C'], onSelect: run('New invoice') },
          { id: 'invite', label: 'Invite teammates', group: 'Actions', icon: 'userPlus', keywords: 'member seat', onSelect: run('Invite') },
          {
            id: 'theme',
            label: 'Change theme…',
            group: 'Actions',
            icon: 'contrast',
            children: [
              { id: 'light', label: 'Light', group: 'Theme', icon: 'sun', onSelect: run('Light theme') },
              { id: 'dark', label: 'Dark', group: 'Theme', icon: 'moon', onSelect: run('Dark theme') },
              { id: 'system', label: 'System', group: 'Theme', icon: 'monitor', onSelect: run('System theme') },
            ],
          },
        ]}
      />
    </View>
  );
}
```

## Example: act on an email

A mail app's palette works on the open email: Archive and Mark as unread run at once, while Snooze and Move to open a page of choices. The email above shows what happened.

```tsx live
import { useState } from 'react';
import { View } from 'react-native';
import { Badge, Box, Button, HStack, Kbd, Text, VStack } from 'patine-ui';
import { CommandPalette } from '@patine-ui/pro';

export default function Example() {
  const [open, setOpen] = useState(false);
  const [mail, setMail] = useState({ folder: 'Inbox', unread: false, snoozed: '' });
  const set = (change: Partial<typeof mail>) => () => setMail((m) => ({ ...m, ...change }));
  return (
    <VStack gap="md" style={{ width: '100%', maxWidth: 460 }}>
      <Box border radius="lg" padding="md" gap="xs">
        <HStack gap="sm" align="center" wrap>
          <Text weight={mail.unread ? 'semibold' : 'regular'}>Lena Novak</Text>
          <Badge variant="secondary">{mail.folder}</Badge>
          {mail.snoozed ? <Badge variant="outline">{`Snoozed · ${mail.snoozed}`}</Badge> : null}
        </HStack>
        <Text weight={mail.unread ? 'semibold' : 'medium'}>Contract renewal: two questions</Text>
        <Text size="sm" color="textSecondary">Hi Maya, before we sign the renewal, could you confirm the seat count…</Text>
      </Box>
      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
        <Button variant="outline" onPress={() => setOpen(true)}>
          Commands…
        </Button>
        <Kbd keys={['⌘', 'K']} size="sm" />
      </View>
      <CommandPalette
        open={open}
        onClose={() => setOpen(false)}
        placeholder="What do you want to do with this email?"
        commands={[
          { id: 'archive', label: 'Archive', group: 'This email', icon: 'archive', shortcut: ['E'], onSelect: set({ folder: 'Archive' }) },
          { id: 'unread', label: mail.unread ? 'Mark as read' : 'Mark as unread', group: 'This email', icon: 'mail', shortcut: ['U'], onSelect: set({ unread: !mail.unread }) },
          {
            id: 'snooze',
            label: 'Snooze…',
            group: 'This email',
            icon: 'clock',
            shortcut: ['H'],
            children: ['This evening', 'Tomorrow', 'Next week'].map((when) => ({ id: when, label: when, group: 'Snooze until', icon: 'calendar', onSelect: set({ snoozed: when }) })),
          },
          {
            id: 'move',
            label: 'Move to…',
            group: 'This email',
            icon: 'folder',
            keywords: 'folder label',
            children: ['Inbox', 'Clients', 'Finance', 'Receipts'].map((folder) => ({ id: folder, label: folder, group: 'Folders', icon: 'folder', onSelect: set({ folder }) })),
          },
        ]}
      />
    </VStack>
  );
}
```

## In place

`CommandMenu` draws the panel where you put it, with the same search, groups and keys. Try ↑ ↓ and Enter, or type `drk`: nested commands are found from the top, with the page they're in.

```tsx live
import { CommandMenu } from '@patine-ui/pro';

export default function Example() {
  return (
    <CommandMenu
      style={{ width: '100%', maxWidth: 560 }}
      commands={[
        { id: 'profile', label: 'Profile', group: 'Account', icon: 'user', description: 'Name, photo, email' },
        { id: 'security', label: 'Password and 2FA', group: 'Account', icon: 'shieldCheck', keywords: 'two factor security login' },
        { id: 'billing', label: 'Billing', group: 'Workspace', icon: 'card', description: 'Plan, invoices, cards' },
        { id: 'members', label: 'Members', group: 'Workspace', icon: 'users', hint: '24' },
        { id: 'api', label: 'API keys', group: 'Developers', icon: 'key', shortcut: ['⌘', '⇧', 'K'] },
        {
          id: 'theme',
          label: 'Appearance…',
          group: 'Workspace',
          icon: 'contrast',
          children: [
            { id: 'light', label: 'Light', group: 'Theme', icon: 'sun' },
            { id: 'dark', label: 'Dark', group: 'Theme', icon: 'moon' },
          ],
        },
      ]}
    />
  );
}
```

## Pages

A command with `children` opens them as a page instead of running: the page's title shows as a chip in the search, ↵ goes in, and Backspace on an empty search or Escape comes back. Give it a `placeholder` for the page's search ("Search workspaces…").

## Recent

Before you type, the commands run last come first under **Recent**, newest first. Keep them with `recent` and `onRecentChange` (save them in storage to keep them between visits), or let the palette keep its own from `defaultRecent`.

## Results from your server

`source(query, signal)` returns commands for the query, such as customers or issues, each with its own `group`. It's called after a short pause in typing, and the `signal` aborts when the query changes again, so a slow answer never replaces a newer one. While it loads, a spinner shows in the search and skeleton rows stand in; the last results stay until the new ones arrive. If it fails, a **Try again** row appears.

```tsx live
import { CommandMenu } from '@patine-ui/pro';

const PEOPLE = ['Maya Lindqvist', 'Leo Brandt', 'Ana Ferreira', 'Jonas Weber', 'Priya Natarajan'];

// Your API, here with a pause like a network's.
const searchPeople = (query, signal) =>
  new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      const q = query.toLowerCase();
      resolve(
        PEOPLE.filter((name) => name.toLowerCase().includes(q)).map((name) => ({
          id: name,
          label: name,
          group: 'People',
          icon: 'user',
          description: `${name.split(' ')[0].toLowerCase()}@northwind.dev`,
        }))
      );
    }, 600);
    signal.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(new Error('aborted'));
    });
  });

export default function Example() {
  return (
    <CommandMenu
      style={{ width: '100%', maxWidth: 560 }}
      placeholder="Search people and actions…"
      source={searchPeople}
      commands={[{ id: 'invite', label: 'Invite someone', group: 'Actions', icon: 'userPlus' }]}
    />
  );
}
```

## In the app shell

Give [AppShell](../pro/layout) your `commands` and it does the rest: ⌘K or Ctrl+K opens the palette, the search buttons in the sidebar, rail and top bar open it, and every destination in the navigation comes first under **Navigation**, with its section and its **G then letter** shortcut. `commandSource` adds your server's results.

```tsx
<AppShell
  {...shell}
  commands={[
    { id: 'new-report', label: 'New report', group: 'Actions', icon: 'plus', onSelect: createReport },
    { id: 'theme', label: 'Change theme…', group: 'Actions', icon: 'contrast', children: themeCommands },
  ]}
  commandSource={(query, signal) => api.search(query, { signal }).then(toCommands)}
>
```

## Phones

On phones the palette is a tall bottom sheet with the search at the top and the keyboard up; the key hints and shortcuts hide, since there's no keyboard to press them on.

## Accessibility

- The search is a combobox that controls a listbox of options, and says which option is highlighted (`aria-activedescendant`), so screen readers follow ↑ ↓ without moving focus out of the field.
- Groups are labelled groups; each option reads its page, label, description and hint, and disabled ones say so and are skipped by the arrows.
- ↑ ↓ wrap, Home and End jump, Enter runs, Escape goes back a page and then closes, Backspace on an empty search goes back. The highlighted row scrolls into view.
- The overlay is a modal dialog named Command menu that holds focus while open. Opening and closing respect reduce motion.

## Props

| Prop | Type | Default |
| --- | --- | --- |
| `open`, `onClose` | `boolean`, `() => void` (CommandPalette only) | |
| `commands` | `Command[]`: `{ id, label, group, icon, description?, hint?, shortcut?, keywords?, children?, placeholder?, disabled?, onSelect? }` | |
| `source` | `(query, signal) => Promise<Command[]>` | |
| `recent`, `defaultRecent`, `onRecentChange` | `string[]`, the ids run last | `[]` |
| `placeholder` | `string` | `'Type a command or search…'` |
| `emptyLabel` | `string` | `'No results for “…”'` |
| `footer` | `ReactNode`, beside the key hints | |
| `autoFocus` | `boolean` (CommandMenu) | `false` |

`fuzzyMatch(query, text)` returns `{ score, indices }` or `null`, and `rankCommands(commands, query, recent)` the grouped results, for your own search UIs. `useCommandMenu` is the palette's state, to draw your own.

## Related

- [App layout](../pro/layout): AppShell opens it with ⌘K.
- [Kbd](./kbd): the keys it draws, free.
- [Navbar](./navbar): the marketing site's bar.
