import { useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import LoadingButton from './LoadingButton'; import SortTh from './SortTh'; import { supabase } from '../lib/supabase'; import { popupMenuStyle } from '../lib/popupStyles'; const TABLE_TH = { fontSize: 10, fontWeight: 500, color: 'var(--text-muted)', letterSpacing: 0.6, textTransform: 'uppercase', padding: '0 0 12px', border: 'none', background: 'transparent', verticalAlign: 'top' }; const TABLE_TD = { padding: '5px', fontSize: 13, color: 'var(--text-primary)', border: 'none', background: 'transparent' }; const LABEL = { fontSize: 11, fontWeight: 500, color: 'var(--text-secondary)', letterSpacing: 0.8, textTransform: 'uppercase' }; const ITEM_STYLE = { display: 'flex', alignItems: 'center', gap: 8, padding: '7px 14px', fontSize: 13, cursor: 'pointer', color: 'var(--text-primary)', background: 'none', border: 'none', width: '100%', textAlign: 'left', borderRadius: 4, whiteSpace: 'nowrap' }; const SEP = { height: 1, background: 'var(--border)', margin: '4px 0' }; function formatBytes(bytes) { const value = Number(bytes || 0); if (!value) return '—'; const units = ['B', 'KB', 'MB', 'GB']; const index = Math.min(Math.floor(Math.log(value) / Math.log(1024)), units.length - 1); return `${(value / (1024 ** index)).toFixed(index === 0 ? 0 : 1)} ${units[index]}`; } function formatDate(dt) { if (!dt) return '—'; const d = new Date(dt); return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + ' ' + d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit', hour12: true }); } function fileIconStyle(ext) { const e = ext.toLowerCase(); if (['jpg','jpeg','png','gif','webp','svg','ico','bmp','tiff','avif','heic'].includes(e)) return { bg: '#16a34a', color: '#fff' }; if (['mp4','mov','avi','mkv','webm','m4v','wmv','flv'].includes(e)) return { bg: '#7c3aed', color: '#fff' }; if (['mp3','wav','ogg','flac','aac','m4a'].includes(e)) return { bg: '#db2777', color: '#fff' }; if (e === 'pdf') return { bg: '#dc2626', color: '#fff' }; if (['doc','docx','rtf'].includes(e)) return { bg: '#2563eb', color: '#fff' }; if (['txt','md'].includes(e)) return { bg: '#64748b', color: '#fff' }; if (['xls','xlsx','csv'].includes(e)) return { bg: '#16a34a', color: '#fff' }; if (['ppt','pptx'].includes(e)) return { bg: '#ea580c', color: '#fff' }; if (['zip','rar','7z','tar','gz'].includes(e)) return { bg: '#92400e', color: '#fff' }; if (['ai','eps'].includes(e)) return { bg: '#ff6c00', color: '#fff' }; if (['psd','psb'].includes(e)) return { bg: '#001e36', color: '#31a8ff' }; if (['indd','idml'].includes(e)) return { bg: '#49021f', color: '#ff3366' }; if (['fig','sketch'].includes(e)) return { bg: '#7c3aed', color: '#fff' }; return { bg: '#475569', color: '#fff' }; } function FileIcon({ entry }) { if (entry.type === 'dir') { return (
); } const ext = (entry.name.includes('.') ? entry.name.split('.').pop() : '').toUpperCase().slice(0, 4) || 'FILE'; const { bg, color } = fileIconStyle(ext); return (
{ext}
); } function pathParts(path) { return String(path || '/').split('/').filter(Boolean); } function pathTo(index, parts) { return `/${parts.slice(0, index + 1).join('/')}`; } function joinVirtualPath(...parts) { return ('/' + parts.join('/')).replace(/\/+/g, '/').replace(/\/$/, '') || '/'; } export default function FileBrowser({ initialPath = '/', rootPath = '/' }) { const [currentPath, setCurrentPath] = useState(initialPath); const [entries, setEntries] = useState([]); const [parentPath, setParentPath] = useState('/'); const [canGoUp, setCanGoUp] = useState(false); const [loading, setLoading] = useState(true); const [working, setWorking] = useState(''); const [dragging, setDragging] = useState(false); const [error, setError] = useState(''); const [readOnly, setReadOnly] = useState(false); const [folderName, setFolderName] = useState(''); const [showFolderInput, setShowFolderInput] = useState(false); const [renamingEntry, setRenamingEntry] = useState(null); const [renameValue, setRenameValue] = useState(''); const [uploadProgress, setUploadProgress] = useState(null); const [selected, setSelected] = useState(new Set()); const [sortKey, setSortKey] = useState('name'); const [sortDir, setSortDir] = useState('asc'); const [ctxMenu, setCtxMenu] = useState(null); const [clipboard, setClipboard] = useState(null); const fileInputRef = useRef(null); const folderInputRef = useRef(null); const breadcrumbs = useMemo(() => pathParts(currentPath), [currentPath]); useEffect(() => { if (!ctxMenu) return; const close = () => setCtxMenu(null); window.addEventListener('click', close); return () => window.removeEventListener('click', close); }, [ctxMenu]); const apiFetch = async (url, options = {}) => { const { data: { session } } = await supabase.auth.getSession(); if (!session?.access_token) throw new Error('Session expired. Please sign in again.'); const response = await fetch(url, { ...options, headers: { Authorization: `Bearer ${session.access_token}`, ...(options.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), ...(options.headers || {}), }, }); const data = await response.json().catch(() => ({})); if (!response.ok) throw new Error(data.error || 'File request failed.'); return data; }; const loadFiles = async (path = currentPath) => { setLoading(true); setError(''); setSelected(new Set()); try { const params = new URLSearchParams({ action: 'list', path }); const data = await apiFetch(`/api/filebrowser?${params}`); if (data.configured === false) { setError(data.error || 'File browser not configured.'); return; } setEntries(data.entries || []); setCurrentPath(data.path || path); setParentPath(data.parentPath || '/'); setCanGoUp(data.canGoUp || false); setReadOnly(data.readOnly || false); } catch (err) { setError(err.message); } finally { setLoading(false); } }; useEffect(() => { loadFiles(initialPath); }, [initialPath]); // eslint-disable-line react-hooks/exhaustive-deps const toggleSort = (col) => { if (sortKey === col) setSortDir(d => d === 'asc' ? 'desc' : 'asc'); else { setSortKey(col); setSortDir(col === 'modified' ? 'desc' : 'asc'); } }; const sortedEntries = useMemo(() => { return [...entries].sort((a, b) => { const aDir = a.type === 'dir'; const bDir = b.type === 'dir'; if (aDir !== bDir) return aDir ? -1 : 1; let av, bv; if (sortKey === 'name') { av = (a.name || '').toLowerCase(); bv = (b.name || '').toLowerCase(); } else if (sortKey === 'size') { av = Number(a.size || 0); bv = Number(b.size || 0); } else if (sortKey === 'modified') { av = new Date(a.mtime || 0).getTime(); bv = new Date(b.mtime || 0).getTime(); } else { av = ''; bv = ''; } const r = typeof av === 'string' ? av.localeCompare(bv) : (av > bv ? 1 : av < bv ? -1 : 0); return sortDir === 'asc' ? r : -r; }); }, [entries, sortKey, sortDir]); const downloadFile = async (entry) => { setWorking(`dl:${entry.path}`); try { const data = await apiFetch(`/api/filebrowser?action=download&path=${encodeURIComponent(entry.path)}`); if (data.url && data.token) { const sep = data.url.includes('?') ? '&' : '?'; const a = document.createElement('a'); a.href = `${data.url}${sep}auth=${encodeURIComponent(data.token)}`; a.download = entry.name; a.target = '_blank'; a.rel = 'noopener noreferrer'; document.body.appendChild(a); a.click(); document.body.removeChild(a); } } catch (err) { setError(err.message); } finally { setWorking(''); } }; const downloadSelected = async () => { if (!selected.size) return; setWorking('dl-sel'); try { for (const name of selected) { const entry = entries.find(e => e.name === name); if (entry && entry.type !== 'dir') await downloadFile(entry); } } finally { setWorking(''); } }; const deleteEntry = async (entry) => { if (!window.confirm(`Delete "${entry.name}"? This cannot be undone.`)) return; setWorking(`del:${entry.path}`); try { await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' }); await loadFiles(currentPath); } catch (err) { setError(err.message); } finally { setWorking(''); } }; const deleteSelected = async () => { if (!selected.size || !window.confirm(`Delete ${selected.size} item(s)?`)) return; for (const name of selected) { const entry = entries.find(e => e.name === name); if (!entry) continue; await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' }).catch(() => {}); } setSelected(new Set()); await loadFiles(currentPath); }; const createFolder = async (e) => { e.preventDefault(); if (!folderName.trim()) return; setWorking('mkdir'); try { await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: folderName }) }); setFolderName(''); setShowFolderInput(false); await loadFiles(currentPath); } catch (err) { setError(err.message); } finally { setWorking(''); } }; const renameEntry = async (e) => { e.preventDefault(); const newName = renameValue.trim(); if (!newName || newName === renamingEntry.name) { setRenamingEntry(null); return; } setWorking(`ren:${renamingEntry.path}`); try { await apiFetch('/api/filebrowser?action=rename', { method: 'POST', body: JSON.stringify({ path: renamingEntry.path, name: newName }) }); setRenamingEntry(null); await loadFiles(currentPath); } catch (err) { setError(err.message); } finally { setWorking(''); } }; const pasteClipboard = async () => { if (!clipboard) return; setWorking('paste'); try { for (const item of clipboard.items) { await apiFetch('/api/filebrowser?action=' + (clipboard.mode === 'copy' ? 'copy' : 'move'), { method: 'POST', body: JSON.stringify({ srcPath: item.path, dstParentPath: currentPath }), }); } if (clipboard.mode === 'move') setClipboard(null); await loadFiles(currentPath); } catch (err) { setError(err.message); } finally { setWorking(''); } }; async function uploadOneFile(vPath, file, retries = 3) { for (let attempt = 1; attempt <= retries; attempt++) { try { await apiFetch(`/api/filebrowser?action=upload&path=${encodeURIComponent(vPath)}`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: file, }); return; } catch (err) { if (attempt === retries) throw err; await new Promise(r => setTimeout(r, attempt * 1000)); } } } const uploadFiles = async (files) => { const sel = Array.from(files || []); if (!sel.length) return; setWorking('upload'); setUploadProgress(0); setError(''); try { for (let i = 0; i < sel.length; i++) { await uploadOneFile(joinVirtualPath(currentPath, sel[i].name), sel[i]); setUploadProgress(Math.round(((i + 1) / sel.length) * 100)); } } catch (err) { setError(err.message); } finally { setWorking(''); setUploadProgress(null); if (fileInputRef.current) fileInputRef.current.value = ''; setDragging(false); await loadFiles(currentPath); } }; const uploadFolder = async (files) => { const sel = Array.from(files || []).filter(f => f.webkitRelativePath); if (!sel.length) return; setWorking('upload'); setUploadProgress(0); setError(''); try { const dirsNeeded = new Set(); for (const file of sel) { const parts = file.webkitRelativePath.split('/').slice(0, -1); for (let i = 1; i <= parts.length; i++) dirsNeeded.add(parts.slice(0, i).join('/')); } for (const dir of [...dirsNeeded].sort((a, b) => a.split('/').length - b.split('/').length)) { await apiFetch('/api/filebrowser?action=mkdir', { method: 'POST', body: JSON.stringify({ path: currentPath, name: dir.split('/').pop() }) }).catch(() => {}); } for (let i = 0; i < sel.length; i++) { await uploadOneFile(joinVirtualPath(currentPath, sel[i].webkitRelativePath), sel[i]); setUploadProgress(Math.round(((i + 1) / sel.length) * 100)); } } catch (err) { setError(err.message); } finally { setWorking(''); setUploadProgress(null); if (folderInputRef.current) folderInputRef.current.value = ''; await loadFiles(currentPath); } }; const handleDragEnter = (e) => { e.preventDefault(); if (!readOnly) setDragging(true); }; const handleDragOver = (e) => { e.preventDefault(); if (!readOnly) { e.dataTransfer.dropEffect = 'copy'; setDragging(true); } }; const handleDragLeave = (e) => { e.preventDefault(); if (!e.currentTarget.contains(e.relatedTarget)) setDragging(false); }; const handleDrop = async (e) => { e.preventDefault(); setDragging(false); if (readOnly) return; const items = Array.from(e.dataTransfer.items || []); const fsEntries = items.map(i => i.webkitGetAsEntry?.()).filter(Boolean); if (fsEntries.some(en => en.isDirectory)) { const readFsEntry = (entry) => new Promise(resolve => { if (entry.isFile) { entry.file(file => { Object.defineProperty(file, 'webkitRelativePath', { value: entry.fullPath.replace(/^\//, ''), writable: false, configurable: true }); resolve([file]); }); } else if (entry.isDirectory) { const reader = entry.createReader(); const readAll = acc => reader.readEntries(async entries => { if (!entries.length) { resolve(acc); return; } const nested = await Promise.all(entries.map(readFsEntry)); readAll([...acc, ...nested.flat()]); }); readAll([]); } else { resolve([]); } }); uploadFolder((await Promise.all(fsEntries.map(readFsEntry))).flat()); } else { if (!e.dataTransfer.files?.length) return; uploadFiles(e.dataTransfer.files); } }; const toggleSelect = (name) => setSelected(prev => { const next = new Set(prev); next.has(name) ? next.delete(name) : next.add(name); return next; }); const openCtxMenu = (e, entry, childPath) => { e.preventDefault(); e.stopPropagation(); setCtxMenu({ x: e.clientX, y: e.clientY, entry, childPath }); }; return (
{dragging && (
Drop files to upload
)} {/* Toolbar */}
{/* Selection actions — absolute top-right like FileSharing */} {selected.size > 0 && (
{!readOnly && }
)}
0 ? 260 : 0 }}>
Files
{uploadProgress !== null && Uploading {uploadProgress}%} {!readOnly && ( <> uploadFolder(e.target.files)} {...{ webkitdirectory: '' }} /> uploadFiles(e.target.files)} /> )}
Drag and drop files or folders here.
{/* Breadcrumbs */}
{breadcrumbs.slice(pathParts(rootPath).length).map((part, i) => { const absIdx = pathParts(rootPath).length + i; return ( / ); })}
{uploadProgress !== null && (
)} {/* File table */}
{error &&
{error}
} {loading ? (
Loading…
) : entries.length === 0 ? (
This folder is empty.
) : ( NameSizeModified {sortedEntries.map((entry, idx) => { const isDir = entry.type === 'dir'; const childPath = entry.path; const isRenaming = renamingEntry?.path === entry.path; const rowBg = idx % 2 === 0 ? 'var(--file-row-alt-bg, rgba(255,255,255,0.02))' : 'transparent'; return ( isDir && loadFiles(childPath)} onContextMenu={e => openCtxMenu(e, entry, childPath)} > ); })}
0} onChange={e => setSelected(e.target.checked ? new Set(entries.map(en => en.name)) : new Set())} />
{ e.stopPropagation(); toggleSelect(entry.name); }}> toggleSelect(entry.name)} onClick={e => e.stopPropagation()} /> {isRenaming ? (
e.stopPropagation()}> setRenameValue(e.target.value)} disabled={Boolean(working)} onKeyDown={e => { if (e.key === 'Escape') setRenamingEntry(null); }} style={{ fontSize: 13, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--card-bg-2)', color: 'var(--text-primary)', flex: 1, minWidth: 0 }} /> Save
) : (
{isDir ? ( ) : ( {entry.name} )}
)}
{isDir ? '—' : formatBytes(entry.size)} {formatDate(entry.mtime)}
)}
{/* Context menu — portal to escape stacking context */} {ctxMenu && createPortal(
e.stopPropagation()} style={{ ...popupMenuStyle, position: 'fixed', left: ctxMenu.x, top: ctxMenu.y, zIndex: 9999, padding: '4px 0', minWidth: 160 }}> {ctxMenu.entry?.type === 'dir' && ( )} {ctxMenu.entry?.type !== 'dir' && ( )} {ctxMenu.entry && !readOnly && ( <>
)} {ctxMenu.entry && ( <>
{!readOnly && ( )} )} {clipboard && ( <>
)} {!readOnly && ctxMenu.entry && ( <>
)}
, document.body )}
); }