import { useState, useEffect, useRef, useCallback, forwardRef, useImperativeHandle } from 'react' import { FileTree } from './FileTree' import { FileOperations } from './FileOperations' import { FilePreview } from './FilePreview' import { MobileFilePreviewModal } from './MobileFilePreviewModal' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog' import { Progress } from '@/components/ui/progress' import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react' import type { FileInfo } from '@/types/files' import { useMobile } from '@/hooks/useMobile' import { getFileApiUrl, useFile } from '@/api/files' export interface FileBrowserHandle { goBack: () => void canGoBack: () => boolean getCurrentPath: () => string } interface FileBrowserProps { basePath?: string onFileSelect?: (file: FileInfo) => void embedded?: boolean initialSelectedFile?: string onDirectoryLoad?: (info: { workspaceRoot?: string; currentPath: string }) => void onPreviewStateChange?: (isOpen: boolean) => void allowNavigateAboveBase?: boolean compact?: boolean } interface UploadItem { file: File relativePath: string } interface UploadProgress { current: number total: number currentFile: string errors: string[] cancelled: boolean } const encodeBase64 = (content: string) => { const bytes = new TextEncoder().encode(content) let binary = '' for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]) } return btoa(binary) } async function readFileEntry(entry: FileSystemFileEntry): Promise { return new Promise((resolve, reject) => { entry.file(resolve, reject) }) } async function readDirectoryEntries(dirReader: FileSystemDirectoryReader): Promise { return new Promise((resolve, reject) => { dirReader.readEntries(resolve, reject) }) } async function traverseFileSystemEntry( entry: FileSystemEntry, basePath: string = '' ): Promise { const items: UploadItem[] = [] const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name if (entry.isFile) { const fileEntry = entry as FileSystemFileEntry const file = await readFileEntry(fileEntry) items.push({ file, relativePath }) } else if (entry.isDirectory) { const dirEntry = entry as FileSystemDirectoryEntry const dirReader = dirEntry.createReader() let entries: FileSystemEntry[] = [] let batch: FileSystemEntry[] do { batch = await readDirectoryEntries(dirReader) entries = entries.concat(batch) } while (batch.length > 0) for (const childEntry of entries) { const childItems = await traverseFileSystemEntry(childEntry, relativePath) items.push(...childItems) } } return items } async function getUploadItemsFromDataTransfer(dataTransfer: DataTransfer): Promise { const items: UploadItem[] = [] const entries: FileSystemEntry[] = [] for (let i = 0; i < dataTransfer.items.length; i++) { const item = dataTransfer.items[i] const entry = item.webkitGetAsEntry?.() if (entry) { entries.push(entry) } } if (entries.length > 0) { for (const entry of entries) { const entryItems = await traverseFileSystemEntry(entry) items.push(...entryItems) } } else { for (let i = 0; i < dataTransfer.files.length; i++) { const file = dataTransfer.files[i] items.push({ file, relativePath: file.name }) } } return items } function getUploadItemsFromFileList(fileList: FileList): UploadItem[] { const items: UploadItem[] = [] for (let i = 0; i < fileList.length; i++) { const file = fileList[i] const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name items.push({ file, relativePath }) } return items } export const FileBrowser = forwardRef(function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile, onDirectoryLoad, onPreviewStateChange, allowNavigateAboveBase = false, compact = false }, ref) { const [currentPath, setCurrentPath] = useState(basePath) const [files, setFiles] = useState(null) const [selectedFile, setSelectedFile] = useState(null) const [searchQuery, setSearchQuery] = useState('') const [loading, setLoading] = useState(false) const [error, setError] = useState(null) const [isDragging, setIsDragging] = useState(false) const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false) const [uploadProgress, setUploadProgress] = useState(null) const dropZoneRef = useRef(null) const uploadCancelledRef = useRef(false) const loadRequestRef = useRef(0) const isMobile = useMobile() const stacked = isMobile || compact const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile) useEffect(() => { if (initialFileError) { setError(initialFileError.message) } }, [initialFileError]) const loadFiles = useCallback(async (path: string) => { const request = ++loadRequestRef.current setLoading(true) setError(null) try { const response = await fetch(getFileApiUrl(path)) if (!response.ok) { throw new Error(`Failed to load files: ${response.statusText}`) } const data = await response.json() if (request !== loadRequestRef.current) return setFiles(data) setCurrentPath(path) onDirectoryLoad?.({ workspaceRoot: data.workspaceRoot, currentPath: path }) } catch (err) { if (request !== loadRequestRef.current) return setError(err instanceof Error ? err.message : 'Failed to load files') } finally { if (request === loadRequestRef.current) setLoading(false) } }, [onDirectoryLoad]) const normalizePath = useCallback((path: string) => { const normalized = path .trim() .replace(/\\/g, '/') .replace(/\/+/g, '/') .replace(/\/+$/, '') if (normalized === '.' || normalized === './') { return '' } if (normalized.startsWith('./')) { return normalized.slice(2) } return normalized }, []) const getPathParts = useCallback((path: string) => normalizePath(path).split('/').filter(Boolean), [normalizePath]) const canNavigateUp = useCallback(() => { if (allowNavigateAboveBase && normalizePath(currentPath) === '') { return true } if (normalizePath(currentPath) === '..') { return false } const pathParts = getPathParts(currentPath) if (allowNavigateAboveBase) { return pathParts.length > 0 } return pathParts.length > 0 && normalizePath(currentPath) !== normalizePath(basePath) }, [allowNavigateAboveBase, basePath, currentPath, getPathParts, normalizePath]) const goToParentDirectory = useCallback(() => { if (allowNavigateAboveBase && normalizePath(currentPath) === '') { loadFiles('..') return } const pathParts = getPathParts(currentPath) if (pathParts.length > 0) { pathParts.pop() const parentPath = pathParts.join('/') loadFiles(allowNavigateAboveBase ? parentPath : parentPath || basePath) } }, [allowNavigateAboveBase, currentPath, basePath, loadFiles, getPathParts, normalizePath]) useImperativeHandle(ref, () => ({ goBack: goToParentDirectory, canGoBack: canNavigateUp, getCurrentPath: () => currentPath, }), [currentPath, goToParentDirectory, canNavigateUp]) const openFilePath = useCallback(async (path: string) => { setLoading(true) try { const response = await fetch(getFileApiUrl(path)) if (!response.ok) { throw new Error(`Failed to load file: ${response.statusText}`) } const fullFileData: FileInfo = await response.json() if (fullFileData.isDirectory) { setSelectedFile(null) setIsPreviewModalOpen(false) onPreviewStateChange?.(false) await loadFiles(fullFileData.path) return } setSelectedFile(fullFileData) onFileSelect?.(fullFileData) // On mobile, open preview in modal if (stacked) { setIsPreviewModalOpen(true) onPreviewStateChange?.(true) } } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load file') setSelectedFile(null) } finally { setLoading(false) } }, [onFileSelect, stacked, onPreviewStateChange, loadFiles]) const handleFileSelect = useCallback(async (file: FileInfo) => { if (file.isDirectory) { setSelectedFile(null) return } await openFilePath(file.path) }, [openFilePath]) const handleCloseModal = useCallback(() => { setIsPreviewModalOpen(false) setSelectedFile(null) onPreviewStateChange?.(false) }, [onPreviewStateChange]) const handleDirectoryClick = (path: string) => { loadFiles(path) } const handleRefresh = () => { loadFiles(currentPath) } const uploadSingleFile = useCallback(async (item: UploadItem): Promise => { const formData = new FormData() formData.append('file', item.file) formData.append('relativePath', item.relativePath) try { const response = await fetch(getFileApiUrl(currentPath), { method: 'POST', body: formData, }) if (!response.ok) { const errorData = await response.json().catch(() => ({})) return errorData.error || `Upload failed: ${response.statusText}` } return null } catch (err) { return err instanceof Error ? err.message : 'Upload failed' } }, [currentPath]) const handleUploadItems = useCallback(async (items: UploadItem[]) => { if (items.length === 0) return uploadCancelledRef.current = false const errors: string[] = [] setUploadProgress({ current: 0, total: items.length, currentFile: items[0].relativePath, errors: [], cancelled: false, }) for (let i = 0; i < items.length; i++) { if (uploadCancelledRef.current) { setUploadProgress(prev => prev ? { ...prev, cancelled: true } : null) break } const item = items[i] setUploadProgress(prev => prev ? { ...prev, current: i, currentFile: item.relativePath, } : null) const error = await uploadSingleFile(item) if (error) { errors.push(`${item.relativePath}: ${error}`) } } setUploadProgress(prev => prev ? { ...prev, current: items.length, errors, cancelled: uploadCancelledRef.current, } : null) await loadFiles(currentPath) }, [currentPath, uploadSingleFile, loadFiles]) const handleUpload = useCallback(async (fileList: FileList) => { const items = getUploadItemsFromFileList(fileList) await handleUploadItems(items) }, [handleUploadItems]) const cancelUpload = useCallback(() => { uploadCancelledRef.current = true }, []) const handleCreateFile = useCallback(async (name: string, type: 'file' | 'folder') => { try { const response = await fetch(getFileApiUrl([currentPath, name].filter(Boolean).join('/')), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ type, content: type === 'file' ? '' : undefined }), }) if (!response.ok) { throw new Error(`Create failed: ${response.statusText}`) } await loadFiles(currentPath) } catch (err) { setError(err instanceof Error ? err.message : 'Create failed') } }, [currentPath, loadFiles]) const handleDelete = useCallback(async (path: string) => { try { const response = await fetch(getFileApiUrl(path), { method: 'DELETE', }) if (!response.ok) { throw new Error(`Delete failed: ${response.statusText}`) } await loadFiles(currentPath) setSelectedFile(null) } catch (err) { setError(err instanceof Error ? err.message : 'Delete failed') } }, [currentPath, loadFiles]) const handleRename = useCallback(async (oldPath: string, newPath: string) => { try { const response = await fetch(getFileApiUrl(oldPath), { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ newPath }), }) if (!response.ok) { throw new Error(`Rename failed: ${response.statusText}`) } await loadFiles(currentPath) } catch (err) { setError(err instanceof Error ? err.message : 'Rename failed') } }, [currentPath, loadFiles]) const handleDragEnter = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setIsDragging(true) } const handleDragLeave = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() if (e.currentTarget === dropZoneRef.current) { setIsDragging(false) } } const handleDragOver = (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() } const handleDrop = async (e: React.DragEvent) => { e.preventDefault() e.stopPropagation() setIsDragging(false) const items = await getUploadItemsFromDataTransfer(e.dataTransfer) if (items.length > 0) { await handleUploadItems(items) } } useEffect(() => { loadFiles(basePath) }, [basePath, loadFiles]) useEffect(() => { if (!initialFileData) return setError(null) if (initialFileData.isDirectory) { setSelectedFile(null) void loadFiles(initialFileData.path) return } setSelectedFile(initialFileData) }, [initialFileData, loadFiles]) useEffect(() => { if (!initialFileData || initialFileData.isDirectory || !stacked) return setIsPreviewModalOpen(true) onPreviewStateChange?.(true) }, [initialFileData, stacked, onPreviewStateChange]) useEffect(() => { const handleFileSaved = (event: CustomEvent<{ path: string; content?: string }>) => { if (selectedFile && selectedFile.path === event.detail.path) { if (event.detail.content !== undefined) { const nextFile = { ...selectedFile, content: encodeBase64(event.detail.content), size: new Blob([event.detail.content]).size, lastModified: new Date(), } setSelectedFile(nextFile) onFileSelect?.(nextFile) return } handleFileSelect(selectedFile) } } window.addEventListener('fileSaved', handleFileSaved as EventListener) return () => window.removeEventListener('fileSaved', handleFileSaved as EventListener) }, [selectedFile, handleFileSelect, onFileSelect]) useEffect(() => { if (!isPreviewModalOpen) return const handleEscape = (e: KeyboardEvent) => { if (e.key === 'Escape') { handleCloseModal() } } document.addEventListener('keydown', handleEscape) return () => document.removeEventListener('keydown', handleEscape) }, [isPreviewModalOpen, handleCloseModal]) const showNavigateUp = allowNavigateAboveBase && normalizePath(currentPath) !== '..' ? true : canNavigateUp() const filteredFiles = files?.children?.filter(file => file.name.toLowerCase().includes(searchQuery.toLowerCase()) ) const isUploadComplete = uploadProgress && uploadProgress.current >= uploadProgress.total const canDismissDialog = isUploadComplete || uploadProgress?.cancelled const uploadDialog = ( { if (!open && canDismissDialog) setUploadProgress(null) }}> {uploadProgress?.cancelled ? 'Upload Cancelled' : isUploadComplete ? 'Upload Complete' : 'Uploading...'} {uploadProgress && uploadProgress.current < uploadProgress.total && !uploadProgress.cancelled && ( )} {uploadProgress && (

{uploadProgress.current} / {uploadProgress.total} files

{!isUploadComplete && (

{uploadProgress.currentFile}

)} {uploadProgress.errors.length > 0 && (

{uploadProgress.errors.length} file(s) failed:

{uploadProgress.errors.map((error, index) => (

{error}

))}
)} {canDismissDialog && ( )}
)}
) if (embedded) { return (
{isDragging && (

Drop files or folders here to upload

)} {uploadDialog} {/* Mobile: Full width file listing, Desktop: Split view */}
{compact && !isMobile && isPreviewModalOpen && selectedFile && !selectedFile.isDirectory ? (
) : (
setSearchQuery(e.target.value)} className="flex-1" />
{error && (
{error}
)}
{loading ? (
) : ( )}
)} {/* Desktop only: Preview panel */} {!stacked && (
{selectedFile && !selectedFile.isDirectory ? ( ) : (
Select a file to preview
)}
)}
{/* Mobile: File Preview Modal */}
) } return (
{isDragging && (

Drop files or folders here to upload

)}
File Browser
{error && (
{error}
)}
{/* Mobile: Full width file listing, Desktop: Split view */}
setSearchQuery(e.target.value)} className="flex-1" />
{loading ? (
) : (
)}
{/* Desktop only: Preview panel */} {!stacked && (
{selectedFile && !selectedFile.isDirectory ? ( ) : (
Select a file to preview
)}
)}
{/* Mobile: File Preview Modal */} {uploadDialog}
) })