Merge all role-dispatcher pages into single files; add FileBrowser with file-type icons
- DashboardPage, Projects, RequestsPage, ProjectDetailPage, RequestDetail: each now handles team/external/client in one file via role flags — removed 10 old role-specific sub-files - Layout: client Company nav link goes directly to /company/:id when user has a single company - FileBrowser: replace emoji icons with colored extension-text badges (square); folder icon stays 📁; Adobe/Figma/design-tool colors for design files - CompaniesPage: merged team Companies + client company routing (single-company redirect, multi-company list) - FileSharing: integrated FileBrowser component - Removed: seafile API + lib, old ServerStatus, TaskDetail, role-split page files Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,664 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import LoadingButton from './LoadingButton';
|
||||
import { supabase } from '../lib/supabase';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
function formatBytes(bytes) {
|
||||
const value = Number(bytes || 0);
|
||||
if (!value) return '—';
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
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();
|
||||
}
|
||||
|
||||
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 (e === 'pdf') return { bg: '#dc2626', color: '#fff' };
|
||||
if (['doc','docx','rtf','odt'].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 (['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' };
|
||||
return { bg: '#475569', color: '#fff' };
|
||||
}
|
||||
|
||||
function FileIcon({ entry }) {
|
||||
if (entry.type === 'dir') return <span className="file-icon">📁</span>;
|
||||
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: 700, letterSpacing: 0.4, fontFamily: 'monospace' }}>
|
||||
{ext}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function pathParts(path) {
|
||||
return String(path || '/').split('/').filter(Boolean);
|
||||
}
|
||||
|
||||
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();
|
||||
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);
|
||||
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 [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 fileInputRef = useRef(null);
|
||||
const folderInputRef = useRef(null);
|
||||
|
||||
const breadcrumbs = useMemo(() => pathParts(currentPath), [currentPath]);
|
||||
|
||||
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.');
|
||||
|
||||
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('');
|
||||
try {
|
||||
const params = new URLSearchParams({ action: 'list', path });
|
||||
const data = await apiFetch(`/api/filebrowser?${params}`);
|
||||
setConfigured(data.configured !== false);
|
||||
setEntries(data.entries || []);
|
||||
setCurrentPath(data.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 {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles(initialPath);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [initialPath]);
|
||||
|
||||
const openFolder = (entry) => {
|
||||
if (entry.type === 'dir') loadFiles(entry.path);
|
||||
};
|
||||
|
||||
const downloadFile = async (entry) => {
|
||||
setWorking(`download:${entry.path}`);
|
||||
setError('');
|
||||
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);
|
||||
}
|
||||
} 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('');
|
||||
try {
|
||||
await apiFetch(`/api/filebrowser?action=delete&path=${encodeURIComponent(entry.path)}`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
await loadFiles(currentPath);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setWorking('');
|
||||
}
|
||||
};
|
||||
|
||||
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 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(`rename:${renamingEntry.path}`);
|
||||
setError('');
|
||||
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 startRename = (entry) => {
|
||||
setMovingEntry(null);
|
||||
setRenamingEntry(entry);
|
||||
setRenameValue(entry.name);
|
||||
};
|
||||
|
||||
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,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const text = await res.text();
|
||||
throw new Error(`${text || res.status}`);
|
||||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
if (attempt === retries) throw new Error(`Upload failed for ${file.name} after ${retries} attempts: ${e.message}`);
|
||||
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('');
|
||||
try {
|
||||
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);
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
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('');
|
||||
|
||||
try {
|
||||
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) {
|
||||
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(() => {});
|
||||
}
|
||||
|
||||
// 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);
|
||||
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 handleDrop = async (e) => {
|
||||
e.preventDefault();
|
||||
setDragging(false);
|
||||
if (draggedEntry) return;
|
||||
if (!configured || loading || working) 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 allFiles = (await Promise.all(fsEntries.map(readFsEntry))).flat();
|
||||
uploadFolder(allFiles);
|
||||
} else {
|
||||
if (!e.dataTransfer.files?.length) return;
|
||||
uploadFiles(e.dataTransfer.files);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRowDragStart = (e, entry) => {
|
||||
e.stopPropagation();
|
||||
setDraggedEntry(entry);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`file-browser${dragging ? ' file-browser-dragging' : ''}`}
|
||||
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>
|
||||
</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;
|
||||
return (
|
||||
<button type="button" key={`${part}-${absIndex}`} onClick={() => loadFiles(pathTo(absIndex, breadcrumbs))} className="file-breadcrumb">
|
||||
{part}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="file-browser-actions">
|
||||
{!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: 6, 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>
|
||||
</form>
|
||||
) : (
|
||||
<button className="btn btn-outline btn-sm" disabled={!configured || loading || Boolean(working)} onClick={() => setShowFolderInput(true)}>
|
||||
+ New 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>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{uploadProgress !== null && (
|
||||
<div style={{ padding: '4px 12px', fontSize: 12, color: 'var(--text-muted)' }}>
|
||||
Uploading... {uploadProgress}%
|
||||
</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>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">Loading files...</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: 6 } : 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: 6, 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>
|
||||
)}
|
||||
{!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>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user