"use client"; import React, { useEffect, useRef, useState,useCallback } from "react"; import Link from "next/link"; import Image from "next/image"; import { usePathname } from "next/navigation"; import { useSidebar } from "../context/SidebarContext"; import { BoxCubeIcon, CalenderIcon, ChevronDownIcon, GridIcon, HorizontaLDots, ListIcon, PageIcon, PieChartIcon, PlugInIcon, TableIcon, UserCircleIcon, } from "../icons/index"; type NavItem = { name: string; icon: React.ReactNode; path?: string; subItems?: { name: string; path: string; pro?: boolean; new?: boolean }[]; }; const navItems: NavItem[] = [ { icon: , name: "Dashboard", subItems: [{ name: "Ecommerce", path: "/", pro: false }], }, { name: "All Registration", icon: , path: "/all-registration", }, ]; const othersItems: NavItem[] = [ ]; const AppSidebar: React.FC = () => { const { isExpanded, isMobileOpen, isHovered, setIsHovered } = useSidebar(); const pathname = usePathname(); const renderMenuItems = ( navItems: NavItem[], menuType: "main" ) => ( ); const [openSubmenu, setOpenSubmenu] = useState<{ type: "main"; index: number; } | null>(null); const [subMenuHeight, setSubMenuHeight] = useState>( {} ); const subMenuRefs = useRef>({}); // const isActive = (path: string) => path === pathname; const isActive = useCallback((path: string) => path === pathname, [pathname]); useEffect(() => { // Check if the current path matches any submenu item let submenuMatched = false; ["main"].forEach((menuType) => { const items = menuType === "main" ? navItems : othersItems; items.forEach((nav, index) => { if (nav.subItems) { nav.subItems.forEach((subItem) => { if (isActive(subItem.path)) { setOpenSubmenu({ type: menuType as "main", index, }); submenuMatched = true; } }); } }); }); // If no submenu item matches, close the open submenu if (!submenuMatched) { setOpenSubmenu(null); } }, [pathname,isActive]); useEffect(() => { // Set the height of the submenu items when the submenu is opened if (openSubmenu !== null) { const key = `${openSubmenu.type}-${openSubmenu.index}`; if (subMenuRefs.current[key]) { setSubMenuHeight((prevHeights) => ({ ...prevHeights, [key]: subMenuRefs.current[key]?.scrollHeight || 0, })); } } }, [openSubmenu]); const handleSubmenuToggle = (index: number, menuType: "main") => { setOpenSubmenu((prevOpenSubmenu) => { if ( prevOpenSubmenu && prevOpenSubmenu.type === menuType && prevOpenSubmenu.index === index ) { return null; } return { type: menuType, index }; }); }; return ( ); }; export default AppSidebar;