import { useCallback, useEffect, useRef, useState, type DragEvent as ReactDragEvent, } from "react"; import { ArrowUp, Download, FileIcon, Folder, FolderOpen, FolderPlus, RefreshCw, Trash2, Upload, } from "lucide-react"; import { Badge } from "@nous-research/ui/ui/components/badge"; import { Button } from "@nous-research/ui/ui/components/button"; import { Card, CardContent } from "@nous-research/ui/ui/components/card"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@nous-research/ui/ui/components/dialog"; import { Input } from "@nous-research/ui/ui/components/input"; import { Spinner } from "@nous-research/ui/ui/components/spinner"; import { Toast } from "@nous-research/ui/ui/components/toast"; import { useToast } from "@nous-research/ui/hooks/use-toast"; import { DeleteConfirmDialog } from "@/components/DeleteConfirmDialog"; import { usePageHeader } from "@/contexts/usePageHeader"; import { api } from "@/lib/api"; import type { ManagedFileEntry, ManagedFilesResponse } from "@/lib/api"; import { PluginSlot } from "@/plugins"; const DATE_FORMAT = new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeStyle: "short", }); function joinPath(base: string, name: string): string { const cleanName = name.trim().replace(/^[\\/]+/, ""); if (!cleanName) return base; const separator = base.includes("\\") && !base.includes("/") ? "\\" : "/"; if (!base || base.endsWith("/") || base.endsWith("\\")) return `${base}${cleanName}`; return `${base}${separator}${cleanName}`; } function formatBytes(size: number | null): string { if (size === null) return "-"; if (size < 1024) return `${size} B`; if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`; if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`; return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`; } function readAsDataUrl(file: globalThis.File): Promise { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.addEventListener("load", () => { if (typeof reader.result === "string") resolve(reader.result); else reject(new Error("Could not read file")); }); reader.addEventListener("error", () => reject(reader.error ?? new Error("Could not read file"))); reader.readAsDataURL(file); }); } function downloadDataUrl(dataUrl: string, name: string) { const link = document.createElement("a"); link.href = dataUrl; link.download = name || "download"; document.body.appendChild(link); link.click(); link.remove(); } function displayPath(path: string | null | undefined): string { return path?.trim() || "Files"; } function transferHasFiles(event: ReactDragEvent): boolean { return Array.from(event.dataTransfer.types).includes("Files"); } export default function FilesPage() { const { toast, showToast } = useToast(); const { setAfterTitle, setEnd } = usePageHeader(); const fileInputRef = useRef(null); const dragDepthRef = useRef(0); const [currentPath, setCurrentPath] = useState(undefined); const [pathInput, setPathInput] = useState(""); const [listing, setListing] = useState(null); const [loading, setLoading] = useState(false); const [uploading, setUploading] = useState(false); const [draggingFiles, setDraggingFiles] = useState(false); const [creating, setCreating] = useState(false); const [createDialogOpen, setCreateDialogOpen] = useState(false); const [deleting, setDeleting] = useState(false); const [folderName, setFolderName] = useState(""); const [pendingDelete, setPendingDelete] = useState(null); const [error, setError] = useState(null); const activePath = listing?.path ?? currentPath ?? ""; const canChangePath = listing?.can_change_path ?? false; const canUpload = Boolean(activePath) && !uploading; const headerPath = displayPath(listing?.locked_root ?? listing?.path ?? currentPath); const load = useCallback( async (path = currentPath) => { setLoading(true); setError(null); try { const result = await api.listFiles(path); setListing(result); setCurrentPath(result.path); setPathInput(result.path); } catch (e) { setError(String(e)); } finally { setLoading(false); } }, [currentPath], ); useEffect(() => { // Existing dashboard data pages fetch from effects; keep this local and explicit // until the shared lint profile is updated for async page loaders. // eslint-disable-next-line react-hooks/set-state-in-effect void load(currentPath); }, [currentPath]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { setAfterTitle( {headerPath} , ); setEnd(
, ); return () => { setAfterTitle(null); setEnd(null); }; }, [headerPath, load, loading, setAfterTitle, setEnd]); const openDirectory = (entry: ManagedFileEntry) => { if (entry.is_directory) { setCurrentPath(entry.path); } }; const goToPath = async () => { const nextPath = pathInput.trim(); if (!nextPath) { showToast("Path required", "error"); return; } await load(nextPath); }; const createDirectory = async () => { const name = folderName.trim(); if (!activePath) { showToast("Directory unavailable", "error"); return; } if (!name) { showToast("Folder name required", "error"); return; } setCreating(true); try { await api.createDirectory(joinPath(activePath, name)); setFolderName(""); setCreateDialogOpen(false); showToast("Folder created", "success"); await load(); } catch (e) { showToast(`Create failed: ${e}`, "error"); } finally { setCreating(false); } }; const uploadFiles = async (files: FileList | null) => { if (!files?.length) return; setUploading(true); try { for (const file of Array.from(files)) { const dataUrl = await readAsDataUrl(file); await api.uploadFile(joinPath(activePath, file.name), dataUrl, true); } showToast(`${files.length} file${files.length === 1 ? "" : "s"} uploaded`, "success"); await load(); } catch (e) { showToast(`Upload failed: ${e}`, "error"); } finally { setUploading(false); if (fileInputRef.current) fileInputRef.current.value = ""; } }; const handleDragEnter = (event: ReactDragEvent) => { if (!canUpload || !transferHasFiles(event)) return; event.preventDefault(); dragDepthRef.current += 1; setDraggingFiles(true); }; const handleDragOver = (event: ReactDragEvent) => { if (!canUpload || !transferHasFiles(event)) return; event.preventDefault(); event.dataTransfer.dropEffect = "copy"; }; const handleDragLeave = (event: ReactDragEvent) => { if (!canUpload || !transferHasFiles(event)) return; event.preventDefault(); dragDepthRef.current = Math.max(0, dragDepthRef.current - 1); if (dragDepthRef.current === 0) { setDraggingFiles(false); } }; const handleDrop = (event: ReactDragEvent) => { if (!canUpload) return; event.preventDefault(); dragDepthRef.current = 0; setDraggingFiles(false); void uploadFiles(event.dataTransfer.files); }; const downloadFile = async (entry: ManagedFileEntry) => { if (entry.is_directory) return; try { const file = await api.readFile(entry.path); downloadDataUrl(file.data_url, file.name); } catch (e) { showToast(`Download failed: ${e}`, "error"); } }; const confirmDelete = async () => { if (!pendingDelete) return; setDeleting(true); try { await api.deleteFile(pendingDelete.path, pendingDelete.is_directory); showToast("Deleted", "success"); setPendingDelete(null); await load(); } catch (e) { showToast(`Delete failed: ${e}`, "error"); } finally { setDeleting(false); } }; return (
void uploadFiles(event.currentTarget.files)} />
{canChangePath ? (
{ event.preventDefault(); void goToPath(); }} > setPathInput(event.target.value)} aria-label="Path" placeholder="Path" className="h-9 min-w-0 flex-1 font-mono" />
) : (
{activePath}
)}
{error && (
{error}
)}
Name Size Modified Actions
{listing?.parent && ( )} {loading && !listing ? (
Loading files...
) : listing && listing.entries.length === 0 ? (
No files
) : ( listing?.entries.map((entry) => (
{formatBytes(entry.size)} {Number.isFinite(entry.mtime) ? DATE_FORMAT.format(entry.mtime * 1000) : "-"} {entry.is_directory ? ( ) : ( )}
)) )}
{ if (creating) return; setCreateDialogOpen(open); if (!open) setFolderName(""); }} > Create folder Target: {activePath || "Loading"}
setFolderName(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") void createDirectory(); }} placeholder="Folder name" disabled={creating} />
setPendingDelete(null)} onConfirm={() => void confirmDelete()} title={pendingDelete ? `Delete ${pendingDelete.name}?` : "Delete item?"} description={ pendingDelete?.is_directory ? "This removes the folder and everything inside it." : "This removes the file." } />
); }