# Context Menu

> Opens a set of link actions from a right-click, a keyboard shortcut, or a visible button.

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

## Use when
- A file, card, or list item needs contextual navigation shortcuts.
- The same actions should be discoverable by touch and keyboard.

## Avoid when
- A primary action needs to stay prominent on the item itself.

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique popover ID. |
| items | `MenuItem[]` |  | no | Links with labels and optional icons, hints, and grouping. An item with items (and no href) becomes a one-level submenu. |
| label | `string` | Item actions | no | Accessible name of the target region. |
| menuLabel | `string` | Actions | no | Label of the visible menu button. |
| class | `string` |  | no | Classes for the target and menu wrapper. |

## Accessibility
- The visible menu button opens the same links even when scripting is disabled.
- Escape from a context-opened popup returns focus to the target.
- Submenus work as in the dropdown menu: the trigger has aria-haspopup="menu" and aria-expanded, and without scripting the submenu links list inline.
- Key Shift+F10: Open the menu while the target is focused.
- Key ↑ / ↓: Move between links in the menu.
- Key Home / End: Focus the first or last link.
- Key → / Enter / Space: Open a submenu and focus its first link.
- Key ← / Escape: Close a submenu and return to its item.
- Key Escape: Dismiss the menu.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze context-menu ui for our product. Replace the demo values of these props with our real content: id, items, label, menuLabel, class. Keep the layout, the heading level rules and these accessibility details: The visible menu button opens the same links even when scripting is disabled. Escape from a context-opened popup returns focus to the target. Submenus work as in the dropdown menu: the trigger has aria-haspopup="menu" and aria-expanded, and without scripting the submenu links list inline. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using context-menu, check it fits: use it when a file, card, or list item needs contextual navigation shortcuts.; the same actions should be discoverable by touch and keyboard.. Avoid it when a primary action needs to stay prominent on the item itself.. Alternatives: @haze/dropdown-menu, @haze/popover, @haze/command-menu.

## Example requests that should lead here
- Add a context menu to a project-folder card.
- Expose secondary links for a saved document by right-click and a visible action button.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import DropdownMenu from "./dropdown-menu.astro";

interface MenuItem {
  label: string;
  href?: string;
  hint?: string;
  destructive?: boolean;
  separatorBefore?: boolean;
  heading?: string;
  icon?: (props: Record<string, unknown>) => unknown;
  /** Makes the item a submenu trigger. One level. */
  items?: { label: string; href: string; hint?: string; destructive?: boolean; separatorBefore?: boolean; icon?: (props: Record<string, unknown>) => unknown }[];
}

interface Props {
  id: string;
  items?: MenuItem[];
  label?: string;
  menuLabel?: string;
  class?: string;
}

const {
  id, items = [{ label: "View overview", href: "#overview" }], label = "Item actions",
  menuLabel = "Actions", class: className,
} = Astro.props;
---

<div data-haze-context-menu class={cn("relative grid min-w-0 gap-2", className)}>
  <div role="group" aria-label={label} aria-keyshortcuts="Shift+F10" data-context-target
    class="min-w-0 rounded-xl border border-border bg-card p-4.5 text-card-foreground focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring">
    <slot><p class="text-[0.8125rem]/5 font-medium">Untitled item</p></slot>
  </div>
  <div class="justify-self-start">
    <DropdownMenu id={id} label={menuLabel} items={items} size="sm"
      class="data-[context-point]:m-0! data-[context-point]:[position-area:none]! data-[context-point]:inset-[var(--haze-menu-y)_auto_auto_var(--haze-menu-x)]! data-[context-point]:max-w-[calc(100vw-1rem)]" />
  </div>
</div>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const target = root.querySelector<HTMLElement>("[data-context-target]");
    const menu = root.querySelector<HTMLElement>("[data-haze-menu]");
    const trigger = root.querySelector<HTMLButtonElement>("[popovertarget]");
    if (!target || !menu || !trigger || typeof menu.showPopover !== "function") return;
    const links = Array.from(menu.querySelectorAll<HTMLElement>("a[href], button[data-submenu-trigger]")).filter((item) => !item.closest("[data-submenu-panel]"));
    if (!links.length) return;

    const openAt = (x: number, y: number) => {
      target.focus({ preventScroll: true });
      menu.setAttribute("data-context-point", "");
      menu.style.setProperty("--haze-menu-x", "0px");
      menu.style.setProperty("--haze-menu-y", "0px");
      if (!menu.matches(":popover-open")) menu.showPopover();
      const left = Math.max(8, Math.min(x, document.documentElement.clientWidth - menu.offsetWidth - 8));
      const top = Math.max(8, Math.min(y, window.innerHeight - menu.offsetHeight - 8));
      menu.style.setProperty("--haze-menu-x", `${left}px`);
      menu.style.setProperty("--haze-menu-y", `${top}px`);
      links[0].focus({ preventScroll: true });
    };
    target.addEventListener("contextmenu", (event) => {
      event.preventDefault();
      openAt(event.clientX, event.clientY);
    });
    target.addEventListener("keydown", (event) => {
      if (event.target !== target || (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10"))) return;
      event.preventDefault();
      const rect = target.getBoundingClientRect();
      openAt(rect.left, rect.bottom + 4);
    });
    trigger.addEventListener("click", () => menu.removeAttribute("data-context-point"));
    menu.addEventListener("keydown", (event) => {
      if (event.key === "Escape" && menu.hasAttribute("data-context-point")) {
        event.preventDefault();
        event.stopPropagation();
        menu.hidePopover();
        target.focus({ preventScroll: true });
        return;
      }
      // Arrow, Home, End and typeahead navigation, and submenu keys, live in dropdown-menu.astro.
    });
    target.tabIndex = 0;
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-context-menu]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-context-menu-listener")) {
    document.documentElement.setAttribute("data-haze-context-menu-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
