# Dropdown Menu

Menu aksi berbasis Popover API dengan navigasi keyboard sesuai pola WAI-ARIA Menu Button.

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

## Kapan dipakai

Kumpulan aksi untuk satu objek, misalnya ubah, duplikat, dan hapus pada baris tabel atau kartu.

- Pakai untuk aksi, bukan untuk memilih nilai form; gunakan Select untuk itu
- Letakkan aksi berbahaya di akhir dengan danger: true dan pisahkan dengan separator
- Jangan menaruh elemen interaktif lain di dalam item menu

## Kode

### Blade

Simpan di `resources/views/components/markas/dropdown-menu.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'items' => [],
    'label' => 'Options',
])

@php
    $root = 'inline-block';
    $triggerClass = 'inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none';
    $chevron = 'size-4 text-muted';
    $menu = 'inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay';
    $item = 'flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $tones = [
        'default' => 'text-ink hover:bg-subtle focus:bg-subtle',
        'danger' => 'text-danger hover:bg-danger/10 focus:bg-danger/10',
    ];
    $separator = 'my-1 h-px bg-line';

    // Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#".
    $safeHref = function (string $href): string {
        $value = ltrim(str_replace(["\t", "\n", "\r"], '', $href), "\x00..\x20");
        $hasScheme = preg_match('/^[a-z][a-z0-9+.\-]*:/i', $value) === 1;

        return $hasScheme && preg_match('/^(https?|mailto|tel):/i', $value) !== 1 ? '#' : $href;
    };

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

<div
    x-data="{
        open: false,
        focusTarget: 'first',
        menuItems() {
            return Array.from(this.$refs.menu.querySelectorAll('[role=menuitem]:not(:disabled)'));
        },
        focusItem(index) {
            const list = this.menuItems();
            if (list.length === 0) return;
            list[(index + list.length) % list.length].focus();
        },
        focusEdge(target) {
            this.focusItem(target === 'first' ? 0 : -1);
        },
        {{-- Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. --}}
        place() {
            const gap = 4;
            const anchor = this.$refs.trigger.getBoundingClientRect();
            const { width, height } = this.$refs.menu.getBoundingClientRect();
            const below = anchor.bottom + gap;
            const above = anchor.top - gap - height;
            const fitsBelow = below + height <= window.innerHeight;
            this.$refs.menu.style.top = (fitsBelow || above < 0 ? below : above) + 'px';
            this.$refs.menu.style.left = Math.max(gap, Math.min(anchor.left, window.innerWidth - width - gap)) + 'px';
        },
        unfollow: null,
        {{-- Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. --}}
        follow() {
            this.unfollow?.();
            const update = () => this.place();
            const scrollOptions = { capture: true, passive: true };
            window.addEventListener('scroll', update, scrollOptions);
            window.addEventListener('resize', update, { passive: true });
            this.unfollow = () => {
                window.removeEventListener('scroll', update, scrollOptions);
                window.removeEventListener('resize', update);
                this.unfollow = null;
            };
        },
        destroy() {
            this.unfollow?.();
        },
        close() {
            this.$refs.menu.hidePopover();
            this.$refs.trigger.focus();
        },
        select(value) {
            this.$dispatch('markas-select', value);
            this.close();
        },
        {{-- beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya. --}}
        onBeforeToggle(event) {
            this.open = event.newState === 'open';
        },
        onToggle(event) {
            if (event.newState !== 'open') return this.unfollow?.();
            this.place();
            this.follow();
            this.focusEdge(this.focusTarget);
            this.focusTarget = 'first';
        },
        onTriggerKeydown(event) {
            const target = { ArrowDown: 'first', ArrowUp: 'last' }[event.key];
            if (target === undefined) return;
            event.preventDefault();
            if (this.open) return this.focusEdge(target);
            this.focusTarget = target;
            this.$refs.menu.showPopover();
        },
        onMenuKeydown(event) {
            if (event.key === 'Escape') {
                event.preventDefault();
                return this.close();
            }
            if (event.key === 'Tab') return this.$refs.menu.hidePopover();
            const index = this.menuItems().indexOf(document.activeElement);
            const target = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: -1 }[event.key];
            if (target === undefined) return;
            event.preventDefault();
            this.focusItem(target);
        },
    }"
    {{ $attributes->except('id')->class([$root]) }}
>
    <button
        x-ref="trigger"
        type="button"
        id="{{ $id }}-trigger"
        popovertarget="{{ $id }}"
        aria-haspopup="menu"
        aria-expanded="false"
        aria-controls="{{ $id }}"
        data-state="closed"
        :aria-expanded="open ? 'true' : 'false'"
        :data-state="open ? 'open' : 'closed'"
        @keydown="onTriggerKeydown($event)"
        class="{{ $triggerClass }}"
    >{{ $trigger ?? $label }}<svg class="{{ $chevron }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6" /></svg></button>
    <div
        x-ref="menu"
        id="{{ $id }}"
        popover="auto"
        wire:ignore.self
        role="menu"
        aria-labelledby="{{ $id }}-trigger"
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @beforetoggle="onBeforeToggle($event)"
        @toggle="onToggle($event)"
        @keydown="onMenuKeydown($event)"
        class="{{ $menu }}"
    >
        @foreach ($items as $entry)
            @if ($entry['separator'] ?? false)
                <div role="separator" class="{{ $separator }}"></div>
            @else
                @php
                    $itemClass = $item.' '.$tones[($entry['danger'] ?? false) ? 'danger' : 'default'];
                    $value = (string) ($entry['value'] ?? $entry['label']);
                    $disabled = (bool) ($entry['disabled'] ?? false);
                @endphp
                @if (isset($entry['href']) && ! $disabled)
                    <a href="{{ $safeHref((string) $entry['href']) }}" role="menuitem" tabindex="-1" class="{{ $itemClass }}" @click="select(@js($value))">{{ $entry['label'] }}</a>
                @else
                    <button type="button" role="menuitem" tabindex="-1" @disabled($disabled) class="{{ $itemClass }}" @click="select(@js($value))">{{ $entry['label'] }}</button>
                @endif
            @endif
        @endforeach
    </div>
</div>
```

```blade
<x-markas.dropdown-menu
    label="Aksi"
    :items="[
        ['label' => 'Ubah', 'value' => 'ubah'],
        ['label' => 'Lihat detail', 'href' => '/proyek/1'],
        ['separator' => true],
        ['label' => 'Hapus', 'value' => 'hapus', 'danger' => true],
    ]"
    x-on:markas-select="console.log($event.detail)"
/>
```

Butuh Alpine.js. Item yang dipilih memancarkan event `markas-select` dengan `$event.detail` berisi value item. Di Livewire: `x-on:markas-select="$wire.aksi($event.detail)"`.

### Livewire

```blade
<x-markas.dropdown-menu label="Actions" :items="$actions" wire:markas-select="run($event.detail)" />
```

Memilih item memancarkan `markas-select` dengan value; `wire:markas-select` memanggil action Livewire dengan value itu. Menu yang terbuka tetap di posisinya saat komponen dirender ulang.

### React

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

```tsx
"use client";

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

const root = "inline-block";
const triggerClass =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const chevron = "size-4 text-muted";
const menu =
  "inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
  "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
  default: "text-ink hover:bg-subtle focus:bg-subtle",
  danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

const GAP = 4;
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';

/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const below = anchor.bottom + GAP;
  const above = anchor.top - GAP - height;
  const fitsBelow = below + height <= window.innerHeight;
  const top = fitsBelow || above < 0 ? below : above;
  const left = Math.max(
    GAP,
    Math.min(anchor.left, window.innerWidth - width - GAP),
  );
  panel.style.top = `${top}px`;
  panel.style.left = `${left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

export type DropdownMenuItem =
  | { separator: true }
  | {
      separator?: false;
      label: string;
      value?: string;
      href?: string;
      danger?: boolean;
      disabled?: boolean;
    };

export type DropdownMenuProps = Omit<ComponentProps<"div">, "onSelect"> & {
  items: DropdownMenuItem[];
  label?: string;
  trigger?: ReactNode;
  onSelect?: (value: string) => void;
};

type FocusTarget = "first" | "last";

export function DropdownMenu({
  items,
  label = "Options",
  trigger,
  onSelect,
  id,
  className,
  ...props
}: DropdownMenuProps) {
  const generatedId = useId();
  const menuId = id ?? generatedId;
  const triggerRef = useRef<HTMLButtonElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const focusTarget = useRef<FocusTarget>("first");
  const [open, setOpen] = useState(false);
  const state = open ? "open" : "closed";

  useEffect(() => {
    if (!open) return;
    return followViewport(() => {
      if (triggerRef.current && menuRef.current)
        placeMenu(triggerRef.current, menuRef.current);
    });
  }, [open]);

  const menuItems = () =>
    Array.from(
      menuRef.current?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? [],
    );
  const focusItem = (index: number) => {
    const list = menuItems();
    if (list.length === 0) return;
    list[(index + list.length) % list.length]?.focus();
  };
  const focusEdge = (target: FocusTarget) =>
    focusItem(target === "first" ? 0 : -1);

  const close = () => {
    menuRef.current?.hidePopover();
    triggerRef.current?.focus();
  };
  const select = (value: string) => {
    onSelect?.(value);
    close();
  };

  // beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
  const handleBeforeToggle = (event: ToggleEvent<HTMLDivElement>) =>
    setOpen(event.newState === "open");
  const handleToggle = (event: ToggleEvent<HTMLDivElement>) => {
    if (event.newState !== "open" || !triggerRef.current || !menuRef.current)
      return;
    placeMenu(triggerRef.current, menuRef.current);
    focusEdge(focusTarget.current);
    focusTarget.current = "first";
  };

  const handleTriggerKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
    const targets: Record<string, FocusTarget | undefined> = {
      ArrowDown: "first",
      ArrowUp: "last",
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    if (open) return focusEdge(target);
    focusTarget.current = target;
    menuRef.current?.showPopover();
  };

  const handleMenuKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key === "Escape") {
      event.preventDefault();
      return close();
    }
    if (event.key === "Tab") return menuRef.current?.hidePopover();
    const index = menuItems().indexOf(document.activeElement as HTMLElement);
    const targets: Record<string, number | undefined> = {
      ArrowDown: index + 1,
      ArrowUp: index - 1,
      Home: 0,
      End: -1,
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    focusItem(target);
  };

  return (
    <div className={cx(root, className)} {...props}>
      <button
        ref={triggerRef}
        type="button"
        id={`${menuId}-trigger`}
        popoverTarget={menuId}
        aria-haspopup="menu"
        aria-expanded={open}
        aria-controls={menuId}
        data-state={state}
        className={triggerClass}
        onKeyDown={handleTriggerKeyDown}
      >
        {trigger ?? label}
        <svg
          className={chevron}
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>
      <div
        ref={menuRef}
        id={menuId}
        popover="auto"
        role="menu"
        aria-labelledby={`${menuId}-trigger`}
        data-state={state}
        className={menu}
        onBeforeToggle={handleBeforeToggle}
        onToggle={handleToggle}
        onKeyDown={handleMenuKeyDown}
      >
        {items.map((entry, index) => {
          if (entry.separator)
            return <div key={index} role="separator" className={separator} />;
          const itemClass = cx(
            item,
            tones[entry.danger ? "danger" : "default"],
          );
          const handleClick = () => select(entry.value ?? entry.label);
          if (entry.href && !entry.disabled)
            return (
              <a
                key={index}
                href={safeHref(entry.href)}
                role="menuitem"
                tabIndex={-1}
                className={itemClass}
                onClick={handleClick}
              >
                {entry.label}
              </a>
            );
          return (
            <button
              key={index}
              type="button"
              role="menuitem"
              tabIndex={-1}
              disabled={entry.disabled}
              className={itemClass}
              onClick={handleClick}
            >
              {entry.label}
            </button>
          );
        })}
      </div>
    </div>
  );
}
```

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

<DropdownMenu
  label="Aksi"
  items={[
    { label: "Ubah", value: "ubah" },
    { label: "Lihat detail", href: "/proyek/1" },
    { separator: true },
    { label: "Hapus", value: "hapus", danger: true },
  ]}
  onSelect={(value) => console.log(value)}
/>;
```

### Vue

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

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

export type DropdownMenuItem =
  | { separator: true }
  | {
      separator?: false;
      label: string;
      value?: string;
      href?: string;
      danger?: boolean;
      disabled?: boolean;
    };

type FocusTarget = "first" | "last";

const props = withDefaults(
  defineProps<{
    items: DropdownMenuItem[];
    label?: string;
    id?: string;
  }>(),
  { label: "Options", id: undefined },
);
const emit = defineEmits<{ select: [value: string] }>();

const root = "inline-block";
const triggerClass =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const chevron = "size-4 text-muted";
const menu =
  "inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
  "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
  default: "text-ink hover:bg-subtle focus:bg-subtle",
  danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

const GAP = 4;
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';

/** Letakkan menu di bawah pemicu rata kiri, pindah ke atas kalau tidak muat. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const below = anchor.bottom + GAP;
  const above = anchor.top - GAP - height;
  const fitsBelow = below + height <= window.innerHeight;
  const top = fitsBelow || above < 0 ? below : above;
  const left = Math.max(
    GAP,
    Math.min(anchor.left, window.innerWidth - width - GAP),
  );
  panel.style.top = `${top}px`;
  panel.style.left = `${left}px`;
}

/** Jalankan ulang penempatan saat halaman digulir atau jendela berubah ukuran. Mengembalikan fungsi pelepas. */
function followViewport(update: () => void) {
  const scrollOptions = { capture: true, passive: true };
  window.addEventListener("scroll", update, scrollOptions);
  window.addEventListener("resize", update, { passive: true });
  return () => {
    window.removeEventListener("scroll", update, scrollOptions);
    window.removeEventListener("resize", update);
  };
}

const generatedId = useId();
const menuId = computed(() => props.id ?? generatedId);
const triggerEl = useTemplateRef<HTMLButtonElement>("trigger");
const menuEl = useTemplateRef<HTMLDivElement>("menuRef");
const open = ref(false);
const state = computed(() => (open.value ? "open" : "closed"));
let focusTarget: FocusTarget = "first";
let unfollow: (() => void) | undefined;

const menuItems = () =>
  Array.from(menuEl.value?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? []);

function focusItem(index: number) {
  const list = menuItems();
  if (list.length === 0) return;
  list[(index + list.length) % list.length]?.focus();
}

const focusEdge = (target: FocusTarget) =>
  focusItem(target === "first" ? 0 : -1);

function close() {
  menuEl.value?.hidePopover();
  triggerEl.value?.focus();
}

function select(value: string) {
  emit("select", value);
  close();
}

// beforetoggle berjalan sinkron, jadi status selalu terbaru untuk tombol berikutnya.
function onBeforeToggle(event: Event) {
  open.value = (event as ToggleEvent).newState === "open";
}

function stopFollowing() {
  unfollow?.();
  unfollow = undefined;
}

function place() {
  if (triggerEl.value && menuEl.value) placeMenu(triggerEl.value, menuEl.value);
}

function onToggle(event: Event) {
  stopFollowing();
  const isOpen = (event as ToggleEvent).newState === "open";
  if (!isOpen || !triggerEl.value || !menuEl.value) return;
  place();
  unfollow = followViewport(place);
  focusEdge(focusTarget);
  focusTarget = "first";
}

onBeforeUnmount(stopFollowing);

function onTriggerKeydown(event: KeyboardEvent) {
  const targets: Record<string, FocusTarget | undefined> = {
    ArrowDown: "first",
    ArrowUp: "last",
  };
  const target = targets[event.key];
  if (target === undefined) return;
  event.preventDefault();
  if (open.value) return focusEdge(target);
  focusTarget = target;
  menuEl.value?.showPopover();
}

function onMenuKeydown(event: KeyboardEvent) {
  if (event.key === "Escape") {
    event.preventDefault();
    return close();
  }
  if (event.key === "Tab") return menuEl.value?.hidePopover();
  const index = menuItems().indexOf(document.activeElement as HTMLElement);
  const targets: Record<string, number | undefined> = {
    ArrowDown: index + 1,
    ArrowUp: index - 1,
    Home: 0,
    End: -1,
  };
  const target = targets[event.key];
  if (target === undefined) return;
  event.preventDefault();
  focusItem(target);
}
</script>

<template>
  <div :class="root">
    <button
      :id="`${menuId}-trigger`"
      ref="trigger"
      type="button"
      :popovertarget="menuId"
      aria-haspopup="menu"
      :aria-expanded="open ? 'true' : 'false'"
      :aria-controls="menuId"
      :data-state="state"
      :class="triggerClass"
      @keydown="onTriggerKeydown"
    >
      <slot name="trigger">{{ props.label }}</slot>
      <svg
        :class="chevron"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m6 9 6 6 6-6" />
      </svg>
    </button>
    <div
      :id="menuId"
      ref="menuRef"
      popover="auto"
      role="menu"
      :aria-labelledby="`${menuId}-trigger`"
      :data-state="state"
      :class="menu"
      @beforetoggle="onBeforeToggle"
      @toggle="onToggle"
      @keydown="onMenuKeydown"
    >
      <template v-for="(entry, index) in props.items" :key="index">
        <div v-if="entry.separator" role="separator" :class="separator" />
        <a
          v-else-if="entry.href && !entry.disabled"
          :href="safeHref(entry.href)"
          role="menuitem"
          tabindex="-1"
          :class="[item, tones[entry.danger ? 'danger' : 'default']]"
          @click="select(entry.value ?? entry.label)"
          >{{ entry.label }}</a
        >
        <button
          v-else
          type="button"
          role="menuitem"
          tabindex="-1"
          :disabled="entry.disabled"
          :class="[item, tones[entry.danger ? 'danger' : 'default']]"
          @click="select(entry.value ?? entry.label)"
        >
          {{ entry.label }}
        </button>
      </template>
    </div>
  </div>
</template>
```

```vue
<template>
  <DropdownMenu
    label="Aksi"
    :items="[
      { label: 'Ubah', value: 'ubah' },
      { label: 'Lihat detail', href: '/proyek/1' },
      { separator: true },
      { label: 'Hapus', value: 'hapus', danger: true },
    ]"
    @select="(value) => console.log(value)"
  />
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type DropdownMenuItem =
    | { separator: true }
    | {
        separator?: false;
        label: string;
        value?: string;
        href?: string;
        danger?: boolean;
        disabled?: boolean;
      };
</script>

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

  const root = "inline-block";
  const triggerClass =
    "inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
  const chevron = "size-4 text-muted";
  const menu =
    "inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
  const item =
    "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const tones = {
    default: "text-ink hover:bg-subtle focus:bg-subtle",
    danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
  };
  const separator = "my-1 h-px bg-line";

  const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
  const SAFE_SCHEME = /^(https?|mailto|tel):/i;

  /** Hrefs with a scheme other than http, https, mailto, and tel (such as javascript:) become "#". */
  const safeHref = (href: string) => {
    const cleaned = href.replace(/[\t\n\r]/g, "");
    const start = [...cleaned].findIndex((char) => char > " ");
    const value = cleaned.slice(Math.max(start, 0));
    return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
  };

  const GAP = 4;
  const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';

  /** Places the menu below the trigger, aligned to its start, and flips above when it does not fit. */
  function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
    const anchor = trigger.getBoundingClientRect();
    const { width, height } = panel.getBoundingClientRect();
    const below = anchor.bottom + GAP;
    const above = anchor.top - GAP - height;
    const fitsBelow = below + height <= window.innerHeight;
    const top = fitsBelow || above < 0 ? below : above;
    const left = Math.max(
      GAP,
      Math.min(anchor.left, window.innerWidth - width - GAP),
    );
    panel.style.top = `${top}px`;
    panel.style.left = `${left}px`;
  }

  type FocusTarget = "first" | "last";

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "onselect"> & {
    items: DropdownMenuItem[];
    label?: string;
    trigger?: Snippet;
    onselect?: (value: string) => void;
  };

  let {
    items,
    label = "Options",
    trigger,
    onselect,
    id,
    class: className,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const menuId = $derived(id ?? generatedId);
  let triggerEl = $state<HTMLButtonElement>();
  let menuEl = $state<HTMLDivElement>();
  let open = $state(false);
  const dataState = $derived(open ? "open" : "closed");
  let focusTarget: FocusTarget = "first";

  const place = () => {
    if (triggerEl && menuEl) placeMenu(triggerEl, menuEl);
  };

  // Re-run placement while the page scrolls or the window resizes.
  $effect(() => {
    if (!open) return;
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", place, scrollOptions);
    window.addEventListener("resize", place, { passive: true });
    return () => {
      window.removeEventListener("scroll", place, scrollOptions);
      window.removeEventListener("resize", place);
    };
  });

  const menuItems = () =>
    Array.from(menuEl?.querySelectorAll<HTMLElement>(ITEM_SELECTOR) ?? []);

  function focusItem(index: number) {
    const list = menuItems();
    if (list.length === 0) return;
    list[(index + list.length) % list.length]?.focus();
  }

  const focusEdge = (target: FocusTarget) =>
    focusItem(target === "first" ? 0 : -1);

  function close() {
    menuEl?.hidePopover();
    triggerEl?.focus();
  }

  function select(value: string) {
    onselect?.(value);
    close();
  }

  // beforetoggle runs synchronously, so the state is current for the next key press.
  function handleBeforeToggle(event: ToggleEvent) {
    open = event.newState === "open";
  }

  function handleToggle(event: ToggleEvent) {
    if (event.newState !== "open") return;
    place();
    focusEdge(focusTarget);
    focusTarget = "first";
  }

  function handleTriggerKeydown(event: KeyboardEvent) {
    const targets: Record<string, FocusTarget | undefined> = {
      ArrowDown: "first",
      ArrowUp: "last",
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    if (open) return focusEdge(target);
    focusTarget = target;
    menuEl?.showPopover();
  }

  function handleMenuKeydown(event: KeyboardEvent) {
    if (event.key === "Escape") {
      event.preventDefault();
      return close();
    }
    if (event.key === "Tab") return menuEl?.hidePopover();
    const index = menuItems().indexOf(document.activeElement as HTMLElement);
    const targets: Record<string, number | undefined> = {
      ArrowDown: index + 1,
      ArrowUp: index - 1,
      Home: 0,
      End: -1,
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    focusItem(target);
  }
</script>

<div class={[root, className]} {...rest}>
  <button
    bind:this={triggerEl}
    type="button"
    id={`${menuId}-trigger`}
    popovertarget={menuId}
    aria-haspopup="menu"
    aria-expanded={open}
    aria-controls={menuId}
    data-state={dataState}
    class={triggerClass}
    onkeydown={handleTriggerKeydown}
  >
    {#if trigger}{@render trigger()}{:else}{label}{/if}
    <svg
      class={chevron}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6" />
    </svg>
  </button>
  <!-- svelte-ignore a11y_interactive_supports_focus -->
  <div
    bind:this={menuEl}
    id={menuId}
    popover="auto"
    role="menu"
    aria-labelledby={`${menuId}-trigger`}
    data-state={dataState}
    class={menu}
    onbeforetoggle={handleBeforeToggle}
    ontoggle={handleToggle}
    onkeydown={handleMenuKeydown}
  >
    {#each items as entry, index (index)}
      {#if entry.separator}
        <div role="separator" class={separator}></div>
      {:else if entry.href && !entry.disabled}
        <a
          href={safeHref(entry.href)}
          role="menuitem"
          tabindex="-1"
          class={[item, tones[entry.danger ? "danger" : "default"]]}
          onclick={() => select(entry.value ?? entry.label)}>{entry.label}</a
        >
      {:else}
        <button
          type="button"
          role="menuitem"
          tabindex="-1"
          disabled={entry.disabled}
          class={[item, tones[entry.danger ? "danger" : "default"]]}
          onclick={() => select(entry.value ?? entry.label)}
          >{entry.label}</button
        >
      {/if}
    {/each}
  </div>
</div>
```

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

<DropdownMenu
  label="Actions"
  items={[
    { label: "Edit", value: "edit" },
    { label: "View details", href: "/projects/1" },
    { separator: true },
    { label: "Delete", value: "delete", danger: true },
  ]}
  onselect={(value) => console.log(value)}
/>
```

### Astro

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

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

export type DropdownMenuItem =
  | { separator: true }
  | {
      separator?: false;
      label: string;
      value?: string;
      href?: string;
      danger?: boolean;
      disabled?: boolean;
    };

const root = "inline-block";
const triggerClass =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const chevron = "size-4 text-muted";
const menu =
  "inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
  "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
  default: "text-ink hover:bg-subtle focus:bg-subtle",
  danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Hrefs with a scheme other than http, https, mailto, and tel (such as javascript:) become "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

type Props = HTMLAttributes<"div"> & {
  items: DropdownMenuItem[];
  label?: string;
};

const { items, label = "Options", id, class: className, ...rest } =
  Astro.props;
const menuId = id ?? `markas-dropdown-menu-${crypto.randomUUID().slice(0, 8)}`;
---

<div class:list={[root, className]} {...rest}>
  <button
    type="button"
    id={`${menuId}-trigger`}
    popovertarget={menuId}
    aria-haspopup="menu"
    aria-expanded="false"
    aria-controls={menuId}
    data-state="closed"
    data-markas-dropdown-menu-trigger
    class={triggerClass}
  >
    <slot name="trigger">{label}</slot>
    <svg
      class={chevron}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      stroke-width="1.5"
      stroke-linecap="round"
      stroke-linejoin="round"
      aria-hidden="true"
    >
      <path d="m6 9 6 6 6-6"></path>
    </svg>
  </button>
  <div
    id={menuId}
    popover="auto"
    role="menu"
    aria-labelledby={`${menuId}-trigger`}
    data-state="closed"
    data-markas-dropdown-menu
    class={menu}
  >
    {
      items.map((entry) => {
        if (entry.separator)
          return <div role="separator" class={separator} />;
        const itemClass = [item, tones[entry.danger ? "danger" : "default"]];
        const value = entry.value ?? entry.label;
        if (entry.href && !entry.disabled)
          return (
            <a
              href={safeHref(entry.href)}
              role="menuitem"
              tabindex="-1"
              data-value={value}
              class:list={itemClass}
            >
              {entry.label}
            </a>
          );
        return (
          <button
            type="button"
            role="menuitem"
            tabindex="-1"
            disabled={entry.disabled}
            data-value={value}
            class:list={itemClass}
          >
            {entry.label}
          </button>
        );
      })
    }
  </div>
</div>

<script>
  // One set of listeners per page serves every dropdown menu, including markup added later
  // and pages reached through view transitions. Only one auto popover menu is open at a time.
  type FocusTarget = "first" | "last";

  const GAP = 4;
  const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
  let focusTarget: FocusTarget = "first";
  let followed: HTMLElement | undefined;
  let unfollow: (() => void) | undefined;

  const isMenu = (node: EventTarget | null): node is HTMLElement =>
    node instanceof HTMLElement && node.hasAttribute("data-markas-dropdown-menu");
  const triggerOf = (menu: HTMLElement) =>
    document.getElementById(`${menu.id}-trigger`);
  const menuItems = (menu: HTMLElement) =>
    Array.from(menu.querySelectorAll<HTMLElement>(ITEM_SELECTOR));

  function focusItem(menu: HTMLElement, index: number) {
    const list = menuItems(menu);
    if (list.length === 0) return;
    list[(index + list.length) % list.length]?.focus();
  }

  const focusEdge = (menu: HTMLElement, target: FocusTarget) =>
    focusItem(menu, target === "first" ? 0 : -1);

  /** Places the menu below the trigger, aligned to its start, and flips above when it does not fit. */
  function place(menu: HTMLElement) {
    const trigger = triggerOf(menu);
    if (!trigger) return;
    const anchor = trigger.getBoundingClientRect();
    const { width, height } = menu.getBoundingClientRect();
    const below = anchor.bottom + GAP;
    const above = anchor.top - GAP - height;
    const fitsBelow = below + height <= window.innerHeight;
    const top = fitsBelow || above < 0 ? below : above;
    const left = Math.max(
      GAP,
      Math.min(anchor.left, window.innerWidth - width - GAP),
    );
    menu.style.top = `${top}px`;
    menu.style.left = `${left}px`;
  }

  /** Re-runs placement while the page scrolls or the window resizes. */
  function follow(menu: HTMLElement) {
    unfollow?.();
    followed = menu;
    const update = () => place(menu);
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", update, scrollOptions);
    window.addEventListener("resize", update, { passive: true });
    unfollow = () => {
      window.removeEventListener("scroll", update, scrollOptions);
      window.removeEventListener("resize", update);
      unfollow = followed = undefined;
    };
  }

  function close(menu: HTMLElement) {
    menu.hidePopover();
    triggerOf(menu)?.focus();
  }

  function onTriggerKeydown(event: KeyboardEvent, trigger: HTMLElement) {
    const target = ({ ArrowDown: "first", ArrowUp: "last" } as const)[
      event.key as "ArrowDown" | "ArrowUp"
    ];
    const menu = document.getElementById(
      trigger.getAttribute("aria-controls") ?? "",
    );
    if (target === undefined || !isMenu(menu)) return;
    event.preventDefault();
    if (menu.matches(":popover-open")) return focusEdge(menu, target);
    focusTarget = target;
    menu.showPopover();
  }

  function onMenuKeydown(event: KeyboardEvent, menu: HTMLElement) {
    if (event.key === "Escape") {
      event.preventDefault();
      return close(menu);
    }
    if (event.key === "Tab") return menu.hidePopover();
    const index = menuItems(menu).indexOf(
      document.activeElement as HTMLElement,
    );
    const targets: Record<string, number | undefined> = {
      ArrowDown: index + 1,
      ArrowUp: index - 1,
      Home: 0,
      End: -1,
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    focusItem(menu, target);
  }

  document.addEventListener("keydown", (event) => {
    const target = event.target as Element;
    const trigger = target.closest<HTMLElement>(
      "[data-markas-dropdown-menu-trigger]",
    );
    if (trigger) return onTriggerKeydown(event, trigger);
    const menu = target.closest("[data-markas-dropdown-menu]");
    if (isMenu(menu)) onMenuKeydown(event, menu);
  });

  document.addEventListener("click", (event) => {
    const entry = (event.target as Element).closest<HTMLElement>(
      "[data-markas-dropdown-menu] [role=menuitem]",
    );
    const menu = entry?.closest("[data-markas-dropdown-menu]") ?? null;
    if (!entry || !isMenu(menu)) return;
    menu.dispatchEvent(
      new CustomEvent("markas-select", {
        bubbles: true,
        detail: entry.dataset.value,
      }),
    );
    close(menu);
  });

  // beforetoggle and toggle do not bubble, so listen in the capture phase. beforetoggle runs
  // synchronously, so the state is current for the next key press.
  document.addEventListener(
    "beforetoggle",
    (event) => {
      if (!isMenu(event.target)) return;
      const state = (event as ToggleEvent).newState;
      event.target.dataset.state = state;
      const trigger = triggerOf(event.target);
      if (!trigger) return;
      trigger.dataset.state = state;
      trigger.setAttribute("aria-expanded", String(state === "open"));
    },
    true,
  );

  document.addEventListener(
    "toggle",
    (event) => {
      if (!isMenu(event.target)) return;
      if ((event as ToggleEvent).newState !== "open") {
        if (followed === event.target) unfollow?.();
        return;
      }
      place(event.target);
      follow(event.target);
      focusEdge(event.target, focusTarget);
      focusTarget = "first";
    },
    true,
  );
</script>
```

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

<DropdownMenu
  label="Actions"
  items={[
    { label: "Edit", value: "edit" },
    { label: "View details", href: "/projects/1" },
    { separator: true },
    { label: "Delete", value: "delete", danger: true },
  ]}
/>

<script>
  document.addEventListener("markas-select", (event) =>
    console.log((event as CustomEvent<string>).detail),
  );
</script>
```

Satu script kecil yang dibundel menjalankan semua dropdown menu di halaman, juga setelah view transition. Memilih item memancarkan event `markas-select` (bubble) dengan value item di `detail`.

### Angular

Simpan di `src/app/markas/dropdown-menu.component.ts`. Tanpa dependensi tambahan.

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

export type DropdownMenuItem =
  | { separator: true }
  | {
      separator?: false;
      label: string;
      value?: string;
      href?: string;
      danger?: boolean;
      disabled?: boolean;
    };

const root = "inline-block";
const triggerClass =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg border border-line bg-surface px-4 text-sm font-medium whitespace-nowrap text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary data-[state=open]:bg-subtle motion-reduce:transition-none";
const chevron = "size-4 text-muted";
const menu =
  "inset-auto m-0 min-w-48 rounded-lg border border-line bg-surface p-1 text-ink shadow-overlay";
const item =
  "flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const tones = {
  default: "text-ink hover:bg-subtle focus:bg-subtle",
  danger: "text-danger hover:bg-danger/10 focus:bg-danger/10",
};
const separator = "my-1 h-px bg-line";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Hrefs with a scheme other than http, https, mailto, and tel (such as javascript:) become "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

const GAP = 4;
const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';

/** Places the menu below the trigger, aligned to its start, and flips above when it does not fit. */
function placeMenu(trigger: HTMLElement, panel: HTMLElement) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const below = anchor.bottom + GAP;
  const above = anchor.top - GAP - height;
  const fitsBelow = below + height <= window.innerHeight;
  const top = fitsBelow || above < 0 ? below : above;
  const left = Math.max(
    GAP,
    Math.min(anchor.left, window.innerWidth - width - GAP),
  );
  panel.style.top = `${top}px`;
  panel.style.left = `${left}px`;
}

type FocusTarget = "first" | "last";
type Entry = {
  separator: boolean;
  label: string;
  value: string;
  href: string | null;
  disabled: boolean;
  classes: string;
};

let nextId = 0;

/**
 * Slots: an element with the `trigger` attribute (an ng-container works) replaces the label
 * inside the trigger button. Host stays out of layout; id moves to the menu, class to the root.
 */
@Component({
  selector: "markas-dropdown-menu",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.id]": "null" },
  template: `
    <div [class]="rootClasses()">
      <button
        #trigger
        type="button"
        [id]="menuId() + '-trigger'"
        [attr.popovertarget]="menuId()"
        aria-haspopup="menu"
        [attr.aria-expanded]="open() ? 'true' : 'false'"
        [attr.aria-controls]="menuId()"
        [attr.data-state]="state()"
        [class]="triggerClass"
        (keydown)="handleTriggerKeydown($event)"
      >
        <ng-content select="[trigger]">{{ label() }}</ng-content>
        <svg
          [class]="chevron"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>
      <div
        #menuEl
        [id]="menuId()"
        popover="auto"
        role="menu"
        [attr.aria-labelledby]="menuId() + '-trigger'"
        [attr.data-state]="state()"
        [class]="menu"
        (beforetoggle)="handleBeforeToggle($event)"
        (toggle)="handleToggle($event)"
        (keydown)="handleMenuKeydown($event)"
      >
        @for (entry of entries(); track $index) {
          @if (entry.separator) {
            <div role="separator" [class]="separator"></div>
          } @else if (entry.href !== null) {
            <a
              [href]="entry.href"
              role="menuitem"
              tabindex="-1"
              [class]="entry.classes"
              (click)="select(entry.value)"
              >{{ entry.label }}</a
            >
          } @else {
            <button
              type="button"
              role="menuitem"
              tabindex="-1"
              [disabled]="entry.disabled"
              [class]="entry.classes"
              (click)="select(entry.value)"
            >
              {{ entry.label }}
            </button>
          }
        }
      </div>
    </div>
  `,
})
export class DropdownMenu {
  readonly items = input.required<DropdownMenuItem[]>();
  readonly label = input("Options");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });
  /** Emits the value (or label) of the chosen item. */
  readonly selected = output<string>();

  protected readonly triggerClass = triggerClass;
  protected readonly chevron = chevron;
  protected readonly menu = menu;
  protected readonly separator = separator;
  protected readonly open = signal(false);
  protected readonly state = computed(() => (this.open() ? "open" : "closed"));
  private readonly generatedId = `markas-dropdown-menu-${nextId++}`;
  protected readonly menuId = computed(() => this.id() ?? this.generatedId);
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  protected readonly entries = computed(() =>
    this.items().map((entry): Entry =>
      entry.separator
        ? {
            separator: true,
            label: "",
            value: "",
            href: null,
            disabled: false,
            classes: "",
          }
        : {
            separator: false,
            label: entry.label,
            value: entry.value ?? entry.label,
            href: entry.href && !entry.disabled ? safeHref(entry.href) : null,
            disabled: entry.disabled ?? false,
            classes: `${item} ${tones[entry.danger ? "danger" : "default"]}`,
          },
    ),
  );
  private readonly triggerEl =
    viewChild.required<ElementRef<HTMLButtonElement>>("trigger");
  private readonly menuEl =
    viewChild.required<ElementRef<HTMLDivElement>>("menuEl");
  private focusTarget: FocusTarget = "first";
  private unfollow: (() => void) | undefined;

  constructor() {
    inject(DestroyRef).onDestroy(() => this.unfollow?.());
  }

  private readonly place = () =>
    placeMenu(this.triggerEl().nativeElement, this.menuEl().nativeElement);

  /** Re-runs placement while the page scrolls or the window resizes. */
  private follow() {
    this.unfollow?.();
    const scrollOptions = { capture: true, passive: true };
    window.addEventListener("scroll", this.place, scrollOptions);
    window.addEventListener("resize", this.place, { passive: true });
    this.unfollow = () => {
      window.removeEventListener("scroll", this.place, scrollOptions);
      window.removeEventListener("resize", this.place);
      this.unfollow = undefined;
    };
  }

  private menuItems() {
    return Array.from(
      this.menuEl().nativeElement.querySelectorAll<HTMLElement>(ITEM_SELECTOR),
    );
  }

  private focusItem(index: number) {
    const list = this.menuItems();
    if (list.length === 0) return;
    list[(index + list.length) % list.length]?.focus();
  }

  private focusEdge(target: FocusTarget) {
    this.focusItem(target === "first" ? 0 : -1);
  }

  private close() {
    this.menuEl().nativeElement.hidePopover();
    this.triggerEl().nativeElement.focus();
  }

  protected select(value: string) {
    this.selected.emit(value);
    this.close();
  }

  // beforetoggle runs synchronously, so the state is current for the next key press.
  protected handleBeforeToggle(event: Event) {
    this.open.set((event as ToggleEvent).newState === "open");
  }

  protected handleToggle(event: Event) {
    if ((event as ToggleEvent).newState !== "open") return this.unfollow?.();
    this.place();
    this.follow();
    this.focusEdge(this.focusTarget);
    this.focusTarget = "first";
  }

  protected handleTriggerKeydown(event: KeyboardEvent) {
    const targets: Record<string, FocusTarget | undefined> = {
      ArrowDown: "first",
      ArrowUp: "last",
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    if (this.open()) return this.focusEdge(target);
    this.focusTarget = target;
    this.menuEl().nativeElement.showPopover();
  }

  protected handleMenuKeydown(event: KeyboardEvent) {
    if (event.key === "Escape") {
      event.preventDefault();
      return this.close();
    }
    if (event.key === "Tab") return this.menuEl().nativeElement.hidePopover();
    const index = this.menuItems().indexOf(
      document.activeElement as HTMLElement,
    );
    const targets: Record<string, number | undefined> = {
      ArrowDown: index + 1,
      ArrowUp: index - 1,
      Home: 0,
      End: -1,
    };
    const target = targets[event.key];
    if (target === undefined) return;
    event.preventDefault();
    this.focusItem(target);
  }
}
```

```ts
import { Component } from "@angular/core";
import { DropdownMenu } from "./markas/dropdown-menu.component";

@Component({
  selector: "app-project-actions",
  imports: [DropdownMenu],
  template: `
    <markas-dropdown-menu
      label="Actions"
      [items]="items"
      (selected)="onSelect($event)"
    />
  `,
})
export class ProjectActions {
  readonly items = [
    { label: "Edit", value: "edit" },
    { label: "View details", href: "/projects/1" },
    { separator: true as const },
    { label: "Delete", value: "delete", danger: true },
  ];

  onSelect(value: string) {}
}
```

Isi tombol pemicu bisa diganti dengan elemen beratribut `trigger` (`ng-container` juga bisa).

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `items` | `{ label, value?, href?, danger?, disabled? }[] or { separator: true }` | [] | Daftar item menu. Item dengan href dirender sebagai link, separator menjadi garis pemisah. |
| `label` | `string` | Options | Teks tombol pemicu. Default "Options", isi misalnya "Opsi" atau "Aksi" untuk situs berbahasa Indonesia. |
| `trigger` | `slot / ReactNode / snippet` | - | Isi tombol pemicu kustom, menggantikan label. Angular: elemen dengan atribut trigger. |
| `onSelect / @select / markas-select` | `(value: string) => void` | - | Dipanggil saat item dipilih dengan value item (atau label bila value kosong). Blade memancarkan event markas-select. |
| `id` | `string` | auto | Id panel menu. Tombol pemicu memakai id ini dengan akhiran -trigger. |
| `selected` | `output<string>` | - | Khusus Angular. Dipancarkan dengan value item (atau label) saat item dipilih. Svelte memakai prop onselect, Astro memancarkan event markas-select seperti Blade. |

## Aksesibilitas

- Tombol pemicu memakai aria-haspopup=menu, aria-expanded, dan aria-controls ke panel role=menu.
- Enter, Spasi, atau panah bawah membuka menu dan memfokuskan item pertama; panah atas memfokuskan item terakhir.
- Panah atas dan bawah berpindah item (berputar di ujung), Home dan End ke item pertama dan terakhir, item nonaktif dilewati.
- Escape menutup menu dan mengembalikan fokus ke pemicu. Klik di luar menutup menu (light dismiss Popover API).

## Catatan

- Isi tombol bisa diganti lewat slot `trigger` (Blade dan Vue) atau prop `trigger` (React). Ikon panah tetap ditampilkan.
- Kalau `value` kosong, callback menerima `label` item.
- Panel menu tampil di top layer lewat Popover API, jadi tidak terpotong oleh `overflow: hidden` induknya.
- Teks tombol pemicu default dalam bahasa Inggris ("Options"). Isi `label` dengan "Opsi" atau "Aksi" untuk situs berbahasa Indonesia.
