mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-19 14:16:29 +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:
+1
-1
@@ -17,7 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Changed
|
||||
|
||||
- **upload**: Optimize file status polling during upload and transcoding by eliminating redundant polling during active uploads and batching transcoding status checks across multiple files
|
||||
- **upload**: Display file cards directly in their sorted position during upload with live transfer rate and remaining time, while showing uploader attribution for other viewers
|
||||
- **agent**: ⚠️ **Important Behavior Change**: Autofill and Embedding agents will no longer post completion comments when finishing successfully to prevent clutter in asset comment feeds. Comments are now only posted if a task encounters an error.
|
||||
|
||||
## [0.6.2] - 2026-10-29
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatRemainingTime, getTrashDaysLeft } from './time'
|
||||
import { formatRemainingTime, formatRemainingTimeSeconds, getTrashDaysLeft } from './time'
|
||||
|
||||
describe('formatRemainingTime', () => {
|
||||
const baseNow = new Date('2026-08-17T12:00:00Z')
|
||||
@@ -45,6 +45,33 @@ describe('formatRemainingTime', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('formatRemainingTimeSeconds', () => {
|
||||
it('formats hours and minutes', () => {
|
||||
expect(formatRemainingTimeSeconds(3 * 3600 + 18 * 60)).toBe('3h 18m')
|
||||
})
|
||||
|
||||
it('formats exact hours', () => {
|
||||
expect(formatRemainingTimeSeconds(3 * 3600)).toBe('3h')
|
||||
})
|
||||
|
||||
it('formats minutes', () => {
|
||||
expect(formatRemainingTimeSeconds(8 * 60)).toBe('8m')
|
||||
expect(formatRemainingTimeSeconds(45 * 60 + 20)).toBe('45m')
|
||||
})
|
||||
|
||||
it('formats seconds', () => {
|
||||
expect(formatRemainingTimeSeconds(45)).toBe('45s')
|
||||
expect(formatRemainingTimeSeconds(1)).toBe('1s')
|
||||
})
|
||||
|
||||
it('handles zero, negative, or invalid numbers', () => {
|
||||
expect(formatRemainingTimeSeconds(0)).toBe('< 1s')
|
||||
expect(formatRemainingTimeSeconds(-5)).toBe('< 1s')
|
||||
expect(formatRemainingTimeSeconds(NaN)).toBe('< 1s')
|
||||
expect(formatRemainingTimeSeconds(Infinity)).toBe('< 1s')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTrashDaysLeft', () => {
|
||||
const now = new Date('2026-08-17T12:00:00Z')
|
||||
|
||||
|
||||
@@ -75,6 +75,28 @@ export const formatRemainingTime = (targetDate: string | Date, now: Date = new D
|
||||
return minutes > 0 ? `${minutes}m` : '< 1m'
|
||||
}
|
||||
|
||||
export const formatRemainingTimeSeconds = (totalSeconds: number): string => {
|
||||
if (!isFinite(totalSeconds) || totalSeconds <= 0) {
|
||||
return '< 1s'
|
||||
}
|
||||
const total = Math.round(totalSeconds)
|
||||
const days = Math.floor(total / 86400)
|
||||
const hours = Math.floor((total % 86400) / 3600)
|
||||
const minutes = Math.floor((total % 3600) / 60)
|
||||
const seconds = total % 60
|
||||
|
||||
if (days > 0) {
|
||||
return hours > 0 ? `${days}d ${hours}h` : `${days}d`
|
||||
}
|
||||
if (hours > 0) {
|
||||
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`
|
||||
}
|
||||
if (minutes > 0) {
|
||||
return `${minutes}m`
|
||||
}
|
||||
return `${seconds}s`
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole days remaining before a soft-deleted asset is permanently purged.
|
||||
* Returns `null` when there is no valid `deletedAt` timestamp, and `0` once the
|
||||
|
||||
@@ -409,12 +409,53 @@ export async function uploadFilesWithUppy({
|
||||
window.addEventListener('offline', handleOffline)
|
||||
}
|
||||
|
||||
const fileSpeedTrackers = new Map<
|
||||
string,
|
||||
{ lastBytes: number; lastTime: number; smoothedSpeed?: number }
|
||||
>()
|
||||
|
||||
uppy.on('upload-progress', (file, progress) => {
|
||||
if (!file) return
|
||||
const fileId = file.meta.fileId as string
|
||||
if (fileId && progress.bytesUploaded != null) {
|
||||
updateFileProgress(taskId, fileId, progress.bytesUploaded)
|
||||
if (!fileId || progress.bytesUploaded == null) return
|
||||
|
||||
const now = Date.now()
|
||||
const tracker = fileSpeedTrackers.get(fileId)
|
||||
let speed: number | undefined
|
||||
let eta: number | undefined
|
||||
|
||||
if (tracker) {
|
||||
const timeDelta = (now - tracker.lastTime) / 1000
|
||||
const bytesDelta = progress.bytesUploaded - tracker.lastBytes
|
||||
if (timeDelta >= 0.5 && bytesDelta >= 0) {
|
||||
const instantSpeed = bytesDelta / timeDelta
|
||||
speed =
|
||||
tracker.smoothedSpeed !== undefined
|
||||
? tracker.smoothedSpeed * 0.7 + instantSpeed * 0.3
|
||||
: instantSpeed
|
||||
tracker.smoothedSpeed = speed
|
||||
tracker.lastBytes = progress.bytesUploaded
|
||||
tracker.lastTime = now
|
||||
|
||||
const remainingBytes = (progress.bytesTotal ?? 0) - progress.bytesUploaded
|
||||
if (speed > 0 && remainingBytes > 0) {
|
||||
eta = Math.round(remainingBytes / speed)
|
||||
}
|
||||
} else {
|
||||
speed = tracker.smoothedSpeed
|
||||
if (speed && speed > 0) {
|
||||
const remainingBytes = (progress.bytesTotal ?? 0) - progress.bytesUploaded
|
||||
eta = Math.round(remainingBytes / speed)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
fileSpeedTrackers.set(fileId, {
|
||||
lastBytes: progress.bytesUploaded,
|
||||
lastTime: now,
|
||||
})
|
||||
}
|
||||
|
||||
updateFileProgress(taskId, fileId, progress.bytesUploaded, speed, eta)
|
||||
})
|
||||
|
||||
uppy.on('upload-success', (file) => {
|
||||
@@ -423,6 +464,7 @@ export async function uploadFilesWithUppy({
|
||||
if (fileId) {
|
||||
pendingNetworkRetries.delete(fileId)
|
||||
retryCounts.delete(fileId)
|
||||
fileSpeedTrackers.delete(fileId)
|
||||
}
|
||||
activeUploads.delete(fileId)
|
||||
|
||||
@@ -459,6 +501,7 @@ export async function uploadFilesWithUppy({
|
||||
const uploadUrl = (file.meta?.url as string | undefined) || active?.url
|
||||
|
||||
activeUploads.delete(fileId)
|
||||
fileSpeedTrackers.delete(fileId)
|
||||
failFile(taskId, fileId)
|
||||
|
||||
if (isLocalhostStorageMismatch(uploadUrl)) {
|
||||
|
||||
@@ -126,6 +126,9 @@
|
||||
"project_cover": "Project Cover",
|
||||
"remove_cover": "Remove Cover",
|
||||
"uploading": "Uploading...",
|
||||
"user_is_uploading": "{user} is uploading...",
|
||||
"upload_eta_speed": "{eta} left ({speed})",
|
||||
"someone": "Someone",
|
||||
"cover_preview": "Cover Preview",
|
||||
"upload_image": "Upload Image",
|
||||
"upload_cover": "Upload cover",
|
||||
|
||||
@@ -126,6 +126,9 @@
|
||||
"project_cover": "项目封面",
|
||||
"remove_cover": "移除封面",
|
||||
"uploading": "上传中...",
|
||||
"user_is_uploading": "{user} 正在上传...",
|
||||
"upload_eta_speed": "剩余 {eta} ({speed})",
|
||||
"someone": "有人",
|
||||
"cover_preview": "封面预览",
|
||||
"upload_image": "上传图片",
|
||||
"upload_cover": "上传封面",
|
||||
|
||||
@@ -31,9 +31,11 @@ describe('useUploadStore', () => {
|
||||
{ fileId: 'f2', name: 'video2.mp4', size: 2000 },
|
||||
])
|
||||
|
||||
useUploadStore.getState().updateFileProgress('task-1', 'f1', 500)
|
||||
useUploadStore.getState().updateFileProgress('task-1', 'f1', 500, 250, 2)
|
||||
expect(useUploadStore.getState().tasks['task-1'].loaded).toBe(500)
|
||||
expect(useUploadStore.getState().fileProgress['f1'].loaded).toBe(500)
|
||||
expect(useUploadStore.getState().fileProgress['f1'].speed).toBe(250)
|
||||
expect(useUploadStore.getState().fileProgress['f1'].eta).toBe(2)
|
||||
|
||||
useUploadStore.getState().completeFile('task-1', 'f1')
|
||||
expect(useUploadStore.getState().tasks['task-1'].files['f1'].status).toBe('completed')
|
||||
|
||||
@@ -6,6 +6,8 @@ export interface FileUploadState {
|
||||
loaded: number
|
||||
total: number
|
||||
status: 'uploading' | 'completed' | 'failed'
|
||||
speed?: number
|
||||
eta?: number
|
||||
}
|
||||
|
||||
export interface TaskUploadState {
|
||||
@@ -27,7 +29,13 @@ type UploadStore = {
|
||||
taskName: string,
|
||||
files: Array<{ fileId: string; name: string; size: number }>,
|
||||
) => void
|
||||
updateFileProgress: (taskId: string, fileId: string, loaded: number) => void
|
||||
updateFileProgress: (
|
||||
taskId: string,
|
||||
fileId: string,
|
||||
loaded: number,
|
||||
speed?: number,
|
||||
eta?: number,
|
||||
) => void
|
||||
completeFile: (taskId: string, fileId: string) => void
|
||||
failFile: (taskId: string, fileId: string) => void
|
||||
cancelTask: (taskId: string) => void
|
||||
@@ -78,7 +86,7 @@ export const useUploadStore = create<UploadStore>((set) => ({
|
||||
}
|
||||
}),
|
||||
|
||||
updateFileProgress: (taskId, fileId, loaded) =>
|
||||
updateFileProgress: (taskId, fileId, loaded, speed, eta) =>
|
||||
set((state) => {
|
||||
const task = state.tasks[taskId]
|
||||
if (!task) return {}
|
||||
@@ -86,7 +94,12 @@ export const useUploadStore = create<UploadStore>((set) => ({
|
||||
const file = task.files[fileId]
|
||||
if (!file) return {}
|
||||
|
||||
const updatedFile = { ...file, loaded }
|
||||
const updatedFile: FileUploadState = {
|
||||
...file,
|
||||
loaded,
|
||||
...(speed !== undefined ? { speed } : {}),
|
||||
...(eta !== undefined ? { eta } : {}),
|
||||
}
|
||||
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||
|
||||
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||
|
||||
Reference in New Issue
Block a user