gengx
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
## layout
|
||||
|
||||
### header
|
||||
|
||||
- 支持N个自定义插槽,命名方式:header-right-n,header-left-n
|
||||
- header-left-n ,排序方式:0-19 ,breadcrumb 21-x
|
||||
- header-right-n ,排序方式:0-49,global-search,51-59,theme-toggle,61-69,language-toggle,71-79,fullscreen,81-89,notification,91-149,user-dropdown,151-x
|
||||
@@ -0,0 +1,176 @@
|
||||
import type { App } from 'vue';
|
||||
import type { NavigationGuard, NavigationHookAfter, Router } from 'vue-router';
|
||||
|
||||
import { createApp } from 'vue';
|
||||
|
||||
import { ELEMENT_ID_LAYOUT_SCROLL } from '@vben-core/shared/constants';
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { useLayoutScroll } from '../use-layout-scroll';
|
||||
|
||||
let activeApp: App | undefined;
|
||||
|
||||
function createRouterMock() {
|
||||
let afterHook: NavigationHookAfter | undefined;
|
||||
let beforeGuard: NavigationGuard | undefined;
|
||||
const removeAfterHook = vi.fn();
|
||||
const removeBeforeGuard = vi.fn();
|
||||
|
||||
const router = {
|
||||
afterEach: vi.fn((hook: NavigationHookAfter) => {
|
||||
afterHook = hook;
|
||||
return removeAfterHook;
|
||||
}),
|
||||
beforeEach: vi.fn((guard: NavigationGuard) => {
|
||||
beforeGuard = guard;
|
||||
return removeBeforeGuard;
|
||||
}),
|
||||
} as unknown as Router;
|
||||
|
||||
function getHooks() {
|
||||
if (!afterHook || !beforeGuard) {
|
||||
throw new Error('Router hooks were not registered');
|
||||
}
|
||||
return { afterHook, beforeGuard };
|
||||
}
|
||||
|
||||
return {
|
||||
getHooks,
|
||||
removeAfterHook,
|
||||
removeBeforeGuard,
|
||||
router,
|
||||
};
|
||||
}
|
||||
|
||||
function createScrollElement() {
|
||||
const element = document.createElement('div');
|
||||
element.id = ELEMENT_ID_LAYOUT_SCROLL;
|
||||
element.scrollTo = vi.fn();
|
||||
document.body.append(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
function mountLayoutScroll(router: Router) {
|
||||
const host = document.createElement('div');
|
||||
document.body.append(host);
|
||||
activeApp = createApp({
|
||||
setup() {
|
||||
useLayoutScroll(router);
|
||||
return () => null;
|
||||
},
|
||||
});
|
||||
activeApp.mount(host);
|
||||
}
|
||||
|
||||
async function runBeforeGuard(guard: NavigationGuard) {
|
||||
await guard({} as never, {} as never, vi.fn());
|
||||
}
|
||||
|
||||
async function runAfterHook(hook: NavigationHookAfter, hash = '') {
|
||||
await hook({ hash } as never, {} as never, undefined);
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
document.body.innerHTML = '';
|
||||
window.history.replaceState({}, '');
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('useLayoutScroll', () => {
|
||||
it('should scroll to top after a normal navigation', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
element.scrollTop = 240;
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook, beforeGuard } = routerMock.getHooks();
|
||||
|
||||
await runBeforeGuard(beforeGuard);
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
expect(element.scrollTo).toHaveBeenCalledWith({ top: 0 });
|
||||
});
|
||||
|
||||
it('should scroll a hash target into view', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
const hashTarget = document.createElement('div');
|
||||
hashTarget.id = 'section';
|
||||
hashTarget.scrollIntoView = vi.fn();
|
||||
element.append(hashTarget);
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook } = routerMock.getHooks();
|
||||
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook, '#section');
|
||||
|
||||
expect(hashTarget.scrollIntoView).toHaveBeenCalledWith({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
});
|
||||
expect(element.scrollTo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should ignore matching hash targets outside the layout', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const hostTarget = document.createElement('div');
|
||||
hostTarget.id = 'section';
|
||||
hostTarget.scrollIntoView = vi.fn();
|
||||
document.body.append(hostTarget);
|
||||
const element = createScrollElement();
|
||||
const layoutTarget = document.createElement('div');
|
||||
layoutTarget.id = 'section';
|
||||
layoutTarget.scrollIntoView = vi.fn();
|
||||
element.append(layoutTarget);
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook } = routerMock.getHooks();
|
||||
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook, '#section');
|
||||
|
||||
expect(layoutTarget.scrollIntoView).toHaveBeenCalledWith({
|
||||
behavior: 'smooth',
|
||||
block: 'start',
|
||||
});
|
||||
expect(hostTarget.scrollIntoView).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should restore a saved position on history navigation', async () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
const element = createScrollElement();
|
||||
element.scrollTop = 240;
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
const { afterHook, beforeGuard } = routerMock.getHooks();
|
||||
|
||||
await runBeforeGuard(beforeGuard);
|
||||
window.history.replaceState({ position: 1 }, '');
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
element.scrollTop = 80;
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
await runBeforeGuard(beforeGuard);
|
||||
await runAfterHook(afterHook);
|
||||
|
||||
expect(element.scrollTo).toHaveBeenLastCalledWith({ top: 240 });
|
||||
});
|
||||
|
||||
it('should remove router hooks when the scope is disposed', () => {
|
||||
window.history.replaceState({ position: 0 }, '');
|
||||
createScrollElement();
|
||||
const routerMock = createRouterMock();
|
||||
mountLayoutScroll(routerMock.router);
|
||||
|
||||
activeApp?.unmount();
|
||||
activeApp = undefined;
|
||||
|
||||
expect(routerMock.removeBeforeGuard).toHaveBeenCalledOnce();
|
||||
expect(routerMock.removeAfterHook).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
<script lang="ts" setup>
|
||||
import { VbenSpinner } from '@vben-core/shadcn-ui';
|
||||
|
||||
import { useContentSpinner } from './use-content-spinner';
|
||||
|
||||
defineOptions({ name: 'LayoutContentSpinner' });
|
||||
|
||||
const { spinning } = useContentSpinner();
|
||||
</script>
|
||||
<template>
|
||||
<VbenSpinner :spinning="spinning" />
|
||||
</template>
|
||||
@@ -0,0 +1,112 @@
|
||||
<script lang="ts" setup>
|
||||
import type { RouteLocationNormalizedLoadedGeneric } from 'vue-router';
|
||||
|
||||
import { unref } from 'vue';
|
||||
import { RouterView } from 'vue-router';
|
||||
|
||||
import { usePreferences } from '@vben/preferences';
|
||||
import { getTabKey, storeToRefs, useTabbarStore } from '@vben/stores';
|
||||
|
||||
import { transformComponent, useLayoutHook } from '../../hooks';
|
||||
import { IFrameRouterView } from '../../iframe';
|
||||
import { RouteCachedPage, RouteCachedView } from '../../route-cached';
|
||||
|
||||
defineOptions({ name: 'LayoutContent' });
|
||||
|
||||
const tabbarStore = useTabbarStore();
|
||||
const { keepAlive } = usePreferences();
|
||||
|
||||
const { getCachedTabs, getExcludeCachedTabs, renderRouteView } =
|
||||
storeToRefs(tabbarStore);
|
||||
|
||||
const { getEnabledTransition, getTransitionName } = useLayoutHook();
|
||||
|
||||
/**
|
||||
* 是否显示component
|
||||
* @param route
|
||||
*/
|
||||
const showComponent = (route: RouteLocationNormalizedLoadedGeneric) => {
|
||||
return !route.meta.domCached && unref(renderRouteView);
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-route-container relative h-full">
|
||||
<IFrameRouterView />
|
||||
<RouteCachedView />
|
||||
<RouterView v-slot="{ Component, route }">
|
||||
<RouteCachedPage
|
||||
:component="Component"
|
||||
:route="route"
|
||||
v-if="route.meta.domCached"
|
||||
/>
|
||||
<Transition
|
||||
v-if="getEnabledTransition"
|
||||
:name="getTransitionName(route)"
|
||||
appear
|
||||
:leave-active-class="`${getTransitionName(route)}-leave-active page-route-leave-active`"
|
||||
>
|
||||
<KeepAlive
|
||||
v-if="keepAlive"
|
||||
:exclude="getExcludeCachedTabs"
|
||||
:include="getCachedTabs"
|
||||
>
|
||||
<component
|
||||
:is="transformComponent(Component, route)"
|
||||
v-if="showComponent(route)"
|
||||
v-show="!route.meta.iframeSrc"
|
||||
:key="getTabKey(route)"
|
||||
/>
|
||||
</KeepAlive>
|
||||
<component
|
||||
:is="Component"
|
||||
v-else-if="showComponent(route)"
|
||||
:key="getTabKey(route)"
|
||||
/>
|
||||
</Transition>
|
||||
<template v-else>
|
||||
<KeepAlive
|
||||
v-if="keepAlive"
|
||||
:exclude="getExcludeCachedTabs"
|
||||
:include="getCachedTabs"
|
||||
>
|
||||
<component
|
||||
:is="transformComponent(Component, route)"
|
||||
v-if="showComponent(route)"
|
||||
v-show="!route.meta.iframeSrc"
|
||||
:key="getTabKey(route)"
|
||||
/>
|
||||
</KeepAlive>
|
||||
<component
|
||||
:is="Component"
|
||||
v-else-if="showComponent(route)"
|
||||
:key="getTabKey(route)"
|
||||
/>
|
||||
</template>
|
||||
</RouterView>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style>
|
||||
/* 优化router动画切换切换重叠问题 */
|
||||
.page-route-leave-active {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* 移除动画切换的横向滚动条 translateX(-30px) */
|
||||
.page-route-container:has(> .fade-slide-enter-active),
|
||||
.page-route-container:has(> .fade-slide-leave-active) {
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
/* 移除动画切换的纵向滚动条 */
|
||||
.page-route-container:has(> .fade-up-enter-active),
|
||||
.page-route-container:has(> .fade-up-leave-active),
|
||||
.page-route-container:has(> .fade-down-enter-active),
|
||||
.page-route-container:has(> .fade-down-leave-active) {
|
||||
overflow-y: hidden;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as LayoutContentSpinner } from './content-spinner.vue';
|
||||
export { default as LayoutContent } from './content.vue';
|
||||
@@ -0,0 +1,50 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { preferences } from '@vben/preferences';
|
||||
|
||||
function useContentSpinner() {
|
||||
const spinning = ref(false);
|
||||
const startTime = ref(0);
|
||||
const router = useRouter();
|
||||
const minShowTime = 500; // 最小显示时间
|
||||
const enableLoading = computed(() => preferences.transition.loading);
|
||||
|
||||
// 结束加载动画
|
||||
const onEnd = () => {
|
||||
if (!enableLoading.value) {
|
||||
return;
|
||||
}
|
||||
const processTime = performance.now() - startTime.value;
|
||||
if (processTime < minShowTime) {
|
||||
setTimeout(() => {
|
||||
spinning.value = false;
|
||||
}, minShowTime - processTime);
|
||||
} else {
|
||||
spinning.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// 路由前置守卫
|
||||
router.beforeEach((to) => {
|
||||
if (to.meta.loaded || !enableLoading.value || to.meta.iframeSrc) {
|
||||
return true;
|
||||
}
|
||||
startTime.value = performance.now();
|
||||
spinning.value = true;
|
||||
return true;
|
||||
});
|
||||
|
||||
// 路由后置守卫
|
||||
router.afterEach((to) => {
|
||||
if (to.meta.loaded || !enableLoading.value || to.meta.iframeSrc) {
|
||||
return true;
|
||||
}
|
||||
onEnd();
|
||||
return true;
|
||||
});
|
||||
|
||||
return { spinning };
|
||||
}
|
||||
|
||||
export { useContentSpinner };
|
||||
@@ -0,0 +1,49 @@
|
||||
<script lang="ts" setup>
|
||||
interface Props {
|
||||
companyName?: string;
|
||||
companySiteLink?: string;
|
||||
date?: string;
|
||||
icp?: string;
|
||||
icpLink?: string;
|
||||
}
|
||||
|
||||
defineOptions({
|
||||
name: 'Copyright',
|
||||
});
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
companyName: 'Vben Admin',
|
||||
companySiteLink: '',
|
||||
date: '2024',
|
||||
icp: '',
|
||||
icpLink: '',
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="text-md flex-center">
|
||||
<!-- ICP Link -->
|
||||
<a
|
||||
v-if="icp"
|
||||
:href="icpLink || 'https://beian.miit.gov.cn/'"
|
||||
class="mx-1 hover:text-primary-hover"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
{{ icp }}
|
||||
</a>
|
||||
|
||||
<!-- Copyright Text -->
|
||||
Copyright © {{ date }}
|
||||
|
||||
<!-- Company Link -->
|
||||
<a
|
||||
v-if="companyName"
|
||||
:href="companySiteLink || 'javascript:void(0)'"
|
||||
class="mx-1 hover:text-primary-hover"
|
||||
target="_blank"
|
||||
>
|
||||
{{ companyName }}
|
||||
</a>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Copyright } from './copyright.vue';
|
||||
@@ -0,0 +1,11 @@
|
||||
<script lang="ts" setup>
|
||||
defineOptions({
|
||||
name: 'LayoutFooter',
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative flex-center size-full text-xs text-muted-foreground">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as LayoutFooter } from './footer.vue';
|
||||
@@ -0,0 +1,408 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, useSlots } from 'vue';
|
||||
|
||||
import { useRefresh } from '@vben/hooks';
|
||||
import { LockKeyhole, LogOut, RotateCw } from '@vben/icons';
|
||||
import { $t } from '@vben/locales';
|
||||
import { preferences, usePreferences } from '@vben/preferences';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { useVbenModal } from '@vben-core/popup-ui';
|
||||
import {
|
||||
VbenFullScreen,
|
||||
VbenIconButton,
|
||||
VbenTooltip,
|
||||
} from '@vben-core/shadcn-ui';
|
||||
|
||||
import { useMagicKeys, whenever } from '@vueuse/core';
|
||||
|
||||
import {
|
||||
GlobalSearch,
|
||||
LanguageToggle,
|
||||
LockScreenModal,
|
||||
Notification,
|
||||
PreferencesButton,
|
||||
ThemeToggle,
|
||||
TimezoneButton,
|
||||
} from '../../widgets';
|
||||
|
||||
interface Props {
|
||||
/**
|
||||
* 头像
|
||||
*/
|
||||
avatar?: string;
|
||||
/**
|
||||
* Logo 主题
|
||||
*/
|
||||
theme?: string;
|
||||
/**
|
||||
* 用户文本
|
||||
*/
|
||||
text?: string;
|
||||
}
|
||||
|
||||
defineOptions({
|
||||
name: 'LayoutHeader',
|
||||
});
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
avatar: '',
|
||||
theme: 'light',
|
||||
text: '',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
clearPreferencesAndLogout: [];
|
||||
logout: [];
|
||||
openLockScreen: [];
|
||||
}>();
|
||||
|
||||
const REFERENCE_VALUE = 100;
|
||||
|
||||
const accessStore = useAccessStore();
|
||||
const {
|
||||
globalLockScreenShortcutKey,
|
||||
globalLogoutShortcutKey,
|
||||
globalSearchShortcutKey,
|
||||
preferencesButtonPosition,
|
||||
} = usePreferences();
|
||||
const slots = useSlots();
|
||||
const { refresh } = useRefresh();
|
||||
|
||||
const showLockInHeader = computed(
|
||||
() =>
|
||||
preferences.widget.lockScreen &&
|
||||
preferences.widget.lockScreenButtonPosition === 'header',
|
||||
);
|
||||
|
||||
const showLogoutInHeader = computed(
|
||||
() => preferences.widget.logoutButtonPosition === 'header',
|
||||
);
|
||||
|
||||
const enableLockScreenShortcutKey = computed(() => {
|
||||
return showLockInHeader.value && globalLockScreenShortcutKey.value;
|
||||
});
|
||||
|
||||
const enableLogoutShortcutKey = computed(() => {
|
||||
return showLogoutInHeader.value && globalLogoutShortcutKey.value;
|
||||
});
|
||||
|
||||
const [LockModal, lockModalApi] = useVbenModal({
|
||||
connectedComponent: LockScreenModal,
|
||||
});
|
||||
const [LogoutModal, logoutModalApi] = useVbenModal({
|
||||
onConfirm() {
|
||||
handleSubmitLogout();
|
||||
},
|
||||
});
|
||||
|
||||
function handleOpenLock() {
|
||||
lockModalApi.open();
|
||||
}
|
||||
|
||||
function handleSubmitLock(lockScreenPassword: string) {
|
||||
lockModalApi.close();
|
||||
accessStore.lockScreen(lockScreenPassword);
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
logoutModalApi.open();
|
||||
}
|
||||
|
||||
function handleSubmitLogout() {
|
||||
emit('logout');
|
||||
logoutModalApi.close();
|
||||
}
|
||||
|
||||
// 快捷键
|
||||
if (preferences.shortcutKeys.enable) {
|
||||
const keys = useMagicKeys();
|
||||
const lockKey = keys['Alt+KeyL'];
|
||||
const logoutKey = keys['Alt+KeyQ'];
|
||||
|
||||
if (lockKey) {
|
||||
whenever(lockKey, () => {
|
||||
if (enableLockScreenShortcutKey.value) {
|
||||
handleOpenLock();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (logoutKey) {
|
||||
whenever(logoutKey, () => {
|
||||
if (enableLogoutShortcutKey.value) {
|
||||
handleLogout();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 插槽列表类型
|
||||
*/
|
||||
type SlotItem = { index: number; name: string };
|
||||
|
||||
const rightSlots = computed(() => {
|
||||
const list: Array<SlotItem> = [];
|
||||
|
||||
// 按 widget.order 顺序遍历,检查每个部件是否应在 header 中显示
|
||||
const widgetChecks: Record<string, { slotName: string; visible: boolean }> = {
|
||||
globalSearch: {
|
||||
visible:
|
||||
preferences.widget.globalSearch &&
|
||||
preferences.widget.globalSearchButtonPosition === 'header',
|
||||
slotName: 'global-search',
|
||||
},
|
||||
preferences: {
|
||||
visible: preferencesButtonPosition.value.header,
|
||||
slotName: 'preferences',
|
||||
},
|
||||
themeToggle: {
|
||||
visible:
|
||||
preferences.widget.themeToggle &&
|
||||
preferences.widget.themeToggleButtonPosition === 'header',
|
||||
slotName: 'theme-toggle',
|
||||
},
|
||||
languageToggle: {
|
||||
visible:
|
||||
preferences.widget.languageToggle &&
|
||||
preferences.widget.languageToggleButtonPosition === 'header',
|
||||
slotName: 'language-toggle',
|
||||
},
|
||||
timezone: {
|
||||
visible:
|
||||
preferences.widget.timezone &&
|
||||
preferences.widget.timezoneButtonPosition === 'header',
|
||||
slotName: 'timezone',
|
||||
},
|
||||
fullscreen: {
|
||||
visible:
|
||||
preferences.widget.fullscreen &&
|
||||
preferences.widget.fullscreenButtonPosition === 'header',
|
||||
slotName: 'fullscreen',
|
||||
},
|
||||
refresh: {
|
||||
visible:
|
||||
preferences.widget.refresh &&
|
||||
preferences.widget.refreshButtonPosition === 'header',
|
||||
slotName: 'refresh',
|
||||
},
|
||||
notification: {
|
||||
visible:
|
||||
preferences.widget.notification &&
|
||||
preferences.widget.notificationButtonPosition === 'header',
|
||||
slotName: 'notification',
|
||||
},
|
||||
lockScreenBtn: {
|
||||
visible:
|
||||
preferences.widget.lockScreen &&
|
||||
preferences.widget.lockScreenButtonPosition === 'header',
|
||||
slotName: 'lock-screen-btn',
|
||||
},
|
||||
logoutBtn: {
|
||||
visible: preferences.widget.logoutButtonPosition === 'header',
|
||||
slotName: 'logout-btn',
|
||||
},
|
||||
};
|
||||
|
||||
for (const key of preferences.widget.order) {
|
||||
const check = widgetChecks[key];
|
||||
if (check?.visible) {
|
||||
list.push({ index: REFERENCE_VALUE + list.length, name: check.slotName });
|
||||
}
|
||||
}
|
||||
|
||||
// 用户插槽(header-right-N)追加在后面
|
||||
Object.keys(slots).forEach((key) => {
|
||||
if (key.startsWith('header-right')) {
|
||||
const slotIndex = Number(key.split('-')[2]);
|
||||
const index = Number.isNaN(slotIndex) ? nextIndex(list) : slotIndex;
|
||||
list.push({ index, name: key });
|
||||
}
|
||||
});
|
||||
// 最后追加用户下拉框,若是索引值超过1000时则固定在1000(适配用户按钮不在最后的场景)
|
||||
const userDropdownIndex = Math.min(1000, nextIndex(list));
|
||||
list.push({ index: userDropdownIndex, name: 'user-dropdown' });
|
||||
// 按照索引排序,保证插槽顺序
|
||||
return list.toSorted((a, b) => a.index - b.index);
|
||||
});
|
||||
|
||||
const leftSlots = computed(() => {
|
||||
const list: Array<SlotItem> = [];
|
||||
|
||||
Object.keys(slots).forEach((key) => {
|
||||
// 适配插槽名称,例如第一个插槽名:header-left-1
|
||||
if (key.startsWith('header-left')) {
|
||||
// 取第三个占位的数字,若是第三个占位不是数字,则自动分配排序索引
|
||||
const slotIndex = Number(key.split('-')[2]);
|
||||
const index = Number.isNaN(slotIndex) ? nextIndex(list) : slotIndex;
|
||||
list.push({ index, name: key });
|
||||
}
|
||||
});
|
||||
// 按照索引排序,保证插槽顺序
|
||||
return list.toSorted((a, b) => a.index - b.index);
|
||||
});
|
||||
|
||||
/**
|
||||
* 获取列表下一个索引值(用于排序)
|
||||
* @param list 列表
|
||||
*/
|
||||
function nextIndex(list: Array<SlotItem>) {
|
||||
const index =
|
||||
list.length > 0 ? Math.max(...list.map((item) => item.index)) : 0;
|
||||
return index + 1;
|
||||
}
|
||||
|
||||
function clearPreferencesAndLogout() {
|
||||
emit('clearPreferencesAndLogout');
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<LockModal
|
||||
v-if="showLockInHeader"
|
||||
:avatar="avatar"
|
||||
:text="text"
|
||||
@submit="handleSubmitLock"
|
||||
/>
|
||||
|
||||
<LogoutModal
|
||||
v-if="showLogoutInHeader"
|
||||
:cancel-text="$t('common.cancel')"
|
||||
:confirm-text="$t('common.confirm')"
|
||||
:fullscreen-button="false"
|
||||
:title="$t('common.prompt')"
|
||||
centered
|
||||
content-class="px-8 min-h-10"
|
||||
footer-class="border-none mb-3 mr-3"
|
||||
header-class="border-none"
|
||||
>
|
||||
{{ $t('ui.widgets.logoutTip') }}
|
||||
</LogoutModal>
|
||||
|
||||
<template
|
||||
v-for="slot in leftSlots.filter((item) => item.index < REFERENCE_VALUE)"
|
||||
:key="slot.name"
|
||||
>
|
||||
<slot :name="slot.name">
|
||||
<template v-if="slot.name === 'refresh'">
|
||||
<VbenIconButton class="my-0 mr-1 rounded-md" @click="refresh">
|
||||
<RotateCw class="size-4" />
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
</slot>
|
||||
</template>
|
||||
<div class="flex-center hidden lg:block">
|
||||
<slot name="breadcrumb"></slot>
|
||||
</div>
|
||||
<template
|
||||
v-for="slot in leftSlots.filter((item) => item.index > REFERENCE_VALUE)"
|
||||
:key="slot.name"
|
||||
>
|
||||
<slot :name="slot.name"></slot>
|
||||
</template>
|
||||
<div
|
||||
:class="`menu-align-${preferences.header.menuAlign}`"
|
||||
class="flex h-full min-w-0 flex-1 items-center"
|
||||
>
|
||||
<slot name="menu"></slot>
|
||||
</div>
|
||||
<div class="flex h-full min-w-0 shrink-0 items-center">
|
||||
<template v-for="slot in rightSlots" :key="slot.name">
|
||||
<slot :name="slot.name">
|
||||
<template v-if="slot.name === 'global-search'">
|
||||
<GlobalSearch
|
||||
:enable-shortcut-key="globalSearchShortcutKey"
|
||||
:menus="accessStore.accessMenus"
|
||||
class="mr-1 sm:mr-4"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else-if="slot.name === 'preferences'">
|
||||
<VbenTooltip side="bottom">
|
||||
<template #trigger>
|
||||
<PreferencesButton
|
||||
class="mr-1"
|
||||
@clear-preferences-and-logout="clearPreferencesAndLogout"
|
||||
/>
|
||||
</template>
|
||||
{{ $t('preferences.title') }}
|
||||
</VbenTooltip>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'theme-toggle'">
|
||||
<VbenTooltip side="bottom">
|
||||
<template #trigger>
|
||||
<ThemeToggle class="mt-0.5 mr-1" />
|
||||
</template>
|
||||
{{ $t('preferences.theme.title') }}
|
||||
</VbenTooltip>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'language-toggle'">
|
||||
<VbenTooltip side="bottom">
|
||||
<template #trigger>
|
||||
<LanguageToggle class="mr-1" />
|
||||
</template>
|
||||
{{ $t('preferences.widget.languageToggle') }}
|
||||
</VbenTooltip>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'fullscreen'">
|
||||
<VbenFullScreen
|
||||
class="mr-1"
|
||||
:tooltip="$t('preferences.widget.fullscreen')"
|
||||
/>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'timezone'">
|
||||
<TimezoneButton class="mt-0.5 mr-1" />
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'lock-screen-btn'">
|
||||
<VbenIconButton
|
||||
class="mr-1"
|
||||
:tooltip="$t('ui.widgets.lockScreen.title')"
|
||||
@click="handleOpenLock"
|
||||
>
|
||||
<LockKeyhole class="size-4" />
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'logout-btn'">
|
||||
<VbenIconButton
|
||||
class="mr-1"
|
||||
:tooltip="$t('common.logout')"
|
||||
@click="handleLogout"
|
||||
>
|
||||
<LogOut class="size-4" />
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'notification'">
|
||||
<VbenTooltip side="bottom">
|
||||
<template #trigger>
|
||||
<Notification class="mr-1" />
|
||||
</template>
|
||||
{{ $t('preferences.widget.notification') }}
|
||||
</VbenTooltip>
|
||||
</template>
|
||||
<template v-else-if="slot.name === 'refresh'">
|
||||
<VbenIconButton
|
||||
class="my-0 mr-1 rounded-md"
|
||||
:tooltip="$t('preferences.widget.refresh')"
|
||||
@click="refresh"
|
||||
>
|
||||
<RotateCw class="size-4" />
|
||||
</VbenIconButton>
|
||||
</template>
|
||||
</slot>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
<style lang="scss" scoped>
|
||||
.menu-align-start {
|
||||
--menu-align: start;
|
||||
}
|
||||
|
||||
.menu-align-center {
|
||||
--menu-align: center;
|
||||
}
|
||||
|
||||
.menu-align-end {
|
||||
--menu-align: end;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as LayoutHeader } from './header.vue';
|
||||
@@ -0,0 +1 @@
|
||||
export { default as BasicLayout } from './layout.vue';
|
||||
@@ -0,0 +1,479 @@
|
||||
<script lang="ts" setup>
|
||||
import type { SetupContext } from 'vue';
|
||||
import type { RouteLocationNormalizedLoaded } from 'vue-router';
|
||||
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import { computed, onMounted, useSlots, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { useRefresh } from '@vben/hooks';
|
||||
import { $t, i18n } from '@vben/locales';
|
||||
import {
|
||||
preferences,
|
||||
updatePreferences,
|
||||
usePreferences,
|
||||
} from '@vben/preferences';
|
||||
import { useAccessStore, useTabbarStore, useTimezoneStore } from '@vben/stores';
|
||||
import { cloneDeep, mapTree } from '@vben/utils';
|
||||
|
||||
import { VbenAdminLayout } from '@vben-core/layout-ui';
|
||||
import { VbenBackTop, VbenLogo } from '@vben-core/shadcn-ui';
|
||||
import { ELEMENT_ID_LAYOUT_SCROLL } from '@vben-core/shared/constants';
|
||||
|
||||
import { Breadcrumb, CheckUpdates, Preferences } from '../widgets';
|
||||
import { LayoutContent, LayoutContentSpinner } from './content';
|
||||
import { Copyright } from './copyright';
|
||||
import { LayoutFooter } from './footer';
|
||||
import { LayoutHeader } from './header';
|
||||
import {
|
||||
LayoutExtraMenu,
|
||||
LayoutMenu,
|
||||
LayoutMixedMenu,
|
||||
useExtraMenu,
|
||||
useMixedMenu,
|
||||
} from './menu';
|
||||
import { LayoutTabbar } from './tabbar';
|
||||
import { useLayoutScroll } from './use-layout-scroll';
|
||||
|
||||
defineOptions({ name: 'BasicLayout' });
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
avatar: '',
|
||||
text: '',
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
clearPreferencesAndLogout: [];
|
||||
clickLogo: [];
|
||||
logout: [];
|
||||
}>();
|
||||
|
||||
interface Props {
|
||||
avatar?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
const {
|
||||
isDark,
|
||||
isHeaderNav,
|
||||
isMixedNav,
|
||||
isMobile,
|
||||
isSideMode,
|
||||
isSideMixedNav,
|
||||
isHeaderMixedNav,
|
||||
isHeaderSidebarNav,
|
||||
layout,
|
||||
preferencesButtonPosition,
|
||||
sidebarCollapsed,
|
||||
theme,
|
||||
} = usePreferences();
|
||||
const accessStore = useAccessStore();
|
||||
const timezoneStore = useTimezoneStore();
|
||||
const { refresh } = useRefresh();
|
||||
const layoutScrollTarget = `#${ELEMENT_ID_LAYOUT_SCROLL}`;
|
||||
|
||||
useLayoutScroll();
|
||||
|
||||
const sidebarTheme = computed(() => {
|
||||
const dark = isDark.value || preferences.theme.semiDarkSidebar;
|
||||
return dark ? 'dark' : 'light';
|
||||
});
|
||||
|
||||
const sidebarThemeSub = computed(() => {
|
||||
const dark = isDark.value || preferences.theme.semiDarkSidebarSub;
|
||||
return dark ? 'dark' : 'light';
|
||||
});
|
||||
|
||||
const headerTheme = computed(() => {
|
||||
const dark = isDark.value || preferences.theme.semiDarkHeader;
|
||||
return dark ? 'dark' : 'light';
|
||||
});
|
||||
|
||||
const logoClass = computed(() => {
|
||||
const { collapsedShowTitle } = preferences.sidebar;
|
||||
const classes: string[] = [];
|
||||
|
||||
if (collapsedShowTitle && sidebarCollapsed.value && !isMixedNav.value) {
|
||||
classes.push('mx-auto');
|
||||
}
|
||||
|
||||
if (isSideMixedNav.value) {
|
||||
classes.push('flex-center');
|
||||
}
|
||||
|
||||
return classes.join(' ');
|
||||
});
|
||||
|
||||
const isMenuRounded = computed(() => {
|
||||
return preferences.navigation.styleType === 'rounded';
|
||||
});
|
||||
|
||||
const logoCollapsed = computed(() => {
|
||||
if (isMobile.value && sidebarCollapsed.value) {
|
||||
return true;
|
||||
}
|
||||
if (isHeaderNav.value || isMixedNav.value || isHeaderSidebarNav.value) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
sidebarCollapsed.value || isSideMixedNav.value || isHeaderMixedNav.value
|
||||
);
|
||||
});
|
||||
|
||||
const showHeaderNav = computed(() => {
|
||||
return (
|
||||
!isMobile.value &&
|
||||
(isHeaderNav.value || isMixedNav.value || isHeaderMixedNav.value)
|
||||
);
|
||||
});
|
||||
|
||||
const logoTheme = computed(() => {
|
||||
const showLogoInHeader =
|
||||
!isSideMode.value ||
|
||||
isHeaderSidebarNav.value ||
|
||||
isMixedNav.value ||
|
||||
isMobile.value;
|
||||
return showLogoInHeader ? headerTheme.value : sidebarTheme.value;
|
||||
});
|
||||
|
||||
/**
|
||||
* layout-sidebar扩展区域插槽extra-title的高度
|
||||
*/
|
||||
const sidebarExtraTitleHeight = computed<number | undefined>(() => {
|
||||
const showSideExtraTitle =
|
||||
preferences.logo.enable && preferences.logo.showText;
|
||||
return showSideExtraTitle ? undefined : 0;
|
||||
});
|
||||
|
||||
const {
|
||||
handleMenuSelect,
|
||||
handleMenuOpen,
|
||||
headerActive,
|
||||
headerMenus,
|
||||
sidebarActive,
|
||||
sidebarMenus,
|
||||
mixHeaderMenus,
|
||||
sidebarVisible,
|
||||
} = useMixedMenu();
|
||||
|
||||
// 侧边多列菜单
|
||||
const {
|
||||
extraActiveMenu,
|
||||
extraMenus,
|
||||
handleDefaultSelect,
|
||||
handleMenuMouseEnter,
|
||||
handleMixedMenuSelect,
|
||||
handleSideMouseLeave,
|
||||
sidebarExtraVisible,
|
||||
} = useExtraMenu(mixHeaderMenus);
|
||||
|
||||
/**
|
||||
* 包装菜单,翻译菜单名称
|
||||
* @param menus 原始菜单数据
|
||||
* @param deep 是否深度包装。对于双列布局,只需要包装第一层,因为更深层的数据会在扩展菜单中重新包装
|
||||
*/
|
||||
function wrapperMenus(menus: MenuRecordRaw[], deep: boolean = true) {
|
||||
return deep
|
||||
? mapTree(menus, (item) => {
|
||||
return { ...cloneDeep(item), name: $t(item.name) };
|
||||
})
|
||||
: menus.map((item) => {
|
||||
return { ...cloneDeep(item), name: $t(item.name) };
|
||||
});
|
||||
}
|
||||
|
||||
function toggleSidebar() {
|
||||
updatePreferences({
|
||||
sidebar: {
|
||||
hidden: !preferences.sidebar.hidden,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function clearPreferencesAndLogout() {
|
||||
emit('clearPreferencesAndLogout');
|
||||
}
|
||||
|
||||
function handleLogout() {
|
||||
emit('logout');
|
||||
}
|
||||
|
||||
function clickLogo() {
|
||||
emit('clickLogo');
|
||||
}
|
||||
|
||||
function autoCollapseMenuByRouteMeta(route: RouteLocationNormalizedLoaded) {
|
||||
// 只在双列模式下生效
|
||||
if (
|
||||
['header-mixed-nav', 'sidebar-mixed-nav'].includes(
|
||||
preferences.app.layout,
|
||||
) &&
|
||||
route.meta &&
|
||||
route.meta.hideInMenu
|
||||
) {
|
||||
sidebarExtraVisible.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
onMounted(() => {
|
||||
autoCollapseMenuByRouteMeta(route);
|
||||
});
|
||||
|
||||
watch(
|
||||
() => preferences.app.layout,
|
||||
async (val) => {
|
||||
if (val === 'sidebar-mixed-nav' && preferences.sidebar.hidden) {
|
||||
updatePreferences({
|
||||
sidebar: {
|
||||
hidden: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const tabbarStore = useTabbarStore();
|
||||
|
||||
function refreshAll() {
|
||||
tabbarStore.cachedTabs.clear();
|
||||
refresh();
|
||||
}
|
||||
|
||||
// 语言更新后,刷新页面
|
||||
// i18n.global.locale会在preference.app.locale变更之后才会更新,因此watchpreference.app.locale是不合适的,刷新页面时可能语言配置尚未完全加载完成
|
||||
watch(i18n.global.locale, refreshAll, { flush: 'post' });
|
||||
|
||||
// 时区更新后,刷新页面
|
||||
watch(() => timezoneStore.timezone, refreshAll, { flush: 'post' });
|
||||
|
||||
const slots: SetupContext['slots'] = useSlots();
|
||||
const headerSlots = computed(() => {
|
||||
return Object.keys(slots).filter((key) => key.startsWith('header-'));
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<VbenAdminLayout
|
||||
v-model:sidebar-extra-visible="sidebarExtraVisible"
|
||||
:content-compact="preferences.app.contentCompact"
|
||||
:content-compact-width="preferences.app.contentCompactWidth"
|
||||
:content-padding="preferences.app.contentPadding"
|
||||
:content-padding-bottom="preferences.app.contentPaddingBottom"
|
||||
:content-padding-left="preferences.app.contentPaddingLeft"
|
||||
:content-padding-right="preferences.app.contentPaddingRight"
|
||||
:content-padding-top="preferences.app.contentPaddingTop"
|
||||
:footer-enable="preferences.footer.enable"
|
||||
:footer-fixed="preferences.footer.fixed"
|
||||
:footer-height="preferences.footer.height"
|
||||
:header-height="preferences.header.height"
|
||||
:header-hidden="preferences.header.hidden"
|
||||
:header-mode="preferences.header.mode"
|
||||
:header-theme="headerTheme"
|
||||
:header-toggle-sidebar-button="preferences.widget.sidebarToggle"
|
||||
:header-visible="preferences.header.enable"
|
||||
:is-mobile="preferences.app.isMobile"
|
||||
:layout="layout"
|
||||
:sidebar-draggable="preferences.sidebar.draggable"
|
||||
:sidebar-collapse="preferences.sidebar.collapsed"
|
||||
:sidebar-collapse-show-title="preferences.sidebar.collapsedShowTitle"
|
||||
:sidebar-enable="sidebarVisible"
|
||||
:sidebar-collapsed-button="preferences.sidebar.collapsedButton"
|
||||
:sidebar-fixed-button="preferences.sidebar.fixedButton"
|
||||
:sidebar-expand-on-hover="preferences.sidebar.expandOnHover"
|
||||
:sidebar-extra-collapse="preferences.sidebar.extraCollapse"
|
||||
:sidebar-extra-collapsed-width="preferences.sidebar.extraCollapsedWidth"
|
||||
:sidebar-extra-title-height="sidebarExtraTitleHeight"
|
||||
:sidebar-hidden="preferences.sidebar.hidden"
|
||||
:sidebar-mixed-width="preferences.sidebar.mixedWidth"
|
||||
:sidebar-theme="sidebarTheme"
|
||||
:sidebar-theme-sub="sidebarThemeSub"
|
||||
:sidebar-width="preferences.sidebar.width"
|
||||
:side-collapse-width="preferences.sidebar.collapseWidth"
|
||||
:sidebar-logo-visible="preferences.logo.enable"
|
||||
:tabbar-enable="preferences.tabbar.enable"
|
||||
:tabbar-height="preferences.tabbar.height"
|
||||
:z-index="preferences.app.zIndex"
|
||||
@side-mouse-leave="handleSideMouseLeave"
|
||||
@toggle-sidebar="toggleSidebar"
|
||||
@update:sidebar-collapse="
|
||||
(value: boolean) => updatePreferences({ sidebar: { collapsed: value } })
|
||||
"
|
||||
@update:sidebar-enable="
|
||||
(value: boolean) => updatePreferences({ sidebar: { enable: value } })
|
||||
"
|
||||
@update:sidebar-expand-on-hover="
|
||||
(value: boolean) =>
|
||||
updatePreferences({ sidebar: { expandOnHover: value } })
|
||||
"
|
||||
@update:sidebar-extra-collapse="
|
||||
(value: boolean) =>
|
||||
updatePreferences({ sidebar: { extraCollapse: value } })
|
||||
"
|
||||
@update:sidebar-width="
|
||||
(value: number) => updatePreferences({ sidebar: { width: value } })
|
||||
"
|
||||
>
|
||||
<!-- logo -->
|
||||
<template #logo>
|
||||
<VbenLogo
|
||||
v-if="preferences.logo.enable"
|
||||
:fit="preferences.logo.fit"
|
||||
:class="logoClass"
|
||||
:collapsed="logoCollapsed"
|
||||
:src="preferences.logo.source"
|
||||
:src-dark="preferences.logo.sourceDark"
|
||||
:text="preferences.app.name"
|
||||
:show-text="preferences.logo.showText"
|
||||
:logo-mode="preferences.logo.logoMode"
|
||||
:full-logo-height="preferences.logo.fullLogoHeight"
|
||||
:theme="logoTheme"
|
||||
@click="clickLogo"
|
||||
>
|
||||
<template v-if="$slots['logo-text']" #text>
|
||||
<slot name="logo-text"></slot>
|
||||
</template>
|
||||
</VbenLogo>
|
||||
</template>
|
||||
<!-- 头部区域 -->
|
||||
<template #header>
|
||||
<LayoutHeader
|
||||
:avatar="avatar"
|
||||
:theme="theme"
|
||||
:text="text"
|
||||
@clear-preferences-and-logout="clearPreferencesAndLogout"
|
||||
@logout="handleLogout"
|
||||
>
|
||||
<template
|
||||
v-if="!showHeaderNav && preferences.breadcrumb.enable"
|
||||
#breadcrumb
|
||||
>
|
||||
<Breadcrumb
|
||||
:hide-when-only-one="preferences.breadcrumb.hideOnlyOne"
|
||||
:show-home="preferences.breadcrumb.showHome"
|
||||
:show-icon="preferences.breadcrumb.showIcon"
|
||||
:type="preferences.breadcrumb.styleType"
|
||||
/>
|
||||
</template>
|
||||
<template v-if="showHeaderNav" #menu>
|
||||
<LayoutMenu
|
||||
:default-active="headerActive"
|
||||
:menus="wrapperMenus(headerMenus)"
|
||||
:rounded="isMenuRounded"
|
||||
:theme="headerTheme"
|
||||
class="w-full"
|
||||
mode="horizontal"
|
||||
@select="handleMenuSelect"
|
||||
/>
|
||||
</template>
|
||||
<template #user-dropdown>
|
||||
<slot name="user-dropdown"></slot>
|
||||
</template>
|
||||
<template #notification>
|
||||
<slot name="notification"></slot>
|
||||
</template>
|
||||
<template v-for="item in headerSlots" #[item]>
|
||||
<slot :name="item"></slot>
|
||||
</template>
|
||||
</LayoutHeader>
|
||||
</template>
|
||||
<!-- 侧边菜单区域 -->
|
||||
<template #menu>
|
||||
<LayoutMenu
|
||||
:accordion="preferences.navigation.accordion"
|
||||
:collapse="preferences.sidebar.collapsed"
|
||||
:collapse-show-title="preferences.sidebar.collapsedShowTitle"
|
||||
:default-active="sidebarActive"
|
||||
:menus="wrapperMenus(sidebarMenus)"
|
||||
:rounded="isMenuRounded"
|
||||
:theme="sidebarTheme"
|
||||
mode="vertical"
|
||||
@open="handleMenuOpen"
|
||||
@select="handleMenuSelect"
|
||||
/>
|
||||
</template>
|
||||
<template #mixed-menu>
|
||||
<LayoutMixedMenu
|
||||
:active-path="extraActiveMenu"
|
||||
:menus="wrapperMenus(mixHeaderMenus, false)"
|
||||
:rounded="isMenuRounded"
|
||||
:theme="sidebarTheme"
|
||||
@default-select="handleDefaultSelect"
|
||||
@enter="handleMenuMouseEnter"
|
||||
@select="handleMixedMenuSelect"
|
||||
/>
|
||||
</template>
|
||||
<!-- 侧边额外区域 -->
|
||||
<template #side-extra>
|
||||
<LayoutExtraMenu
|
||||
:accordion="preferences.navigation.accordion"
|
||||
:collapse="preferences.sidebar.extraCollapse"
|
||||
:menus="wrapperMenus(extraMenus)"
|
||||
:rounded="isMenuRounded"
|
||||
:theme="sidebarThemeSub"
|
||||
/>
|
||||
</template>
|
||||
<template #side-extra-title>
|
||||
<VbenLogo
|
||||
v-if="preferences.logo.enable"
|
||||
:fit="preferences.logo.fit"
|
||||
:show-text="preferences.logo.showText"
|
||||
:text="preferences.app.name"
|
||||
:theme="sidebarThemeSub"
|
||||
>
|
||||
<template v-if="$slots['logo-text']" #text>
|
||||
<slot name="logo-text"></slot>
|
||||
</template>
|
||||
</VbenLogo>
|
||||
</template>
|
||||
|
||||
<template #tabbar>
|
||||
<LayoutTabbar
|
||||
v-if="preferences.tabbar.enable"
|
||||
:show-icon="preferences.tabbar.showIcon"
|
||||
:theme="theme"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- 主体内容 -->
|
||||
<template #content>
|
||||
<LayoutContent />
|
||||
</template>
|
||||
|
||||
<template v-if="preferences.transition.loading" #content-overlay>
|
||||
<LayoutContentSpinner />
|
||||
</template>
|
||||
|
||||
<!-- 页脚 -->
|
||||
<template v-if="preferences.footer.enable" #footer>
|
||||
<LayoutFooter>
|
||||
<Copyright
|
||||
v-if="preferences.copyright.enable"
|
||||
v-bind="preferences.copyright"
|
||||
/>
|
||||
</LayoutFooter>
|
||||
</template>
|
||||
|
||||
<template #extra>
|
||||
<slot name="extra"></slot>
|
||||
<CheckUpdates
|
||||
v-if="preferences.app.enableCheckUpdates"
|
||||
:check-updates-interval="preferences.app.checkUpdatesInterval"
|
||||
/>
|
||||
|
||||
<Transition v-if="preferences.widget.lockScreen" name="slide-up">
|
||||
<slot v-if="accessStore.isLockScreen" name="lock-screen"></slot>
|
||||
</Transition>
|
||||
|
||||
<template v-if="preferencesButtonPosition.fixed">
|
||||
<Preferences
|
||||
class="fixed top-1/2 right-0 z-100 -translate-y-1/2 transform"
|
||||
@clear-preferences-and-logout="clearPreferencesAndLogout"
|
||||
/>
|
||||
</template>
|
||||
<VbenBackTop :target="layoutScrollTarget" />
|
||||
</template>
|
||||
</VbenAdminLayout>
|
||||
</template>
|
||||
@@ -0,0 +1,41 @@
|
||||
<script lang="ts" setup>
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import type { MenuProps } from '@vben-core/menu-ui';
|
||||
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { Menu } from '@vben-core/menu-ui';
|
||||
|
||||
import { useNavigation } from './use-navigation';
|
||||
|
||||
interface Props extends MenuProps {
|
||||
collapse?: boolean;
|
||||
menus?: MenuRecordRaw[];
|
||||
}
|
||||
|
||||
withDefaults(defineProps<Props>(), {
|
||||
accordion: true,
|
||||
menus: () => [],
|
||||
});
|
||||
|
||||
const route = useRoute();
|
||||
const { navigation } = useNavigation();
|
||||
|
||||
async function handleSelect(key: string) {
|
||||
await navigation(key);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Menu
|
||||
:accordion="accordion"
|
||||
:collapse="collapse"
|
||||
:default-active="route.meta?.activePath || route.path"
|
||||
:menus="menus"
|
||||
:rounded="rounded"
|
||||
:theme="theme"
|
||||
mode="vertical"
|
||||
@select="handleSelect"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,5 @@
|
||||
export { default as LayoutExtraMenu } from './extra-menu.vue';
|
||||
export { default as LayoutMenu } from './menu.vue';
|
||||
export { default as LayoutMixedMenu } from './mixed-menu.vue';
|
||||
export * from './use-extra-menu';
|
||||
export * from './use-mixed-menu';
|
||||
@@ -0,0 +1,45 @@
|
||||
<script lang="ts" setup>
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import type { MenuProps } from '@vben-core/menu-ui';
|
||||
|
||||
import { Menu } from '@vben-core/menu-ui';
|
||||
|
||||
interface Props extends MenuProps {
|
||||
menus?: MenuRecordRaw[];
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
accordion: true,
|
||||
menus: () => [],
|
||||
});
|
||||
|
||||
const emit = defineEmits<{
|
||||
open: [string, string[]];
|
||||
select: [string, string?];
|
||||
}>();
|
||||
|
||||
function handleMenuSelect(key: string) {
|
||||
emit('select', key, props.mode);
|
||||
}
|
||||
|
||||
function handleMenuOpen(key: string, path: string[]) {
|
||||
emit('open', key, path);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Menu
|
||||
:accordion="accordion"
|
||||
:collapse="collapse"
|
||||
:collapse-show-title="collapseShowTitle"
|
||||
:default-active="defaultActive"
|
||||
:menus="menus"
|
||||
:mode="mode"
|
||||
:rounded="rounded"
|
||||
scroll-to-active
|
||||
:theme="theme"
|
||||
@open="handleMenuOpen"
|
||||
@select="handleMenuSelect"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,46 @@
|
||||
<script lang="ts" setup>
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import type { NormalMenuProps } from '@vben-core/menu-ui';
|
||||
|
||||
import { onBeforeMount } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { findMenuByPath } from '@vben/utils';
|
||||
|
||||
import { NormalMenu } from '@vben-core/menu-ui';
|
||||
|
||||
interface Props extends NormalMenuProps {}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
defaultSelect: [MenuRecordRaw, MenuRecordRaw?];
|
||||
enter: [MenuRecordRaw];
|
||||
select: [MenuRecordRaw];
|
||||
}>();
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
onBeforeMount(() => {
|
||||
const menu = findMenuByPath(props.menus || [], route.path);
|
||||
if (menu) {
|
||||
const rootMenu = (props.menus || []).find(
|
||||
(item) => item.path === menu.parents?.[0],
|
||||
);
|
||||
emit('defaultSelect', menu, rootMenu);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<NormalMenu
|
||||
:active-path="activePath"
|
||||
:collapse="collapse"
|
||||
:menus="menus"
|
||||
:rounded="rounded"
|
||||
:theme="theme"
|
||||
@enter="(menu) => emit('enter', menu)"
|
||||
@select="(menu) => emit('select', menu)"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { ComputedRef } from 'vue';
|
||||
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { findRootMenuByPath } from '@vben/utils';
|
||||
|
||||
import { useNavigation } from './use-navigation';
|
||||
|
||||
function useExtraMenu(useRootMenus?: ComputedRef<MenuRecordRaw[]>) {
|
||||
const accessStore = useAccessStore();
|
||||
const { navigation, willOpenedByWindow } = useNavigation();
|
||||
|
||||
const menus = computed(() => useRootMenus?.value ?? accessStore.accessMenus);
|
||||
|
||||
/** 记录当前顶级菜单下哪个子菜单最后激活 */
|
||||
const defaultSubMap = new Map<string, string>();
|
||||
const extraRootMenus = ref<MenuRecordRaw[]>([]);
|
||||
const route = useRoute();
|
||||
const extraMenus = ref<MenuRecordRaw[]>([]);
|
||||
const sidebarExtraVisible = ref<boolean>(false);
|
||||
const extraActiveMenu = ref('');
|
||||
const parentLevel = computed(() =>
|
||||
preferences.app.layout === 'header-mixed-nav' ? 1 : 0,
|
||||
);
|
||||
|
||||
/**
|
||||
* 选择混合菜单事件
|
||||
* @param menu
|
||||
*/
|
||||
const handleMixedMenuSelect = async (menu: MenuRecordRaw) => {
|
||||
const _extraMenus = menu?.children ?? [];
|
||||
const hasChildren = _extraMenus.length > 0;
|
||||
|
||||
if (!willOpenedByWindow(menu.path)) {
|
||||
extraMenus.value = _extraMenus ?? [];
|
||||
extraActiveMenu.value = menu.parents?.[parentLevel.value] ?? menu.path;
|
||||
sidebarExtraVisible.value = hasChildren;
|
||||
}
|
||||
|
||||
if (!hasChildren) {
|
||||
await navigation(menu.path);
|
||||
} else if (preferences.sidebar.autoActivateChild) {
|
||||
await navigation(
|
||||
defaultSubMap.has(menu.path)
|
||||
? (defaultSubMap.get(menu.path) as string)
|
||||
: menu.path,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 选择默认菜单事件
|
||||
* @param menu
|
||||
* @param rootMenu
|
||||
*/
|
||||
const handleDefaultSelect = async (
|
||||
menu: MenuRecordRaw,
|
||||
rootMenu?: MenuRecordRaw,
|
||||
) => {
|
||||
extraMenus.value = rootMenu?.children ?? extraRootMenus.value ?? [];
|
||||
extraActiveMenu.value = menu.parents?.[parentLevel.value] ?? menu.path;
|
||||
|
||||
if (preferences.sidebar.expandOnHover) {
|
||||
sidebarExtraVisible.value = extraMenus.value.length > 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 侧边菜单鼠标移出事件
|
||||
*/
|
||||
const handleSideMouseLeave = () => {
|
||||
if (preferences.sidebar.expandOnHover) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
|
||||
menus.value,
|
||||
route.path,
|
||||
);
|
||||
extraActiveMenu.value = rootMenuPath ?? findMenu?.path ?? '';
|
||||
extraMenus.value = rootMenu?.children ?? [];
|
||||
};
|
||||
|
||||
const handleMenuMouseEnter = (menu: MenuRecordRaw) => {
|
||||
if (!preferences.sidebar.expandOnHover) {
|
||||
const { findMenu } = findRootMenuByPath(menus.value, menu.path);
|
||||
extraMenus.value = findMenu?.children ?? [];
|
||||
extraActiveMenu.value = menu.parents?.[parentLevel.value] ?? menu.path;
|
||||
sidebarExtraVisible.value = extraMenus.value.length > 0;
|
||||
}
|
||||
};
|
||||
|
||||
function calcExtraMenus(path: string) {
|
||||
const currentPath = route.meta?.activePath || path;
|
||||
const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
|
||||
menus.value,
|
||||
currentPath,
|
||||
parentLevel.value,
|
||||
);
|
||||
extraRootMenus.value = rootMenu?.children ?? [];
|
||||
if (rootMenuPath) defaultSubMap.set(rootMenuPath, currentPath);
|
||||
extraActiveMenu.value = rootMenuPath ?? findMenu?.path ?? '';
|
||||
extraMenus.value = rootMenu?.children ?? [];
|
||||
if (preferences.sidebar.expandOnHover) {
|
||||
sidebarExtraVisible.value = extraMenus.value.length > 0;
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [route.path, preferences.app.layout],
|
||||
([path]) => {
|
||||
calcExtraMenus(path || '');
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
return {
|
||||
extraActiveMenu,
|
||||
extraMenus,
|
||||
handleDefaultSelect,
|
||||
handleMenuMouseEnter,
|
||||
handleMixedMenuSelect,
|
||||
handleSideMouseLeave,
|
||||
sidebarExtraVisible,
|
||||
};
|
||||
}
|
||||
|
||||
export { useExtraMenu };
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { MenuRecordRaw } from '@vben/types';
|
||||
|
||||
import { computed, onBeforeMount, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { preferences, usePreferences } from '@vben/preferences';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
import { findRootMenuByPath } from '@vben/utils';
|
||||
|
||||
import { useNavigation } from './use-navigation';
|
||||
|
||||
function useMixedMenu() {
|
||||
const { navigation, willOpenedByWindow } = useNavigation();
|
||||
const accessStore = useAccessStore();
|
||||
const route = useRoute();
|
||||
const splitSideMenus = ref<MenuRecordRaw[]>([]);
|
||||
const rootMenuPath = ref<string>('');
|
||||
const mixedRootMenuPath = ref<string>('');
|
||||
const mixExtraMenus = ref<MenuRecordRaw[]>([]);
|
||||
/** 记录当前顶级菜单下哪个子菜单最后激活 */
|
||||
const defaultSubMap = new Map<string, string>();
|
||||
const { isMixedNav, isHeaderMixedNav, isMobile } = usePreferences();
|
||||
|
||||
const needSplit = computed(
|
||||
() =>
|
||||
!isMobile.value &&
|
||||
((preferences.navigation.split && isMixedNav.value) ||
|
||||
isHeaderMixedNav.value),
|
||||
);
|
||||
|
||||
const sidebarVisible = computed(() => {
|
||||
const enableSidebar = preferences.sidebar.enable;
|
||||
if (needSplit.value) {
|
||||
return enableSidebar && splitSideMenus.value.length > 0;
|
||||
}
|
||||
return enableSidebar;
|
||||
});
|
||||
const menus = computed(() => accessStore.accessMenus);
|
||||
|
||||
/**
|
||||
* 头部菜单
|
||||
*/
|
||||
const headerMenus = computed(() => {
|
||||
if (!needSplit.value) {
|
||||
return menus.value;
|
||||
}
|
||||
return menus.value.map((item) => {
|
||||
return {
|
||||
...item,
|
||||
children: [],
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 侧边菜单
|
||||
*/
|
||||
const sidebarMenus = computed(() => {
|
||||
return needSplit.value ? splitSideMenus.value : menus.value;
|
||||
});
|
||||
|
||||
const mixHeaderMenus = computed(() => {
|
||||
return isHeaderMixedNav.value ? sidebarMenus.value : headerMenus.value;
|
||||
});
|
||||
|
||||
/**
|
||||
* 侧边菜单激活路径
|
||||
*/
|
||||
const sidebarActive = computed(() => {
|
||||
return (route?.meta?.activePath as string) ?? route.path;
|
||||
});
|
||||
|
||||
/**
|
||||
* 头部菜单激活路径
|
||||
*/
|
||||
const headerActive = computed(() => {
|
||||
if (!needSplit.value) {
|
||||
return route.meta?.activePath ?? route.path;
|
||||
}
|
||||
return rootMenuPath.value;
|
||||
});
|
||||
|
||||
/**
|
||||
* 菜单点击事件处理
|
||||
* @param key 菜单路径
|
||||
* @param mode 菜单模式
|
||||
*/
|
||||
const handleMenuSelect = (key: string, mode?: string) => {
|
||||
if (!needSplit.value || mode === 'vertical') {
|
||||
navigation(key);
|
||||
return;
|
||||
}
|
||||
const rootMenu = menus.value.find((item) => item.path === key);
|
||||
const _splitSideMenus = rootMenu?.children ?? [];
|
||||
|
||||
if (!willOpenedByWindow(key)) {
|
||||
rootMenuPath.value = rootMenu?.path ?? '';
|
||||
splitSideMenus.value = _splitSideMenus;
|
||||
}
|
||||
|
||||
if (_splitSideMenus.length === 0) {
|
||||
navigation(key);
|
||||
} else if (rootMenu && preferences.sidebar.autoActivateChild) {
|
||||
navigation(
|
||||
defaultSubMap.has(rootMenu.path)
|
||||
? (defaultSubMap.get(rootMenu.path) as string)
|
||||
: rootMenu.path,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 侧边菜单展开事件
|
||||
* @param key 路由路径
|
||||
* @param parentsPath 父级路径
|
||||
*/
|
||||
const handleMenuOpen = (key: string, parentsPath: string[]) => {
|
||||
if (parentsPath.length <= 1 && preferences.sidebar.autoActivateChild) {
|
||||
navigation(
|
||||
defaultSubMap.has(key) ? (defaultSubMap.get(key) as string) : key,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 计算侧边菜单
|
||||
* @param path 路由路径
|
||||
*/
|
||||
function calcSideMenus(path: string = route.path) {
|
||||
let { rootMenu } = findRootMenuByPath(menus.value, path);
|
||||
if (!rootMenu) {
|
||||
rootMenu = menus.value.find((item) => item.path === path);
|
||||
}
|
||||
const result = findRootMenuByPath(rootMenu?.children || [], path, 1);
|
||||
mixedRootMenuPath.value = result.rootMenuPath ?? '';
|
||||
mixExtraMenus.value = result.rootMenu?.children ?? [];
|
||||
rootMenuPath.value = rootMenu?.path ?? '';
|
||||
splitSideMenus.value = rootMenu?.children ?? [];
|
||||
}
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
(path) => {
|
||||
const currentPath = route?.meta?.activePath ?? route?.meta?.link ?? path;
|
||||
if (willOpenedByWindow(currentPath)) {
|
||||
return;
|
||||
}
|
||||
calcSideMenus(currentPath);
|
||||
if (rootMenuPath.value)
|
||||
defaultSubMap.set(rootMenuPath.value, currentPath);
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
// 初始化计算侧边菜单
|
||||
onBeforeMount(() => {
|
||||
calcSideMenus(route.meta?.activePath || route.path);
|
||||
});
|
||||
|
||||
return {
|
||||
handleMenuSelect,
|
||||
handleMenuOpen,
|
||||
headerActive,
|
||||
headerMenus,
|
||||
sidebarActive,
|
||||
sidebarMenus,
|
||||
mixHeaderMenus,
|
||||
mixExtraMenus,
|
||||
sidebarVisible,
|
||||
};
|
||||
}
|
||||
|
||||
export { useMixedMenu };
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { RouteRecordNormalized } from 'vue-router';
|
||||
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { isHttpUrl, openRouteInNewWindow, openWindow } from '@vben/utils';
|
||||
|
||||
function useNavigation() {
|
||||
const router = useRouter();
|
||||
const routeMetaMap = new Map<string, RouteRecordNormalized>();
|
||||
|
||||
// 初始化路由映射
|
||||
const initRouteMetaMap = () => {
|
||||
const routes = router.getRoutes();
|
||||
routes.forEach((route) => {
|
||||
routeMetaMap.set(route.path, route);
|
||||
});
|
||||
};
|
||||
|
||||
initRouteMetaMap();
|
||||
|
||||
// 监听路由变化
|
||||
router.afterEach(() => {
|
||||
initRouteMetaMap();
|
||||
});
|
||||
|
||||
// 检查是否应该在新窗口打开
|
||||
const shouldOpenInNewWindow = (path: string): boolean => {
|
||||
if (isHttpUrl(path)) {
|
||||
return true;
|
||||
}
|
||||
const route = routeMetaMap.get(path);
|
||||
// 如果有外链或者设置了在新窗口打开,返回 true
|
||||
return !!(route?.meta?.link || route?.meta?.openInNewWindow);
|
||||
};
|
||||
|
||||
const resolveHref = (path: string): string => {
|
||||
return router.resolve(path).href;
|
||||
};
|
||||
|
||||
const navigation = async (path: string) => {
|
||||
try {
|
||||
const route = routeMetaMap.get(path);
|
||||
const { openInNewWindow = false, query = {}, link } = route?.meta ?? {};
|
||||
|
||||
// 检查是否有外链
|
||||
if (link && typeof link === 'string') {
|
||||
openWindow(link, { target: '_blank' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (isHttpUrl(path)) {
|
||||
openWindow(path, { target: '_blank' });
|
||||
} else if (openInNewWindow) {
|
||||
openRouteInNewWindow(resolveHref(path));
|
||||
} else {
|
||||
await router.push({
|
||||
path,
|
||||
query,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Navigation failed:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const willOpenedByWindow = (path: string) => {
|
||||
return shouldOpenInNewWindow(path);
|
||||
};
|
||||
|
||||
return { navigation, willOpenedByWindow };
|
||||
}
|
||||
|
||||
export { useNavigation };
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as LayoutTabbar } from './tabbar.vue';
|
||||
export * from './use-tabbar';
|
||||
@@ -0,0 +1,84 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
|
||||
import { useContentMaximize, useTabs } from '@vben/hooks';
|
||||
import { preferences } from '@vben/preferences';
|
||||
import { useTabbarStore } from '@vben/stores';
|
||||
|
||||
import {
|
||||
TabsToolMore,
|
||||
TabsToolRefresh,
|
||||
TabsToolScreen,
|
||||
TabsView,
|
||||
} from '@vben-core/tabs-ui';
|
||||
|
||||
import { useTabbar } from './use-tabbar';
|
||||
|
||||
defineOptions({
|
||||
name: 'LayoutTabbar',
|
||||
});
|
||||
|
||||
defineProps<{ showIcon?: boolean; theme?: string }>();
|
||||
|
||||
const route = useRoute();
|
||||
const tabbarStore = useTabbarStore();
|
||||
const { contentIsMaximize, toggleMaximize } = useContentMaximize();
|
||||
const { refreshTab, unpinTab } = useTabs();
|
||||
|
||||
const {
|
||||
createContextMenus,
|
||||
currentActive,
|
||||
currentTabs,
|
||||
handleClick,
|
||||
handleClose,
|
||||
} = useTabbar();
|
||||
|
||||
const menus = computed(() => {
|
||||
const tab = tabbarStore.getTabByKey(currentActive.value);
|
||||
const menus = createContextMenus(tab);
|
||||
return menus.map((item) => {
|
||||
return {
|
||||
...item,
|
||||
label: item.text,
|
||||
value: item.key,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
// 刷新后如果不保持tab状态,关闭其他tab
|
||||
if (!preferences.tabbar.persist) {
|
||||
tabbarStore.closeOtherTabs(route);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TabsView
|
||||
:active="currentActive"
|
||||
:class="theme"
|
||||
:context-menus="createContextMenus"
|
||||
:draggable="preferences.tabbar.draggable"
|
||||
:show-icon="showIcon"
|
||||
:style-type="preferences.tabbar.styleType"
|
||||
:tabs="currentTabs"
|
||||
:wheelable="preferences.tabbar.wheelable"
|
||||
:middle-click-to-close="preferences.tabbar.middleClickToClose"
|
||||
@close="handleClose"
|
||||
@sort-tabs="tabbarStore.sortTabs"
|
||||
@unpin="unpinTab"
|
||||
@update:active="handleClick"
|
||||
/>
|
||||
<div class="flex-center h-full">
|
||||
<TabsToolMore v-if="preferences.tabbar.showMore" :menus="menus" />
|
||||
<TabsToolRefresh
|
||||
v-if="preferences.tabbar.showRefresh"
|
||||
@refresh="refreshTab"
|
||||
/>
|
||||
<TabsToolScreen
|
||||
v-if="preferences.tabbar.showMaximize"
|
||||
:screen="contentIsMaximize"
|
||||
@change="toggleMaximize"
|
||||
@update:screen="toggleMaximize"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,227 @@
|
||||
import type { RouteLocationNormalizedGeneric } from 'vue-router';
|
||||
|
||||
import type { TabDefinition } from '@vben/types';
|
||||
|
||||
import type { IContextMenuItem } from '@vben-core/tabs-ui';
|
||||
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
|
||||
import { useContentMaximize, useTabs } from '@vben/hooks';
|
||||
import {
|
||||
ArrowLeftToLine,
|
||||
ArrowRightLeft,
|
||||
ArrowRightToLine,
|
||||
ExternalLink,
|
||||
FoldHorizontal,
|
||||
Fullscreen,
|
||||
Minimize2,
|
||||
Pin,
|
||||
PinOff,
|
||||
RotateCw,
|
||||
X,
|
||||
} from '@vben/icons';
|
||||
import { $t, useI18n } from '@vben/locales';
|
||||
import { getTabKey, useAccessStore, useTabbarStore } from '@vben/stores';
|
||||
import { filterTree } from '@vben/utils';
|
||||
|
||||
export function useTabbar() {
|
||||
const router = useRouter();
|
||||
const route = useRoute();
|
||||
const accessStore = useAccessStore();
|
||||
const tabbarStore = useTabbarStore();
|
||||
const { contentIsMaximize, toggleMaximize } = useContentMaximize();
|
||||
const {
|
||||
closeAllTabs,
|
||||
closeCurrentTab,
|
||||
closeLeftTabs,
|
||||
closeOtherTabs,
|
||||
closeRightTabs,
|
||||
closeTabByKey,
|
||||
getTabDisableState,
|
||||
openTabInNewWindow,
|
||||
refreshTab,
|
||||
toggleTabPin,
|
||||
} = useTabs();
|
||||
|
||||
/**
|
||||
* 当前路径对应的tab的key
|
||||
*/
|
||||
const currentActive = computed(() => {
|
||||
return getTabKey(route);
|
||||
});
|
||||
|
||||
const { locale } = useI18n();
|
||||
const currentTabs = ref<RouteLocationNormalizedGeneric[]>();
|
||||
watch(
|
||||
[
|
||||
() => tabbarStore.getTabs,
|
||||
() => tabbarStore.updateTime,
|
||||
() => locale.value,
|
||||
],
|
||||
([tabs]) => {
|
||||
currentTabs.value = tabs.map((item) => wrapperTabLocale(item));
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 初始化固定标签页
|
||||
*/
|
||||
const initAffixTabs = () => {
|
||||
const affixTabs = filterTree(router.getRoutes(), (route) => {
|
||||
return !!route.meta?.affixTab;
|
||||
});
|
||||
tabbarStore.setAffixTabs(affixTabs);
|
||||
};
|
||||
|
||||
// 点击tab,跳转路由
|
||||
const handleClick = (key: string) => {
|
||||
const { fullPath, path } = tabbarStore.getTabByKey(key);
|
||||
router.push(fullPath || path);
|
||||
};
|
||||
|
||||
// 关闭tab
|
||||
const handleClose = async (key: string) => {
|
||||
await closeTabByKey(key);
|
||||
};
|
||||
|
||||
function wrapperTabLocale(tab: RouteLocationNormalizedGeneric) {
|
||||
return {
|
||||
...tab,
|
||||
meta: {
|
||||
...tab?.meta,
|
||||
title: $t(tab?.meta?.title as string),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
watch(
|
||||
() => accessStore.accessMenus,
|
||||
() => {
|
||||
initAffixTabs();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(
|
||||
() => route.fullPath,
|
||||
() => {
|
||||
const meta = route.matched?.[route.matched.length - 1]?.meta;
|
||||
tabbarStore.addTab({
|
||||
...route,
|
||||
meta: meta || route.meta,
|
||||
});
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const createContextMenus = (tab: TabDefinition) => {
|
||||
const {
|
||||
disabledCloseAll,
|
||||
disabledCloseCurrent,
|
||||
disabledCloseLeft,
|
||||
disabledCloseOther,
|
||||
disabledCloseRight,
|
||||
disabledRefresh,
|
||||
} = getTabDisableState(tab);
|
||||
|
||||
const affixTab = tab?.meta?.affixTab ?? false;
|
||||
|
||||
const menus: IContextMenuItem[] = [
|
||||
{
|
||||
disabled: disabledCloseCurrent,
|
||||
handler: async () => {
|
||||
await closeCurrentTab(tab);
|
||||
},
|
||||
icon: X,
|
||||
key: 'close',
|
||||
text: $t('preferences.tabbar.contextMenu.close'),
|
||||
},
|
||||
{
|
||||
handler: async () => {
|
||||
await toggleTabPin(tab);
|
||||
},
|
||||
icon: affixTab ? PinOff : Pin,
|
||||
key: 'affix',
|
||||
text: affixTab
|
||||
? $t('preferences.tabbar.contextMenu.unpin')
|
||||
: $t('preferences.tabbar.contextMenu.pin'),
|
||||
},
|
||||
{
|
||||
handler: async () => {
|
||||
if (!contentIsMaximize.value) {
|
||||
await router.push(tab.fullPath);
|
||||
}
|
||||
toggleMaximize();
|
||||
},
|
||||
icon: contentIsMaximize.value ? Minimize2 : Fullscreen,
|
||||
key: contentIsMaximize.value ? 'restore-maximize' : 'maximize',
|
||||
text: contentIsMaximize.value
|
||||
? $t('preferences.tabbar.contextMenu.restoreMaximize')
|
||||
: $t('preferences.tabbar.contextMenu.maximize'),
|
||||
},
|
||||
{
|
||||
disabled: disabledRefresh,
|
||||
handler: () => refreshTab(),
|
||||
icon: RotateCw,
|
||||
key: 'reload',
|
||||
text: $t('preferences.tabbar.contextMenu.reload'),
|
||||
},
|
||||
{
|
||||
handler: async () => {
|
||||
await openTabInNewWindow(tab);
|
||||
},
|
||||
icon: ExternalLink,
|
||||
key: 'open-in-new-window',
|
||||
separator: true,
|
||||
text: $t('preferences.tabbar.contextMenu.openInNewWindow'),
|
||||
},
|
||||
|
||||
{
|
||||
disabled: disabledCloseLeft,
|
||||
handler: async () => {
|
||||
await closeLeftTabs(tab);
|
||||
},
|
||||
icon: ArrowLeftToLine,
|
||||
key: 'close-left',
|
||||
text: $t('preferences.tabbar.contextMenu.closeLeft'),
|
||||
},
|
||||
{
|
||||
disabled: disabledCloseRight,
|
||||
handler: async () => {
|
||||
await closeRightTabs(tab);
|
||||
},
|
||||
icon: ArrowRightToLine,
|
||||
key: 'close-right',
|
||||
separator: true,
|
||||
text: $t('preferences.tabbar.contextMenu.closeRight'),
|
||||
},
|
||||
{
|
||||
disabled: disabledCloseOther,
|
||||
handler: async () => {
|
||||
await closeOtherTabs(tab);
|
||||
},
|
||||
icon: FoldHorizontal,
|
||||
key: 'close-other',
|
||||
text: $t('preferences.tabbar.contextMenu.closeOther'),
|
||||
},
|
||||
{
|
||||
disabled: disabledCloseAll,
|
||||
handler: closeAllTabs,
|
||||
icon: ArrowRightLeft,
|
||||
key: 'close-all',
|
||||
text: $t('preferences.tabbar.contextMenu.closeAll'),
|
||||
},
|
||||
];
|
||||
|
||||
return menus.filter((item) => tabbarStore.getMenuList.includes(item.key));
|
||||
};
|
||||
|
||||
return {
|
||||
createContextMenus,
|
||||
currentActive,
|
||||
currentTabs,
|
||||
handleClick,
|
||||
handleClose,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Router } from 'vue-router';
|
||||
|
||||
import { nextTick, onScopeDispose } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { getLayoutScrollElement } from '@vben-core/shared/utils';
|
||||
|
||||
type LayoutScrollRouter = Pick<Router, 'afterEach' | 'beforeEach'>;
|
||||
|
||||
function getHistoryPosition() {
|
||||
if (typeof window === 'undefined') {
|
||||
return undefined;
|
||||
}
|
||||
const position = (window.history.state as null | { position?: unknown })
|
||||
?.position;
|
||||
return typeof position === 'number' ? position : undefined;
|
||||
}
|
||||
|
||||
function getHashTarget(scrollElement: HTMLElement, hash: string) {
|
||||
if (!hash.startsWith('#')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = hash.slice(1);
|
||||
try {
|
||||
return scrollElement.querySelector<HTMLElement>(
|
||||
`#${CSS.escape(decodeURIComponent(id))}`,
|
||||
);
|
||||
} catch {
|
||||
return scrollElement.querySelector<HTMLElement>(`#${CSS.escape(id)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function useLayoutScroll(router: LayoutScrollRouter = useRouter()) {
|
||||
const scrollPositions = new Map<number, number>();
|
||||
let currentHistoryPosition = getHistoryPosition();
|
||||
let isHistoryNavigation = false;
|
||||
|
||||
const removeBeforeGuard = router.beforeEach(() => {
|
||||
const scrollElement = getLayoutScrollElement();
|
||||
if (scrollElement && currentHistoryPosition !== undefined) {
|
||||
scrollPositions.set(currentHistoryPosition, scrollElement.scrollTop);
|
||||
}
|
||||
|
||||
const nextHistoryPosition = getHistoryPosition();
|
||||
isHistoryNavigation =
|
||||
currentHistoryPosition !== undefined &&
|
||||
nextHistoryPosition !== undefined &&
|
||||
currentHistoryPosition !== nextHistoryPosition;
|
||||
});
|
||||
|
||||
const removeAfterHook = router.afterEach(async (to, _from, failure) => {
|
||||
const nextHistoryPosition = getHistoryPosition();
|
||||
|
||||
if (!failure) {
|
||||
await nextTick();
|
||||
const scrollElement = getLayoutScrollElement();
|
||||
if (scrollElement) {
|
||||
const savedPosition =
|
||||
isHistoryNavigation && nextHistoryPosition !== undefined
|
||||
? scrollPositions.get(nextHistoryPosition)
|
||||
: undefined;
|
||||
|
||||
if (savedPosition === undefined) {
|
||||
const hashTarget = getHashTarget(scrollElement, to.hash);
|
||||
if (hashTarget) {
|
||||
hashTarget.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
} else {
|
||||
scrollElement.scrollTo({ top: 0 });
|
||||
}
|
||||
} else {
|
||||
scrollElement.scrollTo({ top: savedPosition });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
currentHistoryPosition = nextHistoryPosition;
|
||||
isHistoryNavigation = false;
|
||||
});
|
||||
|
||||
onScopeDispose(() => {
|
||||
removeBeforeGuard();
|
||||
removeAfterHook();
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user