- 新增 PageShell/PageTabs/ContentPanel/PageLoading/PageEmpty 页面骨架 - index.css 设计令牌文档化,布局令牌与纯色主按钮(去除渐变粉彩) - 全站路由页接入 PageShell,云账单三 Tab 为标杆 - 主题体系:跟随系统 + 主流/开发者分组,新增 Dracula/Tokyo Night,One Dark 暖灰差异化 - 登录页/侧栏/顶栏去渐变光球,企业克制风 - 修复 AIAlertAnalyzer JSX 与构建依赖导入问题
284 lines
12 KiB
TypeScript
284 lines
12 KiB
TypeScript
// PodFileBrowser.tsx — Pod 容器文件浏览器组件
|
|
// 作者: Logan <admin@attacker.club>
|
|
import { useState, useEffect, useCallback, useRef } from 'react';
|
|
import { kubernetesApi } from '@/api';
|
|
import { Button } from '@/components/ui/button';
|
|
import { Badge } from '@/components/ui/badge';
|
|
import {
|
|
|
|
Loader2,
|
|
X,
|
|
Folder,
|
|
File,
|
|
ChevronRight,
|
|
Download,
|
|
Upload,
|
|
RefreshCw,
|
|
ArrowLeft,
|
|
HardDrive,
|
|
} from 'lucide-react';
|
|
import type { JsonData } from '@/types/common';
|
|
|
|
|
|
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<FileEntry[]>([]);
|
|
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<HTMLInputElement>(null);
|
|
const workdirDetected = useRef(false);
|
|
|
|
const loadFiles = useCallback(async (path: string) => {
|
|
setLoading(true);
|
|
setError('');
|
|
setPreview(null);
|
|
try {
|
|
const res: JsonData = await kubernetesApi.listPodFiles(clusterCode, namespace, podName, path, container || undefined);
|
|
// 兼容后端 {files: [...]} 和 {entries: [...]} 两种返回格式
|
|
const raw: JsonData[] = res?.entries || res?.files || res?.data?.entries || res?.data?.files || (Array.isArray(res) ? res : []);
|
|
const list: FileEntry[] = raw.map((it: JsonData) => ({
|
|
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) {
|
|
setError((e as JsonData).message || '加载文件列表失败');
|
|
setEntries([]);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, [clusterCode, namespace, podName, container]);
|
|
|
|
useEffect(() => {
|
|
if (open) {
|
|
// 检测容器 WORKDIR 作为初始路径(执行 pwd 命令)
|
|
const detectWorkdir = async () => {
|
|
if (workdirDetected.current) {
|
|
loadFiles(currentPath);
|
|
return;
|
|
}
|
|
setLoading(true);
|
|
try {
|
|
const res: JsonData = await kubernetesApi.execPod(clusterCode, namespace, podName, ['pwd'], container || undefined);
|
|
const stdout = (res?.stdout || res?.data?.stdout || '').trim();
|
|
const workdir = stdout && stdout.startsWith('/') ? stdout : '/';
|
|
workdirDetected.current = true;
|
|
setCurrentPath(workdir);
|
|
loadFiles(workdir);
|
|
} catch {
|
|
// pwd 失败则默认 /
|
|
workdirDetected.current = true;
|
|
loadFiles('/');
|
|
}
|
|
};
|
|
detectWorkdir();
|
|
} else {
|
|
workdirDetected.current = false;
|
|
}
|
|
}, [open, container]);
|
|
|
|
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) {
|
|
setPreview({ file: fileName, content: `读取失败: ${(e as JsonData).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<HTMLInputElement>) => {
|
|
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) {
|
|
setError(`上传失败: ${(err as JsonData).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 (
|
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70" onClick={() => onOpenChange(false)}>
|
|
<div
|
|
className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-xl w-[90vw] max-w-5xl h-[80vh] flex flex-col shadow-2xl"
|
|
onClick={(e) => e.stopPropagation()}
|
|
>
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between p-3 border-b border-[var(--dg-border)] shrink-0 gap-3">
|
|
<div className="flex items-center gap-2 min-w-0 flex-1">
|
|
<HardDrive className="h-4 w-4 shrink-0 dg-text-yellow" />
|
|
<span className="text-sm font-semibold text-[var(--dg-text-primary)] truncate" title={podName}>文件: {podName}</span>
|
|
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary text-[10px] shrink-0">{namespace}</Badge>
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
{containers.length > 0 && (
|
|
<select
|
|
value={container}
|
|
onChange={(e) => { setContainer(e.target.value); }}
|
|
className="bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-2 py-1"
|
|
>
|
|
{containers.map((c) => <option key={c} value={c}>{c}</option>)}
|
|
</select>
|
|
)}
|
|
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary" onClick={() => onOpenChange(false)}>
|
|
<X className="h-4 w-4" />
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Breadcrumb + Actions */}
|
|
<div className="flex items-center justify-between p-2 border-b border-[var(--dg-border)] shrink-0">
|
|
<div className="flex items-center gap-1 text-xs dg-text-secondary">
|
|
<Button variant="ghost" size="icon" className="h-6 w-6 dg-text-muted" onClick={handleGoUp} disabled={currentPath === '/'}>
|
|
<ArrowLeft className="h-3.5 w-3.5" />
|
|
</Button>
|
|
<button className="hover:text-[var(--dg-text-primary)]" onClick={() => loadFiles('/')}>root</button>
|
|
{pathSegments.map((seg, i) => {
|
|
const path = `/${pathSegments.slice(0, i + 1).join('/')}`;
|
|
return (
|
|
<span key={path} className="flex items-center gap-1">
|
|
<ChevronRight className="h-3 w-3" />
|
|
<button className="hover:text-[var(--dg-text-primary)]" onClick={() => loadFiles(path)}>{seg}</button>
|
|
</span>
|
|
);
|
|
})}
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<input type="file" ref={fileInputRef} className="hidden" onChange={handleUpload} />
|
|
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={() => fileInputRef.current?.click()} disabled={uploading}>
|
|
{uploading ? <Loader2 className="h-3 w-3 animate-spin mr-1" /> : <Upload className="h-3 w-3 mr-1" />}上传
|
|
</Button>
|
|
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={() => loadFiles(currentPath)} disabled={loading}>
|
|
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Content */}
|
|
<div className="flex-1 overflow-hidden flex">
|
|
{/* File list */}
|
|
<div className={`${preview ? 'w-1/2' : 'w-full'} overflow-auto p-2 border-r border-[var(--dg-border)]`}>
|
|
{error && <p className="text-xs dg-text-red p-2">{error}</p>}
|
|
{loading ? (
|
|
<div className="flex items-center justify-center h-32"><Loader2 className="h-5 w-5 animate-spin dg-text-muted" /></div>
|
|
) : entries.length === 0 ? (
|
|
<p className="text-xs dg-text-muted p-4 text-center">空目录</p>
|
|
) : (
|
|
<div className="space-y-0.5">
|
|
{entries.sort((a, b) => (a.isDir === b.isDir ? a.name.localeCompare(b.name) : a.isDir ? -1 : 1)).map((entry) => (
|
|
<div
|
|
key={entry.name}
|
|
className="flex items-center gap-2 px-2 py-1.5 rounded hover:bg-[var(--dg-bg-hover)] cursor-pointer group"
|
|
onClick={() => handleClick(entry)}
|
|
>
|
|
{entry.isDir ? (
|
|
<Folder className="h-4 w-4 dg-text-blue shrink-0" />
|
|
) : (
|
|
<File className="h-4 w-4 dg-text-muted shrink-0" />
|
|
)}
|
|
<span className={`text-xs truncate ${entry.isDir ? 'text-blue-300' : 'text-[var(--dg-text-secondary)]'}`}>
|
|
{entry.name}
|
|
</span>
|
|
{!entry.isDir && (
|
|
<span className="text-[10px] dg-text-muted ml-auto shrink-0">{formatSize(entry.size)}</span>
|
|
)}
|
|
{!entry.isDir && (
|
|
<Button
|
|
variant="ghost" size="icon" className="h-5 w-5 opacity-0 group-hover:opacity-100 dg-text-secondary hover:dg-text-green shrink-0"
|
|
onClick={(e) => { e.stopPropagation(); handleDownload(entry.name); }}
|
|
title="下载"
|
|
>
|
|
<Download className="h-3 w-3" />
|
|
</Button>
|
|
)}
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{/* Preview */}
|
|
{preview && (
|
|
<div className="w-1/2 flex flex-col overflow-hidden">
|
|
<div className="flex items-center justify-between p-2 border-b border-[var(--dg-border)] shrink-0">
|
|
<span className="text-xs text-[var(--dg-text-secondary)] font-mono">{preview.file}</span>
|
|
<Button variant="ghost" size="icon" className="h-6 w-6 dg-text-secondary" onClick={() => setPreview(null)}>
|
|
<X className="h-3.5 w-3.5" />
|
|
</Button>
|
|
</div>
|
|
<div className="flex-1 overflow-auto p-3">
|
|
<pre className="text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap break-all bg-[var(--dg-bg-primary)] rounded p-3">
|
|
{preview.content || '(空文件)'}
|
|
</pre>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|