Files
shumai/packages/webui/components/file-browser/file-card.test.tsx
T
Yiling-J 22fede0290 fix(webui): prevent clipping of long text overlay and date picker in cards (#490)
* fix(webui): prevent clipping of long text overlay and date picker in cards

* docs: update DeepWiki badge url in README and README_CN

* fix(webui): preserve expanded overlay height and textarea style in LongTextField

* fix(webui): add bottom padding to file list to prevent screen clipping of expanded fields

* fix(webui): expand directly into edit mode on single click for LongTextField

* fix(webui): prevent file selection when interacting with metadata fields in cards and list rows
2026-10-24 11:40:47 +08:00

578 lines
18 KiB
TypeScript

// @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'
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<React.ComponentProps<typeof FileCard>> = {}) => {
return render(
<QueryClientProvider client={queryClient}>
<FileCard
item={stackItem}
isSelected={false}
isChecked={false}
isEditing={false}
onSelect={vi.fn()}
onDoubleClick={vi.fn()}
onContextMenu={vi.fn()}
onDragStart={vi.fn()}
onDrop={vi.fn()}
onRename={vi.fn()}
onFinishEditing={vi.fn()}
onSaveField={vi.fn()}
fields={[]}
canEdit={true}
{...props}
/>
</QueryClientProvider>,
)
}
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 "Uploading..." in place of the creator while uploading', () => {
const uploadingItem: AssetInfo = {
...fileItem,
status: 'uploading',
creator: { id: 'u1', name: 'Alice' },
} as AssetInfo
renderComponent({ item: uploadingItem })
expect(screen.getByText(/Uploading|上传中/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()
})
})