fix(i18n): 回退到稳定的 32% 覆盖率状态 (tsc + Vite 构建通过)

批量转换脚本引入的语法错误已回退,保留稳定的 i18n 转换:
- 翻译词典: 22 namespaces, 3600+ keys
- 已接入: 145+ 文件 (Dashboard/Login/K8s 主页面/Monitor/System/Deploy)
- 语言切换器在 Header 中可用 (🇨🇳/🇺🇸)
- tsc 零错误, Vite 构建成功
This commit is contained in:
attacker committed 2026-07-03 02:02:29 +08:00
1 parent ecec73989b
commit 72bfb0e12d
191 files changed
+5057 -7592

No files matched your search

@@ -13,10 +13,8 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function CapacityPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -78,8 +76,8 @@ export default function CapacityPage() {
return (
<PageShell
variant="list"
title=t('kubernetes.capacitypage.s4e67a9')
subtitle={clusterName ? t('kubernetes.capacitypage.sd54408', { clusterName: clusterName }) : t('kubernetes.capacitypage.s6a1128')}
title="资源容量分析"
subtitle={clusterName ? `${clusterName} · Deployment 资源请求与限制` : 'Deployment 资源请求与限制'}
icon={<BarChart3 className="h-5 w-5" />}
actions={(
<>
@@ -90,9 +88,9 @@ export default function CapacityPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={setSelectedNs}>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue placeholder=t('kubernetes.capacitypage.s58173b') /></SelectTrigger>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue placeholder="所有命名空间" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('kubernetes.capacitypage.s58173b')}</SelectItem>
<SelectItem value="all">所有命名空间</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
@@ -111,9 +109,9 @@ export default function CapacityPage() {
<Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Deployment</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.capacitypage.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.containers')}</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">副本</TableHead>
<TableHead className="dg-text-secondary">容器</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU Req</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU Lim</TableHead>
<TableHead className="dg-text-secondary"><HardDrive className="h-3 w-3 inline mr-1" />Mem Req</TableHead>
@@ -26,12 +26,10 @@ import {
import { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const CHART_COLORS = ['#3B82F6', '#207060', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899', '#14B8A6', '#F97316'];
export default function ClusterComparePage() {
const { t } = useTranslation();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
const [data, setData] = useState<JsonData>(null);
@@ -44,7 +42,7 @@ export default function ClusterComparePage() {
const res: JsonData = await kubernetesApi.getMultiClusterComparison();
setData(res || null);
} catch (e) {
setError(e?.message || t('common.loadFailed'));
setError(e?.message || '加载失败');
setData(null);
} finally {
setLoading(false);
@@ -68,16 +66,16 @@ export default function ClusterComparePage() {
const usageBarData = clusters.map((c: JsonData) => ({
name: c.code || c.name,
'CPU %': Number((c.cpu_usage || 0).toFixed(1)),
t('kubernetes.clustercomparepage.sbe9d77'): Number((c.memory_usage || 0).toFixed(1)),
'内存 %': Number((c.memory_usage || 0).toFixed(1)),
}));
const radarData = clusters.length > 0 ? [
{ metric: t('kubernetes.cluster.nodeCount'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.node_count || 0])) },
{ metric: t('kubernetes.clustercomparepage.s5fe4af'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Math.min(c.pod_count || 0, 100)])) },
{ metric: t('kubernetes.clustercomparepage.s7d207a'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.deployment_count || 0])) },
{ metric: t('kubernetes.clustercomparepage.s020267'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.cpu_usage || 0).toFixed(1))])) },
{ metric: t('kubernetes.clustercomparepage.s5d9ce3'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.memory_usage || 0).toFixed(1))])) },
{ metric: t('kubernetes.clustercomparepage.sbdb608'), ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.total_cpu_cores || 0])) },
{ metric: '节点数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.node_count || 0])) },
{ metric: 'Pod数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Math.min(c.pod_count || 0, 100)])) },
{ metric: '部署数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.deployment_count || 0])) },
{ metric: 'CPU使用', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.cpu_usage || 0).toFixed(1))])) },
{ metric: '内存使用', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, Number((c.memory_usage || 0).toFixed(1))])) },
{ metric: 'CPU核数', ...Object.fromEntries(clusters.map((c: JsonData) => [c.code || c.name, c.total_cpu_cores || 0])) },
] : [];
const nodeRolePie = clusters.flatMap((c: JsonData) => [
@@ -99,7 +97,7 @@ export default function ClusterComparePage() {
// 格式化同步时间
const fmtTime = (t: string | null | undefined) => {
if (!t) return t('kubernetes.clustercomparepage.s910982');
if (!t) return '从未同步';
try {
const d = new Date(t);
return d.toLocaleString('zh-CN', { hour12: false });
@@ -113,8 +111,8 @@ export default function ClusterComparePage() {
<div className="flex items-center gap-3">
<Layers className="h-5 w-5 dg-text-blue" />
<div>
<h1 className="text-lg font-semibold">{t('kubernetes.clustercomparepage.s5a25a6')}</h1>
<p className="text-xs dg-text-muted">{t('kubernetes.clustercomparepage.s9807a2')}</p>
<h1 className="text-lg font-semibold">多集群资源对比看板</h1>
<p className="text-xs dg-text-muted">跨集群资源用量、节点分布、健康状态对比</p>
</div>
</div>
<div className="flex items-center gap-2">
@@ -141,8 +139,8 @@ export default function ClusterComparePage() {
{/* 概览卡片 */}
<StatStrip
items={[
{ label: t('kubernetes.clustercomparepage.s85fe50'), value: totals.cluster_count || 0, color: 'blue' },
{ label: t('k8s.tab.nodes'), value: totals.node_count || 0, color: 'emerald' },
{ label: '集群', value: totals.cluster_count || 0, color: 'blue' },
{ label: '节点', value: totals.node_count || 0, color: 'emerald' },
{ label: 'Pod', value: totals.pod_count || 0, color: 'purple' },
{ label: 'Deploy', value: totals.deployment_count || 0, color: 'amber' },
{ label: 'Service', value: totals.service_count || 0, color: 'cyan' },
@@ -153,7 +151,7 @@ export default function ClusterComparePage() {
<Card className="bg-[var(--dg-bg-secondary)]/60 border-[var(--dg-border)]">
<CardContent className="py-12 text-center">
<Cloud className="h-12 w-12 dg-text-muted mx-auto mb-3" />
<p className="dg-text-muted">{t('kubernetes.clustercomparepage.s4f921c')}</p>
<p className="dg-text-muted">暂无集群数据,请先添加 Kubernetes 集群并同步</p>
<Link to="/kubernetes" className="inline-block mt-3">
<Button variant="outline" size="sm" className="border-[var(--dg-border)]">
去添加集群 <ChevronRight className="h-3.5 w-3.5 ml-1" />
@@ -171,7 +169,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Layers className="h-4 w-4 dg-text-blue" />
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.se37201')}</h3>
<h3 className="text-sm font-semibold">资源数量对比</h3>
</div>
<ResponsiveContainer width="100%" height={280}>
<BarChart data={resourceBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}>
@@ -180,7 +178,7 @@ export default function ClusterComparePage() {
<YAxis tick={{ fill: '#94a3b8', fontSize: 11 }} />
<Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey=t('k8s.tab.nodes') fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey="节点" fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Pod" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Deployment" fill={CHART_COLORS[2]} radius={[3, 3, 0, 0]} />
<Bar dataKey="Service" fill={CHART_COLORS[5]} radius={[3, 3, 0, 0]} />
@@ -193,7 +191,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Activity className="h-4 w-4 dg-text-green" />
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.s8af9cf')}</h3>
<h3 className="text-sm font-semibold">CPU / 内存使用率对比</h3>
</div>
<ResponsiveContainer width="100%" height={280}>
<BarChart data={usageBarData} margin={{ top: 5, right: 10, left: -15, bottom: 5 }}>
@@ -203,7 +201,7 @@ export default function ClusterComparePage() {
<Tooltip contentStyle={{ background: '#0f172a', border: '1px solid #334155', borderRadius: 8, fontSize: 12 }} />
<Legend wrapperStyle={{ fontSize: 11 }} />
<Bar dataKey="CPU %" fill={CHART_COLORS[0]} radius={[3, 3, 0, 0]} />
<Bar dataKey=t('kubernetes.clustercomparepage.sbe9d77') fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
<Bar dataKey="内存 %" fill={CHART_COLORS[1]} radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
@@ -217,7 +215,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<TrendingUp className="h-4 w-4 dg-text-purple" />
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.sc7d7a7')}</h3>
<h3 className="text-sm font-semibold">资源雷达对比</h3>
</div>
<ResponsiveContainer width="100%" height={320}>
<RadarChart data={radarData}>
@@ -244,7 +242,7 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Server className="h-4 w-4 dg-text-yellow" />
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.sefdd7a')}</h3>
<h3 className="text-sm font-semibold">节点角色分布</h3>
</div>
{nodeRolePie.length > 0 ? (
<ResponsiveContainer width="100%" height={320}>
@@ -262,7 +260,7 @@ export default function ClusterComparePage() {
</PieChart>
</ResponsiveContainer>
) : (
<div className="h-[320px] flex items-center justify-center dg-text-muted text-sm">{t('kubernetes.clustercomparepage.s394f38')}</div>
<div className="h-[320px] flex items-center justify-center dg-text-muted text-sm">无节点角色数据</div>
)}
</CardContent>
</Card>
@@ -274,25 +272,25 @@ export default function ClusterComparePage() {
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<HardDrive className="h-4 w-4 dg-text-cyan" />
<h3 className="text-sm font-semibold">{t('kubernetes.clustercomparepage.s3e920c')}</h3>
<span className="text-xs dg-text-muted ml-2">{t('kubernetes.clustercomparepage.sbcb4f0')}</span>
<h3 className="text-sm font-semibold">详细对比</h3>
<span className="text-xs dg-text-muted ml-2">点击行可进入集群概览</span>
</div>
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">{t('kubernetes.clustercomparepage.s85fe50')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('k8s.tab.nodes')}</TableHead>
<TableHead className="dg-text-secondary">集群</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead>
<TableHead className="dg-text-secondary text-right">节点</TableHead>
<TableHead className="dg-text-secondary text-right">Pod</TableHead>
<TableHead className="dg-text-secondary text-right">Deployment</TableHead>
<TableHead className="dg-text-secondary text-right">Service</TableHead>
<TableHead className="dg-text-secondary text-right">{t('kubernetes.clustercomparepage.s2e32ab')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('monitor.hostCpu')}</TableHead>
<TableHead className="dg-text-secondary text-right">{t('monitor.hostMemory')}</TableHead>
<TableHead className="dg-text-secondary">{t('pipeline.role')}</TableHead>
<TableHead className="dg-text-secondary">{t('cloud.syncTime')}</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 核数</TableHead>
<TableHead className="dg-text-secondary text-right">内存</TableHead>
<TableHead className="dg-text-secondary text-right">CPU 使用率</TableHead>
<TableHead className="dg-text-secondary text-right">内存使用率</TableHead>
<TableHead className="dg-text-secondary">角色</TableHead>
<TableHead className="dg-text-secondary">同步时间</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -307,7 +305,7 @@ export default function ClusterComparePage() {
</TableCell>
<TableCell>
<Badge variant="outline" className={`text-xs ${statusColorMap[c.status] || statusColorMap.error}`}>
{c.status === 'healthy' ? t('kubernetes.clustercomparepage.s33108c') : c.status === 'warning' ? t('kubernetes.clustercomparepage.s5ddbdd') : t('kubernetes.clustercomparepage.sc94103')}
{c.status === 'healthy' ? '✓ 健康' : c.status === 'warning' ? '⚠ 警告' : '✗ 异常'}
</Badge>
</TableCell>
<TableCell className="text-right font-mono text-[var(--dg-text-secondary)]">{c.node_count}</TableCell>
@@ -25,7 +25,6 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>>> = {
'kube-system': Server,
@@ -35,7 +34,6 @@ const NAMESPACE_ICON: Record<string, React.ComponentType<Record<string, unknown>
};
export default function ClusterOverviewPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const { toast } = useToast();
@@ -55,7 +53,7 @@ export default function ClusterOverviewPage() {
const current = list.find((c: JsonData) => (c.code || String(c.id)) === clusterCode);
setClusterInfo(current || null);
if (!current && list.length > 0 && clusterCode) {
toast({ title: t('kubernetes.clusteroverviewpage.s9ff765'), description: t('kubernetes.clusteroverviewpage.s59f69c', { clusterCode: clusterCode }), variant: 'destructive' });
toast({ title: '集群未找到', description: `找不到集群 ${clusterCode}`, variant: 'destructive' });
}
} catch { setClusters([]); }
}, [clusterCode]);
@@ -85,15 +83,15 @@ export default function ClusterOverviewPage() {
return (
<PageShell
variant="default"
title={clusterCode || t('kubernetes.clusteroverviewpage.s066c0a')}
subtitle={clusterInfo?.version ? t('kubernetes.clusteroverviewpage.s966b2d', { clusterInfo.version: clusterInfo.version }) : t('kubernetes.clusteroverviewpage.s066c0a')}
title={clusterCode || '集群概览'}
subtitle={clusterInfo?.version ? `集群概览 · Kubernetes ${clusterInfo.version}` : '集群概览'}
icon={<Server className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: t('k8s.tab.nodes'), value: nodes.length, color: 'blue' },
{ label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: t('common.version'), value: clusterInfo?.version || '-', color: 'muted' },
{ label: '节点', value: nodes.length, color: 'blue' },
{ label: '命名空间', value: namespaces.length, color: 'green' },
{ label: '版本', value: clusterInfo?.version || '-', color: 'muted' },
]}
/>
) : undefined}
@@ -113,21 +111,21 @@ export default function ClusterOverviewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('pipeline.role')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">角色</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">OS</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">CPU</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.pods.memory')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">内存</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
) : nodes.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Cpu className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.topology.noNodes')}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Cpu className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无节点</TableCell></TableRow>
) : (
nodes.map((n: JsonData) => {
const cpuCores = n.cpu || 0;
@@ -16,10 +16,8 @@ import { DeploymentHpaTab } from './deployment-detail/DeploymentHpaTab';
import { DeploymentPodModals } from './deployment-detail/DeploymentPodModals';
import { YamlViewer } from './YamlViewer';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBack }: DeploymentDetailProps) {
const { t } = useTranslation();
const { toast } = useToast();
const confirm = useConfirm();
const [deployment, setDeployment] = useState<JsonData>(null);
@@ -62,7 +60,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setPods(allPods.filter((p: JsonData) => p.namespace === namespace && p.name.startsWith(deploymentName)));
setHpas(allHpas.filter((h: JsonData) => h.target_name === deploymentName && h.namespace === namespace));
} catch (e) {
console.error(t('kubernetes.deploymentdetail.sb46ea9'), e);
console.error('加载详情失败:', e);
} finally {
setLoading(false);
}
@@ -76,10 +74,10 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas);
toast({ title: t('kubernetes.deploymentdetail.s0b3ea1'), description: t('kubernetes.deploymentdetail.sacbcbd', { newReplicas: newReplicas }) });
toast({ title: '扩缩容成功', description: `副本数已设置为 ${newReplicas}` });
loadData();
} catch (e) {
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -87,9 +85,9 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('restart');
try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: t('kubernetes.deploymentdetail.s68a700'), description: t('kubernetes.deploymentdetail.sd18761') });
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' });
} catch (e) {
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -98,28 +96,28 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
setActionLoading('image');
try {
await kubernetesApi.updateDeploymentImage(clusterCode, namespace, deploymentName, newImage);
toast({ title: t('kubernetes.deploymentdetail.s6df3c3'), description: t('kubernetes.deploymentdetail.sa982c3', { newImage: newImage }) });
toast({ title: '镜像更新成功', description: `正在滚动更新为 ${newImage}` });
setShowImageUpdate(false);
loadData();
} catch (e) {
toast({ title: t('alert.updateFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '更新失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleHpaToggle = async (hpa: JsonData) => {
const ok = await confirm({
title: t('kubernetes.hpa.deleteHpa'),
description: t('kubernetes.deploymentdetail.s209f7e', { hpa.name: hpa.name }),
confirmText: t('common.delete'),
title: '删除 HPA',
description: `确定删除 HPA "${hpa.name}"?`,
confirmText: '删除',
variant: 'destructive',
});
if (!ok) return;
try {
await kubernetesApi.deleteHPA(clusterCode, namespace, hpa.name);
toast({ title: t('kubernetes.deploymentdetail.s0f958f') });
toast({ title: 'HPA 已删除' });
loadData();
} catch (e) {
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -128,7 +126,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3">{t('common.loading')}</p>
<p className="dg-text-muted mt-3">加载中...</p>
</CardContent>
</Card>
);
@@ -140,7 +138,7 @@ export function DeploymentDetail({ clusterCode, namespace, deploymentName, onBac
<CardContent className="p-12 text-center">
<XCircle className="h-8 w-8 mx-auto dg-text-red" />
<p className="dg-text-secondary mt-3">未找到 Deployment: {deploymentName}</p>
<Button variant="outline" className="mt-4" onClick={onBack}>{t('common.back')}</Button>
<Button variant="outline" className="mt-4" onClick={onBack}>返回</Button>
</CardContent>
</Card>
);
@@ -15,7 +15,6 @@ import { saveDeploymentManifest } from './deployment-manifest-save';
import { SchedulingSection, type ScheduleMode } from './deployment-edit-advanced/SchedulingSection';
import { DnsHostSection } from './deployment-edit-advanced/DnsHostSection';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface Props {
clusterCode: string;
@@ -35,7 +34,6 @@ interface Toleration {
}
export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -313,10 +311,10 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
else delete podSpec.dnsConfig;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: t('kubernetes.deploymenteditadvanced.s9762d0'), description: t('kubernetes.deploymenteditadvanced.s1952a7', { deploymentName: deploymentName }) });
toast({ title: '高级设置已保存', description: `${deploymentName} 更新已提交` });
onSaved(base);
} catch (e) {
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -325,7 +323,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
@@ -366,12 +364,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
{strategyType === 'RollingUpdate' && (
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s282929')}</Label>
<Label className="dg-text-muted text-xs">maxSurge(整数或百分比,超出期望副本数)</Label>
<Input value={maxSurge} onChange={e => setMaxSurge(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s7754b7')}</Label>
<Label className="dg-text-muted text-xs">maxUnavailable(整数或百分比,不可用上限)</Label>
<Input value={maxUnavailable} onChange={e => setMaxUnavailable(e.target.value)}
placeholder="25%" className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
@@ -389,12 +387,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.s0d8e53')}</Label>
<Label className="dg-text-muted text-xs">revisionHistoryLimit(保留 RS 历史)</Label>
<Input type="number" value={revisionHistoryLimit} onChange={e => setRevisionHistoryLimit(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.deploymenteditadvanced.scd3a9b')}</Label>
<Label className="dg-text-muted text-xs">progressDeadlineSeconds(升级超时秒数)</Label>
<Input type="number" value={progressDeadlineSeconds} onChange={e => setProgressDeadlineSeconds(e.target.value)}
className="h-8 mt-1 dg-input text-sm font-mono" />
</div>
@@ -405,7 +403,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-sm text-[var(--dg-text-primary)]">{t('kubernetes.deploymenteditadvanced.s13a831')}</CardTitle>
<CardTitle className="text-sm text-[var(--dg-text-primary)]">容忍 (Tolerations)</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs"
onClick={() => setTolerations(prev => [...prev, { key: '', operator: 'Equal', value: '', effect: 'NoSchedule', tolerationSeconds: '' }])}>
<Plus className="h-3 w-3 mr-1" />添加
@@ -413,7 +411,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
</div>
</CardHeader>
<CardContent className="pt-0 space-y-2">
{tolerations.length === 0 && <p className="text-xs dg-text-muted">{t('kubernetes.deploymenteditadvanced.s8bc06b')}</p>}
{tolerations.length === 0 && <p className="text-xs dg-text-muted">未配置容忍</p>}
{tolerations.map((t, i) => (
<div key={i} className="grid grid-cols-[1fr_80px_1fr_100px_80px_auto] gap-2 items-center">
<Input value={t.key} placeholder="key" onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, key: e.target.value } : x))}
@@ -428,12 +426,12 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
className="h-7 dg-input text-xs font-mono" />
<select value={t.effect} onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, effect: e.target.value } : x))}
className="h-7 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1">
<option value="">{t('kubernetes.deploymenteditadvanced.s2a6eb2')}</option>
<option value="">任意</option>
<option value="NoSchedule">NoSchedule</option>
<option value="PreferNoSchedule">PreferNoSchedule</option>
<option value="NoExecute">NoExecute</option>
</select>
<Input value={t.tolerationSeconds} placeholder=t('common.second') disabled={t.effect !== 'NoExecute'}
<Input value={t.tolerationSeconds} placeholder="秒" disabled={t.effect !== 'NoExecute'}
onChange={e => setTolerations(prev => prev.map((x, idx) => idx === i ? { ...x, tolerationSeconds: e.target.value } : x))}
className="h-7 dg-input text-xs font-mono" />
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red" onClick={() => setTolerations(prev => prev.filter((_, idx) => idx !== i))}>
@@ -580,7 +578,7 @@ export function DeploymentEditAdvanced({ clusterCode, namespace, deploymentName,
{/* 操作栏 */}
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存
@@ -10,7 +10,6 @@ import { Badge } from '@/components/ui/badge';
import { Plus, Trash2, Save, Loader2, Tags, FileText, Hash, Lock } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { saveDeploymentManifest } from './deployment-manifest-save';
import { useTranslation } from 'react-i18next';
interface DeploymentEditBasicProps {
clusterCode: string;
@@ -39,7 +38,6 @@ function kvToObj(arr: Array<{ key: string; value: string }>): Record<string, str
}
export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel, isCreate = false }: DeploymentEditBasicProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -95,7 +93,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
const merged = { ...kvToObj(prev), ...sel };
return Object.entries(merged).map(([key, value]) => ({ key, value }));
});
toast({ title: t('kubernetes.deploymenteditbasic.s8bf97a'), description: t('kubernetes.deploymenteditbasic.s841d0d') });
toast({ title: '已同步', description: 'Selector 标签已合并到 Pod 模板标签' });
};
const save = async () => {
@@ -108,7 +106,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
base.metadata = base.metadata || {};
if (isCreate) {
const trimmed = resName.trim();
if (!trimmed) throw new Error(t('kubernetes.deploymenteditbasic.sdf09ff'));
if (!trimmed) throw new Error('名称不能为空');
base.metadata.name = trimmed;
base.metadata.namespace = namespace;
}
@@ -129,10 +127,10 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
delete base.spec.template.metadata.labels;
}
const savedName = await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: isCreate ? t('monitor.dashboard.custom.toastCreateSuccess') : t('kubernetes.deploymenteditbasic.sa59c4d'), description: isCreate ? t('kubernetes.deploymenteditbasic.s220fce', { savedName: savedName }) : t('kubernetes.deploymenteditbasic.s253b77', { savedName: savedName }) });
toast({ title: isCreate ? '创建成功' : '基本信息已保存', description: isCreate ? `${savedName} 已创建` : `${savedName} 更新已提交` });
onSaved(base);
} catch (e) {
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -141,7 +139,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
@@ -176,7 +174,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
onChange={e => setReplicas(Math.max(0, Number(e.target.value) || 0))}
className="w-32 dg-input"
/>
<span className="text-xs dg-text-muted">{t('kubernetes.deploymenteditbasic.s6e47fc')}</span>
<span className="text-xs dg-text-muted">期望运行的 Pod 实例数量</span>
</div>
</CardContent>
</Card>
@@ -186,12 +184,12 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<CardHeader className="pb-3">
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Lock className="h-4 w-4 dg-text-muted" />
{isCreate ? t('kubernetes.deploymenteditbasic.sc8de32') : t('kubernetes.deploymenteditbasic.sc4d9eb')}
{isCreate ? '基本标识' : '基本标识(只读)'}
</CardTitle>
</CardHeader>
<CardContent className="pt-0 grid grid-cols-2 gap-4">
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deploymenteditbasic.sab7247')}</Label>
<Label className="dg-text-secondary text-xs">名称 (name)</Label>
<Input
value={isCreate ? resName : deploymentName}
readOnly={!isCreate}
@@ -200,7 +198,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
/>
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deploymenteditbasic.s00e648')}</Label>
<Label className="dg-text-secondary text-xs">命名空间 (namespace)</Label>
<Input value={namespace} readOnly
className="mt-1 bg-[var(--dg-bg-primary)] border-[var(--dg-border)] dg-text-muted font-mono text-sm cursor-not-allowed" />
</div>
@@ -222,7 +220,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
{labels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.s3f9afc')}</p>}
{labels.length === 0 && <p className="text-[11px] dg-text-muted">无标签</p>}
{labels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app"
@@ -245,7 +243,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<Tags className="h-4 w-4 dg-text-yellow" />
选择器 (Selector)
<Badge variant="outline" className="border-amber-700/50 text-amber-500 text-[10px]">{t('kubernetes.deploymenteditbasic.s36e4c3')}</Badge>
<Badge variant="outline" className="border-amber-700/50 text-amber-500 text-[10px]">⚠️ 需与模板标签一致</Badge>
</CardTitle>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={addSelector}>
<Plus className="h-3 w-3 mr-1" />新增
@@ -253,8 +251,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
<p className="text-[11px] text-amber-500/70 mb-1">{t('kubernetes.deploymenteditbasic.sc29c88')}</p>
{selectorLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.service.noSelector')}</p>}
<p className="text-[11px] text-amber-500/70 mb-1">Selector 决定哪些 Pod 归属此 Deployment。修改时必须确保与 Pod Template Labels 匹配,否则 Deployment 将无法管理 Pod。</p>
{selectorLabels.length === 0 && <p className="text-[11px] dg-text-muted">无选择器</p>}
{selectorLabels.map((s, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={s.key} placeholder="app"
@@ -289,8 +287,8 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
<p className="text-[11px] dg-text-muted mb-1">{t('kubernetes.deploymenteditbasic.s9faa25')}</p>
{templateLabels.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.se9c9f6')}</p>}
<p className="text-[11px] dg-text-muted mb-1">Pod 模板标签必须包含 Selector 全部键值,否则 Deployment 无法管理 Pod</p>
{templateLabels.length === 0 && <p className="text-[11px] dg-text-muted">无模板标签</p>}
{templateLabels.map((l, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={l.key} placeholder="app"
@@ -321,7 +319,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
</div>
</CardHeader>
<CardContent className="pt-0 space-y-1.5">
{annotations.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.deploymenteditbasic.sbe1e7c')}</p>}
{annotations.length === 0 && <p className="text-[11px] dg-text-muted">无注解</p>}
{annotations.map((a, i) => (
<div key={i} className="grid grid-cols-[1fr_1.4fr_auto] gap-2">
<Input value={a.key} placeholder="deployment.kubernetes.io/revision"
@@ -343,7 +341,7 @@ export function DeploymentEditBasic({ clusterCode, namespace, deploymentName, ma
保存将通过 <code className="dg-text-secondary">PUT application/yaml</code> 提交(自动剥离 status/managedFields 等只读字段)
</p>
<div className="flex gap-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存
@@ -26,10 +26,8 @@ import {
} from './deployment-edit/container-utils';
import type { ContainerForm, DeploymentEditContainersProps } from './deployment-edit/types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentEditContainers({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: DeploymentEditContainersProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -83,11 +81,11 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
// validate
for (const c of [...initContainers, ...containers]) {
if (!c.name.trim()) {
toast({ title: t('common.saveFailed'), description: t('kubernetes.deploymenteditcontainers.s14b12c'), variant: 'destructive' });
toast({ title: '保存失败', description: '容器名称不能为空', variant: 'destructive' });
return;
}
if (!c.image.trim()) {
toast({ title: t('common.saveFailed'), description: t('kubernetes.deploymenteditcontainers.sb01a6a', { c.name: c.name }), variant: 'destructive' });
toast({ title: '保存失败', description: `容器 ${c.name} 的镜像不能为空`, variant: 'destructive' });
return;
}
}
@@ -103,10 +101,10 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
? imagePullSecrets.filter(s => s.trim()).map((s: string) => ({ name: s }))
: undefined;
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: t('kubernetes.deploymenteditcontainers.sdf22b9'), description: t('kubernetes.deploymenteditcontainers.s1952a7', { deploymentName: deploymentName }) });
toast({ title: '容器配置已保存', description: `${deploymentName} 更新已提交` });
onSaved(base);
} catch (e) {
toast({ title: t('common.saveFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '保存失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -115,7 +113,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
@@ -138,7 +136,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<CardTitle className="text-sm text-[var(--dg-text-primary)] flex items-center gap-2">
<KeyRound className="h-4 w-4 dg-text-yellow" />
镜像拉取凭证 (imagePullSecrets)
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-muted text-[10px]">{t('kubernetes.deploymenteditcontainers.s2f29fb')}</Badge>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-muted text-[10px]">Pod 级别</Badge>
</CardTitle>
</CardHeader>
<CardContent className="pt-0 space-y-2">
@@ -150,10 +148,10 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
className="dg-text-red hover:dg-text-red ml-1"><Trash2 className="h-3 w-3" /></button>
</div>
))}
{imagePullSecrets.length === 0 && <span className="text-[11px] dg-text-muted">{t('common.none')}</span>}
{imagePullSecrets.length === 0 && <span className="text-[11px] dg-text-muted">无</span>}
</div>
<div className="flex gap-2">
<Input placeholder=t('kubernetes.deploymenteditcontainers.s960f6a') className="dg-input text-xs h-8"
<Input placeholder="输入 Secret 名称后回车" className="dg-input text-xs h-8"
onKeyDown={(e) => {
if (e.key === 'Enter') {
const val = (e.target as HTMLInputElement).value.trim();
@@ -170,8 +168,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 初始化容器 */}
<ContainerGroupSection
title=t('kubernetes.pod.initContainer')
description=t('kubernetes.deploymenteditcontainers.s883e09')
title="初始化容器"
description="在主容器启动前按顺序执行的容器,用于初始化环境"
icon={<Play className="h-4 w-4 dg-text-purple" />}
containers={initContainers}
accentColor="purple"
@@ -182,8 +180,8 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
{/* 工作容器 */}
<ContainerGroupSection
title=t('kubernetes.deploymenteditcontainers.sc61b83')
description=t('kubernetes.deploymenteditcontainers.s43eebd')
title="工作容器"
description="Deployment 运行的主容器,定义应用进程及其运行时配置"
icon={<Container className="h-4 w-4 dg-text-blue" />}
containers={containers}
accentColor="blue"
@@ -200,7 +198,7 @@ export function DeploymentEditContainers({ clusterCode, namespace, deploymentNam
<span className="text-[var(--dg-text-secondary)] font-semibold ml-1">{containers.length}</span> 个工作容器
</div>
<div className="flex gap-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存
@@ -28,7 +28,6 @@ import { useConfirm } from '@/components/ui/confirm-dialog';
import { kubernetesApi } from '@/api';
import { dumpManifest } from './k8s-manifest-utils';
import { ResourceVisualEditor } from './ResourceVisualEditor';
import { useTranslation } from 'react-i18next';
interface Props {
clusterCode: string;
@@ -76,7 +75,6 @@ interface _SvcPortForm {
const toArray = ( v: any) => (Array.isArray(v) ? v : (v?.list || v?.items || v?.data || []));
export function DeploymentEditService({ clusterCode, namespace, deploymentName, manifest, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const confirm = useConfirm();
const [loading, setLoading] = useState(true);
@@ -227,11 +225,11 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
try {
const yaml = await dumpManifest(svcManifest);
await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: t('kubernetes.deploymenteditservice.sabd7e0'), description: name });
toast({ title: 'Service 已创建', description: name });
setShowCreate(null);
load();
} catch (e) {
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '创建失败', description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -262,30 +260,30 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
try {
const yaml = await dumpManifest(manifest);
await kubernetesApi.applyYAML(clusterCode, yaml);
toast({ title: t('kubernetes.deploymenteditservice.se356fb'), description: name });
toast({ title: 'Ingress 已创建', description: name });
setShowCreate(null);
load();
} catch (e) {
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '创建失败', description: e?.message || String(e), variant: 'destructive' });
}
};
// 删除资源
const deleteResource = async (kind: 'service' | 'ingress', name: string) => {
const ok = await confirm({
title: t('kubernetes.deploymenteditservice.s8a2a35'),
description: t('kubernetes.deploymenteditservice.s4742c2', { kind === 'service' ? 'Service' : 'Ingress': kind === 'service' ? 'Service' : 'Ingress', name: name }),
confirmText: t('common.delete'),
title: '删除资源',
description: `确认删除 ${kind === 'service' ? 'Service' : 'Ingress'} 「${name}」?此操作不可撤销。`,
confirmText: '删除',
variant: 'destructive',
});
if (!ok) return;
try {
const resource = kind === 'service' ? 'services' : 'ingresses';
await kubernetesApi.deleteResourceYaml(clusterCode, namespace, resource, name);
toast({ title: t('alert.deleted'), description: t('kubernetes.deploymenteditservice.s857e9a', { kind === 'service' ? 'Service' : 'Ingress': kind === 'service' ? 'Service' : 'Ingress', name: name }) });
toast({ title: '已删除', description: `${kind === 'service' ? 'Service' : 'Ingress'} ${name} 已删除` });
load();
} catch (e) {
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
}
};
@@ -294,7 +292,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
@@ -307,13 +305,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<CardContent className="p-3">
<div className="flex items-center gap-2 text-xs dg-text-secondary">
<Network className="h-3.5 w-3.5 dg-text-blue" />
<span>{t('kubernetes.deploymenteditservice.sb8eef7')}</span>
<span>选择器:</span>
<div className="flex flex-wrap gap-1">
{Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-[var(--dg-bg-tertiary)] px-1.5 py-0.5 rounded text-[var(--dg-text-secondary)] text-[11px]">{k}={v}</code>
))}
{Object.keys(selectorLabels).length === 0 && (
<span className="dg-text-muted italic">{t('kubernetes.deploymenteditservice.s33360b')}</span>
<span className="dg-text-muted italic">(无 selector)</span>
)}
</div>
<Button size="sm" variant="ghost" className="h-6 ml-auto text-xs dg-text-secondary" onClick={load}>
@@ -340,7 +338,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Plus className="h-3 w-3 mr-1" />创建 Service
</Button>
</div>
<p className="text-xs dg-text-muted mt-1">{t('kubernetes.deploymenteditservice.sd0ad85')}</p>
<p className="text-xs dg-text-muted mt-1">仅显示 selector 匹配此 Deployment 的关联 Service</p>
</CardHeader>
<CardContent className="pt-0">
{matchedSvcs.length === 0 && showCreate !== 'service' ? (
@@ -358,14 +356,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{matched ? <CheckCircle className="h-4 w-4 dg-text-blue" /> : <Network className="h-4 w-4 dg-text-muted" />}
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">{svc.name}</span>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary text-[10px]">{svc.type}</Badge>
{matched && <Badge className="bg-blue-500/20 text-blue-300 border-blue-500/30 text-[10px]">{t('kubernetes.deploymenteditservice.s1c3cf7')}</Badge>}
{matched && <Badge className="bg-blue-500/20 text-blue-300 border-blue-500/30 text-[10px]">关联</Badge>}
<code className="text-[11px] dg-text-muted ml-auto">{svc.clusterIP}</code>
<Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green"
onClick={() => setVisualEditor({ resource: 'services', name: svc.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red"
title=t('kubernetes.service.deleteService') onClick={() => deleteResource('service', svc.name)}>
title="删除 Service" onClick={() => deleteResource('service', svc.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -401,13 +399,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 基本信息 */}
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="dg-text-muted text-[11px]">{t('common.name')}</Label>
<Label className="dg-text-muted text-[11px]">名称</Label>
<Input value={svcForm.name} onChange={e => setSvcForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-svc`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">{t('common.type')}</Label>
<Label className="dg-text-muted text-[11px]">类型</Label>
<select value={svcForm.type} onChange={e => setSvcForm(s => ({ ...s, type: e.target.value }))}
className="h-7 mt-0.5 w-full bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-2">
<option value="ClusterIP">ClusterIP</option>
@@ -418,7 +416,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* 快速预设 */}
<div>
<Label className="dg-text-muted text-[11px] mb-1 block">{t('kubernetes.deploymenteditservice.s83907c')}</Label>
<Label className="dg-text-muted text-[11px] mb-1 block">快速添加常用端口</Label>
<div className="flex gap-1.5">
{PORT_PRESETS.map(p => (
<button key={p.name} onClick={() => addPort(p)}
@@ -479,19 +477,19 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{/* Selector 预览 */}
<div className="text-[10px] dg-text-muted border-t border-[var(--dg-border)]/50 pt-2">
<span className="dg-text-muted">{t('kubernetes.deploymenteditservice.sfd3a08')} </span>
<span className="dg-text-muted">selector (自动检测): </span>
{Object.keys(selectorLabels).length > 0 ? (
Object.entries(selectorLabels).map(([k, v]) => (
<code key={k} className="bg-[var(--dg-bg-tertiary)] px-1 py-0.5 rounded dg-text-secondary ml-1">{k}={v}</code>
))
) : (
<span className="dg-text-muted italic">{t('kubernetes.deploymenteditservice.s5847b0')}</span>
<span className="dg-text-muted italic">未检测到</span>
)}
</div>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>{t('common.cancel')}</Button>
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>{t('common.create')}</Button>
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-blue-600 hover:bg-blue-700 text-xs" onClick={createService}>创建</Button>
</div>
</div>
)}
@@ -515,7 +513,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
<Plus className="h-3 w-3 mr-1" />创建 Ingress
</Button>
</div>
<p className="text-xs dg-text-muted mt-1">{t('kubernetes.deploymenteditservice.s847cc9')}</p>
<p className="text-xs dg-text-muted mt-1">backend 指向关联 Service 的 Ingress 自动高亮</p>
</CardHeader>
<CardContent className="pt-0">
{ingresses.length === 0 ? (
@@ -533,13 +531,13 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
{matched ? <CheckCircle className="h-4 w-4 dg-text-purple" /> : <GitBranch className="h-4 w-4 dg-text-muted" />}
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">{ing.name}</span>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary text-[10px]">{ing.className}</Badge>
{matched && <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-[10px]">{t('kubernetes.deploymenteditservice.s1c3cf7')}</Badge>}
{matched && <Badge className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-[10px]">关联</Badge>}
<Button size="sm" variant="ghost" className="h-6 text-xs dg-text-green ml-auto"
onClick={() => setVisualEditor({ resource: 'ingresses', name: ing.name })}>
<Pencil className="h-3 w-3 mr-1" />编辑
</Button>
<Button size="sm" variant="ghost" className="h-6 w-6 p-0 dg-text-red hover:dg-text-red"
title=t('kubernetes.ingress.deleteIngress') onClick={() => deleteResource('ingress', ing.name)}>
title="删除 Ingress" onClick={() => deleteResource('ingress', ing.name)}>
<Trash2 className="h-3 w-3" />
</Button>
</div>
@@ -571,7 +569,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
</div>
<div className="grid grid-cols-2 gap-2">
<div>
<Label className="dg-text-muted text-[11px]">{t('common.name')}</Label>
<Label className="dg-text-muted text-[11px]">名称</Label>
<Input value={ingForm.name} onChange={e => setIngForm(s => ({ ...s, name: e.target.value }))}
placeholder={`${deploymentName}-ingress`}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
@@ -583,7 +581,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">{t('kubernetes.deploymenteditservice.s4d9e8d')}</Label>
<Label className="dg-text-muted text-[11px]">host (域名)</Label>
<Input value={ingForm.host} onChange={e => setIngForm(s => ({ ...s, host: e.target.value }))}
placeholder="app.example.com"
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
@@ -595,14 +593,14 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
<div>
<Label className="dg-text-muted text-[11px]">{t('kubernetes.deploymenteditservice.sef5625')}</Label>
<Label className="dg-text-muted text-[11px]">Service 端口</Label>
<Input type="number" value={ingForm.svcPort} onChange={e => setIngForm(s => ({ ...s, svcPort: e.target.value }))}
className="h-7 mt-0.5 dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
<div className="flex justify-end gap-2 pt-1">
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>{t('common.cancel')}</Button>
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>{t('common.create')}</Button>
<Button size="sm" variant="ghost" className="h-7 text-xs dg-text-secondary" onClick={() => setShowCreate(null)}>取消</Button>
<Button size="sm" className="h-7 bg-purple-600 hover:bg-purple-700 text-xs" onClick={createIngress}>创建</Button>
</div>
</div>
)}
@@ -621,7 +619,7 @@ export function DeploymentEditService({ clusterCode, namespace, deploymentName,
)}
<div className="flex justify-end gap-2 pt-2">
<Button size="sm" variant="outline" className="h-7 text-xs border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('kubernetes.deploymenteditservice.s3a7752')}</Button>
<Button size="sm" variant="outline" className="h-7 text-xs border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>返回查看</Button>
</div>
</div>
);
@@ -28,8 +28,6 @@ import {
emptyMountRow,
} from './deployment-volume-utils';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
interface Props {
clusterCode: string;
@@ -41,12 +39,12 @@ interface Props {
}
const VOLUME_TYPES: { key: VolumeForm['type']; label: string; icon: typeof HardDrive; color: string }[] = [
{ key: 'persistentVolumeClaim', label: i18n.t('kubernetes.deploymenteditstorage.s18c900'), icon: Database, color: 'dg-text-green' },
{ key: 'emptyDir', label: i18n.t('kubernetes.deploymenteditstorage.s5449b2'), icon: Disc, color: 'dg-text-secondary' },
{ key: 'persistentVolumeClaim', label: '存储卷声明', icon: Database, color: 'dg-text-green' },
{ key: 'emptyDir', label: '临时目录(EmptyDir)', icon: Disc, color: 'dg-text-secondary' },
{ key: 'hostPath', label: 'HostPath', icon: HardDrive, color: 'dg-text-yellow' },
{ key: 'nfs', label: 'NFS', icon: Server, color: 'dg-text-purple' },
{ key: 'configMap', label: i18n.t('kubernetes.deploymenteditstorage.s0986a6'), icon: File, color: 'dg-text-blue' },
{ key: 'secret', label: i18n.t('kubernetes.deploymenteditstorage.sc09936'), icon: Lock, color: 'text-rose-400' },
{ key: 'configMap', label: '配置字典', icon: File, color: 'dg-text-blue' },
{ key: 'secret', label: '密文', icon: Lock, color: 'text-rose-400' },
];
const SELECTABLE_TYPES = new Set(VOLUME_TYPES.map((t) => t.key));
@@ -54,7 +52,6 @@ const SELECTABLE_TYPES = new Set(VOLUME_TYPES.map((t) => t.key));
type CreateResourceKind = 'configmaps' | 'secrets' | 'pvcs';
export function DeploymentEditStorage({ clusterCode, namespace, deploymentName, manifest, onSaved, onCancel }: Props) {
const { t } = useTranslation();
const { toast } = useToast();
const [saving, setSaving] = useState(false);
const [loading, setLoading] = useState(!manifest);
@@ -131,20 +128,20 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const save = async () => {
for (const entry of entries) {
if (!entry.volume.name.trim()) {
toast({ title: t('kubernetes.deploymenteditstorage.s5b59d2'), variant: 'destructive' });
toast({ title: '请填写数据卷名称', variant: 'destructive' });
return;
}
if (!formToVolume(entry.volume)) {
const hint = entry.volume.type === 'configMap' ? t('kubernetes.deploymenteditstorage.s2a6856')
: entry.volume.type === 'secret' ? t('kubernetes.deploymenteditstorage.s1f31e4')
: entry.volume.type === 'persistentVolumeClaim' ? t('kubernetes.deploymenteditstorage.sba9fc6')
: t('kubernetes.deploymenteditstorage.s03480a');
toast({ title: t('kubernetes.deploymenteditstorage.se542a6'), description: t('kubernetes.deploymenteditstorage.s3152b4', { entry.volume.name: entry.volume.name, hint: hint }), variant: 'destructive' });
const hint = entry.volume.type === 'configMap' ? '请选择 ConfigMap'
: entry.volume.type === 'secret' ? '请选择 Secret'
: entry.volume.type === 'persistentVolumeClaim' ? '请选择 PVC'
: '的类型必填项';
toast({ title: '数据卷配置不完整', description: `请为「${entry.volume.name}」${hint}`, variant: 'destructive' });
return;
}
const validMounts = entry.mounts.filter((m) => m.mountPath.trim());
if (validMounts.length === 0) {
toast({ title: t('kubernetes.deploymenteditstorage.s24b5b9'), description: t('kubernetes.deploymenteditstorage.s5532a8', { entry.volume.name: entry.volume.name }), variant: 'destructive' });
toast({ title: '请填写挂载路径', description: `数据卷「${entry.volume.name}」需至少挂载到一个容器`, variant: 'destructive' });
return;
}
}
@@ -153,10 +150,10 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
const { volumes, mounts } = volumeEntriesToStorage(entries);
const base = applyStorageToManifest(rawManifest, volumes, mounts, passthroughVolumes);
await saveDeploymentManifest(clusterCode, namespace, deploymentName, base);
toast({ title: t('kubernetes.deploymenteditstorage.sa8cd7d'), description: t('kubernetes.deploymenteditstorage.s1952a7', { deploymentName: deploymentName }) });
toast({ title: '存储配置已保存', description: `${deploymentName} 更新已提交` });
onSaved(base);
} catch (e) {
toast({ title: t('common.saveFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: '保存失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -165,7 +162,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<Card className="dg-card">
<CardContent className="p-12 text-center">
<Loader2 className="h-6 w-6 animate-spin mx-auto dg-text-muted" />
<p className="dg-text-muted mt-3 text-sm">{t('common.loading')}</p>
<p className="dg-text-muted mt-3 text-sm">加载中...</p>
</CardContent>
</Card>
);
@@ -174,7 +171,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (!manifest) {
return (
<Card className="dg-card">
<CardContent className="p-8 text-center dg-text-muted">{t('kubernetes.deploymenteditstorage.s800b9f')}</CardContent>
<CardContent className="p-8 text-center dg-text-muted">未获取到 manifest 数据,请使用 YAML 编辑模式。</CardContent>
</Card>
);
}
@@ -201,7 +198,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
数据卷
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary">{entries.length}</Badge>
</CardTitle>
<p className="text-[11px] dg-text-muted mt-1">{t('kubernetes.deploymenteditstorage.s1e0b32')}</p>
<p className="text-[11px] dg-text-muted mt-1">定义数据卷,并将其挂载到工作负载的容器中</p>
</div>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs shrink-0" onClick={addEntry}>
<Plus className="h-3 w-3 mr-1" />添加数据卷
@@ -225,7 +222,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<div className="p-3 space-y-2.5 border-b border-[var(--dg-border)]/80">
<div className="flex items-center gap-2 flex-wrap">
<VIcon className={`h-4 w-4 ${vtype?.color || 'dg-text-secondary'}`} />
<span className="text-xs dg-text-secondary shrink-0">{t('kubernetes.deploymenteditstorage.sa3119d')}</span>
<span className="text-xs dg-text-secondary shrink-0">数据卷名称</span>
<Input
value={vol.name}
onChange={(e) => {
@@ -236,7 +233,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
if (vol.type === 'persistentVolumeClaim' && !vol.pvcName) patch.pvcName = name;
updateVolume(i, patch);
}}
placeholder=t('kubernetes.deploymenteditstorage.s478bfa')
placeholder="如 app-logs / fluent-bit-config"
className="h-8 w-44 dg-input text-sm font-mono"
/>
{/* 原生 select,避免 Radix Select 在 overflow 容器内无法下拉 // Logan.Li */}
@@ -298,7 +295,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
onChange={(e) => updateMount(i, mi, { containerName: e.target.value })}
className="h-8 min-w-[140px] max-w-[280px] bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-md text-sm text-[var(--dg-text-primary)] px-2 font-medium truncate"
>
{containers.length === 0 && <option value="">{t('kubernetes.deploymenteditstorage.s327178')}</option>}
{containers.length === 0 && <option value="">(无容器)</option>}
{containers.map((cn) => <option key={cn} value={cn}>{cn}</option>)}
</select>
<div className="flex items-center gap-1 bg-[var(--dg-bg-tertiary)] rounded-lg p-0.5 border border-[var(--dg-border)]">
@@ -314,7 +311,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
<Input
value={mount.mountPath}
onChange={(e) => updateMount(i, mi, { mountPath: e.target.value })}
placeholder=t('kubernetes.deploymenteditstorage.seb88e4')
placeholder="挂载路径 /bitcloud/app/.../logs"
className="h-8 flex-1 min-w-[200px] dg-input text-sm font-mono"
/>
{entry.mounts.length > 1 && (
@@ -324,11 +321,11 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
)}
</div>
<div className="flex items-center gap-2">
<span className="text-[11px] dg-text-muted shrink-0">{t('kubernetes.deploymenteditstorage.sf4b25a')}</span>
<span className="text-[11px] dg-text-muted shrink-0">子路径 subPath</span>
<Input
value={mount.subPath}
onChange={(e) => updateMount(i, mi, { subPath: e.target.value })}
placeholder=t('kubernetes.deploymenteditstorage.s68ab2e')
placeholder="如 config.yaml(挂载单文件时填写)"
className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono"
/>
</div>
@@ -342,7 +339,7 @@ export function DeploymentEditStorage({ clusterCode, namespace, deploymentName,
</Card>
<div className="flex justify-end gap-2 pt-2">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>{t('common.cancel')}</Button>
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onCancel}>取消</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={saving} onClick={save}>
{saving ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Save className="h-4 w-4 mr-1" />}
保存
@@ -25,10 +25,8 @@ import type { DeploymentViewProps, SvcItem, IngItem, EventItem } from './deploym
export type { DeploymentViewProps } from './deployment-view/types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function DeploymentView(props: DeploymentViewProps) {
const { t } = useTranslation();
const { clusterCode, namespace, deployment, pods, revisions, onRefresh } = props;
const { toast } = useToast();
const confirm = useConfirm();
@@ -140,19 +138,19 @@ export function DeploymentView(props: DeploymentViewProps) {
const handleRollback = async (rev: JsonData) => {
const revision = rev.revision ?? rev.revision_number ?? rev.number;
const ok = await confirm({
title: t('kubernetes.deploymentview.s6a374e'),
description: t('kubernetes.deploymentview.s01eec9', { revision: revision }),
confirmText: t('common.rollback'),
title: '回滚版本',
description: `确认回滚到修订版本 #${revision}?`,
confirmText: '回滚',
variant: 'destructive',
});
if (!ok) return;
setRollbackLoading(revision);
try {
await kubernetesApi.rollbackDeployment(clusterCode, namespace, deployment.name, Number(revision));
toast({ title: t('kubernetes.deploymentview.s754d92'), description: t('kubernetes.deploymentview.s817a27', { revision: revision }) });
toast({ title: '回滚已下发', description: `正在回滚到 #${revision}` });
onRefresh();
} catch (e) {
toast({ title: t('pipeline.rollbackFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '回滚失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setRollbackLoading(null); }
};
@@ -161,19 +159,19 @@ export function DeploymentView(props: DeploymentViewProps) {
setScaleLoading(true);
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deployment.name, scaleValue);
toast({ title: t('kubernetes.deploymentview.sb9c9e0'), description: t('kubernetes.deploymentview.sb8f328', { scaleValue: scaleValue }) });
toast({ title: '伸缩已提交', description: `副本数 → ${scaleValue}` });
onRefresh();
} catch (e) {
toast({ title: t('kubernetes.msg.scaleFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '伸缩失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setScaleLoading(false); }
};
const TABS = [
{ key: 'pods', label: t('kubernetes.deploymentview.s479692'), icon: Container, count: pods.length },
{ key: 'services', label: t('kubernetes.deploymentview.s706804'), icon: Network, count: services.length },
{ key: 'events', label: t('menu.events'), icon: Activity, count: events.length },
{ key: 'scale', label: t('kubernetes.deploymentview.s3b291d'), icon: Plus },
{ key: 'history', label: t('kubernetes.deployment.revisions'), icon: History, count: revisions.length },
{ key: 'pods', label: '容器组', icon: Container, count: pods.length },
{ key: 'services', label: '访问方式', icon: Network, count: services.length },
{ key: 'events', label: '事件', icon: Activity, count: events.length },
{ key: 'scale', label: '容器伸缩', icon: Plus },
{ key: 'history', label: '历史版本', icon: History, count: revisions.length },
];
return (
@@ -182,24 +180,24 @@ export function DeploymentView(props: DeploymentViewProps) {
<Card className="dg-card">
<CardContent className="p-4">
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 text-sm">
<InfoItem label=t('common.status') value={
<InfoItem label="状态" value={
<Badge style={{ background: `${isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange}22`, color: isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange, border: `1px solid ${isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange}44` }}>
{isHealthy ? 'Running' : 'Updating'}
</Badge>
} />
<InfoItem label=t('kubernetes.deploymentview.s0428b3') value={<span className="font-mono">{ready}/{total}</span>} />
<InfoItem label=t('kubernetes.deploymentview.s669145') value={deployment?.strategy || 'RollingUpdate'} />
<InfoItem label="副本" value={<span className="font-mono">{ready}/{total}</span>} />
<InfoItem label="策略" value={deployment?.strategy || 'RollingUpdate'} />
{pods[0] && (
<>
<InfoItem label=t('kubernetes.pod.nodeName') value={
<InfoItem label="所在节点" value={
<button className="text-[var(--dg-blue)] hover:underline" onClick={() => window.open(`/kubernetes/${clusterCode}/nodes/${pods[0].node_name || pods[0].node}`, '_blank')}>
{pods[0].node_name || pods[0].node || '-'}
</button>
} />
<InfoItem label=t('kubernetes.deploymentview.s6d2d95') value={<span className="font-mono">{pods[0].ip || pods[0].pod_ip || '-'}</span>} />
<InfoItem label="容器组 IP" value={<span className="font-mono">{pods[0].ip || pods[0].pod_ip || '-'}</span>} />
</>
)}
<InfoItem label=t('common.createdAt') value={formatK8sTime(deployment?.created_at || deployment?.creationTimestamp)} />
<InfoItem label="创建时间" value={formatK8sTime(deployment?.created_at || deployment?.creationTimestamp)} />
</div>
{pods.length === 1 && (
<div className="mt-3 pt-3 border-t border-[var(--dg-border)]">
@@ -245,7 +243,7 @@ export function DeploymentView(props: DeploymentViewProps) {
{scaleValue !== total && (
<Button size="sm" className="h-7 text-xs bg-[var(--dg-blue)] hover:bg-[var(--dg-blue-hover)]"
disabled={scaleLoading} onClick={handleScale}>
{scaleLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : t('common.apply')}
{scaleLoading ? <Loader2 className="h-3 w-3 animate-spin" /> : '应用'}
</Button>
)}
</div>
@@ -40,12 +40,10 @@ import { CREATE_DEPLOYMENT_SLUG, isCreateDeployment } from './deployment-constan
import { extractContainers } from './deployment-detail/helpers';
import { PageShell } from '@/components/layout/PageShell';
import type { ActionModal, DeploymentWorkloadProps } from './deployment-workload/types';
import { useTranslation } from 'react-i18next';
export type { DeploymentWorkloadProps, WorkloadMode } from './deployment-workload/types';
export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mode, onBack, onModeChange }: DeploymentWorkloadProps) {
const { t } = useTranslation();
const isCreate = isCreateDeployment(deploymentName);
const navigate = useNavigate();
const { toast } = useToast();
@@ -119,7 +117,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setRevisions(toArray(revRes));
} catch (e) {
console.error(t('kubernetes.deploymentworkload.sb46ea9'), e);
console.error('加载详情失败:', e);
} finally {
setLoading(false);
}
@@ -134,7 +132,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const { manifest: parsed } = await parseEditableManifest(yamlText);
setManifest(parsed || deployment);
} catch (e) {
console.warn(t('kubernetes.deploymentworkload.sce123f'), e);
console.warn('加载 manifest 失败(编辑功能降级):', e);
setManifest(deployment);
}
}, [clusterCode, namespace, deploymentName, deployment]);
@@ -162,10 +160,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, newReplicas);
toast({ title: t('kubernetes.deploymentworkload.s0b3ea1'), description: t('kubernetes.deploymentworkload.sacbcbd', { newReplicas: newReplicas }) });
toast({ title: '扩缩容成功', description: `副本数已设置为 ${newReplicas}` });
loadData();
} catch (e) {
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -173,37 +171,37 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
setActionLoading('scale');
try {
await kubernetesApi.scaleDeployment(clusterCode, namespace, deploymentName, scaleValue);
toast({ title: t('kubernetes.msg.scaleSuccess'), description: t('kubernetes.deploymentworkload.s1755d8', { scaleValue: scaleValue }) });
toast({ title: '伸缩成功', description: `副本数已设置为 ${scaleValue}` });
setModal(null);
loadData();
} catch (e) {
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '操作失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleRestart = async () => {
const ok = await confirm({
title: t('kubernetes.deployment.restart'),
description: t('kubernetes.deploymentworkload.s0703ab', { deploymentName: deploymentName }),
confirmText: t('common.reboot'),
title: '滚动重启',
description: `确认滚动重启 Deployment "${deploymentName}"?`,
confirmText: '重启',
});
if (!ok) return;
setActionLoading('restart');
try {
await kubernetesApi.restartDeployment(clusterCode, namespace, deploymentName);
toast({ title: t('kubernetes.deploymentworkload.s68a700'), description: t('kubernetes.deploymentworkload.sd18761') });
toast({ title: '重启指令已下发', description: 'Deployment 正在滚动重启' });
setTimeout(loadData, 1500);
} catch (e) {
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
const handleTogglePause = async () => {
const isPaused = !!deployment?.paused;
const action = isPaused ? t('common.resume') : t('common.pause');
const action = isPaused ? '恢复' : '暂停';
const ok = await confirm({
title: t('kubernetes.deploymentworkload.s704225', { action: action }),
description: t('kubernetes.deploymentworkload.se0945f', { action: action, deploymentName: deploymentName }),
title: `${action}滚动更新`,
description: `确认${action} Deployment "${deploymentName}" 的滚动更新?`,
confirmText: action,
});
if (!ok) return;
@@ -214,10 +212,10 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
} else {
await kubernetesApi.pauseDeployment(clusterCode, namespace, deploymentName);
}
toast({ title: t('kubernetes.deploymentworkload.s408125', { action: action }), description: t('kubernetes.deploymentworkload.s6c1899', { action: action }) });
toast({ title: `${action}成功`, description: `Deployment 滚动更新已${action}` });
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: t('kubernetes.deploymentworkload.s74fa4c', { action: action }), description: e?.message || String(e), variant: 'destructive' });
toast({ title: `${action}失败`, description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -234,11 +232,11 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
await kubernetesApi.updateDeploymentImage(
clusterCode, namespace, deploymentName, newImage, cicdContainerName || undefined,
);
toast({ title: t('kubernetes.deploymentworkload.s6df3c3'), description: t('kubernetes.deploymentworkload.sa982c3', { newImage: newImage }) });
toast({ title: '镜像更新成功', description: `正在滚动更新为 ${newImage}` });
setModal(null);
loadData();
} catch (e) {
toast({ title: t('alert.updateFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '更新失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -251,11 +249,11 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const url = `${baseUrl}/api/v1/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}`;
const resp = await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${tk}` } });
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
toast({ title: t('common.deleteSuccess'), description: t('kubernetes.deploymentworkload.saaac2f', { deploymentName: deploymentName }) });
toast({ title: '删除成功', description: `${deploymentName} 已删除` });
setModal(null);
setTimeout(() => navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/deployments`), 800);
} catch (e) {
toast({ title: t('common.deleteFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '删除失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(''); }
};
@@ -271,24 +269,24 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const handleDeletePod = async (pod: any) => {
const ok = await confirm({
title: t('kubernetes.pod.deletePod'),
description: t('kubernetes.deploymentworkload.s96e132', { pod.name: pod.name }),
confirmText: t('common.delete'),
title: '删除 Pod',
description: `确认删除 Pod "${pod.name}"?操作不可恢复。`,
confirmText: '删除',
});
if (!ok) return;
try {
await kubernetesApi.deletePod(clusterCode, namespace, pod.name);
toast({ title: t('kubernetes.pod.deleted') });
toast({ title: 'Pod 已删除' });
loadData();
} catch (e) {
toast({ title: t('common.deleteFailed'), description: (e as any)?.message || String(e), variant: 'destructive' });
toast({ title: '删除失败', description: (e as any)?.message || String(e), variant: 'destructive' });
}
};
// ============ 渲染 // Logan.Li ============
if (loading) {
return (
<PageShell variant="workspace" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} loading loadingLabel=t('kubernetes.deploymentworkload.seb300b') actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
<PageShell variant="workspace" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} loading loadingLabel="加载 Deployment..." actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
{null}
</PageShell>
);
@@ -296,7 +294,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (!deployment && !isCreate) {
return (
<PageShell variant="default" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
<PageShell variant="default" title={deploymentName} subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
<Card className="dg-card"><CardContent className="p-12 text-center"><XCircle className="h-8 w-8 mx-auto dg-text-red" /><p className="dg-text-secondary mt-3">未找到 Deployment: {deploymentName}</p></CardContent></Card>
</PageShell>
);
@@ -308,7 +306,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
if (name) navigate(`/kubernetes/${clusterCode}/namespace/${namespace}/workload/view/Deployment/${name}`);
};
return (
<PageShell variant="workspace" title=t('kubernetes.deploymentworkload.se2c85a') subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>}>
<PageShell variant="workspace" title="新建 Deployment" subtitle={`${clusterCode} / ${namespace}`} actions={<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>}>
<EditModeContainer clusterCode={clusterCode} namespace={namespace} deploymentName={CREATE_DEPLOYMENT_SLUG} manifest={manifest} isCreate onSaved={handleCreated} onCancel={onBack} />
</PageShell>
);
@@ -320,8 +318,8 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
const modeTabs = (
<div className="inline-flex rounded-md border border-[var(--dg-border)] overflow-hidden">
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'view' ? 'bg-[var(--dg-bg-active)] text-[var(--dg-text-primary)]' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('view')}>{t('common.view')}</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'edit' ? 'bg-blue-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('edit')}>{t('common.edit')}</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'view' ? 'bg-[var(--dg-bg-active)] text-[var(--dg-text-primary)]' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('view')}>查看</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'edit' ? 'bg-blue-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('edit')}>编辑</button>
<button className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'yaml' ? 'bg-emerald-600 text-white' : 'bg-transparent dg-text-secondary hover:text-[var(--dg-text-primary)]'}`} onClick={() => onModeChange('yaml')}>YAML</button>
</div>
);
@@ -330,19 +328,19 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
<PageShell
variant="workspace"
title={deploymentName}
subtitle={t('kubernetes.deploymentworkload.s804752', { clusterCode: clusterCode, namespace: namespace, deployment?.image || '-': deployment?.image || '-' })}
subtitle={`${clusterCode} / ${namespace} · Deployment · 镜像: ${deployment?.image || '-'}`}
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={onBack}><ArrowLeft className="h-4 w-4 mr-1" />返回</Button>
{modeTabs}
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData}><RefreshCw className="h-4 w-4" /></Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { setNewImage(deployment?.image || ''); setModal({ kind: 'image' }); }}><ImageIcon className="h-3.5 w-3.5 mr-1" />{t('kubernetes.deploymentworkload.sf2e020')}</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleRestart}><RotateCw className="h-3.5 w-3.5 mr-1" />{t('common.reboot')}</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { setNewImage(deployment?.image || ''); setModal({ kind: 'image' }); }}><ImageIcon className="h-3.5 w-3.5 mr-1" />调整镜像</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleRestart}><RotateCw className="h-3.5 w-3.5 mr-1" />重启</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" disabled={!!actionLoading} onClick={handleTogglePause}>
{deployment?.paused ? <><Play className="h-3.5 w-3.5 mr-1 dg-text-green" />{t('common.resume')}</> : <><Pause className="h-3.5 w-3.5 mr-1 dg-text-orange" />{t('common.pause')}</>}
{deployment?.paused ? <><Play className="h-3.5 w-3.5 mr-1 dg-text-green" />恢复</> : <><Pause className="h-3.5 w-3.5 mr-1 dg-text-orange" />暂停</>}
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={handleCICD}><Rocket className="h-3.5 w-3.5 mr-1 dg-text-purple" />CI/CD</Button>
<Button variant="outline" size="sm" className="dg-btn-danger" onClick={() => setModal({ kind: 'delete' })}><Trash2 className="h-3.5 w-3.5 mr-1" />{t('common.delete')}</Button>
<Button variant="outline" size="sm" className="dg-btn-danger" onClick={() => setModal({ kind: 'delete' })}><Trash2 className="h-3.5 w-3.5 mr-1" />删除</Button>
</>
)}
>
@@ -352,7 +350,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
<Badge className={isHealthy ? 'bg-emerald-500/20 dg-text-green border-emerald-500/30' : 'bg-amber-500/20 dg-text-yellow border-amber-500/30'}>
{isHealthy ? <CheckCircle className="h-3 w-3 mr-1" /> : <AlertTriangle className="h-3 w-3 mr-1" />}{ready}/{total}
</Badge>
{deployment?.paused && <Badge className="bg-orange-500/20 dg-text-orange border-orange-500/30"><Pause className="h-3 w-3 mr-1" />{t('kubernetes.deploymentworkload.s8be252')}</Badge>}
{deployment?.paused && <Badge className="bg-orange-500/20 dg-text-orange border-orange-500/30"><Pause className="h-3 w-3 mr-1" />已暂停更新</Badge>}
</div>
{/* ============ 主体:view / edit / yaml ============ */}
@@ -379,7 +377,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
resource="deployments"
name={deploymentName}
inline
resourceHint=t('kubernetes.deploymentworkload.s239604')
resourceHint="含关联 Service"
loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml}
onSaved={loadData}
@@ -404,7 +402,7 @@ export function DeploymentWorkload({ clusterCode, namespace, deploymentName, mod
namespace={namespace}
resource="deployments"
name={deploymentName}
resourceHint=t('kubernetes.deploymentworkload.s239604')
resourceHint="含关联 Service"
loadYamlFn={loadBundleYaml}
saveYamlFn={saveBundleYaml}
onClose={() => setModal(null)}
@@ -4,9 +4,8 @@ import { useState, useRef } from 'react';
import { useVirtualizer } from '@tanstack/react-virtual';
import { Badge } from '@/components/ui/badge';
import { Loader2 } from 'lucide-react';
import {
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
import {
type NormalizedEvent,
formatEventRepeatSpan,
formatEventTimeCell,
@@ -32,7 +31,7 @@ const MIN_W = '980px';
export function EventTable({
events,
loading = false,
emptyText = i18n.t('k8s.empty.events'),
emptyText,
showNamespace = false,
scrollHeight = 600,
}: EventTableProps) {
@@ -44,8 +43,9 @@ export function EventTable({
const gridCols = showNamespace ? COLS_NS : COLS;
const minWidth = showNamespace ? MIN_W_NS : MIN_W;
const headers = showNamespace
? [t('kubernetes.eventtable.sc00582'), t('kubernetes.eventtable.s0b2f54'), t('kubernetes.event.eventCount'), t('kubernetes.eventtable.s33e3c0'), t('common.type'), t('kubernetes.event.eventReason'), t('kubernetes.event.eventObject'), t('k8s.column.namespace'), t('common.source'), t('kubernetes.event.eventMessage')]
: [t('kubernetes.eventtable.sc00582'), t('kubernetes.eventtable.s0b2f54'), t('kubernetes.event.eventCount'), t('kubernetes.eventtable.s33e3c0'), t('common.type'), t('kubernetes.event.eventReason'), t('kubernetes.event.eventObject'), t('common.source'), t('kubernetes.event.eventMessage')];
? [t('k8s.event.colLast'), t('k8s.event.colFirst'), t('k8s.event.colCount'), t('k8s.event.colRepeat'), t('k8s.event.colType'), t('k8s.event.colReason'), t('k8s.event.colObject'), t('k8s.event.colNamespace'), t('k8s.event.colSource'), t('k8s.event.colMessage')]
: [t('k8s.event.colLast'), t('k8s.event.colFirst'), t('k8s.event.colCount'), t('k8s.event.colRepeat'), t('k8s.event.colType'), t('k8s.event.colReason'), t('k8s.event.colObject'), t('k8s.event.colSource'), t('k8s.event.colMessage')];
const resolvedEmpty = emptyText || t('k8s.event.empty');
const virtualizer = useVirtualizer({
count: events.length,
@@ -76,7 +76,7 @@ export function EventTable({
<Loader2 className="h-5 w-5 animate-spin text-[var(--dg-text-muted)]" />
</div>
) : events.length === 0 ? (
<div className="flex items-center justify-center text-[var(--dg-text-muted)] py-10">{emptyText}</div>
<div className="flex items-center justify-center text-[var(--dg-text-muted)] py-10">{resolvedEmpty}</div>
) : (
<div style={{ height: totalHeight, position: 'relative', minWidth }}>
{virtualRows.map((vr) => {
@@ -152,7 +152,7 @@ export function EventTable({
</div>
{isExpanded && e.name && (
<div className="mt-1 pt-1 border-t border-[var(--dg-border)] text-[10px] text-[var(--dg-text-muted)]">
事件名: {e.name}
{t('k8s.event.nameLabel')} {e.name}
</div>
)}
</div>
@@ -166,7 +166,7 @@ export function EventTable({
{/* 行数统计 */}
{events.length > 0 && (
<div className="text-center py-2 text-xs text-[var(--dg-text-muted)] border-t border-[var(--dg-border)]">
共 {events.length} 条事件 {events.length > 500 && t('kubernetes.eventtable.sd0a696')}
{t('k8s.event.totalCount', { count: events.length })} {events.length > 500 ? `· ${t('k8s.event.virtualScroll')}` : ''}
</div>
)}
</div>
@@ -13,7 +13,6 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface RankItem { name: string; count: number }
@@ -27,14 +26,13 @@ function RankPanel({
onSelect?: (name: string) => void;
emptyText?: string;
}) {
const { t } = useTranslation();
const max = Math.max(...items.map((i) => i.count), 1);
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-4">
<h3 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{title}</h3>
{items.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-6 text-center">{emptyText || t('common.noData')}</p>
<p className="text-xs text-[var(--dg-text-muted)] py-6 text-center">{emptyText || '暂无数据'}</p>
) : (
<div className="space-y-1.5 max-h-[220px] overflow-y-auto pr-1">
{items.map((item) => {
@@ -69,7 +67,6 @@ function RankPanel({
}
export default function EventsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -163,7 +160,7 @@ export default function EventsPage() {
const filterToolbar = (selectedReason || selectedKind) ? (
<div className="flex items-center gap-2 text-xs">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.eventspage.s841389')}</span>
<span className="text-[var(--dg-text-muted)]">筛选:</span>
{selectedReason && (
<button type="button" className="inline-flex items-center gap-1 rounded border border-[var(--dg-border)] px-2 py-0.5 text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]" onClick={() => setSelectedReason('')}>
原因 {selectedReason} <X className="h-3 w-3" />
@@ -180,16 +177,16 @@ export default function EventsPage() {
return (
<PageShell
variant="list"
title=t('kubernetes.eventspage.s08bf79')
subtitle={clusterName ? t('kubernetes.eventspage.s49c5d1', { clusterName: clusterName }) : t('kubernetes.eventspage.s6bef2b')}
title="事件中心"
subtitle={clusterName ? `${clusterName} · 集群事件与告警` : '集群事件与告警'}
icon={<Bell className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: t('kubernetes.eventspage.s0d3047'), value: summary?.total ?? events.length, color: 'muted' },
{ label: t('kubernetes.eventspage.s0e5b83'), value: summary?.warning_count ?? warningCount, color: 'amber' },
{ label: t('kubernetes.eventspage.s349c62'), value: summary?.normal_count ?? normalCount, color: 'green' },
{ label: t('kubernetes.eventspage.sc62e34'), value: reasonData.length, color: 'red' },
{ label: '事件总数', value: summary?.total ?? events.length, color: 'muted' },
{ label: '告警事件', value: summary?.warning_count ?? warningCount, color: 'amber' },
{ label: '正常事件', value: summary?.normal_count ?? normalCount, color: 'green' },
{ label: '告警类型', value: reasonData.length, color: 'red' },
]}
/>
) : undefined}
@@ -205,20 +202,20 @@ export default function EventsPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={(v) => { setSelectedNs(v); setSelectedReason(''); setSelectedKind(''); }}>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder=t('k8s.column.namespace') /></SelectTrigger>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder="命名空间" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('kubernetes.eventspage.s58173b')}</SelectItem>
<SelectItem value="all">所有命名空间</SelectItem>
{namespaces.map((n) => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
<Select value={timeWindow} onValueChange={setTimeWindow}>
<SelectTrigger className="w-32 h-9 dg-input"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="0">{t('kubernetes.eventspage.s98c99f')}</SelectItem>
<SelectItem value="1">{t('kubernetes.eventspage.sf972b7')}</SelectItem>
<SelectItem value="6">{t('monitor.siteProtocol.rangeDefault')}</SelectItem>
<SelectItem value="24">{t('kubernetes.eventspage.s6e99b7')}</SelectItem>
<SelectItem value="168">{t('kubernetes.eventspage.sd765ef')}</SelectItem>
<SelectItem value="0">全部时间</SelectItem>
<SelectItem value="1">近 1 小时</SelectItem>
<SelectItem value="6">近 6 小时</SelectItem>
<SelectItem value="24">近 24 小时</SelectItem>
<SelectItem value="168">近 7 天</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => { loadEvents(); loadSummary(); }} disabled={loading}>
@@ -230,10 +227,10 @@ export default function EventsPage() {
>
{reasonData.length > 0 && (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
<RankPanel title=t('kubernetes.eventspage.s8c894f') items={reasonData} selected={selectedReason} onSelect={setSelectedReason} />
{nsData.length > 0 && <RankPanel title=t('k8s.column.namespace') items={nsData} />}
<RankPanel title="告警原因" items={reasonData} selected={selectedReason} onSelect={setSelectedReason} />
{nsData.length > 0 && <RankPanel title="命名空间" items={nsData} />}
{kindData.length > 0 && (
<RankPanel title=t('kubernetes.eventspage.s14871a') items={kindData} selected={selectedKind} onSelect={setSelectedKind} />
<RankPanel title="资源类型" items={kindData} selected={selectedKind} onSelect={setSelectedKind} />
)}
</div>
)}
@@ -271,7 +268,7 @@ export default function EventsPage() {
<Select value={filterType} onValueChange={setFilterType}>
<SelectTrigger className="w-28 h-8 dg-input text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('kubernetes.eventspage.sfb9951')}</SelectItem>
<SelectItem value="all">所有类型</SelectItem>
<SelectItem value="Warning">Warning</SelectItem>
<SelectItem value="Normal">Normal</SelectItem>
</SelectContent>
@@ -3,8 +3,8 @@ import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Loader2 } from 'lucide-react';
import { kubernetesApi } from '@/api';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import type { JsonData } from '@/types/common';
interface Props {
/** 集群下路径,如 events、namespace/default/deployments */
@@ -32,7 +32,7 @@ export default function K8sShortcutRedirect({ target }: Props) {
return (
<div className="flex flex-col items-center justify-center py-24 dg-text-muted gap-2">
<Loader2 className="h-6 w-6 animate-spin" />
<span className="text-sm">{t('kubernetes.k8sshortcutredirect.s9d1aae')}</span>
<span className="text-sm">{t('k8s.redirect.redirecting')}</span>
</div>
);
}
@@ -11,7 +11,6 @@ import 'xterm/css/xterm.css';
import { Terminal, Maximize2, Minimize2, X, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useUserStore } from '@/store';
import { useTranslation } from 'react-i18next';
interface KubectlTerminalProps {
open: boolean;
@@ -21,7 +20,6 @@ interface KubectlTerminalProps {
}
export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }: KubectlTerminalProps) {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null);
const wsRef = useRef<WebSocket | null>(null);
@@ -108,12 +106,12 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
ws.onclose = () => {
setConnected(false);
term.write(t('kubernetes.kubectlterminal.sf4ee00'));
term.write('\r\n\x1b[31m[连接已断开]\x1b[0m\r\n');
};
ws.onerror = () => {
setError(t('kubernetes.kubectlterminal.s5b4a67'));
term.write(t('kubernetes.kubectlterminal.sc81077'));
setError('WebSocket 连接失败');
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n');
};
return () => {
@@ -176,7 +174,7 @@ export function KubectlTerminal({ open, onOpenChange, clusterId, clusterName }:
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '900px', width: '90vw' }}
>
<DialogTitle className="sr-only">kubectl — {clusterName}</DialogTitle>
<DialogDescription className="sr-only">{t('kubernetes.kubectlterminal.s66981e')}</DialogDescription>
<DialogDescription className="sr-only">Kubernetes 集群命令行终端</DialogDescription>
{/* 头部 */}
<div className="flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]">
@@ -15,7 +15,6 @@ import {
import { kubernetesApi } from '@/api';
import { toast } from 'sonner';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
// 名称即 code,只允许英文/数字/连字符
const NAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/;
@@ -41,7 +40,6 @@ export function KubernetesClusterDialog({
editingCluster?: JsonData;
onSaved: () => void;
}) {
const { t } = useTranslation();
const [formData, setFormData] = useState({ ...emptyForm });
const [submitting, setSubmitting] = useState(false);
const [hasToken, setHasToken] = useState(false);
@@ -90,7 +88,7 @@ export function KubernetesClusterDialog({
if (!value.trim()) {
setNameError('');
} else if (!NAME_RE.test(value)) {
setNameError(t('kubernetes.kubernetesclusterdialog.sc7ec6c'));
setNameError('只允许英文、数字和连字符(-),首尾不能是连字符');
} else {
setNameError('');
}
@@ -112,7 +110,7 @@ export function KubernetesClusterDialog({
const handleSubmit = async () => {
if (!formData.name.trim() || !NAME_RE.test(formData.name.trim())) {
toast.error(t('kubernetes.kubernetesclusterdialog.s38bbfe')); return;
toast.error('请输入有效的集群名称(英文/数字/连字符)'); return;
}
try {
setSubmitting(true);
@@ -134,7 +132,7 @@ export function KubernetesClusterDialog({
onOpenChange(false);
onSaved();
} catch (e) {
console.error(t('kubernetes.kubernetesclusterdialog.s7aa44b'), e);
console.error('保存集群失败:', e);
} finally {
setSubmitting(false);
}
@@ -147,20 +145,20 @@ export function KubernetesClusterDialog({
<DialogContent className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl">
<DialogHeader>
<DialogTitle className="text-[var(--dg-text-primary)]">
{editingCluster ? t('kubernetes.cluster.editCluster') : t('kubernetes.cluster.addCluster')}
{editingCluster ? '编辑集群' : '添加集群'}
</DialogTitle>
<DialogDescription className="text-[var(--dg-text-secondary)]">
{editingCluster ? t('kubernetes.kubernetesclusterdialog.s2d42f2') : t('kubernetes.kubernetesclusterdialog.sfe6c79')}
{editingCluster ? '修改集群接入配置' : '配置新的 Kubernetes 集群接入信息'}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.cluster.clusterName')}</Label>
<Label className="text-[var(--dg-text-secondary)]">集群名称</Label>
<Input
value={formData.name}
onChange={(e) => handleNameChange(e.target.value)}
placeholder=t('kubernetes.kubernetesclusterdialog.s298c86')
placeholder="如: prod-cluster"
className={`bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] ${nameError ? 'border-red-500' : ''}`}
/>
{nameError && <p className="text-xs dg-text-red">{nameError}</p>}
@@ -169,28 +167,28 @@ export function KubernetesClusterDialog({
</p>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.kubernetesclusterdialog.sbf23eb')}</Label>
<Label className="text-[var(--dg-text-secondary)]">版本(可选)</Label>
<Input
value={formData.version}
onChange={(e) => setFormData({ ...formData, version: e.target.value })}
placeholder=t('kubernetes.kubernetesclusterdialog.s90a9ef')
placeholder="如: 1.28.0"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
/>
</div>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">{t('common.description')}</Label>
<Label className="text-[var(--dg-text-secondary)]">描述</Label>
<Input
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
placeholder=t('kubernetes.kubernetesclusterdialog.s33a940')
placeholder="集群用途描述"
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"
/>
</div>
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">{t('kubernetes.kubernetesclusterdialog.saaa159')}</Label>
<Label className="text-[var(--dg-text-secondary)]">接入方式</Label>
<RadioGroup
value={String(formData.config_type)}
onValueChange={(v) => setFormData({ ...formData, config_type: Number(v) })}
@@ -220,12 +218,12 @@ export function KubernetesClusterDialog({
{formData.config_type === 0 ? (
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">
Token {hasToken && <span className="dg-text-green text-xs ml-1">{t('kubernetes.kubernetesclusterdialog.sb7caaa')}</span>}
Token {hasToken && <span className="dg-text-green text-xs ml-1">✓ 已配置(留空不修改)</span>}
</Label>
<Textarea
value={formData.token}
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
placeholder={hasToken ? t('kubernetes.kubernetesclusterdialog.sf26ca5') : t('kubernetes.kubernetesclusterdialog.s105008')}
placeholder={hasToken ? '已配置,输入新值覆盖...' : '粘贴 Service Account Token...'}
rows={4}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
/>
@@ -233,12 +231,12 @@ export function KubernetesClusterDialog({
) : (
<div className="space-y-2">
<Label className="text-[var(--dg-text-secondary)]">
Kubeconfig {hasKubeConfig && <span className="dg-text-green text-xs ml-1">{t('kubernetes.kubernetesclusterdialog.sb7caaa')}</span>}
Kubeconfig {hasKubeConfig && <span className="dg-text-green text-xs ml-1">✓ 已配置(留空不修改)</span>}
</Label>
<Textarea
value={formData.kube_config}
onChange={(e) => handleKubeConfigChange(e.target.value)}
placeholder={hasKubeConfig ? t('kubernetes.kubernetesclusterdialog.sf26ca5') : 'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
placeholder={hasKubeConfig ? '已配置,输入新值覆盖...' : 'apiVersion: v1\nkind: Config\nclusters:\n- cluster:\n server: https://10.0.0.1:6443\n ...'}
rows={10}
className="bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"
/>
@@ -263,7 +261,7 @@ export function KubernetesClusterDialog({
disabled={canSubmit}
className="bg-[var(--dg-blue)] hover:opacity-90 text-white"
>
{submitting ? i18n.t('k8s.topology.saving') : editingCluster ? i18n.t('common.save') : i18n.t('common.add')}
{submitting ? '保存中...' : editingCluster ? '保存' : '添加'}
</Button>
</DialogFooter>
</DialogContent>
@@ -30,13 +30,13 @@ import {
} from 'lucide-react';
import { kubernetesApi } from '@/api';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import type { KubernetesCluster } from '@/types';
import { KubernetesClusterDetail } from './KubernetesClusterDetail';
import { KubernetesClusterDialog } from './KubernetesClusterDialog';
import { KubectlTerminal } from './KubectlTerminal';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesClusters() {
const { t } = useTranslation();
@@ -63,7 +63,7 @@ export function KubernetesClusters() {
const res: JsonData = await kubernetesApi.getClusters();
setClusters(res?.list || []);
} catch (e) {
console.error(t('kubernetes.kubernetesclusters.s64090a'), e);
console.error('加载集群列表失败:', e);
setClusters([]);
} finally {
setLoading(false);
@@ -97,18 +97,18 @@ export function KubernetesClusters() {
await kubernetesApi.deleteCluster(id);
loadData();
} catch (e) {
console.error(t('kubernetes.kubernetesclusters.s3d78e3'), e);
console.error('删除集群失败:', e);
}
};
const handleSync = async (id: number | string, silent?: boolean) => {
try {
if (!silent) toast.info(t('kubernetes.kubernetesclusters.sf31179'));
if (!silent) toast.info(t('k8s.clusters.syncing'));
const res: JsonData = await kubernetesApi.syncCluster(id);
if (!silent) toast.success(res?.message || t('kubernetes.kubernetesclusters.s02f667'));
if (!silent) toast.success(res?.message || t('k8s.clusters.syncDone'));
loadData();
} catch (e) {
if (!silent) toast.error(e?.message || t('cloud.syncFailed'));
if (!silent) toast.error(e?.message || t('k8s.clusters.syncFailed'));
}
};
@@ -117,12 +117,12 @@ export function KubernetesClusters() {
const code = exportCluster.code || String(exportCluster.id);
try {
setExporting(true);
toast.info(t('kubernetes.kubernetesclusters.s1d9a60', { exportCluster.name: exportCluster.name }));
toast.info(t('k8s.clusters.exporting', { name: exportCluster.name }));
await kubernetesApi.exportAllResources(code);
toast.success(t('kubernetes.kubernetesclusters.s10a4f7'));
toast.success(t('k8s.clusters.exportDone'));
setExportCluster(null);
} catch (e) {
toast.error(e?.message || t('common.exportFailed'));
toast.error(e?.message || t('k8s.clusters.exportFailed'));
} finally {
setExporting(false);
}
@@ -140,21 +140,21 @@ export function KubernetesClusters() {
return (
<Badge variant="outline" className="border-[var(--dg-green)]/30 text-[var(--dg-green)] bg-[var(--dg-green)]/10">
<CheckCircle className="h-3 w-3 mr-1" />
健康
{t('k8s.clusters.statusHealthy')}
</Badge>
);
case 'warning':
return (
<Badge variant="outline" className="border-[var(--dg-orange)]/30 text-[var(--dg-orange)] bg-[var(--dg-orange)]/10">
<AlertTriangle className="h-3 w-3 mr-1" />
警告
{t('k8s.clusters.statusWarning')}
</Badge>
);
case 'error':
return (
<Badge variant="outline" className="border-[var(--dg-red)]/30 text-[var(--dg-red)] bg-[var(--dg-red)]/10">
<XCircle className="h-3 w-3 mr-1" />
异常
{t('common.abnormal')}
</Badge>
);
default:
@@ -168,7 +168,7 @@ export function KubernetesClusters() {
<div className="relative w-80">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input
placeholder=t('kubernetes.kubernetesclusters.s317554')
placeholder={t('k8s.clusters.searchPlaceholder')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 dg-input"
@@ -179,21 +179,21 @@ export function KubernetesClusters() {
return (
<PageShell
variant="list"
title=t('menu.clusterList')
subtitle=t('kubernetes.kubernetesclusters.sb0fcb9')
title={t('k8s.clusters.title')}
subtitle={t('k8s.clusters.subtitle')}
icon={<Cloud className="h-5 w-5" />}
toolbar={searchToolbar}
loading={loading}
loadingLabel=t('kubernetes.kubernetesclusters.se5a067')
loadingLabel={t('k8s.clusters.loading')}
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData}>
<RefreshCw className={cn('h-4 w-4 mr-1', loading && 'animate-spin')} />
刷新
{t('common.refresh')}
</Button>
<Button size="sm" className="dg-btn-primary" onClick={() => { setEditingCluster(null); setDialogOpen(true); }}>
<Plus className="h-4 w-4 mr-1" />
添加集群
{t('k8s.clusters.add')}
</Button>
</>
)}
@@ -202,7 +202,7 @@ export function KubernetesClusters() {
<div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
{!loading && filteredClusters.length === 0 ? (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] col-span-full">
<CardContent className="p-12 text-center text-[var(--dg-text-muted)]">{t('dashboard.clusters.empty')}</CardContent>
<CardContent className="p-12 text-center text-[var(--dg-text-muted)]">{t('k8s.clusters.empty')}</CardContent>
</Card>
) : (
filteredClusters.map((cluster) => {
@@ -249,7 +249,7 @@ export function KubernetesClusters() {
<DropdownMenuSeparator className="bg-[var(--dg-border-hover)]" />
<DropdownMenuItem className="text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]">
<Eye className="h-4 w-4 mr-2" />
查看详情
{t('common.viewDetail')}
</DropdownMenuItem>
<DropdownMenuItem
className="text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]"
@@ -260,7 +260,7 @@ export function KubernetesClusters() {
}}
>
<Settings className="h-4 w-4 mr-2" />
配置
{t('common.config')}
</DropdownMenuItem>
<DropdownMenuItem
className="text-[var(--dg-cyan)] focus:bg-[var(--dg-bg-hover)]"
@@ -270,7 +270,7 @@ export function KubernetesClusters() {
}}
>
<RefreshCw className="h-4 w-4 mr-2" />
同步
{t('k8s.clusters.sync')}
</DropdownMenuItem>
<DropdownMenuItem
className="text-[var(--dg-green)] focus:bg-[var(--dg-bg-hover)]"
@@ -291,7 +291,7 @@ export function KubernetesClusters() {
}}
>
<Download className="h-4 w-4 mr-2" />
导出资源
{t('k8s.clusters.export')}
</DropdownMenuItem>
<DropdownMenuSeparator className="bg-[var(--dg-border-hover)]" />
<DropdownMenuItem
@@ -302,7 +302,7 @@ export function KubernetesClusters() {
}}
>
<Trash2 className="h-4 w-4 mr-2" />
删除
{t('common.delete')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -345,7 +345,7 @@ export function KubernetesClusters() {
<span className="text-xs text-[var(--dg-text-secondary)] w-10 text-right">{cpuUsage.toFixed(1)}%</span>
</div>
<div className="flex items-center gap-2">
<span className="text-xs text-[var(--dg-text-muted)] w-10">{t('k8s.pods.memory')}</span>
<span className="text-xs text-[var(--dg-text-muted)] w-10">{t('k8s.column.memory')}</span>
<div className="flex-1 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden">
<div
className={cn(
@@ -360,7 +360,7 @@ export function KubernetesClusters() {
</>
) : (
<div className="text-xs text-[var(--dg-text-muted)] text-center">
Ingress {cluster.ingress_count || 0} · SVC {cluster.service_count || 0} · Deployment {cluster.deployment_count || 0} · Pod {cluster.pod_count || 0} · 资源使用率待采集
Ingress {cluster.ingress_count || 0} · SVC {cluster.service_count || 0} · Deployment {cluster.deployment_count || 0} · Pod {cluster.pod_count || 0} · {t('k8s.clusters.metricsPending')}
</div>
)}
</div>
@@ -404,28 +404,27 @@ export function KubernetesClusters() {
onClick={() => { if (!exporting) setExportCluster(null); }}
>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-5 w-[420px] shadow-xl" onClick={(e) => e.stopPropagation()}>
<h3 className="text-base font-semibold text-[var(--dg-text-primary)] mb-1">{t('kubernetes.yaml.exportCluster')}</h3>
<h3 className="text-base font-semibold text-[var(--dg-text-primary)] mb-1">{t('k8s.clusters.exportTitle')}</h3>
{exporting ? (
<div className="flex flex-col items-center py-6 gap-3">
<Loader2 className="h-9 w-9 animate-spin text-[var(--dg-blue)]" />
<p className="text-sm text-[var(--dg-text-primary)]">正在导出 {exportCluster.name}</p>
<p className="text-sm text-[var(--dg-text-primary)]">{t('k8s.clusters.exportingName', { name: exportCluster.name })}</p>
<p className="text-xs text-[var(--dg-text-muted)] text-center leading-relaxed px-2">
正在拉取所有命名空间的 Deployment、Service、Ingress、ConfigMap、Secret 并打包为 tar.gz
{t('k8s.clusters.exportPulling')}
<br />
资源较多时可能需要 1~3 分钟,请稍候勿关闭页面
{t('k8s.clusters.exportWait')}
</p>
</div>
) : (
<>
<p className="text-xs text-[var(--dg-text-secondary)] mb-4 leading-relaxed">
导出 <span className="text-[var(--dg-text-primary)]">{exportCluster.name}</span> 所有命名空间的
Deployment、Service、Ingress、ConfigMap、Secret 为 tar.gz
{t('k8s.clusters.exportConfirm', { name: exportCluster.name })}
</p>
<div className="flex justify-end gap-2">
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setExportCluster(null)}>{t('common.cancel')}</Button>
<Button className="bg-[var(--dg-blue)] hover:opacity-90 text-white" onClick={handleExport}>
<Download className="h-4 w-4 mr-1.5" />
确认导出
{t('k8s.clusters.confirmExport')}
</Button>
</div>
</>
@@ -13,10 +13,8 @@ import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesNodes() {
const { t } = useTranslation();
const [clusters, setClusters] = useState<JsonData[]>([]);
const [selectedCluster, setSelectedCluster] = useState('');
const [nodes, setNodes] = useState<JsonData[]>([]);
@@ -65,14 +63,14 @@ export function KubernetesNodes() {
<div className="flex items-center gap-3 flex-wrap">
<div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder=t('k8s.topology.searchPlaceholder') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder="搜索节点..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
<Select value={roleFilter} onValueChange={setRoleFilter}>
<SelectTrigger className="w-32 h-9 dg-input">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('kubernetes.kubernetesnodes.s5bcc10')}</SelectItem>
<SelectItem value="all">全部角色</SelectItem>
<SelectItem value="master">Master</SelectItem>
<SelectItem value="worker">Worker</SelectItem>
</SelectContent>
@@ -85,14 +83,14 @@ export function KubernetesNodes() {
return (
<PageShell
variant="list"
title=t('menu.nodeManagement')
subtitle={clusterLabel ? t('kubernetes.kubernetesnodes.s055d95', { clusterLabel: clusterLabel }) : t('kubernetes.kubernetesnodes.s01b441')}
title="节点管理"
subtitle={clusterLabel ? `${clusterLabel} · 工作节点状态与资源` : 'Kubernetes 集群工作节点状态与资源'}
icon={<Server className="h-5 w-5" />}
actions={(
<>
<Select value={selectedCluster} onValueChange={setSelectedCluster}>
<SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder=t('k8s.topology.selectCluster') />
<SelectValue placeholder="选择集群" />
</SelectTrigger>
<SelectContent>
{clusters.map((c) => (
@@ -111,21 +109,21 @@ export function KubernetesNodes() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.topology.nodeName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">节点名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('pipeline.role')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.config')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('server.usage')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">角色</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">配置</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">使用率</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Pods</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Kubelet</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
) : filtered.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Server className="h-8 w-8 mx-auto mb-2 opacity-50" />{selectedCluster ? t('k8s.empty.nodes') : t('kubernetes.kubernetesnodes.sf8c388')}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center text-[var(--dg-text-muted)] py-12"><Server className="h-8 w-8 mx-auto mb-2 opacity-50" />{selectedCluster ? '暂无节点数据' : '请选择集群'}</TableCell></TableRow>
) : (
filtered.map((n) => (
<TableRow key={n.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
@@ -134,7 +132,7 @@ export function KubernetesNodes() {
<TableCell>{getRoleBadge(n.role)}</TableCell>
<TableCell>{getStatusBadge(n.status)}</TableCell>
<TableCell className="text-sm text-[var(--dg-text-secondary)]">
{n.cpu ? t('kubernetes.kubernetesnodes.s90ecb6', { n.cpu: n.cpu }) : '-'} / {n.memory ? `${Math.round(n.memory / 1024)}GB` : '-'}
{n.cpu ? `${n.cpu}核` : '-'} / {n.memory ? `${Math.round(n.memory / 1024)}GB` : '-'}
</TableCell>
<TableCell>
{(() => {
@@ -24,9 +24,9 @@ import {
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
import { DeploymentDetail } from './DeploymentDetail';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export function KubernetesWorkloads() {
const { t } = useTranslation();
@@ -121,7 +121,7 @@ export function KubernetesWorkloads() {
const newReplicas = (dep.replicas || 0) + delta;
if (newReplicas < 0) return;
await kubernetesApi.scaleDeployment(selectedCluster, dep.namespace, dep.name, newReplicas);
toast({ title: t('kubernetes.kubernetesworkloads.s0b3ea1'), description: t('kubernetes.kubernetesworkloads.scf7f1c', { dep.name: dep.name, newReplicas: newReplicas }) });
toast({ title: t('k8s.workloads.scaleSuccess'), description: t('k8s.workloads.scaleDesc', { name: dep.name, count: newReplicas }) });
loadData();
} catch (e) {
toast({ title: t('common.operationFailed'), description: e?.message || String(e), variant: 'destructive' });
@@ -146,13 +146,13 @@ export function KubernetesWorkloads() {
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">{t('menu.workloads')}</h1>
<p className="text-sm dg-text-muted mt-1">{t('kubernetes.kubernetesworkloads.sf90ced')}</p>
<h1 className="text-2xl font-bold text-[var(--dg-text-primary)]">{t('k8s.workloads.title')}</h1>
<p className="text-sm dg-text-muted mt-1">{t('k8s.workloads.subtitle')}</p>
</div>
<div className="flex items-center gap-2">
<Select value={selectedCluster} onValueChange={(v) => { setSelectedCluster(v); setSelectedNamespace('all'); }}>
<SelectTrigger className="w-48 h-9 dg-input">
<SelectValue placeholder=t('k8s.topology.selectCluster') />
<SelectValue placeholder={t('k8s.workloads.selectCluster')} />
</SelectTrigger>
<SelectContent className="dg-input">
{clusters.map((c) => (
@@ -162,10 +162,10 @@ export function KubernetesWorkloads() {
</Select>
<Select value={selectedNamespace} onValueChange={setSelectedNamespace}>
<SelectTrigger className="w-40 h-9 dg-input">
<SelectValue placeholder=t('k8s.column.namespace') />
<SelectValue placeholder={t('k8s.workloads.namespace')} />
</SelectTrigger>
<SelectContent className="dg-input max-h-[300px]">
<SelectItem value="all">{t('kubernetes.namespace.allNamespaces')}</SelectItem>
<SelectItem value="all">{t('k8s.workloads.allNamespaces')}</SelectItem>
{namespaces.map((ns) => (
<SelectItem key={ns} value={ns}>{ns}</SelectItem>
))}
@@ -180,7 +180,7 @@ export function KubernetesWorkloads() {
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{[
{ label: 'Deployment', value: deployments.length, icon: <Boxes className="h-5 w-5" />, color: 'text-rose-400' },
{ label: t('kubernetes.kubernetesworkloads.s83481f'), value: pods.length, icon: <Container className="h-5 w-5" />, color: 'dg-text-blue' },
{ label: t('k8s.workloads.podTotal'), value: pods.length, icon: <Container className="h-5 w-5" />, color: 'dg-text-blue' },
{ label: 'Running', value: pods.filter((p) => p.status === 'Running').length, icon: <Container className="h-5 w-5" />, color: 'dg-text-green' },
{ label: t('common.abnormal'), value: pods.filter((p) => ['Failed', 'Pending'].includes(p.status)).length, icon: <Container className="h-5 w-5" />, color: 'dg-text-red' },
].map((s) => (
@@ -200,7 +200,7 @@ export function KubernetesWorkloads() {
<div className="relative w-56">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder=t('kubernetes.kubernetesworkloads.s64e327') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder={t('common.search') + '...'} value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
<Tabs value={activeTab} onValueChange={setActiveTab}>
@@ -217,7 +217,7 @@ export function KubernetesWorkloads() {
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.kubernetesworkloads.s0428b3')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.replicas')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
<TableHead className="dg-text-secondary w-[140px]">{t('common.actions')}</TableHead>
</TableRow>
@@ -226,7 +226,7 @@ export function KubernetesWorkloads() {
{loading ? (
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filteredDeps.length === 0 ? (
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Boxes className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('kubernetes.kubernetesworkloads.s5689d3')}</TableCell></TableRow>
<TableRow><TableCell colSpan={5} className="text-center dg-text-muted py-12"><Boxes className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.workloads.noDeployment')}</TableCell></TableRow>
) : (
filteredDeps.map((d) => (
<TableRow key={d.id || d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer"
@@ -253,16 +253,16 @@ export function KubernetesWorkloads() {
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:text-[var(--dg-text-primary)]"
title=t('kubernetes.kubernetesworkloads.sd4db1c') disabled={(d.replicas || 0) <= 0}
title={t('k8s.workloads.decreaseReplica')} disabled={(d.replicas || 0) <= 0}
onClick={() => handleQuickScale(d, -1)}>
<Minus className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:text-[var(--dg-text-primary)]"
title=t('kubernetes.kubernetesworkloads.se80820') onClick={() => handleQuickScale(d, 1)}>
title={t('k8s.workloads.increaseReplica')} onClick={() => handleQuickScale(d, 1)}>
<Plus className="h-3.5 w-3.5" />
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary hover:dg-text-blue"
title=t('common.viewDetail') onClick={() => setSelectedDeployment({ name: d.name, namespace: d.namespace })}>
title={t('common.viewDetail')} onClick={() => setSelectedDeployment({ name: d.name, namespace: d.namespace })}>
<Eye className="h-3.5 w-3.5" />
</Button>
</div>
@@ -285,10 +285,10 @@ export function KubernetesWorkloads() {
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.tab.nodes')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.node')}</TableHead>
<TableHead className="dg-text-secondary">CPU</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.memory')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.reboot')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.memory')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.restartCount')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.image')}</TableHead>
</TableRow>
</TableHeader>
@@ -296,7 +296,7 @@ export function KubernetesWorkloads() {
{loading ? (
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
) : filteredPods.length === 0 ? (
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Container className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.deploymentDetail.noPod')}</TableCell></TableRow>
<TableRow><TableCell colSpan={8} className="text-center dg-text-muted py-12"><Container className="h-8 w-8 mx-auto mb-2 opacity-50" />{t('k8s.workloads.noPod')}</TableCell></TableRow>
) : (
filteredPods.map((p) => (
<TableRow key={p.id} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]">
@@ -19,7 +19,6 @@ import { toast } from 'sonner';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import { useTranslation } from 'react-i18next';
interface NamespaceDetail {
name: string;
@@ -40,7 +39,6 @@ const SYSTEM_NAMESPACES = new Set([
]);
export default function NamespaceManagementPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [namespaces, setNamespaces] = useState<NamespaceDetail[]>([]);
@@ -80,7 +78,7 @@ export default function NamespaceManagementPage() {
setCreateOpen(false);
await loadData();
} catch (err) {
toast.error(err?.message || t('monitor.quickSetupFailed'));
toast.error(err?.message || '创建失败');
} finally {
setCreating(false);
}
@@ -94,7 +92,7 @@ export default function NamespaceManagementPage() {
setDeleteTarget(null);
await loadData();
} catch (err) {
toast.error(err?.message || t('common.deleteFailed'));
toast.error(err?.message || '删除失败');
} finally {
setDeleting(false);
}
@@ -113,7 +111,7 @@ export default function NamespaceManagementPage() {
<Input
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder=t('kubernetes.namespacemanagementpage.se91247')
placeholder="搜索命名空间..."
className="max-w-xs dg-input"
/>
);
@@ -121,17 +119,17 @@ export default function NamespaceManagementPage() {
return (
<PageShell
variant="list"
title=t('kubernetes.namespacemanagementpage.se935a3')
subtitle={t('kubernetes.namespacemanagementpage.s81e4b3', { clusterCode: clusterCode })}
title="命名空间管理"
subtitle={`${clusterCode} · 资源配额与生命周期管理`}
icon={<Boxes className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: t('k8s.column.namespace'), value: namespaces.length, color: 'green' },
{ label: '命名空间', value: namespaces.length, color: 'green' },
{ label: 'Deployments', value: totalDeploys, color: 'blue' },
{ label: 'Pods', value: totalPods, color: 'purple' },
{ label: 'Services', value: totalSvcs, color: 'cyan' },
{ label: t('kubernetes.namespacemanagementpage.s47c3ae'), value: quotaCount, color: 'amber' },
{ label: '配额限制', value: quotaCount, color: 'amber' },
]}
/>
) : undefined}
@@ -149,15 +147,15 @@ export default function NamespaceManagementPage() {
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('kubernetes.namespacemanagementpage.s737f41')}</DialogTitle>
<DialogTitle>创建命名空间</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label>{t('kubernetes.namespace.namespaceName')}</Label>
<Label>命名空间名称</Label>
<Input
value={newName}
onChange={(e) => setNewName(e.target.value)}
placeholder=t('kubernetes.namespacemanagementpage.scba008')
placeholder="例如: my-app"
onKeyDown={(e) => e.key === 'Enter' && handleCreate()}
/>
<p className="text-xs text-[var(--dg-text-muted)]">
@@ -166,7 +164,7 @@ export default function NamespaceManagementPage() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setCreateOpen(false)}>{t('common.cancel')}</Button>
<Button variant="outline" onClick={() => setCreateOpen(false)}>取消</Button>
<Button onClick={handleCreate} disabled={creating || !newName.trim()}>
{creating ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
创建
@@ -181,15 +179,15 @@ export default function NamespaceManagementPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.namespacemanagementpage.sa01a99')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">年龄</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Deploy</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Pods</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">Svc</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">{t('common.quota')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.tag')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">{t('common.actions')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">配额</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">标签</TableHead>
<TableHead className="text-[var(--dg-text-secondary)] text-center">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -249,13 +247,13 @@ export default function NamespaceManagementPage() {
</TableCell>
<TableCell className="text-center">
{isSystem ? (
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.system3')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">系统</span>
) : (
<Button
variant="ghost" size="icon"
className="h-7 w-7 text-[var(--dg-red)] hover:text-[var(--dg-red)] hover:bg-[var(--dg-red)]/10"
onClick={() => setDeleteTarget(ns.name)}
title=t('kubernetes.namespace.deleteNamespace')
title="删除命名空间"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
@@ -288,7 +286,7 @@ export default function NamespaceManagementPage() {
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>{t('common.cancel')}</Button>
<Button variant="outline" onClick={() => setDeleteTarget(null)}>取消</Button>
<Button variant="destructive" onClick={handleDelete} disabled={deleting}>
{deleting ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : null}
确认删除
@@ -16,22 +16,19 @@ import {
import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
const RESOURCE_LINKS = [
{ type: 'deployments', label: 'Deployments', icon: Boxes, desc: i18n.t('kubernetes.namespaceoverviewpage.sb68c63') },
{ type: 'pods', label: 'Pods', icon: Container, desc: i18n.t('kubernetes.namespaceoverviewpage.sfdac25') },
{ type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: i18n.t('kubernetes.namespaceoverviewpage.s9c9fc5') },
{ type: 'services', label: 'Services', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.s3a3f6d') },
{ type: 'ingresses', label: 'Ingresses', icon: Network, desc: i18n.t('kubernetes.namespaceoverviewpage.scc6971') },
{ type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: i18n.t('kubernetes.namespaceoverviewpage.s0986a6') },
{ type: 'secrets', label: 'Secrets', icon: Shield, desc: i18n.t('kubernetes.namespaceoverviewpage.sb3fb72') },
{ type: 'hpas', label: 'HPAs', icon: Activity, desc: i18n.t('kubernetes.namespaceoverviewpage.sa84da2') },
{ type: 'deployments', label: 'Deployments', icon: Boxes, desc: '工作负载副本管理' },
{ type: 'pods', label: 'Pods', icon: Container, desc: '容器实例运行状态' },
{ type: 'cronjobs', label: 'CronJobs', icon: Clock, desc: '定时任务管理' },
{ type: 'services', label: 'Services', icon: Network, desc: '服务发现与负载均衡' },
{ type: 'ingresses', label: 'Ingresses', icon: Network, desc: '外部流量路由规则' },
{ type: 'configmaps', label: 'ConfigMaps', icon: FileText, desc: '配置字典' },
{ type: 'secrets', label: 'Secrets', icon: Shield, desc: '密钥与凭证' },
{ type: 'hpas', label: 'HPAs', icon: Activity, desc: '水平自动伸缩策略' },
];
export default function NamespaceOverviewPage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const [counts, setCounts] = useState<Record<string, number>>({});
const [loading, setLoading] = useState(false);
@@ -69,11 +66,11 @@ export default function NamespaceOverviewPage() {
return (
<PageShell
variant="default"
title={namespace || t('k8s.column.namespace')}
subtitle={t('kubernetes.namespaceoverviewpage.s6d60aa', { clusterCode: clusterCode })}
title={namespace || '命名空间'}
subtitle={`${clusterCode} · 命名空间概览`}
icon={<Cloud className="h-5 w-5" />}
loading={loading}
loadingLabel=t('kubernetes.namespaceoverviewpage.sfa525a')
loadingLabel="加载资源统计..."
>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
{RESOURCE_LINKS.map((r) => (
@@ -25,8 +25,6 @@ import { useToast } from '@/hooks/use-toast';
import { useConfirm } from '@/components/ui/confirm-dialog';
import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
type ResourceType =
| 'deployments' | 'pods' | 'services' | 'ingresses'
@@ -45,8 +43,8 @@ const BULK_EXPORT_TYPES: ResourceType[] = ['services', 'ingresses', 'configmaps'
const VisualActions = ({ name, opts }: { name: string; opts: { onYaml?: (n: string) => void; onEdit?: (n: string) => void } }) => (
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('k8s.resource.visualEditor')
onClick={() => opts.onEdit?.(name)}><Pencil className="h-3.5 w-3.5 mr-1" />{i18n.t('common.edit')}</Button>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="可视化编辑"
onClick={() => opts.onEdit?.(name)}><Pencil className="h-3.5 w-3.5 mr-1" />编辑</Button>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-secondary)]" title="YAML"
onClick={() => opts.onYaml?.(name)}><FileCode className="h-3.5 w-3.5 mr-1" />YAML</Button>
</div>
@@ -60,8 +58,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
renderRow: ( item: any, opts: { clusterCode: string; namespace: string; onDetail?: ( item: any) => void; onYaml?: (name: string) => void; onEdit?: (name: string) => void; onTerminal?: ( item: any) => void; onFileBrowser?: ( item: any) => void; onDeletePod?: ( item: any) => void; onPodDetail?: ( item: any) => void }) => React.ReactNode;
}> = {
deployments: {
title: 'Deployments', subtitle: i18n.t('kubernetes.namespaceresourcepage.s35c744'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s0428b3'), i18n.t('k8s.column.image')],
title: 'Deployments', subtitle: 'Deployment 工作负载运行状态', icon: Boxes,
columns: ['名称', '命名空间', '副本', '镜像'],
renderRow: (d, opts) => (
<TableRow key={d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(d)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -85,8 +83,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
pods: {
title: 'Pods', subtitle: i18n.t('kubernetes.namespaceresourcepage.s780b7d'), icon: Container,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.status'), i18n.t('k8s.tab.nodes'), 'CPU', i18n.t('k8s.pods.memory'), i18n.t('common.reboot'), i18n.t('k8s.column.image'), i18n.t('common.actions')],
title: 'Pods', subtitle: 'Pod 实例运行状态', icon: Container,
columns: ['名称', '命名空间', '状态', '节点', 'CPU', '内存', '重启', '镜像', '操作'],
renderRow: (p, opts) => {
const statusMap: Record<string, string> = { Running: 'bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30', Pending: 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30', Failed: 'bg-[var(--dg-red)]/20 text-[var(--dg-red)] border-[var(--dg-red)]/30' };
return (
@@ -106,13 +104,13 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)] max-w-[200px] truncate">{p.image || '-'}</TableCell>
<TableCell>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-green)]" title=i18n.t('kubernetes.pod.terminal')
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-green)]" title="终端"
onClick={() => (opts as Record<string, any>).onTerminal?.(p)}><Terminal className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-orange)]" title=i18n.t('k8s.pods.action.file')
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-orange)]" title="文件"
onClick={() => (opts as Record<string, any>).onFileBrowser?.(p)}><HardDrive className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-blue)]" title="YAML"
onClick={() => opts.onYaml?.(p.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-red)] hover:text-[var(--dg-red)]" title=i18n.t('common.delete')
<Button variant="ghost" size="sm" className="h-7 w-7 p-0 shrink-0 text-[var(--dg-red)] hover:text-[var(--dg-red)]" title="删除"
onClick={() => opts.onDeletePod?.(p)}><Trash2 className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -121,8 +119,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
services: {
title: 'Services', subtitle: i18n.t('kubernetes.namespaceresourcepage.s5e76b6'), icon: Network,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.type'), 'Cluster IP', i18n.t('server.csv.port'), i18n.t('common.actions')],
title: 'Services', subtitle: 'Service 网络服务', icon: Network,
columns: ['名称', '命名空间', '类型', 'Cluster IP', '端口', '操作'],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -135,8 +133,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
ingresses: {
title: 'Ingresses', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8d5014'), icon: Network,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), 'Hosts', 'TLS', i18n.t('common.actions')],
title: 'Ingresses', subtitle: 'Ingress 路由规则', icon: Network,
columns: ['名称', '命名空间', 'Hosts', 'TLS', '操作'],
renderRow: (i, opts) => {
const hosts = i.hosts || [];
return (
@@ -151,8 +149,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
configmaps: {
title: 'ConfigMaps', subtitle: i18n.t('kubernetes.namespaceresourcepage.s0986a6'), icon: FileText,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.sbd1fa0'), i18n.t('common.actions')],
title: 'ConfigMaps', subtitle: '配置字典', icon: FileText,
columns: ['名称', '命名空间', '键数量', '操作'],
renderRow: (c, opts) => (
<TableRow key={c.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{c.name}</TableCell>
@@ -163,8 +161,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
secrets: {
title: 'Secrets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sd1424a'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.type'), i18n.t('common.actions')],
title: 'Secrets', subtitle: '密钥管理(仅名称与类型)', icon: Shield,
columns: ['名称', '命名空间', '类型', '操作'],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -175,8 +173,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
hpas: {
title: 'HPAs', subtitle: i18n.t('kubernetes.namespaceresourcepage.s9abc8d'), icon: Activity,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.target'), i18n.t('k8s.hpaCronHpa.col.minMax'), 'CPU%', 'Mem%'],
title: 'HPAs', subtitle: '水平自动伸缩', icon: Activity,
columns: ['名称', '命名空间', '目标', '最小/最大', 'CPU%', 'Mem%'],
renderRow: (h, _opts) => (
<TableRow key={h.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{h.name}</TableCell>
@@ -189,21 +187,21 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
cronjobs: {
title: 'CronJobs', subtitle: i18n.t('menu.cronJobs'), icon: Clock,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('k8s.workload.scheduling'), i18n.t('common.status'), i18n.t('common.lastRun')],
title: 'CronJobs', subtitle: '定时任务', icon: Clock,
columns: ['名称', '命名空间', '调度', '状态', '上次执行'],
renderRow: (cj) => (
<TableRow key={cj.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{cj.name}</TableCell>
<TableCell><Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{cj.namespace}</Badge></TableCell>
<TableCell className="text-sm font-mono text-[var(--dg-text-secondary)]">{cj.schedule || '-'}</TableCell>
<TableCell><Badge className={cj.suspend ? 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)]' : 'bg-[var(--dg-green)]/20 text-[var(--dg-green)]'}>{cj.suspend ? i18n.t('kubernetes.deployment.paused') : i18n.t('common.running')}</Badge></TableCell>
<TableCell><Badge className={cj.suspend ? 'bg-[var(--dg-orange)]/20 text-[var(--dg-orange)]' : 'bg-[var(--dg-green)]/20 text-[var(--dg-green)]'}>{cj.suspend ? '已暂停' : '运行中'}</Badge></TableCell>
<TableCell className="text-sm text-[var(--dg-text-secondary)]">{cj.last_schedule || '-'}</TableCell>
</TableRow>
),
},
pvcs: {
title: i18n.t('kubernetes.namespaceresourcepage.s18c900'), subtitle: 'PersistentVolumeClaim', icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('common.status'), i18n.t('deploy.table.size'), 'StorageClass', i18n.t('common.actions')],
title: '存储卷声明', subtitle: 'PersistentVolumeClaim', icon: Boxes,
columns: ['名称', '命名空间', '状态', '大小', 'StorageClass', '操作'],
renderRow: (p, opts) => (
<TableRow key={p.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{p.name}</TableCell>
@@ -216,8 +214,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
statefulsets: {
title: 'StatefulSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.sbfeb44'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s0428b3'), i18n.t('common.ready'), i18n.t('k8s.column.image')],
title: 'StatefulSets', subtitle: '有状态应用', icon: Boxes,
columns: ['名称', '命名空间', '副本', '就绪', '镜像'],
renderRow: (s, opts) => (
<TableRow key={s.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(s)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{s.name}</TableCell>
@@ -229,8 +227,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
daemonsets: {
title: 'DaemonSets', subtitle: i18n.t('kubernetes.namespaceresourcepage.se1c074'), icon: Boxes,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('monitor.siteProtocol.http.expectedPrefix'), i18n.t('common.current'), i18n.t('common.ready'), i18n.t('k8s.column.image')],
title: 'DaemonSets', subtitle: '守护进程集', icon: Boxes,
columns: ['名称', '命名空间', '期望', '当前', '就绪', '镜像'],
renderRow: (d, opts) => (
<TableRow key={d.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30 cursor-pointer" onClick={() => opts.onDetail?.(d)}>
<TableCell className="font-medium text-[var(--dg-text-primary)]">{d.name}</TableCell>
@@ -243,8 +241,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
),
},
serviceaccounts: {
title: 'ServiceAccounts', subtitle: i18n.t('kubernetes.namespaceresourcepage.s645c9a'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.sbaf7ed'), i18n.t('kubernetes.namespaceresourcepage.s260c11'), i18n.t('common.createdAt'), i18n.t('common.actions')],
title: 'ServiceAccounts', subtitle: '服务账号(RBAC 身份标识)', icon: Shield,
columns: ['名称', '命名空间', 'Secret数', '镜像拉取凭证', '创建时间', '操作'],
renderRow: (sa, opts) => (
<TableRow key={sa.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{sa.name}</TableCell>
@@ -255,15 +253,15 @@ const RESOURCE_CONFIG: Record<ResourceType, {
</TableCell>
<TableCell className="text-xs text-[var(--dg-text-muted)]">{sa.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
onClick={() => opts.onYaml?.(sa.name)}><FileCode className="h-3.5 w-3.5" /></Button>
</TableCell>
</TableRow>
),
},
roles: {
title: 'Roles', subtitle: i18n.t('kubernetes.namespaceresourcepage.s8905a6'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.secde03'), i18n.t('system.apiKeyScope'), i18n.t('common.createdAt'), i18n.t('common.actions')],
title: 'Roles', subtitle: '命名空间级角色权限(RBAC)', icon: Shield,
columns: ['名称', '命名空间', '规则数', '权限范围', '创建时间', '操作'],
renderRow: (r, opts) => {
const verbs = r.verbs || [];
const resources = r.resources || [];
@@ -283,9 +281,9 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)]">{r.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
onClick={() => opts.onYaml?.(r.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('common.edit')
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="编辑"
onClick={() => opts.onEdit?.(r.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -294,8 +292,8 @@ const RESOURCE_CONFIG: Record<ResourceType, {
},
},
rolebindings: {
title: 'RoleBindings', subtitle: i18n.t('kubernetes.namespaceresourcepage.sca10fe'), icon: Shield,
columns: [i18n.t('common.name'), i18n.t('k8s.column.namespace'), i18n.t('kubernetes.namespaceresourcepage.s227e5e'), i18n.t('kubernetes.namespaceresourcepage.s2667c7'), i18n.t('common.createdAt'), i18n.t('common.actions')],
title: 'RoleBindings', subtitle: '角色绑定关系(RBAC 授权)', icon: Shield,
columns: ['名称', '命名空间', '角色引用', '绑定主体', '创建时间', '操作'],
renderRow: (rb, opts) => {
const subjects = rb.subjects || [];
const subjStr = subjects.length > 3 ? subjects.slice(0, 3).join(', ') + ` +${subjects.length - 3}` : subjects.join(', ');
@@ -314,9 +312,9 @@ const RESOURCE_CONFIG: Record<ResourceType, {
<TableCell className="text-xs text-[var(--dg-text-muted)]">{rb.age || '-'}</TableCell>
<TableCell onClick={(e) => e.stopPropagation()}>
<div className="flex items-center gap-0.5">
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title=i18n.t('kubernetes.namespaceresourcepage.s4bde08')
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]" title="查看YAML"
onClick={() => opts.onYaml?.(rb.name)}><FileCode className="h-3.5 w-3.5" /></Button>
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title=i18n.t('common.edit')
<Button variant="ghost" size="icon" className="h-7 w-7 text-[var(--dg-green)] hover:text-[var(--dg-green)]" title="编辑"
onClick={() => opts.onEdit?.(rb.name)}><Pencil className="h-3.5 w-3.5" /></Button>
</div>
</TableCell>
@@ -327,7 +325,6 @@ const RESOURCE_CONFIG: Record<ResourceType, {
};
export default function NamespaceResourcePage() {
const { t } = useTranslation();
const { clusterCode, namespace } = useParams<{ clusterCode: string; namespace: string }>();
const location = useLocation();
const navigate = useNavigate();
@@ -442,26 +439,26 @@ export default function NamespaceResourcePage() {
if (!clusterCode || !namespace) return;
try {
await kubernetesApi.exportNamespaceResources(clusterCode, namespace);
toast({ title: t('common.exportComplete'), description: t('kubernetes.namespaceresourcepage.sadafd4', { namespace: namespace }) });
toast({ title: '导出完成', description: `${namespace} 资源 YAML 已开始下载` });
} catch (e) {
toast({ title: t('common.exportFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: '导出失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
}
};
// Pod 删除 // Logan.Li
const handleDeletePod = async (p: any) => {
const ok = await confirm({
title: t('kubernetes.pod.deletePod'),
description: t('kubernetes.namespaceresourcepage.sc5bb25') + (p.name || '') + t('kubernetes.namespaceresourcepage.s3ec1f4'),
confirmText: t('common.delete'),
title: '删除 Pod',
description: '确认删除 Pod "' + (p.name || '') + '"?操作不可恢复。',
confirmText: '删除',
});
if (!ok) return;
try {
await kubernetesApi.deletePod(clusterCode || '', namespace || '', p.name);
toast({ title: t('kubernetes.pod.deleted') });
toast({ title: 'Pod 已删除' });
loadData();
} catch (e) {
toast({ title: t('common.deleteFailed'), description: (e as any)?.message || String(e), variant: 'destructive' });
toast({ title: '删除失败', description: (e as any)?.message || String(e), variant: 'destructive' });
}
};
@@ -470,7 +467,7 @@ export default function NamespaceResourcePage() {
const searchToolbar = (
<div className="relative w-56 flex-1 min-w-[200px] max-w-xs">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 dg-text-muted" />
<Input placeholder=t('kubernetes.namespaceresourcepage.s64e327') value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
<Input placeholder="搜索..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9 h-9 dg-input" />
</div>
);
@@ -485,11 +482,11 @@ export default function NamespaceResourcePage() {
actions={(
<>
<Select value={clusterCode || ''} onValueChange={(v) => navigate(`/kubernetes/${v}/namespace/${namespace || 'default'}/${type}`)}>
<SelectTrigger className="w-48 h-9 dg-input"><SelectValue placeholder=t('k8s.topology.selectCluster') /></SelectTrigger>
<SelectTrigger className="w-48 h-9 dg-input"><SelectValue placeholder="选择集群" /></SelectTrigger>
<SelectContent>{clusters.map((c) => <SelectItem key={c.id} value={c.code || String(c.id)}>{c.name}</SelectItem>)}</SelectContent>
</Select>
<Select value={namespace || ''} onValueChange={(v) => navigate(`/kubernetes/${clusterCode}/namespace/${v}/${type}`)}>
<SelectTrigger className="w-40 h-9 dg-input"><SelectValue placeholder=t('k8s.column.namespace') /></SelectTrigger>
<SelectTrigger className="w-40 h-9 dg-input"><SelectValue placeholder="命名空间" /></SelectTrigger>
<SelectContent className="max-h-[300px]">{namespaces.map((ns) => <SelectItem key={ns} value={ns}>{ns}</SelectItem>)}</SelectContent>
</Select>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={loadData} disabled={loading}>
@@ -498,16 +495,16 @@ export default function NamespaceResourcePage() {
</Button>
{BULK_EXPORT_TYPES.includes(type) && (
<>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportCSV} title=t('kubernetes.namespaceresourcepage.sef28d5')>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportCSV} title="导出CSV">
<Download className="h-3 w-3 mr-1" />CSV
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportJSON} title=t('kubernetes.namespaceresourcepage.se11b48')>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportJSON} title="导出JSON">
<Download className="h-3 w-3 mr-1" />JSON
</Button>
</>
)}
{EXPORT_YAML_TYPES.includes(type) && (
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportYaml} title=t('kubernetes.namespaceresourcepage.s2f8992')>
<Button variant="outline" size="sm" className="dg-btn-secondary text-xs" onClick={handleExportYaml} title="导出命名空间 YAML(tar.gz)">
<Download className="h-3 w-3 mr-1" />导出YAML
</Button>
)}
@@ -559,7 +556,7 @@ export default function NamespaceResourcePage() {
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">{config.columns.map((col) => <TableHead key={col} className="text-[var(--dg-text-secondary)]">{col}</TableHead>)}</TableRow></TableHeader>
<TableBody>
{loading ? (
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />{t('common.loading')}</TableCell></TableRow>
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />加载中...</TableCell></TableRow>
) : filtered.length === 0 ? (
<TableRow><TableCell colSpan={config.columns.length} className="text-center text-[var(--dg-text-muted)] py-12"><config.icon className="h-8 w-8 mx-auto mb-2 opacity-50" />暂无 {config.title}</TableCell></TableRow>
) : (
@@ -601,7 +598,7 @@ export default function NamespaceResourcePage() {
<div className="p-5 space-y-5">
{/* 基本信息 */}
<div>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{t('deploy.label.basicInfo')}</h4>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">基本信息</h4>
{(() => {
const p = podDetail;
const labels = p.labels || p.metadata?.labels || {};
@@ -612,23 +609,23 @@ export default function NamespaceResourcePage() {
return (
<div className="grid grid-cols-2 gap-x-6 gap-y-2.5">
<div>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.name')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">名称</span>
<p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.name || '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">{t('k8s.column.namespace')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">命名空间</span>
<p className="text-sm text-[var(--dg-text-primary)]">{p.namespace || '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.status')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">状态</span>
<div><Badge className={statusMap[st] || 'bg-[var(--dg-text-muted)]/20 text-[var(--dg-text-secondary)]'}>{st}</Badge></div>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.createdAt')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">创建时间</span>
<p className="text-sm text-[var(--dg-text-primary)]">{created ? new Date(created).toLocaleString('zh-CN') : '-'}</p>
</div>
<div>
<span className="text-xs text-[var(--dg-text-muted)]">{t('k8s.tab.nodes')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">节点</span>
<p className="text-sm text-[var(--dg-text-primary)]">{p.node_name || p.node || '-'}</p>
</div>
<div>
@@ -636,7 +633,7 @@ export default function NamespaceResourcePage() {
<p className="text-sm text-[var(--dg-text-primary)] font-mono">{p.ip || p.pod_ip || '-'}</p>
</div>
<div className="col-span-2">
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.tag')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">标签</span>
<div className="flex flex-wrap gap-1 mt-0.5">
{Object.keys(labels).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(labels).map(([k, v]) => (
@@ -646,7 +643,7 @@ export default function NamespaceResourcePage() {
</div>
</div>
<div className="col-span-2">
<span className="text-xs text-[var(--dg-text-muted)]">{t('common.annotation')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">注解</span>
<div className="flex flex-wrap gap-1 mt-0.5">
{Object.keys(annotations).length === 0 ? <span className="text-xs text-[var(--dg-text-muted)]">-</span>
: Object.entries(annotations).slice(0, 6).map(([k, v]) => (
@@ -662,19 +659,19 @@ export default function NamespaceResourcePage() {
{/* 现状详情(Conditions) */}
<div>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">{t('kubernetes.namespaceresourcepage.s1d8d6e')}</h4>
<h4 className="text-sm font-medium text-[var(--dg-text-primary)] mb-3">现状详情</h4>
{(() => {
const cond: any[] = podDetail.conditions || podDetail.pod_conditions || [];
if (cond.length === 0) return <p className="text-xs text-[var(--dg-text-muted)] py-2">{t('common.noData')}</p>;
if (cond.length === 0) return <p className="text-xs text-[var(--dg-text-muted)] py-2">暂无数据</p>;
return (
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.type')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('common.updatedAt')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventReason')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">{t('kubernetes.event.eventMessage')}</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">类型</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">状态</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">更新时间</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">原因</TableHead>
<TableHead className="text-[var(--dg-text-muted)] text-xs">消息</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -705,7 +702,7 @@ export default function NamespaceResourcePage() {
</div>
</div>
<div className="flex justify-end px-5 py-3 border-t border-[var(--dg-border)]">
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setPodDetail(null)}>{t('common.close')}</Button>
<Button variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setPodDetail(null)}>关闭</Button>
</div>
</div>
</div>
@@ -22,10 +22,8 @@ import {
import { kubernetesApi } from '@/api';
import { PageShell } from '@/components/layout/PageShell';
import { useTranslation } from 'react-i18next';
export default function NodeDetailPage() {
const { t } = useTranslation();
const { clusterCode, nodeName } = useParams<{ clusterCode: string; nodeName: string }>();
const navigate = useNavigate();
const [data, setData] = useState<any>(null);
@@ -97,11 +95,11 @@ export default function NodeDetailPage() {
return (
<PageShell
variant="default"
title={nodeName || t('kubernetes.nodedetailpage.sb88b98')}
title={nodeName || '节点详情'}
subtitle={nodeSubtitle || clusterCode}
icon={<Server className="h-5 w-5" />}
loading={loading && !data}
loadingLabel=t('kubernetes.nodedetailpage.sfdff61')
loadingLabel="加载节点详情..."
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -145,7 +143,7 @@ export default function NodeDetailPage() {
</h2>
<div className="space-y-2 text-xs">
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">{t('kubernetes.node.containerRuntime')}</span>
<span className="dg-text-muted">容器运行时</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.container_runtime || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
@@ -153,19 +151,19 @@ export default function NodeDetailPage() {
<span className="text-[var(--dg-text-secondary)] font-mono">{data.kubelet_version || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">{t('server.csv.os')}</span>
<span className="dg-text-muted">操作系统</span>
<span className="text-[var(--dg-text-secondary)]">{data.os_image || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">{t('monitor.systemInfo.kernel')}</span>
<span className="dg-text-muted">内核版本</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.kernel_version || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">{t('agent.agentArch')}</span>
<span className="dg-text-muted">架构</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{data.architecture || '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5 border-b border-[var(--dg-border)]/50">
<span className="dg-text-muted">{t('common.createdAt')}</span>
<span className="dg-text-muted">创建时间</span>
<span className="text-[var(--dg-text-secondary)]">{data.creation_time ? new Date(data.creation_time).toLocaleString('zh-CN') : '-'}</span>
</div>
<div className="flex items-center justify-between py-1.5">
@@ -185,9 +183,9 @@ export default function NodeDetailPage() {
<div className="space-y-4 mt-4">
{/* CPU allocation (requested vs allocatable) */}
<ResourceBar
label=t('kubernetes.nodedetailpage.s7c3900')
used={t('kubernetes.nodedetailpage.s8c635b', { (data.cpu_request_m / 1000).toFixed(2): (data.cpu_request_m / 1000).toFixed(2) })}
total={t('kubernetes.nodedetailpage.s3523f6', { data.cpu_allocatable: data.cpu_allocatable })}
label="CPU 已分配"
used={`${(data.cpu_request_m / 1000).toFixed(2)} 核`}
total={`${data.cpu_allocatable} 核`}
unit=""
pct={data.cpu_alloc_pct}
color="dg-text-green"
@@ -195,9 +193,9 @@ export default function NodeDetailPage() {
{/* CPU real usage (from metrics) */}
{data.cpu_usage_m && (
<ResourceBar
label=t('kubernetes.nodedetailpage.s1ce996')
label="CPU 实时使用"
used={data.cpu_usage_m}
total={t('kubernetes.nodedetailpage.s2d6586', { data.cpu_capacity: data.cpu_capacity })}
total={`${data.cpu_capacity} 核`}
unit=""
pct={(parseFloat(data.cpu_usage_m.replace('m', '')) / (data.cpu_capacity * 1000)) * 100}
color="dg-text-blue"
@@ -205,7 +203,7 @@ export default function NodeDetailPage() {
)}
{/* Memory allocation */}
<ResourceBar
label=t('kubernetes.nodedetailpage.sccf1cf')
label="内存已分配"
used={`${data.mem_request_mi} Mi`}
total={`${data.mem_allocatable_mb} Mi`}
unit=""
@@ -215,7 +213,7 @@ export default function NodeDetailPage() {
{/* Memory real usage */}
{data.mem_usage_mi && (
<ResourceBar
label=t('kubernetes.nodedetailpage.s841b8a')
label="内存实时使用"
used={data.mem_usage_mi}
total={`${data.mem_capacity_mb} Mi`}
unit=""
@@ -225,7 +223,7 @@ export default function NodeDetailPage() {
)}
{/* Pod allocation */}
<ResourceBar
label=t('kubernetes.nodedetailpage.s55edf2')
label="Pod 数量"
used={`${data.pod_count}`}
total={`${data.pod_allocatable}`}
unit=""
@@ -236,15 +234,15 @@ export default function NodeDetailPage() {
{/* Capacity vs Allocatable raw */}
<div className="mt-4 pt-3 border-t border-[var(--dg-border)]/50 space-y-1 text-[11px] dg-text-muted">
<div className="flex justify-between">
<span>{t('kubernetes.nodedetailpage.s8babfd')}</span>
<span>CPU 容量 / 可分配</span>
<span className="font-mono">{data.cpu_capacity} / {data.cpu_allocatable} 核</span>
</div>
<div className="flex justify-between">
<span>{t('kubernetes.nodedetailpage.s503852')}</span>
<span>内存容量 / 可分配</span>
<span className="font-mono">{data.mem_capacity_mb} / {data.mem_allocatable_mb} Mi</span>
</div>
<div className="flex justify-between">
<span>{t('kubernetes.nodedetailpage.s674f45')}</span>
<span>Pod 容量 / 可分配</span>
<span className="font-mono">{data.pod_capacity} / {data.pod_allocatable}</span>
</div>
</div>
@@ -261,7 +259,7 @@ export default function NodeDetailPage() {
<CheckCircle2 className="h-4 w-4 dg-text-blue" />节点条件
</h2>
{(!data.conditions || data.conditions.length === 0) ? (
<p className="text-xs dg-text-muted py-4 text-center">{t('kubernetes.nodedetailpage.s0f03f9')}</p>
<p className="text-xs dg-text-muted py-4 text-center">无条件数据</p>
) : (
<div className="space-y-2">
{data.conditions.map(( cond: any, i: number) => (
@@ -288,7 +286,7 @@ export default function NodeDetailPage() {
<AlertTriangle className="h-4 w-4 dg-text-yellow" />污点 (Taints)
</h2>
{(!data.taints || data.taints.length === 0) ? (
<p className="text-xs dg-text-muted py-4 text-center">{t('kubernetes.node.noTaint')}</p>
<p className="text-xs dg-text-muted py-4 text-center">无污点</p>
) : (
<div className="space-y-2">
{data.taints.map(( t: any, i: number) => (
@@ -335,18 +333,18 @@ export default function NodeDetailPage() {
</h2>
</div>
{(!data.pods || data.pods.length === 0) ? (
<p className="text-xs dg-text-muted py-8 text-center">{t('kubernetes.nodedetailpage.s86d276')}</p>
<p className="text-xs dg-text-muted py-8 text-center">该节点上暂无 Pod</p>
) : (
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.name')}</TableHead>
<TableHead className="dg-text-secondary">{t('common.status')}</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">名称</TableHead>
<TableHead className="dg-text-secondary">状态</TableHead>
<TableHead className="dg-text-secondary">IP</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.node.cpuRequests')}</TableHead>
<TableHead className="dg-text-secondary">{t('kubernetes.node.memoryRequests')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.restartCount')}</TableHead>
<TableHead className="dg-text-secondary">CPU 请求</TableHead>
<TableHead className="dg-text-secondary">内存请求</TableHead>
<TableHead className="dg-text-secondary">重启次数</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -22,7 +22,6 @@ import {
import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useTranslation } from 'react-i18next';
export interface PodExecTerminalProps {
open: boolean;
@@ -50,7 +49,6 @@ export function PodExecTerminal({
containers = [],
initialContainer,
}: PodExecTerminalProps) {
const { t } = useTranslation();
const { toast } = useToast();
const containerRef = useRef<HTMLDivElement>(null);
const termRef = useRef<XTerm | null>(null);
@@ -94,7 +92,7 @@ export function PodExecTerminal({
setConnState('connecting');
term.clear();
term.writeln(t('kubernetes.podexecterminal.s2f4703', { podName: podName, container ? '/' + container : '': container ? '/' + container : '', shell: shell }));
term.writeln(`\x1b[36m[正在连接 ${podName}${container ? '/' + container : ''} shell=${shell} ...]\x1b[0m`);
const wsUrl = kubernetesApi.buildPodExecWsUrl(clusterId, namespace, podName, container || undefined, shell);
@@ -118,9 +116,9 @@ export function PodExecTerminal({
if (msg.status === 0 && typeof msg.data === 'string') {
term.write(msg.data);
} else if (msg.status === 2 || msg.error) {
const errMsg = msg.data || msg.message || msg.error || t('kubernetes.podexecterminal.s05f6e9');
const errMsg = msg.data || msg.message || msg.error || '执行错误';
if (errMsg.includes('not found') && shell === 'bash') {
term.writeln(t('kubernetes.podexecterminal.s14481b'));
term.writeln('\r\n\x1b[33m⚠ bash 不可用,请切换 /bin/sh 后重连。\x1b[0m');
errorShownRef.current = true;
return;
}
@@ -134,14 +132,14 @@ export function PodExecTerminal({
ws.onclose = (_ev) => {
setConnState((s) => (s === 'error' ? s : 'closed'));
if (!errorShownRef.current) {
term.write(t('kubernetes.podexecterminal.s123d94'));
term.write('\r\n\x1b[33m[连接已关闭]\x1b[0m\r\n');
}
};
ws.onerror = (ev) => {
console.error('[PodExec:connect] WS error event fired, readyState=', ws.readyState, 'type=', ev.type);
setConnState('error');
term.write(t('kubernetes.podexecterminal.sc81077'));
term.write('\r\n\x1b[31m[连接发生错误]\x1b[0m\r\n');
};
}, [clusterId, namespace, podName, container, shell]);
@@ -268,10 +266,10 @@ export function PodExecTerminal({
const statusColor = connState === 'connected' ? 'bg-emerald-400'
: connState === 'error' ? 'bg-red-400'
: connState === 'closed' ? 'bg-[var(--dg-bg-active)]' : 'bg-amber-400';
const statusText = connState === 'connected' ? t('common.connected')
: connState === 'connecting' ? t('common.connecting')
: connState === 'error' ? t('kubernetes.podexecterminal.sd52359')
: connState === 'closed' ? t('common.disconnected') : t('common.idle');
const statusText = connState === 'connected' ? '已连接'
: connState === 'connecting' ? '连接中'
: connState === 'error' ? '连接错误'
: connState === 'closed' ? '已断开' : '空闲';
const handleTerminalClick = useCallback(() => {
try { termRef.current?.focus(); } catch { /* noop */ }
@@ -291,7 +289,7 @@ export function PodExecTerminal({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '960px', width: '92vw' }}
>
<DialogTitle className="sr-only">exec — {podName}</DialogTitle>
<DialogDescription className="sr-only">{t('kubernetes.podexecterminal.s1a62d4')}</DialogDescription>
<DialogDescription className="sr-only">进入 Pod 容器执行命令</DialogDescription>
{/* 工具栏 */}
<div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-[var(--dg-border)] flex-wrap">
@@ -307,7 +305,7 @@ export function PodExecTerminal({
<Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]">
<Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder=t('k8s.pods.containers') />
<SelectValue placeholder="容器" />
</SelectTrigger>
<SelectContent>{containers.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
</Select>
@@ -319,13 +317,13 @@ export function PodExecTerminal({
<SelectContent>{SHELLS.map(s => <SelectItem key={s.value} value={s.value}>{s.label}</SelectItem>)}</SelectContent>
</Select>
<Button variant="ghost" size="sm" className="h-8 px-2 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"
onClick={() => { connect(); toast({ title: t('kubernetes.podexecterminal.sad127c') }); }} title=t('kubernetes.podexecterminal.s114d0e')>
onClick={() => { connect(); toast({ title: '正在重连…' }); }} title="重连">
<RotateCw className="h-3.5 w-3.5" />
</Button>
<button onClick={() => setFullscreen(!fullscreen)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title={fullscreen ? t('common.exitFullscreen') : t('common.fullscreen')}>
<button onClick={() => setFullscreen(!fullscreen)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title={fullscreen ? '退出全屏' : '全屏'}>
{fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button onClick={() => onOpenChange(false)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title=t('common.close')>
<button onClick={() => onOpenChange(false)} className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]" title="关闭">
<X className="h-4 w-4" />
</button>
</div>
@@ -18,7 +18,6 @@ import {
HardDrive,
} from 'lucide-react';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export interface PodFileBrowserProps {
@@ -41,7 +40,6 @@ interface FileEntry {
export function PodFileBrowser({
open, onOpenChange, clusterCode, namespace, podName, containers = [], initialContainer,
}: PodFileBrowserProps) {
const { t } = useTranslation();
const [container, setContainer] = useState(initialContainer || containers[0] || '');
const [currentPath, setCurrentPath] = useState('/');
const [entries, setEntries] = useState<FileEntry[]>([]);
@@ -69,7 +67,7 @@ export function PodFileBrowser({
setEntries(list);
setCurrentPath(path);
} catch (e) {
setError((e as JsonData).message || t('kubernetes.podfilebrowser.s78d4a7'));
setError((e as JsonData).message || '加载文件列表失败');
setEntries([]);
} finally {
setLoading(false);
@@ -119,7 +117,7 @@ export function PodFileBrowser({
const text = await kubernetesApi.readPodFileText(clusterCode, namespace, podName, filePath, container || undefined);
setPreview({ file: fileName, content: text });
} catch (e) {
setPreview({ file: fileName, content: t('kubernetes.podfilebrowser.s888006', { (e as JsonData).message: (e as JsonData).message }) });
setPreview({ file: fileName, content: `读取失败: ${(e as JsonData).message}` });
}
};
@@ -137,7 +135,7 @@ export function PodFileBrowser({
await kubernetesApi.uploadPodFile(clusterCode, namespace, podName, currentPath, file, container || undefined);
loadFiles(currentPath);
} catch (err) {
setError(t('kubernetes.podfilebrowser.s560770', { (err as JsonData).message: (err as JsonData).message }));
setError(`上传失败: ${(err as JsonData).message}`);
} finally {
setUploading(false);
if (fileInputRef.current) fileInputRef.current.value = '';
@@ -227,7 +225,7 @@ export function PodFileBrowser({
{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">{t('kubernetes.workload.emptyDir')}</p>
<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) => (
@@ -251,7 +249,7 @@ export function PodFileBrowser({
<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=t('common.download')
title="下载"
>
<Download className="h-3 w-3" />
</Button>
@@ -273,7 +271,7 @@ export function PodFileBrowser({
</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 || t('kubernetes.podfilebrowser.sf42649')}
{preview.content || '(空文件)'}
</pre>
</div>
</div>
@@ -22,8 +22,6 @@ import { cn } from '@/lib/utils';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
/**
* 增强版 Pod 日志查看器 — 增强 DeploymentDetail 的日志体验
@@ -53,10 +51,10 @@ interface PodLogsViewerProps {
}
const TAIL_OPTIONS = [
{ value: '100', label: i18n.t('kubernetes.podlogsviewer.s58b02a') },
{ value: '500', label: i18n.t('kubernetes.podlogsviewer.s9a0368') },
{ value: '1000', label: i18n.t('kubernetes.podlogsviewer.sf89a33') },
{ value: '0', label: i18n.t('common.all') },
{ value: '100', label: '最近 100 行' },
{ value: '500', label: '最近 500 行' },
{ value: '1000', label: '最近 1000 行' },
{ value: '0', label: '全部' },
];
// 环形缓冲大小(借鉴 opsx-agent)
@@ -76,7 +74,6 @@ export function PodLogsViewer({
containers = [],
initialContainer,
}: PodLogsViewerProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [fullscreen, setFullscreen] = useState(false);
@@ -167,8 +164,8 @@ export function PodLogsViewer({
const arr = typeof raw === 'string' ? raw.split('\n') : (Array.isArray(raw) ? raw : String(raw).split('\n'));
appendLines(arr);
} catch (e) {
appendLines([t('kubernetes.podlogsviewer.s69828a', { e?.message || String(e): e?.message || String(e) })]);
toast({ title: t('kubernetes.podlogsviewer.sc93f33'), description: e?.message || String(e), variant: 'destructive' });
appendLines([`\x1b[31m[获取日志失败: ${e?.message || String(e)}]\x1b[0m`]);
toast({ title: '获取日志失败', description: e?.message || String(e), variant: 'destructive' });
} finally {
setLoading(false);
}
@@ -228,12 +225,12 @@ export function PodLogsViewer({
}
}
flush(); // 收尾
appendLines([t('kubernetes.podlogsviewer.s4f0e17')]);
appendLines(['\x1b[33m— 流式结束 —\x1b[0m']);
} catch (e) {
if (e?.name === 'AbortError') {
appendLines([t('kubernetes.podlogsviewer.s1ca901')]);
appendLines(['\x1b[33m— 已停止 —\x1b[0m']);
} else {
appendLines([t('kubernetes.podlogsviewer.s11530d', { e?.message || String(e): e?.message || String(e) })]);
appendLines([`\x1b[31m[流式连接中断: ${e?.message || String(e)}]\x1b[0m`]);
}
} finally {
setStreaming(false);
@@ -278,7 +275,7 @@ export function PodLogsViewer({
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
toast({ title: t('kubernetes.podlogsviewer.s5c51c3'), description: filename });
toast({ title: '已导出', description: filename });
}, [podName, container, previous, toast]);
// 关键字过滤
@@ -333,7 +330,7 @@ export function PodLogsViewer({
style={fullscreen ? { maxWidth: '100vw', width: '100vw', height: '100vh' } : { maxWidth: '1100px', width: '94vw' }}
>
<DialogTitle className="sr-only">日志 — {podName}</DialogTitle>
<DialogDescription className="sr-only">{t('kubernetes.podlogsviewer.s24ae3a')}</DialogDescription>
<DialogDescription className="sr-only">Pod 容器日志查看</DialogDescription>
{/* 头部工具栏 */}
<div className="flex items-center justify-between gap-2 px-4 py-2 border-b border-[var(--dg-border)] flex-wrap">
@@ -346,8 +343,8 @@ export function PodLogsViewer({
<span className="text-[var(--dg-text-primary)] font-medium truncate">日志 — {podName}</span>
{loading && <Loader2 className="h-3 w-3 animate-spin text-[var(--dg-text-muted)]" />}
<span className="text-xs text-[var(--dg-text-muted)]">
{streaming ? (paused ? t('kubernetes.deployment.paused') : t('kubernetes.podlogsviewer.sd9c71f')) : t('common.stopped')} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行
{lineCount >= RING_BUFFER_MAX && t('kubernetes.podlogsviewer.sf3280b')}
{streaming ? (paused ? '已暂停' : '实时跟踪') : '已停止'} · {matchedCount}{keyword ? `/${lineCount}` : ''} 行
{lineCount >= RING_BUFFER_MAX && ' (缓冲已满)'}
</span>
</div>
@@ -355,14 +352,14 @@ export function PodLogsViewer({
<button
onClick={() => setFullscreen(!fullscreen)}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]"
title={fullscreen ? t('common.exitFullscreen') : t('common.fullscreen')}
title={fullscreen ? '退出全屏' : '全屏'}
>
{fullscreen ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button
onClick={handleClose}
className="p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]"
title=t('common.close')
title="关闭"
>
<X className="h-4 w-4" />
</button>
@@ -376,7 +373,7 @@ export function PodLogsViewer({
<Select value={container} onValueChange={setContainer}>
<SelectTrigger className="h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]">
<Box className="h-3 w-3 mr-1 text-[var(--dg-text-muted)]" />
<SelectValue placeholder=t('k8s.pods.containers') />
<SelectValue placeholder="容器" />
</SelectTrigger>
<SelectContent>
{containers.map((c) => (
@@ -404,7 +401,7 @@ export function PodLogsViewer({
size="sm"
className={cn('h-8 text-xs', previous ? 'bg-amber-600 hover:bg-amber-700' : 'border-[var(--dg-border)] text-[var(--dg-text-secondary)]')}
onClick={() => setPrevious(!previous)}
title=t('kubernetes.podlogsviewer.s76a2e6')
title="查看上一次(崩溃)容器的日志"
>
<History className="h-3.5 w-3.5 mr-1" />
previous
@@ -421,7 +418,7 @@ export function PodLogsViewer({
setSinceTime(v ? new Date(v).toISOString() : '');
}}
className="h-8 w-[170px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
title=t('kubernetes.podlogsviewer.s127892')
title="起始时间(sinceTime)"
/>
</div>
@@ -433,7 +430,7 @@ export function PodLogsViewer({
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
placeholder=t('kubernetes.podlogsviewer.s7558f1')
placeholder="关键字过滤…"
className="h-8 w-[160px] pl-7 text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
</div>
@@ -443,7 +440,7 @@ export function PodLogsViewer({
variant="outline" size="sm"
className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={handleDownload}
title=t('kubernetes.podlogsviewer.s1a023d')
title="导出当前日志"
disabled={filteredLines.length === 0}
>
<Download className="h-3.5 w-3.5 mr-1" />导出
@@ -455,7 +452,7 @@ export function PodLogsViewer({
className="h-8 text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]"
onClick={fetchLogs}
disabled={loading}
title=t('kubernetes.podlogsviewer.s930b4e')
title="重新拉取"
>
<RefreshCw className={cn('h-3.5 w-3.5 mr-1', loading && 'animate-spin')} />刷新
</Button>
@@ -467,7 +464,7 @@ export function PodLogsViewer({
className="h-8 text-xs bg-emerald-600 hover:bg-emerald-700"
onClick={startStream}
disabled={loading}
title=t('kubernetes.podlogsviewer.s0d519c')
title="实时跟踪(tail -f)"
>
<Play className="h-3.5 w-3.5 mr-1" />实时
</Button>
@@ -477,16 +474,16 @@ export function PodLogsViewer({
variant="outline" size="sm"
className={cn('h-8 text-xs', paused ? 'border-emerald-500 dg-text-green' : 'border-amber-500 dg-text-yellow')}
onClick={() => setPaused(!paused)}
title={paused ? t('common.continue') : t('common.pause')}
title={paused ? '继续' : '暂停'}
>
{paused ? <Play className="h-3.5 w-3.5 mr-1" /> : <Pause className="h-3.5 w-3.5 mr-1" />}
{paused ? t('common.continue') : t('common.pause')}
{paused ? '继续' : '暂停'}
</Button>
<Button
variant="outline" size="sm"
className="h-8 text-xs border-red-500 dg-text-red"
onClick={stopStream}
title=t('common.stop')
title="停止"
>
<Pause className="h-3.5 w-3.5 mr-1" />停止
</Button>
@@ -513,7 +510,7 @@ export function PodLogsViewer({
{lineCount === 0 && !loading && (
<div className="flex flex-col items-center justify-center h-full text-[var(--dg-text-muted)]">
<AlertCircle className="h-8 w-8 mb-2 opacity-50" />
<span>{t('pipeline.noLog')}</span>
<span>暂无日志</span>
</div>
)}
{loading && lineCount === 0 && (
@@ -545,7 +542,7 @@ export function PodLogsViewer({
}
}}
>
<Maximize2 className="h-3 w-3" />{autoScroll ? t('kubernetes.podlogsviewer.sd7eb1e') : t('kubernetes.podlogsviewer.s130db3')}
<Maximize2 className="h-3 w-3" />{autoScroll ? '跟随底部' : '已暂停跟随'}
</button>
</div>
</DialogContent>
@@ -14,10 +14,8 @@ import { PageShell } from '@/components/layout/PageShell';
import { ContentPanel } from '@/components/layout/ContentPanel';
import { StatStrip } from '@/components/ui/stat-strip';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
export default function PodMetricsPage() {
const { t } = useTranslation();
const { clusterCode } = useParams<{ clusterCode: string }>();
const navigate = useNavigate();
const [loading, setLoading] = useState(false);
@@ -87,15 +85,15 @@ export default function PodMetricsPage() {
return (
<PageShell
variant="list"
title=t('kubernetes.podmetricspage.s94c067')
subtitle={clusterName ? t('kubernetes.podmetricspage.sc3a5a8', { clusterName: clusterName }) : t('kubernetes.podmetricspage.s6dbb5e')}
title="Pod 资源用量"
subtitle={clusterName ? `${clusterName} · 容器 CPU/内存实时指标` : '容器 CPU/内存实时指标'}
icon={<Activity className="h-5 w-5" />}
metrics={!loading ? (
<StatStrip
items={[
{ label: t('kubernetes.node.podCount'), value: metrics.length, color: 'muted' },
{ label: t('kubernetes.podmetricspage.sac1fc3'), value: `${totalCPU}m`, color: 'blue' },
{ label: t('monitor.systemInfo.memTotal'), value: `${totalMem.toFixed(0)}Mi`, color: 'green' },
{ label: 'Pod 数', value: metrics.length, color: 'muted' },
{ label: '总 CPU', value: `${totalCPU}m`, color: 'blue' },
{ label: '总内存', value: `${totalMem.toFixed(0)}Mi`, color: 'green' },
]}
/>
) : undefined}
@@ -108,9 +106,9 @@ export default function PodMetricsPage() {
</SelectContent>
</Select>
<Select value={selectedNs} onValueChange={setSelectedNs}>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder=t('kubernetes.podmetricspage.s58173b') /></SelectTrigger>
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder="所有命名空间" /></SelectTrigger>
<SelectContent>
<SelectItem value="all">{t('kubernetes.podmetricspage.s58173b')}</SelectItem>
<SelectItem value="all">所有命名空间</SelectItem>
{namespaces.map(n => <SelectItem key={n} value={n}>{n}</SelectItem>)}
</SelectContent>
</Select>
@@ -125,8 +123,8 @@ export default function PodMetricsPage() {
<Table>
<TableHeader><TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="dg-text-secondary">Pod</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.column.namespace')}</TableHead>
<TableHead className="dg-text-secondary">{t('k8s.pods.containers')}</TableHead>
<TableHead className="dg-text-secondary">命名空间</TableHead>
<TableHead className="dg-text-secondary">容器</TableHead>
<TableHead className="dg-text-secondary"><Cpu className="h-3 w-3 inline mr-1" />CPU</TableHead>
<TableHead className="dg-text-secondary"><HardDrive className="h-3 w-3 inline mr-1" />Memory</TableHead>
</TableRow></TableHeader>
@@ -17,7 +17,6 @@ import { YamlEditorToolbar } from './YamlEditorToolbar';
import { YamlCodeMirror } from './YamlCodeMirror';
import { getYamlResourceConfig, yamlDownloadFilename } from './k8s-yaml-resource-config';
import { downloadYamlFile } from '@/utils/export';
import { useTranslation } from 'react-i18next';
interface ResourceVisualEditorProps {
clusterCode: string;
@@ -31,7 +30,6 @@ interface ResourceVisualEditorProps {
}
export function ResourceVisualEditor({ clusterCode, namespace, resource, name, onClose, onSaved, isCreate = false }: ResourceVisualEditorProps) {
const { t } = useTranslation();
const { toast } = useToast();
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
@@ -68,10 +66,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
setManifest(parsed);
if (!parsed) {
setMode('yaml');
toast({ title: t('kubernetes.resourcevisualeditor.s80ca4f'), description: t('kubernetes.resourcevisualeditor.scc94aa') });
toast({ title: '可视化编辑不可用', description: '无法解析资源结构,已切换到 YAML 编辑模式' });
}
} catch (e) {
toast({ title: t('common.loadFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: '加载失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setLoading(false); }
}, [clusterCode, namespace, resource, name, isCreate]);
@@ -84,19 +82,19 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const resName = updatedManifest?.metadata?.name || name;
if (isCreate) {
if (!resName?.trim()) {
toast({ title: t('deploy.form.nameRequired'), variant: 'destructive' });
toast({ title: '请填写名称', variant: 'destructive' });
return;
}
await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: `${resource}/${resName}` });
toast({ title: '创建成功', description: `${resource}/${resName}` });
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
toast({ title: t('common.savedSuccessfully'), description: t('kubernetes.resourcevisualeditor.se7e1ac_0', { resource: resource, name: name }) });
toast({ title: '保存成功', description: `${resource}/${name} 已更新` });
}
onSaved?.();
onClose();
} catch (e) {
toast({ title: isCreate ? t('monitor.quickSetupFailed') : t('common.saveFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: isCreate ? '创建失败' : '保存失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -106,10 +104,10 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const yamlStr = await prepareYamlForSave(editYaml);
if (isCreate) {
await kubernetesApi.applyYAML(clusterCode, yamlStr);
toast({ title: t('monitor.dashboard.custom.toastCreateSuccess'), description: t('kubernetes.resourcevisualeditor.se5ff4b') });
toast({ title: '创建成功', description: 'YAML 已应用' });
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
toast({ title: t('common.savedSuccessfully'), description: t('kubernetes.resourcevisualeditor.se7e1ac', { resource: resource, name: name }) });
toast({ title: '保存成功', description: `${resource}/${name} 已更新` });
}
setYamlEditing(false);
setDisplayYaml(yamlStr);
@@ -118,7 +116,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
onSaved?.();
onClose();
} catch (e) {
toast({ title: t('common.saveFailed'), description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
toast({ title: '保存失败', description: e instanceof Error ? e.message : String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -126,7 +124,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const switchToVisual = async () => {
const parsed = await parseManifest(editYaml);
if (!parsed) {
toast({ title: t('kubernetes.resourcevisualeditor.sf53bdf'), description: t('kubernetes.resourcevisualeditor.sf2219a'), variant: 'destructive' });
toast({ title: '无法解析 YAML', description: '请检查语法后继续用 YAML 模式', variant: 'destructive' });
return;
}
setManifest(parsed);
@@ -155,7 +153,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
const downloadYamlContent = () => {
const fname = yamlDownloadFilename(resource, namespace, name || manifest?.metadata?.name || 'resource');
downloadYamlFile(fname, currentYamlText());
toast({ title: t('kubernetes.resourcevisualeditor.s9719fe'), description: fname });
toast({ title: '已下载', description: fname });
};
const resCfg = getYamlResourceConfig(resource);
@@ -181,7 +179,7 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
<MetaIcon className={`h-5 w-5 shrink-0 ${meta.color}`} />
<div className="min-w-0">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate">
{isCreate ? t('kubernetes.resourcevisualeditor.s1876b4', { meta.title: meta.title }) : t('kubernetes.resourcevisualeditor.sc05c9e', { meta.title: meta.title })}
{isCreate ? `新建 ${meta.title}` : `${meta.title} 编辑`}
</h2>
<p
className="text-xs text-[var(--dg-text-muted)] truncate"
@@ -198,11 +196,11 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'visual' ? 'bg-blue-600 text-white' : 'bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]'}`}
onClick={() => { if (mode === 'yaml') switchToVisual(); else setMode('visual'); }}
disabled={!manifest && mode !== 'yaml'}
>{t('k8s.resource.visualEditor')}</button>
>可视化编辑</button>
<button
className={`px-3 py-1.5 text-xs font-medium transition-colors ${mode === 'yaml' ? 'bg-blue-600 text-white' : 'bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]'}`}
onClick={() => { if (mode === 'visual') switchToYaml(); else setMode('yaml'); }}
>{t('k8s.resource.yamlEditor')}</button>
>YAML 编辑</button>
</div>
<Button variant="ghost" size="icon" className="h-8 w-8 text-[var(--dg-text-secondary)]" onClick={onClose}><X className="h-4 w-4" /></Button>
</div>
@@ -261,16 +259,16 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
{!['configmaps', 'secrets', 'services', 'ingresses', 'pvcs'].includes(resource) && (
<div className="flex-1 flex items-center justify-center text-center text-[var(--dg-text-muted)]">
<div>
<p>{t('kubernetes.resourcevisualeditor.sfeb34f')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
<p>该资源类型暂不支持可视化编辑</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button>
</div>
</div>
)}
</div>
) : (
<div className="text-center py-12 text-[var(--dg-text-muted)]">
<p>{t('kubernetes.resourcevisualeditor.s8fe0ae')}</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>{t('kubernetes.resourcevisualeditor.s54c78d')}</Button>
<p>无法解析资源结构</p>
<Button variant="outline" size="sm" className="mt-4" onClick={() => setMode('yaml')}>切换到 YAML 编辑</Button>
</div>
)}
</div>
@@ -283,7 +281,6 @@ export function ResourceVisualEditor({ clusterCode, namespace, resource, name, o
// ConfigMap 编辑器 — 键值对表格
// ══════════════════════════════════════════════
function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const data = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [entries, setEntries] = useState<{ key: string; value: string }[]>(
@@ -311,18 +308,18 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.s6bd91c')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-sm">配置数据 (键值对)</Label>
<div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
{expandAll ? '折叠全部' : '展开全部'}
</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />{t('common.add')}</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />添加</Button>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-2 border border-[var(--dg-border)] rounded-lg bg-[var(--dg-bg-secondary)] p-2">
@@ -331,13 +328,13 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
<Input
value={entry.key}
onChange={e => update(i, 'key', e.target.value)}
placeholder=t('kubernetes.resourcevisualeditor.s65017d')
placeholder="键名 (如 LOG_LEVEL)"
className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<Textarea
value={entry.value}
onChange={e => update(i, 'value', e.target.value)}
placeholder=t('k8s.resource.value')
placeholder="值"
rows={expandAll || entry.value.length > 300 ? 10 : (entry.value.length > 100 ? 6 : 3)}
className="flex-[2] font-mono text-xs min-h-[70px] max-h-[420px] resize-y bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] leading-relaxed"
/>
@@ -347,7 +344,7 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
</div>
))}
{entries.length === 0 && (
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.saf7696')}</div>
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">暂无配置数据,点击「添加」创建</div>
)}
</div>
</div>
@@ -366,7 +363,6 @@ function ConfigMapEditor({ manifest, onSave, saving, isCreate }: { manifest: any
// Secret 编辑器 — 键值对表格 (Base64 编码/解码)
// ══════════════════════════════════════════════
function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const rawData = manifest?.data || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [expandAll, setExpandAll] = useState(false);
@@ -408,23 +404,23 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
<div className="flex flex-col h-full">
<div className="shrink-0 grid grid-cols-2 gap-4">
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.type')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">类型</Label>
<Input value={manifest?.type || 'Opaque'} readOnly className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.se19370')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-sm">密钥数据 (已自动解码 Base64)</Label>
<div className="flex gap-1">
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => setExpandAll(!expandAll)}>
{expandAll ? t('kubernetes.resourcevisualeditor.s880e84') : t('common.expandAll')}
{expandAll ? '折叠全部' : '展开全部'}
</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />{t('common.add')}</Button>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRow}><Plus className="h-3 w-3 mr-1" />添加</Button>
</div>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-2 border border-[var(--dg-border)] rounded-lg bg-[var(--dg-bg-secondary)] p-2">
@@ -433,13 +429,13 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
<Input
value={entry.key}
onChange={e => update(i, 'key', e.target.value)}
placeholder=t('kubernetes.resourcevisualeditor.scdecc4')
placeholder="键名 (如 password)"
className="flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<Textarea
value={entry.value}
onChange={e => update(i, 'value', e.target.value)}
placeholder=t('kubernetes.resourcevisualeditor.s7f123d')
placeholder="明文值"
rows={expandAll || entry.value.length > 300 ? 10 : (entry.value.length > 100 ? 6 : 3)}
className="flex-[2] font-mono text-xs min-h-[70px] max-h-[420px] resize-y bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] leading-relaxed"
/>
@@ -449,7 +445,7 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
</div>
))}
{entries.length === 0 && (
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.s47ff69')}</div>
<div className="text-center py-8 text-[var(--dg-text-muted)] text-xs">暂无密钥数据,点击「添加」创建</div>
)}
</div>
</div>
@@ -468,7 +464,6 @@ function SecretEditor({ manifest, onSave, saving, isCreate }: { manifest: any; o
// Service 编辑器 — 端口配置 + 类型 + 选择器
// ══════════════════════════════════════════════
function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [svcType, setSvcType] = useState(spec.type || 'ClusterIP');
@@ -529,11 +524,11 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('agent.agentServiceName')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">服务名称</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="shrink-0 mt-3">
<Label className="text-[var(--dg-text-secondary)] text-xs mb-2 block">{t('k8s.resource.serviceType')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs mb-2 block">服务类型</Label>
<div className="flex rounded-lg border border-[var(--dg-border)] overflow-hidden w-fit">
{svcTypes.map((t) => (
<button
@@ -552,16 +547,16 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
<div className="flex-1 min-h-0 overflow-y-auto mt-3 pr-1 space-y-3">
<div>
<div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.s736788')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addPort}><Plus className="h-3 w-3 mr-1" />{t('agent.addPort')}</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">端口映射</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addPort}><Plus className="h-3 w-3 mr-1" />添加端口</Button>
</div>
<div className="space-y-2 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]">
{ports.map((p, i) => (
<div key={i} className="overflow-x-auto">
<div className="grid grid-cols-[minmax(80px,1fr)_80px_80px_80px_80px_32px] gap-2 items-center min-w-[480px]">
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)} placeholder=t('common.name') className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)} placeholder=t('server.csv.port') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)} placeholder=t('common.target') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.name} onChange={e => updatePort(i, 'name', e.target.value)} placeholder="名称" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.port} onChange={e => updatePort(i, 'port', e.target.value)} placeholder="端口" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.targetPort} onChange={e => updatePort(i, 'targetPort', e.target.value)} placeholder="目标" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Select value={p.protocol} onValueChange={v => updatePort(i, 'protocol', v)}>
<SelectTrigger className="h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="TCP">TCP</SelectItem><SelectItem value="UDP">UDP</SelectItem></SelectContent>
@@ -573,26 +568,26 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
</div>
</div>
))}
{ports.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.sf3ba5e')}</div>}
{ports.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无端口,点击「添加端口」</div>}
</div>
</div>
{/* Selector */}
<div>
<div className="flex items-center justify-between mb-2">
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('kubernetes.resourcevisualeditor.scecdd7')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addSelector}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.resourcevisualeditor.s736eaa')}</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">选择器 (Selector)</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addSelector}><Plus className="h-3 w-3 mr-1" />添加标签</Button>
</div>
<div className="space-y-2">
{selector.map((s, i) => (
<div key={i} className="flex items-center gap-2 min-w-0">
<Input value={s.key} onChange={e => updateSelector(i, 'key', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.s450c99') className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={s.key} onChange={e => updateSelector(i, 'key', e.target.value)} placeholder="键 (如 app)" className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<span className="text-[var(--dg-text-muted)] text-xs shrink-0">=</span>
<Input value={s.value} onChange={e => updateSelector(i, 'value', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.sb873e4') className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={s.value} onChange={e => updateSelector(i, 'value', e.target.value)} placeholder="值 (如 nginx)" className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Button variant="ghost" size="icon" className="h-7 w-7 shrink-0 dg-text-red hover:dg-text-red" onClick={() => removeSelector(i)}><Trash2 className="h-3 w-3" /></Button>
</div>
))}
{selector.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('k8s.resource.noSelectors')}</div>}
{selector.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无选择器</div>}
</div>
</div>
</div>
@@ -611,7 +606,6 @@ function ServiceEditor({ manifest, onSave, saving, isCreate }: { manifest: any;
// Ingress 编辑器 — Host/Path 路由规则
// ══════════════════════════════════════════════
function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { manifest: any; clusterCode: string; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
const [ingressClass, setIngressClass] = useState(spec.ingressClassName || 'nginx');
@@ -695,13 +689,13 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
<div className="flex flex-col h-full min-h-0">
<div className="shrink-0 grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="min-w-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="min-w-0">
<Label className="text-[var(--dg-text-secondary)] text-xs flex items-center gap-1">
Ingress Class
<span className="text-[10px] text-[var(--dg-text-muted)]">{t('kubernetes.resourcevisualeditor.s6c9a78')}</span>
<span className="text-[10px] text-[var(--dg-text-muted)]">(可选)</span>
</Label>
{/* IngressClass 下拉 + 手工输入支持 // Logan.Li */}
<div className="space-y-1 mt-1">
@@ -714,7 +708,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
}}
>
<SelectTrigger className="h-8 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
<SelectValue placeholder={loadingClasses ? t('common.loading') : t('kubernetes.resourcevisualeditor.s25a87d')} />
<SelectValue placeholder={loadingClasses ? '加载中...' : '选择或输入 IngressClass'} />
</SelectTrigger>
<SelectContent>
{ingressClasses.length > 0 ? (
@@ -724,13 +718,13 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</SelectItem>
))
) : (
!loadingClasses && <div className="px-2 py-1.5 text-xs text-[var(--dg-text-muted)]">{t('kubernetes.resourcevisualeditor.s619a36')}</div>
!loadingClasses && <div className="px-2 py-1.5 text-xs text-[var(--dg-text-muted)]">未发现 IngressClass,请手动输入</div>
)}
{/* 当前自定义值作为选项,确保选中态 */}
{ingressClass && !ingressClasses.some((ic) => ic.name === ingressClass) && (
<SelectItem value={ingressClass}>{ingressClass} (手动输入)</SelectItem>
)}
<SelectItem value="__manual__">{t('kubernetes.resourcevisualeditor.se83eb1')}</SelectItem>
<SelectItem value="__manual__">—— 继续手动输入 ——</SelectItem>
</SelectContent>
</Select>
@@ -761,8 +755,8 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
</div>
<div className="flex-1 min-h-0 flex flex-col mt-3">
<div className="flex items-center justify-between mb-2 shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-sm">{t('k8s.resource.routeRules')}</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRule}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.resourcevisualeditor.s4f0a38')}</Button>
<Label className="text-[var(--dg-text-secondary)] text-sm">路由规则</Label>
<Button variant="outline" size="sm" className="h-7 text-xs" onClick={addRule}><Plus className="h-3 w-3 mr-1" />添加 Host</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto pr-1 space-y-3 border border-[var(--dg-border)] rounded-lg p-2 bg-[var(--dg-bg-secondary)]">
{rules.map((rule, ri) => (
@@ -771,7 +765,7 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
<Input
value={rule.host}
onChange={e => updateRule(ri, e.target.value)}
placeholder=t('kubernetes.resourcevisualeditor.s33cde9')
placeholder="域名 (如 api.example.com)"
className="flex-1 min-w-0 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
title={rule.host}
/>
@@ -780,21 +774,21 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
{rule.paths.map((p, pi) => (
<div key={pi} className="overflow-x-auto pl-4">
<div className="grid grid-cols-[minmax(80px,1fr)_100px_minmax(80px,1fr)_60px_28px] gap-1.5 items-center min-w-[420px]">
<Input value={p.path} onChange={e => updatePath(ri, pi, 'path', e.target.value)} placeholder=t('kubernetes.resourcevisualeditor.sdfd5eb') className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.path} onChange={e => updatePath(ri, pi, 'path', e.target.value)} placeholder="路径 /" className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Select value={p.pathType} onValueChange={v => updatePath(ri, pi, 'pathType', v)}>
<SelectTrigger className="h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"><SelectValue /></SelectTrigger>
<SelectContent><SelectItem value="Prefix">Prefix</SelectItem><SelectItem value="Exact">Exact</SelectItem></SelectContent>
</Select>
<Input value={p.serviceName} onChange={e => updatePath(ri, pi, 'serviceName', e.target.value)} placeholder="Service" className="font-mono text-xs h-7 min-w-0 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.servicePort} onChange={e => updatePath(ri, pi, 'servicePort', e.target.value)} placeholder=t('server.csv.port') type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Input value={p.servicePort} onChange={e => updatePath(ri, pi, 'servicePort', e.target.value)} placeholder="端口" type="number" className="font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]" />
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" onClick={() => removePath(ri, pi)}><Trash2 className="h-3 w-3" /></Button>
</div>
</div>
))}
<Button variant="ghost" size="sm" className="h-6 text-xs text-[var(--dg-text-muted)]" onClick={() => addPath(ri)}><Plus className="h-3 w-3 mr-1" />{t('kubernetes.ingress.addPath')}</Button>
<Button variant="ghost" size="sm" className="h-6 text-xs text-[var(--dg-text-muted)]" onClick={() => addPath(ri)}><Plus className="h-3 w-3 mr-1" />添加路径</Button>
</div>
))}
{rules.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">{t('kubernetes.resourcevisualeditor.s0b0794')}</div>}
{rules.length === 0 && <div className="text-center py-4 text-[var(--dg-text-muted)] text-xs">暂无路由规则,点击「添加 Host」</div>}
</div>
</div>
<div className="shrink-0 flex justify-end gap-2 pt-3 mt-2 border-t border-[var(--dg-border)]">
@@ -811,7 +805,6 @@ function IngressEditor({ manifest, clusterCode, onSave, saving, isCreate }: { ma
// PVC 编辑器 — 存储大小/访问模式/StorageClass
// ══════════════════════════════════════════════
function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSave: (m: any) => void; saving: boolean; isCreate?: boolean }) {
const { t } = useTranslation();
const spec = manifest?.spec || {};
const resources = spec.resources?.requests || {};
const [resName, setResName] = useState(manifest?.metadata?.name || '');
@@ -835,30 +828,30 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
return (
<div className="flex flex-col h-full">
<div className="shrink-0">
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('common.name')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">名称</Label>
<Input value={resName} onChange={(e) => setResName(e.target.value)} readOnly={!isCreate} className="mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]" />
</div>
<div className="grid grid-cols-2 gap-4 mt-3 shrink-0">
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('kubernetes.resourcevisualeditor.s61aa82')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">存储大小</Label>
<Input
value={size}
onChange={e => setSize(e.target.value)}
placeholder=t('kubernetes.resourcevisualeditor.s1b915a')
placeholder="如 10Gi"
className="mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">{t('kubernetes.resourcevisualeditor.s6a1c7a')}</p>
<p className="text-[10px] text-[var(--dg-text-muted)] mt-1">单位:Gi (GiB), Mi (MiB), Ti (TiB)</p>
</div>
<div>
<Label className="text-[var(--dg-text-secondary)] text-xs">{t('k8s.resource.accessMode')}</Label>
<Label className="text-[var(--dg-text-secondary)] text-xs">访问模式</Label>
<Select value={accessMode} onValueChange={setAccessMode}>
<SelectTrigger className="mt-1 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ReadWriteOnce">{t('kubernetes.resourcevisualeditor.se1444f')}</SelectItem>
<SelectItem value="ReadOnlyMany">{t('kubernetes.resourcevisualeditor.s9d4ea0')}</SelectItem>
<SelectItem value="ReadWriteMany">{t('kubernetes.resourcevisualeditor.s093227')}</SelectItem>
<SelectItem value="ReadWriteOnce">ReadWriteOnce (单节点读写)</SelectItem>
<SelectItem value="ReadOnlyMany">ReadOnlyMany (多节点只读)</SelectItem>
<SelectItem value="ReadWriteMany">ReadWriteMany (多节点读写)</SelectItem>
</SelectContent>
</Select>
</div>
@@ -868,7 +861,7 @@ function PvcEditor({ manifest, onSave, saving, isCreate }: { manifest: any; onSa
<Input
value={storageClass}
onChange={e => setStorageClass(e.target.value)}
placeholder=i18n.t('kubernetes.resourcevisualeditor.s06195f')
placeholder="留空使用默认 StorageClass"
className="mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"
/>
</div>
@@ -382,7 +382,7 @@ export function TopologyView() {
<SelectTrigger className="w-36 h-9 dg-input"><SelectValue placeholder={t('k8s.topology.nodeTypeLabel')} /></SelectTrigger>
<SelectContent className="dg-input">
<SelectItem value="all">{t('k8s.topology.allTypes')}</SelectItem>
{Object.entries(NODE_TYPE_LABELS).map(([v, l]) => <SelectItem key={v} value={v}>{l}</SelectItem>)}
{Object.entries(NODE_TYPE_LABELS).map(([v, l]) => <SelectItem key={v} value={v}>{t(l)}</SelectItem>)}
</SelectContent>
</Select>
</div>
@@ -495,7 +495,7 @@ export function TopologyView() {
<div className={`p-2 rounded-lg ${getNodeColor(node.type)}`}>{getNodeIcon(node.type)}</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-[var(--dg-text-primary)] truncate">{node.name}</p>
<p className="text-xs dg-text-muted">{NODE_TYPE_LABELS[node.type] || node.type}{isCustomNode(node.id) ? ` · ${t('k8s.topology.customSuffix')}` : ''}</p>
<p className="text-xs dg-text-muted">{NODE_TYPE_LABELS[node.type] ? t(NODE_TYPE_LABELS[node.type]) : node.type}{isCustomNode(node.id) ? ` · ${t('k8s.topology.customSuffix')}` : ''}</p>
</div>
</div>
))
@@ -515,7 +515,7 @@ export function TopologyView() {
{selectedNode?.name}
{selectedNode && isCustomNode(selectedNode.id) && <Badge variant="outline" className="border-amber-500/30 dg-text-yellow text-xs">{t('k8s.topology.custom2')}</Badge>}
</DialogTitle>
<DialogDescription className="dg-text-muted">{t('common.type')}: {NODE_TYPE_LABELS[selectedNode?.type || ''] || selectedNode?.type}</DialogDescription>
<DialogDescription className="dg-text-muted">{t('common.type')}: {NODE_TYPE_LABELS[selectedNode?.type || ''] ? t(NODE_TYPE_LABELS[selectedNode?.type || '']) : selectedNode?.type}</DialogDescription>
</DialogHeader>
{selectedNode && (
<div className="space-y-4">
@@ -575,7 +575,7 @@ export function TopologyView() {
<Select value={editForm.type} onValueChange={(v) => setEditForm({ ...editForm, type: v as TopologyNode['type'] })}>
<SelectTrigger className="dg-input"><SelectValue /></SelectTrigger>
<SelectContent className="dg-input">
{CUSTOM_NODE_TYPES.map((t) => <SelectItem key={t.value} value={t.value}>{t.label} — {t.desc}</SelectItem>)}
{CUSTOM_NODE_TYPES.map((opt) => <SelectItem key={opt.value} value={opt.value}>{t(opt.label)} — {t(opt.desc)}</SelectItem>)}
</SelectContent>
</Select>
</div>
@@ -22,13 +22,11 @@ import { PodFileBrowser } from './PodFileBrowser';
import { formatK8sTime, statusColor, STATUS_COLORS } from './k8s-yaml-utils';
import { PageShell } from '@/components/layout/PageShell';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
type WorkloadKind = 'StatefulSet' | 'DaemonSet';
type ViewMode = 'view' | 'yaml';
function StatCard({ label, value, sub, color }: { label: string; value: React.ReactNode; sub?: string; color?: string }) {
const { t } = useTranslation();
return (
<Card className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]">
<CardContent className="p-3">
@@ -42,9 +40,8 @@ function StatCard({ label, value, sub, color }: { label: string; value: React.Re
// Helper: render key-value pairs as badges
function LabelBadges({ labels }: { labels: Record<string, string> | undefined }) {
const { t } = useTranslation();
const entries = Object.entries(labels || {});
if (entries.length === 0) return <span className="text-xs text-[var(--dg-text-muted)]">{t('common.none')}</span>;
if (entries.length === 0) return <span className="text-xs text-[var(--dg-text-muted)]">无</span>;
return (
<div className="flex flex-wrap gap-1.5">
{entries.map(([k, v]) => (
@@ -57,7 +54,6 @@ function LabelBadges({ labels }: { labels: Record<string, string> | undefined })
}
export default function WorkloadViewPage() {
const { t } = useTranslation();
const params = useParams<{ clusterCode: string; namespace: string; name: string; mode?: string }>();
const navigate = useNavigate();
const location = useLocation();
@@ -123,9 +119,9 @@ export default function WorkloadViewPage() {
const handleRestart = async () => {
const ok = await confirm({
title: t('kubernetes.deployment.restart'),
description: t('kubernetes.workloadviewpage.s6139f5', { kind: kind, name: name }),
confirmText: t('common.reboot'),
title: '滚动重启',
description: `确认重启 ${kind} ${name}?将触发滚动重启。`,
confirmText: '重启',
});
if (!ok) return;
setActionLoading(true);
@@ -135,10 +131,10 @@ export default function WorkloadViewPage() {
} else {
await kubernetesApi.restartDaemonSet(clusterCode, namespace, name);
}
toast({ title: t('kubernetes.workloadviewpage.s68a700'), description: t('kubernetes.workloadviewpage.sb0614d', { kind: kind }) });
toast({ title: '重启指令已下发', description: `${kind} 滚动重启已触发` });
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: t('kubernetes.deployment.restartFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '重启失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(false); }
};
@@ -146,11 +142,11 @@ export default function WorkloadViewPage() {
setActionLoading(true);
try {
await kubernetesApi.scaleStatefulSet(clusterCode, namespace, name, scaleValue);
toast({ title: t('kubernetes.workloadviewpage.s0b3ea1'), description: t('kubernetes.workloadviewpage.s27c3cf', { scaleValue: scaleValue }) });
toast({ title: '扩缩容成功', description: `StatefulSet 副本数已更新为 ${scaleValue}` });
setScaleModal(false);
setTimeout(loadData, 1000);
} catch (e) {
toast({ title: t('kubernetes.workloadviewpage.s0b329f'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: '扩缩容失败', description: e?.message || String(e), variant: 'destructive' });
} finally { setActionLoading(false); }
};
@@ -194,7 +190,7 @@ export default function WorkloadViewPage() {
const modeTabs = (
<div className="flex items-center gap-1 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-0.5">
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'view' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('view')}>{t('common.view')}</button>
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'view' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('view')}>查看</button>
<button className={`px-3 py-1 text-xs rounded transition-colors ${mode === 'yaml' ? 'bg-[var(--dg-blue)]/20 text-[var(--dg-blue)]' : 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]'}`} onClick={() => handleModeChange('yaml')}>YAML</button>
</div>
);
@@ -206,7 +202,7 @@ export default function WorkloadViewPage() {
subtitle={`${clusterCode} / ${namespace} · ${kind}`}
icon={<Boxes className="h-5 w-5" />}
loading={loading}
loadingLabel=t('kubernetes.workloadviewpage.s4eb429')
loadingLabel="加载工作负载..."
actions={(
<>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => navigate(-1)}>
@@ -219,7 +215,7 @@ export default function WorkloadViewPage() {
</Button>
)}
<Button variant="outline" size="sm" className="dg-btn-secondary" disabled={actionLoading} onClick={handleRestart}>
<RotateCcw className="h-3.5 w-3.5 mr-1" />{actionLoading ? t('kubernetes.workloadviewpage.s9ac104') : t('common.reboot')}
<RotateCcw className="h-3.5 w-3.5 mr-1" />{actionLoading ? '重启中...' : '重启'}
</Button>
<Button variant="outline" size="sm" className="dg-btn-secondary" onClick={() => setYamlModal(true)}>
<FileCode className="h-3.5 w-3.5 mr-1" />YAML
@@ -231,8 +227,8 @@ export default function WorkloadViewPage() {
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{kind}</Badge>
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{namespace}</Badge>
{isHealthy
? <Badge className="bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30">{t('common.healthy')}</Badge>
: <Badge className="bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30">{t('kubernetes.workloadviewpage.sf339d4')}</Badge>}
? <Badge className="bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30">健康</Badge>
: <Badge className="bg-[var(--dg-orange)]/20 text-[var(--dg-orange)] border-[var(--dg-orange)]/30">更新中</Badge>}
</div>
{!loading && (mode === 'yaml' ? (
@@ -255,21 +251,21 @@ export default function WorkloadViewPage() {
<div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
{isSts ? (
<>
<StatCard label=t('kubernetes.workloadviewpage.sea6396') value={`${readyReplicas}/${replicas}`} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} sub={isHealthy ? t('kubernetes.workloadviewpage.s23c944') : t('kubernetes.workloadviewpage.sac1002')} />
<StatCard label=t('kubernetes.hpa.currentReplicas') value={currentReplicas} color={STATUS_COLORS.blue} />
<StatCard label=t('kubernetes.deployment.updatedReplicas') value={updatedReplicas} color={STATUS_COLORS.green} />
<StatCard label=t('kubernetes.workloadviewpage.sf592ef') value={spec.serviceName || '-'} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.workloadviewpage.s55edf2') value={pods.length} color="var(--dg-text-secondary)" />
<StatCard label=t('common.createdAt') value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
<StatCard label="副本就绪" value={`${readyReplicas}/${replicas}`} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} sub={isHealthy ? '全部就绪' : '部分未就绪'} />
<StatCard label="当前副本" value={currentReplicas} color={STATUS_COLORS.blue} />
<StatCard label="已更新副本" value={updatedReplicas} color={STATUS_COLORS.green} />
<StatCard label="服务名" value={spec.serviceName || '-'} color="var(--dg-text-secondary)" />
<StatCard label="Pod 数量" value={pods.length} color="var(--dg-text-secondary)" />
<StatCard label="创建时间" value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
</>
) : (
<>
<StatCard label=t('kubernetes.workloadviewpage.sd78bc8') value={desiredScheduled} color={STATUS_COLORS.blue} />
<StatCard label=t('kubernetes.workloadviewpage.sb76164') value={currentScheduled} color="var(--dg-text-secondary)" />
<StatCard label=t('kubernetes.daemonset.numberReady') value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} />
<StatCard label=t('kubernetes.daemonset.numberAvailable') value={numberAvailable} color={STATUS_COLORS.green} />
<StatCard label=t('deploy.toast.updated') value={numberUpdated} color="var(--dg-text-secondary)" />
<StatCard label=t('common.createdAt') value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
<StatCard label="期望调度" value={desiredScheduled} color={STATUS_COLORS.blue} />
<StatCard label="当前调度" value={currentScheduled} color="var(--dg-text-secondary)" />
<StatCard label="就绪数量" value={numberReady} color={isHealthy ? STATUS_COLORS.green : STATUS_COLORS.orange} />
<StatCard label="可用数量" value={numberAvailable} color={STATUS_COLORS.green} />
<StatCard label="已更新" value={numberUpdated} color="var(--dg-text-secondary)" />
<StatCard label="创建时间" value={<span className="text-xs">{formatK8sTime(manifest?.metadata?.creationTimestamp)}</span>} color="var(--dg-text-secondary)" />
</>
)}
</div>
@@ -284,18 +280,18 @@ export default function WorkloadViewPage() {
</CardHeader>
<CardContent className="pt-0 space-y-2 text-xs">
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s0511a2')}</span>
<span className="text-[var(--dg-text-muted)]">策略类型</span>
<Badge variant="outline" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]">{strategyType}</Badge>
</div>
{strategyType === 'RollingUpdate' && isSts && updateStrategy.rollingUpdate && (
<>
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s45cb9d')}</span>
<span className="text-[var(--dg-text-muted)]">分区 (partition)</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{updateStrategy.rollingUpdate.partition ?? 0}</span>
</div>
{updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.daemonset.maxUnavailable')}</span>
<span className="text-[var(--dg-text-muted)]">最大不可用</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div>
)}
@@ -305,13 +301,13 @@ export default function WorkloadViewPage() {
<>
{updateStrategy.rollingUpdate.maxUnavailable && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.daemonset.maxUnavailable')}</span>
<span className="text-[var(--dg-text-muted)]">最大不可用</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxUnavailable === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxUnavailable) : updateStrategy.rollingUpdate.maxUnavailable}</span>
</div>
)}
{updateStrategy.rollingUpdate.maxSurge && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.sfed4ce')}</span>
<span className="text-[var(--dg-text-muted)]">最大 surge</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{typeof updateStrategy.rollingUpdate.maxSurge === 'object' ? JSON.stringify(updateStrategy.rollingUpdate.maxSurge) : updateStrategy.rollingUpdate.maxSurge}</span>
</div>
)}
@@ -319,12 +315,12 @@ export default function WorkloadViewPage() {
)}
{isSts && (
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.statefulset.podManagementPolicy')}</span>
<span className="text-[var(--dg-text-muted)]">Pod 管理策略</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{spec.podManagementPolicy || 'OrderedReady'}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-[var(--dg-text-muted)]">{t('kubernetes.workloadviewpage.s450a4e')}</span>
<span className="text-[var(--dg-text-muted)]">修订历史限制</span>
<span className="text-[var(--dg-text-secondary)] font-mono">{spec.revisionHistoryLimit ?? 10}</span>
</div>
</CardContent>
@@ -373,10 +369,10 @@ export default function WorkloadViewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.name')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.accessMode')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('k8s.resource.storageClass')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('deploy.table.size')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">访问模式</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">存储类</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">大小</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -418,7 +414,7 @@ export default function WorkloadViewPage() {
</div>
)}
{containers.length === 0 ? (
<p className="text-xs text-[var(--dg-text-muted)] py-3">{t('kubernetes.workloadviewpage.se4b610')}</p>
<p className="text-xs text-[var(--dg-text-muted)] py-3">暂无容器数据,请查看 YAML</p>
) : (
<div className="space-y-3">
<p className="text-[11px] text-[var(--dg-text-muted)] mb-1 uppercase tracking-wide">Containers</p>
@@ -441,17 +437,17 @@ export default function WorkloadViewPage() {
<Table>
<TableHeader>
<TableRow className="border-[var(--dg-border)] hover:bg-transparent">
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.pod.podName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.status')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('kubernetes.pod.nodeName')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Pod 名称</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">状态</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">所在节点</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">Pod IP</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.reboot')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">{t('common.actions')}</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">重启</TableHead>
<TableHead className="text-[var(--dg-text-secondary)]">操作</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{pods.length === 0 ? (
<TableRow><TableCell colSpan={6} className="text-center text-[var(--dg-text-muted)] py-8">{t('k8s.deploymentDetail.noPod')}</TableCell></TableRow>
<TableRow><TableCell colSpan={6} className="text-center text-[var(--dg-text-muted)] py-8">暂无 Pod</TableCell></TableRow>
) : pods.map((pod: JsonData) => (
<TableRow key={pod.name} className="border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/30">
<TableCell className="font-medium text-[var(--dg-text-primary)]">{pod.name}</TableCell>
@@ -488,7 +484,7 @@ export default function WorkloadViewPage() {
{scaleModal && (
<div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center" onClick={() => setScaleModal(false)}>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-lg p-6 w-80" onClick={e => e.stopPropagation()}>
<h3 className="text-sm font-semibold text-[var(--dg-text-primary)] mb-4">{t('kubernetes.workloadviewpage.s7f541e')}</h3>
<h3 className="text-sm font-semibold text-[var(--dg-text-primary)] mb-4">伸缩 StatefulSet</h3>
<div className="flex items-center justify-center gap-4 mb-4">
<Button variant="outline" size="icon" className="h-9 w-9" onClick={() => setScaleValue(Math.max(0, scaleValue - 1))}>
<Minus className="h-4 w-4" />
@@ -499,9 +495,9 @@ export default function WorkloadViewPage() {
</Button>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" className="flex-1 border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setScaleModal(false)}>{t('common.cancel')}</Button>
<Button variant="outline" size="sm" className="flex-1 border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setScaleModal(false)}>取消</Button>
<Button size="sm" className="flex-1 bg-[var(--dg-blue)] hover:opacity-90" disabled={actionLoading} onClick={handleScale}>
{actionLoading ? t('pipeline.executing') : t('common.confirm')}
{actionLoading ? '执行中...' : '确认'}
</Button>
</div>
</div>
@@ -548,7 +544,6 @@ export default function WorkloadViewPage() {
// Container info sub-component
function ContainerInfo({ c }: { c: JsonData}) {
const { t } = useTranslation();
return (
<div className="border border-[var(--dg-border)] rounded-lg p-3 bg-[var(--dg-bg-primary)]/30">
<div className="flex items-center justify-between mb-2">
@@ -5,9 +5,9 @@ import { Button } from '@/components/ui/button';
import { ModalOverlay } from '@/components/ui/modal-overlay';
import { useToast } from '@/hooks/use-toast';
import { kubernetesApi } from '@/api';
import { useTranslation } from 'react-i18next';
import { YamlCodeMirror } from './YamlCodeMirror';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlImportDialogProps {
clusterCode: string;
@@ -23,17 +23,17 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
const apply = async () => {
if (!content.trim()) {
toast({ title: t('kubernetes.yamlimportdialog.s81d637'), variant: 'destructive' });
toast({ title: t('k8s.yamlImport.empty'), variant: 'destructive' });
return;
}
setApplying(true);
try {
await kubernetesApi.applyYAML(clusterCode, content);
toast({ title: t('system.importSuccess'), description: t('kubernetes.yamlimportdialog.sb66e8e') });
toast({ title: t('k8s.yamlImport.success'), description: t('k8s.yamlImport.successDesc') });
onApplied?.();
onClose();
} catch (e) {
toast({ title: t('common.importFailed'), description: (e as JsonData).message, variant: 'destructive' });
toast({ title: t('k8s.yamlImport.failed'), description: (e as JsonData).message, variant: 'destructive' });
} finally { setApplying(false); }
};
@@ -47,8 +47,8 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
<div className="flex items-center gap-2">
<Upload className="h-5 w-5 text-[var(--dg-text-muted)]" />
<div>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)]">{t('kubernetes.yaml.importYaml')}</h2>
<p className="text-xs text-[var(--dg-text-muted)]">{t('kubernetes.yamlimportdialog.s92b733')}</p>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)]">{t('k8s.yamlImport.title')}</h2>
<p className="text-xs text-[var(--dg-text-muted)]">{t('k8s.yamlImport.hint')}</p>
</div>
</div>
<Button variant="ghost" size="icon" className="h-8 w-8" onClick={onClose}><X className="h-4 w-4" /></Button>
@@ -65,7 +65,7 @@ export function YamlImportDialog({ clusterCode, onClose, onApplied }: YamlImport
<Button variant="outline" onClick={onClose}>{t('common.cancel')}</Button>
<Button className="bg-blue-600 hover:bg-blue-700" onClick={apply} disabled={applying}>
{applying ? <Loader2 className="h-4 w-4 animate-spin mr-1" /> : <Upload className="h-4 w-4 mr-1" />}
应用
{t('k8s.yamlImport.apply')}
</Button>
</div>
</div>
@@ -11,7 +11,6 @@ import { YamlEditorToolbar } from './YamlEditorToolbar';
import { YamlCodeMirror } from './YamlCodeMirror';
import { downloadYamlFile } from '@/utils/export';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
interface YamlViewerProps {
clusterCode: string;
@@ -38,7 +37,6 @@ export function YamlViewer({
autoEdit = false, inline = false, initialYaml, readOnly: readOnlyProp,
loadYamlFn, saveYamlFn, resourceHint,
}: YamlViewerProps) {
const { t } = useTranslation();
const { toast } = useToast();
const resCfg = getYamlResourceConfig(resource);
const readOnly = readOnlyProp ?? resCfg.readOnly;
@@ -75,7 +73,7 @@ export function YamlViewer({
setRawYaml(text);
await applyStripped(text);
} catch (e) {
toast({ title: t('kubernetes.yamlviewer.s1a72e3'), description: (e as JsonData).message, variant: 'destructive' });
toast({ title: '获取YAML失败', description: (e as JsonData).message, variant: 'destructive' });
const err = `# Error: ${(e as Error).message}`;
setRawYaml(err);
setDisplayYaml(err);
@@ -105,14 +103,14 @@ export function YamlViewer({
} else {
await kubernetesApi.updateResourceYaml(clusterCode, namespace, resource, name, yamlStr);
}
toast({ title: t('common.savedSuccessfully'), description: saveYamlFn ? t('kubernetes.yamlviewer.s68f258') : t('kubernetes.yamlviewer.se7e1ac', { resource: resource, name: name }) });
toast({ title: '保存成功', description: saveYamlFn ? '多文档 YAML 已应用' : `${resource}/${name} 已更新` });
setEditing(false);
setRawYaml(yamlStr);
setDisplayYaml(yamlStr);
setEditYaml(yamlStr);
onSaved?.();
} catch (e) {
toast({ title: t('common.saveFailed'), description: (e as Error)?.message || String(e), variant: 'destructive' });
toast({ title: '保存失败', description: (e as Error)?.message || String(e), variant: 'destructive' });
} finally { setSaving(false); }
};
@@ -126,7 +124,7 @@ export function YamlViewer({
const downloadYaml = () => {
downloadYamlFile(yamlDownloadFilename(resource, namespace, name), currentYaml());
toast({ title: t('kubernetes.yamlviewer.s9719fe'), description: yamlDownloadFilename(resource, namespace, name) });
toast({ title: '已下载', description: yamlDownloadFilename(resource, namespace, name) });
};
const display = editing ? editYaml : (showRaw ? rawYaml : displayYaml);
@@ -188,7 +186,7 @@ export function YamlViewer({
<div className="min-w-0 flex-1">
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] truncate" title={`${resCfg.label} YAML — ${name}`}>
{resCfg.label} YAML — {name}
{readOnly && <span className="ml-2 text-xs font-normal dg-text-muted">{t('common.readonly')}</span>}
{readOnly && <span className="ml-2 text-xs font-normal dg-text-muted">只读</span>}
</h2>
<p className="text-xs dg-text-muted truncate" title={`${namespace} · ${clusterCode}`}>{namespace} · {clusterCode}</p>
</div>
@@ -2,7 +2,6 @@
// Deployment 多文档 YAML(Deployment + 关联 Service)加载与保存 // Logan.Li
import { kubernetesApi } from '@/api';
import {
import i18n from '@/i18n';
manifestToEditableYaml,
parseEditableManifest,
parseEditableManifests,
@@ -81,12 +80,12 @@ export async function saveDeploymentBundleYaml(
yamlText: string,
): Promise<void> {
const { manifests } = await parseEditableManifests(yamlText);
if (manifests.length === 0) throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s47161e'));
if (manifests.length === 0) throw new Error('YAML 内容为空或解析失败');
for (const manifest of manifests) {
const kind = String(manifest.kind || '').toLowerCase();
const name = String(manifest.metadata?.name || '').trim();
if (!kind || !name) throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s659c1b'));
if (!kind || !name) throw new Error('每个 YAML 文档必须包含 kind 和 metadata.name');
const docYaml = await prepareManifestForSave(manifest);
if (kind === 'deployment') {
@@ -97,6 +96,6 @@ export async function saveDeploymentBundleYaml(
await kubernetesApi.applyYAML(clusterCode, docYaml);
continue;
}
throw new Error(i18n.t('kubernetes.deploymentBundleYaml.s94a65d', { manifest.kind: manifest.kind }));
throw new Error(`不支持的资源类型: ${manifest.kind}(仅支持 Deployment / Service)`);
}
}
@@ -30,7 +30,7 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
const handleCreate = async () => {
if (!form.name.trim()) {
toast({ title: t('kubernetes.createhpadialog.sdf09ff'), variant: 'destructive' });
toast({ title: t('k8s.hpa.nameRequired'), variant: 'destructive' });
return;
}
setLoading(true);
@@ -45,24 +45,24 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
cpuPercent: form.cpuPercent,
memPercent: form.memPercent,
});
toast({ title: t('kubernetes.createhpadialog.s74b0b0') });
toast({ title: t('k8s.hpa.createSuccess') });
setOpen(false);
onCreated();
setForm({ name: '', minReplicas: 1, maxReplicas: 10, cpuPercent: 80, memPercent: 0 });
} catch (e: any) {
toast({ title: t('monitor.quickSetupFailed'), description: e?.message || String(e), variant: 'destructive' });
toast({ title: t('k8s.hpa.createFailed'), description: e?.message || String(e), variant: 'destructive' });
} finally { setLoading(false); }
};
return (
<>
<Button variant="outline" size="sm" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)]" onClick={() => setOpen(true)}>
<Plus className="h-3.5 w-3.5 mr-1" />创建 HPA
<Plus className="h-3.5 w-3.5 mr-1" />{t('k8s.hpa.create')}
</Button>
{open && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4" onClick={() => setOpen(false)}>
<div className="bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-xl w-[480px] max-w-[92vw] max-h-[85vh] flex flex-col" onClick={(e) => e.stopPropagation()}>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] px-6 pt-6 pb-4 shrink-0">{t('k8s.hpaCronHpa.createHpa')}</h2>
<h2 className="text-lg font-bold text-[var(--dg-text-primary)] px-6 pt-6 pb-4 shrink-0">{t('k8s.hpa.create')}</h2>
<div className="flex-1 min-h-0 overflow-y-auto px-6 space-y-3">
<div>
<Label className="dg-text-secondary text-sm">{t('common.name')}</Label>
@@ -71,20 +71,20 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">{t('common.target')}</Label>
<p className="text-[var(--dg-text-secondary)] text-sm mt-1 bg-[var(--dg-bg-tertiary)] rounded px-3 py-2 truncate" title={t('kubernetes.createhpadialog.s7aa398', { deploymentName: deploymentName, namespace: namespace })}>
Deployment: {deploymentName} · 命名空间: {namespace}
<Label className="dg-text-secondary text-sm">{t('k8s.hpa.target')}</Label>
<p className="text-[var(--dg-text-secondary)] text-sm mt-1 bg-[var(--dg-bg-tertiary)] rounded px-3 py-2 truncate" title={t('k8s.hpa.targetSummary', { deployment: deploymentName, namespace })}>
{t('k8s.hpa.targetSummary', { deployment: deploymentName, namespace })}
</p>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s6a5bed')}</Label>
<Label className="dg-text-secondary text-sm">{t('k8s.hpa.minReplicas')}</Label>
<Input type="number" value={form.minReplicas} min={1}
onChange={(e) => setForm({ ...form, minReplicas: Number(e.target.value) })}
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.sc3f2cf')}</Label>
<Label className="dg-text-secondary text-sm">{t('k8s.hpa.maxReplicas')}</Label>
<Input type="number" value={form.maxReplicas} min={1}
onChange={(e) => setForm({ ...form, maxReplicas: Number(e.target.value) })}
className="dg-input mt-1" />
@@ -92,13 +92,13 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s94bfd4')}</Label>
<Label className="dg-text-secondary text-sm">{t('k8s.hpa.cpuTarget')}</Label>
<Input type="number" value={form.cpuPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, cpuPercent: Number(e.target.value) })}
className="dg-input mt-1" />
</div>
<div>
<Label className="dg-text-secondary text-sm">{t('kubernetes.createhpadialog.s82f202')} <span className="dg-text-muted">{t('common.optional')}</span></Label>
<Label className="dg-text-secondary text-sm">{t('k8s.hpa.memTarget')} <span className="dg-text-muted">{t('common.optional')}</span></Label>
<Input type="number" value={form.memPercent} min={0} max={100}
onChange={(e) => setForm({ ...form, memPercent: Number(e.target.value) })}
className="dg-input mt-1" />
@@ -108,7 +108,7 @@ export function CreateHPADialog({ clusterCode, namespace, deploymentName, onCrea
<div className="flex justify-end gap-2 px-6 py-4 border-t border-[var(--dg-border)] shrink-0">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={() => setOpen(false)}>{t('common.cancel')}</Button>
<Button className="bg-blue-600 hover:bg-blue-700" disabled={loading} onClick={handleCreate}>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : i18n.t('common.create')}
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : t('common.create')}
</Button>
</div>
</div>
@@ -7,8 +7,8 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { CreateHPADialog } from './CreateHPADialog';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import type { JsonData } from '@/types/common';
export interface DeploymentOverviewProps {
deploymentName: string;
@@ -44,25 +44,25 @@ export function DeploymentOverview({
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<Button variant="ghost" size="sm" className="dg-text-secondary" onClick={onBack}>
<ArrowLeft className="h-4 w-4 mr-1" />返回
<ArrowLeft className="h-4 w-4 mr-1" />{t('common.back')}
</Button>
<div>
<div className="flex items-center gap-2">
<h1 className="text-xl font-bold text-[var(--dg-text-primary)]">{deploymentName}</h1>
<Badge variant="outline" className="border-[var(--dg-border)] dg-text-secondary">{namespace}</Badge>
</div>
<p className="text-sm dg-text-muted mt-0.5">镜像: {deployment.image || '-'}</p>
<p className="text-sm dg-text-muted mt-0.5">{t('k8s.overview.imageLabel')}: {deployment.image || '-'}</p>
</div>
</div>
<Button variant="outline" size="sm" className="border-[var(--dg-border)] dg-text-secondary" onClick={onRefresh}>
<RefreshCw className="h-4 w-4 mr-1" />刷新
<RefreshCw className="h-4 w-4 mr-1" />{t('common.refresh')}
</Button>
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">{t('kubernetes.deploymentoverview.sb4cac1')}</p>
<p className="text-xs dg-text-muted">{t('k8s.overview.replicaStatus')}</p>
<p className={`text-lg font-bold ${isHealthy ? 'dg-text-green' : 'dg-text-yellow'}`}>
{ready}/{total}
</p>
@@ -70,13 +70,13 @@ export function DeploymentOverview({
</Card>
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">{t('k8s.column.availableReplicas')}</p>
<p className="text-xs dg-text-muted">{t('k8s.overview.availableReplicas')}</p>
<p className="text-lg font-bold dg-text-blue">{available}</p>
</CardContent>
</Card>
<Card className="dg-card">
<CardContent className="p-3">
<p className="text-xs dg-text-muted">{t('k8s.column.image')}</p>
<p className="text-xs dg-text-muted">{t('k8s.overview.image')}</p>
<p className="text-sm font-mono text-[var(--dg-text-secondary)] truncate max-w-[200px]" title={deployment.image}>
{deployment.image?.split('/').pop() || '-'}
</p>
@@ -86,10 +86,10 @@ export function DeploymentOverview({
<CardContent className="p-3">
<p className="text-xs dg-text-muted">HPA</p>
{hpas.length > 0 ? (
<p className="text-lg font-bold dg-text-purple">{t('alert.enabled')}</p>
<p className="text-lg font-bold dg-text-purple">{t('common.enabled')}</p>
) : (
<div className="flex items-center justify-between">
<p className="text-lg font-bold dg-text-muted">{t('k8s.dnsHost.notConfigured')}</p>
<p className="text-lg font-bold dg-text-muted">{t('k8s.overview.notConfigured')}</p>
<CreateHPADialog
clusterCode={clusterCode}
namespace={namespace}
@@ -133,14 +133,14 @@ export function DeploymentOverview({
onClick={onRestart}
>
{actionLoading === 'restart' ? <Loader2 className="h-4 w-4 mr-1 animate-spin" /> : <RotateCw className="h-4 w-4 mr-1" />}
滚动重启
{t('k8s.cicd.rollingRestart')}
</Button>
<Button
variant="outline" size="sm" className="border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"
onClick={onToggleImageUpdate}
>
<Upload className="h-4 w-4 mr-1" />
更新镜像
{t('k8s.editImage.updateImage')}
</Button>
</div>
{showImageUpdate && (
@@ -148,7 +148,7 @@ export function DeploymentOverview({
<Input
value={newImage}
onChange={(e) => onNewImageChange(e.target.value)}
placeholder=t('kubernetes.deploymentoverview.s416d7e')
placeholder={t('k8s.overview.newImagePlaceholder')}
className="flex-1 h-9 dg-input text-[var(--dg-text-primary)] text-sm font-mono"
/>
<Button size="sm" className="bg-blue-600 hover:bg-blue-700"
@@ -19,10 +19,10 @@ import {
Zap,
Network,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { arrToText, textToArr } from './container-utils';
import type {
import { useTranslation } from 'react-i18next';
ContainerEditorProps, ProbeEditorProps, LifecycleHandlerEditorProps,
BoolToggleProps, ProbeDef, LifecycleHandler,
} from './types';
@@ -37,25 +37,25 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 基本设置 ---- */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.sa51cd0')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.name')}</Label>
<Input value={c.name} onChange={e => onUpdate({ name: e.target.value })}
placeholder="my-app"
className="mt-1 dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s332ca5')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.image')}</Label>
<Input value={c.image} onChange={e => onUpdate({ image: e.target.value })}
placeholder="nginx:1.25"
className="mt-1 dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.deployment.imagePullPolicy')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.imagePullPolicy')}</Label>
<Select value={c.imagePullPolicy || '__none'} onValueChange={v => onUpdate({ imagePullPolicy: v === '__none' ? '' : v })}>
<SelectTrigger className="mt-1 dg-input text-xs h-8">
<SelectValue />
</SelectTrigger>
<SelectContent className="dg-input">
<SelectItem value="__none" className="dg-text-secondary">{t('kubernetes.containereditor.sd2f3ee')}</SelectItem>
<SelectItem value="__none" className="dg-text-secondary">{t('k8s.container.pullPolicyNone')}</SelectItem>
<SelectItem value="Always" className="text-[var(--dg-text-primary)]">Always</SelectItem>
<SelectItem value="IfNotPresent" className="text-[var(--dg-text-primary)]">IfNotPresent</SelectItem>
<SelectItem value="Never" className="text-[var(--dg-text-primary)]">Never</SelectItem>
@@ -63,7 +63,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Select>
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s4867b9')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.workingDir')}</Label>
<Input value={c.workingDir || ''} onChange={e => onUpdate({ workingDir: e.target.value })}
placeholder="/app"
className="mt-1 dg-input font-mono text-xs h-8" />
@@ -73,13 +73,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 命令与参数 ---- */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s34ab0f')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.command')}</Label>
<Textarea value={arrToText(c.command)} placeholder={"/bin/sh\n-c"}
onChange={e => onUpdate({ command: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.containereditor.s6dd286')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.container.args')}</Label>
<Textarea value={arrToText(c.args)} placeholder={"--config=/etc/app.yaml\n--debug"}
onChange={e => onUpdate({ args: textToArr(e.target.value) })}
className="mt-1 dg-input font-mono text-xs min-h-[60px]" />
@@ -89,10 +89,10 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 环境变量 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><Terminal className="h-3.5 w-3.5 dg-text-cyan" /> {t('pipeline.envVar')}</div>
<div className={sectionBtn}><Terminal className="h-3.5 w-3.5 dg-text-cyan" /> {t('k8s.container.envVars')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ env: [...c.env, { name: '', value: '' }] })}>
<Plus className="h-3 w-3 mr-1" />新增
<Plus className="h-3 w-3 mr-1" />{t('common.add')}
</Button>
</div>
<div className="space-y-1.5">
@@ -110,17 +110,17 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.env.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s9f809d')}</p>}
{c.env.length === 0 && <p className="text-[11px] dg-text-muted">{t('k8s.container.noEnv')}</p>}
</div>
</div>
{/* ---- 端口 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><Network className="h-3.5 w-3.5 text-indigo-400" /> {t('server.csv.port')}</div>
<div className={sectionBtn}><Network className="h-3.5 w-3.5 text-indigo-400" /> {t('k8s.container.ports')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ ports: [...c.ports, { name: '', containerPort: '', protocol: 'TCP' }] })}>
<Plus className="h-3 w-3 mr-1" />新增
<Plus className="h-3 w-3 mr-1" />{t('common.add')}
</Button>
</div>
<div className="space-y-1.5">
@@ -148,34 +148,34 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.ports.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sbc8b87')}</p>}
{c.ports.length === 0 && <p className="text-[11px] dg-text-muted">{t('k8s.container.noPortsExposed')}</p>}
</div>
</div>
{/* ---- 资源 requests/limits ---- */}
<div>
<div className={sectionBtn}><Cpu className="h-3.5 w-3.5 dg-text-yellow" /> {t('kubernetes.containereditor.s0b1499')}</div>
<div className={sectionBtn}><Cpu className="h-3.5 w-3.5 dg-text-yellow" /> {t('k8s.container.resources')}</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-2">
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.node.cpuRequests')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.cpuRequest')}</Label>
<Input value={c.resources.requests?.cpu || ''} placeholder="100m"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s96ac88')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.cpuLimit')}</Label>
<Input value={c.resources.limits?.cpu || ''} placeholder="500m"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, cpu: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.node.memoryRequests')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.memRequest')}</Label>
<Input value={c.resources.requests?.memory || ''} placeholder="128Mi"
onChange={e => onUpdate({ resources: { ...c.resources, requests: { ...c.resources.requests, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sa0a98f')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.memLimit')}</Label>
<Input value={c.resources.limits?.memory || ''} placeholder="512Mi"
onChange={e => onUpdate({ resources: { ...c.resources, limits: { ...c.resources.limits, memory: e.target.value } } })}
className="dg-input font-mono text-xs h-8" />
@@ -185,11 +185,11 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 健康检查 ---- */}
<div>
<div className={sectionBtn}><Heart className="h-3.5 w-3.5 text-rose-400" /> {t('kubernetes.containereditor.s6779ab')}</div>
<div className={sectionBtn}><Heart className="h-3.5 w-3.5 text-rose-400" /> {t('k8s.container.probes')}</div>
<div className="space-y-2">
{(['livenessProbe', 'readinessProbe', 'startupProbe'] as const).map(pt => (
<ProbeEditor key={pt}
label={{ livenessProbe: t('kubernetes.containereditor.sff49b1'), readinessProbe: t('kubernetes.containereditor.s176e68'), startupProbe: t('kubernetes.containereditor.sc5a531') }[pt]}
label={t({ livenessProbe: 'k8s.container.liveness', readinessProbe: 'k8s.container.readiness', startupProbe: 'k8s.container.startup' }[pt])}
probe={c[pt]}
onChange={(p) => onUpdate({ [pt]: p } as Record<string, unknown>)}
/>
@@ -199,24 +199,24 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 生命周期 ---- */}
<div>
<div className={sectionBtn}><Zap className="h-3.5 w-3.5 dg-text-yellow" /> {t('kubernetes.containereditor.s12d037')}</div>
<div className={sectionBtn}><Zap className="h-3.5 w-3.5 dg-text-yellow" /> {t('k8s.container.lifecycle')}</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<LifecycleHandlerEditor label=t('kubernetes.containereditor.s650280') handler={c.lifecycle?.postStart}
<LifecycleHandlerEditor label={t('k8s.container.postStart')} handler={c.lifecycle?.postStart}
onChange={h => onUpdate({ lifecycle: { ...c.lifecycle, postStart: h } })} />
<LifecycleHandlerEditor label=t('kubernetes.containereditor.s5b7228') handler={c.lifecycle?.preStop}
<LifecycleHandlerEditor label={t('k8s.container.preStop')} handler={c.lifecycle?.preStop}
onChange={h => onUpdate({ lifecycle: { ...c.lifecycle, preStop: h } })} />
</div>
{!c.lifecycle && (
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px] mt-1"
onClick={() => onUpdate({ lifecycle: { postStart: { type: 'none' }, preStop: { type: 'none' } } })}>
<Plus className="h-3 w-3 mr-1" />启用生命周期回调
<Plus className="h-3 w-3 mr-1" />{t('k8s.container.enableLifecycle')}
</Button>
)}
</div>
{/* ---- 安全上下文 ---- */}
<div>
<div className={sectionBtn}><Shield className="h-3.5 w-3.5 dg-text-green" /> {t('kubernetes.containereditor.s195d42')}</div>
<div className={sectionBtn}><Shield className="h-3.5 w-3.5 dg-text-green" /> {t('k8s.container.securityContext')}</div>
{c.securityContext ? (
<div className="space-y-2 border border-[var(--dg-border)] rounded-md p-3 bg-[var(--dg-bg-primary)]/30">
<div className="grid grid-cols-2 md:grid-cols-3 gap-2">
@@ -233,13 +233,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s3142a7')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.capsAdd')}</Label>
<Input value={(c.securityContext.capabilitiesAdd || []).join(',')} placeholder="NET_ADMIN"
onChange={e => onUpdate({ securityContext: { ...c.securityContext!, capabilitiesAdd: e.target.value.split(',').map(s => s.trim()).filter(Boolean) } })}
className="dg-input font-mono text-xs h-8" />
</div>
<div>
<Label className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.sd705f3')}</Label>
<Label className="text-[11px] dg-text-muted">{t('k8s.container.capsDrop')}</Label>
<Input value={(c.securityContext.capabilitiesDrop || []).join(',')} placeholder="ALL"
onChange={e => onUpdate({ securityContext: { ...c.securityContext!, capabilitiesDrop: e.target.value.split(',').map(s => s.trim()).filter(Boolean) } })}
className="dg-input font-mono text-xs h-8" />
@@ -257,13 +257,13 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</div>
<Button size="sm" variant="ghost" className="h-6 dg-text-red text-[11px]"
onClick={() => onUpdate({ securityContext: null })}>
<Trash2 className="h-3 w-3 mr-1" />移除安全上下文
<Trash2 className="h-3 w-3 mr-1" />{t('k8s.container.removeSecurity')}
</Button>
</div>
) : (
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ securityContext: { runAsNonRoot: false, privileged: false } })}>
<Plus className="h-3 w-3 mr-1" />启用安全上下文
<Plus className="h-3 w-3 mr-1" />{t('k8s.container.enableSecurity')}
</Button>
)}
</div>
@@ -271,22 +271,22 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
{/* ---- 卷挂载 ---- */}
<div>
<div className="flex items-center justify-between mb-2">
<div className={sectionBtn}><FolderOpen className="h-3.5 w-3.5 text-teal-400" /> {t('kubernetes.containereditor.s778eec')}</div>
<div className={sectionBtn}><FolderOpen className="h-3.5 w-3.5 text-teal-400" /> {t('k8s.container.volumeMounts')}</div>
<Button size="sm" variant="outline" className="h-6 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-[11px]"
onClick={() => onUpdate({ volumeMounts: [...c.volumeMounts, { name: '', mountPath: '', subPath: '', readOnly: false }] })}>
<Plus className="h-3 w-3 mr-1" />新增
<Plus className="h-3 w-3 mr-1" />{t('common.add')}
</Button>
</div>
<div className="space-y-1.5">
{c.volumeMounts.map((m, mi) => (
<div key={mi} className="grid grid-cols-[1fr_1fr_1fr_60px_auto] gap-2 items-center">
<Input value={m.name} placeholder=t('kubernetes.containereditor.sb19f3d')
<Input value={m.name} placeholder={t('k8s.container.volumeName')}
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, name: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<Input value={m.mountPath} placeholder="/data"
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, mountPath: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<Input value={m.subPath || ''} placeholder=t('kubernetes.containereditor.s4f4937')
<Input value={m.subPath || ''} placeholder={t('k8s.container.subPathPlaceholder')}
onChange={e => { const n = [...c.volumeMounts]; n[mi] = { ...m, subPath: e.target.value }; onUpdate({ volumeMounts: n }); }}
className="dg-input font-mono text-xs h-8" />
<label className="flex items-center gap-1 text-[10px] dg-text-muted cursor-pointer">
@@ -300,7 +300,7 @@ export function ContainerEditor({ container, onUpdate }: ContainerEditorProps) {
</Button>
</div>
))}
{c.volumeMounts.length === 0 && <p className="text-[11px] dg-text-muted">{t('kubernetes.containereditor.s9b6826')}</p>}
{c.volumeMounts.length === 0 && <p className="text-[11px] dg-text-muted">{t('k8s.container.noMounts')}</p>}
</div>
</div>
</>
@@ -324,7 +324,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
{enabled && (
<>
<div className="flex items-center gap-2 mb-2">
<span className="text-[10px] dg-text-muted w-8">{t('common.type')}</span>
<span className="text-[10px] dg-text-muted w-8">{t('k8s.container.type')}</span>
<Select value={p.type || 'httpGet'} onValueChange={v => setField({ type: v as ProbeDef['type'] })}>
<SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue />
@@ -332,7 +332,7 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<SelectContent className="dg-input">
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</SelectItem>
<SelectItem value="tcpSocket" className="text-[var(--dg-text-primary)]">TCP Socket</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('kubernetes.containereditor.s16d93f')}</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('k8s.container.execCmd')}</SelectItem>
</SelectContent>
</Select>
</div>
@@ -344,52 +344,52 @@ function ProbeEditor({ label, probe, onChange }: ProbeEditorProps) {
<Input type="number" value={p.httpPort ?? ''} placeholder="8080"
onChange={e => setField({ httpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
<Input value={p.httpHost || ''} placeholder=t('kubernetes.containereditor.s3cf87c')
<Input value={p.httpHost || ''} placeholder={t('k8s.container.hostPlaceholder')}
onChange={e => setField({ httpHost: e.target.value })}
className="dg-input font-mono text-xs h-7" />
</div>
)}
{p.type === 'tcpSocket' && (
<div className="mb-2">
<Input type="number" value={p.tcpPort ?? ''} placeholder=t('server.csv.port')
<Input type="number" value={p.tcpPort ?? ''} placeholder={t('k8s.container.portPlaceholder')}
onChange={e => setField({ tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
)}
{p.type === 'exec' && (
<div className="mb-2">
<Textarea value={p.execCommand || ''} placeholder=t('kubernetes.containereditor.s743f00')
<Textarea value={p.execCommand || ''} placeholder={t('k8s.container.execCmdPlaceholder')}
onChange={e => setField({ execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" />
</div>
)}
<div className="grid grid-cols-5 gap-2">
<div>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.s39b4e6')}</Label>
<Label className="text-[10px] dg-text-muted">{t('k8s.container.delay')}</Label>
<Input type="number" value={p.initialDelaySeconds ?? ''} placeholder="10"
onChange={e => setField({ initialDelaySeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.sbbf419')}</Label>
<Label className="text-[10px] dg-text-muted">{t('k8s.container.interval')}</Label>
<Input type="number" value={p.periodSeconds ?? ''} placeholder="10"
onChange={e => setField({ periodSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">{t('kubernetes.containereditor.sde332f')}</Label>
<Label className="text-[10px] dg-text-muted">{t('k8s.container.timeout')}</Label>
<Input type="number" value={p.timeoutSeconds ?? ''} placeholder="1"
onChange={e => setField({ timeoutSeconds: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">{t('common.success')}</Label>
<Label className="text-[10px] dg-text-muted">{t('k8s.container.success')}</Label>
<Input type="number" value={p.successThreshold ?? ''} placeholder="1"
onChange={e => setField({ successThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
</div>
<div>
<Label className="text-[10px] dg-text-muted">{t('common.failed')}</Label>
<Label className="text-[10px] dg-text-muted">{t('k8s.container.failure')}</Label>
<Input type="number" value={p.failureThreshold ?? ''} placeholder="3"
onChange={e => setField({ failureThreshold: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
@@ -410,21 +410,21 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
<div className="border border-[var(--dg-border)] rounded-md p-2.5 bg-[var(--dg-bg-primary)]/30">
<span className="text-xs text-[var(--dg-text-secondary)] font-medium block mb-2">{label}</span>
<div className="flex items-center gap-2 mb-2">
<span className="text-[10px] dg-text-muted w-8">{t('common.type')}</span>
<span className="text-[10px] dg-text-muted w-8">{t('k8s.container.type')}</span>
<Select value={selVal} onValueChange={v => onChange({ ...h, type: (v === '__none' ? 'none' : v) as LifecycleHandler['type'] })}>
<SelectTrigger className="dg-input text-xs h-7 flex-1">
<SelectValue />
</SelectTrigger>
<SelectContent className="dg-input">
<SelectItem value="__none" className="dg-text-secondary">{t('kubernetes.containereditor.s2e3432')}</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('kubernetes.containereditor.s16d93f')}</SelectItem>
<SelectItem value="__none" className="dg-text-secondary">{t('k8s.container.none')}</SelectItem>
<SelectItem value="exec" className="text-[var(--dg-text-primary)]">{t('k8s.container.execCmd')}</SelectItem>
<SelectItem value="httpGet" className="text-[var(--dg-text-primary)]">HTTP GET</SelectItem>
<SelectItem value="tcpSocket" className="text-[var(--dg-text-primary)]">TCP Socket</SelectItem>
</SelectContent>
</Select>
</div>
{h.type === 'exec' && (
<Textarea value={h.execCommand || ''} placeholder=t('kubernetes.containereditor.s7970e5')
<Textarea value={h.execCommand || ''} placeholder={t('k8s.container.execCmdLinePlaceholder')}
onChange={e => onChange({ ...h, execCommand: e.target.value })}
className="dg-input font-mono text-xs min-h-[50px]" />
)}
@@ -439,7 +439,7 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
</div>
)}
{h.type === 'tcpSocket' && (
<Input type="number" value={h.tcpPort ?? ''} placeholder=i18n.t('server.csv.port')
<Input type="number" value={h.tcpPort ?? ''} placeholder={t('k8s.container.portPlaceholder')}
onChange={e => onChange({ ...h, tcpPort: e.target.value === '' ? undefined : Number(e.target.value) })}
className="dg-input font-mono text-xs h-7" />
)}
@@ -448,11 +448,10 @@ function LifecycleHandlerEditor({ label, handler, onChange }: LifecycleHandlerEd
}
function BoolToggle({ label, value, onChange }: BoolToggleProps) {
const { t } = useTranslation();
return (
<label className="flex items-center gap-1.5 cursor-pointer">
<Switch checked={value} onCheckedChange={onChange} />
<span className="text-[11px] dg-text-secondary font-mono">{label}</span>
</label>
);
}
}
@@ -45,14 +45,14 @@ export function ContainerGroupSection({
<Badge variant="outline" className={`border-[var(--dg-border)] dg-text-secondary text-[10px]`}>{containers.length}</Badge>
</div>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] text-[var(--dg-text-secondary)] text-xs" onClick={onAdd}>
<Plus className="h-3 w-3 mr-1" />新增容器
<Plus className="h-3 w-3 mr-1" />{t('k8s.container.add')}
</Button>
</div>
<p className="text-[11px] dg-text-muted">{description}</p>
</CardHeader>
<CardContent className="pt-0 space-y-3">
{containers.length === 0 && (
<div className="text-center py-6 dg-text-muted text-xs">{t('kubernetes.containergroupsection.s79ed70')}</div>
<div className="text-center py-6 dg-text-muted text-xs">{t('k8s.container.empty')}</div>
)}
{containers.map((c, idx) => {
const isOpen = openIndices.has(idx) || containers.length === 1;
@@ -63,21 +63,21 @@ export function ContainerGroupSection({
<div className="flex items-center gap-2">
{isOpen ? <ChevronDown className="h-4 w-4 dg-text-muted" /> : <ChevronRight className="h-4 w-4 dg-text-muted" />}
<Container className={`h-4 w-4 ${accentColor === 'blue' ? 'dg-text-blue' : 'dg-text-purple'}`} />
<span className="text-sm font-mono text-[var(--dg-text-primary)] font-semibold">{c.name || t('kubernetes.containergroupsection.sac52a9')}</span>
<span className="text-sm font-mono text-[var(--dg-text-primary)] font-semibold">{c.name || t('k8s.container.unnamed')}</span>
{c.image && <code className="text-[10px] dg-text-muted font-mono truncate max-w-[300px]">{c.image}</code>}
</div>
<div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
{onDuplicate && (
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-muted hover:text-[var(--dg-text-secondary)]" title=t('common.copy')
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-muted hover:text-[var(--dg-text-secondary)]" title={t('common.copy')}
onClick={() => onDuplicate(idx)}>
<RotateCw className="h-3.5 w-3.5" />
</Button>
)}
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" title=t('common.delete')
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-red hover:dg-text-red" title={t('common.delete')}
onClick={async () => {
const ok = await confirm({
title: t('kubernetes.containergroupsection.s860aaf'),
description: t('kubernetes.containergroupsection.s04ce19', { c.name: c.name }),
title: t('k8s.container.deleteTitle'),
description: t('k8s.container.deleteConfirm', { name: c.name }),
confirmText: t('common.delete'),
variant: 'destructive',
});
@@ -2,7 +2,6 @@
import { kubernetesApi } from '@/api';
import { prepareManifestForSave } from './k8s-manifest-utils';
import { isCreateDeployment } from './deployment-constants';
import i18n from '@/i18n';
export async function saveDeploymentManifest(
clusterCode: string,
@@ -11,7 +10,7 @@ export async function saveDeploymentManifest(
manifest: Record<string, any>,
): Promise<string> {
const resName = String(manifest?.metadata?.name || '').trim();
if (!resName) throw new Error(i18n.t('kubernetes.deploymentManifestSave.scb497f'));
if (!resName) throw new Error('Deployment 名称不能为空');
const yaml = await prepareManifestForSave(manifest);
if (isCreateDeployment(deploymentName)) {
await kubernetesApi.applyYAML(clusterCode, yaml);
@@ -2,8 +2,8 @@
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { RefreshCw, Plus, Loader2 } from 'lucide-react';
import type { VolumeForm } from './deployment-volume-utils';
import { useTranslation } from 'react-i18next';
import type { VolumeForm } from './deployment-volume-utils';
export interface NamespaceResourceLists {
configMaps: string[];
@@ -43,18 +43,18 @@ export function NamespaceResourcePicker({
disabled={loading}
className="h-7 flex-1 min-w-[160px] max-w-xs bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-2 font-mono"
>
<option value="" disabled>{options.length === 0 ? t('kubernetes.deploymentStorageFields.s21ff31') : t('common.selectPlaceholder')}</option>
{orphan && <option value={value}>{value}(未在集群中找到)</option>}
<option value="" disabled>{options.length === 0 ? t('k8s.storage.noResource') : t('k8s.storage.pleaseSelect')}</option>
{orphan && <option value={value}>{t('k8s.storage.orphan', { value })}</option>}
{options.map((n) => <option key={n} value={n}>{n}</option>)}
</select>
<Button type="button" size="sm" variant="outline" className="h-7 px-2 border-[var(--dg-border)] dg-text-secondary text-xs" onClick={onRefresh} disabled={loading}>
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
</Button>
<Button type="button" size="sm" variant="outline" className="h-7 px-2 border-[var(--dg-border)] dg-text-blue text-xs" onClick={onCreate}>
<Plus className="h-3 w-3 mr-0.5" />新建
<Plus className="h-3 w-3 mr-0.5" />{t('k8s.storage.create')}
</Button>
{options.length === 0 && !orphan && (
<span className="text-[10px] dg-text-yellow/90">命名空间内暂无{label},请先新建</span>
<span className="text-[10px] dg-text-yellow/90">{t('k8s.storage.nsNoResource', { label })}</span>
)}
</div>
);
@@ -77,7 +77,7 @@ export function VolumeTypeFields({
return (
<div className="space-y-2">
<NamespaceResourcePicker
label=t('kubernetes.deploymentStorageFields.s9f74c4')
label={t('k8s.storage.pvcLink')}
value={vol.pvcName || ''}
options={resources.pvcs}
loading={resourcesLoading}
@@ -87,7 +87,7 @@ export function VolumeTypeFields({
/>
<label className="flex items-center gap-1.5 text-xs dg-text-secondary cursor-pointer whitespace-nowrap pl-[88px]">
<input type="checkbox" checked={!!vol.pvcReadOnly} onChange={(e) => onChange({ pvcReadOnly: e.target.checked })} className="accent-blue-500" />
卷只读
{t('k8s.storage.volumeReadOnly')}
</label>
</div>
);
@@ -95,28 +95,28 @@ export function VolumeTypeFields({
if (vol.type === 'emptyDir') {
return (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('kubernetes.deploymentStorageFields.sfac9d2')}</span>
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('k8s.storage.medium')}</span>
<select value={vol.medium || ''} onChange={(e) => onChange({ medium: e.target.value })}
className="h-7 w-28 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1.5">
<option value="">{t('kubernetes.deploymentStorageFields.s83f939')}</option>
<option value="">{t('k8s.storage.defaultDisk')}</option>
<option value="Memory">Memory</option>
</select>
<Input value={vol.sizeLimit || ''} onChange={(e) => onChange({ sizeLimit: e.target.value })}
placeholder=t('kubernetes.deploymentStorageFields.s503cb1') className="h-7 flex-1 min-w-[120px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder={t('k8s.storage.sizeLimitPlaceholder')} className="h-7 flex-1 min-w-[120px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
);
}
if (vol.type === 'hostPath') {
return (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('kubernetes.workload.hostPath')}</span>
<span className="text-[10px] dg-text-muted w-20 shrink-0">{t('k8s.storage.hostPath')}</span>
<Input value={vol.path || ''} onChange={(e) => onChange({ path: e.target.value })}
placeholder="/data/app" className="h-7 flex-1 min-w-[160px] dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
<select value={vol.pathType || 'Directory'} onChange={(e) => onChange({ pathType: e.target.value })}
className="h-7 w-28 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded text-xs text-[var(--dg-text-secondary)] px-1.5">
<option value="Directory">Directory</option>
<option value="File">File</option>
<option value="">{t('approval.status.default')}</option>
<option value="">{t('k8s.storage.default')}</option>
</select>
</div>
);
@@ -145,9 +145,9 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('configmaps')}
/>
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] dg-text-muted shrink-0">{t('kubernetes.deploymentStorageFields.sca72ee')}</span>
<span className="text-[10px] dg-text-muted shrink-0">{t('k8s.storage.keyMapping')}</span>
<Input value={vol.cmItems || ''} onChange={(e) => onChange({ cmItems: e.target.value })}
placeholder=t('kubernetes.deploymentStorageFields.s6f0d57') className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder={t('k8s.storage.keyMappingPlaceholder')} className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
);
@@ -165,15 +165,15 @@ export function VolumeTypeFields({
onCreate={() => onCreateResource('secrets')}
/>
<div className="flex items-center gap-2 pl-[88px]">
<span className="text-[10px] dg-text-muted shrink-0">{t('kubernetes.deploymentStorageFields.sca72ee')}</span>
<span className="text-[10px] dg-text-muted shrink-0">{t('k8s.storage.keyMapping')}</span>
<Input value={vol.secItems || ''} onChange={(e) => onChange({ secItems: e.target.value })}
placeholder=t('kubernetes.deploymentStorageFields.s6f0d57') className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
placeholder={t('k8s.storage.keyMappingPlaceholder')} className="h-7 flex-1 max-w-md dg-input text-[var(--dg-text-secondary)] text-xs font-mono" />
</div>
</div>
);
}
if (vol.type === 'custom') {
return <p className="text-[11px] dg-text-yellow/80">{t('kubernetes.deploymentStorageFields.s98d353')}</p>;
return <p className="text-[11px] dg-text-yellow/80">{t('k8s.storage.unknownVolumeType')}</p>;
}
return null;
}
@@ -1,12 +1,11 @@
// deployment-view/helpers.tsx — 时间线 / 信息面板辅助组件 // Logan.Li
import { Fragment } from 'react';
import { useTranslation } from 'react-i18next';
import {
formatK8sTime, formatDuration, elapsedSeconds, STATUS_COLORS,
} from '../k8s-yaml-utils';
import type { PodItem } from './types';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import i18n from '@/i18n';
export interface PodStage {
label: string;
@@ -32,16 +31,15 @@ export function getPodTimeline(pod: PodItem) {
export function getPodStages(pod: PodItem): PodStage[] {
const tl = getPodTimeline(pod);
return [
{ label: i18n.t('kubernetes.event.scheduled'), ts: tl.scheduled, color: STATUS_COLORS.blue },
{ label: i18n.t('kubernetes.helpers.scee76a'), ts: tl.initialized, color: STATUS_COLORS.orange },
{ label: i18n.t('kubernetes.helpers.s712b04'), ts: tl.containersReady, color: STATUS_COLORS.green },
{ label: i18n.t('kubernetes.helpers.s504965'), ts: tl.ready, color: STATUS_COLORS.green },
{ label: 'k8s.podStage.scheduled', ts: tl.scheduled, color: STATUS_COLORS.blue },
{ label: 'k8s.podStage.initialized', ts: tl.initialized, color: STATUS_COLORS.orange },
{ label: 'k8s.podStage.containersReady', ts: tl.containersReady, color: STATUS_COLORS.green },
{ label: 'k8s.podStage.podReady', ts: tl.ready, color: STATUS_COLORS.green },
];
}
// 信息面板单项 // Logan.Li
export function InfoItem({ label, value }: { label: string; value: React.ReactNode }) {
const { t } = useTranslation();
return (
<div>
<p className="text-xs text-[var(--dg-text-muted)] mb-1">{label}</p>
@@ -60,13 +58,13 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
return (
<div className="flex items-center gap-2 min-w-[88px]">
<div className="flex items-center gap-0.5" aria-label=t('kubernetes.helpers.sfc9c68')>
<div className="flex items-center gap-0.5" aria-label={t('k8s.podStage.bootProgress')}>
{stages.map((s, i) => (
<Fragment key={s.label}>
<span
className="inline-block h-1.5 w-1.5 rounded-full shrink-0"
style={{ background: s.ts ? s.color : 'var(--dg-border)' }}
title={`${s.label}${s.ts ? ` · ${formatK8sTime(s.ts)}` : ''}`}
title={`${t(s.label)}${s.ts ? ` · ${formatK8sTime(s.ts)}` : ''}`}
/>
{i < stages.length - 1 && (
<span
@@ -81,7 +79,7 @@ export function PodStatusCompact({ pod }: { pod: PodItem }) {
className="text-[11px] whitespace-nowrap"
style={{ color: allReady ? STATUS_COLORS.green : 'var(--dg-text-muted)' }}
>
{allReady ? t('common.ready') : pending?.label || `${done}/${stages.length}`}
{allReady ? t('k8s.podStage.ready') : (pending ? t(pending.label) : `${done}/${stages.length}`)}
</span>
</div>
);
@@ -96,10 +94,10 @@ export function PodConditionsRow({ pod }: { pod: PodItem }) {
return (
<div className="rounded-lg bg-[var(--dg-bg-tertiary)]/60 px-4 py-3">
<div className="flex items-center justify-between mb-3">
<span className="text-xs text-[var(--dg-text-muted)]">{t('kubernetes.helpers.s684494')}</span>
<span className="text-xs text-[var(--dg-text-muted)]">{t('k8s.podStage.timeline')}</span>
{totalBoot != null && (
<span className="text-[11px] text-[var(--dg-text-muted)]">
总耗时 <span className="font-mono text-[var(--dg-text-secondary)]">{formatDuration(totalBoot)}</span>
{t('k8s.podStage.totalDuration')} <span className="font-mono text-[var(--dg-text-secondary)]">{formatDuration(totalBoot)}</span>
</span>
)}
</div>
@@ -123,7 +121,7 @@ export function PodConditionsRow({ pod }: { pod: PodItem }) {
{i + 1}
</span>
<span className="text-xs font-medium" style={{ color: active ? s.color : 'var(--dg-text-muted)' }}>
{s.label}
{t(s.label)}
</span>
</div>
<span className="mt-1.5 pl-7 text-[11px] font-mono text-[var(--dg-text-muted)]">
@@ -57,22 +57,19 @@ export function CICDWebhookContent({
const restartUrl = `${apiBase}/kubernetes/${clusterCode}/namespace/${namespace}/deployments/${deploymentName}/restart`;
const updateBody = useMemo(() => {
const body: Record<string, string> = { image: image || t('kubernetes.cicdwebhookcontent.sc4be9c') };
const body: Record<string, string> = { image: image || t('k8s.cicd.newImagePlaceholder') };
if (containerName) body.container_name = containerName;
return JSON.stringify(body);
}, [image, containerName]);
const accessKeyPlaceholder = t('k8s.cicd.accessKeyPlaceholder');
const updateCurl = accessKey
? `curl -X POST '${updateUrl}' \\
-H 'X-AIOps-Access-Key: ${accessKey}' \\
-H 'Content-Type: application/json' \\
-d '${updateBody}'`
: t('kubernetes.cicdwebhookcontent.s1976d2', { updateUrl: updateUrl, updateBody: updateBody });
? `curl -X POST '${updateUrl}' \\\n -H 'X-AIOps-Access-Key: ${accessKey}' \\\n -H 'Content-Type: application/json' \\\n -d '${updateBody}'`
: `curl -X POST '${updateUrl}' \\\n -H 'X-AIOps-Access-Key: ${accessKeyPlaceholder}' \\\n -H 'Content-Type: application/json' \\\n -d '${updateBody}'`;
const restartCurl = accessKey
? `curl -X POST '${restartUrl}' \\
-H 'X-AIOps-Access-Key: ${accessKey}'`
: t('kubernetes.cicdwebhookcontent.s0e3668', { restartUrl: restartUrl });
? `curl -X POST '${restartUrl}' \\\n -H 'X-AIOps-Access-Key: ${accessKey}'`
: `curl -X POST '${restartUrl}' \\\n -H 'X-AIOps-Access-Key: ${accessKeyPlaceholder}'`;
const canCopy = !!accessKey && !keyExpired;
@@ -81,53 +78,53 @@ export function CICDWebhookContent({
<div className="rounded-md bg-[var(--dg-bg-tertiary)]/50 px-3 py-2 text-xs text-[var(--dg-text-muted)] leading-relaxed">
{keyLoading ? (
<span className="inline-flex items-center gap-1.5">
<Loader2 className="h-3 w-3 animate-spin" />正在读取 API 密钥…
<Loader2 className="h-3 w-3 animate-spin" />{t('k8s.cicd.readingKey')}
</span>
) : keyExpired ? (
<>
访问凭证已过期,请前往
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
调整有效期或轮换凭证后再复制 curl。
{t('k8s.cicd.expiredPrefix')}
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('k8s.cicd.profileCenter')}</Link>
{t('k8s.cicd.expiredSuffix')}
</>
) : accessKey ? (
<>{t('kubernetes.cicdwebhookcontent.scd2b7d')}</>
<>{t('k8s.cicd.cachedHint')}</>
) : hasKey ? (
<>
已检测到访问凭证,但本机未缓存明文。请前往
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
轮换凭证一次,之后 curl 将自动填入。
{t('k8s.cicd.detectedPrefix')}
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('k8s.cicd.profileCenter')}</Link>
{t('k8s.cicd.detectedSuffix')}
</>
) : (
<>
请先在
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('header.profile')}</Link>
签发 CI/CD 访问凭证,curl 将自动填入。
{t('k8s.cicd.noKeyPrefix')}
<Link to="/profile" className="text-[var(--dg-blue)] hover:underline mx-1">{t('k8s.cicd.profileCenter')}</Link>
{t('k8s.cicd.noKeySuffix')}
</>
)}
</div>
<CodeSnippetBlock
label=t('kubernetes.deployment.updateImage')
label={t('k8s.editImage.updateImage')}
code={updateCurl}
copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyLabel={t('k8s.cicd.copyLabel')}
copyDisabled={!canCopy}
copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
copyDisabledTitle={t('k8s.cicd.copyDisabledTitle')}
/>
<CodeSnippetBlock
label=t('kubernetes.deployment.restart')
label={t('k8s.cicd.rollingRestart')}
code={restartCurl}
copyLabel=t('kubernetes.cicdwebhookcontent.s25a990')
copyLabel={t('k8s.cicd.copyLabel')}
copyDisabled={!canCopy}
copyDisabledTitle=t('kubernetes.cicdwebhookcontent.sc3bc41')
copyDisabledTitle={t('k8s.cicd.copyDisabledTitle')}
/>
<div className="text-xs text-[var(--dg-text-muted)] space-y-1">
<p>{t('kubernetes.cicdwebhookcontent.s1bdaf4')}<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code>
{containerName ? <> {t('kubernetes.cicdwebhookcontent.s9b07e8')} <code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null}
<p>{t('k8s.cicd.sampleImage')}<code className="text-[var(--dg-text-secondary)]">{image || '—'}</code>
{containerName ? <>{t('k8s.cicd.container')}<code className="text-[var(--dg-text-secondary)]">{containerName}</code></> : null}
</p>
<p>{t('kubernetes.cicdwebhookcontent.se067d1')}</p>
<p>{t('kubernetes.cicdwebhookcontent.s311998')} <code className="text-[var(--dg-text-secondary)]">image</code> {t('kubernetes.cicdwebhookcontent.s55260c')}</p>
<p>{t('kubernetes.cicdwebhookcontent.s4e20ba')} <code className="text-[var(--dg-text-secondary)]">{t('kubernetes.cicdwebhookcontent.s67cc60')}</code></p>
<p>{t('k8s.cicd.tipLongTermKey')}</p>
<p>{t('k8s.cicd.tipEditImagePrefix')}<code className="text-[var(--dg-text-secondary)]">image</code>{t('k8s.cicd.tipEditImageSuffix')}</p>
<p>{t('k8s.cicd.tipBearerPrefix')}<code className="text-[var(--dg-text-secondary)]">Authorization: Bearer &lt;{t('k8s.cicd.tipBearerKey')}&gt;</code>{t('k8s.cicd.tipBearerSuffix')}</p>
</div>
</div>
);
@@ -1,13 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// EditModeContainer.tsx — 编辑模式 Tab 容器,共享 manifest 状态 // Logan.Li
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Container, Settings, Database, Network } from 'lucide-react';
import { DeploymentEditBasic } from '../DeploymentEditBasic';
import { DeploymentEditContainers } from '../DeploymentEditContainers';
import { DeploymentEditStorage } from '../DeploymentEditStorage';
import { DeploymentEditAdvanced } from '../DeploymentEditAdvanced';
import { DeploymentEditService } from '../DeploymentEditService';
import { useTranslation } from 'react-i18next';
export interface EditModeContainerProps {
clusterCode: string;
@@ -36,11 +36,11 @@ export function EditModeContainer({ clusterCode, namespace, deploymentName, mani
};
const tabs: Array<{ key: EditTab; label: string; icon: typeof Settings }> = [
{ key: 'basic', label: t('deploy.label.basicInfo'), icon: Settings },
{ key: 'containers', label: t('kubernetes.editmodecontainer.sd58c2e'), icon: Container },
{ key: 'storage', label: t('kubernetes.editmodecontainer.s9ffdac'), icon: Database },
{ key: 'advanced', label: t('kubernetes.editmodecontainer.se37075'), icon: Settings },
{ key: 'service', label: t('kubernetes.editmodecontainer.s8bdc2d'), icon: Network },
{ key: 'basic', label: t('k8s.editMode.basic'), icon: Settings },
{ key: 'containers', label: t('k8s.editMode.containers'), icon: Container },
{ key: 'storage', label: t('k8s.editMode.storage'), icon: Database },
{ key: 'advanced', label: t('k8s.editMode.advanced'), icon: Settings },
{ key: 'service', label: t('k8s.editMode.service'), icon: Network },
];
const commonProps = {
@@ -8,8 +8,8 @@ import { FileText, RefreshCw, Loader2, X } from 'lucide-react';
import { kubernetesApi } from '@/api';
import { useToast } from '@/hooks/use-toast';
import { useUserStore } from '@/store';
import type { JsonData } from '@/types/common';
import { useTranslation } from 'react-i18next';
import type { JsonData } from '@/types/common';
export interface PodLogsModalProps {
clusterCode: string;
@@ -32,9 +32,9 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLoading(true);
try {
const res: JsonData = await kubernetesApi.getPodLogs(clusterCode, namespace, podName, tail, container || undefined);
setLogs(res?.data?.logs || res?.logs || res || t('kubernetes.podlogsmodal.s4ff3b4'));
setLogs(res?.data?.logs || res?.logs || res || t('k8s.podLogs.noLogs'));
} catch {
setLogs(t('kubernetes.podlogsmodal.sc93f33'));
setLogs(t('k8s.podLogs.loadFailed'));
} finally { setLoading(false); }
};
@@ -59,7 +59,7 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
setLogs(buf);
}
} catch {
toast({ title: t('kubernetes.podlogsmodal.s6273c9'), variant: 'destructive' });
toast({ title: t('k8s.podLogs.streamInterrupted'), variant: 'destructive' });
} finally { setStreaming(false); }
};
@@ -87,14 +87,14 @@ export function PodLogsModal({ clusterCode, namespace, podName, containers, onCl
{loading ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
</Button>
<Button size="sm" variant="outline" className="h-7 border-[var(--dg-border)] dg-text-green text-xs" onClick={startStream} disabled={streaming}>
{streaming ? t('kubernetes.podlogsmodal.s2d4fb3') : t('monitor.logStreaming')}
{streaming ? t('k8s.podLogs.streaming') : t('k8s.podLogs.liveStream')}
</Button>
<Button variant="ghost" size="icon" className="h-7 w-7 dg-text-secondary" onClick={onClose}><X className="h-4 w-4" /></Button>
</div>
</div>
<div className="flex-1 overflow-auto p-3">
<pre className="bg-[var(--dg-bg-primary)] rounded p-3 text-xs text-[var(--dg-text-secondary)] font-mono whitespace-pre-wrap max-h-[60vh] overflow-auto">
{logs || t('kubernetes.podlogsmodal.s99eac0')}
{logs || t('k8s.podLogs.noLogContent')}
</pre>
</div>
</div>
@@ -4,9 +4,9 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { ArrowRight, Loader2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { joinImageRef, parseImageRef } from '../image-ref-utils';
import { ModalShell } from './ModalShell';
import { useTranslation } from 'react-i18next';
export interface UpdateImageModalProps {
deployment: any;
@@ -48,14 +48,14 @@ export function UpdateImageModal({
};
return (
<ModalShell title=t('kubernetes.updateimagemodal.s22a2ed') onClose={onClose} size="xl">
<ModalShell title={t('k8s.editImage.title')} onClose={onClose} size="xl">
<div className="space-y-5">
{/* 当前镜像:只读展示完整地址与 Tag // Logan.Li */}
<div className="rounded-lg border border-[var(--dg-border)]/80 bg-[var(--dg-bg-tertiary)]/40 p-4 space-y-3">
<p className="text-xs font-medium dg-text-secondary">{t('kubernetes.deployment.currentImage')}</p>
<p className="text-xs font-medium dg-text-secondary">{t('k8s.editImage.currentImage')}</p>
<div className="grid grid-cols-[1fr_180px] gap-3">
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<Label className="dg-text-muted text-xs">{t('k8s.editImage.imageAddress')}</Label>
<p
className="mt-1.5 text-sm text-[var(--dg-text-primary)] font-mono break-all leading-relaxed bg-[var(--dg-bg-secondary)]/60 rounded-md px-3 py-2.5 min-h-[42px]"
title={current.repository || '-'}
@@ -64,7 +64,7 @@ export function UpdateImageModal({
</p>
</div>
<div>
<Label className="dg-text-muted text-xs">{t('kubernetes.updateimagemodal.sf08c71')}</Label>
<Label className="dg-text-muted text-xs">{t('k8s.editImage.currentTag')}</Label>
<p
className="mt-1.5 text-sm text-cyan-300 font-mono break-all leading-relaxed bg-[var(--dg-bg-secondary)]/60 rounded-md px-3 py-2.5 min-h-[42px]"
title={current.tag || '-'}
@@ -74,7 +74,7 @@ export function UpdateImageModal({
</div>
</div>
<p className="text-[11px] dg-text-muted font-mono break-all" title={currentImage}>
完整引用:<span className="dg-text-secondary">{currentImage || '-'}</span>
{t('k8s.editImage.fullRef')}<span className="dg-text-secondary">{currentImage || '-'}</span>
</p>
</div>
@@ -84,10 +84,10 @@ export function UpdateImageModal({
{/* 新镜像:地址与 Tag 分栏编辑 // Logan.Li */}
<div className="rounded-lg border border-blue-500/30 bg-blue-500/5 p-4 space-y-3">
<p className="text-xs font-medium text-blue-300/90">{t('kubernetes.deployment.newImage')}</p>
<p className="text-xs font-medium text-blue-300/90">{t('k8s.editImage.newImage')}</p>
<div className="grid grid-cols-[1fr_180px] gap-3">
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.sdbe6a6')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.editImage.imageAddress')}</Label>
<Input
value={newRepo}
onChange={e => {
@@ -100,7 +100,7 @@ export function UpdateImageModal({
/>
</div>
<div>
<Label className="dg-text-secondary text-xs">{t('kubernetes.updateimagemodal.s6a38a8')}</Label>
<Label className="dg-text-secondary text-xs">{t('k8s.editImage.newTag')}</Label>
<Input
value={newTag}
onChange={e => {
@@ -115,7 +115,7 @@ export function UpdateImageModal({
</div>
<div className="flex flex-wrap items-center gap-2 text-xs">
<span className="dg-text-muted">{t('kubernetes.updateimagemodal.sec74e0')}</span>
<span className="dg-text-muted">{t('k8s.editImage.tagChange')}</span>
<code className="px-2 py-0.5 rounded bg-[var(--dg-bg-tertiary)] dg-text-secondary font-mono">{current.tag}</code>
<ArrowRight className="h-3 w-3 dg-text-muted" />
<code
@@ -126,28 +126,28 @@ export function UpdateImageModal({
{newTag.trim() || '-'}
</code>
{!tagChanged && !repoChanged && (
<span className="dg-text-muted">{t('kubernetes.updateimagemodal.s47c8cf')}</span>
<span className="dg-text-muted">{t('k8s.editImage.notModified')}</span>
)}
{repoChanged && !tagChanged && (
<span className="dg-text-yellow/80">{t('kubernetes.updateimagemodal.sdb3122')}</span>
<span className="dg-text-yellow/80">{t('k8s.editImage.addressChanged')}</span>
)}
</div>
<p className="text-[11px] dg-text-muted font-mono break-all">
更新预览:<span className="text-[var(--dg-text-secondary)]">{previewImage || '-'}</span>
{t('k8s.editImage.updatePreview')}<span className="text-[var(--dg-text-secondary)]">{previewImage || '-'}</span>
</p>
</div>
<div className="flex justify-end gap-2 pt-1">
<Button variant="outline" className="border-[var(--dg-border)] dg-text-secondary" onClick={onClose}>
取消
{t('common.cancel')}
</Button>
<Button
className="bg-blue-600 hover:bg-blue-700"
disabled={actionLoading === 'image' || !previewImage.trim() || !hasChanges}
onClick={onUpdateImage}
>
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : i18n.t('kubernetes.deployment.updateImage')}
{actionLoading === 'image' ? <Loader2 className="h-4 w-4 animate-spin" /> : t('k8s.editImage.updateImage')}
</Button>
</div>
</div>
@@ -1,7 +1,6 @@
// k8s-event-utils — K8s Event 字段归一化与展示 // Logan.Li
import { elapsedSeconds, formatDuration, formatK8sTime } from './k8s-yaml-utils';
import type { JsonData } from '@/types/common';
import i18n from '@/i18n';
export interface NormalizedEvent {
name: string;
@@ -60,11 +59,11 @@ export function formatEventRelative(ts: string): string {
const diff = Date.now() - new Date(ts).getTime();
if (diff < 0) return '';
const mins = Math.floor(diff / 60000);
if (mins < 1) return i18n.t('task.cronJob.time.justNow');
if (mins < 60) return i18n.t('kubernetes.k8sEventUtils.s9dc098', { mins: mins });
if (mins < 1) return '刚刚';
if (mins < 60) return `${mins}分钟前`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return i18n.t('kubernetes.k8sEventUtils.sc71bd7', { hrs: hrs });
return i18n.t('kubernetes.k8sEventUtils.s02f1ca', { Math.floor(hrs / 24): Math.floor(hrs / 24) });
if (hrs < 24) return `${hrs}小时前`;
return `${Math.floor(hrs / 24)}天前`;
}
/** 重复跨度:首次 → 最后 // Logan.Li */
@@ -3,26 +3,25 @@ import {
Network, Server, Globe, Cloud, Boxes, Database, Zap, Box,
} from 'lucide-react';
import type { TopologyNode, TopologyEdge } from '@/types';
import i18n from '@/i18n';
// K8s 资源类型 → 拓扑节点类型标签 // Logan.Li
export const NODE_TYPE_LABELS: Record<string, string> = {
cluster: i18n.t('kubernetes.topologyHelpers.s85fe50'),
loadbalancer: 'Ingress',
service: 'Service',
app: 'Deployment',
pod: 'Pod',
server: 'Node',
database: i18n.t('kubernetes.topologyHelpers.s68051b'),
external: i18n.t('kubernetes.topologyHelpers.s47921e'),
custom: i18n.t('common.custom'),
cluster: 'k8s.topology.typeCluster',
loadbalancer: 'k8s.topology.typeIngress',
service: 'k8s.topology.typeService',
app: 'k8s.topology.typeDeployment',
pod: 'k8s.topology.typePod',
server: 'k8s.topology.typeNode',
database: 'k8s.topology.typeDatabase',
external: 'k8s.topology.typeExternal',
custom: 'k8s.topology.typeCustom',
};
// 自定义节点类型选项(编辑模式用)
export const CUSTOM_NODE_TYPES = [
{ value: 'database', label: i18n.t('kubernetes.topologyHelpers.s68051b'), desc: i18n.t('kubernetes.topologyHelpers.sf6a891') },
{ value: 'external', label: i18n.t('kubernetes.topologyHelpers.s47921e'), desc: i18n.t('kubernetes.topologyHelpers.s39b435') },
{ value: 'custom', label: i18n.t('common.custom'), desc: i18n.t('kubernetes.topologyHelpers.sfb5d27') },
{ value: 'database', label: 'k8s.topology.typeDatabase', desc: 'k8s.topology.customDbDesc' },
{ value: 'external', label: 'k8s.topology.typeExternal', desc: 'k8s.topology.customExtDesc' },
{ value: 'custom', label: 'k8s.topology.typeCustom', desc: 'k8s.topology.customCustomDesc' },
];
// 判断是否为自定义节点(非 K8s 原生资源)
@@ -86,7 +85,7 @@ export function buildTopology( cluster: any, ingresses: any[], services: any[],
// Layer 0: Cluster
const clusterId = `cluster-${cluster.id}`;
tNodes.push({
id: clusterId, name: cluster.name || i18n.t('kubernetes.topologyHelpers.s85fe50'), type: 'cluster',
id: clusterId, name: cluster.name || 'Cluster', type: 'cluster',
x: canvasW / 2, y: layerY[0],
data: { kind: 'cluster', version: cluster.version, status: cluster.status, api_server: cluster.api_server, node_count: cluster.node_count, pod_count: cluster.pod_count },
});