Files
wireguard-dashboard-admin/src/router/utils.ts

382 lines
12 KiB
TypeScript
Raw Normal View History

2021-12-14 10:51:07 +08:00
import {
RouterHistory,
RouteRecordRaw,
RouteComponent,
createWebHistory,
createWebHashHistory,
RouteRecordNormalized
} from "vue-router";
import { router } from "./index";
2022-08-22 21:34:55 +08:00
import { isProxy, toRaw } from "vue";
2021-12-14 10:51:07 +08:00
import { useTimeoutFn } from "@vueuse/core";
import { RouteConfigs } from "@/layout/types";
2022-10-25 17:51:21 +08:00
import {
isString,
2022-12-13 14:37:56 +08:00
cloneDeep,
isAllEmpty,
2022-12-13 14:37:56 +08:00
intersection,
2022-10-25 17:51:21 +08:00
storageSession,
isIncludeAllChildren
} from "@pureadmin/utils";
import { getConfig } from "@/config";
2022-11-26 19:14:08 +08:00
import { buildHierarchyTree } from "@/utils/tree";
import { sessionKey, type DataInfo } from "@/utils/auth";
import { usePermissionStoreHook } from "@/store/modules/permission";
const IFrame = () => import("@/layout/frameView.vue");
2021-12-14 10:51:07 +08:00
// https://cn.vitejs.dev/guide/features.html#glob-import
2022-01-05 14:17:06 +08:00
const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
2021-12-14 10:51:07 +08:00
// 动态路由
import { getAsyncRoutes } from "@/api/routes";
2021-12-14 10:51:07 +08:00
2022-12-07 17:22:07 +08:00
function handRank(routeInfo: any) {
const { name, path, parentId, meta } = routeInfo;
return isAllEmpty(parentId)
? isAllEmpty(meta?.rank) ||
(meta?.rank === 0 && name !== "Home" && path !== "/")
? true
: false
: false;
}
/** 按照路由中meta下的rank等级升序来排序路由 */
2022-01-21 14:03:00 +08:00
function ascending(arr: any[]) {
arr.forEach((v, index) => {
// 当rank不存在时根据顺序自动创建首页路由永远在第一位
2022-12-07 17:22:07 +08:00
if (handRank(v)) v.meta.rank = index + 2;
2022-03-17 19:00:01 +08:00
});
2021-12-14 10:51:07 +08:00
return arr.sort(
(a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
return a?.meta.rank - b?.meta.rank;
2021-12-14 10:51:07 +08:00
}
);
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
2022-10-25 17:51:21 +08:00
/** 过滤meta中showLink为false的菜单 */
2022-01-21 14:03:00 +08:00
function filterTree(data: RouteComponent[]) {
2022-08-22 21:34:55 +08:00
const newTree = cloneDeep(data).filter(
2022-02-05 14:45:20 +08:00
(v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
2021-12-14 10:51:07 +08:00
);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
2022-10-25 17:51:21 +08:00
/** 过滤children长度为0的的目录当目录下没有菜单时会过滤此目录目录没有赋予roles权限当目录下只要有一个菜单有显示权限那么此目录就会显示 */
function filterChildrenTree(data: RouteComponent[]) {
const newTree = cloneDeep(data).filter((v: any) => v?.children?.length !== 0);
newTree.forEach(
(v: { children }) => v.children && (v.children = filterTree(v.children))
);
return newTree;
}
/** 判断两个数组彼此是否存在相同值 */
function isOneOfArray(a: Array<string>, b: Array<string>) {
return Array.isArray(a) && Array.isArray(b)
? intersection(a, b).length > 0
? true
: false
: true;
}
/** 从sessionStorage里取出当前登陆用户的角色roles过滤无权限的菜单 */
function filterNoPermissionTree(data: RouteComponent[]) {
const currentRoles =
2022-12-09 12:45:47 +08:00
storageSession().getItem<DataInfo<number>>(sessionKey)?.roles ?? [];
2022-10-25 17:51:21 +08:00
const newTree = cloneDeep(data).filter((v: any) =>
isOneOfArray(v.meta?.roles, currentRoles)
);
newTree.forEach(
(v: any) => v.children && (v.children = filterNoPermissionTree(v.children))
);
return filterChildrenTree(newTree);
}
/** 批量删除缓存路由(keepalive) */
2022-01-21 14:03:00 +08:00
function delAliveRoutes(delAliveRouteList: Array<RouteConfigs>) {
2021-12-14 10:51:07 +08:00
delAliveRouteList.forEach(route => {
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: route?.name
});
});
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 通过path获取父级路径 */
2022-01-21 14:03:00 +08:00
function getParentPaths(path: string, routes: RouteRecordRaw[]) {
2021-12-14 10:51:07 +08:00
// 深度遍历查找
function dfs(routes: RouteRecordRaw[], path: string, parents: string[]) {
for (let i = 0; i < routes.length; i++) {
const item = routes[i];
// 找到path则返回父级path
if (item.path === path) return parents;
// children不存在或为空则不递归
if (!item.children || !item.children.length) continue;
// 往下查找时将当前path入栈
parents.push(item.path);
if (dfs(item.children, path, parents).length) return parents;
// 深度遍历查找未找到时当前path 出栈
parents.pop();
}
// 未找到时返回空数组
return [];
}
return dfs(routes, path, []);
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 查找对应path的路由信息 */
2022-01-21 14:03:00 +08:00
function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
2021-12-14 10:51:07 +08:00
let res = routes.find((item: { path: string }) => item.path == path);
if (res) {
2022-08-22 21:34:55 +08:00
return isProxy(res) ? toRaw(res) : res;
2021-12-14 10:51:07 +08:00
} else {
for (let i = 0; i < routes.length; i++) {
if (
routes[i].children instanceof Array &&
routes[i].children.length > 0
) {
res = findRouteByPath(path, routes[i].children);
if (res) {
2022-08-22 21:34:55 +08:00
return isProxy(res) ? toRaw(res) : res;
2021-12-14 10:51:07 +08:00
}
}
}
return null;
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
2022-08-22 21:34:55 +08:00
function addPathMatch() {
if (!router.hasRoute("pathMatch")) {
router.addRoute({
path: "/:pathMatch(.*)",
name: "pathMatch",
redirect: "/error/404"
});
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 处理动态路由(后端返回的路由) */
function handleAsyncRoutes(routeList) {
if (routeList.length === 0) {
usePermissionStoreHook().handleWholeMenus(routeList);
} else {
formatFlatteningRoutes(addAsyncRoutes(routeList)).map(
(v: RouteRecordRaw) => {
// 防止重复添加路由
if (
router.options.routes[0].children.findIndex(
value => value.path === v.path
) !== -1
) {
return;
} else {
// 切记将路由push到routes后还需要使用addRoute这样路由才能正常跳转
router.options.routes[0].children.push(v);
// 最终路由进行升序
ascending(router.options.routes[0].children);
if (!router.hasRoute(v?.name)) router.addRoute(v);
const flattenRouters: any = router
.getRoutes()
.find(n => n.path === "/");
router.addRoute(flattenRouters);
}
}
);
usePermissionStoreHook().handleWholeMenus(routeList);
}
addPathMatch();
}
/** 初始化路由(`new Promise` 写法防止在异步请求中造成无限循环)*/
2022-10-25 17:51:21 +08:00
function initRouter() {
if (getConfig()?.CachingAsyncRoutes) {
// 开启动态路由缓存本地sessionStorage
const key = "async-routes";
2022-12-09 12:45:47 +08:00
const asyncRouteList = storageSession().getItem(key) as any;
if (asyncRouteList && asyncRouteList?.length > 0) {
return new Promise(resolve => {
handleAsyncRoutes(asyncRouteList);
resolve(router);
});
} else {
return new Promise(resolve => {
getAsyncRoutes().then(({ data }) => {
2022-12-04 18:00:16 +08:00
handleAsyncRoutes(cloneDeep(data));
2022-12-09 12:45:47 +08:00
storageSession().setItem(key, data);
resolve(router);
});
});
}
} else {
return new Promise(resolve => {
getAsyncRoutes().then(({ data }) => {
2022-12-04 18:00:16 +08:00
handleAsyncRoutes(cloneDeep(data));
resolve(router);
});
});
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/**
*
* @param routesList
* @returns
*/
2022-01-21 14:03:00 +08:00
function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
2022-02-27 13:31:19 +08:00
let hierarchyList = buildHierarchyTree(routesList);
for (let i = 0; i < hierarchyList.length; i++) {
if (hierarchyList[i].children) {
hierarchyList = hierarchyList
2021-12-14 10:51:07 +08:00
.slice(0, i + 1)
2022-02-27 13:31:19 +08:00
.concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
2021-12-14 10:51:07 +08:00
}
}
2022-02-27 13:31:19 +08:00
return hierarchyList;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/**
* keep-alive
2023-02-08 20:10:08 +08:00
* https://github.com/pure-admin/vue-pure-admin/issues/67
2021-12-14 10:51:07 +08:00
* @param routesList
* @returns
*/
2022-01-21 14:03:00 +08:00
function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
if (routesList.length === 0) return routesList;
2021-12-14 10:51:07 +08:00
const newRoutesList: RouteRecordRaw[] = [];
routesList.forEach((v: RouteRecordRaw) => {
if (v.path === "/") {
newRoutesList.push({
component: v.component,
name: v.name,
path: v.path,
redirect: v.redirect,
meta: v.meta,
children: []
});
} else {
newRoutesList[0]?.children.push({ ...v });
2021-12-14 10:51:07 +08:00
}
});
return newRoutesList;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 处理缓存路由(添加、删除、刷新) */
2022-01-21 14:03:00 +08:00
function handleAliveRoute(matched: RouteRecordNormalized[], mode?: string) {
2021-12-14 10:51:07 +08:00
switch (mode) {
case "add":
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
break;
case "delete":
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
break;
default:
usePermissionStoreHook().cacheOperate({
mode: "delete",
name: matched[matched.length - 1].name
});
useTimeoutFn(() => {
matched.forEach(v => {
usePermissionStoreHook().cacheOperate({ mode: "add", name: v.name });
});
}, 100);
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 过滤后端传来的动态路由 重新生成规范路由 */
2022-01-21 14:03:00 +08:00
function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
2021-12-14 10:51:07 +08:00
if (!arrRoutes || !arrRoutes.length) return;
2022-01-05 14:17:06 +08:00
const modulesRoutesKeys = Object.keys(modulesRoutes);
2021-12-14 10:51:07 +08:00
arrRoutes.forEach((v: RouteRecordRaw) => {
2022-08-22 21:34:55 +08:00
// 将backstage属性加入meta标识此路由为后端返回路由
v.meta.backstage = true;
// 父级的redirect属性取值如果子级存在且父级的redirect属性不存在默认取第一个子级的path如果子级存在且父级的redirect属性存在取存在的redirect属性会覆盖默认值
2022-08-23 10:43:33 +08:00
if (v?.children && v.children.length && !v.redirect)
v.redirect = v.children[0].path;
2022-10-26 11:25:45 +08:00
// 父级的name属性取值如果子级存在且父级的name属性不存在默认取第一个子级的name如果子级存在且父级的name属性存在取存在的name属性会覆盖默认值注意测试中发现父级的name不能和子级name重复如果重复会造成重定向无效跳转404所以这里给父级的name起名的时候后面会自动加上`Parent`,避免重复)
2022-08-23 10:43:33 +08:00
if (v?.children && v.children.length && !v.name)
2022-10-26 11:25:45 +08:00
v.name = (v.children[0].name as string) + "Parent";
2022-08-23 10:43:33 +08:00
if (v.meta?.frameSrc) {
v.component = IFrame;
} else {
// 对后端传component组件路径和不传做兼容如果后端传component组件路径那么path可以随便写如果不传component组件路径会跟path保持一致
const index = v?.component
? modulesRoutesKeys.findIndex(ev => ev.includes(v.component as any))
: modulesRoutesKeys.findIndex(ev => ev.includes(v.path));
v.component = modulesRoutes[modulesRoutesKeys[index]];
}
if (v?.children && v.children.length) {
2021-12-14 10:51:07 +08:00
addAsyncRoutes(v.children);
}
});
return arrRoutes;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
/** 获取路由历史模式 https://next.router.vuejs.org/zh/guide/essentials/history-mode.html */
2022-01-21 14:03:00 +08:00
function getHistoryMode(): RouterHistory {
2022-12-19 13:45:28 +08:00
const routerHistory = import.meta.env.VITE_ROUTER_HISTORY;
2021-12-14 10:51:07 +08:00
// len为1 代表只有历史模式 为2 代表历史模式中存在base参数 https://next.router.vuejs.org/zh/api/#%E5%8F%82%E6%95%B0-1
const historyMode = routerHistory.split(",");
const leftMode = historyMode[0];
const rightMode = historyMode[1];
// no param
if (historyMode.length === 1) {
if (leftMode === "hash") {
return createWebHashHistory("");
} else if (leftMode === "h5") {
return createWebHistory("");
}
} //has param
else if (historyMode.length === 2) {
if (leftMode === "hash") {
return createWebHashHistory(rightMode);
} else if (leftMode === "h5") {
return createWebHistory(rightMode);
}
}
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
2022-10-25 17:51:21 +08:00
/** 获取当前页面按钮级别的权限 */
function getAuths(): Array<string> {
return router.currentRoute.value.meta.auths as Array<string>;
}
2021-12-14 10:51:07 +08:00
2022-10-25 17:51:21 +08:00
/** 是否有按钮级别的权限 */
function hasAuth(value: string | Array<string>): boolean {
if (!value) return false;
/** 从当前路由的`meta`字段里获取按钮级别的所有自定义`code`值 */
const metaAuths = getAuths();
2022-12-07 17:22:07 +08:00
if (!metaAuths) return false;
2022-10-25 17:51:21 +08:00
const isAuths = isString(value)
? metaAuths.includes(value)
: isIncludeAllChildren(value, metaAuths);
return isAuths ? true : false;
2022-01-21 14:03:00 +08:00
}
2021-12-14 10:51:07 +08:00
export {
2022-10-25 17:51:21 +08:00
hasAuth,
getAuths,
2021-12-14 10:51:07 +08:00
ascending,
filterTree,
initRouter,
2022-10-25 17:51:21 +08:00
isOneOfArray,
2021-12-14 10:51:07 +08:00
getHistoryMode,
addAsyncRoutes,
delAliveRoutes,
getParentPaths,
findRouteByPath,
handleAliveRoute,
formatTwoStageRoutes,
2022-10-25 17:51:21 +08:00
formatFlatteningRoutes,
filterNoPermissionTree
2021-12-14 10:51:07 +08:00
};