Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(dify-ui): lean on Base UI toast ownership and add Toaster (#43753)

yyh96d14004c849
diff --git a/packages/dify-ui/docs/testing.md b/packages/dify-ui/docs/testing.md
index 76016a9b13a..9c565385497 100644
--- a/packages/dify-ui/docs/testing.md
+++ b/packages/dify-ui/docs/testing.md
@@ -57,22 +57,6 @@ that assert final DOM state. Storybook uses its preview setup and retains real a
A unit test that intentionally asserts animation behavior may set the flag to `false` locally,
but must restore the previous value during cleanup.
-## Failure artifacts
-
-Vitest writes automatic failure screenshots and attachments to its default `.vitest/attachments/`
-directory. Configured browser screenshots and unit Playwright traces use `.vitest-browser/`.
-The failure upload steps in `.github/workflows/web-tests.yml` collect both directories, including
-hidden files, and retain them for seven days.
-
-Read the failing test's log for the screenshot or trace path, then download the matching job's
-artifact: `dify-ui-test-failures` for unit tests or `dify-ui-storybook-test-failures` for Storybook.
-
-```sh
-gh run download <run-id> --repo langgenius/dify --name <artifact-name> --dir <output-dir>
-```
-
-The download preserves `.vitest/attachments/` and `.vitest-browser/` relative to `<output-dir>`.
-
[Browser Mode]: https://vitest.dev/guide/browser
[Storybook Vitest addon]: https://storybook.js.org/docs/writing-tests/integrations/vitest-addon/index
[Vitest projects]: https://vitest.dev/guide/projects.html
diff --git a/packages/dify-ui/src/toast/__tests__/index.spec.tsx b/packages/dify-ui/src/toast/__tests__/index.spec.tsx
index 9cf5de8b106..86219c79bc2 100644
--- a/packages/dify-ui/src/toast/__tests__/index.spec.tsx
+++ b/packages/dify-ui/src/toast/__tests__/index.spec.tsx
@@ -1,43 +1,7 @@
-import type { ToastManager, ToastViewportProps } from '../index'
import * as React from 'react'
import { userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
-import {
- createToast,
- createToastManager,
- ToastCard,
- ToastPortal,
- ToastProvider,
- ToastViewport,
- useToastManager,
-} from '../index'
-
-function ToastCards() {
- const { toasts } = useToastManager<Record<string, never>>()
- return toasts.map((item) => <ToastCard key={item.id} toast={item} />)
-}
-
-function ExampleToastHost({
- manager,
- timeout,
- limit,
- offset,
-}: {
- manager: ToastManager
- timeout?: number
- limit?: number
- offset?: ToastViewportProps['offset']
-}) {
- return (
- <ToastProvider toastManager={manager} timeout={timeout} limit={limit}>
- <ToastPortal>
- <ToastViewport offset={offset}>
- <ToastCards />
- </ToastViewport>
- </ToastPortal>
- </ToastProvider>
- )
-}
+import { createToast, createToastManager, Toaster } from '../index'
const manager = createToastManager()
const toast = createToast(manager)
@@ -62,7 +26,7 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should render a success toast when called through the typed shortcut', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
toast.success('Saved', {
description: 'Your changes are available now.',
@@ -75,13 +39,13 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should keep multiple toast roots mounted in a collapsed stack', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
- toast('First toast')
+ toast.info('First toast')
await expect.element(screen.getByText('First toast')).toBeInTheDocument()
- toast('Second toast')
- toast('Third toast')
+ toast.info('Second toast')
+ toast.info('Third toast')
await expect.element(screen.getByText('Third toast')).toBeInTheDocument()
expect(document.body.querySelectorAll('[role="dialog"]')).toHaveLength(3)
@@ -103,12 +67,12 @@ describe('@langgenius/dify-ui/toast', () => {
>
Underlying action
</button>
- <ExampleToastHost manager={manager} timeout={0} />
+ <Toaster toastManager={manager} timeout={0} />
</React.Fragment>,
)
- toast('Older notification')
- toast('Newest notification')
+ toast.info('Older notification')
+ toast.info('Newest notification')
const newestToast = screen.getByRole('dialog', { name: 'Newest notification' })
await expect.element(newestToast).toBeInTheDocument()
@@ -170,11 +134,11 @@ describe('@langgenius/dify-ui/toast', () => {
height: 20,
}}
/>
- <ExampleToastHost manager={manager} timeout={0} offset={{ top: 120 }} />
+ <Toaster toastManager={manager} timeout={0} offset={{ top: 120 }} />
</React.Fragment>,
)
- toast('Directional notification')
+ toast.info('Directional notification')
const toastDialog = screen.getByRole('dialog', { name: 'Directional notification' })
await expect.element(toastDialog).toBeInTheDocument()
@@ -230,12 +194,12 @@ describe('@langgenius/dify-ui/toast', () => {
height: 20,
}}
/>
- <ExampleToastHost manager={manager} timeout={0} />
+ <Toaster toastManager={manager} timeout={0} />
</React.Fragment>,
)
- toast('Background notification')
- toast('Front notification')
+ toast.info('Background notification')
+ toast.info('Front notification')
const backgroundToast = screen.getByRole('dialog', { name: 'Background notification' })
await expect.element(backgroundToast).toBeInTheDocument()
@@ -258,12 +222,14 @@ describe('@langgenius/dify-ui/toast', () => {
}
})
- it('should render a neutral toast when called directly', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ it('should render the type passed to the callable API', async () => {
+ const screen = await render(<Toaster toastManager={manager} />)
- toast('Neutral toast')
+ toast('Typed toast', { type: 'warning' })
- await expect.element(screen.getByText('Neutral toast')).toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('dialog', { name: 'Typed toast' }))
+ .toHaveAttribute('data-type', 'warning')
})
it('should isolate toasts between managers', async () => {
@@ -271,8 +237,8 @@ describe('@langgenius/dify-ui/toast', () => {
const localToast = createToast(localManager)
const screen = await render(
<React.Fragment>
- <ExampleToastHost manager={manager} />
- <ExampleToastHost manager={localManager} />
+ <Toaster toastManager={manager} />
+ <Toaster toastManager={localManager} />
</React.Fragment>,
)
@@ -293,9 +259,9 @@ describe('@langgenius/dify-ui/toast', () => {
it('should apply custom positioning to the viewport', async () => {
const localManager = createToastManager()
const localToast = createToast(localManager)
- const screen = await render(<ExampleToastHost manager={localManager} offset={{ top: 80 }} />)
+ const screen = await render(<Toaster toastManager={localManager} offset={{ top: 80 }} />)
- localToast('Positioned viewport')
+ localToast.info('Positioned viewport')
const viewport = screen.getByRole('region', { name: 'Notifications' })
await expect.element(screen.getByText('Positioned viewport')).toBeInTheDocument()
@@ -307,19 +273,19 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should mark overflow toasts as limited when the stack exceeds the configured limit', async () => {
- const screen = await render(<ExampleToastHost manager={manager} limit={1} />)
+ const screen = await render(<Toaster toastManager={manager} limit={1} />)
- toast('First toast')
- toast('Second toast')
+ toast.info('First toast')
+ toast.info('Second toast')
await expect.element(screen.getByText('Second toast')).toBeInTheDocument()
expect(document.body.querySelector('[data-limited]')).toBeInTheDocument()
})
it('should dismiss a toast when dismiss(id) is called', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
- const toastId = toast('Closable', {
+ const toastId = toast.info('Closable', {
description: 'This toast can be removed.',
})
@@ -334,9 +300,9 @@ describe('@langgenius/dify-ui/toast', () => {
it('should close a toast when the dismiss button is clicked', async () => {
const onClose = vi.fn()
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
- toast('Dismiss me', {
+ toast.info('Dismiss me', {
description: 'Manual dismissal path.',
onClose,
})
@@ -391,11 +357,11 @@ describe('@langgenius/dify-ui/toast', () => {
>
Underlying action
</button>
- <ExampleToastHost manager={manager} />
+ <Toaster toastManager={manager} />
</React.Fragment>,
)
- toast('Dismiss me', {
+ toast.info('Dismiss me', {
timeout: 0,
})
@@ -436,9 +402,9 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should pass the host timeout to added toasts', async () => {
- const screen = await render(<ExampleToastHost manager={manager} timeout={1000} />)
+ const screen = await render(<Toaster toastManager={manager} timeout={1000} />)
- toast('Auto dismiss')
+ toast.info('Auto dismiss')
await expect.element(screen.getByText('Auto dismiss')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(999)
@@ -452,9 +418,9 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should keep a toast persistent when its timeout is zero', async () => {
- const screen = await render(<ExampleToastHost manager={manager} timeout={1000} />)
+ const screen = await render(<Toaster toastManager={manager} timeout={1000} />)
- toast('Persistent', {
+ toast.info('Persistent', {
timeout: 0,
})
@@ -465,7 +431,7 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should update an existing toast', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
const toastId = toast.info('Loading', {
description: 'Preparing your data…',
@@ -484,9 +450,9 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should upsert an existing toast when add is called with the same id', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
- toast('Draft saving', {
+ toast.info('Draft saving', {
id: 'draft-save-status',
description: 'Saving changes…',
})
@@ -507,9 +473,9 @@ describe('@langgenius/dify-ui/toast', () => {
it('should render and invoke toast action props', async () => {
const onAction = vi.fn()
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
- toast('Action toast', {
+ toast.info('Action toast', {
actionProps: {
children: 'Undo',
onClick: onAction,
@@ -523,7 +489,7 @@ describe('@langgenius/dify-ui/toast', () => {
})
it('should transition a promise toast from loading to success', async () => {
- const screen = await render(<ExampleToastHost manager={manager} />)
+ const screen = await render(<Toaster toastManager={manager} />)
let resolvePromise: ((value: string) => void) | undefined
const promise = new Promise<string>((resolve) => {
@@ -540,7 +506,7 @@ describe('@langgenius/dify-ui/toast', () => {
error: 'Failed',
})
- await expect.element(screen.getByText('Saving…')).toBeInTheDocument()
+ await expect.element(screen.getByRole('dialog', { name: 'Saving…' })).toBeInTheDocument()
resolvePromise?.('Your changes are available now.')
await promise
@@ -548,4 +514,19 @@ describe('@langgenius/dify-ui/toast', () => {
await expect.element(screen.getByText('Saved')).toBeInTheDocument()
await expect.element(screen.getByText('Your changes are available now.')).toBeInTheDocument()
})
+
+ it('should use a string promise result as the toast title', async () => {
+ const screen = await render(<Toaster toastManager={manager} />)
+
+ await toast
+ .promise(Promise.reject(new Error('Denied')), {
+ loading: 'Uploading…',
+ success: 'Uploaded',
+ error: (error) => (error as Error).message,
+ })
+ .catch(() => undefined)
+
+ await expect.element(screen.getByRole('dialog', { name: 'Denied' })).toBeInTheDocument()
+ expect(document.body.querySelectorAll('[role="dialog"]')).toHaveLength(1)
+ })
})
diff --git a/packages/dify-ui/src/toast/index.stories.tsx b/packages/dify-ui/src/toast/index.stories.tsx
index 1d792668f8c..2831f351ef2 100644
--- a/packages/dify-ui/src/toast/index.stories.tsx
+++ b/packages/dify-ui/src/toast/index.stories.tsx
@@ -1,45 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react-vite'
-import type { ToastManager, ToastViewportProps } from '.'
import * as React from 'react'
import { expect, within } from 'storybook/test'
-import {
- createToast,
- createToastManager,
- ToastCard,
- ToastPortal,
- ToastProvider,
- ToastViewport,
- useToastManager,
-} from '.'
+import { createToast, createToastManager, Toaster } from '.'
import { Button } from '../button'
-function ToastCards() {
- const { toasts } = useToastManager<Record<string, never>>()
- return toasts.map((item) => <ToastCard key={item.id} toast={item} />)
-}
-
-function ExampleToastHost({
- manager,
- timeout,
- limit,
- offset,
-}: {
- manager: ToastManager
- timeout?: number
- limit?: number
- offset?: ToastViewportProps['offset']
-}) {
- return (
- <ToastProvider toastManager={manager} timeout={timeout} limit={limit}>
- <ToastPortal>
- <ToastViewport offset={offset}>
- <ToastCards />
- </ToastViewport>
- </ToastPortal>
- </ToastProvider>
- )
-}
-
const manager = createToastManager()
const toast = createToast(manager)
@@ -368,7 +332,7 @@ function UpdateExamples() {
function ToastDocsDemo() {
return (
<React.Fragment>
- <ExampleToastHost manager={manager} />
+ <Toaster toastManager={manager} />
<div className="min-h-screen bg-background-default-subtle px-6 py-12">
<div className="mx-auto flex w-full max-w-6xl flex-col gap-8">
<div className="space-y-3">
diff --git a/packages/dify-ui/src/toast/index.tsx b/packages/dify-ui/src/toast/index.tsx
index b8f5689b6c1..ae740328321 100644
--- a/packages/dify-ui/src/toast/index.tsx
+++ b/packages/dify-ui/src/toast/index.tsx
@@ -12,44 +12,10 @@ import { cn } from '../cn'
import { iconButtonVariants } from '../icon-button/variants'
type ToastData = Record<string, never>
-type ToastToneStyle = {
- gradientClassName: string
- iconClassName: string
-}
-
-const TOAST_TONE_STYLES = {
- loading: {
- iconClassName: 'i-ri-loader-2-line animate-spin text-text-accent motion-reduce:animate-none',
- gradientClassName:
- 'from-components-badge-status-light-normal-halo to-background-gradient-mask-transparent',
- },
- success: {
- iconClassName: 'i-ri-checkbox-circle-fill text-text-success',
- gradientClassName:
- 'from-components-badge-status-light-success-halo to-background-gradient-mask-transparent',
- },
- error: {
- iconClassName: 'i-ri-error-warning-fill text-text-destructive',
- gradientClassName:
- 'from-components-badge-status-light-error-halo to-background-gradient-mask-transparent',
- },
- warning: {
- iconClassName: 'i-ri-alert-fill text-text-warning-secondary',
- gradientClassName:
- 'from-components-badge-status-light-warning-halo to-background-gradient-mask-transparent',
- },
- info: {
- iconClassName: 'i-ri-information-2-fill text-text-accent',
- gradientClassName:
- 'from-components-badge-status-light-normal-halo to-background-gradient-mask-transparent',
- },
-} satisfies Record<string, ToastToneStyle>
+// `loading` is reserved for `promise`, which resolves it into `success` or `error`.
+type ToastType = 'success' | 'error' | 'warning' | 'info'
const toastCloseLabel = 'Close notification'
-const toastViewportLabel = 'Notifications'
-
-type ToastRenderType = keyof typeof TOAST_TONE_STYLES
-type ToastType = Exclude<ToastRenderType, 'loading'>
type ToastAddOptions = Omit<
ToastManagerAddOptions<ToastData>,
@@ -65,8 +31,9 @@ type ToastUpdateOptions = Omit<
type?: ToastType
}
-type ToastOptions = Omit<ToastAddOptions, 'title'>
-type TypedToastOptions = Omit<ToastOptions, 'type'>
+// Every toast carries a tone: the callable form takes it as an option, the shortcuts fix it.
+type TypedToastOptions = Omit<ToastAddOptions, 'title' | 'type'>
+type ToastOptions = TypedToastOptions & { type: ToastType }
type ToastPromiseResultOption<Value> =
| string
@@ -85,25 +52,22 @@ type ToastCardProps = {
children?: React.ReactNode
}
-type ToastViewportProps = {
- offset?: ToastHostOffset
- children: React.ReactNode
-}
-
-const ToastProvider = BaseToast.Provider
-type ToastProviderProps = BaseToast.Provider.Props
-const ToastPortal = BaseToast.Portal
-type ToastPortalProps = BaseToast.Portal.Props
-const useToastManager = BaseToast.useToastManager
+type ToasterOffset = Pick<React.CSSProperties, 'top' | 'right'>
-type ToastHostOffset = Pick<React.CSSProperties, 'top' | 'right'>
+// `children` fills the viewport and defaults to a `ToastCard` per toast; compose `useToasts` to
+// customize it.
+type ToasterProps = Pick<BaseToast.Provider.Props, 'timeout' | 'limit'> &
+ Pick<BaseToast.Viewport.Props, 'children'> & {
+ toastManager: ToastManager
+ offset?: ToasterOffset
+ }
type ToastDismiss = (toastId?: string) => void
-type ToastCall = (title: React.ReactNode, options?: ToastOptions) => string
+type ToastCall = (title: React.ReactNode, options: ToastOptions) => string
type TypedToastCall = (title: React.ReactNode, options?: TypedToastOptions) => string
type ToastApi = {
- (title: React.ReactNode, options?: ToastOptions): string
+ (title: React.ReactNode, options: ToastOptions): string
success: TypedToastCall
error: TypedToastCall
warning: TypedToastCall
@@ -118,12 +82,15 @@ type ToastApi = {
type ToastManager = BaseToastManager<ToastData>
-function isToastRenderType(type: string): type is ToastRenderType {
- return Object.prototype.hasOwnProperty.call(TOAST_TONE_STYLES, type)
+// Base UI reads a bare string as the description; this API reads it as the title.
+function toTitleOptions(option: string | ToastUpdateOptions): ToastUpdateOptions {
+ return typeof option === 'string' ? { title: option } : option
}
-function getToastRenderType(type?: string): ToastRenderType | undefined {
- return type && isToastRenderType(type) ? type : undefined
+function toTitleResultOption<Value>(option: ToastPromiseResultOption<Value>) {
+ return typeof option === 'function'
+ ? (value: Value) => toTitleOptions(option(value))
+ : toTitleOptions(option)
}
function createToast(manager: ToastManager): ToastApi {
@@ -154,7 +121,12 @@ function createToast(manager: ToastManager): ToastApi {
const promiseToast = <Value,>(
promiseValue: Promise<Value>,
options: ToastPromiseOptions<Value>,
- ) => manager.promise(promiseValue, options)
+ ) =>
+ manager.promise(promiseValue, {
+ loading: toTitleOptions(options.loading),
+ success: toTitleResultOption(options.success),
+ error: toTitleResultOption(options.error),
+ })
return Object.assign(showToast, {
success: createTypedToast('success'),
@@ -171,20 +143,7 @@ function createToastManager(): ToastManager {
return BaseToast.createToastManager<ToastData>()
}
-function ToastIcon({ type }: { type?: ToastRenderType }) {
- return type ? (
- <span aria-hidden="true" className={cn('h-5 w-5', TOAST_TONE_STYLES[type].iconClassName)} />
- ) : null
-}
-
-function getToneGradientClasses(type?: ToastRenderType) {
- if (type) return TOAST_TONE_STYLES[type].gradientClassName
- return 'from-background-default-subtle to-background-gradient-mask-transparent'
-}
-
function ToastCard({ toast: toastItem, children }: ToastCardProps) {
- const toastType = getToastRenderType(toastItem.type)
-
return (
<BaseToast.Root
toast={toastItem}
@@ -199,7 +158,7 @@ function ToastCard({ toast: toastItem, children }: ToastCardProps) {
'data-ending-style:pointer-events-none data-ending-style:transform-[translateY(-150%)] data-ending-style:opacity-0 data-ending-style:after:pointer-events-none',
'data-ending-style:data-[swipe-direction=up]:transform-[translateY(calc(var(--toast-swipe-movement-y)-150%))]',
'data-ending-style:data-[swipe-direction=right]:transform-[translateX(calc(var(--toast-swipe-movement-x)+150%))_translateY(var(--toast-expanded-offset-y))]',
- 'data-limited:pointer-events-none data-limited:opacity-0 data-starting-style:transform-[translateY(-150%)] data-starting-style:opacity-0',
+ 'data-limited:opacity-0 data-starting-style:transform-[translateY(-150%)] data-starting-style:opacity-0',
"after:pointer-events-auto after:absolute after:bottom-full after:left-0 after:h-[calc(var(--toast-gap)+1px)] after:w-full after:content-['']",
)}
>
@@ -207,37 +166,38 @@ function ToastCard({ toast: toastItem, children }: ToastCardProps) {
<div
aria-hidden="true"
className={cn(
- 'absolute -inset-px bg-linear-to-r opacity-40',
- getToneGradientClasses(toastType),
+ 'absolute -inset-px bg-linear-to-r to-background-gradient-mask-transparent opacity-40',
+ 'group-data-[type=loading]/toast:from-components-badge-status-light-normal-halo',
+ 'group-data-[type=info]/toast:from-components-badge-status-light-normal-halo',
+ 'group-data-[type=success]/toast:from-components-badge-status-light-success-halo',
+ 'group-data-[type=warning]/toast:from-components-badge-status-light-warning-halo',
+ 'group-data-[type=error]/toast:from-components-badge-status-light-error-halo',
)}
/>
<BaseToast.Content className="relative flex items-start gap-1 overflow-hidden p-3 transition-opacity duration-200 data-behind:opacity-0 data-expanded:opacity-100 motion-reduce:transition-none">
<div className="flex shrink-0 items-center justify-center p-0.5">
- <ToastIcon type={toastType} />
+ <span
+ aria-hidden="true"
+ className={cn(
+ // Each tone sets its own size: the icon utility carries a 1rem size that only a
+ // utility under the same variant overrides.
+ 'group-data-[type=loading]/toast:i-ri-loader-2-line group-data-[type=loading]/toast:size-5 group-data-[type=loading]/toast:animate-spin group-data-[type=loading]/toast:text-text-accent motion-reduce:animate-none',
+ 'group-data-[type=info]/toast:i-ri-information-2-fill group-data-[type=info]/toast:size-5 group-data-[type=info]/toast:text-text-accent',
+ 'group-data-[type=success]/toast:i-ri-checkbox-circle-fill group-data-[type=success]/toast:size-5 group-data-[type=success]/toast:text-text-success',
+ 'group-data-[type=warning]/toast:i-ri-alert-fill group-data-[type=warning]/toast:size-5 group-data-[type=warning]/toast:text-text-warning-secondary',
+ 'group-data-[type=error]/toast:i-ri-error-warning-fill group-data-[type=error]/toast:size-5 group-data-[type=error]/toast:text-text-destructive',
+ )}
+ />
</div>
<div className="min-w-0 flex-1 p-1">
- <div className="flex w-full min-w-0 items-center gap-1">
- {toastItem.title != null && (
- <BaseToast.Title className="min-w-0 flex-1 system-sm-semibold wrap-break-word text-text-primary">
- {toastItem.title}
- </BaseToast.Title>
+ <BaseToast.Title className="min-w-0 system-sm-semibold wrap-break-word text-text-primary" />
+ <BaseToast.Description className="mt-1 min-w-0 system-xs-regular wrap-break-word text-text-secondary" />
+ <BaseToast.Action
+ className={cn(
+ 'mt-2 mb-1 flex w-fit items-center justify-center overflow-hidden rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 py-2 system-sm-medium text-components-button-secondary-text shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]',
+ 'hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
)}
- </div>
- {toastItem.description != null && (
- <BaseToast.Description className="mt-1 min-w-0 system-xs-regular wrap-break-word text-text-secondary">
- {toastItem.description}
- </BaseToast.Description>
- )}
- {toastItem.actionProps && (
- <div className="flex w-full items-start gap-1 pt-2 pb-1">
- <BaseToast.Action
- className={cn(
- 'inline-flex items-center justify-center overflow-hidden rounded-md border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 py-2 system-sm-medium text-components-button-secondary-text shadow-xs shadow-shadow-shadow-3 backdrop-blur-[5px]',
- 'hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
- )}
- />
- </div>
- )}
+ />
</div>
{children}
<div className="flex shrink-0 items-center justify-center rounded-md p-0.5">
@@ -245,7 +205,7 @@ function ToastCard({ toast: toastItem, children }: ToastCardProps) {
aria-label={toastCloseLabel}
className={cn(
iconButtonVariants({ size: 'sm' }),
- 'focus-visible:bg-state-base-hover disabled:cursor-not-allowed disabled:opacity-50',
+ 'focus-visible:bg-state-base-hover',
)}
>
<span aria-hidden="true" className="i-ri-close-line size-4 text-text-tertiary" />
@@ -257,33 +217,36 @@ function ToastCard({ toast: toastItem, children }: ToastCardProps) {
)
}
-function ToastViewport({ offset, children }: ToastViewportProps) {
- return (
- <BaseToast.Viewport
- aria-label={toastViewportLabel}
- className="group/toast-viewport pointer-events-none fixed top-4 right-4 z-60 w-90 max-w-[calc(100vw-2rem)] overflow-visible sm:right-8"
- style={offset}
- >
- {children}
- </BaseToast.Viewport>
- )
+function useToasts(): ToastObject<ToastData>[] {
+ return BaseToast.useToastManager<ToastData>().toasts
}
-export {
- createToast,
- createToastManager,
- ToastCard,
- ToastPortal,
- ToastProvider,
- ToastViewport,
- useToastManager,
+function ToastCards() {
+ const toasts = useToasts()
+ return toasts.map((item) => <ToastCard key={item.id} toast={item} />)
}
-export type {
- ToastApi,
- ToastCardProps,
- ToastManager,
- ToastPortalProps,
- ToastProviderProps,
- ToastViewportProps,
+function Toaster({
+ toastManager,
+ timeout,
+ limit,
+ offset,
+ children = <ToastCards />,
+}: ToasterProps) {
+ return (
+ <BaseToast.Provider toastManager={toastManager} timeout={timeout} limit={limit}>
+ <BaseToast.Portal>
+ <BaseToast.Viewport
+ className="pointer-events-none fixed top-4 right-4 z-60 w-90 max-w-[calc(100vw-2rem)] overflow-visible sm:right-8"
+ style={offset}
+ >
+ {children}
+ </BaseToast.Viewport>
+ </BaseToast.Portal>
+ </BaseToast.Provider>
+ )
}
+
+export { createToast, createToastManager, ToastCard, Toaster, useToasts }
+
+export type { ToastApi, ToastCardProps, ToasterProps, ToastManager, ToastType }
diff --git a/web/app/components/plugins/install-plugin/hooks.ts b/web/app/components/plugins/install-plugin/hooks.ts
index ffcb2b4441a..9761560c5a0 100644
--- a/web/app/components/plugins/install-plugin/hooks.ts
+++ b/web/app/components/plugins/install-plugin/hooks.ts
@@ -1,3 +1,4 @@
+import type { ToastType } from '@langgenius/dify-ui/toast'
import type { GitHubRepoReleaseResponse } from '../types'
import { toast } from '@/app/notifications'
import { uploadGitHub } from '@/service/plugins'
@@ -40,7 +41,7 @@ export const checkForUpdates = (
currentVersion: string,
) => {
let needUpdate = false
- const toastProps: { type?: 'success' | 'error' | 'info' | 'warning'; message: string } = {
+ const toastProps: { type: ToastType; message: string } = {
type: 'info',
message: 'No new version available',
}
diff --git a/web/app/components/share/text-generation/index.tsx b/web/app/components/share/text-generation/index.tsx
index 7fb76acfd0a..f39a6877250 100644
--- a/web/app/components/share/text-generation/index.tsx
+++ b/web/app/components/share/text-generation/index.tsx
@@ -1,4 +1,5 @@
'use client'
+import type { ToastType } from '@langgenius/dify-ui/toast'
import type { FC } from 'react'
import type { InputValueTypes, TextGenerationRunControl } from './types'
import type { VisionFile } from '@/types/app'
@@ -37,12 +38,9 @@ const TextGeneration: FC<IMainProps> = ({ isInstalledApp = false, isWorkflow = f
const [resultExisted, setResultExisted] = useState(false)
const [isShowResultPanel, { setTrue: showResultPanelState, setFalse: hideResultPanel }] =
useBoolean(false)
- const notify = useCallback(
- ({ type, message }: { type: 'error' | 'info' | 'success' | 'warning'; message: string }) => {
- toast(message, { type })
- },
- [],
- )
+ const notify = useCallback(({ type, message }: { type: ToastType; message: string }) => {
+ toast(message, { type })
+ }, [])
const updateInputs = useCallback((newInputs: Record<string, InputValueTypes>) => {
setInputs(newInputs)
inputsRef.current = newInputs
diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsx
index 7b7aa9751e8..0605f55374e 100644
--- a/web/app/components/share/text-generation/result/index.tsx
+++ b/web/app/components/share/text-generation/result/index.tsx
@@ -1,4 +1,5 @@
'use client'
+import type { ToastType } from '@langgenius/dify-ui/toast'
import type { FC } from 'react'
import type { PromptConfig } from '@/models/debug'
import type { SiteInfo } from '@/models/share'
@@ -73,12 +74,9 @@ const Result: FC<IResultProps> = ({
hideInlineStopButton = false,
}) => {
const { t } = useTranslation(['share', 'appDebug', 'common'])
- const notify = useCallback(
- ({ type, message }: { type: 'error' | 'info' | 'success' | 'warning'; message: string }) => {
- toast(message, { type })
- },
- [],
- )
+ const notify = useCallback(({ type, message }: { type: ToastType; message: string }) => {
+ toast(message, { type })
+ }, [])
const runState = useResultRunState({
appId,
appSourceType,
diff --git a/web/app/notifications/__tests__/toast.spec.tsx b/web/app/notifications/__tests__/toast.spec.tsx
index 97bfe785c92..00b69731f26 100644
--- a/web/app/notifications/__tests__/toast.spec.tsx
+++ b/web/app/notifications/__tests__/toast.spec.tsx
@@ -177,16 +177,16 @@ it('retains a caller action across upserts and promise failure', async () => {
})
.catch(() => {})
})
- const failedToast = screen.getByRole('dialog', { name: 'Loading' })
+ const failedToast = screen.getByRole('dialog', { name: 'Failed' })
await user.click(
within(failedToast).getByRole('button', { name: 'common.operation.copyErrorDetails' }),
)
- expect(copy).toHaveBeenCalledWith('Loading\nFailed')
+ expect(copy).toHaveBeenCalledWith('Failed')
await user.click(screen.getByRole('button', { name: 'Details' }))
expect(retry).toHaveBeenCalledTimes(2)
})
-it('copies the resolved string description without retaining loading text', async () => {
+it('copies the resolved string title without retaining loading text', async () => {
const { toast, user } = setup()
await act(async () => {
await toast
@@ -198,7 +198,7 @@ it('copies the resolved string description without retaining loading text', asyn
.catch(() => {})
})
expect(screen.queryByText('Loading')).not.toBeInTheDocument()
- expect(screen.queryByRole('heading')).not.toBeInTheDocument()
+ expect(screen.getByRole('heading', { name: 'Failed' })).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.copyErrorDetails' }))
expect(copy).toHaveBeenCalledWith('Failed')
})
diff --git a/web/app/notifications/host.tsx b/web/app/notifications/host.tsx
index 2b337465aef..d5f3677f29a 100644
--- a/web/app/notifications/host.tsx
+++ b/web/app/notifications/host.tsx
@@ -1,13 +1,7 @@
'use client'
-import type { ToastManager, ToastViewportProps } from '@langgenius/dify-ui/toast'
-import {
- ToastCard,
- ToastPortal,
- ToastProvider,
- ToastViewport,
- useToastManager,
-} from '@langgenius/dify-ui/toast'
+import type { ToasterProps, ToastManager } from '@langgenius/dify-ui/toast'
+import { ToastCard, Toaster, useToasts } from '@langgenius/dify-ui/toast'
import { manager } from '.'
import { CopyErrorAction } from './copy-error-action'
@@ -15,11 +9,11 @@ export type AppToastHostProps = {
manager?: ToastManager
timeout?: number
limit?: number
- offset?: ToastViewportProps['offset']
+ offset?: ToasterProps['offset']
}
function Notifications() {
- const { toasts } = useToastManager<Record<string, never>>()
+ const toasts = useToasts()
return toasts.map((item) => {
const parts = [item.title, item.description]
const text = parts.every((part) => part == null || typeof part === 'string')
@@ -40,12 +34,8 @@ export function AppToastHost({
offset,
}: AppToastHostProps) {
return (
- <ToastProvider toastManager={toastManager} timeout={timeout} limit={limit}>
- <ToastPortal>
- <ToastViewport offset={offset}>
- <Notifications />
- </ToastViewport>
- </ToastPortal>
- </ToastProvider>
+ <Toaster toastManager={toastManager} timeout={timeout} limit={limit} offset={offset}>
+ <Notifications />
+ </Toaster>
)
}
diff --git a/web/app/notifications/notifications.stories.tsx b/web/app/notifications/notifications.stories.tsx
index 41f76b18d1d..c5707dea4b7 100644
--- a/web/app/notifications/notifications.stories.tsx
+++ b/web/app/notifications/notifications.stories.tsx
@@ -1,46 +1,11 @@
-import type { ToastApi, ToastManager, ToastViewportProps } from '@langgenius/dify-ui/toast'
+import type { ToastApi } from '@langgenius/dify-ui/toast'
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import {
- createToast,
- createToastManager,
- ToastCard,
- ToastPortal,
- ToastProvider,
- ToastViewport,
- useToastManager,
-} from '@langgenius/dify-ui/toast'
+import { createToast, createToastManager, Toaster } from '@langgenius/dify-ui/toast'
import { useState } from 'react'
import { expect, spyOn, userEvent, within } from 'storybook/test'
import { toast as globalToast } from '.'
import { AppToastHost } from './host'
-function ToastCards() {
- const { toasts } = useToastManager<Record<string, never>>()
- return toasts.map((item) => <ToastCard key={item.id} toast={item} />)
-}
-
-function ExampleToastHost({
- manager,
- timeout,
- limit,
- offset,
-}: {
- manager: ToastManager
- timeout?: number
- limit?: number
- offset?: ToastViewportProps['offset']
-}) {
- return (
- <ToastProvider toastManager={manager} timeout={timeout} limit={limit}>
- <ToastPortal>
- <ToastViewport offset={offset}>
- <ToastCards />
- </ToastViewport>
- </ToastPortal>
- </ToastProvider>
- )
-}
-
type Scenario = { label: string; run: (toast: ToastApi) => void }
type PlaygroundProps = {
description: string
@@ -98,7 +63,7 @@ function Playground({
/>
</label>
{primitive ? (
- <ExampleToastHost manager={manager} timeout={timeout} limit={limit} />
+ <Toaster toastManager={manager} timeout={timeout} limit={limit} />
) : (
<AppToastHost manager={manager} timeout={timeout} limit={limit} />
)}
@@ -120,9 +85,8 @@ type Story = StoryObj<typeof meta>
export const Tones: Story = {
args: {
description:
- 'Only error notifications gain an automatic copy action. Plain, success, warning, and info retain the primitive appearance.',
+ 'Only error notifications gain an automatic copy action. Success, warning, and info retain the primitive appearance.',
scenarios: [
- { label: 'Plain', run: (toast) => toast('New activity') },
{
label: 'Success',
run: (toast) => toast.success('Saved', { description: 'Your changes are available.' }),