# Popover

Panel mengambang non-modal berbasis Popover API untuk form kecil dan detail tambahan, menempel pada tombol pemicu.

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

## Kapan dipakai

Menampilkan form kecil atau detail tambahan di samping tombol tanpa pindah halaman, misalnya opsi berbagi, filter, atau pengaturan cepat.

- Jaga isi tetap singkat; gunakan Modal atau Drawer untuk form panjang
- Gunakan Dropdown Menu untuk daftar aksi dan Tooltip untuk petunjuk singkat
- Tambahkan teks sr-only di slot trigger bila pemicu hanya berisi ikon

## Kode

### Blade

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

```blade
@props([
    'label' => 'Open',
    'side' => 'bottom',
    'align' => 'start',
])

@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';
    $panel = 'inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay';

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

<div
    x-data="{
        open: false,
        {{-- Letakkan panel di sisi pilihan dengan perataan pilihan, pindah sisi kalau tidak muat. --}}
        place() {
            const gap = 4;
            const anchor = this.$refs.trigger.getBoundingClientRect();
            const { width, height } = this.$refs.panel.getBoundingClientRect();
            const above = anchor.top - gap - height;
            const below = anchor.bottom + gap;
            const fitsAbove = above >= 0;
            const fitsBelow = below + height <= window.innerHeight;
            const onTop = @js($side) === 'top' ? fitsAbove || ! fitsBelow : ! fitsBelow && fitsAbove;
            const starts = { start: anchor.left, center: anchor.left + anchor.width / 2 - width / 2, end: anchor.right - width };
            const start = starts[@js($align)] ?? starts.start;
            this.$refs.panel.style.top = (onTop ? above : below) + 'px';
            this.$refs.panel.style.left = Math.max(gap, Math.min(start, 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?.();
        },
        {{-- beforetoggle berjalan sinkron, jadi status selalu terbaru untuk klik berikutnya. --}}
        onBeforeToggle(event) {
            this.open = event.newState === 'open';
        },
        onToggle(event) {
            if (event.newState === 'open') {
                this.place();
                this.follow();
                this.$refs.panel.querySelector('a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex=\'-1\'])')?.focus();
                return;
            }
            this.unfollow?.();
            {{-- Fokus kembali ke pemicu, kecuali user sudah memindahkannya ke elemen lain di luar panel. --}}
            const active = document.activeElement;
            if (active === document.body || this.$refs.panel.contains(active)) this.$refs.trigger.focus();
        },
        onKeydown(event) {
            if (event.key !== 'Escape') return;
            event.preventDefault();
            this.$refs.panel.hidePopover();
            this.$refs.trigger.focus();
        },
    }"
    {{ $attributes->except('id')->class([$root]) }}
>
    <button
        x-ref="trigger"
        type="button"
        id="{{ $id }}-trigger"
        popovertarget="{{ $id }}"
        aria-haspopup="dialog"
        aria-expanded="false"
        aria-controls="{{ $id }}"
        data-state="closed"
        :aria-expanded="open ? 'true' : 'false'"
        :data-state="open ? 'open' : 'closed'"
        class="{{ $triggerClass }}"
    >{{ $trigger ?? $label }}</button>
    <div
        x-ref="panel"
        id="{{ $id }}"
        popover="auto"
        wire:ignore.self
        role="dialog"
        aria-labelledby="{{ $id }}-trigger"
        data-state="closed"
        :data-state="open ? 'open' : 'closed'"
        @beforetoggle="onBeforeToggle($event)"
        @toggle="onToggle($event)"
        @keydown="onKeydown($event)"
        class="{{ $panel }}"
    >{{ $slot }}</div>
</div>
```

```blade
<x-markas.popover label="Bagikan">
    <div class="grid gap-3">
        <p class="text-muted">Siapa pun yang punya link bisa melihat proyek ini.</p>
        <x-markas.button size="sm">Salin link</x-markas.button>
    </div>
</x-markas.popover>
```

Butuh Alpine.js.

### React

Simpan di `src/components/markas/Popover.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 panel =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const GAP = 4;
const FOCUSABLE =
  "a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex='-1'])";

type Side = "top" | "bottom";
type Align = "start" | "center" | "end";

/** Letakkan panel di sisi pilihan dengan perataan pilihan, pindah sisi kalau tidak muat. */
function placePanel(
  trigger: HTMLElement,
  target: HTMLElement,
  side: Side,
  align: Align,
) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = target.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const fitsAbove = above >= 0;
  const fitsBelow = below + height <= window.innerHeight;
  const onTop =
    side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
  const starts: Record<Align, number> = {
    start: anchor.left,
    center: anchor.left + anchor.width / 2 - width / 2,
    end: anchor.right - width,
  };
  const start = starts[align] ?? starts.start;
  const left = Math.max(GAP, Math.min(start, window.innerWidth - width - GAP));
  target.style.top = `${onTop ? above : below}px`;
  target.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 PopoverProps = ComponentProps<"div"> & {
  /** Teks tombol pemicu. */
  label?: string;
  /** Isi tombol pemicu kustom, menggantikan label. */
  trigger?: ReactNode;
  side?: Side;
  align?: Align;
};

export function Popover({
  label = "Open",
  trigger,
  side = "bottom",
  align = "start",
  id,
  className,
  children,
  ...props
}: PopoverProps) {
  const generatedId = useId();
  const panelId = id ?? generatedId;
  const triggerRef = useRef<HTMLButtonElement>(null);
  const panelRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const state = open ? "open" : "closed";

  const place = () => {
    if (triggerRef.current && panelRef.current)
      placePanel(triggerRef.current, panelRef.current, side, align);
  };

  useEffect(() => {
    if (!open) return;
    return followViewport(() => {
      if (triggerRef.current && panelRef.current)
        placePanel(triggerRef.current, panelRef.current, side, align);
    });
  }, [open, side, align]);

  // beforetoggle berjalan sinkron, jadi status selalu terbaru untuk klik berikutnya.
  const handleBeforeToggle = (event: ToggleEvent<HTMLDivElement>) =>
    setOpen(event.newState === "open");
  const handleToggle = (event: ToggleEvent<HTMLDivElement>) => {
    const target = panelRef.current;
    if (!target) return;
    if (event.newState === "open") {
      place();
      target.querySelector<HTMLElement>(FOCUSABLE)?.focus();
      return;
    }
    // Fokus kembali ke pemicu, kecuali user sudah memindahkannya ke elemen lain di luar panel.
    const active = document.activeElement;
    if (active === document.body || target.contains(active))
      triggerRef.current?.focus();
  };
  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key !== "Escape") return;
    event.preventDefault();
    panelRef.current?.hidePopover();
    triggerRef.current?.focus();
  };

  return (
    <div className={cx(root, className)} {...props}>
      <button
        ref={triggerRef}
        type="button"
        id={`${panelId}-trigger`}
        popoverTarget={panelId}
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-controls={panelId}
        data-state={state}
        className={triggerClass}
      >
        {trigger ?? label}
      </button>
      <div
        ref={panelRef}
        id={panelId}
        popover="auto"
        role="dialog"
        aria-labelledby={`${panelId}-trigger`}
        data-state={state}
        className={panel}
        onBeforeToggle={handleBeforeToggle}
        onToggle={handleToggle}
        onKeyDown={handleKeyDown}
      >
        {children}
      </div>
    </div>
  );
}
```

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

<Popover label="Bagikan" align="end">
  <div className="grid gap-3">
    <p className="text-muted">
      Siapa pun yang punya link bisa melihat proyek ini.
    </p>
    <Button size="sm">Salin link</Button>
  </div>
</Popover>;
```

### Vue

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

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

type Side = "top" | "bottom";
type Align = "start" | "center" | "end";

const props = withDefaults(
  defineProps<{
    label?: string;
    side?: Side;
    align?: Align;
    id?: string;
  }>(),
  { label: "Open", side: "bottom", align: "start", id: undefined },
);

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 panel =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

const GAP = 4;
const FOCUSABLE =
  "a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex='-1'])";

/** Letakkan panel di sisi pilihan dengan perataan pilihan, pindah sisi kalau tidak muat. */
function placePanel(
  trigger: HTMLElement,
  target: HTMLElement,
  side: Side,
  align: Align,
) {
  const anchor = trigger.getBoundingClientRect();
  const { width, height } = target.getBoundingClientRect();
  const above = anchor.top - GAP - height;
  const below = anchor.bottom + GAP;
  const fitsAbove = above >= 0;
  const fitsBelow = below + height <= window.innerHeight;
  const onTop =
    side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
  const starts: Record<Align, number> = {
    start: anchor.left,
    center: anchor.left + anchor.width / 2 - width / 2,
    end: anchor.right - width,
  };
  const start = starts[align] ?? starts.start;
  const left = Math.max(GAP, Math.min(start, window.innerWidth - width - GAP));
  target.style.top = `${onTop ? above : below}px`;
  target.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 panelId = computed(() => props.id ?? generatedId);
const triggerEl = useTemplateRef<HTMLButtonElement>("trigger");
const panelEl = useTemplateRef<HTMLDivElement>("panelRef");
const open = ref(false);
const state = computed(() => (open.value ? "open" : "closed"));
let unfollow: (() => void) | undefined;

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

function place() {
  if (triggerEl.value && panelEl.value)
    placePanel(triggerEl.value, panelEl.value, props.side, props.align);
}

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

function onToggle(event: Event) {
  stopFollowing();
  const target = panelEl.value;
  if (!target) return;
  if ((event as ToggleEvent).newState === "open") {
    place();
    unfollow = followViewport(place);
    target.querySelector<HTMLElement>(FOCUSABLE)?.focus();
    return;
  }
  // Fokus kembali ke pemicu, kecuali user sudah memindahkannya ke elemen lain di luar panel.
  const active = document.activeElement;
  if (active === document.body || target.contains(active))
    triggerEl.value?.focus();
}

function onKeydown(event: KeyboardEvent) {
  if (event.key !== "Escape") return;
  event.preventDefault();
  panelEl.value?.hidePopover();
  triggerEl.value?.focus();
}

onBeforeUnmount(stopFollowing);
</script>

<template>
  <div :class="root">
    <button
      :id="`${panelId}-trigger`"
      ref="trigger"
      type="button"
      :popovertarget="panelId"
      aria-haspopup="dialog"
      :aria-expanded="open ? 'true' : 'false'"
      :aria-controls="panelId"
      :data-state="state"
      :class="triggerClass"
    >
      <slot name="trigger">{{ props.label }}</slot>
    </button>
    <div
      :id="panelId"
      ref="panelRef"
      popover="auto"
      role="dialog"
      :aria-labelledby="`${panelId}-trigger`"
      :data-state="state"
      :class="panel"
      @beforetoggle="onBeforeToggle"
      @toggle="onToggle"
      @keydown="onKeydown"
    >
      <slot />
    </div>
  </div>
</template>
```

```vue
<template>
  <Popover label="Bagikan" side="top">
    <div class="grid gap-3">
      <p class="text-muted">
        Siapa pun yang punya link bisa melihat proyek ini.
      </p>
      <Button size="sm">Salin link</Button>
    </div>
  </Popover>
</template>
```

### Svelte

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

```svelte
<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 panel =
    "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

  const GAP = 4;
  const FOCUSABLE =
    "a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex='-1'])";

  type Side = "top" | "bottom";
  type Align = "start" | "center" | "end";

  type Props = HTMLAttributes<HTMLDivElement> & {
    /** Text of the trigger button. */
    label?: string;
    /** Custom trigger button content, replaces label. */
    trigger?: Snippet;
    side?: Side;
    align?: Align;
    children?: Snippet;
  };

  let {
    label = "Open",
    trigger,
    side = "bottom",
    align = "start",
    id,
    class: className,
    children,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const panelId = $derived(id ?? generatedId);
  let triggerEl = $state<HTMLButtonElement>();
  let panelEl = $state<HTMLDivElement>();
  let open = $state(false);
  const dataState = $derived(open ? "open" : "closed");

  /** Place the panel on the chosen side with the chosen alignment, flip when it does not fit. */
  function place() {
    if (!triggerEl || !panelEl) return;
    const anchor = triggerEl.getBoundingClientRect();
    const { width, height } = panelEl.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const fitsAbove = above >= 0;
    const fitsBelow = below + height <= window.innerHeight;
    const onTop =
      side === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
    const starts: Record<Align, number> = {
      start: anchor.left,
      center: anchor.left + anchor.width / 2 - width / 2,
      end: anchor.right - width,
    };
    const start = starts[align] ?? starts.start;
    const left = Math.max(
      GAP,
      Math.min(start, window.innerWidth - width - GAP),
    );
    panelEl.style.top = `${onTop ? above : below}px`;
    panelEl.style.left = `${left}px`;
  }

  // Re-place while open when 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);
    };
  });

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

  function handleToggle(event: ToggleEvent) {
    if (!panelEl) return;
    if (event.newState === "open") {
      place();
      panelEl.querySelector<HTMLElement>(FOCUSABLE)?.focus();
      return;
    }
    // Focus returns to the trigger, unless the user already moved it outside the panel.
    const active = document.activeElement;
    if (active === document.body || panelEl.contains(active))
      triggerEl?.focus();
  }

  function handleKeydown(event: KeyboardEvent) {
    if (event.key !== "Escape") return;
    event.preventDefault();
    panelEl?.hidePopover();
    triggerEl?.focus();
  }
</script>

<div class={[root, className]} {...rest}>
  <button
    bind:this={triggerEl}
    type="button"
    id={`${panelId}-trigger`}
    popovertarget={panelId}
    aria-haspopup="dialog"
    aria-expanded={open}
    aria-controls={panelId}
    data-state={dataState}
    class={triggerClass}
  >
    {#if trigger}{@render trigger()}{:else}{label}{/if}
  </button>
  <!-- svelte-ignore a11y_interactive_supports_focus -->
  <div
    bind:this={panelEl}
    id={panelId}
    popover="auto"
    role="dialog"
    aria-labelledby={`${panelId}-trigger`}
    data-state={dataState}
    class={panel}
    onbeforetoggle={handleBeforeToggle}
    ontoggle={handleToggle}
    onkeydown={handleKeydown}
  >
    {@render children?.()}
  </div>
</div>
```

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

<Popover label="Bagikan" align="end">
  <div class="grid gap-3">
    <p class="text-muted">Siapa pun yang punya link bisa melihat proyek ini.</p>
    <Button size="sm">Salin link</Button>
  </div>
</Popover>
```

### Astro

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

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

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 panel =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

type Props = HTMLAttributes<"div"> & {
  /** Text of the trigger button. */
  label?: string;
  side?: "top" | "bottom";
  align?: "start" | "center" | "end";
};

const {
  label = "Open",
  side = "bottom",
  align = "start",
  id,
  class: className,
  ...rest
} = Astro.props;
const panelId = id ?? `markas-popover-${crypto.randomUUID().slice(0, 8)}`;
---

<div class:list={[root, className]} {...rest}>
  <button
    type="button"
    id={`${panelId}-trigger`}
    popovertarget={panelId}
    aria-haspopup="dialog"
    aria-expanded="false"
    aria-controls={panelId}
    data-state="closed"
    class={triggerClass}
  >
    {Astro.slots.has("trigger") ? <slot name="trigger" /> : label}
  </button>
  <div
    id={panelId}
    popover="auto"
    role="dialog"
    aria-labelledby={`${panelId}-trigger`}
    data-state="closed"
    data-markas-popover
    data-side={side}
    data-align={align}
    class={panel}
  >
    <slot />
  </div>
</div>

<script>
  // One set of listeners per page serves every popover, including markup added later and
  // pages reached through view transitions.
  const GAP = 4;
  const FOCUSABLE =
    "a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex='-1'])";
  const open = new Set<HTMLElement>();

  const isPopover = (node: EventTarget | null): node is HTMLElement =>
    node instanceof HTMLElement && node.hasAttribute("data-markas-popover");
  const triggerOf = (panel: HTMLElement) =>
    document.getElementById(`${panel.id}-trigger`);

  /** Place the panel on the chosen side with the chosen alignment, flip when it does not fit. */
  function place(panel: HTMLElement) {
    const trigger = triggerOf(panel);
    if (!trigger) return;
    const anchor = trigger.getBoundingClientRect();
    const { width, height } = panel.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const fitsAbove = above >= 0;
    const fitsBelow = below + height <= window.innerHeight;
    const onTop =
      panel.dataset.side === "top"
        ? fitsAbove || !fitsBelow
        : !fitsBelow && fitsAbove;
    const starts: Record<string, number> = {
      start: anchor.left,
      center: anchor.left + anchor.width / 2 - width / 2,
      end: anchor.right - width,
    };
    const start = starts[panel.dataset.align ?? ""] ?? anchor.left;
    const left = Math.max(GAP, Math.min(start, window.innerWidth - width - GAP));
    panel.style.top = `${onTop ? above : below}px`;
    panel.style.left = `${left}px`;
  }

  // beforetoggle and toggle do not bubble, so listen in the capture phase.
  document.addEventListener(
    "beforetoggle",
    (event) => {
      if (!isPopover(event.target)) return;
      const state = (event as ToggleEvent).newState;
      const trigger = triggerOf(event.target);
      event.target.dataset.state = state;
      trigger?.setAttribute("data-state", state);
      trigger?.setAttribute("aria-expanded", String(state === "open"));
    },
    true,
  );

  document.addEventListener(
    "toggle",
    (event) => {
      const panel = event.target;
      if (!isPopover(panel)) return;
      if ((event as ToggleEvent).newState === "open") {
        open.add(panel);
        place(panel);
        panel.querySelector<HTMLElement>(FOCUSABLE)?.focus();
        return;
      }
      open.delete(panel);
      // Focus returns to the trigger, unless the user already moved it outside the panel.
      const active = document.activeElement;
      if (active === document.body || panel.contains(active))
        triggerOf(panel)?.focus();
    },
    true,
  );

  document.addEventListener("keydown", (event) => {
    if (event.key !== "Escape") return;
    const panel = (event.target as Element).closest?.(
      "[data-markas-popover]",
    );
    if (!isPopover(panel)) return;
    event.preventDefault();
    panel.hidePopover();
    triggerOf(panel)?.focus();
  });

  // Re-place open panels when the page scrolls or the window resizes.
  const update = () =>
    open.forEach((panel) =>
      panel.isConnected ? place(panel) : open.delete(panel),
    );
  window.addEventListener("scroll", update, { capture: true, passive: true });
  window.addEventListener("resize", update, { passive: true });
</script>
```

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

<Popover label="Bagikan" align="end">
  <div class="grid gap-3">
    <p class="text-muted">Siapa pun yang punya link bisa melihat proyek ini.</p>
    <Button size="sm">Salin link</Button>
  </div>
</Popover>
```

Satu script kecil yang dibundel menempatkan semua popover di halaman. Tetap jalan setelah view transition.

### Angular

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

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

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 panel =
  "inset-auto m-0 w-72 max-w-[calc(100vw-16px)] rounded-xl border border-line bg-surface p-4 text-sm text-ink shadow-overlay";

const GAP = 4;
const FOCUSABLE =
  "a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex='-1'])";

type Side = "top" | "bottom";
type Align = "start" | "center" | "end";

let nextId = 0;

/**
 * Slots: an element with the `trigger` attribute (an ng-container works) replaces the label
 * inside the trigger button, everything else is the panel content.
 * Host stays out of layout; id and class move to the root element and the panel.
 */
@Component({
  selector: "markas-popover",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.id]": "null" },
  template: `
    <div [class]="rootClasses()">
      <button
        #trigger
        type="button"
        [id]="panelId() + '-trigger'"
        [attr.popovertarget]="panelId()"
        aria-haspopup="dialog"
        [attr.aria-expanded]="open() ? 'true' : 'false'"
        [attr.aria-controls]="panelId()"
        [attr.data-state]="dataState()"
        [class]="triggerClass"
      >
        <ng-content select="[trigger]">{{ label() }}</ng-content>
      </button>
      <div
        #panelEl
        [id]="panelId()"
        popover="auto"
        role="dialog"
        [attr.aria-labelledby]="panelId() + '-trigger'"
        [attr.data-state]="dataState()"
        [class]="panel"
        (beforetoggle)="handleBeforeToggle($event)"
        (toggle)="handleToggle($event)"
        (keydown)="handleKeydown($event)"
      >
        <ng-content />
      </div>
    </div>
  `,
})
export class Popover {
  /** Text of the trigger button. */
  readonly label = input("Open");
  readonly side = input<Side>("bottom");
  readonly align = input<Align>("start");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly triggerClass = triggerClass;
  protected readonly panel = panel;
  protected readonly open = signal(false);
  protected readonly dataState = computed(() =>
    this.open() ? "open" : "closed",
  );
  private readonly generatedId = `markas-popover-${nextId++}`;
  protected readonly panelId = computed(() => this.id() ?? this.generatedId);
  protected readonly rootClasses = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  private readonly triggerRef =
    viewChild.required<ElementRef<HTMLButtonElement>>("trigger");
  private readonly panelRef =
    viewChild.required<ElementRef<HTMLDivElement>>("panelEl");
  private readonly update = () => this.place();
  private readonly scrollOptions = { capture: true, passive: true };

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

  /** Place the panel on the chosen side with the chosen alignment, flip when it does not fit. */
  private place() {
    const target = this.panelRef().nativeElement;
    const anchor = this.triggerRef().nativeElement.getBoundingClientRect();
    const { width, height } = target.getBoundingClientRect();
    const above = anchor.top - GAP - height;
    const below = anchor.bottom + GAP;
    const fitsAbove = above >= 0;
    const fitsBelow = below + height <= window.innerHeight;
    const onTop =
      this.side() === "top" ? fitsAbove || !fitsBelow : !fitsBelow && fitsAbove;
    const starts: Record<Align, number> = {
      start: anchor.left,
      center: anchor.left + anchor.width / 2 - width / 2,
      end: anchor.right - width,
    };
    const start = starts[this.align()] ?? starts.start;
    const left = Math.max(
      GAP,
      Math.min(start, window.innerWidth - width - GAP),
    );
    target.style.top = `${onTop ? above : below}px`;
    target.style.left = `${left}px`;
  }

  private stopFollowing() {
    window.removeEventListener("scroll", this.update, this.scrollOptions);
    window.removeEventListener("resize", this.update);
  }

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

  protected handleToggle(event: Event) {
    this.stopFollowing();
    const target = this.panelRef().nativeElement;
    if ((event as ToggleEvent).newState === "open") {
      this.place();
      // Re-place while open when the page scrolls or the window resizes.
      window.addEventListener("scroll", this.update, this.scrollOptions);
      window.addEventListener("resize", this.update, { passive: true });
      target.querySelector<HTMLElement>(FOCUSABLE)?.focus();
      return;
    }
    // Focus returns to the trigger, unless the user already moved it outside the panel.
    const active = document.activeElement;
    if (active === document.body || target.contains(active))
      this.triggerRef().nativeElement.focus();
  }

  protected handleKeydown(event: KeyboardEvent) {
    if (event.key !== "Escape") return;
    event.preventDefault();
    this.panelRef().nativeElement.hidePopover();
    this.triggerRef().nativeElement.focus();
  }
}
```

```ts
import { Component } from "@angular/core";
import { Button } from "./markas/button.component";
import { Popover } from "./markas/popover.component";

@Component({
  selector: "app-share",
  imports: [Button, Popover],
  template: `
    <markas-popover label="Bagikan" align="end">
      <div class="grid gap-3">
        <p class="text-muted">
          Siapa pun yang punya link bisa melihat proyek ini.
        </p>
        <button markas-button size="sm">Salin link</button>
      </div>
    </markas-popover>
  `,
})
export class Share {}
```

Untuk pemicu ikon, taruh ikon dan teks sr-only di elemen dengan atribut `trigger`, misalnya `<ng-container trigger>`.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `label` | `string` | Open | Teks tombol pemicu. Default "Open", isi misalnya "Bagikan" untuk situs berbahasa Indonesia. |
| `trigger` | `slot / ReactNode / snippet` | - | Isi tombol pemicu kustom, menggantikan label. Tambahkan teks sr-only bila isinya hanya ikon. Angular: elemen dengan atribut trigger (ng-container bisa). |
| `children / slot` | `slot / ReactNode` | - | Isi panel, misalnya form singkat atau detail. |
| `side` | `top \| bottom` | bottom | Sisi pemicu tempat panel muncul. Pindah ke sisi lain bila tidak muat di layar. |
| `align` | `start \| center \| end` | start | Perataan horizontal panel terhadap pemicu. |
| `id` | `string` | auto | Id panel. Tombol pemicu memakai id ini dengan akhiran -trigger. |

## Aksesibilitas

- Tombol pemicu memakai aria-haspopup=dialog, aria-expanded, dan aria-controls ke panel role=dialog yang diberi nama dari pemicu.
- Enter atau Spasi pada pemicu membuka panel dan memindahkan fokus ke elemen fokus pertama di dalamnya.
- Escape menutup panel dan mengembalikan fokus ke pemicu.
- Klik di luar menutup panel (light dismiss Popover API). Fokus kembali ke pemicu kecuali sudah pindah ke elemen lain.

## Catatan

- Panel muncul di bawah pemicu, rata dengan tepi awalnya. Ubah lewat `side` (`top`, `bottom`) dan `align` (`start`, `center`, `end`).
- Pakai slot `trigger` untuk pemicu ikon dan sertakan teks sr-only, misalnya `<span class="sr-only">Pengaturan notifikasi</span>`.
- Teks pemicu default dalam bahasa Inggris ("Open"). Isi `label` dalam bahasa situs Anda, misalnya "Buka" atau "Bagikan".
