# Alert Dialog

> A modal confirmation that requires an explicit answer before the user continues.

```tsx title="hero.tsx"
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import {
  AlertDialog,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'

export function AlertDialogHeroDemo() {
  const actionsRef = React.useRef<AlertDialogActions>(null)

  return (
    <AlertDialog actionsRef={actionsRef}>
      <AlertDialogTrigger render={<Button variant="secondary" tone="destructive" />}>
        Delete knowledge base
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete this knowledge base?</AlertDialogTitle>
          <AlertDialogDescription>
            Its documents and embeddings are removed, and apps that retrieve from it stop finding
            results. This cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancelButton>Cancel</AlertDialogCancelButton>
          <AlertDialogConfirmButton onClick={() => actionsRef.current?.close()}>
            Delete
          </AlertDialogConfirmButton>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
```

## Usage guidelines

- Use `AlertDialog` only for a destructive or must-confirm decision that needs an explicit answer. A task, a form or content to read uses `Dialog`.
- Outside presses never dismiss an alert dialog. `Escape` and `AlertDialogCancelButton` still close it; when the answer must be explicit, cancel that close in `onOpenChange`.
- Put the title and description in `AlertDialogHeader`. Anything the user fills in or reviews before answering goes in `AlertDialogBody`.
- Every alert dialog has an `AlertDialogTitle` phrased as the question, which names the dialog. The description states the consequence.
- `AlertDialogConfirmButton` defaults to a primary destructive button and does not close the dialog. Close it from the handler through `actionsRef`, a handle or controlled `open`. Set `tone="default"` for a confirmation that destroys nothing.
- Use `AlertDialogTrigger` under the root for a dedicated button. A menu command opens a sibling alert dialog through a handle, and controlled `open` is for open state another owner must observe.
- Keep the dialog open while its request is pending only when closing would lose the outcome or the way to retry. Close it on success and keep it open with the error on failure.

## Anatomy

```tsx
import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
```

```tsx
<AlertDialog>
  <AlertDialogTrigger />
  <AlertDialogContent>
    <AlertDialogHeader>
      <AlertDialogTitle />
      <AlertDialogDescription />
    </AlertDialogHeader>
    <AlertDialogBody />
    <AlertDialogFooter>
      <AlertDialogCancelButton />
      <AlertDialogConfirmButton />
    </AlertDialogFooter>
  </AlertDialogContent>
</AlertDialog>
```

`AlertDialogContent` bundles the portal, backdrop and centered popup. `AlertDialogCancelButton` and `AlertDialogConfirmButton` render `Button` and take its props.

## Examples

### Typing to confirm

For an irreversible action on a named resource, ask the user to type the name in `AlertDialogBody`. A `Form` with `className="contents"` keeps the body and footer in the surface layout, and the confirm button submits it once the name matches.

```tsx title="type-to-confirm.tsx"
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'

const workspaceName = 'Acme Support'

function WorkspaceNameConfirmation() {
  const [value, setValue] = React.useState('')

  return (
    <React.Fragment>
      <AlertDialogBody>
        <Field name="confirmation">
          <FieldLabel>
            Type <span className="font-semibold text-text-primary">{workspaceName}</span> to confirm
          </FieldLabel>
          <Input
            autoComplete="off"
            placeholder="Case-sensitive"
            spellCheck={false}
            value={value}
            onValueChange={setValue}
          />
        </Field>
      </AlertDialogBody>
      <AlertDialogFooter>
        <AlertDialogCancelButton>Cancel</AlertDialogCancelButton>
        <AlertDialogConfirmButton type="submit" disabled={value !== workspaceName}>
          Delete workspace
        </AlertDialogConfirmButton>
      </AlertDialogFooter>
    </React.Fragment>
  )
}

export function AlertDialogTypeToConfirmDemo() {
  const actionsRef = React.useRef<AlertDialogActions>(null)

  return (
    <AlertDialog actionsRef={actionsRef}>
      <AlertDialogTrigger render={<Button variant="secondary" tone="destructive" />}>
        Delete workspace
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete the {workspaceName} workspace?</AlertDialogTitle>
          <AlertDialogDescription>
            All apps, knowledge bases and members are removed. This cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <Form className="contents" onFormSubmit={() => actionsRef.current?.close()}>
          <WorkspaceNameConfirmation />
        </Form>
      </AlertDialogContent>
    </AlertDialog>
  )
}
```

### Pending request

Control `open` to close the dialog when the request succeeds. While it is pending, `onOpenChange` cancels the close so `Escape` cannot dismiss it, and the confirm button keeps focus with a stable `aria-labelledby` name. A failed request keeps the dialog open with the error in `AlertDialogBody` so the user can retry. In this example, the **Fail the next request** switch makes the next attempt fail and turns itself off, so the retry succeeds.

```tsx title="pending.tsx"
import { Alert, AlertTitle } from '@langgenius/dify-ui/alert'
import {
  AlertDialog,
  AlertDialogBody,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'
import * as React from 'react'

function revokeApiKey(fail: boolean, signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => {
      if (fail) reject(new Error('The request timed out.'))
      else resolve()
    }, 1000)

    signal.addEventListener(
      'abort',
      () => {
        clearTimeout(timer)
        reject(new DOMException('Aborted', 'AbortError'))
      },
      { once: true },
    )
  })
}

export function AlertDialogPendingDemo() {
  const [failNextRequest, setFailNextRequest] = React.useState(true)
  const [open, setOpen] = React.useState(false)
  const [error, setError] = React.useState<string | null>(null)
  const [isPending, startTransition] = React.useTransition()
  const controllerRef = React.useRef<AbortController | null>(null)
  const confirmLabelId = React.useId()

  React.useEffect(() => () => controllerRef.current?.abort(), [])

  return (
    <div className="flex flex-col items-center gap-4">
      <AlertDialog
        open={open}
        onOpenChange={(nextOpen, details) => {
          if (!nextOpen && isPending) details.cancel()
          else setOpen(nextOpen)
        }}
        onOpenChangeComplete={(nextOpen) => {
          if (!nextOpen) setError(null)
        }}
      >
        <AlertDialogTrigger render={<Button variant="secondary" tone="destructive" />}>
          Revoke API key
        </AlertDialogTrigger>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Revoke the production API key?</AlertDialogTitle>
            <AlertDialogDescription>
              Requests signed with this key start failing as soon as it is revoked.
            </AlertDialogDescription>
          </AlertDialogHeader>
          {error && (
            <AlertDialogBody>
              <Alert type="error">
                <AlertTitle>{error} Try again.</AlertTitle>
              </Alert>
            </AlertDialogBody>
          )}
          <AlertDialogFooter>
            <AlertDialogCancelButton disabled={isPending}>Cancel</AlertDialogCancelButton>
            <AlertDialogConfirmButton
              loading={isPending}
              aria-labelledby={confirmLabelId}
              onClick={() => {
                setError(null)
                controllerRef.current?.abort()
                const controller = new AbortController()
                controllerRef.current = controller

                startTransition(async () => {
                  try {
                    await revokeApiKey(failNextRequest, controller.signal)
                    startTransition(() => setOpen(false))
                  } catch (cause) {
                    if (cause instanceof DOMException && cause.name === 'AbortError') return
                    startTransition(() => {
                      setFailNextRequest(false)
                      setError(cause instanceof Error ? cause.message : 'Something went wrong.')
                    })
                  }
                })
              }}
            >
              <span id={confirmLabelId}>{isPending ? 'Revoking…' : 'Revoke'}</span>
            </AlertDialogConfirmButton>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      <Field name="failNextRequest">
        <FieldLabel className="flex items-center gap-2 system-xs-medium text-text-secondary">
          <Switch checked={failNextRequest} onCheckedChange={setFailNextRequest} />
          Fail the next request
        </FieldLabel>
      </Field>
    </div>
  )
}
```

### Opening from a menu command

Keep the menu and the alert dialog as siblings. The menu item calls `open(null)` on the dialog's handle, and focus returns to the menu trigger when the dialog closes.

```tsx title="menu-command.tsx"
import {
  AlertDialog,
  AlertDialogCancelButton,
  AlertDialogConfirmButton,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  createAlertDialogHandle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
import * as React from 'react'

export function AlertDialogMenuCommandDemo() {
  const [deleteDialog] = React.useState(() => createAlertDialogHandle())

  return (
    <React.Fragment>
      <Menu>
        <MenuTrigger
          render={
            <Button className="data-popup-open:bg-components-button-secondary-bg-hover data-popup-open:inset-ring-components-button-secondary-border-hover" />
          }
        >
          App actions
          <span aria-hidden="true" className="i-ri-arrow-down-s-line size-4 text-text-tertiary" />
        </MenuTrigger>
        <MenuContent align="start" className="w-44">
          <MenuItem>
            <span
              aria-hidden="true"
              className="i-ri-edit-line size-4 shrink-0 text-text-tertiary"
            />
            Edit info
          </MenuItem>
          <MenuItem>
            <span
              aria-hidden="true"
              className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary"
            />
            Duplicate
          </MenuItem>
          <MenuSeparator />
          <MenuItem variant="destructive" onClick={() => deleteDialog.open(null)}>
            <span aria-hidden="true" className="i-ri-delete-bin-line size-4 shrink-0" />
            Delete…
          </MenuItem>
        </MenuContent>
      </Menu>
      <AlertDialog handle={deleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete this app?</AlertDialogTitle>
            <AlertDialogDescription>
              The app, its logs and its API access are removed. This cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancelButton>Cancel</AlertDialogCancelButton>
            <AlertDialogConfirmButton onClick={() => deleteDialog.close()}>
              Delete
            </AlertDialogConfirmButton>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </React.Fragment>
  )
}
```

## Keyboard

| Key                    | Action                                                                                      |
| ---------------------- | ------------------------------------------------------------------------------------------- |
| `Enter`, `Space`       | Opens the alert dialog from a focused trigger.                                              |
| `Tab`, `Shift` + `Tab` | Moves focus between the dialog's controls. Focus stays inside the dialog while it is open.  |
| `Escape`               | Closes the alert dialog and returns focus to the trigger, unless `onOpenChange` cancels it. |

## API reference

### AlertDialog

Groups all parts of a confirmation dialog that requires an explicit user response. Doesn't render its own HTML element.

Outside presses do not dismiss it; users close it with Escape, `AlertDialogCancelButton`, or your confirm handler.

Inherits `onOpenChange`, `actionsRef`, `handle`, `open`, `defaultOpen`, `onOpenChangeComplete`, `children`, `triggerId`, `defaultTriggerId` from [Base UI AlertDialog.Root](https://base-ui.com/react/components/alert-dialog#root).

### AlertDialogBody

Accepts the props of the element it renders.

### AlertDialogCancelButton

A button that closes the alert dialog when activated. Renders a `<button>` element.

**Props**

| Prop       | Type                                                                                        | Default       | Description                                                                                                                                                                                                                                                            |
| ---------- | ------------------------------------------------------------------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `size?`    | `'large' \| 'medium' \| 'small'`                                                            | `'medium'`    | The height, padding, and type scale of the button.                                                                                                                                                                                                                     |
| `variant?` | `'ghost' \| 'ghost-accent' \| 'primary' \| 'secondary' \| 'secondary-accent' \| 'tertiary'` | `'secondary'` | The visual emphasis of the button. The accent variants cannot be combined with `tone="destructive"`.                                                                                                                                                                   |
| `tone?`    | `'default' \| 'destructive'`                                                                | `'default'`   | Whether the button represents a destructive action.                                                                                                                                                                                                                    |
| `loading?` | `boolean`                                                                                   | —             | Marks an action as pending, blocks activation, and keeps the button focusable by default. Keep a non-empty visible label. If that label changes while loading, give it a stable ID and reference it with `aria-labelledby` so it remains the explicit accessible name. |

Valid prop combinations:

- `variant?: 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`

Inherits `focusableWhenDisabled`, `className`, `render`, `style`, `nativeButton` from [Base UI Button](https://base-ui.com/react/components/button).

**Data attributes**

| Attribute       | Description                          |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |

### AlertDialogConfirmButton

A confirmation button defaulting to `variant="primary"` and `tone="destructive"` unless an accent variant is specified. Renders a `<button>` element.

Does not close the dialog automatically; close it from your handler via `actionsRef`, a handle, or controlled `open`.

**Props**

| Prop       | Type                                                                                        | Default         | Description                                                                                                                                                                                                                                                            |
| ---------- | ------------------------------------------------------------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `size?`    | `'large' \| 'medium' \| 'small'`                                                            | `'medium'`      | The height, padding, and type scale of the button.                                                                                                                                                                                                                     |
| `loading?` | `boolean`                                                                                   | —               | Marks an action as pending, blocks activation, and keeps the button focusable by default. Keep a non-empty visible label. If that label changes while loading, give it a stable ID and reference it with `aria-labelledby` so it remains the explicit accessible name. |
| `variant?` | `'ghost' \| 'ghost-accent' \| 'primary' \| 'secondary' \| 'secondary-accent' \| 'tertiary'` | `'primary'`     | The visual emphasis of the button. The accent variants cannot be combined with `tone="destructive"`.                                                                                                                                                                   |
| `tone?`    | `'default' \| 'destructive'`                                                                | `'destructive'` | Whether the button represents a destructive action.                                                                                                                                                                                                                    |

Valid prop combinations:

- `variant?: 'ghost' | 'primary' | 'secondary' | 'tertiary'`, `tone?: 'default' | 'destructive'`
- `variant: 'ghost-accent' | 'secondary-accent'`, `tone?: 'default'`

Inherits `className`, `render`, `style`, `nativeButton`, `focusableWhenDisabled` from [Base UI Button](https://base-ui.com/react/components/button).

**Data attributes**

| Attribute       | Description                          |
| --------------- | ------------------------------------ |
| `data-disabled` | Present when the button is disabled. |

### AlertDialogContent

A centered modal alert dialog surface bundled with a portal and backdrop. Renders a `<div>` element.

**Props**

| Prop             | Type                  | Default | Description                                       |
| ---------------- | --------------------- | ------- | ------------------------------------------------- |
| `children`       | `React.ReactNode`     | —       | The dialog content, rendered inside the popup.    |
| `backdropProps?` | `DialogBackdropProps` | —       | Props for the backdrop rendered behind the popup. |

Inherits `className`, `render`, `style`, `initialFocus`, `finalFocus` from [Base UI Dialog.Popup](https://base-ui.com/react/components/dialog#popup).

**Data attributes**

| Attribute                 | Description                                                      |
| ------------------------- | ---------------------------------------------------------------- |
| `data-open`               | Present when the dialog is open.                                 |
| `data-closed`             | Present when the dialog is closed.                               |
| `data-starting-style`     | Present when the dialog begins animating in.                     |
| `data-ending-style`       | Present when the dialog is animating out.                        |
| `data-nested`             | Present when the dialog is nested within another dialog.         |
| `data-nested-dialog-open` | Present when the dialog has other open dialogs nested within it. |

**CSS variables**

| Variable           | Type     | Description                                   |
| ------------------ | -------- | --------------------------------------------- |
| `--nested-dialogs` | `number` | Indicates how many dialogs are nested within. |

### AlertDialogDescription

A paragraph with additional information about the dialog. Renders a `<p>` element.

Inherits `className`, `render`, `style` from [Base UI Dialog.Description](https://base-ui.com/react/components/dialog#description).

### AlertDialogFooter

**Props**

| Prop       | Type                     | Default     | Description                                                |
| ---------- | ------------------------ | ----------- | ---------------------------------------------------------- |
| `spacing?` | `'compact' \| 'default'` | `'default'` | The vertical padding of the footer; `'compact'` uses less. |

### AlertDialogHeader

Accepts the props of the element it renders.

### AlertDialogTitle

A heading that labels the dialog. Renders an `<h2>` element.

Inherits `className`, `render`, `style` from [Base UI Dialog.Title](https://base-ui.com/react/components/dialog#title).

### AlertDialogTrigger

A button that opens the alert dialog. Renders a `<button>` element.

Inherits `handle`, `className`, `render`, `style`, `nativeButton`, `payload`, `id` from [Base UI AlertDialog.Trigger](https://base-ui.com/react/components/alert-dialog#trigger).

**Data attributes**

| Attribute         | Description                                          |
| ----------------- | ---------------------------------------------------- |
| `data-disabled`   | Present when the trigger is disabled.                |
| `data-popup-open` | Present when the corresponding alert dialog is open. |

### createAlertDialogHandle

Creates a new handle to connect an AlertDialog.Root with detached AlertDialog.Trigger components.

```ts
createAlertDialogHandle<Payload>(): BaseAlertDialog.Handle<Payload>
```

**Returns:** `BaseAlertDialog.Handle<Payload>`

**Return properties**

| Member            | Type                                  | Description                                                                                                                                                                  |
| ----------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open`            | `(triggerId: string \| null) => void` | Opens the dialog, optionally associating it with a trigger. This method should only be called in an event handler or an effect (not during rendering).                       |
| `openWithPayload` | `(payload: Payload) => void`          | Opens the dialog with the given payload, without associating it with any trigger. This method should only be called in an event handler or an effect (not during rendering). |
| `close`           | `() => void`                          | Closes the dialog. This method should only be called in an event handler or an effect (not during rendering).                                                                |
| `isOpen`          | `boolean`                             | Whether the dialog is currently open. Returns `false` while no root is attached to the handle.                                                                               |
