# Command Palette

Every page and action of an app in one searchable list, opened with ⌘K.

The app's ⌘K: every page and action in one searchable list over the page. The Search panel in a bare Dialog pinned near the top: ⌘K (Ctrl K) anywhere opens and closes it, typing filters on names and keywords, the arrow keys move the gliding highlight through groups, Enter runs the command and closes the palette. While the query is empty the recently used commands come first. Rows lead with an icon and end with a note and the command's own shortcut (Kbd). It opens and closes at once, from the pointer too: a palette is used many times a day. Behaviour, focus and ARIA come from the Zag dialog and combobox machines, through Ark UI in React, Vue and Svelte.

Kind: block · Category: Navigation · Status: beta · Targets: React, Vue, Svelte · Behaviour: Zag `dialog` machine, through Ark UI

## Add

```bash
npx fndn add command-palette
```

It writes the folder `command-palette/` into the project's ui folder (`index.ts`, `command-palette.tsx`, `CommandPalette.vue`, `CommandPalette.svelte`, `command-palette.recipe.ts`), and what it is built from: [Dialog](/components/dialog.md), [Search](/components/search.md). First time: [Installation](/installation.md).

## Usage

```tsx
import { CommandPalette } from "@/components/ui/command-palette";
```

```vue
import { CommandPalette } from "@/components/ui/command-palette";
```

```svelte
import { CommandPalette } from "$lib/components/ui/command-palette";
```

## Parts

In the DOM the root carries `data-slot="command-palette"` and each part `data-slot="command-palette-<part>"`; in the recipe the root is the `base` slot and each part a slot named after it in camelCase.

| Part | Element | data-slot | Flags | Notes |
| --- | --- | --- | --- | --- |
| `root` | `div` | `command-palette` |  | data-slot="command-palette"; holds no box of its own (display: contents): where the palette is written in the page changes nothing. |
| `search` | `div` | `command-palette-search` |  | The real Search (data-command-palette="search") as the one surface of a bare, instant Dialog placed at the top (data-slot dialog-content): its panel takes the window radius and the overlay shadow. Mounted while open, so every opening starts with the field focused, the given query and the first row highlighted. |

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `{ value: string; label: string; group: string? ("Pages", "Actions"); icon: icon? (React an element, Vue / Svelte a component); meta?: string; shortcut?: string[]; keywords?: string[]; disabled?: boolean }[]` |  | Every command and page, in order; the Search's items. Rows with the same group are listed together under its label. |
| `recent` | `string[]` | `[]` | Values of recently used commands, most recent first. While the query is empty they come first under the recent label (and leave their own group, so each command is listed once). The caller keeps the list (prepend the chosen value in select). |
| `recentLabel` | `string` | `"Recent"` |  |
| `open` | `boolean` | `false` | Bindable (React: `defaultOpen` and `onOpenChange`; Vue: `v-model:open`; Svelte: `bind:open`). Whether the palette is open. React open / onOpenChange (or defaultOpen), Vue v-model:open, Svelte bind:open. |
| `defaultQuery` | `string` | `""` | The query each opening starts with (a search field that opens the palette on a printable key passes that key). |
| `hotkey` | `string` | `"k"` | ⌘ + this key on macOS, Ctrl + it elsewhere (both are accepted everywhere), anywhere on the page, opens and closes the palette. Pass false to bind your own (an app that takes the key on its own root first: a key already handled, defaultPrevented, is left alone). |
| `limit` | `number` | `8` | Rows shown while the query is empty, after the recent ones. A query shows every match. |
| `title` | `string` | `"Command palette"` | Names the dialog for assistive technology (not shown). |
| `label` | `string` | `"Search commands"` | Accessible name of the field. |
| `placeholder` | `string` | `"Type a command or search…"` |  |
| `emptyTitle` | `string` | `"No results found"` |  |
| `emptyHint` | `string` | `"Try another word, or a page name."` |  |

Other attributes and `class` go to the root; `class` is merged through the recipe.

## Events

| Event | Payload |
| --- | --- |
| `openChange` | (open: boolean) |
| `select` | (value: string, item) when a command is chosen with Enter or a click; the palette has already closed |

## States

`closed`, `open`, `empty-query`, `recent`, `no-results`

## Keyboard and accessibility

Role: dialog containing a combobox + listbox.

Keyboard:

- ⌘K / Ctrl K anywhere opens the palette with the field focused; pressed again, it closes it
- Typing filters on names and keywords; the first match is highlighted
- ArrowDown / ArrowUp move the highlight through the rows as drawn, groups included; Home / End jump to the first and last
- Enter runs the highlighted command and closes the palette; focus returns to what had it before
- Escape clears a query, then closes the palette
- Tab stays inside the palette (focus trap)

Notes:

- The dialog is named by its title (visually hidden in a bare dialog); the field by its label.
- A trigger that opens it (a search field, a button) should say so: aria-haspopup="dialog" and aria-keyshortcuts="Meta+K" ("Control+K" off macOS), with the shortcut shown in a Kbd.
- The shortcut is a hint, never the only way in: give the palette a visible trigger.

## Motion

- open and close: instant, from the pointer too (Dialog instant): no fade, no scale, no backdrop fade
- rows: the Search's: no entrance, the highlight glides between neighbouring rows and moves at once across a group label

## Tokens

`radius.window`, `shadow.overlay`, `color.scrim`

## Dependencies

- [Dialog](/components/dialog.md)
- [Search](/components/search.md)

## Examples

### ⌘K across the workspace

React · `workspace.tsx`

```tsx
import { useState } from "react";
import { Gear, GitBranch, Lock, MagnifyingGlass, Moon, RocketLaunch, UserPlus } from "@phosphor-icons/react";
import { Button } from "@/components/ui/button";
import { CommandPalette, type CommandPaletteItem } from "@/components/ui/command-palette";
import { Kbd } from "@/components/ui/kbd";

const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.userAgent) ? "⌘" : "Ctrl";

const commands: CommandPaletteItem[] = [
  { value: "/projects/web-app", label: "web-app", group: "Projects", meta: "Production", icon: <GitBranch data-slot="icon" weight="bold" /> },
  { value: "/projects/billing-api", label: "billing-api", group: "Projects", meta: "Staging", icon: <GitBranch data-slot="icon" weight="bold" /> },
  { value: "/projects/data-pipeline", label: "data-pipeline", group: "Projects", meta: "Preview", icon: <GitBranch data-slot="icon" weight="bold" /> },
  { value: "deploy", label: "Deploy web-app to Production", group: "Actions", shortcut: [mod, "D"], keywords: ["ship", "release"], icon: <RocketLaunch data-slot="icon" weight="bold" /> },
  { value: "invite", label: "Invite teammates", group: "Actions", shortcut: [mod, "I"], keywords: ["members", "add"], icon: <UserPlus data-slot="icon" weight="bold" /> },
  { value: "/settings/api-keys", label: "API keys", group: "Settings", keywords: ["token", "nw_live"], icon: <Lock data-slot="icon" weight="bold" /> },
  { value: "/settings", label: "Workspace settings", group: "Settings", keywords: ["billing", "plan"], icon: <Gear data-slot="icon" weight="bold" /> },
  { value: "theme", label: "Switch to dark theme", group: "Settings", keywords: ["appearance", "night"], icon: <Moon data-slot="icon" weight="bold" /> },
];

/* ⌘K / Ctrl K anywhere opens it; the button is the visible way in. Recent commands come first
 * while the query is empty: keep them yourself, most recent first */
export default function Workspace() {
  const [open, setOpen] = useState(false);
  const [recent, setRecent] = useState(["deploy", "/projects/billing-api"]);
  return (
    <span className="relative inline-flex w-60">
      <Button
        variant="outline" size="sm" className="w-full justify-start pe-14 text-ink-3"
        icon={<MagnifyingGlass data-slot="icon" weight="bold" />}
        aria-haspopup="dialog" aria-keyshortcuts={mod === "⌘" ? "Meta+K" : "Control+K"}
        onClick={() => setOpen(true)}
      >
        Search Northwind…
      </Button>
      <span className="pointer-events-none absolute inset-y-0 end-1.5 flex items-center" aria-hidden><Kbd keys={[mod, "K"]} /></span>
      <CommandPalette
        items={commands}
        recent={recent}
        open={open}
        onOpenChange={setOpen}
        placeholder="Search projects, settings and actions…"
        onSelect={(value) => setRecent((list) => [value, ...list.filter((v) => v !== value)].slice(0, 3))}
      />
    </span>
  );
}
```

Vue · `workspace.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { PhGear, PhGitBranch, PhLock, PhMagnifyingGlass, PhMoon, PhRocketLaunch, PhUserPlus } from "@phosphor-icons/vue";
import { Button } from "@/components/ui/button";
import { CommandPalette, type CommandPaletteItem } from "@/components/ui/command-palette";
import { Kbd } from "@/components/ui/kbd";

const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.userAgent) ? "⌘" : "Ctrl";

const commands: CommandPaletteItem[] = [
  { value: "/projects/web-app", label: "web-app", group: "Projects", meta: "Production", icon: PhGitBranch },
  { value: "/projects/billing-api", label: "billing-api", group: "Projects", meta: "Staging", icon: PhGitBranch },
  { value: "/projects/data-pipeline", label: "data-pipeline", group: "Projects", meta: "Preview", icon: PhGitBranch },
  { value: "deploy", label: "Deploy web-app to Production", group: "Actions", shortcut: [mod, "D"], keywords: ["ship", "release"], icon: PhRocketLaunch },
  { value: "invite", label: "Invite teammates", group: "Actions", shortcut: [mod, "I"], keywords: ["members", "add"], icon: PhUserPlus },
  { value: "/settings/api-keys", label: "API keys", group: "Settings", keywords: ["token", "nw_live"], icon: PhLock },
  { value: "/settings", label: "Workspace settings", group: "Settings", keywords: ["billing", "plan"], icon: PhGear },
  { value: "theme", label: "Switch to dark theme", group: "Settings", keywords: ["appearance", "night"], icon: PhMoon },
];

const open = ref(false);
const recent = ref(["deploy", "/projects/billing-api"]);
function remember(value: string) {
  recent.value = [value, ...recent.value.filter((v) => v !== value)].slice(0, 3);
}
</script>

<!-- ⌘K / Ctrl K anywhere opens it; the button is the visible way in. Recent commands come first
     while the query is empty: keep them yourself, most recent first -->
<template>
  <span class="relative inline-flex w-60">
    <Button
      variant="outline" size="sm" class="w-full justify-start pe-14 text-ink-3"
      aria-haspopup="dialog" :aria-keyshortcuts="mod === '⌘' ? 'Meta+K' : 'Control+K'"
      @click="open = true"
    >
      <template #icon><PhMagnifyingGlass data-slot="icon" weight="bold" /></template>
      Search Northwind…
    </Button>
    <span class="pointer-events-none absolute inset-y-0 end-1.5 flex items-center" aria-hidden="true"><Kbd :keys="[mod, 'K']" /></span>
    <CommandPalette
      v-model:open="open"
      :items="commands"
      :recent="recent"
      placeholder="Search projects, settings and actions…"
      @select="remember"
    />
  </span>
</template>
```

Svelte · `workspace.svelte`

```svelte
<script lang="ts">
  import Gear from "phosphor-svelte/lib/GearIcon";
  import GitBranch from "phosphor-svelte/lib/GitBranchIcon";
  import Lock from "phosphor-svelte/lib/LockIcon";
  import MagnifyingGlass from "phosphor-svelte/lib/MagnifyingGlassIcon";
  import Moon from "phosphor-svelte/lib/MoonIcon";
  import RocketLaunch from "phosphor-svelte/lib/RocketLaunchIcon";
  import UserPlus from "phosphor-svelte/lib/UserPlusIcon";
  import { Button } from "$lib/components/ui/button";
  import { CommandPalette, type CommandPaletteItem } from "$lib/components/ui/command-palette";
  import { Kbd } from "$lib/components/ui/kbd";

  const mod = typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.userAgent) ? "⌘" : "Ctrl";

  const commands: CommandPaletteItem[] = [
    { value: "/projects/web-app", label: "web-app", group: "Projects", meta: "Production", icon: GitBranch },
    { value: "/projects/billing-api", label: "billing-api", group: "Projects", meta: "Staging", icon: GitBranch },
    { value: "/projects/data-pipeline", label: "data-pipeline", group: "Projects", meta: "Preview", icon: GitBranch },
    { value: "deploy", label: "Deploy web-app to Production", group: "Actions", shortcut: [mod, "D"], keywords: ["ship", "release"], icon: RocketLaunch },
    { value: "invite", label: "Invite teammates", group: "Actions", shortcut: [mod, "I"], keywords: ["members", "add"], icon: UserPlus },
    { value: "/settings/api-keys", label: "API keys", group: "Settings", keywords: ["token", "nw_live"], icon: Lock },
    { value: "/settings", label: "Workspace settings", group: "Settings", keywords: ["billing", "plan"], icon: Gear },
    { value: "theme", label: "Switch to dark theme", group: "Settings", keywords: ["appearance", "night"], icon: Moon },
  ];

  let open = $state(false);
  let recent = $state(["deploy", "/projects/billing-api"]);
</script>

<!-- ⌘K / Ctrl K anywhere opens it; the button is the visible way in. Recent commands come first
     while the query is empty: keep them yourself, most recent first -->
<span class="relative inline-flex w-60">
  <Button
    variant="outline" size="sm" class="w-full justify-start pe-14 text-ink-3"
    aria-haspopup="dialog" aria-keyshortcuts={mod === "⌘" ? "Meta+K" : "Control+K"}
    onclick={() => (open = true)}
  >
    {#snippet icon()}<MagnifyingGlass data-slot="icon" weight="bold" />{/snippet}
    Search Northwind…
  </Button>
  <span class="pointer-events-none absolute inset-y-0 end-1.5 flex items-center" aria-hidden="true"><Kbd keys={[mod, "K"]} /></span>
  <CommandPalette
    bind:open
    items={commands}
    {recent}
    placeholder="Search projects, settings and actions…"
    onselect={(value) => (recent = [value, ...recent.filter((v) => v !== value)].slice(0, 3))}
  />
</span>
```

## Recipe

`command-palette.recipe.ts`:

```ts
import { tv, type VariantProps } from "../lib/tv";

/* command-palette — the Search panel in a bare Dialog pinned near the top: ⌘K / Ctrl K anywhere
 * opens it, typing filters every command and page of the app, Enter runs one and closes it.
 *
 * One surface (house rule: never a box in a box): the Dialog is only the frame (position, focus
 * trap, dimmed page) and the Search's own panel is the window, given the window's radius and the
 * overlay's shadow here. It opens and closes at once, from the pointer too (Dialog `instant`): a
 * palette is used many times a day. The root holds no box of its own (display: contents); the
 * Search is the real Search, marked data-command-palette="search". */

export const commandPalette = tv({
  slots: {
    base: "contents",
    search: [
      "w-full max-w-none",
      "[&>[data-slot=search-panel]]:rounded-window [&>[data-slot=search-panel]]:shadow-overlay",
    ],
  },
});

export type CommandPaletteRecipeProps = VariantProps<typeof commandPalette>;
```
