'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 { uploadFilesWithUppy } from '@/ui/lib/uploader' 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' import { AlertTriangle, ChevronDown, ChevronRight, Download, FolderClock, FolderPlus, Loader2, Plus, Upload, } from 'lucide-react' import React, { useMemo, 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' import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status' import { useArchiveConfig } from '@/ui/hooks/use-archive-config' import { ArchiveConfirmDialog } from '../archive-confirm-dialog' 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, meta?: { isCheckbox?: boolean }) => 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() useBatchFileStatus({ teamId, items: files }) 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, skippedArchivedCount, startDownload, archiveConfirmState, setArchiveConfirmState, confirmArchiveOrRestore, isArchiving, isRestoringArchive, handleCopy, } = useFileActions({ teamId, projectId, assetId, folders, files, selectedIds, isPublic, shareId, }) const { archiveStorageEnabled } = useArchiveConfig() // 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 startTask = useUploadStore((state) => state.startTask) const throttledInvalidateSearch = useMemo(() => { let timer: ReturnType | null = null let lastRun = 0 const THROTTLE_MS = 2500 const run = () => { const now = Date.now() if (now - lastRun >= THROTTLE_MS) { lastRun = now queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) } else if (!timer) { timer = setTimeout( () => { timer = null lastRun = Date.now() queryClient.invalidateQueries({ queryKey: ['search', teamId, assetId], }) }, THROTTLE_MS - (now - lastRun), ) } } const cancel = () => { if (timer) { clearTimeout(timer) timer = null } } const reset = () => { cancel() lastRun = Date.now() } return Object.assign(run, { cancel, reset }) }, [queryClient, teamId, assetId]) 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] } }, onError: () => { toast.error(m.failed_upload_file()) }, onSuccess: async (data, variables, context) => { const currentFiles = context?.files || [] const filesProgressInfo = currentFiles .map((f) => { const assetInfo = data.createdAssets?.find((a) => a.tempId === f.id) const urlInfo = data.presignedUrls?.find((p) => p.id === f.id) return { fileId: assetInfo?.assetId || 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'] }) throttledInvalidateSearch.reset() try { await uploadFilesWithUppy({ files: currentFiles, taskId: data.taskId!, teamId: teamId!, storageBackend: (data.storageBackend as 's3' | 'local') || 'local', createdAssets: data.createdAssets, presignedUrls: data.presignedUrls, onFileFinished: () => { throttledInvalidateSearch() }, }) } finally { throttledInvalidateSearch.cancel() 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' | 'archive' | 'restore-archive', item, ) } isRecentlyDeleted={isRecentlyDeleted} isRecents={isRecents} selectedCount={selectedIds.size} isPublic={isPublic} canEdit={canEdit} archiveStorageEnabled={archiveStorageEnabled} isShareView={isShareView} allowDownload={allowDownload} onCopy={handleCopy} isTeamOwner={canAdmin} /> ))}
)}
)} {/* 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' | 'archive' | 'restore-archive', item, ) } isRecentlyDeleted={isRecentlyDeleted} isRecents={isRecents} selectedCount={selectedIds.size} isPublic={isPublic} canEdit={canEdit} archiveStorageEnabled={archiveStorageEnabled} isShareView={isShareView} allowDownload={allowDownload} onCopy={handleCopy} isTeamOwner={canAdmin} /> ))}
)}
)}
)} {/* 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()} { e.preventDefault() 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 })}
{skippedArchivedCount > 0 && (
{m.download_skipped_archived_notice({ count: skippedArchivedCount })}
)}

{m.no_folder_structure()}

{m.folder_structure_warning()}

)} {!isLoadingLinks ? ( <> ) : ( )}
setArchiveConfirmState((prev) => ({ ...prev, open }))} mode={archiveConfirmState.mode} onConfirm={confirmArchiveOrRestore} isPending={isArchiving || isRestoringArchive} />
) }