feat(asset): show poster and hover preview while video is transcoding (#419)

* feat(asset): show poster and hover preview while video is transcoding

Generate and persist the sprite (and its poster) before the proxy
transcodes run, so the poster/sprite are available in the file list
while the asset is still processing.

Render the preview in the file card behind a translucent processing
overlay instead of a blank skeleton, and replace hardcoded status text
with existing i18n keys.

* feat(asset): pulse the cover and show Preparing/Uploading labels while processing

Drop the processing text overlay on the file card preview in favour of a
subtle pulsing opacity on the cover, and show "Uploading..."/"Preparing..."
in the creator row so the real author and date only appear once the asset
is ready.

* feat(asset): use a hollow ring for the preparing placeholder

Match the geometry of the upload progress ring (empty inside, no
percentage) and hide the duration badge while processing, so the
upload-to-processing transition reads as one continuous animation.

* style(asset): shrink-only preparing ring in muted grey at fixed opacity

Animate only the ring size (1 -> 0.8 -> 1) and hold a constant 0.6
opacity, using a muted grey stroke instead of primary.
This commit is contained in:
Yiling-J
2026-09-19 15:25:41 +08:00
committed by GitHub
parent 09b65a1eb6
commit de634a5dc5
10 changed files with 398 additions and 84 deletions
+1
View File
@@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **release**: Automatically populate GitHub release bodies from CHANGELOG.md and promote unreleased notes during version bumps
- **settings**: Add FFmpeg threads slider to team media processing settings
- **asset**: Show previews of a folder's contents and a "days left" countdown for each item in Recently Deleted
- **asset**: Show the poster and hover preview for a video in the file list while it is still transcoding, with a gently pulsing cover (or an animated waiting circle before the poster is ready), "Uploading..."/"Preparing..." labels, and the duration hidden until it is ready
### Fixed
+2
View File
@@ -105,6 +105,8 @@ apps/web/e2e/
| Upload an image file, wait for transcode, and create a comment with draw | `tests/file/image-draw-comment.spec.ts` |
| Upload a video file, wait for transcode, and create a comment with draw at a non-zero timestamp | `tests/file/video-draw-comment.spec.ts` |
| Upload an audio file, wait for transcode, and create a comment at a non-zero timestamp | `tests/file/audio-timestamp-comment.spec.ts` |
| Show a breathing poster preview and "Preparing..." while a video is still transcoding | `tests/file/processing-preview.spec.ts` |
| Show a preparing circle before the poster is generated | `tests/file/processing-preview.spec.ts` |
## Conventions
@@ -0,0 +1,82 @@
import { expect, test } from '../../fixtures'
import { fileCard } from '../../helpers/files'
// Uploaded as a binary file so no real transcode task races with the simulated mid-transcode
// state we set up directly in the database.
test.use({ fileOptions: { mediaType: 'binary' } })
test('shows the poster preview and "Preparing..." while a video is still transcoding', async ({
file,
prisma,
}) => {
const { page, projectId, fileId, fileName } = file
// Simulate a video that is mid-transcode: the poster/sprite preview already exists, but the
// asset is still marked as processing.
const assetDir = `files/e2e/${fileId}`
await prisma.asset.update({
where: { id: fileId },
data: {
status: 'processing',
mediaType: 'video/mp4',
media: {
duration: 10,
filesize: 0,
frames: 300,
proxyType: 'video',
imageTranscodes: [],
videoTranscodes: [],
sprite: { key: `${assetDir}/sprite.webp`, frames: 100, tileX: 10, tileY: 10 },
poster: { key: `${assetDir}/poster.webp` },
finishedAt: new Date().toISOString(),
metadata: {
originalWidth: 1920,
originalHeight: 1080,
hasAudio: false,
duration: 10,
bitRate: 0,
frameRate: 30,
totalFrames: 300,
startTimecode: '00:00:00:00',
format: {},
},
original: { key: `${assetDir}/original.mp4`, filesizeInBytes: 0, codec: '' },
},
},
})
await page.goto(`/projects/${projectId}`)
const card = fileCard(page, fileName)
await expect(card).toBeVisible()
// The preview (poster thumbnail used as the sprite scrubber base) is rendered instead of a
// blank placeholder, and its opacity breathes while transcoding is in progress.
await expect(card.locator('img[alt="Thumbnail"]')).toBeVisible()
await expect(card.getByTestId('file-card-preview-media')).toHaveClass(/animate-pulse/)
// The creator row is replaced by a "Preparing..." label while transcoding.
await expect(card.getByText(/Preparing|准备中/i)).toBeVisible()
// The duration badge is hidden until the asset is ready.
await expect(card.getByText('00:10')).toHaveCount(0)
})
test('shows a preparing circle before the poster is generated', async ({ file, prisma }) => {
const { page, projectId, fileId, fileName } = file
// Simulate an asset whose upload finished but whose poster does not exist yet.
await prisma.asset.update({
where: { id: fileId },
data: { status: 'processing', mediaType: 'video/mp4' },
})
await page.goto(`/projects/${projectId}`)
const card = fileCard(page, fileName)
await expect(card).toBeVisible()
// A size-breathing circle stands in until the poster is available, with a "Preparing..." label.
await expect(card.getByTestId('file-card-preparing-circle')).toBeVisible()
await expect(card.getByText(/Preparing|准备中/i)).toBeVisible()
})
@@ -402,4 +402,99 @@ describe('transcodeVideoWorkflow', () => {
}),
})
})
it('should persist poster/sprite before transcoding proxies so previews are available early', async () => {
const task: WorkflowTask = {
id: 'task-sprite',
assetId: 'asset-sprite',
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
sessionId: null,
output: null,
payload: {
projectId: 'proj-1',
transcode: {
poster: true,
sprite: true,
videoStrategy: 'best_match',
},
},
createdAt: new Date(),
updatedAt: new Date(),
heartbeat: null,
teamId: 'team-1',
projectId: 'proj-1',
uid: 'task-uid-sprite',
model: null,
inputTokens: 0,
outputTokens: 0,
}
mockActivities.getAssetActivity.mockResolvedValue({
id: 'asset-sprite',
storageKey: { key: 'files/asset-sprite/video.mp4' },
mediaType: 'video/mp4',
})
mockActivities.getMediaInfoActivity.mockResolvedValue({
proxyType: 'video',
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
startTimecode: '00:00:00:00',
bitRate: 1000,
hasAudio: false,
format: {},
},
videoTranscodes: [],
imageTranscodes: [],
})
mockActivities.extractPosterActivity.mockResolvedValue({
poster: { key: 'files/asset-sprite/poster.webp' },
})
mockActivities.generateSpriteActivity.mockResolvedValue({
sprite: { key: 'files/asset-sprite/sprite.webp', frames: 100, tileX: 10, tileY: 10 },
poster: { key: 'files/asset-sprite/poster.webp' },
})
mockActivities.transcodeVideoActivity.mockResolvedValue({
key: 'files/asset-sprite/video-180p.mp4',
width: 320,
height: 180,
})
// Capture a snapshot of the media payload at each commit: the workflow mutates the same
// `mediaInfo` object in place, so the recorded mock call args would reflect the final state.
const commitSnapshots: Array<{ sprite?: unknown; videoTranscodes: unknown[] }> = []
mockActivities.updateAssetMediaActivity.mockImplementation(
(params: { mediaInfo: { sprite?: unknown; videoTranscodes?: unknown[] } }) => {
commitSnapshots.push({
sprite: params.mediaInfo.sprite,
videoTranscodes: [...(params.mediaInfo.videoTranscodes ?? [])],
})
return Promise.resolve()
},
)
await transcodeVideoWorkflow(task)
const spriteOrder = mockActivities.generateSpriteActivity.mock.invocationCallOrder[0]
const firstProxyOrder = mockActivities.transcodeVideoActivity.mock.invocationCallOrder[0]
// Sprite generation must run before any proxy transcode.
expect(spriteOrder).toBeLessThan(firstProxyOrder)
// The media commit that carries the sprite must land before the first proxy transcode too,
// and must not yet contain any proxy transcodes.
const spriteCommitIndex = commitSnapshots.findIndex((snapshot) => snapshot.sprite !== undefined)
expect(spriteCommitIndex).toBeGreaterThanOrEqual(0)
expect(commitSnapshots[spriteCommitIndex].videoTranscodes).toEqual([])
expect(
mockActivities.updateAssetMediaActivity.mock.invocationCallOrder[spriteCommitIndex],
).toBeLessThan(firstProxyOrder)
})
})
@@ -77,6 +77,43 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
})
}
// Generate the sprite (and its poster fallback) before the expensive proxy transcodes so the
// file list can show a poster/sprite preview while the asset is still processing.
if (spec.sprite || (spec.poster && !mediaInfo.poster)) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const spriteSpec: PrismaJson.SpriteInfo = {
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
frames: 100,
tileX: 10,
tileY: 10,
}
const posterSpec: PrismaJson.PosterInfo = mediaInfo.poster || {
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
}
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
taskId: task.id,
assetKey: key,
filePath,
spriteSpec,
posterSpec,
mediaInfo,
})
if (spec.sprite) {
mediaInfo.sprite = spriteResult.sprite
}
if (!mediaInfo.poster) {
mediaInfo.poster = spriteResult.poster
}
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
})
}
const metadata = mediaInfo.metadata
if (mediaInfo.proxyType === 'video' && metadata) {
@@ -138,36 +175,6 @@ export async function transcodeVideoWorkflow(task: WorkflowTask): Promise<void>
mediaInfo.thumbnail = thumbTranscode
}
if (spec.sprite || (spec.poster && !mediaInfo.poster)) {
const lastSlashIndex = key.lastIndexOf('/')
const assetDir = lastSlashIndex === -1 ? '' : key.substring(0, lastSlashIndex)
const spriteSpec: PrismaJson.SpriteInfo = {
key: assetDir ? `${assetDir}/sprite.webp` : 'sprite.webp',
frames: 100,
tileX: 10,
tileY: 10,
}
const posterSpec: PrismaJson.PosterInfo = mediaInfo.poster || {
key: assetDir ? `${assetDir}/poster.webp` : 'poster.webp',
}
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
taskId: task.id,
assetKey: key,
filePath,
spriteSpec,
posterSpec,
mediaInfo,
})
if (spec.sprite) {
mediaInfo.sprite = spriteResult.sprite
}
if (!mediaInfo.poster) {
mediaInfo.poster = spriteResult.poster
}
}
await executeActivity(workerQueue, updateAssetMediaActivity, {
assetId: asset.id,
mediaInfo,
@@ -295,4 +295,91 @@ describe('FileCard', () => {
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()
})
})
@@ -21,7 +21,6 @@ import {
TooltipTrigger,
} from '@/ui/components/ui/tooltip'
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
import { Skeleton } from '@/ui/components/ui/skeleton'
import { formatTimeAgo, getTrashDaysLeft } from '@/ui/lib/time'
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
import { cn } from '@/ui/lib/utils'
@@ -261,6 +260,49 @@ export function FileCard({
? m.n_days_left_singular({ count: daysLeft })
: m.n_days_left_plural({ count: daysLeft })
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
const isProcessing = displayItem.status === 'processing' || displayItem.status === 'uploaded'
// While uploading/transcoding, the creator row is replaced by a short status label so the real
// date/author only appears once the asset is ready.
const statusText =
displayItem.status === 'uploading'
? m.uploading()
: displayItem.status === 'uploaded' || displayItem.status === 'processing'
? m.preparing()
: null
const previewBadges =
daysLeft !== null ||
(typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0) ? (
<div
data-testid="file-card-preview-badges"
className="pointer-events-none absolute bottom-1 left-1 z-10 flex items-center gap-1"
>
{daysLeft !== null && (
<span
data-testid="file-card-days-left"
title={daysLeftTooltip}
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
>
<Clock className="h-3.5 w-3.5" />
<span>{m.days_left_short({ count: daysLeft })}</span>
</span>
)}
{typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0 && (
<span
data-testid="file-card-comments-count"
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
>
<MessageCircleMore className="h-3.5 w-3.5" />
<span>{displayItem.commentsCount}</span>
</span>
)}
</div>
) : null
return (
<div
ref={setNodeRef}
@@ -312,63 +354,48 @@ export function FileCard({
</div>
<div className="relative aspect-square overflow-hidden bg-muted/30">
{displayItem.status === 'uploading' ||
displayItem.status === 'processing' ||
displayItem.status === 'uploaded' ||
displayItem.status === 'error' ? (
{displayItem.status === 'uploading' ? (
<div className="flex h-full w-full items-center justify-center bg-background/50">
{displayItem.status !== 'error' && (
<Skeleton className="absolute inset-0 h-full w-full" />
)}
{displayItem.status === 'uploading' ? (
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
) : (
<span
className={cn(
'z-10 font-medium px-2 text-center text-sm',
displayItem.status === 'error'
? 'text-destructive font-semibold'
: 'text-muted-foreground capitalize',
)}
>
{displayItem.status === 'uploaded'
? 'Processing'
: displayItem.status === 'error'
? 'Failed to upload'
: displayItem.status}
</span>
)}
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
</div>
) : hasPreview ? (
<>
<div
data-testid="file-card-preview-media"
className={cn('h-full w-full', isProcessing && 'animate-pulse')}
>
<FilePreview item={displayItem} showDuration={!isProcessing} />
</div>
{previewBadges}
</>
) : displayItem.status === 'error' ? (
<div className="flex h-full w-full items-center justify-center bg-background/50">
<span className="z-10 font-medium px-2 text-center text-sm text-destructive font-semibold">
{m.failed_to_upload()}
</span>
</div>
) : displayItem.status === 'processing' || displayItem.status === 'uploaded' ? (
<div className="flex h-full w-full items-center justify-center">
{/* Same geometry as the upload progress ring, but empty inside and no percentage. */}
<svg
viewBox="0 0 50 50"
data-testid="file-card-preparing-circle"
className="h-16 w-16 opacity-60 animate-preparing-breathe"
>
<circle
cx="25"
cy="25"
r="20"
className="stroke-muted-foreground"
strokeWidth="4"
fill="transparent"
/>
</svg>
</div>
) : (
<>
<FilePreview item={displayItem} showDuration />
{(daysLeft !== null ||
(typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0)) && (
<div
data-testid="file-card-preview-badges"
className="pointer-events-none absolute bottom-1 left-1 z-10 flex items-center gap-1"
>
{daysLeft !== null && (
<span
data-testid="file-card-days-left"
title={daysLeftTooltip}
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
>
<Clock className="h-3.5 w-3.5" />
<span>{m.days_left_short({ count: daysLeft })}</span>
</span>
)}
{typeof displayItem.commentsCount === 'number' && displayItem.commentsCount > 0 && (
<span
data-testid="file-card-comments-count"
className="flex items-center gap-1 rounded bg-black/60 px-1 py-0.5 text-xs font-medium tabular-nums text-white"
>
<MessageCircleMore className="h-3.5 w-3.5" />
<span>{displayItem.commentsCount}</span>
</span>
)}
</div>
)}
{previewBadges}
</>
)}
</div>
@@ -405,7 +432,7 @@ export function FileCard({
>
<TooltipTrigger asChild>
<p ref={creatorRef} className="text-sm text-muted-foreground line-clamp-2 h-[2lh]">
{creatorText}
{statusText ?? creatorText}
</p>
</TooltipTrigger>
{isCreatorTooltipOpen && (
+11
View File
@@ -114,9 +114,20 @@
--color-sidebar-ring: var(--sidebar-ring);
--animate-upload-breathing: upload-breathing 2s cubic-bezier(0.4, 0, 0.6, 1) infinite alternate;
--animate-preparing-breathe: preparing-breathe 1.6s ease-in-out infinite;
--animate-drift-slow: drift-slow 15s ease-in-out infinite alternate;
--animate-drift-medium: drift-medium 12s ease-in-out infinite alternate;
@keyframes preparing-breathe {
0%,
100% {
transform: scale(1);
}
50% {
transform: scale(0.8);
}
}
@keyframes upload-breathing {
0% {
filter: drop-shadow(0 0 1px rgb(var(--primary)));
+1
View File
@@ -132,6 +132,7 @@
"activity_notifications": "Activity Notifications",
"activity_notifications_description": "Receive in-app updates for comments, uploads, and automated background analysis tasks inside this project.",
"processing": "Processing...",
"preparing": "Preparing...",
"project_updated": "Project updated",
"failed_update_project": "Failed to update project",
"project_notification_updated": "Project notification settings updated",
+1
View File
@@ -132,6 +132,7 @@
"activity_notifications": "活动通知",
"activity_notifications_description": "接收此项目中评论、上传及自动后台分析任务的应用内通知。",
"processing": "处理中...",
"preparing": "准备中...",
"project_updated": "项目已更新",
"failed_update_project": "更新项目失败",
"project_notification_updated": "项目通知设置已更新",