# Shared mega menu

> Navigation disclosures share one floating surface that adjusts its height when a different section is chosen.

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

## Use when
- A product header has several small groups of destination links
- Different navigation sections should reuse one anchored panel instead of opening competing overlays

## Avoid when
- Use navigation-menu for a simpler disclosure navigation tree
- Use dropdown-menu for application commands rather than site destinations

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller-supplied prefix for this component and its related elements. |
| label | `string` | "Explore Northline" | no | Accessible name of the navigation landmark. |
| groups | `{ label: string; links: { label: string; href: string; description?: string }[]; footer?: string }[]` | Product and Resources | no | Navigation sections with destination links and optional contextual footer. |
| class | `string` |  | no | Additional classes for the component root. |

## Accessibility
- Each destination stays a normal link; the component follows disclosure navigation rather than application menu roles.
- The no-script form is a set of native details sections; enhancement moves their original content into one native popover.
- Expanded states follow the active trigger; Escape and focus leaving the navigation close the shared surface.
- Key Enter, Space: Toggle a navigation section.
- Key ArrowLeft, ArrowRight: Move between section triggers.
- Key ArrowDown, Tab: Move from an open trigger into its first destination.
- Key Escape: Close the shared panel and restore focus to its active trigger.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze mega-menu-morph ui for our product. Replace the demo values of these props with our real content: id, label, groups, class. Keep the layout, the heading level rules and these accessibility details: Each destination stays a normal link; the component follows disclosure navigation rather than application menu roles. The no-script form is a set of native details sections; enhancement moves their original content into one native popover. Expanded states follow the active trigger; Escape and focus leaving the navigation close the shared surface. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using mega-menu-morph, check it fits: use it when a product header has several small groups of destination links; different navigation sections should reuse one anchored panel instead of opening competing overlays. Avoid it when use navigation-menu for a simpler disclosure navigation tree; use dropdown-menu for application commands rather than site destinations. Alternatives: @haze/navigation-menu, @haze/dropdown-menu, @haze/popover.

## Example requests that should lead here
- Build original product navigation whose disclosure groups share one resizing popover surface.

## Source

```astro
---
import { ChevronDown, ArrowUpRight } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface MenuLink { label: string; href: string; description?: string }
interface MenuGroup { label: string; links: MenuLink[]; footer?: string }
interface Props {
  id: string;
  label?: string;
  groups?: MenuGroup[];
  class?: string;
}
const { id, label = "Explore Northline", groups = [{ label: "Product", links: [{ label: "Plan work", href: "#planning", description: "Turn an idea into the next step." }, { label: "Ship together", href: "#releases", description: "Keep decisions next to the work." }, { label: "Stay informed", href: "#updates", description: "Read a clear record of what changed." }], footer: "Built for teams with thoughtful workflows." }, { label: "Resources", links: [{ label: "Quick start", href: "#start", description: "Make your first workspace." }, { label: "Guides", href: "#guides", description: "Find a pattern that fits your team." }] }], class: className } = Astro.props;
const trigger = "inline-flex h-8 cursor-pointer items-center justify-between gap-2 rounded-lg px-3 text-[0.8125rem]/5 font-medium transition-colors duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring aria-expanded:bg-accent [&[hidden]]:hidden";
---

<nav id={id} aria-label={label} data-haze-mega-menu-morph class={cn("grid min-w-0 gap-2", className)}>
  <div data-mega-triggers hidden class="flex max-w-full flex-wrap gap-1 [&[hidden]]:hidden">{groups.map((group, index) => <button id={`${id}-trigger-${index}`} data-mega-trigger data-index={index} type="button" aria-expanded="false" aria-controls={`${id}-panel`} style={`anchor-name: --${id}-menu-${index}`} class={trigger}>{group.label}<ChevronDown aria-hidden="true" class="size-3.5 text-muted-foreground transition-[rotate] duration-200 ease-spring motion-reduce:transition-none [[aria-expanded=true]_&]:rotate-180" /></button>)}</div>
  <div data-mega-fallback class="grid gap-2">{groups.map((group, index) => <details class="group min-w-0 rounded-lg border border-border bg-card p-1"><summary class={cn(trigger, "rounded-sm list-none [&::-webkit-details-marker]:hidden")}>{group.label}<ChevronDown aria-hidden="true" class="size-3.5 transition-[rotate] duration-200 ease-spring motion-reduce:transition-none group-open:rotate-180" /></summary><div data-mega-content data-index={index} role="group" aria-label={group.label} class="grid min-w-0 gap-1 [&[hidden]]:hidden"><div class={cn("grid min-w-0 gap-1", group.links.length > 2 && "sm:grid-cols-2")}>{group.links.map(link => <a href={link.href} class="group/link grid min-w-0 content-start gap-1 rounded-sm p-3 text-[0.8125rem]/5 transition-colors duration-75 hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"><span class="flex items-center gap-2 font-medium"><span class="min-w-0 wrap-anywhere">{link.label}</span><ArrowUpRight aria-hidden="true" class="size-3.5 shrink-0 text-muted-foreground" /></span>{link.description && <span class="text-[0.8125rem]/5 wrap-anywhere text-muted-foreground">{link.description}</span>}</a>)}</div>{group.footer && <p class="mt-1 border-t border-border px-3 pt-2 pb-1 text-[0.8125rem]/5 wrap-anywhere text-muted-foreground">{group.footer}</p>}</div></details>)}</div>
  <div id={`${id}-panel`} data-mega-panel role="group" popover class="m-auto max-h-[calc(100dvh-2rem)] w-[min(32rem,calc(100vw-2rem))] max-w-[calc(100vw-1rem)] overflow-x-hidden overflow-y-auto rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-float backdrop:bg-background/60 scale-[0.97] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:scale-100 open:opacity-100 starting:open:-translate-y-1 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]:me-2 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline,flip-block_flip-inline]"></div>
</nav>

<script>
  function initMegaMenuMorphs() {
    document.querySelectorAll<HTMLElement>("[data-haze-mega-menu-morph]").forEach(root => {
      if (root.hasAttribute("data-enhanced")) return;
      const row = root.querySelector<HTMLElement>("[data-mega-triggers]");
      const fallback = root.querySelector<HTMLElement>("[data-mega-fallback]");
      const panel = root.querySelector<HTMLElement>("[data-mega-panel]");
      const triggers = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-mega-trigger]"));
      const contents = Array.from(root.querySelectorAll<HTMLElement>("[data-mega-content]"));
      if (!row || !fallback || !panel || typeof panel.showPopover !== "function" || triggers.length === 0) return;
      let active = -1;
      let sizing: Animation | undefined;
      const close = (focus = false) => { if (panel.matches(":popover-open")) panel.hidePopover(); triggers.forEach(trigger => trigger.setAttribute("aria-expanded", "false")); if (focus) triggers[active]?.focus(); };
      const open = (index: number, focus = false) => {
        const wasOpen = panel.matches(":popover-open");
        const before = panel.getBoundingClientRect();
        const previous = active;
        const refocus = contents[previous]?.contains(document.activeElement) ?? false;
        active = index;
        triggers.forEach((trigger, i) => trigger.setAttribute("aria-expanded", String(i === index)));
        contents.forEach((content, i) => { content.hidden = i !== index; });
        panel.style.setProperty("position-anchor", `--${root.id}-menu-${index}`);
        panel.setAttribute("aria-labelledby", triggers[index]!.id);
        if (!wasOpen) panel.showPopover();
        if (wasOpen && previous !== index && !matchMedia("(prefers-reduced-motion: reduce)").matches) {
          sizing?.cancel();
          const after = panel.getBoundingClientRect();
          sizing = panel.animate([{ height: `${before.height}px` }, { height: `${after.height}px` }], { duration: 200, easing: "cubic-bezier(.2,.8,.2,1)" });
          contents[index]?.animate([{ opacity: .45, translate: `${index > previous ? 6 : -6}px 0` }, { opacity: 1, translate: "0 0" }], { duration: 200 });
        }
        if (focus || refocus) contents[index]?.querySelector<HTMLAnchorElement>("a")?.focus();
      };
      contents.forEach(content => { content.hidden = true; panel.append(content); });
      triggers.forEach((trigger, index) => {
        // An auto popover light-dismisses on pointerdown, before click runs, so note whether this trigger's panel was open.
        let wasActive = false;
        trigger.addEventListener("pointerdown", () => { wasActive = panel.matches(":popover-open") && active === index; });
        const reset = () => { wasActive = false; };
        trigger.addEventListener("pointercancel", reset);
        trigger.addEventListener("pointerleave", reset);
        trigger.addEventListener("click", event => { if (event.detail === 0) wasActive = false; const open_ = wasActive || (panel.matches(":popover-open") && active === index); wasActive = false; if (open_) close(); else open(index); });
        trigger.addEventListener("pointerenter", event => { if (event.pointerType === "mouse" && panel.matches(":popover-open")) open(index); });
        trigger.addEventListener("keydown", event => {
          if (event.key === "ArrowDown") { event.preventDefault(); open(index, true); }
          if (event.key === "Tab" && !event.shiftKey && panel.matches(":popover-open") && active === index) { event.preventDefault(); contents[index]?.querySelector<HTMLAnchorElement>("a")?.focus(); }
          if (event.key === "ArrowRight" || event.key === "ArrowLeft") { event.preventDefault(); const next = (index + (event.key === "ArrowRight" ? 1 : triggers.length - 1)) % triggers.length; triggers[next]?.focus(); if (panel.matches(":popover-open")) open(next); }
        });
      });
      panel.addEventListener("toggle", event => { if ((event as ToggleEvent).newState === "closed") triggers.forEach(trigger => trigger.setAttribute("aria-expanded", "false")); });
      panel.addEventListener("click", event => { if ((event.target as Element).closest("a")) close(); });
      root.addEventListener("keydown", event => { if (event.key === "Escape") { event.preventDefault(); close(true); } });
      root.addEventListener("focusout", () => queueMicrotask(() => { if (!root.contains(document.activeElement)) close(); }));
      fallback.hidden = true;
      row.hidden = false;
      root.setAttribute("data-enhanced", "");
    });
  }
  initMegaMenuMorphs();
  if (!document.documentElement.hasAttribute("data-haze-mega-menu-morph-listener")) {
    document.documentElement.setAttribute("data-haze-mega-menu-morph-listener", "");
    document.addEventListener("astro:page-load", initMegaMenuMorphs);
  }
</script>
```
