# Command Menu

> Opens a searchable dialog of page links with keyword matching and arrow-key navigation.

- Kind: ui · Category: Overlays · Interactivity: script
- Install: `npx shadcn@latest add @haze/command-menu`
- File: `src/components/haze/ui/command-menu.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/dialog, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/command-menu

## Use when
- Several common destinations are available from one place.
- Aliases can help users find pages by the terms they already know.

## Avoid when
- The available actions should be visible on the page at all times.

## Alternatives
- [dialog](https://hazeui.com/ui/dialog.md)
- [dropdown-menu](https://hazeui.com/ui/dropdown-menu.md)
- [combobox](https://hazeui.com/ui/combobox.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID for the dialog and its inner controls. |
| title | `string` | Jump to | no | Visible accessible dialog title. |
| triggerLabel | `string` | Find a page | no | Caption on the visible launch button. |
| placeholder | `string` | Search pages | no | Search prompt and accessible label. |
| items | `Command[]` |  | no | Page links with optional context, icon, and search keywords. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Level of the dialog heading. |
| class | `string` |  | no | Classes for the wrapper. |

## Accessibility
- The link list remains readable and navigable without the search enhancement.
- A live region announces match counts as the list filters.
- Key ↑ / ↓: Move from search to a result or between results.
- Key Enter: Open the focused result or the first match from search.
- Key Escape: Close the dialog and return focus to the trigger.

## Agent prompts

### Install and use

Install the Haze UI component "Command Menu" with `npx shadcn@latest add @haze/command-menu`. 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 CommandMenu from "@/components/haze/ui/command-menu.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/ui/command-menu.md

### Customize with real content

Adapt the Haze command-menu ui for our product. Replace the demo values of these props with our real content: id, title, triggerLabel, placeholder, items, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: The link list remains readable and navigable without the search enhancement. A live region announces match counts as the list filters. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using command-menu, check it fits: use it when several common destinations are available from one place.; aliases can help users find pages by the terms they already know.. Avoid it when the available actions should be visible on the page at all times.. Alternatives: @haze/dialog, @haze/dropdown-menu, @haze/combobox.

## Example requests that should lead here
- Build a keyboard-friendly menu for finding catalog pages.
- Add a searchable jump menu with aliases for settings and reports.

## Source

```astro
---
import { ArrowUpRight, Search } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Dialog from "./dialog.astro";
import Input from "./input.astro";

interface Command {
  label: string;
  href: string;
  context?: string;
  keywords?: string;
  icon?: (props: Record<string, unknown>) => unknown;
}
interface Props {
  id: string;
  title?: string;
  triggerLabel?: string;
  placeholder?: string;
  items?: Command[];
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  class?: string;
}

const {
  id, title = "Jump to", triggerLabel = "Find a page", placeholder = "Search pages",
  items = [{ href: "#overview", label: "Overview" }], headingLevel, class: className,
} = Astro.props;
---

<div data-haze-command-menu class={cn("min-w-0", className)}>
  <Dialog id={id} title={title} headingLevel={headingLevel} class="[&>div]:gap-3 sm:[&>div]:p-5 [&>div]:p-4">
    <Fragment slot="trigger"><Search aria-hidden="true" />{triggerLabel}</Fragment>
    <div class="hidden [[data-haze-command-menu][data-enhanced]_&]:block">
      <Input id={`${id}-search`} name="" type="search" placeholder={placeholder} aria-label={placeholder}
        aria-controls={`${id}-items`} autocomplete="off" data-command-search />
    </div>
    <ul id={`${id}-items`} role="list" class="grid max-h-64 gap-0.5 overflow-y-auto [[data-haze-command-menu][data-enhanced]_&]:mt-3">
      {items.map((item) => (
        <li data-command-row data-search-text={[item.label, item.context, item.keywords].filter(Boolean).join(" ")} class="aria-hidden:hidden">
          <a href={item.href} class="group flex min-h-9 items-center gap-2.5 rounded-sm px-3 py-1.5 text-[0.8125rem]/5 transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:outline-ring [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-muted-foreground">
            {item.icon && <item.icon aria-hidden="true" />}
            <span class="min-w-0 flex-1 wrap-anywhere">{item.label}
              {item.context && <span class="block text-[0.75rem]/4 text-muted-foreground">{item.context}</span>}
            </span>
            <ArrowUpRight aria-hidden="true" class="opacity-0 transition-opacity duration-75 group-hover:opacity-100 group-focus-visible:opacity-100" />
          </a>
        </li>
      ))}
    </ul>
    <p data-command-status role="status" class={cn(items.length && "sr-only", "px-2 text-[0.8125rem]/5 text-muted-foreground")}>{items.length ? "" : "No matching pages."}</p>
  </Dialog>
</div>

<script>
  const fold = (value: string) => value.normalize("NFD").replace(/\p{Diacritic}/gu, "").toLocaleLowerCase();

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const dialog = root.querySelector<HTMLDialogElement>("dialog");
    const search = root.querySelector<HTMLInputElement>("[data-command-search]");
    const status = root.querySelector<HTMLElement>("[data-command-status]");
    if (!dialog || !search || !status) return;
    const rows = Array.from(root.querySelectorAll<HTMLElement>("[data-command-row]"));
    let links: HTMLAnchorElement[] = [];
    const filter = () => {
      const terms = fold(search.value).trim().split(/\s+/);
      links = [];
      for (const row of rows) {
        const text = fold(row.dataset.searchText ?? "");
        const match = terms.every((term) => text.includes(term));
        row.setAttribute("aria-hidden", String(!match));
        const link = row.querySelector("a");
        if (match && link) links.push(link);
      }
      status.classList.toggle("sr-only", links.length > 0);
      status.textContent = links.length ? `${links.length} matching ${links.length === 1 ? "page" : "pages"}.` : "No matching pages.";
    };
    search.autofocus = true;
    search.addEventListener("input", filter);
    dialog.addEventListener("close", () => { search.value = ""; filter(); });
    dialog.addEventListener("click", (event) => {
      if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
      if ((event.target as Element).closest("[data-command-row] a")) dialog.close();
    });
    dialog.addEventListener("keydown", (event) => {
      if (event.isComposing) return;
      if (document.activeElement === search && event.key === "Enter" && links.length) {
        event.preventDefault();
        links[0].click();
        return;
      }
      const index = links.findIndex((link) => link === document.activeElement);
      if (document.activeElement !== search && index < 0) return;
      if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
      event.preventDefault();
      const next = event.key === "ArrowDown" ? links[index + 1] : links[index < 0 ? links.length - 1 : index - 1];
      (next ?? search).focus();
    });
    filter();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-command-menu]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-command-menu-listener")) {
    document.documentElement.setAttribute("data-haze-command-menu-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
