# Dialog
A modal window over the page.
Source page: https://dinachi.dev/docs/components/dialog

## Installation
```bash
npx @dinachi/cli@latest add dialog
```
Adds to your project:
- `components/ui/dialog/dialog.tsx`
- `components/ui/dialog/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

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

export function RenameProject() {
  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Rename project</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename project</DialogTitle>
          <DialogDescription>The new name shows everywhere at once.</DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose>Cancel</DialogClose>
          <Button>Save</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
```

## Anatomy
```tsx
<Dialog>
  <DialogTrigger />
  <DialogContent>
    <DialogHeader>
      <DialogTitle />
      <DialogDescription />
    </DialogHeader>
    <DialogFooter>
      <DialogClose />
    </DialogFooter>
  </DialogContent>
</Dialog>
```
- `Dialog`: Holds the open state.
- `DialogTrigger`: The button that opens the dialog.
- `DialogContent`: Portal, backdrop, viewport and popup in one.
- `DialogTitle`: The heading that names the dialog.
- `DialogDescription`: Supporting text, announced with the title.
- `DialogClose`: An outline button that closes the dialog.
- `DialogHeader`: Stacks the title and description.
- `DialogFooter`: Actions: stacked, then a row from sm.
- `DialogPortal`: Renders its children into the body.
- `DialogBackdrop`: The dimmed layer behind the popup.
- `DialogViewport`: A fixed, scrollable layer that centres the popup.
- `DialogPopup`: The window, for composing layers yourself.

## Examples

### Default
A header, two fields and footer actions.
```tsx
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Open Dialog</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Edit Profile</DialogTitle>
          <DialogDescription>
            Make changes to your profile here. Click save when you're done.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <label htmlFor="name" className="text-sm font-medium">Name</label>
            <input id="name" defaultValue="John Doe" className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" />
          </div>
          <div className="space-y-2">
            <label htmlFor="username" className="text-sm font-medium">Username</label>
            <input id="username" defaultValue="@johndoe" className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" />
          </div>
        </div>
        <DialogFooter>
          <DialogClose>Cancel</DialogClose>
          <Button>Save changes</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

### Controlled
Hold the open state to close it from your own button.
```tsx
import React from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';

export function Example() {
  const [open, setOpen] = React.useState(false);

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger render={<Button variant="destructive" />}>Delete Item</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Confirm Deletion</DialogTitle>
          <DialogDescription>
            Are you sure you want to delete this item? This action cannot be undone.
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <DialogClose>Cancel</DialogClose>
          <Button variant="destructive" onClick={() => setOpen(false)}>
            Delete
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

### Nested
A dialog that opens another on top.
```tsx
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
  DialogClose,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

export function Example() {
  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Edit Settings</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Account Settings</DialogTitle>
          <DialogDescription>
            Manage your account preferences.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-4 py-4">
          <div className="space-y-2">
            <label htmlFor="display-name" className="text-sm font-medium">Display name</label>
            <Input id="display-name" defaultValue="John Doe" />
          </div>
          <div className="space-y-2">
            <label htmlFor="email" className="text-sm font-medium">Email</label>
            <Input id="email" defaultValue="john@example.com" />
          </div>
        </div>
        <DialogFooter>
          <Dialog>
            <DialogTrigger render={<Button variant="destructive" />}>
              Delete Account
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Are you absolutely sure?</DialogTitle>
                <DialogDescription>
                  This will permanently delete your account and all associated data. This action cannot be undone.
                </DialogDescription>
              </DialogHeader>
              <DialogFooter>
                <DialogClose>Go Back</DialogClose>
                <Button variant="destructive">Yes, Delete</Button>
              </DialogFooter>
            </DialogContent>
          </Dialog>
          <DialogClose>Cancel</DialogClose>
          <Button>Save Changes</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

### With form
Inputs, a select, radios and a checkbox inside a modal.
```tsx
import React from 'react';
import {
  Dialog, DialogContent, DialogHeader, DialogTitle,
  DialogDescription, DialogFooter, DialogClose, DialogTrigger,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Radio, RadioGroup } from '@/components/ui/radio';
import { Checkbox } from '@/components/ui/checkbox';

export function Example() {
  const [severity, setSeverity] = React.useState("medium");

  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Create Rule</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Create Monitoring Rule</DialogTitle>
          <DialogDescription>
            Configure a rule to trigger notifications for important events.
          </DialogDescription>
        </DialogHeader>
        <div className="space-y-5 py-4">
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <label htmlFor="rule-name" className="text-sm font-medium uppercase tracking-wide">Name</label>
              <Input id="rule-name" placeholder="Ex: NVDA" />
            </div>
            <div className="space-y-2">
              <label className="text-sm font-medium uppercase tracking-wide">Condition</label>
              <Select defaultValue="volatility">
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                {/* portal={false} keeps the dropdown inside the dialog focus trap */}
                <SelectContent portal={false}>
                  <SelectItem value="price-above">Price above</SelectItem>
                  <SelectItem value="price-below">Price below</SelectItem>
                  <SelectItem value="volatility">Volatility</SelectItem>
                  <SelectItem value="volume-spike">Volume spike</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium uppercase tracking-wide">Severity</label>
            <RadioGroup value={severity} onValueChange={(value) => setSeverity(value as string)} className="grid grid-cols-3 gap-3">
              {["low", "medium", "high"].map((value) => (
                <label
                  key={value}
                  className="flex cursor-pointer items-center gap-2 rounded-md border border-input px-3 py-2.5 text-sm has-checked:border-primary has-checked:bg-primary/5"
                >
                  <Radio value={value} />
                  <span className="capitalize">{value}</span>
                </label>
              ))}
            </RadioGroup>
          </div>
          <div className="space-y-2">
            <label className="text-sm font-medium uppercase tracking-wide">Notify via</label>
            <div className="grid grid-cols-3 gap-3">
              {[{ label: "Slack", defaultChecked: true }, { label: "Email", defaultChecked: true }, { label: "SMS", defaultChecked: false }].map((ch) => (
                <label
                  key={ch.label}
                  className="flex cursor-pointer items-center gap-2 rounded-md border border-input px-3 py-2.5 text-sm has-checked:border-primary has-checked:bg-primary/5"
                >
                  <Checkbox defaultChecked={ch.defaultChecked} />
                  <span>{ch.label}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="space-y-2">
            <label htmlFor="rule-notes" className="text-sm font-medium uppercase tracking-wide">Notes</label>
            <Textarea id="rule-notes" placeholder="Alert context, owner, and escalation path..." rows={3} />
          </div>
        </div>
        <DialogFooter>
          <DialogClose>Cancel</DialogClose>
          <Button>Save Rule</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

## Notes

### Composing the layers
`DialogContent` is `DialogPortal`, `DialogBackdrop`, `DialogViewport` and `DialogPopup` stacked in that order. Compose them yourself to style or drop a layer; the agent still finds the popup.

### Popups inside a dialog
A Select inside a dialog renders its list in place by default, so it stays inside the dialog's focus trap and stacking. The **With form** example composes Input, Select, Radio, Checkbox and Textarea this way.

## API reference
Props marked **agent** change what an agent reads or may do.

### Dialog
Holds the open state.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | - | Controlled open state. |
| `defaultOpen` | `boolean` | `false` | Starting open state when uncontrolled. |
| `onOpenChange` **agent** | `(open, details) => void` | - | Runs on open or close, for people and agents. `details.cancel()` refuses it. |
| `modal` | `boolean \| "trap-focus"` | `true` | Traps focus, locks page scroll and blocks outside clicks. `trap-focus` only traps focus. |
| `disablePointerDismissal` | `boolean` | `false` | Keeps the dialog open on an outside click. |
| `onOpenChangeComplete` | `(open) => void` | - | Runs once the open or close animation finishes. |

### DialogTrigger
The button that opens the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element, keep the behaviour. |
| `children` **agent** | `ReactNode` | - | Also the agent's label while closed. |

### DialogContent
Portal, backdrop, viewport and popup in one.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `initialFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on open. Passed to the popup. |
| `finalFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on close. Passed to the popup. |

### DialogTitle
The heading that names the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Also the agent's label while open. |

### DialogDescription
Supporting text, announced with the title.

Takes the props of the element it renders.

### DialogClose
An outline button that closes the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element. Built-in styles are dropped. |

### DialogHeader
Stacks the title and description.

Takes the props of the element it renders.

### DialogFooter
Actions: stacked, then a row from sm.

Takes the props of the element it renders.

### DialogPortal
Renders its children into the body.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keepMounted` | `boolean` | `false` | Keeps the popup in the DOM while closed. |
| `container` | `HTMLElement \| RefObject` | - | Where to portal. Defaults to the body. |

### DialogBackdrop
The dimmed layer behind the popup.

Takes the props of the element it renders.

### DialogViewport
A fixed, scrollable layer that centres the popup.

Takes the props of the element it renders.

### DialogPopup
The window, for composing layers yourself.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `initialFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on open. |
| `finalFocus` | `boolean \| RefObject \| (type) => element` | - | Where focus goes on close. |

## Agent
Inside an `AgentProvider`, Dialog appears in `agent.snapshot()` as `dialog`.
Reads:
- `label`: The `DialogTitle` while open. The trigger's name while closed, or while open with no title.
- `open`: Whether the dialog is showing. Open dialogs are listed first.
Actions:
- `open()`: While closed. act returns the opened dialog under `appeared`.
- `close()`: While open.
An agent's open or close runs through `onOpenChange`. `isAgentChange(details)` is true for it; `details.cancel()` refuses it and tells the agent. Controls inside report the dialog's title as `in`.
```ts
await agent.act({
  steps: [{ ref: "Open Dialog", action: "open" }],
})
```

## Accessibility
- The popup is a dialog named by `DialogTitle` and described by `DialogDescription`.
- Give every dialog a `DialogTitle`; the agent reads the same name.
- While modal, focus is trapped and the page behind is inert.
- Focus returns to the trigger on close, unless `finalFocus` says otherwise.
- Reduced motion turns the animation into a fade.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens the dialog from the trigger |
| `Tab` | Moves focus, kept inside the dialog while modal |
| `Esc` | Closes and returns focus to the trigger |

## Source
`components/ui/dialog/dialog.tsx`
```tsx
"use client"

import * as React from "react"
import { Dialog as BaseDialog } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { type AgentOpenParts, useAgentOpen, useHasAgent, useMergedRef } from "@/components/ui/agent"

const DialogAgentContext = React.createContext<AgentOpenParts | null>(null)

/**
 * Base UI's root, holding its own open state so an agent can open and close it the way a
 * parent would. Controlled use is unchanged, and `onOpenChange` sees the agent's changes
 * first and can cancel them. Closed, the agent sees the trigger; open, the popup.
 */
function Dialog<Payload>({ open, defaultOpen, onOpenChange, ...props }: BaseDialog.Root.Props<Payload>) {
  const [state, change, parts] = useAgentOpen("dialog", open, defaultOpen, onOpenChange)
  return (
    <DialogAgentContext.Provider value={useHasAgent() ? parts : null}>
      <BaseDialog.Root<Payload> {...props} open={state} onOpenChange={change} />
    </DialogAgentContext.Provider>
  )
}

function DialogTrigger<Payload>({ ref, ...props }: BaseDialog.Trigger.Props<Payload> & React.RefAttributes<HTMLElement>) {
  const dialog = React.useContext(DialogAgentContext)
  return <BaseDialog.Trigger<Payload> ref={useMergedRef(ref, dialog?.trigger)} data-slot="dialog-trigger" {...props} />
}

function DialogPortal(props: React.ComponentProps<typeof BaseDialog.Portal>) {
  return <BaseDialog.Portal data-slot="dialog-portal" {...props} />
}

const DialogBackdrop = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseDialog.Backdrop>
>(({ className, ...props }, ref) => (
  <BaseDialog.Backdrop
    ref={ref}
    className={cn(
      "fixed inset-0 z-50 bg-black/80",
      "data-[starting-style]:opacity-0 data-[ending-style]:opacity-0",
      "transition-opacity duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      "data-[ending-style]:duration-[var(--motion-duration-fast,150ms)]",
      className
    )}
    data-slot="dialog-backdrop"
    {...props}
  />
))
DialogBackdrop.displayName = "DialogBackdrop"

const DialogViewport = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseDialog.Viewport>
>(({ className, ...props }, ref) => (
  <BaseDialog.Viewport
    ref={ref}
    className={cn(
      "fixed inset-0 z-50 flex items-center justify-center overflow-auto",
      className
    )}
    data-slot="dialog-viewport"
    {...props}
  />
))
DialogViewport.displayName = "DialogViewport"

const DialogPopup = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseDialog.Popup>
>(({ className, ...props }, ref) => {
  const dialog = React.useContext(DialogAgentContext)
  const mergedRef = useMergedRef(ref, dialog?.popup)
  return (
  <BaseDialog.Popup
    ref={mergedRef}
    className={cn(
      "w-[95%] max-w-lg gap-4 rounded-lg border bg-background p-6 shadow-lg",
      // A dialog is not anchored to its trigger, so scaling from the centre is correct
      // here in a way it is not for a popover.
      "data-[starting-style]:scale-95 data-[starting-style]:opacity-0",
      "data-[ending-style]:scale-95 data-[ending-style]:opacity-0",
      "motion-reduce:data-[starting-style]:scale-100 motion-reduce:data-[ending-style]:scale-100",
      "transition-[transform,scale,opacity] duration-[var(--motion-duration-base,200ms)] ease-[var(--motion-ease-out,cubic-bezier(0.23,1,0.32,1))]",
      // Slower in than out. The user is deciding on the way in and has already decided
      // on the way out.
      "data-[ending-style]:duration-[var(--motion-duration-fast,150ms)]",
      className
    )}
    data-slot="dialog-popup"
    {...props}
  />
  )
})
DialogPopup.displayName = "DialogPopup"

const DialogTitle = React.forwardRef<
  HTMLHeadingElement,
  React.ComponentProps<typeof BaseDialog.Title>
>(({ className, ...props }, ref) => (
  <BaseDialog.Title
    ref={ref}
    className={cn("text-lg font-medium leading-none tracking-tight", className)}
    data-slot="dialog-title"
    {...props}
  />
))
DialogTitle.displayName = "DialogTitle"

const DialogDescription = React.forwardRef<
  HTMLParagraphElement,
  React.ComponentProps<typeof BaseDialog.Description>
>(({ className, ...props }, ref) => (
  <BaseDialog.Description
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    data-slot="dialog-description"
    {...props}
  />
))
DialogDescription.displayName = "DialogDescription"

const DialogClose = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof BaseDialog.Close>
>(({ className, render, ...props }, ref) => (
  <BaseDialog.Close
    ref={ref}
    render={render}
    className={
      render
        ? className
        : cn(
            "inline-flex h-10 items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium shadow-sm transition-colors",
            "hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
            "disabled:cursor-not-allowed disabled:opacity-50",
            className,
          )
    }
    data-slot="dialog-close"
    {...props}
  />
))
DialogClose.displayName = "DialogClose"

const DialogHeader = ({
  className,
  ...props
}: React.HTMLAttributes<HTMLDivElement>) => (
  <div
    className={cn(
      "flex flex-col space-y-1.5 text-center sm:text-left",
      className
    )}
    data-slot="dialog-header"
    {...props}
  />
)
DialogHeader.displayName = "DialogHeader"

const DialogFooter = ({
  className,
  ...props
}: React.HTMLAttributes<HTMLDivElement>) => (
  <div
    className={cn(
      "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end mt-1.5",
      className
    )}
    data-slot="dialog-footer"
    {...props}
  />
)
DialogFooter.displayName = "DialogFooter"

const DialogContent = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseDialog.Popup>
>(({ className, children, ...props }, ref) => (
  <DialogPortal>
    <DialogBackdrop />
    <DialogViewport>
      <DialogPopup ref={ref} className={className} data-slot="dialog-content" {...props}>
        {children}
      </DialogPopup>
    </DialogViewport>
  </DialogPortal>
))
DialogContent.displayName = "DialogContent"

export {
  Dialog,
  DialogTrigger,
  DialogPortal,
  DialogBackdrop,
  DialogViewport,
  DialogPopup,
  DialogTitle,
  DialogDescription,
  DialogClose,
  DialogHeader,
  DialogFooter,
  DialogContent,
}
```
