123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478 |
- import {
- type RouterHistory,
- type RouteRecordRaw,
- type RouteComponent,
- createWebHistory,
- createWebHashHistory
- } from "vue-router";
- import { router } from "./index";
- import { isProxy, toRaw, ref } from "vue";
- import { useTimeoutFn } from "@vueuse/core";
- import {
- isString,
- cloneDeep,
- isAllEmpty,
- intersection,
- storageLocal,
- isIncludeAllChildren
- } from "@pureadmin/utils";
- import { getConfig } from "@/config";
- import type { menuType } from "@/layout/types";
- import { buildHierarchyTree } from "@/utils/tree";
- import { userKey, type DataInfo } from "@/utils/auth";
- import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
- import { usePermissionStoreHook } from "@/store/modules/permission";
- import { getMenuListForUser } from "@/api/menu";
- import background from "@/routerList/background";
- import draw from "@/routerList/draw";
- import evaluate from "@/routerList/evaluate";
- import home from "@/routerList/home";
- import _import from "@/routerList/import";
- import indexDefine from "@/routerList/index";
- import other from "@/routerList/other";
- import password from "@/routerList/password";
- const muenList = [
- background,
- draw,
- evaluate,
- home,
- _import,
- indexDefine,
- other,
- password
- ];
- const btnList = ref([]);
- const IFrame = () => import("@/layout/frameView.vue");
- const modulesRoutes = import.meta.glob("/src/views/**/*.{vue,tsx}");
- 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;
- }
- function ascending(arr: any[]) {
- arr.forEach((v, index) => {
-
- if (handRank(v)) v.meta.rank = index + 2;
- });
- return arr.sort(
- (a: { meta: { rank: number } }, b: { meta: { rank: number } }) => {
- return a?.meta.rank - b?.meta.rank;
- }
- );
- }
- function filterTree(data: RouteComponent[]) {
- const newTree = cloneDeep(data).filter(
- (v: { meta: { showLink: boolean } }) => v.meta?.showLink !== false
- );
- newTree.forEach(
- (v: { children }) => v.children && (v.children = filterTree(v.children))
- );
- return newTree;
- }
- 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;
- }
- function filterNoPermissionTree(data: RouteComponent[]) {
- const currentRoles =
- storageLocal().getItem<DataInfo<number>>(userKey)?.roles ?? [];
- 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);
- }
- function getParentPaths(value: string, routes: RouteRecordRaw[], key = "path") {
-
- function dfs(routes: RouteRecordRaw[], value: string, parents: string[]) {
- for (let i = 0; i < routes.length; i++) {
- const item = routes[i];
-
- if (item[key] === value) return parents;
-
- if (!item.children || !item.children.length) continue;
-
- parents.push(item.path);
- if (dfs(item.children, value, parents).length) return parents;
-
- parents.pop();
- }
-
- return [];
- }
- return dfs(routes, value, []);
- }
- function findRouteByPath(path: string, routes: RouteRecordRaw[]) {
- let res = routes.find((item: { path: string }) => item.path == path);
- if (res) {
- return isProxy(res) ? toRaw(res) : res;
- } 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) {
- return isProxy(res) ? toRaw(res) : res;
- }
- }
- }
- return null;
- }
- }
- function addPathMatch() {
- if (!router.hasRoute("pathMatch")) {
- router.addRoute({
- path: "/:pathMatch(.*)",
- name: "pathMatch",
- redirect: "/error/404"
- });
- }
- }
- 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 {
-
- 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();
- }
- let matchAndMerge = (data, menuList) => {
- return data
- .map(item => {
- if (item.menuType == "button") {
- let btn = {
- path: item.moduleUrl,
- name: item.menuName
- };
- btnList.value.push(btn);
- }
- const matchedMenu = menuList.find(menu => {
- return menu.path === item.moduleUrl;
- });
- if (matchedMenu) {
-
- delete matchedMenu.component;
-
- const newItem = {
- ...matchedMenu,
- children: matchAndMerge(
- item.childrenRes || [],
- matchedMenu.children || []
- )
- };
- return newItem;
- }
- return null;
- })
- .filter(Boolean);
- };
- let cleanEmptyChildren = routes => {
- return routes.map(route => {
-
- if (route.children && route.children.length > 0) {
- route.children = cleanEmptyChildren(route.children);
- } else {
- delete route.children;
- }
- return route;
- });
- };
- function addAuths(menu, data) {
- for (const item of menu) {
-
- data.forEach(d => {
- if (d.path === item.path) {
- item.meta.auths.push(d.name);
- }
- });
- if (item.children) {
- addAuths(item.children, data);
- }
- }
- }
- function initRouter() {
- if (getConfig()?.CachingAsyncRoutes) {
-
- const key = "async-routes";
- const asyncRouteList = storageLocal().getItem(key) as any;
- if (asyncRouteList && asyncRouteList?.length > 0) {
- return new Promise(resolve => {
- handleAsyncRoutes(asyncRouteList);
- resolve(router);
- });
- } else {
- return new Promise(resolve => {
- getMenuListForUser().then(({ data }) => {
- let menuDataList = matchAndMerge(data, muenList);
- addAuths(cleanEmptyChildren(menuDataList), btnList.value);
- handleAsyncRoutes(cloneDeep(cleanEmptyChildren(menuDataList)));
- storageLocal().setItem(key, cleanEmptyChildren(menuDataList));
- resolve(router);
- });
- });
- }
- } else {
- return new Promise(resolve => {
- getMenuListForUser().then(({ data }) => {
- let menuDataList = matchAndMerge(data, muenList);
- addAuths(cleanEmptyChildren(menuDataList), btnList.value);
- handleAsyncRoutes(cloneDeep(cleanEmptyChildren(menuDataList)));
- console.log(
- "路由打印router/utils-296",
- cleanEmptyChildren(menuDataList)
- );
- resolve(router);
- });
- });
- }
- }
- function formatFlatteningRoutes(routesList: RouteRecordRaw[]) {
- if (routesList.length === 0) return routesList;
- let hierarchyList = buildHierarchyTree(routesList);
- for (let i = 0; i < hierarchyList.length; i++) {
- if (hierarchyList[i].children) {
- hierarchyList = hierarchyList
- .slice(0, i + 1)
- .concat(hierarchyList[i].children, hierarchyList.slice(i + 1));
- }
- }
- return hierarchyList;
- }
- function formatTwoStageRoutes(routesList: RouteRecordRaw[]) {
- if (routesList.length === 0) return routesList;
- 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 });
- }
- });
- return newRoutesList;
- }
- function handleAliveRoute({ name }: ToRouteType, mode?: string) {
- switch (mode) {
- case "add":
- usePermissionStoreHook().cacheOperate({
- mode: "add",
- name
- });
- break;
- case "delete":
- usePermissionStoreHook().cacheOperate({
- mode: "delete",
- name
- });
- break;
- case "refresh":
- usePermissionStoreHook().cacheOperate({
- mode: "refresh",
- name
- });
- break;
- default:
- usePermissionStoreHook().cacheOperate({
- mode: "delete",
- name
- });
- useTimeoutFn(() => {
- usePermissionStoreHook().cacheOperate({
- mode: "add",
- name
- });
- }, 100);
- }
- }
- function addAsyncRoutes(arrRoutes: Array<RouteRecordRaw>) {
- if (!arrRoutes || !arrRoutes.length) return;
- const modulesRoutesKeys = Object.keys(modulesRoutes);
- arrRoutes.forEach((v: RouteRecordRaw) => {
-
- v.meta.backstage = true;
-
- if (v?.children && v.children.length && !v.redirect)
- v.redirect = v.children[0].path;
-
- if (v?.children && v.children.length && !v.name)
- v.name = (v.children[0].name as string) + "Parent";
- if (v.meta?.frameSrc) {
- v.component = IFrame;
- } else {
-
- 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) {
- addAsyncRoutes(v.children);
- }
- });
- return arrRoutes;
- }
- function getHistoryMode(routerHistory): RouterHistory {
-
- const historyMode = routerHistory.split(",");
- const leftMode = historyMode[0];
- const rightMode = historyMode[1];
-
- if (historyMode.length === 1) {
- if (leftMode === "hash") {
- return createWebHashHistory("");
- } else if (leftMode === "h5") {
- return createWebHistory("");
- }
- }
- else if (historyMode.length === 2) {
- if (leftMode === "hash") {
- return createWebHashHistory(rightMode);
- } else if (leftMode === "h5") {
- return createWebHistory(rightMode);
- }
- }
- }
- function getAuths(): Array<string> {
- return router.currentRoute.value.meta.auths as Array<string>;
- }
- function hasAuth(value: string | Array<string>): boolean {
- if (!value) return false;
-
- const metaAuths = getAuths();
- if (!metaAuths) return false;
- const isAuths = isString(value)
- ? metaAuths.includes(value)
- : isIncludeAllChildren(value, metaAuths);
- return isAuths ? true : false;
- }
- function getTopMenu(tag = false): menuType {
- const topMenu = usePermissionStoreHook().wholeMenus[0]?.children[0];
- tag && useMultiTagsStoreHook().handleTags("push", topMenu);
- return topMenu;
- }
- export {
- hasAuth,
- getAuths,
- ascending,
- filterTree,
- initRouter,
- getTopMenu,
- addPathMatch,
- isOneOfArray,
- getHistoryMode,
- addAsyncRoutes,
- getParentPaths,
- findRouteByPath,
- handleAliveRoute,
- formatTwoStageRoutes,
- formatFlatteningRoutes,
- filterNoPermissionTree
- };
|