import React, { useState, useEffect, useRef } from 'react'; import { RemoteFile, Host } from '../types'; import { Folder, FileText, Download, Upload, ArrowUp, RefreshCw, HardDrive, Trash2, File, Loader2, Plus } from 'lucide-react'; import { Button } from './ui/button'; import { cn } from '../lib/utils'; import { Input } from './ui/input'; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from './ui/context-menu'; interface SFTPPanelProps { host: Host; credentials: { username: string; hostname: string; port?: number; password?: string; privateKey?: string; }; isVisible: boolean; onClose: () => void; } const SFTPPanel: React.FC = ({ host, credentials, isVisible, onClose }) => { const [currentPath, setCurrentPath] = useState('/'); const [files, setFiles] = useState([]); const [loading, setLoading] = useState(false); const [dragActive, setDragActive] = useState(false); const [error, setError] = useState(null); const inputRef = useRef(null); const sftpIdRef = useRef(null); const initializedRef = useRef(false); const ensureSftp = async () => { if (sftpIdRef.current) return sftpIdRef.current; if (!window.nebula?.openSftp) throw new Error("SFTP bridge unavailable"); const sftpId = await window.nebula.openSftp({ sessionId: `sftp-${host.id}`, ...credentials, }); sftpIdRef.current = sftpId; return sftpId; }; const loadFiles = async (path: string) => { try { setError(null); const sftpId = await ensureSftp(); setLoading(true); const list = await window.nebula.listSftp(sftpId, path); setFiles(list); } catch (e) { console.error("Failed to load files", e); setError(e instanceof Error ? e.message : 'Failed to load directory'); setFiles([]); } finally { setLoading(false); } }; const closeSftp = async () => { if (sftpIdRef.current && window.nebula?.closeSftp) { try { await window.nebula.closeSftp(sftpIdRef.current); } catch {} } sftpIdRef.current = null; }; useEffect(() => { return () => { closeSftp(); }; }, []); const handleNavigate = (path: string) => { setCurrentPath(path); }; useEffect(() => { if (isVisible) { if (!initializedRef.current) { initializedRef.current = true; setCurrentPath('/'); } loadFiles(currentPath); } else { closeSftp(); } }, [isVisible, currentPath]); const handleUp = () => { if (currentPath === '/') return; const parent = currentPath.split('/').slice(0, -1).join('/') || '/'; setCurrentPath(parent); }; const handleDownload = async (file: RemoteFile) => { try { const sftpId = await ensureSftp(); const fullPath = currentPath === '/' ? `/${file.name}` : `${currentPath}/${file.name}`; setLoading(true); const content = await window.nebula.readSftp(sftpId, fullPath); const blob = new Blob([content], { type: 'text/plain' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = file.name; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } finally { setLoading(false); } }; const handleUpload = async (file: File) => { const sftpId = await ensureSftp(); setLoading(true); try { const reader = new FileReader(); reader.onload = async (e) => { const content = e.target?.result as string; const fullPath = currentPath === '/' ? `/${file.name}` : `${currentPath}/${file.name}`; await window.nebula.writeSftp(sftpId, fullPath, content); await loadFiles(currentPath); }; reader.readAsText(file); } finally { setLoading(false); } }; const handleClose = async () => { await closeSftp(); onClose(); }; const handleCreateFolder = async () => { try { const folderName = prompt("New folder name?"); if (!folderName) return; const sftpId = await ensureSftp(); const fullPath = currentPath === '/' ? `/${folderName}` : `${currentPath}/${folderName}`; await window.nebula.mkdirSftp(sftpId, fullPath); await loadFiles(currentPath); } catch (e) { setError(e instanceof Error ? e.message : 'Failed to create folder'); } }; const handleFileSelect = (e: React.ChangeEvent) => { if (e.target.files && e.target.files[0]) { handleUpload(e.target.files[0]); } }; // Drag and Drop const handleDrag = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); if (e.type === "dragenter" || e.type === "dragover") { setDragActive(true); } else if (e.type === "dragleave") { setDragActive(false); } }; const handleDrop = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setDragActive(false); if (e.dataTransfer.files && e.dataTransfer.files[0]) { handleUpload(e.dataTransfer.files[0]); } }; return (
{/* Header */}
SFTP
{/* Toolbar & Breadcrumbs */}
setCurrentPath(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && loadFiles(currentPath)} className="h-7 text-xs font-mono bg-background" />
{error &&
{error}
}
{/* File List */}
{dragActive && (
Drop to upload
)}
{loading && (
)} {files.length === 0 && !loading && (
Empty Directory
)} {!loading && files.map((file, idx) => (
file.type === 'directory' && handleNavigate(currentPath === '/' ? `/${file.name}` : `${currentPath}/${file.name}`)} >
{file.type === 'directory' ? : }
{file.name}
{file.size} • {file.lastModified}
{file.type === 'file' && ( )}
{file.type === 'directory' && ( handleNavigate(currentPath === '/' ? `/${file.name}` : `${currentPath}/${file.name}`)}> Open )} {file.type === 'file' && ( handleDownload(file)}> Download )}
))}
New folder
{/* Footer Status */}
{files.length} items {loading ? "Syncing..." : "Ready"}
); }; export default SFTPPanel;