feat: 前端全面优化 — 懒加载/骨架屏/错误边界/面包屑/主题增强/Glass登录页/动画系统

- 新增: ErrorBoundary, PageTransition, Breadcrumb, SkeletonCard (4组件)
- 重构: App.tsx (React.lazy懒加载所有页面), index.css (55+主题变量/动画/工具类)
- 优化: MainLayout (CSS变量布局+Footer), Header (搜索增强+快捷键), Sidebar (折叠Tooltip+子菜单动画)
- 优化: Dashboard骨架屏+级联动画, Stats/Charts/Recent主题感知颜色
- 优化: Login.tsx Glass毛玻璃效果+密码显隐图标+光球动画
- 图表Recharts主题化(CustomTooltip/chart-grid/chart-axis)
- 减少动画偏好支持(prefers-reduced-motion)
This commit is contained in:
attacker committed 2026-06-24 02:06:07 +00:00
1 parent 3d7932c087
commit 722587ab84
14 files changed
+2026 -969

No files matched your search

@@ -15,8 +15,9 @@ import {
Bar,
} from 'recharts';
import { Cpu, HardDrive, Activity, MemoryStick, Database } from 'lucide-react';
import { cn } from '@/lib/utils';
// 云平台颜色映射
// Cloud platform color mapping (theme-aware)
const CLOUD_COLORS: Record<string, string> = {
'阿里云': '#ff6a00',
aliyun: '#ff6a00',
@@ -31,7 +32,6 @@ const CLOUD_COLORS: Record<string, string> = {
};
const FALLBACK_CLOUD_COLORS = ['#ff6a00', '#ff9900', '#006eff', '#ff0000', '#0078d4', '#10b981', '#a855f7', '#ec4899'];
// 计算月度环比变化(基于 month_trend 最后两个月)
export function computeMonthChange(monthTrend: any[]): {
pct: number;
label: string;
@@ -51,22 +51,61 @@ export function computeMonthChange(monthTrend: any[]): {
return { pct, label, direction };
}
// 根据平均值生成24小时趋势数据(无实时指标时使用)
function generateMetricsData(avgCpu: number, avgMemory: number, avgDisk: number, points = 24) {
const data = [];
for (let i = points - 1; i >= 0; i--) {
const d = new Date(Date.now() - i * 60 * 60 * 1000);
data.push({
time: `${d.getHours().toString().padStart(2, '0')}:00`,
cpu: Number(Math.max(0, avgCpu + (Math.random() - 0.5) * 15).toFixed(1)),
memory: Number(Math.max(0, avgMemory + (Math.random() - 0.5) * 10).toFixed(1)),
disk: Number(Math.max(0, avgDisk + (Math.random() - 0.5) * 5).toFixed(1)),
cpu: Number(Math.max(0, Math.min(100, avgCpu + (Math.random() - 0.5) * 15)).toFixed(1)),
memory: Number(Math.max(0, Math.min(100, avgMemory + (Math.random() - 0.5) * 10)).toFixed(1)),
disk: Number(Math.max(0, Math.min(100, avgDisk + (Math.random() - 0.5) * 5)).toFixed(1)),
});
}
return data;
}
// 成本费用卡片
function buildMetricsFromReal(metrics: any[], avgDisk: number) {
if (!metrics || metrics.length === 0) return [];
const buckets: Record<string, { cpu?: number; memory?: number }> = {};
for (const m of metrics) {
const ts = m.timestamp;
if (!ts) continue;
const d = new Date(ts);
const label = `${d.getHours().toString().padStart(2, '0')}:00`;
if (!buckets[label]) buckets[label] = {};
if (m.name === 'cpu') buckets[label].cpu = Number(m.value) || 0;
if (m.name === 'memory') buckets[label].memory = Number(m.value) || 0;
}
return Object.entries(buckets)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([time, v]) => ({
time,
cpu: Number((v.cpu ?? 0).toFixed(1)),
memory: Number((v.memory ?? 0).toFixed(1)),
disk: Number(avgDisk.toFixed(1)),
}));
}
// Custom tooltip for charts (theme-aware)
function CustomTooltip({ active, payload, label }: any) {
if (!active || !payload) return null;
return (
<div className="chart-tooltip px-3 py-2">
<p className="text-xs font-medium mb-1.5" style={{ color: 'var(--dg-text-secondary)' }}>{label}</p>
{payload.map((entry: any, index: number) => (
<div key={index} className="flex items-center gap-2 text-xs">
<span className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color }} />
<span style={{ color: 'var(--dg-text-muted)' }}>{entry.name}:</span>
<span className="font-medium" style={{ color: 'var(--dg-text-primary)' }}>
{typeof entry.value === 'number' ? `${entry.value}%` : entry.value}
</span>
</div>
))}
</div>
);
}
export function CostOverviewCard({ costStats }: { costStats: any }) {
const cloudCosts: any[] = costStats?.cloud_costs ?? [];
const monthTrend: any[] = costStats?.month_trend ?? [];
@@ -77,27 +116,27 @@ export function CostOverviewCard({ costStats }: { costStats: any }) {
color: CLOUD_COLORS[c.cloud] || FALLBACK_CLOUD_COLORS[i % FALLBACK_CLOUD_COLORS.length],
}));
const monthlyData = monthTrend.map((m) => ({ month: m.month, cost: m.cost }));
const totalCost =
costStats?.total_cost ?? costData.reduce((sum, item) => sum + item.value, 0);
const totalCost = costStats?.total_cost ?? costData.reduce((sum, item) => sum + item.value, 0);
const costChange = computeMonthChange(monthTrend);
return (
<Card className="bg-slate-900 border-slate-800">
<Card className="dg-card dg-card-hover">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-slate-100">云成本概览</CardTitle>
<CardDescription className="text-slate-500">本月各云平台费用支出</CardDescription>
<CardTitle className="text-[var(--dg-text-primary)]">云成本概览</CardTitle>
<CardDescription className="text-[var(--dg-text-muted)]">本月各云平台费用支出</CardDescription>
</div>
<div className="text-right">
<p className="text-2xl font-bold text-slate-100">¥{Number(totalCost).toLocaleString()}</p>
<p className={`text-xs ${
costChange.direction === 'up'
? 'text-emerald-400'
: costChange.direction === 'down'
? 'text-red-400'
: 'text-slate-500'
}`}>
<p className="text-2xl font-bold text-[var(--dg-text-primary)] tracking-tight">
¥{Number(totalCost).toLocaleString()}
</p>
<p className={cn(
'text-xs font-medium mt-0.5',
costChange.direction === 'up' ? 'text-[var(--dg-green)]' :
costChange.direction === 'down' ? 'text-[var(--dg-red)]' :
'text-[var(--dg-text-muted)]'
)}>
{costChange.label}
</p>
</div>
@@ -106,7 +145,7 @@ export function CostOverviewCard({ costStats }: { costStats: any }) {
<CardContent>
<div className="grid grid-cols-2 gap-4">
<div>
<p className="text-sm text-slate-400 mb-2">费用分布</p>
<p className="text-sm text-[var(--dg-text-secondary)] mb-2">费用分布</p>
<div className="h-[180px]">
<ResponsiveContainer width="100%" height="100%">
<PieChart>
@@ -118,42 +157,27 @@ export function CostOverviewCard({ costStats }: { costStats: any }) {
outerRadius={70}
paddingAngle={2}
dataKey="value"
stroke="none"
>
{costData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip
contentStyle={{
backgroundColor: '#0f172a',
border: '1px solid #1e293b',
borderRadius: '6px',
color: '#f8fafc',
}}
formatter={(value: number) => `¥${value.toLocaleString()}`}
/>
<Tooltip content={<CustomTooltip />} />
</PieChart>
</ResponsiveContainer>
</div>
</div>
<div>
<p className="text-sm text-slate-400 mb-2">月度趋势</p>
<p className="text-sm text-[var(--dg-text-secondary)] mb-2">月度趋势</p>
<div className="h-[180px]">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={monthlyData} margin={{ top: 5, right: 5, left: 0, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
<XAxis dataKey="month" stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
<YAxis stroke="#475569" fontSize={10} tickLine={false} axisLine={false} />
<Tooltip
contentStyle={{
backgroundColor: '#0f172a',
border: '1px solid #1e293b',
borderRadius: '6px',
color: '#f8fafc',
}}
formatter={(value: number) => `¥${value.toLocaleString()}`}
/>
<Bar dataKey="cost" fill="#3b82f6" radius={[4, 4, 0, 0]} />
<CartesianGrid strokeDasharray="3 3" className="chart-grid-stroke" stroke="var(--chart-grid)" />
<XAxis dataKey="month" stroke="var(--chart-axis)" fontSize={10} tickLine={false} axisLine={false} />
<YAxis stroke="var(--chart-axis)" fontSize={10} tickLine={false} axisLine={false} />
<Tooltip content={<CustomTooltip />} />
<Bar dataKey="cost" fill="var(--dg-blue)" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
@@ -164,9 +188,11 @@ export function CostOverviewCard({ costStats }: { costStats: any }) {
<div key={item.name} className="flex items-center justify-between">
<div className="flex items-center gap-2">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
<span className="text-sm text-slate-300">{item.name}</span>
<span className="text-sm text-[var(--dg-text-secondary)]">{item.name}</span>
</div>
<span className="text-sm font-medium text-slate-100">¥{Number(item.value).toLocaleString()}</span>
<span className="text-sm font-semibold text-[var(--dg-text-primary)]">
¥{Number(item.value).toLocaleString()}
</span>
</div>
))}
</div>
@@ -175,7 +201,6 @@ export function CostOverviewCard({ costStats }: { costStats: any }) {
);
}
// Top5 资源使用卡片
export function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
const topCpuServers = (topUsage?.cpu ?? []).slice(0, 5);
const topMemoryServers = (topUsage?.memory ?? []).slice(0, 5);
@@ -191,28 +216,32 @@ export function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
<div>
<div className="flex items-center gap-2 mb-3">
{icon}
<span className="text-sm font-medium text-slate-300">{label}</span>
<span className="text-sm font-semibold text-[var(--dg-text-secondary)]">{label}</span>
</div>
<div className="space-y-2">
<div className="space-y-2.5">
{items.map((item, index) => {
const usage = Number(item.usage ?? 0);
return (
<div key={item.id ?? index} className="flex items-center gap-2">
<span className="text-xs text-slate-500 w-4">{index + 1}</span>
<div key={item.id ?? index} className="flex items-center gap-2.5">
<span className="text-xs font-mono text-[var(--dg-text-muted)] w-5 text-center">
{index + 1}
</span>
<div className="flex-1 min-w-0">
<p className="text-xs text-slate-300 truncate">{item.hostname}</p>
<div className="flex items-center gap-2">
<div className="flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden">
<p className="text-xs text-[var(--dg-text-secondary)] truncate font-medium">{item.hostname}</p>
<div className="flex items-center gap-2 mt-1">
<div className="flex-1 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden">
<div
className={`h-full rounded-full ${
usage > 80 ? 'bg-red-400' : usage > 60 ? 'bg-amber-400' : BarColor
}`}
style={{ width: `${usage}%` }}
className={cn(
'h-full rounded-full transition-all duration-500',
usage > 80 ? 'bg-[var(--dg-red)]' : usage > 60 ? 'bg-[var(--dg-yellow)]' : BarColor
)}
style={{ width: `${Math.min(usage, 100)}%` }}
/>
</div>
<span className={`text-xs ${
usage > 80 ? 'text-red-400' : usage > 60 ? 'text-amber-400' : 'text-slate-400'
}`}>
<span className={cn(
'text-xs font-mono font-medium w-12 text-right',
usage > 80 ? 'text-[var(--dg-red)]' : usage > 60 ? 'text-[var(--dg-yellow)]' : 'text-[var(--dg-text-muted)]'
)}>
{usage.toFixed(1)}%
</span>
</div>
@@ -225,55 +254,24 @@ export function TopResourceUsageCard({ topUsage }: { topUsage: any }) {
);
return (
<Card className="bg-slate-900 border-slate-800">
<Card className="dg-card dg-card-hover">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div>
<CardTitle className="text-slate-100">Top5 资源使用</CardTitle>
<CardDescription className="text-slate-500">CPU、内存、磁盘使用率最高</CardDescription>
</div>
<div>
<CardTitle className="text-[var(--dg-text-primary)]">Top5 资源使用</CardTitle>
<CardDescription className="text-[var(--dg-text-muted)]">CPU、内存、磁盘使用率最高</CardDescription>
</div>
</CardHeader>
<CardContent>
<div className="grid grid-cols-3 gap-4">
{/* CPU Top5 */}
{renderList(topCpuServers, 'blue', 'bg-blue-400', <Cpu className="h-4 w-4 text-blue-400" />, 'CPU')}
{/* Memory Top5 */}
{renderList(topMemoryServers, 'emerald', 'bg-emerald-400', <MemoryStick className="h-4 w-4 text-emerald-400" />, '内存')}
{/* Disk Top5 */}
{renderList(topDiskServers, 'purple', 'bg-purple-400', <Database className="h-4 w-4 text-purple-400" />, '磁盘')}
{renderList(topCpuServers, 'blue', 'bg-[var(--dg-blue)]', <Cpu className="h-4 w-4 text-[var(--dg-blue)]" />, 'CPU')}
{renderList(topMemoryServers, 'emerald', 'bg-[var(--dg-green)]', <MemoryStick className="h-4 w-4 text-[var(--dg-green)]" />, '内存')}
{renderList(topDiskServers, 'purple', 'bg-[var(--dg-purple)]', <Database className="h-4 w-4 text-[var(--dg-purple)]" />, '磁盘')}
</div>
</CardContent>
</Card>
);
}
// 将后端 MetricData[] 时间序列转换为图表所需格式 { time, cpu, memory } // Logan.Li
function buildMetricsFromReal(metrics: any[], avgDisk: number): { time: string; cpu: number; memory: number; disk: number }[] {
if (!metrics || metrics.length === 0) return [];
// 按 timestamp 分组:同一时刻有 cpu + memory 两条记录
const buckets: Record<string, { cpu?: number; memory?: number }> = {};
for (const m of metrics) {
const ts = m.timestamp;
if (!ts) continue;
// 提取 HH:MM 格式作为 X 轴标签
const d = new Date(ts);
const label = `${d.getHours().toString().padStart(2, '0')}:00`;
if (!buckets[label]) buckets[label] = {};
if (m.name === 'cpu') buckets[label].cpu = Number(m.value) || 0;
if (m.name === 'memory') buckets[label].memory = Number(m.value) || 0;
}
return Object.entries(buckets)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([time, v]) => ({
time,
cpu: Number((v.cpu ?? 0).toFixed(1)),
memory: Number((v.memory ?? 0).toFixed(1)),
disk: Number(avgDisk.toFixed(1)), // 磁盘无历史序列,用平均值
}));
}
// 资源使用率趋势卡片
export function ResourceUsageCard({
avgCpu,
avgMemory,
@@ -285,28 +283,27 @@ export function ResourceUsageCard({
avgDisk: number;
metrics?: any[];
}) {
// 优先使用真实 Agent 指标时间序列;无数据时回退到平均值生成(带随机波动) // Logan.Li
const realData = buildMetricsFromReal(metrics ?? [], avgDisk);
const data = realData.length > 0 ? realData : generateMetricsData(avgCpu, avgMemory, avgDisk, 24);
return (
<Card className="bg-slate-900 border-slate-800">
<Card className="dg-card">
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center justify-between flex-wrap gap-3">
<div>
<CardTitle className="text-slate-100">资源使用率趋势</CardTitle>
<CardDescription className="text-slate-500">过去24小时系统资源使用情况</CardDescription>
<CardTitle className="text-[var(--dg-text-primary)]">资源使用率趋势</CardTitle>
<CardDescription className="text-[var(--dg-text-muted)]">过去24小时系统资源使用情况</CardDescription>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline" className="border-blue-500/30 text-blue-400 bg-blue-500/10">
<Badge variant="outline" className="dg-badge-blue border">
<Cpu className="h-3 w-3 mr-1" />
CPU
</Badge>
<Badge variant="outline" className="border-emerald-500/30 text-emerald-400 bg-emerald-500/10">
<Badge variant="outline" className="dg-badge-green border">
<Activity className="h-3 w-3 mr-1" />
内存
</Badge>
<Badge variant="outline" className="border-purple-500/30 text-purple-400 bg-purple-500/10">
<Badge variant="outline" className="dg-badge-purple border">
<HardDrive className="h-3 w-3 mr-1" />
磁盘
</Badge>
@@ -319,56 +316,25 @@ export function ResourceUsageCard({
<AreaChart data={data} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
<defs>
<linearGradient id="colorCpu" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
<stop offset="5%" stopColor="var(--dg-blue)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--dg-blue)" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorMemory" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#10b981" stopOpacity={0.3} />
<stop offset="95%" stopColor="#10b981" stopOpacity={0} />
<stop offset="5%" stopColor="var(--dg-green)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--dg-green)" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorDisk" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#a855f7" stopOpacity={0.3} />
<stop offset="95%" stopColor="#a855f7" stopOpacity={0} />
<stop offset="5%" stopColor="var(--dg-purple)" stopOpacity={0.3} />
<stop offset="95%" stopColor="var(--dg-purple)" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="#1e293b" />
<XAxis dataKey="time" stroke="#475569" fontSize={12} tickLine={false} axisLine={false} />
<YAxis stroke="#475569" fontSize={12} tickLine={false} axisLine={false} unit="%" />
<Tooltip
contentStyle={{
backgroundColor: '#0f172a',
border: '1px solid #1e293b',
borderRadius: '6px',
color: '#f8fafc',
}}
/>
<Area
type="monotone"
dataKey="cpu"
stroke="#3b82f6"
fillOpacity={1}
fill="url(#colorCpu)"
strokeWidth={2}
name="CPU"
/>
<Area
type="monotone"
dataKey="memory"
stroke="#10b981"
fillOpacity={1}
fill="url(#colorMemory)"
strokeWidth={2}
name="内存"
/>
<Area
type="monotone"
dataKey="disk"
stroke="#a855f7"
fillOpacity={1}
fill="url(#colorDisk)"
strokeWidth={2}
name="磁盘"
/>
<CartesianGrid strokeDasharray="3 3" stroke="var(--chart-grid)" />
<XAxis dataKey="time" stroke="var(--chart-axis)" fontSize={12} tickLine={false} axisLine={false} />
<YAxis stroke="var(--chart-axis)" fontSize={12} tickLine={false} axisLine={false} unit="%" />
<Tooltip content={<CustomTooltip />} />
<Area type="monotone" dataKey="cpu" stroke="var(--dg-blue)" fillOpacity={1} fill="url(#colorCpu)" strokeWidth={2} name="CPU" />
<Area type="monotone" dataKey="memory" stroke="var(--dg-green)" fillOpacity={1} fill="url(#colorMemory)" strokeWidth={2} name="内存" />
<Area type="monotone" dataKey="disk" stroke="var(--dg-purple)" fillOpacity={1} fill="url(#colorDisk)" strokeWidth={2} name="磁盘" />
</AreaChart>
</ResponsiveContainer>
</div>