# Navigation Menu

Desktop site navigation with mega menu panels on the Popover API, a sliding active indicator, hover intent, and WAI-ARIA disclosure keyboard support.

- Category: Navigation
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/navigation-menu.json
- CLI: `npx markasui@latest add navigation-menu`

## When to use

Main navigation of a marketing site or docs site on desktop, where top-level sections group several destinations with short descriptions.

- Keep top-level labels to one or two words and no more than six entries
- Give each panel link a description of a few words so the panel scans quickly
- Use featured for one highlighted destination per panel, not for every panel
- Pair it with Navbar or Drawer for the mobile menu; this component scrolls horizontally on narrow screens
- Use Menubar for application commands, not Navigation Menu

## Code

### Blade

Save at `resources/views/components/markas/navigation-menu.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'items' => [],
    'navLabel' => 'Main',
])

@php
    $root = 'relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none';
    $list = 'flex items-center gap-1';
    $topItem = 'group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink';
    $chevron = 'size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180';
    $indicatorClass = 'absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100';
    $panel = 'inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0';
    $featuredLayout = 'sm:grid-cols-[13rem_1fr]';
    $featuredClass = 'group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong';
    $featuredArrow = 'relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5';
    $featuredPattern = 'absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]';
    $featuredBody = 'relative grid gap-1';
    $featuredTitle = 'font-semibold';
    $featuredText = 'text-on-primary/75';
    $linkGrid = 'grid content-start gap-1 sm:grid-cols-2';
    $panelLink = 'flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle';
    $iconClass = 'size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]';
    $linkBody = 'grid gap-0.5';
    $linkTitle = 'font-medium';
    $linkDescription = 'text-muted';

    // Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser.
    $safeHref = fn (string $href): string => preg_match('/^(?!https?:|mailto:|tel:)[a-z][\w+.\-]*:/i', preg_replace('/[\x00-\x20]/', '', $href)) === 1 ? '#' : $href;
    $svg = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"';
    $items = array_values($items);
    $activeIndex = -1;
    foreach ($items as $index => $item) {
        if ($item['active'] ?? false) {
            $activeIndex = $index;
            break;
        }
    }

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-navigation-menu|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-navigation-menu-'.hash('xxh32', $idKey.$idIndex);
@endphp

<nav
    x-data="{
        openIndex: null,
        timer: null,
        {{-- Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. Jarak panel dari pemicu dan tepi layar. --}}
        openDelay: 120,
        closeDelay: 180,
        gap: 8,
        {{-- Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. --}}
        tops() {
            return Array.from(this.$root.querySelectorAll(':scope > ul > li > :first-child'));
        },
        {{-- Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. --}}
        sync() {
            const open = this.openIndex;
            const active = @js($activeIndex);
            const target = this.tops()[open ?? Math.max(active, 0)];
            if (!target) return;
            const bar = this.$refs.bar;
            bar.style.width = target.offsetWidth + 'px';
            bar.style.translate = target.offsetLeft + 'px 0';
            bar.dataset.state = open === null && active < 0 ? 'hidden' : 'visible';
            bar.hidden = false;
            const panel = open === null ? null : target.nextElementSibling;
            if (!panel) return;
            const maxLeft = innerWidth - panel.offsetWidth - this.gap;
            panel.style.top = (target.getBoundingClientRect().bottom + this.gap) + 'px';
            panel.style.left = Math.max(this.gap, Math.min(this.$root.getBoundingClientRect().left, maxLeft)) + 'px';
        },
        update: null,
        {{-- Indikator dan panel terbuka mengikuti perubahan, gulir, ukuran jendela, dan font yang selesai dimuat. --}}
        init() {
            this.update = () => this.sync();
            this.update();
            document.fonts?.ready.then(this.update);
            addEventListener('scroll', this.update, true);
            addEventListener('resize', this.update);
            this.$watch('openIndex', () => this.$nextTick(this.update));
        },
        destroy() {
            removeEventListener('scroll', this.update, true);
            removeEventListener('resize', this.update);
            clearTimeout(this.timer);
        },
        {{-- Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel. --}}
        onHover(event) {
            if (event.pointerType !== 'mouse') return;
            clearTimeout(this.timer);
            const open = this.$root.querySelector('[aria-expanded=true] + *');
            const target = event.type === 'pointerenter' ? event.currentTarget.querySelector('[popover]') : null;
            if (target && target === open) return;
            this.timer = setTimeout(() => target ? target.showPopover() : open?.hidePopover(), target ? (open ? 0 : this.openDelay) : this.closeDelay);
        },
        {{-- Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya. --}}
        onClick(event) {
            const panel = event.target.closest('[popover]');
            if (panel) return event.target.closest('a') && panel.hidePopover();
            clearTimeout(this.timer);
            if (event.detail && event.target.closest('[aria-expanded=true]')) event.preventDefault();
        },
        {{-- Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya. --}}
        onKeydown(event) {
            const element = event.target;
            const panel = element.closest('[popover]');
            if (panel) {
                if (event.key !== 'Escape') return;
                panel.hidePopover();
                return panel.previousElementSibling.focus();
            }
            const all = this.tops();
            const current = all.indexOf(element);
            const own = element.nextElementSibling;
            const target = { ArrowRight: current + 1, ArrowLeft: current - 1, Home: 0, End: -1 }[event.key];
            if (target === undefined && (event.key !== 'ArrowDown' || !own)) return;
            event.preventDefault();
            if (target !== undefined) return all.at(target % all.length)?.focus();
            own.showPopover();
            own.querySelector('a')?.focus();
        },
        {{-- Fokus keluar dari entri (pemicu dan panelnya) menutup panel. --}}
        onFocusout(event) {
            const panel = event.target.closest('[popover]') ?? event.target.nextElementSibling;
            const next = event.relatedTarget;
            if (next && panel && !panel.parentElement.contains(next)) panel.hidePopover();
        },
        {{-- beforetoggle berjalan sinkron; posisi panel diatur setelah status berubah. --}}
        onToggle(index, event) {
            if (event.newState === 'open') this.openIndex = index;
            else if (this.openIndex === index) this.openIndex = null;
        },
    }"
    id="{{ $id }}"
    aria-label="{{ $navLabel }}"
    {{ $attributes->except('id')->class([$root]) }}
>
    <ul class="{{ $list }}" @keydown="onKeydown($event)" @click="onClick($event)" @focusout="onFocusout($event)">
        @foreach ($items as $index => $item)
            @php
                $active = (bool) ($item['active'] ?? false);
                $featured = $item['featured'] ?? null;
                $links = $item['links'] ?? [];
                $panelId = $id.'-panel-'.$index;
            @endphp
            <li @pointerenter="onHover($event)" @pointerleave="onHover($event)">
                @if (count($links) > 0 || $featured)
                    <button
                        type="button"
                        popovertarget="{{ $panelId }}"
                        aria-expanded="false"
                        aria-controls="{{ $panelId }}"
                        @if ($active) aria-current="true" @endif
                        :aria-expanded="openIndex === {{ $index }} ? 'true' : 'false'"
                        class="{{ $topItem }}"
                    ><span>{{ $item['label'] }}</span><svg class="{{ $chevron }}" {!! $svg !!}><path d="m6 9 6 6 6-6" /></svg></button>
                    <div
                        id="{{ $panelId }}"
                        popover="auto"
                        wire:ignore.self
                        class="{{ $panel }}{{ $featured ? ' '.$featuredLayout : '' }}"
                        @beforetoggle="onToggle({{ $index }}, $event)"
                    >
                        @if ($featured)
                            <a href="{{ $safeHref((string) $featured['href']) }}" class="{{ $featuredClass }}">
                                <span aria-hidden="true" class="{{ $featuredPattern }}"></span>
                                <svg class="{{ $featuredArrow }}" {!! $svg !!}><path d="M5 12h14m-6-6 6 6-6 6" /></svg>
                                <span class="{{ $featuredBody }}">
                                    <span class="{{ $featuredTitle }}">{{ $featured['title'] }}</span>
                                    @if (! empty($featured['description']))
                                        <span class="{{ $featuredText }}">{{ $featured['description'] }}</span>
                                    @endif
                                </span>
                            </a>
                        @endif
                        @if (count($links) > 0)
                            <ul class="{{ $linkGrid }}">
                                @foreach ($links as $link)
                                    <li>
                                        <a href="{{ $safeHref((string) $link['href']) }}" class="{{ $panelLink }}">
                                            @if (! empty($link['icon']))
                                                <svg class="{{ $iconClass }}" {!! $svg !!}><path d="{{ $link['icon'] }}" /></svg>
                                            @endif
                                            <span class="{{ $linkBody }}">
                                                <span class="{{ $linkTitle }}">{{ $link['label'] }}</span>
                                                @if (! empty($link['description']))
                                                    <span class="{{ $linkDescription }}">{{ $link['description'] }}</span>
                                                @endif
                                            </span>
                                        </a>
                                    </li>
                                @endforeach
                            </ul>
                        @endif
                    </div>
                @else
                    <a href="{{ $safeHref((string) ($item['href'] ?? '#')) }}" @if ($active) aria-current="page" @endif class="{{ $topItem }}">{{ $item['label'] }}</a>
                @endif
            </li>
        @endforeach
    </ul>
    <span x-ref="bar" wire:ignore aria-hidden="true" data-state="hidden" hidden class="{{ $indicatorClass }}"></span>
</nav>
```

```blade
<x-markas.navigation-menu
    :items="[
        ['label' => 'Products', 'featured' => [
            'title' => 'Workflows 2.0',
            'href' => '/workflows',
            'description' => 'Branching, retries, and a visual editor',
        ], 'links' => [
            ['label' => 'Analytics', 'href' => '/analytics', 'description' => 'See where visitors come from', 'icon' => 'M3 3v18h18M7 15l4-4 3 3 5-6'],
            ['label' => 'Automation', 'href' => '/automation', 'description' => 'Run workflows on a schedule'],
        ]],
        ['label' => 'Developers', 'links' => [
            ['label' => 'Documentation', 'href' => '/docs', 'description' => 'Guides and API reference'],
            ['label' => 'Changelog', 'href' => '/changelog', 'description' => 'What shipped this month'],
        ]],
        ['label' => 'Pricing', 'href' => '/pricing', 'active' => true],
    ]"
/>
```

Needs Alpine.js. Livewire 3 and 4 already ship Alpine, so there is nothing else to install.

### React

Save at `src/components/markas/NavigationMenu.tsx`. No extra dependencies.

```tsx
"use client";

import {
  useEffect,
  useId,
  useLayoutEffect,
  useRef,
  useState,
  type ComponentProps,
  type FocusEvent,
  type KeyboardEvent,
  type MouseEvent,
  type PointerEvent,
} from "react";

const root =
  "relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const list = "flex items-center gap-1";
const topItem =
  "group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180";
const indicatorClass =
  "absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100";
const panel =
  "inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const featuredLayout = "sm:grid-cols-[13rem_1fr]";
const featuredClass =
  "group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong";
const featuredArrow =
  "relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5";
const featuredPattern =
  "absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]";
const featuredBody = "relative grid gap-1";
const featuredTitle = "font-semibold";
const featuredText = "text-on-primary/75";
const linkGrid = "grid content-start gap-1 sm:grid-cols-2";
const panelLink =
  "flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle";
const iconClass =
  "size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]";
const linkBody = "grid gap-0.5";
const linkTitle = "font-medium";
const linkDescription = "text-muted";

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

/** Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. */
const OPEN_DELAY = 120;
const CLOSE_DELAY = 180;
/** Jarak panel dari pemicu dan dari tepi layar. */
const GAP = 8;

/** Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. */
const tops = (nav: HTMLElement | null) =>
  Array.from(
    nav?.querySelectorAll<HTMLElement>(":scope > ul > li > :first-child") ?? [],
  );

/** Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. */
function sync(nav: HTMLElement | null, open: number | null, active: number) {
  const target = tops(nav)[open ?? Math.max(active, 0)];
  const bar = target?.closest("ul")?.nextElementSibling as HTMLElement;
  const panel =
    open === null ? null : (target?.nextElementSibling as HTMLElement);
  if (!nav || !target) return;
  bar.style.width = `${target.offsetWidth}px`;
  bar.style.translate = `${target.offsetLeft}px 0`;
  bar.dataset.state = open === null && active < 0 ? "hidden" : "visible";
  bar.hidden = false;
  if (!panel) return;
  const maxLeft = innerWidth - panel.offsetWidth - GAP;
  panel.style.top = `${target.getBoundingClientRect().bottom + GAP}px`;
  panel.style.left = `${Math.max(GAP, Math.min(nav.getBoundingClientRect().left, maxLeft))}px`;
}

export type NavigationMenuLink = {
  label: string;
  href: string;
  description?: string;
  /** Data path SVG (atribut d) untuk ikon 24x24 bergaris. */
  icon?: string;
};

export type NavigationMenuFeatured = {
  title: string;
  href: string;
  description?: string;
};

export type NavigationMenuItem = {
  label: string;
  /** Tujuan link biasa. Diabaikan bila item punya links atau featured. */
  href?: string;
  links?: NavigationMenuLink[];
  featured?: NavigationMenuFeatured;
  /** Tandai halaman atau bagian yang sedang dibuka. */
  active?: boolean;
};

export type NavigationMenuProps = ComponentProps<"nav"> & {
  items: NavigationMenuItem[];
  /** Accessible name of the nav element (aria-label). */
  navLabel?: string;
};

const icon = (path: string, className: string) => (
  <svg
    className={className}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d={path} />
  </svg>
);

function PanelContent({ featured, links = [] }: NavigationMenuItem) {
  return (
    <>
      {featured && (
        <a href={safeHref(featured.href)} className={featuredClass}>
          <span aria-hidden="true" className={featuredPattern} />
          {icon("M5 12h14m-6-6 6 6-6 6", featuredArrow)}
          <span className={featuredBody}>
            <span className={featuredTitle}>{featured.title}</span>
            {featured.description && (
              <span className={featuredText}>{featured.description}</span>
            )}
          </span>
        </a>
      )}
      {links.length > 0 && (
        <ul className={linkGrid}>
          {links.map((link, index) => (
            <li key={index}>
              <a href={safeHref(link.href)} className={panelLink}>
                {link.icon && icon(link.icon, iconClass)}
                <span className={linkBody}>
                  <span className={linkTitle}>{link.label}</span>
                  {link.description && (
                    <span className={linkDescription}>{link.description}</span>
                  )}
                </span>
              </a>
            </li>
          ))}
        </ul>
      )}
    </>
  );
}

export function NavigationMenu({
  items,
  navLabel = "Main",
  id,
  className,
  ...props
}: NavigationMenuProps) {
  const generatedId = useId();
  const baseId = id ?? generatedId;
  const navRef = useRef<HTMLElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
  const [openIndex, setOpenIndex] = useState<number | null>(null);
  const activeIndex = items.findIndex((item) => item.active);

  // Indikator dan panel terbuka mengikuti perubahan, gulir, ukuran jendela, dan font yang selesai dimuat.
  useLayoutEffect(() => {
    const update = () => sync(navRef.current, openIndex, activeIndex);
    update();
    document.fonts?.ready.then(update);
    addEventListener("scroll", update, true);
    addEventListener("resize", update);
    return () => {
      removeEventListener("scroll", update, true);
      removeEventListener("resize", update);
    };
  }, [openIndex, activeIndex]);

  useEffect(() => () => clearTimeout(timer.current), []);

  /** Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel dari hover. */
  const handleHover = (event: PointerEvent) => {
    if (event.pointerType !== "mouse") return;
    clearTimeout(timer.current);
    const open = navRef.current?.querySelector<HTMLElement>(
      "[aria-expanded=true] + *",
    );
    const target =
      event.type === "pointerenter"
        ? event.currentTarget.querySelector<HTMLElement>("[popover]")
        : null;
    if (target && target === open) return;
    timer.current = setTimeout(
      () => {
        if (target) target.showPopover();
        else open?.hidePopover();
      },
      target ? (open ? 0 : OPEN_DELAY) : CLOSE_DELAY,
    );
  };

  // Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya.
  const handleClick = (event: MouseEvent) => {
    const element = event.target as Element;
    const panel = element.closest<HTMLElement>("[popover]");
    if (panel) return element.closest("a") && panel.hidePopover();
    clearTimeout(timer.current);
    if (event.detail && element.closest("[aria-expanded=true]"))
      event.preventDefault();
  };

  // Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya.
  const handleKeyDown = (event: KeyboardEvent) => {
    const element = event.target as HTMLElement;
    const panel = element.closest<HTMLElement>("[popover]");
    if (panel) {
      if (event.key !== "Escape") return;
      panel.hidePopover();
      return (panel.previousElementSibling as HTMLElement).focus();
    }
    const all = tops(navRef.current);
    const current = all.indexOf(element);
    const own = element.nextElementSibling as HTMLElement | null;
    const target = {
      ArrowRight: current + 1,
      ArrowLeft: current - 1,
      Home: 0,
      End: -1,
    }[event.key];
    if (target === undefined && (event.key !== "ArrowDown" || !own)) return;
    event.preventDefault();
    if (target !== undefined) return all.at(target % all.length)?.focus();
    own!.showPopover();
    own!.querySelector("a")?.focus();
  };

  // Fokus keluar dari entri (pemicu dan panelnya) menutup panel.
  const handleBlur = (event: FocusEvent) => {
    const panel = (event.target.closest("[popover]") ??
      event.target.nextElementSibling) as HTMLElement | null;
    const next = event.relatedTarget;
    if (next && panel && !panel.parentElement?.contains(next))
      panel.hidePopover();
  };

  return (
    <nav
      ref={navRef}
      id={baseId}
      aria-label={navLabel}
      className={`${root} ${className ?? ""}`}
      {...props}
    >
      <ul
        className={list}
        onKeyDown={handleKeyDown}
        onClick={handleClick}
        onBlur={handleBlur}
      >
        {items.map((item, index) => {
          const panelId = `${baseId}-panel-${index}`;
          return (
            <li
              key={index}
              onPointerEnter={handleHover}
              onPointerLeave={handleHover}
            >
              {item.links?.length || item.featured ? (
                <>
                  <button
                    type="button"
                    popoverTarget={panelId}
                    aria-expanded={openIndex === index}
                    aria-controls={panelId}
                    aria-current={item.active ? "true" : undefined}
                    className={topItem}
                  >
                    <span>{item.label}</span>
                    {icon("m6 9 6 6 6-6", chevron)}
                  </button>
                  <div
                    id={panelId}
                    popover="auto"
                    className={`${panel} ${item.featured ? featuredLayout : ""}`}
                    // beforetoggle berjalan sinkron; posisi panel diatur efek setelah status berubah.
                    onBeforeToggle={(event) =>
                      setOpenIndex((current) =>
                        event.newState === "open"
                          ? index
                          : current === index
                            ? null
                            : current,
                      )
                    }
                    onToggle={(event) =>
                      event.newState === "open" &&
                      sync(navRef.current, index, activeIndex)
                    }
                  >
                    <PanelContent {...item} />
                  </div>
                </>
              ) : (
                <a
                  href={safeHref(item.href ?? "#")}
                  aria-current={item.active ? "page" : undefined}
                  className={topItem}
                >
                  {item.label}
                </a>
              )}
            </li>
          );
        })}
      </ul>
      <span
        aria-hidden="true"
        data-state="hidden"
        hidden
        className={indicatorClass}
      />
    </nav>
  );
}
```

```tsx
import { NavigationMenu } from "@/components/markas/NavigationMenu";

<NavigationMenu
  items={[
    {
      label: "Products",
      featured: {
        title: "Workflows 2.0",
        href: "/workflows",
        description: "Branching, retries, and a visual editor",
      },
      links: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "See where visitors come from",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        {
          label: "Automation",
          href: "/automation",
          description: "Run workflows on a schedule",
        },
      ],
    },
    {
      label: "Developers",
      links: [
        {
          label: "Documentation",
          href: "/docs",
          description: "Guides and API reference",
        },
        {
          label: "Changelog",
          href: "/changelog",
          description: "What shipped this month",
        },
      ],
    },
    { label: "Pricing", href: "/pricing", active: true },
  ]}
/>;
```

### Vue

Save at `src/components/markas/NavigationMenu.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref, useId, watch } from "vue";

export type NavigationMenuLink = {
  label: string;
  href: string;
  description?: string;
  /** Data path SVG (atribut d) untuk ikon 24x24 bergaris. */
  icon?: string;
};

export type NavigationMenuFeatured = {
  title: string;
  href: string;
  description?: string;
};

export type NavigationMenuItem = {
  label: string;
  /** Tujuan link biasa. Diabaikan bila item punya links atau featured. */
  href?: string;
  links?: NavigationMenuLink[];
  featured?: NavigationMenuFeatured;
  /** Tandai halaman atau bagian yang sedang dibuka. */
  active?: boolean;
};

const props = withDefaults(
  defineProps<{
    items: NavigationMenuItem[];
    navLabel?: string;
    id?: string;
  }>(),
  { navLabel: "Main", id: undefined },
);

const root =
  "relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const list = "flex items-center gap-1";
const topItem =
  "group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180";
const indicatorClass =
  "absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100";
const panel =
  "inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const featuredLayout = "sm:grid-cols-[13rem_1fr]";
const featuredClass =
  "group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong";
const featuredArrow =
  "relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5";
const featuredPattern =
  "absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]";
const featuredBody = "relative grid gap-1";
const featuredTitle = "font-semibold";
const featuredText = "text-on-primary/75";
const linkGrid = "grid content-start gap-1 sm:grid-cols-2";
const panelLink =
  "flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle";
const iconClass =
  "size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]";
const linkBody = "grid gap-0.5";
const linkTitle = "font-medium";
const linkDescription = "text-muted";

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

/** Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. */
const OPEN_DELAY = 120;
const CLOSE_DELAY = 180;
/** Jarak panel dari pemicu dan dari tepi layar. */
const GAP = 8;

/** Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. */
const tops = (nav: HTMLElement | null) =>
  Array.from(
    nav?.querySelectorAll<HTMLElement>(":scope > ul > li > :first-child") ?? [],
  );

/** Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. */
function sync(nav: HTMLElement | null, open: number | null, active: number) {
  const target = tops(nav)[open ?? Math.max(active, 0)];
  const bar = target?.closest("ul")?.nextElementSibling as HTMLElement;
  const panel =
    open === null ? null : (target?.nextElementSibling as HTMLElement);
  if (!nav || !target) return;
  bar.style.width = `${target.offsetWidth}px`;
  bar.style.translate = `${target.offsetLeft}px 0`;
  bar.dataset.state = open === null && active < 0 ? "hidden" : "visible";
  bar.hidden = false;
  if (!panel) return;
  const maxLeft = innerWidth - panel.offsetWidth - GAP;
  panel.style.top = `${target.getBoundingClientRect().bottom + GAP}px`;
  panel.style.left = `${Math.max(GAP, Math.min(nav.getBoundingClientRect().left, maxLeft))}px`;
}

const generatedId = useId();
const baseId = props.id ?? generatedId;
const openIndex = ref<number | null>(null);
let timer: ReturnType<typeof setTimeout> | undefined;
const nav = () => document.getElementById(baseId);

// Indikator dan panel terbuka mengikuti perubahan, gulir, ukuran jendela, dan font yang selesai dimuat.
const update = () =>
  sync(
    nav(),
    openIndex.value,
    props.items.findIndex((item) => item.active),
  );
watch(openIndex, update, { flush: "post" });
onMounted(() => {
  update();
  document.fonts?.ready.then(update);
  addEventListener("scroll", update, true);
  addEventListener("resize", update);
});
onBeforeUnmount(() => {
  removeEventListener("scroll", update, true);
  removeEventListener("resize", update);
});

/** Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel dari hover. */
function onHover(event: PointerEvent) {
  if (event.pointerType !== "mouse") return;
  clearTimeout(timer);
  const open = nav()?.querySelector<HTMLElement>("[aria-expanded=true] + *");
  const target =
    event.type === "pointerenter"
      ? (event.currentTarget as Element).querySelector<HTMLElement>("[popover]")
      : null;
  if (target && target === open) return;
  timer = setTimeout(
    () => {
      if (target) target.showPopover();
      else open?.hidePopover();
    },
    target ? (open ? 0 : OPEN_DELAY) : CLOSE_DELAY,
  );
}

// Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya.
function onClick(event: MouseEvent) {
  const element = event.target as Element;
  const panel = element.closest<HTMLElement>("[popover]");
  if (panel) return element.closest("a") && panel.hidePopover();
  clearTimeout(timer);
  if (event.detail && element.closest("[aria-expanded=true]"))
    event.preventDefault();
}

// Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya.
function onKeydown(event: KeyboardEvent) {
  const element = event.target as HTMLElement;
  const panel = element.closest<HTMLElement>("[popover]");
  if (panel) {
    if (event.key !== "Escape") return;
    panel.hidePopover();
    return (panel.previousElementSibling as HTMLElement).focus();
  }
  const all = tops(nav());
  const current = all.indexOf(element);
  const own = element.nextElementSibling as HTMLElement | null;
  const target = {
    ArrowRight: current + 1,
    ArrowLeft: current - 1,
    Home: 0,
    End: -1,
  }[event.key];
  if (target === undefined && (event.key !== "ArrowDown" || !own)) return;
  event.preventDefault();
  if (target !== undefined) return all.at(target % all.length)?.focus();
  own!.showPopover();
  own!.querySelector("a")?.focus();
}

// Fokus keluar dari entri (pemicu dan panelnya) menutup panel.
function onFocusout(event: FocusEvent) {
  const element = event.target as Element;
  const panel = (element.closest("[popover]") ??
    element.nextElementSibling) as HTMLElement | null;
  const next = event.relatedTarget as Node | null;
  if (next && panel && !panel.parentElement?.contains(next))
    panel.hidePopover();
}
</script>

<template>
  <nav :id="baseId" :aria-label="props.navLabel" :class="root">
    <ul
      :class="list"
      @keydown="onKeydown"
      @click="onClick"
      @focusout="onFocusout"
    >
      <li
        v-for="(item, index) in props.items"
        :key="index"
        @pointerenter="onHover"
        @pointerleave="onHover"
      >
        <template v-if="item.links?.length || item.featured">
          <button
            type="button"
            :popovertarget="`${baseId}-panel-${index}`"
            :aria-expanded="openIndex === index"
            :aria-controls="`${baseId}-panel-${index}`"
            :aria-current="item.active ? 'true' : undefined"
            :class="topItem"
          >
            <span>{{ item.label }}</span>
            <svg
              :class="chevron"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              aria-hidden="true"
            >
              <path d="m6 9 6 6 6-6" />
            </svg>
          </button>
          <div
            :id="`${baseId}-panel-${index}`"
            popover="auto"
            :class="[panel, item.featured && featuredLayout]"
            @beforetoggle="
              openIndex =
                $event.newState === 'open'
                  ? index
                  : openIndex === index
                    ? null
                    : openIndex
            "
          >
            <a
              v-if="item.featured"
              :href="safeHref(item.featured.href)"
              :class="featuredClass"
            >
              <span aria-hidden="true" :class="featuredPattern" />
              <svg
                :class="featuredArrow"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
                aria-hidden="true"
              >
                <path d="M5 12h14m-6-6 6 6-6 6" />
              </svg>
              <span :class="featuredBody">
                <span :class="featuredTitle">{{ item.featured.title }}</span>
                <span v-if="item.featured.description" :class="featuredText">{{
                  item.featured.description
                }}</span>
              </span>
            </a>
            <ul v-if="item.links?.length" :class="linkGrid">
              <li v-for="(link, linkIndex) in item.links" :key="linkIndex">
                <a :href="safeHref(link.href)" :class="panelLink">
                  <svg
                    v-if="link.icon"
                    :class="iconClass"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    stroke-width="1.5"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    aria-hidden="true"
                  >
                    <path :d="link.icon" />
                  </svg>
                  <span :class="linkBody">
                    <span :class="linkTitle">{{ link.label }}</span>
                    <span v-if="link.description" :class="linkDescription">{{
                      link.description
                    }}</span>
                  </span>
                </a>
              </li>
            </ul>
          </div>
        </template>
        <a
          v-else
          :href="safeHref(item.href ?? '#')"
          :aria-current="item.active ? 'page' : undefined"
          :class="topItem"
          >{{ item.label }}</a
        >
      </li>
    </ul>
    <span
      aria-hidden="true"
      data-state="hidden"
      hidden
      :class="indicatorClass"
    />
  </nav>
</template>
```

```vue
<script setup lang="ts">
import NavigationMenu from "@/components/markas/NavigationMenu.vue";

const items = [
  {
    label: "Products",
    featured: {
      title: "Workflows 2.0",
      href: "/workflows",
      description: "Branching, retries, and a visual editor",
    },
    links: [
      {
        label: "Analytics",
        href: "/analytics",
        description: "See where visitors come from",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      {
        label: "Automation",
        href: "/automation",
        description: "Run workflows on a schedule",
      },
    ],
  },
  {
    label: "Developers",
    links: [
      {
        label: "Documentation",
        href: "/docs",
        description: "Guides and API reference",
      },
      {
        label: "Changelog",
        href: "/changelog",
        description: "What shipped this month",
      },
    ],
  },
  { label: "Pricing", href: "/pricing", active: true },
];
</script>

<template>
  <NavigationMenu :items="items" />
</template>
```

### Svelte

Save at `src/lib/components/markas/NavigationMenu.svelte`. No extra dependencies.

```svelte
<script lang="ts" module>
  export type NavigationMenuLink = {
    label: string;
    href: string;
    description?: string;
    /** Data path SVG (atribut d) untuk ikon 24x24 bergaris. */
    icon?: string;
  };

  export type NavigationMenuFeatured = {
    title: string;
    href: string;
    description?: string;
  };

  export type NavigationMenuItem = {
    label: string;
    /** Tujuan link biasa. Diabaikan bila item punya links atau featured. */
    href?: string;
    links?: NavigationMenuLink[];
    featured?: NavigationMenuFeatured;
    /** Tandai halaman atau bagian yang sedang dibuka. */
    active?: boolean;
  };
</script>

<script lang="ts">
  import type { HTMLAttributes } from "svelte/elements";

  const root =
    "relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
  const list = "flex items-center gap-1";
  const topItem =
    "group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink";
  const chevron =
    "size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180";
  const indicatorClass =
    "absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100";
  const panel =
    "inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
  const featuredLayout = "sm:grid-cols-[13rem_1fr]";
  const featuredClass =
    "group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong";
  const featuredArrow =
    "relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5";
  const featuredPattern =
    "absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]";
  const featuredBody = "relative grid gap-1";
  const featuredTitle = "font-semibold";
  const featuredText = "text-on-primary/75";
  const linkGrid = "grid content-start gap-1 sm:grid-cols-2";
  const panelLink =
    "flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle";
  const iconClass =
    "size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]";
  const linkBody = "grid gap-0.5";
  const linkTitle = "font-medium";
  const linkDescription = "text-muted";

  /** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
  const safeHref = (href: string) =>
    /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
      ? "#"
      : href;

  /** Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. */
  const OPEN_DELAY = 120;
  const CLOSE_DELAY = 180;
  /** Jarak panel dari pemicu dan dari tepi layar. */
  const GAP = 8;

  /**
   * Perilaku menu dipasang langsung ke nav (pola yang sama dengan versi Astro): status terbuka
   * dibaca dari DOM lewat aria-expanded, jadi template tetap statis dan bundel tetap kecil.
   */
  function controller(nav: HTMLElement) {
    const list = nav.firstElementChild as HTMLElement;
    const bar = nav.lastElementChild as HTMLElement;
    let timer: ReturnType<typeof setTimeout> | undefined;

    /** Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. */
    const tops = () =>
      Array.from(
        nav.querySelectorAll<HTMLElement>(":scope > ul > li > :first-child"),
      );

    /** Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. */
    const sync = () => {
      const all = tops();
      const open = all.findIndex((el) => el.ariaExpanded === "true");
      const active = all.findIndex((el) => el.hasAttribute("aria-current"));
      const target = all[open >= 0 ? open : Math.max(active, 0)];
      if (!target) return;
      bar.style.width = `${target.offsetWidth}px`;
      bar.style.translate = `${target.offsetLeft}px 0`;
      bar.dataset.state = open < 0 && active < 0 ? "hidden" : "visible";
      bar.hidden = false;
      const panel = target.nextElementSibling as HTMLElement | null;
      if (open < 0 || !panel) return;
      const maxLeft = innerWidth - panel.offsetWidth - GAP;
      panel.style.top = `${target.getBoundingClientRect().bottom + GAP}px`;
      panel.style.left = `${Math.max(GAP, Math.min(nav.getBoundingClientRect().left, maxLeft))}px`;
    };

    /** Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel dari hover. */
    const onHover = (event: PointerEvent) => {
      if (event.pointerType !== "mouse") return;
      clearTimeout(timer);
      const open = nav.querySelector<HTMLElement>("[aria-expanded=true] + *");
      const target =
        event.type === "pointerenter"
          ? (event.currentTarget as Element).querySelector<HTMLElement>(
              "[popover]",
            )
          : null;
      if (target && target === open) return;
      timer = setTimeout(
        () => (target ? target.showPopover() : open?.hidePopover()),
        target ? (open ? 0 : OPEN_DELAY) : CLOSE_DELAY,
      );
    };

    // Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya.
    const onClick = (event: MouseEvent) => {
      const element = event.target as Element;
      const panel = element.closest<HTMLElement>("[popover]");
      if (panel) return element.closest("a") && panel.hidePopover();
      clearTimeout(timer);
      if (event.detail && element.closest("[aria-expanded=true]"))
        event.preventDefault();
    };

    // Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya.
    const onKeydown = (event: KeyboardEvent) => {
      const element = event.target as HTMLElement;
      const panel = element.closest<HTMLElement>("[popover]");
      if (panel) {
        if (event.key !== "Escape") return;
        panel.hidePopover();
        return (panel.previousElementSibling as HTMLElement).focus();
      }
      const all = tops();
      const current = all.indexOf(element);
      const own = element.nextElementSibling as HTMLElement | null;
      const moves: Record<string, number | undefined> = {
        ArrowRight: current + 1,
        ArrowLeft: current - 1,
        Home: 0,
        End: -1,
      };
      const target = moves[event.key];
      if (target === undefined && (event.key !== "ArrowDown" || !own)) return;
      event.preventDefault();
      if (target !== undefined) return all.at(target % all.length)?.focus();
      own!.showPopover();
      own!.querySelector("a")?.focus();
    };

    // Fokus keluar dari entri (pemicu dan panelnya) menutup panel.
    const onFocusout = (event: FocusEvent) => {
      const element = event.target as Element;
      const panel = (element.closest("[popover]") ??
        element.nextElementSibling) as HTMLElement | null;
      const next = event.relatedTarget as Node | null;
      if (next && panel && !panel.parentElement?.contains(next))
        panel.hidePopover();
    };

    // beforetoggle tidak bubble dan berjalan sinkron: dengarkan di fase capture, posisi diatur setelah status berubah.
    const onBeforeToggle = (event: Event) => {
      const open = (event as ToggleEvent).newState === "open";
      (event.target as Element).previousElementSibling?.setAttribute(
        "aria-expanded",
        `${open}`,
      );
      // Event toggle baru datang di task berikutnya; atur posisi sebelum frame pertama panel dilukis.
      if (open) requestAnimationFrame(sync);
    };

    // Indikator dan panel terbuka mengikuti perubahan, gulir, ukuran jendela, dan font yang selesai dimuat.
    const listeners: [EventTarget, string, EventListener, boolean?][] = [
      [list, "keydown", onKeydown as EventListener],
      [list, "click", onClick as EventListener],
      [list, "focusout", onFocusout as EventListener],
      [nav, "beforetoggle", onBeforeToggle, true],
      [nav, "toggle", sync, true],
      [window, "scroll", sync, true],
      [window, "resize", sync],
      ...Array.from(list.children).flatMap((li) =>
        ["pointerenter", "pointerleave"].map(
          (type): [EventTarget, string, EventListener] => [
            li,
            type,
            onHover as EventListener,
          ],
        ),
      ),
    ];
    for (const [target, type, fn, capture] of listeners)
      target.addEventListener(type, fn, capture);
    sync();
    document.fonts?.ready.then(sync);
    return () => {
      clearTimeout(timer);
      for (const [target, type, fn, capture] of listeners)
        target.removeEventListener(type, fn, capture);
    };
  }

  type Props = HTMLAttributes<HTMLElement> & {
    items: NavigationMenuItem[];
    /** Accessible name of the nav element (aria-label). */
    navLabel?: string;
  };

  let {
    items,
    navLabel = "Main",
    id,
    class: className,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const baseId = $derived(id ?? generatedId);
</script>

{#snippet icon(path: string, className: string)}
  <svg
    class={className}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d={path} />
  </svg>
{/snippet}

<nav
  {@attach (node) => {
    void items;
    return controller(node);
  }}
  id={baseId}
  aria-label={navLabel}
  class={[root, className]}
  {...rest}
>
  <ul class={list}>
    {#each items as item, index}
      {@const panelId = `${baseId}-panel-${index}`}
      <li>
        {#if item.links?.length || item.featured}
          <button
            type="button"
            popovertarget={panelId}
            aria-expanded="false"
            aria-controls={panelId}
            aria-current={item.active ? "true" : undefined}
            class={topItem}
          >
            <span>{item.label}</span>
            {@render icon("m6 9 6 6 6-6", chevron)}
          </button>
          <div
            id={panelId}
            popover="auto"
            class={[panel, item.featured && featuredLayout]}
          >
            {#if item.featured}
              <a href={safeHref(item.featured.href)} class={featuredClass}>
                <span aria-hidden="true" class={featuredPattern}></span>
                {@render icon("M5 12h14m-6-6 6 6-6 6", featuredArrow)}
                <span class={featuredBody}>
                  <span class={featuredTitle}>{item.featured.title}</span>
                  {#if item.featured.description}
                    <span class={featuredText}>{item.featured.description}</span
                    >
                  {/if}
                </span>
              </a>
            {/if}
            {#if item.links?.length}
              <ul class={linkGrid}>
                {#each item.links as link}
                  <li>
                    <a href={safeHref(link.href)} class={panelLink}>
                      {#if link.icon}
                        {@render icon(link.icon, iconClass)}
                      {/if}
                      <span class={linkBody}>
                        <span class={linkTitle}>{link.label}</span>
                        {#if link.description}
                          <span class={linkDescription}>{link.description}</span
                          >
                        {/if}
                      </span>
                    </a>
                  </li>
                {/each}
              </ul>
            {/if}
          </div>
        {:else}
          <a
            href={safeHref(item.href ?? "#")}
            aria-current={item.active ? "page" : undefined}
            class={topItem}>{item.label}</a
          >
        {/if}
      </li>
    {/each}
  </ul>
  <span aria-hidden="true" data-state="hidden" hidden class={indicatorClass}
  ></span>
</nav>
```

```svelte
<script lang="ts">
  import NavigationMenu from "$lib/components/markas/NavigationMenu.svelte";

  const items = [
    {
      label: "Products",
      featured: {
        title: "Workflows 2.0",
        href: "/workflows",
        description: "Branching, retries, and a visual editor",
      },
      links: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "See where visitors come from",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        {
          label: "Automation",
          href: "/automation",
          description: "Run workflows on a schedule",
        },
      ],
    },
    {
      label: "Developers",
      links: [
        {
          label: "Documentation",
          href: "/docs",
          description: "Guides and API reference",
        },
        {
          label: "Changelog",
          href: "/changelog",
          description: "What shipped this month",
        },
      ],
    },
    { label: "Pricing", href: "/pricing", active: true },
  ];
</script>

<NavigationMenu {items} />
```

### Astro

Save at `src/components/markas/NavigationMenu.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root =
  "relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const list = "flex items-center gap-1";
const topItem =
  "group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180";
const indicatorClass =
  "absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100";
const panel =
  "inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const featuredLayout = "sm:grid-cols-[13rem_1fr]";
const featuredClass =
  "group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong";
const featuredArrow =
  "relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5";
const featuredPattern =
  "absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]";
const featuredBody = "relative grid gap-1";
const featuredTitle = "font-semibold";
const featuredText = "text-on-primary/75";
const linkGrid = "grid content-start gap-1 sm:grid-cols-2";
const panelLink =
  "flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle";
const iconClass =
  "size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]";
const linkBody = "grid gap-0.5";
const linkTitle = "font-medium";
const linkDescription = "text-muted";

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

export type NavigationMenuLink = {
  label: string;
  href: string;
  description?: string;
  /** Data path SVG (atribut d) untuk ikon 24x24 bergaris. */
  icon?: string;
};

export type NavigationMenuFeatured = {
  title: string;
  href: string;
  description?: string;
};

export type NavigationMenuItem = {
  label: string;
  /** Tujuan link biasa. Diabaikan bila item punya links atau featured. */
  href?: string;
  links?: NavigationMenuLink[];
  featured?: NavigationMenuFeatured;
  /** Tandai halaman atau bagian yang sedang dibuka. */
  active?: boolean;
};

type Props = HTMLAttributes<"nav"> & {
  items: NavigationMenuItem[];
  /** Accessible name of the nav element (aria-label). */
  navLabel?: string;
};

const { items, navLabel = "Main", id, class: className, ...rest } = Astro.props;
const baseId = id ?? `markas-navigation-menu-${crypto.randomUUID().slice(0, 8)}`;
const svg = {
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  "stroke-width": "1.5",
  "stroke-linecap": "round",
  "stroke-linejoin": "round",
  "aria-hidden": "true",
} as const;
---

<markas-navigation-menu class="contents">
  <nav id={baseId} aria-label={navLabel} class:list={[root, className]} {...rest}>
    <ul class={list}>
      {
        items.map((item, index) => {
          const panelId = `${baseId}-panel-${index}`;
          return (
            <li>
              {item.links?.length || item.featured ? (
                <>
                  <button
                    type="button"
                    popovertarget={panelId}
                    aria-expanded="false"
                    aria-controls={panelId}
                    aria-current={item.active ? "true" : undefined}
                    class={topItem}
                  >
                    <span>{item.label}</span>
                    <svg class={chevron} {...svg}>
                      <path d="m6 9 6 6 6-6" />
                    </svg>
                  </button>
                  <div
                    id={panelId}
                    popover="auto"
                    class:list={[panel, item.featured && featuredLayout]}
                  >
                    {item.featured && (
                      <a href={safeHref(item.featured.href)} class={featuredClass}>
                        <span aria-hidden="true" class={featuredPattern} />
                        <svg class={featuredArrow} {...svg}>
                          <path d="M5 12h14m-6-6 6 6-6 6" />
                        </svg>
                        <span class={featuredBody}>
                          <span class={featuredTitle}>{item.featured.title}</span>
                          {item.featured.description && (
                            <span class={featuredText}>{item.featured.description}</span>
                          )}
                        </span>
                      </a>
                    )}
                    {item.links?.length ? (
                      <ul class={linkGrid}>
                        {item.links.map((link) => (
                          <li>
                            <a href={safeHref(link.href)} class={panelLink}>
                              {link.icon && (
                                <svg class={iconClass} {...svg}>
                                  <path d={link.icon} />
                                </svg>
                              )}
                              <span class={linkBody}>
                                <span class={linkTitle}>{link.label}</span>
                                {link.description && (
                                  <span class={linkDescription}>{link.description}</span>
                                )}
                              </span>
                            </a>
                          </li>
                        ))}
                      </ul>
                    ) : null}
                  </div>
                </>
              ) : (
                <a
                  href={safeHref(item.href ?? "#")}
                  aria-current={item.active ? "page" : undefined}
                  class={topItem}
                >
                  {item.label}
                </a>
              )}
            </li>
          );
        })
      }
    </ul>
    <span aria-hidden="true" data-state="hidden" hidden class={indicatorClass}></span>
  </nav>
</markas-navigation-menu>

<script>
  /** Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. Jarak panel dari pemicu dan tepi layar. */
  const OPEN_DELAY = 120;
  const CLOSE_DELAY = 180;
  const GAP = 8;

  type Item = HTMLElement & { nextElementSibling: HTMLElement | null };

  // Satu custom element per menu: ia menyimpan panel terbuka dan timer hover, dan memasang
  // listener gulir dan ukuran jendela hanya selama berada di halaman (juga setelah view transition).
  class MarkasNavigationMenu extends HTMLElement {
    private nav!: HTMLElement;
    private timer?: ReturnType<typeof setTimeout>;
    private readonly update = () => this.sync();

    connectedCallback() {
      if (!this.nav) this.setup();
      this.update();
      document.fonts?.ready.then(this.update);
      addEventListener("scroll", this.update, true);
      addEventListener("resize", this.update);
    }

    disconnectedCallback() {
      removeEventListener("scroll", this.update, true);
      removeEventListener("resize", this.update);
      clearTimeout(this.timer);
    }

    private setup() {
      this.nav = this.querySelector("nav")!;
      const list = this.nav.firstElementChild as HTMLElement;
      list.addEventListener("keydown", (event) => this.onKeydown(event));
      list.addEventListener("click", (event) => this.onClick(event));
      list.addEventListener("focusout", (event) => this.onFocusout(event));
      for (const li of list.children) {
        li.addEventListener("pointerenter", (event) => this.onHover(event as PointerEvent));
        li.addEventListener("pointerleave", (event) => this.onHover(event as PointerEvent));
      }
      // beforetoggle tidak bubble; dengarkan di fase capture. Posisi panel diatur setelah status berubah.
      this.nav.addEventListener(
        "beforetoggle",
        (event) => {
          const panel = event.target as HTMLElement;
          const open = (event as ToggleEvent).newState === "open";
          panel.previousElementSibling!.setAttribute("aria-expanded", `${open}`);
          // Event toggle baru datang di task berikutnya; atur posisi sebelum frame pertama panel dilukis.
          if (open) requestAnimationFrame(this.update);
        },
        true,
      );
      this.nav.addEventListener("toggle", this.update, true);
    }

    /** Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. */
    private tops() {
      return [
        ...this.nav.querySelectorAll<Item>(":scope > ul > li > :first-child"),
      ];
    }

    /** Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. */
    private sync() {
      const all = this.tops();
      const open = all.findIndex((el) => el.ariaExpanded === "true");
      const active = all.findIndex((el) => el.hasAttribute("aria-current"));
      const target = all[open >= 0 ? open : Math.max(active, 0)];
      const bar = this.nav.lastElementChild as HTMLElement;
      if (!target) return;
      bar.style.width = `${target.offsetWidth}px`;
      bar.style.translate = `${target.offsetLeft}px 0`;
      bar.dataset.state = open < 0 && active < 0 ? "hidden" : "visible";
      bar.hidden = false;
      const panel = open < 0 ? null : target.nextElementSibling;
      if (!panel) return;
      const maxLeft = innerWidth - panel.offsetWidth - GAP;
      panel.style.top = `${target.getBoundingClientRect().bottom + GAP}px`;
      panel.style.left = `${Math.max(GAP, Math.min(this.nav.getBoundingClientRect().left, maxLeft))}px`;
    }

    /** Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel. */
    private onHover(event: PointerEvent) {
      if (event.pointerType !== "mouse") return;
      clearTimeout(this.timer);
      const open = this.nav.querySelector<HTMLElement>("[aria-expanded=true] + *");
      const target =
        event.type === "pointerenter"
          ? (event.currentTarget as Element).querySelector<HTMLElement>("[popover]")
          : null;
      if (target && target === open) return;
      this.timer = setTimeout(
        () => (target ? target.showPopover() : open?.hidePopover()),
        target ? (open ? 0 : OPEN_DELAY) : CLOSE_DELAY,
      );
    }

    /** Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya. */
    private onClick(event: MouseEvent) {
      const element = event.target as Element;
      const panel = element.closest<HTMLElement>("[popover]");
      if (panel) return element.closest("a") && panel.hidePopover();
      clearTimeout(this.timer);
      if (event.detail && element.closest("[aria-expanded=true]"))
        event.preventDefault();
    }

    /** Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya. */
    private onKeydown(event: KeyboardEvent) {
      const element = event.target as Item;
      const panel = element.closest<HTMLElement>("[popover]");
      if (panel) {
        if (event.key !== "Escape") return;
        panel.hidePopover();
        return (panel.previousElementSibling as HTMLElement).focus();
      }
      const all = this.tops();
      const current = all.indexOf(element);
      const own = element.nextElementSibling;
      const moves: Record<string, number | undefined> = {
        ArrowRight: current + 1,
        ArrowLeft: current - 1,
        Home: 0,
        End: -1,
      };
      const target = moves[event.key];
      if (target === undefined && (event.key !== "ArrowDown" || !own)) return;
      event.preventDefault();
      if (target !== undefined) return all.at(target % all.length)?.focus();
      own!.showPopover();
      own!.querySelector("a")?.focus();
    }

    /** Fokus keluar dari entri (pemicu dan panelnya) menutup panel. */
    private onFocusout(event: FocusEvent) {
      const element = event.target as Element;
      const panel = (element.closest("[popover]") ??
        element.nextElementSibling) as HTMLElement | null;
      const next = event.relatedTarget as Node | null;
      if (next && panel && !panel.parentElement?.contains(next))
        panel.hidePopover();
    }
  }

  if (!customElements.get("markas-navigation-menu"))
    customElements.define("markas-navigation-menu", MarkasNavigationMenu);
</script>
```

```astro
---
import NavigationMenu from "@/components/markas/NavigationMenu.astro";

const items = [
  {
    label: "Products",
    featured: {
      title: "Workflows 2.0",
      href: "/workflows",
      description: "Branching, retries, and a visual editor",
    },
    links: [
      {
        label: "Analytics",
        href: "/analytics",
        description: "See where visitors come from",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      {
        label: "Automation",
        href: "/automation",
        description: "Run workflows on a schedule",
      },
    ],
  },
  {
    label: "Developers",
    links: [
      {
        label: "Documentation",
        href: "/docs",
        description: "Guides and API reference",
      },
      {
        label: "Changelog",
        href: "/changelog",
        description: "What shipped this month",
      },
    ],
  },
  { label: "Pricing", href: "/pricing", active: true },
];
---

<NavigationMenu items={items} />
```

A small bundled script powers every menu on the page. It also works after view transitions.

### Angular

Save at `src/app/markas/navigation-menu.component.ts`. No extra dependencies.

```ts
import {
  afterRenderEffect,
  ChangeDetectionStrategy,
  Component,
  computed,
  DestroyRef,
  type ElementRef,
  inject,
  input,
  signal,
  viewChild,
} from "@angular/core";

const root =
  "relative block max-w-full overflow-x-auto p-1 text-sm **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const list = "flex items-center gap-1";
const topItem =
  "group inline-flex h-9 items-center gap-1.5 rounded-md px-3 font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink aria-[current]:text-ink aria-expanded:bg-subtle aria-expanded:text-ink";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out group-aria-expanded:rotate-180";
const indicatorClass =
  "absolute bottom-0 left-0 h-0.5 rounded-full bg-primary opacity-0 transition-[translate,width,opacity] duration-200 ease-out data-[state=visible]:opacity-100";
const panel =
  "inset-auto m-0 w-[min(40rem,calc(100vw-1rem))] gap-2 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay open:grid transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const featuredLayout = "sm:grid-cols-[13rem_1fr]";
const featuredClass =
  "group relative flex min-h-36 flex-col justify-between gap-6 overflow-hidden rounded-lg bg-primary p-4 text-on-primary transition-colors duration-150 ease-out hover:bg-primary-strong";
const featuredArrow =
  "relative size-5 self-end transition-transform duration-150 ease-out group-hover:translate-x-0.5";
const featuredPattern =
  "absolute inset-0 bg-[radial-gradient(currentColor_1px,transparent_1px)] bg-size-[12px_12px] opacity-20 [mask-image:linear-gradient(to_bottom,black,transparent_75%)]";
const featuredBody = "relative grid gap-1";
const featuredTitle = "font-semibold";
const featuredText = "text-on-primary/75";
const linkGrid = "grid content-start gap-1 sm:grid-cols-2";
const panelLink =
  "flex items-start gap-3 rounded-lg p-3 transition-colors duration-150 ease-out hover:bg-subtle focus-visible:bg-subtle";
const iconClass =
  "size-9 shrink-0 rounded-md border border-line bg-canvas p-[7px]";
const linkBody = "grid gap-0.5";
const linkTitle = "font-medium";
const linkDescription = "text-muted";

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href: string) =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

/** Jeda sebelum panel terbuka saat kursor singgah, dan sebelum tertutup saat kursor pergi. */
const OPEN_DELAY = 120;
const CLOSE_DELAY = 180;
/** Jarak panel dari pemicu dan dari tepi layar. */
const GAP = 8;

/** Pemicu dan link tingkat atas, berurutan. Panel sebuah pemicu adalah saudara berikutnya. */
const tops = (nav: HTMLElement) =>
  Array.from(
    nav.querySelectorAll<HTMLElement>(":scope > ul > li > :first-child"),
  );

/** Geser indikator ke panel terbuka atau item aktif, lalu letakkan panel terbuka di bawah pemicunya, rata kiri dengan nav. */
function sync(nav: HTMLElement, open: number | null, active: number) {
  const target = tops(nav)[open ?? Math.max(active, 0)];
  const bar = nav.lastElementChild as HTMLElement;
  if (!target) return;
  bar.style.width = `${target.offsetWidth}px`;
  bar.style.translate = `${target.offsetLeft}px 0`;
  bar.dataset["state"] = open === null && active < 0 ? "hidden" : "visible";
  bar.hidden = false;
  const panel =
    open === null ? null : (target.nextElementSibling as HTMLElement | null);
  if (!panel) return;
  const maxLeft = innerWidth - panel.offsetWidth - GAP;
  panel.style.top = `${target.getBoundingClientRect().bottom + GAP}px`;
  panel.style.left = `${Math.max(GAP, Math.min(nav.getBoundingClientRect().left, maxLeft))}px`;
}

export type NavigationMenuLink = {
  label: string;
  href: string;
  description?: string;
  /** Data path SVG (atribut d) untuk ikon 24x24 bergaris. */
  icon?: string;
};

export type NavigationMenuFeatured = {
  title: string;
  href: string;
  description?: string;
};

export type NavigationMenuItem = {
  label: string;
  /** Tujuan link biasa. Diabaikan bila item punya links atau featured. */
  href?: string;
  links?: NavigationMenuLink[];
  featured?: NavigationMenuFeatured;
  /** Tandai halaman atau bagian yang sedang dibuka. */
  active?: boolean;
};

let nextId = 0;

/** Host stays out of layout; id, title, and class move to the nav element. */
@Component({
  selector: "markas-navigation-menu",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.id]": "null", "[attr.title]": "null" },
  template: `
    <nav
      #nav
      [id]="baseId()"
      [attr.aria-label]="navLabel()"
      [class]="navClasses()"
    >
      <ul
        [class]="list"
        (keydown)="handleKeydown($event)"
        (click)="handleClick($event)"
        (focusout)="handleFocusout($event)"
      >
        @for (item of items(); track $index; let index = $index) {
          <li
            (pointerenter)="handleHover($event)"
            (pointerleave)="handleHover($event)"
          >
            @if (item.links?.length || item.featured) {
              <button
                type="button"
                [attr.popovertarget]="panelId(index)"
                [attr.aria-expanded]="openIndex() === index"
                [attr.aria-controls]="panelId(index)"
                [attr.aria-current]="item.active ? 'true' : null"
                [class]="topItem"
              >
                <span>{{ item.label }}</span>
                <svg
                  [class]="chevron"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  aria-hidden="true"
                >
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </button>
              <div
                [id]="panelId(index)"
                popover="auto"
                [class]="item.featured ? panel + ' ' + featuredLayout : panel"
                (beforetoggle)="handleToggle(index, $event)"
              >
                @if (item.featured; as featured) {
                  <a [href]="safeHref(featured.href)" [class]="featuredClass">
                    <span aria-hidden="true" [class]="featuredPattern"></span>
                    <svg
                      [class]="featuredArrow"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      stroke-width="1.5"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                      aria-hidden="true"
                    >
                      <path d="M5 12h14m-6-6 6 6-6 6" />
                    </svg>
                    <span [class]="featuredBody">
                      <span [class]="featuredTitle">{{ featured.title }}</span>
                      @if (featured.description) {
                        <span [class]="featuredText">{{
                          featured.description
                        }}</span>
                      }
                    </span>
                  </a>
                }
                @if (item.links?.length) {
                  <ul [class]="linkGrid">
                    @for (link of item.links; track $index) {
                      <li>
                        <a [href]="safeHref(link.href)" [class]="panelLink">
                          @if (link.icon) {
                            <svg
                              [class]="iconClass"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              stroke-width="1.5"
                              stroke-linecap="round"
                              stroke-linejoin="round"
                              aria-hidden="true"
                            >
                              <path [attr.d]="link.icon" />
                            </svg>
                          }
                          <span [class]="linkBody">
                            <span [class]="linkTitle">{{ link.label }}</span>
                            @if (link.description) {
                              <span [class]="linkDescription">{{
                                link.description
                              }}</span>
                            }
                          </span>
                        </a>
                      </li>
                    }
                  </ul>
                }
              </div>
            } @else {
              <a
                [href]="safeHref(item.href ?? '#')"
                [attr.aria-current]="item.active ? 'page' : null"
                [class]="topItem"
                >{{ item.label }}</a
              >
            }
          </li>
        }
      </ul>
      <span
        aria-hidden="true"
        data-state="hidden"
        hidden
        [class]="indicatorClass"
      ></span>
    </nav>
  `,
})
export class NavigationMenu {
  readonly items = input.required<NavigationMenuItem[]>();
  /** Accessible name of the nav element (aria-label). */
  readonly navLabel = input("Main");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly list = list;
  protected readonly topItem = topItem;
  protected readonly chevron = chevron;
  protected readonly indicatorClass = indicatorClass;
  protected readonly panel = panel;
  protected readonly featuredLayout = featuredLayout;
  protected readonly featuredClass = featuredClass;
  protected readonly featuredArrow = featuredArrow;
  protected readonly featuredPattern = featuredPattern;
  protected readonly featuredBody = featuredBody;
  protected readonly featuredTitle = featuredTitle;
  protected readonly featuredText = featuredText;
  protected readonly linkGrid = linkGrid;
  protected readonly panelLink = panelLink;
  protected readonly iconClass = iconClass;
  protected readonly linkBody = linkBody;
  protected readonly linkTitle = linkTitle;
  protected readonly linkDescription = linkDescription;
  protected readonly safeHref = safeHref;

  protected readonly openIndex = signal<number | null>(null);
  private readonly generatedId = `markas-navigation-menu-${nextId++}`;
  protected readonly baseId = computed(() => this.id() ?? this.generatedId);
  protected readonly navClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly activeIndex = computed(() =>
    this.items().findIndex((item) => item.active),
  );
  private readonly nav = viewChild.required<ElementRef<HTMLElement>>("nav");
  private timer?: ReturnType<typeof setTimeout>;

  constructor() {
    // Indikator dan panel terbuka mengikuti perubahan, gulir, ukuran jendela, dan font yang selesai dimuat.
    afterRenderEffect((onCleanup) => {
      const nav = this.nav().nativeElement;
      const open = this.openIndex();
      const active = this.activeIndex();
      const update = () => sync(nav, open, active);
      update();
      document.fonts?.ready.then(update);
      addEventListener("scroll", update, true);
      addEventListener("resize", update);
      onCleanup(() => {
        removeEventListener("scroll", update, true);
        removeEventListener("resize", update);
      });
    });
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  protected panelId(index: number) {
    return `${this.baseId()}-panel-${index}`;
  }

  /** Hover mouse: masuk membuka setelah jeda (langsung bila panel lain terbuka), keluar menutup panel dari hover. */
  protected handleHover(event: PointerEvent) {
    if (event.pointerType !== "mouse") return;
    clearTimeout(this.timer);
    const open = this.nav().nativeElement.querySelector<HTMLElement>(
      "[aria-expanded=true] + *",
    );
    const target =
      event.type === "pointerenter"
        ? (event.currentTarget as Element).querySelector<HTMLElement>(
            "[popover]",
          )
        : null;
    if (target && target === open) return;
    this.timer = setTimeout(
      () => {
        if (target) target.showPopover();
        else open?.hidePopover();
      },
      target ? (open ? 0 : OPEN_DELAY) : CLOSE_DELAY,
    );
  }

  /** Link di panel menutup panelnya. Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya. */
  protected handleClick(event: MouseEvent) {
    const element = event.target as Element;
    const panel = element.closest<HTMLElement>("[popover]");
    if (panel) {
      if (element.closest("a")) panel.hidePopover();
      return;
    }
    clearTimeout(this.timer);
    if (event.detail && element.closest("[aria-expanded=true]"))
      event.preventDefault();
  }

  /** Panah kiri/kanan, Home, dan End berpindah antar item tingkat atas; ArrowDown membuka panel dan memfokuskan link pertama; Escape di panel menutupnya. */
  protected handleKeydown(event: KeyboardEvent) {
    const element = event.target as HTMLElement;
    const panel = element.closest<HTMLElement>("[popover]");
    if (panel) {
      if (event.key !== "Escape") return;
      panel.hidePopover();
      return (panel.previousElementSibling as HTMLElement).focus();
    }
    const all = tops(this.nav().nativeElement);
    const current = all.indexOf(element);
    const own = element.nextElementSibling as HTMLElement | null;
    const target = (
      {
        ArrowRight: current + 1,
        ArrowLeft: current - 1,
        Home: 0,
        End: -1,
      } as Record<string, number>
    )[event.key];
    if (target === undefined && (event.key !== "ArrowDown" || !own)) return;
    event.preventDefault();
    if (target !== undefined) return all.at(target % all.length)?.focus();
    own!.showPopover();
    own!.querySelector("a")?.focus();
  }

  /** Fokus keluar dari entri (pemicu dan panelnya) menutup panel. */
  protected handleFocusout(event: FocusEvent) {
    const element = event.target as Element;
    const panel = (element.closest("[popover]") ??
      element.nextElementSibling) as HTMLElement | null;
    const next = event.relatedTarget as Node | null;
    if (next && panel && !panel.parentElement?.contains(next))
      panel.hidePopover();
  }

  /** beforetoggle berjalan sinkron; posisi panel diatur efek setelah status berubah. */
  protected handleToggle(index: number, event: Event) {
    const open = (event as ToggleEvent).newState === "open";
    this.openIndex.update((current) =>
      open ? index : current === index ? null : current,
    );
  }
}
```

```ts
import { Component } from "@angular/core";
import {
  NavigationMenu,
  type NavigationMenuItem,
} from "./markas/navigation-menu.component";

@Component({
  selector: "app-site-nav",
  imports: [NavigationMenu],
  template: `<markas-navigation-menu [items]="items" />`,
})
export class SiteNav {
  protected readonly items: NavigationMenuItem[] = [
    {
      label: "Products",
      featured: {
        title: "Workflows 2.0",
        href: "/workflows",
        description: "Branching, retries, and a visual editor",
      },
      links: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "See where visitors come from",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        {
          label: "Automation",
          href: "/automation",
          description: "Run workflows on a schedule",
        },
      ],
    },
    {
      label: "Developers",
      links: [
        {
          label: "Documentation",
          href: "/docs",
          description: "Guides and API reference",
        },
        {
          label: "Changelog",
          href: "/changelog",
          description: "What shipped this month",
        },
      ],
    },
    { label: "Pricing", href: "/pricing", active: true },
  ];
}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `{ label, href?, active?, links?: { label, href, description?, icon? }[], featured?: { title, href, description? } }[]` | [] | Top-level entries. An entry with links or featured becomes a trigger with a panel; otherwise it renders as a plain link to href. icon is the d attribute of a 24x24 stroked SVG path. |
| `navLabel` | `string` | Main | Accessible name of the nav element (aria-label). |
| `id` | `string` | auto | Nav id. Panels use it with a -panel-<index> suffix. |

## Accessibility

- Follows the WAI-ARIA disclosure navigation pattern: each trigger is a button with aria-expanded and aria-controls pointing at its panel, and plain links stay regular links.
- Enter or Space toggles a panel, Arrow Down opens it and focuses the first link. Tab moves through the panel links in document order.
- Arrow Left and Arrow Right move between top-level items, Home and End jump to the first and last.
- Escape closes the panel and returns focus to its trigger. Moving focus outside the entry or clicking outside closes it too.
- The current page link gets aria-current=page; an active trigger gets aria-current=true. The sliding indicator is decorative and hidden from assistive technology.
- Hover opens a panel only for mouse pointers, after a short delay, so touch and keyboard users are not surprised. Motion is removed under prefers-reduced-motion.

## Notes

- An entry with `links` or `featured` becomes a trigger with a panel. Any other entry is a plain link to `href`.
- `icon` is the `d` attribute of a 24x24 stroked SVG path, so the same data works in Blade, React, and Vue. Copy it from an icon set such as Lucide.
- Panels render in the top layer through the Popover API and line up with the left edge of the nav, so switching between triggers swaps content in place. Only one panel is open at a time.
- Mouse hover opens a panel after a short delay and moves straight to the next trigger once one is open. Clicking a trigger that is already open does not close it, so a click right after hover keeps the panel open. Moving the pointer away, clicking outside, or pressing Escape closes it.
- The indicator under the triggers follows the open panel and rests on the entry marked `active`.
- On narrow screens the top level scrolls horizontally. For a full mobile menu, pair it with Navbar or Drawer.
- The nav's accessible name defaults to "Main". Translate it with `navLabel` (`nav-label` in Blade).
