新增前端vue

This commit is contained in:
2025-11-26 13:55:01 +08:00
parent ae391f1b94
commit ffd5a6ad66
781 changed files with 83348 additions and 0 deletions

View File

@@ -0,0 +1,23 @@
export const REDIRECT_NAME = 'Redirect';
export const PARENT_LAYOUT_NAME = 'ParentLayout';
export const PAGE_NOT_FOUND_NAME = 'PageNotFound';
/**
* @description: default layout
*/
export const LAYOUT = () => import('@jeesite/core/layouts/default/index.vue');
export const IFRAME_BLANK = () => import('@jeesite/core/layouts/iframe/FrameBlank.vue');
export const IFRAME_SIMPLE = () => import('@jeesite/core/layouts/iframe/FrameSimple.vue');
export const EXCEPTION_COMPONENT = () => import('@jeesite/core/layouts/views/exception/Exception.vue');
/**
* @description: parent-layout
*/
export const getParentLayout = (_name?: string) => {
return () =>
new Promise((resolve) => {
resolve({
name: PARENT_LAYOUT_NAME,
});
});
};

View File

@@ -0,0 +1,148 @@
import type { Router, RouteLocationNormalized } from 'vue-router';
import { useAppStoreWithOut } from '@jeesite/core/store/modules/app';
import { useUserStoreWithOut } from '@jeesite/core/store/modules/user';
import { useTransitionSetting } from '@jeesite/core/hooks/setting/useTransitionSetting';
import { AxiosCanceler } from '@jeesite/core/utils/http/axios/axiosCancel';
import { Modal, notification } from 'ant-design-vue';
import { warn } from '@jeesite/core/utils/log';
import { unref } from 'vue';
import { setRouteChange } from '@jeesite/core/logics/mitt/routeChange';
import { createPermissionGuard } from './permissionGuard';
import { createStateGuard } from './stateGuard';
// import nProgress from 'nprogress';
import projectSetting from '@jeesite/core/settings/projectSetting';
// import { createParamMenuGuard } from './paramMenuGuard';
// Don't change the order of creation
export function setupRouterGuard(router: Router) {
createPageGuard(router);
createPageLoadingGuard(router);
createHttpGuard(router);
createScrollGuard(router);
createMessageGuard(router);
// createProgressGuard(router);
createPermissionGuard(router);
// createParamMenuGuard(router); // must after createPermissionGuard (menu has been built.) 用不到,暂时去掉
createStateGuard(router);
}
/**
* Hooks for handling page state
*/
function createPageGuard(router: Router) {
const loadedPageMap = new Map<string, boolean>();
router.beforeEach(async (to) => {
// The page has already been loaded, it will be faster to open it again, you dont need to do loading and other processing
to.meta.loaded = !!loadedPageMap.get(to.path);
// Notify routing changes
setRouteChange(to);
return true;
});
router.afterEach((to) => {
loadedPageMap.set(to.path, true);
});
}
// Used to handle page loading status
function createPageLoadingGuard(router: Router) {
const userStore = useUserStoreWithOut();
const appStore = useAppStoreWithOut();
const { getOpenPageLoading } = useTransitionSetting();
router.beforeEach(async (to) => {
// if (!userStore.getToken) {
if (userStore.getSessionTimeout) {
return true;
}
if (to.meta.loaded) {
return true;
}
if (unref(getOpenPageLoading)) {
appStore.setPageLoadingAction(true);
return true;
}
return true;
});
router.afterEach(async () => {
if (unref(getOpenPageLoading)) {
// TODO Looking for a better way
// The timer simulates the loading time to prevent flashing too fast,
setTimeout(() => {
appStore.setPageLoading(false);
}, 220);
}
return true;
});
}
/**
* The interface used to close the current page to complete the request when the route is switched
* @param router
*/
function createHttpGuard(router: Router) {
const { removeAllHttpPending } = projectSetting;
let axiosCanceler: Nullable<AxiosCanceler>;
if (removeAllHttpPending) {
axiosCanceler = new AxiosCanceler();
}
router.beforeEach(async () => {
// Switching the route will delete the previous request
axiosCanceler?.removeAllPending();
return true;
});
}
// Routing switch back to the top
function createScrollGuard(router: Router) {
const isHash = (href: string) => {
return /^#/.test(href);
};
const body = document.body;
router.afterEach(async (to) => {
// scroll top
isHash((to as RouteLocationNormalized & { href: string })?.href) && body.scrollTo(0, 0);
return true;
});
}
/**
* Used to close the message instance when the route is switched
* @param router
*/
export function createMessageGuard(router: Router) {
const { closeMessageOnSwitch } = projectSetting;
router.beforeEach(async () => {
try {
if (closeMessageOnSwitch) {
Modal.destroyAll();
notification.destroy();
}
} catch (error) {
warn('message guard error:' + error);
}
return true;
});
}
// export function createProgressGuard(router: Router) {
// const { getOpenNProgress } = useTransitionSetting();
// router.beforeEach(async (to) => {
// if (to.meta.loaded) {
// return true;
// }
// unref(getOpenNProgress) && nProgress.start();
// return true;
// });
//
// router.afterEach(async () => {
// unref(getOpenNProgress) && nProgress.done();
// return true;
// });
// }

View File

@@ -0,0 +1,47 @@
import type { Router } from 'vue-router';
import { configureDynamicParamsMenu } from '../helper/menuHelper';
import { Menu } from '../types';
import { PermissionModeEnum } from '@jeesite/core/enums/appEnum';
import { useAppStoreWithOut } from '@jeesite/core/store/modules/app';
import { usePermissionStoreWithOut } from '@jeesite/core/store/modules/permission';
export function createParamMenuGuard(router: Router) {
const permissionStore = usePermissionStoreWithOut();
router.beforeEach(async (to, _, next) => {
// filter no name route
if (!to.name) {
next();
return;
}
// menu has been built.
if (!permissionStore.getIsDynamicAddedRoute) {
next();
return;
}
let menus: Menu[] = [];
if (isBackMode()) {
menus = permissionStore.getBackMenuList;
} else if (isRouteMappingMode()) {
menus = permissionStore.getFrontMenuList;
}
menus.forEach((item) => configureDynamicParamsMenu(item, to.params));
next();
});
}
const getPermissionMode = () => {
const appStore = useAppStoreWithOut();
return appStore.getProjectConfig.permissionMode;
};
const isBackMode = () => {
return getPermissionMode() === PermissionModeEnum.BACK;
};
const isRouteMappingMode = () => {
return getPermissionMode() === PermissionModeEnum.ROUTE_MAPPING;
};

View File

@@ -0,0 +1,147 @@
import type { Router, RouteRecordRaw } from 'vue-router';
import { usePermissionStoreWithOut } from '@jeesite/core/store/modules/permission';
import { RootRoute } from '@jeesite/core/router/routes';
import { PageEnum } from '@jeesite/core/enums/pageEnum';
import { useUserStoreWithOut } from '@jeesite/core/store/modules/user';
import { PAGE_NOT_FOUND_ROUTE } from '@jeesite/core/router/routes/basic';
const ROOT_PATH = RootRoute.path;
const HOME_PATH = PageEnum.BASE_HOME;
const LOGIN_PATH = PageEnum.BASE_LOGIN;
const MOD_PWD_PAGE = PageEnum.MOD_PWD_PAGE;
// 白名单路由列表,无需权限即可访问的页面
const whitePathList: PageEnum[] = [LOGIN_PATH, MOD_PWD_PAGE];
export function createPermissionGuard(router: Router) {
const userStore = useUserStoreWithOut();
const permissionStore = usePermissionStoreWithOut();
router.beforeEach(async (to, from, next) => {
if (
from.path === ROOT_PATH &&
to.path === HOME_PATH &&
userStore.getUserInfo.homePath &&
userStore.getUserInfo.homePath !== HOME_PATH
) {
next(userStore.getUserInfo.homePath);
return;
}
// const token = userStore.getToken;
const token = !userStore.getSessionTimeout;
// Whitelist can be directly entered
if (whitePathList.includes(to.path as PageEnum)) {
// if (to.path === LOGIN_PATH && token) {
// const isSessionTimeout = userStore.getSessionTimeout;
// try {
// await userStore.afterLoginAction();
// if (!isSessionTimeout) {
// next((to.query?.redirect as string) || '/');
// return;
// }
// } catch {}
// }
if (to.path === MOD_PWD_PAGE) {
try {
await userStore.getUserInfoAction();
} catch (error: any) {
console.error(error);
}
}
next();
return;
}
// force modify password
if (userStore.getPageCacheByKey('modifyPasswordMsg')) {
next({
path: MOD_PWD_PAGE,
replace: true,
});
return;
}
// token does not exist
if (!token) {
// You can access without permission. You need to set the routing meta.ignoreAuth to true
if (to.meta.ignoreAuth) {
next();
return;
}
// redirect login page
const redirectData: { path: string; replace: boolean; query?: Recordable<string> } = {
path: LOGIN_PATH,
replace: true,
};
if (to.path) {
redirectData.query = {
...redirectData.query,
redirect: to.path,
};
}
next(redirectData);
return;
}
// Jump to the 404 page after processing the login
if (
from.path === LOGIN_PATH &&
to.name === PAGE_NOT_FOUND_ROUTE.name &&
to.fullPath !== (userStore.getUserInfo.homePath || HOME_PATH)
) {
// 如果用户定义的 desktopUrl 是非法路径,就跳转到 404防止无法进入系统
next('/404/' + (userStore.getUserInfo.homePath || HOME_PATH));
return;
}
// get userinfo while last fetch time is empty
if (userStore.getLastUpdateTime === 0) {
try {
await userStore.getUserInfoAction();
} catch (error: any) {
// const err: string = error?.toString?.() ?? '';
// if (
// from.fullPath === '/' &&
// ((error?.code === 'ECONNABORTED' && err.indexOf('timeout of') !== -1) ||
// err.indexOf('Network Error') !== -1)
// ) {
// next(LOGIN_PATH);
// return;
// }
let path = LOGIN_PATH as string;
if (to.path !== '/' && to.path !== LOGIN_PATH) {
path = path + '?redirect=' + to.fullPath;
}
next(path);
return;
}
}
if (permissionStore.getIsDynamicAddedRoute) {
next();
return;
}
const routes = await permissionStore.buildRoutesAction();
routes.forEach((route) => {
router.addRoute(route as unknown as RouteRecordRaw);
});
router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
permissionStore.setDynamicAddedRoute(true);
if (to.name === PAGE_NOT_FOUND_ROUTE.name) {
// 动态添加路由后此处应当重定向到fullPath否则会加载404页面内容
next({ path: to.fullPath, replace: true, query: to.query });
} else {
const redirectPath = (from.query.redirect || to.path) as string;
const redirect = decodeURIComponent(redirectPath);
const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect };
next(nextData);
}
});
}

View File

@@ -0,0 +1,24 @@
import type { Router } from 'vue-router';
import { useAppStore } from '@jeesite/core/store/modules/app';
import { useMultipleTabStore } from '@jeesite/core/store/modules/multipleTab';
import { useUserStore } from '@jeesite/core/store/modules/user';
import { usePermissionStore } from '@jeesite/core/store/modules/permission';
import { PageEnum } from '@jeesite/core/enums/pageEnum';
import { removeTabChangeListener } from '@jeesite/core/logics/mitt/routeChange';
export function createStateGuard(router: Router) {
router.afterEach((to) => {
const tabStore = useMultipleTabStore();
const userStore = useUserStore();
const appStore = useAppStore();
const permissionStore = usePermissionStore();
// Just enter the login page and clear the authentication information
if (to.path === PageEnum.BASE_LOGIN) {
appStore.resetAllState();
permissionStore.resetState();
tabStore.resetState();
userStore.resetState();
removeTabChangeListener();
}
});
}

View File

@@ -0,0 +1,108 @@
import { AppRouteModule } from '@jeesite/core/router/types';
import type { MenuModule, Menu, AppRouteRecordRaw } from '@jeesite/core/router/types';
import { findPath } from '@jeesite/core/utils/helper/treeHelper';
import { isUrl } from '@jeesite/core/utils/is';
import { RouteParams } from 'vue-router';
import { toRaw } from 'vue';
export function getAllParentPath<T = Recordable>(treeData: T[], path: string) {
const menuList = findPath(treeData, (n) => n.path === path) as Menu[];
return (menuList || []).map((item) => item.path);
}
function joinParentPath(menus: Menu[], parentPath = '') {
for (let index = 0; index < menus.length; index++) {
const menu = menus[index];
// https://next.router.vuejs.org/guide/essentials/nested-routes.html
// Note that nested paths that start with / will be treated as a root path.
// This allows you to leverage the component nesting without having to use a nested URL.
if (!(menu.path.startsWith('/') || isUrl(menu.path))) {
// path doesn't start with /, nor is it a url, join parent path
menu.path = `${parentPath}/${menu.path}`;
}
if (menu?.children?.length) {
joinParentPath(menu.children, menu.meta?.hidePathForChildren ? parentPath : menu.path);
}
}
}
// Parsing the menu module
export function transformMenuModule(menuModule: MenuModule): Menu {
const { menu } = menuModule;
const menuList = [menu];
joinParentPath(menuList);
return menuList[0];
}
export function transformRouteToMenu(routeModuleList: AppRouteModule[], routerMapping = false, parentPath = '') {
const routeList: AppRouteRecordRaw[] = [];
routeModuleList.forEach((node) => {
if (node.meta.hideMenu) {
return;
}
const item = {
...(node.meta || {}),
meta: node.meta,
name: node.meta.title,
path: node.path,
url: node.url,
target: node.target,
...(node.redirect ? { redirect: node.redirect } : {}),
children: node.children || [],
};
if (item.children) {
item.children = transformRouteToMenu(
item.children,
routerMapping,
item.meta?.hidePathForChildren ? parentPath : item.path,
);
}
if (routerMapping && item.meta.hideChildrenInMenu && typeof item.redirect === 'string') {
item.path = item.redirect;
}
// https://next.router.vuejs.org/guide/essentials/nested-routes.html
// Note that nested paths that start with / will be treated as a root path.
// This allows you to leverage the component nesting without having to use a nested URL.
// if (!(item.path.startsWith('/') || isUrl(item.path))) {
// // path doesn't start with /, nor is it a url, join parent path
// item.path = `${parentPath}/${item.path}`;
// }
if (item.meta?.single) {
const realItem = item?.children?.[0];
realItem && routeList.push(realItem);
} else {
routeList.push(item);
}
});
return routeList;
}
/**
* config menu with given params
*/
const menuParamRegex = /(?::)([\s\S]+?)((?=\/)|$)/g;
export function configureDynamicParamsMenu(menu: Menu, params: RouteParams) {
const { path, paramPath } = toRaw(menu);
let realPath = paramPath ? paramPath : path;
const matchArr = realPath.match(menuParamRegex);
matchArr?.forEach((it) => {
const realIt = it.substr(1);
if (params[realIt]) {
realPath = realPath.replace(`:${realIt}`, params[realIt] as string);
}
});
// save original param path.
if (!paramPath && matchArr && matchArr.length > 0) {
menu.paramPath = path;
}
menu.path = realPath;
// children
menu.children?.forEach((item) => configureDynamicParamsMenu(item, params));
}

View File

@@ -0,0 +1,169 @@
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
* No deletion without permission, or be held responsible to law.
* @author Vben、ThinkGem
*/
import type { AppRouteModule, AppRouteRecordRaw } from '@jeesite/core/router/types';
import type { Router, RouteRecordNormalized } from 'vue-router';
import { cloneDeep, omit } from 'lodash-es';
import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import { LAYOUT, IFRAME_BLANK, IFRAME_SIMPLE, EXCEPTION_COMPONENT } from '@jeesite/core/router/constant';
import { warn, env } from '@jeesite/core/utils/log';
// Dynamic introduction
function asyncImportRoute(
routes: AppRouteRecordRaw[] | undefined,
parent: AppRouteRecordRaw | undefined,
root: AppRouteRecordRaw | undefined,
) {
if (!routes) return;
routes.forEach((item) => {
item.meta = item.meta || {};
if (!item.meta.icon) {
item.meta.icon = 'bx:bx-circle';
}
if (parent && item.meta.hideMenu) {
item.meta.currentActiveMenu = parent.path;
}
const component = (item.component as string).toUpperCase();
if (!component || component === 'LAYOUT') {
item.component = LAYOUT;
} else if (component === 'IFRAME') {
item.component = root?.component ? IFRAME_BLANK : IFRAME_SIMPLE;
} else {
item.component = dynamicImport(item.component as string);
}
if (!item.component) {
item.component = EXCEPTION_COMPONENT;
item.props = item.props || {};
item.props.status = 404;
}
item.children && asyncImportRoute(item.children, item, root);
});
}
let dynamicViewsModules: Record<string, () => Promise<Recordable>>;
export function dynamicImport(component: string) {
if (!dynamicViewsModules) {
dynamicViewsModules = import.meta.glob('../../../../**/views/**/*.{vue,tsx}');
}
const keys = Object.keys(dynamicViewsModules);
const matchKeys = keys.filter((key) => {
const viewsPath = '/views',
l = viewsPath.length,
index = key.indexOf(viewsPath);
let k = key.substring(index + l);
const lastIndex = k.lastIndexOf('.');
k = k.substring(0, lastIndex);
return k === component;
});
if (matchKeys?.length === 1) {
const matchKey = matchKeys[0];
return dynamicViewsModules[matchKey];
}
if (matchKeys?.length > 1) {
warn(
'Please do not create `.vue` and `.TSX` files with the same file name in the same hierarchical directory under the views folder. This will cause dynamic introduction failure',
);
return;
}
}
// Turn background objects into routing objects
export function transformObjToRoute<T = AppRouteModule>(routeList: AppRouteModule[]): T[] {
routeList.forEach((item) => {
const component = (item.component as string).toUpperCase();
if (component === 'BLANK') {
item.component = item.path;
item.children = [cloneDeep(item)];
item.component = undefined;
} else {
item.children = [cloneDeep(item)];
item.component = LAYOUT;
}
item.path = '';
item.name = `${item.name}Parent`;
item.meta = item.meta || {};
item.meta.single = true;
item.meta.affix = false;
item.children && asyncImportRoute(item.children, item, item);
});
return routeList as unknown as T[];
}
/**
* Convert multi-level routing to level 2 routing
*/
export function flatMultiLevelRoutes(routeModules: AppRouteModule[]) {
const modules: AppRouteModule[] = cloneDeep(routeModules);
for (let index = 0; index < modules.length; index++) {
const routeModule = modules[index];
if (!isMultipleRoute(routeModule)) {
continue;
}
promoteRouteLevel(routeModule);
}
return modules;
}
export function createRouteHistory() {
if (env.VITE_ROUTE_WEB_HISTORY == 'true') {
return createWebHistory(env.VITE_PUBLIC_PATH);
} else {
return createWebHashHistory(env.VITE_PUBLIC_PATH);
}
}
// Routing level upgrade
function promoteRouteLevel(routeModule: AppRouteModule) {
// Use vue-router to splice menus
let router: Router | null = createRouter({
routes: [routeModule as unknown as RouteRecordNormalized],
history: createRouteHistory(),
});
const routes = router.getRoutes();
addToChildren(routes, routeModule.children || [], routeModule);
router = null;
routeModule.children = routeModule.children?.map((item) => omit(item, 'children'));
}
// Add all sub-routes to the secondary route
function addToChildren(routes: RouteRecordNormalized[], children: AppRouteRecordRaw[], routeModule: AppRouteModule) {
for (let index = 0; index < children.length; index++) {
const child = children[index];
const route = routes.find((item) => item.name === child.name);
if (!route) {
continue;
}
routeModule.children = routeModule.children || [];
if (!routeModule.children.find((item) => item.name === route.name)) {
routeModule.children?.push(route as unknown as AppRouteModule);
}
if (child.children?.length) {
addToChildren(routes, child.children, routeModule);
}
}
}
// Determine whether the level exceeds 2 levels
function isMultipleRoute(routeModule: AppRouteModule) {
if (!routeModule || !Reflect.has(routeModule, 'children') || !routeModule.children?.length) {
return false;
}
const children = routeModule.children;
let flag = false;
for (let index = 0; index < children.length; index++) {
const child = children[index];
if (child.children?.length) {
flag = true;
break;
}
}
return flag;
}

View File

@@ -0,0 +1,128 @@
import type { RouteRecordRaw } from 'vue-router';
import type { App } from 'vue';
import { createRouter } from 'vue-router';
import { basicRoutes } from './routes';
import { createRouteHistory } from './helper/routeHelper';
import { useMessage } from '@jeesite/core/hooks/web/useMessage';
import { useGlobSetting } from '@jeesite/core/hooks/setting';
import { useTabs } from '@jeesite/core/hooks/web/useTabs';
import { useGo } from '@jeesite/core/hooks/web/usePage';
import { initFramePage } from '@jeesite/core/layouts/iframe/useFrameKeepAlive';
import { encryptByMd5 } from '@jeesite/core/utils/cipher';
// import qs from 'qs';
// 白名单应该包含基本静态路由
const WHITE_NAME_LIST: string[] = [];
const getRouteNames = (array: any[]) =>
array.forEach((item) => {
WHITE_NAME_LIST.push(item.name);
getRouteNames(item.children || []);
});
getRouteNames(basicRoutes);
// app router
export const router = createRouter({
history: createRouteHistory(),
routes: basicRoutes as unknown as RouteRecordRaw[],
strict: true,
scrollBehavior: () => ({ left: 0, top: 0 }),
});
// reset router
export function resetRouter() {
router.getRoutes().forEach((route) => {
const { name } = route;
if (name && !WHITE_NAME_LIST.includes(name as string)) {
router.hasRoute(name) && router.removeRoute(name);
}
});
}
function initTabPage() {
const { showMessage, showMessageModal } = useMessage();
const { ctxAdminPath } = useGlobSetting();
const addFramePage = initFramePage();
const go = useGo(router);
window['tabPage'] = Object.assign(window['tabPage'] || {}, {
addTabPage: async function (_$this: any, title: string, url: string) {
if (url && !String(url).startsWith(ctxAdminPath)) {
await go(url);
return;
}
const idx = url.indexOf('?');
const path = (idx == -1 ? url : url.substring(0, idx)).replace(ctxAdminPath, '');
// const paramStr = idx == -1 ? '' : url.substring(idx + 1);
// const params = (paramStr && paramStr != '' ? qs.parse(paramStr) : {});
const name = encryptByMd5(url).substring(5, 15);
const route = {
meta: { frameSrc: url, title },
path: path + '/' + name,
name: 'JeeSite' + name,
url,
};
addFramePage(route);
await go(route.path);
},
getCurrentTabPage: function (currentTabCallback: Fn) {
const route = router.currentRoute.value;
const frame = document.querySelector(`.jeesite-iframe-page .${route.name as string}`);
if (frame && typeof currentTabCallback == 'function') {
try {
currentTabCallback(frame['contentWindow']);
} catch (e) {
console.error(e);
}
}
return frame;
},
getPrevTabPage: async function (preTabCallback: Fn, isCloseCurrentTab = false) {
const { tabStore, closeCurrent } = useTabs(router);
const index = tabStore.getTabList.findIndex((item) => item.path === router.currentRoute.value.path);
if (index > 1) {
const rotue = tabStore.getTabList[index - 1];
const frame = document.querySelector(`.jeesite-iframe-page .${rotue.name as string}`);
if (frame && typeof preTabCallback == 'function') {
try {
preTabCallback(frame['contentWindow']);
} catch (e) {
console.error(e);
}
}
}
if (isCloseCurrentTab) {
setTimeout(closeCurrent, 0);
}
},
closeCurrentTabPage: async function (preTabCallback: Fn) {
await this.getPrevTabPage(preTabCallback, true);
},
});
window['toastr'] = Object.assign(window['toastr'] || {}, {
options: { positionClass: {}, timeOut: undefined },
showMessage: function (msg: string, _title?: string, type = 'info') {
if (this.options?.positionClass == 'toast-top-full-width') {
return showMessage('posfull:' + msg, type, this.options?.timeOut);
}
return showMessage(msg, type, this.options?.timeOut);
},
error: function (msg: string, title?: string) {
this.showMessage(msg, title, 'error');
},
warning: function (msg: string, title?: string) {
this.showMessage(msg, title, 'warning');
},
success: function (msg: string, title?: string) {
this.showMessage(msg, title, 'success');
},
info: function (msg: string, title?: string) {
this.showMessage(msg, title, 'info');
},
});
}
// config router
export function setupRouter(app: App<Element>) {
app.use(router);
initTabPage();
}

View File

@@ -0,0 +1,129 @@
import type { Menu, MenuModule } from '@jeesite/core/router/types';
import type { RouteRecordNormalized } from 'vue-router';
import { useAppStoreWithOut } from '@jeesite/core/store/modules/app';
import { usePermissionStore } from '@jeesite/core/store/modules/permission';
import { transformMenuModule, getAllParentPath } from '@jeesite/core/router/helper/menuHelper';
import { filter } from '@jeesite/core/utils/helper/treeHelper';
import { isUrl } from '@jeesite/core/utils/is';
import { router } from '@jeesite/core/router';
import { PermissionModeEnum } from '@jeesite/core/enums/appEnum';
import { pathToRegexp } from 'path-to-regexp';
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });
const menuModules: MenuModule[] = [];
Object.keys(modules).forEach((key) => {
const mod = (modules as Recordable)[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
menuModules.push(...modList);
});
// ===========================
// ==========Helper===========
// ===========================
const getPermissionMode = () => {
const appStore = useAppStoreWithOut();
return appStore.getProjectConfig.permissionMode;
};
const isBackMode = () => {
return getPermissionMode() === PermissionModeEnum.BACK;
};
const isRouteMappingMode = () => {
return getPermissionMode() === PermissionModeEnum.ROUTE_MAPPING;
};
const isRoleMode = () => {
return getPermissionMode() === PermissionModeEnum.ROLE;
};
const staticMenus: Menu[] = [];
(() => {
menuModules.sort((a, b) => {
return (a.orderNo || 0) - (b.orderNo || 0);
});
for (const menu of menuModules) {
staticMenus.push(transformMenuModule(menu));
}
})();
async function getAsyncMenus() {
const permissionStore = usePermissionStore();
if (isBackMode()) {
// return permissionStore.getBackMenuList.filter((item) => !item.meta?.hideMenu && !item.hideMenu);
return permissionStore.getBackMenuList;
}
if (isRouteMappingMode()) {
// return permissionStore.getFrontMenuList.filter((item) => !item.hideMenu);
return permissionStore.getFrontMenuList;
}
return staticMenus;
}
export const getMenus = async (): Promise<Menu[]> => {
const menus = await getAsyncMenus();
if (isRoleMode()) {
const routes = router.getRoutes();
return filter(menus, basicFilter(routes));
}
return menus;
};
export async function getCurrentParentPath(currentPath: string) {
const menus = await getAsyncMenus();
const allParentPath = await getAllParentPath(menus, currentPath);
return allParentPath?.[0];
}
// Get the level 1 menu, delete children
export async function getShallowMenus(): Promise<Menu[]> {
const menus = await getAsyncMenus();
const shallowMenuList = menus.map((item) => ({ ...item, children: undefined }));
if (isRoleMode()) {
const routes = router.getRoutes();
return shallowMenuList.filter(basicFilter(routes));
}
return shallowMenuList;
}
// Get the children of the menu
export async function getChildrenMenus(parentPath: string) {
const menus = await getMenus();
const parent = menus.find((item) => item.path === parentPath);
if (!parent || !parent.children || !!parent?.meta?.hideChildrenInMenu) {
return [] as Menu[];
}
// console.log(menus, parent, parentPath);
if (isRoleMode()) {
const routes = router.getRoutes();
return filter(parent.children, basicFilter(routes));
}
return parent.children;
}
function basicFilter(routes: RouteRecordNormalized[]) {
return (menu: Menu) => {
const matchRoute = routes.find((route) => {
if (isUrl(menu.path)) return true;
if (route.meta?.carryParam) {
return pathToRegexp(route.path).regexp.test(menu.path);
}
const isSame = route.path === menu.path;
if (!isSame) return false;
if (route.meta?.ignoreAuth) return true;
return isSame || pathToRegexp(route.path).regexp.test(menu.path);
});
if (!matchRoute) return false;
menu.icon = (menu.icon || matchRoute.meta.icon) as string;
menu.meta = matchRoute.meta;
return true;
};
}

View File

@@ -0,0 +1,73 @@
import type { AppRouteRecordRaw } from '@jeesite/core/router/types';
import { t } from '@jeesite/core/hooks/web/useI18n';
import { REDIRECT_NAME, LAYOUT, EXCEPTION_COMPONENT, PAGE_NOT_FOUND_NAME } from '@jeesite/core/router/constant';
// 404 on a page
export const PAGE_NOT_FOUND_ROUTE: AppRouteRecordRaw = {
path: '/:path(.*)*',
name: PAGE_NOT_FOUND_NAME,
component: LAYOUT,
meta: {
title: 'ErrorPage',
hideBreadcrumb: true,
hideMenu: true,
},
children: [
{
path: '/404/:path(.*)*',
name: PAGE_NOT_FOUND_NAME + '404',
component: EXCEPTION_COMPONENT,
meta: {
title: '404',
hideBreadcrumb: true,
hideMenu: true,
},
},
],
};
export const REDIRECT_ROUTE: AppRouteRecordRaw = {
path: '/redirect',
component: LAYOUT,
name: 'RedirectTo',
meta: {
title: REDIRECT_NAME,
hideBreadcrumb: true,
hideMenu: true,
},
children: [
{
path: '/redirect/:path(.*)',
name: REDIRECT_NAME,
component: () => import('@jeesite/core/layouts/views/redirect/index.vue'),
meta: {
title: '',
hideBreadcrumb: true,
},
},
],
};
export const ERROR_LOG_ROUTE: AppRouteRecordRaw = {
path: '/errorLog',
name: 'ErrorLog',
component: LAYOUT,
redirect: '/errorLog/list',
meta: {
title: 'ErrorLog',
hideBreadcrumb: true,
hideChildrenInMenu: true,
},
children: [
{
path: 'list',
name: 'ErrorLogList',
component: () => import('@jeesite/core/layouts/views/errorLog/index.vue'),
meta: {
title: t('routes.basic.errorLogList'),
hideBreadcrumb: true,
currentActiveMenu: '/errorLog',
},
},
],
};

View File

@@ -0,0 +1,50 @@
import type { AppRouteRecordRaw, AppRouteModule } from '@jeesite/core/router/types';
import { PAGE_NOT_FOUND_ROUTE, REDIRECT_ROUTE } from '@jeesite/core/router/routes/basic';
import { mainOutRoutes } from './mainOut';
import { PageEnum } from '@jeesite/core/enums/pageEnum';
import { t } from '@jeesite/core/hooks/web/useI18n';
const modules = import.meta.glob('./modules/**/*.ts', { eager: true });
const routeModuleList: AppRouteModule[] = [];
Object.keys(modules).forEach((key) => {
const mod = (modules as Recordable)[key].default || {};
const modList = Array.isArray(mod) ? [...mod] : [mod];
routeModuleList.push(...modList);
});
export const asyncRoutes = [PAGE_NOT_FOUND_ROUTE, ...routeModuleList];
export const RootRoute: AppRouteRecordRaw = {
path: '/',
name: 'Root',
redirect: PageEnum.BASE_LOGIN,
meta: {
title: 'Root',
},
};
export const LoginRoute: AppRouteRecordRaw = {
path: '/login',
name: 'Login',
component: () => import('@jeesite/core/layouts/views/login/Login.vue'),
meta: {
title: t('routes.basic.login'),
},
};
const ModPwdRoute: AppRouteModule = {
path: '/modPwd',
name: 'ModPwd',
component: () => import('@jeesite/core/layouts/views/account/modPwd.vue'),
meta: {
icon: 'i-ant-design:key-outlined',
title: t('sys.account.modifyPwd'),
},
};
// Basic routing without permission
export const basicRoutes = [LoginRoute, ModPwdRoute, RootRoute, ...mainOutRoutes, REDIRECT_ROUTE, PAGE_NOT_FOUND_ROUTE];

View File

@@ -0,0 +1,12 @@
/**
The routing of this file will not show the layout.
It is an independent new page.
the contents of the file still need to log in to access
*/
import type { AppRouteModule } from '@jeesite/core/router/types';
// test
// http:ip:port/main-out
export const mainOutRoutes: AppRouteModule[] = [];
export const mainOutRouteNames = mainOutRoutes.map((item) => item.name);

View File

@@ -0,0 +1,47 @@
import type { AppRouteModule } from '@jeesite/core/router/types';
import { LAYOUT } from '@jeesite/core/router/constant';
import { t } from '@jeesite/core/hooks/web/useI18n';
const account: AppRouteModule = {
path: '/account',
name: 'Account',
component: LAYOUT,
redirect: '/account/center',
meta: {
icon: 'i-ion:person-outline',
title: t('sys.account.center'),
orderNo: 100000,
},
children: [
{
path: 'center',
name: 'AccountCenter',
component: () => import('@jeesite/core/layouts/views/account/center.vue'),
meta: {
icon: 'i-ion:person-outline',
title: t('sys.account.center'),
},
},
{
path: 'modPwd',
name: 'AccountModPwd',
component: () => import('@jeesite/core/layouts/views/account/modPwd.vue'),
meta: {
icon: 'i-ant-design:key-outlined',
title: t('sys.account.modifyPwd'),
},
},
{
path: 'modPwdQuestion',
name: 'AccountModPwdQuestion',
component: () => import('@jeesite/core/layouts/views/account/modPwdQuestion.vue'),
meta: {
icon: 'i-ant-design:key-outlined',
title: t('sys.account.modifyPqa'),
},
},
],
};
export default account;

View File

@@ -0,0 +1,50 @@
import type { AppRouteModule } from '@jeesite/core/router/types';
import { LAYOUT } from '@jeesite/core/router/constant';
import { t } from '@jeesite/core/hooks/web/useI18n';
const desktop: AppRouteModule = {
path: '/desktop',
name: 'Desktop',
component: LAYOUT,
redirect: '/desktop/analysis',
meta: {
orderNo: 10,
icon: 'i-ant-design:home-outlined',
title: t('routes.dashboard.dashboard'),
},
children: [
{
path: 'analysis',
name: 'Analysis',
component: () => import('@jeesite/core/layouts/views/desktop/analysis/index.vue'),
meta: {
// affix: true,
icon: 'i-ant-design:home-outlined',
tabIcon: 'i-ant-design:home-outlined',
title: t('routes.dashboard.analysis'),
},
},
{
path: 'workbench',
name: 'Workbench',
component: () => import('@jeesite/core/layouts/views/desktop/workbench/index.vue'),
meta: {
icon: 'i-ant-design:read-outlined',
title: t('routes.dashboard.workbench'),
},
},
{
path: 'about',
name: 'AboutPage',
component: () => import('@jeesite/core/layouts/views/desktop/about/index.vue'),
meta: {
title: t('routes.dashboard.about'),
icon: 'i-ant-design:tag-outlined',
hideMenu: true,
},
},
],
};
export default desktop;

View File

@@ -0,0 +1,63 @@
import type { RouteRecordRaw, RouteMeta } from 'vue-router';
import { RoleEnum } from '@jeesite/core/enums/roleEnum';
import { defineComponent } from 'vue';
export type Component<T = any> =
| ReturnType<typeof defineComponent>
// | (() => Promise<typeof import('*.vue')>)
| (() => Promise<T>);
// @ts-ignore
export interface AppRouteRecordRaw extends Omit<RouteRecordRaw, 'meta'>, Menu {
name: string;
meta: RouteMeta;
component?: Component | string;
components?: Component;
children?: AppRouteRecordRaw[];
props?: Recordable;
fullPath?: string;
url?: string;
}
export interface MenuTag {
type?: 'primary' | 'error' | 'warn' | 'success';
content?: string;
dot?: boolean;
}
export interface Menu {
name: string;
icon?: string;
color?: string;
path: string;
target?: string;
// path contains param, auto assignment.
paramPath?: string;
disabled?: boolean;
children?: Menu[];
orderNo?: number;
roles?: RoleEnum[];
meta?: Partial<RouteMeta>;
tag?: MenuTag;
hideMenu?: boolean;
}
export interface MenuModule {
orderNo?: number;
menu: Menu;
}
// export type AppRouteModule = RouteModule | AppRouteRecordRaw;
export type AppRouteModule = AppRouteRecordRaw;