mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
feat(upload): simplify upload file list display and add live speed & ETA (#513)
* feat(upload): simplify upload file list display and add live speed and ETA * fix(upload): retain authoritative server search results and handle local failed upload state gracefully
This commit is contained in:
@@ -13,7 +13,6 @@ import type {
|
||||
AssetInfo,
|
||||
CollectionInfo,
|
||||
CreateUploadTaskRequest,
|
||||
FileNode,
|
||||
SearchCondition,
|
||||
SearchSort,
|
||||
ShareLinkInfo,
|
||||
@@ -251,16 +250,7 @@ export function FileBrowser({
|
||||
}
|
||||
}
|
||||
|
||||
const [localUploadingFiles, setLocalUploadingFiles] = useState<AssetInfo[]>([])
|
||||
const fileProgress = useUploadStore((state) => state.fileProgress)
|
||||
|
||||
const displayedFiles = useMemo(() => {
|
||||
const existingIds = new Set(files.map((f) => f.id))
|
||||
const filteredLocal = localUploadingFiles
|
||||
.filter((f) => !existingIds.has(f.id))
|
||||
.filter((f) => fileProgress[f.id!]?.status !== 'failed')
|
||||
return [...filteredLocal, ...files]
|
||||
}, [files, localUploadingFiles, fileProgress])
|
||||
const displayedFiles = files
|
||||
|
||||
useBatchFileStatus({ teamId, items: displayedFiles })
|
||||
|
||||
@@ -598,7 +588,6 @@ export function FileBrowser({
|
||||
},
|
||||
onSuccess: async (data, variables, context) => {
|
||||
const currentFiles = context?.files || []
|
||||
const isCurrentFolderUpload = variables.json.parentId === assetId
|
||||
|
||||
// Register task and files in the store for real-time progress tracking
|
||||
const filesProgressInfo = currentFiles
|
||||
@@ -623,60 +612,10 @@ export function FileBrowser({
|
||||
startTask(data.taskId, taskName, filesProgressInfo)
|
||||
}
|
||||
|
||||
let batchIds: Set<string> | null = null
|
||||
if (isCurrentFolderUpload) {
|
||||
const newLocalFiles: AssetInfo[] = currentFiles
|
||||
.filter((f) => {
|
||||
const path = (f.file.webkitRelativePath || f.file.name).split('/')
|
||||
return path.length === 1
|
||||
})
|
||||
.map((f) => {
|
||||
const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id)
|
||||
const urlInfo = (
|
||||
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||
)?.find((p) => p.id === f.id)
|
||||
const fileId = assetInfo?.assetId || urlInfo?.fileId || f.id
|
||||
const hasUrl = !!urlInfo && !!urlInfo.url
|
||||
return {
|
||||
id: fileId,
|
||||
name: f.file.name,
|
||||
sizeByte: f.file.size,
|
||||
fileCount: 0,
|
||||
type: 'file',
|
||||
status: hasUrl ? 'uploading' : 'error',
|
||||
proxyType:
|
||||
f.file.name.toLowerCase().endsWith('.wma') && f.file.type?.startsWith('video/')
|
||||
? 'audio'
|
||||
: f.file.type?.startsWith('image/')
|
||||
? 'image'
|
||||
: f.file.type?.startsWith('video/')
|
||||
? 'video'
|
||||
: f.file.type?.startsWith('audio/')
|
||||
? 'audio'
|
||||
: f.file.name.endsWith('.pdf') ||
|
||||
f.file.name.endsWith('.txt') ||
|
||||
f.file.name.endsWith('.csv') ||
|
||||
f.file.name.endsWith('.md') ||
|
||||
f.file.name.endsWith('.markdown')
|
||||
? 'pdf'
|
||||
: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
})
|
||||
batchIds = new Set(newLocalFiles.map((f) => f.id!))
|
||||
setLocalUploadingFiles((prev) => [...newLocalFiles, ...prev])
|
||||
}
|
||||
|
||||
// Invalidate queries immediately only if newly created folders appear
|
||||
const hasCreatedFolders = (variables.json.files as FileNode[]).some(
|
||||
(f) => f.children && f.children.length > 0,
|
||||
)
|
||||
if (hasCreatedFolders) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
}
|
||||
// Invalidate queries immediately so newly created assets (and folders) appear
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'upload', 'tasks'],
|
||||
})
|
||||
@@ -690,16 +629,12 @@ export function FileBrowser({
|
||||
storageBackend: (data.storageBackend as 's3' | 'local') || 'local',
|
||||
createdAssets: data.createdAssets,
|
||||
presignedUrls: data.presignedUrls,
|
||||
onFileFinished: (fileId) => {
|
||||
setLocalUploadingFiles((prev) => prev.filter((f) => f.id !== fileId))
|
||||
onFileFinished: () => {
|
||||
throttledInvalidateSearch()
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
throttledInvalidateSearch.cancel()
|
||||
if (batchIds) {
|
||||
setLocalUploadingFiles((prev) => prev.filter((f) => !batchIds!.has(f.id!)))
|
||||
}
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['search', teamId, assetId],
|
||||
})
|
||||
|
||||
@@ -329,7 +329,7 @@ describe('FileCard', () => {
|
||||
expect(screen.queryByText('00:10')).toBeNull()
|
||||
})
|
||||
|
||||
it('shows "Uploading..." in place of the creator while uploading', () => {
|
||||
it('shows "[User] is uploading..." and indeterminate circle for remote viewer', () => {
|
||||
const uploadingItem: AssetInfo = {
|
||||
...fileItem,
|
||||
status: 'uploading',
|
||||
@@ -338,8 +338,87 @@ describe('FileCard', () => {
|
||||
|
||||
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.queryByText(/Alice/i)).toBeNull()
|
||||
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', () => {
|
||||
|
||||
@@ -21,7 +21,8 @@ import {
|
||||
TooltipTrigger,
|
||||
} from '@/ui/components/ui/tooltip'
|
||||
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||
import { formatTimeAgo, getTrashDaysLeft } from '@/ui/lib/time'
|
||||
import { formatRemainingTimeSeconds, formatTimeAgo, getTrashDaysLeft } from '@/ui/lib/time'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
@@ -266,16 +267,38 @@ export function FileCard({
|
||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
||||
const isFailed = displayItem.status === 'failed'
|
||||
const isLocalUploader = Boolean(fileUploadState)
|
||||
const isUploadFailed = fileUploadState?.status === 'failed'
|
||||
const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone && !isUploadFailed
|
||||
const isProcessing =
|
||||
displayItem.status === 'processing' ||
|
||||
displayItem.status === 'uploaded' ||
|
||||
(displayItem.status === 'uploading' && isUploadDone)
|
||||
|
||||
// While uploading/transcoding, the creator row is replaced by a short status label so the real
|
||||
// While uploading/transcoding/error, the creator row is replaced by a status label so the real
|
||||
// date/author only appears once the asset is ready or failed.
|
||||
const statusText = isUploading ? m.uploading() : isProcessing ? m.preparing() : null
|
||||
let statusText: string | null = null
|
||||
if (isUploadFailed || displayItem.status === 'error') {
|
||||
statusText = m.failed_to_upload()
|
||||
} else if (isUploading) {
|
||||
if (isLocalUploader) {
|
||||
if (fileUploadState?.speed && fileUploadState?.eta != null) {
|
||||
statusText = m.upload_eta_speed({
|
||||
eta: formatRemainingTimeSeconds(fileUploadState.eta),
|
||||
speed: `${formatSize(fileUploadState.speed)}/s`,
|
||||
})
|
||||
} else {
|
||||
statusText = m.uploading()
|
||||
}
|
||||
} else {
|
||||
statusText = m.user_is_uploading({
|
||||
user: displayItem.creator?.name || m.someone(),
|
||||
})
|
||||
}
|
||||
} else if (isProcessing) {
|
||||
statusText = m.preparing()
|
||||
}
|
||||
|
||||
const failedErrorMessage = displayItem.media?.error || m.processing_failed()
|
||||
|
||||
@@ -384,7 +407,24 @@ export function FileCard({
|
||||
<div className="relative aspect-square overflow-hidden bg-muted/30">
|
||||
{isUploading ? (
|
||||
<div className="flex h-full w-full items-center justify-center bg-background/50">
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
{isLocalUploader ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||
) : (
|
||||
<svg
|
||||
viewBox="0 0 50 50"
|
||||
data-testid="file-card-remote-uploading-circle"
|
||||
className="h-16 w-16 opacity-60 animate-preparing-breathe z-10"
|
||||
>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r="20"
|
||||
className="stroke-muted-foreground"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
) : hasPreview ? (
|
||||
<>
|
||||
@@ -404,7 +444,7 @@ export function FileCard({
|
||||
</div>
|
||||
{previewBadges}
|
||||
</>
|
||||
) : displayItem.status === 'error' ? (
|
||||
) : displayItem.status === 'error' || isUploadFailed ? (
|
||||
<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()}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { FileListItem } from './file-list-item'
|
||||
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: () => ({
|
||||
@@ -35,6 +36,7 @@ describe('FileListItem', () => {
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
useUploadStore.setState({ fileProgress: {} })
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
@@ -183,4 +185,69 @@ describe('FileListItem', () => {
|
||||
expect(screen.getByDisplayValue('List text value')).toBeTruthy()
|
||||
expect(onSelect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders dynamic ETA and speed for local uploader', () => {
|
||||
useUploadStore.setState({
|
||||
fileProgress: {
|
||||
'file-123': {
|
||||
fileId: 'file-123',
|
||||
name: 'very_long_file_name_for_testing_purposes.mov',
|
||||
loaded: 500,
|
||||
total: 1000,
|
||||
status: 'uploading',
|
||||
speed: 400 * 1024,
|
||||
eta: 480,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const uploadingItem: AssetInfo = {
|
||||
...mockItem,
|
||||
status: 'uploading',
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: uploadingItem })
|
||||
|
||||
const statusBadge = screen.getByTestId('file-list-item-uploading-status')
|
||||
expect(statusBadge.textContent).toMatch(/8m.*(left|剩余).*409\.6 KB\/s/i)
|
||||
expect(screen.queryByTestId('file-list-item-remote-uploading-circle')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders "Uploading..." fallback during local warm-up', () => {
|
||||
useUploadStore.setState({
|
||||
fileProgress: {
|
||||
'file-123': {
|
||||
fileId: 'file-123',
|
||||
name: 'very_long_file_name_for_testing_purposes.mov',
|
||||
loaded: 100,
|
||||
total: 1000,
|
||||
status: 'uploading',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const uploadingItem: AssetInfo = {
|
||||
...mockItem,
|
||||
status: 'uploading',
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: uploadingItem })
|
||||
|
||||
const statusBadge = screen.getByTestId('file-list-item-uploading-status')
|
||||
expect(statusBadge.textContent).toMatch(/Uploading|上传中/i)
|
||||
})
|
||||
|
||||
it('renders "[User] is uploading..." and indeterminate circle for remote viewer', () => {
|
||||
const uploadingItem: AssetInfo = {
|
||||
...mockItem,
|
||||
status: 'uploading',
|
||||
creator: { id: 'u1', name: 'Alice' },
|
||||
} as AssetInfo
|
||||
|
||||
renderComponent({ item: uploadingItem })
|
||||
|
||||
const statusBadge = screen.getByTestId('file-list-item-uploading-status')
|
||||
expect(statusBadge.textContent).toMatch(/Alice.*(is uploading|正在上传)/i)
|
||||
expect(screen.getByTestId('file-list-item-remote-uploading-circle')).toBeTruthy()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { AlertCircle, File, Folder, MoreVertical, AudioLines } from 'lucide-reac
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { formatRemainingTimeSeconds } from '@/ui/lib/time'
|
||||
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
|
||||
import type { DragState } from '../dnd-types'
|
||||
import FieldRenderer from '../field-renderer'
|
||||
@@ -100,8 +101,28 @@ export function FileListItem({
|
||||
return polledItem || item
|
||||
}, [item, polledItem])
|
||||
|
||||
const isLocalUploader = Boolean(fileUploadState)
|
||||
const isUploadFailed = fileUploadState?.status === 'failed'
|
||||
const isUploadDone = fileUploadState?.status === 'completed' || uploadPercent >= 100
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone
|
||||
const isUploading = displayItem.status === 'uploading' && !isUploadDone && !isUploadFailed
|
||||
|
||||
let uploadingText: string | null = null
|
||||
if (isUploading) {
|
||||
if (isLocalUploader) {
|
||||
if (fileUploadState?.speed && fileUploadState?.eta != null) {
|
||||
uploadingText = m.upload_eta_speed({
|
||||
eta: formatRemainingTimeSeconds(fileUploadState.eta),
|
||||
speed: `${formatSize(fileUploadState.speed)}/s`,
|
||||
})
|
||||
} else {
|
||||
uploadingText = m.uploading()
|
||||
}
|
||||
} else {
|
||||
uploadingText = m.user_is_uploading({
|
||||
user: displayItem.creator?.name || m.someone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// dnd-kit hooks
|
||||
const { ref: setDraggableRef, isDragging: isDraggableDragging } = useDraggable({
|
||||
@@ -213,7 +234,24 @@ export function FileListItem({
|
||||
/>
|
||||
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
||||
{isUploading ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
|
||||
isLocalUploader ? (
|
||||
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
|
||||
) : (
|
||||
<svg
|
||||
viewBox="0 0 50 50"
|
||||
data-testid="file-list-item-remote-uploading-circle"
|
||||
className="w-7 h-7 opacity-60 animate-preparing-breathe"
|
||||
>
|
||||
<circle
|
||||
cx="25"
|
||||
cy="25"
|
||||
r="20"
|
||||
className="stroke-muted-foreground"
|
||||
strokeWidth="4"
|
||||
fill="transparent"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
) : displayItem.status === 'failed' && !displayItem.preview?.thumbnailUrl ? (
|
||||
<AlertCircle className="h-4 w-4 text-destructive" />
|
||||
) : displayItem.preview?.thumbnailUrl ? (
|
||||
@@ -239,7 +277,15 @@ export function FileListItem({
|
||||
disabled={!isEditing}
|
||||
className="h-auto p-0 text-sm font-medium text-foreground truncate min-w-0 flex-1"
|
||||
/>
|
||||
{displayItem.status === 'error' && (
|
||||
{uploadingText && (
|
||||
<span
|
||||
data-testid="file-list-item-uploading-status"
|
||||
className="text-xs text-muted-foreground font-medium shrink-0"
|
||||
>
|
||||
{uploadingText}
|
||||
</span>
|
||||
)}
|
||||
{(displayItem.status === 'error' || isUploadFailed) && (
|
||||
<span className="text-xs text-destructive font-semibold shrink-0">
|
||||
{m.failed_to_upload_parenthesized()}
|
||||
</span>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { usePermissions } from '@/ui/hooks/use-permissions'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useUploadStore } from '@/ui/stores/upload'
|
||||
import { uploadFilesWithUppy } from '@/ui/lib/uploader'
|
||||
import type { AssetInfo, CreateUploadTaskRequest, FileNode } from '@shumai/dtos'
|
||||
import type { AssetInfo, CreateUploadTaskRequest } from '@shumai/dtos'
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import type { InferRequestType, InferResponseType } from 'hono/client'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
@@ -283,12 +283,7 @@ export function MobileFileBrowser({
|
||||
startTask(data.taskId, taskName, filesProgressInfo)
|
||||
}
|
||||
|
||||
const hasCreatedFolders = (variables.json.files as FileNode[]).some(
|
||||
(f) => f.children && f.children.length > 0,
|
||||
)
|
||||
if (hasCreatedFolders) {
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] })
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] })
|
||||
throttledInvalidateSearch.reset()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user