菜单权限

This commit is contained in:
liamzi
2025-01-14 18:52:03 +08:00
parent 2edb91cbea
commit 34550d0517
10 changed files with 790 additions and 409 deletions

View File

@@ -1,7 +1,7 @@
import React from "react";
import { generateRoutes } from "@/routes/routes";
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(
@@ -10,25 +10,69 @@ const getAntIcon = (iconName) => {
return AntIcons[iconKey] ? React.createElement(AntIcons[iconKey]) : null;
};
const generateMenuItems = (routes, parentPath = "") => {
const generateMenuItems = (routes, menuKeys = [], parentPath = "") => {
return routes
.filter((route) => !route.hidden)
.filter((route) => {
if (!menuKeys.length) return !route.hidden;
const isRouteAllowed = menuKeys.includes(route.key);
// 如果有子路由,只要子路由中有被授权的,父路由就应该显示
if (route.children) {
const hasAllowedChildren = route.children.some(child =>
menuKeys.includes(child.key) ||
(child.children && child.children.some(grandChild => menuKeys.includes(grandChild.key)))
);
return hasAllowedChildren || isRouteAllowed;
}
return isRouteAllowed;
})
.map((route) => {
const fullPath = `${parentPath}/${route.path}`.replace(/\/+/g, "/");
const icon = route.icon && <ColorIcon icon={getAntIcon(route.icon)} />;
const menuItem = {
key: fullPath,
key: route.key, // 使用 key 而不是 fullPath
icon,
label: route.name,
};
if (route.children) {
menuItem.children = generateMenuItems(route.children, fullPath);
const filteredChildren = generateMenuItems(route.children, menuKeys, fullPath);
if (filteredChildren.length > 0) {
menuItem.children = filteredChildren;
}
}
return menuItem;
});
};
export const getMenuItems = (role) => generateMenuItems(generateRoutes(role));
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) => {
// 检查当前路由的 key 是否在 menuKeys 中
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 };