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

@@ -0,0 +1,157 @@
import { Link, useLocation } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react';
import { useMemo } from 'react';
/**
* Route name mapping - breadcrumb display names
*/
const ROUTE_NAME_MAP: Record<string, string> = {
'': '仪表盘',
'servers': '服务器管理',
'cloud-accounts': '云账号管理',
'domains': '域名管理',
'regions': '区域管理',
'platforms': '云平台',
'cloud-billing': '云账单',
'kubernetes': 'Kubernetes',
'clusters': '集群列表',
'nodes': '节点管理',
'workloads': '工作负载',
'deployments': 'Deployments',
'statefulsets': 'StatefulSets',
'daemonsets': 'DaemonSets',
'cronjobs': '定时任务',
'services': 'Services',
'ingresses': 'Ingresses',
'configmaps': 'ConfigMaps',
'secrets': 'Secrets',
'hpas': 'HPA',
'pvcs': '存储',
'metrics': '资源用量',
'events': '事件',
'capacity': '容量分析',
'topology': '架构拓扑',
'namespace': '命名空间',
'workload': '工作负载',
'view': '查看',
'edit': '编辑',
'pipelines': '流水线',
'deploy': '应用发布',
'configureTools': '发布配置',
'groups': '用户组',
'rbac': '权限管理',
'monitor-center': '资源监控',
'trace': '链路追踪',
'alert-center': '告警中心',
'datasources': '数据源',
'dashboards': '监控大屏',
'host-monitor': '主机监控',
'alerts': '监控告警',
'approval': '资源申请',
'scripts': '脚本库',
'ansible': 'Ansible',
'ai-assistant': '智能助手',
'ai-alert-analyzer': '告警分析',
'ai-predictive': '容量预测',
'users': '用户管理',
'roles': '角色权限',
'logs-audit': '操作审计',
'terminal-audit': '终端审计',
'credentials': '凭证配置',
'settings': '系统设置',
};
interface BreadcrumbItem {
name: string;
path: string;
isLast: boolean;
}
/**
* Breadcrumb - 智能面包屑导航
*
* 根据当前路由自动生成面包屑路径
* 支持动态参数(如 clusterCode, namespace, name)显示
*/
export function Breadcrumb() {
const location = useLocation();
const breadcrumbs = useMemo<BreadcrumbItem[]>(() => {
const paths = location.pathname.split('/').filter(Boolean);
if (paths.length === 0) {
return [{ name: '仪表盘', path: '/', isLast: true }];
}
const items: BreadcrumbItem[] = [];
let currentPath = '';
paths.forEach((segment, index) => {
currentPath += `/${segment}`;
const isLast = index === paths.length - 1;
// Check if it's a dynamic parameter (looks like an identifier, not a known route)
const knownName = ROUTE_NAME_MAP[segment];
let displayName = knownName;
if (!displayName) {
// Dynamic parameter - could be cluster code, namespace, resource name, etc.
if (segment.length > 20 || segment.includes('-')) {
// Likely a UUID or complex identifier - truncate
displayName = segment.length > 15 ? `${segment.slice(0, 12)}...` : segment;
} else {
displayName = segment;
}
}
items.push({
name: displayName,
path: currentPath,
isLast,
});
});
return items;
}, [location.pathname]);
// Don't show breadcrumb on dashboard (root path)
if (breadcrumbs.length <= 1 && location.pathname === '/') {
return null;
}
return (
<nav
aria-label="面包屑导航"
className="flex items-center gap-1.5 text-sm animate-fade-in"
>
<Link
to="/"
className="flex items-center gap-1 text-[var(--dg-text-muted)] hover:text-[var(--dg-blue)] transition-colors duration-200"
title="仪表盘"
>
<Home className="h-3.5 w-3.5" />
</Link>
{breadcrumbs.map((item) => (
<div key={item.path} className="flex items-center gap-1.5">
<ChevronRight className="h-3.5 w-3.5 text-[var(--dg-border)] flex-shrink-0" />
{item.isLast ? (
<span
className="text-[var(--dg-text-primary)] font-medium truncate max-w-[200px] sm:max-w-[300px] md:max-w-[400px]"
title={item.name}
>
{item.name}
</span>
) : (
<Link
to={item.path}
className="text-[var(--dg-text-muted)] hover:text-[var(--dg-blue)] transition-colors duration-200 truncate max-w-[150px]"
title={item.name}
>
{item.name}
</Link>
)}
</div>
))}
</nav>
);
}
@@ -0,0 +1,133 @@
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { Button } from '@/components/ui/button';
import { AlertTriangle, RotateCcw, Home, Bug } from 'lucide-react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
/**
* ErrorBoundary - 全局错误边界组件
*
* 捕获 React 组件树中的错误,防止整个应用崩溃
* 提供友好的错误提示和恢复操作
*/
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error, errorInfo: null };
}
override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('[ErrorBoundary] 捕获到错误:', error);
console.error('[ErrorBoundary] 错误信息:', errorInfo.componentStack);
this.setState({ error, errorInfo });
}
handleRetry = () => {
this.setState({ hasError: false, error: null, errorInfo: null });
};
handleGoHome = () => {
window.location.href = '/';
};
handleReport = () => {
const { error, errorInfo } = this.state;
const body = `## 错误报告\n\n**时间:** ${new Date().toISOString()}\n**URL:** ${window.location.href}\n**用户代理:** ${navigator.userAgent}\n\n### 错误信息\n\n\`\`\`\n${error?.name}: ${error?.message}\n\`\`\`\n\n### 组件堆栈\n\n\`\`\`\n${errorInfo?.componentStack}\n\`\`\`\n`;
navigator.clipboard.writeText(body).then(() => {
alert('错误信息已复制到剪贴板,请粘贴到 Issue 中');
});
};
override render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback;
}
return (
<div className="min-h-[60vh] flex items-center justify-center p-6">
<div className="dg-card max-w-lg w-full p-8 text-center space-y-6">
{/* Error Icon */}
<div className="mx-auto w-16 h-16 rounded-2xl bg-red-500/10 flex items-center justify-center">
<AlertTriangle className="h-8 w-8 text-red-400" />
</div>
{/* Title */}
<div>
<h2 className="text-xl font-bold text-[var(--dg-text-primary)]">
页面出现错误
</h2>
<p className="text-sm text-[var(--dg-text-muted)] mt-2">
抱歉,该页面遇到了意外错误。您可以尝试重新加载或返回首页。
</p>
</div>
{/* Error Detail (collapsible) */}
{this.state.error && (
<div className="text-left">
<details className="group">
<summary className="cursor-pointer text-xs text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] transition-colors flex items-center gap-1.5">
<Bug className="h-3.5 w-3.5" />
查看错误详情
</summary>
<div className="mt-2 p-3 rounded-lg bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] overflow-auto max-h-48">
<code className="text-xs text-red-400 font-mono block whitespace-pre-wrap">
{this.state.error.name}: {this.state.error.message}
</code>
{this.state.errorInfo && (
<pre className="text-xs text-[var(--dg-text-muted)] mt-2 whitespace-pre-wrap">
{this.state.errorInfo.componentStack}
</pre>
)}
</div>
</details>
</div>
)}
{/* Actions */}
<div className="flex items-center justify-center gap-3">
<Button
variant="outline"
className="dg-btn-secondary"
onClick={this.handleGoHome}
>
<Home className="h-4 w-4 mr-1.5" />
返回首页
</Button>
<Button
className="dg-btn-primary"
onClick={this.handleRetry}
>
<RotateCcw className="h-4 w-4 mr-1.5" />
重新加载
</Button>
<Button
variant="outline"
className="dg-btn-ghost"
onClick={this.handleReport}
>
<Bug className="h-4 w-4 mr-1.5" />
复制错误
</Button>
</div>
</div>
</div>
);
}
return this.props.children;
}
}
+259 -72
View File
@@ -1,9 +1,9 @@
import { useState } from 'react';
import { useState, useCallback, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { useThemeStore, useNotificationStore, useUserStore } from '@/store';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
DropdownMenu,
@@ -26,16 +26,48 @@ import {
CheckCircle,
Palette,
Check,
X,
Keyboard,
} from 'lucide-react';
import { formatDistanceToNow } from '@/lib/utils';
import { useTheme, THEME_OPTIONS } from '@/hooks/useTheme';
// Keyboard shortcut handler
function useKeyboardShortcuts() {
const navigate = useNavigate();
const [searchOpen, setSearchOpen] = useState(false);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
// Cmd/Ctrl + K to open search
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
setSearchOpen((prev) => !prev);
}
// Cmd/Ctrl + B to toggle sidebar
if ((e.metaKey || e.ctrlKey) && e.key === 'b') {
e.preventDefault();
// Dispatch custom event for sidebar toggle
window.dispatchEvent(new CustomEvent('toggle-sidebar'));
}
};
window.addEventListener('keydown', handler);
return () => window.removeEventListener('keydown', handler);
}, []);
return { searchOpen, setSearchOpen };
}
export function Header() {
const { sidebarCollapsed, toggleSidebar } = useThemeStore();
const { notifications, unreadCount, markAsRead, markAllAsRead } = useNotificationStore();
const { user, logout } = useUserStore();
const { theme, setTheme } = useTheme();
const navigate = useNavigate();
const [searchValue, setSearchValue] = useState('');
const [searchFocused, setSearchFocused] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
const { searchOpen, setSearchOpen } = useKeyboardShortcuts();
const handleLogout = () => {
logout();
@@ -44,7 +76,7 @@ export function Header() {
const displayName = user?.real_name || user?.username || '管理员';
const getNotificationIcon = (type: string) => {
const getNotificationIcon = useCallback((type: string) => {
switch (type) {
case 'error':
return <AlertTriangle className="h-4 w-4 text-red-500" />;
@@ -55,73 +87,166 @@ export function Header() {
default:
return <Info className="h-4 w-4 text-blue-500" />;
}
};
}, []);
// Quick nav items for search
const quickNavItems = [
{ name: '仪表盘', path: '/', icon: 'LayoutDashboard' },
{ name: '服务器管理', path: '/servers', icon: 'Server' },
{ name: 'Kubernetes 集群', path: '/kubernetes', icon: 'Cloud' },
{ name: '监控告警', path: '/alerts', icon: 'Bell' },
{ name: '告警中心', path: '/alert-center', icon: 'AlertTriangle' },
{ name: '流水线', path: '/pipelines', icon: 'GitBranch' },
{ name: '智能助手', path: '/ai-assistant', icon: 'Brain' },
{ name: '脚本库', path: '/scripts', icon: 'FileCode' },
];
return (
<header className="fixed top-0 right-0 left-0 z-30 h-14 bg-slate-900/95 backdrop-blur supports-[backdrop-filter]:bg-slate-900/60 border-b border-slate-800 transition-all duration-300"
style={{ marginLeft: sidebarCollapsed ? '4rem' : '16rem' }}
<header
className={cn(
'fixed top-0 right-0 z-30 h-[var(--header-height)] bg-[var(--dg-bg-secondary)]/95 backdrop-blur-md',
'border-b border-[var(--dg-border)] transition-[margin] duration-300 ease-in-out',
'supports-[backdrop-filter]:bg-[var(--dg-bg-secondary)]/75',
)}
style={{ marginLeft: 'var(--sidebar-width)', left: 0 }}
>
<div className="flex items-center justify-between h-full px-4">
{/* Left: Toggle & Search */}
<div className="flex items-center gap-3 flex-1">
{sidebarCollapsed && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-slate-400 hover:text-slate-100"
onClick={toggleSidebar}
>
<Menu className="h-4 w-4" />
</Button>
)}
<div className="flex items-center gap-3 flex-1 min-w-0">
{/* Sidebar Toggle */}
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)] flex-shrink-0"
onClick={toggleSidebar}
title={sidebarCollapsed ? '展开侧边栏' : '收起侧边栏'}
>
<Menu className="h-4 w-4" />
</Button>
{/* Global Search */}
<div className="relative w-96 max-w-full">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
<div className={cn(
'relative transition-all duration-300',
searchFocused ? 'w-[28rem] max-w-full' : 'w-80'
)}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-muted)] pointer-events-none" />
<Input
ref={searchInputRef}
type="text"
placeholder="搜索服务器、应用、工单、文档..."
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
className="pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500 focus-visible:ring-blue-500/30"
onFocus={() => setSearchFocused(true)}
onBlur={() => setTimeout(() => setSearchFocused(false), 200)}
className={cn(
'pl-9 h-9 text-sm transition-all duration-300',
'bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]',
'text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]',
'focus:border-[var(--dg-blue)] focus:ring-1 focus:ring-[var(--dg-blue)]/30',
'hover:border-[var(--dg-border-hover)]',
)}
/>
<kbd className="absolute right-3 top-1/2 -translate-y-1/2 px-1.5 py-0.5 text-xs font-mono text-slate-500 bg-slate-800 rounded">
<kbd className="absolute right-3 top-1/2 -translate-y-1/2 px-1.5 py-0.5 text-[10px] font-mono text-[var(--dg-text-muted)] bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded hidden sm:inline-block">
⌘K
</kbd>
</div>
{/* Search Dropdown */}
{searchFocused && searchValue && (
<div
className={cn(
'absolute top-full left-0 right-0 mt-2 py-2 rounded-lg',
'bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]',
'shadow-lg z-50 animate-scale-in',
)}
style={{ boxShadow: 'var(--shadow-dropdown)' }}
>
<div className="px-3 py-1.5 text-xs font-medium text-[var(--dg-text-muted)] uppercase tracking-wider">
快速导航
</div>
{quickNavItems
.filter((item) =>
item.name.toLowerCase().includes(searchValue.toLowerCase())
)
.map((item) => (
<button
key={item.path}
className={cn(
'w-full flex items-center gap-2.5 px-3 py-2 text-sm',
'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]',
'hover:bg-[var(--dg-bg-hover)] transition-colors text-left',
)}
onMouseDown={(e) => {
e.preventDefault();
navigate(item.path);
setSearchValue('');
setSearchFocused(false);
}}
>
<Search className="h-3.5 w-3.5" />
<span>{item.name}</span>
</button>
))}
{quickNavItems.filter((item) =>
item.name.toLowerCase().includes(searchValue.toLowerCase())
).length === 0 && (
<div className="px-3 py-4 text-center text-sm text-[var(--dg-text-muted)]">
未找到匹配的结果
</div>
)}
</div>
)}
</div>
</div>
{/* Right: Actions */}
<div className="flex items-center gap-2">
<div className="flex items-center gap-1.5 flex-shrink-0">
{/* Theme Switcher */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
title="切换主题"
>
<Palette className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56 bg-slate-800 border-slate-700">
<DropdownMenuLabel className="text-slate-300">主题切换</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-slate-700" />
<DropdownMenuContent
align="end"
className="w-60 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"
style={{ boxShadow: 'var(--shadow-dropdown)' }}
>
<DropdownMenuLabel className="text-[var(--dg-text-secondary)]">主题切换</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-[var(--dg-border)]" />
{THEME_OPTIONS.map((option) => (
<DropdownMenuItem
key={option.id}
className={cn(
'flex items-center gap-2 cursor-pointer focus:bg-slate-700 focus:text-slate-100',
theme === option.id ? 'text-slate-100' : 'text-slate-300'
'flex items-center gap-2.5 cursor-pointer transition-colors',
'focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]',
theme === option.id
? 'text-[var(--dg-text-primary)]'
: 'text-[var(--dg-text-secondary)]',
)}
onClick={() => setTheme(option.id)}
>
<span
className="w-3 h-3 rounded-full shrink-0 ring-2 ring-slate-900"
style={{ backgroundColor: option.primaryColor }}
className="w-3.5 h-3.5 rounded-full shrink-0 ring-2"
style={{
backgroundColor: option.primaryColor,
boxShadow: '0 0 0 2px var(--dg-bg-primary)',
}}
/>
<div className="flex-1 min-w-0">
<span className="text-sm font-medium">{option.name}</span>
<span className="block text-xs text-slate-500 truncate">{option.description}</span>
<span className="block text-xs text-[var(--dg-text-muted)] truncate">
{option.description}
</span>
</div>
{theme === option.id && <Check className="h-4 w-4 text-blue-400 shrink-0" />}
{theme === option.id && (
<Check className="h-4 w-4 text-[var(--dg-blue)] shrink-0" />
)}
</DropdownMenuItem>
))}
</DropdownMenuContent>
@@ -130,101 +255,163 @@ export function Header() {
{/* Notifications */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100 relative">
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)] relative"
title="通知"
>
<Bell className="h-4 w-4" />
{unreadCount > 0 && (
<span className="absolute -top-0.5 -right-0.5 h-4 w-4 rounded-full bg-red-500 text-[10px] font-medium text-white flex items-center justify-center">
<span className="absolute -top-0.5 -right-0.5 h-4.5 w-4.5 rounded-full bg-red-500 text-[10px] font-semibold text-white flex items-center justify-center animate-scale-in">
{unreadCount > 99 ? '99+' : unreadCount}
</span>
)}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 bg-slate-800 border-slate-700">
<DropdownMenuLabel className="flex items-center justify-between text-slate-300">
<span>通知</span>
<DropdownMenuContent
align="end"
className="w-96 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0"
style={{ boxShadow: 'var(--shadow-dropdown)' }}
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--dg-border)]">
<span className="text-sm font-medium text-[var(--dg-text-primary)]">
通知
</span>
{unreadCount > 0 && (
<Button
variant="ghost"
size="sm"
className="h-6 text-xs text-slate-400 hover:text-slate-100"
className="h-7 text-xs text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
onClick={markAllAsRead}
>
<CheckCheck className="h-3 w-3 mr-1" />
<CheckCheck className="h-3.5 w-3.5 mr-1" />
全部已读
</Button>
)}
</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-slate-700" />
<div className="max-h-80 overflow-y-auto">
</div>
{/* Notification List */}
<div className="max-h-80 overflow-y-auto scrollbar-thin">
{notifications.length === 0 ? (
<div className="py-8 text-center text-slate-500">
<Bell className="h-8 w-8 mx-auto mb-2 opacity-50" />
<div className="flex flex-col items-center justify-center py-10 text-[var(--dg-text-muted)]">
<Bell className="h-10 w-10 mb-3 opacity-30" />
<p className="text-sm">暂无通知</p>
</div>
) : (
notifications.slice(0, 10).map((notification) => (
<DropdownMenuItem
<div
key={notification.id}
className={cn(
'flex items-start gap-3 p-3 cursor-pointer focus:bg-slate-700',
!notification.read && 'bg-slate-700/30'
'flex items-start gap-3 px-4 py-3 cursor-pointer transition-colors',
'hover:bg-[var(--dg-bg-hover)] border-b border-[var(--dg-border)] last:border-0',
!notification.read && 'bg-[var(--dg-blue)]/[0.04]',
)}
onClick={() => markAsRead(notification.id)}
>
{getNotificationIcon(notification.type)}
<div className="mt-0.5 flex-shrink-0">
{getNotificationIcon(notification.type)}
</div>
<div className="flex-1 min-w-0">
<p className={cn('text-sm font-medium', !notification.read ? 'text-slate-200' : 'text-slate-400')}>
<p
className={cn(
'text-sm font-medium',
!notification.read
? 'text-[var(--dg-text-primary)]'
: 'text-[var(--dg-text-secondary)]',
)}
>
{notification.title}
</p>
<p className="text-xs text-slate-500 mt-0.5 line-clamp-2">{notification.message}</p>
<p className="text-xs text-slate-600 mt-1">
<p className="text-xs text-[var(--dg-text-muted)] mt-0.5 line-clamp-2">
{notification.message}
</p>
<p className="text-xs text-[var(--dg-text-muted)]/60 mt-1">
{formatDistanceToNow(notification.timestamp)}
</p>
</div>
{!notification.read && (
<span className="w-2 h-2 rounded-full bg-blue-500 mt-1" />
<span className="w-2 h-2 rounded-full bg-[var(--dg-blue)] mt-2 flex-shrink-0" />
)}
</DropdownMenuItem>
</div>
))
)}
</div>
{/* Footer */}
{notifications.length > 0 && (
<div className="px-4 py-2 border-t border-[var(--dg-border)] text-center">
<button
className="text-xs text-[var(--dg-text-muted)] hover:text-[var(--dg-blue)] transition-colors"
onClick={() => navigate('/alert-center')}
>
查看全部通知
</button>
</div>
)}
</DropdownMenuContent>
</DropdownMenu>
<Separator orientation="vertical" className="h-6 bg-slate-800" />
<Separator orientation="vertical" className="h-5 bg-[var(--dg-border)] mx-1" />
{/* User Menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" className="h-8 gap-2 px-2 text-slate-300 hover:text-slate-100">
<div className="w-6 h-6 rounded-full bg-blue-600 flex items-center justify-center text-white text-xs font-medium">
{displayName.charAt(0)}
<Button
variant="ghost"
className="h-8 gap-2 px-2 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
>
<div className="w-7 h-7 rounded-full bg-gradient-to-br from-[var(--dg-blue)] to-[var(--dg-purple)] flex items-center justify-center text-white text-xs font-bold">
{displayName.charAt(0).toUpperCase()}
</div>
<span className="hidden md:inline text-sm">{displayName}</span>
<span className="hidden md:inline text-sm max-w-[100px] truncate">
{displayName}
</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 bg-slate-800 border-slate-700">
<DropdownMenuLabel className="text-slate-300">我的账号</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-slate-700" />
<DropdownMenuItem className="text-slate-300 focus:bg-slate-700 focus:text-slate-100">
<User className="h-4 w-4 mr-2" />
<DropdownMenuContent
align="end"
className="w-52 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"
style={{ boxShadow: 'var(--shadow-dropdown)' }}
>
<DropdownMenuLabel className="text-[var(--dg-text-secondary)]">
<div className="flex flex-col">
<span className="text-sm font-medium text-[var(--dg-text-primary)]">
{displayName}
</span>
<span className="text-xs text-[var(--dg-text-muted)] truncate">
{user?.email || user?.username || ''}
</span>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator className="bg-[var(--dg-border)]" />
<DropdownMenuItem
className="text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)] cursor-pointer"
onClick={() => navigate('/users')}
>
<User className="h-4 w-4 mr-2.5" />
个人中心
</DropdownMenuItem>
<DropdownMenuItem className="text-slate-300 focus:bg-slate-700 focus:text-slate-100">
<Settings className="h-4 w-4 mr-2" />
<DropdownMenuItem
className="text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)] cursor-pointer"
onClick={() => navigate('/settings')}
>
<Settings className="h-4 w-4 mr-2.5" />
账号设置
</DropdownMenuItem>
<DropdownMenuSeparator className="bg-slate-700" />
<DropdownMenuItem className="text-red-400 focus:bg-slate-700 focus:text-red-400" onClick={handleLogout}>
<LogOut className="h-4 w-4 mr-2" />
<DropdownMenuSeparator className="bg-[var(--dg-border)]" />
<DropdownMenuItem
className="text-red-400 focus:bg-red-500/10 focus:text-red-400 cursor-pointer"
onClick={handleLogout}
>
<LogOut className="h-4 w-4 mr-2.5" />
退出登录
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Tabs 已移除 — 侧边栏导航已足够,tab 栏多余且遮挡内容 */}
</header>
);
}
+35 -9
View File
@@ -3,28 +3,54 @@ import { cn } from '@/lib/utils';
import { useThemeStore } from '@/store';
import { Sidebar } from './Sidebar';
import { Header } from './Header';
import { Breadcrumb } from './Breadcrumb';
/**
* MainLayout - 优化后的主布局组件
*
* 优化点:
* 1. 使用 CSS 变量 + Tailwind 类替代硬编码的 style 属性
* 2. sidebar 宽度通过 CSS 变量管理,统一协调
* 3. 添加 Breadcrumb 面包屑导航
* 4. 布局过渡动画平滑
* 5. 支持响应式布局
*/
export function MainLayout() {
const { sidebarCollapsed } = useThemeStore();
return (
<div className="min-h-screen bg-slate-950">
<div
className="min-h-screen bg-[var(--dg-bg-primary)] transition-colors duration-300"
style={{
'--sidebar-width': sidebarCollapsed ? '4rem' : '16rem',
'--header-height': '3.5rem',
} as React.CSSProperties}
>
<Sidebar />
<div
className="transition-all duration-300"
style={{ marginLeft: sidebarCollapsed ? '4rem' : '16rem' }}
className={cn(
'flex flex-col min-h-screen transition-[margin] duration-300 ease-in-out',
)}
style={{ marginLeft: 'var(--sidebar-width)' }}
>
<Header />
<main
className={cn(
'pt-14 transition-all duration-300',
'min-h-[calc(100vh-3.5rem)]'
)}
>
<main className="flex-1 pt-[var(--header-height)]">
{/* Breadcrumb Navigation */}
<div className="px-6 pt-4 pb-0">
<Breadcrumb />
</div>
{/* Page Content */}
<div className="p-6">
<Outlet />
</div>
</main>
{/* Footer */}
<footer className="px-6 py-4 border-t border-[var(--dg-border)] mt-auto">
<div className="flex items-center justify-between text-xs text-[var(--dg-text-muted)]">
<span>AIOps 智能运维平台</span>
<span>v1.0.0</span>
</div>
</footer>
</div>
</div>
);
@@ -0,0 +1,34 @@
import { useRef, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
/**
* PageTransition - 页面切换过渡动画包装器
*
* 使用 IntersectionObserver + CSS animation 实现平滑的页面进入动画
* 所有子页面自动获得 fade-in 动画效果
*/
export function PageTransition({ children, key }: { children: React.ReactNode; key?: string }) {
const ref = useRef<HTMLDivElement>(null);
const [isVisible, setIsVisible] = useState(false);
const location = useLocation();
const transitionKey = key || location.pathname;
useEffect(() => {
// Reset visibility on route change
setIsVisible(false);
const timer = setTimeout(() => setIsVisible(true), 30);
return () => clearTimeout(timer);
}, [transitionKey]);
return (
<div
ref={ref}
className={`transition-all duration-350 ease-out ${
isVisible ? 'opacity-100 translate-y-0' : 'opacity-0 translate-y-2'
}`}
style={{ willChange: 'opacity, transform' }}
>
{children}
</div>
);
}
+159 -63
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
import { cn } from '@/lib/utils';
import { useThemeStore, useMenuStore } from '@/store';
@@ -9,10 +9,10 @@ import {
Menu, Network, CloudCog, Globe, MapPin, Key,
Brain, Activity, BarChart3, GitBranch,
Bot, AlertTriangle, Container, Boxes, Clock, Rocket,
Layers,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
interface MenuItem {
id: string;
@@ -39,7 +39,6 @@ const menuItems: MenuItem[] = [
id: 'kubernetes', name: 'Kubernetes', icon: Cloud,
children: [
{ id: 'k8s-clusters', name: '集群列表', icon: Cloud, path: '/kubernetes' },
{ id: 'k8s-compare', name: '多集群对比', icon: Layers, path: '/kubernetes/compare' },
{ id: 'k8s-nodes', name: '节点管理', icon: Cpu, path: '/nodes' },
{
id: 'k8s-workload', name: '工作负载', icon: Boxes,
@@ -95,7 +94,7 @@ const menuItems: MenuItem[] = [
children: [
{ id: 'cronjobs', name: '定时任务', icon: PlayCircle, path: '/cronjobs' },
{ id: 'scripts', name: '脚本库', icon: FileCode, path: '/scripts' },
{ id: 'ansible', name: '远程执行', icon: Terminal, path: '/remote-exec' },
{ id: 'ansible', name: '远程执行', icon: Terminal, path: '/ansible' },
],
},
{
@@ -120,18 +119,38 @@ const menuItems: MenuItem[] = [
},
];
/**
* MenuItemComponent - 侧边栏菜单项(支持多级嵌套)
*
* 优化点:
* 1. 使用 Tooltip 在折叠状态下显示菜单名称
* 2. 动画过渡平滑
* 3. 活动状态判断更精确
* 4. 子菜单展开/收起动画
*/
function MenuItemComponent({ item, depth = 0 }: { item: MenuItem; depth?: number }) {
const location = useLocation();
const { openMenus, toggleMenu, activeMenu, setActiveMenu } = useMenuStore();
const { sidebarCollapsed } = useThemeStore();
const hasChildren = item.children && item.children.length > 0;
const isOpen = openMenus.includes(item.id);
// Determine if this menu item is active
const isActive = item.path
? location.pathname === item.path || location.pathname.startsWith(item.path + '/')
: (item.id === 'kubernetes' && location.pathname.startsWith('/kubernetes')) ||
(item.id === 'k8s-workload' && location.pathname.startsWith('/workloads')) ||
(item.id === 'k8s-network' && (location.pathname.includes('/services') || location.pathname.includes('/ingresses'))) ||
(item.id === 'k8s-config' && (location.pathname.includes('/configmaps') || location.pathname.includes('/secrets'))) ||
activeMenu === item.id;
const isActiveParent = hasChildren && item.children?.some((child) => {
if (child.path) {
return location.pathname === child.path || location.pathname.startsWith(child.path + '/');
}
return false;
});
const handleClick = () => {
if (hasChildren) {
toggleMenu(item.id);
@@ -140,107 +159,184 @@ function MenuItemComponent({ item, depth = 0 }: { item: MenuItem; depth?: number
}
};
// Collapsed mode (only top-level)
if (sidebarCollapsed && depth === 0) {
return (
<div className="relative group">
<Button
variant={isActive ? 'secondary' : 'ghost'}
size="icon"
className={cn('w-10 h-10 mx-auto mb-1', isActive && 'bg-blue-600/20 text-blue-400')}
asChild={!hasChildren}
>
{hasChildren ? (
<span onClick={handleClick}><item.icon className="h-5 w-5" /></span>
) : (
<NavLink to={item.path || '#'} onClick={handleClick}><item.icon className="h-5 w-5" /></NavLink>
)}
</Button>
<div className="absolute left-full top-1/2 -translate-y-1/2 ml-2 px-3 py-1.5 bg-slate-800 text-slate-100 text-sm rounded-md opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all whitespace-nowrap z-50 border border-slate-700">
{item.name}
{hasChildren && (
<div className="absolute left-0 top-0 mt-2 ml-2 w-48 bg-slate-800 rounded-md border border-slate-700 shadow-lg py-1">
{item.children?.map((child) => (
<NavLink key={child.id} to={child.path || '#'}
className={({ isActive }) => cn('block px-4 py-2 text-sm hover:bg-slate-700 transition-colors', isActive ? 'text-blue-400 bg-blue-600/10' : 'text-slate-300')}>
{child.name}
</NavLink>
))}
<TooltipProvider delayDuration={100}>
<Tooltip>
<TooltipTrigger asChild>
<div className="relative">
{hasChildren ? (
<Button
variant={isActive || isActiveParent ? 'secondary' : 'ghost'}
size="icon"
className={cn(
'w-10 h-10 mx-auto mb-1 transition-all duration-200',
(isActive || isActiveParent)
? 'bg-[var(--dg-blue)]/15 text-[var(--dg-blue)]'
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]',
)}
onClick={handleClick}
>
<item.icon className="h-5 w-5" />
</Button>
) : (
<Button
variant={isActive ? 'secondary' : 'ghost'}
size="icon"
className={cn(
'w-10 h-10 mx-auto mb-1 transition-all duration-200',
isActive
? 'bg-[var(--dg-blue)]/15 text-[var(--dg-blue)]'
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]',
)}
asChild
>
<NavLink to={item.path || '#'} onClick={handleClick}>
<item.icon className="h-5 w-5" />
</NavLink>
</Button>
)}
</div>
)}
</div>
</div>
</TooltipTrigger>
<TooltipContent side="right" className="bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]">
{item.name}
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
return (
<div className={cn('mb-0.5', depth > 0 && 'ml-3')}>
<div className={cn('mb-0.5', depth > 0 && 'ml-2.5')}>
{hasChildren ? (
<>
<Button
variant={isActive ? 'secondary' : 'ghost'}
className={cn('w-full justify-between h-8 px-2.5 text-xs font-normal', isActive ? 'bg-blue-600/20 text-blue-400 hover:bg-blue-600/30' : 'text-slate-300 hover:text-slate-100 hover:bg-slate-800')}
variant={isActive || isActiveParent ? 'secondary' : 'ghost'}
className={cn(
'w-full justify-between h-8 px-2.5 text-xs font-normal transition-all duration-200',
(isActive || isActiveParent)
? 'bg-[var(--dg-blue)]/10 text-[var(--dg-blue)] hover:bg-[var(--dg-blue)]/15'
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]',
)}
onClick={handleClick}
>
<span className="flex items-center gap-1.5">
<item.icon className="h-3.5 w-3.5" />
<span>{item.name}</span>
<span className="flex items-center gap-2">
<item.icon className={cn('h-3.5 w-3.5', (isActive || isActiveParent) && 'text-[var(--dg-blue)]')} />
<span className="truncate">{item.name}</span>
</span>
{isOpen ? <ChevronDown className="h-3 w-3 text-slate-500" /> : <ChevronRight className="h-3 w-3 text-slate-500" />}
<ChevronDown
className={cn(
'h-3 w-3 text-[var(--dg-text-muted)] transition-transform duration-200',
!isOpen && '-rotate-90',
)}
/>
</Button>
{isOpen && (
<div className="mt-0.5 space-y-0.5">
{/* Submenu with animation */}
<div
className={cn(
'overflow-hidden transition-all duration-200 ease-in-out',
isOpen ? 'max-h-[800px] opacity-100 mt-0.5' : 'max-h-0 opacity-0',
)}
>
<div className="space-y-0.5 border-l border-[var(--dg-border)] ml-4 pl-1.5">
{item.children?.map((child) => (
<MenuItemComponent key={child.id} item={child} depth={depth + 1} />
))}
</div>
)}
</div>
</>
) : (
<NavLink
to={item.path || '#'}
onClick={handleClick}
className={({ isActive }) =>
cn('flex items-center gap-1.5 h-8 px-2.5 text-xs rounded-md transition-colors',
isActive ? 'bg-blue-600/20 text-blue-400' : 'text-slate-400 hover:text-slate-100 hover:bg-slate-800')
className={({ isActive: navActive }) =>
cn(
'flex items-center gap-2 h-8 px-2.5 text-xs rounded-md transition-all duration-200',
navActive || isActive
? 'bg-[var(--dg-blue)]/10 text-[var(--dg-blue)] font-medium'
: 'text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]',
)
}
>
<item.icon className="h-3.5 w-3.5" />
<span>{item.name}</span>
<item.icon className="h-3.5 w-3.5 flex-shrink-0" />
<span className="truncate">{item.name}</span>
</NavLink>
)}
</div>
);
}
/**
* Sidebar - 优化后的侧边栏导航
*
* 优化点:
* 1. 使用 CSS 变量控制宽度,统一协调
* 2. 添加 Tooltip 支持(折叠状态)
* 3. 子菜单展开/收起动画
* 4. Logo 区域更精致
* 5. 底部添加版本信息
*/
export function Sidebar() {
const { sidebarCollapsed, toggleSidebar } = useThemeStore();
// Listen for keyboard shortcut
useEffect(() => {
const handler = () => toggleSidebar();
window.addEventListener('toggle-sidebar' as any, handler);
return () => window.removeEventListener('toggle-sidebar' as any, handler);
}, [toggleSidebar]);
return (
<aside className={cn('fixed left-0 top-0 z-40 h-screen bg-slate-900 border-r border-slate-800 transition-all duration-300', sidebarCollapsed ? 'w-16' : 'w-64')}>
<div className="flex items-center justify-between h-14 px-4 border-b border-slate-800">
{!sidebarCollapsed && (
<div className="flex items-center gap-2">
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center">
<Cloud className="h-5 w-5 text-white" />
</div>
<span className="font-semibold text-slate-100">AIOps平台</span>
</div>
)}
{sidebarCollapsed && (
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center mx-auto">
<aside
className={cn(
'fixed left-0 top-0 z-40 h-screen bg-[var(--dg-bg-secondary)] border-r border-[var(--dg-border)]',
'flex flex-col transition-[width] duration-300 ease-in-out',
)}
style={{ width: 'var(--sidebar-width)' }}
>
{/* Logo Area */}
<div className="flex items-center h-14 px-3 border-b border-[var(--dg-border)] flex-shrink-0">
<div className={cn('flex items-center gap-2.5 flex-1 min-w-0', sidebarCollapsed && 'justify-center')}>
<div className="w-8 h-8 rounded-lg bg-gradient-to-br from-[var(--dg-blue)] to-[var(--dg-cyan)] flex items-center justify-center flex-shrink-0 shadow-lg shadow-[var(--dg-blue)]/20">
<Cloud className="h-5 w-5 text-white" />
</div>
)}
{!sidebarCollapsed && (
<span className="font-bold text-[var(--dg-text-primary)] text-sm tracking-tight truncate">
AIOps平台
</span>
)}
</div>
{!sidebarCollapsed && (
<Button variant="ghost" size="icon" className="h-8 w-8 text-slate-400 hover:text-slate-100" onClick={toggleSidebar}>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)] flex-shrink-0"
onClick={toggleSidebar}
title="收起侧边栏"
>
<Menu className="h-4 w-4" />
</Button>
)}
</div>
<ScrollArea className="h-[calc(100vh-3.5rem)]">
<div className={cn('p-1.5', sidebarCollapsed && 'px-1')}>
{menuItems.map((item) => <MenuItemComponent key={item.id} item={item} />)}
</div>
{/* Menu Items */}
<ScrollArea className="flex-1 py-2 px-1.5">
<nav className="space-y-0.5">
{menuItems.map((item) => (
<MenuItemComponent key={item.id} item={item} />
))}
</nav>
</ScrollArea>
{/* Footer */}
{!sidebarCollapsed && (
<div className="px-3 py-2 border-t border-[var(--dg-border)] flex-shrink-0">
<div className="text-[10px] text-[var(--dg-text-muted)] text-center">
AIOps v1.0.0
</div>
</div>
)}
</aside>
);
}
@@ -0,0 +1,133 @@
import { cn } from '@/lib/utils';
/**
* SkeletonCard - 骨架屏卡片组件
*
* 优化点:
* 1. 使用 CSS 动画实现 shimmer 效果
* 2. 主题感知(跟随当前主题的颜色)
* 3. 多种变体:统计卡片、图表、列表、表格
*/
interface SkeletonCardProps {
variant?: 'stat' | 'chart' | 'list' | 'table' | 'card';
className?: string;
}
export function SkeletonCard({ variant = 'card', className }: SkeletonCardProps) {
const shimmerClass = 'dg-skeleton';
if (variant === 'stat') {
return (
<div className={cn('dg-card p-6 space-y-4', className)}>
<div className="flex items-start justify-between">
<div className="space-y-3 flex-1">
<div className={cn('h-4 w-24 rounded', shimmerClass)} />
<div className={cn('h-8 w-16 rounded', shimmerClass)} />
</div>
<div className={cn('h-10 w-10 rounded-lg', shimmerClass)} />
</div>
<div className={cn('h-3 w-32 rounded', shimmerClass)} />
</div>
);
}
if (variant === 'chart') {
return (
<div className={cn('dg-card p-6 space-y-4', className)}>
<div className="space-y-2">
<div className={cn('h-5 w-32 rounded', shimmerClass)} />
<div className={cn('h-3 w-48 rounded', shimmerClass)} />
</div>
<div className={cn('h-[200px] rounded-lg', shimmerClass)} />
</div>
);
}
if (variant === 'table') {
return (
<div className={cn('dg-card overflow-hidden', className)}>
{/* Header */}
<div className="flex items-center gap-4 p-4 border-b border-[var(--dg-border)]">
<div className={cn('h-4 w-8 rounded', shimmerClass)} />
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className={cn('h-4 flex-1 rounded', shimmerClass)} />
))}
</div>
{/* Rows */}
{Array.from({ length: 5 }).map((_, rowIdx) => (
<div key={rowIdx} className="flex items-center gap-4 p-4 border-b border-[var(--dg-border)] last:border-0">
<div className={cn('h-4 w-8 rounded', shimmerClass)} />
{Array.from({ length: 6 }).map((_, colIdx) => (
<div key={colIdx} className={cn('h-4 flex-1 rounded', shimmerClass)} />
))}
</div>
))}
</div>
);
}
// Default list skeleton
return (
<div className={cn('dg-card p-6 space-y-4', className)}>
<div className="space-y-2">
<div className={cn('h-5 w-40 rounded', shimmerClass)} />
<div className={cn('h-3 w-56 rounded', shimmerClass)} />
</div>
<div className="space-y-3">
{Array.from({ length: 4 }).map((_, i) => (
<div key={i} className="flex items-center gap-3">
<div className={cn('h-8 w-8 rounded-lg', shimmerClass)} />
<div className="flex-1 space-y-2">
<div className={cn('h-3 w-full rounded', shimmerClass)} />
<div className={cn('h-3 w-2/3 rounded', shimmerClass)} />
</div>
</div>
))}
</div>
</div>
);
}
/**
* SkeletonStats - 统计卡片骨架屏网格
*/
export function SkeletonStats({ count = 4 }: { count?: number }) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{Array.from({ length: count }).map((_, i) => (
<SkeletonCard key={i} variant="stat" />
))}
</div>
);
}
/**
* SkeletonDashboard - 仪表盘骨架屏
*/
export function SkeletonDashboard() {
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div className="space-y-2">
<div className="dg-skeleton h-7 w-24 rounded" />
<div className="dg-skeleton h-4 w-48 rounded" />
</div>
<div className="dg-skeleton h-9 w-20 rounded-lg" />
</div>
{/* Stats */}
<SkeletonStats count={4} />
{/* Chart */}
<SkeletonCard variant="chart" />
{/* Two column layout */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<SkeletonCard variant="list" />
<SkeletonCard variant="list" />
</div>
</div>
);
}