"use client" import { useEffect, useState } from "react" import Link from "next/link" import { usePathname } from "next/navigation" import { getMenus, type MenuItem } from "@/lib/menu-api" import * as LucideIcons from "lucide-react" import { ChevronDown, ChevronRight } from "lucide-react" export function Sidebar() { const pathname = usePathname() const [menus, setMenus] = useState([]) const [loading, setLoading] = useState(true) // 使用Set来存储已展开的菜单ID const [expandedMenus, setExpandedMenus] = useState>(new Set()) useEffect(() => { const fetchMenus = async () => { setLoading(true) try { const data = await getMenus() setMenus(data || []) // 自动展开当前活动菜单的父菜单 autoExpandActiveMenuParent(data || []); } catch (error) { console.error("获取菜单失败:", error) } finally { setLoading(false) } } fetchMenus() }, []) // 自动展开当前活动菜单的父菜单 const autoExpandActiveMenuParent = (menuItems: MenuItem[]) => { const newExpandedMenus = new Set(); // 递归查找当前路径匹配的菜单项 const findActiveMenu = (items: MenuItem[], parentIds: number[] = []) => { for (const item of items) { const currentPath = pathname === "/" ? "/dashboard" : pathname; const itemPath = item.path; if (currentPath === itemPath || currentPath.startsWith(itemPath + "/")) { // 将所有父菜单ID添加到展开集合 parentIds.forEach(id => newExpandedMenus.add(id)); return true; } if (item.children && item.children.length > 0) { const found = findActiveMenu(item.children, [...parentIds, item.id]); if (found) { return true; } } } return false; }; findActiveMenu(menuItems); setExpandedMenus(newExpandedMenus); }; // 切换菜单展开状态 const toggleMenu = (menuId: number) => { setExpandedMenus(prev => { const newExpanded = new Set(prev); if (newExpanded.has(menuId)) { newExpanded.delete(menuId); } else { newExpanded.add(menuId); } return newExpanded; }); }; // 获取Lucide图标组件 const getLucideIcon = (iconName: string) => { if (!iconName) return null; const Icon = (LucideIcons as any)[iconName]; return Icon ? : null; }; // 递归渲染菜单项 const renderMenuItem = (item: MenuItem) => { const hasChildren = item.children && item.children.length > 0; const isExpanded = expandedMenus.has(item.id); const isActive = pathname === item.path; const isChildActive = hasChildren && item.children!.some(child => pathname === child.path || pathname.startsWith(child.path + "/") ); return (
  • {hasChildren ? (
    {isExpanded && hasChildren && (
      {item.children!.map(child => { const isChildItemActive = pathname === child.path; return (
    • {child.icon && getLucideIcon(child.icon)} {child.title}
    • ); })}
    )}
    ) : ( {item.icon && getLucideIcon(item.icon)} {item.title} )}
  • ); }; return (

    超级管理员

    ); }