# Alert Dialog

Konfirmasi modal berbasis elemen dialog native. Wajib memilih batal atau aksi, tidak tertutup saat backdrop diklik.

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

## Kapan dipakai

Konfirmasi aksi yang merusak atau tidak bisa dibatalkan, misalnya menghapus data, keluar dari semua perangkat, atau membuang perubahan yang belum disimpan.

- Tulis judul sebagai pertanyaan dan sebut aksinya di actionLabel, misalnya Hapus akun
- Pakai variant danger hanya bila aksi menghapus data atau tidak bisa dibatalkan
- Isi cukup satu atau dua kalimat, gunakan Modal untuk form atau konten panjang

## Kode

### Blade

Simpan di `resources/views/components/markas/alert-dialog.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'title',
    'variant' => 'default',
    'cancelLabel' => 'Cancel',
    'actionLabel' => 'Continue',
])

@php
    $dialog = 'm-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40';
    $panel = 'grid gap-4 p-6';
    $titleClass = 'text-lg font-semibold text-ink';
    $body = 'text-sm text-muted';
    $footerClass = 'flex flex-wrap justify-end gap-2';
    $button = 'inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
    $cancelClass = 'border border-line bg-surface text-ink hover:bg-subtle';
    $actionTones = [
        'default' => 'bg-primary text-on-primary hover:bg-primary-strong',
        'danger' => 'bg-danger text-on-primary hover:bg-danger/90',
    ];

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

{{-- wire:model and x-model bind the open state (x-modelable), so a boolean property can open and close the dialog. --}}
<div
    class="contents"
    x-data="{
        open: false,
        init() {
            this.$watch('open', (value) => {
                if (value && ! this.$refs.dialog.open) this.show();
                if (! value && this.$refs.dialog.open) this.$refs.dialog.close();
            });
        },
        show() {
            this.$refs.dialog.returnValue = '';
            this.$refs.dialog.showModal();
            this.open = true;
            this.$refs.cancel.focus();
        },
        {{-- Selain tombol aksi (tombol batal, Escape, close() dari kode) dihitung batal. --}}
        onClose() {
            this.open = false;
            const isAction = this.$refs.dialog.returnValue === 'action';
            if (! isAction) this.$refs.dialog.returnValue = 'cancel';
            this.$dispatch(isAction ? 'markas-action' : 'markas-cancel');
        },
    }"
    x-modelable="open"
    {{ $attributes->whereStartsWith(['wire:model', 'x-model']) }}
>
    @isset($trigger)
        <div class="contents" @click="show()">{{ $trigger }}</div>
    @endisset
    <dialog
        wire:ignore.self
        x-ref="dialog"
        role="alertdialog"
        :data-state="open ? 'open' : 'closed'"
        @close="onClose()"
        {{ $attributes->whereDoesntStartWith(['wire:model', 'x-model'])->merge(['id' => $id, 'aria-labelledby' => $id.'-title', 'aria-describedby' => $id.'-description', 'data-state' => 'closed'])->class([$dialog]) }}
    >
        <div class="{{ $panel }}">
            <h2 id="{{ $id }}-title" class="{{ $titleClass }}">{{ $title }}</h2>
            <div id="{{ $id }}-description" class="{{ $body }}">{{ $slot }}</div>
            <form method="dialog" class="{{ $footerClass }}">
                <button x-ref="cancel" type="submit" value="cancel" class="{{ $button }} {{ $cancelClass }}">{{ $cancelLabel }}</button>
                <button type="submit" value="action" class="{{ $button }} {{ $actionTones[$variant] ?? $actionTones['default'] }}">{{ $actionLabel }}</button>
            </form>
        </div>
    </dialog>
</div>
```

```blade
<x-markas.alert-dialog title="Hapus akun Anda?" variant="danger" cancel-label="Batal" action-label="Hapus akun" x-on:markas-action="hapusAkun()">
    <x-slot:trigger>
        <x-markas.button variant="danger">Hapus akun</x-markas.button>
    </x-slot:trigger>

    Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
</x-markas.alert-dialog>
```

Butuh Alpine.js. Livewire 3 dan 4 sudah membawa Alpine, jadi tidak perlu dipasang lagi.

### Livewire

```blade
<x-markas.alert-dialog title="Delete project?" wire:model="confirming" wire:markas-action="delete">
    This cannot be undone.
</x-markas.alert-dialog>
```

`wire:model` terhubung ke status terbuka. `wire:markas-action` menjalankan action Livewire saat tombol aksi ditekan; `wire:markas-cancel` untuk penutupan lainnya.

### React

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

```tsx
"use client";

import {
  useId,
  useRef,
  useState,
  type ComponentProps,
  type ReactNode,
  type SyntheticEvent,
} from "react";

const dialogClass =
  "m-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "grid gap-4 p-6";
const titleClass = "text-lg font-semibold text-ink";
const body = "text-sm text-muted";
const footerClass = "flex flex-wrap justify-end gap-2";
const button =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const cancelClass = "border border-line bg-surface text-ink hover:bg-subtle";
const actionTones = {
  default: "bg-primary text-on-primary hover:bg-primary-strong",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const ACTION = "action";
const CANCEL = "cancel";

export type AlertDialogProps = Omit<
  ComponentProps<"dialog">,
  "title" | "ref" | "open" | "onCancel"
> & {
  title: ReactNode;
  trigger?: ReactNode;
  /** Warna tombol aksi. Pakai danger untuk aksi yang menghapus atau tidak bisa dibatalkan. */
  variant?: keyof typeof actionTones;
  cancelLabel?: string;
  actionLabel?: string;
  /** Dipanggil saat tombol aksi dipilih. */
  onAction?: () => void;
  /** Dipanggil saat dialog ditutup lewat tombol batal atau Escape. */
  onCancel?: () => void;
};

export function AlertDialog({
  title,
  trigger,
  variant = "default",
  cancelLabel = "Cancel",
  actionLabel = "Continue",
  onAction,
  onCancel,
  id,
  className,
  children,
  onClose,
  ...props
}: AlertDialogProps) {
  const generatedId = useId();
  const dialogId = id ?? generatedId;
  const dialogRef = useRef<HTMLDialogElement>(null);
  const cancelRef = useRef<HTMLButtonElement>(null);
  const [open, setOpen] = useState(false);

  const show = () => {
    const dialog = dialogRef.current;
    if (!dialog) return;
    dialog.returnValue = "";
    dialog.showModal();
    setOpen(true);
    cancelRef.current?.focus();
  };
  // Selain tombol aksi (tombol batal, Escape, close() dari kode) dihitung batal.
  const handleClose = (event: SyntheticEvent<HTMLDialogElement>) => {
    const dialog = event.currentTarget;
    setOpen(false);
    if (dialog.returnValue === ACTION) onAction?.();
    else {
      dialog.returnValue = CANCEL;
      onCancel?.();
    }
    onClose?.(event);
  };

  return (
    <div className="contents">
      {trigger && (
        <div className="contents" onClick={show}>
          {trigger}
        </div>
      )}
      <dialog
        ref={dialogRef}
        id={dialogId}
        role="alertdialog"
        aria-labelledby={`${dialogId}-title`}
        aria-describedby={`${dialogId}-description`}
        data-state={open ? "open" : "closed"}
        className={cx(dialogClass, className)}
        onClose={handleClose}
        {...props}
      >
        <div className={panel}>
          <h2 id={`${dialogId}-title`} className={titleClass}>
            {title}
          </h2>
          <div id={`${dialogId}-description`} className={body}>
            {children}
          </div>
          <form method="dialog" className={footerClass}>
            <button
              ref={cancelRef}
              type="submit"
              value={CANCEL}
              className={cx(button, cancelClass)}
            >
              {cancelLabel}
            </button>
            <button
              type="submit"
              value={ACTION}
              className={cx(
                button,
                actionTones[variant] ?? actionTones.default,
              )}
            >
              {actionLabel}
            </button>
          </form>
        </div>
      </dialog>
    </div>
  );
}
```

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

<AlertDialog
  title="Hapus akun Anda?"
  variant="danger"
  cancelLabel="Batal"
  actionLabel="Hapus akun"
  trigger={<Button variant="danger">Hapus akun</Button>}
  onAction={() => hapusAkun()}
  onCancel={() => console.log("batal")}
>
  Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
</AlertDialog>;
```

### Vue

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

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

defineOptions({ inheritAttrs: false });

type Variant = "default" | "danger";

const props = withDefaults(
  defineProps<{
    title: string;
    variant?: Variant;
    id?: string;
    cancelLabel?: string;
    actionLabel?: string;
  }>(),
  {
    variant: "default",
    id: undefined,
    cancelLabel: "Cancel",
    actionLabel: "Continue",
  },
);
const emit = defineEmits<{ action: []; cancel: [] }>();

const dialogClass =
  "m-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "grid gap-4 p-6";
const titleClass = "text-lg font-semibold text-ink";
const body = "text-sm text-muted";
const footerClass = "flex flex-wrap justify-end gap-2";
const button =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const cancelClass = "border border-line bg-surface text-ink hover:bg-subtle";
const actionTones: Record<Variant, string> = {
  default: "bg-primary text-on-primary hover:bg-primary-strong",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};

const ACTION = "action";
const CANCEL = "cancel";

const generatedId = useId();
const dialogId = computed(() => props.id ?? generatedId);
const dialog = useTemplateRef<HTMLDialogElement>("dialog");
const cancelButton = useTemplateRef<HTMLButtonElement>("cancelButton");
const open = ref(false);
const actionClass = computed(
  () => actionTones[props.variant] ?? actionTones.default,
);

function show() {
  if (!dialog.value) return;
  dialog.value.returnValue = "";
  dialog.value.showModal();
  open.value = true;
  cancelButton.value?.focus();
}

// Selain tombol aksi (tombol batal, Escape, close() dari kode) dihitung batal.
function onClose() {
  open.value = false;
  if (!dialog.value) return;
  if (dialog.value.returnValue === ACTION) return emit("action");
  dialog.value.returnValue = CANCEL;
  emit("cancel");
}
</script>

<template>
  <div class="contents">
    <div v-if="$slots.trigger" class="contents" @click="show">
      <slot name="trigger" />
    </div>
    <dialog
      :id="dialogId"
      ref="dialog"
      role="alertdialog"
      :aria-labelledby="`${dialogId}-title`"
      :aria-describedby="`${dialogId}-description`"
      :data-state="open ? 'open' : 'closed'"
      :class="dialogClass"
      v-bind="$attrs"
      @close="onClose"
    >
      <div :class="panel">
        <h2 :id="`${dialogId}-title`" :class="titleClass">
          {{ props.title }}
        </h2>
        <div :id="`${dialogId}-description`" :class="body"><slot /></div>
        <form method="dialog" :class="footerClass">
          <button
            ref="cancelButton"
            type="submit"
            :value="CANCEL"
            :class="[button, cancelClass]"
          >
            {{ props.cancelLabel }}
          </button>
          <button type="submit" :value="ACTION" :class="[button, actionClass]">
            {{ props.actionLabel }}
          </button>
        </form>
      </div>
    </dialog>
  </div>
</template>
```

```vue
<template>
  <AlertDialog
    title="Hapus akun Anda?"
    variant="danger"
    cancel-label="Batal"
    action-label="Hapus akun"
    @action="hapusAkun"
  >
    <template #trigger>
      <Button variant="danger">Hapus akun</Button>
    </template>

    Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
  </AlertDialog>
</template>
```

### Svelte

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

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

  const dialogClass =
    "m-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
  const panel = "grid gap-4 p-6";
  const titleClass = "text-lg font-semibold text-ink";
  const body = "text-sm text-muted";
  const footerClass = "flex flex-wrap justify-end gap-2";
  const button =
    "inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
  const cancelClass = "border border-line bg-surface text-ink hover:bg-subtle";
  const actionTones = {
    default: "bg-primary text-on-primary hover:bg-primary-strong",
    danger: "bg-danger text-on-primary hover:bg-danger/90",
  };

  const ACTION = "action";
  const CANCEL = "cancel";

  type Props = Omit<HTMLDialogAttributes, "title" | "open" | "oncancel"> & {
    title: string;
    /** Color of the action button. Use danger for destructive or irreversible actions. */
    variant?: keyof typeof actionTones;
    cancelLabel?: string;
    actionLabel?: string;
    /** Called when the action button is chosen. */
    onaction?: () => void;
    /** Called when the dialog closes through the cancel button or Escape. */
    oncancel?: () => void;
    trigger?: Snippet;
    children?: Snippet;
  };

  let {
    title,
    variant = "default",
    cancelLabel = "Cancel",
    actionLabel = "Continue",
    onaction,
    oncancel,
    id,
    class: className,
    trigger,
    children,
    onclose,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const dialogId = $derived(id ?? generatedId);
  let dialog = $state<HTMLDialogElement>();
  let cancelButton = $state<HTMLButtonElement>();
  let open = $state(false);

  function show() {
    if (!dialog) return;
    dialog.returnValue = "";
    dialog.showModal();
    open = true;
    cancelButton?.focus();
  }

  // Anything but the action button (cancel button, Escape, close() from code) counts as cancel.
  function handleClose(event: Event & { currentTarget: HTMLDialogElement }) {
    const target = event.currentTarget;
    open = false;
    if (target.returnValue === ACTION) onaction?.();
    else {
      target.returnValue = CANCEL;
      oncancel?.();
    }
    onclose?.(event);
  }
</script>

<div class="contents">
  {#if trigger}
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="contents" onclick={show}>{@render trigger()}</div>
  {/if}
  <dialog
    bind:this={dialog}
    id={dialogId}
    role="alertdialog"
    aria-labelledby={`${dialogId}-title`}
    aria-describedby={`${dialogId}-description`}
    data-state={open ? "open" : "closed"}
    class={[dialogClass, className]}
    onclose={handleClose}
    {...rest}
  >
    <div class={panel}>
      <h2 id={`${dialogId}-title`} class={titleClass}>{title}</h2>
      <div id={`${dialogId}-description`} class={body}>
        {@render children?.()}
      </div>
      <form method="dialog" class={footerClass}>
        <button
          bind:this={cancelButton}
          type="submit"
          value={CANCEL}
          class={[button, cancelClass]}
        >
          {cancelLabel}
        </button>
        <button
          type="submit"
          value={ACTION}
          class={[button, actionTones[variant] ?? actionTones.default]}
        >
          {actionLabel}
        </button>
      </form>
    </div>
  </dialog>
</div>
```

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

<AlertDialog
  title="Hapus akun Anda?"
  variant="danger"
  cancelLabel="Batal"
  actionLabel="Hapus akun"
  onaction={hapusAkun}
>
  {#snippet trigger()}
    <Button variant="danger">Hapus akun</Button>
  {/snippet}

  Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
</AlertDialog>
```

### Astro

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

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

const dialogClass =
  "m-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "grid gap-4 p-6";
const titleClass = "text-lg font-semibold text-ink";
const body = "text-sm text-muted";
const footerClass = "flex flex-wrap justify-end gap-2";
const button =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const cancelClass = "border border-line bg-surface text-ink hover:bg-subtle";
const actionTones = {
  default: "bg-primary text-on-primary hover:bg-primary-strong",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};

type Props = Omit<HTMLAttributes<"dialog">, "title" | "open"> & {
  title: string;
  /** Color of the action button. Use danger for destructive or irreversible actions. */
  variant?: keyof typeof actionTones;
  cancelLabel?: string;
  actionLabel?: string;
};

const {
  title,
  variant = "default",
  cancelLabel = "Cancel",
  actionLabel = "Continue",
  id,
  class: className,
  ...rest
} = Astro.props;
const dialogId = id ?? `markas-alert-dialog-${crypto.randomUUID().slice(0, 8)}`;
---

<div class="contents">
  {
    Astro.slots.has("trigger") && (
      <div class="contents" data-markas-alert-dialog-trigger={dialogId}>
        <slot name="trigger" />
      </div>
    )
  }
  <dialog
    id={dialogId}
    role="alertdialog"
    aria-labelledby={`${dialogId}-title`}
    aria-describedby={`${dialogId}-description`}
    data-state="closed"
    data-markas-alert-dialog
    class:list={[dialogClass, className]}
    {...rest}
  >
    <div class={panel}>
      <h2 id={`${dialogId}-title`} class={titleClass}>{title}</h2>
      <div id={`${dialogId}-description`} class={body}><slot /></div>
      <form method="dialog" class={footerClass}>
        <button
          type="submit"
          value="cancel"
          data-markas-alert-dialog-cancel
          class:list={[button, cancelClass]}
        >
          {cancelLabel}
        </button>
        <button
          type="submit"
          value="action"
          class:list={[button, actionTones[variant] ?? actionTones.default]}
        >
          {actionLabel}
        </button>
      </form>
    </div>
  </dialog>
</div>

<script>
  // One listener per page serves every alert dialog, including markup added later and pages
  // reached through view transitions. A backdrop click does nothing on purpose.
  const isAlertDialog = (node: EventTarget | null): node is HTMLDialogElement =>
    node instanceof HTMLDialogElement &&
    node.hasAttribute("data-markas-alert-dialog");

  document.addEventListener("click", (event) => {
    const trigger = (event.target as Element).closest<HTMLElement>(
      "[data-markas-alert-dialog-trigger]",
    );
    if (!trigger) return;
    const dialog = document.getElementById(
      trigger.dataset.markasAlertDialogTrigger ?? "",
    );
    if (!isAlertDialog(dialog)) return;
    dialog.returnValue = "";
    dialog.showModal();
    dialog.dataset.state = "open";
    dialog
      .querySelector<HTMLButtonElement>("[data-markas-alert-dialog-cancel]")
      ?.focus();
  });

  // Anything but the action button (cancel button, Escape, close() from code) counts as cancel.
  // The close event does not bubble, so listen in the capture phase.
  document.addEventListener(
    "close",
    (event) => {
      const dialog = event.target;
      if (!isAlertDialog(dialog)) return;
      dialog.dataset.state = "closed";
      const isAction = dialog.returnValue === "action";
      if (!isAction) dialog.returnValue = "cancel";
      dialog.dispatchEvent(
        new CustomEvent(isAction ? "markas-action" : "markas-cancel", {
          bubbles: true,
        }),
      );
    },
    true,
  );
</script>
```

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

<AlertDialog
  title="Hapus akun Anda?"
  variant="danger"
  cancelLabel="Batal"
  actionLabel="Hapus akun"
>
  <Button slot="trigger" variant="danger">Hapus akun</Button>

  Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
</AlertDialog>
```

Satu script kecil yang dibundel Astro membuka semua alert dialog di halaman dan memancarkan event `markas-action` atau `markas-cancel` (bubbling) dari dialog saat tertutup.

### Angular

Simpan di `src/app/markas/alert-dialog.component.ts`. Tanpa dependensi tambahan.

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

const dialogClass =
  "m-auto w-full max-w-md rounded-xl border border-line bg-surface p-0 text-ink shadow-overlay backdrop:bg-ink/40";
const panel = "grid gap-4 p-6";
const titleClass = "text-lg font-semibold text-ink";
const body = "text-sm text-muted";
const footerClass = "flex flex-wrap justify-end gap-2";
const button =
  "inline-flex h-10 items-center justify-center gap-2 rounded-lg px-4 text-sm font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const cancelClass = "border border-line bg-surface text-ink hover:bg-subtle";
const actionTones = {
  default: "bg-primary text-on-primary hover:bg-primary-strong",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};

const ACTION = "action";
const CANCEL = "cancel";

export type AlertDialogVariant = keyof typeof actionTones;

let nextId = 0;

/**
 * Slots: an element with the `trigger` attribute opens the dialog, everything else is the
 * explanation. Host stays out of layout; id, title, and class move to the dialog.
 */
@Component({
  selector: "markas-alert-dialog",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.id]": "null", "[attr.title]": "null" },
  template: `
    <div class="contents" (click)="show()">
      <ng-content select="[trigger]" />
    </div>
    <dialog
      #dialog
      [id]="dialogId()"
      role="alertdialog"
      [attr.aria-labelledby]="dialogId() + '-title'"
      [attr.aria-describedby]="dialogId() + '-description'"
      [attr.data-state]="open() ? 'open' : 'closed'"
      [class]="dialogClasses()"
      (close)="handleClose()"
    >
      <div [class]="panel">
        <h2 [id]="dialogId() + '-title'" [class]="titleClass">
          {{ title() }}
        </h2>
        <div [id]="dialogId() + '-description'" [class]="body">
          <ng-content />
        </div>
        <form method="dialog" [class]="footerClass">
          <button
            #cancelButton
            type="submit"
            [value]="CANCEL"
            [class]="cancelClasses"
          >
            {{ cancelLabel() }}
          </button>
          <button type="submit" [value]="ACTION" [class]="actionClasses()">
            {{ actionLabel() }}
          </button>
        </form>
      </div>
    </dialog>
  `,
})
export class AlertDialog {
  readonly title = input.required<string>();
  /** Color of the action button. Use danger for destructive or irreversible actions. */
  readonly variant = input<AlertDialogVariant>("default");
  readonly cancelLabel = input("Cancel");
  readonly actionLabel = input("Continue");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });
  /** Emits when the action button is chosen. */
  readonly action = output<void>();
  /** Emits when the dialog closes through the cancel button or Escape. */
  readonly cancelled = output<void>();

  protected readonly ACTION = ACTION;
  protected readonly CANCEL = CANCEL;
  protected readonly panel = panel;
  protected readonly titleClass = titleClass;
  protected readonly body = body;
  protected readonly footerClass = footerClass;
  protected readonly cancelClasses = `${button} ${cancelClass}`;
  protected readonly open = signal(false);
  private readonly generatedId = `markas-alert-dialog-${nextId++}`;
  protected readonly dialogId = computed(() => this.id() ?? this.generatedId);
  protected readonly dialogClasses = computed(() =>
    [dialogClass, this.userClass()].filter(Boolean).join(" "),
  );
  protected readonly actionClasses = computed(
    () => `${button} ${actionTones[this.variant()] ?? actionTones.default}`,
  );
  private readonly dialog =
    viewChild.required<ElementRef<HTMLDialogElement>>("dialog");
  private readonly cancelButton =
    viewChild.required<ElementRef<HTMLButtonElement>>("cancelButton");

  /** Opens the dialog. Also callable from a template reference: dialog.show(). */
  show() {
    const dialog = this.dialog().nativeElement;
    dialog.returnValue = "";
    dialog.showModal();
    this.open.set(true);
    this.cancelButton().nativeElement.focus();
  }

  // Anything but the action button (cancel button, Escape, close() from code) counts as cancel.
  protected handleClose() {
    const dialog = this.dialog().nativeElement;
    this.open.set(false);
    if (dialog.returnValue === ACTION) return this.action.emit();
    dialog.returnValue = CANCEL;
    this.cancelled.emit();
  }
}
```

```ts
import { Component } from "@angular/core";
import { AlertDialog } from "./markas/alert-dialog.component";
import { Button } from "./markas/button.component";

@Component({
  selector: "app-hapus-akun",
  imports: [AlertDialog, Button],
  template: `
    <markas-alert-dialog
      title="Hapus akun Anda?"
      variant="danger"
      cancelLabel="Batal"
      actionLabel="Hapus akun"
      (action)="hapusAkun()"
    >
      <button markas-button trigger variant="danger">Hapus akun</button>

      Semua proyek dan invoice akan dihapus. Aksi ini tidak bisa dibatalkan.
    </markas-alert-dialog>
  `,
})
export class HapusAkun {
  hapusAkun() {}
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `title` | `string` | - | Judul dialog, dipakai sebagai aria-labelledby. |
| `children / slot` | `slot / ReactNode / snippet` | - | Penjelasan singkat akibat aksi, dipakai sebagai aria-describedby. |
| `trigger` | `slot / ReactNode / snippet` | - | Elemen yang membuka dialog saat diklik. Angular: elemen dengan atribut trigger. |
| `variant` | `default \| danger` | default | Warna tombol aksi. Pakai danger untuk aksi yang merusak atau tidak bisa dibatalkan. |
| `cancelLabel` | `string` | Cancel | Teks tombol batal. Isi "Batal" untuk situs berbahasa Indonesia. |
| `actionLabel` | `string` | Continue | Teks tombol aksi. Isi "Lanjutkan" atau nama aksinya untuk situs berbahasa Indonesia. |
| `onAction / @action / markas-action` | `() => void` | - | Dipanggil saat tombol aksi dipilih. Svelte: onaction. Blade dan Astro memancarkan event markas-action. |
| `onCancel / @cancel / markas-cancel` | `() => void` | - | Dipanggil saat dialog ditutup lewat tombol batal atau Escape. Svelte: oncancel. Blade dan Astro memancarkan event markas-cancel. |
| `id` | `string` | auto | Id dialog. Bisa dipakai untuk membuka dialog dari luar lewat showModal(). |
| `action` | `output<void>` | - | Khusus Angular. Dipancarkan saat tombol aksi dipilih. |
| `cancelled` | `output<void>` | - | Khusus Angular. Dipancarkan saat dialog ditutup lewat tombol batal atau Escape. |

## Aksesibilitas

- Memakai dialog dengan role=alertdialog dan showModal(), jadi fokus terkunci di dalam dan halaman di belakangnya inert.
- Judul terhubung lewat aria-labelledby dan penjelasan lewat aria-describedby.
- Fokus awal ada di tombol batal, jadi Enter yang tidak sengaja tidak menjalankan aksi.
- Escape menutup dialog dan dihitung sebagai batal. Klik backdrop tidak melakukan apa pun.

## Catatan

- Berbeda dengan Modal, klik backdrop tidak menutup dialog. User wajib memilih batal atau aksi; Escape dihitung sebagai batal.
- Fokus awal ada di tombol batal.
- `dialog.returnValue` berisi `action` atau `cancel` saat event `close`.
- Teks tombol default dalam bahasa Inggris ("Cancel" dan "Continue"). Isi `cancelLabel` dan `actionLabel` (Blade: `cancel-label`, `action-label`) untuk situs berbahasa Indonesia.
