// @vitest-environment happy-dom import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' import React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { FileCard } from './file-card' import type { AssetInfo } from '@shumai/dtos' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { useUploadStore } from '@/ui/stores/upload' vi.mock('@dnd-kit/react', () => ({ useDraggable: () => ({ ref: vi.fn(), isDragging: false, }), useDroppable: () => ({ ref: vi.fn(), isDropTarget: false, }), })) vi.mock('@/ui/api/client', () => ({ client: { api: { files: { ':fileId': { $get: vi.fn().mockResolvedValue({ ok: true, json: async () => ({}), }), }, }, }, }, })) describe('FileCard', () => { let queryClient: QueryClient beforeEach(() => { queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } }, }) }) afterEach(() => { cleanup() }) const stackItem: AssetInfo = { id: 'stack-123', name: 'version_stack_test', type: 'version_stack', status: 'processed', fileCount: 2, createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z', } as AssetInfo const fileItem: AssetInfo = { id: 'file-123', name: 'regular_file.png', type: 'file', status: 'processed', createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z', } as AssetInfo const renderComponent = (props: Partial> = {}) => { return render( , ) } it('renders Manage versions in 3-dot dropdown menu for version_stack item', () => { const onAction = vi.fn() renderComponent({ item: stackItem, onAction }) const moreBtn = screen.getByRole('button', { name: '' }) fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' }) const manageItem = screen.getByText(/Manage versions|管理版本/i) expect(manageItem).toBeTruthy() fireEvent.click(manageItem) expect(onAction).toHaveBeenCalledWith('manage-versions', stackItem) }) it('does not render Manage versions in 3-dot dropdown menu for regular file item', () => { renderComponent({ item: fileItem }) const moreBtn = screen.getByRole('button', { name: '' }) fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' }) expect(screen.queryByText(/Manage versions|管理版本/i)).toBeNull() }) it('renders Bot icon badge and user via agent creator when agent created the asset', () => { const agentCreatedItem: AssetInfo = { ...fileItem, creator: { id: 'u1', name: 'Alice' }, agentId: 'agent-1', agent: { id: 'agent-1', name: 'Copilot Bot' }, } as AssetInfo renderComponent({ item: agentCreatedItem }) const agentBadge = screen.getByTestId('agent-badge') expect(agentBadge).toBeTruthy() expect(agentBadge.getAttribute('title')).toBe('Copilot Bot') expect(agentBadge.textContent).toBe('AI') // Should show user via agent in author line expect(screen.getByText(/Alice via Copilot Bot|Alice 通过 Copilot Bot/i)).toBeTruthy() }) it('renders both AI text badge and version badge side-by-side on version stack', () => { const agentStackItem: AssetInfo = { ...stackItem, creator: { id: 'u1', name: 'Alice' }, agentId: 'agent-1', agent: { id: 'agent-1', name: 'Copilot Bot' }, versionStack: { versions: [ { id: 'v1', version: 1, name: 'v1' }, { id: 'stack-123', version: 2, name: 'v2' }, ], }, } as AssetInfo renderComponent({ item: agentStackItem }) const agentBadge = screen.getByTestId('agent-badge') expect(agentBadge).toBeTruthy() expect(agentBadge.textContent).toBe('AI') expect(screen.getByText('v2')).toBeTruthy() }) it('applies line-clamp-2 and h-[2lh] to creation info paragraph', () => { const itemWithCreator: AssetInfo = { ...fileItem, creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: itemWithCreator }) const creatorParagraph = screen.getByText(/Alice/i) expect(creatorParagraph.className).toContain('line-clamp-2') expect(creatorParagraph.className).toContain('h-[2lh]') }) it('does not show tooltip on hover when creator text is not truncated', () => { vi.useFakeTimers() const itemWithCreator: AssetInfo = { ...fileItem, creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: itemWithCreator }) const creatorParagraph = screen.getByText(/Alice/i) Object.defineProperty(creatorParagraph, 'scrollHeight', { value: 30, configurable: true }) Object.defineProperty(creatorParagraph, 'clientHeight', { value: 40, configurable: true }) Object.defineProperty(creatorParagraph, 'scrollWidth', { value: 100, configurable: true }) Object.defineProperty(creatorParagraph, 'clientWidth', { value: 150, configurable: true }) fireEvent.pointerMove(creatorParagraph, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(200) }) expect(screen.queryByRole('tooltip')).toBeNull() vi.useRealTimers() }) it('shows tooltip on hover when creator text is truncated', () => { vi.useFakeTimers() const itemWithCreator: AssetInfo = { ...fileItem, creator: { id: 'u1', name: 'Very Long Creator Name That Wraps' }, } as AssetInfo renderComponent({ item: itemWithCreator }) const creatorParagraph = screen.getByText(/Very Long Creator Name/i) Object.defineProperty(creatorParagraph, 'scrollHeight', { value: 80, configurable: true }) Object.defineProperty(creatorParagraph, 'clientHeight', { value: 40, configurable: true }) fireEvent.pointerMove(creatorParagraph, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(200) }) const tooltip = screen.getByRole('tooltip') expect(tooltip).toBeTruthy() expect(tooltip.textContent).toContain('Very Long Creator Name') vi.useRealTimers() }) it('renders comments count badge in preview area when commentsCount > 0', () => { const itemWithComments: AssetInfo = { ...fileItem, commentsCount: 5, } as AssetInfo renderComponent({ item: itemWithComments }) const wrapper = screen.getByTestId('file-card-preview-badges') expect(wrapper.className).toContain('absolute') expect(wrapper.className).toContain('bottom-1') expect(wrapper.className).toContain('left-1') expect(wrapper.className).toContain('pointer-events-none') const commentsBadge = screen.getByTestId('file-card-comments-count') expect(commentsBadge.textContent).toContain('5') expect(commentsBadge.className).toContain('bg-black/60') expect(commentsBadge.className).toContain('text-white') expect(commentsBadge.className).toContain('tabular-nums') }) it('does not render comments count badge when commentsCount is 0 or undefined', () => { const itemZeroComments: AssetInfo = { ...fileItem, commentsCount: 0, } as AssetInfo const { unmount } = renderComponent({ item: itemZeroComments }) expect(screen.queryByTestId('file-card-comments-count')).toBeNull() unmount() const itemNoComments: AssetInfo = { ...fileItem, commentsCount: undefined, } as AssetInfo renderComponent({ item: itemNoComments }) expect(screen.queryByTestId('file-card-comments-count')).toBeNull() }) it('renders the days-left badge in preview area for recently deleted items', () => { const deletedItem: AssetInfo = { ...fileItem, deletedAt: new Date().toISOString(), } as AssetInfo renderComponent({ item: deletedItem, isRecentlyDeleted: true }) const badge = screen.getByTestId('file-card-days-left') expect(badge.textContent).toMatch(/30\s*(d|天)/) }) it('places the comments badge to the right of the days-left badge', () => { const deletedItem: AssetInfo = { ...fileItem, deletedAt: new Date().toISOString(), commentsCount: 3, } as AssetInfo renderComponent({ item: deletedItem, isRecentlyDeleted: true }) const wrapper = screen.getByTestId('file-card-preview-badges') const order = Array.from(wrapper.children).map((child) => child.getAttribute('data-testid')) expect(order).toEqual(['file-card-days-left', 'file-card-comments-count']) }) it('does not render the days-left badge outside of recently deleted', () => { const deletedItem: AssetInfo = { ...fileItem, deletedAt: new Date().toISOString(), } as AssetInfo renderComponent({ item: deletedItem, isRecentlyDeleted: false }) expect(screen.queryByTestId('file-card-days-left')).toBeNull() }) it('does not render the days-left badge when deletedAt is missing', () => { renderComponent({ item: fileItem, isRecentlyDeleted: true }) expect(screen.queryByTestId('file-card-days-left')).toBeNull() }) it('breathes the preview and shows "Preparing..." in place of the creator while processing', () => { const processingItem: AssetInfo = { ...fileItem, status: 'processing', creator: { id: 'u1', name: 'Alice' }, preview: { proxyType: 'video', thumbnailUrl: 'https://example.com/poster.webp', spriteUrl: 'https://example.com/sprite.webp', originalWidth: 1920, originalHeight: 1080, duration: 10, }, } as AssetInfo renderComponent({ item: processingItem }) // The preview (sprite scrubber base thumbnail) is rendered and breathes instead of an overlay. const media = screen.getByTestId('file-card-preview-media') expect(media.className).toContain('animate-pulse') expect(screen.getByAltText('Thumbnail').getAttribute('src')).toBe( 'https://example.com/poster.webp', ) // The creator row is replaced by the status label while processing. expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy() expect(screen.queryByText(/Alice/i)).toBeNull() // The duration badge is hidden until the asset is ready. expect(screen.queryByText('00:10')).toBeNull() }) it('shows "[User] is uploading..." and indeterminate circle for remote viewer', () => { const uploadingItem: AssetInfo = { ...fileItem, status: 'uploading', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: uploadingItem }) expect(screen.getByText(/Alice.*(is uploading|正在上传)/i)).toBeTruthy() expect(screen.getByTestId('file-card-remote-uploading-circle')).toBeTruthy() }) it('shows "Uploading..." during local warm-up and progress circle for local uploader', () => { useUploadStore.setState({ fileProgress: { 'file-1': { fileId: 'file-1', name: 'photo.jpg', loaded: 100, total: 1000, status: 'uploading', }, }, }) const uploadingItem: AssetInfo = { ...fileItem, id: 'file-1', status: 'uploading', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: uploadingItem }) expect(screen.getByText(/Uploading|上传中/i)).toBeTruthy() expect(screen.queryByTestId('file-card-remote-uploading-circle')).toBeNull() }) it('shows dynamic ETA and speed for local uploader when available', () => { useUploadStore.setState({ fileProgress: { 'file-1': { fileId: 'file-1', name: 'photo.jpg', loaded: 500, total: 1000, status: 'uploading', speed: 400 * 1024, eta: 480, // 8 minutes }, }, }) const uploadingItem: AssetInfo = { ...fileItem, id: 'file-1', status: 'uploading', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: uploadingItem }) expect(screen.getByText(/8m.*(left|剩余).*409\.6 KB\/s/i)).toBeTruthy() }) it('shows failed state when fileProgress marks upload as failed', () => { useUploadStore.setState({ fileProgress: { 'file-1': { fileId: 'file-1', name: 'photo.jpg', loaded: 100, total: 1000, status: 'failed', }, }, }) const uploadingItem: AssetInfo = { ...fileItem, id: 'file-1', status: 'uploading', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: uploadingItem }) expect(screen.getAllByText(/Failed to upload|上传失败/i).length).toBeGreaterThan(0) expect(screen.queryByTestId('file-card-remote-uploading-circle')).toBeNull() }) it('transitions from uploading to preparing circle when upload store marks file completed', () => { useUploadStore.setState({ fileProgress: { 'file-uploading': { fileId: 'file-uploading', name: 'clip.mp4', loaded: 1000, total: 1000, status: 'completed', }, }, }) const uploadingItem: AssetInfo = { ...fileItem, id: 'file-uploading', status: 'uploading', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: uploadingItem }) expect(screen.queryByTestId('file-card-preview-media')).toBeNull() const circle = screen.getByTestId('file-card-preparing-circle') expect(circle.tagName.toLowerCase()).toBe('svg') expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy() expect(screen.queryByText(/Alice/i)).toBeNull() }) it('shows a preparing circle and "Preparing..." when processing without a preview yet', () => { const processingItem: AssetInfo = { ...fileItem, status: 'processing', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: processingItem }) expect(screen.queryByTestId('file-card-preview-media')).toBeNull() const circle = screen.getByTestId('file-card-preparing-circle') expect(circle.tagName.toLowerCase()).toBe('svg') expect(circle.querySelector('circle')?.getAttribute('fill')).toBe('transparent') expect(screen.getByText(/Preparing|准备中/i)).toBeTruthy() expect(screen.queryByText(/Alice/i)).toBeNull() }) it('stops breathing the preview and shows the creator once processed', () => { const processedItem: AssetInfo = { ...fileItem, status: 'processed', creator: { id: 'u1', name: 'Alice' }, preview: { proxyType: 'video', thumbnailUrl: 'https://example.com/poster.webp', duration: 10, }, } as AssetInfo renderComponent({ item: processedItem }) const media = screen.getByTestId('file-card-preview-media') expect(media.className).not.toContain('animate-pulse') expect(screen.getByAltText('Preview').getAttribute('src')).toBe( 'https://example.com/poster.webp', ) expect(screen.getByText(/Alice/i)).toBeTruthy() // The duration badge appears once processing is done. expect(screen.getByText('00:10')).toBeTruthy() }) it('renders failed state with alert icon and shows creator at bottom when status is failed without a preview', () => { const failedItem: AssetInfo = { ...fileItem, status: 'failed', creator: { id: 'u1', name: 'Alice' }, } as AssetInfo renderComponent({ item: failedItem }) expect(screen.queryByTestId('file-card-preparing-circle')).toBeNull() const failedState = screen.getByTestId('file-card-failed-state') expect(failedState).toBeTruthy() expect(screen.getByText(/Processing failed|处理失败/i)).toBeTruthy() expect(screen.getByText(/Alice/i)).toBeTruthy() }) it('renders thumbnail with failed badge in top-right corner, shows error in tooltip on hover, and shows creator at bottom', () => { vi.useFakeTimers() const failedItemWithPreview: AssetInfo = { ...fileItem, status: 'failed', creator: { id: 'u1', name: 'Alice' }, media: { error: 'FFmpeg transcode failed: exit code 1', }, preview: { proxyType: 'video', thumbnailUrl: 'https://example.com/poster.webp', duration: 10, }, } as AssetInfo renderComponent({ item: failedItemWithPreview }) const media = screen.getByTestId('file-card-preview-media') expect(media.className).not.toContain('animate-pulse') const badge = screen.getByTestId('file-card-failed-badge') expect(badge).toBeTruthy() expect(badge.textContent).toMatch(/Transcoding Failed|转码失败/i) expect(badge.querySelector('svg')).toBeNull() // Failed badge is in the top-right container const rightTopContainer = badge.closest('.absolute.right-2.top-2') expect(rightTopContainer).toBeTruthy() // Creator is still shown at the bottom of the card expect(screen.getByText(/Alice/i)).toBeTruthy() // Hovering the badge reveals the error message in tooltip fireEvent.pointerMove(badge, { pointerType: 'mouse' }) act(() => { vi.advanceTimersByTime(200) }) const tooltip = screen.getByRole('tooltip') expect(tooltip).toBeTruthy() expect(tooltip.textContent).toContain('FFmpeg transcode failed: exit code 1') vi.useRealTimers() }) it('does not render selection checkbox when hideCheckbox is true', () => { renderComponent({ item: fileItem, hideCheckbox: true }) expect(screen.queryByRole('checkbox')).toBeNull() }) it('renders selection checkbox by default when hideCheckbox is false or omitted', () => { renderComponent({ item: fileItem }) expect(screen.getByRole('checkbox')).toBeTruthy() }) it('does not render 3-dot dropdown menu when hideActions is true', () => { renderComponent({ item: fileItem, hideActions: true }) // No dropdown trigger button rendered expect(screen.queryByRole('button')).toBeNull() }) it('renders matched duration chunk in preview when startTime and endTime are present', () => { const videoWithMatch: AssetInfo = { ...fileItem, startTime: 65, endTime: 125, preview: { proxyType: 'video', thumbnailUrl: 'https://example.com/poster.webp', duration: 300, }, } as AssetInfo renderComponent({ item: videoWithMatch }) const matchedDuration = screen.getByTestId('file-preview-matched-duration') expect(matchedDuration).toBeTruthy() expect(matchedDuration.textContent).toBe('01:05 - 02:05') }) it('renders custom fields and allows expanding longText in FileCard', () => { const itemWithFields: AssetInfo = { ...fileItem, fieldValues: [ { fieldId: 'field_long_text', value: 'Line 1\nLine 2\nLine 3\nLine 4', }, ], } as AssetInfo const fields = [ { id: 'field_long_text', name: 'Notes', scope: 'project', readOnly: false, visible: true, description: '', config: { type: 'longText' as const, name: 'Notes', }, }, ] renderComponent({ item: itemWithFields, fields }) expect(screen.getByText('Notes')).toBeTruthy() const collapsed = screen.getByTestId('long-text-placeholder') expect(collapsed).toBeTruthy() // Expanding directly enters editing mode on single click fireEvent.click(collapsed) const textarea = screen.getByRole('textbox') as HTMLTextAreaElement expect(textarea).toBeTruthy() expect(textarea.value).toContain('Line 1') expect(textarea.value).toContain('Line 4') }) it('does not trigger onSelect when clicking a single line text field or number field to edit', () => { const onSelect = vi.fn() const itemWithFields: AssetInfo = { ...fileItem, fieldValues: [ { fieldId: 'field_text', value: 'Single line text', }, { fieldId: 'field_number', value: 42, }, ], } as AssetInfo const fields = [ { id: 'field_text', name: 'Title', scope: 'project', readOnly: false, visible: true, description: '', config: { type: 'text' as const, name: 'Title', }, }, { id: 'field_number', name: 'Score', scope: 'project', readOnly: false, visible: true, description: '', config: { type: 'number' as const, name: 'Score', }, }, ] renderComponent({ item: itemWithFields, fields, onSelect }) // Click single line text field const textField = screen.getByText('Single line text') fireEvent.click(textField) expect(screen.getByDisplayValue('Single line text')).toBeTruthy() expect(onSelect).not.toHaveBeenCalled() // Click number field const numberField = screen.getByText('42') fireEvent.click(numberField) expect(screen.getByDisplayValue('42')).toBeTruthy() expect(onSelect).not.toHaveBeenCalled() }) it('renders Archived, Archiving, and Restoring badges and Archive / Restore menu actions when archiveStorageEnabled is true', () => { const onAction = vi.fn() const archivedItem: AssetInfo = { ...fileItem, status: 'archived', } as AssetInfo const { rerender } = render( , ) expect(screen.getByTestId('file-card-archived-badge')).toBeTruthy() const moreBtn = screen.getByRole('button', { name: '' }) fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' }) const restoreItem = screen.getByTestId('file-card-restore-archive-action') expect(restoreItem).toBeTruthy() fireEvent.click(restoreItem) expect(onAction).toHaveBeenCalledWith('restore-archive', archivedItem) rerender( , ) expect(screen.getByTestId('file-card-archiving-badge')).toBeTruthy() rerender( , ) expect(screen.getByTestId('file-card-restoring-badge')).toBeTruthy() }) it('renders Copy submenu in dropdown menu', () => { render( , ) const moreBtn = screen.getByRole('button', { name: '' }) fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' }) const copyOption = screen.getByText(/^Copy$|^复制$/i) expect(copyOption).toBeTruthy() }) it('triggers onDoubleClick on single card body click in public share view even when checked', () => { const onSelect = vi.fn() const onDoubleClick = vi.fn() renderComponent({ item: fileItem, isPublic: true, isChecked: true, onSelect, onDoubleClick, }) const card = screen.getByTestId('file-card') fireEvent.click(card) expect(onDoubleClick).toHaveBeenCalledWith(fileItem) expect(onSelect).not.toHaveBeenCalled() }) it('does not trigger onDoubleClick multiple times on double-click in public share view', () => { const onSelect = vi.fn() const onDoubleClick = vi.fn() renderComponent({ item: fileItem, isPublic: true, onSelect, onDoubleClick, }) const card = screen.getByTestId('file-card') // Click 1 (detail = 1) fireEvent.click(card, { detail: 1 }) // Click 2 (detail = 2) fireEvent.click(card, { detail: 2 }) // Double click event fireEvent.doubleClick(card) expect(onDoubleClick).toHaveBeenCalledTimes(1) expect(onDoubleClick).toHaveBeenCalledWith(fileItem) }) it('triggers onSelect instead of onDoubleClick on public share card when clicking with modifier keys', () => { const onSelect = vi.fn() const onDoubleClick = vi.fn() renderComponent({ item: fileItem, isPublic: true, onSelect, onDoubleClick, }) const card = screen.getByTestId('file-card') fireEvent.click(card, { shiftKey: true }) expect(onDoubleClick).not.toHaveBeenCalled() expect(onSelect).toHaveBeenCalledWith(fileItem, expect.anything()) }) it('preserves multi-selection in internal workspace when clicking an already selected card body', () => { const onSelect = vi.fn() const onDoubleClick = vi.fn() renderComponent({ item: fileItem, isPublic: false, isChecked: true, selectedCount: 3, onSelect, onDoubleClick, }) const card = screen.getByTestId('file-card') fireEvent.click(card) expect(onSelect).not.toHaveBeenCalled() expect(onDoubleClick).not.toHaveBeenCalled() }) it('calls onSelect when clicking an unselected card body in internal workspace', () => { const onSelect = vi.fn() renderComponent({ item: fileItem, isPublic: false, isChecked: false, selectedCount: 3, onSelect, }) const card = screen.getByTestId('file-card') fireEvent.click(card) expect(onSelect).toHaveBeenCalledWith(fileItem, expect.anything()) }) it('calls onSelect with { isCheckbox: true } when checkbox is clicked directly', () => { const onSelect = vi.fn() const onDoubleClick = vi.fn() renderComponent({ item: fileItem, isPublic: true, onSelect, onDoubleClick, }) const checkbox = screen.getByRole('checkbox') fireEvent.click(checkbox) expect(onDoubleClick).not.toHaveBeenCalled() expect(onSelect).toHaveBeenCalledWith(fileItem, expect.anything(), { isCheckbox: true }) }) })