Session 2026-05-31: tasks table overhaul, FileBrowser redesign, folder path fix
- Tasks table: added R#, Assigned To (avatar), Priority (HOT/NO) columns; removed Status column; sortable columns; adjustable widths - FileBrowser: full visual rewrite to match FileSharing page (table layout, colored ext badges, SVG folder icon, sortable columns, multi-select, context menu, drag-drop) - TaskDetail folder tab: fix path with safeName(), rootPath set to project folder level - filebrowserFolders: export safeName for reuse Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+302
-461
@@ -1,73 +1,70 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import LoadingButton from './LoadingButton';
|
||||
import SortTh from './SortTh';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
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' };
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!value) return '—';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
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 '—';
|
||||
return new Date(dt).toLocaleDateString();
|
||||
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','wma'].includes(e)) return { bg: '#db2777', 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','odt'].includes(e)) return { bg: '#2563eb', 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','ods','numbers'].includes(e)) return { bg: '#16a34a', color: '#fff' };
|
||||
if (['ppt','pptx','odp','key'].includes(e)) return { bg: '#ea580c', color: '#fff' };
|
||||
if (['zip','rar','7z','tar','gz','bz2','xz'].includes(e)) return { bg: '#92400e', color: '#fff' };
|
||||
if (['js','ts','jsx','tsx','html','css','scss','json','py','rb','php','java','c','cpp','cs','go','rs'].includes(e)) return { bg: '#0891b2', color: '#fff' };
|
||||
if (['ttf','otf','woff','woff2'].includes(e)) return { bg: '#6b7280', 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','xd'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
|
||||
if (['fig','sketch'].includes(e)) return { bg: '#7c3aed', color: '#fff' };
|
||||
return { bg: '#475569', color: '#fff' };
|
||||
}
|
||||
|
||||
function FileIcon({ entry }) {
|
||||
if (entry.type === 'dir') return <span className="file-icon">📁</span>;
|
||||
if (entry.type === 'dir') {
|
||||
return (
|
||||
<div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--accent)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
|
||||
</svg>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const ext = (entry.name.includes('.') ? entry.name.split('.').pop() : '').toUpperCase().slice(0, 4) || 'FILE';
|
||||
const { bg, color } = fileIconStyle(ext);
|
||||
return (
|
||||
<span className="file-icon" style={{ background: bg, color, border: 'none', fontSize: 9, fontWeight: 400, letterSpacing: 0.4, fontFamily: 'monospace' }}>
|
||||
{ext}
|
||||
</span>
|
||||
<div style={{ width: 24, height: 24, borderRadius: 4, background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<span style={{ color, fontSize: 7, fontWeight: 600, letterSpacing: 0.3, fontFamily: 'monospace' }}>{ext}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function pathParts(path) {
|
||||
return String(path || '/').split('/').filter(Boolean);
|
||||
}
|
||||
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(/\/$/, '') || '/'; }
|
||||
|
||||
function pathTo(index, parts) {
|
||||
return `/${parts.slice(0, index + 1).join('/')}`;
|
||||
}
|
||||
|
||||
function encodeFbPath(path) {
|
||||
return path.split('/').map(p => encodeURIComponent(p)).join('/');
|
||||
}
|
||||
|
||||
function joinVirtualPath(...parts) {
|
||||
return ('/' + parts.join('/')).replace(/\/+/g, '/').replace(/\/$/, '') || '/';
|
||||
}
|
||||
|
||||
export default function FileBrowser({ initialPath = '/', rootPath = '/', showSync = false }) {
|
||||
const { currentUser } = useAuth();
|
||||
export default function FileBrowser({ initialPath = '/', rootPath = '/' }) {
|
||||
const [currentPath, setCurrentPath] = useState(initialPath);
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [configured, setConfigured] = useState(true);
|
||||
const [parentPath, setParentPath] = useState('/');
|
||||
const [canGoUp, setCanGoUp] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -77,21 +74,28 @@ export default function FileBrowser({ initialPath = '/', rootPath = '/', showSyn
|
||||
const [readOnly, setReadOnly] = useState(false);
|
||||
const [folderName, setFolderName] = useState('');
|
||||
const [showFolderInput, setShowFolderInput] = useState(false);
|
||||
const [movingEntry, setMovingEntry] = useState(null);
|
||||
const [renamingEntry, setRenamingEntry] = useState(null);
|
||||
const [renameValue, setRenameValue] = useState('');
|
||||
const [draggedEntry, setDraggedEntry] = useState(null);
|
||||
const [dragOverFolder, setDragOverFolder] = useState(null);
|
||||
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 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('Your session expired. Please sign in again.');
|
||||
|
||||
if (!session?.access_token) throw new Error('Session expired. Please sign in again.');
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
@@ -100,7 +104,6 @@ export default function FileBrowser({ initialPath = '/', rootPath = '/', showSyn
|
||||
...(options.headers || {}),
|
||||
},
|
||||
});
|
||||
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(data.error || 'File request failed.');
|
||||
return data;
|
||||
@@ -109,16 +112,16 @@ export default function FileBrowser({ initialPath = '/', rootPath = '/', showSyn
|
||||
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}`);
|
||||
setConfigured(data.configured !== false);
|
||||
if (data.configured === false) { setError(data.error || 'File browser not configured.'); return; }
|
||||
setEntries(data.entries || []);
|
||||
setCurrentPath(data.path || '/');
|
||||
setCurrentPath(data.path || path);
|
||||
setParentPath(data.parentPath || '/');
|
||||
setCanGoUp(data.canGoUp || false);
|
||||
setReadOnly(data.readOnly || false);
|
||||
if (data.configured === false) setError(data.error || 'FileBrowser is not configured.');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
@@ -126,286 +129,174 @@ export default function FileBrowser({ initialPath = '/', rootPath = '/', showSyn
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles(initialPath);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialPath]);
|
||||
useEffect(() => { loadFiles(initialPath); }, [initialPath]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const openFolder = (entry) => {
|
||||
if (entry.type === 'dir') loadFiles(entry.path);
|
||||
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(`download:${entry.path}`);
|
||||
setError('');
|
||||
setWorking(`dl:${entry.path}`);
|
||||
try {
|
||||
const data = await apiFetch(`/api/filebrowser?action=download&path=${encodeURIComponent(entry.path)}`);
|
||||
if (data.url && data.token) {
|
||||
// Append token as query param for browser direct download
|
||||
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);
|
||||
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('');
|
||||
}
|
||||
} catch (err) { setError(err.message); }
|
||||
finally { setWorking(''); }
|
||||
};
|
||||
|
||||
const deleteEntry = async (entry) => {
|
||||
const kind = entry.type === 'dir' ? 'folder' : 'file';
|
||||
if (!window.confirm(`Delete "${entry.name}" ${kind}? This cannot be undone.`)) return;
|
||||
|
||||
setWorking(`delete:${entry.path}`);
|
||||
setError('');
|
||||
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 apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, { method: 'DELETE' });
|
||||
await loadFiles(currentPath);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
} 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');
|
||||
setError('');
|
||||
try {
|
||||
await apiFetch('/api/filebrowser?action=mkdir', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path: currentPath, name: folderName }),
|
||||
});
|
||||
setFolderName('');
|
||||
setShowFolderInput(false);
|
||||
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('');
|
||||
}
|
||||
} 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(`rename:${renamingEntry.path}`);
|
||||
setError('');
|
||||
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 }),
|
||||
});
|
||||
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 startRename = (entry) => {
|
||||
setMovingEntry(null);
|
||||
setRenamingEntry(entry);
|
||||
setRenameValue(entry.name);
|
||||
} catch (err) { setError(err.message); }
|
||||
finally { setWorking(''); }
|
||||
};
|
||||
|
||||
async function uploadOneFile(url, token, fbPath, file, retries = 3) {
|
||||
for (let attempt = 1; attempt <= retries; attempt++) {
|
||||
try {
|
||||
const res = await fetch(`${url}/api/resources?source=files&path=${encodeURIComponent(fbPath)}&override=true`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/octet-stream',
|
||||
},
|
||||
body: file,
|
||||
method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/octet-stream' }, body: file,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`${text || res.status}`);
|
||||
}
|
||||
if (!res.ok) { const t = await res.text(); throw new Error(t || res.status); }
|
||||
return;
|
||||
} catch (e) {
|
||||
if (attempt === retries) throw new Error(`Upload failed for ${file.name} after ${retries} attempts: ${e.message}`);
|
||||
} catch (err) {
|
||||
if (attempt === retries) throw err;
|
||||
await new Promise(r => setTimeout(r, attempt * 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runConcurrent(tasks, concurrency = 2) {
|
||||
let index = 0;
|
||||
let done = 0;
|
||||
const total = tasks.length;
|
||||
const errors = [];
|
||||
await Promise.all(Array.from({ length: concurrency }, async () => {
|
||||
while (index < total) {
|
||||
const task = tasks[index++];
|
||||
try { await task(); } catch (e) { errors.push(e); }
|
||||
done++;
|
||||
setUploadProgress(Math.round((done / total) * 100));
|
||||
}
|
||||
}));
|
||||
if (errors.length) throw errors[0];
|
||||
}
|
||||
|
||||
// Upload files directly to FileBrowser using admin token
|
||||
const uploadFiles = async (files) => {
|
||||
const selected = Array.from(files || []);
|
||||
if (!selected.length) return;
|
||||
|
||||
setWorking('upload');
|
||||
setUploadProgress(0);
|
||||
setError('');
|
||||
const sel = Array.from(files || []);
|
||||
if (!sel.length) return;
|
||||
setWorking('upload'); setUploadProgress(0); setError('');
|
||||
try {
|
||||
const tokenData = await apiFetch('/api/filebrowser?action=upload-token', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path: currentPath }),
|
||||
});
|
||||
|
||||
const tokenData = await apiFetch('/api/filebrowser?action=upload-token', { method: 'POST', body: JSON.stringify({ path: currentPath }) });
|
||||
const { token, url, fbPath } = tokenData;
|
||||
const tasks = selected.map(file => () => uploadOneFile(url, token, joinVirtualPath(fbPath, file.name), file));
|
||||
await runConcurrent(tasks);
|
||||
setUploadProgress(100);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
setUploadProgress(null);
|
||||
for (let i = 0; i < sel.length; i++) {
|
||||
await uploadOneFile(url, token, joinVirtualPath(fbPath, 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);
|
||||
setDragging(false); await loadFiles(currentPath);
|
||||
}
|
||||
};
|
||||
|
||||
const uploadFolder = async (files) => {
|
||||
const selected = Array.from(files || []).filter(f => f.webkitRelativePath);
|
||||
if (!selected.length) return;
|
||||
|
||||
setWorking('upload');
|
||||
setUploadProgress(0);
|
||||
setError('');
|
||||
|
||||
const sel = Array.from(files || []).filter(f => f.webkitRelativePath);
|
||||
if (!sel.length) return;
|
||||
setWorking('upload'); setUploadProgress(0); setError('');
|
||||
try {
|
||||
const tokenData = await apiFetch('/api/filebrowser?action=upload-token', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ path: currentPath }),
|
||||
});
|
||||
|
||||
const tokenData = await apiFetch('/api/filebrowser?action=upload-token', { method: 'POST', body: JSON.stringify({ path: currentPath }) });
|
||||
const { token, url, fbPath } = tokenData;
|
||||
|
||||
// Create directories sequentially shallow-first
|
||||
const dirsNeeded = new Set();
|
||||
for (const file of selected) {
|
||||
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('/'));
|
||||
}
|
||||
const sortedDirs = [...dirsNeeded].sort((a, b) => a.split('/').length - b.split('/').length);
|
||||
for (const dir of sortedDirs) {
|
||||
const dirFbPath = joinVirtualPath(fbPath, dir);
|
||||
await fetch(`${url}/api/resources?source=files&path=${encodeURIComponent(dirFbPath)}&isDir=true`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
}).catch(() => {});
|
||||
for (const dir of [...dirsNeeded].sort((a, b) => a.split('/').length - b.split('/').length)) {
|
||||
await fetch(`${url}/api/resources?source=files&path=${encodeURIComponent(joinVirtualPath(fbPath, dir))}&isDir=true`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } }).catch(() => {});
|
||||
}
|
||||
|
||||
// Upload files concurrently
|
||||
const tasks = selected.map(file => () => uploadOneFile(url, token, joinVirtualPath(fbPath, file.webkitRelativePath), file));
|
||||
await runConcurrent(tasks);
|
||||
setUploadProgress(100);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
setUploadProgress(null);
|
||||
for (let i = 0; i < sel.length; i++) {
|
||||
await uploadOneFile(url, token, joinVirtualPath(fbPath, 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 moveEntry = async (entry, targetFolderPath) => {
|
||||
setWorking(`move:${entry.path}`);
|
||||
setError('');
|
||||
try {
|
||||
await apiFetch('/api/filebrowser?action=move', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ srcPath: entry.path, dstPath: targetFolderPath }),
|
||||
});
|
||||
setMovingEntry(null);
|
||||
await loadFiles(currentPath);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragEnter = (e) => {
|
||||
e.preventDefault();
|
||||
if (!configured || loading || working || draggedEntry || readOnly) return;
|
||||
setDragging(true);
|
||||
};
|
||||
|
||||
const handleDragOver = (e) => {
|
||||
e.preventDefault();
|
||||
if (!configured || loading || working || draggedEntry || readOnly) return;
|
||||
e.dataTransfer.dropEffect = 'copy';
|
||||
setDragging(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (e) => {
|
||||
e.preventDefault();
|
||||
if (!e.currentTarget.contains(e.relatedTarget)) setDragging(false);
|
||||
};
|
||||
|
||||
const readFsEntry = (entry) => new Promise((resolve) => {
|
||||
if (entry.isFile) {
|
||||
entry.file(file => {
|
||||
const rel = entry.fullPath.replace(/^\//, '');
|
||||
Object.defineProperty(file, 'webkitRelativePath', { value: rel, 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([]);
|
||||
}
|
||||
});
|
||||
|
||||
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 (draggedEntry) return;
|
||||
if (!configured || loading || working) return;
|
||||
|
||||
e.preventDefault(); setDragging(false);
|
||||
if (readOnly) return;
|
||||
const items = Array.from(e.dataTransfer.items || []);
|
||||
const fsEntries = items.map(item => item.webkitGetAsEntry?.()).filter(Boolean);
|
||||
|
||||
if (fsEntries.length && fsEntries.some(en => en.isDirectory)) {
|
||||
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([]); }
|
||||
});
|
||||
const allFiles = (await Promise.all(fsEntries.map(readFsEntry))).flat();
|
||||
uploadFolder(allFiles);
|
||||
} else {
|
||||
@@ -414,251 +305,201 @@ export default function FileBrowser({ initialPath = '/', rootPath = '/', showSyn
|
||||
}
|
||||
};
|
||||
|
||||
const handleRowDragStart = (e, entry) => {
|
||||
e.stopPropagation();
|
||||
setDraggedEntry(entry);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
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 });
|
||||
};
|
||||
|
||||
const handleRowDragEnd = () => {
|
||||
setDraggedEntry(null);
|
||||
setDragOverFolder(null);
|
||||
};
|
||||
|
||||
const handleFolderDragOver = (e, folder) => {
|
||||
if (!draggedEntry || draggedEntry.path === folder.path) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
setDragOverFolder(folder.path);
|
||||
};
|
||||
|
||||
const handleFolderDragLeave = (e) => {
|
||||
if (!e.currentTarget.contains(e.relatedTarget)) setDragOverFolder(null);
|
||||
};
|
||||
|
||||
const handleFolderDrop = (e, folder) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setDragOverFolder(null);
|
||||
if (!draggedEntry || draggedEntry.path === folder.path) return;
|
||||
const entry = draggedEntry;
|
||||
setDraggedEntry(null);
|
||||
moveEntry(entry, folder.path);
|
||||
};
|
||||
const CTX_ITEM = { 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' };
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`file-browser${dragging ? ' file-browser-dragging' : ''}`}
|
||||
<div
|
||||
style={{ display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0, borderRadius: 8, border: `1px solid ${dragging ? 'var(--accent)' : 'var(--border)'}`, transition: 'border-color 140ms ease', position: 'relative', overflow: 'hidden' }}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
{(loading || working || uploadProgress !== null) && (
|
||||
<div className="file-browser-progress">
|
||||
<div
|
||||
className={`file-browser-progress-bar${uploadProgress === null ? ' indeterminate' : ''}`}
|
||||
style={uploadProgress !== null ? { width: `${uploadProgress}%` } : undefined}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dragging && (
|
||||
<div className="file-drop-overlay">
|
||||
<div className="file-drop-panel">
|
||||
<div className="file-drop-icon">↑</div>
|
||||
<div className="file-drop-title">Drop files to upload</div>
|
||||
<div className="file-drop-subtitle">Files will be added to the current folder.</div>
|
||||
<div style={{ position: 'absolute', inset: 0, zIndex: 10, background: 'rgba(245,165,35,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<div style={{ fontSize: 28, marginBottom: 8 }}>↑</div>
|
||||
<div style={{ fontSize: 14, fontWeight: 500, color: 'var(--accent)' }}>Drop files to upload</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="file-browser-toolbar">
|
||||
<div className="file-browser-breadcrumbs">
|
||||
<button type="button" onClick={() => loadFiles(rootPath)} className="file-breadcrumb">Files</button>
|
||||
{breadcrumbs.slice(pathParts(rootPath).length).map((part, index) => {
|
||||
const absIndex = pathParts(rootPath).length + index;
|
||||
{/* Toolbar */}
|
||||
<div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-secondary)', flexWrap: 'wrap' }}>
|
||||
<button type="button" onClick={() => loadFiles(rootPath)} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>Files</button>
|
||||
{breadcrumbs.slice(pathParts(rootPath).length).map((part, i) => {
|
||||
const absIdx = pathParts(rootPath).length + i;
|
||||
return (
|
||||
<button type="button" key={`${part}-${absIndex}`} onClick={() => loadFiles(pathTo(absIndex, breadcrumbs))} className="file-breadcrumb">
|
||||
{part}
|
||||
</button>
|
||||
<span key={`${part}-${absIdx}`} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
|
||||
<span style={{ opacity: 0.4 }}>/</span>
|
||||
<button type="button" onClick={() => loadFiles(pathTo(absIdx, breadcrumbs))} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 11, fontWeight: 500, letterSpacing: 0.6, textTransform: 'uppercase', color: absIdx === breadcrumbs.length - 1 ? 'var(--accent)' : 'var(--text-primary)', fontFamily: 'inherit', padding: 0 }}>{part}</button>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="file-browser-actions">
|
||||
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
|
||||
{uploadProgress !== null && <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>Uploading {uploadProgress}%</span>}
|
||||
{selected.size > 0 && (
|
||||
<button className="btn btn-danger" style={{ fontSize: 11, padding: '3px 10px' }} onClick={deleteSelected}>Delete ({selected.size})</button>
|
||||
)}
|
||||
{!readOnly && (showFolderInput ? (
|
||||
<form style={{ display: 'flex', gap: 6 }} onSubmit={createFolder}>
|
||||
<input
|
||||
type="text"
|
||||
value={folderName}
|
||||
onChange={(e) => setFolderName(e.target.value)}
|
||||
placeholder="Folder name"
|
||||
autoFocus
|
||||
disabled={!configured || loading || Boolean(working)}
|
||||
style={{ fontSize: 13, padding: '4px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text-primary)', width: 160 }}
|
||||
/>
|
||||
<LoadingButton type="submit" className="btn btn-outline btn-sm" loading={working === 'mkdir'} disabled={!folderName.trim() || !configured || loading || Boolean(working)} loadingText="Creating...">
|
||||
Create
|
||||
</LoadingButton>
|
||||
<button type="button" className="btn btn-outline btn-sm" onClick={() => { setShowFolderInput(false); setFolderName(''); }}>Cancel</button>
|
||||
<input autoFocus type="text" value={folderName} onChange={e => setFolderName(e.target.value)} placeholder="Folder name" disabled={Boolean(working)} style={{ fontSize: 12, padding: '3px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--card-bg-2)', color: 'var(--text-primary)', width: 140 }} />
|
||||
<LoadingButton type="submit" className="btn btn-outline" style={{ fontSize: 11, padding: '3px 10px' }} loading={working === 'mkdir'} disabled={!folderName.trim() || Boolean(working)} loadingText="…">Create</LoadingButton>
|
||||
<button type="button" className="btn btn-outline" style={{ fontSize: 11, padding: '3px 10px' }} onClick={() => { setShowFolderInput(false); setFolderName(''); }}>Cancel</button>
|
||||
</form>
|
||||
) : (
|
||||
<button className="btn btn-outline btn-sm" disabled={!configured || loading || Boolean(working)} onClick={() => setShowFolderInput(true)}>
|
||||
+ New Folder
|
||||
</button>
|
||||
<button className="btn btn-outline" style={{ fontSize: 11, padding: '3px 10px' }} disabled={Boolean(working)} onClick={() => setShowFolderInput(true)}>+ Folder</button>
|
||||
))}
|
||||
<LoadingButton className="btn btn-outline btn-sm" loading={loading} disabled={Boolean(working)} loadingText="Refreshing..." onClick={() => loadFiles(currentPath)}>
|
||||
⟳ Refresh
|
||||
</LoadingButton>
|
||||
{entries.length > 0 && (
|
||||
<LoadingButton className="btn btn-outline btn-sm" loading={working === `download:${currentPath}`} disabled={Boolean(working)} loadingText="Zipping..." onClick={() => downloadFile({ path: currentPath, name: breadcrumbs[breadcrumbs.length - 1] || 'files', type: 'dir' })}>
|
||||
↓ ZIP
|
||||
</LoadingButton>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<>
|
||||
<input ref={fileInputRef} type="file" multiple className="file-upload-input" onChange={(e) => uploadFiles(e.target.files)} />
|
||||
<input ref={folderInputRef} type="file" className="file-upload-input" onChange={(e) => uploadFolder(e.target.files)} {...{ webkitdirectory: '' }} />
|
||||
<LoadingButton className="btn btn-outline btn-sm" loading={working === 'upload'} disabled={!configured || loading || Boolean(working)} loadingText="Uploading..." onClick={() => folderInputRef.current?.click()}>
|
||||
↑ Folder
|
||||
</LoadingButton>
|
||||
<LoadingButton className="btn btn-primary btn-sm" loading={working === 'upload'} disabled={!configured || loading || Boolean(working)} loadingText="Uploading..." onClick={() => fileInputRef.current?.click()}>
|
||||
↑ Files
|
||||
</LoadingButton>
|
||||
<input ref={folderInputRef} type="file" style={{ display: 'none' }} onChange={e => uploadFolder(e.target.files)} {...{ webkitdirectory: '' }} />
|
||||
<input ref={fileInputRef} type="file" multiple style={{ display: 'none' }} onChange={e => uploadFiles(e.target.files)} />
|
||||
<LoadingButton className="btn btn-outline" style={{ fontSize: 11, padding: '3px 10px' }} loading={working === 'upload'} disabled={Boolean(working)} loadingText="Uploading…" onClick={() => folderInputRef.current?.click()}>↑ Folder</LoadingButton>
|
||||
<LoadingButton className="btn btn-primary" style={{ fontSize: 11, padding: '3px 10px' }} loading={working === 'upload'} disabled={Boolean(working)} loadingText="Uploading…" onClick={() => fileInputRef.current?.click()}>↑ Files</LoadingButton>
|
||||
</>
|
||||
)}
|
||||
<LoadingButton className="btn btn-outline" style={{ fontSize: 11, padding: '3px 10px' }} loading={loading} disabled={Boolean(working)} loadingText="…" onClick={() => loadFiles(currentPath)}>⟳</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{uploadProgress !== null && (
|
||||
<div style={{ padding: '4px 12px', fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
Uploading... {uploadProgress}%
|
||||
<div style={{ height: 2, background: 'var(--border)', flexShrink: 0 }}>
|
||||
<div style={{ height: '100%', background: 'var(--accent)', width: `${uploadProgress}%`, transition: 'width 200ms' }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <div className="notification notification-info">{error}</div>}
|
||||
|
||||
{draggedEntry && (
|
||||
<div style={{ padding: '6px 12px', fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
Dragging "{draggedEntry.name}" — drop onto a folder to move it
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="file-list">
|
||||
{canGoUp && currentPath !== rootPath && (
|
||||
<button type="button" className="file-row file-row-button" onClick={() => loadFiles(parentPath)} disabled={loading || Boolean(working)}>
|
||||
<span className="file-icon">↰</span>
|
||||
<span className="file-name">Up one folder</span>
|
||||
<span className="file-meta">—</span>
|
||||
<span className="file-meta">—</span>
|
||||
<span />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<div className="file-row file-row-head">
|
||||
<span />
|
||||
<span>Name</span>
|
||||
<span style={{ textAlign: 'right' }}>Size</span>
|
||||
<span style={{ textAlign: 'right' }}>Modified</span>
|
||||
<span />
|
||||
</div>
|
||||
|
||||
{/* File table */}
|
||||
<div className="scrollbar-thin-theme table-scroll-hidden" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '18px 21px' }}>
|
||||
{error && <div style={{ fontSize: 13, color: 'var(--danger)', marginBottom: 12 }}>{error}</div>}
|
||||
{loading ? (
|
||||
<div className="empty-state">Loading files...</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80, fontSize: 13, color: 'var(--text-muted)' }}>Loading…</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<h3>No files here yet</h3>
|
||||
<p>Upload files or create a folder to start this workspace.</p>
|
||||
</div>
|
||||
) : entries.map(entry => {
|
||||
const isMoving = movingEntry?.path === entry.path;
|
||||
const isRenaming = renamingEntry?.path === entry.path;
|
||||
const targetFolders = entries.filter(e => e.type === 'dir' && e.path !== entry.path);
|
||||
const isDragTarget = entry.type === 'dir' && draggedEntry && draggedEntry.path !== entry.path;
|
||||
const isDragOver = dragOverFolder === entry.path;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`file-row${isDragOver ? ' file-row-drag-over' : ''}`}
|
||||
key={`${entry.type}:${entry.path}`}
|
||||
draggable={!working}
|
||||
onDragStart={(e) => handleRowDragStart(e, entry)}
|
||||
onDragEnd={handleRowDragEnd}
|
||||
onDragOver={isDragTarget ? (e) => handleFolderDragOver(e, entry) : undefined}
|
||||
onDragLeave={isDragTarget ? handleFolderDragLeave : undefined}
|
||||
onDrop={isDragTarget ? (e) => handleFolderDrop(e, entry) : undefined}
|
||||
style={isDragOver ? { outline: '2px solid var(--accent)', borderRadius: 4 } : undefined}
|
||||
>
|
||||
<FileIcon entry={entry} />
|
||||
{isRenaming ? (
|
||||
<form style={{ display: 'flex', gap: 6, flex: 1 }} onSubmit={renameEntry}>
|
||||
<input
|
||||
type="text"
|
||||
value={renameValue}
|
||||
onChange={(e) => setRenameValue(e.target.value)}
|
||||
autoFocus
|
||||
disabled={Boolean(working)}
|
||||
style={{ fontSize: 13, padding: '2px 8px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--input-bg)', color: 'var(--text-primary)', flex: 1, minWidth: 0 }}
|
||||
onKeyDown={(e) => { if (e.key === 'Escape') setRenamingEntry(null); }}
|
||||
/>
|
||||
<LoadingButton type="submit" className="btn btn-outline btn-sm" loading={working === `rename:${entry.path}`} disabled={!renameValue.trim() || Boolean(working)} loadingText="Renaming...">
|
||||
Save
|
||||
</LoadingButton>
|
||||
<button type="button" className="btn btn-outline btn-sm" onClick={() => setRenamingEntry(null)}>Cancel</button>
|
||||
</form>
|
||||
) : entry.type === 'dir' ? (
|
||||
<button type="button" className="file-name file-name-button" onClick={() => openFolder(entry)} disabled={Boolean(working)}>
|
||||
{entry.name}
|
||||
</button>
|
||||
) : (
|
||||
<span className="file-name">{entry.name}</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 80, fontSize: 13, color: 'var(--text-muted)' }}>This folder is empty.</div>
|
||||
) : (
|
||||
<table className="table-sticky-head" style={{ width: '100%', tableLayout: 'fixed', borderCollapse: 'collapse' }}>
|
||||
<colgroup>
|
||||
<col style={{ width: 32 }} />
|
||||
<col />
|
||||
<col style={{ width: 90 }} />
|
||||
<col style={{ width: 180 }} />
|
||||
<col style={{ width: 80 }} />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ ...TABLE_TH, textAlign: 'center', padding: '0 5px 12px' }}>
|
||||
<input type="checkbox" checked={selected.size === entries.length && entries.length > 0} onChange={e => setSelected(e.target.checked ? new Set(entries.map(en => en.name)) : new Set())} />
|
||||
</th>
|
||||
<SortTh col="name" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'left', paddingLeft: 5 }}>Name</SortTh>
|
||||
<SortTh col="size" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Size</SortTh>
|
||||
<SortTh col="modified" sortKey={sortKey} sortDir={sortDir} onSort={toggleSort} style={{ ...TABLE_TH, textAlign: 'right' }}>Modified</SortTh>
|
||||
<th style={{ ...TABLE_TH }} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{canGoUp && currentPath !== rootPath && (
|
||||
<tr style={{ cursor: 'pointer' }} onClick={() => loadFiles(parentPath)}>
|
||||
<td style={TABLE_TD} />
|
||||
<td style={TABLE_TD}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<div style={{ width: 24, height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M19 12H5M12 5l-7 7 7 7" /></svg>
|
||||
</div>
|
||||
<span style={{ fontSize: 13, color: 'var(--text-muted)' }}>Up one folder</span>
|
||||
</div>
|
||||
</td>
|
||||
<td /><td /><td />
|
||||
</tr>
|
||||
)}
|
||||
{!isRenaming && (
|
||||
<>
|
||||
<span className="file-meta">{formatBytes(entry.size)}</span>
|
||||
<span className="file-meta">{formatDate(entry.mtime)}</span>
|
||||
<span className="file-row-actions">
|
||||
{readOnly ? null : isMoving ? (
|
||||
<>
|
||||
<span style={{ fontSize: 11, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>Move to:</span>
|
||||
{targetFolders.length === 0 ? (
|
||||
<span style={{ fontSize: 11, color: 'var(--text-muted)' }}>No folders here</span>
|
||||
) : targetFolders.map(folder => (
|
||||
<LoadingButton
|
||||
key={folder.path}
|
||||
className="btn btn-outline btn-sm"
|
||||
loading={working === `move:${entry.path}`}
|
||||
disabled={Boolean(working)}
|
||||
loadingText="Moving..."
|
||||
onClick={() => moveEntry(entry, folder.path)}
|
||||
>
|
||||
{folder.name}
|
||||
</LoadingButton>
|
||||
))}
|
||||
<button type="button" className="btn btn-outline btn-sm" onClick={() => setMovingEntry(null)} disabled={Boolean(working)}>✕</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LoadingButton className="btn-icon" title={entry.type === 'dir' ? 'Download ZIP' : 'Download'} loading={working === `download:${entry.path}`} disabled={Boolean(working)} loadingText="↓" onClick={() => downloadFile(entry)}>
|
||||
↓
|
||||
</LoadingButton>
|
||||
<button type="button" className="btn-icon" title="Rename" disabled={Boolean(working)} onClick={() => startRename(entry)}>
|
||||
<svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
</button>
|
||||
<LoadingButton className="btn-icon btn-icon-danger" title="Delete" loading={working === `delete:${entry.path}`} disabled={Boolean(working)} loadingText="…" onClick={() => deleteEntry(entry)}>
|
||||
✕
|
||||
</LoadingButton>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{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 (
|
||||
<tr
|
||||
key={`${entry.type}:${entry.path}`}
|
||||
style={{ cursor: isDir ? 'pointer' : 'default' }}
|
||||
onClick={() => isDir && loadFiles(childPath)}
|
||||
onContextMenu={e => openCtxMenu(e, entry, childPath)}
|
||||
>
|
||||
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'center' }} onClick={e => { e.stopPropagation(); toggleSelect(entry.name); }}>
|
||||
<input type="checkbox" checked={selected.has(entry.name)} onChange={() => toggleSelect(entry.name)} onClick={e => e.stopPropagation()} />
|
||||
</td>
|
||||
<td style={{ ...TABLE_TD, background: rowBg }}>
|
||||
{isRenaming ? (
|
||||
<form style={{ display: 'flex', gap: 6 }} onSubmit={renameEntry} onClick={e => e.stopPropagation()}>
|
||||
<input autoFocus type="text" value={renameValue} onChange={e => 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 }} />
|
||||
<LoadingButton type="submit" className="btn btn-outline" style={{ fontSize: 11, padding: '2px 8px' }} loading={working === `ren:${entry.path}`} disabled={!renameValue.trim()} loadingText="…">Save</LoadingButton>
|
||||
<button type="button" className="btn btn-outline" style={{ fontSize: 11, padding: '2px 8px' }} onClick={() => setRenamingEntry(null)}>Cancel</button>
|
||||
</form>
|
||||
) : (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<FileIcon entry={entry} />
|
||||
{isDir ? (
|
||||
<button type="button" onClick={e => { e.stopPropagation(); loadFiles(childPath); }} style={{ fontSize: 13, fontWeight: 400, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', textAlign: 'left', background: 'none', border: 'none', cursor: 'pointer', padding: 0, color: 'var(--accent)' }}>{entry.name}</button>
|
||||
) : (
|
||||
<span style={{ fontSize: 13, color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{entry.name}</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12, color: 'var(--text-muted)' }}>{isDir ? '—' : formatBytes(entry.size)}</td>
|
||||
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right', fontSize: 12, color: 'var(--text-muted)' }}>{formatDate(entry.mtime)}</td>
|
||||
<td style={{ ...TABLE_TD, background: rowBg, textAlign: 'right' }} onClick={e => e.stopPropagation()}>
|
||||
{!isRenaming && !readOnly && (
|
||||
<div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
|
||||
{!isDir && (
|
||||
<LoadingButton className="btn btn-outline" style={{ fontSize: 10, padding: '1px 8px', height: 22 }} loading={working === `dl:${entry.path}`} disabled={Boolean(working)} loadingText="↓" onClick={() => downloadFile(entry)}>↓</LoadingButton>
|
||||
)}
|
||||
<button className="btn btn-outline" style={{ fontSize: 10, padding: '1px 8px', height: 22 }} disabled={Boolean(working)} onClick={() => { setRenamingEntry(entry); setRenameValue(entry.name); }}>
|
||||
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
</button>
|
||||
<button className="btn btn-danger" style={{ fontSize: 10, padding: '1px 8px', height: 22 }} disabled={Boolean(working)} onClick={() => deleteEntry(entry)}>✕</button>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Context menu */}
|
||||
{ctxMenu && (
|
||||
<div onClick={e => e.stopPropagation()} style={{ ...popupMenuStyle, position: 'fixed', left: ctxMenu.x, top: ctxMenu.y, zIndex: 1000, padding: '4px 0', minWidth: 150 }}>
|
||||
{ctxMenu.entry && ctxMenu.entry.type !== 'dir' && (
|
||||
<button style={CTX_ITEM} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { downloadFile(ctxMenu.entry); setCtxMenu(null); }}>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/><polyline points="7,10 12,15 17,10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
|
||||
Download
|
||||
</button>
|
||||
)}
|
||||
{ctxMenu.entry && (
|
||||
<>
|
||||
<button style={CTX_ITEM} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { setRenamingEntry(ctxMenu.entry); setRenameValue(ctxMenu.entry.name); setCtxMenu(null); }}>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
|
||||
Rename
|
||||
</button>
|
||||
<div style={{ height: 1, background: 'var(--border)', margin: '4px 0' }} />
|
||||
<button style={{ ...CTX_ITEM, color: 'var(--danger)' }} onMouseEnter={e => e.currentTarget.style.background = 'var(--interactive-row-hover)'} onMouseLeave={e => e.currentTarget.style.background = 'none'} onClick={() => { deleteEntry(ctxMenu.entry); setCtxMenu(null); }}>
|
||||
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="3,6 5,6 21,6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
|
||||
Delete
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user