# Dialog

> A modal surface for a focused task that interrupts the page, with header, body and footer parts.

```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'

export function DialogHeroDemo() {
  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Setup checklist</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Get started with Dify</DialogTitle>
          <DialogDescription>
            Complete these steps before publishing your first app.
          </DialogDescription>
          <DialogHeaderCloseButton aria-label="Close dialog" />
        </DialogHeader>
        <DialogBody>
          <ol className="list-inside list-decimal space-y-1.5 system-sm-regular text-text-secondary">
            <li>Connect a model provider</li>
            <li>Import your first knowledge base</li>
            <li>Create an API key for your app</li>
          </ol>
        </DialogBody>
        <DialogFooter>
          <DialogClose render={<Button variant="primary" />}>Got it</DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
```

## Usage guidelines

- Use `Dialog` for modal content that needs focus containment and scroll locking, such as editing settings or collecting short input. Use `AlertDialog` only for a destructive or must-confirm decision, and `Drawer` for a side panel.
- Compose `DialogHeader`, `DialogBody` and `DialogFooter` inside `DialogContent`. The parts own the spacing, and `DialogBody` scrolls between the header and the footer when the surface reaches the viewport height.
- Every dialog has a `DialogTitle`. Add a `DialogDescription` when a sentence of context helps before the user acts.
- Use `DialogHeaderCloseButton` for the standard corner close icon and give it an `aria-label`. Use `DialogClose` with `render` for footer actions such as Cancel.
- Outside-press dismissal is the default. Set `disablePointerDismissal` on the root only when an accidental close would throw away work the user would have to redo.
- Use `DialogTrigger` under the root for a dedicated button. When a trigger lives outside the root or a menu command opens a sibling dialog, connect them with `createDialogHandle`.
- Keep a dialog open while its request is pending only when closing would lose the way to see the outcome or retry. Close it on success and keep it open with the error on failure.

## Anatomy

```tsx
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'
```

```tsx
<Dialog>
  <DialogTrigger />
  <DialogContent>
    <DialogHeader>
      <DialogTitle />
      <DialogDescription />
      <DialogHeaderCloseButton />
    </DialogHeader>
    <DialogBody />
    <DialogFooter>
      <DialogClose />
    </DialogFooter>
  </DialogContent>
</Dialog>
```

`DialogContent` bundles the portal, backdrop and centered popup. `DialogPopup` is the bare dialog element for a surface that places and dresses itself; compose it with `DialogPortal`, `DialogBackdrop` and `DialogViewport`.

## Examples

### Scrolling body

Long content scrolls inside `DialogBody` while the header and footer stay in place.

```tsx title="scrolling-body.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'

const notes = [
  {
    title: 'Parallel branches',
    body: 'Run independent workflow branches at the same time and merge their outputs downstream.',
  },
  {
    title: 'Model fallback',
    body: 'Retry a failed LLM node automatically with a backup provider or smaller model.',
  },
  {
    title: 'Knowledge metadata',
    body: 'Attach custom metadata fields to documents and filter retrieval results per request.',
  },
  {
    title: 'Variable inspector',
    body: 'Inspect and edit node variables directly after a debug run without restarting the graph.',
  },
  {
    title: 'Faster PDF indexing',
    body: 'Large multi-column PDFs parse tables and headings up to twice as fast during ingestion.',
  },
  {
    title: 'Structured output',
    body: 'Validate LLM responses against a JSON schema and expose typed fields to later nodes.',
  },
  {
    title: 'Conversation export',
    body: 'Export filtered chat logs and feedback annotations as CSV from the Logs page.',
  },
  {
    title: 'Plugin sandbox',
    body: 'Custom tools and model plugins run with per-workspace CPU, memory and network limits.',
  },
  {
    title: 'Annotation reply',
    body: 'Match incoming user questions against curated answers before invoking the language model.',
  },
  {
    title: 'Webhook trigger',
    body: 'Start a workflow from an incoming HTTP request with signature verification.',
  },
  {
    title: 'Iteration error handling',
    body: 'Choose whether a failed item stops the iteration, skips the entry or continues with null.',
  },
  {
    title: 'Prompt version history',
    body: 'Compare published prompt revisions side by side and restore any previous snapshot.',
  },
  {
    title: 'Draft autosave',
    body: 'Workflow edits save continuously in the background and warn before overwriting changes.',
  },
  {
    title: 'Hybrid retrieval weights',
    body: 'Tune semantic and keyword score weights independently for each knowledge base.',
  },
  {
    title: 'Streaming code node',
    body: 'Stream incremental chunks from Python and JavaScript nodes into the final answer.',
  },
  {
    title: 'Scoped API keys',
    body: 'Issue separate service keys per environment and revoke compromised keys immediately.',
  },
  {
    title: 'Rate-limit headers',
    body: 'API responses now include remaining quota and reset timestamps for client backoff.',
  },
  {
    title: 'Evaluation datasets',
    body: 'Run regression suites across saved test cases before promoting a workflow to production.',
  },
  {
    title: 'Audit trail export',
    body: 'Workspace owners can export member role changes and key events for compliance review.',
  },
  {
    title: 'Theme support',
    body: 'Switch between light and dark themes or follow your operating system preference.',
  },
]

export function DialogScrollingBodyDemo() {
  return (
    <Dialog>
      <DialogTrigger render={<Button />}>Read release notes</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Release notes</DialogTitle>
          <DialogDescription>
            Highlights across workflows, knowledge bases and plugins.
          </DialogDescription>
          <DialogHeaderCloseButton aria-label="Close dialog" />
        </DialogHeader>
        <DialogBody>
          <ul className="divide-y divide-divider-subtle">
            {notes.map((note) => (
              <li key={note.title} className="py-3 first:pt-0 last:pb-0">
                <h3 className="system-sm-semibold text-text-primary">{note.title}</h3>
                <p className="mt-1 system-sm-regular text-text-secondary">{note.body}</p>
              </li>
            ))}
          </ul>
        </DialogBody>
        <DialogFooter>
          <DialogClose render={<Button variant="primary" />}>Done</DialogClose>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
```

### Closing after a request

Control `open` to close the dialog when an async submission succeeds. While the request is pending, `onOpenChange` cancels dismissal and `DialogHeaderCloseButton` and Cancel stay disabled so the outcome remains visible. A failed request keeps the dialog open with the error and the user's input so they can retry; the first submit on each open fails in this demo.

```tsx title="async-close.tsx"
import { Alert, AlertDescription } from '@langgenius/dify-ui/alert'
import { Button } from '@langgenius/dify-ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldError, 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'

function saveAppName(fail: boolean, signal: AbortSignal) {
  return new Promise<void>((resolve, reject) => {
    const timer = setTimeout(() => {
      if (fail) reject(new Error('Could not save changes. Try again.'))
      else resolve()
    }, 1000)

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

export function DialogAsyncCloseDemo() {
  const [open, setOpen] = React.useState(false)
  const [appName, setAppName] = React.useState('Customer support bot')
  const [error, setError] = React.useState<string | null>(null)
  const [isPending, startTransition] = React.useTransition()
  const controllerRef = React.useRef<AbortController | null>(null)
  const saveLabelId = React.useId()

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

  return (
    <Dialog
      open={open}
      onOpenChange={(nextOpen, details) => {
        if (!nextOpen && isPending) {
          details.cancel()
          return
        }
        setOpen(nextOpen)
      }}
      onOpenChangeComplete={(nextOpen) => {
        if (!nextOpen) setError(null)
      }}
    >
      <DialogTrigger render={<Button />}>Rename app</DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Rename app</DialogTitle>
          <DialogDescription>
            Changes appear across your workspace and service API logs.
          </DialogDescription>
          <DialogHeaderCloseButton aria-label="Close dialog" disabled={isPending} />
        </DialogHeader>
        <Form
          className="contents"
          onFormSubmit={(values) => {
            const nextName = String(values.name ?? '').trim()
            if (!nextName) return
            // The first attempt per open fails so the demo shows the retry path.
            const shouldFail = error === null
            setError(null)
            controllerRef.current?.abort()
            const controller = new AbortController()
            controllerRef.current = controller

            startTransition(async () => {
              try {
                await saveAppName(shouldFail, controller.signal)
                startTransition(() => {
                  setAppName(nextName)
                  setOpen(false)
                })
              } catch (cause) {
                if (cause instanceof DOMException && cause.name === 'AbortError') return
                startTransition(() =>
                  setError(
                    cause instanceof Error ? cause.message : 'Could not save changes. Try again.',
                  ),
                )
              }
            })
          }}
        >
          <DialogBody className="flex flex-col gap-3">
            <Field name="name" disabled={isPending}>
              <FieldLabel>App name</FieldLabel>
              <Input required defaultValue={appName} placeholder="e.g. Research agent" />
              <FieldError match="valueMissing">Enter an app name.</FieldError>
            </Field>
            {error && (
              <Alert type="error">
                <AlertDescription>{error}</AlertDescription>
              </Alert>
            )}
          </DialogBody>
          <DialogFooter>
            <DialogClose render={<Button disabled={isPending} />}>Cancel</DialogClose>
            <Button
              type="submit"
              variant="primary"
              loading={isPending}
              aria-labelledby={saveLabelId}
            >
              <span id={saveLabelId}>{isPending ? 'Saving…' : 'Save'}</span>
            </Button>
          </DialogFooter>
        </Form>
      </DialogContent>
    </Dialog>
  )
}
```

### One dialog for a list of items

A list whose items open the same dialog renders one `Dialog` around the list. Each `DialogTrigger` carries its item as `payload`, and the dialog reads the payload of the trigger that opened it.

```tsx title="payload.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
  DialogTrigger,
} from '@langgenius/dify-ui/dialog'
import * as React from 'react'

type Member = {
  name: string
  email: string
  role: string
  lastActive: string
}

const members: Member[] = [
  { name: 'Ada Lovelace', email: 'ada@example.com', role: 'Owner', lastActive: 'Today' },
  { name: 'Alan Turing', email: 'alan@example.com', role: 'Editor', lastActive: 'Yesterday' },
  { name: 'Grace Hopper', email: 'grace@example.com', role: 'Member', lastActive: '3 days ago' },
]

export function DialogPayloadDemo() {
  const id = React.useId()

  return (
    <Dialog<Member>>
      {({ payload }) => (
        <React.Fragment>
          <ul className="w-full max-w-sm divide-y divide-divider-subtle">
            {members.map((member, index) => (
              <li key={member.email} className="flex items-center gap-3 py-2.5">
                <div className="min-w-0 flex-1">
                  <p
                    id={`${id}-name-${index}`}
                    className="truncate system-sm-medium text-text-primary"
                  >
                    {member.name}
                  </p>
                  <p className="truncate system-xs-regular text-text-tertiary">{member.email}</p>
                </div>
                <DialogTrigger<Member>
                  payload={member}
                  aria-labelledby={`${id}-action-${index} ${id}-name-${index}`}
                  render={<Button size="small" />}
                >
                  <span id={`${id}-action-${index}`}>View</span>
                </DialogTrigger>
              </li>
            ))}
          </ul>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{payload?.name}</DialogTitle>
              <DialogDescription>{payload?.email}</DialogDescription>
              <DialogHeaderCloseButton aria-label="Close dialog" />
            </DialogHeader>
            <DialogBody>
              <dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-2 system-sm-regular">
                <dt className="text-text-tertiary">Role</dt>
                <dd className="text-text-primary">{payload?.role}</dd>
                <dt className="text-text-tertiary">Last active</dt>
                <dd className="text-text-primary">{payload?.lastActive}</dd>
              </dl>
            </DialogBody>
            <DialogFooter>
              <DialogClose render={<Button />}>Close</DialogClose>
            </DialogFooter>
          </DialogContent>
        </React.Fragment>
      )}
    </Dialog>
  )
}
```

### Opening with a handle

Keep a dialog opened by a menu command or a distant trigger as a sibling and connect it with `createDialogHandle`. Calling `open(null)` opens the dialog without controlled `open` state, and focus returns to the menu trigger when it closes.

```tsx title="detached-trigger.tsx"
import { Button } from '@langgenius/dify-ui/button'
import {
  createDialogHandle,
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogHeaderCloseButton,
  DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Menu, MenuContent, MenuItem, MenuSeparator, MenuTrigger } from '@langgenius/dify-ui/menu'
import * as React from 'react'

const dslSnippet = `app:
  name: Customer support bot
  mode: advanced-chat
workflow:
  features:
    retriever_resource:
      enabled: true`

export function DialogDetachedTriggerDemo() {
  const [dslDialog] = React.useState(() => createDialogHandle())

  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 onClick={() => dslDialog.open(null)}>
            <span
              aria-hidden="true"
              className="i-ri-code-s-slash-line size-4 shrink-0 text-text-tertiary"
            />
            View DSL…
          </MenuItem>
        </MenuContent>
      </Menu>
      <Dialog handle={dslDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>App DSL</DialogTitle>
            <DialogDescription>Read-only YAML export for Customer support bot.</DialogDescription>
            <DialogHeaderCloseButton aria-label="Close dialog" />
          </DialogHeader>
          <DialogBody>
            <pre className="overflow-x-auto rounded-lg bg-background-section p-3 font-mono system-xs-regular text-text-secondary">
              {dslSnippet}
            </pre>
          </DialogBody>
          <DialogFooter>
            <DialogClose render={<Button />}>Close</DialogClose>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </React.Fragment>
  )
}
```

## Keyboard

| Key                | Action                                                                                     |
| ------------------ | ------------------------------------------------------------------------------------------ |
| `Enter`, `Space`   | Opens the 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 dialog and returns focus to the trigger.                                        |

## API reference

### Dialog

Groups all parts of a modal dialog. Doesn't render its own HTML element.

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

### DialogBackdrop

An overlay displayed beneath the popup. Renders a `<div>` element.

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

**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.    |

### DialogBody

Accepts the props of the element it renders.

### DialogClose

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

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

**Data attributes**

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

### DialogContent

A centered modal 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. |

### DialogDescription

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).

### DialogFooter

Accepts the props of the element it renders.

### DialogHeader

Accepts the props of the element it renders.

### DialogHeaderCloseButton

An icon close button positioned in the corner of `DialogHeader`, which reserves space for it automatically. Renders a `<button>` element.

**Props**

| Prop         | Type     | Default | Description                                                                                              |
| ------------ | -------- | ------- | -------------------------------------------------------------------------------------------------------- |
| `aria-label` | `string` | —       | Defines a string value that labels the current element. Names the close button for assistive technology. |

Inherits `style`, `nativeButton` from [Base UI Dialog.Close](https://base-ui.com/react/components/dialog#close).

**Data attributes**

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

### DialogPopup

A container for the dialog contents. Renders a `<div>` element.

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. |

### DialogPortal

A portal element that moves the popup to a different part of the DOM. By default, the portal element is appended to `<body>`. Renders a `<div>` element.

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

### DialogTitle

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).

### DialogTrigger

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

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

**Data attributes**

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

### DialogViewport

A positioning container for the dialog popup that can be made scrollable. Renders a `<div>` element.

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

**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. |

### createDialogHandle

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

```ts
createDialogHandle<Payload>(): BaseDialog.Handle<Payload>
```

**Returns:** `BaseDialog.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.                                                                               |
