mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-05 23:54:25 +00:00
Merge pull request #138 from shumaiOne/feat/upload-progress-xhr
feat(upload): track byte-level progress with XMLHttpRequest
This commit is contained in:
@@ -457,18 +457,45 @@ export function FileBrowser({
|
|||||||
const { mutate: createUploadTaskMutation } = useMutation<
|
const { mutate: createUploadTaskMutation } = useMutation<
|
||||||
InferResponseType<typeof $createUploadTask>,
|
InferResponseType<typeof $createUploadTask>,
|
||||||
Error,
|
Error,
|
||||||
InferRequestType<typeof $createUploadTask>
|
InferRequestType<typeof $createUploadTask>,
|
||||||
|
{ files: FileWithId[] }
|
||||||
>({
|
>({
|
||||||
mutationFn: async (request) => {
|
mutationFn: async (request) => {
|
||||||
const res = await $createUploadTask(request)
|
const res = await $createUploadTask(request)
|
||||||
if (!res.ok) throw new Error('Failed to create upload task')
|
if (!res.ok) throw new Error('Failed to create upload task')
|
||||||
return (await res.json()) as InferResponseType<typeof $createUploadTask>
|
return (await res.json()) as InferResponseType<typeof $createUploadTask>
|
||||||
},
|
},
|
||||||
onSuccess: async (data, variables) => {
|
onMutate: () => {
|
||||||
|
return { files: [...filesToUpload] }
|
||||||
|
},
|
||||||
|
onSuccess: async (data, variables, context) => {
|
||||||
|
const currentFiles = context?.files || []
|
||||||
const isCurrentFolderUpload = variables.json.parentId === assetId
|
const isCurrentFolderUpload = variables.json.parentId === assetId
|
||||||
|
|
||||||
|
// Register task and files in the store for real-time progress tracking
|
||||||
|
const filesProgressInfo = currentFiles
|
||||||
|
.map((f) => {
|
||||||
|
const urlInfo = (
|
||||||
|
data.presignedUrls as { id?: string; url?: string; fileId?: string }[] | undefined
|
||||||
|
)?.find((p) => p.id === f.id)
|
||||||
|
return {
|
||||||
|
fileId: urlInfo?.fileId || f.id,
|
||||||
|
name: f.file.name,
|
||||||
|
size: f.file.size,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter((info) => !!info.fileId)
|
||||||
|
|
||||||
|
const visibleFiles = currentFiles.filter((f) => !f.file.name.startsWith('.'))
|
||||||
|
const taskName =
|
||||||
|
visibleFiles.length === 1 ? visibleFiles[0].file.name : `${visibleFiles.length} Items`
|
||||||
|
|
||||||
|
if (data.taskId) {
|
||||||
|
startTask(data.taskId, taskName, filesProgressInfo)
|
||||||
|
}
|
||||||
|
|
||||||
if (isCurrentFolderUpload) {
|
if (isCurrentFolderUpload) {
|
||||||
const newLocalFiles: AssetInfo[] = filesToUpload
|
const newLocalFiles: AssetInfo[] = currentFiles
|
||||||
.filter((f) => {
|
.filter((f) => {
|
||||||
const path = (f.file.webkitRelativePath || f.file.name).split('/')
|
const path = (f.file.webkitRelativePath || f.file.name).split('/')
|
||||||
return path.length === 1
|
return path.length === 1
|
||||||
@@ -500,7 +527,7 @@ export function FileBrowser({
|
|||||||
|
|
||||||
// The RPC client returns an object that we cast to the expected type
|
// The RPC client returns an object that we cast to the expected type
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
await uploadFiles(filesToUpload, data.presignedUrls as any, data.taskId!)
|
await uploadFiles(currentFiles, data.presignedUrls as any, data.taskId!)
|
||||||
queryClient.invalidateQueries({
|
queryClient.invalidateQueries({
|
||||||
queryKey: ['search', teamId, assetId],
|
queryKey: ['search', teamId, assetId],
|
||||||
})
|
})
|
||||||
@@ -509,6 +536,10 @@ export function FileBrowser({
|
|||||||
|
|
||||||
const incrementUploading = useUploadStore((state) => state.increment)
|
const incrementUploading = useUploadStore((state) => state.increment)
|
||||||
const decrementUploading = useUploadStore((state) => state.decrement)
|
const decrementUploading = useUploadStore((state) => state.decrement)
|
||||||
|
const startTask = useUploadStore((state) => state.startTask)
|
||||||
|
const updateFileProgress = useUploadStore((state) => state.updateFileProgress)
|
||||||
|
const completeFile = useUploadStore((state) => state.completeFile)
|
||||||
|
const failFile = useUploadStore((state) => state.failFile)
|
||||||
const { fields } = useFieldStore()
|
const { fields } = useFieldStore()
|
||||||
const displayedFields = useMemo(() => {
|
const displayedFields = useMemo(() => {
|
||||||
if (!isShareView) return fields.filter((f) => f.visible)
|
if (!isShareView) return fields.filter((f) => f.visible)
|
||||||
@@ -688,25 +719,53 @@ export function FileBrowser({
|
|||||||
incrementUploading()
|
incrementUploading()
|
||||||
try {
|
try {
|
||||||
try {
|
try {
|
||||||
const resp = await fetch(uploadInfo.url, {
|
const xhr = new XMLHttpRequest()
|
||||||
method: 'PUT',
|
const uploadPromise = new Promise<{ ok: boolean; status: number }>(
|
||||||
body: file.file,
|
(resolve, reject) => {
|
||||||
headers: {
|
xhr.open('PUT', uploadInfo.url)
|
||||||
'Content-Type': file.file.type,
|
xhr.setRequestHeader('Content-Type', file.file.type)
|
||||||
|
|
||||||
|
xhr.upload.onprogress = (event) => {
|
||||||
|
if (event.lengthComputable) {
|
||||||
|
updateFileProgress(taskId, uploadInfo.fileId, event.loaded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xhr.onload = () => {
|
||||||
|
if (xhr.status >= 200 && xhr.status < 300) {
|
||||||
|
resolve({ ok: true, status: xhr.status })
|
||||||
|
} else {
|
||||||
|
resolve({ ok: false, status: xhr.status })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
xhr.onerror = () => {
|
||||||
|
reject(new Error('Network error'))
|
||||||
|
}
|
||||||
|
|
||||||
|
xhr.onabort = () => {
|
||||||
|
reject(new Error('Upload aborted'))
|
||||||
|
}
|
||||||
|
|
||||||
|
xhr.send(file.file)
|
||||||
},
|
},
|
||||||
})
|
)
|
||||||
|
|
||||||
|
const resp = await uploadPromise
|
||||||
|
|
||||||
if (resp.ok) {
|
if (resp.ok) {
|
||||||
|
completeFile(taskId, uploadInfo.fileId)
|
||||||
await confirmUpload({
|
await confirmUpload({
|
||||||
param: { teamId: teamId, taskId: taskId },
|
param: { teamId: teamId!, taskId: taskId },
|
||||||
json: {
|
json: {
|
||||||
fileId: uploadInfo.fileId,
|
fileId: uploadInfo.fileId,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
|
failFile(taskId, uploadInfo.fileId)
|
||||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||||
await confirmUpload({
|
await confirmUpload({
|
||||||
param: { teamId: teamId, taskId: taskId },
|
param: { teamId: teamId!, taskId: taskId },
|
||||||
json: {
|
json: {
|
||||||
fileId: uploadInfo.fileId,
|
fileId: uploadInfo.fileId,
|
||||||
errorMessage: `upload failed with status: ${resp.status}`,
|
errorMessage: `upload failed with status: ${resp.status}`,
|
||||||
@@ -715,9 +774,10 @@ export function FileBrowser({
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
failFile(taskId, uploadInfo.fileId)
|
||||||
toast.error(`Failed to upload file: ${file.file.name}`)
|
toast.error(`Failed to upload file: ${file.file.name}`)
|
||||||
await confirmUpload({
|
await confirmUpload({
|
||||||
param: { teamId: teamId, taskId: taskId },
|
param: { teamId: teamId!, taskId: taskId },
|
||||||
json: {
|
json: {
|
||||||
fileId: uploadInfo.fileId,
|
fileId: uploadInfo.fileId,
|
||||||
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`,
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ import { Badge } from '@/ui/components/ui/badge'
|
|||||||
import { Button } from '@/ui/components/ui/button'
|
import { Button } from '@/ui/components/ui/button'
|
||||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/ui/components/ui/dropdown-menu'
|
} from '@/ui/components/ui/dropdown-menu'
|
||||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||||
import { Skeleton } from '@/ui/components/ui/skeleton'
|
import { Skeleton } from '@/ui/components/ui/skeleton'
|
||||||
@@ -22,6 +22,8 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
|
|||||||
import type { DragState } from '../dnd-types'
|
import type { DragState } from '../dnd-types'
|
||||||
import FieldRenderer from '../field-renderer'
|
import FieldRenderer from '../field-renderer'
|
||||||
import { FilePreview } from './file-preview'
|
import { FilePreview } from './file-preview'
|
||||||
|
import { useUploadStore } from '@/ui/stores/upload'
|
||||||
|
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||||
|
|
||||||
import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
import { FieldType, type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||||
import { FIELD_TYPE_ICONS } from '../fields-manager'
|
import { FIELD_TYPE_ICONS } from '../fields-manager'
|
||||||
@@ -82,6 +84,13 @@ export function FileCard({
|
|||||||
const [name, setName] = useState(item.name)
|
const [name, setName] = useState(item.name)
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
|
||||||
|
const uploadPercent = fileUploadState
|
||||||
|
? fileUploadState.total > 0
|
||||||
|
? (fileUploadState.loaded / fileUploadState.total) * 100
|
||||||
|
: 0
|
||||||
|
: 0
|
||||||
|
|
||||||
const shouldPoll =
|
const shouldPoll =
|
||||||
(item.type === 'file' || item.type === 'version_stack') &&
|
(item.type === 'file' || item.type === 'version_stack') &&
|
||||||
!!teamId &&
|
!!teamId &&
|
||||||
@@ -247,20 +256,24 @@ export function FileCard({
|
|||||||
{displayItem.status !== 'error' && (
|
{displayItem.status !== 'error' && (
|
||||||
<Skeleton className="absolute inset-0 h-full w-full" />
|
<Skeleton className="absolute inset-0 h-full w-full" />
|
||||||
)}
|
)}
|
||||||
<span
|
{displayItem.status === 'uploading' ? (
|
||||||
className={cn(
|
<ProgressCircle progress={uploadPercent} className="w-16 h-16 z-10" />
|
||||||
'z-10 font-medium px-2 text-center text-sm',
|
) : (
|
||||||
displayItem.status === 'error'
|
<span
|
||||||
? 'text-destructive font-semibold'
|
className={cn(
|
||||||
: 'text-muted-foreground capitalize',
|
'z-10 font-medium px-2 text-center text-sm',
|
||||||
)}
|
displayItem.status === 'error'
|
||||||
>
|
? 'text-destructive font-semibold'
|
||||||
{displayItem.status === 'uploaded'
|
: 'text-muted-foreground capitalize',
|
||||||
? 'Processing'
|
)}
|
||||||
: displayItem.status === 'error'
|
>
|
||||||
? 'Failed to upload'
|
{displayItem.status === 'uploaded'
|
||||||
: displayItem.status}
|
? 'Processing'
|
||||||
</span>
|
: displayItem.status === 'error'
|
||||||
|
? 'Failed to upload'
|
||||||
|
: displayItem.status}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<FilePreview item={displayItem} />
|
<FilePreview item={displayItem} />
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ import FieldRenderer from '../field-renderer'
|
|||||||
import { Badge } from '@/ui/components/ui/badge'
|
import { Badge } from '@/ui/components/ui/badge'
|
||||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||||
import { EditableText } from '@/ui/components/ui/editable-text'
|
import { EditableText } from '@/ui/components/ui/editable-text'
|
||||||
|
import { useUploadStore } from '@/ui/stores/upload'
|
||||||
|
import { ProgressCircle } from '@/ui/components/ui/progress-circle'
|
||||||
|
|
||||||
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos'
|
||||||
|
|
||||||
@@ -60,6 +62,13 @@ export function FileListItem({
|
|||||||
const [name, setName] = useState(item.name)
|
const [name, setName] = useState(item.name)
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
|
const fileUploadState = useUploadStore((state) => state.fileProgress[item.id || ''])
|
||||||
|
const uploadPercent = fileUploadState
|
||||||
|
? fileUploadState.total > 0
|
||||||
|
? (fileUploadState.loaded / fileUploadState.total) * 100
|
||||||
|
: 0
|
||||||
|
: 0
|
||||||
|
|
||||||
const shouldPoll =
|
const shouldPoll =
|
||||||
(item.type === 'file' || item.type === 'version_stack') &&
|
(item.type === 'file' || item.type === 'version_stack') &&
|
||||||
!!teamId &&
|
!!teamId &&
|
||||||
@@ -197,7 +206,9 @@ export function FileListItem({
|
|||||||
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
className="h-4 w-4 shrink-0 data-[state=checked]:bg-primary data-[state=checked]:border-primary"
|
||||||
/>
|
/>
|
||||||
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
<div className="w-8 h-8 shrink-0 flex items-center justify-center bg-muted rounded overflow-hidden">
|
||||||
{displayItem.preview?.thumbnailUrl ? (
|
{displayItem.status === 'uploading' ? (
|
||||||
|
<ProgressCircle progress={uploadPercent} className="w-7 h-7" />
|
||||||
|
) : displayItem.preview?.thumbnailUrl ? (
|
||||||
<img
|
<img
|
||||||
src={displayItem.preview.thumbnailUrl}
|
src={displayItem.preview.thumbnailUrl}
|
||||||
alt=""
|
alt=""
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
import { cn } from '@/ui/lib/utils'
|
||||||
|
|
||||||
interface ProgressCircleProps {
|
interface ProgressCircleProps {
|
||||||
progress: number
|
progress: number
|
||||||
@@ -8,15 +9,15 @@ interface ProgressCircleProps {
|
|||||||
export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, className }) => {
|
export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, className }) => {
|
||||||
const radius = 20
|
const radius = 20
|
||||||
const circumference = 2 * Math.PI * radius
|
const circumference = 2 * Math.PI * radius
|
||||||
const offset = circumference - (progress / 100) * circumference
|
const offset = circumference - (Math.min(100, Math.max(0, progress)) / 100) * circumference
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<svg width="50" height="50" viewBox="0 0 50 50" className={className}>
|
<svg viewBox="0 0 50 50" className={cn('w-12 h-12', className)}>
|
||||||
<circle
|
<circle
|
||||||
cx="25"
|
cx="25"
|
||||||
cy="25"
|
cy="25"
|
||||||
r={radius}
|
r={radius}
|
||||||
className="stroke-current text-gray-200"
|
className="stroke-muted"
|
||||||
strokeWidth="4"
|
strokeWidth="4"
|
||||||
fill="transparent"
|
fill="transparent"
|
||||||
/>
|
/>
|
||||||
@@ -24,12 +25,11 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
|
|||||||
cx="25"
|
cx="25"
|
||||||
cy="25"
|
cy="25"
|
||||||
r={radius}
|
r={radius}
|
||||||
className="stroke-current text-blue-600"
|
className="stroke-primary transition-all duration-300 ease-out"
|
||||||
strokeWidth="4"
|
strokeWidth="4"
|
||||||
fill="transparent"
|
fill="transparent"
|
||||||
strokeDasharray={circumference}
|
strokeDasharray={circumference}
|
||||||
strokeDashoffset={offset}
|
strokeDashoffset={offset}
|
||||||
style={{ transition: 'stroke-dashoffset 0.3s' }}
|
|
||||||
transform="rotate(-90 25 25)"
|
transform="rotate(-90 25 25)"
|
||||||
/>
|
/>
|
||||||
<text
|
<text
|
||||||
@@ -37,7 +37,7 @@ export const ProgressCircle: React.FC<ProgressCircleProps> = ({ progress, classN
|
|||||||
y="50%"
|
y="50%"
|
||||||
textAnchor="middle"
|
textAnchor="middle"
|
||||||
dy=".3em"
|
dy=".3em"
|
||||||
className="text-xs font-semibold text-gray-700"
|
className="fill-foreground text-[10px] font-bold"
|
||||||
>
|
>
|
||||||
{`${Math.round(progress)}%`}
|
{`${Math.round(progress)}%`}
|
||||||
</text>
|
</text>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useTeamId } from '@/ui/hooks/use-team-id'
|
|||||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||||
import { useUploadStore } from '@/ui/stores/upload'
|
import { useUploadStore } from '@/ui/stores/upload'
|
||||||
import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react'
|
import { Loader2, CheckCircle2, Clock, UploadCloud } from 'lucide-react'
|
||||||
import { useEffect } from 'react'
|
import { useEffect, useMemo } from 'react'
|
||||||
import { useInView } from 'react-intersection-observer'
|
import { useInView } from 'react-intersection-observer'
|
||||||
import { format, parseISO, isToday, isYesterday } from 'date-fns'
|
import { format, parseISO, isToday, isYesterday } from 'date-fns'
|
||||||
import { Progress } from '@/ui/components/ui/progress'
|
import { Progress } from '@/ui/components/ui/progress'
|
||||||
@@ -24,9 +24,28 @@ function formatDayHeader(dateString: string): string {
|
|||||||
return format(date, 'MMMM d, yyyy')
|
return format(date, 'MMMM d, yyyy')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes === 0) return '0 B'
|
||||||
|
const k = 1024
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||||
|
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||||
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
|
||||||
|
}
|
||||||
|
|
||||||
function UploadTaskItem({ task }: { task: TaskInfo }) {
|
function UploadTaskItem({ task }: { task: TaskInfo }) {
|
||||||
const isCompleted = task.uploaded === task.total
|
const clientProgress = useUploadStore((state) => state.tasks[task.id])
|
||||||
const percent = task.total > 0 ? (task.uploaded / task.total) * 100 : 0
|
|
||||||
|
const isCompleted = clientProgress
|
||||||
|
? clientProgress.loaded === clientProgress.total && task.uploaded === task.total
|
||||||
|
: task.uploaded === task.total
|
||||||
|
|
||||||
|
const percent = clientProgress
|
||||||
|
? clientProgress.total > 0
|
||||||
|
? (clientProgress.loaded / clientProgress.total) * 100
|
||||||
|
: 0
|
||||||
|
: task.total > 0
|
||||||
|
? (task.uploaded / task.total) * 100
|
||||||
|
: 0
|
||||||
|
|
||||||
let formattedTime: string
|
let formattedTime: string
|
||||||
try {
|
try {
|
||||||
@@ -72,7 +91,9 @@ function UploadTaskItem({ task }: { task: TaskInfo }) {
|
|||||||
<div className="space-y-1.5 mt-auto">
|
<div className="space-y-1.5 mt-auto">
|
||||||
<div className="flex items-center justify-between text-xs font-semibold">
|
<div className="flex items-center justify-between text-xs font-semibold">
|
||||||
<span className="text-muted-foreground/80">
|
<span className="text-muted-foreground/80">
|
||||||
{task.uploaded} / {task.total} {task.total === 1 ? 'file' : 'files'}
|
{clientProgress
|
||||||
|
? `${formatBytes(clientProgress.loaded)} / ${formatBytes(clientProgress.total)} (${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'})`
|
||||||
|
: `${task.uploaded} / ${task.total} ${task.total === 1 ? 'file' : 'files'}`}
|
||||||
</span>
|
</span>
|
||||||
{!isCompleted && (
|
{!isCompleted && (
|
||||||
<span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span>
|
<span className="text-sidebar-primary font-mono font-bold">{Math.round(percent)}%</span>
|
||||||
@@ -92,6 +113,7 @@ interface TaskGroup {
|
|||||||
export function UploadTasks() {
|
export function UploadTasks() {
|
||||||
const teamId = useTeamId()
|
const teamId = useTeamId()
|
||||||
const uploading = useUploadStore((state) => state.uploading)
|
const uploading = useUploadStore((state) => state.uploading)
|
||||||
|
const clientActiveTasks = useUploadStore((state) => state.tasks)
|
||||||
const {
|
const {
|
||||||
data: tasksData,
|
data: tasksData,
|
||||||
fetchNextPage,
|
fetchNextPage,
|
||||||
@@ -126,6 +148,27 @@ export function UploadTasks() {
|
|||||||
|
|
||||||
const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? []
|
const tasks = tasksData?.pages.flatMap((page) => page.data ?? []) ?? []
|
||||||
|
|
||||||
|
const combinedTasks = useMemo(() => {
|
||||||
|
const serverTaskIds = new Set(tasks.map((t) => t.id))
|
||||||
|
const clientOnlyTasks: TaskInfo[] = Object.values(clientActiveTasks)
|
||||||
|
.filter((ct) => !serverTaskIds.has(ct.taskId))
|
||||||
|
.map((ct) => {
|
||||||
|
const completedCount = Object.values(ct.files).filter(
|
||||||
|
(f) => f.status === 'completed' || f.status === 'failed',
|
||||||
|
).length
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: ct.taskId,
|
||||||
|
name: ct.name,
|
||||||
|
total: Object.keys(ct.files).length,
|
||||||
|
uploaded: completedCount,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return [...clientOnlyTasks, ...tasks].sort((a, b) => b.id.localeCompare(a.id))
|
||||||
|
}, [tasks, clientActiveTasks])
|
||||||
|
|
||||||
if (isLoading) {
|
if (isLoading) {
|
||||||
return (
|
return (
|
||||||
<div className="flex items-center justify-center p-8">
|
<div className="flex items-center justify-center p-8">
|
||||||
@@ -134,7 +177,7 @@ export function UploadTasks() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tasks.length === 0) {
|
if (combinedTasks.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col items-center justify-center p-8 text-center border border-dashed border-border rounded-xl bg-muted/10 my-4">
|
<div className="flex flex-col items-center justify-center p-8 text-center border border-dashed border-border rounded-xl bg-muted/10 my-4">
|
||||||
<UploadCloud className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
<UploadCloud className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||||
@@ -148,7 +191,7 @@ export function UploadTasks() {
|
|||||||
|
|
||||||
// Group tasks by day (maintaining desc ordering)
|
// Group tasks by day (maintaining desc ordering)
|
||||||
const taskGroups: TaskGroup[] = []
|
const taskGroups: TaskGroup[] = []
|
||||||
tasks.forEach((task) => {
|
combinedTasks.forEach((task) => {
|
||||||
const day = formatDayHeader(task.createdAt)
|
const day = formatDayHeader(task.createdAt)
|
||||||
let group = taskGroups.find((g) => g.day === day)
|
let group = taskGroups.find((g) => g.day === day)
|
||||||
if (!group) {
|
if (!group) {
|
||||||
|
|||||||
@@ -1,13 +1,166 @@
|
|||||||
import { create } from 'zustand'
|
import { create } from 'zustand'
|
||||||
|
|
||||||
|
export interface FileUploadState {
|
||||||
|
fileId: string
|
||||||
|
name: string
|
||||||
|
loaded: number
|
||||||
|
total: number
|
||||||
|
status: 'uploading' | 'completed' | 'failed'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TaskUploadState {
|
||||||
|
taskId: string
|
||||||
|
name: string
|
||||||
|
loaded: number
|
||||||
|
total: number
|
||||||
|
files: Record<string, FileUploadState>
|
||||||
|
}
|
||||||
|
|
||||||
type UploadStore = {
|
type UploadStore = {
|
||||||
uploading: number
|
uploading: number
|
||||||
|
tasks: Record<string, TaskUploadState>
|
||||||
|
fileProgress: Record<string, FileUploadState>
|
||||||
increment: () => void
|
increment: () => void
|
||||||
decrement: () => void
|
decrement: () => void
|
||||||
|
startTask: (
|
||||||
|
taskId: string,
|
||||||
|
taskName: string,
|
||||||
|
files: Array<{ fileId: string; name: string; size: number }>,
|
||||||
|
) => void
|
||||||
|
updateFileProgress: (taskId: string, fileId: string, loaded: number) => void
|
||||||
|
completeFile: (taskId: string, fileId: string) => void
|
||||||
|
failFile: (taskId: string, fileId: string) => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useUploadStore = create<UploadStore>((set) => ({
|
export const useUploadStore = create<UploadStore>((set) => ({
|
||||||
uploading: 0,
|
uploading: 0,
|
||||||
|
tasks: {},
|
||||||
|
fileProgress: {},
|
||||||
increment: () => set((state) => ({ uploading: state.uploading + 1 })),
|
increment: () => set((state) => ({ uploading: state.uploading + 1 })),
|
||||||
decrement: () => set((state) => ({ uploading: state.uploading - 1 })),
|
decrement: () => set((state) => ({ uploading: state.uploading - 1 })),
|
||||||
|
|
||||||
|
startTask: (taskId, taskName, files) =>
|
||||||
|
set((state) => {
|
||||||
|
const taskFiles: Record<string, FileUploadState> = {}
|
||||||
|
let totalBytes = 0
|
||||||
|
|
||||||
|
files.forEach((f) => {
|
||||||
|
taskFiles[f.fileId] = {
|
||||||
|
fileId: f.fileId,
|
||||||
|
name: f.name,
|
||||||
|
loaded: 0,
|
||||||
|
total: f.size,
|
||||||
|
status: 'uploading',
|
||||||
|
}
|
||||||
|
totalBytes += f.size
|
||||||
|
})
|
||||||
|
|
||||||
|
const newTasks = {
|
||||||
|
...state.tasks,
|
||||||
|
[taskId]: {
|
||||||
|
taskId,
|
||||||
|
name: taskName,
|
||||||
|
loaded: 0,
|
||||||
|
total: totalBytes,
|
||||||
|
files: taskFiles,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const newFileProgress = { ...state.fileProgress }
|
||||||
|
files.forEach((f) => {
|
||||||
|
newFileProgress[f.fileId] = taskFiles[f.fileId]
|
||||||
|
})
|
||||||
|
|
||||||
|
return {
|
||||||
|
tasks: newTasks,
|
||||||
|
fileProgress: newFileProgress,
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
updateFileProgress: (taskId, fileId, loaded) =>
|
||||||
|
set((state) => {
|
||||||
|
const task = state.tasks[taskId]
|
||||||
|
if (!task) return {}
|
||||||
|
|
||||||
|
const file = task.files[fileId]
|
||||||
|
if (!file) return {}
|
||||||
|
|
||||||
|
const updatedFile = { ...file, loaded }
|
||||||
|
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||||
|
|
||||||
|
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
tasks: {
|
||||||
|
...state.tasks,
|
||||||
|
[taskId]: {
|
||||||
|
...task,
|
||||||
|
loaded: loadedBytes,
|
||||||
|
files: updatedFiles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fileProgress: {
|
||||||
|
...state.fileProgress,
|
||||||
|
[fileId]: updatedFile,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
completeFile: (taskId, fileId) =>
|
||||||
|
set((state) => {
|
||||||
|
const task = state.tasks[taskId]
|
||||||
|
if (!task) return {}
|
||||||
|
|
||||||
|
const file = task.files[fileId]
|
||||||
|
if (!file) return {}
|
||||||
|
|
||||||
|
const updatedFile: FileUploadState = { ...file, status: 'completed', loaded: file.total }
|
||||||
|
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||||
|
|
||||||
|
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
tasks: {
|
||||||
|
...state.tasks,
|
||||||
|
[taskId]: {
|
||||||
|
...task,
|
||||||
|
loaded: loadedBytes,
|
||||||
|
files: updatedFiles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fileProgress: {
|
||||||
|
...state.fileProgress,
|
||||||
|
[fileId]: updatedFile,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
|
||||||
|
failFile: (taskId, fileId) =>
|
||||||
|
set((state) => {
|
||||||
|
const task = state.tasks[taskId]
|
||||||
|
if (!task) return {}
|
||||||
|
|
||||||
|
const file = task.files[fileId]
|
||||||
|
if (!file) return {}
|
||||||
|
|
||||||
|
const updatedFile: FileUploadState = { ...file, status: 'failed' }
|
||||||
|
const updatedFiles = { ...task.files, [fileId]: updatedFile }
|
||||||
|
|
||||||
|
const loadedBytes = Object.values(updatedFiles).reduce((sum, f) => sum + f.loaded, 0)
|
||||||
|
|
||||||
|
return {
|
||||||
|
tasks: {
|
||||||
|
...state.tasks,
|
||||||
|
[taskId]: {
|
||||||
|
...task,
|
||||||
|
loaded: loadedBytes,
|
||||||
|
files: updatedFiles,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fileProgress: {
|
||||||
|
...state.fileProgress,
|
||||||
|
[fileId]: updatedFile,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}),
|
||||||
}))
|
}))
|
||||||
|
|||||||
Reference in New Issue
Block a user