mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-20 02:03:35 +08:00
feat: enhance menu tags, breadcrumbs, and useMenu
Add configurable tab controls, breadcrumb icons, and interactive useMenu examples. Batch pointer updates per frame and scope writes to the tab cache.
This commit is contained in:
parent
94c2e6cdb6
commit
c2019b10e6
102
__test__/hooks/useMenu.spec.tsx
Normal file
102
__test__/hooks/useMenu.spec.tsx
Normal file
@ -0,0 +1,102 @@
|
||||
import { useMenu } from '@ray-template/composables/useMenu'
|
||||
import type { UseMenuOptions } from '@ray-template/composables/useMenu'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { NMenu } from 'naive-ui'
|
||||
import { defineComponent, nextTick } from 'vue'
|
||||
|
||||
const daily = { key: 2, label: 'Daily' }
|
||||
const options = [
|
||||
{ key: 'home', label: 'Home' },
|
||||
{ key: 1, label: 'Reports', children: [daily] },
|
||||
]
|
||||
|
||||
const mountMenu = (initial: UseMenuOptions) => {
|
||||
const menu = useMenu(initial)
|
||||
const wrapper = mount(
|
||||
defineComponent({
|
||||
setup: () => () => <NMenu ref={menu.menuRef} {...menu.menuProps} />,
|
||||
}),
|
||||
)
|
||||
const select = (label: string) =>
|
||||
wrapper
|
||||
.findAll('.n-menu-item-content')
|
||||
.find((row) => row.text() === label)!
|
||||
.trigger('click')
|
||||
|
||||
return { ...menu, wrapper, select }
|
||||
}
|
||||
|
||||
it('updates controlled selection and expansion before notifying native callbacks', async () => {
|
||||
const onValue = vi.fn(() => menu.menuProps.value)
|
||||
const onExpanded = vi.fn(() => menu.menuProps.expandedKeys)
|
||||
const onExpandedAlias = vi.fn()
|
||||
const menu = mountMenu({
|
||||
options,
|
||||
value: 'home',
|
||||
expandedKeys: [],
|
||||
'onUpdate:value': onValue,
|
||||
onUpdateExpandedKeys: [onExpanded, onExpandedAlias],
|
||||
})
|
||||
|
||||
try {
|
||||
menu.showOption(2)
|
||||
await nextTick()
|
||||
expect(onExpanded).toHaveBeenCalledExactlyOnceWith([1])
|
||||
expect(onExpanded).toHaveReturnedWith([1])
|
||||
expect(onExpandedAlias).toHaveBeenCalledExactlyOnceWith([1])
|
||||
expect(menu.menuProps.value).toBe('home')
|
||||
|
||||
await menu.select('Daily')
|
||||
expect(onValue).toHaveBeenCalledExactlyOnceWith(2, daily)
|
||||
expect(onValue).toHaveReturnedWith(2)
|
||||
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
|
||||
'Daily',
|
||||
)
|
||||
} finally {
|
||||
menu.wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps native defaults for independently uncontrolled props', async () => {
|
||||
const menu = mountMenu({
|
||||
options: [],
|
||||
defaultValue: 'home',
|
||||
defaultExpandAll: true,
|
||||
watchProps: ['defaultExpandedKeys'],
|
||||
})
|
||||
|
||||
try {
|
||||
menu.menuProps.options = options
|
||||
await nextTick()
|
||||
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
|
||||
'Home',
|
||||
)
|
||||
expect(menu.wrapper.get('[aria-expanded="true"]').text()).toContain('Daily')
|
||||
|
||||
await menu.select('Daily')
|
||||
expect(menu.wrapper.get('.n-menu-item-content--selected').text()).toBe(
|
||||
'Daily',
|
||||
)
|
||||
expect(menu.menuProps.value).toBeUndefined()
|
||||
expect(menu.menuProps.expandedKeys).toBeUndefined()
|
||||
} finally {
|
||||
menu.wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('delegates instance methods only while the menu is mounted', () => {
|
||||
const menu = useMenu()
|
||||
const instance = { showOption: vi.fn(), deriveResponsiveState: vi.fn() }
|
||||
|
||||
menu.showOption()
|
||||
menu.deriveResponsiveState()
|
||||
menu.menuRef.value = instance
|
||||
menu.showOption()
|
||||
menu.deriveResponsiveState()
|
||||
menu.menuRef.value = null
|
||||
menu.showOption('home')
|
||||
menu.deriveResponsiveState()
|
||||
|
||||
expect(instance.showOption).toHaveBeenCalledExactlyOnceWith(void 0)
|
||||
expect(instance.deriveResponsiveState).toHaveBeenCalledExactlyOnceWith()
|
||||
})
|
||||
@ -5,6 +5,7 @@ import { setupI18n } from '@/locales'
|
||||
import { permissionRouter } from '@/router/utils/permission'
|
||||
import { piniaKeepAliveStore } from '@/store/modules/keep-alive'
|
||||
import { piniaMenuStore } from '@/store/modules/menu'
|
||||
import { getCatchMenuTagOptions } from '@/store/modules/menu/utils'
|
||||
import { piniaSettingStore } from '@/store/modules/setting'
|
||||
import { piniaSigningStore } from '@/store/modules/signing'
|
||||
import { setStorage } from '@/utils/cache'
|
||||
@ -183,6 +184,90 @@ it('closes all tags independently of missing or unauthorized root preferences',
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('keeps topped tabs together and restores tab order and flags with the latest URL', async () => {
|
||||
for (const path of ['/reports', '/orders', '/private'])
|
||||
await router.push(path)
|
||||
|
||||
const cachedPages = piniaKeepAliveStore().keepAliveInclude
|
||||
|
||||
menu.toggleMenuTagTop('/private')
|
||||
menu.toggleMenuTagFixed('/orders')
|
||||
expect(menu.moveMenuTag('/orders', '/private', 'before')).toBe(false)
|
||||
expect(menu.moveMenuTag('/orders', '/reports', 'before')).toBe(true)
|
||||
expect(piniaKeepAliveStore().keepAliveInclude).toBe(cachedPages)
|
||||
await router.push('/orders?sort=desc#details')
|
||||
await flushPromises()
|
||||
|
||||
menu.menuTagOptions = getCatchMenuTagOptions()
|
||||
await menu.setupAppMenu()
|
||||
expect(
|
||||
menu.menuTagOptions.map(({ fullPath, topped, fixed }) => [
|
||||
fullPath,
|
||||
topped,
|
||||
fixed,
|
||||
]),
|
||||
).toEqual([
|
||||
['/private', true, false],
|
||||
['/orders?sort=desc#details', false, true],
|
||||
['/reports', false, false],
|
||||
])
|
||||
expect(
|
||||
menu.options.find((option) => option.fullPath === '/private'),
|
||||
).not.toHaveProperty('topped')
|
||||
expect(menu.currentMenuOption?.fullPath).toBe('/orders?sort=desc#details')
|
||||
|
||||
const settings = piniaSettingStore()
|
||||
|
||||
settings.updateSettingState('menuTagDrag', false)
|
||||
expect(
|
||||
menu.moveMenuTag('/reports', '/orders?sort=desc#details', 'before'),
|
||||
).toBe(false)
|
||||
settings.updateSettingState('menuTagDrag', true)
|
||||
settings.updateSettingState('menuTagTop', false)
|
||||
expect(menu.moveMenuTag('/reports', '/private', 'before')).toBe(true)
|
||||
settings.updateSettingState('menuTagTop', true)
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/private',
|
||||
'/reports',
|
||||
'/orders?sort=desc#details',
|
||||
])
|
||||
})
|
||||
|
||||
it('preserves fixed tabs through single and bulk closes until protection is disabled', async () => {
|
||||
for (const path of ['/reports', '/orders', '/private'])
|
||||
await router.push(path)
|
||||
|
||||
menu.toggleMenuTagFixed('/orders')
|
||||
await actions.close('/orders')
|
||||
await actions.closeLeft('/private')
|
||||
expect(actions.checkCloseLeft('/private')).toBe(false)
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/orders',
|
||||
'/private',
|
||||
])
|
||||
await actions.closeRight('/orders')
|
||||
expect(actions.checkCloseRight('/orders')).toBe(false)
|
||||
expect(router.currentRoute.value.path).toBe('/orders')
|
||||
|
||||
await router.push('/reports')
|
||||
await router.push('/private')
|
||||
await actions.closeOther('/private')
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/orders',
|
||||
'/private',
|
||||
])
|
||||
await actions.closeAll()
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/orders',
|
||||
])
|
||||
expect(router.currentRoute.value.path).toBe('/orders')
|
||||
|
||||
piniaSettingStore().updateSettingState('menuTagFixed', false)
|
||||
await actions.close('/orders')
|
||||
expect(menu.menuTagOptions).toEqual([])
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('keeps status routes out of tabs and clears active business navigation', async () => {
|
||||
await router.push('/reports')
|
||||
|
||||
@ -254,6 +339,7 @@ it('closes a directly opened 403 to the workspace with no business tags', async
|
||||
it('removes revoked tags and cached views without choosing another active page', async () => {
|
||||
await router.push('/reports')
|
||||
await router.push('/private?mode=edit#section')
|
||||
menu.toggleMenuTagFixed('/private?mode=edit#section')
|
||||
piniaSigningStore().signingCallback.role = 'member'
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
|
||||
73
__test__/layout/breadcrumb.spec.tsx
Normal file
73
__test__/layout/breadcrumb.spec.tsx
Normal file
@ -0,0 +1,73 @@
|
||||
import Breadcrumb from '@/layout/components/SiderBar/components/Breadcrumb'
|
||||
import type { AppMenuOption } from '@/types'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { h, nextTick, ref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
compact: null as unknown as Ref<boolean>,
|
||||
icons: null as unknown as Ref<boolean>,
|
||||
fallback: null as unknown as Ref<boolean>,
|
||||
options: null as unknown as Ref<AppMenuOption[]>,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks', () => ({
|
||||
useDevice: () => ({ isTabletOrSmaller: state.compact }),
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useMenuActions: () => ({ changeMenuModelValue: vi.fn() }),
|
||||
useMenuGetters: () => ({ getBreadcrumbOptions: state.options }),
|
||||
useSettingGetters: () => ({
|
||||
getBreadcrumbIcon: state.icons,
|
||||
getBreadcrumbIconFallback: state.fallback,
|
||||
}),
|
||||
}))
|
||||
|
||||
const option = (path: string, label: string): AppMenuOption => ({
|
||||
name: label,
|
||||
path,
|
||||
key: path,
|
||||
fullPath: path,
|
||||
label,
|
||||
breadcrumbLabel: label,
|
||||
meta: {},
|
||||
})
|
||||
|
||||
it('displays menu images and defaults to a fallback for the missing icon', async () => {
|
||||
state.compact = ref(false)
|
||||
state.icons = ref(true)
|
||||
state.fallback = ref(true)
|
||||
state.options = ref([
|
||||
{
|
||||
...option('/reports', 'Reports'),
|
||||
icon: () => h('img', { src: '/report.png', alt: '' }),
|
||||
},
|
||||
option('/reports/monthly', 'Monthly'),
|
||||
])
|
||||
const wrapper = mount(Breadcrumb)
|
||||
|
||||
try {
|
||||
const iconSelector = '.layout-breadcrumb__icon'
|
||||
|
||||
expect(wrapper.get(`${iconSelector} img`).attributes('src')).toBe(
|
||||
'/report.png',
|
||||
)
|
||||
expect(wrapper.findAll(iconSelector)).toHaveLength(2)
|
||||
state.fallback.value = false
|
||||
await nextTick()
|
||||
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
|
||||
|
||||
state.compact.value = true
|
||||
state.fallback.value = true
|
||||
await nextTick()
|
||||
expect(wrapper.get('[aria-current="page"]').text()).toBe('Monthly')
|
||||
expect(wrapper.findAll(iconSelector)).toHaveLength(1)
|
||||
|
||||
state.icons.value = false
|
||||
await nextTick()
|
||||
expect(wrapper.findAll(iconSelector)).toHaveLength(0)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
@ -12,8 +12,14 @@ const state = vi.hoisted(() => ({
|
||||
tags: null as unknown as Ref<MenuTagOptions[]>,
|
||||
active: null as unknown as Ref<MenuTagOptions | null>,
|
||||
round: null as unknown as Ref<boolean>,
|
||||
top: null as unknown as Ref<boolean>,
|
||||
fixed: null as unknown as Ref<boolean>,
|
||||
drag: null as unknown as Ref<boolean>,
|
||||
close: vi.fn(),
|
||||
navigate: vi.fn(),
|
||||
move: vi.fn(),
|
||||
toggleTop: vi.fn(),
|
||||
toggleFixed: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks', () => ({
|
||||
@ -37,9 +43,23 @@ vi.mock('@/store', () => ({
|
||||
getMenuTagOptions: state.tags,
|
||||
getCurrentMenuOption: state.active,
|
||||
}),
|
||||
useMenuActions: () => ({ changeMenuModelValue: state.navigate }),
|
||||
useMenuActions: () => ({
|
||||
changeMenuModelValue: state.navigate,
|
||||
isMenuTagTopped: (tag?: MenuTagOptions) =>
|
||||
state.top.value && tag?.topped === true,
|
||||
isMenuTagFixed: (tag?: MenuTagOptions) =>
|
||||
state.fixed.value && tag?.fixed === true,
|
||||
toggleMenuTagTop: state.toggleTop,
|
||||
toggleMenuTagFixed: state.toggleFixed,
|
||||
moveMenuTag: state.move,
|
||||
}),
|
||||
useRuntimeGetters: () => ({ globalMainLayoutLoad: ref(true) }),
|
||||
useSettingGetters: () => ({ getMenuTagRound: state.round }),
|
||||
useSettingGetters: () => ({
|
||||
getMenuTagRound: state.round,
|
||||
getMenuTagTop: state.top,
|
||||
getMenuTagFixed: state.fixed,
|
||||
getMenuTagDrag: state.drag,
|
||||
}),
|
||||
}))
|
||||
|
||||
let wrapper: VueWrapper
|
||||
@ -58,6 +78,9 @@ beforeEach(async () => {
|
||||
)
|
||||
state.active = ref(state.tags.value[0]!)
|
||||
state.round = ref(false)
|
||||
state.top = ref(true)
|
||||
state.fixed = ref(true)
|
||||
state.drag = ref(true)
|
||||
router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
@ -72,6 +95,7 @@ beforeEach(async () => {
|
||||
attachTo: host,
|
||||
global: {
|
||||
plugins: [router],
|
||||
stubs: { 'transition-group': false },
|
||||
mocks: {
|
||||
$t: (key: string, params?: { name: string }) =>
|
||||
params ? `${key}:${params.name}` : key,
|
||||
@ -85,6 +109,7 @@ afterEach(() => {
|
||||
router.options.history.destroy()
|
||||
host.remove()
|
||||
outside.remove()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
const contextDropdown = () =>
|
||||
@ -206,6 +231,120 @@ it('applies a context command to the most recently right-clicked tag', async ()
|
||||
expect(contextDropdown().props('show')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps context commands tied to the selected page when the order changes', async () => {
|
||||
await openContextMenu(0)
|
||||
state.tags.value.reverse()
|
||||
await nextTick()
|
||||
const command = Array.from(
|
||||
document.querySelectorAll('.n-dropdown-option-body'),
|
||||
).find((option) => option.textContent === 'fix')
|
||||
|
||||
mouse(command!, 'click', 0)
|
||||
expect(state.toggleFixed).toHaveBeenCalledExactlyOnceWith('/reports')
|
||||
})
|
||||
|
||||
it('updates tab indicators and actions while preferences change', async () => {
|
||||
state.tags.value[0].topped = true
|
||||
state.tags.value[0].fixed = true
|
||||
await openContextMenu(0)
|
||||
const tab = wrapper.get('[data-menu-tag-path="/reports"]')
|
||||
const actions = () =>
|
||||
contextDropdown()
|
||||
.props('options')
|
||||
?.map((option) => option.key)
|
||||
|
||||
expect(tab.find('.n-tag__close').exists()).toBe(false)
|
||||
expect(tab.findAll('.menu-tag__indicator')).toHaveLength(2)
|
||||
expect(actions()).toEqual(
|
||||
expect.arrayContaining(['toggleTop', 'toggleFixed']),
|
||||
)
|
||||
|
||||
state.top.value = false
|
||||
state.fixed.value = false
|
||||
state.drag.value = false
|
||||
await nextTick()
|
||||
expect(tab.find('.n-tag__close').exists()).toBe(true)
|
||||
expect(tab.findAll('.menu-tag__indicator')).toHaveLength(0)
|
||||
expect(wrapper.findAll('.menu-tag__handle')).toHaveLength(0)
|
||||
expect(actions()).not.toContain('toggleTop')
|
||||
expect(actions()).not.toContain('toggleFixed')
|
||||
})
|
||||
|
||||
it('sends the focused handle’s keyboard reorder to the tab store', async () => {
|
||||
const handle = wrapper.get(
|
||||
'[data-menu-tag-path="/reports"] .menu-tag__handle',
|
||||
)
|
||||
|
||||
await handle.trigger('keydown', { key: 'ArrowRight' })
|
||||
expect(state.move).not.toHaveBeenCalled()
|
||||
await handle.trigger('keydown', { key: 'ArrowRight', shiftKey: true })
|
||||
expect(state.move).toHaveBeenCalledExactlyOnceWith(
|
||||
'/reports',
|
||||
'/orders',
|
||||
'after',
|
||||
)
|
||||
expect(state.navigate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('measures a burst of pointer moves once and uses the release position', () => {
|
||||
const row = wrapper.get<HTMLElement>('.menu-tag-wrapper').element
|
||||
const scroller = row.closest('.n-scrollbar-container')!
|
||||
const measure = vi.fn(() => new DOMRect(0, 0, 300, 32))
|
||||
|
||||
scroller.getBoundingClientRect = measure
|
||||
row.getBoundingClientRect = () => new DOMRect(0, 0, 300, 32)
|
||||
const tags = wrapper.findAll<HTMLElement>('[data-menu-tag-path]')
|
||||
|
||||
tags.forEach(({ element }, index) => {
|
||||
Object.defineProperties(element, {
|
||||
offsetLeft: { value: index * 100 },
|
||||
offsetWidth: { value: 100 },
|
||||
})
|
||||
})
|
||||
const handle = tags[0].get<HTMLButtonElement>('.menu-tag__handle').element
|
||||
const release = vi.fn()
|
||||
|
||||
handle.setPointerCapture = vi.fn()
|
||||
handle.hasPointerCapture = () => true
|
||||
handle.releasePointerCapture = release
|
||||
const requestFrame = vi.fn((_callback: FrameRequestCallback) => 1)
|
||||
|
||||
vi.stubGlobal('requestAnimationFrame', requestFrame)
|
||||
const point = (type: string, clientX: number) =>
|
||||
handle.dispatchEvent(
|
||||
new PointerEvent(type, {
|
||||
bubbles: true,
|
||||
isPrimary: true,
|
||||
pointerId: 2,
|
||||
clientX,
|
||||
clientY: 16,
|
||||
}),
|
||||
)
|
||||
|
||||
point('pointerdown', 10)
|
||||
point('pointermove', 110)
|
||||
point('pointermove', 180)
|
||||
expect(measure).not.toHaveBeenCalled()
|
||||
expect(requestFrame).toHaveBeenCalledTimes(1)
|
||||
|
||||
requestFrame.mock.calls[0][0](16)
|
||||
expect(measure).toHaveBeenCalledTimes(1)
|
||||
expect(requestFrame).toHaveBeenCalledTimes(1)
|
||||
expect(tags[2].attributes('data-menu-tag-drop')).toBe('before')
|
||||
expect(state.move).not.toHaveBeenCalled()
|
||||
|
||||
point('pointerup', 285)
|
||||
expect(state.move).toHaveBeenCalledExactlyOnceWith(
|
||||
'/reports',
|
||||
'/users',
|
||||
'after',
|
||||
)
|
||||
expect(release).toHaveBeenCalledExactlyOnceWith(2)
|
||||
expect(
|
||||
row.querySelector('[data-menu-tag-drop],[data-menu-tag-dragged]'),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it.each([0, 2])(
|
||||
'dismisses when mouse button %i is clicked outside the tags and menu',
|
||||
async (button) => {
|
||||
|
||||
@ -133,6 +133,13 @@ describe('layout preferences', () => {
|
||||
expect(store.localeLanguage).toBe('en-US')
|
||||
expect(store.menuTagSwitch).toBe(false)
|
||||
expect(store.menuTagRound).toBe(false)
|
||||
expect(store).toMatchObject({
|
||||
menuTagTop: true,
|
||||
menuTagFixed: true,
|
||||
menuTagDrag: true,
|
||||
breadcrumbIcon: true,
|
||||
breadcrumbIconFallback: true,
|
||||
})
|
||||
expect(store.menuConfig).toMatchObject({
|
||||
iconSize: 20,
|
||||
collapsedIconSize: 22,
|
||||
@ -188,6 +195,11 @@ describe('layout preferences', () => {
|
||||
store.updateSettingState('appTheme', 'dark')
|
||||
store.updateSettingState('themeStyle', 'material')
|
||||
store.updateSettingState('menuTagRound', true)
|
||||
store.updateSettingState('menuTagTop', false)
|
||||
store.updateSettingState('menuTagFixed', false)
|
||||
store.updateSettingState('menuTagDrag', false)
|
||||
store.updateSettingState('breadcrumbIcon', false)
|
||||
store.updateSettingState('breadcrumbIconFallback', false)
|
||||
store.updateSettingState('watermarkConfig', { content: 'Portable' })
|
||||
store.updateSettingState('keepAliveConfig', {
|
||||
keepAliveExclude: ['Page'],
|
||||
@ -198,6 +210,8 @@ describe('layout preferences', () => {
|
||||
store.updateSettingState('layoutConfig', { mode: 'top' })
|
||||
store.updateSettingState('appTheme', 'light')
|
||||
store.updateSettingState('menuTagRound', false)
|
||||
store.updateSettingState('menuTagDrag', true)
|
||||
store.updateSettingState('breadcrumbIcon', true)
|
||||
store.updateSettingState('appRootRoute', { path: '/custom-home' })
|
||||
store.changePrimaryColor('#000000')
|
||||
store.updateSettingState('themeStyle', 'plain')
|
||||
@ -221,6 +235,11 @@ describe('layout preferences', () => {
|
||||
appTheme: 'dark',
|
||||
themeStyle: 'material',
|
||||
menuTagRound: true,
|
||||
menuTagTop: false,
|
||||
menuTagFixed: false,
|
||||
menuTagDrag: false,
|
||||
breadcrumbIcon: false,
|
||||
breadcrumbIconFallback: false,
|
||||
})
|
||||
} finally {
|
||||
app.unmount()
|
||||
@ -243,12 +262,24 @@ describe('layout preferences', () => {
|
||||
const {
|
||||
themeStyle: _style,
|
||||
menuTagRound: _round,
|
||||
menuTagTop: _top,
|
||||
menuTagFixed: _fixed,
|
||||
menuTagDrag: _drag,
|
||||
breadcrumbIcon: _icon,
|
||||
breadcrumbIconFallback: _fallback,
|
||||
...legacy
|
||||
} = preferences
|
||||
|
||||
store.importPreferences(JSON.stringify({ ...file, preferences: legacy }))
|
||||
expect(store.themeStyle).toBe('modern')
|
||||
expect(store.menuTagRound).toBe(false)
|
||||
expect(store.exportPreferences().preferences).toMatchObject({
|
||||
menuTagTop: true,
|
||||
menuTagFixed: true,
|
||||
menuTagDrag: true,
|
||||
breadcrumbIcon: true,
|
||||
breadcrumbIconFallback: true,
|
||||
})
|
||||
expect(store.themeOverrides.Card?.borderRadius).toBe('12px')
|
||||
expect(store.themeOverrides.common?.primaryColor).toBe('#3468db')
|
||||
|
||||
|
||||
@ -11,6 +11,7 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
|
||||
| template | `useWatermark` | `/template-hooks`: text, show, hide, and toggle | [useWatermark](../../../../__test__/hooks/useWatermark.spec.ts) |
|
||||
| template | `useAppNavigation` | `/template-hooks`: full paths, indexes, nested menus, and query | [useAppNavigation](../../../../__test__/hooks/useAppNavigation.spec.ts) |
|
||||
| template | `useSiderBar` | `/template-hooks`: close tabs by path or close left/right/other/all tabs | [useSiderBar](../../../../__test__/hooks/useSiderBar.spec.ts) |
|
||||
| components | `useMenu` | `/template-hooks`: bind an NMenu, change the selection, and reveal a nested option | [useMenu](../../../../__test__/hooks/useMenu.spec.tsx) |
|
||||
| template | `useContentScroll` | `/template-hooks`: scroll content to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
|
||||
| template | `useSiderScroll` | `/template-hooks`: scroll sidebar to top or coordinates | [useLayoutScroll](../../../../__test__/hooks/useLayoutScroll.spec.ts) |
|
||||
| web | `useDevice` | `/web-hooks`: update breakpoint checks with window size | [useDevice](../../../../__test__/hooks/useDevice.spec.ts) |
|
||||
@ -34,6 +35,7 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
|
||||
- Both scroll hooks can be created during setup and read the layout instance only when invoked. Missing sidebars or unmounted instances are safely ignored.
|
||||
- `useMaximize` acts on layout content and shares state across callers. `useElementFullscreen` acts on one arbitrary element and owns per-instance state. Neither calls the browser Fullscreen API.
|
||||
- `navigationTo` indexes start at 0. Negative, fractional, non-finite, or out-of-range indexes do not navigate. Full URLs support dynamic parameters, query, and hash; additional query parameters override matching URL parameters. Successful calls return the Router navigation Promise.
|
||||
- Bind `useMenu().menuRef` and `menuProps` to `NMenu`. Provide `value` or `expandedKeys` to keep that state in the hook. Omit an input to use the corresponding Naive UI defaults. Replace option arrays for shallow reactivity. The hook is available from `@/hooks` and `@ray-template/composables/useMenu`.
|
||||
- `useDomToImage` return types follow the default format or the current `create(format)` call. Failures reject with Error. `finally` also runs when the target is missing, so its argument may be empty. The `created` callback receives results from runtime format overrides as well; its argument is a union of actual output types and must be narrowed first.
|
||||
- `useI18n('hooks').t('code')` and `.t('hooks.code')` address the same translation key. Switch application locales with `useSettingActions().updateLocale` to keep dates and component-library locales synchronized.
|
||||
- Development HMR reuses the internationalization instance. Translation methods created before initialization read the current instance at invocation rather than permanently retaining the fallback that returns raw keys.
|
||||
|
||||
@ -1,2 +1,3 @@
|
||||
export * from './useContextmenuCoordinate'
|
||||
export * from './useMenu'
|
||||
export * from './usePagination'
|
||||
|
||||
1
apps/admin/src/hooks/components/useMenu.ts
Normal file
1
apps/admin/src/hooks/components/useMenu.ts
Normal file
@ -0,0 +1 @@
|
||||
export * from '@ray-template/composables/useMenu'
|
||||
@ -42,8 +42,24 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
|
||||
export function useSiderBar() {
|
||||
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters()
|
||||
const { router } = useVueRouter()
|
||||
const { changeMenuModelValue, spliceMenTagOptions, setMenuTagOptions } =
|
||||
useMenuActions()
|
||||
const {
|
||||
changeMenuModelValue,
|
||||
spliceMenTagOptions,
|
||||
setMenuTagOptions,
|
||||
isMenuTagFixed,
|
||||
} = useMenuActions()
|
||||
|
||||
const canClose = (tag: MenuTagOptions) => !isMenuTagFixed(tag)
|
||||
const closeWhere = (matches: (index: number) => boolean) => {
|
||||
const current = getMenuTagOptions.value
|
||||
const remaining = current.filter(
|
||||
(tag, index) => !matches(index) || !canClose(tag),
|
||||
)
|
||||
|
||||
if (remaining.length !== current.length) setMenuTagOptions(remaining, false)
|
||||
|
||||
return remaining
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
@ -64,14 +80,9 @@ export function useSiderBar() {
|
||||
const checkCloseRight = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'checkCloseRight')
|
||||
|
||||
if (normal) {
|
||||
const { index } = normal
|
||||
const length = getMenuTagOptions.value.length - 1
|
||||
|
||||
return !(index >= length)
|
||||
}
|
||||
|
||||
return false
|
||||
return (
|
||||
!!normal && getMenuTagOptions.value.slice(normal.index + 1).some(canClose)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -83,7 +94,9 @@ export function useSiderBar() {
|
||||
const checkCloseLeft = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'checkCloseLeft')
|
||||
|
||||
return !!normal && normal.index > 0
|
||||
return (
|
||||
!!normal && getMenuTagOptions.value.slice(0, normal.index).some(canClose)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -91,14 +104,14 @@ export function useSiderBar() {
|
||||
* @param target 要关闭的标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 所有业务标签都可关闭;关闭最后一项进入空工作区,其余激活项切换到相邻标签。
|
||||
* 固定的标签会保留;关闭最后一项进入空工作区,关闭激活项时切换到相邻标签。
|
||||
*
|
||||
* @returns 需要跳转时返回 Router 导航结果。
|
||||
*/
|
||||
const close = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'close')
|
||||
|
||||
if (normal) {
|
||||
if (normal && canClose(normal.option)) {
|
||||
const { index, option } = normal
|
||||
const active = option.fullPath === getCurrentMenuOption.value?.fullPath
|
||||
|
||||
@ -118,14 +131,17 @@ export function useSiderBar() {
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 清空所有业务标签及其缓存,然后进入空工作区;不依赖任何业务首页。
|
||||
* 关闭未固定的标签;优先保留当前页面,再尝试第一个固定标签或空工作区。
|
||||
*
|
||||
* @returns Router 导航结果。
|
||||
*/
|
||||
const closeAll = () => {
|
||||
setMenuTagOptions([], false)
|
||||
const current = getCurrentMenuOption.value?.fullPath
|
||||
const remaining = closeWhere(() => true)
|
||||
|
||||
return router.replace(WELCOME_ROUTE_PATH)
|
||||
if (remaining.some((tag) => tag.fullPath === current)) return
|
||||
|
||||
return router.replace(remaining[0]?.fullPath ?? WELCOME_ROUTE_PATH)
|
||||
}
|
||||
|
||||
const closeForbiddenPage = () => {
|
||||
@ -148,19 +164,19 @@ export function useSiderBar() {
|
||||
* @param target 要保留的边界标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 关闭右侧标签;激活项被移除时切换到边界标签。
|
||||
* 关闭右侧未固定的标签;激活项被移除时切换到边界标签。
|
||||
*/
|
||||
const closeRight = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeRight')
|
||||
|
||||
if (normal) {
|
||||
const { option, index } = normal
|
||||
const spliceLength = getMenuTagOptions.value.length - index // 待删除长度
|
||||
const currentIndex = getCurrentTagIndex()
|
||||
const current = getMenuTagOptions.value[currentIndex]
|
||||
|
||||
spliceMenTagOptions(index + 1, spliceLength)
|
||||
closeWhere((tagIndex) => tagIndex > index)
|
||||
|
||||
if (currentIndex > index)
|
||||
if (currentIndex > index && canClose(current))
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
@ -170,7 +186,7 @@ export function useSiderBar() {
|
||||
* @param target 要保留的边界标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 关闭左侧标签;激活项被移除时切换到边界标签。
|
||||
* 关闭左侧未固定的标签;激活项被移除时切换到边界标签。
|
||||
*/
|
||||
const closeLeft = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeLeft')
|
||||
@ -178,10 +194,11 @@ export function useSiderBar() {
|
||||
if (normal) {
|
||||
const { option, index } = normal
|
||||
const currentIndex = getCurrentTagIndex()
|
||||
const current = getMenuTagOptions.value[currentIndex]
|
||||
|
||||
spliceMenTagOptions(0, index)
|
||||
closeWhere((tagIndex) => tagIndex < index)
|
||||
|
||||
if (currentIndex >= 0 && currentIndex < index)
|
||||
if (currentIndex >= 0 && currentIndex < index && canClose(current))
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
@ -191,15 +208,15 @@ export function useSiderBar() {
|
||||
* @param target 要保留的标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 仅保留并激活目标标签;目标无效时不操作。
|
||||
* 保留目标与所有固定标签,并激活目标。
|
||||
*/
|
||||
const closeOther = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeOther')
|
||||
|
||||
if (normal) {
|
||||
const { option } = normal
|
||||
const { option, index } = normal
|
||||
|
||||
setMenuTagOptions(option, false)
|
||||
closeWhere((tagIndex) => tagIndex !== index)
|
||||
|
||||
if (getCurrentMenuOption.value?.fullPath !== option.fullPath)
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
|
||||
@ -11,9 +11,9 @@ import {
|
||||
} from '@/store'
|
||||
import type { AppMenuOption, NaiveMenuOptions } from '@/types'
|
||||
import { useMenuKeyboard } from '@ray-template/admin-shell'
|
||||
import { useMenu } from '@ray-template/composables/useMenu'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { NButton, NDrawer, NLayoutContent, NLayoutSider, NMenu } from 'naive-ui'
|
||||
import type { MenuInst } from 'naive-ui'
|
||||
import type { PropType } from 'vue'
|
||||
import SiderBarLogo from './components/SiderBarLogo'
|
||||
|
||||
@ -28,7 +28,7 @@ export default defineComponent({
|
||||
inert: Boolean,
|
||||
},
|
||||
setup(props) {
|
||||
const menuRef = shallowRef<MenuInst | null>(null)
|
||||
const { menuRef, showOption } = useMenu()
|
||||
const { changeMenuModelValue, collapsedMenu } = useMenuActions()
|
||||
const { t } = useI18n('layout')
|
||||
const { getAppTheme, getMenuConfig } = useSettingGetters()
|
||||
@ -56,8 +56,7 @@ export default defineComponent({
|
||||
async () => {
|
||||
await nextTick()
|
||||
|
||||
if (getMenuKey.value != null)
|
||||
menuRef.value?.showOption(String(getMenuKey.value))
|
||||
if (getMenuKey.value != null) showOption(String(getMenuKey.value))
|
||||
|
||||
positionSelectedMenuItem()
|
||||
},
|
||||
|
||||
@ -4,3 +4,109 @@
|
||||
border: 1px solid var(--r-line);
|
||||
border-radius: var(--r-radius);
|
||||
}
|
||||
|
||||
.menu-tag-wrapper {
|
||||
position: relative;
|
||||
padding-inline: 4px;
|
||||
}
|
||||
|
||||
.menu-tag__item .n-tag__content {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.menu-tag__handle {
|
||||
display: grid;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
min-inline-size: 24px;
|
||||
min-block-size: 24px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--r-control-radius);
|
||||
background: transparent;
|
||||
color: var(--r-text-secondary);
|
||||
touch-action: none;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
cursor: grab;
|
||||
|
||||
&:is(:hover, :focus-visible) {
|
||||
background: var(--r-surface-hover);
|
||||
color: var(--r-text);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline-offset: -2px;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-tag__indicator {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.menu-tag__top-icon {
|
||||
rotate: 180deg;
|
||||
}
|
||||
|
||||
.menu-tag-wrapper--dragging,
|
||||
.menu-tag-wrapper--dragging * {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.menu-tag__item[data-menu-tag-dragged] {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.menu-tag__item[data-menu-tag-drop]::after {
|
||||
position: absolute;
|
||||
inset-block: 0;
|
||||
inline-size: 2px;
|
||||
border-radius: var(--r-control-radius);
|
||||
background: var(--r-theme-primary-color);
|
||||
pointer-events: none;
|
||||
content: '';
|
||||
}
|
||||
|
||||
.menu-tag__item[data-menu-tag-drop='before']::after {
|
||||
inset-inline-start: -4px;
|
||||
}
|
||||
|
||||
.menu-tag__item[data-menu-tag-drop='after']::after {
|
||||
inset-inline-end: -4px;
|
||||
}
|
||||
|
||||
.menu-tag-move {
|
||||
transition: transform 150ms var(--r-bezier);
|
||||
}
|
||||
|
||||
.menu-tag__status {
|
||||
position: absolute;
|
||||
inline-size: 1px;
|
||||
block-size: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@media (hover: none) {
|
||||
.menu-tag__handle {
|
||||
min-inline-size: 32px;
|
||||
min-block-size: 28px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.menu-tag__item[data-menu-tag-drop]::after {
|
||||
background: Highlight;
|
||||
forced-color-adjust: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.menu-tag-move {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,10 +11,15 @@ import type { AppMenuOption, MenuTagOptions } from '@/types'
|
||||
import { ShellTab } from '@ray-template/admin-shell'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { RMoreDropdown } from '@ray-template/ui/more-dropdown'
|
||||
import { usePreferredReducedMotion, useResizeObserver } from '@vueuse/core'
|
||||
import {
|
||||
usePreferredReducedMotion,
|
||||
useResizeObserver,
|
||||
useTimeoutFn,
|
||||
} from '@vueuse/core'
|
||||
import { NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui'
|
||||
import type { ScrollbarInst } from 'naive-ui'
|
||||
import { useTemplateRef } from 'vue'
|
||||
import { TransitionGroup, useTemplateRef } from 'vue'
|
||||
import { useTagReorder } from './use-tag-reorder'
|
||||
|
||||
const Chevron = ({ direction }: { direction: 'left' | 'right' }) => (
|
||||
<RIcon
|
||||
@ -30,15 +35,25 @@ export default defineComponent({
|
||||
const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef')
|
||||
const tagsRef = useTemplateRef<HTMLElement>('tags')
|
||||
const actionsButton = useTemplateRef<HTMLButtonElement>('actionsButton')
|
||||
const statusRef = useTemplateRef<HTMLSpanElement>('reorderStatus')
|
||||
const route = useRoute()
|
||||
const showingForbidden = computed(() => route.path === FORBIDDEN_ROUTE_PATH)
|
||||
const { t } = useI18n('menuTag')
|
||||
const { t: translate } = useI18n()
|
||||
const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters()
|
||||
const { getMenuTagRound } = useSettingGetters()
|
||||
const { getMenuTagRound, getMenuTagTop, getMenuTagFixed, getMenuTagDrag } =
|
||||
useSettingGetters()
|
||||
const getMenuKey = computed(
|
||||
() => getCurrentMenuOption.value?.fullPath ?? null,
|
||||
)
|
||||
const { changeMenuModelValue } = useMenuActions()
|
||||
const {
|
||||
changeMenuModelValue,
|
||||
isMenuTagTopped,
|
||||
isMenuTagFixed,
|
||||
toggleMenuTagTop,
|
||||
toggleMenuTagFixed,
|
||||
moveMenuTag,
|
||||
} = useMenuActions()
|
||||
const { maximize } = useMaximize()
|
||||
const { reload } = useSpinning()
|
||||
const {
|
||||
@ -51,8 +66,15 @@ export default defineComponent({
|
||||
checkCloseLeft,
|
||||
checkCloseRight,
|
||||
} = useSiderBar()
|
||||
// 当前右键标签页索引位置
|
||||
const currentContextmenuIndex = ref(-1)
|
||||
const contextPath = ref<string>()
|
||||
const currentContextmenuIndex = computed(() =>
|
||||
getMenuTagOptions.value.findIndex(
|
||||
({ fullPath }) => fullPath === contextPath.value,
|
||||
),
|
||||
)
|
||||
const contextTag = computed(
|
||||
() => getMenuTagOptions.value[currentContextmenuIndex.value],
|
||||
)
|
||||
const closeStatus = async (restoreFocus: boolean) => {
|
||||
const navigation = closeForbiddenPage()
|
||||
|
||||
@ -73,7 +95,7 @@ export default defineComponent({
|
||||
key: 'closeCurrentPage',
|
||||
disabled:
|
||||
!(showingForbidden.value && currentContextmenuIndex.value === -1) &&
|
||||
!canClose(getMenuTagOptions.value[currentContextmenuIndex.value]),
|
||||
!canClose(contextTag.value),
|
||||
icon: () => <RIcon name="action/close" size="1em" />,
|
||||
},
|
||||
{
|
||||
@ -89,9 +111,35 @@ export default defineComponent({
|
||||
{
|
||||
label: t('newWindow'),
|
||||
key: 'windowOpenTab',
|
||||
disabled: !getMenuTagOptions.value[currentContextmenuIndex.value],
|
||||
disabled: !contextTag.value,
|
||||
icon: () => <RIcon name="navigation/window" size="1em" />,
|
||||
},
|
||||
...(getMenuTagTop.value
|
||||
? [
|
||||
{
|
||||
label: t(isMenuTagTopped(contextTag.value) ? 'untop' : 'top'),
|
||||
key: 'toggleTop',
|
||||
disabled: !contextTag.value,
|
||||
icon: () => (
|
||||
<RIcon
|
||||
name="directional/expanded"
|
||||
size="1em"
|
||||
customClassName="menu-tag__top-icon"
|
||||
/>
|
||||
),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(getMenuTagFixed.value
|
||||
? [
|
||||
{
|
||||
label: t(isMenuTagFixed(contextTag.value) ? 'unfix' : 'fix'),
|
||||
key: 'toggleFixed',
|
||||
disabled: !contextTag.value,
|
||||
icon: () => <RIcon name="action/lock" size="1em" />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
type: 'divider',
|
||||
key: 'd1',
|
||||
@ -100,16 +148,14 @@ export default defineComponent({
|
||||
label: t('closeLeft'),
|
||||
key: 'closeLeft',
|
||||
disabled:
|
||||
!getMenuTagOptions.value[currentContextmenuIndex.value] ||
|
||||
!checkCloseLeft(currentContextmenuIndex.value),
|
||||
!contextTag.value || !checkCloseLeft(currentContextmenuIndex.value),
|
||||
icon: () => <RIcon name="action/close_left" size="1em" />,
|
||||
},
|
||||
{
|
||||
label: t('closeRight'),
|
||||
key: 'closeRight',
|
||||
disabled:
|
||||
!getMenuTagOptions.value[currentContextmenuIndex.value] ||
|
||||
!checkCloseRight(currentContextmenuIndex.value),
|
||||
!contextTag.value || !checkCloseRight(currentContextmenuIndex.value),
|
||||
icon: () => <RIcon name="action/close_right" size="1em" />,
|
||||
},
|
||||
{
|
||||
@ -120,15 +166,17 @@ export default defineComponent({
|
||||
label: t('closeOther'),
|
||||
key: 'closeOther',
|
||||
disabled:
|
||||
getMenuTagOptions.value.length < 2 ||
|
||||
!getMenuTagOptions.value[currentContextmenuIndex.value],
|
||||
!contextTag.value ||
|
||||
!getMenuTagOptions.value.some(
|
||||
(tag) => tag !== contextTag.value && canClose(tag),
|
||||
),
|
||||
icon: () => <RIcon name="action/close_other" size="1em" />,
|
||||
},
|
||||
{
|
||||
label: t('closeAll'),
|
||||
key: 'closeAll',
|
||||
icon: () => <RIcon name="action/close_all" size="1em" />,
|
||||
disabled: getMenuTagOptions.value.length === 0,
|
||||
disabled: !getMenuTagOptions.value.some(canClose),
|
||||
},
|
||||
])
|
||||
const actionMap = {
|
||||
@ -139,7 +187,7 @@ export default defineComponent({
|
||||
closeCurrentMenuTag(currentContextmenuIndex.value)
|
||||
},
|
||||
reloadCurrentPage: async () => {
|
||||
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
|
||||
const option = contextTag.value
|
||||
|
||||
if (option && route.fullPath !== option.fullPath) {
|
||||
await changeMenuModelValue(option.fullPath, option)
|
||||
@ -161,8 +209,26 @@ export default defineComponent({
|
||||
closeOther: () => {
|
||||
$closeOther(currentContextmenuIndex.value)
|
||||
},
|
||||
toggleTop: () => {
|
||||
const option = contextTag.value
|
||||
|
||||
if (!option || !toggleMenuTagTop(option.fullPath)) return
|
||||
|
||||
void nextTick(() => {
|
||||
const tag = Array.from(tagsRef.value?.children ?? []).find(
|
||||
(element): element is HTMLElement =>
|
||||
element instanceof HTMLElement &&
|
||||
element.dataset.menuTagPath === option.fullPath,
|
||||
)
|
||||
|
||||
if (tag) revealTag(tag)
|
||||
})
|
||||
},
|
||||
toggleFixed: () => {
|
||||
if (contextTag.value) toggleMenuTagFixed(contextTag.value.fullPath)
|
||||
},
|
||||
windowOpenTab: () => {
|
||||
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
|
||||
const option = contextTag.value
|
||||
|
||||
if (!option?.fullPath) {
|
||||
return
|
||||
@ -176,7 +242,7 @@ export default defineComponent({
|
||||
window.open(path, '_blank', 'noopener')
|
||||
},
|
||||
maximizeLayoutContent: () => {
|
||||
const option = getMenuTagOptions.value[currentContextmenuIndex.value]
|
||||
const option = contextTag.value
|
||||
|
||||
maximize(true)
|
||||
option && menuTagClick(option)
|
||||
@ -189,7 +255,12 @@ export default defineComponent({
|
||||
actionDropdownShow: false,
|
||||
})
|
||||
const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad
|
||||
const canClose = (option?: MenuTagOptions) => !!option
|
||||
const canClose = (option?: MenuTagOptions) =>
|
||||
!!option && !isMenuTagFixed(option)
|
||||
const tagLabel = (tag: MenuTagOptions) =>
|
||||
tag.meta.i18nKey
|
||||
? translate(tag.meta.i18nKey)
|
||||
: tag.breadcrumbLabel || tag.fullPath
|
||||
|
||||
const closeCurrentMenuTag = (index: number, restoreFocus = false) => {
|
||||
const option = getMenuTagOptions.value[index]
|
||||
@ -223,6 +294,61 @@ export default defineComponent({
|
||||
)
|
||||
const scrollState = reactive({ left: false, right: false })
|
||||
const reducedMotion = usePreferredReducedMotion()
|
||||
const revealTag = (tag: HTMLElement) => {
|
||||
const element = scroller.value
|
||||
|
||||
if (!element) return
|
||||
|
||||
const start = tag.offsetLeft
|
||||
const end = start + tag.offsetWidth
|
||||
const left = element.scrollLeft
|
||||
const right = left + element.clientWidth
|
||||
|
||||
if (start < left || tag.offsetWidth >= element.clientWidth)
|
||||
element.scrollLeft = start
|
||||
else if (end > right) element.scrollLeft = end - element.clientWidth
|
||||
}
|
||||
const { start: scheduleAnnouncement } = useTimeoutFn(
|
||||
(message: string) => {
|
||||
if (statusRef.value) statusRef.value.textContent = message
|
||||
},
|
||||
500,
|
||||
{ immediate: false },
|
||||
)
|
||||
const announce = (message: string) => {
|
||||
if (statusRef.value) statusRef.value.textContent = ''
|
||||
|
||||
scheduleAnnouncement(message)
|
||||
}
|
||||
const reorder = useTagReorder(
|
||||
getMenuTagDrag,
|
||||
tagsRef,
|
||||
scroller,
|
||||
(path, target, handle) => {
|
||||
if (!moveMenuTag(path, target.path, target.placement)) return
|
||||
|
||||
const position = getMenuTagOptions.value.findIndex(
|
||||
(tag) => tag.fullPath === path,
|
||||
)
|
||||
const option = getMenuTagOptions.value[position]
|
||||
const wasFocused = document.activeElement === handle
|
||||
|
||||
void nextTick(() => {
|
||||
const tag = handle.closest<HTMLElement>('[data-menu-tag-path]')
|
||||
|
||||
if (!tag?.isConnected) return
|
||||
|
||||
revealTag(tag)
|
||||
|
||||
if (wasFocused) handle.focus({ preventScroll: true })
|
||||
|
||||
announce(
|
||||
t('moved', { name: tagLabel(option), position: position + 1 }),
|
||||
)
|
||||
})
|
||||
},
|
||||
() => announce(t('moveCanceled')),
|
||||
)
|
||||
const syncScroll = () => {
|
||||
const element = scroller.value
|
||||
|
||||
@ -258,12 +384,10 @@ export default defineComponent({
|
||||
return fn?.()
|
||||
}
|
||||
|
||||
// 右键点击标签页
|
||||
// 缓存当前点击标签页索引值(用于关闭左或者右侧标签页操作)
|
||||
const menuTagContextMenu = (idx: number, e: MouseEvent) => {
|
||||
const menuTagContextMenu = (path: string, e: MouseEvent) => {
|
||||
e.preventDefault()
|
||||
|
||||
currentContextmenuIndex.value = idx
|
||||
contextPath.value = path
|
||||
actionState.x = e.clientX
|
||||
actionState.y = e.clientY
|
||||
actionState.actionDropdownShow = true
|
||||
@ -282,10 +406,8 @@ export default defineComponent({
|
||||
actionState.actionDropdownShow = false
|
||||
}
|
||||
|
||||
const setCurrentContextmenuIndex = () => {
|
||||
currentContextmenuIndex.value = getMenuTagOptions.value.findIndex(
|
||||
({ fullPath }) => fullPath === getMenuKey.value,
|
||||
)
|
||||
const selectActiveContext = () => {
|
||||
contextPath.value = getMenuKey.value ?? void 0
|
||||
}
|
||||
|
||||
const positionMenuTag = () => {
|
||||
@ -326,7 +448,11 @@ export default defineComponent({
|
||||
return {
|
||||
getMenuTagOptions,
|
||||
getMenuTagRound,
|
||||
canClose,
|
||||
getMenuTagDrag,
|
||||
isMenuTagTopped,
|
||||
isMenuTagFixed,
|
||||
reorder,
|
||||
tagLabel,
|
||||
closeCurrentMenuTag,
|
||||
getMenuKey,
|
||||
menuTagClick,
|
||||
@ -342,7 +468,7 @@ export default defineComponent({
|
||||
actionState,
|
||||
menuTagContextMenu,
|
||||
dismissContextMenu,
|
||||
setCurrentContextmenuIndex,
|
||||
selectActiveContext,
|
||||
maximize,
|
||||
reload,
|
||||
globalMainLayoutLoad,
|
||||
@ -351,7 +477,6 @@ export default defineComponent({
|
||||
render() {
|
||||
const { getMenuTagOptions, globalMainLayoutLoad } = this
|
||||
const {
|
||||
canClose,
|
||||
closeCurrentMenuTag,
|
||||
$t,
|
||||
menuTagClick,
|
||||
@ -408,32 +533,102 @@ export default defineComponent({
|
||||
role="group"
|
||||
aria-label={$t('menuTag.pages')}
|
||||
>
|
||||
{getMenuTagOptions.map((curr, idx) => {
|
||||
const active = curr.fullPath === this.getMenuKey
|
||||
const label = curr.meta.i18nKey
|
||||
? $t(curr.meta.i18nKey)
|
||||
: curr.breadcrumbLabel || curr.fullPath
|
||||
<TransitionGroup name="menu-tag" css={false}>
|
||||
{getMenuTagOptions.map((curr, idx) => {
|
||||
const active = curr.fullPath === this.getMenuKey
|
||||
const label = this.tagLabel(curr)
|
||||
const topped = this.isMenuTagTopped(curr)
|
||||
const fixed = this.isMenuTagFixed(curr)
|
||||
const topLabel = topped ? $t('menuTag.topped') : ''
|
||||
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
|
||||
const moveLabel = this.getMenuTagDrag
|
||||
? $t('menuTag.moveNamed', { name: label })
|
||||
: ''
|
||||
|
||||
return (
|
||||
<ShellTab
|
||||
key={curr.fullPath}
|
||||
label={label}
|
||||
active={active}
|
||||
round={this.getMenuTagRound}
|
||||
select={() => menuTagClick(curr)}
|
||||
closeLabel={$t('menuTag.closeNamed', { name: label })}
|
||||
close={
|
||||
canClose(curr)
|
||||
? (restoreFocus) =>
|
||||
closeCurrentMenuTag(idx, restoreFocus)
|
||||
: void 0
|
||||
}
|
||||
contextMenu={(event) => menuTagContextMenu(idx, event)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
return (
|
||||
<ShellTab
|
||||
key={curr.fullPath}
|
||||
label={label}
|
||||
active={active}
|
||||
data-menu-tag-path={curr.fullPath}
|
||||
data-menu-tag-top={topped ? '' : void 0}
|
||||
statusLabel={
|
||||
topLabel && fixedLabel
|
||||
? `${topLabel} · ${fixedLabel}`
|
||||
: topLabel || fixedLabel
|
||||
}
|
||||
round={this.getMenuTagRound}
|
||||
select={() => menuTagClick(curr)}
|
||||
closeLabel={$t('menuTag.closeNamed', { name: label })}
|
||||
close={
|
||||
!fixed
|
||||
? (restoreFocus) =>
|
||||
closeCurrentMenuTag(idx, restoreFocus)
|
||||
: void 0
|
||||
}
|
||||
contextMenu={(event) =>
|
||||
menuTagContextMenu(curr.fullPath, event)
|
||||
}
|
||||
>
|
||||
{{
|
||||
prefix: () => (
|
||||
<>
|
||||
{this.getMenuTagDrag && (
|
||||
<button
|
||||
type="button"
|
||||
class="menu-tag__handle"
|
||||
aria-label={moveLabel}
|
||||
title={moveLabel}
|
||||
aria-keyshortcuts="Shift+ArrowLeft Shift+ArrowRight"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onPointerdown={this.reorder.start}
|
||||
onPointermove={this.reorder.track}
|
||||
onPointerup={this.reorder.drop}
|
||||
onPointercancel={this.reorder.cancelPointer}
|
||||
onLostpointercapture={
|
||||
this.reorder.cancelPointer
|
||||
}
|
||||
onKeydown={this.reorder.moveWithKey}
|
||||
>
|
||||
<RIcon
|
||||
name="action/draggable"
|
||||
size={14}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</button>
|
||||
)}
|
||||
{topped && (
|
||||
<span
|
||||
class="menu-tag__indicator"
|
||||
title={topLabel}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<RIcon
|
||||
name="directional/expanded"
|
||||
size={14}
|
||||
customClassName="menu-tag__top-icon"
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
{fixed && (
|
||||
<span
|
||||
class="menu-tag__indicator"
|
||||
title={fixedLabel}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<RIcon name="action/lock" size={14} />
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
}}
|
||||
</ShellTab>
|
||||
)
|
||||
})}
|
||||
</TransitionGroup>
|
||||
</div>
|
||||
</NScrollbar>
|
||||
<span ref="reorderStatus" class="menu-tag__status" role="status" />
|
||||
<button
|
||||
type="button"
|
||||
class="menu-tag__control menu-tag__control--scroll"
|
||||
@ -494,7 +689,7 @@ export default defineComponent({
|
||||
class="menu-tag__control"
|
||||
aria-label={$t('menuTag.actions')}
|
||||
title={$t('menuTag.actions')}
|
||||
onClick={this.setCurrentContextmenuIndex}
|
||||
onClick={this.selectActiveContext}
|
||||
>
|
||||
<RIcon name="action/more" size={16} />
|
||||
</button>
|
||||
|
||||
293
apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts
Normal file
293
apps/admin/src/layout/components/MenuTag/use-tag-reorder.ts
Normal file
@ -0,0 +1,293 @@
|
||||
import { useEventListener } from '@vueuse/core'
|
||||
import { onScopeDispose, watch } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
type Placement = 'before' | 'after'
|
||||
|
||||
interface DropTarget {
|
||||
path: string
|
||||
placement: Placement
|
||||
}
|
||||
|
||||
interface DropMarker {
|
||||
tab: HTMLElement
|
||||
placement: Placement
|
||||
}
|
||||
|
||||
interface Drag {
|
||||
wrapper: HTMLElement
|
||||
handle: HTMLButtonElement
|
||||
item: HTMLElement
|
||||
path: string
|
||||
pointer: number
|
||||
startX: number
|
||||
x: number
|
||||
y: number
|
||||
moved: boolean
|
||||
lastScrollFrame?: number
|
||||
}
|
||||
|
||||
const withinRow = ({ y }: Drag, { top, bottom }: DOMRect) =>
|
||||
y >= top && y <= bottom
|
||||
|
||||
const findDropMarker = (
|
||||
{ wrapper, item, x }: Drag,
|
||||
{ left, right }: DOMRect,
|
||||
scrollDelta = 0,
|
||||
): DropMarker | undefined => {
|
||||
const isTop = item.hasAttribute('data-menu-tag-top')
|
||||
const cursor =
|
||||
Math.min(right, Math.max(left, x)) -
|
||||
wrapper.getBoundingClientRect().left +
|
||||
scrollDelta
|
||||
const tabs = wrapper.children as HTMLCollectionOf<HTMLElement>
|
||||
let first = 0
|
||||
let last = tabs.length
|
||||
|
||||
// 置顶组先于普通组。两组各自按布局中点递增,排序动画不改变中点。
|
||||
while (first < last) {
|
||||
const middle = Math.floor((first + last) / 2)
|
||||
const tab = tabs[middle]
|
||||
const before =
|
||||
tab.hasAttribute('data-menu-tag-top') === isTop
|
||||
? cursor < tab.offsetLeft + tab.offsetWidth / 2
|
||||
: isTop
|
||||
|
||||
if (before) last = middle
|
||||
else first = middle + 1
|
||||
}
|
||||
|
||||
const next = tabs[first]
|
||||
const previous = tabs[first - 1]
|
||||
|
||||
if (next === item || previous === item) return
|
||||
|
||||
if (next && next.hasAttribute('data-menu-tag-top') === isTop)
|
||||
return { tab: next, placement: 'before' }
|
||||
|
||||
if (previous && previous.hasAttribute('data-menu-tag-top') === isTop)
|
||||
return { tab: previous, placement: 'after' }
|
||||
}
|
||||
|
||||
export function useTagReorder(
|
||||
enabled: Ref<boolean>,
|
||||
list: Ref<HTMLElement | null>,
|
||||
scroller: Ref<HTMLElement | null | undefined>,
|
||||
move: (path: string, target: DropTarget, handle: HTMLButtonElement) => void,
|
||||
announceCancellation: () => void,
|
||||
) {
|
||||
let drag: Drag | undefined
|
||||
let marker: DropMarker | undefined
|
||||
let frame: number | undefined
|
||||
|
||||
const mark = (target?: DropMarker) => {
|
||||
if (target?.tab === marker?.tab && target?.placement === marker?.placement)
|
||||
return
|
||||
|
||||
// 临时落点由 DOM 属性绘制,避免触发整排标签的渲染和位移动画测量。
|
||||
marker?.tab.removeAttribute('data-menu-tag-drop')
|
||||
target?.tab.setAttribute('data-menu-tag-drop', target.placement)
|
||||
marker = target
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
const current = drag
|
||||
|
||||
drag = void 0
|
||||
mark()
|
||||
|
||||
if (frame !== void 0) cancelAnimationFrame(frame)
|
||||
|
||||
frame = void 0
|
||||
current?.wrapper.classList.remove('menu-tag-wrapper--dragging')
|
||||
current?.item.removeAttribute('data-menu-tag-dragged')
|
||||
|
||||
if (current?.handle.hasPointerCapture(current.pointer))
|
||||
current.handle.releasePointerCapture(current.pointer)
|
||||
}
|
||||
|
||||
const updateFrame = (time: number) => {
|
||||
frame = void 0
|
||||
const current = drag
|
||||
const element = scroller.value
|
||||
|
||||
if (
|
||||
!current ||
|
||||
!element ||
|
||||
current.item.parentElement !== current.wrapper
|
||||
) {
|
||||
clear()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const viewport = element.getBoundingClientRect()
|
||||
|
||||
if (!withinRow(current, viewport)) {
|
||||
current.lastScrollFrame = void 0
|
||||
mark()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const edge = Math.min(36, viewport.width / 3)
|
||||
const pressure =
|
||||
Math.max(0, current.x - (viewport.right - edge)) -
|
||||
Math.max(0, viewport.left + edge - current.x)
|
||||
let offset = 0
|
||||
let nextOffset = 0
|
||||
|
||||
if (edge > 0 && pressure !== 0) {
|
||||
const elapsed = Math.min(
|
||||
32,
|
||||
time - (current.lastScrollFrame ?? time - 16),
|
||||
)
|
||||
const distance = Math.max(
|
||||
1,
|
||||
Math.min(1, Math.abs(pressure / edge)) * elapsed * 0.65,
|
||||
)
|
||||
|
||||
offset = element.scrollLeft
|
||||
const limit = element.scrollWidth - element.clientWidth
|
||||
|
||||
nextOffset = Math.max(
|
||||
0,
|
||||
Math.min(limit, offset + Math.sign(pressure) * distance),
|
||||
)
|
||||
}
|
||||
|
||||
const target = findDropMarker(current, viewport, nextOffset - offset)
|
||||
|
||||
if (!current.item.hasAttribute('data-menu-tag-dragged')) {
|
||||
current.wrapper.classList.add('menu-tag-wrapper--dragging')
|
||||
current.item.setAttribute('data-menu-tag-dragged', '')
|
||||
}
|
||||
|
||||
mark(target)
|
||||
|
||||
if (nextOffset !== offset) {
|
||||
element.scrollLeft = nextOffset
|
||||
current.lastScrollFrame = time
|
||||
frame = requestAnimationFrame(updateFrame)
|
||||
} else {
|
||||
current.lastScrollFrame = void 0
|
||||
}
|
||||
}
|
||||
|
||||
const cancel = () => {
|
||||
if (drag?.moved) announceCancellation()
|
||||
|
||||
clear()
|
||||
}
|
||||
|
||||
const start = (event: PointerEvent) => {
|
||||
if (!enabled.value || drag || !event.isPrimary || event.button !== 0) return
|
||||
|
||||
const handle = event.currentTarget as HTMLButtonElement
|
||||
const item = handle.closest<HTMLElement>('[data-menu-tag-path]')
|
||||
const path = item?.dataset.menuTagPath
|
||||
const wrapper = list.value
|
||||
|
||||
if (!item || !path || !wrapper || item.parentElement !== wrapper) return
|
||||
|
||||
handle.setPointerCapture(event.pointerId)
|
||||
drag = {
|
||||
wrapper,
|
||||
handle,
|
||||
item,
|
||||
path,
|
||||
pointer: event.pointerId,
|
||||
startX: event.clientX,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
moved: false,
|
||||
}
|
||||
}
|
||||
|
||||
const updatePointer = (event: PointerEvent) => {
|
||||
if (drag?.pointer !== event.pointerId) return
|
||||
|
||||
drag.x = event.clientX
|
||||
drag.y = event.clientY
|
||||
drag.moved ||= Math.abs(drag.x - drag.startX) >= 5
|
||||
|
||||
return drag
|
||||
}
|
||||
|
||||
const track = (event: PointerEvent) => {
|
||||
if (updatePointer(event)?.moved && frame === void 0)
|
||||
frame = requestAnimationFrame(updateFrame)
|
||||
}
|
||||
|
||||
const drop = (event: PointerEvent) => {
|
||||
const current = updatePointer(event)
|
||||
|
||||
if (!current) return
|
||||
|
||||
const viewport = current.moved && scroller.value?.getBoundingClientRect()
|
||||
const target =
|
||||
viewport &&
|
||||
current.item.parentElement === current.wrapper &&
|
||||
withinRow(current, viewport)
|
||||
? findDropMarker(current, viewport)
|
||||
: void 0
|
||||
const targetPath = target?.tab.dataset.menuTagPath
|
||||
|
||||
clear()
|
||||
|
||||
if (target && targetPath)
|
||||
move(
|
||||
current.path,
|
||||
{ path: targetPath, placement: target.placement },
|
||||
current.handle,
|
||||
)
|
||||
}
|
||||
|
||||
const cancelPointer = (event: PointerEvent) => {
|
||||
if (drag?.pointer === event.pointerId) cancel()
|
||||
}
|
||||
|
||||
const moveWithKey = (event: KeyboardEvent) => {
|
||||
if (
|
||||
!enabled.value ||
|
||||
!event.shiftKey ||
|
||||
event.altKey ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
event.isComposing ||
|
||||
(event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')
|
||||
)
|
||||
return
|
||||
|
||||
event.preventDefault()
|
||||
const handle = event.currentTarget as HTMLButtonElement
|
||||
const item = handle.closest<HTMLElement>('[data-menu-tag-path]')
|
||||
const placement = event.key === 'ArrowLeft' ? 'before' : 'after'
|
||||
const neighbor =
|
||||
placement === 'before'
|
||||
? item?.previousElementSibling
|
||||
: item?.nextElementSibling
|
||||
const path = item?.dataset.menuTagPath
|
||||
const target =
|
||||
neighbor instanceof HTMLElement ? neighbor.dataset.menuTagPath : void 0
|
||||
|
||||
if (path && target) move(path, { path: target, placement }, handle)
|
||||
}
|
||||
|
||||
useEventListener(
|
||||
'keydown',
|
||||
(event) => {
|
||||
if (event.key !== 'Escape' || !drag) return
|
||||
|
||||
event.preventDefault()
|
||||
cancel()
|
||||
},
|
||||
{ capture: true },
|
||||
)
|
||||
watch(enabled, (allowed) => {
|
||||
if (!allowed) cancel()
|
||||
})
|
||||
onScopeDispose(clear)
|
||||
|
||||
return { start, track, drop, cancelPointer, moveWithKey }
|
||||
}
|
||||
@ -20,15 +20,40 @@
|
||||
}
|
||||
|
||||
.layout-breadcrumb,
|
||||
.layout-breadcrumb__current {
|
||||
.layout-breadcrumb__item {
|
||||
min-inline-size: 0;
|
||||
}
|
||||
|
||||
.layout-breadcrumb__item {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
max-inline-size: 100%;
|
||||
}
|
||||
|
||||
.layout-breadcrumb__icon {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
place-items: center;
|
||||
inline-size: 1em;
|
||||
block-size: 1em;
|
||||
|
||||
img {
|
||||
inline-size: 100%;
|
||||
block-size: 100%;
|
||||
object-fit: contain;
|
||||
}
|
||||
}
|
||||
|
||||
.layout-breadcrumb__current {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
color: var(--r-text);
|
||||
}
|
||||
|
||||
.layout-breadcrumb__current .layout-breadcrumb__label {
|
||||
min-inline-size: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import './index.scss'
|
||||
import { useDevice } from '@/hooks'
|
||||
import { useMenuActions, useMenuGetters } from '@/store'
|
||||
import { useMenuActions, useMenuGetters, useSettingGetters } from '@/store'
|
||||
import type { AppMenuOption } from '@/types'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { NBreadcrumb, NBreadcrumbItem, NDropdown } from 'naive-ui'
|
||||
import type { DropdownOption } from 'naive-ui'
|
||||
import { TransitionGroup } from 'vue'
|
||||
@ -11,6 +12,7 @@ export default defineComponent({
|
||||
setup() {
|
||||
const { changeMenuModelValue } = useMenuActions()
|
||||
const { getBreadcrumbOptions } = useMenuGetters()
|
||||
const { getBreadcrumbIcon, getBreadcrumbIconFallback } = useSettingGetters()
|
||||
const { isTabletOrSmaller } = useDevice()
|
||||
|
||||
const dropdownSelect = (key: string | number, option: DropdownOption) => {
|
||||
@ -33,53 +35,78 @@ export default defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
getBreadcrumbOptions,
|
||||
dropdownSelect,
|
||||
breadcrumbItemClick,
|
||||
isTabletOrSmaller,
|
||||
const renderIcon = (option: Pick<AppMenuOption, 'icon'>) => {
|
||||
if (!getBreadcrumbIcon.value) return null
|
||||
|
||||
const icon =
|
||||
option.icon?.() ??
|
||||
(getBreadcrumbIconFallback.value ? (
|
||||
<RIcon name="navigation/document" size="1em" />
|
||||
) : null)
|
||||
|
||||
return (
|
||||
icon && (
|
||||
<span class="layout-breadcrumb__icon" aria-hidden="true">
|
||||
{icon}
|
||||
</span>
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
const renderLabel = (
|
||||
option: AppMenuOption,
|
||||
current: boolean,
|
||||
compact = false,
|
||||
) => (
|
||||
<span
|
||||
class={[
|
||||
'layout-breadcrumb__item',
|
||||
{ 'layout-breadcrumb__current': compact },
|
||||
]}
|
||||
aria-current={current ? 'page' : void 0}
|
||||
>
|
||||
{renderIcon(option)}
|
||||
<span class="layout-breadcrumb__label">
|
||||
{!compact && typeof option.label === 'function'
|
||||
? option.label()
|
||||
: option.breadcrumbLabel}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
|
||||
return () => {
|
||||
const trail = getBreadcrumbOptions.value
|
||||
const current = trail.at(-1)
|
||||
|
||||
if (isTabletOrSmaller.value)
|
||||
return current && renderLabel(current, true, true)
|
||||
|
||||
return (
|
||||
<NBreadcrumb class="layout-breadcrumb">
|
||||
<TransitionGroup name="breadcrumb" appear>
|
||||
{trail.map((option) => (
|
||||
<NBreadcrumbItem
|
||||
key={option.fullPath}
|
||||
onClick={() => breadcrumbItemClick(option)}
|
||||
>
|
||||
{option.children && option.children.length > 1 ? (
|
||||
<NDropdown
|
||||
labelField="breadcrumbLabel"
|
||||
keyField="fullPath"
|
||||
options={option.children}
|
||||
renderIcon={renderIcon}
|
||||
onSelect={dropdownSelect}
|
||||
>
|
||||
{renderLabel(option, option === current)}
|
||||
</NDropdown>
|
||||
) : (
|
||||
renderLabel(option, option === current)
|
||||
)}
|
||||
</NBreadcrumbItem>
|
||||
))}
|
||||
</TransitionGroup>
|
||||
</NBreadcrumb>
|
||||
)
|
||||
}
|
||||
},
|
||||
render() {
|
||||
const { isTabletOrSmaller, getBreadcrumbOptions } = this
|
||||
const { dropdownSelect, breadcrumbItemClick } = this
|
||||
|
||||
return isTabletOrSmaller ? (
|
||||
<span class="layout-breadcrumb__current" aria-current="page">
|
||||
{getBreadcrumbOptions.at(-1)?.breadcrumbLabel}
|
||||
</span>
|
||||
) : (
|
||||
<NBreadcrumb class="layout-breadcrumb">
|
||||
<TransitionGroup tag="li" name="breadcrumb" appear>
|
||||
{getBreadcrumbOptions.map((curr) => (
|
||||
<NBreadcrumbItem
|
||||
key={curr.fullPath}
|
||||
onClick={breadcrumbItemClick.bind(this, curr)}
|
||||
>
|
||||
<NDropdown
|
||||
labelField="breadcrumbLabel"
|
||||
keyField="fullPath"
|
||||
options={
|
||||
curr.children && curr.children?.length > 1
|
||||
? curr.children
|
||||
: []
|
||||
}
|
||||
onSelect={dropdownSelect.bind(this)}
|
||||
>
|
||||
{{
|
||||
default: () => (
|
||||
<span>
|
||||
{curr.label && typeof curr.label === 'function'
|
||||
? curr.label()
|
||||
: curr.breadcrumbLabel}
|
||||
</span>
|
||||
),
|
||||
}}
|
||||
</NDropdown>
|
||||
</NBreadcrumbItem>
|
||||
))}
|
||||
</TransitionGroup>
|
||||
</NBreadcrumb>
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
@ -39,7 +39,12 @@ export default defineComponent({
|
||||
getContentTransition,
|
||||
getMenuTagSwitch,
|
||||
getMenuTagRound,
|
||||
getMenuTagTop,
|
||||
getMenuTagFixed,
|
||||
getMenuTagDrag,
|
||||
getBreadcrumbSwitch,
|
||||
getBreadcrumbIcon,
|
||||
getBreadcrumbIconFallback,
|
||||
getCopyrightSwitch,
|
||||
getColorWeakness,
|
||||
} = useSettingGetters()
|
||||
@ -79,8 +84,13 @@ export default defineComponent({
|
||||
})
|
||||
const switches = [
|
||||
['breadcrumbSwitch', getBreadcrumbSwitch],
|
||||
['breadcrumbIcon', getBreadcrumbIcon],
|
||||
['breadcrumbIconFallback', getBreadcrumbIconFallback],
|
||||
['menuTagSwitch', getMenuTagSwitch],
|
||||
['menuTagRound', getMenuTagRound],
|
||||
['menuTagTop', getMenuTagTop],
|
||||
['menuTagFixed', getMenuTagFixed],
|
||||
['menuTagDrag', getMenuTagDrag],
|
||||
['copyrightSwitch', getCopyrightSwitch],
|
||||
['colorWeakness', getColorWeakness],
|
||||
] as const
|
||||
|
||||
@ -22,7 +22,15 @@
|
||||
"closeLeft": "Close tabs on the left",
|
||||
"closeRight": "Close tabs on the right",
|
||||
"closeCurrent": "Close current tab",
|
||||
"closeAll": "Close all and open workspace",
|
||||
"closeAll": "Close all tabs",
|
||||
"menuExample": "Menu hook example",
|
||||
"menuOverview": "Overview",
|
||||
"menuReports": "Reports",
|
||||
"menuDaily": "Daily report",
|
||||
"menuMonthly": "Monthly report",
|
||||
"menuReveal": "Reveal monthly report",
|
||||
"menuClear": "Clear selection",
|
||||
"menuState": "Selected {selected} · Expanded {expanded}",
|
||||
"contentTop": "Scroll content to top",
|
||||
"content300": "Scroll content to 300 px",
|
||||
"siderTop": "Scroll sidebar to top",
|
||||
@ -55,6 +63,7 @@
|
||||
"useWatermark": "Update the global watermark and control visibility. An empty string keeps the previous text.",
|
||||
"useAppNavigation": "Navigate by menu object, full path or zero-based top-level index. Returns an awaitable navigation result.",
|
||||
"useSiderBar": "Close tabs and their neighbors by path, index or tab object.",
|
||||
"useMenu": "Manage NMenu selection and expanded groups. Reveal a menu item through the component instance.",
|
||||
"useContentScroll": "Obtain a scroll function in setup. Each call resolves the current layout instance.",
|
||||
"useSiderScroll": "Scroll the current sidebar. Safely does nothing when top navigation has no sidebar.",
|
||||
"useDevice": "Observe viewport size and apply a custom tablet breakpoint. Resize the window to see changes.",
|
||||
|
||||
@ -9,6 +9,15 @@
|
||||
"maximize": "Maximize page",
|
||||
"reload": "Reload page",
|
||||
"newWindow": "Open in new window",
|
||||
"top": "Move to front",
|
||||
"untop": "Remove from front group",
|
||||
"topped": "At the front",
|
||||
"fix": "Protect tab",
|
||||
"unfix": "Unprotect tab",
|
||||
"fixed": "Protected",
|
||||
"moveNamed": "Reorder {name} (drag or press Shift + Left/Right)",
|
||||
"moved": "{name} moved to position {position}",
|
||||
"moveCanceled": "Tab reordering canceled",
|
||||
"scrollLeft": "Scroll tabs left",
|
||||
"scrollRight": "Scroll tabs right",
|
||||
"actions": "Tab actions"
|
||||
|
||||
@ -42,8 +42,13 @@
|
||||
"placement": "Drawer position",
|
||||
"display": "Interface display",
|
||||
"breadcrumbSwitch": "Breadcrumbs",
|
||||
"breadcrumbIcon": "Show breadcrumb icons",
|
||||
"breadcrumbIconFallback": "Use a fallback for missing icons",
|
||||
"menuTagSwitch": "Page tabs",
|
||||
"menuTagRound": "Pill-shaped page tabs",
|
||||
"menuTagTop": "Allow moving tabs to the front",
|
||||
"menuTagFixed": "Allow protecting tabs",
|
||||
"menuTagDrag": "Allow dragging to reorder tabs",
|
||||
"copyrightSwitch": "Footer",
|
||||
"colorWeakness": "Color vision mode",
|
||||
"displayHint": "Show or hide breadcrumbs, page tabs, and the footer together, or adjust each below.",
|
||||
|
||||
@ -22,7 +22,15 @@
|
||||
"closeLeft": "关闭左侧标签",
|
||||
"closeRight": "关闭右侧标签",
|
||||
"closeCurrent": "关闭当前标签",
|
||||
"closeAll": "关闭全部并进入工作区",
|
||||
"closeAll": "关闭全部",
|
||||
"menuExample": "菜单 Hook 示例",
|
||||
"menuOverview": "概览",
|
||||
"menuReports": "报表",
|
||||
"menuDaily": "日报",
|
||||
"menuMonthly": "月报",
|
||||
"menuReveal": "展开月报所在菜单",
|
||||
"menuClear": "清除选中项",
|
||||
"menuState": "选中 {selected} · 展开 {expanded}",
|
||||
"contentTop": "内容滚动到顶部",
|
||||
"content300": "内容滚动到 300px",
|
||||
"siderTop": "侧栏滚动到顶部",
|
||||
@ -55,6 +63,7 @@
|
||||
"useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。",
|
||||
"useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。",
|
||||
"useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。",
|
||||
"useMenu": "管理 NMenu 的选中项和展开项,并通过实例方法展开指定菜单。",
|
||||
"useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。",
|
||||
"useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。",
|
||||
"useDevice": "观察窗口尺寸并按自定义断点判断是否为平板或更小设备。缩放窗口查看结果。",
|
||||
|
||||
@ -9,6 +9,15 @@
|
||||
"maximize": "最大化当前页面",
|
||||
"reload": "刷新当前页面",
|
||||
"newWindow": "新窗口打开",
|
||||
"top": "置顶标签页",
|
||||
"untop": "取消置顶",
|
||||
"topped": "已置顶",
|
||||
"fix": "固定标签页",
|
||||
"unfix": "取消固定",
|
||||
"fixed": "已固定",
|
||||
"moveNamed": "排序 {name}(拖拽或 Shift + ←/→)",
|
||||
"moved": "{name} 已移至第 {position} 位",
|
||||
"moveCanceled": "已取消标签页排序",
|
||||
"scrollLeft": "向左滚动标签页",
|
||||
"scrollRight": "向右滚动标签页",
|
||||
"actions": "标签页操作"
|
||||
|
||||
@ -42,8 +42,13 @@
|
||||
"placement": "设置抽屉位置",
|
||||
"display": "界面显示",
|
||||
"breadcrumbSwitch": "面包屑导航",
|
||||
"breadcrumbIcon": "显示面包屑图标",
|
||||
"breadcrumbIconFallback": "缺少图标时显示占位图标",
|
||||
"menuTagSwitch": "页面标签",
|
||||
"menuTagRound": "胶囊形页面标签",
|
||||
"menuTagTop": "允许置顶标签",
|
||||
"menuTagFixed": "允许固定标签",
|
||||
"menuTagDrag": "允许拖拽排序标签",
|
||||
"copyrightSwitch": "页脚信息",
|
||||
"colorWeakness": "色弱模式",
|
||||
"displayHint": "批量调整面包屑、页面标签和页脚,也可继续逐项设置。",
|
||||
|
||||
@ -93,8 +93,9 @@ See the [layout guide](../layout/README.md) for usage and slots.
|
||||
## Menu synchronization
|
||||
|
||||
- Build menu trees and path indexes when roles change or during explicit refresh. Do not mutate original module routes. After navigation, synchronize tabs and breadcrumbs from Vue Router's matched records.
|
||||
- No business root is mandatory or protected. System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Never fabricate an active tab from cached selection or the first visible menu.
|
||||
- System states (`/welcome`, `/403`, `/404`, `/500`) have no active business menu, breadcrumb, or tab. Derive the active tab from the actual route.
|
||||
- Preserve existing cache keys and tab-list structure. Restore historical tabs using registered routes and roles, ignoring deleted or inaccessible routes. Write the session cache only when the tab list changes.
|
||||
- Store tab order and optional `topped` and `fixed` flags in the ordered tab list. Topped tabs form the leading group while the preference is enabled. The close actions in `useSiderBar` preserve fixed tabs while their preference is enabled. Role or account reconciliation still prunes unavailable tabs.
|
||||
- Keep one tag per concrete pathname and preserve its latest query/hash in `fullPath`; keep the sidebar's `menuKey` canonical. Derive menu selection from Router rather than a persisted key.
|
||||
- Update KeepAlive in recent-access order, deduplicate, trim to its limit, and prune closed or revoked tab names. Merge themes only when the effective theme changes; observe color-weakness mode and document titles independently.
|
||||
|
||||
|
||||
@ -63,6 +63,11 @@ export const useMenuActions = () => {
|
||||
collapsedMenu,
|
||||
spliceMenTagOptions,
|
||||
setMenuTagOptions,
|
||||
isMenuTagTopped,
|
||||
isMenuTagFixed,
|
||||
toggleMenuTagTop,
|
||||
toggleMenuTagFixed,
|
||||
moveMenuTag,
|
||||
resolveOption,
|
||||
updateMenuState,
|
||||
setupAppMenu,
|
||||
@ -73,6 +78,11 @@ export const useMenuActions = () => {
|
||||
collapsedMenu,
|
||||
spliceMenTagOptions,
|
||||
setMenuTagOptions,
|
||||
isMenuTagTopped,
|
||||
isMenuTagFixed,
|
||||
toggleMenuTagTop,
|
||||
toggleMenuTagFixed,
|
||||
moveMenuTag,
|
||||
resolveOption,
|
||||
updateMenuState,
|
||||
setupAppMenu,
|
||||
|
||||
@ -39,12 +39,19 @@ export const useSettingGetters = () => {
|
||||
*/
|
||||
const getMenuTagSwitch = computed(() => variable.menuTagSwitch)
|
||||
const getMenuTagRound = computed(() => variable.menuTagRound)
|
||||
const getMenuTagTop = computed(() => variable.menuTagTop)
|
||||
const getMenuTagFixed = computed(() => variable.menuTagFixed)
|
||||
const getMenuTagDrag = computed(() => variable.menuTagDrag)
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 获取面包屑开关。
|
||||
*/
|
||||
const getBreadcrumbSwitch = computed(() => variable.breadcrumbSwitch)
|
||||
const getBreadcrumbIcon = computed(() => variable.breadcrumbIcon)
|
||||
const getBreadcrumbIconFallback = computed(
|
||||
() => variable.breadcrumbIconFallback,
|
||||
)
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
@ -134,7 +141,12 @@ export const useSettingGetters = () => {
|
||||
getAppTheme,
|
||||
getMenuTagSwitch,
|
||||
getMenuTagRound,
|
||||
getMenuTagTop,
|
||||
getMenuTagFixed,
|
||||
getMenuTagDrag,
|
||||
getBreadcrumbSwitch,
|
||||
getBreadcrumbIcon,
|
||||
getBreadcrumbIconFallback,
|
||||
getLocaleLanguage,
|
||||
getLockScreenSwitch,
|
||||
getCopyrightSwitch,
|
||||
|
||||
@ -19,6 +19,7 @@ import { pick } from 'lodash-es'
|
||||
import { NEllipsis } from 'naive-ui'
|
||||
import type { LocationQuery } from 'vue-router'
|
||||
import { piniaNavigationHistoryStore } from '../navigation-history'
|
||||
import { piniaSettingStore } from '../setting'
|
||||
import { piniaSigningStore } from '../signing'
|
||||
import { pickRouteRecordNormalizedConstant } from './constant'
|
||||
import {
|
||||
@ -67,16 +68,14 @@ export const piniaMenuStore = defineStore(
|
||||
breadcrumbOptions: [], // 面包屑菜单
|
||||
currentMenuOption: null, // 当前激活菜单项
|
||||
})
|
||||
const settings = piniaSettingStore()
|
||||
const signing = piniaSigningStore()
|
||||
const navigationHistory = piniaNavigationHistoryStore()
|
||||
const menuIndex = new Map<
|
||||
string,
|
||||
{ option: AppMenuOption; parentPath: string }
|
||||
>()
|
||||
const cacheTags = () => {
|
||||
retainKeepAliveInclude(
|
||||
new Set(menuState.menuTagOptions.map(({ name }) => name)),
|
||||
)
|
||||
const persistTags = () => {
|
||||
setStorage(
|
||||
APP_CATCH_KEY.appMenuTagOptions,
|
||||
menuState.menuTagOptions.map(
|
||||
@ -89,20 +88,119 @@ export const piniaMenuStore = defineStore(
|
||||
breadcrumbLabel,
|
||||
fullPath,
|
||||
closeable,
|
||||
topped,
|
||||
fixed,
|
||||
}) => ({
|
||||
name,
|
||||
key,
|
||||
path,
|
||||
show,
|
||||
meta,
|
||||
meta: {
|
||||
...meta,
|
||||
icon: typeof meta.icon === 'string' ? meta.icon : void 0,
|
||||
extra: meta.extra && {
|
||||
...meta.extra,
|
||||
icon:
|
||||
typeof meta.extra.icon === 'string'
|
||||
? meta.extra.icon
|
||||
: void 0,
|
||||
},
|
||||
},
|
||||
breadcrumbLabel,
|
||||
fullPath,
|
||||
closeable,
|
||||
topped,
|
||||
fixed,
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const syncOpenTags = () => {
|
||||
retainKeepAliveInclude(
|
||||
new Set(menuState.menuTagOptions.map(({ name }) => name)),
|
||||
)
|
||||
persistTags()
|
||||
}
|
||||
|
||||
const isMenuTagTopped = (tag?: MenuTagOptions) =>
|
||||
settings.menuTagTop && tag?.topped === true
|
||||
|
||||
const isMenuTagFixed = (tag?: MenuTagOptions) =>
|
||||
settings.menuTagFixed && tag?.fixed === true
|
||||
|
||||
const orderMenuTags = (tags: MenuTagOptions[]) =>
|
||||
settings.menuTagTop
|
||||
? [
|
||||
...tags.filter(isMenuTagTopped),
|
||||
...tags.filter((tag) => !isMenuTagTopped(tag)),
|
||||
]
|
||||
: tags
|
||||
|
||||
const toggleMenuTagTop = (fullPath: string) => {
|
||||
if (!settings.menuTagTop) return false
|
||||
|
||||
const tags = [...menuState.menuTagOptions]
|
||||
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||
|
||||
if (index < 0) return false
|
||||
|
||||
const [tag] = tags.splice(index, 1)
|
||||
const topped = !tag.topped
|
||||
const firstRegular = tags.findIndex((tag) => !isMenuTagTopped(tag))
|
||||
const insert = topped ? 0 : firstRegular < 0 ? tags.length : firstRegular
|
||||
|
||||
tags.splice(insert, 0, { ...tag, topped })
|
||||
menuState.menuTagOptions = tags
|
||||
persistTags()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const toggleMenuTagFixed = (fullPath: string) => {
|
||||
if (!settings.menuTagFixed) return
|
||||
|
||||
const tags = menuState.menuTagOptions
|
||||
const index = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||
|
||||
if (index < 0) return
|
||||
|
||||
tags[index] = { ...tags[index], fixed: !tags[index].fixed }
|
||||
persistTags()
|
||||
}
|
||||
|
||||
const moveMenuTag = (
|
||||
fullPath: string,
|
||||
targetPath: string,
|
||||
placement: 'before' | 'after',
|
||||
) => {
|
||||
if (!settings.menuTagDrag) return false
|
||||
|
||||
const tags = [...menuState.menuTagOptions]
|
||||
const from = tags.findIndex((tag) => tag.fullPath === fullPath)
|
||||
const to = tags.findIndex((tag) => tag.fullPath === targetPath)
|
||||
|
||||
if (
|
||||
from < 0 ||
|
||||
to < 0 ||
|
||||
from === to ||
|
||||
isMenuTagTopped(tags[from]) !== isMenuTagTopped(tags[to])
|
||||
)
|
||||
return false
|
||||
|
||||
const insert = to + Number(placement === 'after') - Number(from < to)
|
||||
|
||||
if (from === insert) return false
|
||||
|
||||
const [tag] = tags.splice(from, 1)
|
||||
|
||||
tags.splice(insert, 0, tag)
|
||||
menuState.menuTagOptions = tags
|
||||
persistTags()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const clearActiveMenu = () => {
|
||||
menuState.menuKey = null
|
||||
menuState.currentMenuOption = null
|
||||
@ -206,11 +304,11 @@ export const piniaMenuStore = defineStore(
|
||||
!option.meta.windowOpen,
|
||||
)
|
||||
|
||||
isAppend
|
||||
? menuState.menuTagOptions.push(...arr)
|
||||
: (menuState.menuTagOptions = arr)
|
||||
menuState.menuTagOptions = orderMenuTags(
|
||||
isAppend ? [...menuState.menuTagOptions, ...arr] : arr,
|
||||
)
|
||||
|
||||
cacheTags()
|
||||
syncOpenTags()
|
||||
|
||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||
}
|
||||
@ -237,12 +335,14 @@ export const piniaMenuStore = defineStore(
|
||||
|
||||
if (tagIndex < 0) {
|
||||
menuState.menuTagOptions.push(option)
|
||||
cacheTags()
|
||||
syncOpenTags()
|
||||
} else if (
|
||||
menuState.menuTagOptions[tagIndex].fullPath !== option.fullPath
|
||||
) {
|
||||
menuState.menuTagOptions[tagIndex] = option
|
||||
cacheTags()
|
||||
const { topped, fixed } = menuState.menuTagOptions[tagIndex]
|
||||
|
||||
menuState.menuTagOptions[tagIndex] = { ...option, topped, fixed }
|
||||
syncOpenTags()
|
||||
}
|
||||
|
||||
setBreadcrumbOptions(option.key)
|
||||
@ -372,22 +472,25 @@ export const piniaMenuStore = defineStore(
|
||||
menuState.currentMenuOption = null
|
||||
menuState.breadcrumbOptions = []
|
||||
|
||||
const restoredTags = menuState.menuTagOptions.flatMap(({ fullPath }) => {
|
||||
if (typeof fullPath !== 'string' || !fullPath.startsWith('/')) return []
|
||||
const restoredTags = menuState.menuTagOptions.flatMap(
|
||||
({ fullPath, topped, fixed }) => {
|
||||
if (typeof fullPath !== 'string' || !fullPath.startsWith('/'))
|
||||
return []
|
||||
|
||||
const option = optionForRoute(resolve(fullPath))
|
||||
const option = optionForRoute(resolve(fullPath))
|
||||
|
||||
return option && !option.meta.sameLevel && !option.meta.windowOpen
|
||||
? [option]
|
||||
: []
|
||||
})
|
||||
return option && !option.meta.sameLevel && !option.meta.windowOpen
|
||||
? [{ ...option, topped: topped === true, fixed: fixed === true }]
|
||||
: []
|
||||
},
|
||||
)
|
||||
|
||||
menuState.menuTagOptions = [
|
||||
menuState.menuTagOptions = orderMenuTags([
|
||||
...new Map(
|
||||
restoredTags.map((option) => [resolve(option.fullPath).path, option]),
|
||||
).values(),
|
||||
]
|
||||
cacheTags()
|
||||
])
|
||||
syncOpenTags()
|
||||
|
||||
const active = optionForRoute(route)
|
||||
|
||||
@ -426,13 +529,29 @@ export const piniaMenuStore = defineStore(
|
||||
const spliceMenTagOptions = (idx: number, length = 1) => {
|
||||
const r = menuState.menuTagOptions.splice(idx, length)
|
||||
|
||||
cacheTags()
|
||||
syncOpenTags()
|
||||
|
||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
watch(
|
||||
() => settings.menuTagTop,
|
||||
(enabled) => {
|
||||
if (!enabled) return
|
||||
|
||||
const current = menuState.menuTagOptions
|
||||
const ordered = orderMenuTags(current)
|
||||
|
||||
if (ordered.every((tag, index) => tag === current[index])) return
|
||||
|
||||
menuState.menuTagOptions = ordered
|
||||
persistTags()
|
||||
},
|
||||
{ flush: 'sync' },
|
||||
)
|
||||
|
||||
watch(
|
||||
[
|
||||
() => signing.signingCallback.role,
|
||||
@ -446,7 +565,7 @@ export const piniaMenuStore = defineStore(
|
||||
if (!current[1]) {
|
||||
menuState.options = []
|
||||
menuIndex.clear()
|
||||
cacheTags()
|
||||
syncOpenTags()
|
||||
clearActiveMenu()
|
||||
|
||||
return
|
||||
@ -488,6 +607,11 @@ export const piniaMenuStore = defineStore(
|
||||
collapsedMenu,
|
||||
spliceMenTagOptions,
|
||||
setMenuTagOptions,
|
||||
isMenuTagTopped,
|
||||
isMenuTagFixed,
|
||||
toggleMenuTagTop,
|
||||
toggleMenuTagFixed,
|
||||
moveMenuTag,
|
||||
resolveOption,
|
||||
updateMenuState,
|
||||
setupAppMenu,
|
||||
|
||||
@ -1,12 +1,17 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { resolveIconName } from '@/icons'
|
||||
import type { AppMenuKey, AppMenuOption } from '@/types/modules/app'
|
||||
import type {
|
||||
AppMenuKey,
|
||||
AppMenuOption,
|
||||
MenuTagOptions,
|
||||
} from '@/types/modules/app'
|
||||
import { getStorage } from '@/utils/cache'
|
||||
import { isValueType } from '@/utils/core'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { NTag } from 'naive-ui'
|
||||
import type { TagProps } from 'naive-ui'
|
||||
import { cloneVNode } from 'vue'
|
||||
import { piniaSettingStore } from '../setting'
|
||||
|
||||
/**
|
||||
@ -148,7 +153,7 @@ export const createMenuIcon = (option: AppMenuOption) => {
|
||||
}
|
||||
|
||||
if (isValueType<object>(icon, 'Object')) {
|
||||
return () => icon
|
||||
return () => cloneVNode(icon)
|
||||
}
|
||||
|
||||
const name = resolveIconName(icon)
|
||||
@ -228,7 +233,7 @@ export const getCatchMenuKey = () => {
|
||||
* @returns 获取缓存的菜单标签页
|
||||
*/
|
||||
export const getCatchMenuTagOptions = () => {
|
||||
const cached = getStorage<AppMenuOption[]>(
|
||||
const cached = getStorage<MenuTagOptions[]>(
|
||||
APP_CATCH_KEY.appMenuTagOptions,
|
||||
'sessionStorage',
|
||||
)
|
||||
|
||||
@ -11,7 +11,12 @@ type OmitKeys =
|
||||
| 'menuConfig'
|
||||
| 'menuTagSwitch'
|
||||
| 'menuTagRound'
|
||||
| 'menuTagTop'
|
||||
| 'menuTagFixed'
|
||||
| 'menuTagDrag'
|
||||
| 'breadcrumbSwitch'
|
||||
| 'breadcrumbIcon'
|
||||
| 'breadcrumbIconFallback'
|
||||
| 'copyrightSwitch'
|
||||
| 'drawerPlacement'
|
||||
| 'colorWeakness'
|
||||
@ -59,8 +64,13 @@ const defaultSettingConfig: Readonly<Config> = {
|
||||
// 多标签页开关
|
||||
menuTagSwitch: true,
|
||||
menuTagRound: false,
|
||||
menuTagTop: true,
|
||||
menuTagFixed: true,
|
||||
menuTagDrag: true,
|
||||
// 面包屑开关
|
||||
breadcrumbSwitch: true,
|
||||
breadcrumbIcon: true,
|
||||
breadcrumbIconFallback: true,
|
||||
// 底部区域开关
|
||||
copyrightSwitch: true,
|
||||
// 默认设置出现位置
|
||||
|
||||
@ -61,8 +61,13 @@ const preferences = v.strictObject({
|
||||
),
|
||||
drawerPlacement: v.picklist(['left', 'right']),
|
||||
breadcrumbSwitch: flag,
|
||||
breadcrumbIcon: v.optional(flag, true),
|
||||
breadcrumbIconFallback: v.optional(flag, true),
|
||||
menuTagSwitch: flag,
|
||||
menuTagRound: v.optional(flag, false),
|
||||
menuTagTop: v.optional(flag, true),
|
||||
menuTagFixed: v.optional(flag, true),
|
||||
menuTagDrag: v.optional(flag, true),
|
||||
copyrightSwitch: flag,
|
||||
colorWeakness: flag,
|
||||
menuConfig: v.strictObject({
|
||||
|
||||
@ -38,7 +38,12 @@ export interface SettingState {
|
||||
_appTheme: boolean
|
||||
menuTagSwitch: boolean
|
||||
menuTagRound: boolean
|
||||
menuTagTop: boolean
|
||||
menuTagFixed: boolean
|
||||
menuTagDrag: boolean
|
||||
breadcrumbSwitch: boolean
|
||||
breadcrumbIcon: boolean
|
||||
breadcrumbIconFallback: boolean
|
||||
localeLanguage: string
|
||||
lockScreenSwitch: boolean
|
||||
watermarkSwitch: boolean
|
||||
|
||||
@ -12,9 +12,11 @@ import {
|
||||
useWatermark,
|
||||
} from '@/hooks'
|
||||
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
|
||||
import { useMenuKeyboard } from '@ray-template/admin-shell'
|
||||
import { useMenu } from '@ray-template/composables/useMenu'
|
||||
import { RIcon } from '@ray-template/ui/icon'
|
||||
import { useTimeoutFn } from '@vueuse/core'
|
||||
import { NButton, NFlex, NInput, NTag } from 'naive-ui'
|
||||
import { NButton, NFlex, NInput, NMenu, NTag } from 'naive-ui'
|
||||
import DemoPage from '../components/DemoPage'
|
||||
import HookExample from '../hooks/HookExample'
|
||||
|
||||
@ -32,6 +34,22 @@ export default defineComponent({
|
||||
const spinning = useSpinning()
|
||||
const maximize = useMaximize()
|
||||
const tags = useSiderBar()
|
||||
const menuKeyboard = useMenuKeyboard(false)
|
||||
const { menuRef, menuProps, showOption } = useMenu({
|
||||
options: [
|
||||
{ key: 'overview', label: () => text('menuOverview') },
|
||||
{
|
||||
key: 'reports',
|
||||
label: () => text('menuReports'),
|
||||
children: [
|
||||
{ key: 'daily', label: () => text('menuDaily') },
|
||||
{ key: 'monthly', label: () => text('menuMonthly') },
|
||||
],
|
||||
},
|
||||
],
|
||||
value: 'monthly',
|
||||
expandedKeys: [],
|
||||
})
|
||||
const { navigationTo } = useAppNavigation()
|
||||
const contentScrollTo = useContentScroll()
|
||||
const siderScrollTo = useSiderScroll()
|
||||
@ -70,7 +88,7 @@ export default defineComponent({
|
||||
title={label('templateTitle')}
|
||||
description={text('templateIntro')}
|
||||
eyebrow={label('templateEyebrow')}
|
||||
meta="9 Hooks"
|
||||
meta="10 Hooks"
|
||||
>
|
||||
<h2 class="r-demo-section-heading">{label('appearanceAndPage')}</h2>
|
||||
<div class="r-hook-grid">
|
||||
@ -256,6 +274,59 @@ export default defineComponent({
|
||||
</NFlex>
|
||||
),
|
||||
)}
|
||||
{example(
|
||||
'useMenu',
|
||||
`const { menuRef, menuProps, showOption } = useMenu({
|
||||
options: [
|
||||
{ key: 'overview', label: 'Overview' },
|
||||
{
|
||||
key: 'reports',
|
||||
label: 'Reports',
|
||||
children: [
|
||||
{ key: 'daily', label: 'Daily report' },
|
||||
{ key: 'monthly', label: 'Monthly report' },
|
||||
],
|
||||
},
|
||||
],
|
||||
value: 'monthly',
|
||||
expandedKeys: [],
|
||||
})
|
||||
|
||||
// TSX
|
||||
<NMenu ref={menuRef} {...menuProps} />
|
||||
<NButton onClick={() => showOption('monthly')}>Reveal monthly report</NButton>`,
|
||||
() => (
|
||||
<NFlex vertical>
|
||||
<nav
|
||||
aria-label={text('menuExample')}
|
||||
onKeydown={menuKeyboard.onKeydown}
|
||||
>
|
||||
<NMenu
|
||||
ref={menuRef}
|
||||
{...menuProps}
|
||||
nodeProps={menuKeyboard.nodeProps}
|
||||
/>
|
||||
</nav>
|
||||
<NFlex>
|
||||
<NButton onClick={() => showOption('monthly')}>
|
||||
{text('menuReveal')}
|
||||
</NButton>
|
||||
<NButton
|
||||
disabled={menuProps.value === null}
|
||||
onClick={() => (menuProps.value = null)}
|
||||
>
|
||||
{text('menuClear')}
|
||||
</NButton>
|
||||
</NFlex>
|
||||
<code>
|
||||
{t('menuState', {
|
||||
selected: menuProps.value ?? '—',
|
||||
expanded: menuProps.expandedKeys?.join(', ') || '—',
|
||||
})}
|
||||
</code>
|
||||
</NFlex>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<h2 class="r-demo-section-heading">{label('scrollControls')}</h2>
|
||||
<div class="r-hook-grid">
|
||||
|
||||
@ -41,6 +41,14 @@ updateSettingState('layoutConfig', {
|
||||
|
||||
在「偏好设置 → 外观 → 界面显示」开启「胶囊形页面标签」可切换标签形状。默认关闭;刷新后保留,也可随偏好文件导出和导入。
|
||||
|
||||
### 页面标签与面包屑
|
||||
|
||||
- 右键点击标签或打开右侧「标签页操作」菜单,可置顶或固定标签。置顶将标签移至最左侧,取消置顶时移到普通标签组开头。固定会阻止单个关闭和批量关闭操作。
|
||||
- 拖动标签左侧的手柄可以排序。也可聚焦手柄后按 Shift + ← 或 Shift + →。置顶标签和普通标签各自组内排序。顺序、置顶和固定状态随当前会话刷新恢复。
|
||||
- 面包屑复用菜单配置中的图标,支持 SVG 图标名和代码路由里的图片 VNode。缺少图标时使用统一的文档图标。窄屏显示当前路径项及其图标。
|
||||
|
||||
「偏好设置 → 外观 → 界面显示」提供五个独立开关,默认全部开启。关闭固定或置顶开关会暂停对应效果并保留标签标记,重新开启后恢复生效。关闭面包屑图标开关会一并隐藏占位图标,也可单独关闭占位图标。
|
||||
|
||||
## 菜单图标
|
||||
|
||||
展开侧栏、移动端抽屉和顶部导航默认使用 20 px 的图标;折叠侧栏默认 22 px,方便只凭图形辨认菜单。线性图标跟随菜单状态和明暗主题变色。可在「偏好设置 → 菜单」调整「图标尺寸」与「折叠图标尺寸」,修改即时生效。紧凑和舒适预设只调整宽度、缩进和图标尺寸;折叠方式、侧栏折叠/展开、回到菜单顶部和刷新菜单也可直接操作。当前布局没有桌面侧栏时,侧栏快捷操作禁用,已配置的尺寸仍会保留。
|
||||
|
||||
@ -2,14 +2,14 @@
|
||||
|
||||
模板的公开 Hooks 从 `@/hooks` 导入。与具体组件一起使用的 `useForm`、`useModal`、`useChart`、`useFlow` 从 `@/components` 导入,请看对应组件页。`useRequest` 从 `@/axios` 导入。
|
||||
|
||||
| 需求 | API |
|
||||
| ---------------------------- | ---------------------------------- |
|
||||
| 跳转页面,操作标签和菜单标记 | [导航与菜单](./hooks/navigation) |
|
||||
| 内容最大化、重载或滚动 | [布局与滚动](./hooks/layout) |
|
||||
| 主题、语言、水印 | [主题与国际化](./hooks/appearance) |
|
||||
| 分页与右键菜单 | [组件交互](./hooks/interaction) |
|
||||
| 窗口尺寸、元素全屏和日期 | [窗口与日期](./hooks/browser) |
|
||||
| DOM 截图、打印 | [截图与打印](./hooks/output) |
|
||||
| 需求 | API |
|
||||
| -------------------------------------- | ---------------------------------- |
|
||||
| 封装菜单、跳转页面、操作标签和菜单标记 | [导航与菜单](./hooks/navigation) |
|
||||
| 内容最大化、重载或滚动 | [布局与滚动](./hooks/layout) |
|
||||
| 主题、语言、水印 | [主题与国际化](./hooks/appearance) |
|
||||
| 分页与右键菜单 | [组件交互](./hooks/interaction) |
|
||||
| 窗口尺寸、元素全屏和日期 | [窗口与日期](./hooks/browser) |
|
||||
| DOM 截图、打印 | [截图与打印](./hooks/output) |
|
||||
|
||||
需要订阅、事件或清理的 Hook 在 `setup()` 或有效的 Vue effect scope 中创建。在 DOM 挂载后或用户操作时执行截图、打印和全屏。`BasicTarget` 接受元素、ref 或 getter,解析规则和可用元素类型见[Vue 与 DOM 目标](./utils/browser#vue-目标解析)。
|
||||
|
||||
|
||||
@ -55,6 +55,53 @@ export function useTableNavigation() {
|
||||
}
|
||||
```
|
||||
|
||||
## useMenu
|
||||
|
||||
`useMenu(options?)` 封装 Naive UI 的 `NMenu`,可用于独立菜单示例、局部导航或选择器。传入原生菜单配置即可使用横向和纵向布局、分组、分隔线、自定义字段和渲染函数。
|
||||
|
||||
<AdminExample path="/template-hooks" title="选中与展开菜单项" focus="useMenu" deferred />
|
||||
|
||||
| 返回值 | 用途 |
|
||||
| ------------------------- | ------------------------------------------------------------------------ |
|
||||
| `menuRef` | 绑定到 `NMenu` 的组件引用。 |
|
||||
| `menuProps` | 浅响应式的菜单属性,直接绑定给组件。异步加载时替换 `menuProps.options`。 |
|
||||
| `showOption(key?)` | 展开指定菜单项的父级。省略 key 时展开当前选中项的父级,选中值保持原样。 |
|
||||
| `deriveResponsiveState()` | 重新计算启用了 `responsive` 的横向菜单的溢出状态。 |
|
||||
|
||||
传入 `value` 或 `expandedKeys` 后,Hook 会先同步对应的属性,再调用原始更新回调。`value: null` 表示清除选中项,`expandedKeys: []` 表示收起所有分组。省略某个属性时,由 `NMenu` 管理该状态并应用 `defaultValue`、`defaultExpandedKeys` 或 `defaultExpandAll`。组件挂载后即可调用实例方法,异步更新选项后可用 `nextTick()` 等待组件接收新数据。
|
||||
|
||||
```tsx
|
||||
import { useMenu } from '@/hooks'
|
||||
import { NButton, NMenu } from 'naive-ui'
|
||||
import { defineComponent } from 'vue'
|
||||
|
||||
export default defineComponent({
|
||||
setup() {
|
||||
const { menuRef, menuProps, showOption } = useMenu({
|
||||
options: [
|
||||
{ key: 'overview', label: '概览' },
|
||||
{
|
||||
key: 'reports',
|
||||
label: '报表',
|
||||
children: [{ key: 'monthly', label: '月报' }],
|
||||
},
|
||||
],
|
||||
value: 'monthly',
|
||||
expandedKeys: [],
|
||||
})
|
||||
|
||||
return () => (
|
||||
<>
|
||||
<NMenu ref={menuRef} {...menuProps} />
|
||||
<NButton onClick={() => showOption()}>展开选中项</NButton>
|
||||
</>
|
||||
)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
工作区导航由 `useAppNavigation` 和路由菜单 Store 管理。独立菜单可用 `useMenu`,工作区菜单的键盘行为由 `useMenuKeyboard` 提供。[Naive UI Menu API](https://www.naiveui.com/zh-CN/components/menu#API)
|
||||
|
||||
<span id="useapproot-兼容接口"></span>
|
||||
|
||||
## useAppRoot(兼容接口) {#useapproot}
|
||||
@ -74,14 +121,14 @@ export function useOpenWorkspace() {
|
||||
|
||||
操作工作区的标签页。接受 `CloseMenuTag` 的方法可传从 0 开始的索引、与标签 `fullPath` 匹配的字符串或标签对象。
|
||||
|
||||
| 方法 | 行为 |
|
||||
| ---------------------------------------------------- | ------------------------------------------------------------ |
|
||||
| `getCurrentTagIndex()` | 当前标签索引;找不到返回 `-1`。 |
|
||||
| `checkCloseLeft(target)` / `checkCloseRight(target)` | 检查目标对应方向是否有标签可关。 |
|
||||
| `close(target)` | 关闭业务标签;激活项切到相邻项,最后一项关闭后进入空工作区。 |
|
||||
| `closeLeft(target)` / `closeRight(target)` | 关闭目标左侧或右侧标签。需要时切换至目标。 |
|
||||
| `closeOther(target)` | 只保留目标并激活。 |
|
||||
| `closeAll()` | 清空业务标签及其缓存,进入 `/welcome`,不依赖业务首页。 |
|
||||
| 方法 | 行为 |
|
||||
| ---------------------------------------------------- | -------------------------------------------------------------------------- |
|
||||
| `getCurrentTagIndex()` | 当前标签索引;找不到返回 `-1`。 |
|
||||
| `checkCloseLeft(target)` / `checkCloseRight(target)` | 检查目标对应方向是否有标签可关。 |
|
||||
| `close(target)` | 关闭可关闭的业务标签。关闭激活项时切到相邻项,关闭最后一项后进入空工作区。 |
|
||||
| `closeLeft(target)` / `closeRight(target)` | 关闭目标对应方向的可关闭标签。激活项被关闭时切换至目标。 |
|
||||
| `closeOther(target)` | 保留目标和固定标签,并激活目标。 |
|
||||
| `closeAll()` | 关闭可关闭标签,优先保留当前固定页面,再尝试第一个固定标签或 `/welcome`。 |
|
||||
|
||||
不要在存在未保存表单的工作流里直接调用批量关闭;这些方法不会替业务处理未保存确认。
|
||||
|
||||
@ -114,4 +161,4 @@ export function useUnreadBadge() {
|
||||
}
|
||||
```
|
||||
|
||||
源码:[useAppNavigation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppNavigation.ts) · [useAppRoot](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppRoot.ts) · [useSiderBar](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useSiderBar.ts) · [useBadge](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useBadge.ts) · [useVueRouter](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useVueRouter.ts)
|
||||
源码:[useMenu](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/packages/composables/src/useMenu.ts) · [useAppNavigation](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppNavigation.ts) · [useAppRoot](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useAppRoot.ts) · [useSiderBar](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useSiderBar.ts) · [useBadge](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useBadge.ts) · [useVueRouter](https://github.com/XiaoDaiGua-Ray/ray-template/blob/main/apps/admin/src/hooks/template/useVueRouter.ts)
|
||||
|
||||
@ -25,7 +25,7 @@
|
||||
|
||||
`depthSearchAppMenu(options, key)` 从菜单树按完整路径查找菜单项。`changeMenuModelValue` 不返回 Router 的导航 Promise;需要等待守卫结果时使用 Router 或 `navigationTo`。更新角色后还要同步服务端授权及直接路由校验,菜单过滤本身不能授权。
|
||||
|
||||
`piniaMenuStore` 在 Local Storage 只持久化 `menuKey`、`collapsed`。标签列表单独使用 Session Storage 的 `appMenuTagOptions`。当前路由变化会重新同步菜单与面包屑,避免手工写缓存制造冲突。
|
||||
`piniaMenuStore` 在 Local Storage 持久化 `collapsed`。标签列表以 Session Storage 的 `appMenuTagOptions` 保存顺序及可选的 `topped`、`fixed` 标记。刷新时根据当前路由与权限恢复,访问被撤销的页面也会移出列表。当前路由变化会同步选中菜单与面包屑。
|
||||
|
||||
## KeepAlive Store
|
||||
|
||||
|
||||
@ -4,24 +4,26 @@
|
||||
|
||||
## Getters
|
||||
|
||||
| Getter | 字段与默认行为 |
|
||||
| ---------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| `getLayoutConfig` | `layoutConfig`,布局模式和工作区尺寸,见下表。 |
|
||||
| `getDrawerPlacement` | `drawerPlacement`,设置抽屉方向,默认 `right`。 |
|
||||
| `getPrimaryColorOverride` | Naive UI 生效的 token 覆盖,由当前风格、明暗和用户主色计算。 |
|
||||
| `getThemeStyle` / `getCustomPrimaryColor` | 界面风格与手动主色。默认 `modern`,未指定手动主色时使用风格原色。 |
|
||||
| `getAppTheme` / `getAppThemeStr` | `_appTheme` 为实际深色布尔值,`appTheme` 为 `light/dark/auto` 模式,初始 `light`。 |
|
||||
| `getLocaleLanguage` | `localeLanguage`,应用语言,默认读取历史值或系统默认配置。 |
|
||||
| `getMenuTagSwitch` / `getBreadcrumbSwitch` | `menuTagSwitch` / `breadcrumbSwitch`,默认显示标签和面包屑。 |
|
||||
| `getLockScreenSwitch` | `lockScreenSwitch`,锁屏设置弹窗显隐,默认关,不持久化。 |
|
||||
| `getCopyrightSwitch` | `copyrightSwitch`,默认显示版权区。 |
|
||||
| `getContentTransition` | `contentTransition`,路由切换动画,默认 `scale`。 |
|
||||
| `getWatermarkSwitch` / `getWatermarkConfig` | `watermarkSwitch` 默认关;配置包含文字、字体大小、行高、宽高、偏移、间隔、旋转和 `cross`。 |
|
||||
| `getAppRootRoute` | `appRootRoute`,默认 `{ name: 'Dashboard', path: '/dashboard' }`。 |
|
||||
| `getSideBarLogo` | `sideBarLogo`,`icon`、`title`、`url`、`jumpType`。默认 `logo/ray`,站内跳转到仪表盘。 |
|
||||
| `getKeepAliveConfig` | `keepAliveConfig`,默认开启、最多 10 个、排除列表为空。 |
|
||||
| `getMenuConfig` | `menuConfig`,侧栏、折叠、图标、手风琴与滚动配置。 |
|
||||
| `getColorWeakness` / `getDynamicDocumentTitle` | `colorWeakness` 默认关,`dynamicDocumentTitle` 默认开。 |
|
||||
| Getter | 字段与默认行为 |
|
||||
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
|
||||
| `getLayoutConfig` | `layoutConfig`,布局模式和工作区尺寸,见下表。 |
|
||||
| `getDrawerPlacement` | `drawerPlacement`,设置抽屉方向,默认 `right`。 |
|
||||
| `getPrimaryColorOverride` | Naive UI 生效的 token 覆盖,由当前风格、明暗和用户主色计算。 |
|
||||
| `getThemeStyle` / `getCustomPrimaryColor` | 界面风格与手动主色。默认 `modern`,未指定手动主色时使用风格原色。 |
|
||||
| `getAppTheme` / `getAppThemeStr` | `_appTheme` 为实际深色布尔值,`appTheme` 为 `light/dark/auto` 模式,初始 `light`。 |
|
||||
| `getLocaleLanguage` | `localeLanguage`,应用语言,默认读取历史值或系统默认配置。 |
|
||||
| `getMenuTagSwitch` / `getBreadcrumbSwitch` | `menuTagSwitch` / `breadcrumbSwitch`,默认显示标签和面包屑。 |
|
||||
| `getMenuTagTop` / `getMenuTagFixed` / `getMenuTagDrag` | `menuTagTop` / `menuTagFixed` / `menuTagDrag`,默认启用标签置顶、固定和拖拽排序。 |
|
||||
| `getBreadcrumbIcon` / `getBreadcrumbIconFallback` | `breadcrumbIcon` / `breadcrumbIconFallback`,默认显示菜单图标和缺图时的占位图标。 |
|
||||
| `getLockScreenSwitch` | `lockScreenSwitch`,锁屏设置弹窗显隐,默认关,不持久化。 |
|
||||
| `getCopyrightSwitch` | `copyrightSwitch`,默认显示版权区。 |
|
||||
| `getContentTransition` | `contentTransition`,路由切换动画,默认 `scale`。 |
|
||||
| `getWatermarkSwitch` / `getWatermarkConfig` | `watermarkSwitch` 默认关;配置包含文字、字体大小、行高、宽高、偏移、间隔、旋转和 `cross`。 |
|
||||
| `getAppRootRoute` | `appRootRoute`,默认 `{ name: 'Dashboard', path: '/dashboard' }`。 |
|
||||
| `getSideBarLogo` | `sideBarLogo`,`icon`、`title`、`url`、`jumpType`。默认 `logo/ray`,站内跳转到仪表盘。 |
|
||||
| `getKeepAliveConfig` | `keepAliveConfig`,默认开启、最多 10 个、排除列表为空。 |
|
||||
| `getMenuConfig` | `menuConfig`,侧栏、折叠、图标、手风琴与滚动配置。 |
|
||||
| `getColorWeakness` / `getDynamicDocumentTitle` | `colorWeakness` 默认关,`dynamicDocumentTitle` 默认开。 |
|
||||
|
||||
`layoutConfig` 的 `mode` 为 `side`(默认)、`top`、`mixed`。`contentWidth` 默认 `fluid`,也可取 `fixed`。`contentMaxWidth` 默认 1200,限制在 640–2560;`contentPadding` 默认 16,限制在 0–48;`fixedHeader`、`fixedFooter` 默认开启。旧缓存水合时补齐字段并规范化范围。
|
||||
|
||||
|
||||
@ -9,6 +9,7 @@ export const ShellTab = defineComponent({
|
||||
label: { type: String, required: true },
|
||||
active: Boolean,
|
||||
round: Boolean,
|
||||
statusLabel: { type: String, default: '' },
|
||||
closeLabel: { type: String, default: '' },
|
||||
select: { type: Function as PropType<() => void>, required: true },
|
||||
close: {
|
||||
@ -20,7 +21,7 @@ export const ShellTab = defineComponent({
|
||||
default: void 0,
|
||||
},
|
||||
},
|
||||
setup(props) {
|
||||
setup(props, { slots }) {
|
||||
const setNativeCloseLabel = ({ el }: VNode) => {
|
||||
if (!(el instanceof HTMLElement)) return
|
||||
|
||||
@ -46,10 +47,14 @@ export const ShellTab = defineComponent({
|
||||
}}
|
||||
onClose={(event) => props.close?.(event.detail === 0)}
|
||||
>
|
||||
{slots.prefix?.()}
|
||||
<button
|
||||
type="button"
|
||||
class="menu-tag__tab"
|
||||
aria-current={props.active ? 'page' : void 0}
|
||||
aria-label={
|
||||
props.statusLabel ? `${props.label} · ${props.statusLabel}` : void 0
|
||||
}
|
||||
title={props.label}
|
||||
onKeydown={(event) => {
|
||||
if (event.key === 'Delete' && props.close) {
|
||||
|
||||
@ -12,6 +12,7 @@
|
||||
"./element": "./src/element.ts",
|
||||
"./types": "./src/types.ts",
|
||||
"./usePagination": "./src/usePagination.ts",
|
||||
"./useMenu": "./src/useMenu.ts",
|
||||
"./useElementFullscreen": "./src/useElementFullscreen.ts",
|
||||
"./vue": "./src/vue/index.ts",
|
||||
"./vue/*": "./src/vue/*.ts",
|
||||
|
||||
@ -7,5 +7,6 @@ export * from './useDevice'
|
||||
export * from './useDomToImage'
|
||||
export * from './useElementFullscreen'
|
||||
export * from './usePagination'
|
||||
export * from './useMenu'
|
||||
export * from './usePrint'
|
||||
export * from './useDayjs'
|
||||
|
||||
68
packages/composables/src/useMenu.ts
Normal file
68
packages/composables/src/useMenu.ts
Normal file
@ -0,0 +1,68 @@
|
||||
import type { MaybeArray } from '@ray-template/utils/types'
|
||||
import type { MenuInst, MenuOption, MenuProps } from 'naive-ui'
|
||||
import { shallowReactive, shallowRef } from 'vue'
|
||||
import { call } from './vue/call'
|
||||
|
||||
type MenuKey = NonNullable<MenuProps['value']>
|
||||
type ExpandedKeys = NonNullable<MenuProps['expandedKeys']>
|
||||
type ValueListener = (key: MenuKey, option: MenuOption) => void
|
||||
type ExpandedKeysListener = (keys: ExpandedKeys) => void
|
||||
|
||||
export interface UseMenuOptions extends Omit<
|
||||
MenuProps,
|
||||
| 'onUpdateValue'
|
||||
| 'onUpdate:value'
|
||||
| 'onUpdateExpandedKeys'
|
||||
| 'onUpdate:expandedKeys'
|
||||
> {
|
||||
onUpdateValue?: MaybeArray<ValueListener>
|
||||
'onUpdate:value'?: MaybeArray<ValueListener>
|
||||
onUpdateExpandedKeys?: MaybeArray<ExpandedKeysListener>
|
||||
'onUpdate:expandedKeys'?: MaybeArray<ExpandedKeysListener>
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param options NMenu 的初始配置与更新回调
|
||||
*
|
||||
* @description
|
||||
* 仅同步显式控制的选中值和展开项;省略对应字段时由 NMenu 应用其默认配置。
|
||||
*
|
||||
* @returns 菜单实例引用、浅响应式属性和实例方法。
|
||||
*/
|
||||
export function useMenu(options: UseMenuOptions = {}) {
|
||||
const {
|
||||
onUpdateValue,
|
||||
'onUpdate:value': onValueUpdate,
|
||||
onUpdateExpandedKeys,
|
||||
'onUpdate:expandedKeys': onExpandedKeysUpdate,
|
||||
...props
|
||||
} = options
|
||||
const menuRef = shallowRef<MenuInst | null>(null)
|
||||
const menuProps = shallowReactive({
|
||||
...props,
|
||||
onUpdateValue(key: MenuKey, option: MenuOption) {
|
||||
if (menuProps.value !== void 0) menuProps.value = key
|
||||
|
||||
if (onUpdateValue) call(onUpdateValue, key, option)
|
||||
|
||||
if (onValueUpdate) call(onValueUpdate, key, option)
|
||||
},
|
||||
onUpdateExpandedKeys(keys: ExpandedKeys) {
|
||||
if (menuProps.expandedKeys !== void 0) menuProps.expandedKeys = keys
|
||||
|
||||
if (onExpandedKeysUpdate) call(onExpandedKeysUpdate, keys)
|
||||
|
||||
if (onUpdateExpandedKeys) call(onUpdateExpandedKeys, keys)
|
||||
},
|
||||
})
|
||||
|
||||
const showOption: MenuInst['showOption'] = (key) =>
|
||||
menuRef.value?.showOption(key)
|
||||
const deriveResponsiveState: MenuInst['deriveResponsiveState'] = () =>
|
||||
menuRef.value?.deriveResponsiveState()
|
||||
|
||||
return { menuRef, menuProps, showOption, deriveResponsiveState }
|
||||
}
|
||||
|
||||
export type UseMenuReturn = ReturnType<typeof useMenu>
|
||||
@ -1,4 +1,4 @@
|
||||
import type { VNode } from 'vue'
|
||||
import type { VNode, VNodeChild } from 'vue'
|
||||
import type { AppRouteMeta } from './types'
|
||||
|
||||
export type Key = string | number
|
||||
@ -8,6 +8,7 @@ export interface AppMenuOption {
|
||||
key: Key
|
||||
path: string
|
||||
label: string | (() => VNode)
|
||||
icon?: () => VNodeChild
|
||||
show?: boolean
|
||||
children?: AppMenuOption[]
|
||||
meta: AppRouteMeta
|
||||
@ -18,6 +19,8 @@ export interface AppMenuOption {
|
||||
|
||||
export interface MenuTagOptions extends AppMenuOption {
|
||||
closeable?: boolean
|
||||
topped?: boolean
|
||||
fixed?: boolean
|
||||
}
|
||||
|
||||
export type AppMenuKey = Key | null
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user