# Navbar

Header situs dengan brand, link, menu dropdown, pill hover yang meluncur, area aksi, dan menu seluler dengan grup yang bisa dibuka.

- Kategori: Navigasi
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/navbar.json
- CLI: `npx markasui@latest add navbar`

## Kapan dipakai

Header utama di bagian atas setiap halaman situs atau aplikasi, termasuk situs pemasaran dengan dropdown produk dan sumber daya.

- Tandai halaman saat ini dengan active
- Jaga jumlah link utama sedikit, kelompokkan halaman terkait di children
- Beri deskripsi singkat pada setiap child dropdown bila labelnya saja kurang jelas
- Pakai variant blur dengan sticky hanya di atas konten yang tergulir di bawah header

## Kode

### Blade

Simpan di `resources/views/components/markas/navbar.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'links' => [],
    'variant' => 'default',
    'sticky' => false,
    'menuLabel' => 'Menu',
    'navLabel' => 'Main',
    'mobileNavLabel' => 'Main mobile',
])

@php
    $root = '@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none';
    $variants = [
        'default' => 'top-0 border-b border-line bg-surface',
        'floating' => 'top-3 rounded-2xl border border-line bg-surface shadow-overlay',
        'blur' => 'top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md',
    ];
    $stickyClass = 'sticky z-40';
    $bar = 'flex h-14 items-center gap-4 px-3 @sm:px-4';
    $brandClass = 'flex shrink-0 items-center gap-2 text-sm font-semibold text-ink';
    $desktopNav = 'relative hidden items-center @2xl:flex';
    $indicator = 'absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out';
    $list = 'relative flex items-center';
    $item = 'flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden';
    $chevron = 'size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180';
    $panel = 'inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0';
    $panelList = 'grid grid-flow-col grid-rows-3 gap-1';
    $panelLink = 'flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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';
    $actionsClass = 'ml-auto flex items-center gap-2';
    $toggle = 'inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden';
    $openIcon = 'size-5 in-aria-expanded:hidden';
    $closeIcon = 'hidden size-5 in-aria-expanded:block';
    $mobilePanel = 'border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden';
    $mobileList = 'grid gap-1';
    $groupList = 'my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0';

    // 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]/', '', (string) $href)) === 1 ? '#' : (string) ($href ?? '#');
    $svg = 'viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"';
    $links = array_values($links);

    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-navbar|'.(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-navbar-'.hash('xxh32', $idKey.$idIndex);
    $menuId = $id.'-menu';
@endphp

<header
    x-data="{
        open: false,
        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,
        {{-- Geser indikator ke item yang di-hover, panel terbuka, atau item aktif, lalu letakkan panel terbuka di bawah pemicunya. --}}
        sync() {
            const nav = this.$refs.nav;
            const find = (selector) => nav.querySelector(selector);
            const open = find('[aria-expanded=true]');
            const target = find(':scope>ul>li:hover>:first-child') ?? open ?? find('[aria-current]');
            const pill = nav.firstElementChild;
            pill.hidden = !target;
            if (target) {
                pill.style.width = target.offsetWidth + 'px';
                pill.style.translate = target.offsetLeft + 'px 0';
            }
            const popover = open?.nextElementSibling;
            if (!popover) return;
            const box = open.getBoundingClientRect();
            const maxLeft = innerWidth - popover.offsetWidth - this.gap;
            popover.style.top = (box.bottom + this.gap) + 'px';
            popover.style.left = Math.max(this.gap, Math.min(box.left, maxLeft)) + 'px';
        },
        destroy() {
            clearTimeout(this.timer);
        },
        onEscape() {
            if (!this.open) return;
            this.open = false;
            this.$refs.toggle.focus();
        },
        {{-- Hover mouse: masuk ke item dropdown membukanya setelah jeda, keluar menutupnya setelah jeda. Item tanpa dropdown tidak membatalkan jeda tutup. --}}
        onHover(event) {
            const panel = event.currentTarget.querySelector('[popover]');
            this.sync();
            if (event.pointerType !== 'mouse' || !panel) return;
            const enter = event.type === 'pointerenter';
            clearTimeout(this.timer);
            this.timer = setTimeout(() => panel.togglePopover(enter), enter ? this.openDelay : this.closeDelay);
        },
        {{-- Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya. --}}
        onClick(event) {
            if (event.detail && event.currentTarget.matches('[aria-expanded=true]')) event.preventDefault();
        },
        {{-- ArrowDown di pemicu membuka panel dan memfokuskan link pertama. --}}
        onTriggerKeydown(event) {
            const panel = event.currentTarget.nextElementSibling;
            if (event.key !== 'ArrowDown') return;
            event.preventDefault();
            panel.showPopover();
            panel.querySelector('a')?.focus();
        },
        {{-- beforetoggle berjalan sinkron sehingga aria-expanded selalu terbaru; toggle meletakkan panel setelah tampil. --}}
        onToggle(event) {
            event.target.previousElementSibling.setAttribute('aria-expanded', String(event.newState === 'open'));
            this.sync();
        },
    }"
    @keydown.escape="onEscape()"
    {{ $attributes->merge(['id' => $id])->class([$root, $variants[$variant] ?? $variants['default'], $stickyClass => $sticky]) }}
>
    <div class="{{ $bar }}">
        @isset($brand)
            <div class="{{ $brandClass }}">{{ $brand }}</div>
        @endisset
        <nav x-ref="nav" aria-label="{{ $navLabel }}" class="{{ $desktopNav }}">
            <span aria-hidden="true" hidden class="{{ $indicator }}"></span>
            <ul class="{{ $list }}">
                @foreach ($links as $index => $entry)
                    @php
                        $children = $entry['children'] ?? [];
                        $panelId = $id.'-panel-'.$index;
                    @endphp
                    <li @pointerenter="onHover($event)" @pointerleave="onHover($event)">
                        @if (count($children) > 0)
                            <button
                                type="button"
                                popovertarget="{{ $panelId }}"
                                aria-expanded="false"
                                aria-controls="{{ $panelId }}"
                                class="{{ $item }}"
                                @click="onClick($event)"
                                @keydown="onTriggerKeydown($event)"
                            >{{ $entry['label'] }}<svg class="{{ $chevron }}" {!! $svg !!}><path d="m6 9 6 6 6-6" /></svg></button>
                            <div
                                id="{{ $panelId }}"
                                popover="auto"
                                wire:ignore.self
                                class="{{ $panel }}"
                                @beforetoggle="onToggle($event)"
                                @toggle="onToggle($event)"
                            >
                                <ul class="{{ $panelList }}">
                                    @foreach ($children as $child)
                                        <li>
                                            <a href="{{ $safeHref($child['href'] ?? null) }}" class="{{ $panelLink }}">
                                                @if (! empty($child['icon']))
                                                    <svg class="{{ $iconClass }}" {!! $svg !!}><path d="{{ $child['icon'] }}" /></svg>
                                                @endif
                                                <span class="{{ $linkBody }}">
                                                    <span class="{{ $linkTitle }}">{{ $child['label'] }}</span>
                                                    @if (! empty($child['description']))
                                                        <span class="{{ $linkDescription }}">{{ $child['description'] }}</span>
                                                    @endif
                                                </span>
                                            </a>
                                        </li>
                                    @endforeach
                                </ul>
                            </div>
                        @else
                            <a href="{{ $safeHref($entry['href'] ?? null) }}" @if (! empty($entry['active'])) aria-current="page" @endif class="{{ $item }}">{{ $entry['label'] }}</a>
                        @endif
                    </li>
                @endforeach
            </ul>
        </nav>
        <div class="{{ $actionsClass }}">
            {{ $actions ?? '' }}
            <button
                type="button"
                x-ref="toggle"
                aria-label="{{ $menuLabel }}"
                aria-expanded="false"
                aria-controls="{{ $menuId }}"
                :aria-expanded="open ? 'true' : 'false'"
                @click="open = ! open"
                class="{{ $toggle }}"
            >
                <svg class="{{ $openIcon }}" {!! $svg !!}><path d="M4 6h16M4 12h16M4 18h16" /></svg>
                <svg class="{{ $closeIcon }}" {!! $svg !!}><path d="M18 6 6 18M6 6l12 12" /></svg>
            </button>
        </div>
    </div>
    <div
        id="{{ $menuId }}"
        data-state="closed"
        hidden
        :data-state="open ? 'open' : 'closed'"
        :hidden="! open"
        class="{{ $mobilePanel }}"
    >
        <nav aria-label="{{ $mobileNavLabel }}" class="{{ $mobileList }}">
            @foreach ($links as $entry)
                @if (count($entry['children'] ?? []) > 0)
                    <details wire:ignore.self>
                        <summary class="{{ $item }}">{{ $entry['label'] }}<svg class="{{ $chevron }}" {!! $svg !!}><path d="m6 9 6 6 6-6" /></svg></summary>
                        <div class="{{ $groupList }}">
                            @foreach ($entry['children'] as $child)
                                <a href="{{ $safeHref($child['href'] ?? null) }}" class="{{ $item }}">{{ $child['label'] }}</a>
                            @endforeach
                        </div>
                    </details>
                @else
                    <a href="{{ $safeHref($entry['href'] ?? null) }}" @if (! empty($entry['active'])) aria-current="page" @endif class="{{ $item }}">{{ $entry['label'] }}</a>
                @endif
            @endforeach
        </nav>
    </div>
</header>
```

```blade
<x-markas.navbar
    nav-label="Utama"
    mobile-nav-label="Utama seluler"
    variant="blur"
    :sticky="true"
    :links="[
        ['label' => 'Beranda', 'href' => '/', 'active' => true],
        ['label' => 'Produk', 'children' => [
            [
                'label' => 'Analitik',
                'href' => '/analitik',
                'description' => 'Pantau pemakaian secara langsung',
                'icon' => 'M3 3v18h18M7 15l4-4 3 3 5-6',
            ],
            ['label' => 'Otomasi', 'href' => '/otomasi'],
        ]],
        ['label' => 'Harga', 'href' => '/harga'],
    ]"
>
    <x-slot:brand>MarkasUI</x-slot:brand>
    <x-slot:actions>
        <x-markas.button size="sm">Masuk</x-markas.button>
    </x-slot:actions>
</x-markas.navbar>
```

Butuh Alpine.js untuk dropdown dan menu seluler.

### React

Simpan di `src/components/markas/Navbar.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

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

const root =
  "@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const variants = {
  default: "top-0 border-b border-line bg-surface",
  floating: "top-3 rounded-2xl border border-line bg-surface shadow-overlay",
  blur: "top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md",
};
const stickyClass = "sticky z-40";
const bar = "flex h-14 items-center gap-4 px-3 @sm:px-4";
const brandClass =
  "flex shrink-0 items-center gap-2 text-sm font-semibold text-ink";
const desktopNav = "relative hidden items-center @2xl:flex";
const indicator =
  "absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out";
const list = "relative flex items-center";
const item =
  "flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180";
const panel =
  "inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const panelList = "grid grid-flow-col grid-rows-3 gap-1";
const panelLink =
  "flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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";
const actionsClass = "ml-auto flex items-center gap-2";
const toggle =
  "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden";
const openIcon = "size-5 in-aria-expanded:hidden";
const closeIcon = "hidden size-5 in-aria-expanded:block";
const mobilePanel =
  "border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden";
const mobileList = "grid gap-1";
const groupList =
  "my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0";

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href = "#") =>
  /^(?!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;

/**
 * Geser indikator ke item yang di-hover, panel terbuka, atau item aktif, lalu letakkan panel terbuka
 * di bawah pemicunya. Indikator adalah anak pertama nav, panel adalah saudara berikutnya dari pemicu.
 */
function sync(nav: Element) {
  const find = (selector: string) => nav.querySelector<HTMLElement>(selector);
  const open = find("[aria-expanded=true]");
  const target =
    find(":scope>ul>li:hover>:first-child") ?? open ?? find("[aria-current]");
  const pill = nav.firstElementChild as HTMLElement;
  pill.hidden = !target;
  if (target) {
    pill.style.width = `${target.offsetWidth}px`;
    pill.style.translate = `${target.offsetLeft}px 0`;
  }
  const popover = open?.nextElementSibling as HTMLElement | undefined;
  if (!popover) return;
  const box = open!.getBoundingClientRect();
  const maxLeft = innerWidth - popover.offsetWidth - GAP;
  popover.style.top = `${box.bottom + GAP}px`;
  popover.style.left = `${Math.max(GAP, Math.min(box.left, maxLeft))}px`;
}

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

export type NavbarLink = {
  label: ReactNode;
  /** Tujuan link biasa. Diabaikan bila item punya children. */
  href?: string;
  active?: boolean;
  /** Link di dropdown. Item dengan children menjadi pemicu dropdown. */
  children?: NavbarChild[];
};

export type NavbarProps = ComponentProps<"header"> & {
  links?: NavbarLink[];
  brand?: ReactNode;
  actions?: ReactNode;
  /** default: garis bawah tipis, floating: mengambang membulat, blur: latar semi transparan. */
  variant?: keyof typeof variants;
  sticky?: boolean;
  /** Accessible label of the mobile menu button. */
  menuLabel?: string;
  /** Accessible label of the desktop nav element. */
  navLabel?: string;
  /** Accessible label of the mobile nav element. */
  mobileNavLabel?: string;
};

const svg = (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>
);

/** Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya. */
const handleClick = (event: MouseEvent<HTMLElement>) => {
  if (event.detail && event.currentTarget.matches("[aria-expanded=true]"))
    event.preventDefault();
};

/** ArrowDown di pemicu membuka panel dan memfokuskan link pertama. */
const handleTriggerKeyDown = (event: KeyboardEvent<HTMLElement>) => {
  const panel = event.currentTarget.nextElementSibling as HTMLElement;
  if (event.key !== "ArrowDown") return;
  event.preventDefault();
  panel.showPopover();
  panel.querySelector("a")?.focus();
};

/** beforetoggle berjalan sinkron sehingga aria-expanded selalu terbaru; toggle meletakkan panel setelah tampil. */
const handleToggle = (event: ToggleEvent<HTMLElement>) => {
  const panel = event.currentTarget;
  panel.previousElementSibling!.setAttribute(
    "aria-expanded",
    String(event.newState === "open"),
  );
  sync(panel.closest("nav")!);
};

export function Navbar({
  links = [],
  brand,
  actions,
  variant = "default",
  sticky = false,
  menuLabel = "Menu",
  navLabel = "Main",
  mobileNavLabel = "Main mobile",
  id,
  className,
  onKeyDown,
  ...props
}: NavbarProps) {
  const generatedId = useId();
  const navbarId = id ?? generatedId;
  const menuId = `${navbarId}-menu`;
  const [open, setOpen] = useState(false);
  const toggleRef = useRef<HTMLButtonElement>(null);
  const timer = useRef<ReturnType<typeof setTimeout>>(undefined);

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

  const handleKeyDown = (event: KeyboardEvent<HTMLElement>) => {
    if (event.key === "Escape" && open) {
      setOpen(false);
      toggleRef.current?.focus();
    }
    onKeyDown?.(event);
  };

  /** Hover mouse: masuk ke item dropdown membukanya setelah jeda, keluar menutupnya setelah jeda. Item tanpa dropdown tidak membatalkan jeda tutup. */
  const handleHover = (event: PointerEvent<HTMLElement>) => {
    const item = event.currentTarget;
    const panel = item.querySelector<HTMLElement>("[popover]");
    sync(item.closest("nav")!);
    if (event.pointerType !== "mouse" || !panel) return;
    const enter = event.type === "pointerenter";
    clearTimeout(timer.current);
    timer.current = setTimeout(
      () => panel.togglePopover(enter),
      enter ? OPEN_DELAY : CLOSE_DELAY,
    );
  };

  return (
    <header
      id={navbarId}
      className={cx(root, variants[variant], sticky && stickyClass, className)}
      onKeyDown={handleKeyDown}
      {...props}
    >
      <div className={bar}>
        {brand && <div className={brandClass}>{brand}</div>}
        <nav aria-label={navLabel} className={desktopNav}>
          <span aria-hidden="true" hidden className={indicator} />
          <ul className={list}>
            {links.map((entry, index) => {
              const panelId = `${navbarId}-panel-${index}`;
              return (
                <li
                  key={index}
                  onPointerEnter={handleHover}
                  onPointerLeave={handleHover}
                >
                  {entry.children?.length ? (
                    <>
                      <button
                        type="button"
                        popoverTarget={panelId}
                        aria-expanded="false"
                        aria-controls={panelId}
                        className={item}
                        onClick={handleClick}
                        onKeyDown={handleTriggerKeyDown}
                      >
                        {entry.label}
                        {svg("m6 9 6 6 6-6", chevron)}
                      </button>
                      <div
                        id={panelId}
                        popover="auto"
                        className={panel}
                        onBeforeToggle={handleToggle}
                        onToggle={handleToggle}
                      >
                        <ul className={panelList}>
                          {entry.children.map((child, childIndex) => (
                            <li key={childIndex}>
                              <a
                                href={safeHref(child.href)}
                                className={panelLink}
                              >
                                {child.icon && svg(child.icon, iconClass)}
                                <span className={linkBody}>
                                  <span className={linkTitle}>
                                    {child.label}
                                  </span>
                                  {child.description && (
                                    <span className={linkDescription}>
                                      {child.description}
                                    </span>
                                  )}
                                </span>
                              </a>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </>
                  ) : (
                    <a
                      href={safeHref(entry.href)}
                      aria-current={entry.active ? "page" : undefined}
                      className={item}
                    >
                      {entry.label}
                    </a>
                  )}
                </li>
              );
            })}
          </ul>
        </nav>
        <div className={actionsClass}>
          {actions}
          <button
            ref={toggleRef}
            type="button"
            aria-label={menuLabel}
            aria-expanded={open}
            aria-controls={menuId}
            onClick={() => setOpen((value) => !value)}
            className={toggle}
          >
            {svg("M4 6h16M4 12h16M4 18h16", openIcon)}
            {svg("M18 6 6 18M6 6l12 12", closeIcon)}
          </button>
        </div>
      </div>
      <div
        id={menuId}
        data-state={open ? "open" : "closed"}
        hidden={!open}
        className={mobilePanel}
      >
        <nav aria-label={mobileNavLabel} className={mobileList}>
          {links.map((entry, index) =>
            entry.children?.length ? (
              <details key={index}>
                <summary className={item}>
                  {entry.label}
                  {svg("m6 9 6 6 6-6", chevron)}
                </summary>
                <div className={groupList}>
                  {entry.children.map((child, childIndex) => (
                    <a
                      key={childIndex}
                      href={safeHref(child.href)}
                      className={item}
                    >
                      {child.label}
                    </a>
                  ))}
                </div>
              </details>
            ) : (
              <a
                key={index}
                href={safeHref(entry.href)}
                aria-current={entry.active ? "page" : undefined}
                className={item}
              >
                {entry.label}
              </a>
            ),
          )}
        </nav>
      </div>
    </header>
  );
}
```

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

<Navbar
  variant="blur"
  sticky
  brand="MarkasUI"
  navLabel="Utama"
  mobileNavLabel="Utama seluler"
  links={[
    { label: "Beranda", href: "/", active: true },
    {
      label: "Produk",
      children: [
        {
          label: "Analitik",
          href: "/analitik",
          description: "Pantau pemakaian secara langsung",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Otomasi", href: "/otomasi" },
      ],
    },
    { label: "Harga", href: "/harga" },
  ]}
  actions={<Button size="sm">Masuk</Button>}
/>;
```

### Vue

Simpan di `src/components/markas/Navbar.vue`. Tanpa dependensi tambahan.

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

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

export type NavbarLink = {
  label: string;
  /** Tujuan link biasa. Diabaikan bila item punya children. */
  href?: string;
  active?: boolean;
  /** Link di dropdown. Item dengan children menjadi pemicu dropdown. */
  children?: NavbarChild[];
};

const props = withDefaults(
  defineProps<{
    links?: NavbarLink[];
    /** default: garis bawah tipis, floating: mengambang membulat, blur: latar semi transparan. */
    variant?: "default" | "floating" | "blur";
    sticky?: boolean;
    id?: string;
    menuLabel?: string;
    navLabel?: string;
    mobileNavLabel?: string;
  }>(),
  {
    links: () => [],
    variant: "default",
    sticky: false,
    id: undefined,
    menuLabel: "Menu",
    navLabel: "Main",
    mobileNavLabel: "Main mobile",
  },
);

const root =
  "@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const variants = {
  default: "top-0 border-b border-line bg-surface",
  floating: "top-3 rounded-2xl border border-line bg-surface shadow-overlay",
  blur: "top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md",
};
const stickyClass = "sticky z-40";
const bar = "flex h-14 items-center gap-4 px-3 @sm:px-4";
const brandClass =
  "flex shrink-0 items-center gap-2 text-sm font-semibold text-ink";
const desktopNav = "relative hidden items-center @2xl:flex";
const indicator =
  "absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out";
const list = "relative flex items-center";
const item =
  "flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180";
const panel =
  "inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const panelList = "grid grid-flow-col grid-rows-3 gap-1";
const panelLink =
  "flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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";
const actionsClass = "ml-auto flex items-center gap-2";
const toggle =
  "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden";
const openIcon = "size-5 in-aria-expanded:hidden";
const closeIcon = "hidden size-5 in-aria-expanded:block";
const mobilePanel =
  "border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden";
const mobileList = "grid gap-1";
const groupList =
  "my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0";

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". Spasi dan karakter kontrol diabaikan seperti di browser. */
const safeHref = (href = "#") =>
  /^(?!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;

/**
 * Geser indikator ke item yang di-hover, panel terbuka, atau item aktif, lalu letakkan panel terbuka
 * di bawah pemicunya. Indikator adalah anak pertama nav, panel adalah saudara berikutnya dari pemicu.
 */
function sync(nav: Element) {
  const find = (selector: string) => nav.querySelector<HTMLElement>(selector);
  const open = find("[aria-expanded=true]");
  const target =
    find(":scope>ul>li:hover>:first-child") ?? open ?? find("[aria-current]");
  const pill = nav.firstElementChild as HTMLElement;
  pill.hidden = !target;
  if (target) {
    pill.style.width = `${target.offsetWidth}px`;
    pill.style.translate = `${target.offsetLeft}px 0`;
  }
  const popover = open?.nextElementSibling as HTMLElement | undefined;
  if (!popover) return;
  const box = open!.getBoundingClientRect();
  const maxLeft = innerWidth - popover.offsetWidth - GAP;
  popover.style.top = `${box.bottom + GAP}px`;
  popover.style.left = `${Math.max(GAP, Math.min(box.left, maxLeft))}px`;
}

const svgAttrs = {
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  "stroke-width": "1.5",
  "stroke-linecap": "round",
  "stroke-linejoin": "round",
  "aria-hidden": "true",
} as const;

const generatedId = useId();
const navbarId = props.id ?? generatedId;
const open = ref(false);
let timer: ReturnType<typeof setTimeout> | undefined;

onBeforeUnmount(() => clearTimeout(timer));

function onEscape(event: KeyboardEvent) {
  if (!open.value) return;
  open.value = false;
  (event.currentTarget as Element)
    .querySelector<HTMLElement>("[aria-controls$=-menu]")
    ?.focus();
}

/** Hover mouse: masuk ke item dropdown membukanya setelah jeda, keluar menutupnya setelah jeda. Item tanpa dropdown tidak membatalkan jeda tutup. */
function onHover(event: PointerEvent) {
  const item = event.currentTarget as Element;
  const panel = item.querySelector<HTMLElement>("[popover]");
  sync(item.closest("nav")!);
  if (event.pointerType !== "mouse" || !panel) return;
  const enter = event.type === "pointerenter";
  clearTimeout(timer);
  timer = setTimeout(
    () => panel.togglePopover(enter),
    enter ? OPEN_DELAY : CLOSE_DELAY,
  );
}

// Klik mouse pada pemicu yang sudah terbuka (biasanya oleh hover) tidak menutupnya.
function onClick(event: MouseEvent) {
  const trigger = event.currentTarget as Element;
  if (event.detail && trigger.matches("[aria-expanded=true]"))
    event.preventDefault();
}

// ArrowDown di pemicu membuka panel dan memfokuskan link pertama.
function onKeydown(event: KeyboardEvent) {
  const panel = (event.currentTarget as HTMLElement)
    .nextElementSibling as HTMLElement;
  if (event.key !== "ArrowDown") return;
  event.preventDefault();
  panel.showPopover();
  panel.querySelector("a")?.focus();
}

// beforetoggle berjalan sinkron sehingga aria-expanded selalu terbaru; toggle meletakkan panel setelah tampil.
function onToggle(event: ToggleEvent) {
  const panel = event.target as HTMLElement;
  panel.previousElementSibling!.setAttribute(
    "aria-expanded",
    String(event.newState === "open"),
  );
  sync(panel.closest("nav")!);
}
</script>

<template>
  <header
    :id="navbarId"
    :class="[root, variants[props.variant], props.sticky && stickyClass]"
    @keydown.escape="onEscape"
  >
    <div :class="bar">
      <div v-if="$slots.brand" :class="brandClass"><slot name="brand" /></div>
      <nav :aria-label="props.navLabel" :class="desktopNav">
        <span aria-hidden="true" hidden :class="indicator" />
        <ul :class="list">
          <li
            v-for="(entry, index) in props.links"
            :key="index"
            @pointerenter="onHover"
            @pointerleave="onHover"
          >
            <template v-if="entry.children?.length">
              <button
                type="button"
                :popovertarget="`${navbarId}-panel-${index}`"
                aria-expanded="false"
                :aria-controls="`${navbarId}-panel-${index}`"
                :class="item"
                @click="onClick"
                @keydown="onKeydown"
              >
                {{ entry.label
                }}<svg :class="chevron" v-bind="svgAttrs">
                  <path d="m6 9 6 6 6-6" />
                </svg>
              </button>
              <div
                :id="`${navbarId}-panel-${index}`"
                popover="auto"
                :class="panel"
                @beforetoggle="onToggle"
                @toggle="onToggle"
              >
                <ul :class="panelList">
                  <li
                    v-for="(child, childIndex) in entry.children"
                    :key="childIndex"
                  >
                    <a :href="safeHref(child.href)" :class="panelLink">
                      <svg
                        v-if="child.icon"
                        :class="iconClass"
                        v-bind="svgAttrs"
                      >
                        <path :d="child.icon" />
                      </svg>
                      <span :class="linkBody">
                        <span :class="linkTitle">{{ child.label }}</span>
                        <span
                          v-if="child.description"
                          :class="linkDescription"
                          >{{ child.description }}</span
                        >
                      </span>
                    </a>
                  </li>
                </ul>
              </div>
            </template>
            <a
              v-else
              :href="safeHref(entry.href)"
              :aria-current="entry.active ? 'page' : undefined"
              :class="item"
              >{{ entry.label }}</a
            >
          </li>
        </ul>
      </nav>
      <div :class="actionsClass">
        <slot name="actions" />
        <button
          type="button"
          :aria-label="props.menuLabel"
          :aria-expanded="open ? 'true' : 'false'"
          :aria-controls="`${navbarId}-menu`"
          :class="toggle"
          @click="open = !open"
        >
          <svg :class="openIcon" v-bind="svgAttrs">
            <path d="M4 6h16M4 12h16M4 18h16" />
          </svg>
          <svg :class="closeIcon" v-bind="svgAttrs">
            <path d="M18 6 6 18M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>
    <div
      :id="`${navbarId}-menu`"
      :data-state="open ? 'open' : 'closed'"
      :hidden="!open"
      :class="mobilePanel"
    >
      <nav :aria-label="props.mobileNavLabel" :class="mobileList">
        <template v-for="(entry, index) in props.links" :key="index">
          <details v-if="entry.children?.length">
            <summary :class="item">
              {{ entry.label
              }}<svg :class="chevron" v-bind="svgAttrs">
                <path d="m6 9 6 6 6-6" />
              </svg>
            </summary>
            <div :class="groupList">
              <a
                v-for="(child, childIndex) in entry.children"
                :key="childIndex"
                :href="safeHref(child.href)"
                :class="item"
                >{{ child.label }}</a
              >
            </div>
          </details>
          <a
            v-else
            :href="safeHref(entry.href)"
            :aria-current="entry.active ? 'page' : undefined"
            :class="item"
            >{{ entry.label }}</a
          >
        </template>
      </nav>
    </div>
  </header>
</template>
```

```vue
<script setup lang="ts">
const links = [
  { label: "Beranda", href: "/", active: true },
  {
    label: "Produk",
    children: [
      {
        label: "Analitik",
        href: "/analitik",
        description: "Pantau pemakaian secara langsung",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      { label: "Otomasi", href: "/otomasi" },
    ],
  },
  { label: "Harga", href: "/harga" },
];
</script>

<template>
  <Navbar
    variant="blur"
    sticky
    nav-label="Utama"
    mobile-nav-label="Utama seluler"
    :links="links"
  >
    <template #brand>MarkasUI</template>
    <template #actions>
      <Button size="sm">Masuk</Button>
    </template>
  </Navbar>
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Navbar.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts" module>
  export type NavbarChild = {
    label: string;
    href: string;
    description?: string;
    /** SVG path data (d attribute) for a 24x24 stroke icon. */
    icon?: string;
  };

  export type NavbarLink = {
    label: string;
    /** Plain link target. Ignored when the item has children. */
    href?: string;
    active?: boolean;
    /** Dropdown links. An item with children becomes a dropdown trigger. */
    children?: NavbarChild[];
  };
</script>

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

  const root =
    "@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
  const variants = {
    default: "top-0 border-b border-line bg-surface",
    floating: "top-3 rounded-2xl border border-line bg-surface shadow-overlay",
    blur: "top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md",
  };
  const stickyClass = "sticky z-40";
  const bar = "flex h-14 items-center gap-4 px-3 @sm:px-4";
  const brandClass =
    "flex shrink-0 items-center gap-2 text-sm font-semibold text-ink";
  const desktopNav = "relative hidden items-center @2xl:flex";
  const indicator =
    "absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out";
  const list = "relative flex items-center";
  const item =
    "flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden";
  const chevron =
    "size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180";
  const panel =
    "inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
  const panelList = "grid grid-flow-col grid-rows-3 gap-1";
  const panelLink =
    "flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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";
  const actionsClass = "ml-auto flex items-center gap-2";
  const toggle =
    "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden";
  const openIcon = "size-5 in-aria-expanded:hidden";
  const closeIcon = "hidden size-5 in-aria-expanded:block";
  const mobilePanel =
    "border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden";
  const mobileList = "grid gap-1";
  const groupList =
    "my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0";

  /** Hrefs with a scheme other than http, https, mailto, and tel (javascript: for one) become "#". Spaces and control characters are ignored like browsers do. */
  const safeHref = (href = "#") =>
    /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
      ? "#"
      : href;

  /** Delay before a panel opens when the pointer lingers, and before it closes when the pointer leaves. */
  const OPEN_DELAY = 120;
  const CLOSE_DELAY = 180;
  /** Distance of the panel from its trigger and from the viewport edge. */
  const GAP = 8;

  /**
   * Slide the indicator to the hovered item, the open panel, or the active item, then place the
   * open panel under its trigger. The indicator is the nav's first child, the panel is the trigger's next sibling.
   */
  function sync(nav: Element) {
    const find = (selector: string) => nav.querySelector<HTMLElement>(selector);
    const open = find("[aria-expanded=true]");
    const target =
      find(":scope>ul>li:hover>:first-child") ?? open ?? find("[aria-current]");
    const pill = nav.firstElementChild as HTMLElement;
    pill.hidden = !target;
    if (target) {
      pill.style.width = `${target.offsetWidth}px`;
      pill.style.translate = `${target.offsetLeft}px 0`;
    }
    const popover = open?.nextElementSibling as HTMLElement | undefined;
    if (!popover) return;
    const box = open!.getBoundingClientRect();
    const maxLeft = innerWidth - popover.offsetWidth - GAP;
    popover.style.top = `${box.bottom + GAP}px`;
    popover.style.left = `${Math.max(GAP, Math.min(box.left, maxLeft))}px`;
  }

  type Props = HTMLAttributes<HTMLElement> & {
    links?: NavbarLink[];
    brand?: Snippet;
    actions?: Snippet;
    /** default: hairline bottom border, floating: rounded and floating, blur: translucent background. */
    variant?: keyof typeof variants;
    sticky?: boolean;
    /** Accessible label of the mobile menu button. */
    menuLabel?: string;
    /** Accessible label of the desktop nav element. */
    navLabel?: string;
    /** Accessible label of the mobile nav element. */
    mobileNavLabel?: string;
  };

  let {
    links = [],
    brand,
    actions,
    variant = "default",
    sticky = false,
    menuLabel = "Menu",
    navLabel = "Main",
    mobileNavLabel = "Main mobile",
    id,
    class: className,
    onkeydown,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const navbarId = $derived(id ?? generatedId);
  const menuId = $derived(`${navbarId}-menu`);
  let open = $state(false);
  let toggleButton = $state<HTMLButtonElement>();
  let timer: ReturnType<typeof setTimeout> | undefined;

  onDestroy(() => clearTimeout(timer));

  function handleKeyDown(
    event: KeyboardEvent & { currentTarget: HTMLElement },
  ) {
    if (event.key === "Escape" && open) {
      open = false;
      toggleButton?.focus();
    }
    onkeydown?.(event);
  }

  /** Mouse hover: entering a dropdown item opens it after a delay, leaving closes it after a delay. Items without a dropdown do not cancel the close delay. */
  function handleHover(event: PointerEvent & { currentTarget: HTMLElement }) {
    const entry = event.currentTarget;
    const popover = entry.querySelector<HTMLElement>("[popover]");
    sync(entry.closest("nav")!);
    if (event.pointerType !== "mouse" || !popover) return;
    const enter = event.type === "pointerenter";
    clearTimeout(timer);
    timer = setTimeout(
      () => popover.togglePopover(enter),
      enter ? OPEN_DELAY : CLOSE_DELAY,
    );
  }

  /** A mouse click on a trigger that is already open (usually by hover) does not close it. */
  function handleClick(event: MouseEvent & { currentTarget: HTMLElement }) {
    if (event.detail && event.currentTarget.matches("[aria-expanded=true]"))
      event.preventDefault();
  }

  /** ArrowDown on a trigger opens the panel and focuses the first link. */
  function handleTriggerKeyDown(
    event: KeyboardEvent & { currentTarget: HTMLElement },
  ) {
    const popover = event.currentTarget.nextElementSibling as HTMLElement;
    if (event.key !== "ArrowDown") return;
    event.preventDefault();
    popover.showPopover();
    popover.querySelector("a")?.focus();
  }

  /** beforetoggle runs synchronously so aria-expanded is always current; toggle places the panel once it shows. */
  function handleToggle(event: ToggleEvent & { currentTarget: HTMLElement }) {
    const popover = event.currentTarget;
    popover.previousElementSibling!.setAttribute(
      "aria-expanded",
      String(event.newState === "open"),
    );
    sync(popover.closest("nav")!);
  }
</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}

{#snippet link(entry: Omit<NavbarLink, "children">)}
  <a
    href={safeHref(entry.href)}
    aria-current={entry.active ? "page" : undefined}
    class={item}>{entry.label}</a
  >
{/snippet}

<header
  id={navbarId}
  class={[root, variants[variant], sticky && stickyClass, className]}
  onkeydown={handleKeyDown}
  {...rest}
>
  <div class={bar}>
    {#if brand}
      <div class={brandClass}>{@render brand()}</div>
    {/if}
    <nav aria-label={navLabel} class={desktopNav}>
      <span aria-hidden="true" hidden class={indicator}></span>
      <ul class={list}>
        {#each links as entry, index (index)}
          {@const panelId = `${navbarId}-panel-${index}`}
          <li onpointerenter={handleHover} onpointerleave={handleHover}>
            {#if entry.children?.length}
              <button
                type="button"
                popovertarget={panelId}
                aria-expanded="false"
                aria-controls={panelId}
                class={item}
                onclick={handleClick}
                onkeydown={handleTriggerKeyDown}
                >{entry.label}{@render icon("m6 9 6 6 6-6", chevron)}</button
              >
              <div
                id={panelId}
                popover="auto"
                class={panel}
                onbeforetoggle={handleToggle}
                ontoggle={handleToggle}
              >
                <ul class={panelList}>
                  {#each entry.children as child, childIndex (childIndex)}
                    <li>
                      <a href={safeHref(child.href)} class={panelLink}>
                        {#if child.icon}{@render icon(
                            child.icon,
                            iconClass,
                          )}{/if}
                        <span class={linkBody}>
                          <span class={linkTitle}>{child.label}</span>
                          {#if child.description}
                            <span class={linkDescription}
                              >{child.description}</span
                            >
                          {/if}
                        </span>
                      </a>
                    </li>
                  {/each}
                </ul>
              </div>
            {:else}
              {@render link(entry)}
            {/if}
          </li>
        {/each}
      </ul>
    </nav>
    <div class={actionsClass}>
      {@render actions?.()}
      <button
        bind:this={toggleButton}
        type="button"
        aria-label={menuLabel}
        aria-expanded={open}
        aria-controls={menuId}
        onclick={() => (open = !open)}
        class={toggle}
      >
        {@render icon("M4 6h16M4 12h16M4 18h16", openIcon)}
        {@render icon("M18 6 6 18M6 6l12 12", closeIcon)}
      </button>
    </div>
  </div>
  <div
    id={menuId}
    data-state={open ? "open" : "closed"}
    hidden={!open}
    class={mobilePanel}
  >
    <nav aria-label={mobileNavLabel} class={mobileList}>
      {#each links as entry, index (index)}
        {#if entry.children?.length}
          <details>
            <summary class={item}
              >{entry.label}{@render icon("m6 9 6 6 6-6", chevron)}</summary
            >
            <div class={groupList}>
              {#each entry.children as child, childIndex (childIndex)}
                {@render link(child)}
              {/each}
            </div>
          </details>
        {:else}
          {@render link(entry)}
        {/if}
      {/each}
    </nav>
  </div>
</header>
```

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

  const links = [
    { label: "Beranda", href: "/", active: true },
    {
      label: "Produk",
      children: [
        {
          label: "Analitik",
          href: "/analitik",
          description: "Pantau pemakaian secara langsung",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Otomasi", href: "/otomasi" },
      ],
    },
    { label: "Harga", href: "/harga" },
  ];
</script>

<Navbar
  variant="blur"
  sticky
  navLabel="Utama"
  mobileNavLabel="Utama seluler"
  {links}
>
  {#snippet brand()}MarkasUI{/snippet}
  {#snippet actions()}
    <Button size="sm">Masuk</Button>
  {/snippet}
</Navbar>
```

### Astro

Simpan di `src/components/markas/Navbar.astro`. Tanpa dependensi tambahan.

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

export type NavbarChild = {
  label: string;
  href: string;
  description?: string;
  /** SVG path data (d attribute) for a 24x24 stroke icon. */
  icon?: string;
};

export type NavbarLink = {
  label: string;
  /** Plain link target. Ignored when the item has children. */
  href?: string;
  active?: boolean;
  /** Dropdown links. An item with children becomes a dropdown trigger. */
  children?: NavbarChild[];
};

const root =
  "@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const variants = {
  default: "top-0 border-b border-line bg-surface",
  floating: "top-3 rounded-2xl border border-line bg-surface shadow-overlay",
  blur: "top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md",
};
const stickyClass = "sticky z-40";
const bar = "flex h-14 items-center gap-4 px-3 @sm:px-4";
const brandClass =
  "flex shrink-0 items-center gap-2 text-sm font-semibold text-ink";
const desktopNav = "relative hidden items-center @2xl:flex";
const indicator =
  "absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out";
const list = "relative flex items-center";
const item =
  "flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180";
const panel =
  "inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const panelList = "grid grid-flow-col grid-rows-3 gap-1";
const panelLink =
  "flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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";
const actionsClass = "ml-auto flex items-center gap-2";
const toggle =
  "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden";
const openIcon = "size-5 in-aria-expanded:hidden";
const closeIcon = "hidden size-5 in-aria-expanded:block";
const mobilePanel =
  "border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden";
const mobileList = "grid gap-1";
const groupList =
  "my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0";

/** Hrefs with a scheme other than http, https, mailto, and tel (javascript: for one) become "#". Spaces and control characters are ignored like browsers do. */
const safeHref = (href = "#") =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

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;

type Props = HTMLAttributes<"header"> & {
  links?: NavbarLink[];
  /** default: hairline bottom border, floating: rounded and floating, blur: translucent background. */
  variant?: keyof typeof variants;
  sticky?: boolean;
  /** Accessible label of the mobile menu button. */
  menuLabel?: string;
  /** Accessible label of the desktop nav element. */
  navLabel?: string;
  /** Accessible label of the mobile nav element. */
  mobileNavLabel?: string;
};

const {
  links = [],
  variant = "default",
  sticky = false,
  menuLabel = "Menu",
  navLabel = "Main",
  mobileNavLabel = "Main mobile",
  id,
  class: className,
  ...rest
} = Astro.props;
const navbarId = id ?? `markas-navbar-${crypto.randomUUID().slice(0, 8)}`;
const menuId = `${navbarId}-menu`;
---

<header
  id={navbarId}
  data-markas-navbar
  class:list={[root, variants[variant], sticky && stickyClass, className]}
  {...rest}
>
  <div class={bar}>
    {
      Astro.slots.has("brand") && (
        <div class={brandClass}>
          <slot name="brand" />
        </div>
      )
    }
    <nav aria-label={navLabel} class={desktopNav}>
      <span aria-hidden="true" hidden class={indicator}></span>
      <ul class={list}>
        {
          links.map((entry, index) => {
            const panelId = `${navbarId}-panel-${index}`;
            return (
              <li data-markas-navbar-item>
                {entry.children?.length ? (
                  <>
                    <button
                      type="button"
                      popovertarget={panelId}
                      aria-expanded="false"
                      aria-controls={panelId}
                      data-markas-navbar-trigger
                      class={item}
                    >
                      {entry.label}<svg class={chevron} {...svg}><path d="m6 9 6 6 6-6" /></svg>
                    </button>
                    <div
                      id={panelId}
                      popover="auto"
                      data-markas-navbar-panel
                      class={panel}
                    >
                      <ul class={panelList}>
                        {entry.children.map((child) => (
                          <li>
                            <a href={safeHref(child.href)} class={panelLink}>
                              {child.icon && (
                                <svg class={iconClass} {...svg}>
                                  <path d={child.icon} />
                                </svg>
                              )}
                              <span class={linkBody}>
                                <span class={linkTitle}>{child.label}</span>
                                {child.description && (
                                  <span class={linkDescription}>
                                    {child.description}
                                  </span>
                                )}
                              </span>
                            </a>
                          </li>
                        ))}
                      </ul>
                    </div>
                  </>
                ) : (
                  <a
                    href={safeHref(entry.href)}
                    aria-current={entry.active ? "page" : undefined}
                    class={item}
                  >
                    {entry.label}
                  </a>
                )}
              </li>
            );
          })
        }
      </ul>
    </nav>
    <div class={actionsClass}>
      <slot name="actions" />
      <button
        type="button"
        aria-label={menuLabel}
        aria-expanded="false"
        aria-controls={menuId}
        data-markas-navbar-toggle
        class={toggle}
      >
        <svg class={openIcon} {...svg}>
          <path d="M4 6h16M4 12h16M4 18h16"></path>
        </svg>
        <svg class={closeIcon} {...svg}>
          <path d="M18 6 6 18M6 6l12 12"></path>
        </svg>
      </button>
    </div>
  </div>
  <div id={menuId} data-state="closed" hidden class={mobilePanel}>
    <nav aria-label={mobileNavLabel} class={mobileList}>
      {
        links.map((entry) =>
          entry.children?.length ? (
            <details>
              <summary class={item}>
                {entry.label}<svg class={chevron} {...svg}><path d="m6 9 6 6 6-6" /></svg>
              </summary>
              <div class={groupList}>
                {entry.children.map((child) => (
                  <a href={safeHref(child.href)} class={item}>
                    {child.label}
                  </a>
                ))}
              </div>
            </details>
          ) : (
            <a
              href={safeHref(entry.href)}
              aria-current={entry.active ? "page" : undefined}
              class={item}
            >
              {entry.label}
            </a>
          ),
        )
      }
    </nav>
  </div>
</header>

<script>
  // One set of listeners per page serves every navbar, including markup added later and pages
  // reached through view transitions.
  /** Delay before a panel opens when the pointer lingers, and before it closes when the pointer leaves. */
  const OPEN_DELAY = 120;
  const CLOSE_DELAY = 180;
  /** Distance of the panel from its trigger and from the viewport edge. */
  const GAP = 8;
  let timer: ReturnType<typeof setTimeout> | undefined;

  const closest = (node: EventTarget | null, selector: string) =>
    node instanceof Element ? node.closest<HTMLElement>(selector) : null;

  /**
   * Slide the indicator to the hovered item, the open panel, or the active item, then place the
   * open panel under its trigger. The indicator is the nav's first child, the panel is the trigger's next sibling.
   */
  function sync(nav: Element) {
    const find = (selector: string) => nav.querySelector<HTMLElement>(selector);
    const open = find("[aria-expanded=true]");
    const target =
      find(":scope>ul>li:hover>:first-child") ?? open ?? find("[aria-current]");
    const pill = nav.firstElementChild as HTMLElement;
    pill.hidden = !target;
    if (target) {
      pill.style.width = `${target.offsetWidth}px`;
      pill.style.translate = `${target.offsetLeft}px 0`;
    }
    const popover = open?.nextElementSibling as HTMLElement | undefined;
    if (!popover) return;
    const box = open!.getBoundingClientRect();
    const maxLeft = innerWidth - popover.offsetWidth - GAP;
    popover.style.top = `${box.bottom + GAP}px`;
    popover.style.left = `${Math.max(GAP, Math.min(box.left, maxLeft))}px`;
  }

  /** Opens or closes the mobile panel of a navbar. */
  function setMobile(toggle: HTMLElement, open: boolean) {
    const menu = document.getElementById(toggle.getAttribute("aria-controls")!);
    toggle.setAttribute("aria-expanded", String(open));
    if (!menu) return;
    menu.hidden = !open;
    menu.dataset.state = open ? "open" : "closed";
  }

  document.addEventListener("click", (event) => {
    const toggle = closest(event.target, "[data-markas-navbar-toggle]");
    if (toggle) {
      setMobile(toggle, toggle.getAttribute("aria-expanded") !== "true");
      return;
    }
    // A mouse click on a trigger that is already open (usually by hover) does not close it.
    const trigger = closest(event.target, "[data-markas-navbar-trigger]");
    if (trigger && event.detail && trigger.matches("[aria-expanded=true]"))
      event.preventDefault();
  });

  document.addEventListener("keydown", (event) => {
    // ArrowDown on a trigger opens the panel and focuses the first link.
    const trigger = closest(event.target, "[data-markas-navbar-trigger]");
    if (trigger && event.key === "ArrowDown") {
      const popover = trigger.nextElementSibling as HTMLElement;
      event.preventDefault();
      popover.showPopover();
      popover.querySelector("a")?.focus();
      return;
    }
    // Escape closes the mobile panel and returns focus to the menu button.
    const header = closest(event.target, "[data-markas-navbar]");
    const toggle = header?.querySelector<HTMLElement>(
      "[data-markas-navbar-toggle][aria-expanded=true]",
    );
    if (event.key !== "Escape" || !toggle) return;
    setMobile(toggle, false);
    toggle.focus();
  });

  // pointerenter, pointerleave, beforetoggle, and toggle do not bubble, so listen in the capture phase.
  // Mouse hover: entering a dropdown item opens it after a delay, leaving closes it after a delay.
  // Items without a dropdown do not cancel the close delay.
  const hover = (event: Event) => {
    const entry = event.target;
    if (!(entry instanceof HTMLElement) || !entry.hasAttribute("data-markas-navbar-item"))
      return;
    const popover = entry.querySelector<HTMLElement>("[popover]");
    sync(entry.closest("nav")!);
    if ((event as PointerEvent).pointerType !== "mouse" || !popover) return;
    const enter = event.type === "pointerenter";
    clearTimeout(timer);
    timer = setTimeout(
      () => popover.togglePopover(enter),
      enter ? OPEN_DELAY : CLOSE_DELAY,
    );
  };
  document.addEventListener("pointerenter", hover, true);
  document.addEventListener("pointerleave", hover, true);

  // beforetoggle runs synchronously so aria-expanded is always current; toggle places the panel once it shows.
  const toggled = (event: Event) => {
    const popover = event.target;
    if (!(popover instanceof HTMLElement) || !popover.hasAttribute("data-markas-navbar-panel"))
      return;
    popover.previousElementSibling!.setAttribute(
      "aria-expanded",
      String((event as ToggleEvent).newState === "open"),
    );
    sync(popover.closest("nav")!);
  };
  document.addEventListener("beforetoggle", toggled, true);
  document.addEventListener("toggle", toggled, true);
</script>
```

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

const links = [
  { label: "Beranda", href: "/", active: true },
  {
    label: "Produk",
    children: [
      {
        label: "Analitik",
        href: "/analitik",
        description: "Pantau pemakaian secara langsung",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      { label: "Otomasi", href: "/otomasi" },
    ],
  },
  { label: "Harga", href: "/harga" },
];
---

<Navbar
  variant="blur"
  sticky
  navLabel="Utama"
  mobileNavLabel="Utama seluler"
  links={links}
>
  <Fragment slot="brand">MarkasUI</Fragment>
  <Button slot="actions" size="sm">Masuk</Button>
</Navbar>
```

Satu script kecil yang dibundel menjalankan dropdown dan menu seluler semua navbar di halaman. Tetap jalan setelah view transition.

### Angular

Simpan di `src/app/markas/navbar.component.ts`. Tanpa dependensi tambahan.

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

const root =
  "@container w-full **:focus-visible:outline-2 **:focus-visible:outline-offset-2 **:focus-visible:outline-primary motion-reduce:**:transition-none";
const variants = {
  default: "top-0 border-b border-line bg-surface",
  floating: "top-3 rounded-2xl border border-line bg-surface shadow-overlay",
  blur: "top-0 border-b border-line/60 bg-surface/70 backdrop-blur-md",
};
const stickyClass = "sticky z-40";
const bar = "flex h-14 items-center gap-4 px-3 @sm:px-4";
const brandClass =
  "flex shrink-0 items-center gap-2 text-sm font-semibold text-ink";
const desktopNav = "relative hidden items-center @2xl:flex";
const indicator =
  "absolute inset-y-0 left-0 rounded-md bg-subtle transition-[translate,width] duration-200 ease-out";
const list = "relative flex items-center";
const item =
  "flex h-9 cursor-pointer items-center justify-between gap-1 rounded-md px-3 text-sm font-medium whitespace-nowrap text-muted transition-colors duration-150 ease-out hover:text-ink aria-expanded:text-ink aria-[current]:bg-subtle aria-[current]:text-ink @max-2xl:hover:bg-subtle [&::-webkit-details-marker]:hidden";
const chevron =
  "size-3.5 text-faint transition-transform duration-200 ease-out in-aria-expanded:rotate-180 in-open:rotate-180";
const panel =
  "inset-auto m-0 rounded-xl border border-line bg-surface p-2 text-ink shadow-overlay transition-[opacity,translate] duration-200 ease-out starting:open:translate-y-1.5 starting:open:opacity-0";
const panelList = "grid grid-flow-col grid-rows-3 gap-1";
const panelLink =
  "flex w-64 items-start gap-3 rounded-lg p-3 text-sm 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";
const actionsClass = "ml-auto flex items-center gap-2";
const toggle =
  "inline-flex size-9 shrink-0 items-center justify-center rounded-md text-ink transition-colors duration-150 ease-out hover:bg-subtle @2xl:hidden";
const openIcon = "size-5 in-aria-expanded:hidden";
const closeIcon = "hidden size-5 in-aria-expanded:block";
const mobilePanel =
  "border-t border-line px-4 py-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0 @2xl:hidden";
const mobileList = "grid gap-1";
const groupList =
  "my-1 ml-3 grid gap-1 border-l border-line pl-2 transition-[opacity,translate] duration-200 ease-out starting:-translate-y-1 starting:opacity-0";

/** Hrefs with a scheme other than http, https, mailto, and tel (javascript: for one) become "#". Spaces and control characters are ignored like browsers do. */
const safeHref = (href = "#") =>
  /^(?!https?:|mailto:|tel:)[a-z][\w+.-]*:/i.test(href.replace(/[\0- ]/g, ""))
    ? "#"
    : href;

/** Delay before a panel opens when the pointer lingers, and before it closes when the pointer leaves. */
const OPEN_DELAY = 120;
const CLOSE_DELAY = 180;
/** Distance of the panel from its trigger and from the viewport edge. */
const GAP = 8;

/**
 * Slide the indicator to the hovered item, the open panel, or the active item, then place the
 * open panel under its trigger. The indicator is the nav's first child, the panel is the trigger's next sibling.
 */
function sync(nav: Element) {
  const find = (selector: string) => nav.querySelector<HTMLElement>(selector);
  const open = find("[aria-expanded=true]");
  const target =
    find(":scope>ul>li:hover>:first-child") ?? open ?? find("[aria-current]");
  const pill = nav.firstElementChild as HTMLElement;
  pill.hidden = !target;
  if (target) {
    pill.style.width = `${target.offsetWidth}px`;
    pill.style.translate = `${target.offsetLeft}px 0`;
  }
  const popover = open?.nextElementSibling as HTMLElement | undefined;
  if (!popover) return;
  const box = open!.getBoundingClientRect();
  const maxLeft = innerWidth - popover.offsetWidth - GAP;
  popover.style.top = `${box.bottom + GAP}px`;
  popover.style.left = `${Math.max(GAP, Math.min(box.left, maxLeft))}px`;
}

export type NavbarChild = {
  label: string;
  href: string;
  description?: string;
  /** SVG path data (d attribute) for a 24x24 stroke icon. */
  icon?: string;
};

export type NavbarLink = {
  label: string;
  /** Plain link target. Ignored when the item has children. */
  href?: string;
  active?: boolean;
  /** Dropdown links. An item with children becomes a dropdown trigger. */
  children?: NavbarChild[];
};

export type NavbarVariant = keyof typeof variants;

let nextId = 0;

/**
 * Attribute selector on the native header: id, class, data-*, and aria-* stay on the header.
 * Slots: an element with the `brand` attribute fills the left side, an element with the
 * `actions` attribute (an ng-container works) fills the right side.
 */
@Component({
  selector: "header[markas-navbar]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.id]": "navbarId()",
    "[class]": "classes()",
    "(keydown)": "handleKeyDown($event)",
  },
  template: `
    <div [class]="bar">
      <div #brand [class]="brandClass" [hidden]="!hasBrand()">
        <ng-content select="[brand]" />
      </div>
      <nav [attr.aria-label]="navLabel()" [class]="desktopNav">
        <span aria-hidden="true" hidden [class]="indicator"></span>
        <ul [class]="list">
          @for (entry of links(); track $index) {
            @let panelId = navbarId() + "-panel-" + $index;
            <li
              (pointerenter)="handleHover($event)"
              (pointerleave)="handleHover($event)"
            >
              @if (entry.children?.length) {
                <button
                  type="button"
                  [attr.popovertarget]="panelId"
                  aria-expanded="false"
                  [attr.aria-controls]="panelId"
                  [class]="item"
                  (click)="handleClick($event)"
                  (keydown)="handleTriggerKeyDown($event)"
                >
                  {{ entry.label
                  }}<svg
                    [attr.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"
                  popover="auto"
                  [class]="panel"
                  (beforetoggle)="handleToggle($event)"
                  (toggle)="handleToggle($event)"
                >
                  <ul [class]="panelList">
                    @for (child of entry.children; track $index) {
                      <li>
                        <a [href]="safeHref(child.href)" [class]="panelLink">
                          @if (child.icon) {
                            <svg
                              [attr.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]="child.icon" />
                            </svg>
                          }
                          <span [class]="linkBody">
                            <span [class]="linkTitle">{{ child.label }}</span>
                            @if (child.description) {
                              <span [class]="linkDescription">{{
                                child.description
                              }}</span>
                            }
                          </span>
                        </a>
                      </li>
                    }
                  </ul>
                </div>
              } @else {
                <a
                  [href]="safeHref(entry.href)"
                  [attr.aria-current]="entry.active ? 'page' : null"
                  [class]="item"
                  >{{ entry.label }}</a
                >
              }
            </li>
          }
        </ul>
      </nav>
      <div [class]="actionsClass">
        <ng-content select="[actions]" />
        <button
          #toggleButton
          type="button"
          [attr.aria-label]="menuLabel()"
          [attr.aria-expanded]="open()"
          [attr.aria-controls]="menuId()"
          [class]="toggle"
          (click)="open.set(!open())"
        >
          <svg
            [attr.class]="openIcon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M4 6h16M4 12h16M4 18h16" />
          </svg>
          <svg
            [attr.class]="closeIcon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="M18 6 6 18M6 6l12 12" />
          </svg>
        </button>
      </div>
    </div>
    <div
      [id]="menuId()"
      [attr.data-state]="open() ? 'open' : 'closed'"
      [hidden]="!open()"
      [class]="mobilePanel"
    >
      <nav [attr.aria-label]="mobileNavLabel()" [class]="mobileList">
        @for (entry of links(); track $index) {
          @if (entry.children?.length) {
            <details>
              <summary [class]="item">
                {{ entry.label
                }}<svg
                  [attr.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>
              </summary>
              <div [class]="groupList">
                @for (child of entry.children; track $index) {
                  <a [href]="safeHref(child.href)" [class]="item">{{
                    child.label
                  }}</a>
                }
              </div>
            </details>
          } @else {
            <a
              [href]="safeHref(entry.href)"
              [attr.aria-current]="entry.active ? 'page' : null"
              [class]="item"
              >{{ entry.label }}</a
            >
          }
        }
      </nav>
    </div>
  `,
})
export class Navbar {
  readonly links = input<NavbarLink[]>([]);
  /** default: hairline bottom border, floating: rounded and floating, blur: translucent background. */
  readonly variant = input<NavbarVariant>("default");
  readonly sticky = input(false, { transform: booleanAttribute });
  readonly id = input<string>();
  /** Accessible label of the mobile menu button. */
  readonly menuLabel = input("Menu");
  /** Accessible label of the desktop nav element. */
  readonly navLabel = input("Main");
  /** Accessible label of the mobile nav element. */
  readonly mobileNavLabel = input("Main mobile");

  protected readonly bar = bar;
  protected readonly brandClass = brandClass;
  protected readonly desktopNav = desktopNav;
  protected readonly indicator = indicator;
  protected readonly list = list;
  protected readonly item = item;
  protected readonly chevron = chevron;
  protected readonly panel = panel;
  protected readonly panelList = panelList;
  protected readonly panelLink = panelLink;
  protected readonly iconClass = iconClass;
  protected readonly linkBody = linkBody;
  protected readonly linkTitle = linkTitle;
  protected readonly linkDescription = linkDescription;
  protected readonly actionsClass = actionsClass;
  protected readonly toggle = toggle;
  protected readonly openIcon = openIcon;
  protected readonly closeIcon = closeIcon;
  protected readonly mobilePanel = mobilePanel;
  protected readonly mobileList = mobileList;
  protected readonly groupList = groupList;
  protected readonly safeHref = safeHref;

  protected readonly open = signal(false);
  protected readonly hasBrand = signal(false);
  private readonly generatedId = `markas-navbar-${nextId++}`;
  protected readonly navbarId = computed(() => this.id() ?? this.generatedId);
  protected readonly menuId = computed(() => `${this.navbarId()}-menu`);
  protected readonly classes = computed(() =>
    [root, variants[this.variant()], this.sticky() && stickyClass]
      .filter(Boolean)
      .join(" "),
  );
  private readonly brand = viewChild.required<ElementRef<HTMLElement>>("brand");
  private readonly toggleButton =
    viewChild.required<ElementRef<HTMLButtonElement>>("toggleButton");
  private timer: ReturnType<typeof setTimeout> | undefined;

  constructor() {
    // Projected content is only known after the first render.
    afterNextRender(() =>
      this.hasBrand.set(this.brand().nativeElement.hasChildNodes()),
    );
    inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
  }

  protected handleKeyDown(event: KeyboardEvent) {
    if (event.key !== "Escape" || !this.open()) return;
    this.open.set(false);
    this.toggleButton().nativeElement.focus();
  }

  /** Mouse hover: entering a dropdown item opens it after a delay, leaving closes it after a delay. Items without a dropdown do not cancel the close delay. */
  protected handleHover(event: PointerEvent) {
    const entry = event.currentTarget as HTMLElement;
    const popover = entry.querySelector<HTMLElement>("[popover]");
    sync(entry.closest("nav")!);
    if (event.pointerType !== "mouse" || !popover) return;
    const enter = event.type === "pointerenter";
    clearTimeout(this.timer);
    this.timer = setTimeout(
      () => popover.togglePopover(enter),
      enter ? OPEN_DELAY : CLOSE_DELAY,
    );
  }

  /** A mouse click on a trigger that is already open (usually by hover) does not close it. */
  protected handleClick(event: MouseEvent) {
    const trigger = event.currentTarget as HTMLElement;
    if (event.detail && trigger.matches("[aria-expanded=true]"))
      event.preventDefault();
  }

  /** ArrowDown on a trigger opens the panel and focuses the first link. */
  protected handleTriggerKeyDown(event: KeyboardEvent) {
    const trigger = event.currentTarget as HTMLElement;
    const popover = trigger.nextElementSibling as HTMLElement;
    if (event.key !== "ArrowDown") return;
    event.preventDefault();
    popover.showPopover();
    popover.querySelector("a")?.focus();
  }

  /** beforetoggle runs synchronously so aria-expanded is always current; toggle places the panel once it shows. */
  protected handleToggle(event: Event) {
    const popover = event.currentTarget as HTMLElement;
    popover.previousElementSibling!.setAttribute(
      "aria-expanded",
      String((event as ToggleEvent).newState === "open"),
    );
    sync(popover.closest("nav")!);
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Navbar, type NavbarLink } from "./markas/navbar.component";

@Component({
  selector: "app-header",
  imports: [Button, Navbar],
  template: `
    <header
      markas-navbar
      variant="blur"
      sticky
      navLabel="Utama"
      mobileNavLabel="Utama seluler"
      [links]="links"
    >
      <ng-container brand>MarkasUI</ng-container>
      <button markas-button actions size="sm">Masuk</button>
    </header>
  `,
})
export class AppHeader {
  readonly links: NavbarLink[] = [
    { label: "Beranda", href: "/", active: true },
    {
      label: "Produk",
      children: [
        {
          label: "Analitik",
          href: "/analitik",
          description: "Pantau pemakaian secara langsung",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Otomasi", href: "/otomasi" },
      ],
    },
    { label: "Harga", href: "/harga" },
  ];
}
```

Komponen dipasang di elemen `header` native (`header[markas-navbar]`), jadi atribut `id`, `class`, dan `data-*` tetap di header.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `links` | `{ label, href?, active?, children?: { label, href, description?, icon? }[] }[]` | [] | Menu utama. Link dengan active diberi aria-current=page. Item dengan children menjadi pemicu dropdown; icon adalah path SVG (d) untuk ikon garis 24px. |
| `brand` | `slot / ReactNode` | - | Logo atau nama situs di kiri. |
| `actions` | `slot / ReactNode` | - | Area kanan, misalnya tombol Masuk. |
| `variant` | `"default" \| "floating" \| "blur"` | "default" | default: garis bawah tipis. floating: bar membulat berborder dengan bayangan halus. blur: latar semi transparan dengan backdrop blur untuk konten yang tergulir di bawahnya. |
| `sticky` | `boolean` | false | Header tetap di atas saat halaman digulir (floating menyisakan jarak kecil). |
| `menuLabel` | `string` | Menu | Label aksesibel tombol menu seluler. Default "Menu" sudah cocok untuk Bahasa Indonesia. |
| `navLabel` | `string` | Main | Label aksesibel nav desktop. Isi "Utama" untuk situs berbahasa Indonesia. |
| `mobileNavLabel` | `string` | Main mobile | Label aksesibel nav seluler. Isi "Utama seluler" untuk situs berbahasa Indonesia. |

## Aksesibilitas

- Tombol menu seluler memakai aria-expanded dan aria-controls yang menunjuk ke panel menu.
- Escape menutup panel seluler dan fokus kembali ke tombol menu.
- Menu desktop dan seluler masing-masing dibungkus nav dengan label berbeda (navLabel dan mobileNavLabel).
- Tata letak mengikuti lebar header (container query), menu desktop tampil mulai lebar 42rem.
- Dropdown mengikuti pola WAI-ARIA disclosure navigation: tombol dengan aria-expanded dan aria-controls membuka popover native. Klik, Enter, Spasi, dan ArrowDown membukanya, ArrowDown juga memfokuskan link pertama, Escape menutupnya dan mengembalikan fokus ke tombol.
- Hover membuka dropdown setelah 120ms dan menutupnya 180ms setelah mouse pergi; sentuhan dan pena mengabaikan hover.
- Di seluler, item dengan children menjadi grup details dan summary yang dibuka dengan Enter atau Spasi.
- Animasi dimatikan dengan prefers-reduced-motion.

## Catatan

- Link biasa dari versi sebelumnya tetap jalan. Tambahkan `children` pada item untuk menjadikannya dropdown; `href` item itu lalu diabaikan.
- Panel dropdown memakai Popover API native, jadi tampil di top layer di atas konten lain dan tertutup saat klik di luar atau Escape. Panel dengan lebih dari tiga link mengalir ke kolom kedua.
- `variant`: `default` memberi garis bawah tipis, `floating` berupa bar membulat dengan border dan bayangan halus, `blur` semi transparan dengan backdrop blur. Pasangkan `blur` dengan `sticky` di atas konten yang tergulir di bawah header.
- Tata letak mengikuti lebar header lewat container query (`@container` dan `@2xl:`), bukan lebar layar. Menu desktop tampil saat header selebar 42rem atau lebih, di bawah itu muncul tombol menu dan dropdown menjadi grup yang bisa dibuka dan ditutup.
- Label bawaan dalam bahasa Inggris: tombol "Menu", nav "Main" dan "Main mobile". Isi `navLabel` dan `mobileNavLabel` (Blade: `nav-label`, `mobile-nav-label`) untuk situs berbahasa Indonesia. `menuLabel` (Blade: `menu-label`) juga bisa diubah, walau "Menu" sudah cocok.
