# Dropdown menu

> Button that opens a short list of links, with group headings, leading icons, trailing hints, a destructive style and one level of submenus.

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

## Use when
- An account or workspace menu in a navbar
- Three to eight secondary destinations behind one button
- A "more" button at the end of a table row or card

## Avoid when
- Choosing a form value; use select
- Only two actions, which fit as visible buttons
- Panels with inputs or rich content; use popover

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique on the page. Links the trigger to the menu and names the CSS anchor. |
| items | `{ label: string; href?: string; hint?: string; destructive?: boolean; separatorBefore?: boolean; heading?: string; icon?: Component; items?: { label: string; href: string; hint?: string; destructive?: boolean; separatorBefore?: boolean; icon?: Component }[] }[]` |  | yes | Menu links in order. separatorBefore draws a divider above an item. heading shows a small label above it to start a group. icon is a component such as one from @lucide/astro, drawn before the label. An item with items (and no href) becomes a submenu trigger with a trailing chevron; one level of nesting. |
| label | `string` | "Options" | no | Visible trigger text when the trigger slot is not used. |
| ariaLabel | `string` |  | no | Accessible name for an icon-only trigger. |
| variant | `"primary" \| "secondary" \| "outline" \| "ghost"` | "outline" | no | Trigger button style. |
| size | `"sm" \| "md" \| "lg" \| "icon"` | "md" | no | Trigger button size. |
| triggerClass | `string` |  | no | Extra classes on the trigger button. |
| align | `"start" \| "end"` | "start" | no | Trigger edge the menu lines up with. |
| side | `"bottom" \| "top"` | "bottom" | no | Preferred edge of the trigger, with native viewport collision fallback. |
| class | `string` |  | no | Menu panel classes. |
| trigger slot | `slot` |  | no | Custom trigger content, such as a name and a chevron. |
| header / actions slots | `slot` |  | no | Optional identity header and trailing native action form. |

## Accessibility
- This is a disclosure list of links, not an ARIA menu: items are reached with Tab, which needs no script and matches what links do.
- Icons are aria-hidden and a heading is plain text above its link, so every link keeps its own name.
- The menu scales and fades in over 150 ms and out again through the native popover; reduced-motion users get no animation.
- The destructive style only adds color, so the item text itself must say what happens ("Sign out", "Delete project").
- Opening and dismissal work natively. Enhancement adds arrow navigation, typeahead and a moving pointer highlight.
- A submenu trigger is a button with aria-haspopup="menu" and aria-expanded; its panel gets role=menu and its links role=menuitem. The root list stays a disclosure of links, so the submenu is the one menu-pattern part.
- Without scripting the submenu has no trigger: its links list inline under the submenu label, so every link stays reachable.
- A submenu opens on hover after a 100 ms intent delay and closes 200 ms after the pointer leaves the row and the panel, so a diagonal path into the panel keeps it open. It enters with a 4 px slide and fade over 150 ms; reduced-motion users get none.
- Key Enter / Space: Open or close the menu from the trigger
- Key Tab / Shift+Tab: Move through the menu links
- Key ArrowUp / ArrowDown / Home / End: Open from the trigger or move focus between links
- Key Letters: Focus a matching link by its visible label
- Key ArrowRight / Enter / Space: On a submenu item, open it and focus its first link
- Key ArrowLeft / Escape: In a submenu, close it and return focus to its item
- Key Escape: Close the menu and return focus to the trigger

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze dropdown-menu ui for our product. Replace the demo values of these props with our real content: id, items, label, ariaLabel, variant, size, triggerClass, align, side, class, trigger slot, header / actions slots. Keep the layout, the heading level rules and these accessibility details: This is a disclosure list of links, not an ARIA menu: items are reached with Tab, which needs no script and matches what links do. Icons are aria-hidden and a heading is plain text above its link, so every link keeps its own name. The menu scales and fades in over 150 ms and out again through the native popover; reduced-motion users get no animation. The destructive style only adds color, so the item text itself must say what happens ("Sign out", "Delete project"). Opening and dismissal work natively. Enhancement adds arrow navigation, typeahead and a moving pointer highlight. A submenu trigger is a button with aria-haspopup="menu" and aria-expanded; its panel gets role=menu and its links role=menuitem. The root list stays a disclosure of links, so the submenu is the one menu-pattern part. Without scripting the submenu has no trigger: its links list inline under the submenu label, so every link stays reachable. A submenu opens on hover after a 100 ms intent delay and closes 200 ms after the pointer leaves the row and the panel, so a diagonal path into the panel keeps it open. It enters with a 4 px slide and fade over 150 ms; reduced-motion users get none. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using dropdown-menu, check it fits: use it when an account or workspace menu in a navbar; three to eight secondary destinations behind one button; a "more" button at the end of a table row or card. Avoid it when choosing a form value; use select; only two actions, which fit as visible buttons; panels with inputs or rich content; use popover. Alternatives: @haze/popover, @haze/button.

## Example requests that should lead here
- Add an account menu with profile, billing and sign out
- Put a three-dot menu on each row with edit and delete links

## Source

```astro
---
import { ChevronRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface SubItem {
  label: string;
  href: string;
  hint?: string;
  destructive?: boolean;
  separatorBefore?: boolean;
  icon?: (props: Record<string, unknown>) => unknown;
}

interface MenuItem {
  label: string;
  /** Required for a plain link. Leave it out when the item has `items`. */
  href?: string;
  /** Short trailing text, such as a shortcut or a count. */
  hint?: string;
  destructive?: boolean;
  /** Draws a divider above this item to start a new group. */
  separatorBefore?: boolean;
  /** Small label shown above this item, to start a group. */
  heading?: string;
  /** An icon component, for example one from @lucide/astro. Decorative. */
  icon?: (props: Record<string, unknown>) => unknown;
  /** Makes this item a submenu trigger. One level of nesting. Without scripting the links list inline under the label. */
  items?: SubItem[];
}

interface Props {
  /** Unique on the page. Links the trigger to the menu and names the CSS anchor. */
  id: string;
  items: MenuItem[];
  /** Visible trigger text. The "trigger" slot replaces it. */
  label?: string;
  /** Accessible name for an icon-only trigger. */
  ariaLabel?: string;
  variant?: "primary" | "secondary" | "outline" | "ghost";
  size?: "sm" | "md" | "lg" | "icon";
  triggerClass?: string;
  /** Which trigger edge the menu lines up with. */
  align?: "start" | "end";
  side?: "bottom" | "top";
  class?: string;
}

const { id, items, label = "Options", ariaLabel, variant = "outline", size = "md", align = "start", side = "bottom", triggerClass, class: className } = Astro.props;

// Same recipe as popover.astro: anchored where CSS anchor positioning exists, a centered sheet elsewhere.
// The margin on the panel's far side keeps an 8 px gutter when it has to hug the viewport edge.
const placement = {
  "bottom-start": "origin-top-left supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:[position-area:block-end_span-inline-end]",
  "bottom-end": "origin-top-right supports-[position-area:block-end]:ms-2 supports-[position-area:block-end]:[position-area:block-end_span-inline-start]",
  "top-start": "origin-bottom-left supports-[position-area:block-end]:me-2 supports-[position-area:block-end]:[position-area:block-start_span-inline-end]",
  "top-end": "origin-bottom-right supports-[position-area:block-end]:ms-2 supports-[position-area:block-end]:[position-area:block-start_span-inline-start]",
};

const itemClass = (destructive?: boolean) =>
  cn(
    "flex min-h-9 w-full items-center gap-2 rounded-sm px-3 py-1.5 text-start transition-colors duration-75 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [&_svg]:size-4 [&_svg]:shrink-0",
    destructive
      ? "text-destructive hover:bg-destructive/8 focus-visible:bg-destructive/8"
      : "text-popover-foreground hover:bg-accent focus-visible:bg-accent [&_svg]:text-muted-foreground",
  );
const headingClass = "px-3 pt-1.5 pb-1 text-[0.6875rem]/4 font-medium tracking-wider text-muted-foreground uppercase";
// A submenu panel is plain inline markup until the script turns it into a popover. The script swaps
// the inline classes for the popover classes, so the no-script list needs nothing from the popover set.
const subInline = "grid min-h-0 gap-0.5 overflow-hidden ps-3";
const subPanel = cn(
  "m-auto h-fit max-h-[min(24rem,calc(100dvh-2rem))] w-48 max-w-[calc(100vw-1rem)] overflow-y-auto rounded-lg border border-border bg-popover p-1 text-[0.8125rem] text-popover-foreground shadow-float",
  "-translate-x-1 opacity-0 transition-[opacity,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-x-0 open:opacity-100 starting:open:-translate-x-1 starting:open:opacity-0 motion-reduce:transition-none",
  // The script picks the side (data-side) so the panel never covers its trigger row; it falls back to inline mode when neither side fits.
  "supports-[position-area:inline-end]:m-0 supports-[position-area:inline-end]:-mt-1 supports-[position-area:inline-end]:ms-0.5 supports-[position-area:inline-end]:me-2 supports-[position-area:inline-end]:[position-area:inline-end_span-block-end] supports-[position-area:inline-end]:[position-try-fallbacks:flip-block] supports-[position-area:inline-end]:data-[side=left]:ms-2 supports-[position-area:inline-end]:data-[side=left]:me-0.5 supports-[position-area:inline-end]:data-[side=left]:[position-area:inline-start_span-block-end]",
);
// Below 640 px, or when neither side has room, the submenu opens inline under its trigger and the menu grows.
const subInlinePanel = "grid grid-rows-[0fr] transition-[grid-template-rows] duration-150 ease-snappy data-[open]:grid-rows-[1fr] motion-reduce:transition-none";
---

<Button variant={variant} size={size} popovertarget={id} aria-label={ariaLabel} class={triggerClass} style={`anchor-name: --${id}`}>
  <slot name="trigger">{label}</slot>
</Button>
<div
  popover
  id={id}
  data-haze-menu
  style={`position-anchor: --${id}`}
  class={cn(
    "m-auto max-h-[min(24rem,calc(100dvh-2rem))] w-56 max-w-[calc(100vw-1rem)] overflow-y-auto rounded-lg border border-border bg-popover p-1 text-[0.8125rem] text-popover-foreground shadow-float backdrop:bg-background/60",
    "-translate-y-1.5 starting:open:-translate-y-1.5",
    "scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 starting:open:scale-[0.97] starting:open:opacity-0",
    "supports-[position-area:block-end]:mx-0 supports-[position-area:block-end]:my-1 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]",
    placement[`${side}-${align}`],
    className,
  )}
>
  <slot name="header" />
  <ul role="list" class="grid gap-0.5">
    {
      items.map((item, index) => {
        const subId = `${id}-sub-${index}`;
        return (
          <li class={cn(item.separatorBefore && "mt-1 border-t border-border pt-1")}>
            {item.heading && <p class={headingClass}>{item.heading}</p>}
            {item.items ? (
              <>
                <button
                  type="button"
                  id={`${subId}-trigger`}
                  data-submenu-trigger
                  aria-haspopup="menu"
                  aria-expanded="false"
                  aria-controls={subId}
                  style={`anchor-name: --${subId}`}
                  class={cn(itemClass(), "hidden cursor-pointer aria-expanded:bg-accent [[data-menu-ready]_&]:flex")}
                >
                  {item.icon && <item.icon aria-hidden="true" />}
                  <span class="min-w-0 flex-1 truncate">{item.label}</span>
                  <ChevronRight aria-hidden="true" class="ms-auto" />
                </button>
                <div id={subId} data-submenu-panel data-panel-class={subPanel} data-inline-class={subInlinePanel} aria-labelledby={`${subId}-trigger`} style={`position-anchor: --${subId}`} class="pb-1">
                  <p class={cn(headingClass, "[[data-menu-ready]_&]:hidden")}>{item.label}</p>
                  <ul role="list" class={subInline}>
                    {item.items.map((sub) => (
                      <li class={cn(sub.separatorBefore && "mt-1 border-t border-border pt-1")}>
                        <a href={sub.href} class={itemClass(sub.destructive)}>
                          {sub.icon && <sub.icon aria-hidden="true" />}
                          <span class="min-w-0 flex-1 truncate">{sub.label}</span>
                          {sub.hint && <span class="font-mono text-xs/4 text-muted-foreground">{sub.hint}</span>}
                        </a>
                      </li>
                    ))}
                  </ul>
                </div>
              </>
            ) : (
              <a href={item.href} class={itemClass(item.destructive)}>
                {item.icon && <item.icon aria-hidden="true" />}
                <span class="min-w-0 flex-1 truncate">{item.label}</span>
                {item.hint && <span class="font-mono text-xs/4 text-muted-foreground">{item.hint}</span>}
              </a>
            )}
          </li>
        );
      })
    }
  </ul>
  <slot name="actions" />
</div>

<script>
  const OPEN_DELAY = 100, CLOSE_DELAY = 200, PANEL_NEED = 192 + 2 + 8;
  const narrow = matchMedia("(max-width: 639.98px)");
  const ITEM = "a[href], button[data-submenu-trigger]";

  function enhance(menu: HTMLElement) {
    if (menu.hasAttribute("data-menu-ready")) return;
    const trigger = document.querySelector<HTMLButtonElement>(`[popovertarget="${CSS.escape(menu.id)}"]`);
    if (!trigger) return;
    const usable = (el: HTMLElement) => !el.hidden && el.getAttribute("aria-disabled") !== "true";
    // Items of the root list only: links inside a submenu panel belong to that panel.
    const links = () => [...menu.querySelectorAll<HTMLElement>(ITEM)].filter(el => !el.closest("[data-submenu-panel]") && usable(el));
    const highlight = document.createElement("span");
    highlight.setAttribute("aria-hidden", "true");
    highlight.className = "pointer-events-none absolute top-0 left-0 rounded-sm bg-foreground/8 opacity-0 transition-[translate,width,height,opacity] duration-200 ease-snappy data-[destructive]:bg-destructive/14 motion-reduce:transition-none";
    menu.prepend(highlight);
    const reduced = matchMedia("(prefers-reduced-motion: reduce)");
    const mark = (link: HTMLElement, keyboard = false) => {
      const panel = menu.getBoundingClientRect(), box = link.getBoundingClientRect();
      highlight.style.transitionDuration = keyboard || reduced.matches ? "0s" : "200ms";
      highlight.style.translate = `${box.left - panel.left - menu.clientLeft + menu.scrollLeft}px ${box.top - panel.top - menu.clientTop + menu.scrollTop}px`;
      highlight.style.width = `${box.width}px`;
      highlight.style.height = `${box.height}px`;
      highlight.style.opacity = "1";
      highlight.toggleAttribute("data-destructive", link.classList.contains("text-destructive"));
    };
    links().forEach(link => {
      link.classList.add("relative", "z-10", "[[data-menu-ready]_&]:hover:bg-transparent", "[[data-menu-ready]_&]:focus-visible:bg-transparent");
    });

    // Submenus: one popover="manual" panel per trigger, closed by this script (outside click and
    // Escape on the root menu close everything, and the root's toggle closes every panel).
    const panels = [...menu.querySelectorAll<HTMLElement>("[data-submenu-panel]")];
    const subs = panels.map(panel => {
      const sub = menu.querySelector<HTMLButtonElement>(`[aria-controls="${CSS.escape(panel.id)}"]`)!;
      const row = sub.closest("li")!;
      panel.className = panel.dataset.panelClass ?? "";
      panel.setAttribute("role", "menu");
      panel.setAttribute("popover", "manual");
      panel.querySelectorAll("a[href]").forEach(link => link.setAttribute("role", "menuitem"));
      return { panel, sub, row, openTimer: 0, closeTimer: 0, inline: false };
    });
    type Entry = (typeof subs)[number];
    const isOpen = (entry: Entry) => (entry.inline ? entry.panel.hasAttribute("data-open") : entry.panel.matches(":popover-open"));
    // Switch a panel between the anchored popover and the inline block under its trigger.
    const setMode = (entry: Entry, inline: boolean) => {
      const { panel } = entry;
      if (entry.inline === inline && panel.dataset.mode) return;
      if (panel.matches(":popover-open")) panel.hidePopover();
      panel.removeAttribute("data-open");
      entry.inline = inline;
      panel.dataset.mode = inline ? "inline" : "popover";
      if (inline) {
        panel.removeAttribute("popover");
        panel.className = panel.dataset.inlineClass ?? "";
        panel.inert = true;
      } else {
        panel.inert = false;
        panel.className = panel.dataset.panelClass ?? "";
        panel.setAttribute("popover", "manual");
      }
    };
    // The anchored panel needs 192 px plus gaps on one side of the trigger row; otherwise it goes inline.
    const pickMode = (entry: Entry) => {
      if (narrow.matches) { setMode(entry, true); return; }
      const box = entry.sub.getBoundingClientRect(), width = document.documentElement.clientWidth;
      const right = box.right + PANEL_NEED <= width, left = box.left - PANEL_NEED >= 0;
      if (!right && !left) { setMode(entry, true); return; }
      setMode(entry, false);
      if (right) entry.panel.removeAttribute("data-side"); else entry.panel.setAttribute("data-side", "left");
    };
    subs.forEach(entry => pickMode(entry));
    narrow.addEventListener("change", () => subs.forEach(entry => { closeSub(entry); pickMode(entry); }));
    const panelItems = (panel: HTMLElement) => [...panel.querySelectorAll<HTMLElement>("a[href]")].filter(usable);
    const sync = (entry: Entry) => entry.sub.setAttribute("aria-expanded", String(isOpen(entry)));
    function closeSub(entry: Entry, restore = false) {
      clearTimeout(entry.openTimer);
      clearTimeout(entry.closeTimer);
      if (entry.inline) { entry.panel.removeAttribute("data-open"); entry.panel.inert = true; }
      else if (entry.panel.matches(":popover-open")) entry.panel.hidePopover();
      sync(entry);
      if (restore) entry.sub.focus();
    }
    function openSub(entry: Entry, focusFirst = false) {
      clearTimeout(entry.closeTimer);
      clearTimeout(entry.openTimer);
      subs.forEach(other => { if (other !== entry) closeSub(other); });
      if (!isOpen(entry) && menu.matches(":popover-open")) {
        pickMode(entry);
        if (entry.inline) { entry.panel.inert = false; entry.panel.setAttribute("data-open", ""); }
        else entry.panel.showPopover();
      }
      sync(entry);
      if (focusFirst) panelItems(entry.panel)[0]?.focus();
    }
    subs.forEach(entry => {
      const { panel, sub, row } = entry;
      sub.addEventListener("click", event => {
        if (event.detail === 0) { openSub(entry, true); return; }
        // A mouse click on a panel that hover already opened keeps it open; touch and inline mode toggle.
        const mouse = (event as PointerEvent).pointerType === "mouse";
        if (isOpen(entry)) { if (entry.inline || !mouse) closeSub(entry); }
        else openSub(entry);
      });
      sub.addEventListener("keydown", event => {
        if (event.key !== "ArrowRight") return;
        event.preventDefault();
        openSub(entry, true);
      });
      row.addEventListener("pointerenter", event => {
        if (event.pointerType === "mouse") clearTimeout(entry.closeTimer);
      });
      sub.addEventListener("pointerenter", event => {
        if (event.pointerType !== "mouse" || entry.inline) return;
        clearTimeout(entry.closeTimer);
        if (!isOpen(entry)) {
          clearTimeout(entry.openTimer);
          entry.openTimer = window.setTimeout(() => openSub(entry), OPEN_DELAY);
        }
      });
      // The panel is a DOM child of the row, so crossing the gap into it re-enters the row and cancels this.
      row.addEventListener("pointerleave", event => {
        if (event.pointerType !== "mouse" || entry.inline) return;
        clearTimeout(entry.openTimer);
        entry.closeTimer = window.setTimeout(() => closeSub(entry), CLOSE_DELAY);
      });
      panel.addEventListener("keydown", event => {
        if (event.altKey || event.ctrlKey || event.metaKey) return;
        const options = panelItems(panel), current = options.indexOf(document.activeElement as HTMLElement);
        let next: HTMLElement | undefined;
        if (event.key === "ArrowLeft" || event.key === "Escape") {
          event.preventDefault();
          event.stopPropagation();
          closeSub(entry, true);
          return;
        }
        if (event.key === "ArrowDown") next = options[(current + 1) % options.length];
        else if (event.key === "ArrowUp") next = options[(current - 1 + options.length) % options.length];
        else if (event.key === "Home") next = options[0];
        else if (event.key === "End") next = options.at(-1);
        if (next) { event.preventDefault(); event.stopPropagation(); next.focus(); }
      });
      row.addEventListener("focusout", event => {
        const to = event.relatedTarget as Node | null;
        if (to && !row.contains(to)) closeSub(entry);
      });
      panel.addEventListener("toggle", () => { if (!entry.inline) sync(entry); });
    });

    trigger.addEventListener("keydown", event => {
      if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;
      event.preventDefault();
      if (!menu.matches(":popover-open")) menu.showPopover();
      const options = links();
      const link = event.key === "ArrowUp" ? options.at(-1) : options[0];
      link?.focus();
      if (link) mark(link, true);
    });
    let buffer = "", lastKey = 0;
    menu.addEventListener("keydown", event => {
      if (event.altKey || event.ctrlKey || event.metaKey || event.key === "Tab") return;
      if ((event.target as Element).closest("[data-submenu-panel]")) return;
      const options = links(), current = options.indexOf(document.activeElement as HTMLElement);
      let next: HTMLElement | undefined;
      if (event.key === "ArrowDown") next = options[(current + 1) % options.length];
      else if (event.key === "ArrowUp") next = options[(current - 1 + options.length) % options.length];
      else if (event.key === "Home") next = options[0];
      else if (event.key === "End") next = options.at(-1);
      else if (event.key.length === 1 && event.key !== " ") {
        buffer = performance.now() - lastKey > 650 ? event.key : buffer + event.key;
        lastKey = performance.now();
        const query = [...buffer].every(character => character === buffer[0]) ? buffer[0] : buffer;
        next = [...options.slice(current + 1), ...options.slice(0, current + 1)].find(link => link.textContent?.trim().toLocaleLowerCase().startsWith(query.toLocaleLowerCase()));
      }
      if (next) { event.preventDefault(); next.focus(); mark(next, true); }
    });
    menu.addEventListener("pointermove", event => {
      if (event.pointerType !== "mouse") return;
      const link = (event.target as Element).closest<HTMLElement>(ITEM);
      if (link && links().includes(link)) mark(link);
    });
    menu.addEventListener("focusin", event => {
      const target = event.target as HTMLElement;
      if (target.matches(ITEM) && links().includes(target)) mark(target, true);
    });
    menu.addEventListener("pointerleave", () => {
      if (!menu.contains(document.activeElement)) highlight.style.opacity = "0";
    });
    menu.addEventListener("toggle", () => {
      trigger.setAttribute("aria-expanded", String(menu.matches(":popover-open")));
      if (!menu.matches(":popover-open")) { subs.forEach(entry => closeSub(entry)); highlight.style.opacity = "0"; buffer = ""; }
    });
    menu.addEventListener("click", event => {
      if ((event.target as Element).closest("a[href]")) menu.hidePopover();
    });
    trigger.setAttribute("aria-expanded", String(menu.matches(":popover-open")));
    menu.setAttribute("data-menu-ready", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-menu]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-menus")) {
    document.documentElement.setAttribute("data-haze-menus", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
