# Dialog

A modal on the level surface: focus trap, inert page, Esc and focus return.

Live variants: https://design.arcadia.is/components/dialog

```tsx
import {
  Dialog, DialogTrigger, DialogClose, DialogContent, DialogHeader, DialogTitle,
  DialogDescription, DialogBody, DialogError, DialogFooter, DialogActions,
} from "@arcadia/ui";
```

## In context

Rename a project without leaving the page.

Edit the name, then save or cancel.

```tsx
import { useRef, useState } from "react";
import {
  Button, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription,
  DialogFooter, DialogHeader, DialogTitle, DialogTrigger, Field, Input,
} from "@arcadia/ui";

function Rename() {
  const [name, setName] = useState("Acme web");
  const [draft, setDraft] = useState(name);
  const [open, setOpen] = useState(false);
  const input = useRef<HTMLInputElement>(null);

  return (
    <Dialog open={open} onOpenChange={(next) => {
      if (next) setDraft(name);
      setOpen(next);
    }}>
      <DialogTrigger render={<Button variant="secondary">Rename project</Button>} />
      <span {...stylex.props(cmp.result)} role="status">{name}</span>
      <DialogContent initialFocus={input}>
        <form onSubmit={(e) => {
          e.preventDefault();
          if (!draft.trim()) return;
          setName(draft.trim());
          setOpen(false);
        }}>
          <DialogHeader>
            <DialogTitle>Rename project</DialogTitle>
            <DialogDescription>Shown in the sidebar and the window title.</DialogDescription>
          </DialogHeader>
          <DialogBody>
            <Field label="Name"><Input ref={input} value={draft} onChange={(e) => setDraft(e.target.value)} /></Field>
          </DialogBody>
          <DialogFooter>
            <DialogClose render={<Button>Cancel</Button>} />
            <Button type="submit" variant="primary" disabled={!draft.trim()}>Save name</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
```

## When to use

Use a dialog for a short task that blocks the page.

## When not to use

Use [Confirm Dialog](/components/confirm-dialog) for irreversible actions. Use [Tray](/components/tray) for questions during work.

## Usage

```tsx
import {
  Button, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription,
  DialogFooter, DialogHeader, DialogTitle, DialogTrigger,
} from "@arcadia/ui";

<Dialog>
  <DialogTrigger render={<Button>Settings</Button>} />
  <DialogContent size="lg">
    <DialogHeader>
      <DialogTitle>Settings</DialogTitle>
      <DialogDescription>Changes apply to every chat.</DialogDescription>
    </DialogHeader>
    <DialogBody><SettingsForm /></DialogBody>
    <DialogFooter>
      <DialogClose render={<Button>Close</Button>} />
    </DialogFooter>
  </DialogContent>
</Dialog>
```

Put Cancel before the primary action and align both to the end.

Keyboard opens are instant. Set `instant` when a shortcut opens the dialog.

Use `placement="top"` for a [Palette](/components/palette). On phones the dialog clears the keyboard.

`DialogHeader` takes an `action`, `DialogError` a `readout`, and `DialogActions` an `aside`.

See [Elevation](/foundations/elevation#backdrop) for the scrim and surface tokens.

## Examples

### Controlled, with an async save

Save keeps the dialog open until the request settles.

```tsx
import { useState } from "react";
import {
  Button, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription,
  DialogFooter, DialogHeader, DialogTitle, DialogTrigger, Field, Input,
} from "@arcadia/ui";

function AsyncSave() {
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [name, setName] = useState("Acme web");
  const [draft, setDraft] = useState(name);
  const save = async () => {
    setSaving(true);
    await saveName(draft.trim());
    setName(draft.trim());
    setSaving(false);
    setOpen(false);
  };
  return (
    <Dialog open={open} onOpenChange={(next) => {
      if (saving) return;
      if (next) setDraft(name);
      setOpen(next);
    }}>
      <DialogTrigger render={<Button variant="secondary">Rename: {name}</Button>} />
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename project</DialogTitle>
          <DialogDescription>Saved for everyone in this workspace.</DialogDescription>
        </DialogHeader>
        <DialogBody>
          <Field label="Name">
            <Input value={draft} onChange={(e) => setDraft(e.target.value)} disabled={saving} />
          </Field>
        </DialogBody>
        <DialogFooter>
          <DialogClose render={<Button disabled={saving}>Cancel</Button>} />
          <Button variant="primary" loading={saving} disabled={!draft.trim()} onClick={save}>Save</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

### A failed action

Show the reason above the actions, with an optional server readout.

```tsx
import { useEffect, useRef, useState } from "react";
import {
  Button, Dialog, DialogActions, DialogBody, DialogClose, DialogContent,
  DialogDescription, DialogError, DialogFooter, DialogHeader, DialogTitle,
  DialogTrigger, Field, IconButton, Input, Link, SettingsGroup, SettingsRow,
  Sheet, Switch,
} from "@arcadia/ui";

function Failed({ container }: { container: HTMLElement }) {
  return (
    <Dialog open modal={false} disablePointerDismissal>
      <DialogContent container={container} initialFocus={false}>
        <DialogHeader>
          <DialogTitle>Rename project</DialogTitle>
        </DialogHeader>
        <DialogBody>
          <Field label="Name"><Input defaultValue="Acme web" /></Field>
        </DialogBody>
        <DialogError readout="503 projects store is read only">Couldn't save. Try again.</DialogError>
        <DialogFooter>
          <DialogActions aside={<Link href="https://status.arcadia.is/" target="_blank" rel="noopener">Service status</Link>}>
            <DialogClose render={<Button>Cancel</Button>} />
            <Button variant="primary">Save</Button>
          </DialogActions>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

export function Thumb() {
  return (
    <>
      <Button>Cancel</Button>
      <Button variant="primary">Save</Button>
    </>
  );
}

function Usage() {
  return (
    <Dialog>
      <DialogTrigger render={<Button>Settings</Button>} />
      <DialogContent size="lg">
        <DialogHeader>
          <DialogTitle>Settings</DialogTitle>
          <DialogDescription>Changes apply to every chat.</DialogDescription>
        </DialogHeader>
        <DialogBody><SettingsForm /></DialogBody>
        <DialogFooter>
          <DialogClose render={<Button>Close</Button>} />
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
const SettingsForm = () => null;

function AsyncSave() {
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [name, setName] = useState("Acme web");
  const [draft, setDraft] = useState(name);
  const save = async () => {
    setSaving(true);
    await saveName(draft.trim());
    setName(draft.trim());
    setSaving(false);
    setOpen(false);
  };
  return (
    <Dialog open={open} onOpenChange={(next) => {
      if (saving) return;
      if (next) setDraft(name);
      setOpen(next);
    }}>
      <DialogTrigger render={<Button variant="secondary">Rename: {name}</Button>} />
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename project</DialogTitle>
          <DialogDescription>Saved for everyone in this workspace.</DialogDescription>
        </DialogHeader>
        <DialogBody>
          <Field label="Name">
            <Input value={draft} onChange={(e) => setDraft(e.target.value)} disabled={saving} />
          </Field>
        </DialogBody>
        <DialogFooter>
          <DialogClose render={<Button disabled={saving}>Cancel</Button>} />
          <Button variant="primary" loading={saving} disabled={!draft.trim()} onClick={save}>Save</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function LongBody() {
  return (
    <Dialog>
      <DialogTrigger render={<Button variant="secondary">Notification settings</Button>} />
      <DialogContent size="lg">
        <DialogHeader>
          <DialogTitle>Notifications</DialogTitle>
          <DialogDescription>Changes apply to every chat in this workspace.</DialogDescription>
        </DialogHeader>
        <DialogBody>
          <div style={settingsBodyStyle}>
          <Switch label="Chime when a turn ends" hint="Plays in background tabs only." defaultChecked
            rootStyle={cmp.settingsChild as never} />
          <Switch label="Reduce motion" hint="When off, it follows the system."
            rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
          <Switch label="Send with ⌘⏎"
            rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
          <Switch label="Show token usage" defaultChecked
            rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
          </div>
        </DialogBody>
        <DialogFooter divided>
          <DialogClose render={<Button>Cancel</Button>} />
          <DialogClose render={<Button variant="primary">Save</Button>} />
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

function SizeOpen({ size, container }: { size: DialogSize; container: HTMLElement }) {
  return (
    <Dialog open modal={false} disablePointerDismissal>
      <DialogContent container={container} size={size} initialFocus={false}>
        <DialogHeader>
          <DialogTitle>{`size="${size}"`}</DialogTitle>
          <DialogDescription>Header, body and footer; the close button sits top-right.</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose render={<Button>Cancel</Button>} />
          <Button variant="primary">Save</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

const WIDTHS: Record<DialogSize, string> = { sm: "320", md: "400, the default", lg: "480", xl: "560", "2xl": "720" };

const depth = stylex.create({

  further: { ...stylex.env.nest.deeper(spaces["--space-4"]), paddingInline: spaces["--space-4"] },
});

function Surfaces({ container, further = false }: { container: HTMLElement; further?: boolean }) {
  return (
    <Dialog open modal={false} disablePointerDismissal>
      <DialogContent container={container} size="2xl" initialFocus={false}>
        <DialogHeader>
          <DialogTitle>Notifications</DialogTitle>
        </DialogHeader>
        <DialogBody>
          <div {...stylex.props(further && depth.further)}>
            <SettingsGroup nesting="contained-object" label="Sounds">
              <SettingsRow label="Play a sound" control={<Switch hideLabel label="Play a sound" defaultChecked />} />
              <SettingsRow label="Sound" value="Default chime" control={<Button size="sm" variant="secondary">Choose file</Button>} />
            </SettingsGroup>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
}

export function SettingsSheet({ initiallyOpen = false }: { initiallyOpen?: boolean } = {}) {
  const [open, setOpen] = useState(false);
  useEffect(() => { if (initiallyOpen) setOpen(true); }, [initiallyOpen]);
  const trigger = useRef<HTMLButtonElement>(null);
  return (
    <>
      <Button ref={trigger} aria-haspopup="dialog" variant="secondary" onClick={() => setOpen(true)}>Open settings sheet</Button>
      <Sheet aria-label="Notification settings" open={open} onOpenChange={setOpen} finalFocus={trigger}>
        <div {...stylex.props(sheetSpecimen.body)}>
          <header {...stylex.props(sheetSpecimen.header)}>
            <h2 {...stylex.props(sheetSpecimen.title)}>Notifications</h2>
            <IconButton icon="x" label="Close sheet" onClick={() => setOpen(false)} />
          </header>
          <Switch label="Email updates" />
          <Switch label="Desktop alerts" />
          <Switch label="Sound" />
        </div>
      </Sheet>
    </>
  );
}

export default function DialogPage() {
  return (
    <>
      <Section title="In context" lead="Rename a project without leaving the page.">
        <Specimen code={SRC.Rename} size="compact" caption="Edit the name, then save or cancel.">
          <Rename />
        </Specimen>
      </Section>

      <Section title="When to use">
        <P>Use a dialog for a short task that blocks the page.</P>
      </Section>

      <Section title="When not to use">
        <P>Use <a href="/components/confirm-dialog">Confirm Dialog</a> for irreversible actions. Use <a href="/components/tray">Tray</a> for questions during work.</P>
      </Section>

      <Section title="Usage">
        <CodeBlock code={displaySnippet(SRC.Usage)} />
        <P>Put Cancel before the primary action and align both to the end.</P>
        <P>Keyboard opens are instant. Set `instant` when a shortcut opens the dialog.</P>
        <P>Use <code>placement="top"</code> for a <a href="/components/palette">Palette</a>. On phones the dialog clears the keyboard.</P>
        <P>`DialogHeader` takes an `action`, `DialogError` a `readout`, and `DialogActions` an `aside`.</P>
        <P>See <a href="/foundations/elevation#backdrop">Elevation</a> for the scrim and surface tokens.</P>
      </Section>
      <Section title="Examples">
        <Sub title="Controlled, with an async save" lead="Save keeps the dialog open until the request settles.">
          <Specimen code={SRC.AsyncSave} size="compact"><AsyncSave /></Specimen>
        </Sub>
        <Sub title="A failed action" lead="Show the reason above the actions, with an optional server readout.">
          <Specimen code={SRC.Failed} cols={1}>
            <Cell caption="Save failed" height={space(20)} stage={(c) => <Failed container={c} />} />
          </Specimen>
        </Sub>
        <Sub title="An action in the header" lead="Place one small action before the close button.">
          <Specimen cols={1}>
            <Cell caption="Refresh in the header" height={space(12.5)} stage={(c) => <HeaderAction container={c} />} />
          </Specimen>
        </Sub>
        <Sub title="Long body" lead="The body scrolls; a divided footer keeps the actions anchored.">
          <Specimen code={SRC.LongBody} size="compact"><LongBody /></Specimen>
        </Sub>
        <Sub title="Surfaces inside" lead="Use `nest.surface` so inner corners follow their inset.">
          <Specimen code={SRC.Surfaces} cols={1}>
            <Cell caption="Card inside the dialog body" height={space(17)} stage={(c) => <Surfaces container={c} />} />
            <Cell caption="Card inset one step further" height={space(17)} stage={(c) => <Surfaces container={c} further />} />
          </Specimen>
        </Sub>
        <Sub title="Sheet" lead="Keep settings in a pane that opens from the edge.">
          <Specimen code={SRC.SettingsSheet} size="compact"><SettingsSheet /></Specimen>
        </Sub>
        <Sub title="Sizes" lead="Five widths, each capped to leave room at the viewport edges.">
          <Specimen cols={1}>
            {union<DialogSize>("DialogSize").map((size) => (
              <Cell key={size} caption={WIDTHS[size]} height={space(12.5)} stage={(c) => <SizeOpen size={size} container={c} />} />
            ))}
          </Specimen>
        </Sub>
      </Section>
      <Section title="Customising" lead="Set the content width and surface through `rootStyle`.">
        <Knobs type="DialogKnobs" label="Dialog knobs" />
      </Section>
    </>
  );
}

export function Notes() {
  return (
    <Section title="Accessibility">
      <P>
        Modal by default: the platform&apos;s `dialog`, opened in the browser&apos;s top layer, so the page behind is inert to
        the pointer, the keys and a reader, and its scroll is held. Focus starts on the first field, else on the footer&apos;s primary action, is trapped, and returns to the trigger on close.
        Escape is the kit&apos;s, not the browser&apos;s: it closes what opened last, a menu inside before the dialog. A menu, a
        popover or a tooltip opened inside stands inside it, and the toast stack moves in while it is open.
        The title names the dialog and the description describes it, so always render a `DialogTitle`. The close button in
        the corner is labelled "Close" (`closeLabel` changes it). A dialog is centred `safe`: one taller or wider than
        its window, at a large text size, starts at the window&apos;s top and side, where its title and close button stay
        in reach, and the window scrolls to the rest.
      </P>
      <Keys rows={[["Enter", "Presses the primary action, unless focus is on a control with its own Enter"], ["Esc", "Closes the dialog"], ["Tab", "Cycles focus inside the dialog"]]} />
    </Section>
  );
}
```

- Save failed

### An action in the header

Place one small action before the close button.

- Refresh in the header

### Long body

The body scrolls; a divided footer keeps the actions anchored.

```tsx
import {
  Button, Dialog, DialogBody, DialogClose, DialogContent, DialogDescription,
  DialogFooter, DialogHeader, DialogTitle, DialogTrigger, Switch,
} from "@arcadia/ui";

<Dialog>
  <DialogTrigger render={<Button variant="secondary">Notification settings</Button>} />
  <DialogContent size="lg">
    <DialogHeader>
      <DialogTitle>Notifications</DialogTitle>
      <DialogDescription>Changes apply to every chat in this workspace.</DialogDescription>
    </DialogHeader>
    <DialogBody>
      <div style={settingsBodyStyle}>
      <Switch label="Chime when a turn ends" hint="Plays in background tabs only." defaultChecked
        rootStyle={cmp.settingsChild as never} />
      <Switch label="Reduce motion" hint="When off, it follows the system."
        rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
      <Switch label="Send with ⌘⏎"
        rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
      <Switch label="Show token usage" defaultChecked
        rootStyle={[cmp.settingsChild, cmp.settingsRest] as never} />
      </div>
    </DialogBody>
    <DialogFooter divided>
      <DialogClose render={<Button>Cancel</Button>} />
      <DialogClose render={<Button variant="primary">Save</Button>} />
    </DialogFooter>
  </DialogContent>
</Dialog>
```

### Surfaces inside

Use `nest.surface` so inner corners follow their inset.

```tsx
import {
  Button, Dialog, DialogBody, DialogContent, DialogHeader, DialogTitle,
  SettingsGroup, SettingsRow, Switch,
} from "@arcadia/ui";

function Surfaces({ container, further = false }: { container: HTMLElement; further?: boolean }) {
  return (
    <Dialog open modal={false} disablePointerDismissal>
      <DialogContent container={container} size="2xl" initialFocus={false}>
        <DialogHeader>
          <DialogTitle>Notifications</DialogTitle>
        </DialogHeader>
        <DialogBody>
          <div {...stylex.props(further && depth.further)}>
            <SettingsGroup nesting="contained-object" label="Sounds">
              <SettingsRow label="Play a sound" control={<Switch hideLabel label="Play a sound" defaultChecked />} />
              <SettingsRow label="Sound" value="Default chime" control={<Button size="sm" variant="secondary">Choose file</Button>} />
            </SettingsGroup>
          </div>
        </DialogBody>
      </DialogContent>
    </Dialog>
  );
}
```

- Card inside the dialog body
- Card inset one step further

### Sheet

Keep settings in a pane that opens from the edge.

```tsx
import { useEffect, useRef, useState } from "react";
import { Button, IconButton, Sheet, Switch } from "@arcadia/ui";

function SettingsSheet({ initiallyOpen = false }: { initiallyOpen?: boolean } = {}) {
  const [open, setOpen] = useState(false);
  useEffect(() => { if (initiallyOpen) setOpen(true); }, [initiallyOpen]);
  const trigger = useRef<HTMLButtonElement>(null);
  return (
    <>
      <Button ref={trigger} aria-haspopup="dialog" variant="secondary" onClick={() => setOpen(true)}>Open settings sheet</Button>
      <Sheet aria-label="Notification settings" open={open} onOpenChange={setOpen} finalFocus={trigger}>
        <div {...stylex.props(sheetSpecimen.body)}>
          <header {...stylex.props(sheetSpecimen.header)}>
            <h2 {...stylex.props(sheetSpecimen.title)}>Notifications</h2>
            <IconButton icon="x" label="Close sheet" onClick={() => setOpen(false)} />
          </header>
          <Switch label="Email updates" />
          <Switch label="Desktop alerts" />
          <Switch label="Sound" />
        </div>
      </Sheet>
    </>
  );
}
```

### Sizes

Five widths, each capped to leave room at the viewport edges.

- 320
- 400, the default
- 480
- 560
- 720

## Customising

Set the content width and surface through `rootStyle`.

- `--dialog-w` (`TokenRef<Measure>`, default `25rem`)
- `--dialog-bg` (`Paint`, default `var(--bg-elevated)`)

## Accessibility

Modal by default: the platform's `dialog`, opened in the browser's top layer, so the page behind is inert to the pointer, the keys and a reader, and its scroll is held. Focus starts on the first field, else on the footer's primary action, is trapped, and returns to the trigger on close. Escape is the kit's, not the browser's: it closes what opened last, a menu inside before the dialog. A menu, a popover or a tooltip opened inside stands inside it, and the toast stack moves in while it is open. The title names the dialog and the description describes it, so always render a `DialogTitle`. The close button in the corner is labelled "Close" (`closeLabel` changes it). A dialog is centred `safe`: one taller or wider than its window, at a large text size, starts at the window's top and side, where its title and close button stay in reach, and the window scrolls to the rest.

- Enter: Presses the primary action, unless focus is on a control with its own Enter
- Esc: Closes the dialog
- Tab: Cycles focus inside the dialog

## API reference

### Dialog

- `modal` (`boolean | "trap-focus"`, default `true`)
- `disablePointerDismissal` (`boolean`, default `false`)
- `open` (`boolean`): Controlled open state.
- `defaultOpen` (`boolean`, default `false`): Initial open state when uncontrolled.
- `onOpenChange` (`(open: boolean, details: OpenChangeDetails) => void`): Called when the popup opens or closes, with why (`details.reason`) and the event.
- `onOpenChangeComplete` (`(open: boolean) => void`): Called once the open or close transition has finished.

### DialogTrigger

- `render` (`RenderProp<{ disabled: boolean }>`): Replace the rendered element, e.g. `render={<a href="/settings" />}`, or a function of props and state.
- `disabled` (`boolean`): Native disabled: no pointer events, no tooltip, skipped by Tab.
- `focusableWhenDisabled` (`boolean`): Keep a disabled control focusable and hoverable (`aria-disabled`), so a tooltip can say why.
- `nativeButton` (`boolean`): Button semantics, inferred from what renders: a `<button>` is native, an `<a>` stays a link, anything else gets `role="button"` and key handling. `false` forces button semantics on whatever renders (a link acting as a button).

Rest props go to `<button>` props.

### DialogContent

- `rootStyle` (`RootStyle<DialogKnobs>`)
- `size` (`"sm" | "md" | "lg" | "xl" | "2xl"`)
- `placement` (`"center" | "top"`)
- `showClose` (`boolean`)
- `closeLabel` (`string`)
- `container` (`PortalContainer`): Where a surface's portal mounts. Default: `document.body`. Pass a themed subtree to keep its `data-theme`, or a transformed stage to contain `position: fixed` overlays (previews): a modal set down in one stays in it, shown in place, out of the browser's top layer.
- `initialFocus` (`FocusTarget`): initialFocus / finalFocus: a ref, a boolean, or a function of how the popup was opened.
- `finalFocus` (`FocusTarget`): initialFocus / finalFocus: a ref, a boolean, or a function of how the popup was opened.
- `instant` (`boolean`)

Rest props go to `<div>` props.

### DialogHeader

- `action` (`ReactNode`)

Rest props go to `<div>` props.

### DialogError

- `readout` (`string`)

Rest props go to `<div>` props.

### DialogFooter

- `divided` (`boolean`)

Rest props go to `<div>` props.

### DialogActions

- `aside` (`ReactNode`)

Rest props go to `<div>` props.

### DialogClose

- `render` (`RenderProp<{ disabled: boolean }>`): Replace the rendered element, e.g. `render={<a href="/settings" />}`, or a function of props and state.
- `disabled` (`boolean`): Native disabled: no pointer events, no tooltip, skipped by Tab.
- `focusableWhenDisabled` (`boolean`): Keep a disabled control focusable and hoverable (`aria-disabled`), so a tooltip can say why.
- `nativeButton` (`boolean`): Button semantics, inferred from what renders: a `<button>` is native, an `<a>` stays a link, anything else gets `role="button"` and key handling. `false` forces button semantics on whatever renders (a link acting as a button).

Rest props go to `<button>` props.
