'use client' import { client } from '@/ui/api/client' import { usePermissions } from '@/ui/hooks/use-permissions' import { m } from '@/ui/paraglide/messages.js' import { useUploadStore } from '@/ui/stores/upload' import type { AssetInfo, CreateUploadTaskRequest, PresignedUrl } from '@shumai/dtos' import { useMutation, useQueryClient } from '@tanstack/react-query' import type { InferRequestType, InferResponseType } from 'hono/client' import { formatSize } from '@/ui/lib/format' import { AlertTriangle, ChevronDown, ChevronRight, Download, FolderClock, FolderPlus, Loader2, Plus, Upload, } from 'lucide-react' import React, { useRef, useState } from 'react' import { useInView } from 'react-intersection-observer' import { toast } from 'sonner' import { ulid } from 'ulid' import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '../ui/alert-dialog' import { Button } from '../ui/button' import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from '../ui/dialog' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '../ui/dropdown-menu' import { Input } from '../ui/input' import { FileCard } from './file-card' import { FolderCard } from './folder-card' import { useFileActions } from './use-file-actions' import { MobileFileBrowserContentSkeleton } from '../loading-skeletons' export interface MobileFileBrowserProps { teamId: string projectId: string assetId: string folders: AssetInfo[] files: AssetInfo[] totalFolders?: number totalFiles?: number totalFoldersSize?: number totalFilesSize?: number selectedItem: AssetInfo | null selectedIds: Set onItemSelect: (item: AssetInfo, event: React.MouseEvent) => void onItemDoubleClick: (item: AssetInfo) => void onSaveField?: (fileId: string, fieldId: string, value: unknown) => void onClearSelection: () => void fetchNextFoldersPage: () => void hasNextFoldersPage: boolean isFetchingNextFoldersPage: boolean fetchNextFilesPage: () => void hasNextFilesPage: boolean isFetchingNextFilesPage: boolean isRecentlyDeleted?: boolean isRecents?: boolean isLoading?: boolean isShareView?: boolean isPublic?: boolean shareId?: string allowDownload?: boolean rootFolderId?: string } type FileWithId = { file: File id: string } let pendingFilesToUpload: FileWithId[] = [] export function MobileFileBrowser({ teamId, projectId, assetId, folders, files, totalFolders, totalFiles, totalFoldersSize, totalFilesSize, selectedItem, selectedIds, onItemSelect, onItemDoubleClick, onSaveField, onClearSelection, fetchNextFoldersPage, hasNextFoldersPage, isFetchingNextFoldersPage, fetchNextFilesPage, hasNextFilesPage, isFetchingNextFilesPage, isRecentlyDeleted = false, isRecents = false, isLoading = false, isShareView = false, isPublic = false, shareId, allowDownload = true, }: MobileFileBrowserProps) { const queryClient = useQueryClient() const { canEdit, canAdmin } = usePermissions(projectId) const fileInputRef = useRef(null) const folderInputRef = useRef(null) const [foldersExpanded, setFoldersExpanded] = useState(true) const [filesExpanded, setFilesExpanded] = useState(true) const [isNewFolderDialogOpen, setIsNewFolderDialogOpen] = useState(false) const [newFolderName, setNewFolderName] = useState('') const [isEmptyTrashDialogOpen, setIsEmptyTrashDialogOpen] = useState(false) const foldersCount = totalFolders ?? folders.length const filesCount = totalFiles ?? files.length const foldersSizeVal = totalFoldersSize ?? (folders.length > 0 ? folders.reduce((acc, f) => acc + (f.sizeByte || 0), 0) : -1) const filesSizeVal = totalFilesSize ?? (files.length > 0 ? files.reduce((acc, f) => acc + (f.sizeByte || 0), 0) : -1) const showFoldersSize = foldersSizeVal > -1 const showFilesSize = filesSizeVal > -1 const formatCount = (count: number, isFile: boolean) => { if (isFile) { return count === 1 ? m.n_assets_singular({ count }) : m.n_assets_plural({ count }) } else { return count === 1 ? m.n_folders_singular({ count }) : m.n_folders_plural({ count }) } } const { editingItemId, setEditingItemId, handleAction, onRenameSubmit, isDeleteDialogOpen, setIsDeleteDialogOpen, confirmDelete, isDownloadDialogOpen, setIsDownloadDialogOpen, isLoadingLinks, resolvedFiles, startDownload, } = useFileActions({ teamId, projectId, assetId, folders, files, selectedIds, isPublic, shareId, }) // Infinite scroll trigger const { ref: loadMoreRef, inView } = useInView() React.useEffect(() => { if (inView) { if (hasNextFoldersPage && !isFetchingNextFoldersPage) { fetchNextFoldersPage() } else if (hasNextFilesPage && !isFetchingNextFilesPage) { fetchNextFilesPage() } } }, [ inView, hasNextFoldersPage, isFetchingNextFoldersPage, hasNextFilesPage, isFetchingNextFilesPage, fetchNextFoldersPage, fetchNextFilesPage, ]) // Upload actions const incrementUploading = useUploadStore((state) => state.increment) 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 $confirmUpload = client.api.teams[':teamId'].upload.tasks[':taskId'].$patch const { mutateAsync: confirmUpload } = useMutation< InferResponseType, Error, InferRequestType >({ mutationFn: async (request) => { const res = await $confirmUpload(request) if (!res.ok) throw new Error('Failed to confirm upload') return (await res.json()) as InferResponseType }, }) const uploadFiles = async ( filesList: FileWithId[], presignedUrls: PresignedUrl[] | undefined, taskId: string, ) => { const uploadUrlMap = presignedUrls?.reduce( (acc: Record, item: PresignedUrl) => { if (item.id) { acc[item.id] = { url: item.url || '', fileId: item.fileId || '', } } return acc }, {}, ) if (!uploadUrlMap) return const concurrencyLimit = 5 const queue = [...filesList] const uploadNext = async () => { while (queue.length > 0) { const item = queue.shift() if (item) { const uploadInfo = uploadUrlMap[item.id] if (uploadInfo && uploadInfo.url) { incrementUploading() try { const xhr = new XMLHttpRequest() const uploadPromise = new Promise<{ ok: boolean; status: number }>( (resolve, reject) => { xhr.open('PUT', uploadInfo.url) xhr.setRequestHeader('Content-Type', item.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(item.file) }, ) const resp = await uploadPromise if (resp.ok) { completeFile(taskId, uploadInfo.fileId) await confirmUpload({ param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, }, }) } else { failFile(taskId, uploadInfo.fileId) toast.error(`Failed to upload file: ${item.file.name}`) await confirmUpload({ param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, errorMessage: `upload failed with status: ${resp.status}`, }, }) return } } catch (error) { failFile(taskId, uploadInfo.fileId) toast.error(`Failed to upload file: ${item.file.name}`) await confirmUpload({ param: { teamId: teamId!, taskId: taskId }, json: { fileId: uploadInfo.fileId, errorMessage: `upload failed with error: ${error instanceof Error ? error.message : String(error)}`, }, }) return } finally { decrementUploading() queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) } } } } } const activeUploaders = Array(concurrencyLimit) .fill(null) .map(() => uploadNext()) await Promise.all(activeUploaders) } const $createUploadTask = client.api.teams[':teamId'].upload.tasks.$post const { mutate: createUploadTaskMutation } = useMutation< InferResponseType, Error, InferRequestType, { files: FileWithId[] } >({ mutationFn: async (request) => { const res = await $createUploadTask(request) if (!res.ok) throw new Error('Failed to create upload task') return (await res.json()) as InferResponseType }, onMutate: () => { return { files: [...pendingFilesToUpload] } }, onSuccess: async (data, _variables, context) => { const currentFiles = context?.files || [] const filesProgressInfo = currentFiles .map((f) => { const urlInfo = data.presignedUrls?.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) } queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] }) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] }) await uploadFiles(currentFiles, data.presignedUrls, data.taskId!) queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] }) queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'upload', 'tasks'] }) }, }) const processAndUploadFiles = (selectedFiles: FileList | File[]) => { if (!selectedFiles || selectedFiles.length === 0) return const fileWithIds: FileWithId[] = [] const root: CreateUploadTaskRequest['files'] = [] const directories = new Map() for (const file of selectedFiles) { const path = (file.webkitRelativePath || file.name).split('/') if (path.some((part) => part.startsWith('.'))) { continue } const fileName = path.pop()! let currentLevel = root let currentPath = '' for (const dir of path) { currentPath = `${currentPath}/${dir}` if (!directories.has(currentPath)) { const newDir: CreateUploadTaskRequest['files'] = [] const parentDir = { name: dir, type: 'folder' as const, id: ulid(), children: newDir, size: 0, } currentLevel.push(parentDir) directories.set(currentPath, newDir) currentLevel = newDir } else { currentLevel = directories.get(currentPath)! } } const fileWithId = { file, id: ulid() } fileWithIds.push(fileWithId) let mediaType = file.type if (fileName.toLowerCase().endsWith('.wma') && mediaType?.startsWith('video/')) { mediaType = mediaType.replace(/^video\//, 'audio/') } currentLevel.push({ name: fileName, size: file.size, type: 'file', id: fileWithId.id, children: [], mediaType, }) } pendingFilesToUpload = fileWithIds createUploadTaskMutation({ param: { teamId: teamId }, json: { parentId: assetId, files: root, }, }) } const $createFolder = client.api.folders.$post const { mutate: createFolderMutation, isPending: isCreatingFolder } = useMutation({ mutationFn: async (name: string) => { const res = await $createFolder({ json: { name, parentId: assetId }, }) if (!res.ok) throw new Error('Failed to create folder') return await res.json() }, onSuccess: () => { toast.success(m.new_folder()) setIsNewFolderDialogOpen(false) setNewFolderName('') queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId] }) queryClient.invalidateQueries({ queryKey: ['folders'] }) }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const { mutate: emptyTrash, isPending: isEmptyingTrash } = useMutation({ mutationFn: async () => { const res = await client.api.projects[':projectId']['empty-trash'].$post({ param: { projectId }, }) if (!res.ok) throw new Error('Failed to empty trash') return await res.json() }, onSuccess: () => { toast.success(m.trash_emptied_successfully()) queryClient.invalidateQueries({ queryKey: ['projects', projectId, 'recently-deleted'], }) onClearSelection() setIsEmptyTrashDialogOpen(false) }, onError: (err) => { toast.error(`Error: ${err.message}`) }, }) const handleCreateFolderSubmit = (e: React.FormEvent) => { e.preventDefault() if (!newFolderName.trim()) return createFolderMutation(newFolderName.trim()) } const isFolderEmpty = !isLoading && folders.length === 0 && files.length === 0 && !isFetchingNextFoldersPage && !isFetchingNextFilesPage return (
{/* Hidden file inputs for upload actions */} {canEdit && ( <> { if (e.target.files) processAndUploadFiles(e.target.files) }} /> { if (e.target.files) processAndUploadFiles(e.target.files) }} /> )} {/* Recently Deleted banner */} {isRecentlyDeleted && (
{m.recently_deleted_notice()}
{canAdmin && ( )}
)} {/* Main scroll area */}
{isLoading && folders.length === 0 && files.length === 0 ? ( ) : (
{/* Folders Section */} {foldersCount > 0 && (
{foldersExpanded && (
{folders.map((folder) => ( {}} onDragStart={() => {}} onDrop={() => {}} onRename={(newName) => onRenameSubmit(folder, newName)} onFinishEditing={() => setEditingItemId(null)} onAction={(action, item) => handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item) } isRecentlyDeleted={isRecentlyDeleted} isRecents={isRecents} selectedCount={selectedIds.size} canEdit={canEdit} isShareView={isShareView} allowDownload={allowDownload} /> ))}
)}
)} {/* Files Section */} {filesCount > 0 && (
{filesExpanded && (
{files.map((file) => ( {}} onDragStart={() => {}} onDrop={() => {}} onRename={(newName) => onRenameSubmit(file, newName)} onFinishEditing={() => setEditingItemId(null)} onSaveField={(fieldId, value) => onSaveField?.(file.id!, fieldId, value)} fields={[]} onAction={(action, item) => handleAction(action as 'rename' | 'delete' | 'download' | 'restore', item) } isRecentlyDeleted={isRecentlyDeleted} isRecents={isRecents} selectedCount={selectedIds.size} canEdit={canEdit} isShareView={isShareView} allowDownload={allowDownload} /> ))}
)}
)}
)} {/* Empty state */} {isFolderEmpty && (
{isRecents ? (

{m.no_recent_files()}

{m.no_recent_files_description()}

) : ( {m.this_folder_is_empty()} )}
)} {/* Infinite scroll loader / trigger */}
{(isFetchingNextFoldersPage || isFetchingNextFilesPage) && ( )}
{/* Floating Action Button (+) for users with edit permissions */} {canEdit && !isRecentlyDeleted && !isRecents && !isShareView && !isPublic && (
fileInputRef.current?.click()} className="flex items-center gap-2.5 py-2 cursor-pointer" > {m.upload_file()} folderInputRef.current?.click()} className="flex items-center gap-2.5 py-2 cursor-pointer" > {m.upload_folder()} setIsNewFolderDialogOpen(true)} className="flex items-center gap-2.5 py-2 cursor-pointer" > {m.new_folder()}
)} {/* New Folder Dialog */}
{m.new_folder()} {m.folder_name()}
setNewFolderName(e.target.value)} />
{/* Delete Confirmation Alert Dialog */} {m.delete_asset_title()} {m.delete_asset_description()} {m.cancel()} confirmDelete()} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > {m.delete()} {/* Empty Trash Confirmation Alert Dialog */} {m.empty_trash_title()} {m.empty_trash_description()} {m.cancel()} emptyTrash()} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" disabled={isEmptyingTrash} > {isEmptyingTrash ? 'Deleting...' : m.delete()} {/* Download Dialog */} {isLoadingLinks ? m.preparing_download() : m.confirm_download()} {isLoadingLinks ? m.resolving_files_wait() : m.folder_files_download_description()} {isLoadingLinks ? (
{m.preparing_download_links()}
) : (
{m.download_includes_files({ count: resolvedFiles.length })}

{m.no_folder_structure()}

{m.folder_structure_warning()}

)} {!isLoadingLinks ? ( <> ) : ( )}
) }