import React from "react"; import * as AntIcons from "@ant-design/icons"; import { ColorIcon } from "@/components/Layout/ColorIcon"; import { allRoutes } from "@/routes/routes"; const getAntIcon = (iconName) => { const iconKey = `${iconName.charAt(0).toUpperCase()}${iconName.slice( 1 )}Outlined`; return AntIcons[iconKey] ? React.createElement(AntIcons[iconKey]) : null; }; const generateMenuItems = (routes, menuKeys = [], parentPath = "") => { return routes .filter((route) => { if (route.hidden) return false; if (!menuKeys.length) return true; const isRouteAllowed = menuKeys.includes(route.key); // 如果有子路由,只要子路由中有被授权的,父路由就应该显示 if (route.children) { const hasAllowedChildren = route.children.some(child => !child.hidden && ( menuKeys.includes(child.key) || (child.children && child.children.some(grandChild => !grandChild.hidden && menuKeys.includes(grandChild.key) )) ) ); return hasAllowedChildren || isRouteAllowed; } return isRouteAllowed; }) .map((route) => { const fullPath = `${parentPath}/${route.path}`.replace(/\/+/g, "/"); const icon = route.icon && ; const menuItem = { key: fullPath, icon, label: route.name, }; if (route.children) { const filteredChildren = generateMenuItems(route.children, menuKeys, fullPath); if (filteredChildren.length > 0) { menuItem.children = filteredChildren; } } return menuItem; }); }; export const getMenuItems = (menuKeys = []) => generateMenuItems(allRoutes, menuKeys); export const filterRoutesByMenuKeys = (routes, menuKeys) => { if (!Array.isArray(routes) || !Array.isArray(menuKeys)) { return []; } return routes.reduce((acc, route) => { const isRouteAllowed = menuKeys.includes(route.key); let filteredChildren = []; if (route.children) { filteredChildren = filterRoutesByMenuKeys(route.children, menuKeys); } if (isRouteAllowed || filteredChildren.length > 0) { acc.push({ ...route, children: filteredChildren.length > 0 ? filteredChildren : undefined }); } return acc; }, []); }; export { generateMenuItems, getAntIcon };