chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+268
@@ -0,0 +1,268 @@
|
||||
import type { DocumentWithSegmentsResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { ChunkingMode, DataSourceType } from '@/models/datasets'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { DocumentPicker } from '../index'
|
||||
|
||||
let mockDocumentListData: { data: DocumentWithSegmentsResponse[] } | undefined
|
||||
|
||||
const { mockUseDocumentList } = vi.hoisted(() => ({
|
||||
mockUseDocumentList: vi.fn(),
|
||||
}))
|
||||
|
||||
const createDocument = (
|
||||
overrides: Partial<DocumentWithSegmentsResponse> = {},
|
||||
): DocumentWithSegmentsResponse => ({
|
||||
id: 'doc-1',
|
||||
position: 1,
|
||||
data_source_type: DataSourceType.FILE,
|
||||
data_source_info: {
|
||||
upload_file: {
|
||||
id: 'file-1',
|
||||
name: 'document.pdf',
|
||||
size: 1024,
|
||||
extension: 'pdf',
|
||||
mime_type: 'application/pdf',
|
||||
created_by: 'user-1',
|
||||
created_at: 1700000000,
|
||||
},
|
||||
job_id: 'job-1',
|
||||
url: '',
|
||||
},
|
||||
dataset_process_rule_id: 'rule-1',
|
||||
name: 'Document 1',
|
||||
created_from: 'web',
|
||||
created_by: 'user-1',
|
||||
created_at: 1700000000,
|
||||
indexing_status: 'completed',
|
||||
display_status: 'enabled',
|
||||
doc_form: ChunkingMode.text,
|
||||
enabled: true,
|
||||
word_count: 1000,
|
||||
archived: false,
|
||||
hit_count: 0,
|
||||
data_source_detail_dict: {
|
||||
upload_file: {
|
||||
id: 'file-1',
|
||||
name: 'document.pdf',
|
||||
size: 1024,
|
||||
extension: 'pdf',
|
||||
mime_type: 'application/pdf',
|
||||
created_by: 'user-1',
|
||||
created_at: 1700000000,
|
||||
},
|
||||
},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createProps = (overrides: Partial<React.ComponentProps<typeof DocumentPicker>> = {}) => ({
|
||||
datasetId: 'dataset-1',
|
||||
currentDocument: createDocument({ id: 'doc-1', name: 'Document 1' }),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderDocumentPicker = (props: Partial<React.ComponentProps<typeof DocumentPicker>> = {}) => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const defaultProps = createProps(props)
|
||||
|
||||
return {
|
||||
props: defaultProps,
|
||||
...render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<DocumentPicker {...defaultProps} />
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
describe('DocumentPicker', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockDocumentListData = {
|
||||
data: [
|
||||
createDocument({ id: 'doc-1', name: 'Document 1' }),
|
||||
createDocument({ id: 'doc-2', name: 'Document 2' }),
|
||||
],
|
||||
}
|
||||
mockUseDocumentList.mockImplementation(() =>
|
||||
Promise.resolve({
|
||||
...mockDocumentListData,
|
||||
total: mockDocumentListData?.data.length ?? 0,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
has_more: false,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should render the current document and chunking mode', () => {
|
||||
renderDocumentPicker({
|
||||
currentDocument: createDocument({
|
||||
id: 'current-doc',
|
||||
name: 'Current Document',
|
||||
doc_form: ChunkingMode.parentChild,
|
||||
}),
|
||||
parentMode: 'paragraph',
|
||||
})
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Current Document' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/dataset.chunkingMode.parentChild/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/dataset.parentMode.paragraph/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should fetch documents with the current dataset and search keyword', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDocumentPicker({ datasetId: 'dataset-custom' })
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Document 1' }))
|
||||
await user.type(screen.getByPlaceholderText('common.operation.search'), 'report')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockUseDocumentList).toHaveBeenLastCalledWith({
|
||||
params: { dataset_id: 'dataset-custom' },
|
||||
query: {
|
||||
keyword: 'report',
|
||||
page: 1,
|
||||
limit: 20,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('should keep focus in the search input when deleting from an empty result', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockUseDocumentList.mockImplementation(({ query }) =>
|
||||
Promise.resolve({
|
||||
...mockDocumentListData,
|
||||
data: query.keyword === 'missing' ? [] : mockDocumentListData?.data,
|
||||
total: query.keyword === 'missing' ? 0 : mockDocumentListData?.data.length,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
has_more: false,
|
||||
}),
|
||||
)
|
||||
|
||||
renderDocumentPicker()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Document 1' })
|
||||
await user.click(trigger)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('common.operation.search')
|
||||
await user.type(searchInput, 'missing')
|
||||
expect(await screen.findByText('common.noData')).toBeInTheDocument()
|
||||
|
||||
await user.keyboard(
|
||||
'{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}{Backspace}',
|
||||
)
|
||||
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(searchInput).toHaveFocus()
|
||||
expect(trigger).not.toHaveFocus()
|
||||
})
|
||||
|
||||
it('renders document links and marks only the current page', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDocumentPicker()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Document 1' }))
|
||||
const currentDocument = await screen.findByRole('menuitem', { name: 'Document 1' })
|
||||
const otherDocument = screen.getByRole('menuitem', { name: 'Document 2' })
|
||||
|
||||
expect(currentDocument).toHaveAttribute('href', '/datasets/dataset-1/documents/doc-1')
|
||||
expect(currentDocument).toHaveAttribute('aria-current', 'page')
|
||||
expect(otherDocument).toHaveAttribute('href', '/datasets/dataset-1/documents/doc-2')
|
||||
expect(otherDocument).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
|
||||
it('removes previous-query links until the new server results arrive', async () => {
|
||||
const user = userEvent.setup()
|
||||
const response = {
|
||||
data: [createDocument({ id: 'report-id', name: 'Quarterly report' })],
|
||||
total: 1,
|
||||
page: 1,
|
||||
limit: 20,
|
||||
has_more: false,
|
||||
}
|
||||
const pendingSearch = createDeferred<typeof response>()
|
||||
const initialResponse = mockUseDocumentList.getMockImplementation()!
|
||||
mockUseDocumentList.mockImplementation((input) =>
|
||||
input.query.keyword === 'report' ? pendingSearch.promise : initialResponse(input),
|
||||
)
|
||||
renderDocumentPicker()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Document 1' }))
|
||||
await screen.findByRole('menuitem', { name: 'Document 2' })
|
||||
const input = screen.getByRole('searchbox', { name: 'common.operation.search' })
|
||||
await user.type(input, 'report')
|
||||
|
||||
expect(screen.queryByRole('menuitem')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('status')).toHaveTextContent('common.loading')
|
||||
expect(screen.queryByText('common.noData')).not.toBeInTheDocument()
|
||||
await waitFor(() => {
|
||||
expect(mockUseDocumentList).toHaveBeenLastCalledWith({
|
||||
params: { dataset_id: 'dataset-1' },
|
||||
query: { keyword: 'report', page: 1, limit: 20 },
|
||||
})
|
||||
})
|
||||
await user.keyboard('{ArrowDown}{Enter}')
|
||||
expect(input).toHaveFocus()
|
||||
expect(screen.queryByRole('menuitem')).not.toBeInTheDocument()
|
||||
|
||||
pendingSearch.resolve(response)
|
||||
const result = await screen.findByRole('menuitem', { name: 'Quarterly report' })
|
||||
expect(result).toHaveAttribute('href', '/datasets/dataset-1/documents/report-id')
|
||||
expect(input).toHaveFocus()
|
||||
})
|
||||
|
||||
it('announces a failed search and retries without closing the menu', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockUseDocumentList.mockRejectedValueOnce(new Error('Search unavailable'))
|
||||
renderDocumentPicker()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Document 1' })
|
||||
await user.click(trigger)
|
||||
const retry = await screen.findByRole('menuitem', { name: 'common.operation.retry' })
|
||||
expect(screen.getByRole('status')).toHaveTextContent('common.dynamicSelect.error')
|
||||
expect(screen.queryByText('common.noData')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(retry)
|
||||
expect(await screen.findByRole('menuitem', { name: 'Document 2' })).toBeInTheDocument()
|
||||
expect(trigger).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByRole('status')).toBeEmptyDOMElement()
|
||||
})
|
||||
|
||||
it('resets the search when the menu closes and reopens', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDocumentPicker()
|
||||
|
||||
const trigger = screen.getByRole('button', { name: 'Document 1' })
|
||||
await user.click(trigger)
|
||||
const input = screen.getByRole('searchbox', { name: 'common.operation.search' })
|
||||
await user.type(input, 'report')
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await user.click(trigger)
|
||||
|
||||
expect(screen.getByRole('searchbox', { name: 'common.operation.search' })).toHaveValue('')
|
||||
expect(await screen.findByRole('menuitem', { name: 'Document 2' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'datasets.byDatasetId.documents.get': mockUseDocumentList,
|
||||
}),
|
||||
}
|
||||
})
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import type { DocumentItem } from '@/models/datasets'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import PreviewDocumentPicker from '../preview-document-picker'
|
||||
|
||||
const documents: DocumentItem[] = [
|
||||
{ id: 'document-1', name: 'First document', extension: 'pdf' } as DocumentItem,
|
||||
{ id: 'document-2', name: 'Second document', extension: 'txt' } as DocumentItem,
|
||||
]
|
||||
|
||||
describe('PreviewDocumentPicker', () => {
|
||||
it('opens the document list and selects a document', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
render(<PreviewDocumentPicker value={documents[0]} files={documents} onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /First document/ }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Second document' }))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(documents[1])
|
||||
expect(screen.getByRole('button', { name: /First document/ })).toHaveAttribute(
|
||||
'aria-expanded',
|
||||
'false',
|
||||
)
|
||||
})
|
||||
|
||||
it('shows loading until the file list arrives', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { rerender } = render(<PreviewDocumentPicker files={[]} onChange={vi.fn()} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /--/ }))
|
||||
|
||||
expect(await screen.findByRole('progressbar')).toBeInTheDocument()
|
||||
rerender(<PreviewDocumentPicker files={documents} onChange={vi.fn()} />)
|
||||
expect(await screen.findByRole('button', { name: 'Second document' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
'use client'
|
||||
import type { DocumentWithSegmentsResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import { MenuItem, MenuLinkItem, MenuList } from '@langgenius/dify-ui/menu'
|
||||
import { SpinnerIcon } from '@langgenius/dify-ui/spinner'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useDebouncedValue } from 'foxact/use-debounced-value'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getUploadFileExtension } from '@/app/components/datasets/documents/document-source'
|
||||
import Link from '@/next/link'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import FileIcon from '../document-file-icon'
|
||||
|
||||
type DocumentListProps = {
|
||||
datasetId: string
|
||||
currentDocumentId?: string
|
||||
searchValue: string
|
||||
}
|
||||
|
||||
function getDocumentExtension(document: DocumentWithSegmentsResponse) {
|
||||
const detailExtension = document.data_source_detail_dict?.upload_file?.extension
|
||||
if (detailExtension) return detailExtension
|
||||
|
||||
return getUploadFileExtension(document.data_source_info) ?? ''
|
||||
}
|
||||
|
||||
export default function DocumentList({
|
||||
datasetId,
|
||||
currentDocumentId,
|
||||
searchValue,
|
||||
}: DocumentListProps) {
|
||||
const { t } = useTranslation(['common'])
|
||||
const keyword = searchValue.trim()
|
||||
const debouncedKeyword = useDebouncedValue(keyword, 500)
|
||||
const documentsQuery = useQuery(
|
||||
consoleQuery.datasets.byDatasetId.documents.get.queryOptions({
|
||||
input: {
|
||||
params: { dataset_id: datasetId },
|
||||
query: { keyword: debouncedKeyword, page: 1, limit: 20 },
|
||||
},
|
||||
}),
|
||||
)
|
||||
const isSearching = keyword !== debouncedKeyword || documentsQuery.isPending
|
||||
const isError = !isSearching && documentsQuery.isError
|
||||
// Previous-query links must not remain actionable during the debounce window.
|
||||
const documents = isSearching || isError ? [] : (documentsQuery.data?.data ?? [])
|
||||
const statusText = isSearching
|
||||
? t(($) => $.loading, { ns: 'common' })
|
||||
: isError
|
||||
? t(($) => $['dynamicSelect.error'], { ns: 'common' })
|
||||
: documents.length === 0
|
||||
? t(($) => $.noData, { ns: 'common' })
|
||||
: null
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
role="status"
|
||||
className="flex items-center gap-2 px-3 py-2 system-sm-regular text-text-tertiary empty:p-0"
|
||||
>
|
||||
{isSearching && <SpinnerIcon aria-hidden="true" />}
|
||||
{statusText}
|
||||
</div>
|
||||
<MenuList aria-busy={isSearching}>
|
||||
{documents.map((document) => (
|
||||
<MenuLinkItem
|
||||
key={document.id}
|
||||
render={<Link href={`/datasets/${datasetId}/documents/${document.id}`} />}
|
||||
aria-current={document.id === currentDocumentId ? 'page' : undefined}
|
||||
className="gap-2 px-3"
|
||||
>
|
||||
<FileIcon name={document.name} extension={getDocumentExtension(document)} size="lg" />
|
||||
<span className="min-w-0 truncate system-sm-regular text-text-secondary">
|
||||
{document.name}
|
||||
</span>
|
||||
</MenuLinkItem>
|
||||
))}
|
||||
{isError && (
|
||||
<MenuItem closeOnClick={false} onClick={() => documentsQuery.refetch()}>
|
||||
{t(($) => $['operation.retry'], { ns: 'common' })}
|
||||
</MenuItem>
|
||||
)}
|
||||
</MenuList>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
'use client'
|
||||
import type { DocumentWithSegmentsResponse } from '@dify/contracts/api/console/datasets/types.gen'
|
||||
import type { ParentMode } from '@/models/datasets'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Menu,
|
||||
MenuContent,
|
||||
MenuFilterProvider,
|
||||
MenuInput,
|
||||
MenuInputGroup,
|
||||
MenuTrigger,
|
||||
} from '@langgenius/dify-ui/menu'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getUploadFileExtension } from '@/app/components/datasets/documents/document-source'
|
||||
import { ChunkingMode } from '@/models/datasets'
|
||||
import FileIcon from '../document-file-icon'
|
||||
import DocumentList from './document-list'
|
||||
|
||||
// The list query and the document detail query both describe the picked document.
|
||||
export type PickerDocument = Pick<
|
||||
DocumentWithSegmentsResponse,
|
||||
'id' | 'doc_form' | 'data_source_info'
|
||||
> & {
|
||||
name?: string | null
|
||||
data_source_detail_dict?: DocumentWithSegmentsResponse['data_source_detail_dict'] | null
|
||||
}
|
||||
|
||||
type DocumentPickerProps = {
|
||||
datasetId: string
|
||||
currentDocument?: PickerDocument | null
|
||||
parentMode?: ParentMode
|
||||
}
|
||||
|
||||
function getDocumentExtension(document?: PickerDocument | null) {
|
||||
if (!document) return ''
|
||||
|
||||
const detailExtension = document.data_source_detail_dict?.upload_file?.extension
|
||||
if (detailExtension) return detailExtension
|
||||
|
||||
return getUploadFileExtension(document.data_source_info) ?? ''
|
||||
}
|
||||
|
||||
function DocumentPickerTriggerValue({
|
||||
currentDocument: document,
|
||||
parentMode,
|
||||
}: Pick<DocumentPickerProps, 'currentDocument' | 'parentMode'>) {
|
||||
const { t } = useTranslation(['dataset'])
|
||||
const isGeneralMode = document?.doc_form === ChunkingMode.text
|
||||
const isParentChild = document?.doc_form === ChunkingMode.parentChild
|
||||
const isQAMode = document?.doc_form === ChunkingMode.qa
|
||||
const parentModeLabel = (() => {
|
||||
if (!parentMode) return '--'
|
||||
return parentMode === 'paragraph'
|
||||
? t(($) => $['parentMode.paragraph'], { ns: 'dataset' })
|
||||
: t(($) => $['parentMode.fullDoc'], { ns: 'dataset' })
|
||||
})()
|
||||
|
||||
return (
|
||||
<span className="flex min-w-0 items-center gap-1.5">
|
||||
<FileIcon
|
||||
name={document?.name ?? undefined}
|
||||
extension={getDocumentExtension(document)}
|
||||
size="xl"
|
||||
/>
|
||||
<span className="flex min-w-0 flex-col items-start">
|
||||
<span className="flex max-w-full min-w-0 items-center gap-1">
|
||||
<span className="max-w-70 min-w-0 truncate system-md-semibold text-text-primary">
|
||||
{document?.name || '--'}
|
||||
</span>
|
||||
<span
|
||||
className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</span>
|
||||
<span className="flex h-3 max-w-75 items-center gap-0.5 text-text-tertiary">
|
||||
<span
|
||||
className={cn(
|
||||
'size-3 shrink-0',
|
||||
isParentChild
|
||||
? 'i-custom-vender-knowledge-parent-child-chunk'
|
||||
: 'i-custom-vender-knowledge-general-chunk',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className={cn('truncate system-2xs-medium-uppercase', isParentChild && 'mt-0.5')}>
|
||||
{isGeneralMode && t(($) => $['chunkingMode.general'], { ns: 'dataset' })}
|
||||
{isQAMode && t(($) => $['chunkingMode.qa'], { ns: 'dataset' })}
|
||||
{isParentChild &&
|
||||
`${t(($) => $['chunkingMode.parentChild'], { ns: 'dataset' })} · ${parentModeLabel}`}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export function DocumentPicker({ datasetId, currentDocument, parentMode }: DocumentPickerProps) {
|
||||
const { t } = useTranslation(['common'])
|
||||
const [searchValue, setSearchValue] = useState('')
|
||||
|
||||
return (
|
||||
<MenuFilterProvider filter={null} value={searchValue} onValueChange={setSearchValue}>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={currentDocument?.name || t(($) => $['operation.search'], { ns: 'common' })}
|
||||
className="ms-1 flex min-w-0 items-center gap-0.5 rounded-lg px-2 py-1 text-start transition-colors hover:bg-state-base-hover focus-visible:bg-state-base-hover data-popup-open:bg-state-base-hover motion-reduce:transition-none"
|
||||
>
|
||||
<DocumentPickerTriggerValue currentDocument={currentDocument} parentMode={parentMode} />
|
||||
</MenuTrigger>
|
||||
<MenuContent
|
||||
align="start"
|
||||
sideOffset={0}
|
||||
aria-label={t(($) => $['operation.search'], { ns: 'common' })}
|
||||
className="w-90 max-w-(--available-width)"
|
||||
>
|
||||
<MenuInputGroup>
|
||||
<span
|
||||
className="i-ri-search-line size-4 shrink-0 text-text-tertiary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<MenuInput
|
||||
aria-label={t(($) => $['operation.search'], { ns: 'common' })}
|
||||
placeholder={t(($) => $['operation.search'], { ns: 'common' })}
|
||||
/>
|
||||
</MenuInputGroup>
|
||||
<DocumentList
|
||||
datasetId={datasetId}
|
||||
currentDocumentId={currentDocument?.id}
|
||||
searchValue={searchValue}
|
||||
/>
|
||||
</MenuContent>
|
||||
</Menu>
|
||||
</MenuFilterProvider>
|
||||
)
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { DocumentItem } from '@/models/datasets'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { RiArrowDownSLine } from '@remixicon/react'
|
||||
import { useBoolean } from 'ahooks'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
|
||||
import FileIcon from '../document-file-icon'
|
||||
|
||||
type Props = Readonly<{
|
||||
className?: string
|
||||
value?: DocumentItem
|
||||
files: DocumentItem[]
|
||||
onChange: (value: DocumentItem) => void
|
||||
}>
|
||||
|
||||
const PreviewDocumentPicker: FC<Props> = ({ className, value, files, onChange }) => {
|
||||
const { t } = useTranslation(['dataset'])
|
||||
const name = value?.name || ''
|
||||
const extension = value?.extension
|
||||
|
||||
const [open, { set: setOpen }] = useBoolean(false)
|
||||
const ArrowIcon = RiArrowDownSLine
|
||||
|
||||
const handleChange = useCallback(
|
||||
(item: DocumentItem) => {
|
||||
onChange(item)
|
||||
setOpen(false)
|
||||
},
|
||||
[onChange, setOpen],
|
||||
)
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger
|
||||
nativeButton={false}
|
||||
render={
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-6 max-w-full min-w-0 items-center rounded-md px-1 select-none hover:bg-state-base-hover data-popup-open:bg-state-base-hover',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<FileIcon name={name} extension={extension} size="lg" />
|
||||
<div className="ml-1 flex min-w-0 flex-col items-start">
|
||||
<div className="flex max-w-full items-center space-x-0.5">
|
||||
<span
|
||||
className={cn('max-w-50 min-w-0 truncate system-md-semibold text-text-primary')}
|
||||
>
|
||||
{' '}
|
||||
{name || '--'}
|
||||
</span>
|
||||
<ArrowIcon className="h-4.5 w-4.5 shrink-0 text-text-primary" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<PopoverContent
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<div className="w-98 max-w-[calc(100vw-2rem)] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-[5px]">
|
||||
{files?.length > 1 && (
|
||||
<div className="flex h-8 items-center pl-2 system-xs-medium-uppercase text-text-tertiary">
|
||||
{t(($) => $.preprocessDocument, { ns: 'dataset', num: files.length })}
|
||||
</div>
|
||||
)}
|
||||
{files?.length > 0 ? (
|
||||
<PreviewDocumentList list={files} onChange={handleChange} />
|
||||
) : (
|
||||
<div className="mt-2 flex h-25 w-90 items-center justify-center max-sm:w-full">
|
||||
<LoadingPlaceholder />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
export default React.memo(PreviewDocumentPicker)
|
||||
|
||||
function PreviewDocumentList({
|
||||
list,
|
||||
onChange,
|
||||
}: {
|
||||
list: DocumentItem[]
|
||||
onChange: (value: DocumentItem) => void
|
||||
}) {
|
||||
return (
|
||||
<div className="max-h-[calc(100vh-120px)] overflow-auto">
|
||||
{list.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className="flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg border-0 bg-transparent px-2 text-left hover:bg-state-base-hover"
|
||||
onClick={() => onChange(item)}
|
||||
>
|
||||
<FileIcon name={item.name} extension={item.extension} size="lg" />
|
||||
<span className="truncate text-sm text-text-secondary">{item.name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user