<!-- generated by scripts/gen-docs.mjs from docs/system/dialog.md. Edit the source and rerun. -->
# Dialog

## Description
A window over the page for one short task, such as a form.

`import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogBody, DialogFooter, DialogError, DialogClose } from "@/components/cobalt/ui/dialog"`, source `registry/cobalt/ui/dialog.tsx`, status `ready-with-gaps`.
Foundation: `shadcn dialog (base-luma, base)`. Traps checked: `trap/overlay-title`, `trap/overlay-focus-return`, `trap/overlay-conditional-render`, `trap/exit-eats-input`, `trap/escape-nested`, `trap/overlay-destructive`, `trap/overlay-pending-dismiss`, `trap/overlay-no-max-height`, `trap/open-trigger-unfocused`, `trap/scroll-chain`, `trap/viewport-height`, `trap/safe-area` (n/a: the popup floats inside the page gutters, never at an edge), `trap/touch-autofocus`, `trap/motion-origin`, `trap/motion-exit-slower`, `trap/reduced-motion-ignored`, `trap/motion-frequent` (n/a: the component surfaces are tier mid in `.design-system/review/surfaces.tsv`, and a dialog opens once per task).

### Foundation
| Given by the foundation | Added by the team |
|---|---|
| Base UI `Dialog`: a portalled `role="dialog"` popup named by its `Title` and described by its `Description` through `aria-labelledby` and `aria-describedby`, a trigger with `aria-haspopup="dialog"` and `aria-expanded`, focus moved into the popup on open and back to the trigger on close, Escape and an outside press to close, `data-starting-style` and `data-ending-style` for the transition, `initialFocus` and `finalFocus` on the popup | The `status` prop on `DialogContent`: while `"pending"` the root cancels every close that is not imperative, the popup carries `aria-busy`, and every `DialogClose` carries `aria-disabled` while keeping focus (`registry/cobalt/ui/dialog.tsx:41`, `registry/cobalt/ui/dialog.tsx:60`); the shared `Overlay` as the backdrop (`registry/cobalt/ui/dialog.tsx:87`); the second click of the double-click that opened the dialog dropped, so it selects no word of the title or the body, presses nothing under the pointer and does not close the dialog from the scrim, while a press that begins inside the open dialog selects as usual (`guardOpeningClick`, `registry/cobalt/ui/dialog.tsx:90`); the popup rendered into the portal container and the page made inert through `useCobaltModal` and `useCobaltPortal` from `registry/cobalt/lib/portal.tsx`; a max height of the viewport minus two gutters; a column (`registry/cobalt/ui/dialog.tsx:99`) in which `DialogBody` scrolls with `overscroll-contain` between a header and a footer that stay, a form wrapping the parts stepping aside with `display: contents`, and the popup itself scrolling only when there is no body or the header and footer alone outgrow the screen; `DialogBody` a tab stop only while it overflows, its rows never shrinking, and its own focus ring drawn inside (`registry/cobalt/ui/dialog.tsx:148-154`); `DialogDescription` scrolling on its own past eight lines, so a long one never takes the body's room; `overflow-wrap: anywhere` on the popup, so an address or a file name breaks rather than run past the edge; the `dialog-motion` fade on `--t-arrive`, leaving in 70 percent of it; `rounded-4xl` on `bg-popover` with `shadow-sheet`, one soft shadow and no edge line; the title at `text-base font-semibold`, the same as the alert dialog and the sheet; the corner close as a ghost `icon-sm` Button with no fill at rest, centred on the title's first line at any text size and on the trailing side in either direction (`registry/cobalt/ui/dialog.tsx:111-113`), with its glyph's edge on the content's 24px edge, since a ghost button shows no corner at rest, and the header padded clear of it so a long title wraps before it, named by `closeLabel`; `DialogError`, a `role="alert"` line for the footer that takes its own line above the actions, and a footer that wraps actions too long to sit side by side (`registry/cobalt/ui/dialog.tsx:169`) |

## Examples
A dialog with a header, a short form and a footer whose submit holds the dialog open while it is pending.

Real uses, 0 call sites (`rg -n "<Dialog\b" app docs/system/examples --glob '!docs/system/examples/dialog/*'`): the showcase chrome renders no Dialog of its own yet, and the examples folder does not count.

Uses inside the registry, which other components build on (planned as product uses once the first screen lands on the system):
- The Sheet is Base UI's Drawer in its own file, `registry/cobalt/ui/sheet.tsx:4`; a dialog and a sheet share the portal and inert behaviour (`registry/cobalt/ui/sheet.tsx:400`), but the sheet has no pending state.
- The AlertDialog keeps its own file for the drift list (D33), `registry/cobalt/ui/alert-dialog.tsx:4`.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/dialog/default.tsx` | default | An invite form that checks the address, sends, then confirms |
| Not applicable: the open state is reached by pressing the trigger on any example | state:open | The popup faded in at the centre over the scrim, focus inside it |
| Not applicable: closing is reached with Escape, the scrim, Cancel or the corner close on any example | state:closing | The popup and the scrim fade out in 70 percent of the arrive time |
| Not applicable: pending is reached by pressing "Send invitation" in default.tsx | state:pending | Escape, the scrim and Cancel do nothing; the submit shows its spinner in place |
| `docs/system/examples/dialog/failure.tsx` | state:failure | A failed submit keeps the dialog open and shows the error |
| `docs/system/examples/dialog/default.tsx` | composition:Field | The address in a Field, its error shown once the form is sent |

Example: An invite form that checks the address, sends, then confirms (`docs/system/examples/dialog/default.tsx`)

```tsx
import { useState } from "react";
import { toast } from "sonner";

import { Button } from "@/components/cobalt/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogError,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/cobalt/ui/dialog";
import { Field, FieldError, FieldLabel } from "@/components/cobalt/ui/field";
import { Input } from "@/components/cobalt/ui/input";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 900),
  );

function problem(email: string) {
  if (email.trim() === "") return "Enter the address to send the invitation to.";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))
    return "Enter an address with a domain, such as ada@example.com.";
  return "";
}

export default function Example() {
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState("");
  // The address is checked on the first submit, then again on every change until it is right.
  const [submitted, setSubmitted] = useState(false);
  const invite = useAction(async (address: string) => {
    await request();
    return address;
  });
  const error = submitted ? problem(email) : "";

  function close() {
    setOpen(false);
    setEmail("");
    setSubmitted(false);
    invite.reset();
  }

  return (
    <>
      <Dialog
        open={open}
        // A click outside would throw away what was typed, so only Cancel and Escape close it then.
        disablePointerDismissal={email !== ""}
        onOpenChange={(next) => {
          if (next) setOpen(true);
          else close();
        }}
      >
        <DialogTrigger render={<Button variant="secondary" />}>Invite someone</DialogTrigger>
        <DialogContent status={invite.status}>
          <form
            noValidate
            className="grid gap-6"
            onSubmit={(event) => {
              event.preventDefault();
              setSubmitted(true);
              if (problem(email) !== "") {
                const field = event.currentTarget.elements.namedItem("email");
                if (field instanceof HTMLInputElement) field.focus();
                return;
              }
              const address = email.trim();
              void invite.run(address).then((sent) => {
                if (sent === undefined) return;
                close();
                // The button that could have said so is gone with the dialog.
                toast(`Invitation sent to ${sent}`, { description: "The link works for seven days." });
              });
            }}
          >
            <DialogHeader>
              <DialogTitle>Invite someone</DialogTitle>
              <DialogDescription>They get an email with a link that works for seven days.</DialogDescription>
            </DialogHeader>
            <Field>
              <FieldLabel>Email</FieldLabel>
              <Input
                name="email"
                type="email"
                autoComplete="email"
                placeholder="name@example.com"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
              />
              {error !== "" && <FieldError>{error}</FieldError>}
            </Field>
            <DialogFooter>
              {invite.error !== null && (
                <DialogError>The invitation was not sent. Check your connection and try again.</DialogError>
              )}
              <DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose>
              <StateButton
                type="submit"
                status={invite.status}
                pendingLabel="Sending"
                failureLabel="Not sent"
              >
                Send invitation
              </StateButton>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  );
}
```

Example: The address in a Field, its error shown once the form is sent (`docs/system/examples/dialog/default.tsx`)

```tsx
import { useState } from "react";
import { toast } from "sonner";

import { Button } from "@/components/cobalt/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogError,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/cobalt/ui/dialog";
import { Field, FieldError, FieldLabel } from "@/components/cobalt/ui/field";
import { Input } from "@/components/cobalt/ui/input";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. It answers after 900ms, and fails while the browser is offline or the
// address has ?network=offline.
const request = () =>
  new Promise<void>((resolve, reject) =>
    setTimeout(() => {
      const offline = !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
      if (offline) reject(new Error("offline"));
      else resolve();
    }, 900),
  );

function problem(email: string) {
  if (email.trim() === "") return "Enter the address to send the invitation to.";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim()))
    return "Enter an address with a domain, such as ada@example.com.";
  return "";
}

export default function Example() {
  const [open, setOpen] = useState(false);
  const [email, setEmail] = useState("");
  // The address is checked on the first submit, then again on every change until it is right.
  const [submitted, setSubmitted] = useState(false);
  const invite = useAction(async (address: string) => {
    await request();
    return address;
  });
  const error = submitted ? problem(email) : "";

  function close() {
    setOpen(false);
    setEmail("");
    setSubmitted(false);
    invite.reset();
  }

  return (
    <>
      <Dialog
        open={open}
        // A click outside would throw away what was typed, so only Cancel and Escape close it then.
        disablePointerDismissal={email !== ""}
        onOpenChange={(next) => {
          if (next) setOpen(true);
          else close();
        }}
      >
        <DialogTrigger render={<Button variant="secondary" />}>Invite someone</DialogTrigger>
        <DialogContent status={invite.status}>
          <form
            noValidate
            className="grid gap-6"
            onSubmit={(event) => {
              event.preventDefault();
              setSubmitted(true);
              if (problem(email) !== "") {
                const field = event.currentTarget.elements.namedItem("email");
                if (field instanceof HTMLInputElement) field.focus();
                return;
              }
              const address = email.trim();
              void invite.run(address).then((sent) => {
                if (sent === undefined) return;
                close();
                // The button that could have said so is gone with the dialog.
                toast(`Invitation sent to ${sent}`, { description: "The link works for seven days." });
              });
            }}
          >
            <DialogHeader>
              <DialogTitle>Invite someone</DialogTitle>
              <DialogDescription>They get an email with a link that works for seven days.</DialogDescription>
            </DialogHeader>
            <Field>
              <FieldLabel>Email</FieldLabel>
              <Input
                name="email"
                type="email"
                autoComplete="email"
                placeholder="name@example.com"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
              />
              {error !== "" && <FieldError>{error}</FieldError>}
            </Field>
            <DialogFooter>
              {invite.error !== null && (
                <DialogError>The invitation was not sent. Check your connection and try again.</DialogError>
              )}
              <DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose>
              <StateButton
                type="submit"
                status={invite.status}
                pendingLabel="Sending"
                failureLabel="Not sent"
              >
                Send invitation
              </StateButton>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  );
}
```

## Variants
Not applicable: a dialog has one form. `AlertDialog` and `Sheet` are the other shapes of the same primitive, each its own component.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| closed | render, or `open={false}` | press the trigger | nothing is in the tree but the trigger, which reads `aria-expanded="false"` | test |
| open | the trigger, or `open` | fill the form, submit, cancel, Escape, press the scrim | the popup centred over the scrim, `aria-expanded="true"` and `data-popup-open` on the trigger, the page behind inert | a11y scan |
| closing | Escape, the scrim, a `DialogClose`, `open={false}` | press the trigger again once it is gone | `data-ending-style` on the popup and the scrim, which take no pointer input while they fade | by hand |
| pending | `status="pending"` on `DialogContent` | wait; a second press on the submit returns early in `StateButton` | `aria-busy` on the popup, `aria-disabled` on every `DialogClose`, the spinner inside the submit | a11y scan |
| failure | the host renders `DialogError` in the footer | read the error, try again, cancel | the `role="alert"` line in red on its own line above the actions, the dialog still open | test |
| scrolling | content taller than the viewport minus two gutters | scroll the body; the header, the footer and the page behind do not move | `DialogBody` clipped between the header and the footer with `overflow-y: auto`, a tab stop while it overflows; measured on `/stress/dialog?data=worst` at 320, 1280 and 1440 | screenshot |

Example: A failed submit keeps the dialog open and shows the error (`docs/system/examples/dialog/failure.tsx`)

```tsx
import { useRef, useState } from "react";

import { Button } from "@/components/cobalt/ui/button";
import {
  Dialog,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogError,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/cobalt/ui/dialog";
import { Field, FieldLabel } from "@/components/cobalt/ui/field";
import { Input } from "@/components/cobalt/ui/input";
import { StateButton } from "@/components/cobalt/ui/state-button";
import { useAction } from "@/lib/cobalt/use-action";

// Stands in for your API call. The first save after opening times out after 1200ms, as a busy
// server would; a retry answers after 900ms. Every try fails while the browser is offline or the
// address has ?network=offline.
const request = (first: boolean) =>
  new Promise<void>((resolve, reject) =>
    setTimeout(
      () => {
        const offline =
          !navigator.onLine || new URLSearchParams(location.search).get("network") === "offline";
        if (offline || first) reject(new Error(offline ? "offline" : "timeout"));
        else resolve();
      },
      first ? 1200 : 900,
    ),
  );

export default function Example() {
  const [open, setOpen] = useState(false);
  const [name, setName] = useState("Credit funds");
  const tries = useRef(0);
  const rename = useAction(async (next: string) => {
    await request(tries.current++ === 0);
    return next;
  });
  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        setOpen(next);
        if (next) tries.current = 0;
        else rename.reset();
      }}
    >
      <div className="flex items-center gap-3">
        <p aria-live="polite" className="text-sm">
          {name}
        </p>
        <DialogTrigger render={<Button variant="secondary" />}>Rename watchlist</DialogTrigger>
      </div>
      <DialogContent status={rename.status}>
        <form
          className="grid gap-6"
          onSubmit={(event) => {
            event.preventDefault();
            const field = event.currentTarget.elements.namedItem("name");
            const next = field instanceof HTMLInputElement ? field.value.trim() : "";
            void rename.run(next || name).then((saved) => {
              if (saved === undefined) return;
              // The new name shows beside the button, so no toast repeats it.
              setName(saved);
              setOpen(false);
            });
          }}
        >
          <DialogHeader>
            <DialogTitle>Rename watchlist</DialogTitle>
            <DialogDescription>Everyone who shares the watchlist sees the new name.</DialogDescription>
          </DialogHeader>
          <Field>
            <FieldLabel>Name</FieldLabel>
            <Input name="name" defaultValue={name} />
          </Field>
          <DialogFooter>
            {rename.error !== null && (
              <DialogError>
                {rename.error instanceof Error && rename.error.message === "offline"
                  ? "You are offline. The name was not saved."
                  : "The server took too long. The name was not saved; try again."}
              </DialogError>
            )}
            <DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose>
            <StateButton type="submit" status={rename.status} pendingLabel="Saving" failureLabel="Not saved">
              Save name
            </StateButton>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
```

### State precedence
- Pending and closing: pending wins. Escape, the scrim and every `DialogClose` are cancelled by the root until the status leaves pending; only the host's own `open={false}` closes it.
- Pending and failure: Not applicable: `status` is one value at a time, and `DialogError` is rendered by the host once the status is failure.
- Failure and open: both show. The dialog stays open with the error in its footer until you retry or cancel.
- Open and scrolling: both show. The max height clips the popup and the body scrolls, with the header, the footer, the scrim and the page behind unmoved.
- Closing and open: closing wins. A press on the trigger during the exit is a new open, and the fading layer takes no input (`trap/exit-eats-input`).
- Open and the second click of the double-click that opened it: open wins, and the click is dropped. Measured on both examples at 1440 and 390, light and dark: before, the click selected a word of the open dialog ("name" in the field's label at 390) or landed on the scrim and closed the dialog it had just opened (both examples at 1440); after, nothing is selected and the dialog stays open, while a double-click on a word of the open dialog still selects it (`.design-system/evidence/dialog/double-click.json`).

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| closed to open | announce | `dialog-motion`, `--t-arrive` on `--curve`, a fade in place, centred (`trap/motion-origin`: nothing scales) | opacity 0 to 1 | the fade stays, and `registry/cobalt/base.css:186` still forces `scale: 1`, now a no-op safety net; measured `transition-property: opacity` only under reduce in `.design-system/evidence/dialog/open-390x320.json` |
| open to closed | announce | `dialog-motion`, 70 percent of `--t-arrive` on `--curve` (`trap/motion-exit-slower`) | opacity 1 to 0 | the fade only |
| scrim in and out | announce | `overlay-motion`, `--t-arrive` and 70 percent of it on `--curve` | opacity | the same fade |

## Props

<!-- Props generated from registry/cobalt/ui/dialog.tsx with TypeScript by scripts/props-table.mjs -->
### Dialog

No props of its own.

Also accepts from Base UI: `actionsRef`, `defaultOpen`, `defaultTriggerId`, `disablePointerDismissal`, `handle`, `modal`, `onOpenChange`, `onOpenChangeComplete`, `open`, `triggerId`.

### DialogBody

No props of its own.

Also accepts every native `<div>` attribute.

### DialogClose

No props of its own.

Also accepts every native `<button>` attribute; from Base UI: `nativeButton`, `render`.

### DialogContent

| Prop | Type | Default | Purpose |
|---|---|---|---|
| `closeLabel?` | `string` | `"Close"` | The accessible name of the close button in the corner. |
| `showCloseButton?` | `boolean` | `true` |  |
| `status?` | `WriteStatus` | `"idle"` | While pending, nothing dismisses the dialog: the submit decides when it closes. |

Also accepts every native `<div>` attribute; from Base UI: `finalFocus`, `initialFocus`, `render`.

### DialogDescription

No props of its own.

Also accepts every native `<p>` attribute; from Base UI: `render`.

### DialogError

No props of its own.

Also accepts every native `<p>` attribute.

### DialogFooter

No props of its own.

Also accepts every native `<div>` attribute.

### DialogHeader

No props of its own.

Also accepts every native `<div>` attribute.

### DialogTitle

No props of its own.

Also accepts every native `<h2>` attribute; from Base UI: `render`.

### DialogTrigger

No props of its own.

Also accepts every native `<button>` attribute; from Base UI: `handle`, `id`, `nativeButton`, `payload`, `render`.

`DialogContent` adds `status` (`Status` from `registry/cobalt/lib/status.ts`: while `"pending"` nothing dismisses the dialog), `showCloseButton` (default true) and `closeLabel` (default "Close", the corner button's accessible name). Everything on Base UI's root passes through `Dialog`: `open`, `defaultOpen`, `onOpenChange` with the reason, `modal` (default true; `false` leaves the page live and skips the inert lock), `disablePointerDismissal`, `onOpenChangeComplete`. `DialogContent` passes Base UI's popup props through, including `initialFocus` and `finalFocus`. `DialogBody` takes a div's props and wraps whatever should scroll between the header and the footer; without it the whole popup scrolls. `DialogTrigger` and `DialogClose` take `render` to compose with Button. `className` on every part is merged last and is for placement.

## Usage

### When to use
- You have one task to finish before the page is useful again: invite someone, rename a list, pick a date range.
- The task has a submit that can take time, and the result must land on the same form.

### When not to use
- The task only asks yes or no before something is removed. Use AlertDialog instead.
- The task is a list, a set of filters or an editor that scrolls. Use Sheet instead.
- The task is one field or one setting beside its trigger, with no need to block the page. Use Popover instead.
- The content is only the name of a control. Use Tooltip instead.
- The task is finding a record or a command by typing. Use CommandPalette instead.

### Rules
- `rule/dialog-controlled-stays-mounted`: When a host opens a dialog from its own state, pass `open` and `onOpenChange` and keep the `Dialog` in the tree, instead of mounting it with `{open && ...}`, because an unmounted dialog has no exit transition and no element to return focus to. Evidence: principle platform: Base UI animates `data-ending-style` on the mounted popup and returns focus to the trigger on close; measured focus on the trigger after Escape and after a success close, .design-system/evidence/dialog/open-390x320.json. Check: lint trap/overlay-conditional-render (scripts/check-system.mjs).
  - Don't: `{open && <Dialog open><DialogContent><DialogTitle>Rename list</DialogTitle></DialogContent></Dialog>}`
  - Do: `<Dialog open={open} onOpenChange={setOpen}><DialogContent><DialogTitle>Rename list</DialogTitle></DialogContent></Dialog>`
- `rule/dialog-pending-holds`: When the dialog's submit is in flight, pass `status="pending"` to `DialogContent` and keep the submit in a `StateButton`, instead of closing on click or disabling Cancel, because the root then cancels Escape, the scrim and every close, Cancel keeps focus with `aria-disabled`, and the result lands on an open form (`trap/overlay-pending-dismiss`). Evidence: person D2; measured Escape and the scrim leave the pending dialog open, Cancel `aria-disabled="true"`, the popup `aria-busy="true"`, .design-system/evidence/dialog/open-390x320.json. Check: review of every `DialogContent` whose footer submits; test `dialog.test.tsx` renders the idle close without `aria-disabled`.
  - Don't: `<DialogFooter><Button disabled={saving} onClick={() => { save(); setOpen(false); }}>Save</Button></DialogFooter>`
  - Do: `<DialogContent status={status}>...<DialogFooter><DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose><StateButton status={status} pendingLabel="Saving" onClick={save}>Save name</StateButton></DialogFooter></DialogContent>`
- `rule/dialog-one-title`: When a dialog opens, render exactly 1 `DialogTitle` inside `DialogContent`, with `className="sr-only"` when the design hides it, because Base UI names the popup by `aria-labelledby` from the title, and a dialog with none is announced as "dialog" and nothing else (`trap/overlay-title`). Evidence: principle wcag: 4.1.2 Name, role, value, a dialog needs a name; measured `aria-labelledby` on the open popup, .design-system/evidence/dialog/open-390x320.json. Check: review of every `DialogContent` for a `DialogTitle`.
  - Don't: `<DialogContent><p className="font-semibold">Invite someone</p><Input /></DialogContent>`
  - Do: `<DialogContent><DialogHeader><DialogTitle>Invite someone</DialogTitle></DialogHeader><Input /></DialogContent>`
- `rule/dialog-initial-focus`: When the first tabbable element in the dialog is a text field and typing is not the only task there, pass `initialFocus` on `DialogContent` pointing at the popup or the primary action, instead of letting the field take focus, because on a phone a focused field raises the keyboard over the dialog before you have read it (`trap/touch-autofocus`). Evidence: principle input: touch has no hover and a focused field opens the software keyboard; measured focus on the first `input` on open, .design-system/evidence/dialog/open-390x320.json. Check: review of every dialog whose first tabbable element is a field.
  - Don't: `<DialogContent><DialogTitle>Share list</DialogTitle><Input placeholder="Add a note" /><Switch /></DialogContent>`
  - Do: `<DialogContent initialFocus={(type) => type === "touch" ? false : true}><DialogTitle>Share list</DialogTitle><Input placeholder="Add a note" /><Switch /></DialogContent>`
- `rule/dialog-footer-order`: When a dialog has a cancel and a primary action, write the cancel first through `DialogClose` and the primary action last in `DialogFooter`, because the footer reverses into a column below 640px, so the primary action lands at the bottom edge under the thumb and is the last tab stop before the close. Evidence: person D13; principle platform: the native alert puts the default action last, on the trailing edge. Check: review of every `DialogFooter`.
  - Don't: `<DialogFooter><Button>Send invite</Button><DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose></DialogFooter>`
  - Do: `<DialogFooter><DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose><Button>Send invite</Button></DialogFooter>`

### Content
- Follows `rule/writing-dialog-title-verb`.
- Follows `rule/writing-dialog-body-sentence`.
- `rule/dialog-error-sentence`: When the submit fails, render `DialogError` in the footer with one sentence naming what did not happen and one naming what to do, such as "The invite could not be sent. Try again.", instead of "Error" or "Something went wrong", because the line is announced as it appears and the dialog stays open for the retry. Evidence: principle heuristic: help users recognize, diagnose and recover from errors, the message names the failure and the way out; person D11. Check: review of every `DialogError`; test `dialog.test.tsx` renders it with `role="alert"`.
  - Don't: `<DialogError>Something went wrong</DialogError>`
  - Do: `<DialogError>The invite could not be sent. Try again.</DialogError>`

### Anti-slop
- `rule/dialog-not-for-confirm`: When the dialog would only ask yes or no before something is removed, use AlertDialog instead of a `Dialog` with two buttons, because a dialog closes on a scrim press and a lost confirm is a lost decision, while the alert dialog ignores the scrim and names itself `alertdialog` (`trap/overlay-destructive`). Evidence: measured a scrim press leaves the alert dialog open and `role="alertdialog"`, .design-system/evidence/alert-dialog/open-390x320.json; principle platform: the OS confirm has no outside dismissal. Check: review of every dialog whose primary action is `variant="destructive"`.
  - Don't: `<Dialog><DialogContent><DialogTitle>Delete list</DialogTitle><DialogFooter><DialogClose>Cancel</DialogClose><Button variant="destructive">Delete list</Button></DialogFooter></DialogContent></Dialog>`
  - Do: `<AlertDialog><AlertDialogContent><AlertDialogTitle>Delete list</AlertDialogTitle><AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction variant="destructive">Delete list</AlertDialogAction></AlertDialogFooter></AlertDialogContent></AlertDialog>`
- `rule/dialog-one-way-out-per-answer`: When the footer has a cancel, keep the corner close button and label the footer action "Cancel" through `DialogClose`, instead of adding a second "Close" text button, because two buttons that do the same thing make you pick between them. Evidence: principle heuristic: aesthetic and minimalist design, one control per answer; person D11. Check: review of every `DialogFooter`.
  - Don't: `<DialogFooter><DialogClose render={<Button variant="ghost" />}>Close</DialogClose><DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose><Button>Save name</Button></DialogFooter>`
  - Do: `<DialogFooter><DialogClose render={<Button variant="ghost" />}>Cancel</DialogClose><Button>Save name</Button></DialogFooter>`

### Limits
- `rule/dialog-title-length`: When a title would run past 42 characters, shorten it instead of letting it wrap, because at 43 characters the 16px title wraps to a second line in the 310px column at 390px. Evidence: measured wrap at 43 characters in a 310px column at 390px, .design-system/evidence/dialog/open-390x320.json. Check: probe `.design-system/scripts/measure-overlays.mjs` grows the title on the showcase at 390.
  - Don't: `<DialogTitle>Invite someone to the workspace and give them a link</DialogTitle>`
  - Do: `<DialogTitle>Invite someone</DialogTitle>`
- `rule/dialog-fits-the-short-screen`: When the content would be taller than 288px, use Sheet instead, because at 390 by 320 the popup's max height is 288px and a header, one field and a footer already measure 296px, so the footer scrolls out of the first view. Evidence: measured max height 288px and a scroll height of 296px at 390 by 320, .design-system/evidence/dialog/open-390x320.json. Check: probe trap/overlay-no-max-height (`node .agents/skills/build-design-system/scripts/probe.mjs --widths 390 --height 320 --click`).
  - Don't: `<DialogContent><DialogTitle>Edit profile</DialogTitle><Input /><Input /><Input /><Textarea /><DialogFooter>...</DialogFooter></DialogContent>`
  - Do: `<SheetContent><SheetHeader><SheetTitle>Edit profile</SheetTitle></SheetHeader><SheetBody><Input /><Input /><Input /><Textarea /></SheetBody><SheetFooter>...</SheetFooter></SheetContent>`

## Accessibility
Rests on Base UI `Dialog`, which renders `role="dialog"` with `aria-labelledby` and `aria-describedby`, moves focus in on open and back to the trigger on close, and closes on Escape; the team makes the page behind inert through `registry/cobalt/lib/portal.tsx` so nothing outside the popup takes focus or a press. Every row below that says `a11y scan` was read from the open popup on the live page into `.design-system/evidence/dialog/open-390x320.json`.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Enter or Space | the trigger | opens the dialog | the first tabbable element in the popup, the field in the default example (`trap/touch-autofocus`) | a11y scan |
| Tab and Shift+Tab | inside the popup | moves between the popup's controls and wraps; the page behind is inert | the next or previous control in the popup | by hand |
| Escape | inside the popup | closes the dialog; while pending, nothing | the trigger (`trap/overlay-focus-return`); while pending, unchanged | a11y scan |
| Escape | inside a menu or popover open within the dialog | closes the menu or popover only, which handles the key before the dialog (`trap/escape-nested`) | the menu's trigger inside the dialog | by hand |
| Enter or Space | a `DialogClose` | closes the dialog; while pending, nothing and the button keeps focus | the trigger; while pending, the close button | a11y scan |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| trigger | button | its text | `aria-haspopup="dialog"`, `aria-expanded`, `aria-controls`, `data-popup-open` while open (`trap/open-trigger-unfocused`) | the name, "button", "collapsed" or "expanded" | test |
| popup | dialog | `aria-labelledby` from `DialogTitle` | `aria-describedby` from `DialogDescription`, `tabindex="-1"`, `aria-busy` while pending, `data-open` | "dialog", the title, then the description on open | a11y scan |
| corner close | button | the sr-only `closeLabel`, "Close" | `aria-disabled` while pending | "Close, button" | by hand |
| error | alert | its text | none | the sentence as it appears | test |
| scrim | none | none | `data-slot="overlay"`, presentation only | nothing | a11y scan |

## Tokens
| Part | State | Token |
|---|---|---|
| popup | all | `--popover`, `--popover-foreground`, `--r-4xl`, `--elev-sheet`, `--gutter` (the margin and the max height), `--t-arrive`, `--curve` |
| title | all | `--foreground`, measured 19.8 to 1 on `--popover` in `.design-system/evidence/dialog/open-390x320.json` |
| description | all | `--muted-foreground`, measured 6.01 to 1 on `--popover` |
| error | failure | `--destructive`, measured 5.61 to 1 on `--popover` in `.design-system/evidence/alert-dialog/open-390x320.json` |
| corner close | rest | none, the ghost Button has no fill until hovered |
| corner close | hover | `--muted` |
| scrim | all | `--scrim`, `--t-arrive` |

## Related
- AlertDialog: a yes or no before something is removed, which the scrim cannot dismiss.
- Sheet: a task that scrolls, from the side or from the bottom of a phone.
- Popover: one field or setting beside its trigger, with the page left live.
- StateButton: the submit that reports pending, success and failure in place.
- Card: a white box that groups one item's title, details and actions.
- Crossfade: new content fades in where the old content was.
- Grow: opens one small answer out of the control that asks for it.
- Toaster: a short message about something that happened in the background.
- Collapsible: extra detail that needs no decision, opened in place.
