# Alert Dialog
A modal decision; an agent's confirm waits for a person.
Source page: https://dinachi.dev/docs/components/alert-dialog

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

## Usage
```tsx
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"

export function DeleteProject() {
  return (
    <AlertDialog>
      <AlertDialogTrigger render={<Button variant="destructive" />}>
        Delete project
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete this project?</AlertDialogTitle>
          <AlertDialogDescription>This cannot be undone.</AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction>Delete</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
```

## Anatomy
```tsx
<AlertDialog>
  <AlertDialogTrigger />
  <AlertDialogContent>
    <AlertDialogHeader>
      <AlertDialogTitle />
      <AlertDialogDescription />
    </AlertDialogHeader>
    <AlertDialogFooter>
      <AlertDialogCancel />
      <AlertDialogAction />
    </AlertDialogFooter>
  </AlertDialogContent>
</AlertDialog>
```
- `AlertDialog`: Holds the open state. Always modal.
- `AlertDialogTrigger`: The button that opens the dialog.
- `AlertDialogContent`: The portal, backdrop, viewport and popup in one.
- `AlertDialogHeader`: Stacks the title and description.
- `AlertDialogTitle`: The heading; names the dialog.
- `AlertDialogDescription`: Explains the decision.
- `AlertDialogFooter`: Lays out buttons; stacks on small screens.
- `AlertDialogAction`: The confirm button. Closes the dialog.
- `AlertDialogCancel`: The back-out button. Closes the dialog.
- `AlertDialogPopup`: The dialog box, for custom layouts.
- `AlertDialogBackdrop`: The dimmed layer behind the popup.
- `AlertDialogViewport`: Fixed layer that centres the popup.
- `AlertDialogPortal`: Renders its children into the body.

## Examples

### Default
A confirmation before a destructive action.
```tsx
import {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogHeader,
  AlertDialogFooter,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';

export function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger render={<Button variant="destructive" />}>
        Delete Account
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
          <AlertDialogDescription>
            This action cannot be undone. This will permanently delete your account.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction>Continue</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
```

### Controlled
The open state held in React state.
```tsx
import React from 'react';
import {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogHeader,
  AlertDialogFooter,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';

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

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger render={<Button />}>
        Save Changes
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Save Changes?</AlertDialogTitle>
          <AlertDialogDescription>
            You have unsaved changes. Do you want to save them?
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Don't Save</AlertDialogCancel>
          <AlertDialogAction onClick={() => setOpen(false)}>Save</AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
```

## Notes

### Your own layout
`AlertDialogContent` combines `AlertDialogPortal`, `AlertDialogBackdrop`, `AlertDialogViewport` and `AlertDialogPopup`. Compose them directly to change one.

### Dismissal
Backdrop clicks do not close it. Only its buttons or Esc do.

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

### AlertDialog
Holds the open state. Always modal.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `open` | `boolean` | - | Controlled open state. |
| `defaultOpen` | `boolean` | `false` | Starting open state when uncontrolled. |
| `onOpenChange` **agent** | `(open, details) => void` | - | Runs for people and agents. `details.cancel()` refuses the change. |
| `onOpenChangeComplete` | `(open) => void` | - | Runs once the open or close animation ends. |
| `actionsRef` | `RefObject<{ close, unmount }>` | - | Closes the dialog imperatively. |

### AlertDialogTrigger
The button that opens the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element, keep the behaviour. For example `<Button />`. |
| `children` **agent** | `ReactNode` | - | Also the agent's name for it while closed. |

### AlertDialogContent
The portal, backdrop, viewport and popup in one.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `initialFocus` | `boolean \| RefObject \| (openType) => ...` | - | Element focused on open. |
| `finalFocus` | `boolean \| RefObject \| (closeType) => ...` | - | Element focused on close. Defaults to the trigger. |

### AlertDialogHeader
Stacks the title and description.

Takes the props of the element it renders.

### AlertDialogTitle
The heading; names the dialog.

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

### AlertDialogDescription
Explains the decision.

Takes the props of the element it renders.

### AlertDialogFooter
Lays out buttons; stacks on small screens.

Takes the props of the element it renders.

### AlertDialogAction
The confirm button. Closes the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onClick` **agent** | `(event) => void` | - | Do the work here. An agent's press needs a person's approval. |
| `render` | `ReactElement` | - | Swap the element. Drops the default styles. |

### AlertDialogCancel
The back-out button. Closes the dialog.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `render` | `ReactElement` | - | Swap the element. Drops the default styles. |
| `data-agent-confirm` **agent** | `string` | `"none"` | Lets an agent press it without approval. |

### AlertDialogPopup
The dialog box, for custom layouts.

Takes the props of the element it renders.

### AlertDialogBackdrop
The dimmed layer behind the popup.

Takes the props of the element it renders.

### AlertDialogViewport
Fixed layer that centres the popup.

Takes the props of the element it renders.

### AlertDialogPortal
Renders its children into the body.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `keepMounted` | `boolean` | `false` | Keeps the dialog in the DOM while closed. |

## Agent
Inside an `AgentProvider`, Alert Dialog appears in `agent.snapshot()` as `dialog`.
Reads:
- `label`: The trigger's text while closed, the title while open.
- `open`: Whether the dialog is showing.
Actions:
- `open()`: Opens the dialog. Only while closed.
- `close()`: Closes it. Only while open; needs no approval.
Open and close run through `onOpenChange`. `isAgentChange(details)` is true for an agent's change; `details.cancel()` refuses it and the agent is told. While open, every control inside except `AlertDialogCancel` needs a person's approval. Without an allow function on the agent, those presses are refused.
```ts
await agent.act({
  steps: [{ ref: "Delete Account", action: "open" }],
})
```

## Accessibility
- Role alertdialog, labelled by `AlertDialogTitle`, described by `AlertDialogDescription`.
- Focus moves in on open and is trapped until close.
- While open, the page behind is hidden from assistive tech and the agent.
- Focus returns to the trigger on close.
### Keyboard
| Keys | Does |
| --- | --- |
| `Space` / `Enter` | Opens the dialog from the trigger, or presses the focused button |
| `Tab` | Moves focus between controls; focus stays in the dialog |
| `Esc` | Closes the dialog and returns focus to the trigger |

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

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

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

/**
 * Base UI's root, holding its own open state so an agent can open and close it. A press
 * inside needs a person's approval by default; closing it does not.
 */
function AlertDialog<Payload>({ open, defaultOpen, onOpenChange, ...props }: BaseAlertDialog.Root.Props<Payload>) {
  const [state, change, parts] = useAgentOpen("dialog", open, defaultOpen, onOpenChange)
  return (
    <AlertDialogAgentContext.Provider value={useHasAgent() ? parts : null}>
      <BaseAlertDialog.Root<Payload> {...props} open={state} onOpenChange={change} />
    </AlertDialogAgentContext.Provider>
  )
}

function AlertDialogTrigger<Payload>({ ref, ...props }: BaseAlertDialog.Trigger.Props<Payload> & React.RefAttributes<HTMLElement>) {
  const parts = React.useContext(AlertDialogAgentContext)
  return <BaseAlertDialog.Trigger<Payload> ref={useMergedRef(ref, parts?.trigger)} data-slot="alert-dialog-trigger" {...props} />
}
function AlertDialogPortal(props: React.ComponentProps<typeof BaseAlertDialog.Portal>) {
  return <BaseAlertDialog.Portal data-slot="alert-dialog-portal" {...props} />
}

const AlertDialogBackdrop = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseAlertDialog.Backdrop>
>(({ className, ...props }, ref) => (
  <BaseAlertDialog.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="alert-dialog-backdrop"
    {...props}
  />
))
AlertDialogBackdrop.displayName = "AlertDialogBackdrop"

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

const AlertDialogPopup = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseAlertDialog.Popup>
>(({ className, ...props }, ref) => (
  <BaseAlertDialog.Popup
    ref={useMergedRef(ref, React.useContext(AlertDialogAgentContext)?.popup)}
    className={cn(
      "w-[95%] max-w-lg gap-4 rounded-lg border bg-background p-6 shadow-lg",
      // An alert 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="alert-dialog-popup"
    {...props}
  />
))
AlertDialogPopup.displayName = "AlertDialogPopup"

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

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

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

const AlertDialogCancel = React.forwardRef<
  HTMLButtonElement,
  React.ComponentProps<typeof BaseAlertDialog.Close>
>(({ className, render, ...props }, ref) => (
  <BaseAlertDialog.Close
    ref={ref}
    data-agent-confirm="none"
    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="alert-dialog-cancel"
    {...props}
  />
))
AlertDialogCancel.displayName = "AlertDialogCancel"

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

const AlertDialogFooter = ({
  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="alert-dialog-footer"
    {...props}
  />
)
AlertDialogFooter.displayName = "AlertDialogFooter"

const AlertDialogContent = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseAlertDialog.Popup>
>(({ className, children, ...props }, ref) => (
  <AlertDialogPortal>
    <AlertDialogBackdrop />
    <AlertDialogViewport>
      <AlertDialogPopup ref={ref} className={className} data-slot="alert-dialog-content" {...props}>
        {children}
      </AlertDialogPopup>
    </AlertDialogViewport>
  </AlertDialogPortal>
))
AlertDialogContent.displayName = "AlertDialogContent"

export {
  AlertDialog,
  AlertDialogTrigger,
  AlertDialogPortal,
  AlertDialogBackdrop,
  AlertDialogViewport,
  AlertDialogPopup,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogHeader,
  AlertDialogFooter,
  AlertDialogContent,
}
```
