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(web): scope attachment previews and Blob resources to dialogs (#43521)

yyh47ef377b08d0
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 636761089af..fb206a5c209 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -880,25 +880,17 @@
"count": 1
}
},
- "web/app/components/base/file-uploader/audio-preview.tsx": {
- "jsx-a11y/media-has-caption": {
- "count": 1
- }
- },
"web/app/components/base/file-uploader/file-list-in-log.tsx": {
"eslint-react/no-missing-key": {
"count": 1
}
},
- "web/app/components/base/file-uploader/file-uploader-in-attachment/file-item.tsx": {
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
+ "web/app/components/base/file-uploader/file-preview-content.tsx": {
+ "jsx-a11y/media-has-caption": {
+ "count": 2
}
},
- "web/app/components/base/file-uploader/file-uploader-in-chat-input/file-item.tsx": {
+ "web/app/components/base/file-uploader/file-uploader-in-attachment/file-item.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
},
@@ -934,11 +926,6 @@
"count": 3
}
},
- "web/app/components/base/file-uploader/video-preview.tsx": {
- "jsx-a11y/media-has-caption": {
- "count": 1
- }
- },
"web/app/components/base/form/components/base/base-form.tsx": {
"typescript/no-explicit-any": {
"count": 6
diff --git a/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx
deleted file mode 100644
index f462c3ccd0a..00000000000
--- a/web/app/components/base/file-uploader/__tests__/audio-preview.spec.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import AudioPreview from '../audio-preview'
-
-describe('AudioPreview', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render audio element with correct source', () => {
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />,
- )
-
- const audio = document.querySelector('audio')
- expect(audio).toBeInTheDocument()
- expect(audio).toHaveAttribute('title', 'Test Audio')
- expect(audio?.parentElement).not.toHaveAttribute('aria-label')
- })
-
- it('should render source element with correct src and type', () => {
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />,
- )
-
- const source = document.querySelector('source')
- expect(source).toHaveAttribute('src', 'https://example.com/audio.mp3')
- expect(source).toHaveAttribute('type', 'audio/mpeg')
- })
-
- it('should render close button with icon', () => {
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />,
- )
-
- expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()
- })
-
- it('should call onCancel when close button is clicked', () => {
- const onCancel = vi.fn()
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={onCancel} />,
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(onCancel).toHaveBeenCalled()
- })
-
- it('should not close when audio content is clicked', () => {
- const onCancel = vi.fn()
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={onCancel} />,
- )
-
- const audio = document.querySelector('audio')
- expect(audio).toBeInTheDocument()
- fireEvent.click(audio!)
-
- expect(onCancel).not.toHaveBeenCalled()
- })
-
- it('should call onCancel when Escape key is pressed', () => {
- const onCancel = vi.fn()
-
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={onCancel} />,
- )
-
- fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
-
- expect(onCancel).toHaveBeenCalled()
- })
-
- it('should render in a portal attached to document.body', () => {
- render(
- <AudioPreview url="https://example.com/audio.mp3" title="Test Audio" onCancel={vi.fn()} />,
- )
-
- const audio = document.querySelector('audio')
- expect(audio?.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
- })
-})
diff --git a/web/app/components/base/file-uploader/__tests__/dynamic-pdf-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/dynamic-pdf-preview.spec.tsx
deleted file mode 100644
index 1e788dd98f8..00000000000
--- a/web/app/components/base/file-uploader/__tests__/dynamic-pdf-preview.spec.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import DynamicPdfPreview from '../dynamic-pdf-preview'
-
-type DynamicPdfPreviewProps = {
- url: string
- onCancel: () => void
-}
-
-type DynamicLoader = () => Promise<unknown>
-type DynamicOptions = {
- ssr?: boolean
-}
-
-const mockState = vi.hoisted(() => ({
- loader: undefined as DynamicLoader | undefined,
- options: undefined as DynamicOptions | undefined,
-}))
-
-const mockDynamicRender = vi.hoisted(() => vi.fn())
-
-const mockDynamic = vi.hoisted(() =>
- vi.fn((loader: DynamicLoader, options: DynamicOptions) => {
- mockState.loader = loader
- mockState.options = options
-
- const MockDynamicPdfPreview = ({ url, onCancel }: DynamicPdfPreviewProps) => {
- mockDynamicRender({ url, onCancel })
- return (
- <button data-testid="dynamic-pdf-preview" data-url={url} onClick={onCancel}>
- Dynamic PDF Preview
- </button>
- )
- }
-
- return MockDynamicPdfPreview
- }),
-)
-
-const mockPdfPreview = vi.hoisted(() => vi.fn(() => null))
-
-vi.mock('next/dynamic', () => ({
- default: mockDynamic,
-}))
-
-vi.mock('../pdf-preview', () => ({
- default: mockPdfPreview,
-}))
-
-describe('dynamic-pdf-preview', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should configure next/dynamic with ssr disabled', () => {
- expect(mockState.loader).toEqual(expect.any(Function))
- expect(mockState.options).toEqual({ ssr: false })
- })
-
- it('should render the dynamic component and forward props', () => {
- const onCancel = vi.fn()
- render(<DynamicPdfPreview url="https://example.com/test.pdf" onCancel={onCancel} />)
-
- const trigger = screen.getByTestId('dynamic-pdf-preview')
- expect(trigger).toHaveAttribute('data-url', 'https://example.com/test.pdf')
- expect(mockDynamicRender).toHaveBeenCalledWith({
- url: 'https://example.com/test.pdf',
- onCancel,
- })
-
- fireEvent.click(trigger)
- expect(onCancel).toHaveBeenCalledTimes(1)
- })
-
- it('should return pdf-preview module when loader is executed in browser-like environment', async () => {
- const loaded = mockState.loader?.()
- expect(loaded).toBeInstanceOf(Promise)
-
- const loadedModule = (await loaded) as { default: unknown }
- const pdfPreviewModule = await import('../pdf-preview')
- expect(loadedModule.default).toBe(pdfPreviewModule.default)
- })
-})
diff --git a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
index b950b0b34ad..7560f7e16da 100644
--- a/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
+++ b/web/app/components/base/file-uploader/__tests__/pdf-preview.spec.tsx
@@ -1,6 +1,16 @@
import type { ReactNode } from 'react'
-import { fireEvent, render, screen } from '@testing-library/react'
-import PdfPreview from '../pdf-preview'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { TransferMethod } from '@/types/app'
+import { FileItem } from '../file-uploader-in-chat-input/file-item'
+
+let mockBasePath = ''
+vi.mock('@/utils/var', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/utils/var')>()),
+ get basePath() {
+ return mockBasePath
+ },
+}))
vi.mock('../pdf-highlighter-adapter', () => ({
PdfLoader: ({
@@ -10,165 +20,85 @@ vi.mock('../pdf-highlighter-adapter', () => ({
}: {
children: (doc: unknown) => ReactNode
beforeLoad: ReactNode
- workerSrc?: string
+ workerSrc: string
}) => (
<div data-testid="pdf-loader" data-worker-src={workerSrc}>
{beforeLoad}
{children({ numPages: 1 })}
</div>
),
- PdfHighlighter: ({
- enableAreaSelection,
- highlightTransform,
- scrollRef,
- onScrollChange,
- onSelectionFinished,
- }: {
- enableAreaSelection?: (event: MouseEvent) => boolean
- highlightTransform?: () => ReactNode
- scrollRef?: (ref: unknown) => void
- onScrollChange?: () => void
- onSelectionFinished?: () => unknown
- }) => {
- enableAreaSelection?.(new MouseEvent('click'))
- highlightTransform?.()
- scrollRef?.(null)
- onScrollChange?.()
- onSelectionFinished?.()
- return <div data-testid="pdf-highlighter" />
- },
+ PdfHighlighter: () => <div>PDF page</div>,
}))
-describe('PdfPreview', () => {
- const mockOnCancel = vi.fn()
-
- const getScaleContainer = () => {
- const container = document.querySelector('div[style*="transform"]') as HTMLDivElement | null
- expect(container).toBeInTheDocument()
- return container!
- }
-
- const getControl = (rightClass: 'right-24' | 'right-16' | 'right-6') => {
- const control = document.querySelector(
- `button.absolute.${rightClass}.top-6`,
- ) as HTMLButtonElement | null
- expect(control).toBeInTheDocument()
- return control!
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- window.innerWidth = 1024
- fireEvent(window, new Event('resize'))
- })
-
- it('should render the pdf preview portal with overlay and loading indicator', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- expect(screen.getByRole('dialog', { name: 'workflow.common.preview' })).toBeInTheDocument()
- expect(document.querySelector('[tabindex="-1"]')).toBeInTheDocument()
- expect(getScaleContainer()).not.toHaveAttribute('aria-label')
- expect(screen.getByTestId('pdf-loader')).toBeInTheDocument()
- expect(screen.getByTestId('pdf-highlighter')).toBeInTheDocument()
- expect(screen.getByRole('progressbar')).toBeInTheDocument()
- })
-
- it('should zoom in when zoom in control is clicked', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getControl('right-16'))
-
- expect(getScaleContainer().getAttribute('style')).toContain('scale(1.2)')
- })
-
- it('should zoom out when zoom out control is clicked', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getControl('right-24'))
-
- expect(getScaleContainer().getAttribute('style')).toMatch(/scale\(0\.8333/)
- })
-
- it('should keep non-1 scale when zooming out from a larger scale', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getControl('right-16'))
- fireEvent.click(getControl('right-16'))
- fireEvent.click(getControl('right-24'))
-
- expect(getScaleContainer().getAttribute('style')).toContain('scale(1.2)')
- })
-
- it('should reset scale back to 1 when zooming in then out', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getControl('right-16'))
- fireEvent.click(getControl('right-24'))
-
- expect(getScaleContainer().getAttribute('style')).toContain('scale(1)')
- })
-
- it('should zoom in when ArrowUp key is pressed', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowUp', code: 'ArrowUp' })
-
- expect(getScaleContainer().getAttribute('style')).toContain('scale(1.2)')
- })
-
- it('should zoom out when ArrowDown key is pressed', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.keyDown(screen.getByRole('dialog'), { key: 'ArrowDown', code: 'ArrowDown' })
-
- expect(getScaleContainer().getAttribute('style')).toMatch(/scale\(0\.8333/)
- })
-
- it('should call onCancel when close control is clicked', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getControl('right-6'))
-
- expect(mockOnCancel).toHaveBeenCalled()
- })
-
- it('should call onCancel when Escape key is pressed', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
-
- expect(mockOnCancel).toHaveBeenCalled()
- })
-
- it('should keep preview content clicks from closing', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
-
- fireEvent.click(getScaleContainer())
- expect(mockOnCancel).not.toHaveBeenCalled()
- })
-
- it('should load the pdf worker from the configured base path', async () => {
- vi.resetModules()
- vi.doMock('@/utils/var', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/utils/var')>()
- return { ...actual, basePath: '/dify' }
- })
- const { default: SubPathPdfPreview } = await import('../pdf-preview')
+const file = {
+ id: 'pdf-1',
+ name: 'document.pdf',
+ type: 'application/pdf',
+ size: 2048,
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ url: 'https://example.com/doc.pdf',
+}
+
+async function openPdf() {
+ render(<FileItem file={file} canPreview />)
+ fireEvent.click(screen.getByRole('button', { name: 'document.pdf' }))
+ await screen.findByText('PDF page')
+}
+
+function scaleContainer() {
+ return screen.getByTestId('pdf-loader').parentElement!
+}
+
+beforeEach(() => {
+ mockBasePath = ''
+})
- render(<SubPathPdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
+it('provides a named preview while loading the PDF worker from the configured base path', async () => {
+ mockBasePath = '/dify'
+ await openPdf()
+ expect(screen.getByRole('dialog', { name: 'document.pdf' })).toBeInTheDocument()
+ expect(screen.getByTestId('pdf-loader')).toHaveAttribute(
+ 'data-worker-src',
+ '/dify/pdf.worker.min.mjs',
+ )
+})
- expect(screen.getByTestId('pdf-loader')).toHaveAttribute(
- 'data-worker-src',
- '/dify/pdf.worker.min.mjs',
- )
- })
+it('uses the root worker path without a deployment base path', async () => {
+ await openPdf()
+ expect(screen.getByTestId('pdf-loader')).toHaveAttribute('data-worker-src', '/pdf.worker.min.mjs')
+})
- it('should load the pdf worker from the origin root when no base path is configured', () => {
- render(<PdfPreview url="https://example.com/doc.pdf" onCancel={mockOnCancel} />)
+it('zooms within its limits and starts again at the original scale after reopening', async () => {
+ const user = userEvent.setup()
+ await openPdf()
+ const zoomIn = screen.getByRole('button', { name: 'common.operation.zoomIn' })
+ const zoomOut = screen.getByRole('button', { name: 'common.operation.zoomOut' })
+ await user.click(zoomIn)
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(1.2)' })
+ await user.click(zoomOut)
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
+ for (let step = 0; step < 20; step++) fireEvent.click(zoomIn)
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(15)' })
+ for (let step = 0; step < 25; step++) fireEvent.click(zoomOut)
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(0.5)' })
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'document.pdf' }))
+ await screen.findByText('PDF page')
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
+})
- expect(screen.getByTestId('pdf-loader')).toHaveAttribute(
- 'data-worker-src',
- '/pdf.worker.min.mjs',
- )
- })
+it('keeps popup-level zoom shortcuts working while Close has focus', async () => {
+ const user = userEvent.setup()
+ await openPdf()
+ const close = screen.getByRole('button', { name: 'common.operation.close' })
+ close.focus()
+ await user.keyboard('{ArrowUp}')
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(1.2)' })
+ await user.keyboard('{ArrowDown}')
+ expect(scaleContainer()).toHaveStyle({ transform: 'scale(1)' })
+ await user.keyboard('{Escape}')
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
diff --git a/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx b/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx
deleted file mode 100644
index a3099f88ebd..00000000000
--- a/web/app/components/base/file-uploader/__tests__/video-preview.spec.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import VideoPreview from '../video-preview'
-
-describe('VideoPreview', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('should render video element with correct title', () => {
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />,
- )
-
- const video = document.querySelector('video')
- expect(video).toBeInTheDocument()
- expect(video).toHaveAttribute('title', 'Test Video')
- expect(video?.parentElement).not.toHaveAttribute('aria-label')
- })
-
- it('should render source element with correct src and type', () => {
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />,
- )
-
- const source = document.querySelector('source')
- expect(source).toHaveAttribute('src', 'https://example.com/video.mp4')
- expect(source).toHaveAttribute('type', 'video/mp4')
- })
-
- it('should render close button with icon', () => {
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />,
- )
-
- expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeInTheDocument()
- })
-
- it('should call onCancel when close button is clicked', () => {
- const onCancel = vi.fn()
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={onCancel} />,
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))
-
- expect(onCancel).toHaveBeenCalled()
- })
-
- it('should not close when video content is clicked', () => {
- const onCancel = vi.fn()
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={onCancel} />,
- )
-
- const video = document.querySelector('video')
- expect(video).toBeInTheDocument()
- fireEvent.click(video!)
-
- expect(onCancel).not.toHaveBeenCalled()
- })
-
- it('should call onCancel when Escape key is pressed', () => {
- const onCancel = vi.fn()
-
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={onCancel} />,
- )
-
- fireEvent.keyDown(document, { key: 'Escape', code: 'Escape' })
-
- expect(onCancel).toHaveBeenCalled()
- })
-
- it('should render in a portal attached to document.body', () => {
- render(
- <VideoPreview url="https://example.com/video.mp4" title="Test Video" onCancel={vi.fn()} />,
- )
-
- const video = document.querySelector('video')
- expect(video?.closest('[data-base-ui-portal]')?.parentElement).toBe(document.body)
- })
-})
diff --git a/web/app/components/base/file-uploader/audio-preview.tsx b/web/app/components/base/file-uploader/audio-preview.tsx
deleted file mode 100644
index 63c5416c5dc..00000000000
--- a/web/app/components/base/file-uploader/audio-preview.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { FC } from 'react'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
-import { useTranslation } from 'react-i18next'
-
-type AudioPreviewProps = {
- url: string
- title: string
- onCancel: () => void
-}
-const AudioPreview: FC<AudioPreviewProps> = ({ url, title, onCancel }) => {
- const { t } = useTranslation(['common'])
-
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onCancel()
- }}
- disablePointerDismissal
- >
- <DialogContent
- className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
- backdropProps={{ className: 'bg-transparent!' }}
- >
- <div tabIndex={-1}>
- <audio controls title={title} autoPlay={false} preload="metadata">
- <source type="audio/mpeg" src={url} className="max-h-full max-w-full" />
- </audio>
- </div>
- <button
- type="button"
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg border-none bg-white/8 p-0 backdrop-blur-[2px]"
- onClick={onCancel}
- >
- <span className="i-ri-close-line size-4 text-gray-500" aria-hidden="true" />
- </button>
- </DialogContent>
- </Dialog>
- )
-}
-
-export default AudioPreview
diff --git a/web/app/components/base/file-uploader/dynamic-pdf-preview.tsx b/web/app/components/base/file-uploader/dynamic-pdf-preview.tsx
deleted file mode 100644
index 516c241ba85..00000000000
--- a/web/app/components/base/file-uploader/dynamic-pdf-preview.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-'use client'
-
-import dynamic from 'next/dynamic'
-
-type DynamicPdfPreviewProps = {
- url: string
- onCancel: () => void
-}
-const DynamicPdfPreview = dynamic<DynamicPdfPreviewProps>(() => import('./pdf-preview'), {
- ssr: false,
-})
-
-export default DynamicPdfPreview
diff --git a/web/app/components/base/file-uploader/file-preview-content.tsx b/web/app/components/base/file-uploader/file-preview-content.tsx
new file mode 100644
index 00000000000..7aedc10483a
--- /dev/null
+++ b/web/app/components/base/file-uploader/file-preview-content.tsx
@@ -0,0 +1,93 @@
+'use client'
+
+import type { FileEntity, FilePreviewKind } from './types'
+import { cn } from '@langgenius/dify-ui/cn'
+import {
+ DialogBackdrop,
+ DialogClose,
+ DialogPopup,
+ DialogPortal,
+ DialogTitle,
+} from '@langgenius/dify-ui/dialog'
+import { IconButton } from '@langgenius/dify-ui/icon-button'
+import dynamic from 'next/dynamic'
+import { useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
+
+const PdfPreview = dynamic(() => import('./pdf-preview').then((module) => module.PdfPreview), {
+ ssr: false,
+ loading: () => <LoadingPlaceholder className="h-64" />,
+})
+
+type FilePreviewContentProps = {
+ file: FileEntity
+ kind: FilePreviewKind
+}
+
+function FilePreviewPopup({ file, kind }: FilePreviewContentProps) {
+ const { t } = useTranslation(['common'])
+ const popupRef = useRef<HTMLDivElement>(null)
+ // Close stays last so it paints above the scaled PDF layer; focus it explicitly instead.
+ const closeRef = useRef<HTMLButtonElement>(null)
+ const [source] = useState(() => ({
+ url: file.url || file.base64Url,
+ originalFile: file.originalFile,
+ }))
+ const [objectUrl, setObjectUrl] = useState<string>()
+ useEffect(() => {
+ if (source.url || !source.originalFile) return
+ const url = URL.createObjectURL(source.originalFile.slice())
+ // oxlint-disable-next-line eslint-react/set-state-in-effect -- Allocate Blob URLs after commit and pair them with Effect cleanup.
+ setObjectUrl(url)
+ return () => URL.revokeObjectURL(url)
+ }, [source])
+ const url = source.url || objectUrl
+
+ return (
+ <>
+ <DialogBackdrop className="bg-transparent" />
+ <DialogPopup
+ ref={popupRef}
+ initialFocus={closeRef}
+ className={cn(
+ 'fixed inset-0 flex h-dvh w-screen items-center justify-center overflow-hidden rounded-none border-none bg-black/80 p-8 shadow-none',
+ kind === 'pdf' && 'max-sm:p-0',
+ )}
+ >
+ <DialogTitle className="sr-only">{file.name}</DialogTitle>
+ {url && kind === 'audio' && (
+ <audio controls title={file.name} autoPlay={false} preload="metadata">
+ <source type="audio/mpeg" src={url} className="max-h-full max-w-full" />
+ </audio>
+ )}
+ {url && kind === 'video' && (
+ <video controls title={file.name} autoPlay={false} preload="metadata">
+ <source type="video/mp4" src={url} className="max-h-full max-w-full" />
+ </video>
+ )}
+ {url && kind === 'pdf' && <PdfPreview url={url} popupRef={popupRef} />}
+ <DialogClose
+ render={
+ <IconButton
+ ref={closeRef}
+ size="lg"
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ className="absolute top-6 right-6 rounded-lg bg-white/8 backdrop-blur-[2px]"
+ >
+ <span className="i-ri-close-line size-4 text-gray-500" aria-hidden />
+ </IconButton>
+ }
+ />
+ </DialogPopup>
+ </>
+ )
+}
+
+export function FilePreviewContent(props: FilePreviewContentProps) {
+ return (
+ <DialogPortal>
+ <FilePreviewPopup {...props} />
+ </DialogPortal>
+ )
+}
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-item.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-item.spec.tsx
index 649b44b70c0..d34c455ea0b 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-item.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-item.spec.tsx
@@ -1,7 +1,8 @@
+import type { ReactNode } from 'react'
import type { FileEntity } from '../../types'
-import { fireEvent, render, screen } from '@testing-library/react'
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { TransferMethod } from '@/types/app'
-import FileItem from '../file-item'
+import { FileItem } from '../file-item'
vi.mock('@/utils/download', () => ({
downloadUrl: vi.fn(),
@@ -11,14 +12,13 @@ vi.mock('@/utils/format', () => ({
formatFileSize: (size: number) => `${size}B`,
}))
-vi.mock('../../dynamic-pdf-preview', () => ({
- default: ({ url, onCancel }: { url: string; onCancel: () => void }) => (
+vi.mock('../../pdf-highlighter-adapter', () => ({
+ PdfLoader: ({ url, children }: { url: string; children: (doc: unknown) => ReactNode }) => (
<div data-testid="pdf-preview" data-url={url}>
- <button data-testid="pdf-close" onClick={onCancel}>
- Close PDF
- </button>
+ {children({ numPages: 1 })}
</div>
),
+ PdfHighlighter: () => <div>PDF page</div>,
}))
const createFile = (overrides: Partial<FileEntity> = {}): FileEntity => ({
@@ -68,10 +68,11 @@ describe('FileItem (chat-input)', () => {
it('should call onRemove when delete button is clicked', () => {
const onRemove = vi.fn()
- render(<FileItem file={createFile()} showDeleteAction onRemove={onRemove} />)
+ render(<FileItem file={createFile()} canPreview showDeleteAction onRemove={onRemove} />)
const delete_button = screen.getByRole('button', { name: 'common.operation.remove' })
fireEvent.click(delete_button)
expect(onRemove).toHaveBeenCalledWith('file-1')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should render progress circle when file is uploading', () => {
@@ -91,12 +92,13 @@ describe('FileItem (chat-input)', () => {
it('should call onReUpload when replay icon is clicked', () => {
const onReUpload = vi.fn()
- render(<FileItem file={createFile({ progress: -1 })} onReUpload={onReUpload} />)
+ render(<FileItem file={createFile({ progress: -1 })} canPreview onReUpload={onReUpload} />)
const replayIcon = screen.getByRole('button', { name: 'common.operation.retry' })
fireEvent.click(replayIcon!)
expect(onReUpload).toHaveBeenCalledWith('file-1')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should show audio preview when audio file name is clicked', async () => {
@@ -135,7 +137,7 @@ describe('FileItem (chat-input)', () => {
expect(videoElement).toBeInTheDocument()
})
- it('should show pdf preview when pdf file name is clicked', () => {
+ it('should show pdf preview when pdf file name is clicked', async () => {
render(
<FileItem
file={createFile({
@@ -149,7 +151,7 @@ describe('FileItem (chat-input)', () => {
fireEvent.click(screen.getByText(/doc\.pdf/i))
- expect(screen.getByTestId('pdf-preview')).toBeInTheDocument()
+ expect(await screen.findByTestId('pdf-preview')).toBeInTheDocument()
})
it('should close audio preview', () => {
@@ -181,12 +183,17 @@ describe('FileItem (chat-input)', () => {
it('should call downloadUrl when download button is clicked', async () => {
const { downloadUrl } = await import('@/utils/download')
- render(<FileItem file={createFile()} showDownloadAction />)
+ render(<FileItem file={createFile()} canPreview showDownloadAction />)
const downloadBtn = screen.getByRole('button', { name: 'common.operation.download' })
fireEvent.click(downloadBtn)
- expect(downloadUrl).toHaveBeenCalled()
+ expect(downloadUrl).toHaveBeenCalledWith({
+ url: 'https://example.com/document.pdf&as_attachment=true',
+ fileName: 'document.pdf',
+ target: '_blank',
+ })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('should not render download button when showDownloadAction is false', () => {
@@ -248,7 +255,7 @@ describe('FileItem (chat-input)', () => {
expect(document.querySelector('video')).not.toBeInTheDocument()
})
- it('should close pdf preview', () => {
+ it('should close pdf preview', async () => {
render(
<FileItem
file={createFile({
@@ -261,10 +268,10 @@ describe('FileItem (chat-input)', () => {
)
fireEvent.click(screen.getByText(/doc\.pdf/i))
- expect(screen.getByTestId('pdf-preview')).toBeInTheDocument()
+ expect(await screen.findByTestId('pdf-preview')).toBeInTheDocument()
- fireEvent.click(screen.getByTestId('pdf-close'))
- expect(screen.queryByTestId('pdf-preview')).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('should use createObjectURL when no url or base64Url but has originalFile', () => {
@@ -280,10 +287,11 @@ describe('FileItem (chat-input)', () => {
})
render(<FileItem file={file} canPreview />)
- fireEvent.click(screen.getByText(/audio\.mp3/i))
+ expect(createObjectURLSpy).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'audio.mp3' }))
expect(document.querySelector('audio')).toBeInTheDocument()
- expect(createObjectURLSpy).toHaveBeenCalled()
+ expect(createObjectURLSpy).toHaveBeenCalledTimes(1)
createObjectURLSpy.mockRestore()
})
@@ -335,4 +343,115 @@ describe('FileItem (chat-input)', () => {
expect(screen.queryByText(/0B/)).not.toBeInTheDocument()
})
+ it.each([
+ { type: 'text/plain', url: 'https://example.com/file.txt', canPreview: true },
+ { type: 'audio/mpeg', url: undefined, canPreview: true },
+ { type: 'audio/mpeg', url: 'https://example.com/audio.mp3', canPreview: false },
+ ])('keeps filename static when preview is unavailable: %j', ({ type, url, canPreview }) => {
+ render(<FileItem file={createFile({ name: 'filename', type, url })} canPreview={canPreview} />)
+ expect(screen.getByText('filename')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'filename' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it.each(['audio/mpeg', 'video/mp4'])(
+ 'preserves native controls without autoplay for %s',
+ (type) => {
+ const { container } = render(
+ <FileItem file={createFile({ name: 'media', type })} canPreview />,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'media' }))
+ const media = within(screen.getByRole('dialog')).getByTitle('media')
+ expect(media.querySelector('source')).toHaveAttribute('type', type)
+ expect(media).toHaveAttribute('controls')
+ expect(media).toHaveAttribute('preload', 'metadata')
+ expect(media).not.toHaveAttribute('autoplay')
+ expect(container.querySelector('audio,video')).not.toBeInTheDocument()
+ fireEvent.click(media)
+ expect(screen.getByRole('dialog', { name: 'media' })).toBeInTheDocument()
+ fireEvent.keyDown(document, { key: 'Escape' })
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ },
+ )
+
+ it('keeps the open source while upload completes and releases its Blob before the next session', async () => {
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:local-audio')
+ const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL')
+ const file = createFile({
+ name: 'audio.mp3',
+ type: 'audio/mpeg',
+ url: undefined,
+ originalFile: new File(['audio'], 'audio.mp3', { type: 'audio/mpeg' }),
+ })
+ const { rerender } = render(<FileItem file={file} canPreview />)
+ expect(createObjectURL).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'audio.mp3' }))
+ expect(document.querySelector('audio source')).toHaveAttribute('src', 'blob:local-audio')
+ rerender(<FileItem file={{ ...file, url: 'https://example.com/uploaded.mp3' }} canPreview />)
+ expect(document.querySelector('audio source')).toHaveAttribute('src', 'blob:local-audio')
+ expect(createObjectURL).toHaveBeenCalledTimes(1)
+ expect(revokeObjectURL).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(revokeObjectURL).toHaveBeenCalledExactlyOnceWith('blob:local-audio')
+ fireEvent.click(screen.getByRole('button', { name: 'audio.mp3' }))
+ expect(document.querySelector('audio source')).toHaveAttribute(
+ 'src',
+ 'https://example.com/uploaded.mp3',
+ )
+ expect(createObjectURL).toHaveBeenCalledTimes(1)
+ fireEvent.keyDown(document, { key: 'Escape' })
+ expect(revokeObjectURL).toHaveBeenCalledTimes(1)
+ createObjectURL.mockRestore()
+ revokeObjectURL.mockRestore()
+ })
+
+ it.each([
+ { url: 'https://example.com/remote.mp3', expected: 'https://example.com/remote.mp3' },
+ { url: undefined, expected: 'data:audio/mpeg;base64,YQ==' },
+ ])(
+ 'borrows the preferred URL without creating or revoking it: $expected',
+ ({ url, expected }) => {
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL')
+ const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL')
+ render(
+ <FileItem
+ file={createFile({
+ name: 'audio.mp3',
+ type: 'audio/mpeg',
+ url,
+ base64Url: 'data:audio/mpeg;base64,YQ==',
+ originalFile: new File(['audio'], 'audio.mp3'),
+ })}
+ canPreview
+ />,
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'audio.mp3' }))
+ expect(document.querySelector('audio source')).toHaveAttribute('src', expected)
+ fireEvent.keyDown(document, { key: 'Escape' })
+ expect(createObjectURL).not.toHaveBeenCalled()
+ expect(revokeObjectURL).not.toHaveBeenCalled()
+ createObjectURL.mockRestore()
+ revokeObjectURL.mockRestore()
+ },
+ )
+
+ it('ends the resource session if preview permission is removed', () => {
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:local-audio')
+ const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL')
+ const file = createFile({
+ name: 'audio.mp3',
+ type: 'audio/mpeg',
+ url: undefined,
+ originalFile: new File(['audio'], 'audio.mp3'),
+ })
+ const { rerender } = render(<FileItem file={file} canPreview />)
+ fireEvent.click(screen.getByRole('button', { name: 'audio.mp3' }))
+ rerender(<FileItem file={file} canPreview={false} />)
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'audio.mp3' })).not.toBeInTheDocument()
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:local-audio')
+ createObjectURL.mockRestore()
+ revokeObjectURL.mockRestore()
+ })
})
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-preview.browser.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-preview.browser.spec.tsx
new file mode 100644
index 00000000000..19b28b64615
--- /dev/null
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-preview.browser.spec.tsx
@@ -0,0 +1,137 @@
+import type { ReactNode } from 'react'
+import type { FileEntity } from '../../types'
+import { useEffect, useState } from 'react'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { TransferMethod } from '@/types/app'
+import { FileItem } from '../file-item'
+
+const pdfEngine = vi.hoisted(() => ({ ready: Promise.resolve() }))
+
+// Keep the preview, zoom controls and lazy boundary real; replace only PDF decoding.
+vi.mock('../../pdf-highlighter-adapter', () => ({
+ PdfLoader: ({
+ children,
+ beforeLoad,
+ }: {
+ children: (document: object) => ReactNode
+ beforeLoad: ReactNode
+ }) => {
+ const [loaded, setLoaded] = useState(false)
+ useEffect(() => {
+ let active = true
+ void pdfEngine.ready.then(() => {
+ if (active) setLoaded(true)
+ })
+ return () => {
+ active = false
+ }
+ }, [])
+ return loaded ? children({}) : beforeLoad
+ },
+ PdfHighlighter: () => (
+ <div role="document" aria-label="PDF page" style={{ width: 200, height: 300 }}>
+ A PDF page
+ </div>
+ ),
+}))
+
+function createFile(overrides: Partial<FileEntity> = {}): FileEntity {
+ return {
+ id: 'file-1',
+ name: 'document.pdf',
+ size: 2048,
+ type: 'application/pdf',
+ progress: 100,
+ transferMethod: TransferMethod.local_file,
+ supportFileType: 'document',
+ uploadedId: 'uploaded-1',
+ url: 'https://example.com/document.pdf',
+ ...overrides,
+ }
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+it('keeps Close focused through PDF loading, handles zoom keys there and starts a fresh preview', async () => {
+ let resolvePdf!: () => void
+ pdfEngine.ready = new Promise<void>((resolve) => {
+ resolvePdf = resolve
+ })
+ const screen = await render(<FileItem file={createFile()} canPreview />)
+ const filename = screen.getByRole('button', { name: 'document.pdf' })
+ await userEvent.tab()
+ await expect.element(filename).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ const dialog = screen.getByRole('dialog', { name: 'document.pdf' })
+ const close = dialog.getByRole('button', { name: 'common.operation.close' })
+ await expect.element(close).toHaveFocus()
+ const initialClose = close.element()
+ const page = dialog.getByRole('document', { name: 'PDF page' })
+ await expect.element(page).not.toBeInTheDocument()
+
+ resolvePdf()
+ await expect.element(page).toBeVisible()
+ expect(close.element()).toBe(initialClose)
+ await expect.element(close).toHaveFocus()
+ await expect.poll(() => Math.round(page.element().getBoundingClientRect().width)).toBe(200)
+ await userEvent.keyboard('{ArrowUp}')
+ await expect.poll(() => Math.round(page.element().getBoundingClientRect().width)).toBe(240)
+ await userEvent.keyboard('{ArrowDown}')
+ await expect.poll(() => Math.round(page.element().getBoundingClientRect().width)).toBe(200)
+ await userEvent.keyboard('{ArrowUp}{Escape}')
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(filename).toHaveFocus()
+
+ await userEvent.keyboard(' ')
+ await expect.element(close).toHaveFocus()
+ await expect.element(page).toBeVisible()
+ await expect.poll(() => Math.round(page.element().getBoundingClientRect().width)).toBe(200)
+ await close.click()
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.element(filename).toHaveFocus()
+})
+
+it('retains the local media resource during the real exit transition and releases it afterwards', async () => {
+ vi.stubGlobal('BASE_UI_ANIMATIONS_DISABLED', false)
+ const createUrl = vi.spyOn(URL, 'createObjectURL')
+ const revokeUrl = vi.spyOn(URL, 'revokeObjectURL')
+ const file = createFile({
+ name: 'recording.wav',
+ type: 'audio/wav',
+ url: undefined,
+ originalFile: new File(['recording'], 'recording.wav', { type: 'audio/wav' }),
+ })
+ const screen = await render(<FileItem file={file} canPreview />)
+ const filename = screen.getByRole('button', { name: 'recording.wav' })
+ expect(createUrl).not.toHaveBeenCalled()
+ await filename.click()
+ const dialog = screen.getByRole('dialog', { name: 'recording.wav' })
+ const close = dialog.getByRole('button', { name: 'common.operation.close' })
+ await expect.element(close).toHaveFocus()
+ await expect.poll(() => createUrl.mock.results.length).toBe(1)
+ const resource = createUrl.mock.results[0]!.value as string
+ const popup = dialog.element()
+ await expect.poll(() => getComputedStyle(popup).opacity).toBe('1')
+ const exitFrame = new Promise<{ opacity: number; revoked: boolean }>((resolve) => {
+ const onTransition = (event: Event) => {
+ if (event.target !== popup || (event as TransitionEvent).propertyName !== 'opacity') return
+ popup.removeEventListener('transitionrun', onTransition)
+ resolve({
+ opacity: Number(getComputedStyle(popup).opacity),
+ revoked: revokeUrl.mock.calls.some(([url]) => url === resource),
+ })
+ }
+ popup.addEventListener('transitionrun', onTransition)
+ })
+ await close.click()
+ const closing = await exitFrame
+ expect(closing.opacity).toBeGreaterThan(0)
+ expect(closing.revoked).toBe(false)
+ await expect.element(dialog).not.toBeInTheDocument()
+ await expect.poll(() => revokeUrl.mock.calls.some(([url]) => url === resource)).toBe(true)
+ await expect.element(filename).toHaveFocus()
+})
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-item.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-item.tsx
index 5d5b0f5e3e8..b88614d9dde 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-item.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-item.tsx
@@ -1,16 +1,19 @@
import type { FileEntity } from '../types'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogTrigger } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { ProgressCircle } from '@langgenius/dify-ui/progress'
-import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AudioPreview from '@/app/components/base/file-uploader/audio-preview'
-import PdfPreview from '@/app/components/base/file-uploader/dynamic-pdf-preview'
-import VideoPreview from '@/app/components/base/file-uploader/video-preview'
import { downloadUrl } from '@/utils/download'
import { formatFileSize } from '@/utils/format'
+import { FilePreviewContent } from '../file-preview-content'
import FileTypeIcon from '../file-type-icon'
-import { fileIsUploaded, getFileAppearanceType, getFileExtension } from '../utils'
+import {
+ fileIsUploaded,
+ getFileAppearanceType,
+ getFileExtension,
+ getFilePreviewKind,
+} from '../utils'
type FileItemProps = {
file: FileEntity
@@ -20,117 +23,104 @@ type FileItemProps = {
onRemove?: (fileId: string) => void
onReUpload?: (fileId: string) => void
}
-const FileItem = ({
+export function FileItem({
file,
showDeleteAction,
showDownloadAction = true,
onRemove,
onReUpload,
canPreview,
-}: FileItemProps) => {
+}: FileItemProps) {
const { t } = useTranslation(['common', 'custom'])
const { id, name, type, progress, url, base64Url, isRemote } = file
- const [previewUrl, setPreviewUrl] = useState('')
const ext = getFileExtension(name, type, isRemote)
const uploadError = progress === -1
- const [typeCategory = '', typeSubtype = ''] = type?.split('/') ?? []
-
- let tmp_preview_url = url || base64Url
- if (!tmp_preview_url && file?.originalFile)
- tmp_preview_url = URL.createObjectURL(file.originalFile.slice()).toString()
const download_url = url ? `${url}&as_attachment=true` : base64Url
+ const previewKind = canPreview ? getFilePreviewKind(file) : undefined
return (
- <>
- <div
- className={cn(
- 'group/file-item relative h-17 w-36 rounded-lg border-[0.5px] border-components-panel-border bg-components-card-bg p-2 shadow-xs',
- !uploadError && 'hover:bg-components-card-bg-alt',
- uploadError && 'border border-state-destructive-border bg-state-destructive-hover',
- uploadError &&
- 'bg-state-destructive-hover-alt hover:border-[0.5px] hover:border-state-destructive-border',
+ <div
+ className={cn(
+ 'group/file-item relative h-17 w-36 rounded-lg border-[0.5px] border-components-panel-border bg-components-card-bg p-2 shadow-xs',
+ !uploadError && 'hover:bg-components-card-bg-alt',
+ uploadError && 'border border-state-destructive-border bg-state-destructive-hover',
+ uploadError &&
+ 'bg-state-destructive-hover-alt hover:border-[0.5px] hover:border-state-destructive-border',
+ )}
+ >
+ {showDeleteAction && (
+ <IconButton
+ aria-label={t(($) => $['operation.remove'], { ns: 'common' })}
+ variant="secondary"
+ size="sm"
+ className="absolute -top-1.5 -right-1.5 z-11 hidden rounded-full group-hover/file-item:flex"
+ onClick={() => onRemove?.(id)}
+ >
+ <span
+ className="i-ri-close-line size-4 text-components-button-secondary-text"
+ aria-hidden="true"
+ />
+ </IconButton>
+ )}
+ <div className="mb-1 h-8">
+ {previewKind ? (
+ <Dialog disablePointerDismissal>
+ <DialogTrigger
+ title={name}
+ className="line-clamp-2 w-full cursor-pointer text-left system-xs-medium break-all text-text-tertiary"
+ >
+ {name}
+ </DialogTrigger>
+ <FilePreviewContent file={file} kind={previewKind} />
+ </Dialog>
+ ) : (
+ <div className="line-clamp-2 system-xs-medium break-all text-text-tertiary" title={name}>
+ {name}
+ </div>
)}
- >
- {showDeleteAction && (
+ </div>
+ <div className="relative flex items-center justify-between">
+ <div className="flex items-center system-2xs-medium-uppercase text-text-tertiary">
+ <FileTypeIcon size="sm" type={getFileAppearanceType(name, type)} className="mr-1" />
+ {ext && (
+ <>
+ {ext}
+ <div className="mx-1">·</div>
+ </>
+ )}
+ {!!file.size && formatFileSize(file.size)}
+ </div>
+ {showDownloadAction && download_url && (
<IconButton
- aria-label={t(($) => $['operation.remove'], { ns: 'common' })}
- variant="secondary"
- size="sm"
- className="absolute -top-1.5 -right-1.5 z-11 hidden rounded-full group-hover/file-item:flex"
- onClick={() => onRemove?.(id)}
+ aria-label={t(($) => $['operation.download'], { ns: 'common' })}
+ size="md"
+ className="absolute -top-1 -right-1 hidden group-hover/file-item:flex"
+ onClick={(e) => {
+ e.stopPropagation()
+ downloadUrl({ url: download_url || '', fileName: name, target: '_blank' })
+ }}
>
- <span
- className="i-ri-close-line size-4 text-components-button-secondary-text"
- aria-hidden="true"
- />
+ <span className="i-ri-download-line size-3.5 text-text-tertiary" aria-hidden="true" />
</IconButton>
)}
- <div
- className="mb-1 line-clamp-2 h-8 cursor-pointer system-xs-medium break-all text-text-tertiary"
- title={name}
- onClick={() => canPreview && setPreviewUrl(tmp_preview_url || '')}
- >
- {name}
- </div>
- <div className="relative flex items-center justify-between">
- <div className="flex items-center system-2xs-medium-uppercase text-text-tertiary">
- <FileTypeIcon size="sm" type={getFileAppearanceType(name, type)} className="mr-1" />
- {ext && (
- <>
- {ext}
- <div className="mx-1">·</div>
- </>
- )}
- {!!file.size && formatFileSize(file.size)}
- </div>
- {showDownloadAction && download_url && (
- <IconButton
- aria-label={t(($) => $['operation.download'], { ns: 'common' })}
- size="md"
- className="absolute -top-1 -right-1 hidden group-hover/file-item:flex"
- onClick={(e) => {
- e.stopPropagation()
- downloadUrl({ url: download_url || '', fileName: name, target: '_blank' })
- }}
- >
- <span className="i-ri-download-line size-3.5 text-text-tertiary" aria-hidden="true" />
- </IconButton>
- )}
- {progress >= 0 && !fileIsUploaded(file) && (
- <ProgressCircle
- value={progress}
- className="shrink-0"
- aria-label={t(($) => $.uploading, { ns: 'custom' })}
- />
- )}
- {uploadError && (
- <button
- type="button"
- aria-label={t(($) => $['operation.retry'], { ns: 'common' })}
- className="size-4 cursor-pointer border-none bg-transparent p-0 text-text-tertiary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
- onClick={() => onReUpload?.(id)}
- >
- <span className="i-custom-vender-other-replay-line block size-4" aria-hidden="true" />
- </button>
- )}
- </div>
+ {progress >= 0 && !fileIsUploaded(file) && (
+ <ProgressCircle
+ value={progress}
+ className="shrink-0"
+ aria-label={t(($) => $.uploading, { ns: 'custom' })}
+ />
+ )}
+ {uploadError && (
+ <button
+ type="button"
+ aria-label={t(($) => $['operation.retry'], { ns: 'common' })}
+ className="size-4 cursor-pointer border-none bg-transparent p-0 text-text-tertiary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
+ onClick={() => onReUpload?.(id)}
+ >
+ <span className="i-custom-vender-other-replay-line block size-4" aria-hidden="true" />
+ </button>
+ )}
</div>
- {typeCategory === 'audio' && canPreview && previewUrl && (
- <AudioPreview title={name} url={previewUrl} onCancel={() => setPreviewUrl('')} />
- )}
- {typeCategory === 'video' && canPreview && previewUrl && (
- <VideoPreview title={name} url={previewUrl} onCancel={() => setPreviewUrl('')} />
- )}
- {typeSubtype === 'pdf' && canPreview && previewUrl && (
- <PdfPreview
- url={previewUrl}
- onCancel={() => {
- setPreviewUrl('')
- }}
- />
- )}
- </>
+ </div>
)
}
-
-export default FileItem
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-list.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-list.tsx
index 87c20043fcc..34b56f80d63 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-list.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/file-list.tsx
@@ -5,7 +5,7 @@ import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { useFile } from '../hooks'
import { useStore } from '../store'
import FileImageItem from './file-image-item'
-import FileItem from './file-item'
+import { FileItem } from './file-item'
type FileListProps = {
className?: string
diff --git a/web/app/components/base/file-uploader/pdf-preview.tsx b/web/app/components/base/file-uploader/pdf-preview.tsx
index e662158d1a2..ccad807b120 100644
--- a/web/app/components/base/file-uploader/pdf-preview.tsx
+++ b/web/app/components/base/file-uploader/pdf-preview.tsx
@@ -1,41 +1,28 @@
-import { Dialog, DialogBackdrop, DialogPopup, DialogPortal } from '@langgenius/dify-ui/dialog'
+import type { RefObject } from 'react'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { RiCloseLine, RiZoomInLine, RiZoomOutLine } from '@remixicon/react'
import { useHotkey } from '@tanstack/react-hotkeys'
import { noop } from 'es-toolkit/function'
-import { useRef, useState } from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { basePath } from '@/utils/var'
import { PdfHighlighter, PdfLoader } from './pdf-highlighter-adapter'
type PdfPreviewProps = {
url: string
- onCancel: () => void
+ popupRef: RefObject<HTMLDivElement | null>
}
-function PdfPreviewContent({ url, onCancel }: PdfPreviewProps) {
- const previewRef = useRef<HTMLDivElement>(null)
- const { t } = useTranslation(['common', 'workflow'])
- const media = useBreakpoints()
+export function PdfPreview({ url, popupRef }: PdfPreviewProps) {
+ const { t } = useTranslation(['common'])
const [scale, setScale] = useState(1)
- const [position, setPosition] = useState({ x: 0, y: 0 })
- const isMobile = media === MediaType.mobile
const zoomIn = () => {
setScale((prevScale) => Math.min(prevScale * 1.2, 15))
- setPosition({ x: position.x - 50, y: position.y - 50 })
}
const zoomOut = () => {
- setScale((prevScale) => {
- const newScale = Math.max(prevScale / 1.2, 0.5)
- if (newScale === 1) setPosition({ x: 0, y: 0 })
- else setPosition({ x: position.x + 50, y: position.y + 50 })
-
- return newScale
- })
+ setScale((prevScale) => Math.max(prevScale / 1.2, 0.5))
}
useHotkey(
@@ -47,7 +34,7 @@ function PdfPreviewContent({ url, onCancel }: PdfPreviewProps) {
zoomIn()
},
{
- target: previewRef,
+ target: popupRef,
enabled: true,
ignoreInputs: true,
requireReset: false,
@@ -64,7 +51,7 @@ function PdfPreviewContent({ url, onCancel }: PdfPreviewProps) {
zoomOut()
},
{
- target: previewRef,
+ target: popupRef,
enabled: true,
ignoreInputs: true,
requireReset: false,
@@ -75,112 +62,71 @@ function PdfPreviewContent({ url, onCancel }: PdfPreviewProps) {
const zoomOutLabel = t(($) => $['operation.zoomOut'], { ns: 'common' })
const zoomInLabel = t(($) => $['operation.zoomIn'], { ns: 'common' })
- const cancelLabel = t(($) => $['operation.cancel'], { ns: 'common' })
return (
<>
- <DialogBackdrop className="bg-transparent!" />
- <DialogPopup
- ref={previewRef}
- aria-label={t(($) => $['common.preview'], { ns: 'workflow' })}
- className={`fixed inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 shadow-none! ${!isMobile ? 'p-8!' : 'p-0!'}`}
+ <div
+ tabIndex={-1}
+ className="h-[95vh] max-h-full w-screen max-w-full overflow-hidden"
+ style={{
+ transform: `scale(${scale})`,
+ transformOrigin: 'center',
+ scrollbarWidth: 'none',
+ msOverflowStyle: 'none',
+ }}
>
- <div
- tabIndex={-1}
- className="h-[95vh] max-h-full w-screen max-w-full overflow-hidden"
- style={{
- transform: `scale(${scale})`,
- transformOrigin: 'center',
- scrollbarWidth: 'none',
- msOverflowStyle: 'none',
- }}
+ <PdfLoader
+ workerSrc={`${basePath}/pdf.worker.min.mjs`}
+ url={url}
+ beforeLoad={<LoadingPlaceholder className="h-64" />}
>
- <PdfLoader
- workerSrc={`${basePath}/pdf.worker.min.mjs`}
- url={url}
- beforeLoad={<LoadingPlaceholder className="h-64" />}
- >
- {(pdfDocument) => {
- return (
- <PdfHighlighter
- pdfDocument={pdfDocument}
- enableAreaSelection={(event) => event.altKey}
- scrollRef={noop}
- onScrollChange={noop}
- onSelectionFinished={() => null}
- highlightTransform={() => {
- return <div />
- }}
- highlights={[]}
- />
- )
- }}
- </PdfLoader>
- </div>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label={zoomOutLabel}
- className="absolute top-6 right-24 flex size-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomOut}
- >
- <RiZoomOutLine className="size-4 text-gray-500" />
- </button>
- }
- />
- <TooltipContent>{zoomOutLabel}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label={zoomInLabel}
- className="absolute top-6 right-16 flex size-8 cursor-pointer items-center justify-center rounded-lg"
- onClick={zoomIn}
- >
- <RiZoomInLine className="size-4 text-gray-500" />
- </button>
- }
- />
- <TooltipContent>{zoomInLabel}</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={
- <button
- type="button"
- aria-label={cancelLabel}
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg bg-white/8 backdrop-blur-[2px]"
- onClick={onCancel}
- >
- <RiCloseLine className="size-4 text-gray-500" />
- </button>
- }
- />
- <TooltipContent>{cancelLabel}</TooltipContent>
- </Tooltip>
- </DialogPopup>
+ {(pdfDocument) => {
+ return (
+ <PdfHighlighter
+ pdfDocument={pdfDocument}
+ enableAreaSelection={(event) => event.altKey}
+ scrollRef={noop}
+ onScrollChange={noop}
+ onSelectionFinished={() => null}
+ highlightTransform={() => {
+ return <div />
+ }}
+ highlights={[]}
+ />
+ )
+ }}
+ </PdfLoader>
+ </div>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label={zoomOutLabel}
+ className="absolute top-6 right-24 flex size-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomOut}
+ >
+ <span aria-hidden className="i-ri-zoom-out-line size-4 text-gray-500" />
+ </button>
+ }
+ />
+ <TooltipContent>{zoomOutLabel}</TooltipContent>
+ </Tooltip>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <button
+ type="button"
+ aria-label={zoomInLabel}
+ className="absolute top-6 right-16 flex size-8 cursor-pointer items-center justify-center rounded-lg"
+ onClick={zoomIn}
+ >
+ <span aria-hidden className="i-ri-zoom-in-line size-4 text-gray-500" />
+ </button>
+ }
+ />
+ <TooltipContent>{zoomInLabel}</TooltipContent>
+ </Tooltip>
</>
)
}
-
-function PdfPreview(props: PdfPreviewProps) {
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) props.onCancel()
- }}
- disablePointerDismissal
- >
- <DialogPortal>
- <PdfPreviewContent {...props} />
- </DialogPortal>
- </Dialog>
- )
-}
-
-export default PdfPreview
diff --git a/web/app/components/base/file-uploader/types.ts b/web/app/components/base/file-uploader/types.ts
index 84f5a0e906f..a08d9c58696 100644
--- a/web/app/components/base/file-uploader/types.ts
+++ b/web/app/components/base/file-uploader/types.ts
@@ -34,3 +34,5 @@ export type FileEntity = {
url?: string
isRemote?: boolean
}
+
+export type FilePreviewKind = 'audio' | 'video' | 'pdf'
diff --git a/web/app/components/base/file-uploader/utils.ts b/web/app/components/base/file-uploader/utils.ts
index 241b1a50be4..282530eb0f6 100644
--- a/web/app/components/base/file-uploader/utils.ts
+++ b/web/app/components/base/file-uploader/utils.ts
@@ -1,5 +1,5 @@
import type { TFunction } from 'i18next'
-import type { FileEntity } from './types'
+import type { FileEntity, FilePreviewKind } from './types'
import type { FileResponse } from '@/types/workflow'
import mime from 'mime'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
@@ -249,3 +249,10 @@ export const fileIsUploaded = (file: FileEntity) => {
if (file.transferMethod === TransferMethod.remote_url && file.progress === 100) return true
}
+
+export const getFilePreviewKind = (file: FileEntity): FilePreviewKind | undefined => {
+ if (!(file.url || file.base64Url || file.originalFile)) return undefined
+ const [category, subtype] = file.type?.split('/') ?? []
+ if (category === 'audio' || category === 'video') return category
+ return subtype === 'pdf' ? 'pdf' : undefined
+}
diff --git a/web/app/components/base/file-uploader/video-preview.tsx b/web/app/components/base/file-uploader/video-preview.tsx
deleted file mode 100644
index cd1039f8afe..00000000000
--- a/web/app/components/base/file-uploader/video-preview.tsx
+++ /dev/null
@@ -1,43 +0,0 @@
-import type { FC } from 'react'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
-import { useTranslation } from 'react-i18next'
-
-type VideoPreviewProps = {
- url: string
- title: string
- onCancel: () => void
-}
-const VideoPreview: FC<VideoPreviewProps> = ({ url, title, onCancel }) => {
- const { t } = useTranslation(['common'])
-
- return (
- <Dialog
- open
- onOpenChange={(open) => {
- if (!open) onCancel()
- }}
- disablePointerDismissal
- >
- <DialogContent
- className="inset-0! top-0! left-0! flex h-dvh! max-h-none! w-screen! max-w-none! translate-0! items-center justify-center overflow-hidden! rounded-none! border-none! bg-black/80 p-8! shadow-none!"
- backdropProps={{ className: 'bg-transparent!' }}
- >
- <div tabIndex={-1}>
- <video controls title={title} autoPlay={false} preload="metadata">
- <source type="video/mp4" src={url} className="max-h-full max-w-full" />
- </video>
- </div>
- <button
- type="button"
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- className="absolute top-6 right-6 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg border-none bg-white/8 p-0 backdrop-blur-[2px]"
- onClick={onCancel}
- >
- <span className="i-ri-close-line size-4 text-gray-500" aria-hidden="true" />
- </button>
- </DialogContent>
- </Dialog>
- )
-}
-
-export default VideoPreview