# Toast

> Transient notifications sent from anywhere in the app through a shared manager.

```tsx title="hero.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { Toaster } from '@langgenius/dify-ui/toast'
import * as React from 'react'
import { manager, toast } from './notifications'

export function ToastHeroDemo() {
  const versionRef = React.useRef(0)

  React.useEffect(() => {
    return () => {
      toast.dismiss()
    }
  }, [])

  return (
    <React.Fragment>
      <Toaster toastManager={manager} />
      <Button
        variant="primary"
        onClick={() => {
          versionRef.current += 1
          toast.success(`Workflow v${versionRef.current} published`, {
            description: 'The new version is now serving API requests.',
          })
        }}
      >
        Publish workflow
      </Button>
    </React.Fragment>
  )
}
```

## Usage guidelines

- Use a toast for short-lived feedback on something the user just did or that just happened in the background, such as a save, an export or a failed request with no other place on the page. A status that stays true while the user works on the page is an `Alert`, and a decision the user must answer is an `AlertDialog`.
- Do not use a toast for a form rejection. A field error goes to that field through `Form` `errors`, and a rejection that belongs to no field stays inside the form as an `Alert`.
- Create one manager in a module with `createToastManager()` and export `createToast(manager)` from it. The returned `toast` is a plain function, so event handlers, mutation callbacks and code outside React all call it the same way.
- Render one `Toaster` for that manager near the application root, inside the isolated root element. `Toaster` includes the provider and portals its viewport to `document.body`, so the app needs no other wrapper. It sets the default `timeout` (5000 ms) and the visible stack `limit` (3).
- Create another manager with its own `Toaster` only when a part of the app needs a separate stack, for example a test or an embedded surface. Toasts never cross between managers.
- The title is the message and names the notification for assistive technology; add a `description` only for detail. Every toast has a type that sets its icon and halo.
- A toast closes on its own, so its action must not be the only way to reach that outcome. Use `timeout: 0` for a toast that stays until the user or the code closes it.

## Anatomy

```tsx
import { createToast, createToastManager, Toaster } from '@langgenius/dify-ui/toast'
```

```tsx
// notifications.ts
export const manager = createToastManager()
export const toast = createToast(manager)

// Application root, rendered once
<div className="isolate">
  <Toaster toastManager={manager} />
  {children}
</div>

// Anywhere in the app
toast.success('Workflow published', { description: 'The new version is live.' })
```

`Toaster` renders the cards itself: icon, title, description, an optional action button and a close button. Call sites pass content through the `toast` API rather than composing parts.

> [!NOTE]
> The demos on this page share one manager from a `notifications.ts` module like the one above. The hero demo renders its `Toaster`, standing in for the application root, and the other demos only call `toast`.

## Examples

### Types

`toast.success`, `toast.info`, `toast.warning` and `toast.error` fix the type. The callable form `toast(title, { type })` takes it as an option.

```tsx title="types.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { toast } from './notifications'

export function ToastTypesDemo() {
  return (
    <div className="flex flex-wrap items-center gap-3">
      <Button
        onClick={() => {
          toast.success('Export complete', {
            description: 'Your workflow is ready to download.',
          })
        }}
      >
        Success
      </Button>
      <Button
        onClick={() => {
          toast.info('Workflow restored', {
            description: 'A collaborator restored an earlier version.',
          })
        }}
      >
        Info
      </Button>
      <Button
        onClick={() => {
          toast.warning('Import completed with warnings', {
            description: 'Two unsupported files were skipped.',
          })
        }}
      >
        Warning
      </Button>
      <Button
        onClick={() => {
          toast.error('Export failed', {
            description: 'The storage service is unavailable. Try again later.',
          })
        }}
      >
        Error
      </Button>
    </div>
  )
}
```

### Action

`actionProps` renders one `Button` in the card and accepts its `variant`. The caller closes the original toast when the action completes.

```tsx title="action.tsx"
import { Button } from '@langgenius/dify-ui/button'
import { toast } from './notifications'

function archiveProject() {
  const id = toast.success('Project archived', {
    description: 'You can restore it from the archive at any time.',
    actionProps: {
      children: 'Undo',
      variant: 'secondary-accent',
      onClick: () => {
        toast.dismiss(id)
        toast.success('Project restored')
      },
    },
  })
}

export function ToastActionDemo() {
  return <Button onClick={archiveProject}>Archive project</Button>
}
```

### Promise

`toast.promise` shows a loading toast and updates the same card to success or error when the promise settles. Each state takes a title string or an options object, and the result states can derive it from the resolved value or the error. It returns the original promise, so handle its rejection, and keep the trigger in `loading` until it settles so the action cannot start twice.

```tsx title="promise.tsx"
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { toast } from './notifications'

type ExportOutcome = 'success' | 'failure'

export function ToastPromiseDemo() {
  const [pending, setPending] = React.useState<ExportOutcome | null>(null)
  const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)
  const mountedRef = React.useRef(true)

  React.useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
      if (timerRef.current) clearTimeout(timerRef.current)
    }
  }, [])

  const startExport = (outcome: ExportOutcome) => {
    setPending(outcome)
    const request = new Promise<string>((resolve, reject) => {
      timerRef.current = setTimeout(() => {
        timerRef.current = null
        if (outcome === 'failure') reject(new Error('The storage service is unavailable.'))
        else resolve('customer-support.yml')
      }, 1500)
    })

    toast
      .promise(request, {
        loading: 'Preparing export',
        success: (fileName) => ({
          title: 'Export complete',
          description: `${fileName} is ready to download.`,
        }),
        error: (error) => ({
          title: 'Export failed',
          description: error instanceof Error ? error.message : undefined,
        }),
      })
      .catch(() => undefined)
      .finally(() => {
        if (mountedRef.current) setPending(null)
      })
  }

  return (
    <div className="flex flex-wrap items-center gap-3">
      <Button
        loading={pending === 'success'}
        disabled={pending === 'failure'}
        onClick={() => startExport('success')}
      >
        Export workflow
      </Button>
      <Button
        loading={pending === 'failure'}
        disabled={pending === 'success'}
        onClick={() => startExport('failure')}
      >
        Export with an error
      </Button>
    </div>
  )
}
```

### Updating and dismissing

Every call returns the toast ID. Pass it to `toast.update` to change the card in place, or to `toast.dismiss` to close it; `toast.dismiss()` without an ID closes every toast of the manager. A call with an existing `id` option also updates that card instead of adding another. The queued toast below uses `timeout: 0` and stays; the update passes a `timeout` so the finished card closes on its own.

```tsx title="update.tsx"
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { toast } from './notifications'

type ImportJob = {
  toastId: string
  complete: boolean
}

export function ToastUpdateDemo() {
  const [job, setJob] = React.useState<ImportJob | null>(null)
  const activeToastIdRef = React.useRef<string | null>(null)

  React.useEffect(() => {
    return () => {
      if (activeToastIdRef.current) {
        toast.dismiss(activeToastIdRef.current)
        activeToastIdRef.current = null
      }
    }
  }, [])

  return (
    <div className="flex flex-wrap items-center gap-3">
      <Button
        disabled={job !== null}
        onClick={() => {
          const toastId = toast.info('Import queued', {
            description: 'Records are imported in the background.',
            timeout: 0,
            onClose: () => {
              if (activeToastIdRef.current === toastId) activeToastIdRef.current = null
              setJob(null)
            },
          })
          activeToastIdRef.current = toastId
          setJob({ toastId, complete: false })
        }}
      >
        Queue import
      </Button>
      <Button
        disabled={job === null || job.complete}
        onClick={() => {
          if (!job) return
          toast.update(job.toastId, {
            type: 'success',
            title: 'Import complete',
            description: '128 records imported.',
            timeout: 5000,
          })
          setJob({ ...job, complete: true })
        }}
      >
        Complete import
      </Button>
      <Button
        disabled={job === null}
        onClick={() => {
          if (job) toast.dismiss(job.toastId)
        }}
      >
        Dismiss
      </Button>
    </div>
  )
}
```

## Keyboard

| Key              | Action                                                                                     |
| ---------------- | ------------------------------------------------------------------------------------------ |
| `F6`             | Moves focus to the notifications region while a toast is shown.                            |
| `Tab`            | Moves focus from the region into the front toast, then to its action and close buttons.    |
| `Shift` + `Tab`  | Returns focus from the region to the element that was focused before `F6`.                 |
| `Enter`, `Space` | Activates the focused action or close button.                                              |
| `Escape`         | Closes the toast that contains focus and returns focus to the element focused before `F6`. |

## API reference

### Toaster

Provides the toast context, portaled viewport, and stacked notification cards. Renders a portaled `<div>` viewport.

Pass a manager from `createToastManager()` and trigger notifications via `createToast(manager)`. Users can move focus to the notifications with F6.

**Props**

| Prop           | Type                                                                                                            | Default | Description                                                                               |
| -------------- | --------------------------------------------------------------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------- |
| `toastManager` | `ToastManager`                                                                                                  | —       | The manager from `createToastManager()` that `createToast` adds toasts to.                |
| `offset?`      | `{ right?: Property.Right<string \| number> \| undefined; top?: Property.Top<string \| number> \| undefined; }` | —       | Overrides the distance of the notifications from the top and right edges of the viewport. |

Inherits `timeout`, `limit` from [Base UI Toast.Provider](https://base-ui.com/react/components/toast#provider).

### createToast

Creates the toast API for a manager. Call it with a title and a `type`, or use a shortcut such as `toast.success(title)`.

```ts
createToast(manager: ToastManager): ToastApi
```

**Parameters**

| Parameter | Type           | Description |
| --------- | -------------- | ----------- |
| `manager` | `ToastManager` | —           |

**Returns:** `ToastApi`

**Call signatures**

- `(title: React.ReactNode, options: ToastOptions) => string`

**Return properties**

| Member    | Type                                                                                           | Description                                                                                                                                |
| --------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `success` | `(title: React.ReactNode, options?: TypedToastOptions) => string`                              | Shows a success toast and returns its ID.                                                                                                  |
| `error`   | `(title: React.ReactNode, options?: TypedToastOptions) => string`                              | Shows an error toast and returns its ID.                                                                                                   |
| `warning` | `(title: React.ReactNode, options?: TypedToastOptions) => string`                              | Shows a warning toast and returns its ID.                                                                                                  |
| `info`    | `(title: React.ReactNode, options?: TypedToastOptions) => string`                              | Shows an info toast and returns its ID.                                                                                                    |
| `dismiss` | `(toastId?: string) => void`                                                                   | Closes the toast with the given ID, or every toast when no ID is passed.                                                                   |
| `update`  | `(toastId: string, options: ToastUpdateOptions) => void`                                       | Updates the toast with the given ID.                                                                                                       |
| `promise` | `<Value>(promiseValue: Promise<Value>, options: ToastPromiseOptions<Value>) => Promise<Value>` | Shows a loading toast that becomes a success or error toast when the promise settles. Returns a promise that settles with the same result. |

### createToastManager

Creates a toast manager to pass to both `Toaster` and `createToast`.

```ts
createToastManager(): ToastManager
```

**Returns:** `ToastManager`
