# Dialog

> Native modal with a title, description, body, and footer actions.

- Kind: ui · Category: Overlays · Interactivity: script
- Install: `npx shadcn@latest add @haze/dialog`
- File: `src/components/haze/ui/dialog.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/utils
- Docs page: https://hazeui.com/ui/dialog

## Use when
- A short task that needs the user's full attention, such as inviting a teammate
- Collecting a short decision or additional context before continuing
- A form with one to four fields that does not deserve its own page

## Avoid when
- Long or multi-step flows need their own page.
- Status messages that need no decision; use alert
- A destructive confirmation needs an explicit choice. Use alert-dialog.

## Alternatives
- [popover](https://hazeui.com/ui/popover.md)
- [alert](https://hazeui.com/ui/alert.md)
- [alert-dialog](https://hazeui.com/ui/alert-dialog.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique on the page. Buttons target it with commandfor="<id>". |
| title | `string` |  | yes | Heading; also the dialog's accessible name. |
| description | `string` |  | no | One or two sentences under the title. |
| trigger | `boolean` | true | no | Set to false when the opening button lives elsewhere. |
| triggerLabel | `string` | "Open dialog" | no | Trigger text when the trigger slot is not used. |
| triggerVariant | `"primary" \| "secondary" \| "outline" \| "ghost"` | "outline" | no | Trigger button style. |
| size | `"sm" \| "md" \| "lg"` | "md" | no | Maximum width: 24, 28 or 42 rem. |
| closeLabel | `string` | "Close" | no | Accessible name of the close button; translate it. |
| role | `"dialog" \| "alertdialog"` | "dialog" | no | Alert dialogs omit the close icon and require a closing action or Escape. |
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | 2 | no | Heading level for the dialog title. |
| class | `string` |  | no | Extra classes on the dialog. |
| default slot | `slot` |  | no | Body content. |
| footer slot | `slot` |  | no | Action buttons. Close with command="close" commandfor="<id>" or a form with method="dialog". |
| trigger slot | `slot` |  | no | Custom trigger content. |

## Accessibility
- showModal() semantics: the page behind is inert, focus moves into the dialog and returns to the trigger on close.
- Opening uses the command and commandfor attributes (Chrome 135, Firefox 144, Safari 26.2). The small script covers older browsers; without both, the trigger does nothing.
- The dialog fades and scales in over 200 ms and out again, and its backdrop fades with it; reduced-motion users get no animation.
- The title is linked with aria-labelledby and the description with aria-describedby.
- Put the least destructive action first in the DOM so it receives initial focus.
- Key Enter / Space: Open the dialog from the trigger
- Key Tab / Shift+Tab: Move between controls; focus stays inside the dialog
- Key Escape: Close the dialog and return focus to the trigger

## Agent prompts

### Install and use

Install the Haze UI component "Dialog" with `npx shadcn@latest add @haze/dialog`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import Dialog from "@/components/haze/ui/dialog.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/dialog.md

### Customize with real content

Adapt the Haze dialog ui for our product. Replace the demo values of these props with our real content: id, title, description, trigger, triggerLabel, triggerVariant, size, closeLabel, role, headingLevel, class, default slot, footer slot, trigger slot. Keep the layout, the heading level rules and these accessibility details: showModal() semantics: the page behind is inert, focus moves into the dialog and returns to the trigger on close. Opening uses the command and commandfor attributes (Chrome 135, Firefox 144, Safari 26.2). The small script covers older browsers; without both, the trigger does nothing. The dialog fades and scales in over 200 ms and out again, and its backdrop fades with it; reduced-motion users get no animation. The title is linked with aria-labelledby and the description with aria-describedby. Put the least destructive action first in the DOM so it receives initial focus. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using dialog, check it fits: use it when a short task that needs the user's full attention, such as inviting a teammate; collecting a short decision or additional context before continuing; a form with one to four fields that does not deserve its own page. Avoid it when long or multi-step flows need their own page.; status messages that need no decision; use alert; a destructive confirmation needs an explicit choice. use alert-dialog.. Alternatives: @haze/popover, @haze/alert, @haze/alert-dialog.

## Example requests that should lead here
- Add an invite dialog with an email field and Cancel and Send buttons
- Ask for confirmation in a dialog before deleting a project

## Source

```astro
---
import { X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";

interface Props {
  /** Unique on the page. Any button with `command="show-modal" commandfor="<id>"` opens this dialog. */
  id: string;
  title: string;
  description?: string;
  /** Set to false when the opening button lives somewhere else on the page. */
  trigger?: boolean;
  /** Visible trigger text. The "trigger" slot replaces it. */
  triggerLabel?: string;
  triggerVariant?: "primary" | "secondary" | "outline" | "ghost";
  size?: "sm" | "md" | "lg";
  closeLabel?: string;
  role?: "dialog" | "alertdialog";
  headingLevel?: 2 | 3 | 4 | 5 | 6;
  class?: string;
}

const {
  id,
  title,
  description,
  trigger = true,
  triggerLabel = "Open dialog",
  triggerVariant = "outline",
  size = "md",
  closeLabel = "Close",
  role = "dialog",
  headingLevel = 2,
  class: className,
} = Astro.props;

const sizes = { sm: "max-w-sm", md: "max-w-md", lg: "max-w-2xl" };
const confirmation = role === "alertdialog";
const Heading = `h${headingLevel}` as const;
---

{
  trigger && (
    <Button variant={triggerVariant} command="show-modal" commandfor={id} aria-haspopup="dialog">
      <slot name="trigger">{triggerLabel}</slot>
    </Button>
  )
}
<dialog
  id={id}
  role={confirmation ? "alertdialog" : undefined}
  data-haze-alert-dialog={confirmation ? "" : undefined}
  aria-labelledby={`${id}-title`}
  aria-describedby={description ? `${id}-description` : undefined}
  closedby={confirmation ? "closerequest" : "any"}
  class={cn(
    "m-auto max-h-[calc(100dvh-2rem)] w-[calc(100vw-2rem)] overflow-y-auto rounded-2xl border border-border bg-popover p-0 text-popover-foreground shadow-float",
    "translate-y-2 scale-[0.96] opacity-0 transition-[opacity,scale,translate,overlay,display] transition-discrete duration-200 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 starting:open:translate-y-2 starting:open:scale-[0.96] starting:open:opacity-0",
    "backdrop:bg-background/60 backdrop:opacity-0 backdrop:transition-[opacity,overlay,display] backdrop:transition-discrete backdrop:duration-200 open:backdrop:opacity-100 starting:open:backdrop:opacity-0",
    sizes[size],
    className,
  )}
>
  <div class="relative grid">
    <header class={cn("grid gap-2 border-b border-border p-5", !confirmation && "pr-14")}>
      <Heading id={`${id}-title`} class="text-[1.0625rem] leading-[1.4] font-medium tracking-[-0.01em] text-foreground">{title}</Heading>
      {description && <p id={`${id}-description`} class="text-[0.8125rem] leading-[1.4] text-muted-foreground">{description}</p>}
    </header>
    <div class="p-5 text-[0.8125rem] leading-[1.4] empty:hidden">
      <slot />
    </div>
    {
      Astro.slots.has("footer") && (
        <footer class="flex flex-col-reverse gap-2 border-t border-border px-5 py-4 sm:flex-row sm:justify-end [div:empty+&]:border-t-0">
          <slot name="footer" />
        </footer>
      )
    }
    {!confirmation && <form method="dialog" class="absolute right-5 top-5">
      <button
        type="submit"
        aria-label={closeLabel}
        class="inline-flex size-6 cursor-pointer items-center justify-center rounded-lg border border-frame bg-muted/50 text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-muted hover:text-foreground active:scale-[0.96] active:duration-100 motion-reduce:transition-none motion-reduce:active:scale-100 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
      >
        <X class="size-3.5" aria-hidden="true" />
      </button>
    </form>}
  </div>
</dialog>

<script>
  // Fallback only. Current browsers open and close the dialog from the `command` / `commandfor`
  // attributes and handle `closedby="any"` themselves; this covers the ones that do not yet.
  const root = document.documentElement;
  const initConfirmations = () => {
    for (const dialog of document.querySelectorAll<HTMLDialogElement>("[data-haze-alert-dialog]:not([data-enhanced])")) {
      dialog.addEventListener("cancel", () => { dialog.returnValue = "cancel"; });
      dialog.setAttribute("data-enhanced", "");
    }
  };
  initConfirmations();
  if (!root.hasAttribute("data-haze-invokers")) {
    root.setAttribute("data-haze-invokers", "");
    document.addEventListener("astro:page-load", initConfirmations);

    if (!("command" in HTMLButtonElement.prototype)) {
      document.addEventListener("click", (event) => {
        const button = (event.target as Element | null)?.closest?.("button[commandfor]");
        const target = button && document.getElementById(button.getAttribute("commandfor") ?? "");
        if (!(target instanceof HTMLDialogElement)) return;
        const command = button!.getAttribute("command");
        if (command === "show-modal" && !target.open) target.showModal();
        if (command === "close" && target.open) target.close();
      });
    }

    if (!("closedBy" in HTMLDialogElement.prototype)) {
      // A click on the backdrop lands on the <dialog> element itself, because its content fills it.
      document.addEventListener("click", (event) => {
        const dialog = event.target;
        if (dialog instanceof HTMLDialogElement && dialog.open && dialog.getAttribute("closedby") === "any") dialog.close();
      });
    }
  }
</script>
```
