# Dialog

> Opens a window over the page for a task or a piece of information that needs focus before the user goes back to the page.

Page: https://design.silkware.dev/docs/components/dialog
shadcn/ui: https://ui.shadcn.com/docs/components/aria/dialog
Primitive: https://react-aria.adobe.com/Modal

Example `components/dialog-demo`:

```tsx
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

export default function DialogDemo() {
  return (
    <DialogTrigger>
      <Button variant="outline">Edit supplier</Button>
      <Dialog>
        <DialogHeader>
          <DialogTitle>Edit supplier</DialogTitle>
          <DialogDescription>
            Update the contact details for Tornival. Purchasing sees the
            change on the next order.
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-4">
          <Field>
            <FieldLabel htmlFor="dialog-demo-name">Supplier name</FieldLabel>
            <Input id="dialog-demo-name" defaultValue="Tornival" />
          </Field>
          <Field>
            <FieldLabel htmlFor="dialog-demo-contact">Contact</FieldLabel>
            <Input id="dialog-demo-contact" defaultValue="Marco" />
          </Field>
        </div>
        <DialogFooter>
          <DialogClose>Cancel</DialogClose>
          <DialogClose variant="default">Save supplier</DialogClose>
        </DialogFooter>
      </Dialog>
    </DialogTrigger>
  )
}
```

## Installation

```bash
pnpm dlx shadcn@latest add @silkware/dialog
```

To copy the component by hand, install its dependencies:

```bash
pnpm add react-aria-components cn lucide-react
```

Then copy the source into `components/ui/dialog.tsx`. It uses the [Button](/docs/components/button) component, so add that first.

Source file: `components/ui/dialog.tsx`. The registry command above copies it into your project.

## Usage

```tsx
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
```

```tsx
<DialogTrigger>
  <Button variant="outline">Edit supplier</Button>
  <Dialog>
    <DialogHeader>
      <DialogTitle>Edit supplier</DialogTitle>
      <DialogDescription>Update the contact details.</DialogDescription>
    </DialogHeader>
    <DialogFooter>
      <DialogClose>Cancel</DialogClose>
    </DialogFooter>
  </Dialog>
</DialogTrigger>
```

`DialogTrigger` takes exactly two children: the pressable trigger first, then the `Dialog`. Components in this set that close the dialog, `DialogClose` and the close button, do so through `slot="close"`, so they must sit inside the `Dialog`. To run your own code when a button is pressed and close the dialog, use controlled state, shown below.

## Examples

### Form

Collect a few fields without leaving the page. Control the open state, so that submitting the form can close the dialog once the data is saved. Give the first field `autoFocus` so focus lands where the user starts typing.

Example `components/dialog-form`:

```tsx
"use client"

import * as React from "react"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Field, FieldLabel } from "@/components/ui/field"
import { Input } from "@/components/ui/input"

export default function DialogForm() {
  const [isOpen, setOpen] = React.useState(false)

  return (
    <DialogTrigger isOpen={isOpen} onOpenChange={setOpen}>
      <Button>New supplier</Button>
      <Dialog>
        <form
          className="grid gap-6"
          onSubmit={(event) => {
            event.preventDefault()
            setOpen(false)
          }}
        >
          <DialogHeader>
            <DialogTitle>New supplier</DialogTitle>
            <DialogDescription>
              Add a supplier to the purchasing list for the Brescia site.
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4">
            <Field>
              <FieldLabel htmlFor="dialog-form-name">Supplier name</FieldLabel>
              <Input id="dialog-form-name" name="name" autoFocus required />
            </Field>
            <Field>
              <FieldLabel htmlFor="dialog-form-email">Contact email</FieldLabel>
              <Input
                id="dialog-form-email"
                name="email"
                type="email"
                required
              />
            </Field>
          </div>
          <DialogFooter>
            <DialogClose>Cancel</DialogClose>
            <Button type="submit">Add supplier</Button>
          </DialogFooter>
        </form>
      </Dialog>
    </DialogTrigger>
  )
}
```

### Controlled

Pass `isOpen` and `onOpenChange` to `DialogTrigger` to open and close the dialog from your own code, for example after a request finishes. Close it from a button with `onPress`.

Example `components/dialog-controlled`:

```tsx
"use client"

import * as React from "react"

import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

export default function DialogControlled() {
  const [isOpen, setOpen] = React.useState(false)
  const [status, setStatus] = React.useState("Waiting for approval")

  return (
    <div className="flex flex-wrap items-center gap-3">
      <DialogTrigger isOpen={isOpen} onOpenChange={setOpen}>
        <Button variant="outline">Review order PO-2041</Button>
        <Dialog>
          <DialogHeader>
            <DialogTitle>Order PO-2041</DialogTitle>
            <DialogDescription>
              40 pallets of sheet steel from Tornival, due at the Brescia
              site on 12 December.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button
              variant="outline"
              onPress={() => {
                setStatus("Sent back to Luca")
                setOpen(false)
              }}
            >
              Send back
            </Button>
            <Button
              onPress={() => {
                setStatus("Approved")
                setOpen(false)
              }}
            >
              Approve order
            </Button>
          </DialogFooter>
        </Dialog>
      </DialogTrigger>
      <p className="text-sm text-muted-foreground">Status: {status}</p>
    </div>
  )
}
```

### Scrollable content

A dialog never grows past the screen. Put long content in a region with a maximum height and `overflow-y-auto`, so that the title and the actions stay in view.

Example `components/dialog-scrollable`:

```tsx
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

const terms = [
  "Delivery is due at the receiving dock of the Brescia site between 7:00 and 15:00 on working days.",
  "Each pallet carries a label with the order number, the lot number and the quantity.",
  "Quality inspects the first pallet of every lot. A failed inspection holds the whole lot.",
  "Invoices quote the order number. Purchasing pays invoices 60 days after the goods are accepted.",
  "A delay of more than two working days is reported to purchasing before the due date.",
  "Damaged goods are returned at the supplier's cost within ten days of delivery.",
  "Price changes apply to new orders only and are agreed in writing with Giulia.",
  "Either side may end the agreement with 90 days' notice.",
]

export default function DialogScrollable() {
  return (
    <DialogTrigger>
      <Button variant="outline">Read delivery terms</Button>
      <Dialog>
        <DialogHeader>
          <DialogTitle>Delivery terms</DialogTitle>
          <DialogDescription>
            Terms that apply to every order from Tornival.
          </DialogDescription>
        </DialogHeader>
        <div className="-mx-6 max-h-[40vh] overflow-y-auto px-6">
          <ol className="grid list-decimal gap-3 pl-5">
            {terms.map((term) => (
              <li key={term}>{term}</li>
            ))}
          </ol>
        </div>
        <DialogFooter>
          <DialogClose variant="default">Close</DialogClose>
        </DialogFooter>
      </Dialog>
    </DialogTrigger>
  )
}
```

### Without the close button

`showCloseButton={false}` removes the cross in the corner. Use it when the footer already has a clear way out. The user can still press Escape or click outside the dialog.

Example `components/dialog-no-close-button`:

```tsx
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

export default function DialogNoCloseButton() {
  return (
    <DialogTrigger>
      <Button variant="outline">Open shift handover</Button>
      <Dialog showCloseButton={false}>
        <DialogHeader>
          <DialogTitle>Shift handover</DialogTitle>
          <DialogDescription>
            Line 3 stopped for a tool change at 13:40. The next shift restarts
            it after the quality check.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose variant="default">Got it</DialogClose>
        </DialogFooter>
      </Dialog>
    </DialogTrigger>
  )
}
```

### Not dismissable

A click outside the dialog closes it by default. Set `isDismissable={false}` to keep it open, and `isKeyboardDismissDisabled` to make Escape do nothing as well. Do this only when the user must choose an action, and then consider an [Alert Dialog](/docs/components/alert-dialog).

Example `components/dialog-not-dismissable`:

```tsx
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogClose,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"

export default function DialogNotDismissable() {
  return (
    <DialogTrigger>
      <Button variant="outline">Sign the quality report</Button>
      <Dialog isDismissable={false} isKeyboardDismissDisabled>
        <DialogHeader>
          <DialogTitle>Sign the quality report</DialogTitle>
          <DialogDescription>
            The report for lot 7731 is final once signed. Choose one of the
            actions to continue.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose>Not now</DialogClose>
          <DialogClose variant="default">Sign report</DialogClose>
        </DialogFooter>
      </Dialog>
    </DialogTrigger>
  )
}
```

## Accessibility

| Keys | Action |
| --- | --- |
| `Tab` | Moves focus to the next control inside the dialog. From the last control it returns to the first. |
| `Shift + Tab` | Moves focus to the previous control inside the dialog. |
| `Esc` | Closes the dialog and returns focus to the trigger, unless isKeyboardDismissDisabled is set. |
| `Space` | Presses the focused button, including the trigger and the close button. |
| `Enter` | Presses the focused button, including the trigger and the close button. |

React Aria provides:

- The `dialog` role on the window, labelled by the `DialogTitle` through the `title` slot.
- Focus that moves into the dialog when it opens, stays inside while it is open and returns to the trigger when it closes.
- Content outside the dialog hidden from screen readers and from the keyboard while the dialog is open, and page scrolling prevented.
- Closing on Escape and on an interaction outside the dialog, with the props above to turn either off.
- The `data-entering` and `data-exiting` states that drive the enter and exit animation.

You provide:

- A `DialogTitle` in every dialog. Without it the dialog has no accessible name.
- A `DialogDescription` that says what the dialog is for, when the title is not enough.
- A label on every control inside the dialog, and an `aria-label` on a trigger that holds only an icon.
- A way to leave: the close button, a Cancel button, or both.

## Guidelines

### When to use

- To complete a short task that needs the user's full attention, such as editing a supplier or adding a note to an order.
- To show a detail that the user asked for and must read before going on, such as delivery terms.
- To ask for a few fields that belong to the page the user is on.

### When not to use

- To ask for confirmation of an action that cannot be undone. Use an [Alert Dialog](/docs/components/alert-dialog), which announces itself as an alert and does not close on an outside click.
- For a longer form or a panel the user may keep open while they look at the page. Use a [Sheet](/docs/components/sheet).
- For a touch-first panel that the user swipes away on a phone. Use a [Drawer](/docs/components/drawer).
- For a small control or a few fields next to the element that opens them. Use a [Popover](/docs/components/popover).
- For a message that needs no decision. Use a toast, or put the message on the page.
- To explain an icon or a button. Use a [Tooltip](/docs/components/tooltip).

### Content

- Write the title as the task, in sentence case with no full stop: "Edit supplier", "Add note".
- Use the description for one or two sentences that say what changes, not to repeat the title.
- Name the buttons after what they do: "Save supplier", "Move delivery". Put the main action last.
- Keep the dialog to one task. If it needs steps or tabs, it is a page.

### Focus and dismissal

A dialog opens above everything and takes focus, so the user must always be able to get out. Keep Escape and the outside click working unless closing would lose work or skip a required choice. When the dialog holds a form with unsaved input, confirm before you throw the input away.

### Actions

  - Do: Title the dialog after the task and name each button after its outcome.
  - Avoid: Don’t ask "Are you sure?" and answer with "Yes" and "No". The user has to guess what each one does.

## API reference

### DialogTrigger

Wraps the trigger and the dialog, and ties them together through the React Aria `DialogTrigger`. It accepts every [React Aria DialogTrigger prop](https://react-aria.adobe.com/Modal#dialogtrigger).

DialogTrigger props:

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `ReactNode` |  | A pressable trigger, then the Dialog. |
| `isOpen?` | `boolean` |  | Whether the dialog is open. Makes the dialog controlled. |
| `defaultOpen?` | `boolean` |  | Whether the dialog is open on first render, when uncontrolled. |
| `onOpenChange?` | `(isOpen: boolean) => void` |  | Called when the dialog opens or closes. |

### Dialog

Renders the overlay, the modal and the dialog through the React Aria [ModalOverlay](https://react-aria.adobe.com/Modal#modaloverlay), `Modal` and `Dialog`. It accepts every ModalOverlay prop and the props below.

Dialog props:

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `showCloseButton?` | `boolean` | `true` | Shows the close button in the top right corner. |
| `isDismissable?` | `boolean` | `true` | Closes the dialog on an interaction outside it. |
| `isKeyboardDismissDisabled?` | `boolean` | `false` | Stops Escape from closing the dialog. |
| `isOpen?` | `boolean` |  | Whether the dialog is open, when you use Dialog without DialogTrigger. |
| `onOpenChange?` | `(isOpen: boolean) => void` |  | Called when the dialog opens or closes. |
| `className?` | `string` |  | Classes merged onto the dialog window. Use it to set the width, for example sm:max-w-lg. |
| `children` | `ReactNode` |  | The dialog content. |

### DialogHeader

A `div` that stacks the title and the description. It accepts every `div` prop.

### DialogTitle

Renders a heading through the React Aria `Heading` with `slot="title"`, which labels the dialog. It accepts every [Heading prop](https://react-aria.adobe.com/Heading) except `slot`.

### DialogDescription

A `div` with muted text. It accepts every `div` prop except `slot`. Links inside it are underlined.

### DialogFooter

A `div` that holds the actions. It stacks them on a phone, with the main action on top, and puts them in a row, aligned to the end, from the `sm` breakpoint.

DialogFooter props:

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `showCloseButton?` | `boolean` | `false` | Adds an outline Close button that closes the dialog. |

### DialogClose

Renders a `Button` with `slot="close"`, so pressing it closes the dialog. It accepts every [Button prop](/docs/components/button#api-reference).

DialogClose props:

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `variant?` | `"default" \| "secondary" \| "outline" \| "ghost" \| "destructive" \| "link"` | `"outline"` | The visual weight of the button. |
| `size?` | `"xs" \| "sm" \| "default" \| "lg" \| "icon-xs" \| "icon-sm" \| "icon" \| "icon-lg"` | `"default"` | The height and padding. |

### DialogOverlay

The dimmed layer behind the dialog, through the React Aria `ModalOverlay`. `Dialog` renders it for you. Use it only to compose a dialog by hand.
