import React, { useState, useEffect, useMemo } from 'react'; import { Outlet, useLocation, } from 'react-router'; import { Layout, Button, Space, Badge, Avatar, Dropdown, Typography, Input, Menu, } from 'antd'; import { MenuFoldOutlined, MenuUnfoldOutlined, BellOutlined, VerticalAlignTopOutlined, UserOutlined } from '@ant-design/icons'; import { useAuth } from '../hooks/AuthProvider'; import { useMenu, useMenuSearch, type MenuItem } from '../menu'; import { getGlobalConfig } from '@/client/utils/utils'; const { Header, Sider, Content } = Layout; /** * 主布局组件 * 包含侧边栏、顶部导航和内容区域 */ export const MainLayout = () => { const { user } = useAuth(); const [showBackTop, setShowBackTop] = useState(false); const location = useLocation(); // 使用菜单hook const { menuItems, userMenuItems, openKeys, collapsed, setCollapsed, handleMenuClick: handleRawMenuClick, onOpenChange } = useMenu(); // 处理菜单点击 const handleMenuClick = (key: string) => { const item = findMenuItem(menuItems, key); if (item && 'label' in item) { handleRawMenuClick(item); } }; // 查找菜单项 const findMenuItem = (items: MenuItem[], key: string): MenuItem | null => { for (const item of items) { if (!item) continue; if (item.key === key) return item; if (item.children) { const found = findMenuItem(item.children, key); if (found) return found; } } return null; }; // 使用菜单搜索hook const { searchText, setSearchText, filteredMenuItems } = useMenuSearch(menuItems); // 获取当前选中的菜单项 const selectedKey = useMemo(() => { const findSelectedKey = (items: MenuItem[]): string | null => { for (const item of items) { if (!item) continue; if (item.path === location.pathname) return item.key || null; if (item.children) { const childKey = findSelectedKey(item.children); if (childKey) return childKey; } } return null; }; return findSelectedKey(menuItems) || ''; }, [location.pathname, menuItems]); // 检测滚动位置,控制回到顶部按钮显示 useEffect(() => { const handleScroll = () => { setShowBackTop(window.pageYOffset > 300); }; window.addEventListener('scroll', handleScroll); return () => window.removeEventListener('scroll', handleScroll); }, []); // 回到顶部 const scrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }; // 应用名称 - 从CONFIG中获取或使用默认值 const appName = getGlobalConfig('APP_NAME') || '应用Starter'; return (
{collapsed ? '应用' : appName} {/* 菜单搜索框 */} {!collapsed && (
setSearchText(e.target.value)} />
)}
{/* 菜单列表 */} handleMenuClick(key)} inlineCollapsed={collapsed} />
{/* 回到顶部按钮 */} {showBackTop && (