# Command palette

> Command palette with keyboard navigation, live filtering, native links and an event for selected actions.

- Kind: block · Category: App shell · Interactivity: script
- Install: `npx shadcn@latest add @haze/command-palette`
- File: `src/components/haze/blocks/command-palette.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/kbd, @haze/utils
- Docs page: https://hazeui.com/blocks/command-palette

## Use when
- Giving power users instant keyboard access to routes and actions in a single searchable palette
- Grouping navigation links and host-handled actions with an empty state for unmatched queries

## Avoid when
- You need an AI answer synthesized above grouped workspace search hits; use ai-search-bar

## Alternatives
- [command-menu](https://hazeui.com/ui/command-menu.md)
- [ai-search-bar](https://hazeui.com/blocks/ai-search-bar.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-command-palette" | no | Unique prefix for input label and heading IDs. |
| placeholder | `string` | "Search commands…" | no | Search input placeholder. |
| items | `CommandItem[]` | 5 grouped commands | no | Set href for links. Actions emit haze:command with id and label. Optional shortcut labels are display-only. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Live filtering hides empty group headings automatically and reveals a clean empty-state message when no command matches.
- Action buttons announce selection in a polite status footer. Listen for haze:command to run an action.
- Key Tab: Move between the search input and visible commands
- Key Arrow Up / Down: Move focus between the search input and visible commands
- Key Enter: Open or select the focused command, or the first match from the input
- Key Space: Select a focused action button
- Key Escape: Return focus to the search input from a command

## Agent prompts

### Install and use

Install the Haze UI block "Command palette" with `npx shadcn@latest add @haze/command-palette`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import CommandPalette from "@/components/haze/blocks/command-palette.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/command-palette.md

### Customize with real content

Adapt the Haze command-palette block for our product. Replace the demo values of these props with our real content: id, placeholder, items, class. Keep the layout, the heading level rules and these accessibility details: Live filtering hides empty group headings automatically and reveals a clean empty-state message when no command matches. Action buttons announce selection in a polite status footer. Listen for haze:command to run an action. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using command-palette, check it fits: use it when giving power users instant keyboard access to routes and actions in a single searchable palette; grouping navigation links and host-handled actions with an empty state for unmatched queries. Avoid it when you need an ai answer synthesized above grouped workspace search hits; use ai-search-bar. Alternatives: @haze/command-menu, @haze/ai-search-bar.

## Example requests that should lead here
- Add a command palette with grouped links and actions, keyboard navigation and live filtering

## Source

```astro
---
import { FileText, FolderKanban, Plus, Search, Settings, Sparkles } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Kbd from "../ui/kbd.astro";

interface CommandItem {
  id: string;
  group: "Navigation" | "Actions";
  label: string;
  href?: string;
  shortcut?: string[];
}

interface Props {
  id?: string;
  placeholder?: string;
  items?: CommandItem[];
  class?: string;
}

const {
  id = "haze-command-palette",
  placeholder = "Search commands…",
  items = [
    { id: "cp1", group: "Navigation", label: "Go to Projects" },
    { id: "cp2", group: "Navigation", label: "Open Documentation", href: "/docs" },
    { id: "cp3", group: "Navigation", label: "Workspace Settings" },
    { id: "cp4", group: "Actions", label: "Create new issue" },
    { id: "cp5", group: "Actions", label: "Ask workspace AI" },
  ],
  class: className,
} = Astro.props;
const groups = (["Navigation", "Actions"] as const)
  .map((name) => ({ name, commands: items.filter((item) => item.group === name) }))
  .filter(({ commands }) => commands.length);
---

<section aria-labelledby={`${id}-title`} data-haze-cmd-palette class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
  <div class="mx-auto max-w-xl overflow-hidden rounded-2xl border border-border bg-popover shadow-float">
    <h2 id={`${id}-title`} class="sr-only">Command palette</h2>
    <div class="flex items-center gap-2.5 border-b border-border px-4 py-3">
      <Search class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
      <label for={`${id}-input`} class="sr-only">Filter commands</label>
      <input
        id={`${id}-input`}
        data-cp-input
        type="search"
        placeholder={placeholder}
        class="-mx-px border border-frame-input h-8 min-w-0 flex-1 rounded-sm bg-transparent px-1 text-sm text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
      />
    </div>

    <div class="max-h-72 overflow-y-auto p-2">
      {
        groups.map(({ name: group, commands }) => (
          <div data-cp-group={group} class="not-first:mt-2">
            <p class="px-2.5 py-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase">{group}</p>
            <ul role="list" class="grid gap-0.5">
              {
                commands.map((it) => {
                  const Command = it.href ? "a" : "button";
                  return (
                    <li data-cp-row data-search={`${it.group} ${it.label}`.toLowerCase()}>
                      <Command
                        href={it.href}
                        type={it.href ? undefined : "button"}
                        data-cp-command={it.id}
                        data-cp-label={it.label}
                        class="flex w-full cursor-pointer items-center justify-between gap-3 rounded-lg px-2.5 py-2 text-left text-sm/5 text-foreground transition-colors duration-100 hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:outline-ring"
                      >
                        <span class="flex min-w-0 items-center gap-2.5">
                          <span class="grid size-6 shrink-0 place-items-center rounded-md border border-frame bg-muted/40 text-muted-foreground" aria-hidden="true">
                            {it.id === "cp1" ? <FolderKanban class="size-3.5" /> : it.id === "cp2" ? <FileText class="size-3.5" /> : it.id === "cp3" ? <Settings class="size-3.5" /> : it.id === "cp4" ? <Plus class="size-3.5" /> : <Sparkles class="size-3.5 text-muted-foreground" />}
                          </span>
                          <span class="truncate">{it.label}</span>
                        </span>
                        {it.shortcut && <Kbd size="sm" keys={it.shortcut} />}
                      </Command>
                    </li>
                  );
                })
              }
            </ul>
          </div>
        ))
      }
      <p data-cp-empty hidden={items.length > 0} class="px-3 py-6 text-center text-xs text-muted-foreground">No commands match your search.</p>
    </div>

    <footer class="flex flex-wrap items-center justify-between gap-2 border-t border-border bg-muted/40 px-4 py-2.5 text-xs text-muted-foreground">
      <div data-cp-keys hidden class="flex items-center gap-3">
        <span class="inline-flex items-center gap-1.5"><Kbd size="sm" keys={["↑", "↓"]} /> navigate</span>
        <span class="inline-flex items-center gap-1.5"><Kbd size="sm">Enter</Kbd> run</span>
      </div>
      <span data-cp-status role="status" class="text-foreground"></span>
    </footer>
  </div>
</section>

<script>
  function initCmdPalettes() {
    document.querySelectorAll<HTMLElement>("[data-haze-cmd-palette]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");
      const input = root.querySelector<HTMLInputElement>("[data-cp-input]");
      const empty = root.querySelector<HTMLElement>("[data-cp-empty]");
      const status = root.querySelector<HTMLElement>("[data-cp-status]");
      const keys = root.querySelector<HTMLElement>("[data-cp-keys]");
      const commands = Array.from(root.querySelectorAll<HTMLElement>("[data-cp-command]"));
      if (keys) keys.hidden = !commands.length;

      input?.addEventListener("input", () => {
        const q = input.value.trim().toLowerCase();
        let shown = 0;
        root.querySelectorAll<HTMLElement>("[data-cp-row]").forEach((row) => {
          const ok = !q || (row.dataset.search ?? "").includes(q);
          row.hidden = !ok;
          if (ok) shown++;
        });
        root.querySelectorAll<HTMLElement>("[data-cp-group]").forEach((g) => {
          g.hidden = g.querySelectorAll("[data-cp-row]:not([hidden])").length === 0;
        });
        if (empty) empty.hidden = shown > 0;
        if (keys) keys.hidden = !shown;
        if (status) status.textContent = "";
      });

      root.addEventListener("keydown", (event) => {
        if (event.defaultPrevented || event.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
        if (!(event.target instanceof HTMLElement)) return;
        const fromInput = event.target === input;
        if (!fromInput && !commands.includes(event.target)) return;

        if (event.key === "Escape" && !fromInput) {
          event.preventDefault();
          event.stopPropagation();
          input?.focus();
          return;
        }

        const direction = event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0;
        const directRun = fromInput && event.key === "Enter";
        if (!direction && !directRun) return;
        const visible = commands.filter((command) => !command.closest<HTMLElement>("[data-cp-row]")?.hidden);
        if (!visible.length) return;

        event.preventDefault();
        if (directRun) {
          visible[0].click();
          return;
        }
        const index = fromInput ? (direction === 1 ? 0 : visible.length - 1) : visible.indexOf(event.target) + direction;
        (visible[index] ?? input)?.focus();
      });

      root.querySelectorAll<HTMLButtonElement>("button[data-cp-command]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const { cpCommand: id, cpLabel: label } = btn.dataset;
          btn.dispatchEvent(new CustomEvent("haze:command", { bubbles: true, detail: { id, label } }));
          if (status) status.textContent = `Selected: ${label}`;
        });
      });
    });
  }
  initCmdPalettes();
  document.addEventListener("astro:page-load", initCmdPalettes);
</script>
```
