# Context Menu

Menu opened by right-clicking an area or pressing Shift+F10, shown at the pointer through the Popover API with WAI-ARIA Menu keyboard support.

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

## When to use

Secondary actions on an object people right-click, such as a file, canvas, table row, or image, where a visible menu button would add clutter.

- Always offer the same actions somewhere visible too; a context menu is a shortcut, not the only path
- Put destructive actions last with danger: true and separate them with a separator
- Give the area visible text or an aria-label so focus on it makes sense

## Code

### Blade

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

```blade
@props([
    'items' => [],
    'menuLabel' => 'Context menu',
    'hintLabel' => 'Press Shift+F10 to open the context menu',
])

@php
    $area = 'block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
    $hint = 'sr-only';
    $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-context-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-context-menu-'.hash('xxh32', $idKey.$idIndex);
@endphp

<div
    class="contents"
    x-data="{
        open: false,
        offset: { x: 0, y: 0 },
        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();
        },
        {{-- Letakkan menu di titik (relatif ke area), geser atau balik ke atas kalau tidak muat di layar. --}}
        place() {
            const gap = 4;
            const anchor = this.$refs.area.getBoundingClientRect();
            const { width, height } = this.$refs.menu.getBoundingClientRect();
            const x = anchor.left + this.offset.x;
            const y = anchor.top + this.offset.y;
            const fitsBelow = y + height <= window.innerHeight - gap;
            this.$refs.menu.style.top = (fitsBelow ? y : Math.max(gap, y - height)) + 'px';
            this.$refs.menu.style.left = Math.max(gap, Math.min(x, 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?.();
        },
        openAt(offset) {
            this.offset = offset;
            // Tempatkan sinkron setelah showPopover; event toggle baru datang belakangan.
            if (!this.open) this.$refs.menu.showPopover();
            this.place();
            this.focusItem(0);
        },
        close() {
            this.$refs.menu.hidePopover();
            this.$refs.area.focus();
        },
        select(value) {
            {{-- Dispatch from the area: it carries the user's attributes (x-on:, wire:), the menu is its sibling. --}}
            this.$refs.area.dispatchEvent(new CustomEvent('markas-select', { detail: value, bubbles: true }));
            this.close();
        },
        onContextMenu(event) {
            event.preventDefault();
            const anchor = this.$refs.area.getBoundingClientRect();
            this.openAt({ x: event.clientX - anchor.left, y: event.clientY - anchor.top });
        },
        {{-- Shift+F10 dan tombol ContextMenu membuka menu dari keyboard. --}}
        onAreaKeydown(event) {
            if (event.key !== 'ContextMenu' && !(event.shiftKey && event.key === 'F10')) return;
            event.preventDefault();
            this.openAt({ x: 0, y: 0 });
        },
        {{-- 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.focusItem(0);
        },
        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);
        },
    }"
>
    <div
        x-ref="area"
        role="group"
        tabindex="0"
        aria-describedby="{{ $id }}-hint"
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @contextmenu="onContextMenu($event)"
        @keydown="onAreaKeydown($event)"
        {{ $attributes->except('id')->class([$area]) }}
    >{{ $slot }}</div>
    <span id="{{ $id }}-hint" class="{{ $hint }}">{{ $hintLabel }}</span>
    <div
        x-ref="menu"
        id="{{ $id }}"
        popover="auto"
        wire:ignore.self
        role="menu"
        aria-label="{{ $menuLabel }}"
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @beforetoggle="onBeforeToggle($event)"
        @toggle="onToggle($event)"
        @keydown="onMenuKeydown($event)"
        @contextmenu.prevent
        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.context-menu
    :items="[
        ['label' => 'Open', 'value' => 'open'],
        ['label' => 'Rename', 'value' => 'rename'],
        ['separator' => true],
        ['label' => 'Delete', 'value' => 'delete', 'danger' => true],
    ]"
    x-on:markas-select="console.log($event.detail)"
>
    <div class="rounded-lg border border-dashed border-line p-8 text-sm text-muted">Right-click here</div>
</x-markas.context-menu>
```

Needs Alpine.js. Selecting an item dispatches a `markas-select` event with the item value in `$event.detail`. In Livewire: `x-on:markas-select="$wire.handle($event.detail)"`.

### Livewire

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

`wire:markas-select` calls a Livewire action with the picked value.

### React

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

```tsx
"use client";

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

const area =
  "block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const hint = "sr-only";
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)';

type Offset = { x: number; y: number };

/** Letakkan menu di titik (relatif ke area), geser atau balik ke atas kalau tidak muat di layar. */
function placeMenu(target: HTMLElement, panel: HTMLElement, offset: Offset) {
  const anchor = target.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const x = anchor.left + offset.x;
  const y = anchor.top + offset.y;
  const fitsBelow = y + height <= window.innerHeight - GAP;
  const top = fitsBelow ? y : Math.max(GAP, y - height);
  const left = Math.max(GAP, Math.min(x, 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);
  };
}

/** Shift+F10 dan tombol ContextMenu membuka menu dari keyboard. */
const isMenuKey = (event: KeyboardEvent) =>
  event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");

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

export type ContextMenuProps = Omit<ComponentProps<"div">, "onSelect"> & {
  items: ContextMenuItem[];
  /** Label aksesibel panel menu. */
  menuLabel?: string;
  /** Petunjuk tersembunyi untuk pembaca layar tentang cara membuka menu. */
  hintLabel?: string;
  onSelect?: (value: string) => void;
};

export function ContextMenu({
  items,
  menuLabel = "Context menu",
  hintLabel = "Press Shift+F10 to open the context menu",
  onSelect,
  id,
  className,
  children,
  ...props
}: ContextMenuProps) {
  const generatedId = useId();
  const menuId = id ?? generatedId;
  const areaRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const offset = useRef<Offset>({ x: 0, y: 0 });
  const [open, setOpen] = useState(false);
  const state = open ? "open" : "closed";

  const place = () => {
    if (areaRef.current && menuRef.current)
      placeMenu(areaRef.current, menuRef.current, offset.current);
  };

  useEffect(() => {
    if (!open) return;
    return followViewport(() => {
      if (areaRef.current && menuRef.current)
        placeMenu(areaRef.current, menuRef.current, offset.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 openAt = (next: Offset) => {
    offset.current = next;
    // Tempatkan sinkron setelah showPopover; event toggle baru datang belakangan.
    if (!open) menuRef.current?.showPopover();
    place();
    focusItem(0);
  };
  const close = () => {
    menuRef.current?.hidePopover();
    areaRef.current?.focus();
  };
  const select = (value: string) => {
    onSelect?.(value);
    close();
  };

  const handleContextMenu = (event: MouseEvent<HTMLDivElement>) => {
    event.preventDefault();
    const anchor = event.currentTarget.getBoundingClientRect();
    openAt({ x: event.clientX - anchor.left, y: event.clientY - anchor.top });
  };
  const handleAreaKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (!isMenuKey(event)) return;
    event.preventDefault();
    openAt({ x: 0, y: 0 });
  };

  // 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") return;
    place();
    focusItem(0);
  };

  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="contents">
      <div
        {...props}
        ref={areaRef}
        role="group"
        tabIndex={0}
        aria-describedby={`${menuId}-hint`}
        data-state={state}
        className={cx(area, className)}
        onContextMenu={handleContextMenu}
        onKeyDown={handleAreaKeyDown}
      >
        {children}
      </div>
      <span id={`${menuId}-hint`} className={hint}>
        {hintLabel}
      </span>
      <div
        ref={menuRef}
        id={menuId}
        popover="auto"
        role="menu"
        aria-label={menuLabel}
        data-state={state}
        className={menu}
        onBeforeToggle={handleBeforeToggle}
        onToggle={handleToggle}
        onKeyDown={handleMenuKeyDown}
        onContextMenu={(event) => event.preventDefault()}
      >
        {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 { ContextMenu } from "@/components/markas/ContextMenu";

<ContextMenu
  items={[
    { label: "Open", value: "open" },
    { label: "Rename", value: "rename" },
    { separator: true },
    { label: "Delete", value: "delete", danger: true },
  ]}
  onSelect={(value) => console.log(value)}
>
  <div className="rounded-lg border border-dashed border-line p-8 text-sm text-muted">
    Right-click here
  </div>
</ContextMenu>;
```

### Vue

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

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

defineOptions({ inheritAttrs: false });

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

type Offset = { x: number; y: number };

const props = withDefaults(
  defineProps<{
    items: ContextMenuItem[];
    menuLabel?: string;
    hintLabel?: string;
    id?: string;
  }>(),
  {
    menuLabel: "Context menu",
    hintLabel: "Press Shift+F10 to open the context menu",
    id: undefined,
  },
);
const emit = defineEmits<{ select: [value: string] }>();

const area =
  "block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const hint = "sr-only";
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 titik (relatif ke area), geser atau balik ke atas kalau tidak muat di layar. */
function placeMenu(target: HTMLElement, panel: HTMLElement, offset: Offset) {
  const anchor = target.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const x = anchor.left + offset.x;
  const y = anchor.top + offset.y;
  const fitsBelow = y + height <= window.innerHeight - GAP;
  const top = fitsBelow ? y : Math.max(GAP, y - height);
  const left = Math.max(GAP, Math.min(x, 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);
  };
}

/** Shift+F10 dan tombol ContextMenu membuka menu dari keyboard. */
const isMenuKey = (event: KeyboardEvent) =>
  event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");

const generatedId = useId();
const menuId = computed(() => props.id ?? generatedId);
const areaEl = useTemplateRef<HTMLDivElement>("areaRef");
const menuEl = useTemplateRef<HTMLDivElement>("menuRef");
const open = ref(false);
const state = computed(() => (open.value ? "open" : "closed"));
let offset: Offset = { x: 0, y: 0 };
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();
}

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

function openAt(next: Offset) {
  offset = next;
  // Tempatkan sinkron setelah showPopover; event toggle baru datang belakangan.
  if (!open.value) menuEl.value?.showPopover();
  place();
  focusItem(0);
}

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

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

function onContextMenu(event: MouseEvent) {
  event.preventDefault();
  const anchor = (event.currentTarget as HTMLElement).getBoundingClientRect();
  openAt({ x: event.clientX - anchor.left, y: event.clientY - anchor.top });
}

function onAreaKeydown(event: KeyboardEvent) {
  if (!isMenuKey(event)) return;
  event.preventDefault();
  openAt({ x: 0, y: 0 });
}

// 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 onToggle(event: Event) {
  stopFollowing();
  if ((event as ToggleEvent).newState !== "open") return;
  place();
  unfollow = followViewport(place);
  focusItem(0);
}

onBeforeUnmount(stopFollowing);

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="contents">
    <div
      ref="areaRef"
      role="group"
      tabindex="0"
      :aria-describedby="`${menuId}-hint`"
      :data-state="state"
      :class="area"
      v-bind="$attrs"
      @contextmenu="onContextMenu"
      @keydown="onAreaKeydown"
    >
      <slot />
    </div>
    <span :id="`${menuId}-hint`" :class="hint">{{ props.hintLabel }}</span>
    <div
      :id="menuId"
      ref="menuRef"
      popover="auto"
      role="menu"
      :aria-label="props.menuLabel"
      :data-state="state"
      :class="menu"
      @beforetoggle="onBeforeToggle"
      @toggle="onToggle"
      @keydown="onMenuKeydown"
      @contextmenu.prevent
    >
      <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>
  <ContextMenu
    :items="[
      { label: 'Open', value: 'open' },
      { label: 'Rename', value: 'rename' },
      { separator: true },
      { label: 'Delete', value: 'delete', danger: true },
    ]"
    @select="(value) => console.log(value)"
  >
    <div
      class="rounded-lg border border-dashed border-line p-8 text-sm text-muted"
    >
      Right-click here
    </div>
  </ContextMenu>
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type ContextMenuItem =
    | { 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 area =
    "block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
  const hint = "sr-only";
  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)';

  type Offset = { x: number; y: number };

  /** Places the menu at the point (relative to the area), shifting or flipping up when it does not fit. */
  function placeMenu(target: HTMLElement, panel: HTMLElement, offset: Offset) {
    const anchor = target.getBoundingClientRect();
    const { width, height } = panel.getBoundingClientRect();
    const x = anchor.left + offset.x;
    const y = anchor.top + offset.y;
    const fitsBelow = y + height <= window.innerHeight - GAP;
    const top = fitsBelow ? y : Math.max(GAP, y - height);
    const left = Math.max(GAP, Math.min(x, window.innerWidth - width - GAP));
    panel.style.top = `${top}px`;
    panel.style.left = `${left}px`;
  }

  /** Shift+F10 and the ContextMenu key open the menu from the keyboard. */
  const isMenuKey = (event: KeyboardEvent) =>
    event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "onselect"> & {
    items: ContextMenuItem[];
    /** Accessible label of the menu panel. */
    menuLabel?: string;
    /** Hidden screen reader hint on how to open the menu. */
    hintLabel?: string;
    onselect?: (value: string) => void;
    children?: Snippet;
  };

  let {
    items,
    menuLabel = "Context menu",
    hintLabel = "Press Shift+F10 to open the context menu",
    onselect,
    id,
    class: className,
    children,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const menuId = $derived(id ?? generatedId);
  let areaEl = $state<HTMLDivElement>();
  let menuEl = $state<HTMLDivElement>();
  let open = $state(false);
  const dataState = $derived(open ? "open" : "closed");
  let offset: Offset = { x: 0, y: 0 };

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

  // 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();
  }

  function openAt(next: Offset) {
    offset = next;
    // Place synchronously after showPopover; the toggle event arrives later.
    if (!open) menuEl?.showPopover();
    place();
    focusItem(0);
  }

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

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

  function handleContextMenu(
    event: MouseEvent & { currentTarget: HTMLDivElement },
  ) {
    event.preventDefault();
    const anchor = event.currentTarget.getBoundingClientRect();
    openAt({ x: event.clientX - anchor.left, y: event.clientY - anchor.top });
  }

  function handleAreaKeydown(event: KeyboardEvent) {
    if (!isMenuKey(event)) return;
    event.preventDefault();
    openAt({ x: 0, y: 0 });
  }

  // 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();
    focusItem(0);
  }

  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="contents">
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
  <div
    {...rest}
    bind:this={areaEl}
    role="group"
    tabindex="0"
    aria-describedby={`${menuId}-hint`}
    data-state={dataState}
    class={[area, className]}
    oncontextmenu={handleContextMenu}
    onkeydown={handleAreaKeydown}
  >
    {@render children?.()}
  </div>
  <span id={`${menuId}-hint`} class={hint}>{hintLabel}</span>
  <!-- svelte-ignore a11y_interactive_supports_focus -->
  <div
    bind:this={menuEl}
    id={menuId}
    popover="auto"
    role="menu"
    aria-label={menuLabel}
    data-state={dataState}
    class={menu}
    onbeforetoggle={handleBeforeToggle}
    ontoggle={handleToggle}
    onkeydown={handleMenuKeydown}
    oncontextmenu={(event) => event.preventDefault()}
  >
    {#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 ContextMenu from "$lib/components/markas/ContextMenu.svelte";
</script>

<ContextMenu
  items={[
    { label: "Open", value: "open" },
    { label: "Rename", value: "rename" },
    { separator: true },
    { label: "Delete", value: "delete", danger: true },
  ]}
  onselect={(value) => console.log(value)}
>
  <div
    class="rounded-lg border border-dashed border-line p-8 text-sm text-muted"
  >
    Right-click here
  </div>
</ContextMenu>
```

### Astro

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

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

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

const area =
  "block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const hint = "sr-only";
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: ContextMenuItem[];
  /** Accessible label of the menu panel. */
  menuLabel?: string;
  /** Hidden screen reader hint on how to open the menu. */
  hintLabel?: string;
};

const {
  items,
  menuLabel = "Context menu",
  hintLabel = "Press Shift+F10 to open the context menu",
  id,
  class: className,
  ...rest
} = Astro.props;
const menuId = id ?? `markas-context-menu-${crypto.randomUUID().slice(0, 8)}`;
---

<div class="contents">
  <div
    {...rest}
    role="group"
    tabindex="0"
    aria-describedby={`${menuId}-hint`}
    data-state="closed"
    data-markas-context-menu={menuId}
    class:list={[area, className]}
  >
    <slot />
  </div>
  <span id={`${menuId}-hint`} class={hint}>{hintLabel}</span>
  <div
    id={menuId}
    popover="auto"
    role="menu"
    aria-label={menuLabel}
    data-state="closed"
    data-markas-context-menu-panel
    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 context menu, including markup added later
  // and pages reached through view transitions. Only one auto popover menu is open at a time.
  type Offset = { x: number; y: number };

  const GAP = 4;
  const ITEM_SELECTOR = '[role="menuitem"]:not(:disabled)';
  const offsets = new WeakMap<HTMLElement, Offset>();
  let followed: HTMLElement | undefined;
  let unfollow: (() => void) | undefined;

  const isMenu = (node: EventTarget | null): node is HTMLElement =>
    node instanceof HTMLElement &&
    node.hasAttribute("data-markas-context-menu-panel");
  const areaOf = (menu: HTMLElement) =>
    document.querySelector<HTMLElement>(
      `[data-markas-context-menu="${CSS.escape(menu.id)}"]`,
    );
  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();
  }

  /** Places the menu at the point (relative to the area), shifting or flipping up when it does not fit. */
  function place(menu: HTMLElement) {
    const target = areaOf(menu);
    if (!target) return;
    const offset = offsets.get(menu) ?? { x: 0, y: 0 };
    const anchor = target.getBoundingClientRect();
    const { width, height } = menu.getBoundingClientRect();
    const x = anchor.left + offset.x;
    const y = anchor.top + offset.y;
    const fitsBelow = y + height <= window.innerHeight - GAP;
    const top = fitsBelow ? y : Math.max(GAP, y - height);
    const left = Math.max(GAP, Math.min(x, 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 openAt(area: HTMLElement, offset: Offset) {
    const menu = document.getElementById(
      area.dataset.markasContextMenu ?? "",
    );
    if (!isMenu(menu)) return;
    offsets.set(menu, offset);
    // Place synchronously after showPopover; the toggle event arrives later.
    if (!menu.matches(":popover-open")) menu.showPopover();
    place(menu);
    focusItem(menu, 0);
  }

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

  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("contextmenu", (event) => {
    const target = event.target as Element;
    if (target.closest("[data-markas-context-menu-panel]"))
      return event.preventDefault();
    const area = target.closest<HTMLElement>("[data-markas-context-menu]");
    if (!area) return;
    event.preventDefault();
    const anchor = area.getBoundingClientRect();
    openAt(area, {
      x: event.clientX - anchor.left,
      y: event.clientY - anchor.top,
    });
  });

  document.addEventListener("keydown", (event) => {
    const target = event.target as Element;
    const menu = target.closest("[data-markas-context-menu-panel]");
    if (isMenu(menu)) return onMenuKeydown(event, menu);
    // Shift+F10 and the ContextMenu key open the menu from the keyboard.
    const isMenuKey =
      event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");
    const area = target.closest<HTMLElement>("[data-markas-context-menu]");
    if (!isMenuKey || !area) return;
    event.preventDefault();
    openAt(area, { x: 0, y: 0 });
  });

  document.addEventListener("click", (event) => {
    const entry = (event.target as Element).closest<HTMLElement>(
      "[data-markas-context-menu-panel] [role=menuitem]",
    );
    const menu = entry?.closest("[data-markas-context-menu-panel]") ?? 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 area = areaOf(event.target);
      if (area) area.dataset.state = state;
    },
    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);
      focusItem(event.target, 0);
    },
    true,
  );
</script>
```

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

<ContextMenu
  items={[
    { label: "Open", value: "open" },
    { label: "Rename", value: "rename" },
    { separator: true },
    { label: "Delete", value: "delete", danger: true },
  ]}
>
  <div class="rounded-lg border border-dashed border-line p-8 text-sm text-muted">
    Right-click here
  </div>
</ContextMenu>

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

A small bundled script runs every context menu on the page, also after view transitions. Selecting an item dispatches a bubbling `markas-select` event with the item value in `detail`.

### Angular

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

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

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

const area =
  "block rounded-lg focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const hint = "sr-only";
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)';

type Offset = { x: number; y: number };

/** Places the menu at the point (relative to the area), shifting or flipping up when it does not fit. */
function placeMenu(target: HTMLElement, panel: HTMLElement, offset: Offset) {
  const anchor = target.getBoundingClientRect();
  const { width, height } = panel.getBoundingClientRect();
  const x = anchor.left + offset.x;
  const y = anchor.top + offset.y;
  const fitsBelow = y + height <= window.innerHeight - GAP;
  const top = fitsBelow ? y : Math.max(GAP, y - height);
  const left = Math.max(GAP, Math.min(x, window.innerWidth - width - GAP));
  panel.style.top = `${top}px`;
  panel.style.left = `${left}px`;
}

/** Shift+F10 and the ContextMenu key open the menu from the keyboard. */
const isMenuKey = (event: KeyboardEvent) =>
  event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");

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

let nextId = 0;

/**
 * The content is the area that opens the menu on right-click, Shift+F10, or the ContextMenu key.
 * Host stays out of layout; id moves to the menu, class and aria-label to the area.
 */
@Component({
  selector: "markas-context-menu",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    class: "contents",
    "[attr.id]": "null",
    "[attr.aria-label]": "null",
  },
  template: `
    <div
      #area
      role="group"
      tabindex="0"
      [attr.aria-label]="ariaLabel() ?? null"
      [attr.aria-describedby]="menuId() + '-hint'"
      [attr.data-state]="state()"
      [class]="areaClasses()"
      (contextmenu)="handleContextMenu($event)"
      (keydown)="handleAreaKeydown($event)"
    >
      <ng-content />
    </div>
    <span [id]="menuId() + '-hint'" [class]="hint">{{ hintLabel() }}</span>
    <div
      #menuEl
      [id]="menuId()"
      popover="auto"
      role="menu"
      [attr.aria-label]="menuLabel()"
      [attr.data-state]="state()"
      [class]="menu"
      (beforetoggle)="handleBeforeToggle($event)"
      (toggle)="handleToggle($event)"
      (keydown)="handleMenuKeydown($event)"
      (contextmenu)="$event.preventDefault()"
    >
      @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>
  `,
})
export class ContextMenu {
  readonly items = input.required<ContextMenuItem[]>();
  /** Accessible label of the menu panel. */
  readonly menuLabel = input("Context menu");
  /** Hidden screen reader hint on how to open the menu. */
  readonly hintLabel = input("Press Shift+F10 to open the context menu");
  readonly id = input<string>();
  readonly ariaLabel = input<string | undefined>(undefined, {
    alias: "aria-label",
  });
  readonly userClass = input("", { alias: "class" });
  /** Emits the value (or label) of the chosen item. */
  readonly selected = output<string>();

  protected readonly hint = hint;
  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-context-menu-${nextId++}`;
  protected readonly menuId = computed(() => this.id() ?? this.generatedId);
  protected readonly areaClasses = computed(() =>
    [area, 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 areaEl =
    viewChild.required<ElementRef<HTMLDivElement>>("area");
  private readonly menuEl =
    viewChild.required<ElementRef<HTMLDivElement>>("menuEl");
  private offset: Offset = { x: 0, y: 0 };
  private unfollow: (() => void) | undefined;

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

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

  /** 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 openAt(next: Offset) {
    this.offset = next;
    // Place synchronously after showPopover; the toggle event arrives later.
    if (!this.open()) this.menuEl().nativeElement.showPopover();
    this.place();
    this.focusItem(0);
  }

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

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

  protected handleContextMenu(event: MouseEvent) {
    event.preventDefault();
    const anchor = this.areaEl().nativeElement.getBoundingClientRect();
    this.openAt({
      x: event.clientX - anchor.left,
      y: event.clientY - anchor.top,
    });
  }

  protected handleAreaKeydown(event: KeyboardEvent) {
    if (!isMenuKey(event)) return;
    event.preventDefault();
    this.openAt({ x: 0, y: 0 });
  }

  // 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.focusItem(0);
  }

  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 { ContextMenu } from "./markas/context-menu.component";

@Component({
  selector: "app-file-card",
  imports: [ContextMenu],
  template: `
    <markas-context-menu [items]="items" (selected)="onSelect($event)">
      <div
        class="rounded-lg border border-dashed border-line p-8 text-sm text-muted"
      >
        Right-click here
      </div>
    </markas-context-menu>
  `,
})
export class FileCard {
  readonly items = [
    { label: "Open", value: "open" },
    { label: "Rename", value: "rename" },
    { separator: true as const },
    { label: "Delete", value: "delete", danger: true },
  ];

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

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `items` | `{ label, value?, href?, danger?, disabled? }[] or { separator: true }` | [] | Menu items. Items with href render as links, separators render as a dividing line. |
| `children / slot` | `ReactNode / slot / snippet` | - | Content of the trigger area. Right-clicking anywhere in it opens the menu. Angular: the projected content. |
| `menuLabel` | `string` | Context menu | Accessible name of the menu panel. |
| `hintLabel` | `string` | Press Shift+F10 to open the context menu | Screen reader hint linked to the trigger area with aria-describedby. |
| `onSelect / @select / markas-select` | `(value: string) => void` | - | Called when an item is selected, with the item value (or label when value is empty). Blade dispatches a markas-select event. |
| `id` | `string` | auto | Menu panel id. The hint uses this id with a -hint suffix. |
| `selected` | `output<string>` | - | Angular only. Emits the item value (or label) when an item is selected. Svelte uses the onselect prop, Astro dispatches a markas-select event like Blade. |

## Accessibility

- The trigger area is focusable (tabindex=0) and described by a hidden hint that explains Shift+F10.
- Right-click opens the menu at the pointer; Shift+F10 or the ContextMenu key opens it at the top left corner of the area. The first item receives focus.
- Arrow Up and Arrow Down move between items (wrapping at the ends), Home and End jump to the first and last item, disabled items are skipped.
- Escape closes the menu and returns focus to the area, Tab closes it. Clicking outside closes the menu (Popover API light dismiss).

## Notes

- Attributes and `class` go to the trigger area, which is focusable. Shift+F10 or the ContextMenu key opens the menu from the keyboard.
- When `value` is empty, the callback receives the item `label`.
- The menu renders in the top layer through the Popover API and stays inside the viewport near the edges.
- `menuLabel` and `hintLabel` default to English. Translate them for other languages.
