// PodFileBrowser.tsx — Pod 容器文件浏览器组件 // 作者: Logan import { useState, useEffect, useCallback, useRef } from 'react'; import { kubernetesApi } from '@/services/api'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Input } from '@/components/ui/input'; import { Loader2, X, Folder, File, ChevronRight, ChevronDown, Download, Upload, RefreshCw, ArrowLeft, HardDrive, } from 'lucide-react'; export interface PodFileBrowserProps { open: boolean; onOpenChange: (open: boolean) => void; clusterCode: string; namespace: string; podName: string; containers?: string[]; initialContainer?: string; } interface FileEntry { name: string; isDir: boolean; size?: number; modTime?: string; } export function PodFileBrowser({ open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer, }: PodFileBrowserProps) { const [container, setContainer] = useState(initialContainer || containers[0] || ''); const [currentPath, setCurrentPath] = useState('/'); const [entries, setEntries] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const [preview, setPreview] = useState<{ file: string; content: string } | null>(null); const [uploading, setUploading] = useState(false); const fileInputRef = useRef(null); const loadFiles = useCallback(async (path: string) => { setLoading(true); setError(''); setPreview(null); try { const res: any = await kubernetesApi.listPodFiles(clusterCode, namespace, podName, path, container || undefined); // 兼容后端 {files: [...]} 和 {entries: [...]} 两种返回格式 const raw: any[] = res?.entries || res?.files || res?.data?.entries || res?.data?.files || (Array.isArray(res) ? res : []); const list: FileEntry[] = raw.map((it: any) => ({ name: it.name ?? it.Name ?? '', isDir: Boolean(it.isDir ?? it.is_dir ?? it.IsDir ?? it.dir ?? it.directory), size: typeof it.size === 'number' ? it.size : (it.Size ? Number(it.Size) : undefined), modTime: it.modTime ?? it.mod_time ?? it.ModTime ?? it.mtime ?? it.modified, })).filter(e => e.name && e.name !== '.'); setEntries(list); setCurrentPath(path); } catch (e: any) { setError(e.message || '加载文件列表失败'); setEntries([]); } finally { setLoading(false); } }, [clusterCode, namespace, podName, container]); useEffect(() => { if (open) loadFiles('/'); }, [open, loadFiles]); const handleClick = (entry: FileEntry) => { if (entry.isDir) { const newPath = currentPath === '/' ? `/${entry.name}` : `${currentPath}/${entry.name}`; loadFiles(newPath); } else { handlePreview(entry.name); } }; const handlePreview = async (fileName: string) => { const filePath = currentPath === '/' ? `/${fileName}` : `${currentPath}/${fileName}`; try { const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined); setPreview({ file: fileName, content: text }); } catch (e: any) { setPreview({ file: fileName, content: `读取失败: ${e.message}` }); } }; const handleDownload = (fileName: string) => { const filePath = currentPath === '/' ? `/${fileName}` : `${currentPath}/${fileName}`; const url = kubernetesApi.buildPodFileDownloadUrl(clusterCode, namespace, podName, filePath, container || undefined); window.open(url, '_blank'); }; const handleUpload = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; setUploading(true); try { await kubernetesApi.uploadPodFile(clusterCode, namespace, podName, currentPath, file, container || undefined); loadFiles(currentPath); } catch (err: any) { setError(`上传失败: ${err.message}`); } finally { setUploading(false); if (fileInputRef.current) fileInputRef.current.value = ''; } }; const handleGoUp = () => { if (currentPath === '/') return; const parts = currentPath.split('/').filter(Boolean); parts.pop(); loadFiles(parts.length === 0 ? '/' : `/${parts.join('/')}`); }; const formatSize = (bytes?: number) => { if (bytes == null) return '-'; if (bytes < 1024) return `${bytes} B`; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`; }; const pathSegments = currentPath.split('/').filter(Boolean); if (!open) return null; return (
onOpenChange(false)}>
e.stopPropagation()} > {/* Header */}
文件浏览器: {podName} {namespace}
{containers.length > 0 && ( )}
{/* Breadcrumb + Actions */}
{pathSegments.map((seg, i) => { const path = `/${pathSegments.slice(0, i + 1).join('/')}`; return ( ); })}
{/* Content */}
{/* File list */}
{error &&

{error}

} {loading ? (
) : entries.length === 0 ? (

空目录

) : (
{entries.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1)).map((entry) => (
handleClick(entry)} > {entry.isDir ? ( ) : ( )} {entry.name} {!entry.isDir && ( {formatSize(entry.size)} )} {!entry.isDir && ( )}
))}
)}
{/* Preview */} {preview && (
{preview.file}
                  {preview.content || '(空文件)'}
                
)}
); }