# Command palette

A ⌘K palette: the trigger shows the shortcut, ⌘K or Ctrl+K opens it from anywhere on the page, and a short Suggested list under it opens the palette with that command highlighted. Inside a `Modal`, a search box filters commands grouped under Navigation, Actions and Recent; the arrow keys move, Enter runs, and running a command closes the palette with a toast.

**Example: Command palette** (`examples/recipes/command-palette.tsx`)

```tsx
'use client'

import { Button, Modal, Stack, Text, toastInfo, toastSuccess } from '@blocks/design-system'
import {
  Copy,
  CreditCard,
  FileText,
  FolderKanban,
  FolderPlus,
  LayoutDashboard,
  type LucideIcon,
  Moon,
  Search,
  SearchX,
  Settings,
  UserPlus,
} from 'lucide-react'
import { type KeyboardEvent, useEffect, useId, useState } from 'react'
import styles from './command-palette.module.css'

interface Command {
  id: string
  group: 'Navigation' | 'Actions' | 'Recent'
  label: string
  icon: LucideIcon
  shortcut?: string
  run: () => void
}

const commands: Command[] = [
  { id: 'dashboard', group: 'Navigation', label: 'Go to Dashboard', icon: LayoutDashboard, shortcut: 'G D', run: () => toastInfo('Opened Dashboard') },
  { id: 'projects', group: 'Navigation', label: 'Go to Projects', icon: FolderKanban, shortcut: 'G P', run: () => toastInfo('Opened Projects') },
  { id: 'billing', group: 'Navigation', label: 'Go to Billing', icon: CreditCard, run: () => toastInfo('Opened Billing') },
  { id: 'settings', group: 'Navigation', label: 'Go to Settings', icon: Settings, shortcut: 'G S', run: () => toastInfo('Opened Settings') },
  { id: 'new-project', group: 'Actions', label: 'Create project', icon: FolderPlus, shortcut: 'C', run: () => toastSuccess('Created “Untitled project”') },
  { id: 'invite', group: 'Actions', label: 'Invite teammate', icon: UserPlus, run: () => toastSuccess('Invite link ready to share') },
  { id: 'theme', group: 'Actions', label: 'Switch to dark theme', icon: Moon, run: () => toastSuccess('Theme set to dark') },
  { id: 'copy-link', group: 'Actions', label: 'Copy link to this page', icon: Copy, run: () => toastSuccess('Link copied') },
  { id: 'q4-plan', group: 'Recent', label: 'Q4 launch plan', icon: FileText, run: () => toastInfo('Opened “Q4 launch plan”') },
  { id: 'onboarding', group: 'Recent', label: 'Onboarding checklist', icon: FileText, run: () => toastInfo('Opened “Onboarding checklist”') },
  { id: 'pricing', group: 'Recent', label: 'Pricing page draft', icon: FileText, run: () => toastInfo('Opened “Pricing page draft”') },
]

const groups = ['Navigation', 'Actions', 'Recent'] as const
const suggested = ['q4-plan', 'new-project', 'invite', 'billing'].flatMap((id) => commands.filter((command) => command.id === id))

// A ⌘K palette: a combobox input owns the keyboard, and the highlighted
// option is announced through aria-activedescendant, so focus never leaves it.
export default function CommandPalette() {
  const [open, setOpen] = useState(false)
  const [query, setQuery] = useState('')
  const [active, setActive] = useState(0)
  const id = useId()
  const listboxId = `${id}-results`
  const optionId = (command: Command) => `${id}-${command.id}`

  const matches = commands.filter((command) => command.label.toLowerCase().includes(query.trim().toLowerCase()))
  const activeCommand = matches[Math.min(active, matches.length - 1)]

  // ⌘K on macOS, Ctrl+K elsewhere, from anywhere on the page.
  useEffect(() => {
    function onKeyDown(event: globalThis.KeyboardEvent) {
      if (event.key.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault()
        setOpen((current) => !current)
      }
    }
    window.addEventListener('keydown', onKeyDown)
    return () => window.removeEventListener('keydown', onKeyDown)
  }, [])

  function changeOpen(next: boolean) {
    setOpen(next)
    if (next) {
      setQuery('')
      setActive(0)
    }
  }

  // A suggestion opens the palette with that command already highlighted.
  function openAt(command: Command) {
    setQuery('')
    setActive(commands.indexOf(command))
    setOpen(true)
  }

  function run(command: Command) {
    setOpen(false)
    command.run()
  }

  function onInputKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (!activeCommand) return
    if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
      event.preventDefault()
      const step = event.key === 'ArrowDown' ? 1 : -1
      const index = (matches.indexOf(activeCommand) + step + matches.length) % matches.length
      setActive(index)
      const next = matches[index]
      if (next) document.getElementById(optionId(next))?.scrollIntoView({ block: 'nearest' })
    } else if (event.key === 'Enter') {
      event.preventDefault()
      run(activeCommand)
    }
  }

  return (
    <Stack gap="lg">
      <Modal open={open} onOpenChange={changeOpen}>
        <Modal.Trigger render={<Button type="button" dangerouslySetClassName={styles.trigger} />} aria-keyshortcuts="Meta+K Control+K">
          <Search aria-hidden size={16} />
          <span className={styles.triggerLabel}>Search or jump to…</span>
          <kbd className={`${styles.kbd} ${styles.keyboardOnly}`}>⌘K</kbd>
        </Modal.Trigger>
        <Modal.Content showCloseButton={false} dangerouslySetClassName={styles.dialog}>
          <Modal.Header dangerouslySetClassName={styles.srOnly}>Command palette</Modal.Header>
          <div className={styles.search}>
            <Search aria-hidden size={18} className={styles.searchIcon} />
            <input
              className={styles.input}
              role="combobox"
              aria-label="Search commands"
              aria-expanded={matches.length > 0}
              aria-controls={matches.length > 0 ? listboxId : undefined}
              aria-autocomplete="list"
              aria-activedescendant={activeCommand ? optionId(activeCommand) : undefined}
              placeholder="Type a command or search…"
              autoComplete="off"
              spellCheck={false}
              value={query}
              onChange={(event) => {
                setQuery(event.target.value)
                setActive(0)
              }}
              onKeyDown={onInputKeyDown}
            />
          </div>
          <div className={styles.results}>
            {matches.length === 0 ? (
              <div className={styles.empty}>
                <SearchX aria-hidden size={24} />
                <Text fontSize="sm" fontWeight="semibold">
                  No results for “{query.trim()}”
                </Text>
                <Text fontSize="sm" color="text-muted">
                  Try a page name, like Billing, or an action, like Invite.
                </Text>
              </div>
            ) : (
              <div id={listboxId} role="listbox" aria-label="Commands">
                {groups.map((group) => {
                  const items = matches.filter((command) => command.group === group)
                  if (items.length === 0) return null
                  return (
                    // biome-ignore lint/a11y/useSemanticElements: a listbox group has no native element outside <select>
                    <div key={group} role="group" aria-labelledby={`${id}-${group}`} className={styles.group}>
                      <div id={`${id}-${group}`} className={styles.groupLabel}>
                        {group}
                      </div>
                      {items.map((command) => (
                        // biome-ignore lint/a11y/useKeyWithClickEvents: the combobox input handles the keyboard for every option
                        <div
                          key={command.id}
                          id={optionId(command)}
                          role="option"
                          tabIndex={-1}
                          aria-selected={command === activeCommand}
                          className={styles.option}
                          onClick={() => run(command)}
                          onMouseMove={() => setActive(matches.indexOf(command))}
                        >
                          <command.icon aria-hidden size={16} className={styles.optionIcon} />
                          <span className={styles.optionLabel}>{command.label}</span>
                          {command.shortcut && <kbd className={`${styles.kbd} ${styles.keyboardOnly}`}>{command.shortcut}</kbd>}
                        </div>
                      ))}
                    </div>
                  )
                })}
              </div>
            )}
          </div>
          <div className={`${styles.footer} ${styles.keyboardOnly}`} aria-hidden>
            <span>
              <kbd className={styles.kbd}>↑</kbd> <kbd className={styles.kbd}>↓</kbd> to move
            </span>
            <span>
              <kbd className={styles.kbd}>↵</kbd> to run
            </span>
            <span>
              <kbd className={styles.kbd}>esc</kbd> to close
            </span>
          </div>
        </Modal.Content>
      </Modal>
      <section className={styles.suggested} aria-labelledby={`${id}-suggested`}>
        <Text as="h3" id={`${id}-suggested`} fontSize="xs" fontWeight="semibold" color="text-muted" margin="none">
          Suggested
        </Text>
        <ul className={styles.suggestions}>
          {suggested.map((command) => (
            <li key={command.id}>
              <button type="button" className={styles.suggestion} onClick={() => openAt(command)}>
                <command.icon aria-hidden size={16} className={styles.optionIcon} />
                <span className={styles.optionLabel}>{command.label}</span>
                <Text fontSize="xs" color="text-muted">
                  {command.group}
                </Text>
              </button>
            </li>
          ))}
        </ul>
        <Text fontSize="xs" color="text-muted" dangerouslySetClassName={styles.keyboardOnly}>
          Press ⌘K (Ctrl+K on Windows and Linux) anywhere on this page.
        </Text>
      </section>
    </Stack>
  )
}
```

## How it works

- The input is a `combobox` that owns the keyboard. The highlighted command is announced through `aria-activedescendant`, so focus never leaves the input while you move through results, and the highlighted option scrolls into view.
- Results are a `listbox` of `option`s in labelled `group`s. Options also respond to the pointer, and hovering one moves the highlight so mouse and keyboard never disagree.
- `Modal.Content` drops its close button (`showCloseButton={false}`), since Escape closes the palette. A visually hidden `Modal.Header` still names the dialog “Command palette”, and the module moves the dialog up the screen so results grow downwards.
- The shortcut listener is one `keydown` effect on `window`, removed on unmount. The trigger declares it with `aria-keyshortcuts`, and the hint row at the bottom is decoration for sighted users.
- Shortcut hints mean nothing on a touch screen, so the ⌘K badge, the shortcut keys and the hint lines hide under `(hover: none), (pointer: coarse)`.

## App-owned CSS

`examples/recipes/command-palette.module.css`:

```css
.trigger {
  justify-content: flex-start;
  inline-size: 100%;
  max-inline-size: var(--ds-measure-sm);
  font-weight: var(--ds-font-weight-body);
  color: var(--ds-color-text-muted);
  border-color: var(--ds-color-border-subtle);
}

.triggerLabel {
  flex: 1;
  text-align: left;
}

.kbd {
  display: inline-grid;
  place-items: center;
  min-inline-size: var(--ds-space-lg);
  padding: 0 var(--ds-space-sm);
  font-family: var(--ds-font-body);
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-medium);
  line-height: var(--ds-line-height-body);
  color: var(--ds-color-text-muted);
  background-color: var(--ds-color-bg-subtle);
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-sm);
}

/* Sits high on the screen like most palettes, so results grow downwards */
.dialog[role='dialog'] {
  top: 12vh;
  translate: -50% 0;
  max-inline-size: 36rem;
}

.search {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  padding: 0 var(--ds-space-lg);
  border-bottom: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

.searchIcon {
  flex-shrink: 0;
  color: var(--ds-color-text-muted);
}

.input {
  flex: 1;
  min-inline-size: 0;
  block-size: calc(var(--ds-control-height-lg) + var(--ds-space-lg));
  padding: 0;
  font: inherit;
  font-size: var(--ds-font-size-md);
  color: var(--ds-color-text);
  background: transparent;
  border: none;
  outline: none;

  &::placeholder {
    color: var(--ds-color-text-muted);
  }
}

/* The input has no outline of its own, so the row shows focus */
.search:has(.input:focus-visible) {
  box-shadow: inset 0 calc(var(--ds-border-width-md) * -1) 0 var(--ds-color-focus-ring);
}

.results {
  max-block-size: 22rem;
  overflow-y: auto;
  padding: var(--ds-space-sm);
}

.group + .group {
  margin-top: var(--ds-space-sm);
}

.groupLabel {
  padding: var(--ds-space-md) var(--ds-space-md) var(--ds-space-sm);
  font-size: var(--ds-font-size-xs);
  font-weight: var(--ds-font-weight-semibold);
  color: var(--ds-color-text-muted);
}

.option {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  min-block-size: var(--ds-control-height-lg);
  padding: 0 var(--ds-space-md);
  font-size: var(--ds-font-size-sm);
  border-radius: var(--ds-border-radius-md);
  cursor: pointer;

  &[aria-selected='true'] {
    background-color: var(--ds-color-surface-hover);
    box-shadow: inset var(--ds-border-width-md) 0 0 var(--ds-color-accent);

    & .optionIcon {
      color: var(--ds-color-accent-text);
    }
  }
}

.optionIcon {
  flex-shrink: 0;
  color: var(--ds-color-text-muted);
}

.optionLabel {
  flex: 1;
  min-inline-size: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.empty {
  display: grid;
  justify-items: center;
  gap: var(--ds-space-sm);
  padding: var(--ds-space-xl) var(--ds-space-lg);
  text-align: center;
  color: var(--ds-color-text-muted);
}

.footer {
  display: flex;
  flex-wrap: wrap;
  gap: var(--ds-space-sm) var(--ds-space-lg);
  padding: var(--ds-space-md) var(--ds-space-lg);
  font-size: var(--ds-font-size-xs);
  color: var(--ds-color-text-muted);
  background-color: var(--ds-color-bg-subtle);
  border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
}

.suggested {
  display: grid;
  gap: var(--ds-space-sm);
  max-inline-size: var(--ds-measure-sm);
}

.suggestions {
  display: grid;
  margin: 0;
  padding: var(--ds-space-xs);
  list-style: none;
  border: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  border-radius: var(--ds-border-radius-md);
}

.suggestion {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  inline-size: 100%;
  min-block-size: var(--ds-control-height-lg);
  padding: 0 var(--ds-space-md);
  font: inherit;
  font-size: var(--ds-font-size-sm);
  color: var(--ds-color-text);
  text-align: left;
  background: transparent;
  border: none;
  border-radius: var(--ds-border-radius-md);
  cursor: pointer;

  &:hover {
    background-color: var(--ds-color-surface-hover);
  }

  &:focus-visible {
    outline: var(--ds-border-width-md) solid var(--ds-color-focus-ring);
    outline-offset: calc(var(--ds-border-width-md) * -1);
  }
}

/* Shortcut hints mean nothing on a touch screen */
@media (hover: none), (pointer: coarse) {
  .keyboardOnly,
  .kbd.keyboardOnly,
  .footer.keyboardOnly {
    display: none;
  }
}

.srOnly {
  position: absolute;
  inline-size: var(--ds-space-xxs);
  block-size: var(--ds-space-xxs);
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
```
