# Navbar

Site header with a brand, links, dropdown menus, a sliding hover pill, an actions area, and a mobile menu with collapsible groups.

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

## When to use

Main header at the top of every page of a site or app, including marketing sites with product and resource dropdowns.

- Mark the current page with active
- Keep the number of main links small, group related pages under children
- Give every dropdown child a short description when the label alone is ambiguous
- Use variant blur with sticky only over content that scrolls under the header

## Code

### Blade

Save at `resources/views/components/markas/navbar.blade.php`. Dependencies: 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 variant="blur" :sticky="true" :links="[
    ['label' => 'Home', 'href' => '/', 'active' => true],
    ['label' => 'Products', 'children' => [
        [
            'label' => 'Analytics',
            'href' => '/analytics',
            'description' => 'Track usage in real time',
            'icon' => 'M3 3v18h18M7 15l4-4 3 3 5-6',
        ],
        ['label' => 'Automation', 'href' => '/automation'],
    ]],
    ['label' => 'Pricing', 'href' => '/pricing'],
]">
    <x-slot:brand>MarkasUI</x-slot:brand>
    <x-slot:actions>
        <x-markas.button size="sm">Sign in</x-markas.button>
    </x-slot:actions>
</x-markas.navbar>
```

Needs Alpine.js for the dropdowns and the mobile menu.

### React

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

```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"
  links={[
    { label: "Home", href: "/", active: true },
    {
      label: "Products",
      children: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "Track usage in real time",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Automation", href: "/automation" },
      ],
    },
    { label: "Pricing", href: "/pricing" },
  ]}
  actions={<Button size="sm">Sign in</Button>}
/>;
```

### Vue

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

```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: "Home", href: "/", active: true },
  {
    label: "Products",
    children: [
      {
        label: "Analytics",
        href: "/analytics",
        description: "Track usage in real time",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      { label: "Automation", href: "/automation" },
    ],
  },
  { label: "Pricing", href: "/pricing" },
];
</script>

<template>
  <Navbar variant="blur" sticky :links="links">
    <template #brand>MarkasUI</template>
    <template #actions>
      <Button size="sm">Sign in</Button>
    </template>
  </Navbar>
</template>
```

### Svelte

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

```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: "Home", href: "/", active: true },
    {
      label: "Products",
      children: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "Track usage in real time",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Automation", href: "/automation" },
      ],
    },
    { label: "Pricing", href: "/pricing" },
  ];
</script>

<Navbar variant="blur" sticky {links}>
  {#snippet brand()}MarkasUI{/snippet}
  {#snippet actions()}
    <Button size="sm">Sign in</Button>
  {/snippet}
</Navbar>
```

### Astro

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

```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: "Home", href: "/", active: true },
  {
    label: "Products",
    children: [
      {
        label: "Analytics",
        href: "/analytics",
        description: "Track usage in real time",
        icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
      },
      { label: "Automation", href: "/automation" },
    ],
  },
  { label: "Pricing", href: "/pricing" },
];
---

<Navbar variant="blur" sticky links={links}>
  <Fragment slot="brand">MarkasUI</Fragment>
  <Button slot="actions" size="sm">Sign in</Button>
</Navbar>
```

A small bundled script runs the dropdowns and the mobile menu of every navbar on the page. It also works after view transitions.

### Angular

Save at `src/app/markas/navbar.component.ts`. No extra dependencies.

```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 [links]="links">
      <ng-container brand>MarkasUI</ng-container>
      <button markas-button actions size="sm">Sign in</button>
    </header>
  `,
})
export class AppHeader {
  readonly links: NavbarLink[] = [
    { label: "Home", href: "/", active: true },
    {
      label: "Products",
      children: [
        {
          label: "Analytics",
          href: "/analytics",
          description: "Track usage in real time",
          icon: "M3 3v18h18M7 15l4-4 3 3 5-6",
        },
        { label: "Automation", href: "/automation" },
      ],
    },
    { label: "Pricing", href: "/pricing" },
  ];
}
```

The component sits on a native `header` element (`header[markas-navbar]`), so `id`, `class`, and `data-*` attributes stay on the header.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `links` | `{ label, href?, active?, children?: { label, href, description?, icon? }[] }[]` | [] | Main menu. Links with active get aria-current=page. An item with children becomes a dropdown trigger; icon is an SVG path (d) for a 24px stroke icon. |
| `brand` | `slot / ReactNode` | - | Logo or site name on the left. |
| `actions` | `slot / ReactNode` | - | Right-hand area, such as a Sign in button. |
| `variant` | `"default" \| "floating" \| "blur"` | "default" | default: hairline bottom border. floating: rounded, bordered bar with a soft shadow. blur: translucent background with backdrop blur for content scrolling underneath. |
| `sticky` | `boolean` | false | Keeps the header at the top while the page scrolls (floating leaves a small gap). |
| `menuLabel` | `string` | Menu | Accessible label of the mobile menu button. |
| `navLabel` | `string` | Main | Accessible label of the desktop nav element. |
| `mobileNavLabel` | `string` | Main mobile | Accessible label of the mobile nav element. |

## Accessibility

- The mobile menu button uses aria-expanded and aria-controls pointing to the menu panel.
- Escape closes the mobile panel and returns focus to the menu button.
- The desktop and mobile menus are each wrapped in a nav with different labels (navLabel and mobileNavLabel).
- The layout follows the header width (container query), the desktop menu shows from 42rem wide.
- Dropdowns follow the WAI-ARIA disclosure navigation pattern: a button with aria-expanded and aria-controls opens a native popover. Click, Enter, Space, and ArrowDown open it, ArrowDown also focuses the first link, Escape closes it and returns focus to the button.
- Hover opens a dropdown after 120ms and closes it 180ms after the mouse leaves; touch and pen ignore hover.
- On mobile, items with children become details and summary groups that open with Enter or Space.
- Animations are disabled with prefers-reduced-motion.

## Notes

- Plain links from earlier versions keep working. Add `children` to an item to turn it into a dropdown; its own `href` is then ignored.
- Dropdown panels use the native Popover API, so they sit in the top layer above other content and close on outside click or Escape. A panel with more than three links flows into a second column.
- `variant`: `default` draws a hairline bottom border, `floating` is a rounded bar with a border and soft shadow, `blur` is translucent with a backdrop blur. Pair `blur` with `sticky` over content that scrolls under the header.
- The layout follows the header width through a container query (`@container` and `@2xl:`), not the viewport. The desktop menu shows when the header is 42rem wide or more, below that the menu button appears and dropdowns become collapsible groups.
- The menu button is labelled "Menu" and the navs "Main" and "Main mobile". Translate them with `menuLabel`, `navLabel`, and `mobileNavLabel` (Blade: `menu-label`, `nav-label`, `mobile-nav-label`).
