Merge remote-tracking branch 'vben/main' into vben-dev

# Conflicts:
#	.gitignore
#	.husky/pre-commit
#	.vscode/extensions.json
#	.vscode/settings.json
#	README.ja-JP.md
#	README.md
#	README.zh-CN.md
#	apps/backend-mock/api/auth/codes.ts
#	apps/backend-mock/api/auth/login.post.ts
#	apps/backend-mock/api/auth/logout.post.ts
#	apps/backend-mock/api/auth/refresh.post.ts
#	apps/backend-mock/api/menu/all.ts
#	apps/backend-mock/api/status.ts
#	apps/backend-mock/api/table/list.ts
#	apps/backend-mock/api/test.get.ts
#	apps/backend-mock/api/test.post.ts
#	apps/backend-mock/api/user/info.ts
#	apps/backend-mock/middleware/1.api.ts
#	apps/backend-mock/nitro.config.ts
#	apps/backend-mock/package.json
#	apps/backend-mock/routes/[...].ts
#	apps/backend-mock/tsconfig.json
#	apps/backend-mock/utils/cookie-utils.ts
#	apps/backend-mock/utils/jwt-utils.ts
#	apps/backend-mock/utils/mock-data.ts
#	apps/backend-mock/utils/response.ts
#	apps/web-antd/.env
#	apps/web-antd/src/adapter/component/index.ts
#	apps/web-antd/src/adapter/form.ts
#	apps/web-antd/src/api/request.ts
#	apps/web-antd/src/layouts/auth.vue
#	apps/web-antd/src/layouts/basic.vue
#	apps/web-antd/src/preferences.ts
#	apps/web-antd/src/router/guard.ts
#	apps/web-antd/src/router/routes/modules/demos.ts
#	apps/web-antd/src/store/auth.ts
#	apps/web-antd/src/views/demos/antd/index.vue
#	apps/web-antdv-next/vite.config.ts
#	apps/web-ele/.env
#	apps/web-ele/index.html
#	apps/web-ele/package.json
#	apps/web-ele/src/adapter/component/index.ts
#	apps/web-ele/src/adapter/form.ts
#	apps/web-ele/src/adapter/vxe-table.ts
#	apps/web-ele/src/api/request.ts
#	apps/web-ele/src/bootstrap.ts
#	apps/web-ele/src/layouts/auth.vue
#	apps/web-ele/src/layouts/basic.vue
#	apps/web-ele/src/locales/index.ts
#	apps/web-ele/src/locales/langs/en-US/demos.json
#	apps/web-ele/src/locales/langs/en-US/page.json
#	apps/web-ele/src/locales/langs/zh-CN/demos.json
#	apps/web-ele/src/locales/langs/zh-CN/page.json
#	apps/web-ele/src/preferences.ts
#	apps/web-ele/src/router/guard.ts
#	apps/web-ele/src/router/routes/core.ts
#	apps/web-ele/src/router/routes/modules/dashboard.ts
#	apps/web-ele/src/router/routes/modules/demos.ts
#	apps/web-ele/src/router/routes/modules/vben.ts
#	apps/web-ele/src/store/auth.ts
#	apps/web-ele/src/views/_core/authentication/code-login.vue
#	apps/web-ele/src/views/_core/authentication/forget-password.vue
#	apps/web-ele/src/views/_core/authentication/register.vue
#	apps/web-ele/src/views/dashboard/analytics/analytics-trends.vue
#	apps/web-ele/src/views/dashboard/analytics/analytics-visits-data.vue
#	apps/web-ele/src/views/dashboard/analytics/analytics-visits-sales.vue
#	apps/web-ele/src/views/dashboard/analytics/analytics-visits-source.vue
#	apps/web-ele/src/views/dashboard/analytics/analytics-visits.vue
#	apps/web-ele/src/views/dashboard/analytics/index.vue
#	apps/web-ele/src/views/demos/element/index.vue
#	apps/web-ele/src/views/demos/form/basic.vue
#	apps/web-ele/tsconfig.json
#	apps/web-ele/tsconfig.node.json
#	apps/web-naive/.env
#	apps/web-naive/index.html
#	apps/web-naive/package.json
#	apps/web-naive/src/adapter/component/index.ts
#	apps/web-naive/src/adapter/form.ts
#	apps/web-naive/src/adapter/vxe-table.ts
#	apps/web-naive/src/api/request.ts
#	apps/web-naive/src/bootstrap.ts
#	apps/web-naive/src/layouts/auth.vue
#	apps/web-naive/src/layouts/basic.vue
#	apps/web-naive/src/locales/index.ts
#	apps/web-naive/src/locales/langs/en-US/demos.json
#	apps/web-naive/src/locales/langs/en-US/page.json
#	apps/web-naive/src/locales/langs/zh-CN/demos.json
#	apps/web-naive/src/locales/langs/zh-CN/page.json
#	apps/web-naive/src/preferences.ts
#	apps/web-naive/src/router/guard.ts
#	apps/web-naive/src/router/routes/core.ts
#	apps/web-naive/src/router/routes/modules/dashboard.ts
#	apps/web-naive/src/router/routes/modules/demos.ts
#	apps/web-naive/src/router/routes/modules/vben.ts
#	apps/web-naive/src/store/auth.ts
#	apps/web-naive/src/views/_core/authentication/code-login.vue
#	apps/web-naive/src/views/_core/authentication/forget-password.vue
#	apps/web-naive/src/views/_core/authentication/register.vue
#	apps/web-naive/src/views/dashboard/analytics/analytics-trends.vue
#	apps/web-naive/src/views/dashboard/analytics/analytics-visits-data.vue
#	apps/web-naive/src/views/dashboard/analytics/analytics-visits-sales.vue
#	apps/web-naive/src/views/dashboard/analytics/analytics-visits-source.vue
#	apps/web-naive/src/views/dashboard/analytics/analytics-visits.vue
#	apps/web-naive/src/views/dashboard/analytics/index.vue
#	apps/web-naive/src/views/demos/form/basic.vue
#	apps/web-naive/src/views/demos/naive/index.vue
#	apps/web-naive/tsconfig.json
#	apps/web-naive/tsconfig.node.json
#	apps/web-naive/vite.config.ts
#	docs/.vitepress/components/demo-preview.vue
#	docs/.vitepress/components/preview-group.vue
#	docs/.vitepress/config/en.mts
#	docs/.vitepress/config/index.mts
#	docs/.vitepress/config/plugins/demo-preview.ts
#	docs/.vitepress/config/shared.mts
#	docs/.vitepress/config/zh.mts
#	docs/.vitepress/theme/components/site-layout.vue
#	docs/.vitepress/theme/components/vben-contributors.vue
#	docs/.vitepress/theme/styles/variables.css
#	docs/package.json
#	docs/src/_env/adapter/component.ts
#	docs/src/_env/adapter/form.ts
#	docs/src/_env/adapter/vxe-table.ts
#	docs/src/commercial/community.md
#	docs/src/components/common-ui/vben-count-to-animator.md
#	docs/src/components/common-ui/vben-drawer.md
#	docs/src/components/common-ui/vben-form.md
#	docs/src/components/common-ui/vben-modal.md
#	docs/src/components/common-ui/vben-vxe-table.md
#	docs/src/components/layout-ui/page.md
#	docs/src/demos/vben-drawer/auto-height/drawer.vue
#	docs/src/demos/vben-drawer/basic/index.vue
#	docs/src/demos/vben-drawer/dynamic/index.vue
#	docs/src/demos/vben-drawer/shared-data/drawer.vue
#	docs/src/demos/vben-drawer/shared-data/index.vue
#	docs/src/demos/vben-form/api/index.vue
#	docs/src/demos/vben-form/basic/index.vue
#	docs/src/demos/vben-form/custom/index.vue
#	docs/src/demos/vben-form/dynamic/index.vue
#	docs/src/demos/vben-form/query/index.vue
#	docs/src/demos/vben-form/rules/index.vue
#	docs/src/demos/vben-modal/auto-height/modal.vue
#	docs/src/demos/vben-modal/basic/index.vue
#	docs/src/demos/vben-modal/dynamic/index.vue
#	docs/src/demos/vben-modal/shared-data/index.vue
#	docs/src/demos/vben-modal/shared-data/modal.vue
#	docs/src/demos/vben-vxe-table/basic/index.vue
#	docs/src/demos/vben-vxe-table/custom-cell/index.vue
#	docs/src/demos/vben-vxe-table/edit-row/index.vue
#	docs/src/demos/vben-vxe-table/fixed/index.vue
#	docs/src/demos/vben-vxe-table/form/index.vue
#	docs/src/demos/vben-vxe-table/remote/index.vue
#	docs/src/demos/vben-vxe-table/tree/index.vue
#	docs/src/demos/vben-vxe-table/virtual/index.vue
#	docs/src/en/guide/essentials/development.md
#	docs/src/en/guide/essentials/external-module.md
#	docs/src/en/guide/essentials/route.md
#	docs/src/en/guide/essentials/server.md
#	docs/src/en/guide/essentials/settings.md
#	docs/src/en/guide/in-depth/access.md
#	docs/src/en/guide/in-depth/loading.md
#	docs/src/en/guide/in-depth/locale.md
#	docs/src/en/guide/in-depth/theme.md
#	docs/src/en/guide/introduction/quick-start.md
#	docs/src/en/guide/introduction/thin.md
#	docs/src/en/guide/introduction/vben.md
#	docs/src/en/guide/other/faq.md
#	docs/src/en/guide/project/dir.md
#	docs/src/en/guide/project/standard.md
#	docs/src/en/guide/project/tailwindcss.md
#	docs/src/en/index.md
#	docs/src/friend-links/index.md
#	docs/src/guide/essentials/build.md
#	docs/src/guide/essentials/development.md
#	docs/src/guide/essentials/external-module.md
#	docs/src/guide/essentials/route.md
#	docs/src/guide/essentials/server.md
#	docs/src/guide/essentials/settings.md
#	docs/src/guide/in-depth/access.md
#	docs/src/guide/in-depth/check-updates.md
#	docs/src/guide/in-depth/loading.md
#	docs/src/guide/in-depth/locale.md
#	docs/src/guide/in-depth/theme.md
#	docs/src/guide/introduction/quick-start.md
#	docs/src/guide/introduction/thin.md
#	docs/src/guide/introduction/vben.md
#	docs/src/guide/introduction/why.md
#	docs/src/guide/other/faq.md
#	docs/src/guide/project/dir.md
#	docs/src/guide/project/standard.md
#	docs/src/guide/project/tailwindcss.md
#	docs/src/index.md
#	docs/tsconfig.json
#	package.json
#	packages/@core/ui-kit/shadcn-ui/src/components/logo/logo.vue
#	packages/constants/src/core.ts
#	packages/effects/common-ui/src/components/index.ts
#	packages/effects/common-ui/src/ui/dashboard/analysis/analysis-overview.vue
#	packages/effects/common-ui/src/ui/dashboard/workbench/workbench-header.vue
#	packages/effects/common-ui/src/ui/dashboard/workbench/workbench-project.vue
#	packages/effects/layouts/src/authentication/authentication.vue
#	packages/effects/layouts/src/basic/layout.vue
#	packages/effects/layouts/src/widgets/notification/notification.vue
#	packages/effects/layouts/src/widgets/notification/types.ts
#	packages/icons/src/iconify/index.ts
#	packages/icons/src/svg/index.ts
#	packages/stores/src/modules/user.ts
#	playground/src/adapter/component/index.ts
#	playground/src/store/auth.ts
#	pnpm-lock.yaml
#	vben-admin.code-workspace
This commit is contained in:
李琦
2026-08-10 16:55:17 +08:00
1278 changed files with 71754 additions and 19298 deletions

View File

@@ -1,6 +1,7 @@
import type { MenuRecordRaw } from '@vben-core/typings';
import type { RouteRecordRaw } from 'vue-router';
import type { MenuRecordRaw } from '@vben-core/typings';
import { acceptHMRUpdate, defineStore } from 'pinia';
type AccessToken = null | string;
@@ -26,6 +27,14 @@ interface AccessState {
* 是否已经检查过权限
*/
isAccessChecked: boolean;
/**
* 是否锁屏状态
*/
isLockScreen: boolean;
/**
* 锁屏密码
*/
lockScreenPassword?: string;
/**
* 登录是否过期
*/
@@ -60,6 +69,10 @@ export const useAccessStore = defineStore('core-access', {
}
return findMenu(this.accessMenus, path);
},
lockScreen(password: string) {
this.isLockScreen = true;
this.lockScreenPassword = password;
},
setAccessCodes(codes: string[]) {
this.accessCodes = codes;
},
@@ -81,10 +94,20 @@ export const useAccessStore = defineStore('core-access', {
setRefreshToken(token: AccessToken) {
this.refreshToken = token;
},
unlockScreen() {
this.isLockScreen = false;
this.lockScreenPassword = undefined;
},
},
persist: {
// 持久化
pick: ['accessToken', 'refreshToken', 'accessCodes'],
pick: [
'accessToken',
'refreshToken',
'accessCodes',
'isLockScreen',
'lockScreenPassword',
],
},
state: (): AccessState => ({
accessCodes: [],
@@ -92,6 +115,8 @@ export const useAccessStore = defineStore('core-access', {
accessRoutes: [],
accessToken: null,
isAccessChecked: false,
isLockScreen: false,
lockScreenPassword: undefined,
loginExpired: false,
refreshToken: null,
}),

View File

@@ -1,4 +1,4 @@
export * from './access';
export * from './lock';
export * from './tabbar';
export * from './timezone';
export * from './user';

View File

@@ -1,31 +0,0 @@
import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it } from 'vitest';
import { useLockStore } from './lock';
describe('useLockStore', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('should initialize with correct default state', () => {
const store = useLockStore();
expect(store.isLockScreen).toBe(false);
expect(store.lockScreenPassword).toBeUndefined();
});
it('should lock screen with a password', () => {
const store = useLockStore();
store.lockScreen('1234');
expect(store.isLockScreen).toBe(true);
expect(store.lockScreenPassword).toBe('1234');
});
it('should unlock screen and clear password', () => {
const store = useLockStore();
store.lockScreen('1234');
store.unlockScreen();
expect(store.isLockScreen).toBe(false);
expect(store.lockScreenPassword).toBeUndefined();
});
});

View File

@@ -1,33 +0,0 @@
import { defineStore } from 'pinia';
interface AppState {
/**
* 是否锁屏状态
*/
isLockScreen: boolean;
/**
* 锁屏密码
*/
lockScreenPassword?: string;
}
export const useLockStore = defineStore('core-lock', {
actions: {
lockScreen(password: string) {
this.isLockScreen = true;
this.lockScreenPassword = password;
},
unlockScreen() {
this.isLockScreen = false;
this.lockScreenPassword = undefined;
},
},
persist: {
pick: ['isLockScreen', 'lockScreenPassword'],
},
state: (): AppState => ({
isLockScreen: false,
lockScreenPassword: undefined,
}),
});

View File

@@ -22,12 +22,13 @@ describe('useAccessStore', () => {
const tab: any = {
fullPath: '/home',
meta: {},
key: '/home',
name: 'Home',
path: '/home',
};
store.addTab(tab);
const addNewTab = store.addTab(tab);
expect(store.tabs.length).toBe(1);
expect(store.tabs[0]).toEqual(tab);
expect(store.tabs[0]).toEqual(addNewTab);
});
it('adds a new tab if it does not exist', () => {
@@ -38,20 +39,22 @@ describe('useAccessStore', () => {
name: 'New',
path: '/new',
};
store.addTab(newTab);
expect(store.tabs).toContainEqual(newTab);
const addNewTab = store.addTab(newTab);
expect(store.tabs).toContainEqual(addNewTab);
});
it('updates an existing tab instead of adding a new one', () => {
const store = useTabbarStore();
const initialTab: any = {
fullPath: '/existing',
meta: {},
meta: {
fullPathKey: false,
},
name: 'Existing',
path: '/existing',
query: {},
};
store.tabs.push(initialTab);
store.addTab(initialTab);
const updatedTab = { ...initialTab, query: { id: '1' } };
store.addTab(updatedTab);
expect(store.tabs.length).toBe(1);
@@ -60,9 +63,12 @@ describe('useAccessStore', () => {
it('closes all tabs', async () => {
const store = useTabbarStore();
store.tabs = [
{ fullPath: '/home', meta: {}, name: 'Home', path: '/home' },
] as any;
store.addTab({
fullPath: '/home',
meta: {},
name: 'Home',
path: '/home',
} as any);
router.replace = vi.fn();
await store.closeAllTabs(router);
@@ -157,7 +163,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store._bulkCloseByPaths(['/home', '/contact']);
await store._bulkCloseByKeys(['/home', '/contact']);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('About');
@@ -183,9 +189,8 @@ describe('useAccessStore', () => {
name: 'Contact',
path: '/contact',
};
store.addTab(targetTab);
await store.closeLeftTabs(targetTab);
const addTargetTab = store.addTab(targetTab);
await store.closeLeftTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('Contact');
@@ -205,7 +210,7 @@ describe('useAccessStore', () => {
name: 'About',
path: '/about',
};
store.addTab(targetTab);
const addTargetTab = store.addTab(targetTab);
store.addTab({
fullPath: '/contact',
meta: {},
@@ -213,7 +218,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store.closeOtherTabs(targetTab);
await store.closeOtherTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('About');
@@ -227,7 +232,7 @@ describe('useAccessStore', () => {
name: 'Home',
path: '/home',
};
store.addTab(targetTab);
const addTargetTab = store.addTab(targetTab);
store.addTab({
fullPath: '/about',
meta: {},
@@ -241,7 +246,7 @@ describe('useAccessStore', () => {
path: '/contact',
} as any);
await store.closeRightTabs(targetTab);
await store.closeRightTabs(addTargetTab);
expect(store.tabs).toHaveLength(1);
expect(store.tabs[0]?.name).toBe('Home');

View File

@@ -1,17 +1,35 @@
import type { ComputedRef, VNode } from 'vue';
import type {
RouteLocationNormalized,
RouteLocationNormalizedLoaded,
RouteLocationNormalizedLoadedGeneric,
Router,
RouteRecordNormalized,
} from 'vue-router';
import type { TabDefinition } from '@vben-core/typings';
import type { Router, RouteRecordNormalized } from 'vue-router';
import { toRaw } from 'vue';
import { markRaw, nextTick, toRaw } from 'vue';
import { preferences } from '@vben-core/preferences';
import {
openRouteInNewWindow,
createStack,
openWindow,
Stack,
startProgress,
stopProgress,
} from '@vben-core/shared/utils';
import { acceptHMRUpdate, defineStore } from 'pinia';
interface RouteCached {
component: VNode;
key: string;
route: RouteLocationNormalizedLoadedGeneric;
}
interface TabbarState {
cachedRoutes: Map<string, RouteCached>;
/**
* @zh_CN 当前打开的标签页列表缓存
*/
@@ -24,6 +42,10 @@ interface TabbarState {
* @zh_CN 需要排除缓存的标签页
*/
excludeCachedTabs: Set<string>;
/**
* @zh_CN 标签右键菜单列表
*/
menuList: string[];
/**
* @zh_CN 是否刷新
*/
@@ -36,8 +58,17 @@ interface TabbarState {
* @zh_CN 更新时间,用于一些更新场景,使用watch深度监听的话,会损耗性能
*/
updateTime?: number;
/**
* @zh_CN 上一个标签页打开的标签
*/
visitHistory: Stack<string>;
}
/**
* @zh_CN 访问历史记录最大数量
*/
const MAX_VISIT_HISTORY = 50;
/**
* @zh_CN 访问权限相关
*/
@@ -46,23 +77,26 @@ export const useTabbarStore = defineStore('core-tabbar', {
/**
* Close tabs in bulk
*/
async _bulkCloseByPaths(paths: string[]) {
this.tabs = this.tabs.filter((item) => {
return !paths.includes(getTabPath(item));
});
async _bulkCloseByKeys(keys: string[]) {
const keySet = new Set(keys);
this.tabs = this.tabs.filter(
(item) => !keySet.has(getTabKeyFromTab(item)),
);
if (isVisitHistory()) {
this.visitHistory.remove(...keys);
}
this.updateCacheTabs();
await this.updateCacheTabs();
},
/**
* @zh_CN 关闭标签页
* @param tab
*/
_close(tab: TabDefinition) {
const { fullPath } = tab;
if (isAffixTab(tab)) {
return;
}
const index = this.tabs.findIndex((item) => item.fullPath === fullPath);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
index !== -1 && this.tabs.splice(index, 1);
},
/**
@@ -95,17 +129,21 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @zh_CN 添加标签页
* @param routeTab
*/
addTab(routeTab: TabDefinition) {
const tab = cloneTab(routeTab);
addTab(routeTab: TabDefinition): TabDefinition {
let tab = cloneTab(routeTab);
if (!tab.key) {
tab.key = getTabKey(routeTab);
}
if (!isTabShown(tab)) {
return;
return tab;
}
const tabIndex = this.tabs.findIndex((tab) => {
return getTabPath(tab) === getTabPath(routeTab);
const tabIndex = this.tabs.findIndex((item) => {
return equalTab(item, tab);
});
if (tabIndex === -1) {
const maxCount = preferences.tabbar.maxCount;
// 获取动态路由打开数,超过 0 即代表需要控制打开数
const maxNumOfOpenTab = (routeTab?.meta?.maxNumOfOpenTab ??
-1) as number;
@@ -121,8 +159,14 @@ export const useTabbarStore = defineStore('core-tabbar', {
(item) => item.name === routeTab.name,
);
index !== -1 && this.tabs.splice(index, 1);
} else if (maxCount > 0 && this.tabs.length >= maxCount) {
// 关闭第一个
const index = this.tabs.findIndex(
(item) =>
!Reflect.has(item.meta, 'affixTab') || !item.meta.affixTab,
);
index !== -1 && this.tabs.splice(index, 1);
}
this.tabs.push(tab);
} else {
// 页面已经存在,不重复添加选项卡,只更新选项卡参数
@@ -141,10 +185,15 @@ export const useTabbarStore = defineStore('core-tabbar', {
mergedTab.meta.newTabTitle = curMeta.newTabTitle;
}
}
tab = mergedTab;
this.tabs.splice(tabIndex, 1, mergedTab);
}
this.updateCacheTabs();
// 添加访问历史记录
if (isVisitHistory()) {
this.visitHistory.push(tab.key as string);
}
return tab;
},
/**
* @zh_CN 关闭所有标签页
@@ -152,6 +201,12 @@ export const useTabbarStore = defineStore('core-tabbar', {
async closeAllTabs(router: Router) {
const newTabs = this.tabs.filter((tab) => isAffixTab(tab));
this.tabs = newTabs.length > 0 ? newTabs : [...this.tabs].splice(0, 1);
// 设置访问历史记录
if (isVisitHistory()) {
this.visitHistory.retain(
this.tabs.map((item) => getTabKeyFromTab(item)),
);
}
await this._goToDefaultTab(router);
this.updateCacheTabs();
},
@@ -160,65 +215,63 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async closeLeftTabs(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index < 1) {
return;
}
const leftTabs = this.tabs.slice(0, index);
const paths: string[] = [];
const keys: string[] = [];
for (const item of leftTabs) {
if (!isAffixTab(item)) {
paths.push(getTabPath(item));
keys.push(item.key as string);
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
},
/**
* @zh_CN 关闭其他标签页
* @param tab
*/
async closeOtherTabs(tab: TabDefinition) {
const closePaths = this.tabs.map((item) => getTabPath(item));
const closeKeys = this.tabs.map((item) => getTabKeyFromTab(item));
const paths: string[] = [];
const keys: string[] = [];
for (const path of closePaths) {
if (path !== tab.fullPath) {
const closeTab = this.tabs.find((item) => getTabPath(item) === path);
for (const key of closeKeys) {
if (key !== getTabKeyFromTab(tab)) {
const closeTab = this.tabs.find(
(item) => getTabKeyFromTab(item) === key,
);
if (!closeTab) {
continue;
}
if (!isAffixTab(closeTab)) {
paths.push(getTabPath(closeTab));
keys.push(closeTab.key as string);
}
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
},
/**
* @zh_CN 关闭右侧标签页
* @param tab
*/
async closeRightTabs(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index !== -1 && index < this.tabs.length - 1) {
const rightTabs = this.tabs.slice(index + 1);
const paths: string[] = [];
const keys: string[] = [];
for (const item of rightTabs) {
if (!isAffixTab(item)) {
paths.push(getTabPath(item));
keys.push(item.key as string);
}
}
await this._bulkCloseByPaths(paths);
await this._bulkCloseByKeys(keys);
}
},
@@ -229,15 +282,46 @@ export const useTabbarStore = defineStore('core-tabbar', {
*/
async closeTab(tab: TabDefinition, router: Router) {
const { currentRoute } = router;
const currentTabKey = getTabKey(currentRoute.value);
// 关闭不是激活选项卡
if (getTabPath(currentRoute.value) !== getTabPath(tab)) {
if (currentTabKey !== getTabKeyFromTab(tab)) {
this._close(tab);
this.updateCacheTabs();
// 移除访问历史记录
if (isVisitHistory()) {
this.visitHistory.remove(getTabKeyFromTab(tab));
}
return;
}
if (this.getTabs.length <= 1) {
console.error('Failed to close the tab; only one tab remains open.');
return;
}
// 从访问历史记录中移除当前关闭的tab
if (isVisitHistory()) {
this.visitHistory.remove(currentTabKey);
this._close(tab);
let previousTab: TabDefinition | undefined;
let previousTabKey: string | undefined;
while (true) {
previousTabKey = this.visitHistory.pop();
if (!previousTabKey) {
break;
}
previousTab = this.getTabByKey(previousTabKey);
if (previousTab) {
break;
}
}
await (previousTab
? this._goToTab(previousTab, router)
: this._goToDefaultTab(router));
return;
}
// 未开启访问历史记录,直接跳转下一个或上一个tab
const index = this.getTabs.findIndex(
(item) => getTabPath(item) === getTabPath(currentRoute.value),
(item) => getTabKeyFromTab(item) === getTabKey(currentRoute.value),
);
const before = this.getTabs[index - 1];
@@ -251,8 +335,6 @@ export const useTabbarStore = defineStore('core-tabbar', {
} else if (before) {
this._close(tab);
await this._goToTab(before, router);
} else {
console.error('Failed to close the tab; only one tab remains open.');
}
},
@@ -264,7 +346,7 @@ export const useTabbarStore = defineStore('core-tabbar', {
async closeTabByKey(key: string, router: Router) {
const originKey = decodeURIComponent(key);
const index = this.tabs.findIndex(
(item) => getTabPath(item) === originKey,
(item) => getTabKeyFromTab(item) === originKey,
);
if (index === -1) {
return;
@@ -277,20 +359,21 @@ export const useTabbarStore = defineStore('core-tabbar', {
},
/**
* 根据路径获取标签页
* @param path
* 根据tab的key获取tab
* @param key
*/
getTabByPath(path: string) {
getTabByKey(key: string) {
return this.getTabs.find(
(item) => getTabPath(item) === path,
(item) => getTabKeyFromTab(item) === key,
) as TabDefinition;
},
/**
* @zh_CN 新窗口打开标签页
* @param tab
*/
async openTabInNewWindow(tab: TabDefinition) {
openRouteInNewWindow(tab.fullPath || tab.path);
async openTabInNewWindow(tab: TabDefinition, router: Router) {
const href = router.resolve(tab.fullPath || tab.path).href;
openWindow(new URL(href, location.href).href, { target: '_blank' });
},
/**
@@ -298,22 +381,19 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async pinTab(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
if (index !== -1) {
const oldTab = this.tabs[index];
tab.meta.affixTab = true;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index === -1) {
return;
}
const oldTab = this.tabs[index];
tab.meta.affixTab = true;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
// 过滤固定tabs,后面更改affixTabOrder的值的话可能会有问题,目前行464排序affixTabs没有设置值
const affixTabs = this.tabs.filter((tab) => isAffixTab(tab));
// 获得固定tabs的index
const newIndex = affixTabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
const newIndex = affixTabs.findIndex((item) => equalTab(item, tab));
// 交换位置重新排序
await this.sortTabs(index, newIndex);
},
@@ -321,7 +401,13 @@ export const useTabbarStore = defineStore('core-tabbar', {
/**
* 刷新标签页
*/
async refresh(router: Router) {
async refresh(router: Router | string) {
// 如果是Router路由,那么就根据当前路由刷新
// 如果是string字符串,为路由名称,则定向刷新指定标签页,不能是当前路由名称,否则不会刷新
if (typeof router === 'string') {
return await this.refreshByName(router);
}
const { currentRoute } = router;
const { name } = currentRoute.value;
@@ -329,13 +415,23 @@ export const useTabbarStore = defineStore('core-tabbar', {
this.renderRouteView = false;
startProgress();
await new Promise((resolve) => setTimeout(resolve, 200));
await nextTick();
// await new Promise((resolve) => setTimeout(resolve, 200));
this.excludeCachedTabs.delete(name as string);
this.renderRouteView = true;
stopProgress();
},
/**
* 根据路由名称刷新指定标签页
*/
async refreshByName(name: string) {
this.excludeCachedTabs.add(name);
await new Promise((resolve) => setTimeout(resolve, 200));
this.excludeCachedTabs.delete(name);
},
/**
* @zh_CN 重置标签页标题
*/
@@ -343,9 +439,7 @@ export const useTabbarStore = defineStore('core-tabbar', {
if (tab?.meta?.newTabTitle) {
return;
}
const findTab = this.tabs.find(
(item) => getTabPath(item) === getTabPath(tab),
);
const findTab = this.tabs.find((item) => equalTab(item, tab));
if (findTab) {
findTab.meta.newTabTitle = undefined;
await this.updateCacheTabs();
@@ -364,14 +458,33 @@ export const useTabbarStore = defineStore('core-tabbar', {
},
/**
* @zh_CN 设置标签页标题
* @param tab
* @param title
* @zh_CN 更新菜单列表
* @param list
*/
async setTabTitle(tab: TabDefinition, title: string) {
const findTab = this.tabs.find(
(item) => getTabPath(item) === getTabPath(tab),
);
setMenuList(list: string[]) {
this.menuList = list;
},
/**
* @zh_CN 设置标签页标题
*
* @zh_CN 支持设置静态标题字符串或计算属性作为动态标题
* @zh_CN 当标题为计算属性时,标题会随计算属性值变化而自动更新
* @zh_CN 适用于需要根据状态或多语言动态更新标题的场景
*
* @param {TabDefinition} tab - 标签页对象
* @param {ComputedRef<string> | string} title - 标题内容,支持静态字符串或计算属性
*
* @example
* // 设置静态标题
* setTabTitle(tab, '新标签页');
*
* @example
* // 设置动态标题
* setTabTitle(tab, computed(() => t('common.dashboard')));
*/
async setTabTitle(tab: TabDefinition, title: ComputedRef<string> | string) {
const findTab = this.tabs.find((item) => equalTab(item, tab));
if (findTab) {
findTab.meta.newTabTitle = title;
@@ -379,7 +492,6 @@ export const useTabbarStore = defineStore('core-tabbar', {
await this.updateCacheTabs();
}
},
setUpdateTime() {
this.updateTime = Date.now();
},
@@ -397,6 +509,7 @@ export const useTabbarStore = defineStore('core-tabbar', {
this.tabs.splice(newIndex, 0, currentTab);
this.dragEndIndex = this.dragEndIndex + 1;
},
/**
* @zh_CN 切换固定标签页
* @param tab
@@ -412,17 +525,15 @@ export const useTabbarStore = defineStore('core-tabbar', {
* @param tab
*/
async unpinTab(tab: TabDefinition) {
const index = this.tabs.findIndex(
(item) => getTabPath(item) === getTabPath(tab),
);
if (index !== -1) {
const oldTab = this.tabs[index];
tab.meta.affixTab = false;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
const index = this.tabs.findIndex((item) => equalTab(item, tab));
if (index === -1) {
return;
}
const oldTab = this.tabs[index];
tab.meta.affixTab = false;
tab.meta.title = oldTab?.meta?.title as string;
// this.addTab(tab);
this.tabs.splice(index, 1, tab);
// 过滤固定tabs,后面更改affixTabOrder的值的话可能会有问题,目前行464排序affixTabs没有设置值
const affixTabs = this.tabs.filter((tab) => isAffixTab(tab));
// 获得固定tabs的index,使用固定tabs的下一个位置也就是活动tabs的第一个位置
@@ -430,7 +541,6 @@ export const useTabbarStore = defineStore('core-tabbar', {
// 交换位置重新排序
await this.sortTabs(index, newIndex);
},
/**
* 根据当前打开的选项卡更新缓存
*/
@@ -454,12 +564,31 @@ export const useTabbarStore = defineStore('core-tabbar', {
}
this.cachedTabs = cacheMap;
},
/**
* 添加缓存的route
* @param component
* @param route
*/
addCachedRoute(component: VNode, route: RouteLocationNormalizedLoaded) {
const key = getTabKey(route);
if (this.cachedRoutes.has(key)) {
return;
}
this.cachedRoutes.set(key, {
key,
component: markRaw(component),
route: markRaw(route),
});
},
removeCachedRoute(key: string) {
this.cachedRoutes.delete(key);
},
},
getters: {
affixTabs(): TabDefinition[] {
const affixTabs = this.tabs.filter((tab) => isAffixTab(tab));
return affixTabs.sort((a, b) => {
return affixTabs.toSorted((a, b) => {
const orderA = (a.meta?.affixTabOrder ?? 0) as number;
const orderB = (b.meta?.affixTabOrder ?? 0) as number;
return orderA - orderB;
@@ -471,22 +600,58 @@ export const useTabbarStore = defineStore('core-tabbar', {
getExcludeCachedTabs(): string[] {
return [...this.excludeCachedTabs];
},
getMenuList(): string[] {
return this.menuList;
},
getTabs(): TabDefinition[] {
const normalTabs = this.tabs.filter((tab) => !isAffixTab(tab));
return [...this.affixTabs, ...normalTabs].filter(Boolean);
},
getCachedRoutes(): Map<string, RouteCached> {
return this.cachedRoutes;
},
},
persist: [
// tabs不需要保存在localStorage
{
pick: ['tabs'],
pick: ['tabs', 'visitHistory'],
storage: sessionStorage,
serializer: {
serialize: JSON.stringify,
deserialize(value: string) {
const parsed = JSON.parse(value);
// Stack 类实例经 JSON 序列化后会变成普通对象 {dedup, items, maxSize},
// 丢失所有方法和 getter,需要重新构建 Stack 实例
if (parsed.visitHistory && !(parsed.visitHistory instanceof Stack)) {
const raw = parsed.visitHistory;
const stack = createStack<string>(true, MAX_VISIT_HISTORY);
if (Array.isArray(raw.items)) {
stack.push(...raw.items);
}
parsed.visitHistory = stack;
}
return parsed;
},
},
},
],
state: (): TabbarState => ({
visitHistory: createStack<string>(true, MAX_VISIT_HISTORY),
cachedRoutes: new Map<string, RouteCached>(),
cachedTabs: new Set(),
dragEndIndex: 0,
excludeCachedTabs: new Set(),
menuList: [
'close',
'affix',
'maximize',
'reload',
'open-in-new-window',
'close-left',
'close-right',
'close-other',
'close-all',
],
renderRouteView: true,
tabs: [],
updateTime: Date.now(),
@@ -542,11 +707,56 @@ function isTabShown(tab: TabDefinition) {
}
/**
* @zh_CN 获取标签页路径
* 从route获取tab页的key
* @param tab
*/
function getTabPath(tab: RouteRecordNormalized | TabDefinition) {
return decodeURIComponent((tab as TabDefinition).fullPath || tab.path);
function getTabKey(tab: RouteLocationNormalized | RouteRecordNormalized) {
const {
fullPath,
path,
meta: { fullPathKey } = {},
query = {},
} = tab as RouteLocationNormalized;
// pageKey可能是数组(查询参数重复时可能出现)
const pageKey = Array.isArray(query.pageKey)
? query.pageKey[0]
: query.pageKey;
let rawKey;
if (pageKey) {
rawKey = pageKey;
} else {
rawKey = fullPathKey === false ? path : (fullPath ?? path);
}
try {
return decodeURIComponent(rawKey);
} catch {
return rawKey;
}
}
/**
* @zh_CN 是否开启访问历史记录
*/
function isVisitHistory() {
return preferences.tabbar.visitHistory;
}
/**
* 从tab获取tab页的key
* 如果tab没有key,那么就从route获取key
* @param tab
*/
function getTabKeyFromTab(tab: TabDefinition): string {
return tab.key ?? getTabKey(tab);
}
/**
* 比较两个tab是否相等
* @param a
* @param b
*/
function equalTab(a: TabDefinition, b: TabDefinition) {
return getTabKeyFromTab(a) === getTabKeyFromTab(b);
}
function routeToTab(route: RouteRecordNormalized) {
@@ -554,5 +764,8 @@ function routeToTab(route: RouteRecordNormalized) {
meta: route.meta,
name: route.name,
path: route.path,
key: getTabKey(route),
} as TabDefinition;
}
export { getTabKey };

View File

@@ -0,0 +1,132 @@
import { ref, unref } from 'vue';
import { DEFAULT_TIME_ZONE_OPTIONS } from '@vben-core/preferences';
import {
getCurrentTimezone,
setCurrentTimezone,
} from '@vben-core/shared/utils';
import { acceptHMRUpdate, defineStore } from 'pinia';
interface TimezoneHandler {
getTimezone?: () => Promise<null | string | undefined>;
getTimezoneOptions?: () => Promise<
{
label: string;
value: string;
}[]
>;
setTimezone?: (timezone: string) => Promise<void>;
}
/**
* 默认时区处理模块
* 时区存储基于pinia存储插件
*/
const getDefaultTimezoneHandler = (): TimezoneHandler => {
return {
getTimezoneOptions: () => {
return Promise.resolve(
DEFAULT_TIME_ZONE_OPTIONS.map((item) => {
return {
label: item.label,
value: item.timezone,
};
}),
);
},
};
};
/**
* 自定义时区处理模块
*/
let customTimezoneHandler: null | Partial<TimezoneHandler> = null;
const setTimezoneHandler = (handler: Partial<TimezoneHandler>) => {
customTimezoneHandler = handler;
};
/**
* 获取时区处理模块
*/
const getTimezoneHandler = () => {
return {
...getDefaultTimezoneHandler(),
...customTimezoneHandler,
};
};
/**
* timezone支持模块
*/
const useTimezoneStore = defineStore(
'core-timezone',
() => {
const timezoneRef = ref(getCurrentTimezone());
/**
* 初始化时区
* Initialize the timezone
*/
async function initTimezone() {
const timezoneHandler = getTimezoneHandler();
const timezone = await timezoneHandler.getTimezone?.();
if (timezone) {
timezoneRef.value = timezone;
}
// 设置dayjs默认时区
setCurrentTimezone(unref(timezoneRef));
}
/**
* 设置时区
* Set the timezone
* @param timezone 时区字符串
*/
async function setTimezone(timezone: string) {
const timezoneHandler = getTimezoneHandler();
await timezoneHandler.setTimezone?.(timezone);
timezoneRef.value = timezone;
// 设置dayjs默认时区
setCurrentTimezone(timezone);
}
/**
* 获取时区选项
* Get the timezone options
*/
async function getTimezoneOptions() {
const timezoneHandler = getTimezoneHandler();
return (await timezoneHandler.getTimezoneOptions?.()) || [];
}
initTimezone().catch((error) => {
console.error('Failed to initialize timezone during store setup:', error);
});
function $reset() {
timezoneRef.value = getCurrentTimezone();
}
return {
timezone: timezoneRef,
setTimezone,
getTimezoneOptions,
$reset,
};
},
{
persist: {
// 持久化
pick: ['timezone'],
},
},
);
export { setTimezoneHandler, useTimezoneStore };
// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
hot.accept(acceptHMRUpdate(useTimezoneStore, hot));
}

View File

@@ -1,3 +1,5 @@
import type { BasicUserInfo } from '@vben-core/typings';
import { acceptHMRUpdate, defineStore } from 'pinia';
interface BasicUserInfo {

View File

@@ -3,9 +3,32 @@ import type { Pinia } from 'pinia';
import type { App } from 'vue';
import { createPinia } from 'pinia';
import SecureLS from 'secure-ls';
let pinia: Pinia;
type SecureLSStorage = {
get(key: string): any;
set(key: string, value: unknown): void;
};
type SecureLSCtor = new (config?: {
encodingType?: string;
encryptionSecret?: string;
isCompression?: boolean;
metaKey?: string;
}) => SecureLSStorage;
const secureLSModule = SecureLS as unknown as {
default?: SecureLSCtor;
SecureLS?: SecureLSCtor;
};
const SecureLSConstructor =
secureLSModule.default ??
secureLSModule.SecureLS ??
(SecureLS as unknown as SecureLSCtor);
export interface InitStoreOptions {
/**
* @zh_CN 应用名,由于 @vben/stores 是公用的,后续可能有多个app,为了防止多个app缓存冲突,可在这里配置应用名,应用名将被用于持久化的前缀
@@ -20,11 +43,26 @@ export async function initStores(app: App, options: InitStoreOptions) {
const { createPersistedState } = await import('pinia-plugin-persistedstate');
pinia = createPinia();
const { namespace } = options;
const ls = new SecureLSConstructor({
encodingType: 'aes',
encryptionSecret: import.meta.env.VITE_APP_STORE_SECURE_KEY,
isCompression: true,
metaKey: `${namespace}-secure-meta`,
});
pinia.use(
createPersistedState({
// key $appName-$store.id
key: (storeKey) => `${namespace}-${storeKey}`,
storage: localStorage,
storage: import.meta.env.DEV
? localStorage
: {
getItem(key) {
return ls.get(key);
},
setItem(key, value) {
ls.set(key, value);
},
},
}),
);
app.use(pinia);