mirror of
https://github.com/XiaoDaiGua-Ray/ray-template.git
synced 2026-11-17 16:13:36 +08:00
feat: refine workspace UI and harden shared components
This commit is contained in:
parent
a7ffb862a2
commit
1409d4a028
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
@ -88,6 +88,7 @@
|
||||
"Popselect",
|
||||
"precommit",
|
||||
"qrcode",
|
||||
"rgba",
|
||||
"sider",
|
||||
"siderbar",
|
||||
"snapline",
|
||||
|
||||
@ -7,5 +7,6 @@ A Vue 3 + TSX admin template with an admin application, a documentation site, an
|
||||
- For complex tasks, the lead agent may choose to use subagents under the [delegation guidelines](harness/README.md#using-subagents-when-useful), when the host supports them and current permissions allow it. Delegation needs no separate approval. The lead agent owns integration and final verification.
|
||||
- Write agent guidance and internal engineering documentation in English. Preserve the intended languages of product copy and reader-facing documentation.
|
||||
- Follow the [comment style](docs/comment-style.md) when adding or editing comments. Maintain both Chinese and English product copy. For visible behavior changes, use [browser verification](harness/README.md#browser-verification) only for affected pages, actions, and dimensions.
|
||||
- For custom CSS, follow the [style contract](docs/ui-design.md#custom-css-contract): consume semantic theme tokens and the shell's runtime layout variables so style, color mode, primary color, and layout preferences keep working. Keep provider ownership and scoped overrides explicit.
|
||||
- Select relevant tests or `pnpm harness verify <scope>` using the [verification scope](harness/README.md#choosing-the-verification-scope). Small changes do not default to full checks or a UI/UX sweep. Use full checks for integration risk, releases, or an explicit request; CI keeps `pnpm check`. Within one task, rerun only checks affected by subsequent changes. Report what was and was not verified.
|
||||
- Establish engineering facts from current source, manifests, and the lockfile. Keep sensitive data out of source, prompts, and evidence. Commits, pushes, and deployments require user authorization.
|
||||
|
||||
79
__test__/app/boot-feedback.spec.ts
Normal file
79
__test__/app/boot-feedback.spec.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { runInNewContext } from 'node:vm'
|
||||
|
||||
const html = readFileSync(
|
||||
resolve(process.cwd(), 'apps/admin/index.html'),
|
||||
'utf8',
|
||||
)
|
||||
const source = new DOMParser()
|
||||
.parseFromString(html, 'text/html')
|
||||
.querySelector('script:not([type])')!.textContent!
|
||||
|
||||
describe('pre-bundle startup failure feedback', () => {
|
||||
let splash: HTMLElement
|
||||
let listener: EventListener
|
||||
|
||||
beforeEach(() => {
|
||||
splash = document.createElement('div')
|
||||
splash.id = 'pre-loading-animation'
|
||||
document.body.append(splash)
|
||||
const subscribe = vi.spyOn(window, 'addEventListener')
|
||||
|
||||
runInNewContext(source, {
|
||||
window,
|
||||
document,
|
||||
localStorage,
|
||||
HTMLScriptElement,
|
||||
ErrorEvent,
|
||||
})
|
||||
listener = subscribe.mock.calls.find(
|
||||
([type]) => type === 'error',
|
||||
)![1] as EventListener
|
||||
subscribe.mockRestore()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
window.removeEventListener('error', listener, true)
|
||||
splash.remove()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('captures a non-bubbling entry/module-graph load error', () => {
|
||||
const script = document.createElement('script')
|
||||
|
||||
script.type = 'module'
|
||||
document.body.append(script)
|
||||
script.dispatchEvent(new Event('error'))
|
||||
expect(splash.dataset.state).toBe('failed')
|
||||
script.remove()
|
||||
})
|
||||
|
||||
it('handles parse, link, or evaluation errors reported on the window', () => {
|
||||
window.dispatchEvent(
|
||||
new ErrorEvent('error', {
|
||||
message: 'The requested module does not provide an export',
|
||||
error: new SyntaxError('Missing export'),
|
||||
}),
|
||||
)
|
||||
expect(splash.dataset.state).toBe('failed')
|
||||
})
|
||||
|
||||
it('does not mistake a decorative image failure for a startup failure', () => {
|
||||
const image = document.createElement('img')
|
||||
|
||||
document.body.append(image)
|
||||
image.dispatchEvent(new Event('error'))
|
||||
expect(splash.dataset.state).toBeUndefined()
|
||||
image.remove()
|
||||
})
|
||||
|
||||
it('stops observing after the mounted application has removed the splash', () => {
|
||||
const unsubscribe = vi.spyOn(window, 'removeEventListener')
|
||||
|
||||
splash.remove()
|
||||
window.dispatchEvent(new ErrorEvent('error'))
|
||||
expect(unsubscribe).toHaveBeenCalledWith('error', listener, true)
|
||||
expect(document.getElementById('pre-loading-animation')).toBeNull()
|
||||
})
|
||||
})
|
||||
115
__test__/app/dashboard-shortcuts.spec.tsx
Normal file
115
__test__/app/dashboard-shortcuts.spec.tsx
Normal file
@ -0,0 +1,115 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { nextTick, ref } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import type { AppMenuOption } from '../../apps/admin/src/types'
|
||||
import Dashboard from '../../apps/admin/src/views/dashboard'
|
||||
|
||||
const menus = ref<AppMenuOption[]>([])
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useMenuGetters: () => ({ getMenuOptions: menus }),
|
||||
}))
|
||||
vi.mock('@/hooks', () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}))
|
||||
|
||||
const menu = (
|
||||
path: string,
|
||||
children?: AppMenuOption[],
|
||||
show = true,
|
||||
): AppMenuOption => ({
|
||||
path,
|
||||
fullPath: path,
|
||||
key: path,
|
||||
name: path,
|
||||
label: path,
|
||||
meta: {},
|
||||
children,
|
||||
show,
|
||||
})
|
||||
|
||||
const setupDashboard = async () => {
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: ['/dashboard', '/template-hooks', '/layout-demo', '/svg-icons'].map(
|
||||
(path) => ({
|
||||
path,
|
||||
component: { render: () => null },
|
||||
}),
|
||||
),
|
||||
})
|
||||
|
||||
await router.push('/dashboard')
|
||||
const wrapper = mount(Dashboard, { global: { plugins: [router] } })
|
||||
const links = () => wrapper.findAll('.r-dashboard-shortcut')
|
||||
|
||||
return { router, wrapper, links }
|
||||
}
|
||||
|
||||
it('shows declared destinations below visible menu groups and navigates to the chosen page', async () => {
|
||||
menus.value = [
|
||||
menu('/examples', [
|
||||
menu('/hooks', [menu('/template-hooks')]),
|
||||
menu('/layout-demo'),
|
||||
menu('/resources', [menu('/svg-icons')]),
|
||||
]),
|
||||
]
|
||||
const { router, wrapper, links } = await setupDashboard()
|
||||
|
||||
try {
|
||||
expect(links().map((link) => link.attributes('href'))).toEqual([
|
||||
'/template-hooks',
|
||||
'/layout-demo',
|
||||
'/svg-icons',
|
||||
])
|
||||
await links()[2].trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/svg-icons')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('prunes hidden ancestors and hidden leaves instead of exposing their destinations', async () => {
|
||||
menus.value = [
|
||||
menu('/hidden-root', [menu('/template-hooks')], false),
|
||||
menu('/visible-root', [
|
||||
menu('/hidden-nested', [menu('/layout-demo')], false),
|
||||
menu('/svg-icons'),
|
||||
]),
|
||||
]
|
||||
const { wrapper, links } = await setupDashboard()
|
||||
|
||||
try {
|
||||
expect(links().map((link) => link.attributes('href'))).toEqual([
|
||||
'/svg-icons',
|
||||
])
|
||||
menus.value[1].children![1].show = false
|
||||
await nextTick()
|
||||
expect(links()).toHaveLength(0)
|
||||
expect(wrapper.find('.r-dashboard-shortcuts').exists()).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('reacts to the current permitted tree without inventing a default or treating external entries as pages', async () => {
|
||||
menus.value = [menu('/template-hooks')]
|
||||
const { router, wrapper, links } = await setupDashboard()
|
||||
|
||||
try {
|
||||
expect(links()).toHaveLength(1)
|
||||
menus.value = [menu('/unrelated')]
|
||||
await nextTick()
|
||||
expect(links()).toHaveLength(0)
|
||||
expect(router.currentRoute.value.path).toBe('/dashboard')
|
||||
|
||||
menus.value = [
|
||||
{ ...menu('/svg-icons'), meta: { windowOpen: 'https://example.com' } },
|
||||
]
|
||||
await nextTick()
|
||||
expect(links()).toHaveLength(0)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
109
__test__/app/doctor.spec.ts
Normal file
109
__test__/app/doctor.spec.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import { runAppDoctor } from '@/doctor'
|
||||
import * as localeDiagnostics from '@/doctor/locale-config'
|
||||
import type { LocaleConfiguration } from '@/doctor/locale-config'
|
||||
|
||||
const configuration = vi.hoisted(() => ({
|
||||
options: [{ key: 'zh-CN' }, { key: 'en-US' }],
|
||||
defaultLocale: 'zh-CN',
|
||||
fallbackLocale: 'zh-CN',
|
||||
dayjsLocales: { 'zh-CN': 'zh-cn', 'en-US': 'en' },
|
||||
defaultDayjsLocale: 'zh-cn',
|
||||
}))
|
||||
|
||||
vi.mock('../../apps/admin/src/app-config/local-config', () => ({
|
||||
get LOCAL_OPTIONS() {
|
||||
return configuration.options
|
||||
},
|
||||
get SYSTEM_DEFAULT_LOCAL() {
|
||||
return configuration.defaultLocale
|
||||
},
|
||||
get SYSTEM_FALLBACK_LOCALE() {
|
||||
return configuration.fallbackLocale
|
||||
},
|
||||
get DAYJS_LOCAL_MAP() {
|
||||
return configuration.dayjsLocales
|
||||
},
|
||||
get DEFAULT_DAYJS_LOCAL() {
|
||||
return configuration.defaultDayjsLocale
|
||||
},
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
configuration.defaultLocale = 'zh-CN'
|
||||
configuration.fallbackLocale = 'zh-CN'
|
||||
})
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('accepts a consistent immutable locale snapshot without changing it', () => {
|
||||
const input = Object.freeze({
|
||||
options: Object.freeze([{ key: 'en-US' }]),
|
||||
defaultLocale: 'en-US',
|
||||
fallbackLocale: 'en-US',
|
||||
dayjsLocales: Object.freeze({ 'en-US': 'en' }),
|
||||
defaultDayjsLocale: 'en',
|
||||
})
|
||||
|
||||
expect(localeDiagnostics.getLocaleConfigIssues(input)).toEqual([])
|
||||
expect(input.options).toEqual([{ key: 'en-US' }])
|
||||
})
|
||||
|
||||
it('reports duplicate choices and all independent membership problems together', () => {
|
||||
const input: LocaleConfiguration = {
|
||||
...configuration,
|
||||
options: [{ key: 'en-US' }, { key: 'en-US' }, { key: 'en-US' }],
|
||||
defaultLocale: 'zh-CN',
|
||||
fallbackLocale: 'fr-FR',
|
||||
defaultDayjsLocale: 'fr',
|
||||
}
|
||||
const issues = localeDiagnostics.getLocaleConfigIssues(input)
|
||||
|
||||
expect(issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
'LOCAL_OPTIONS contains duplicate locale "en-US".',
|
||||
'SYSTEM_DEFAULT_LOCAL "zh-CN" is missing from LOCAL_OPTIONS.',
|
||||
'SYSTEM_FALLBACK_LOCALE "fr-FR" is missing from LOCAL_OPTIONS.',
|
||||
'DAYJS_LOCAL_MAP locale "zh-CN" is missing from LOCAL_OPTIONS.',
|
||||
'DEFAULT_DAYJS_LOCAL "fr" is missing from DAYJS_LOCAL_MAP values.',
|
||||
]),
|
||||
)
|
||||
expect(issues).toHaveLength(5)
|
||||
})
|
||||
|
||||
it('finds a selectable language that has no date-locale mapping', () => {
|
||||
expect(
|
||||
localeDiagnostics.getLocaleConfigIssues({
|
||||
...configuration,
|
||||
dayjsLocales: { 'zh-CN': 'zh-cn' },
|
||||
}),
|
||||
).toEqual(['DAYJS_LOCAL_MAP is missing locale "en-US" from LOCAL_OPTIONS.'])
|
||||
})
|
||||
|
||||
it('reports configuration warnings locally and inspects fresh state on each mount', () => {
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
configuration.defaultLocale = 'missing'
|
||||
expect(() => runAppDoctor()).not.toThrow()
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith(
|
||||
'[Ray Admin doctor] SYSTEM_DEFAULT_LOCAL "missing" is missing from LOCAL_OPTIONS.',
|
||||
)
|
||||
configuration.defaultLocale = 'zh-CN'
|
||||
warn.mockClear()
|
||||
runAppDoctor()
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('contains an unexpected diagnostic exception instead of rejecting application startup', () => {
|
||||
const error = new Error('diagnostic failed')
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
vi.spyOn(localeDiagnostics, 'getLocaleConfigIssues').mockImplementationOnce(
|
||||
() => {
|
||||
throw error
|
||||
},
|
||||
)
|
||||
expect(() => runAppDoctor()).not.toThrow()
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith(
|
||||
'[Ray Admin doctor] Locale diagnostics could not complete.',
|
||||
error,
|
||||
)
|
||||
})
|
||||
241
__test__/app/workspace-states.spec.tsx
Normal file
241
__test__/app/workspace-states.spec.tsx
Normal file
@ -0,0 +1,241 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NResult } from 'naive-ui'
|
||||
import { h, nextTick, ref } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import type { AppMenuOption } from '../../apps/admin/src/types'
|
||||
import PageResult from '../../apps/admin/src/views/error/PageResult'
|
||||
import Welcome from '../../apps/admin/src/views/welcome'
|
||||
|
||||
const menus = ref<AppMenuOption[]>([])
|
||||
const recentPaths = ref<string[]>([])
|
||||
const locale = ref('en-US')
|
||||
const messages: Record<
|
||||
string,
|
||||
Record<string, Record<string, string>>
|
||||
> = Object.fromEntries(
|
||||
['en-US', 'zh-CN'].map((language) => [
|
||||
language,
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
resolve(
|
||||
process.cwd(),
|
||||
`apps/admin/src/locales/lang/${language}/workspaceStates.json`,
|
||||
),
|
||||
'utf8',
|
||||
),
|
||||
),
|
||||
]),
|
||||
)
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useMenuGetters: () => ({ getMenuOptions: menus }),
|
||||
useNavigationHistoryGetters: () => ({ recentPaths }),
|
||||
piniaSigningStore: () => ({ signingCallback: { role: 'viewer' } }),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks', () => ({
|
||||
useI18n: (namespace?: string) => ({
|
||||
t: (key: string) => {
|
||||
if (namespace !== 'workspaceStates') return key
|
||||
|
||||
const [section, field] = key.split('.')
|
||||
|
||||
return messages[locale.value][section]?.[field] ?? key
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const menu = (
|
||||
path: string,
|
||||
extra: Partial<AppMenuOption> = {},
|
||||
): AppMenuOption => ({
|
||||
path,
|
||||
fullPath: path,
|
||||
key: path,
|
||||
name: path,
|
||||
label: path,
|
||||
breadcrumbLabel: path,
|
||||
meta: {},
|
||||
...extra,
|
||||
})
|
||||
|
||||
const createPageRouter = async (path = '/welcome') => {
|
||||
const page = { render: () => null }
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/welcome', name: 'RWelcome', component: page },
|
||||
{ path: '/403', name: 'ErrorPage403', component: page },
|
||||
{ path: '/404', name: 'ErrorPage404', component: page },
|
||||
{ path: '/500', name: 'ErrorPage500', component: page },
|
||||
{ path: '/reports', name: 'Reports', component: page },
|
||||
{ path: '/users', name: 'Users', component: page },
|
||||
{
|
||||
path: '/restricted',
|
||||
name: 'Restricted',
|
||||
component: page,
|
||||
meta: { role: ['admin'] },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
await router.push(path)
|
||||
|
||||
return router
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
menus.value = []
|
||||
recentPaths.value = []
|
||||
locale.value = 'en-US'
|
||||
})
|
||||
|
||||
it('ranks current visible menu entries by recent visits without opening a page', async () => {
|
||||
menus.value = [
|
||||
menu('/group', { children: [menu('/reports'), menu('/users')] }),
|
||||
menu('/hidden', { show: false, children: [menu('/hidden/child')] }),
|
||||
menu('/restricted', { show: false }),
|
||||
menu('/external', { meta: { windowOpen: 'https://example.com' } }),
|
||||
menu('/details/:id'),
|
||||
]
|
||||
recentPaths.value = ['/removed', '/restricted', '/users']
|
||||
const router = await createPageRouter()
|
||||
const wrapper = mount(Welcome, { global: { plugins: [router] } })
|
||||
|
||||
try {
|
||||
expect(
|
||||
wrapper
|
||||
.findAll('.r-welcome__link')
|
||||
.map((link) => link.attributes('href')),
|
||||
).toEqual(['/users', '/reports'])
|
||||
expect(wrapper.findAll('h1')).toHaveLength(1)
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
expect(wrapper.text()).not.toContain('/removed')
|
||||
|
||||
menus.value = [menu('/reports')]
|
||||
await nextTick()
|
||||
expect(
|
||||
wrapper
|
||||
.findAll('.r-welcome__link')
|
||||
.map((link) => link.attributes('href')),
|
||||
).toEqual(['/reports'])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows an honest no-access state and updates its language', async () => {
|
||||
const router = await createPageRouter()
|
||||
const wrapper = mount(Welcome, { global: { plugins: [router] } })
|
||||
|
||||
try {
|
||||
expect(wrapper.find('nav').exists()).toBe(false)
|
||||
expect(wrapper.text()).toContain(messages['en-US'].welcome.noPagesTitle)
|
||||
locale.value = 'zh-CN'
|
||||
await nextTick()
|
||||
expect(wrapper.text()).toContain(messages['zh-CN'].welcome.noPagesTitle)
|
||||
expect(wrapper.get('h1').text()).toBe(messages['zh-CN'].welcome.title)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it.each([
|
||||
['403', 'forbidden'],
|
||||
['404', 'notFound'],
|
||||
['500', 'serverError'],
|
||||
] as const)(
|
||||
'renders %s with its own identity and neutral recovery action',
|
||||
async (status, key) => {
|
||||
const router = await createPageRouter(`/${status}`)
|
||||
const wrapper = mount(PageResult, {
|
||||
props: { status },
|
||||
global: { plugins: [router] },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.getComponent(NResult).props('status')).toBe(status)
|
||||
expect(wrapper.get('h1').text()).toBe(messages['en-US'][key].title)
|
||||
expect(wrapper.get('.error-page__mark').text()).toBe(status)
|
||||
await wrapper.get('button').trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('retries an authorized failed route with its query and hash intact', async () => {
|
||||
const router = await createPageRouter(
|
||||
'/500?from=%2Freports%3Fperiod%3Dweek%23chart',
|
||||
)
|
||||
const wrapper = mount(PageResult, {
|
||||
props: { status: '500' },
|
||||
global: { plugins: [router] },
|
||||
})
|
||||
|
||||
try {
|
||||
const retry = wrapper
|
||||
.findAll('button')
|
||||
.find((button) => button.text() === messages['en-US'].actions.retry)!
|
||||
|
||||
await retry.trigger('click')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.fullPath).toBe(
|
||||
'/reports?period=week#chart',
|
||||
)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['//example.com', '/500', '/restricted'])(
|
||||
'omits retry for unsafe/unavailable target %s',
|
||||
async (from) => {
|
||||
const router = await createPageRouter(
|
||||
`/500?from=${encodeURIComponent(from)}`,
|
||||
)
|
||||
const wrapper = mount(PageResult, {
|
||||
props: { status: '500' },
|
||||
global: { plugins: [router] },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.findAll('button').map((button) => button.text())).toEqual([
|
||||
messages['en-US'].actions.workspace,
|
||||
])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('preserves custom title, description, content and footer configuration', async () => {
|
||||
const router = await createPageRouter('/404')
|
||||
const wrapper = mount(PageResult, {
|
||||
props: {
|
||||
status: '404',
|
||||
title: 'Custom title',
|
||||
description: 'Custom explanation',
|
||||
},
|
||||
slots: {
|
||||
default: () => h('p', 'Details'),
|
||||
footer: () => h('button', 'Custom recovery'),
|
||||
},
|
||||
global: { plugins: [router] },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.get('h1').text()).toBe('Custom title')
|
||||
expect(wrapper.text()).toContain('Custom explanation')
|
||||
expect(wrapper.text()).toContain('Details')
|
||||
expect(wrapper.findAll('button').map((button) => button.text())).toEqual([
|
||||
'Custom recovery',
|
||||
])
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
90
__test__/app/wrapper-lifecycle.spec.tsx
Normal file
90
__test__/app/wrapper-lifecycle.spec.tsx
Normal file
@ -0,0 +1,90 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { NAvatar, NButton, NSpin } from 'naive-ui'
|
||||
import { nextTick } from 'vue'
|
||||
import AppAvatar from '../../apps/admin/src/app-components/app/AppAvatar'
|
||||
import AppGlobalSpin from '../../apps/admin/src/app-components/app/AppGlobalSpin'
|
||||
import UnlockScreen from '../../apps/admin/src/app-components/app/AppLockScreen/components/UnlockScreen'
|
||||
|
||||
vi.mock('@/store', async () => {
|
||||
const { ref } = await import('vue')
|
||||
|
||||
return {
|
||||
useSigningGetters: () => ({
|
||||
getSigningCallback: ref({ name: 'Tester', avatar: '' }),
|
||||
}),
|
||||
useRuntimeGetters: () => ({ globalSpinning: ref(true) }),
|
||||
useSettingActions: () => ({ updateSettingState: vi.fn() }),
|
||||
useSettingGetters: () => ({ getLocaleLanguage: ref('en-US') }),
|
||||
useSigningActions: () => ({ logout: vi.fn() }),
|
||||
useLockScreenActions: () => ({ setLocked: vi.fn() }),
|
||||
useLockScreenGetters: () => ({ getLocked: ref(true) }),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks', () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
useDevice: () => ({ isTabletOrSmaller: false }),
|
||||
}))
|
||||
|
||||
it('honors avatar shape, native size, and keyboard focus', () => {
|
||||
const wrapper = mount(AppAvatar, {
|
||||
props: { round: false, size: 42, objectFit: 'contain' },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.findComponent(NAvatar).props()).toMatchObject({
|
||||
round: false,
|
||||
size: 42,
|
||||
objectFit: 'contain',
|
||||
})
|
||||
expect(wrapper.findComponent(NButton).props('focusable')).toBe(true)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('merges global spin overrides while preserving its owned busy state', () => {
|
||||
const wrapper = mount(AppGlobalSpin, {
|
||||
props: { show: false, themeOverrides: { opacitySpinning: '0.7' } },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.findComponent(NSpin).props()).toMatchObject({
|
||||
show: true,
|
||||
themeOverrides: { opacitySpinning: '0.7' },
|
||||
})
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('updates the lock-screen date at midnight and cancels its minute timer', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-11-06T23:59:59'))
|
||||
vi.spyOn(document, 'hidden', 'get').mockReturnValue(false)
|
||||
const wrapper = mount(UnlockScreen, {
|
||||
global: {
|
||||
stubs: {
|
||||
AppAvatar: true,
|
||||
RForm: { template: '<div><slot /></div>' },
|
||||
NFormItem: { template: '<div><slot /></div>' },
|
||||
NInput: true,
|
||||
NButton: true,
|
||||
NFlex: { template: '<div><slot /></div>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.text()).toContain('2026-11-06')
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
await nextTick()
|
||||
expect(wrapper.text()).toContain('2026-11-07')
|
||||
wrapper.unmount()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
vi.restoreAllMocks()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
@ -16,3 +16,40 @@ describe('arrayBufferToBase64Image', () => {
|
||||
expect(base64Image.startsWith(base64ImagePrefix)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves byte values across chunk boundaries for a large buffer', () => {
|
||||
const bytes = Uint8Array.from({ length: 262145 }, (_, index) => index % 256)
|
||||
|
||||
expect(arrayBufferToBase64Image(bytes.buffer)).toBe(
|
||||
'data:image/png;base64,' + Buffer.from(bytes).toString('base64'),
|
||||
)
|
||||
expect(arrayBufferToBase64Image(new ArrayBuffer(0))).toBe(
|
||||
'data:image/png;base64,',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps a compatible encoding path when native typed-array Base64 is unavailable', () => {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(
|
||||
Uint8Array.prototype,
|
||||
'toBase64',
|
||||
)
|
||||
|
||||
// eslint-disable-next-line no-extend-native -- 模拟缺少原生 API 的浏览器,finally 恢复描述符。
|
||||
Object.defineProperty(Uint8Array.prototype, 'toBase64', {
|
||||
configurable: true,
|
||||
value: void 0,
|
||||
})
|
||||
|
||||
try {
|
||||
const bytes = Uint8Array.from({ length: 65539 }, (_, index) => index % 256)
|
||||
|
||||
expect(arrayBufferToBase64Image(bytes.buffer)).toBe(
|
||||
'data:image/png;base64,' + Buffer.from(bytes).toString('base64'),
|
||||
)
|
||||
} finally {
|
||||
if (descriptor)
|
||||
// eslint-disable-next-line no-extend-native -- 恢复测试前的原生描述符。
|
||||
Object.defineProperty(Uint8Array.prototype, 'toBase64', descriptor)
|
||||
else Reflect.deleteProperty(Uint8Array.prototype, 'toBase64')
|
||||
}
|
||||
})
|
||||
|
||||
@ -31,3 +31,26 @@ it('enforces the requested radix and rejects invalid bounds', () => {
|
||||
expect(() => uuid(-1)).toThrow(RangeError)
|
||||
expect(() => uuid(Infinity)).toThrow(RangeError)
|
||||
})
|
||||
|
||||
it('rejects biased samples while filling identifiers across several batches', () => {
|
||||
let batch = 0
|
||||
const random = vi
|
||||
.spyOn(crypto, 'getRandomValues')
|
||||
.mockImplementation((samples) => {
|
||||
const values = samples as Uint32Array
|
||||
|
||||
values.fill(batch++ === 0 ? 0xffffffff : 9)
|
||||
|
||||
return samples
|
||||
})
|
||||
|
||||
try {
|
||||
expect(uuid(257, 10)).toBe('9'.repeat(257))
|
||||
} finally {
|
||||
random.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('supports long identifiers without exceeding the Web Crypto byte quota', () => {
|
||||
expect(uuid(70000, 10)).toMatch(/^\d{70000}$/)
|
||||
})
|
||||
|
||||
67
__test__/cache/shared-storage.spec.ts
vendored
Normal file
67
__test__/cache/shared-storage.spec.ts
vendored
Normal file
@ -0,0 +1,67 @@
|
||||
import { createStorage } from '@ray-template/utils/storage'
|
||||
|
||||
it('namespaces JSON values and reads the current backend instead of caching a copy', () => {
|
||||
const backend = new Map<string, string>()
|
||||
const storage = createStorage(
|
||||
{
|
||||
getItem: (key) => backend.get(key) ?? null,
|
||||
setItem: (key, value) => {
|
||||
backend.set(key, value)
|
||||
},
|
||||
removeItem: (key) => {
|
||||
backend.delete(key)
|
||||
},
|
||||
},
|
||||
'table:',
|
||||
)
|
||||
|
||||
storage.set('columns', ['name'])
|
||||
expect(backend.get('table:columns')).toBe('["name"]')
|
||||
backend.set('table:columns', '["status"]')
|
||||
expect(storage.get('columns')).toEqual(['status'])
|
||||
storage.remove('columns')
|
||||
expect(storage.get('columns')).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves a saved value when a replacement cannot be serialized', () => {
|
||||
const setItem = vi.fn()
|
||||
const storage = createStorage({
|
||||
getItem: () => '"saved"',
|
||||
setItem,
|
||||
removeItem: vi.fn(),
|
||||
})
|
||||
const circular: { self?: unknown } = {}
|
||||
|
||||
circular.self = circular
|
||||
|
||||
for (const value of [void 0, Symbol('value'), () => 1, circular, 1n]) {
|
||||
storage.set('value', value)
|
||||
}
|
||||
|
||||
expect(setItem).not.toHaveBeenCalled()
|
||||
expect(storage.get('value')).toBe('saved')
|
||||
storage.set('value', null)
|
||||
expect(setItem).toHaveBeenCalledExactlyOnceWith('value', 'null')
|
||||
})
|
||||
|
||||
it('contains unavailable-backend errors and malformed JSON', () => {
|
||||
const fail = () => {
|
||||
throw new Error('storage denied')
|
||||
}
|
||||
const storage = createStorage({
|
||||
getItem: fail,
|
||||
setItem: fail,
|
||||
removeItem: fail,
|
||||
})
|
||||
|
||||
expect(storage.get('value')).toBeNull()
|
||||
expect(() => storage.set('value', 1)).not.toThrow()
|
||||
expect(() => storage.remove('value')).not.toThrow()
|
||||
expect(
|
||||
createStorage({
|
||||
getItem: () => '{bad',
|
||||
setItem: vi.fn(),
|
||||
removeItem: vi.fn(),
|
||||
}).get('value'),
|
||||
).toBeNull()
|
||||
})
|
||||
57
__test__/components/barcode.spec.tsx
Normal file
57
__test__/components/barcode.spec.tsx
Normal file
@ -0,0 +1,57 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import barcode from 'jsbarcode'
|
||||
import { reactive } from 'vue'
|
||||
import { RBarcode } from '../../packages/ui/src/RBarcode'
|
||||
|
||||
vi.mock('jsbarcode', () => ({ default: vi.fn() }))
|
||||
|
||||
beforeEach(() => vi.mocked(barcode).mockClear())
|
||||
|
||||
it('redraws changed format, options and renderer without changing text', async () => {
|
||||
const options = reactive({ lineColor: '#123456' })
|
||||
const wrapper = mount(RBarcode, { props: { text: '123456', options } })
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
expect(barcode).toHaveBeenCalledTimes(1)
|
||||
await wrapper.setProps({ format: 'CODE39' })
|
||||
expect(barcode).toHaveBeenLastCalledWith(
|
||||
expect.any(HTMLCanvasElement),
|
||||
'123456',
|
||||
expect.objectContaining({ format: 'CODE39' }),
|
||||
)
|
||||
options.lineColor = '#abcdef'
|
||||
await flushPromises()
|
||||
expect(barcode).toHaveBeenLastCalledWith(
|
||||
expect.any(HTMLCanvasElement),
|
||||
'123456',
|
||||
expect.objectContaining({ lineColor: '#abcdef' }),
|
||||
)
|
||||
await wrapper.setProps({ barcodeRender: 'svg' })
|
||||
expect(vi.mocked(barcode).mock.lastCall?.[0]).toBe(
|
||||
wrapper.get('svg').element,
|
||||
)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('honors watchText and resumes with the latest value when enabled', async () => {
|
||||
const wrapper = mount(RBarcode, { props: { text: '123', watchText: false } })
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
const count = vi.mocked(barcode).mock.calls.length
|
||||
|
||||
await wrapper.setProps({ text: '456' })
|
||||
expect(barcode).toHaveBeenCalledTimes(count)
|
||||
await wrapper.setProps({ watchText: true })
|
||||
expect(barcode).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
'456',
|
||||
expect.anything(),
|
||||
)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
167
__test__/components/chart-themes.spec.ts
Normal file
167
__test__/components/chart-themes.spec.ts
Normal file
@ -0,0 +1,167 @@
|
||||
import { color } from 'echarts/core'
|
||||
import { darkTheme, lightTheme } from 'naive-ui'
|
||||
import { getCustomEchartTheme } from '../../packages/ui/src/RChart/src/utils/get-custom-echart-theme'
|
||||
import { loadingOptions } from '../../packages/ui/src/RChart/src/utils/loading-options'
|
||||
import {
|
||||
themeStyleOverrides,
|
||||
themeStyles,
|
||||
} from '../../packages/ui/src/theme-presets'
|
||||
|
||||
const registeredThemes = getCustomEchartTheme()
|
||||
const themes = new Map(registeredThemes.map(({ name, theme }) => [name, theme]))
|
||||
const variants = themeStyles.flatMap((style) =>
|
||||
(['light', 'dark'] as const).map((mode) => ({
|
||||
style,
|
||||
mode,
|
||||
name: `ray-${style}${mode === 'dark' ? '-dark' : ''}`,
|
||||
})),
|
||||
)
|
||||
|
||||
const composite = (foreground: number[], background: number[]) =>
|
||||
foreground
|
||||
.slice(0, 3)
|
||||
.map(
|
||||
(channel, index) =>
|
||||
channel * foreground[3] + background[index] * (1 - foreground[3]),
|
||||
)
|
||||
|
||||
const luminance = (rgb: number[]) =>
|
||||
rgb
|
||||
.map((channel) => {
|
||||
const value = channel / 255
|
||||
|
||||
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
|
||||
})
|
||||
.reduce(
|
||||
(sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index],
|
||||
0,
|
||||
)
|
||||
|
||||
const contrast = (foreground: string, background: string, surface = '#fff') => {
|
||||
// 暗色 Naive/Plain 文本和指示线含透明度;必须先与实际底色合成再计算对比度。
|
||||
const back = composite(color.parse(background), color.parse(surface))
|
||||
const front = composite(color.parse(foreground), back)
|
||||
const [lighter, darker] = [luminance(front), luminance(back)].sort(
|
||||
(a, b) => b - a,
|
||||
)
|
||||
|
||||
return (lighter + 0.05) / (darker + 0.05)
|
||||
}
|
||||
|
||||
it('registers every style in both modes with unique deterministic names', () => {
|
||||
expect(registeredThemes).toHaveLength(themes.size)
|
||||
expect([...themes.keys()]).toEqual(
|
||||
expect.arrayContaining(variants.map(({ name }) => name)),
|
||||
)
|
||||
})
|
||||
|
||||
it.each(variants)(
|
||||
'$name matches the owning page surface',
|
||||
({ style, mode, name }) => {
|
||||
const theme = themes.get(name)!
|
||||
const common = {
|
||||
...(mode === 'dark' ? darkTheme : lightTheme).common,
|
||||
...themeStyleOverrides[style][mode].common,
|
||||
}
|
||||
|
||||
expect(color.parse(theme.backgroundColor)).toEqual(
|
||||
color.parse(common.cardColor),
|
||||
)
|
||||
expect(theme.darkMode).toBe(mode === 'dark')
|
||||
expect(color.parse(theme.pie.itemStyle.borderColor)).toEqual(
|
||||
color.parse(common.cardColor),
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it.each(variants)(
|
||||
'$name keeps text, data, and active pointers legible',
|
||||
({ name }) => {
|
||||
const theme = themes.get(name)!
|
||||
const background = theme.backgroundColor
|
||||
const textColors = [
|
||||
theme.textStyle.color,
|
||||
theme.title.textStyle.color,
|
||||
theme.title.subtextStyle.color,
|
||||
theme.legend.textStyle.color,
|
||||
...['categoryAxis', 'valueAxis', 'timeAxis', 'logAxis'].map(
|
||||
(axis) => theme[axis].axisLabel.color,
|
||||
),
|
||||
]
|
||||
|
||||
for (const foreground of textColors) {
|
||||
expect(
|
||||
contrast(foreground, background),
|
||||
`${name}: text ${foreground}`,
|
||||
).toBeGreaterThanOrEqual(4.5)
|
||||
}
|
||||
|
||||
expect(
|
||||
contrast(
|
||||
theme.tooltip.textStyle.color,
|
||||
theme.tooltip.backgroundColor,
|
||||
background,
|
||||
),
|
||||
).toBeGreaterThanOrEqual(4.5)
|
||||
const pointer = theme.tooltip.axisPointer
|
||||
|
||||
expect(
|
||||
contrast(pointer.label.color, pointer.label.backgroundColor, background),
|
||||
).toBeGreaterThanOrEqual(4.5)
|
||||
|
||||
for (const foreground of [
|
||||
...theme.color,
|
||||
pointer.lineStyle.color,
|
||||
pointer.crossStyle.color,
|
||||
]) {
|
||||
expect(
|
||||
contrast(foreground, background),
|
||||
`${name}: mark ${foreground}`,
|
||||
).toBeGreaterThanOrEqual(3)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it.each(variants)(
|
||||
'$name supplies a matching loading layer without mutating its theme',
|
||||
({ mode, name }) => {
|
||||
const theme = themes.get(name)!
|
||||
const before = JSON.stringify(theme)
|
||||
const loading = loadingOptions(theme, mode === 'dark', 'Loading', {})
|
||||
const background = color.parse(theme.backgroundColor)
|
||||
|
||||
expect(color.parse(loading.maskColor)).toEqual([
|
||||
...background.slice(0, 3),
|
||||
0.9,
|
||||
])
|
||||
expect(loading.color).toBe(theme.color[0])
|
||||
expect(loading.textColor).toBe(theme.textStyle.color)
|
||||
expect(JSON.stringify(theme)).toBe(before)
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['transparent', 'rgba(0, 0, 0, 0)', 'invalid', void 0])(
|
||||
'uses a mode-aware surface for a missing/transparent loading background (%s)',
|
||||
(backgroundColor) => {
|
||||
const theme = { backgroundColor }
|
||||
|
||||
expect(
|
||||
color.parse(loadingOptions(theme, false, 'Loading', {}).maskColor),
|
||||
).toEqual([255, 255, 255, 0.9])
|
||||
expect(
|
||||
color.parse(loadingOptions(theme, true, 'Loading', {}).maskColor),
|
||||
).toEqual([23, 33, 49, 0.9])
|
||||
},
|
||||
)
|
||||
|
||||
it('preserves caller loading overrides', () => {
|
||||
const overrides = {
|
||||
maskColor: 'transparent',
|
||||
showSpinner: false,
|
||||
text: 'Preparing',
|
||||
}
|
||||
|
||||
expect(
|
||||
loadingOptions(themes.get('ray-modern'), false, 'Loading', overrides),
|
||||
).toMatchObject(overrides)
|
||||
})
|
||||
66
__test__/components/draggable-card.spec.tsx
Normal file
66
__test__/components/draggable-card.spec.tsx
Normal file
@ -0,0 +1,66 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import interact from 'interactjs'
|
||||
import RDraggableCard from '../../packages/ui/src/RDraggableCard/DraggableCard'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
instances: [] as Array<{
|
||||
draggable: ReturnType<typeof vi.fn>
|
||||
resizable: ReturnType<typeof vi.fn>
|
||||
unset: ReturnType<typeof vi.fn>
|
||||
}>,
|
||||
}))
|
||||
|
||||
vi.mock('interactjs', () => ({
|
||||
default: Object.assign(
|
||||
vi.fn(() => {
|
||||
const instance = {
|
||||
draggable: vi.fn().mockReturnThis(),
|
||||
resizable: vi.fn().mockReturnThis(),
|
||||
unset: vi.fn(),
|
||||
}
|
||||
|
||||
mocks.instances.push(instance)
|
||||
|
||||
return instance
|
||||
}),
|
||||
{ modifiers: { restrictRect: vi.fn((value) => value) } },
|
||||
),
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.instances.length = 0
|
||||
vi.mocked(interact).mockClear()
|
||||
})
|
||||
|
||||
it('releases drag listeners on disable/unmount and removes only the final shared container', async () => {
|
||||
const first = mount(RDraggableCard, { props: { title: 'First' } })
|
||||
const second = mount(RDraggableCard, { props: { title: 'Second' } })
|
||||
|
||||
await flushPromises()
|
||||
expect(interact).toHaveBeenCalledTimes(2)
|
||||
await first.setProps({ dad: false })
|
||||
expect(mocks.instances[0].unset).toHaveBeenCalledOnce()
|
||||
await first.setProps({ dad: true })
|
||||
expect(interact).toHaveBeenCalledTimes(3)
|
||||
first.unmount()
|
||||
expect(mocks.instances[2].unset).toHaveBeenCalledOnce()
|
||||
expect(document.getElementById('r-draggable-card-container')).not.toBeNull()
|
||||
second.unmount()
|
||||
expect(mocks.instances[1].unset).toHaveBeenCalledOnce()
|
||||
expect(document.getElementById('r-draggable-card-container')).toBeNull()
|
||||
})
|
||||
|
||||
it('repositions and rebinds after boundary changes without keeping the previous interaction', async () => {
|
||||
const wrapper = mount(RDraggableCard, { props: { title: 'Test' } })
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
await wrapper.setProps({ defaultPosition: { x: 24, y: 36 } })
|
||||
expect(mocks.instances[0].unset).toHaveBeenCalledOnce()
|
||||
expect(
|
||||
document.querySelector<HTMLElement>('.r-draggable-card')?.style.transform,
|
||||
).toBe('translate(24px, 36px)')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
98
__test__/components/flow.spec.tsx
Normal file
98
__test__/components/flow.spec.tsx
Normal file
@ -0,0 +1,98 @@
|
||||
import LogicFlow from '@logicflow/core'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { RFlow, useFlow } from '../../packages/ui/src/RFlow'
|
||||
import flowProps from '../../packages/ui/src/RFlow/src/props'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
instances: [] as Array<{
|
||||
render: ReturnType<typeof vi.fn>
|
||||
renderRawData: ReturnType<typeof vi.fn>
|
||||
destroy: ReturnType<typeof vi.fn>
|
||||
updateEditConfig: ReturnType<typeof vi.fn>
|
||||
keyboard: { disabled: boolean; disable: ReturnType<typeof vi.fn> }
|
||||
}>,
|
||||
}))
|
||||
|
||||
vi.mock('@logicflow/core', () => {
|
||||
class FakeFlow {
|
||||
static use = vi.fn()
|
||||
render = vi.fn()
|
||||
renderRawData = vi.fn()
|
||||
destroy = vi.fn()
|
||||
updateEditConfig = vi.fn()
|
||||
keyboard = { disabled: true, disable: vi.fn() }
|
||||
getEditConfig = () => ({
|
||||
isSilentMode: false,
|
||||
textEdit: false,
|
||||
adjustNodePosition: false,
|
||||
})
|
||||
constructor() {
|
||||
mocks.instances.push(this)
|
||||
}
|
||||
}
|
||||
|
||||
return { default: FakeFlow }
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.instances.length = 0
|
||||
vi.mocked(LogicFlow.use).mockClear()
|
||||
})
|
||||
|
||||
it('registers later plugin sets, renders initial data, and releases each instance', async () => {
|
||||
const [register, actions] = useFlow()
|
||||
const data = { nodes: [{ id: 'start' }], edges: [] }
|
||||
const plugin = { pluginName: 'later-plugin', install: vi.fn() }
|
||||
const first = mount(RFlow)
|
||||
const second = mount(RFlow, {
|
||||
props: { data, use: [plugin], onRegister: register },
|
||||
})
|
||||
|
||||
expect(LogicFlow.use).toHaveBeenCalledWith(plugin)
|
||||
expect(mocks.instances[1].render).toHaveBeenCalledWith(data)
|
||||
expect(actions.getFlowInstance()).toBe(mocks.instances[1])
|
||||
await second.setProps({ data: void 0 })
|
||||
expect(mocks.instances[1].renderRawData).toHaveBeenLastCalledWith({
|
||||
nodes: [],
|
||||
edges: [],
|
||||
})
|
||||
first.unmount()
|
||||
second.unmount()
|
||||
await flushPromises()
|
||||
expect(
|
||||
mocks.instances.every(
|
||||
(instance) => instance.destroy.mock.calls.length === 1,
|
||||
),
|
||||
).toBe(true)
|
||||
expect(() => actions.getFlowInstance()).toThrow('flow instance is not ready')
|
||||
})
|
||||
|
||||
it('restores configured editing and keyboard behavior after readonly mode', async () => {
|
||||
const wrapper = mount(RFlow)
|
||||
const instance = mocks.instances[0]
|
||||
|
||||
try {
|
||||
expect(instance.updateEditConfig).not.toHaveBeenCalled()
|
||||
await wrapper.setProps({ readonly: true })
|
||||
expect(instance.updateEditConfig).toHaveBeenLastCalledWith({
|
||||
isSilentMode: true,
|
||||
})
|
||||
await wrapper.setProps({ readonly: false })
|
||||
expect(instance.updateEditConfig).toHaveBeenLastCalledWith({
|
||||
isSilentMode: false,
|
||||
textEdit: false,
|
||||
adjustNodePosition: false,
|
||||
})
|
||||
expect(instance.keyboard.disable).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('creates independent nested default options for every instance', () => {
|
||||
const first = flowProps.options.default()
|
||||
const second = flowProps.options.default()
|
||||
|
||||
expect(first).not.toBe(second)
|
||||
expect(first.keyboard).not.toBe(second.keyboard)
|
||||
})
|
||||
@ -4,7 +4,10 @@ import { mount } from '@vue/test-utils'
|
||||
import { NDataTable, NTree } from 'naive-ui'
|
||||
import type { DataTableColumn } from 'naive-ui'
|
||||
import { effectScope, nextTick, ref, shallowRef } from 'vue'
|
||||
import { useColumnVisibility } from '../../packages/ui/src/RTablePro/src/columns'
|
||||
import {
|
||||
getLeafColumns,
|
||||
useColumnVisibility,
|
||||
} from '../../packages/ui/src/RTablePro/src/columns'
|
||||
import ColumnSettings from '../../packages/ui/src/RTablePro/src/components/ColumnSettings'
|
||||
|
||||
const name = { key: 'name', title: 'Name' }
|
||||
@ -20,6 +23,28 @@ afterEach(() => {
|
||||
columns.value = [selection, group, region]
|
||||
})
|
||||
|
||||
it('filters nested leaves and prunes empty groups while retaining unaffected branches', () => {
|
||||
const scope = effectScope()
|
||||
const nested = { key: 'outer', children: [group] }
|
||||
const source = shallowRef<DataTableColumn[]>([nested, region])
|
||||
|
||||
try {
|
||||
const state = scope.run(() => useColumnVisibility(source, ref()))!
|
||||
|
||||
state.setColumnVisible('email', false)
|
||||
expect(
|
||||
getLeafColumns(state.visibleColumns.value).map(({ key }) => key),
|
||||
).toEqual(['name', 'region'])
|
||||
expect(state.visibleColumns.value[1]).toBe(region)
|
||||
state.setColumnVisible('name', false)
|
||||
expect(state.visibleColumns.value).toEqual([region])
|
||||
state.resetColumns()
|
||||
expect(state.visibleColumns.value).toBe(source.value)
|
||||
} finally {
|
||||
scope.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('stores only hidden leaf keys, restores them on mount, and isolates separate keys', () => {
|
||||
const scope = effectScope()
|
||||
const second = effectScope()
|
||||
@ -100,6 +125,126 @@ it('updates visibility without touching storage when no key is configured', () =
|
||||
}
|
||||
})
|
||||
|
||||
it.each([false, true])(
|
||||
'pins and unpins every group descendant without mutating source definitions (controlled=%s)',
|
||||
async (controlled) => {
|
||||
const renderName = (row: { name: string }) => row.name
|
||||
const nameColumn = {
|
||||
...name,
|
||||
width: 120,
|
||||
resizable: true,
|
||||
render: renderName,
|
||||
}
|
||||
const emailColumn = {
|
||||
...email,
|
||||
width: 180,
|
||||
resizable: false,
|
||||
fixed: 'right' as const,
|
||||
}
|
||||
const children = [nameColumn, emailColumn]
|
||||
const nested = { key: 'inner', title: 'Details', children }
|
||||
const grouped = { key: 'contact', title: 'Contact', children: [nested] }
|
||||
const unaffected = { ...region, width: 140, fixed: 'right' as const }
|
||||
const input: DataTableColumn[] = [grouped, unaffected]
|
||||
|
||||
for (const value of [
|
||||
nameColumn,
|
||||
emailColumn,
|
||||
children,
|
||||
nested,
|
||||
grouped.children,
|
||||
grouped,
|
||||
unaffected,
|
||||
input,
|
||||
])
|
||||
Object.freeze(value)
|
||||
|
||||
const update = vi.fn()
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns: input,
|
||||
data: [
|
||||
{ id: 1, name: 'Alice', email: 'alice@example.test', region: 'West' },
|
||||
],
|
||||
scrollX: 440,
|
||||
...(controlled ? { 'onUpdate:columns': update } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const settings = wrapper.getComponent(ColumnSettings)
|
||||
const table = wrapper.getComponent(NDataTable)
|
||||
const patch = async (value: {
|
||||
fixed?: 'left' | 'right'
|
||||
resizable?: boolean
|
||||
}) => {
|
||||
settings.vm.$emit('patchColumn', 'contact', value)
|
||||
|
||||
if (controlled)
|
||||
await wrapper.setProps({ columns: update.mock.lastCall![0] })
|
||||
else await nextTick()
|
||||
}
|
||||
|
||||
await patch({ resizable: true })
|
||||
expect(table.props('columns')![0]).toMatchObject({
|
||||
children: [
|
||||
{
|
||||
children: [
|
||||
{ resizable: true },
|
||||
{ resizable: false, fixed: 'right' },
|
||||
],
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
for (const fixed of ['left', 'right', void 0] as const) {
|
||||
await patch({ fixed })
|
||||
const result = table.props('columns')!
|
||||
const leaves = getLeafColumns(result)
|
||||
|
||||
expect(result[0].fixed).toBe(fixed)
|
||||
expect('children' in result[0] && result[0].children[0].fixed).toBe(
|
||||
fixed,
|
||||
)
|
||||
expect(leaves[0]).toMatchObject({
|
||||
key: 'name',
|
||||
width: 120,
|
||||
resizable: true,
|
||||
render: renderName,
|
||||
})
|
||||
expect(leaves[1]).toMatchObject({
|
||||
key: 'email',
|
||||
width: 180,
|
||||
resizable: false,
|
||||
})
|
||||
expect(leaves[0].fixed).toBe(fixed)
|
||||
expect(leaves[1].fixed).toBe(fixed)
|
||||
expect(result[1]).toBe(unaffected)
|
||||
|
||||
for (const key of ['name', 'email']) {
|
||||
const cell = wrapper.get(`tbody td[data-col-key="${key}"]`)
|
||||
|
||||
if (fixed)
|
||||
expect(cell.classes()).toContain(`n-data-table-td--fixed-${fixed}`)
|
||||
else
|
||||
expect(
|
||||
cell.classes().some((name) => name.includes('--fixed-')),
|
||||
).toBe(false)
|
||||
}
|
||||
}
|
||||
|
||||
expect(nameColumn).not.toHaveProperty('fixed')
|
||||
expect(emailColumn.fixed).toBe('right')
|
||||
expect(grouped).not.toHaveProperty('fixed')
|
||||
expect(nested).not.toHaveProperty('fixed')
|
||||
expect(grouped.children[0]).toBe(nested)
|
||||
expect(nested.children).toBe(children)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('provides the full settings with a frozen plain columns array and keeps adjustments when definitions change', async () => {
|
||||
const input: DataTableColumn[] = [
|
||||
selection,
|
||||
|
||||
161
__test__/components/table-pro-image-svg.spec.ts
Normal file
161
__test__/components/table-pro-image-svg.spec.ts
Normal file
@ -0,0 +1,161 @@
|
||||
import { iconSprites } from '@ray-template/icons/manifest'
|
||||
import { inlineTableSvgUses } from '../../packages/ui/src/RTablePro/src/image-svg'
|
||||
|
||||
const sprite =
|
||||
'<svg xmlns="http://www.w3.org/2000/svg"><symbol id="icon-action/copy-image" viewBox="0 0 48 48" fill="none"><g id="shared-group"><path id="shared-path" d="M4 4h40v40H4z" stroke="currentColor" stroke-width="3" onload="throw 1" /></g></symbol></svg>'
|
||||
const response = (source = sprite) =>
|
||||
new Response(source, { headers: { 'Content-Type': 'image/svg+xml' } })
|
||||
|
||||
afterEach(() => {
|
||||
document.querySelectorAll('[data-svg-test]').forEach((node) => node.remove())
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('inlines repeated registered sprites once, retaining viewport/color without copied IDs or source mutations', async () => {
|
||||
const fetchAsset = vi.fn(async () => response())
|
||||
|
||||
vi.stubGlobal('fetch', fetchAsset)
|
||||
const source = document.createElement('div')
|
||||
|
||||
source.setAttribute('data-svg-test', '')
|
||||
source.innerHTML = `<svg style="color: red; width: 24px; height: 24px"><use href="${iconSprites.action}#icon-action/copy-image" width="24" height="24" /></svg><svg style="color: blue; width: 18px; height: 18px"><use href="${iconSprites.action}#icon-action/copy-image" width="18" height="18" /></svg>`
|
||||
document.body.append(source)
|
||||
const clone = source.cloneNode(true) as HTMLElement
|
||||
|
||||
document.body.append(clone)
|
||||
const colors = Array.from(
|
||||
clone.querySelectorAll('use'),
|
||||
(use) => getComputedStyle(use).color,
|
||||
)
|
||||
|
||||
await inlineTableSvgUses(clone, new AbortController().signal)
|
||||
expect(fetchAsset).toHaveBeenCalledOnce()
|
||||
expect(fetchAsset.mock.calls[0]).toEqual([
|
||||
new URL(iconSprites.action, document.baseURI).href,
|
||||
expect.objectContaining({
|
||||
credentials: 'omit',
|
||||
redirect: 'error',
|
||||
mode: 'same-origin',
|
||||
signal: expect.any(AbortSignal),
|
||||
}),
|
||||
])
|
||||
expect(clone.querySelector('use, [id], [onload]')).toBeNull()
|
||||
expect(clone.querySelectorAll('path')).toHaveLength(2)
|
||||
const vectors = clone.querySelectorAll('svg svg')
|
||||
|
||||
expect(vectors[0].getAttribute('viewBox')).toBe('0 0 48 48')
|
||||
expect(vectors[0].getAttribute('width')).toBe('24')
|
||||
expect(vectors[1].getAttribute('width')).toBe('18')
|
||||
expect(vectors[0].parentElement!.style.color).toBe(colors[0])
|
||||
expect(vectors[1].parentElement!.style.color).toBe(colors[1])
|
||||
expect(clone.querySelector('path')!.getAttribute('stroke')).toBe(
|
||||
'currentColor',
|
||||
)
|
||||
expect(source.querySelectorAll('use')).toHaveLength(2)
|
||||
expect(source.querySelector('path')).toBeNull()
|
||||
})
|
||||
|
||||
it('resolves local symbols outside the captured region without a fetch', async () => {
|
||||
const fetchAsset = vi.fn()
|
||||
|
||||
vi.stubGlobal('fetch', fetchAsset)
|
||||
const definitions = document.createElement('div')
|
||||
|
||||
definitions.setAttribute('data-svg-test', '')
|
||||
definitions.innerHTML =
|
||||
'<svg><symbol id="local-capture-symbol" viewBox="0 0 16 16"><rect id="local-rect" width="16" height="16" fill="currentColor" /></symbol></svg>'
|
||||
const clone = document.createElement('div')
|
||||
|
||||
clone.setAttribute('data-svg-test', '')
|
||||
clone.innerHTML =
|
||||
'<svg width="16" height="16"><use href="#local-capture-symbol" /></svg>'
|
||||
document.body.append(definitions, clone)
|
||||
|
||||
await inlineTableSvgUses(clone, new AbortController().signal)
|
||||
expect(fetchAsset).not.toHaveBeenCalled()
|
||||
expect(clone.querySelector('rect')).not.toBeNull()
|
||||
expect(clone.querySelector('use, [id]')).toBeNull()
|
||||
expect(clone.querySelector('svg svg')!.getAttribute('viewBox')).toBe(
|
||||
'0 0 16 16',
|
||||
)
|
||||
expect(document.getElementById('local-capture-symbol')).not.toBeNull()
|
||||
})
|
||||
|
||||
it.each(['https://outside.example/sprite.svg', '/api/admin/private'])(
|
||||
'rejects an unrelated source %s without fetching it',
|
||||
async (url) => {
|
||||
const fetchAsset = vi.fn()
|
||||
|
||||
vi.stubGlobal('fetch', fetchAsset)
|
||||
const clone = document.createElement('div')
|
||||
|
||||
clone.innerHTML = `<svg><use href="${url}#icon" /></svg>`
|
||||
await expect(
|
||||
inlineTableSvgUses(clone, new AbortController().signal),
|
||||
).rejects.toThrow('same-origin public assets')
|
||||
expect(fetchAsset).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
'<script>window.alert(1)</script>',
|
||||
'<foreignObject><div xmlns="http://www.w3.org/1999/xhtml">Active HTML</div></foreignObject>',
|
||||
'<image href="https://outside.example/image.png" />',
|
||||
'<path fill="url(https://outside.example/paint.svg#paint)" d="M0 0h1" />',
|
||||
'<path fill="var(--paint)" d="M0 0h1" />',
|
||||
'<path style="fill: attr(data-paint)" d="M0 0h1" />',
|
||||
'<path fill="u\\72l(https://outside.example/paint.svg#paint)" d="M0 0h1" />',
|
||||
])(
|
||||
'rejects non-static SVG content before inserting it into the snapshot',
|
||||
async (content) => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () =>
|
||||
response(
|
||||
`<svg xmlns="http://www.w3.org/2000/svg"><symbol id="icon">${content}</symbol></svg>`,
|
||||
),
|
||||
),
|
||||
)
|
||||
const clone = document.createElement('div')
|
||||
|
||||
clone.setAttribute('data-svg-test', '')
|
||||
clone.innerHTML = '<svg><use href="/public/sprite.svg#icon" /></svg>'
|
||||
document.body.append(clone)
|
||||
await expect(
|
||||
inlineTableSvgUses(clone, new AbortController().signal),
|
||||
).rejects.toThrow()
|
||||
expect(clone.querySelector('script, foreignObject, image, path')).toBeNull()
|
||||
},
|
||||
)
|
||||
|
||||
it('bounds streamed source size and forwards cancellation to sprite fetches', async () => {
|
||||
const clone = document.createElement('div')
|
||||
|
||||
clone.innerHTML = '<svg><use href="/public/sprite.svg#icon" /></svg>'
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => response('x'.repeat(1024 * 1024 + 1))),
|
||||
)
|
||||
await expect(
|
||||
inlineTableSvgUses(clone, new AbortController().signal),
|
||||
).rejects.toThrow('too large')
|
||||
|
||||
const controller = new AbortController()
|
||||
const fetchAsset = vi.fn(
|
||||
(_url: string, options: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
options.signal!.addEventListener(
|
||||
'abort',
|
||||
() => reject(new DOMException('Cancelled', 'AbortError')),
|
||||
{ once: true },
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
vi.stubGlobal('fetch', fetchAsset)
|
||||
const pending = inlineTableSvgUses(clone, controller.signal)
|
||||
|
||||
controller.abort()
|
||||
await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
|
||||
expect(fetchAsset.mock.calls[0][1].signal).toBe(controller.signal)
|
||||
})
|
||||
412
__test__/components/table-pro-image.spec.tsx
Normal file
412
__test__/components/table-pro-image.spec.tsx
Normal file
@ -0,0 +1,412 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { h } from 'vue'
|
||||
import { RTablePro, useTablePro } from '../../packages/ui/src/RTablePro'
|
||||
import type {
|
||||
TableProInst,
|
||||
TableProResult,
|
||||
} from '../../packages/ui/src/RTablePro'
|
||||
import {
|
||||
copyTableImage,
|
||||
createTableImageSnapshot,
|
||||
} from '../../packages/ui/src/RTablePro/src/image'
|
||||
import { provideUiServices } from '../../packages/ui/src/services'
|
||||
|
||||
const renderer = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
options: [] as Record<string, unknown>[],
|
||||
nodes: [] as HTMLElement[],
|
||||
}))
|
||||
|
||||
vi.mock('@ray-template/composables/useDomToImage', () => ({
|
||||
useDomToImage: (node: HTMLElement, options: Record<string, unknown>) => {
|
||||
renderer.nodes.push(node)
|
||||
renderer.options.push(options)
|
||||
|
||||
return { create: renderer.create }
|
||||
},
|
||||
}))
|
||||
|
||||
class Item {
|
||||
constructor(readonly data: Record<string, Promise<Blob>>) {}
|
||||
}
|
||||
|
||||
const png = () => new Blob(['png'], { type: 'image/png' })
|
||||
let write: ReturnType<typeof vi.fn<(items: Item[]) => Promise<void>>>
|
||||
let originalClipboard: PropertyDescriptor | undefined
|
||||
const columns = [{ key: 'name', title: 'Name' }]
|
||||
const data = [{ id: 1, name: 'Ray' }]
|
||||
const tickCapture = () => new Promise<void>((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
beforeEach(() => {
|
||||
renderer.create.mockReset().mockResolvedValue(png())
|
||||
renderer.options.length = 0
|
||||
renderer.nodes.length = 0
|
||||
write = vi.fn(async ([item]) => {
|
||||
await item.data['image/png']
|
||||
})
|
||||
originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
configurable: true,
|
||||
value: { write },
|
||||
})
|
||||
vi.stubGlobal('ClipboardItem', Item)
|
||||
vi.stubGlobal('isSecureContext', true)
|
||||
vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(640)
|
||||
vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(240)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
document
|
||||
.querySelectorAll('[data-r-table-image-snapshot]')
|
||||
.forEach((node) => node.remove())
|
||||
|
||||
if (originalClipboard)
|
||||
Object.defineProperty(navigator, 'clipboard', originalClipboard)
|
||||
else Reflect.deleteProperty(navigator, 'clipboard')
|
||||
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('requests clipboard writing synchronously and supplies an eventual PNG without retaining its snapshot', async () => {
|
||||
const target = document.createElement('div')
|
||||
|
||||
target.textContent = 'Current table'
|
||||
document.body.append(target)
|
||||
|
||||
try {
|
||||
const copying = copyTableImage(target, { pixelRatio: 1 })
|
||||
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
expect(renderer.create).not.toHaveBeenCalled()
|
||||
expect(write.mock.calls[0][0][0].data['image/png']).toBeInstanceOf(Promise)
|
||||
await copying
|
||||
expect(renderer.create).toHaveBeenCalledExactlyOnceWith('blob')
|
||||
expect(renderer.options[0]).toMatchObject({
|
||||
imageType: 'blob',
|
||||
type: 'image/png',
|
||||
pixelRatio: 1,
|
||||
})
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
} finally {
|
||||
target.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves scroll viewport and input state in an inert clone without touching the live table', () => {
|
||||
const target = document.createElement('div')
|
||||
|
||||
target.innerHTML =
|
||||
'<div class="viewport"><div class="rows"><input type="checkbox"><input type="radio" name="snapshot-choice" checked autofocus><textarea>Initial</textarea></div></div>'
|
||||
const viewport = target.querySelector<HTMLElement>('.viewport')!
|
||||
|
||||
viewport.scrollLeft = 80
|
||||
viewport.scrollTop = 120
|
||||
target.querySelector<HTMLInputElement>('input')!.checked = true
|
||||
target.querySelector<HTMLTextAreaElement>('textarea')!.value = 'Current'
|
||||
target.style.setProperty('--example-color', 'rgb(10, 20, 30)')
|
||||
document.body.append(target)
|
||||
|
||||
const snapshot = createTableImageSnapshot(target)
|
||||
|
||||
try {
|
||||
expect(snapshot.element.inert).toBe(true)
|
||||
expect(snapshot.element.getAttribute('aria-hidden')).toBe('true')
|
||||
expect(snapshot.element.style.width).toBe('640px')
|
||||
expect(snapshot.element.style.height).toBe('240px')
|
||||
expect(snapshot.element.style.getPropertyValue('--example-color')).toBe(
|
||||
'rgb(10, 20, 30)',
|
||||
)
|
||||
expect(
|
||||
snapshot.element.querySelector<HTMLElement>('.rows')!.style.transform,
|
||||
).toContain('translate(-80px, -120px)')
|
||||
expect(
|
||||
snapshot.element.querySelector<HTMLInputElement>('input')!.defaultChecked,
|
||||
).toBe(true)
|
||||
expect(
|
||||
snapshot.element.querySelector<HTMLTextAreaElement>('textarea')!.value,
|
||||
).toBe('Current')
|
||||
expect(viewport.scrollLeft).toBe(80)
|
||||
expect(viewport.scrollTop).toBe(120)
|
||||
expect(target.querySelector<HTMLElement>('.rows')!.style.transform).toBe('')
|
||||
expect(
|
||||
target.querySelector<HTMLInputElement>('[type="radio"]')!.checked,
|
||||
).toBe(true)
|
||||
expect(snapshot.element.querySelector('[name], [autofocus]')).toBeNull()
|
||||
} finally {
|
||||
snapshot.dispose()
|
||||
target.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it('removes active event attributes and scripts before connecting a snapshot', () => {
|
||||
const target = document.createElement('div')
|
||||
|
||||
target.innerHTML =
|
||||
'<span onclick="throw 1">Cell</span><img onload="throw 1" onerror="throw 1"><script type="application/json">{}</script>'
|
||||
document.body.append(target)
|
||||
const snapshot = createTableImageSnapshot(target)
|
||||
|
||||
try {
|
||||
expect(
|
||||
snapshot.element.querySelector('script, [onclick], [onload], [onerror]'),
|
||||
).toBeNull()
|
||||
expect(target.querySelector('[onclick]')).not.toBeNull()
|
||||
expect(target.querySelector('script')).not.toBeNull()
|
||||
} finally {
|
||||
snapshot.dispose()
|
||||
target.remove()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['iframe', 'object', 'embed', 'audio', 'video'])(
|
||||
'rejects %s content before creating a connected clone',
|
||||
(tag) => {
|
||||
const target = document.createElement('div')
|
||||
|
||||
target.append(document.createElement(tag))
|
||||
vi.spyOn(target, 'isConnected', 'get').mockReturnValue(true)
|
||||
const clone = vi.spyOn(target, 'cloneNode')
|
||||
|
||||
try {
|
||||
expect(() => createTableImageSnapshot(target)).toThrow('Embedded media')
|
||||
expect(clone).not.toHaveBeenCalled()
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
} finally {
|
||||
target.remove()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('aborts a pending sprite request on unmount without rasterizing or leaving a snapshot', async () => {
|
||||
const fetchAsset = vi.fn(
|
||||
(_url: string, options: RequestInit) =>
|
||||
new Promise<Response>((_resolve, reject) => {
|
||||
options.signal!.addEventListener(
|
||||
'abort',
|
||||
() => reject(new DOMException('Cancelled', 'AbortError')),
|
||||
{ once: true },
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
vi.stubGlobal('fetch', fetchAsset)
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
columns: [
|
||||
{
|
||||
key: 'icon',
|
||||
title: 'Icon',
|
||||
render: () =>
|
||||
h('svg', [h('use', { href: '/public/sprite.svg#icon' })]),
|
||||
},
|
||||
],
|
||||
data,
|
||||
},
|
||||
})
|
||||
const copying = (wrapper.vm as unknown as TableProInst).copyImage()
|
||||
|
||||
await tickCapture()
|
||||
expect(fetchAsset).toHaveBeenCalledOnce()
|
||||
wrapper.unmount()
|
||||
expect(await copying).toBe(false)
|
||||
expect(fetchAsset.mock.calls[0][1].signal!.aborted).toBe(true)
|
||||
expect(renderer.create).not.toHaveBeenCalled()
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
})
|
||||
|
||||
it('copies only the native table region and supports configured options and hidden actions through the hook', async () => {
|
||||
const [register, actions] = useTablePro()
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: {
|
||||
columns,
|
||||
data,
|
||||
title: 'Excluded heading',
|
||||
onRegister: register,
|
||||
search: [{ key: 'name', label: 'Excluded search' }],
|
||||
copyImageOptions: { pixelRatio: 1, backgroundColor: '#ffffff' },
|
||||
},
|
||||
slots: {
|
||||
toolbar: 'Excluded toolbar',
|
||||
tableFooter: 'Excluded footer',
|
||||
tableAction: 'Excluded action',
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(true)
|
||||
expect(await actions.copyImage({ pixelRatio: 2 })).toBe(true)
|
||||
const target = renderer.nodes[0]
|
||||
|
||||
expect(target.classList.contains('n-data-table')).toBe(true)
|
||||
expect(target.textContent).toContain('Ray')
|
||||
expect(target.querySelector('th')).not.toBeNull()
|
||||
expect(target.querySelector('.n-data-table__pagination')).not.toBeNull()
|
||||
expect(target.textContent).not.toMatch(/Excluded/)
|
||||
expect(renderer.options[0]).toMatchObject({
|
||||
pixelRatio: 2,
|
||||
backgroundColor: '#ffffff',
|
||||
})
|
||||
expect(wrapper.get('[role="status"]').text()).toBe('Table image copied')
|
||||
await wrapper.setProps({ showCopyImage: false })
|
||||
expect(wrapper.find('[aria-label="Copy table image"]').exists()).toBe(false)
|
||||
expect(await actions.copyImage()).toBe(true)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('reports unavailable and denied clipboard access without rendering or claiming success', async () => {
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: { columns, data },
|
||||
})
|
||||
const instance = wrapper.vm as unknown as TableProInst
|
||||
|
||||
try {
|
||||
vi.stubGlobal('ClipboardItem', void 0)
|
||||
expect(await instance.copyImage()).toBe(false)
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain('cannot copy PNG')
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
vi.stubGlobal('ClipboardItem', Item)
|
||||
write.mockRejectedValueOnce(new DOMException('Denied', 'NotAllowedError'))
|
||||
expect(await instance.copyImage()).toBe(false)
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain('access was denied')
|
||||
expect(renderer.create).not.toHaveBeenCalled()
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['reject', 'empty'] as const)(
|
||||
'cleans up a %s render result and allows a later retry',
|
||||
async (failure) => {
|
||||
if (failure === 'reject')
|
||||
renderer.create.mockRejectedValueOnce(new Error('Image failed'))
|
||||
else renderer.create.mockResolvedValueOnce(null)
|
||||
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: { columns, data },
|
||||
})
|
||||
const instance = wrapper.vm as unknown as TableProInst
|
||||
|
||||
try {
|
||||
expect(await instance.copyImage()).toBe(false)
|
||||
expect(wrapper.get('[role="alert"]').text()).toContain("Couldn't copy")
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
expect(await instance.copyImage()).toBe(true)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('deduplicates an in-flight capture and cancels unfinished clipboard data on unmount', async () => {
|
||||
const pending = Promise.withResolvers<Blob>()
|
||||
|
||||
renderer.create.mockReturnValueOnce(pending.promise)
|
||||
const success = vi.fn()
|
||||
const error = vi.fn()
|
||||
const wrapper = mount(
|
||||
{
|
||||
setup() {
|
||||
provideUiServices({ reportSuccess: success, reportError: error })
|
||||
|
||||
return () => h(RTablePro, { columns, data })
|
||||
},
|
||||
},
|
||||
{ attachTo: document.body },
|
||||
)
|
||||
const instance = wrapper.getComponent(RTablePro).vm as unknown as TableProInst
|
||||
const copying = instance.copyImage()
|
||||
|
||||
await tickCapture()
|
||||
expect(renderer.create).toHaveBeenCalledOnce()
|
||||
expect(await instance.copyImage()).toBe(false)
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
wrapper.unmount()
|
||||
expect(await copying).toBe(false)
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
pending.resolve(png())
|
||||
await flushPromises()
|
||||
expect(success).not.toHaveBeenCalled()
|
||||
expect(error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not capture unconfirmed remote results', async () => {
|
||||
const pending = Promise.withResolvers<TableProResult>()
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: { columns, request: () => pending.promise },
|
||||
})
|
||||
|
||||
try {
|
||||
expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe(
|
||||
false,
|
||||
)
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
pending.resolve({ data, total: 1 })
|
||||
await flushPromises()
|
||||
expect(await (wrapper.vm as unknown as TableProInst).copyImage()).toBe(true)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('uses bilingual host feedback and preserves a successful result if the host notifier fails', async () => {
|
||||
const success = vi.fn(() => {
|
||||
throw new Error('Notifier unavailable')
|
||||
})
|
||||
const wrapper = mount(
|
||||
{
|
||||
setup() {
|
||||
provideUiServices({ locale: () => 'zh-CN', reportSuccess: success })
|
||||
|
||||
return () => h(RTablePro, { columns, data })
|
||||
},
|
||||
},
|
||||
{ attachTo: document.body },
|
||||
)
|
||||
|
||||
try {
|
||||
const instance = wrapper.getComponent(RTablePro)
|
||||
.vm as unknown as TableProInst
|
||||
|
||||
expect(await instance.copyImage()).toBe(true)
|
||||
expect(success).toHaveBeenCalledExactlyOnceWith('表格图片已复制')
|
||||
expect(wrapper.get('[role="status"]').text()).toBe('表格图片已复制')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels pending capture when the displayed dataset changes', async () => {
|
||||
const pending = Promise.withResolvers<Blob>()
|
||||
|
||||
renderer.create.mockReturnValueOnce(pending.promise)
|
||||
const wrapper = mount(RTablePro, {
|
||||
attachTo: document.body,
|
||||
props: { columns, data },
|
||||
})
|
||||
const copying = (wrapper.vm as unknown as TableProInst).copyImage()
|
||||
|
||||
try {
|
||||
await tickCapture()
|
||||
expect(
|
||||
document.querySelector('[data-r-table-image-snapshot]'),
|
||||
).not.toBeNull()
|
||||
await wrapper.setProps({ data: [{ id: 2, name: 'New query' }] })
|
||||
expect(await copying).toBe(false)
|
||||
expect(document.querySelector('[data-r-table-image-snapshot]')).toBeNull()
|
||||
expect(wrapper.find('[role="alert"]').exists()).toBe(false)
|
||||
pending.resolve(png())
|
||||
await flushPromises()
|
||||
expect(wrapper.find('[role="status"]').exists()).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
42
__test__/components/table-pro-pagination.spec.ts
Normal file
42
__test__/components/table-pro-pagination.spec.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { splitPaginationOptions } from '../../packages/ui/src/RTablePro/src/pagination'
|
||||
import type { TableProPagination } from '../../packages/ui/src/RTablePro/src/types'
|
||||
|
||||
it('uses only current update handlers and removes them from native view props', () => {
|
||||
const page = vi.fn()
|
||||
const modelPage = vi.fn()
|
||||
const size = vi.fn()
|
||||
const modelSize = vi.fn()
|
||||
const options: TableProPagination = {
|
||||
page: 2,
|
||||
pageSize: 20,
|
||||
showSizePicker: true,
|
||||
onUpdatePage: [page],
|
||||
'onUpdate:page': modelPage,
|
||||
onUpdatePageSize: size,
|
||||
'onUpdate:pageSize': [modelSize],
|
||||
}
|
||||
const pager = splitPaginationOptions(options)
|
||||
|
||||
pager.notifyPage(3)
|
||||
pager.notifyPageSize(50)
|
||||
expect(page).toHaveBeenCalledExactlyOnceWith(3)
|
||||
expect(modelPage).toHaveBeenCalledExactlyOnceWith(3)
|
||||
expect(size).toHaveBeenCalledExactlyOnceWith(50)
|
||||
expect(modelSize).toHaveBeenCalledExactlyOnceWith(50)
|
||||
expect(pager.view).toEqual({ page: 2, pageSize: 20, showSizePicker: true })
|
||||
})
|
||||
|
||||
it('drops obsolete callback keys from untyped runtime configuration', () => {
|
||||
const onChange = vi.fn()
|
||||
const onPageSizeChange = vi.fn()
|
||||
const legacy = { page: 1, onChange, onPageSizeChange }
|
||||
const pager = splitPaginationOptions(legacy)
|
||||
|
||||
pager.notifyPage(2)
|
||||
pager.notifyPageSize(20)
|
||||
expect(pager.view).toEqual({ page: 1 })
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
expect(onPageSizeChange).not.toHaveBeenCalled()
|
||||
expectTypeOf<TableProPagination>().not.toHaveProperty('onChange')
|
||||
expectTypeOf<TableProPagination>().not.toHaveProperty('onPageSizeChange')
|
||||
})
|
||||
134
__test__/components/table-pro-toolbar.spec.tsx
Normal file
134
__test__/components/table-pro-toolbar.spec.tsx
Normal file
@ -0,0 +1,134 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NDataTable, NDropdown } from 'naive-ui'
|
||||
import { RTablePro } from '../../packages/ui/src/RTablePro'
|
||||
import type { TableProRequest } from '../../packages/ui/src/RTablePro'
|
||||
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
|
||||
import * as printing from '../../packages/ui/src/RTablePro/src/printing'
|
||||
|
||||
const columns = [{ key: 'name', title: 'Name' }]
|
||||
const data = [{ id: 1, name: 'Ray' }]
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('hides print by default and groups secondary actions under one menu', async () => {
|
||||
const wrapper = mount(RTablePro, { props: { columns, data } })
|
||||
|
||||
try {
|
||||
const menu = wrapper.getComponent(NDropdown)
|
||||
const keys = menu.props('options')?.map((option) => option.key)
|
||||
|
||||
expect(keys).toContain('csv')
|
||||
expect(keys).toContain('density')
|
||||
expect(keys).not.toContain('print')
|
||||
expect(wrapper.find('[aria-label="Print table"]').exists()).toBe(false)
|
||||
expect(
|
||||
wrapper.get('[aria-label="More actions"]').attributes('aria-haspopup'),
|
||||
).toBe('menu')
|
||||
await wrapper.get('[aria-label="More actions"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(document.body.textContent).not.toContain('Print table')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('opts into menu printing and retains CSV formatting and output options', async () => {
|
||||
const download = vi
|
||||
.spyOn(csv, 'downloadTableCsv')
|
||||
.mockImplementation(() => {})
|
||||
const print = vi.spyOn(printing, 'printTableContent').mockResolvedValue(true)
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: {
|
||||
columns,
|
||||
data,
|
||||
showPrint: true,
|
||||
downloadCsvTableOptions: { fileName: 'people' },
|
||||
printTableOptions: { title: 'People report' },
|
||||
getCsvCell: (value) => `Person: ${String(value)}`,
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
const menu = wrapper.getComponent(NDropdown)
|
||||
|
||||
expect(
|
||||
menu.props('options')?.some((option) => option.key === 'print'),
|
||||
).toBe(true)
|
||||
menu.vm.$emit('select', 'csv')
|
||||
await flushPromises()
|
||||
expect(download).toHaveBeenCalledExactlyOnceWith(
|
||||
'"Name"\r\n"Person: Ray"',
|
||||
'people',
|
||||
)
|
||||
menu.vm.$emit('select', 'print')
|
||||
await flushPromises()
|
||||
expect(print).toHaveBeenCalledOnce()
|
||||
expect(print.mock.calls[0][1]).toMatchObject({ title: 'People report' })
|
||||
await wrapper.setProps({ showPrint: false })
|
||||
expect(
|
||||
menu.props('options')?.some((option) => option.key === 'print'),
|
||||
).toBe(false)
|
||||
menu.vm.$emit('select', 'print')
|
||||
await flushPromises()
|
||||
expect(print).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('updates density and appearance without changing caller defaults', async () => {
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: { columns, data, size: 'medium', striped: false, bordered: true },
|
||||
})
|
||||
|
||||
try {
|
||||
const menu = wrapper.getComponent(NDropdown)
|
||||
|
||||
menu.vm.$emit('select', 'density:small')
|
||||
menu.vm.$emit('select', 'striped')
|
||||
menu.vm.$emit('select', 'bordered')
|
||||
await flushPromises()
|
||||
expect(wrapper.getComponent(NDataTable).props()).toMatchObject({
|
||||
size: 'small',
|
||||
striped: true,
|
||||
bordered: false,
|
||||
})
|
||||
expect(wrapper.props()).toMatchObject({
|
||||
size: 'medium',
|
||||
striped: false,
|
||||
bordered: true,
|
||||
})
|
||||
await wrapper.setProps({ size: 'large' })
|
||||
expect(wrapper.getComponent(NDataTable).props('size')).toBe('large')
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('refreshes the current remote query and preserves the caller toolbar when tools are disabled', async () => {
|
||||
const request = vi.fn<TableProRequest>(async () => ({ data, total: 1 }))
|
||||
const wrapper = mount(RTablePro, {
|
||||
props: { columns, request },
|
||||
slots: { toolbar: 'Business action' },
|
||||
})
|
||||
|
||||
try {
|
||||
await flushPromises()
|
||||
expect(request).toHaveBeenCalledOnce()
|
||||
await wrapper.get('[aria-label="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(request).toHaveBeenCalledTimes(2)
|
||||
expect(request.mock.lastCall?.[0]).toEqual(request.mock.calls[0][0])
|
||||
expect(request.mock.lastCall?.[1]).not.toBe(request.mock.calls[0][1])
|
||||
expect(wrapper.get('.r-table__business-actions').text()).toBe(
|
||||
'Business action',
|
||||
)
|
||||
await wrapper.setProps({ tool: false })
|
||||
expect(wrapper.find('.r-table__utilities').exists()).toBe(false)
|
||||
expect(wrapper.get('.r-table__business-actions').text()).toBe(
|
||||
'Business action',
|
||||
)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
@ -8,7 +8,6 @@ import { provideUiServices } from '@ray-template/ui/services'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NDataTable, NDropdown, NPagination } from 'naive-ui'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import Size from '../../packages/ui/src/RTablePro/src/components/Size'
|
||||
import * as csv from '../../packages/ui/src/RTablePro/src/csv'
|
||||
|
||||
const columns = [{ title: 'Name', key: 'name' }]
|
||||
@ -568,7 +567,9 @@ it('provides the row that opened the context menu and discards it after data cha
|
||||
},
|
||||
global: { stubs: { teleport: true } },
|
||||
})
|
||||
const menu = wrapper.getComponent(NDropdown)
|
||||
const menu = wrapper
|
||||
.findAllComponents(NDropdown)
|
||||
.find((dropdown) => dropdown.props('trigger') === 'manual')!
|
||||
|
||||
try {
|
||||
const entry = wrapper.get('tbody tr')
|
||||
@ -634,7 +635,7 @@ it('respects a changed density prop without reviving an earlier local choice', a
|
||||
const native = wrapper.getComponent(NDataTable)
|
||||
|
||||
try {
|
||||
wrapper.getComponent(Size).vm.$emit('change', 'small')
|
||||
wrapper.getComponent(NDropdown).vm.$emit('select', 'density:small')
|
||||
await wrapper.vm.$nextTick()
|
||||
expect(native.props('size')).toBe('small')
|
||||
await wrapper.setProps({ size: 'large' })
|
||||
|
||||
214
__test__/components/wrapper-contracts.spec.tsx
Normal file
214
__test__/components/wrapper-contracts.spec.tsx
Normal file
@ -0,0 +1,214 @@
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { NDropdown, NForm, NFormItem, NGrid, NSpin } from 'naive-ui'
|
||||
import { defineComponent, h, nextTick, ref } from 'vue'
|
||||
import { RCollapseGrid } from '../../packages/ui/src/RCollapseGrid'
|
||||
import { RForm, useForm } from '../../packages/ui/src/RForm'
|
||||
import { RIframe } from '../../packages/ui/src/RIframe'
|
||||
import type { RIframeInst } from '../../packages/ui/src/RIframe/src/types'
|
||||
import { RMoreDropdown } from '../../packages/ui/src/RMoreDropdown'
|
||||
import { RSegment } from '../../packages/ui/src/RSegment'
|
||||
|
||||
it('keeps controlled open state and zero grid gaps consistent', async () => {
|
||||
const open = ref(false)
|
||||
const wrapper = mount(
|
||||
defineComponent(() => () => (
|
||||
<RCollapseGrid
|
||||
open={open.value}
|
||||
onUpdateOpen={(value) => (open.value = value)}
|
||||
xGap={0}
|
||||
yGap={0}
|
||||
/>
|
||||
)),
|
||||
)
|
||||
|
||||
try {
|
||||
const button = wrapper.get('button.collapse-icon')
|
||||
|
||||
expect(wrapper.findComponent(NGrid).props()).toMatchObject({
|
||||
xGap: 0,
|
||||
yGap: 0,
|
||||
collapsed: true,
|
||||
})
|
||||
expect(button.attributes('aria-expanded')).toBe('false')
|
||||
await button.trigger('click')
|
||||
expect(open.value).toBe(true)
|
||||
expect(wrapper.findComponent(NGrid).props('collapsed')).toBe(false)
|
||||
await button.trigger('click')
|
||||
expect(open.value).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('forwards dropdown placement and renders segment label functions', () => {
|
||||
const dropdown = mount(RMoreDropdown, {
|
||||
props: { placement: 'top-end', triggerLabel: 'Row actions' },
|
||||
})
|
||||
const segment = mount(RSegment, {
|
||||
props: {
|
||||
options: [{ key: 'one', label: () => h('strong', 'Rendered label') }],
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
expect(dropdown.findComponent(NDropdown).props('placement')).toBe('top-end')
|
||||
expect(dropdown.get('button').attributes('aria-label')).toBe('Row actions')
|
||||
expect(segment.get('strong').text()).toBe('Rendered label')
|
||||
} finally {
|
||||
dropdown.unmount()
|
||||
segment.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('starts iframe loading for every source and exposes the same native element', async () => {
|
||||
const wrapper = mount(RIframe, { props: { src: '/one.html' } })
|
||||
|
||||
try {
|
||||
await nextTick()
|
||||
const frame = wrapper.get('iframe')
|
||||
|
||||
await frame.trigger('load')
|
||||
expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
|
||||
await wrapper.setProps({ src: '/two.html' })
|
||||
expect(wrapper.findComponent(NSpin).props('show')).toBe(true)
|
||||
const instance = wrapper.vm as unknown as RIframeInst
|
||||
|
||||
expect(instance.iframe).toBe(frame.element)
|
||||
expect(instance.iframeInst).toBe(frame.element)
|
||||
await frame.trigger('error')
|
||||
expect(wrapper.findComponent(NSpin).props('show')).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('submits single-line Enter reactively without consuming IME, multiline, or combobox events', async () => {
|
||||
const onFinish = vi.fn()
|
||||
const wrapper = mount(RForm, {
|
||||
props: { submitWhenEnter: false, onFinish },
|
||||
slots: {
|
||||
default: () => [
|
||||
h('input'),
|
||||
h('textarea'),
|
||||
h('input', { role: 'combobox' }),
|
||||
],
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
expect(onFinish).not.toHaveBeenCalled()
|
||||
await wrapper.setProps({ submitWhenEnter: true })
|
||||
await wrapper.get('textarea').trigger('keydown', { key: 'Enter' })
|
||||
await wrapper.get('[role="combobox"]').trigger('keydown', { key: 'Enter' })
|
||||
await wrapper
|
||||
.get('input')
|
||||
.trigger('keydown', { key: 'Enter', isComposing: true })
|
||||
await flushPromises()
|
||||
expect(onFinish).not.toHaveBeenCalled()
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(onFinish).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps validation failures handled and prevents repeated Enter submissions', async () => {
|
||||
const pending = Promise.withResolvers<void>()
|
||||
const onFinish = vi.fn(() => pending.promise)
|
||||
const wrapper = mount(RForm, {
|
||||
props: { submitWhenEnter: true, onFinish, model: { name: '' } },
|
||||
slots: {
|
||||
default: () =>
|
||||
h(
|
||||
NFormItem,
|
||||
{ path: 'name', rule: { required: true, message: 'Required' } },
|
||||
() => h('input'),
|
||||
),
|
||||
},
|
||||
})
|
||||
|
||||
try {
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(onFinish).not.toHaveBeenCalled()
|
||||
expect(wrapper.text()).toContain('Required')
|
||||
await wrapper.setProps({ model: { name: 'Ready' } })
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(onFinish).toHaveBeenCalledOnce()
|
||||
pending.resolve()
|
||||
await flushPromises()
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(onFinish).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears registered form instances when their component unmounts', async () => {
|
||||
const [register, actions] = useForm({ name: 'Initial', enabled: false })
|
||||
const wrapper = mount(RForm, { props: { onRegister: register } })
|
||||
|
||||
expect(actions.getFormInstance().validate).toBe(
|
||||
wrapper.findComponent(NForm).vm.validate,
|
||||
)
|
||||
actions.updateFormCondition({ name: 'Updated' })
|
||||
expect(actions.formConditionRef.value).toEqual({
|
||||
name: 'Updated',
|
||||
enabled: false,
|
||||
})
|
||||
actions.reset({ enabled: true })
|
||||
expect(actions.formConditionRef.value).toEqual({
|
||||
name: 'Initial',
|
||||
enabled: true,
|
||||
})
|
||||
wrapper.unmount()
|
||||
await nextTick()
|
||||
expect(() => actions.getFormInstance()).toThrow('form instance is not ready')
|
||||
})
|
||||
|
||||
it('allows forwarded key handlers to consume Enter before automatic submission', async () => {
|
||||
const onFinish = vi.fn()
|
||||
const onKeydown = vi.fn((event: KeyboardEvent) => event.preventDefault())
|
||||
const wrapper = mount(RForm, {
|
||||
props: { submitWhenEnter: true, onFinish },
|
||||
attrs: { onKeydown },
|
||||
slots: { default: () => h('input') },
|
||||
})
|
||||
|
||||
try {
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
await flushPromises()
|
||||
expect(onKeydown).toHaveBeenCalledOnce()
|
||||
expect(onFinish).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not submit after its component unmounts during asynchronous validation', async () => {
|
||||
const validation = Promise.withResolvers<void>()
|
||||
const onFinish = vi.fn()
|
||||
const wrapper = mount(RForm, {
|
||||
props: { submitWhenEnter: true, onFinish, model: { name: 'Ready' } },
|
||||
slots: {
|
||||
default: () =>
|
||||
h(
|
||||
NFormItem,
|
||||
{ path: 'name', rule: { validator: () => validation.promise } },
|
||||
() => h('input'),
|
||||
),
|
||||
},
|
||||
})
|
||||
|
||||
await wrapper.get('input').trigger('keydown', { key: 'Enter' })
|
||||
wrapper.unmount()
|
||||
validation.resolve()
|
||||
await flushPromises()
|
||||
expect(onFinish).not.toHaveBeenCalled()
|
||||
})
|
||||
31
__test__/hooks/useAccess.spec.ts
Normal file
31
__test__/hooks/useAccess.spec.ts
Normal file
@ -0,0 +1,31 @@
|
||||
import { ref } from 'vue'
|
||||
import { useAccess } from '../../apps/admin/src/hooks/template/useAccess'
|
||||
|
||||
const { state } = vi.hoisted(() => ({
|
||||
state: { permissions: void 0 as unknown },
|
||||
}))
|
||||
|
||||
vi.mock('../../apps/admin/src/store', () => ({
|
||||
useSigningGetters: () => ({ getPermissions: state.permissions }),
|
||||
}))
|
||||
|
||||
it('preserves all/any semantics and invalidates permission lookups after session changes', () => {
|
||||
const permissions = ref(['users:read', 'users:write'])
|
||||
|
||||
state.permissions = permissions
|
||||
const access = useAccess()
|
||||
|
||||
expect(access.permissions).toBe(permissions)
|
||||
expect(access.hasPermission('users:read')).toBe(true)
|
||||
expect(access.hasPermission(['users:read', 'users:write'])).toBe(true)
|
||||
expect(access.hasPermission(['users:read', 'admin:write'])).toBe(false)
|
||||
expect(access.hasPermission(['users:read', 'admin:write'], 'any')).toBe(true)
|
||||
expect(access.hasPermission([])).toBe(true)
|
||||
expect(access.hasPermission([], 'any')).toBe(false)
|
||||
|
||||
permissions.value.splice(1, 1)
|
||||
expect(access.hasPermission('users:write')).toBe(false)
|
||||
permissions.value = ['admin:write']
|
||||
expect(access.hasPermission('users:read')).toBe(false)
|
||||
expect(access.hasPermission('admin:write')).toBe(true)
|
||||
})
|
||||
@ -121,6 +121,9 @@ it('restores original style priority and releases ownership even when manual exi
|
||||
expect(element.style.width).toBe('240px')
|
||||
expect(element.style.getPropertyPriority('width')).toBe('important')
|
||||
expect(element.getAttribute('data-element-fullscreen')).toBe('prior')
|
||||
first.enter()
|
||||
expect(first.isFullscreen.value).toBe(false)
|
||||
expect(element.getAttribute('data-element-fullscreen')).toBe('prior')
|
||||
second.enter()
|
||||
expect(second.isFullscreen.value).toBe(true)
|
||||
second.exit()
|
||||
|
||||
@ -94,3 +94,25 @@ it('resets to the first object page size and reports new values to the current c
|
||||
expect(api.getCallback()).toBeUndefined()
|
||||
expect(callback).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps mutable default page-size options local to each instance', () => {
|
||||
const [first] = usePagination()
|
||||
const [second] = usePagination()
|
||||
|
||||
first.value.pageSizes!.splice(0, 1, 5)
|
||||
|
||||
expect(second.value.pageSizes).toEqual([10, 20, 50, 100])
|
||||
expect(usePagination()[0].value.pageSizes).toEqual([10, 20, 50, 100])
|
||||
})
|
||||
|
||||
it('resets using the currently configured page sizes after replacing them', () => {
|
||||
const [pagination, api] = usePagination()
|
||||
|
||||
pagination.value.pageSizes = [{ label: 'Twenty five', value: 25 }]
|
||||
api.resetPagination()
|
||||
expect(api.getPageSize()).toBe(25)
|
||||
|
||||
pagination.value.pageSizes = []
|
||||
api.resetPagination()
|
||||
expect(api.getPageSize()).toBe(10)
|
||||
})
|
||||
|
||||
@ -1,189 +1,243 @@
|
||||
import { useAppRoot } from '../../apps/admin/src/hooks/template/useAppRoot'
|
||||
import { useSiderBar } from '../../apps/admin/src/hooks/template/useSiderBar'
|
||||
import { useVueRouter } from '../../apps/admin/src/hooks/web/useVueRouter'
|
||||
import { firstMenuLeaf } from '../../apps/admin/src/layout/navigation'
|
||||
import { useMenuActions, useMenuGetters } from '../../apps/admin/src/store'
|
||||
import type {
|
||||
AppMenuOption,
|
||||
MenuTagOptions,
|
||||
} from '../../apps/admin/src/types/modules/app'
|
||||
import setupMiniApp from '../utils/setupMiniApp'
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { useAppRoot } from '@/hooks/template/useAppRoot'
|
||||
import { useSiderBar } from '@/hooks/template/useSiderBar'
|
||||
import { setupI18n } from '@/locales'
|
||||
import { permissionRouter } from '@/router/utils/permission'
|
||||
import { piniaKeepAliveStore } from '@/store/modules/keep-alive'
|
||||
import { piniaMenuStore } from '@/store/modules/menu'
|
||||
import { piniaSettingStore } from '@/store/modules/setting'
|
||||
import { piniaSigningStore } from '@/store/modules/signing'
|
||||
import { setStorage } from '@/utils/cache'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import type { VueWrapper } from '@vue/test-utils'
|
||||
import { createPinia, disposePinia, setActivePinia } from 'pinia'
|
||||
import { defineComponent, h } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import type { Router } from 'vue-router'
|
||||
|
||||
describe('useSiderBar', async () => {
|
||||
await setupMiniApp()
|
||||
const state = vi.hoisted(() => ({
|
||||
router: null as unknown,
|
||||
routes: [] as unknown[],
|
||||
}))
|
||||
|
||||
const { setMenuTagOptions, resolveOption } = useMenuActions()
|
||||
const {
|
||||
close,
|
||||
closeAll,
|
||||
closeRight,
|
||||
closeLeft,
|
||||
closeOther,
|
||||
getCurrentTagIndex,
|
||||
checkCloseRight,
|
||||
checkCloseLeft,
|
||||
} = useSiderBar()
|
||||
vi.mock('../../apps/admin/src/hooks/template/useVueRouter', () => ({
|
||||
useVueRouter: () => ({ router: state.router }),
|
||||
}))
|
||||
vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
|
||||
getAppRawRoutes: () => state.routes,
|
||||
appExpandRoutes: () => state.routes,
|
||||
}))
|
||||
|
||||
const updateMenuTagOptions = () => {
|
||||
const { router } = useVueRouter()
|
||||
const routes = router.getRoutes() as unknown as AppMenuOption[]
|
||||
let pinia: ReturnType<typeof createPinia>
|
||||
let router: Router
|
||||
let wrapper: VueWrapper
|
||||
let menu: ReturnType<typeof piniaMenuStore>
|
||||
let actions: ReturnType<typeof useSiderBar>
|
||||
|
||||
routes.forEach((curr) =>
|
||||
setMenuTagOptions(
|
||||
resolveOption({
|
||||
...curr,
|
||||
fullPath: curr.path,
|
||||
}),
|
||||
true,
|
||||
),
|
||||
)
|
||||
beforeEach(async () => {
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
const component = { render: () => h('div') }
|
||||
const business = [
|
||||
{ path: '/reports', name: 'Reports', component, meta: { keepAlive: true } },
|
||||
{ path: '/orders', name: 'Orders', component, meta: {} },
|
||||
{
|
||||
path: '/private',
|
||||
name: 'Private',
|
||||
component,
|
||||
meta: { role: ['admin'], keepAlive: true },
|
||||
},
|
||||
]
|
||||
|
||||
state.routes = business
|
||||
router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'RLogin', component },
|
||||
{
|
||||
path: '/welcome',
|
||||
name: 'RWelcome',
|
||||
component,
|
||||
meta: { i18nKey: 'workspaceStates.welcome.title' },
|
||||
},
|
||||
{
|
||||
path: '/403',
|
||||
name: 'ErrorPage403',
|
||||
component,
|
||||
meta: { i18nKey: 'workspaceStates.forbidden.title' },
|
||||
},
|
||||
{ path: '/404', name: 'ErrorPage404', component },
|
||||
{ path: '/500', name: 'ErrorPage500', component },
|
||||
{ path: '/:catchAll(.*)', name: 'RNotFound', redirect: '/404' },
|
||||
...business,
|
||||
],
|
||||
})
|
||||
state.router = router
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
piniaSigningStore().signingCallback = {
|
||||
id: 'one',
|
||||
name: 'Tester',
|
||||
role: 'admin',
|
||||
}
|
||||
setStorage(APP_CATCH_KEY.token, 'token', 'localStorage')
|
||||
setStorage(APP_CATCH_KEY.appMenuTagOptions, [{ fullPath: '/dashboard' }])
|
||||
setStorage(APP_CATCH_KEY.appMenuKey, '/dashboard')
|
||||
permissionRouter(router)
|
||||
await router.push('/welcome')
|
||||
wrapper = mount(
|
||||
defineComponent({
|
||||
setup() {
|
||||
menu = piniaMenuStore()
|
||||
actions = useSiderBar()
|
||||
|
||||
it('should close target tag', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [dashboard] = getMenuOptions.value
|
||||
const beforeIndex = getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
close(dashboard.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
const afterIndex = getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
expect(beforeIndex).not.toBe(afterIndex)
|
||||
})
|
||||
|
||||
it('should close all tags', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuTagOptions } = useMenuGetters()
|
||||
|
||||
closeAll()
|
||||
|
||||
await nextTick()
|
||||
|
||||
const afterLength = getMenuTagOptions.value.length
|
||||
|
||||
expect(afterLength).toBe(1)
|
||||
})
|
||||
|
||||
it('should close right tags', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [dashboard] = getMenuOptions.value
|
||||
const beforeIndex = getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
expect(!!getMenuTagOptions.value[beforeIndex + 1]).toBe(true)
|
||||
|
||||
closeRight(dashboard.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
const afterIndex = getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
expect(getMenuTagOptions.value[afterIndex + 1]).toBe(void 0)
|
||||
})
|
||||
|
||||
it('should close left tags', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [dashboard] = getMenuOptions.value
|
||||
|
||||
closeLeft(dashboard.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
const afterIndex = getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
expect(getMenuTagOptions.value[afterIndex - 1]).toBe(void 0)
|
||||
})
|
||||
|
||||
it('should get current tag index', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [dashboard] = getMenuOptions.value
|
||||
|
||||
const index = getMenuOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === dashboard.fullPath,
|
||||
)
|
||||
|
||||
expect(getCurrentTagIndex()).toBe(index)
|
||||
})
|
||||
|
||||
it('should close other tags', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [dashboard] = getMenuOptions.value
|
||||
|
||||
closeOther(dashboard.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
expect(getMenuTagOptions.value[0].fullPath).toBe(dashboard.fullPath)
|
||||
expect(getMenuTagOptions.value.length).toBe(1)
|
||||
})
|
||||
|
||||
it('check menuTagOptions left or right can close', async () => {
|
||||
updateMenuTagOptions()
|
||||
|
||||
const { getMenuOptions, getMenuTagOptions } = useMenuGetters()
|
||||
const [f, group] = getMenuOptions.value
|
||||
const s = firstMenuLeaf(group)!
|
||||
|
||||
closeRight(f.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
const canClose = checkCloseRight(f.fullPath)
|
||||
|
||||
expect(canClose).toBe(false)
|
||||
|
||||
updateMenuTagOptions()
|
||||
|
||||
closeLeft(f.fullPath)
|
||||
|
||||
await nextTick()
|
||||
|
||||
const canCloseLeft = checkCloseLeft(f.fullPath)
|
||||
|
||||
expect(canCloseLeft).toBe(false)
|
||||
|
||||
updateMenuTagOptions()
|
||||
|
||||
expect(checkCloseRight(s.fullPath)).toBe(true)
|
||||
expect(checkCloseLeft(s.fullPath)).toBe(true)
|
||||
})
|
||||
it('keeps existing tags if the configured home route is no longer registered', () => {
|
||||
updateMenuTagOptions()
|
||||
const { getMenuTagOptions } = useMenuGetters()
|
||||
const { getRootRoute, setRootRoute } = useAppRoot()
|
||||
const currentRoot = { ...getRootRoute.value }
|
||||
const currentTags = getMenuTagOptions.value.map((item) => item.fullPath)
|
||||
|
||||
try {
|
||||
setRootRoute({ path: '/deleted-home-route' })
|
||||
closeAll()
|
||||
expect(getMenuTagOptions.value.map((item) => item.fullPath)).toEqual(
|
||||
currentTags,
|
||||
)
|
||||
} finally {
|
||||
setRootRoute(currentRoot)
|
||||
}
|
||||
})
|
||||
return () => h('div')
|
||||
},
|
||||
}),
|
||||
{ global: { plugins: [pinia, router] } },
|
||||
)
|
||||
await flushPromises()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
wrapper.unmount()
|
||||
disposePinia(pinia)
|
||||
router.options.history.destroy()
|
||||
})
|
||||
|
||||
it('starts with no active business page and never injects a missing cached dashboard', () => {
|
||||
expect(menu.menuTagOptions).toEqual([])
|
||||
expect(menu.menuKey).toBeNull()
|
||||
expect(menu.currentMenuOption).toBeNull()
|
||||
expect(menu.breadcrumbOptions).toEqual([])
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
expect(menu.options.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/reports',
|
||||
'/orders',
|
||||
'/private',
|
||||
])
|
||||
})
|
||||
|
||||
it('closes the final business tab, even when it is the legacy root preference', async () => {
|
||||
useAppRoot().setRootRoute({ path: '/reports', name: 'Reports' })
|
||||
await router.push('/reports?sort=asc#summary')
|
||||
await flushPromises()
|
||||
expect(actions.getCurrentTagIndex()).toBe(0)
|
||||
expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports'])
|
||||
await actions.close(0)
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions).toEqual([])
|
||||
expect(menu.menuKey).toBeNull()
|
||||
expect(menu.currentMenuOption).toBeNull()
|
||||
expect(piniaKeepAliveStore().keepAliveInclude).toEqual([])
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('stores one tag per pathname and restores its latest query and hash', async () => {
|
||||
await router.push('/reports?sort=asc#first')
|
||||
await router.push('/reports?sort=desc#summary')
|
||||
await router.push('/orders')
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/reports?sort=desc#summary',
|
||||
'/orders',
|
||||
])
|
||||
await actions.close('/orders')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.fullPath).toBe('/reports?sort=desc#summary')
|
||||
expect(menu.menuKey).toBe('/reports')
|
||||
expect(actions.getCurrentTagIndex()).toBe(0)
|
||||
})
|
||||
|
||||
it('closes left, right and other tabs without protecting any business path', async () => {
|
||||
for (const path of ['/reports', '/orders', '/private'])
|
||||
await router.push(path)
|
||||
|
||||
await flushPromises()
|
||||
expect(actions.checkCloseLeft('/orders')).toBe(true)
|
||||
expect(actions.checkCloseRight('/orders')).toBe(true)
|
||||
await actions.closeRight('/orders')
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/orders')
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/reports',
|
||||
'/orders',
|
||||
])
|
||||
await actions.closeLeft('/orders')
|
||||
await router.push('/reports')
|
||||
await actions.closeOther('/orders')
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/orders',
|
||||
])
|
||||
expect(router.currentRoute.value.path).toBe('/orders')
|
||||
})
|
||||
|
||||
it('closes all tags independently of missing or unauthorized root preferences', async () => {
|
||||
await router.push('/reports')
|
||||
await router.push('/orders')
|
||||
useAppRoot().setRootRoute({ path: '/deleted-home' })
|
||||
await actions.closeAll()
|
||||
await flushPromises()
|
||||
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')
|
||||
|
||||
for (const path of ['/welcome', '/403', '/404', '/500']) {
|
||||
await router.push(path)
|
||||
await flushPromises()
|
||||
expect(menu.currentMenuOption).toBeNull()
|
||||
expect(menu.menuKey).toBeNull()
|
||||
expect(menu.breadcrumbOptions).toEqual([])
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/reports',
|
||||
])
|
||||
}
|
||||
})
|
||||
|
||||
it('removes revoked tags and cached views without choosing another active page', async () => {
|
||||
await router.push('/reports')
|
||||
await router.push('/private?mode=edit#section')
|
||||
piniaSigningStore().signingCallback.role = 'member'
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions.map(({ fullPath }) => fullPath)).toEqual([
|
||||
'/reports',
|
||||
])
|
||||
expect(piniaKeepAliveStore().keepAliveInclude).toEqual(['Reports'])
|
||||
expect(menu.currentMenuOption).toBeNull()
|
||||
expect(router.currentRoute.value.path).toBe('/403')
|
||||
expect(router.currentRoute.value.query.from).toBe(
|
||||
'/private?mode=edit#section',
|
||||
)
|
||||
})
|
||||
|
||||
it('clears account-owned tabs without recreating the still-visible page during logout', async () => {
|
||||
await router.push('/reports')
|
||||
piniaSigningStore().signingCallback = {} as never
|
||||
await flushPromises()
|
||||
expect(menu.menuTagOptions).toEqual([])
|
||||
expect(menu.currentMenuOption).toBeNull()
|
||||
expect(piniaKeepAliveStore().keepAliveInclude).toEqual([])
|
||||
})
|
||||
|
||||
it('updates neutral and status document titles when the language changes', async () => {
|
||||
await setupI18n(wrapper.vm.$.appContext.app)
|
||||
const settings = piniaSettingStore()
|
||||
|
||||
settings.updateLocale('zh-CN')
|
||||
await router.push('/403')
|
||||
await flushPromises()
|
||||
expect(document.title).toContain('暂时无法访问此页面')
|
||||
settings.updateLocale('en-US')
|
||||
await flushPromises()
|
||||
expect(document.title).toContain('This page is not available to you')
|
||||
await router.push('/welcome')
|
||||
await flushPromises()
|
||||
expect(document.title).toContain('Ready for your next task')
|
||||
settings.updateLocale('zh-CN')
|
||||
await flushPromises()
|
||||
expect(document.title).toContain('工作区已就绪')
|
||||
})
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
import { useTheme } from '../../apps/admin/src/hooks/template/useTheme'
|
||||
import { useSettingGetters } from '../../apps/admin/src/store'
|
||||
import {
|
||||
useSettingActions,
|
||||
useSettingGetters,
|
||||
} from '../../apps/admin/src/store'
|
||||
import setupMiniApp from '../utils/setupMiniApp'
|
||||
|
||||
describe('useTheme', async () => {
|
||||
@ -46,6 +49,28 @@ describe('useTheme', async () => {
|
||||
expect(__lightThemeLabel).toBe('Light')
|
||||
})
|
||||
|
||||
it('keeps a reused hook reactive to language and theme changes', () => {
|
||||
const { updateLocale } = useSettingActions()
|
||||
const previousLocale = useSettingGetters().getLocaleLanguage.value
|
||||
|
||||
try {
|
||||
darkTheme()
|
||||
updateLocale('en-US')
|
||||
expect(getAppTheme().themeI18nLabel).toBe('Dark')
|
||||
updateLocale('zh-CN')
|
||||
expect(getAppTheme().themeI18nLabel).toBe('暗色')
|
||||
lightTheme()
|
||||
expect(getAppTheme()).toMatchObject({
|
||||
theme: false,
|
||||
themeLabel: 'Light',
|
||||
themeI18nLabel: '明亮',
|
||||
})
|
||||
} finally {
|
||||
updateLocale(previousLocale)
|
||||
lightTheme()
|
||||
}
|
||||
})
|
||||
|
||||
it('selects auto mode and applies the system color preference', () => {
|
||||
const dark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
|
||||
|
||||
89
__test__/layout/content-loading.spec.tsx
Normal file
89
__test__/layout/content-loading.spec.tsx
Normal file
@ -0,0 +1,89 @@
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { createPinia, disposePinia, setActivePinia } from 'pinia'
|
||||
import { nextTick } from 'vue'
|
||||
import ContentLoading from '../../apps/admin/src/layout/default/ContentWrapper/ContentLoading'
|
||||
import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime'
|
||||
|
||||
vi.mock('@/hooks', () => ({
|
||||
useI18n: () => ({ t: () => 'Loading' }),
|
||||
}))
|
||||
|
||||
describe('content loading feedback', () => {
|
||||
let pinia: ReturnType<typeof createPinia>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
disposePinia(pinia)
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('delays transient work and exposes a labeled indeterminate progress', async () => {
|
||||
const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } })
|
||||
const runtime = piniaRuntimeStore()
|
||||
|
||||
try {
|
||||
runtime.setRuntimeState('layoutContentSpinning', true)
|
||||
await nextTick()
|
||||
await vi.advanceTimersByTimeAsync(119)
|
||||
expect(wrapper.find('progress').exists()).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
|
||||
const progress = wrapper.get('progress')
|
||||
const label = wrapper.get(
|
||||
`[id="${progress.attributes('aria-labelledby')}"]`,
|
||||
)
|
||||
|
||||
expect(progress.attributes('value')).toBeUndefined()
|
||||
expect(label.text()).toBe('Loading')
|
||||
expect(
|
||||
wrapper.find('button, [role="button"], [role="status"]').exists(),
|
||||
).toBe(false)
|
||||
|
||||
runtime.setRuntimeState('layoutContentSpinning', false)
|
||||
await nextTick()
|
||||
expect(wrapper.find('progress').exists()).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels delayed feedback when work finishes or the loading host unmounts', async () => {
|
||||
const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } })
|
||||
const runtime = piniaRuntimeStore()
|
||||
|
||||
runtime.setRuntimeState('layoutContentSpinning', true)
|
||||
await nextTick()
|
||||
await vi.advanceTimersByTimeAsync(60)
|
||||
runtime.setRuntimeState('layoutContentSpinning', false)
|
||||
await nextTick()
|
||||
await vi.advanceTimersByTimeAsync(120)
|
||||
expect(wrapper.find('progress').exists()).toBe(false)
|
||||
|
||||
runtime.setRuntimeState('layoutContentSpinning', true)
|
||||
await nextTick()
|
||||
expect(vi.getTimerCount()).toBe(1)
|
||||
wrapper.unmount()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('shows immediately during a content remount and clears when it completes', async () => {
|
||||
const runtime = piniaRuntimeStore()
|
||||
|
||||
runtime.setRuntimeState('globalMainLayoutLoad', false)
|
||||
const wrapper = mount(ContentLoading, { global: { plugins: [pinia] } })
|
||||
|
||||
try {
|
||||
expect(wrapper.find('progress').exists()).toBe(true)
|
||||
runtime.setRuntimeState('globalMainLayoutLoad', true)
|
||||
await nextTick()
|
||||
expect(wrapper.find('progress').exists()).toBe(false)
|
||||
} finally {
|
||||
wrapper.unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
@ -47,6 +47,8 @@ it('isolates accounts and restores each account without storing titles or URL pa
|
||||
|
||||
store.recordVisit('/system/users')
|
||||
store.recordVisit('/search?private=value')
|
||||
store.recordVisit('/welcome')
|
||||
store.toggleFavorite('/500')
|
||||
store.toggleFavorite('/system/users')
|
||||
account('two')
|
||||
expect(store.recentPaths).toEqual([])
|
||||
|
||||
@ -40,6 +40,48 @@ const mountPersistedSettings = () => {
|
||||
}
|
||||
|
||||
describe('layout preferences', () => {
|
||||
it.each([
|
||||
{ title: 'Ray Admin', migrated: '/welcome' },
|
||||
{ title: 'Custom workspace', migrated: '/dashboard' },
|
||||
])(
|
||||
'migrates only the legacy default logo target ($title)',
|
||||
({ title, migrated }) => {
|
||||
localStorage.setItem(
|
||||
APP_CATCH_KEY.appPiniaSettingStore,
|
||||
JSON.stringify({
|
||||
sideBarLogo: {
|
||||
icon: 'logo/ray',
|
||||
title,
|
||||
url: '/dashboard',
|
||||
jumpType: 'station',
|
||||
},
|
||||
appRootRoute: { name: 'Old', path: '/old-unregistered-home' },
|
||||
}),
|
||||
)
|
||||
const first = mountPersistedSettings()
|
||||
const store = piniaSettingStore()
|
||||
|
||||
expect(store.sideBarLogo?.url).toBe(migrated)
|
||||
expect(store.appRootRoute.path).toBe('/old-unregistered-home')
|
||||
store.updateSettingState('sideBarLogo', { url: '/dashboard' })
|
||||
store.$persist()
|
||||
first.app.unmount()
|
||||
disposePinia(first.pinia)
|
||||
const second = mountPersistedSettings()
|
||||
|
||||
try {
|
||||
expect(piniaSettingStore().sideBarLogo?.url).toBe('/dashboard')
|
||||
expect(
|
||||
piniaSettingStore().exportPreferences().preferences,
|
||||
).not.toHaveProperty('workspaceLandingMigrated')
|
||||
} finally {
|
||||
second.app.unmount()
|
||||
disposePinia(second.pinia)
|
||||
localStorage.removeItem(APP_CATCH_KEY.appPiniaSettingStore)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it('adds defaults and bounds persisted or programmatic invalid values', () => {
|
||||
expect(normalizeLayoutConfig(null)).toEqual(
|
||||
getDefaultSettingConfig().layoutConfig,
|
||||
|
||||
@ -2,6 +2,7 @@ import {
|
||||
appExpandRoutes,
|
||||
getAppRawRoutes,
|
||||
getStaticAppRoutes,
|
||||
setAppRouteModules,
|
||||
} from '@/router/app-route-modules'
|
||||
import {
|
||||
exportRouteConfig,
|
||||
@ -153,10 +154,10 @@ describe('route configuration', () => {
|
||||
[{ ...page, path: '/reports', meta: { keepAlive: true } }],
|
||||
/registered component name/i,
|
||||
],
|
||||
[
|
||||
[{ ...page, path: '/dashboard', meta: { role: ['editor'] } }],
|
||||
/all authenticated roles/i,
|
||||
],
|
||||
[[{ ...page, path: '/welcome' }], /reserved/i],
|
||||
[[{ ...page, path: '/reports', alias: '/403' }], /reserved/i],
|
||||
[[{ ...page, path: '/reports', name: 'ErrorPage500' }], /reserved/i],
|
||||
[[{ ...page, path: '/404' }], /reserved/i],
|
||||
[
|
||||
[{ path: '/external', meta: { windowOpen: 'javascript:alert(1)' } }],
|
||||
/windowOpen/,
|
||||
@ -188,6 +189,27 @@ describe('route configuration', () => {
|
||||
expect(() => parse(routes)).toThrow(message)
|
||||
})
|
||||
|
||||
it('allows restricted dashboard pages and does not inject one into custom sources', () => {
|
||||
expect(
|
||||
parse([{ ...page, path: '/dashboard', meta: { role: ['editor'] } }])
|
||||
.routes,
|
||||
).toHaveLength(1)
|
||||
|
||||
try {
|
||||
setAppRouteModules(
|
||||
toRuntimeRoutes(parse([{ ...page, path: '/reports' }])),
|
||||
)
|
||||
expect(appExpandRoutes().some(({ path }) => path === '/dashboard')).toBe(
|
||||
false,
|
||||
)
|
||||
expect(appExpandRoutes().some(({ path }) => path === '/reports')).toBe(
|
||||
true,
|
||||
)
|
||||
} finally {
|
||||
setAppRouteModules(getStaticAppRoutes())
|
||||
}
|
||||
})
|
||||
|
||||
it('sorts missing order consistently and leaves the input in place', () => {
|
||||
const first = { path: '/first', name: 'A', meta: {} }
|
||||
const second = { path: '/second', name: 'B', meta: { order: 0 } }
|
||||
|
||||
43
__test__/router/initialization.spec.ts
Normal file
43
__test__/router/initialization.spec.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import type { App } from 'vue'
|
||||
import { router, setupRouter } from '../../apps/admin/src/router'
|
||||
|
||||
const { load, register } = vi.hoisted(() => ({
|
||||
load: vi.fn(),
|
||||
register: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../apps/admin/src/router/config/source', () => ({
|
||||
loadRouteConfig: load,
|
||||
}))
|
||||
vi.mock('../../apps/admin/src/router/routes', () => ({
|
||||
constantRoutes: [{ path: '/', component: { render: () => null } }],
|
||||
getLayoutRoutes: () => [],
|
||||
}))
|
||||
vi.mock('../../apps/admin/src/router/app-route-modules', () => ({
|
||||
setAppRouteModules: vi.fn(),
|
||||
}))
|
||||
vi.mock('../../apps/admin/src/router/utils', () => ({
|
||||
scrollViewToTop: vi.fn(),
|
||||
vueRouterRegister: register,
|
||||
}))
|
||||
|
||||
it('retries failed initialization on remount and shares the successful retry', async () => {
|
||||
const app = { use: vi.fn() } as unknown as App<Element>
|
||||
|
||||
load
|
||||
.mockRejectedValueOnce(new Error('route endpoint unavailable'))
|
||||
.mockResolvedValue(void 0)
|
||||
|
||||
try {
|
||||
await expect(setupRouter(app)).rejects.toThrow('route endpoint unavailable')
|
||||
expect(register).not.toHaveBeenCalled()
|
||||
await Promise.all([setupRouter(app), setupRouter(app)])
|
||||
expect(load).toHaveBeenCalledTimes(2)
|
||||
expect(register).toHaveBeenCalledOnce()
|
||||
await setupRouter(app)
|
||||
expect(load).toHaveBeenCalledTimes(2)
|
||||
expect(register).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
router.options.history.destroy()
|
||||
}
|
||||
})
|
||||
@ -1,11 +1,9 @@
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
import { APP_CATCH_KEY } from '../../apps/admin/src/app-config'
|
||||
import { permissionRouter } from '../../apps/admin/src/router/utils/permission'
|
||||
import { resolveLandingPath } from '../../apps/admin/src/router/utils/resolve-landing-path'
|
||||
import { setStorage } from '../../apps/admin/src/utils/cache'
|
||||
|
||||
vi.mock('../../apps/admin/src/hooks', () => ({
|
||||
useAppRoot: () => ({ getRootPath: { value: '/dashboard' } }),
|
||||
}))
|
||||
vi.mock('../../apps/admin/src/router/utils/valid-role', () => ({
|
||||
validRole: (meta: { role?: string[] }) =>
|
||||
!meta.role?.length || meta.role.includes('admin'),
|
||||
@ -17,9 +15,14 @@ function setupRouter(rootRole?: string[]) {
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/', name: 'RLogin', component },
|
||||
{ path: '/welcome', name: 'RWelcome', component },
|
||||
{ path: '/403', name: 'ErrorPage403', component },
|
||||
{ path: '/404', name: 'ErrorPage404', component },
|
||||
{ path: '/500', name: 'ErrorPage500', component },
|
||||
{ path: '/dashboard', component, meta: { role: rootRole } },
|
||||
{ path: '/allowed', component, meta: { role: ['admin'] } },
|
||||
{ path: '/denied', component, meta: { role: ['editor'] } },
|
||||
{ path: '/legacy', redirect: '/allowed' },
|
||||
{
|
||||
path: '/docs',
|
||||
name: 'RayTemplateDoc',
|
||||
@ -48,13 +51,13 @@ describe('Router 5 permission guard', () => {
|
||||
expect(router.currentRoute.value.path).toBe('/')
|
||||
})
|
||||
|
||||
it('redirects authenticated login to the configured home', async () => {
|
||||
it('opens the neutral workspace after login without choosing a business home', async () => {
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push('/')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/dashboard')
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
})
|
||||
|
||||
it('allows permitted roles and authenticated whitelist routes', async () => {
|
||||
@ -70,22 +73,85 @@ describe('Router 5 permission guard', () => {
|
||||
expect(router.currentRoute.value.path).toBe('/docs')
|
||||
})
|
||||
|
||||
it('redirects a denied role to home', async () => {
|
||||
it('shows forbidden state for a denied direct link', async () => {
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push('/denied')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/dashboard')
|
||||
expect(router.currentRoute.value.path).toBe('/403')
|
||||
expect(router.currentRoute.value.query.from).toBe('/denied')
|
||||
})
|
||||
|
||||
it('cancels when home itself is denied instead of redirecting forever', async () => {
|
||||
it('does not depend on the legacy dashboard being permitted', async () => {
|
||||
const router = setupRouter(['editor'])
|
||||
|
||||
await router.push('/')
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
await router.push('/denied')
|
||||
|
||||
expect(router.currentRoute.value.path).toBe('/')
|
||||
expect(router.currentRoute.value.path).toBe('/403')
|
||||
})
|
||||
|
||||
it('retains an authorized requested URL through login with query and hash intact', async () => {
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push('/allowed?filter=open#row-2')
|
||||
expect(router.currentRoute.value.query.redirect).toBe(
|
||||
'/allowed?filter=open#row-2',
|
||||
)
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
await router.replace(
|
||||
resolveLandingPath(router, router.currentRoute.value.query.redirect),
|
||||
)
|
||||
expect(router.currentRoute.value.fullPath).toBe(
|
||||
'/allowed?filter=open#row-2',
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves query and hash when an authenticated login URL supplies a valid redirect', async () => {
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push({
|
||||
path: '/',
|
||||
query: { redirect: '/allowed?filter=open#row-2' },
|
||||
})
|
||||
expect(router.currentRoute.value.fullPath).toBe(
|
||||
'/allowed?filter=open#row-2',
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'/denied',
|
||||
'/missing',
|
||||
'//example.com',
|
||||
'https://example.com',
|
||||
'/500',
|
||||
'/\\example.com',
|
||||
])(
|
||||
'does not restore unsafe, inaccessible or status target %s',
|
||||
async (redirect) => {
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push({ path: '/', query: { redirect } })
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
},
|
||||
)
|
||||
|
||||
it('validates redirect destinations while preserving their original requested URL', () => {
|
||||
expect(resolveLandingPath(setupRouter(), '/legacy?filter=open#row')).toBe(
|
||||
'/legacy?filter=open#row',
|
||||
)
|
||||
})
|
||||
|
||||
it('shows not found for an unknown authenticated route', async () => {
|
||||
setStorage(APP_CATCH_KEY.token, 'demo-token', 'localStorage')
|
||||
const router = setupRouter()
|
||||
|
||||
await router.push('/missing?from=test')
|
||||
expect(router.currentRoute.value.path).toBe('/404')
|
||||
expect(router.currentRoute.value.query.from).toBe('/missing?from=test')
|
||||
})
|
||||
})
|
||||
|
||||
110
__test__/router/workspace-errors.spec.ts
Normal file
110
__test__/router/workspace-errors.spec.ts
Normal file
@ -0,0 +1,110 @@
|
||||
import { setupRouterErrors } from '@/router/utils/setup-router-errors'
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
|
||||
it('routes a failed page import to 500 with its original recovery target', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/welcome', component: { render: () => null } },
|
||||
{ path: '/500', component: { render: () => null } },
|
||||
{
|
||||
path: '/reports',
|
||||
component: () => Promise.reject(new Error('chunk unavailable')),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
setupRouterErrors(router)
|
||||
|
||||
try {
|
||||
await router.push('/welcome')
|
||||
await expect(router.push('/reports?range=week#chart')).rejects.toThrow(
|
||||
'chunk unavailable',
|
||||
)
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe('/500')
|
||||
expect(router.currentRoute.value.query.from).toBe(
|
||||
'/reports?range=week#chart',
|
||||
)
|
||||
} finally {
|
||||
router.options.history.destroy()
|
||||
consoleError.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not retry recursively when the 500 page itself cannot load', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const loader = vi.fn(() => Promise.reject(new Error('status unavailable')))
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/welcome', component: { render: () => null } },
|
||||
{ path: '/500', component: loader },
|
||||
],
|
||||
})
|
||||
|
||||
setupRouterErrors(router)
|
||||
|
||||
try {
|
||||
await router.push('/welcome')
|
||||
await expect(router.push('/500')).rejects.toThrow('status unavailable')
|
||||
await flushPromises()
|
||||
expect(loader).toHaveBeenCalledOnce()
|
||||
expect(router.currentRoute.value.path).toBe('/welcome')
|
||||
} finally {
|
||||
router.options.history.destroy()
|
||||
consoleError.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['succeeded', 'pending', 'duplicated'] as const)(
|
||||
'ignores an older failed import when a newer navigation is %s',
|
||||
async (newer) => {
|
||||
const stale = Promise.withResolvers<{ render: () => null }>()
|
||||
const next = Promise.withResolvers<{ render: () => null }>()
|
||||
const component = { render: () => null }
|
||||
const router = createRouter({
|
||||
history: createMemoryHistory(),
|
||||
routes: [
|
||||
{ path: '/welcome', component },
|
||||
{ path: '/500', component },
|
||||
{ path: '/slow', component: () => stale.promise },
|
||||
{
|
||||
path: '/ready',
|
||||
component: newer === 'pending' ? () => next.promise : component,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
setupRouterErrors(router)
|
||||
|
||||
try {
|
||||
await router.push('/welcome')
|
||||
const oldNavigation = router
|
||||
.push('/slow')
|
||||
.catch((error: unknown) => error)
|
||||
|
||||
await flushPromises()
|
||||
const newNavigation = router.push(
|
||||
newer === 'duplicated' ? '/welcome' : '/ready',
|
||||
)
|
||||
|
||||
await flushPromises()
|
||||
stale.reject(new Error('obsolete chunk'))
|
||||
await oldNavigation
|
||||
await flushPromises()
|
||||
expect(router.currentRoute.value.path).toBe(
|
||||
newer === 'succeeded' ? '/ready' : '/welcome',
|
||||
)
|
||||
next.resolve(component)
|
||||
await newNavigation
|
||||
expect(router.currentRoute.value.path).toBe(
|
||||
newer === 'duplicated' ? '/welcome' : '/ready',
|
||||
)
|
||||
} finally {
|
||||
router.options.history.destroy()
|
||||
}
|
||||
},
|
||||
)
|
||||
@ -8,11 +8,39 @@
|
||||
<meta name="description" content="<%= siteInfo.description %>" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<script>
|
||||
// 入口依赖可能在 main.ts 执行前失败;捕获不冒泡的模块加载错误和窗口求值错误。
|
||||
window.addEventListener(
|
||||
'error',
|
||||
function handleStartupError(event) {
|
||||
const splash = document.getElementById('pre-loading-animation')
|
||||
|
||||
if (!splash) {
|
||||
window.removeEventListener('error', handleStartupError, true)
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
event instanceof ErrorEvent ||
|
||||
(event.target instanceof HTMLScriptElement &&
|
||||
event.target.type === 'module')
|
||||
) {
|
||||
splash.setAttribute('data-state', 'failed')
|
||||
}
|
||||
},
|
||||
true,
|
||||
)
|
||||
try {
|
||||
const settings = JSON.parse(
|
||||
localStorage.getItem('<%= storageKeys.appPiniaSettingStore %>') ||
|
||||
'null',
|
||||
)
|
||||
document.documentElement.dataset.bootStyle = [
|
||||
'plain',
|
||||
'naive',
|
||||
'material',
|
||||
].includes(settings?.themeStyle)
|
||||
? settings.themeStyle
|
||||
: 'modern'
|
||||
const mode = settings?.appTheme
|
||||
if (mode !== 'auto') {
|
||||
const dark =
|
||||
@ -40,6 +68,14 @@
|
||||
}
|
||||
|
||||
.ray-boot {
|
||||
--boot-canvas: light-dark(#f5f7fb, #101722);
|
||||
--boot-surface: light-dark(#fff, #172131);
|
||||
--boot-line: light-dark(#e4e9f1, #2c394d);
|
||||
--boot-text: light-dark(#1d2a3e, #e9eef7);
|
||||
--boot-muted: light-dark(#52647c, #b3c0d3);
|
||||
--boot-accent: light-dark(#3b63d9, #aabaff);
|
||||
--boot-radius: 20px;
|
||||
--boot-shadow: 0 2px 6px rgb(0 0 0 / 3%);
|
||||
position: fixed;
|
||||
z-index: 1;
|
||||
inset: 0;
|
||||
@ -47,32 +83,80 @@
|
||||
place-items: center;
|
||||
padding: 24px;
|
||||
color: CanvasText;
|
||||
color: light-dark(#182436, #e9eef7);
|
||||
color: var(--boot-text);
|
||||
background: Canvas;
|
||||
background: light-dark(#f8f9fc, #141b27);
|
||||
background: var(--boot-canvas);
|
||||
font:
|
||||
400 14px / 1.5 system-ui,
|
||||
sans-serif;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
html[data-boot-style='plain'] .ray-boot {
|
||||
--boot-canvas: light-dark(#f5f5f5, #161616);
|
||||
--boot-surface: light-dark(#fff, #202020);
|
||||
--boot-line: light-dark(#e0e0e0, #383838);
|
||||
--boot-text: light-dark(#252525, #ededed);
|
||||
--boot-muted: light-dark(#616161, #b9b9b9);
|
||||
--boot-accent: light-dark(#454545, #d5d5d5);
|
||||
--boot-radius: 2px;
|
||||
--boot-shadow: none;
|
||||
}
|
||||
|
||||
html[data-boot-style='naive'] .ray-boot {
|
||||
--boot-canvas: light-dark(#fff, #101014);
|
||||
--boot-surface: light-dark(#fff, #18181c);
|
||||
--boot-line: light-dark(#efeff5, #343438);
|
||||
--boot-text: light-dark(#333639, #f0f0f0);
|
||||
--boot-muted: light-dark(#666970, #b5b5b8);
|
||||
--boot-accent: light-dark(#18a058, #63e2b7);
|
||||
--boot-radius: 4px;
|
||||
--boot-shadow: none;
|
||||
}
|
||||
|
||||
html[data-boot-style='material'] .ray-boot {
|
||||
--boot-canvas: light-dark(#f5f1fa, #16121c);
|
||||
--boot-surface: light-dark(#fffaff, #241e2c);
|
||||
--boot-line: light-dark(#e1d8ea, #473c52);
|
||||
--boot-text: light-dark(#201a29, #f1e7fa);
|
||||
--boot-muted: light-dark(#433a50, #ded0e8);
|
||||
--boot-accent: light-dark(#655292, #d6bbff);
|
||||
--boot-radius: 28px;
|
||||
}
|
||||
|
||||
.ray-boot__content {
|
||||
animation: ray-boot-reveal 320ms ease-out both;
|
||||
}
|
||||
|
||||
.ray-boot__brand {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
inline-size: 80px;
|
||||
block-size: 80px;
|
||||
margin: 0 auto 22px;
|
||||
border: 1px solid var(--boot-line);
|
||||
border-radius: var(--boot-radius);
|
||||
background: var(--boot-surface);
|
||||
box-shadow: var(--boot-shadow);
|
||||
}
|
||||
|
||||
.ray-boot__mark {
|
||||
display: block;
|
||||
margin: 0 auto 16px;
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.ray-boot__title {
|
||||
display: block;
|
||||
font-size: 24px;
|
||||
font-weight: 650;
|
||||
letter-spacing: -0.025em;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.035em;
|
||||
}
|
||||
|
||||
.ray-boot__label {
|
||||
margin: 4px 0 0;
|
||||
margin: 14px 0 0;
|
||||
color: inherit;
|
||||
color: light-dark(#52647c, #b3c0d3);
|
||||
color: var(--boot-muted);
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.015em;
|
||||
}
|
||||
|
||||
.ray-boot__track {
|
||||
@ -80,11 +164,11 @@
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
inline-size: 112px;
|
||||
block-size: 3px;
|
||||
margin: 20px auto 0;
|
||||
border-radius: 4px;
|
||||
block-size: 2px;
|
||||
margin: 24px auto 0;
|
||||
border-radius: 1px;
|
||||
background: currentColor;
|
||||
background: light-dark(#dce4f2, #36435c);
|
||||
background: var(--boot-line);
|
||||
}
|
||||
|
||||
.ray-boot__track::after {
|
||||
@ -94,8 +178,8 @@
|
||||
inline-size: 40%;
|
||||
border-radius: inherit;
|
||||
background: Highlight;
|
||||
background: light-dark(#3b63d9, #aabaff);
|
||||
animation: ray-boot-sweep 1.45s ease-in-out infinite alternate;
|
||||
background: var(--boot-accent);
|
||||
animation: ray-boot-sweep 1.4s ease-in-out infinite alternate;
|
||||
content: '';
|
||||
}
|
||||
|
||||
@ -108,6 +192,17 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes ray-boot-reveal {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.ray-boot progress {
|
||||
position: absolute;
|
||||
inline-size: 1px;
|
||||
@ -147,10 +242,43 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ray-boot__retry:focus-visible {
|
||||
outline: 2px solid var(--boot-accent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ray-boot__track::after {
|
||||
.ray-boot__content {
|
||||
animation: none;
|
||||
transform: translateX(75%);
|
||||
}
|
||||
|
||||
.ray-boot__track::after {
|
||||
animation-duration: 6s;
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.ray-boot {
|
||||
color: CanvasText;
|
||||
background: Canvas;
|
||||
}
|
||||
|
||||
.ray-boot__brand {
|
||||
border-color: ButtonBorder;
|
||||
background: Canvas;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.ray-boot__label {
|
||||
color: CanvasText;
|
||||
}
|
||||
|
||||
.ray-boot__track {
|
||||
border-block-end: 2px solid GrayText;
|
||||
}
|
||||
|
||||
.ray-boot__track::after {
|
||||
border-block-end: 2px solid Highlight;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -179,22 +307,24 @@
|
||||
</main>
|
||||
</noscript>
|
||||
<div id="pre-loading-animation" class="ray-boot">
|
||||
<div>
|
||||
<img
|
||||
class="ray-boot__mark"
|
||||
src="/ray.svg"
|
||||
width="56"
|
||||
height="56"
|
||||
alt=""
|
||||
/>
|
||||
<div class="ray-boot__content">
|
||||
<span class="ray-boot__brand">
|
||||
<img
|
||||
class="ray-boot__mark"
|
||||
src="/ray.svg"
|
||||
width="48"
|
||||
height="48"
|
||||
alt=""
|
||||
/>
|
||||
</span>
|
||||
<strong class="ray-boot__title"><%= preloadingConfig.title %></strong>
|
||||
<div class="ray-boot__pending">
|
||||
<span class="ray-boot__track" aria-hidden="true"></span>
|
||||
<p class="ray-boot__label" id="ray-boot-label">
|
||||
<span lang="zh-CN">正在载入工作区</span>
|
||||
<span lang="en-US">Loading your workspace</span>
|
||||
</p>
|
||||
<progress aria-labelledby="ray-boot-label"></progress>
|
||||
<span class="ray-boot__track" aria-hidden="true"></span>
|
||||
</div>
|
||||
<div class="ray-boot__failure" role="alert">
|
||||
<p class="ray-boot__label">
|
||||
|
||||
@ -29,6 +29,7 @@ export default defineComponent({
|
||||
translate: t,
|
||||
columnStorage: createStorage(window.localStorage, APP_CATCH_KEY_PREFIX),
|
||||
reportError: (message) => window.$message?.error(message),
|
||||
reportSuccess: (message) => window.$message?.success(message),
|
||||
iconUrl: (name, prefix) =>
|
||||
`${iconSprites[name.split('/')[0] as IconPackage]}#${prefix}-${name}`,
|
||||
})
|
||||
|
||||
@ -1,12 +0,0 @@
|
||||
# \_\_ray-template
|
||||
|
||||
This module owns template management checks, including:
|
||||
|
||||
- validAppRootPath: Validate the template's `appRootPath` configuration.
|
||||
- validLocal: Validate the template's `localConfig` configuration.
|
||||
|
||||
## Extension
|
||||
|
||||
Add custom template-management operations here when appropriate, then import and call them in `main.ts`.
|
||||
|
||||
Imports and invocation are explicit; this module does not provide automatic discovery or execution.
|
||||
@ -1,16 +0,0 @@
|
||||
import { validAppRootPath } from './valid/valid-app-root-path'
|
||||
import { validLocal } from './valid/valid-local'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 该方法用于初始化 ray-template 配置。
|
||||
*/
|
||||
export const setupRayTemplateCore = async () => {
|
||||
if (!__DEV__) {
|
||||
return
|
||||
}
|
||||
|
||||
await validAppRootPath()
|
||||
await validLocal()
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
import { useVueRouter } from '@/hooks'
|
||||
import { useSettingGetters } from '@/store'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 检查 appRootRoute.path 是否存配置正确。如果配置错误,将抛出错误。
|
||||
*
|
||||
* 如果配置错误可以检查: [src/store/modules/setting/index.ts] 中的 appRootRoute 配置。
|
||||
*
|
||||
* 该方法会通过调用 getRoutes 方法获取所有路由,也就意味着检查的路由格式是铺开之后的格式。当你的路由是嵌套路由时,需要注意检查完整的路径。
|
||||
*/
|
||||
export const validAppRootPath = async () => {
|
||||
const { getAppRootRoute } = useSettingGetters()
|
||||
const {
|
||||
router: { getRoutes },
|
||||
} = useVueRouter()
|
||||
|
||||
const find = getRoutes().find(
|
||||
(curr) => curr.path === getAppRootRoute.value.path,
|
||||
)
|
||||
|
||||
if (!find) {
|
||||
throw new Error(
|
||||
`[validAppRootPath]: 'store setting appRootRoute path: ' '${getAppRootRoute.value.path}' not found in router, please check the 'appRootRoute' setting in the store setting module.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@ -1,99 +0,0 @@
|
||||
import {
|
||||
DAYJS_LOCAL_MAP,
|
||||
DEFAULT_DAYJS_LOCAL,
|
||||
LOCAL_OPTIONS,
|
||||
SYSTEM_DEFAULT_LOCAL,
|
||||
SYSTEM_FALLBACK_LOCALE,
|
||||
} from '@/app-config'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 获取所有的 LOCAL_OPTIONS 的 key。
|
||||
*/
|
||||
const getLocalOptionKeys = () => {
|
||||
return LOCAL_OPTIONS.map((curr) => curr.key)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 验证 SYSTEM_DEFAULT_LOCAL 是否在 LOCAL_OPTIONS 中。
|
||||
*/
|
||||
const validSystemDefaultLocal = () => {
|
||||
const localOptionKeys = getLocalOptionKeys()
|
||||
|
||||
if (!localOptionKeys.includes(SYSTEM_DEFAULT_LOCAL)) {
|
||||
throw new Error(
|
||||
`[validLocal validSystemDefaultLocal:] SYSTEM_DEFAULT_LOCAL: '${SYSTEM_DEFAULT_LOCAL}' is not in LOCAL_OPTIONS: [${localOptionKeys.join(
|
||||
', ',
|
||||
)}]`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 验证 SYSTEM_FALLBACK_LOCALE 是否在 LOCAL_OPTIONS 中。
|
||||
*/
|
||||
const validSystemFallbackLocale = () => {
|
||||
const localOptionKeys = getLocalOptionKeys()
|
||||
|
||||
if (!localOptionKeys.includes(SYSTEM_FALLBACK_LOCALE)) {
|
||||
throw new Error(
|
||||
`[validLocal validSystemFallbackLocale:] SYSTEM_FALLBACK_LOCALE: '${SYSTEM_FALLBACK_LOCALE}' is not in LOCAL_OPTIONS: [${localOptionKeys.join(
|
||||
', ',
|
||||
)}]`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 验证 DAYJS_LOCAL_MAP 是否在 LOCAL_OPTIONS 中。
|
||||
*/
|
||||
const validDayjsLocalMap = () => {
|
||||
const localOptionKeys = getLocalOptionKeys() as string[]
|
||||
const dayjsLocalKeys = Object.keys(DAYJS_LOCAL_MAP)
|
||||
|
||||
dayjsLocalKeys.forEach((key) => {
|
||||
if (!localOptionKeys.includes(key)) {
|
||||
throw new Error(
|
||||
`[validLocal validDayjsLocalMap:] DAYJS_LOCAL_MAP: '${key}' is not in LOCAL_OPTIONS: [${localOptionKeys.join(
|
||||
', ',
|
||||
)}]`,
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 验证 DEFAULT_DAYJS_LOCAL 是否在 DAYJS_LOCAL_MAP 中。
|
||||
*/
|
||||
const validDefaultDayjsLocal = () => {
|
||||
const dayjsLocalKeys = Object.values(DAYJS_LOCAL_MAP)
|
||||
|
||||
if (!dayjsLocalKeys.includes(DEFAULT_DAYJS_LOCAL)) {
|
||||
throw new Error(
|
||||
`[validLocal validDefaultDayjsLocal:] DEFAULT_DAYJS_LOCAL: '${DEFAULT_DAYJS_LOCAL}' is not in DAYJS_LOCAL_MAP: [${dayjsLocalKeys.join(
|
||||
', ',
|
||||
)}]`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 验证所有的 localConfig 相关的配置。
|
||||
*/
|
||||
export const validLocal = async () => {
|
||||
validSystemDefaultLocal()
|
||||
validSystemFallbackLocale()
|
||||
validDayjsLocalMap()
|
||||
validDefaultDayjsLocal()
|
||||
}
|
||||
@ -9,7 +9,9 @@ This directory contains components closely coupled to the template:
|
||||
|
||||
- `AppPageHeader` standardizes the eyebrow, main title, description, and right-side actions. Pages retain their own body layouts; do not wrap business content here.
|
||||
- `AppShareLink` defaults to a compact entry point. The dashboard uses `variant="cards"` for named link cards while preserving the login page's space constraints.
|
||||
- `AppAvatar` reads the avatar and name from the signing store and retains relevant Naive UI Avatar props.
|
||||
- `AppAvatar` reads the avatar and name from the signing store and retains Naive UI size, shape and object-fit props. `avatarSize` remains an optional legacy size override. Its button remains keyboard focusable.
|
||||
- `AppGlobalSpin` binds visibility to runtime state and merges caller theme overrides over its default opacity. It forwards the remaining Spin props and slots.
|
||||
- `AppLockScreen` and its lock/unlock views share bilingual rules and copy. Clock updates align to minute boundaries, pause while the document is hidden, and release their timer on unmount.
|
||||
- `AppNaiveGlobalProvider` supplies Naive UI context and `window.$message`, `$notification`, `$dialog`, and `$loadingBar`. Discrete notification instances initialize and dispose with the provider and track theme/locale changes. Use them only while the provider is mounted.
|
||||
- `AppWatermarkProvider` provides the global watermark entry point; `useWatermark` controls visibility and content. Change the provider's mount location to limit its coverage.
|
||||
- `AppRequestCancelerProvider` cancels old requests before route updates. Default layout content mounts it; custom content slots must retain the required cancellation behavior.
|
||||
|
||||
@ -7,6 +7,11 @@ const AppAvatar = defineComponent({
|
||||
name: 'AppAvatar',
|
||||
props: {
|
||||
...avatarProps,
|
||||
round: { type: Boolean, default: true },
|
||||
objectFit: {
|
||||
type: String as PropType<AvatarProps['objectFit']>,
|
||||
default: 'cover',
|
||||
},
|
||||
cursor: {
|
||||
type: String,
|
||||
default: 'auto',
|
||||
@ -17,7 +22,7 @@ const AppAvatar = defineComponent({
|
||||
},
|
||||
avatarSize: {
|
||||
type: [String, Number] as PropType<AvatarProps['size']>,
|
||||
default: 'medium',
|
||||
default: void 0,
|
||||
},
|
||||
vertical: {
|
||||
type: Boolean,
|
||||
@ -35,14 +40,12 @@ const AppAvatar = defineComponent({
|
||||
const { getSigningCallback, avatarSize, spaceSize, $props, vertical } = this
|
||||
|
||||
return (
|
||||
<NButton quaternary strong focusable={false}>
|
||||
<NButton quaternary strong style={{ cursor: this.cursor }}>
|
||||
<NFlex align="center" size={spaceSize} vertical={vertical}>
|
||||
<NAvatar
|
||||
{...($props as AvatarProps)}
|
||||
src={getSigningCallback?.avatar}
|
||||
objectFit="cover"
|
||||
round
|
||||
size={avatarSize}
|
||||
size={avatarSize ?? this.size}
|
||||
>
|
||||
{{
|
||||
default: () =>
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { useRuntimeActions, useRuntimeGetters } from '@/store'
|
||||
import { useRuntimeGetters } from '@/store'
|
||||
import { NSpin, spinProps } from 'naive-ui'
|
||||
import type { SpinProps } from 'naive-ui'
|
||||
|
||||
@ -7,10 +7,11 @@ const GlobalSpin = defineComponent({
|
||||
props: {
|
||||
...spinProps,
|
||||
},
|
||||
setup() {
|
||||
const overrides = {
|
||||
setup(props) {
|
||||
const overrides = computed(() => ({
|
||||
opacitySpinning: '0.3',
|
||||
}
|
||||
...props.themeOverrides,
|
||||
}))
|
||||
const spinValue = useRuntimeGetters().globalSpinning
|
||||
|
||||
return {
|
||||
|
||||
@ -1,5 +1,12 @@
|
||||
import { useLockScreenActions, useLockScreenGetters } from '@/store'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 复用锁屏 Store 的状态访问,不创建独立缓存或监听器。
|
||||
*
|
||||
* @returns 读取和更新当前锁屏状态的方法
|
||||
*/
|
||||
const useAppLockScreen = () => {
|
||||
const { getLocked } = useLockScreenGetters()
|
||||
const { setLocked } = useLockScreenActions()
|
||||
|
||||
@ -1,8 +1,12 @@
|
||||
import AppAvatar from '@/app-components/app/AppAvatar'
|
||||
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
|
||||
import { rules, useCondition } from '@/app-components/app/AppLockScreen/shared'
|
||||
import {
|
||||
useCondition,
|
||||
useLockRules,
|
||||
} from '@/app-components/app/AppLockScreen/shared'
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { RForm, useForm } from '@/components'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { useSettingActions } from '@/store'
|
||||
import { encrypt, setStorage } from '@/utils'
|
||||
import { NButton, NFormItem, NInput } from 'naive-ui'
|
||||
@ -12,6 +16,8 @@ import { useTemplateRef } from 'vue'
|
||||
const LockScreen = defineComponent({
|
||||
name: 'LockScreen',
|
||||
setup() {
|
||||
const { t } = useI18n('appComponents.lockScreen')
|
||||
const rules = useLockRules()
|
||||
const [register, { validate }] = useForm()
|
||||
const inputInstRef = useTemplateRef<InputInst | null>('inputInstRef')
|
||||
|
||||
@ -22,18 +28,35 @@ const LockScreen = defineComponent({
|
||||
lockCondition: useCondition(),
|
||||
})
|
||||
|
||||
const lockScreen = () => {
|
||||
validate().then(() => {
|
||||
setLockAppScreen(true)
|
||||
updateSettingState('lockScreenSwitch', false)
|
||||
let validating = false
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 校验成功后先保存密码,再启用锁屏;重复触发与字段校验失败不会写入状态。
|
||||
*/
|
||||
const lockScreen = async () => {
|
||||
if (validating) return
|
||||
|
||||
validating = true
|
||||
|
||||
try {
|
||||
try {
|
||||
await validate()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
setStorage(
|
||||
APP_CATCH_KEY.appLockScreenPasswordKey,
|
||||
encrypt(state.lockCondition.lockPassword),
|
||||
'localStorage',
|
||||
)
|
||||
|
||||
setLockAppScreen(true)
|
||||
updateSettingState('lockScreenSwitch', false)
|
||||
state.lockCondition = useCondition()
|
||||
})
|
||||
} finally {
|
||||
validating = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
@ -47,6 +70,8 @@ const LockScreen = defineComponent({
|
||||
lockScreen,
|
||||
register,
|
||||
inputInstRef,
|
||||
rules,
|
||||
t,
|
||||
}
|
||||
},
|
||||
render() {
|
||||
@ -63,7 +88,7 @@ const LockScreen = defineComponent({
|
||||
<RForm
|
||||
ref="formInstRef"
|
||||
model={this.lockCondition}
|
||||
rules={rules}
|
||||
rules={this.rules}
|
||||
labelPlacement="left"
|
||||
onRegister={register}
|
||||
>
|
||||
@ -72,21 +97,21 @@ const LockScreen = defineComponent({
|
||||
ref="inputInstRef"
|
||||
v-model:value={this.lockCondition.lockPassword}
|
||||
type="password"
|
||||
placeholder="请输入锁屏密码"
|
||||
placeholder={this.t('lockPlaceholder')}
|
||||
clearable
|
||||
showPasswordOn="click"
|
||||
minlength={6}
|
||||
maxlength={12}
|
||||
onKeydown={(e: KeyboardEvent) => {
|
||||
if (e.code === 'Enter') {
|
||||
this.lockScreen()
|
||||
if (e.key === 'Enter' && !e.isComposing && !e.repeat) {
|
||||
return this.lockScreen()
|
||||
}
|
||||
}}
|
||||
autofocus
|
||||
/>
|
||||
</NFormItem>
|
||||
<NButton type="primary" onClick={this.lockScreen.bind(this)}>
|
||||
锁屏
|
||||
<NButton type="primary" onClick={this.lockScreen}>
|
||||
{this.t('lock')}
|
||||
</NButton>
|
||||
</RForm>
|
||||
</div>
|
||||
|
||||
@ -1,65 +1,107 @@
|
||||
import '../../index.scss'
|
||||
import AppAvatar from '@/app-components/app/AppAvatar'
|
||||
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
|
||||
import { rules, useCondition } from '@/app-components/app/AppLockScreen/shared'
|
||||
import {
|
||||
useCondition,
|
||||
useLockRules,
|
||||
} from '@/app-components/app/AppLockScreen/shared'
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { RForm, useForm } from '@/components'
|
||||
import { useDevice } from '@/hooks'
|
||||
import { useSettingActions, useSigningActions } from '@/store'
|
||||
import { useDevice, useI18n } from '@/hooks'
|
||||
import {
|
||||
useSettingActions,
|
||||
useSettingGetters,
|
||||
useSigningActions,
|
||||
} from '@/store'
|
||||
import { decrypt, getStorage, removeStorage } from '@/utils'
|
||||
import { useEventListener } from '@vueuse/core'
|
||||
import dayjs from 'dayjs'
|
||||
import { NButton, NFlex, NFormItem, NInput } from 'naive-ui'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'UnlockScreen',
|
||||
setup() {
|
||||
const { t } = useI18n('appComponents.lockScreen')
|
||||
const rules = useLockRules()
|
||||
const [register, { validate }] = useForm()
|
||||
|
||||
const { logout } = useSigningActions()
|
||||
const { updateSettingState } = useSettingActions()
|
||||
const { setLockAppScreen } = useAppLockScreen()
|
||||
const { isTabletOrSmaller } = useDevice()
|
||||
const { getLocaleLanguage } = useSettingGetters()
|
||||
const now = shallowRef(dayjs())
|
||||
const clock = computed(() => {
|
||||
const date = now.value.locale(
|
||||
getLocaleLanguage.value === 'zh-CN' ? 'zh-cn' : 'en',
|
||||
)
|
||||
|
||||
const HH_MM_FORMAT = 'HH:mm'
|
||||
const AM_PM_FORMAT = 'A'
|
||||
const YY_MM_DD_FORMAT = 'YYYY-MM-DD'
|
||||
const DDD_FORMAT = 'ddd'
|
||||
return {
|
||||
HH_MM: date.format('HH:mm'),
|
||||
AM_PM: date.format('A'),
|
||||
YY_MM_DD: date.format('YYYY-MM-DD'),
|
||||
DDD: date.format('ddd'),
|
||||
}
|
||||
})
|
||||
|
||||
const state = reactive({
|
||||
lockCondition: useCondition(),
|
||||
HH_MM: dayjs().format(HH_MM_FORMAT),
|
||||
AM_PM: dayjs().format(AM_PM_FORMAT),
|
||||
YY_MM_DD: dayjs().format(YY_MM_DD_FORMAT),
|
||||
DDD: dayjs().format(DDD_FORMAT),
|
||||
})
|
||||
const dayInterval = setInterval(() => {
|
||||
state.HH_MM = dayjs().format(HH_MM_FORMAT)
|
||||
state.AM_PM = dayjs().format(AM_PM_FORMAT)
|
||||
}, 6_000)
|
||||
const yearInterval = setInterval(() => {
|
||||
state.YY_MM_DD = dayjs().format(YY_MM_DD_FORMAT)
|
||||
state.DDD = dayjs().format(DDD_FORMAT)
|
||||
}, 86_400_000)
|
||||
let clockTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const toSigningFn = () => {
|
||||
removeStorage(APP_CATCH_KEY.appLockScreenPasswordKey, 'localStorage')
|
||||
updateSettingState('lockScreenSwitch', false)
|
||||
setTimeout(() => {
|
||||
logout()
|
||||
}, 100)
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 按分钟边界更新全部时间字段;页面隐藏时暂停,恢复可见时立即校准,避免跨日日期滞后。
|
||||
*/
|
||||
const updateClock = () => {
|
||||
clearTimeout(clockTimer)
|
||||
|
||||
if (document.hidden) return
|
||||
|
||||
now.value = dayjs()
|
||||
clockTimer = setTimeout(updateClock, 60_000 - (Date.now() % 60_000))
|
||||
}
|
||||
|
||||
onMounted(updateClock)
|
||||
useEventListener(document, 'visibilitychange', updateClock)
|
||||
onBeforeUnmount(() => clearTimeout(clockTimer))
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 清理锁屏密码并执行统一退出流程,不创建脱离组件生命周期的延迟计时器。
|
||||
*/
|
||||
const toSigningFn = async () => {
|
||||
removeStorage(APP_CATCH_KEY.appLockScreenPasswordKey, 'localStorage')
|
||||
updateSettingState('lockScreenSwitch', false)
|
||||
await logout()
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 显示重新登录确认框,由确认回调执行退出。
|
||||
*/
|
||||
const backToSigning = () => {
|
||||
window.$dialog.warning({
|
||||
title: '警告',
|
||||
content: '是否返回到登陆页并且重新登录',
|
||||
positiveText: '确定',
|
||||
negativeText: '重新登录',
|
||||
title: t('warning'),
|
||||
content: t('returnPrompt'),
|
||||
positiveText: t('confirm'),
|
||||
negativeText: t('cancel'),
|
||||
onPositiveClick: toSigningFn,
|
||||
})
|
||||
}
|
||||
|
||||
const unlockScreen = () => {
|
||||
let validating = false
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 校验输入并比较当前缓存密码,成功后解除锁屏;失败保持锁定并显示对应提示。
|
||||
*/
|
||||
const unlockScreen = async () => {
|
||||
if (validating) return
|
||||
|
||||
const catchPassword = getStorage<string>(
|
||||
APP_CATCH_KEY.appLockScreenPasswordKey,
|
||||
'localStorage',
|
||||
@ -67,12 +109,12 @@ export default defineComponent({
|
||||
|
||||
if (!catchPassword) {
|
||||
window.$dialog.warning({
|
||||
title: '警告',
|
||||
content: () => '检测到锁屏密码被修改,请重新登录',
|
||||
title: t('warning'),
|
||||
content: () => t('passwordChanged'),
|
||||
closable: false,
|
||||
maskClosable: false,
|
||||
closeOnEsc: false,
|
||||
positiveText: '重新登录',
|
||||
positiveText: t('signIn'),
|
||||
onPositiveClick: toSigningFn,
|
||||
})
|
||||
|
||||
@ -81,7 +123,15 @@ export default defineComponent({
|
||||
|
||||
const dCatchPassword = decrypt(catchPassword)
|
||||
|
||||
validate().then(() => {
|
||||
validating = true
|
||||
|
||||
try {
|
||||
try {
|
||||
await validate()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
if (dCatchPassword === state.lockCondition.lockPassword) {
|
||||
setLockAppScreen(false)
|
||||
updateSettingState('lockScreenSwitch', false)
|
||||
@ -89,27 +139,27 @@ export default defineComponent({
|
||||
|
||||
state.lockCondition = useCondition()
|
||||
} else {
|
||||
window.$message.warning('密码错误,请重新输入')
|
||||
window.$message.warning(t('wrongPassword'))
|
||||
}
|
||||
})
|
||||
} finally {
|
||||
validating = false
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
clearInterval(dayInterval)
|
||||
clearInterval(yearInterval)
|
||||
})
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
backToSigning,
|
||||
unlockScreen,
|
||||
isTabletOrSmaller,
|
||||
register,
|
||||
rules,
|
||||
clock,
|
||||
t,
|
||||
}
|
||||
},
|
||||
render() {
|
||||
const { isTabletOrSmaller } = this
|
||||
const { HH_MM, AM_PM, YY_MM_DD, DDD } = this
|
||||
const { HH_MM, AM_PM, YY_MM_DD, DDD } = this.clock
|
||||
const hmSplit = HH_MM.split(':')
|
||||
const { unlockScreen, backToSigning, register } = this
|
||||
|
||||
@ -142,37 +192,29 @@ export default defineComponent({
|
||||
<RForm
|
||||
onRegister={register}
|
||||
model={this.lockCondition}
|
||||
rules={rules}
|
||||
rules={this.rules}
|
||||
>
|
||||
<NFormItem path="lockPassword">
|
||||
<NInput
|
||||
autofocus
|
||||
v-model:value={this.lockCondition.lockPassword}
|
||||
type="password"
|
||||
placeholder="请输入解锁密码"
|
||||
placeholder={this.t('unlockPlaceholder')}
|
||||
clearable
|
||||
minlength={6}
|
||||
onKeydown={(e: KeyboardEvent) => {
|
||||
if (e.code === 'Enter') {
|
||||
unlockScreen()
|
||||
if (e.key === 'Enter' && !e.isComposing && !e.repeat) {
|
||||
return unlockScreen()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</NFormItem>
|
||||
<NFlex justify="space-between">
|
||||
<NButton
|
||||
type="primary"
|
||||
text
|
||||
onClick={backToSigning.bind(this)}
|
||||
>
|
||||
返回登陆
|
||||
<NButton type="primary" text onClick={backToSigning}>
|
||||
{this.t('backToSignIn')}
|
||||
</NButton>
|
||||
<NButton
|
||||
type="primary"
|
||||
text
|
||||
onClick={unlockScreen.bind(this)}
|
||||
>
|
||||
进入系统
|
||||
<NButton type="primary" text onClick={unlockScreen}>
|
||||
{this.t('unlock')}
|
||||
</NButton>
|
||||
</NFlex>
|
||||
</RForm>
|
||||
|
||||
@ -1,10 +1,12 @@
|
||||
import { RModal } from '@/components'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { useSettingActions, useSettingGetters } from '@/store'
|
||||
import LockScreen from './components/LockScreen'
|
||||
|
||||
const AppLockScreen = defineComponent({
|
||||
name: 'AppLockScreen',
|
||||
setup() {
|
||||
const { t } = useI18n('appComponents.lockScreen')
|
||||
const { updateSettingState } = useSettingActions()
|
||||
const { getLockScreenSwitch } = useSettingGetters()
|
||||
const lockScreenSwitchRef = computed({
|
||||
@ -16,6 +18,7 @@ const AppLockScreen = defineComponent({
|
||||
|
||||
return {
|
||||
lockScreenSwitchRef,
|
||||
t,
|
||||
}
|
||||
},
|
||||
render() {
|
||||
@ -23,12 +26,11 @@ const AppLockScreen = defineComponent({
|
||||
<RModal
|
||||
v-model:show={this.lockScreenSwitchRef}
|
||||
transformOrigin="center"
|
||||
show
|
||||
autoFocus={false}
|
||||
maskClosable={false}
|
||||
closeOnEsc={false}
|
||||
preset="dialog"
|
||||
title="锁定屏幕"
|
||||
title={this.t('title')}
|
||||
>
|
||||
<LockScreen />
|
||||
</RModal>
|
||||
|
||||
@ -1,20 +1,36 @@
|
||||
import type { InputInst } from 'naive-ui'
|
||||
import type { Ref } from 'vue'
|
||||
import { useI18n } from '@/hooks'
|
||||
import type { FormRules } from 'naive-ui'
|
||||
|
||||
/** 统一的校验锁屏密码校验规则 */
|
||||
export const rules = {
|
||||
lockPassword: {
|
||||
required: true,
|
||||
message: '请输入正确格式密码',
|
||||
min: 6,
|
||||
max: 12,
|
||||
trigger: ['input'],
|
||||
},
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 创建锁屏密码规则,错误文案随当前语言更新。
|
||||
*
|
||||
* @returns 密码长度为 6 至 12 位的校验规则
|
||||
*/
|
||||
export const useLockRules = () => {
|
||||
const { t } = useI18n('appComponents.lockScreen')
|
||||
|
||||
return computed<FormRules>(() => ({
|
||||
lockPassword: {
|
||||
required: true,
|
||||
message: t('passwordRule'),
|
||||
min: 6,
|
||||
max: 12,
|
||||
trigger: ['input'],
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
/** 锁屏密码参数 */
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 创建独立的密码输入模型,锁定或解锁完成后用于清空输入。
|
||||
*
|
||||
* @returns 空密码模型
|
||||
*/
|
||||
export const useCondition = () => {
|
||||
return {
|
||||
lockPassword: null,
|
||||
lockPassword: null as string | null,
|
||||
}
|
||||
}
|
||||
|
||||
@ -13,7 +13,7 @@
|
||||
min-width: 0;
|
||||
padding: 13px 16px;
|
||||
border: 1px solid var(--r-line);
|
||||
border-radius: 8px;
|
||||
border-radius: var(--r-control-radius);
|
||||
color: var(--r-text-secondary);
|
||||
text-decoration: none;
|
||||
font-size: 13px;
|
||||
|
||||
@ -67,7 +67,7 @@ export default defineComponent({
|
||||
>
|
||||
<NAvatar round src={item.icon} size={24} />
|
||||
<span>{this.t(item.tooltip)}</span>
|
||||
<RIcon name="action/shared" size={13} />
|
||||
<RIcon name="action/external-link" size={13} />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@ -1,6 +1,15 @@
|
||||
const controls =
|
||||
'input:not([type="hidden"],[type="checkbox"],[type="radio"],[type="button"],[type="submit"],[type="file"],[type="reset"]), textarea, select'
|
||||
|
||||
/**
|
||||
*
|
||||
* @param root 需要补齐自动完成默认值的 DOM 根节点
|
||||
*
|
||||
* @description
|
||||
* 首次扫描根节点,随后仅扫描新增子树;尊重控件显式配置和表单的 autocomplete="on"。
|
||||
*
|
||||
* @returns 停止 MutationObserver 的清理函数,由调用方在卸载时调用
|
||||
*/
|
||||
export function installAutocompleteDefaults(root: HTMLElement) {
|
||||
const apply = (element: Element) => {
|
||||
if (element.hasAttribute('autocomplete')) return
|
||||
|
||||
@ -1,11 +1,13 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { RModal } from '@/components'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { useSigningActions } from '@/store'
|
||||
import { getStorage, setStorage } from '@/utils'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'AppVersionProvider',
|
||||
setup() {
|
||||
const { t } = useI18n('appComponents.version')
|
||||
const {
|
||||
pkg: { version },
|
||||
} = __APP_CFG__
|
||||
@ -30,6 +32,7 @@ export default defineComponent({
|
||||
return {
|
||||
modalShow,
|
||||
logout,
|
||||
t,
|
||||
}
|
||||
},
|
||||
render() {
|
||||
@ -43,12 +46,12 @@ export default defineComponent({
|
||||
maskClosable={false}
|
||||
preset="dialog"
|
||||
closable={false}
|
||||
title="发现新版本"
|
||||
content="当前版本已更新,点击确认加载新版本~"
|
||||
title={this.t('title')}
|
||||
content={this.t('description')}
|
||||
zIndex={999999999}
|
||||
draggable
|
||||
positiveText="确认"
|
||||
negativeText="取消"
|
||||
positiveText={this.t('confirm')}
|
||||
negativeText={this.t('cancel')}
|
||||
onPositiveClick={logout}
|
||||
onNegativeClick={() => {
|
||||
this.modalShow = false
|
||||
|
||||
@ -12,4 +12,6 @@ Organize reusable components by name under `src/components`. Import components a
|
||||
|
||||
Component styles load with their entry points. Scope changes to Naive UI internals using the current component's class. When a component must fill its container, declare dimensions at the call site or within the component. Fullscreen `RModal` card content scrolls only on overflow; `RBarcode` loading regions follow barcode dimensions or responsive containers.
|
||||
|
||||
Custom styles follow the [CSS token, scope, and responsive-sizing contract](../../../../docs/ui-design.md#custom-css). Admin components inherit the existing providers; standalone shared-package consumers use the [public host example](../../../../apps/docs/examples/ThemeScopeExample.vue) instead of importing application stores or writing global theme variables.
|
||||
|
||||
Examples are in `src/views/demo`. Independent hook interactions and lifecycle conventions are in the [hook guide](../hooks/README.md). Follow the [comment style](../../../../docs/comment-style.md) when adding/editing comments; put complete tutorials in READMEs and demo pages.
|
||||
|
||||
21
apps/admin/src/doctor/README.md
Normal file
21
apps/admin/src/doctor/README.md
Normal file
@ -0,0 +1,21 @@
|
||||
# Application doctor
|
||||
|
||||
This small application-owned module reports development configuration mistakes. It does not initialize the application, enforce routing policy, or own a workspace package.
|
||||
|
||||
`main.ts` calls `runAppDoctor()` only under `__DEV__`, after a successful mount and removal of the startup splash. Both standalone and Wujie mounts use the same call. Configuration findings and unexpected diagnostic failures are reported as doctor warnings; they do not reject bootstrap or trigger the startup-failure UI. Each mount may inspect the current configuration; the doctor holds no timers, listeners, or cross-mount state.
|
||||
|
||||
## Retained check
|
||||
|
||||
Locale configuration still needs a consistency check: TypeScript constrains permitted locale strings, but an array can omit or duplicate an option, and separately maintained language/Day.js maps can disagree. `getLocaleConfigIssues` inspects a supplied snapshot without mutation or logging. It checks:
|
||||
|
||||
- Unique language options and membership of the application default/fallback locales.
|
||||
- Matching language-option and Day.js mapping keys in both directions.
|
||||
- Membership of the default Day.js locale in the mapping values.
|
||||
|
||||
The check does not prove that translation resources or Day.js locale modules have been loaded. Resource imports and operational startup failures remain owned by their existing setup functions. It does not inspect user data, persistent preferences, network connectivity, or routes.
|
||||
|
||||
The historical `__ray-template` / `setupRayTemplateCore` entry was internal to `main.ts`, with no package export or other caller. It was removed rather than kept as a misleading initialization alias. Its root-path requirement had already been removed; no business home route is required.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused regression tests live in `__test__/app/doctor.spec.ts`; the existing `layout` and `ui` Harness scopes include them. This module is separate from the repository's Node/pnpm environment doctor at `scripts/doctor.mjs` (`pnpm env:check`).
|
||||
33
apps/admin/src/doctor/index.ts
Normal file
33
apps/admin/src/doctor/index.ts
Normal file
@ -0,0 +1,33 @@
|
||||
import {
|
||||
DAYJS_LOCAL_MAP,
|
||||
DEFAULT_DAYJS_LOCAL,
|
||||
LOCAL_OPTIONS,
|
||||
SYSTEM_DEFAULT_LOCAL,
|
||||
SYSTEM_FALLBACK_LOCALE,
|
||||
} from '../app-config/local-config'
|
||||
import { getLocaleConfigIssues } from './locale-config'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 在开发环境的应用挂载完成后报告语言配置问题;调用入口负责 __DEV__ 判断。
|
||||
* 诊断与启动失败分开处理,不抛出配置错误,也不持有异步任务或跨挂载状态。
|
||||
*/
|
||||
export const runAppDoctor = () => {
|
||||
try {
|
||||
const issues = getLocaleConfigIssues({
|
||||
options: LOCAL_OPTIONS,
|
||||
defaultLocale: SYSTEM_DEFAULT_LOCAL,
|
||||
fallbackLocale: SYSTEM_FALLBACK_LOCALE,
|
||||
dayjsLocales: DAYJS_LOCAL_MAP,
|
||||
defaultDayjsLocale: DEFAULT_DAYJS_LOCAL,
|
||||
})
|
||||
|
||||
for (const issue of issues) console.warn(`[Ray Admin doctor] ${issue}`)
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
'[Ray Admin doctor] Locale diagnostics could not complete.',
|
||||
error,
|
||||
)
|
||||
}
|
||||
}
|
||||
63
apps/admin/src/doctor/locale-config.ts
Normal file
63
apps/admin/src/doctor/locale-config.ts
Normal file
@ -0,0 +1,63 @@
|
||||
export interface LocaleConfiguration {
|
||||
options: readonly { key: string }[]
|
||||
defaultLocale: string
|
||||
fallbackLocale: string
|
||||
dayjsLocales: Readonly<Record<string, string>>
|
||||
defaultDayjsLocale: string
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param config 语言选项、默认语言与 Day.js 映射的配置快照
|
||||
*
|
||||
* @description
|
||||
* 检查独立配置项之间的对应关系,不修改配置、不加载语言包,也不写入控制台。
|
||||
*
|
||||
* @returns 去重后的配置问题;配置一致时为空数组。
|
||||
*/
|
||||
export const getLocaleConfigIssues = (
|
||||
config: LocaleConfiguration,
|
||||
): string[] => {
|
||||
const issues = new Set<string>()
|
||||
const locales = new Set<string>()
|
||||
|
||||
for (const { key } of config.options) {
|
||||
if (locales.has(key))
|
||||
issues.add(`LOCAL_OPTIONS contains duplicate locale "${key}".`)
|
||||
|
||||
locales.add(key)
|
||||
}
|
||||
|
||||
for (const [name, locale] of [
|
||||
['SYSTEM_DEFAULT_LOCAL', config.defaultLocale],
|
||||
['SYSTEM_FALLBACK_LOCALE', config.fallbackLocale],
|
||||
]) {
|
||||
if (!locales.has(locale))
|
||||
issues.add(`${name} "${locale}" is missing from LOCAL_OPTIONS.`)
|
||||
}
|
||||
|
||||
for (const locale of locales) {
|
||||
if (!Object.hasOwn(config.dayjsLocales, locale))
|
||||
issues.add(
|
||||
`DAYJS_LOCAL_MAP is missing locale "${locale}" from LOCAL_OPTIONS.`,
|
||||
)
|
||||
}
|
||||
|
||||
const dayjsLocales = new Set<string>()
|
||||
|
||||
for (const [locale, dayjsLocale] of Object.entries(config.dayjsLocales)) {
|
||||
if (!locales.has(locale))
|
||||
issues.add(
|
||||
`DAYJS_LOCAL_MAP locale "${locale}" is missing from LOCAL_OPTIONS.`,
|
||||
)
|
||||
|
||||
dayjsLocales.add(dayjsLocale)
|
||||
}
|
||||
|
||||
if (!dayjsLocales.has(config.defaultDayjsLocale))
|
||||
issues.add(
|
||||
`DEFAULT_DAYJS_LOCAL "${config.defaultDayjsLocale}" is missing from DAYJS_LOCAL_MAP values.`,
|
||||
)
|
||||
|
||||
return [...issues]
|
||||
}
|
||||
@ -14,6 +14,7 @@ import {
|
||||
getStaticAppRoutes,
|
||||
setAppRouteModules,
|
||||
} from '@/router/app-route-modules'
|
||||
import { getSystemRoutes } from '@/router/routes'
|
||||
import type { AppRouteRecordRaw } from '@/router/types'
|
||||
import { expandRoutes } from '@/router/utils/expand-routes'
|
||||
import { joinRoutePath } from '@/router/utils/join-route-path'
|
||||
@ -103,6 +104,7 @@ const DocumentationExample = defineComponent({
|
||||
`${iconSprites[name.split('/')[0] as IconPackage]}#${prefix}-${name}`,
|
||||
columnStorage: createStorage(window.sessionStorage, 'ray-doc-examples'),
|
||||
reportError: (message) => window.$message?.error(message),
|
||||
reportSuccess: (message) => window.$message?.success(message),
|
||||
})
|
||||
|
||||
return () => (
|
||||
@ -143,7 +145,10 @@ async function mountExample() {
|
||||
router.removeRoute('RLayout')
|
||||
setAppRouteModules(examples)
|
||||
|
||||
const routes = expandRoutes(examples) as unknown as RouteRecordRaw[]
|
||||
const routes = [
|
||||
...expandRoutes(examples),
|
||||
...getSystemRoutes(),
|
||||
] as unknown as RouteRecordRaw[]
|
||||
|
||||
if (withLayout) {
|
||||
router.addRoute({ path: '/', component: Layout, children: routes })
|
||||
@ -151,7 +156,6 @@ async function mountExample() {
|
||||
for (const route of routes) router.addRoute(route)
|
||||
}
|
||||
|
||||
router.addRoute({ path: '/:pathMatch(.*)*', redirect: '/dashboard' })
|
||||
app.use(router)
|
||||
await router.isReady()
|
||||
|
||||
|
||||
@ -10,7 +10,6 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
|
||||
| template | `useBadge` | `/template-hooks`: menu badge text, icons, and visibility | [useBadge](../../../../__test__/hooks/useBadge.spec.ts) |
|
||||
| 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 | `useAppRoot` | `/template-hooks`: read home, use the current page, restore dashboard | [useAppRoot](../../../../__test__/hooks/useAppRoot.spec.ts) |
|
||||
| template | `useSiderBar` | `/template-hooks`: close tabs by path or close left/right/other/all tabs | [useSiderBar](../../../../__test__/hooks/useSiderBar.spec.ts) |
|
||||
| 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) |
|
||||
@ -26,6 +25,8 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
|
||||
|
||||
## Lifecycle and state
|
||||
|
||||
- `useAppRoot` is a deprecated compatibility accessor for stored preferences. It has no landing, tab protection, permission, or startup-validation effect and is no longer an interactive demo. Explicit navigation uses Router; closing the final/all business tabs opens the neutral `/welcome` workspace.
|
||||
|
||||
- Create composables in `setup` or an active effect scope. Trigger DOM operations from user events or post-mount callbacks. Clean up events, subscriptions, and animation frames with the scope.
|
||||
- Pinia `runtime` owns global UI state, accessed through `useRuntimeGetters` / `useRuntimeActions`. It is not persisted.
|
||||
- `useSpinning().reload(wait)` unmounts the page. The runtime store owns the restoration timer; the latest refresh wins across repeated calls.
|
||||
@ -36,7 +37,9 @@ Shared hooks are exported through `@/hooks`. Internal callers should import by r
|
||||
- `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.
|
||||
- `usePagination` resets to the value of the first pageSizes option and supports Naive UI object options. Calling `setCallback()` removes the default callback.
|
||||
- `usePagination` resets to the first option in the current `pagination.value.pageSizes` and supports Naive UI object options. Default option arrays are isolated between instances. Calling `setCallback()` removes the default callback.
|
||||
- `useDomToImage` loads the rendering library on the first `create` call; import failures use the same error and cleanup callbacks as renderer failures.
|
||||
- A disposed `useElementFullscreen` instance cannot enter again; create a fresh instance in a live scope when a target is remounted.
|
||||
- `usePrint` unwraps its target when called. DOM targets print as HTML by default. Blob images and binary PDFs are converted first; callers can await the returned Promise.
|
||||
|
||||
Screenshots and printing depend on real browsers. Happy DOM tests verify state and error handling; they do not replace native print-dialog or physical-output acceptance.
|
||||
|
||||
@ -1,16 +1,34 @@
|
||||
import { useSigningGetters } from '@/store'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 读取当前会话的权限;集合随权限列表更新,并复用于同一实例的多次判断。
|
||||
*
|
||||
* @returns 只读权限列表及权限匹配方法;界面检查不能替代服务端授权。
|
||||
*/
|
||||
export function useAccess() {
|
||||
const { getPermissions } = useSigningGetters()
|
||||
const permissionSet = computed(() => new Set(getPermissions.value))
|
||||
|
||||
/**
|
||||
*
|
||||
* @param codes 单个权限码或权限码列表
|
||||
* @param mode all 要求全部匹配,any 要求至少匹配一个
|
||||
*
|
||||
* @returns 是否满足要求;空列表在 all 模式下为 true,在 any 模式下为 false。
|
||||
*/
|
||||
const hasPermission = (
|
||||
codes: string | readonly string[],
|
||||
mode: 'all' | 'any' = 'all',
|
||||
) => {
|
||||
const required = typeof codes === 'string' ? [codes] : codes
|
||||
const permissions = permissionSet.value
|
||||
|
||||
if (typeof codes === 'string') return permissions.has(codes)
|
||||
|
||||
return mode === 'all'
|
||||
? required.every((code) => getPermissions.value.includes(code))
|
||||
: required.some((code) => getPermissions.value.includes(code))
|
||||
? codes.every((code) => permissions.has(code))
|
||||
: codes.some((code) => permissions.has(code))
|
||||
}
|
||||
|
||||
return { hasPermission, permissions: getPermissions }
|
||||
|
||||
@ -1,6 +1,14 @@
|
||||
import { useSettingActions, useSettingGetters } from '@/store'
|
||||
import type { AppRootRoute } from '@/store/modules/setting/types'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 只读写历史偏好字段,不影响登录落点、标签关闭、菜单激活或路由权限。
|
||||
*
|
||||
* @returns 历史首页偏好的响应式引用和合并更新方法。
|
||||
* @deprecated 仅兼容旧设置;使用 Router 显式导航,空工作区统一为 /welcome。
|
||||
*/
|
||||
export function useAppRoot() {
|
||||
const { getAppRootRoute } = useSettingGetters()
|
||||
const { updateSettingState } = useSettingActions()
|
||||
@ -14,7 +22,7 @@ export function useAppRoot() {
|
||||
* @param route 根路由配置内容
|
||||
*
|
||||
* @description
|
||||
* 设置根路由。
|
||||
* 合并历史首页偏好,不触发导航,也不改变空工作区或标签保护规则。
|
||||
*/
|
||||
const setRootRoute = (route: Partial<AppRootRoute>) => {
|
||||
updateSettingState(
|
||||
|
||||
@ -5,6 +5,14 @@ import type { AppMenuOption } from '@/types'
|
||||
|
||||
export type BadgeKey = string | AppMenuOption
|
||||
|
||||
/**
|
||||
*
|
||||
* @param target 菜单路径或菜单项
|
||||
* @param extra 合并到当前菜单的标记配置
|
||||
*
|
||||
* @description
|
||||
* 通过已加载的菜单树定位真实对象,并重建其标记渲染入口,避免只更新传入的副本。
|
||||
*/
|
||||
const updateBadge = (target: BadgeKey, extra: AppMenuExtraOptions) => {
|
||||
const { getMenuOptions } = useMenuGetters()
|
||||
const key = typeof target === 'string' ? target : target?.fullPath
|
||||
@ -23,6 +31,10 @@ const updateBadge = (target: BadgeKey, extra: AppMenuExtraOptions) => {
|
||||
option.extra = createMenuExtra(option)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 按菜单路径查找并修改共享标记的方法;未加载的菜单不会被创建。
|
||||
*/
|
||||
export function useBadge() {
|
||||
/**
|
||||
*
|
||||
|
||||
@ -6,7 +6,14 @@ import type { LayoutInst } from 'naive-ui'
|
||||
* @returns 内容区 scrollTo;调用时读取当前布局实例,未挂载时不操作。
|
||||
*/
|
||||
export const useContentScroll = () => {
|
||||
// 在事件触发时读取当前实例,支持 setup 中调用和布局重新挂载。
|
||||
/**
|
||||
*
|
||||
* @param options 横向坐标或 Naive UI 滚动选项
|
||||
* @param y 数字坐标模式下的纵向坐标,默认 0
|
||||
*
|
||||
* @description
|
||||
* 事件触发时再读取内容区实例,支持 setup 中创建和布局重新挂载。
|
||||
*/
|
||||
const scrollTo: LayoutInst['scrollTo'] = (
|
||||
options: number | object,
|
||||
y?: number,
|
||||
|
||||
@ -30,6 +30,13 @@ const getI18nKey = (namespace: string | undefined, key: string) => {
|
||||
* @returns 始终可用的翻译、语言设置方法,以及初始化后的原生能力。
|
||||
*/
|
||||
export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
|
||||
/**
|
||||
*
|
||||
* @param key 命名空间内的键、完整翻译键或无命名空间的普通文本
|
||||
* @param args 原样转交 vue-i18n 的插值和翻译选项
|
||||
*
|
||||
* @returns 翻译结果;空键返回空字符串,实例尚未创建时返回解析后的键。
|
||||
*/
|
||||
const translate = <T extends string = string>(
|
||||
key: string,
|
||||
...args: unknown[]
|
||||
@ -51,6 +58,13 @@ export const useI18n = (namespace?: string): OverrideUseI18nReturnType => {
|
||||
return nativeTranslate(fullKey, ...args) as T
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param lang 要写入国际化实例与 html lang 属性的语言标识
|
||||
*
|
||||
* @description
|
||||
* 实例尚未创建时不操作;应用界面切换应使用 Setting Store,以同步日期和组件库。
|
||||
*/
|
||||
const locale = (lang: string) => {
|
||||
const instance = i18n
|
||||
|
||||
|
||||
@ -26,7 +26,16 @@ export const useMaximize = (defaults?: MaximizeOptions) => {
|
||||
useRuntimeGetters()
|
||||
const { setRuntimeState } = useRuntimeActions()
|
||||
|
||||
// 最大化由布局 class 驱动;不同页面、标签菜单与退出按钮共享同一状态。
|
||||
/**
|
||||
*
|
||||
* @param full 是否最大化内容区
|
||||
* @param options 覆盖默认回调、样式与滚动位置
|
||||
*
|
||||
* @description
|
||||
* 最大化由布局 class 驱动;不同调用方共享状态,仅最新一次切换执行完成回调。
|
||||
*
|
||||
* @throws 前置回调抛错时中止切换;完成回调由 Vue nextTick 调度。
|
||||
*/
|
||||
const maximize = (full: boolean, options?: MaximizeOptions) => {
|
||||
if (layoutContentMaximize.value === full) return
|
||||
|
||||
@ -62,6 +71,11 @@ export const useMaximize = (defaults?: MaximizeOptions) => {
|
||||
isLayoutContentMaximized: layoutContentMaximize,
|
||||
isFullscreen: layoutContentMaximize,
|
||||
maximize,
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 使用初始化时的默认配置切换共享最大化状态。
|
||||
*/
|
||||
toggleFullscreen: () => maximize(!layoutContentMaximize.value),
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,10 +1,6 @@
|
||||
import { NOT_FOUND_ROUTE_PATH } from '@/router/constant'
|
||||
import { validRole } from '@/router/utils/valid-role'
|
||||
import { WELCOME_ROUTE_PATH } from '@/router/constant'
|
||||
import { useMenuActions, useMenuGetters } from '@/store'
|
||||
import { pickRouteRecordNormalizedConstant } from '@/store/modules/menu/constant'
|
||||
import type { AppMenuOption, Key, MenuTagOptions } from '@/types'
|
||||
import { pick } from 'lodash-es'
|
||||
import { useAppRoot } from './useAppRoot'
|
||||
import type { Key, MenuTagOptions } from '@/types'
|
||||
import { useVueRouter } from './useVueRouter'
|
||||
|
||||
export type CloseMenuTag = Key | MenuTagOptions
|
||||
@ -38,23 +34,32 @@ const normalMenuTagOption = (target: CloseMenuTag, fn: string) => {
|
||||
return { option: tags[index], index }
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 标签页检查与关闭方法;状态由共享菜单 Store 持有。
|
||||
*/
|
||||
export function useSiderBar() {
|
||||
const { getMenuTagOptions, getMenuKey } = useMenuGetters()
|
||||
const {
|
||||
changeMenuModelValue,
|
||||
spliceMenTagOptions,
|
||||
setMenuTagOptions,
|
||||
resolveOption,
|
||||
} = useMenuActions()
|
||||
const { getMenuTagOptions, getCurrentMenuOption } = useMenuGetters()
|
||||
const { router } = useVueRouter()
|
||||
const { changeMenuModelValue, spliceMenTagOptions, setMenuTagOptions } =
|
||||
useMenuActions()
|
||||
|
||||
// 获取当前激活标签页索引位置
|
||||
/**
|
||||
*
|
||||
* @returns 当前激活标签的索引;未找到时为 -1。
|
||||
*/
|
||||
const getCurrentTagIndex = () => {
|
||||
return getMenuTagOptions.value.findIndex(
|
||||
(curr) => curr.fullPath === getMenuKey.value,
|
||||
(curr) => curr.fullPath === getCurrentMenuOption.value?.fullPath,
|
||||
)
|
||||
}
|
||||
|
||||
// 校验指定标签右侧是否有可关闭的标签
|
||||
/**
|
||||
*
|
||||
* @param target 标签对象、索引或路径
|
||||
*
|
||||
* @returns 目标右侧是否还有标签;目标无效时返回 false。
|
||||
*/
|
||||
const checkCloseRight = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'checkCloseRight')
|
||||
|
||||
@ -68,63 +73,67 @@ export function useSiderBar() {
|
||||
return false
|
||||
}
|
||||
|
||||
// 校验指定标签左侧是否有可关闭的标签
|
||||
/**
|
||||
*
|
||||
* @param target 标签对象、索引或路径
|
||||
*
|
||||
* @returns 目标左侧是否还有标签;目标无效时返回 false。
|
||||
*/
|
||||
const checkCloseLeft = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'checkCloseLeft')
|
||||
|
||||
return !!normal && normal.index > 0
|
||||
}
|
||||
|
||||
// 关闭当前标签
|
||||
/**
|
||||
*
|
||||
* @param target 要关闭的标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 所有业务标签都可关闭;关闭最后一项进入空工作区,其余激活项切换到相邻标签。
|
||||
*
|
||||
* @returns 需要跳转时返回 Router 导航结果。
|
||||
*/
|
||||
const close = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'close')
|
||||
|
||||
if (getMenuTagOptions.value.length === 1) {
|
||||
return
|
||||
}
|
||||
|
||||
if (normal) {
|
||||
const { index, option } = normal
|
||||
const active = option.fullPath === getCurrentMenuOption.value?.fullPath
|
||||
|
||||
spliceMenTagOptions(index)
|
||||
|
||||
if (option.fullPath === getMenuKey.value) {
|
||||
if (!getMenuTagOptions.value.length)
|
||||
return router.replace(WELCOME_ROUTE_PATH)
|
||||
|
||||
if (active) {
|
||||
const tag = getMenuTagOptions.value[Math.max(0, index - 1)]
|
||||
|
||||
tag && changeMenuModelValue(tag.fullPath, tag)
|
||||
return tag && changeMenuModelValue(tag.fullPath, tag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭所有标签并且导航至 root path
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 清空所有业务标签及其缓存,然后进入空工作区;不依赖任何业务首页。
|
||||
*
|
||||
* @returns Router 导航结果。
|
||||
*/
|
||||
const closeAll = () => {
|
||||
const { getRootPath } = useAppRoot()
|
||||
const { router } = useVueRouter()
|
||||
const home = router.resolve(getRootPath.value)
|
||||
const record = home.matched.at(-1)
|
||||
setMenuTagOptions([], false)
|
||||
|
||||
if (
|
||||
!record ||
|
||||
record.path === NOT_FOUND_ROUTE_PATH ||
|
||||
record.redirect ||
|
||||
!validRole(home.meta)
|
||||
)
|
||||
return
|
||||
|
||||
const option = resolveOption({
|
||||
...(pick(
|
||||
record,
|
||||
pickRouteRecordNormalizedConstant,
|
||||
) as unknown as AppMenuOption),
|
||||
fullPath: home.path,
|
||||
})
|
||||
|
||||
setMenuTagOptions(option, false)
|
||||
|
||||
return changeMenuModelValue(home.path, option, home.query)
|
||||
return router.replace(WELCOME_ROUTE_PATH)
|
||||
}
|
||||
|
||||
// 目标标签页右侧所有标签页
|
||||
/**
|
||||
*
|
||||
* @param target 要保留的边界标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 关闭右侧标签;激活项被移除时切换到边界标签。
|
||||
*/
|
||||
const closeRight = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeRight')
|
||||
|
||||
@ -135,15 +144,18 @@ export function useSiderBar() {
|
||||
|
||||
spliceMenTagOptions(index + 1, spliceLength)
|
||||
|
||||
if (index <= currentIndex) {
|
||||
if (getMenuKey.value !== option.fullPath) {
|
||||
changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
if (currentIndex > index)
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭目标标签页左侧所有标签页
|
||||
/**
|
||||
*
|
||||
* @param target 要保留的边界标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 关闭左侧标签;激活项被移除时切换到边界标签。
|
||||
*/
|
||||
const closeLeft = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeLeft')
|
||||
|
||||
@ -153,27 +165,28 @@ export function useSiderBar() {
|
||||
|
||||
spliceMenTagOptions(0, index)
|
||||
|
||||
if (currentIndex <= index) {
|
||||
if (getMenuKey.value !== option.fullPath) {
|
||||
changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
if (currentIndex >= 0 && currentIndex < index)
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭除了当前索引的所有菜单项
|
||||
/**
|
||||
*
|
||||
* @param target 要保留的标签对象、索引或路径
|
||||
*
|
||||
* @description
|
||||
* 仅保留并激活目标标签;目标无效时不操作。
|
||||
*/
|
||||
const closeOther = (target: CloseMenuTag) => {
|
||||
const normal = normalMenuTagOption(target, 'closeOther')
|
||||
|
||||
if (normal) {
|
||||
const { option } = normal
|
||||
|
||||
if (getMenuKey.value !== option.fullPath) {
|
||||
spliceMenTagOptions(0, getMenuTagOptions.value.length)
|
||||
changeMenuModelValue(option.fullPath, option)
|
||||
} else {
|
||||
setMenuTagOptions(option, false)
|
||||
}
|
||||
setMenuTagOptions(option, false)
|
||||
|
||||
if (getCurrentMenuOption.value?.fullPath !== option.fullPath)
|
||||
return changeMenuModelValue(option.fullPath, option)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -6,6 +6,14 @@ import type { LayoutInst } from 'naive-ui'
|
||||
* @returns 侧栏 scrollTo;调用时读取当前布局实例,未挂载时不操作。
|
||||
*/
|
||||
export const useSiderScroll = () => {
|
||||
/**
|
||||
*
|
||||
* @param options 横向坐标或 Naive UI 滚动选项
|
||||
* @param y 数字坐标模式下的纵向坐标,默认 0
|
||||
*
|
||||
* @description
|
||||
* 调用时解析当前侧栏;没有侧栏或侧栏未挂载时不操作。
|
||||
*/
|
||||
const scrollTo: LayoutInst['scrollTo'] = (
|
||||
options: number | object,
|
||||
y?: number,
|
||||
|
||||
@ -1,9 +1,28 @@
|
||||
import { useRuntimeActions } from '@/store'
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 操作共享内容区状态。reload(wait = 800) 会卸载页面,恢复计时器归 Store 所有,
|
||||
* 连续刷新以最后一次为准;手动加载与刷新互不持有对方的状态。
|
||||
*
|
||||
* @returns 页面刷新以及手动开启、关闭加载状态的方法。
|
||||
*/
|
||||
export const useSpinning = () => {
|
||||
const { reloadContent: reload, setRuntimeState } = useRuntimeActions()
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 开启共享的手动加载状态;指示器的显示延迟由布局负责。
|
||||
*/
|
||||
const openSpin = () => setRuntimeState('layoutContentSpinning', true)
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 关闭手动加载状态,不取消由 reload 触发的页面重挂载。
|
||||
*/
|
||||
const closeSpin = () => setRuntimeState('layoutContentSpinning', false)
|
||||
|
||||
return { reload, openSpin, closeSpin }
|
||||
|
||||
@ -12,21 +12,29 @@ export interface AppThemeInfo {
|
||||
themeI18nLabel: string
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 每个 Hook 实例复用主题引用与翻译器;读取快照时仍反映当前主题和语言。
|
||||
*
|
||||
* @returns 读取当前主题快照、切换明暗模式及跟随系统主题的方法。
|
||||
*/
|
||||
export const useTheme = () => {
|
||||
const { getAppTheme: isDark } = useSettingGetters()
|
||||
const { updateSettingState } = useSettingActions()
|
||||
const { t } = useI18n()
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 当前主题、固定英文标签和随语言切换的翻译标签。
|
||||
*/
|
||||
const getAppTheme = (): AppThemeInfo => {
|
||||
const { getAppTheme } = useSettingGetters()
|
||||
const { t } = useI18n()
|
||||
|
||||
return {
|
||||
theme: getAppTheme.value,
|
||||
themeI18nLabel: getAppTheme.value
|
||||
theme: isDark.value,
|
||||
themeI18nLabel: isDark.value
|
||||
? t('headerSettingOptions.ThemeOptions.Dark')
|
||||
: t('headerSettingOptions.ThemeOptions.Light'),
|
||||
themeLabel: getAppTheme.value ? 'Dark' : 'Light',
|
||||
themeLabel: isDark.value ? 'Dark' : 'Light',
|
||||
}
|
||||
}
|
||||
|
||||
@ -36,8 +44,6 @@ export const useTheme = () => {
|
||||
* 切换至暗色主题
|
||||
*/
|
||||
const darkTheme = () => {
|
||||
const { updateSettingState } = useSettingActions()
|
||||
|
||||
updateSettingState('appTheme', 'dark')
|
||||
}
|
||||
|
||||
@ -47,8 +53,6 @@ export const useTheme = () => {
|
||||
* 切换至明色主题
|
||||
*/
|
||||
const lightTheme = () => {
|
||||
const { updateSettingState } = useSettingActions()
|
||||
|
||||
updateSettingState('appTheme', 'light')
|
||||
}
|
||||
|
||||
@ -58,8 +62,6 @@ export const useTheme = () => {
|
||||
* 同步系统主题。
|
||||
*/
|
||||
const syncSystemTheme = () => {
|
||||
const { updateSettingState } = useSettingActions()
|
||||
|
||||
updateSettingState('appTheme', 'auto')
|
||||
}
|
||||
|
||||
@ -69,11 +71,7 @@ export const useTheme = () => {
|
||||
* 切换到与当前相反的手动主题。
|
||||
*/
|
||||
const toggleTheme = () => {
|
||||
const { getAppTheme } = useSettingGetters()
|
||||
const theme = getAppTheme.value
|
||||
const { updateSettingState } = useSettingActions()
|
||||
|
||||
updateSettingState('appTheme', !theme ? 'dark' : 'light')
|
||||
updateSettingState('appTheme', isDark.value ? 'light' : 'dark')
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@ -1,5 +1,9 @@
|
||||
import { useSettingActions, useSettingGetters } from '@/store'
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 更新共享水印文本与显隐的方法,修改通过设置 Store 持久化。
|
||||
*/
|
||||
export const useWatermark = () => {
|
||||
/**
|
||||
*
|
||||
|
||||
@ -9,5 +9,10 @@ export type {
|
||||
UseDayjsReturnType,
|
||||
} from '@ray-template/composables/useDayjs'
|
||||
export type LocalKey = keyof DayjsLocalMap
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 使用应用语言映射的日期工具;locale 会同步 Day.js 全局语言。
|
||||
*/
|
||||
export const useDayjs = () =>
|
||||
createDayjsTools(DAYJS_LOCAL_MAP, DEFAULT_DAYJS_LOCAL, true)
|
||||
|
||||
@ -1,11 +1,5 @@
|
||||
import { RIcon, RMoreDropdown } from '@/components'
|
||||
import {
|
||||
useAppRoot,
|
||||
useI18n,
|
||||
useMaximize,
|
||||
useSiderBar,
|
||||
useSpinning,
|
||||
} from '@/hooks'
|
||||
import { useI18n, useMaximize, useSiderBar, useSpinning } from '@/hooks'
|
||||
import { useMenuActions, useMenuGetters, useRuntimeGetters } from '@/store'
|
||||
import type { AppMenuOption, MenuTagOptions } from '@/types'
|
||||
import { ShellTab } from '@ray-template/admin-shell'
|
||||
@ -28,9 +22,11 @@ export default defineComponent({
|
||||
const scrollRef = useTemplateRef<ScrollbarInst | null>('scrollRef')
|
||||
const tagsRef = useTemplateRef<HTMLElement>('tags')
|
||||
const { t } = useI18n('menuTag')
|
||||
const { getMenuKey, getMenuTagOptions } = useMenuGetters()
|
||||
const { getCurrentMenuOption, getMenuTagOptions } = useMenuGetters()
|
||||
const getMenuKey = computed(
|
||||
() => getCurrentMenuOption.value?.fullPath ?? null,
|
||||
)
|
||||
const { changeMenuModelValue } = useMenuActions()
|
||||
const { getRootPath } = useAppRoot()
|
||||
const { maximize } = useMaximize()
|
||||
const { reload } = useSpinning()
|
||||
const {
|
||||
@ -67,6 +63,7 @@ export default defineComponent({
|
||||
{
|
||||
label: t('newWindow'),
|
||||
key: 'windowOpenTab',
|
||||
disabled: !getMenuTagOptions.value[currentContextmenuIndex.value],
|
||||
icon: () => <RIcon name="navigation/window" size="1em" />,
|
||||
},
|
||||
{
|
||||
@ -96,14 +93,16 @@ export default defineComponent({
|
||||
{
|
||||
label: t('closeOther'),
|
||||
key: 'closeOther',
|
||||
disabled: getMenuTagOptions.value.length < 2,
|
||||
disabled:
|
||||
getMenuTagOptions.value.length < 2 ||
|
||||
!getMenuTagOptions.value[currentContextmenuIndex.value],
|
||||
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 < 2,
|
||||
disabled: getMenuTagOptions.value.length === 0,
|
||||
},
|
||||
])
|
||||
const actionMap = {
|
||||
@ -153,10 +152,7 @@ export default defineComponent({
|
||||
actionDropdownShow: false,
|
||||
})
|
||||
const globalMainLayoutLoad = useRuntimeGetters().globalMainLayoutLoad
|
||||
const canClose = (option?: MenuTagOptions) =>
|
||||
!!option &&
|
||||
getMenuTagOptions.value.length > 1 &&
|
||||
option.fullPath !== getRootPath.value
|
||||
const canClose = (option?: MenuTagOptions) => !!option
|
||||
|
||||
const closeCurrentMenuTag = (index: number, restoreFocus = false) => {
|
||||
const option = getMenuTagOptions.value[index]
|
||||
|
||||
@ -270,7 +270,10 @@ export default defineComponent({
|
||||
)}
|
||||
<span>{option.breadcrumbLabel}</span>
|
||||
{option.meta.windowOpen && (
|
||||
<RIcon name="action/shared" size={14} />
|
||||
<RIcon
|
||||
name="action/external-link"
|
||||
size={14}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
<NButton
|
||||
|
||||
@ -2,7 +2,6 @@ import './index.scss'
|
||||
import { LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE } from '@/app-config'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { useRuntimeGetters } from '@/store'
|
||||
import { NSpin } from 'naive-ui'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'ContentLoading',
|
||||
@ -11,6 +10,7 @@ export default defineComponent({
|
||||
const { globalMainLayoutLoad, layoutContentSpinning } = useRuntimeGetters()
|
||||
const routePending = ref(false)
|
||||
const visible = ref(false)
|
||||
const labelId = useId()
|
||||
|
||||
if (LAYOUT_CONTENT_SPIN_WHEN_ROUTE_CHANGE) {
|
||||
const router = useRouter()
|
||||
@ -43,7 +43,6 @@ export default defineComponent({
|
||||
|
||||
return () => (
|
||||
<div
|
||||
role="status"
|
||||
class={[
|
||||
'layout-content-loading',
|
||||
{ 'layout-content-loading--visible': visible.value },
|
||||
@ -51,8 +50,9 @@ export default defineComponent({
|
||||
>
|
||||
{visible.value ? (
|
||||
<div class="layout-content-loading__indicator">
|
||||
<NSpin size="small" aria-hidden="true" />
|
||||
<span>{t('loading')}</span>
|
||||
<progress aria-labelledby={labelId} />
|
||||
<span class="layout-content-loading__track" aria-hidden="true" />
|
||||
<span id={labelId}>{t('loading')}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@ -9,27 +9,87 @@
|
||||
z-index: 2;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 160ms ease-out;
|
||||
|
||||
&--visible {
|
||||
pointer-events: auto;
|
||||
background: color-mix(in srgb, var(--r-canvas) 72%, transparent);
|
||||
opacity: 1;
|
||||
background: color-mix(in srgb, var(--r-canvas) 88%, transparent);
|
||||
}
|
||||
|
||||
&__indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--r-line);
|
||||
border-radius: var(--r-radius);
|
||||
background: var(--r-surface);
|
||||
color: var(--r-text);
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 14px;
|
||||
padding: 24px;
|
||||
color: var(--r-text-secondary);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
progress {
|
||||
position: absolute;
|
||||
inline-size: 1px;
|
||||
block-size: 1px;
|
||||
clip-path: inset(50%);
|
||||
}
|
||||
|
||||
&__track {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
inline-size: 88px;
|
||||
block-size: 2px;
|
||||
border-radius: 1px;
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--r-theme-primary-color) 18%,
|
||||
transparent
|
||||
);
|
||||
|
||||
&::after {
|
||||
position: absolute;
|
||||
inset-block: 0;
|
||||
inset-inline-start: 0;
|
||||
inline-size: 40%;
|
||||
border-radius: inherit;
|
||||
background: var(--r-theme-primary-color);
|
||||
animation: content-loading-sweep 1.4s ease-in-out infinite alternate;
|
||||
content: '';
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
transition: none;
|
||||
|
||||
&__track::after {
|
||||
animation-duration: 6s;
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
&--visible {
|
||||
background: Canvas;
|
||||
}
|
||||
|
||||
&__track {
|
||||
border-block-end: 2px solid GrayText;
|
||||
}
|
||||
|
||||
&__track::after {
|
||||
border-block-end: 2px solid Highlight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.layout-content-loading .n-spin-body {
|
||||
display: none;
|
||||
@keyframes content-loading-sweep {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(150%);
|
||||
}
|
||||
}
|
||||
|
||||
25
apps/admin/src/locales/lang/en-US/appComponents.json
Normal file
25
apps/admin/src/locales/lang/en-US/appComponents.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"moreActions": "More actions",
|
||||
"lockScreen": {
|
||||
"title": "Lock screen",
|
||||
"passwordRule": "Enter a password of 6–12 characters",
|
||||
"lockPlaceholder": "Enter a screen lock password",
|
||||
"unlockPlaceholder": "Enter your screen lock password",
|
||||
"lock": "Lock screen",
|
||||
"warning": "Warning",
|
||||
"returnPrompt": "Return to the sign-in page and sign in again?",
|
||||
"confirm": "Confirm",
|
||||
"cancel": "Cancel",
|
||||
"passwordChanged": "The screen lock password has changed. Please sign in again.",
|
||||
"signIn": "Sign in again",
|
||||
"wrongPassword": "Incorrect password. Please try again.",
|
||||
"backToSignIn": "Back to sign in",
|
||||
"unlock": "Unlock"
|
||||
},
|
||||
"version": {
|
||||
"title": "New version available",
|
||||
"description": "The application has been updated. Confirm to reload and sign in again.",
|
||||
"confirm": "Confirm",
|
||||
"cancel": "Cancel"
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"code": "View usage",
|
||||
"templateIntro": "Template hooks: each example calls the real API. Theme, layout and home preferences are saved; use the corresponding reset actions to restore them.",
|
||||
"templateIntro": "Template hooks: each example calls the real API. Theme and layout preferences are saved; use the corresponding reset actions to restore them.",
|
||||
"webIntro": "Web and component hooks: interactive examples, reactive results and minimal usage snippets.",
|
||||
"dark": "Dark",
|
||||
"light": "Light",
|
||||
@ -18,13 +18,11 @@
|
||||
"openWeb": "Open Web Hooks",
|
||||
"openNested": "Open a nested menu",
|
||||
"firstMenu": "Navigate to the first menu",
|
||||
"useCurrentHome": "Use this page as home",
|
||||
"restoreHome": "Restore dashboard home",
|
||||
"closeOther": "Close other tabs",
|
||||
"closeLeft": "Close tabs on the left",
|
||||
"closeRight": "Close tabs on the right",
|
||||
"closeCurrent": "Close current tab",
|
||||
"closeAll": "Close all and return home",
|
||||
"closeAll": "Close all and open workspace",
|
||||
"contentTop": "Scroll content to top",
|
||||
"content300": "Scroll content to 300 px",
|
||||
"siderTop": "Scroll sidebar to top",
|
||||
@ -56,7 +54,6 @@
|
||||
"useBadge": "Show, update or hide a menu badge by path, including its icon.",
|
||||
"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.",
|
||||
"useAppRoot": "Read and update the home route, used when all tabs are closed.",
|
||||
"useSiderBar": "Close tabs and their neighbors by path, index or tab object.",
|
||||
"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.",
|
||||
|
||||
38
apps/admin/src/locales/lang/en-US/workspaceStates.json
Normal file
38
apps/admin/src/locales/lang/en-US/workspaceStates.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"welcome": {
|
||||
"eyebrow": "Your workspace",
|
||||
"title": "Ready for your next task",
|
||||
"description": "Choose a starting point below, or use the navigation menu to begin your next task.",
|
||||
"shortcuts": "Choose a page",
|
||||
"recent": "Recently visited",
|
||||
"openPage": "Open page",
|
||||
"navigationHint": "Only available pages appear here, with your recent visits first.",
|
||||
"noPagesTitle": "No starting points are available yet",
|
||||
"noPagesDescription": "There are no navigation entries to show. Ask an administrator to check the page configuration or your access."
|
||||
},
|
||||
"forbidden": {
|
||||
"eyebrow": "Access restricted",
|
||||
"title": "This page is not available to you",
|
||||
"description": "Your account does not have access. Choose another page from your workspace, or ask an administrator for access."
|
||||
},
|
||||
"notFound": {
|
||||
"eyebrow": "Page not found",
|
||||
"title": "We couldn't find this page",
|
||||
"description": "The link may have expired, or the page may have moved. Return to your workspace to choose an available page."
|
||||
},
|
||||
"serverError": {
|
||||
"eyebrow": "Loading interrupted",
|
||||
"title": "This page couldn't load",
|
||||
"description": "The page didn't finish loading. Try again, or return to your workspace to continue elsewhere."
|
||||
},
|
||||
"unavailable": {
|
||||
"eyebrow": "Page status",
|
||||
"title": "This content isn't available",
|
||||
"description": "Return to your workspace to choose another available page."
|
||||
},
|
||||
"actions": {
|
||||
"workspace": "Back to workspace",
|
||||
"back": "Previous page",
|
||||
"retry": "Try again"
|
||||
}
|
||||
}
|
||||
25
apps/admin/src/locales/lang/zh-CN/appComponents.json
Normal file
25
apps/admin/src/locales/lang/zh-CN/appComponents.json
Normal file
@ -0,0 +1,25 @@
|
||||
{
|
||||
"moreActions": "更多操作",
|
||||
"lockScreen": {
|
||||
"title": "锁定屏幕",
|
||||
"passwordRule": "请输入 6 至 12 位密码",
|
||||
"lockPlaceholder": "请输入锁屏密码",
|
||||
"unlockPlaceholder": "请输入解锁密码",
|
||||
"lock": "锁屏",
|
||||
"warning": "提示",
|
||||
"returnPrompt": "是否返回登录页并重新登录?",
|
||||
"confirm": "确定",
|
||||
"cancel": "取消",
|
||||
"passwordChanged": "检测到锁屏密码已被修改,请重新登录",
|
||||
"signIn": "重新登录",
|
||||
"wrongPassword": "密码错误,请重新输入",
|
||||
"backToSignIn": "返回登录",
|
||||
"unlock": "进入系统"
|
||||
},
|
||||
"version": {
|
||||
"title": "发现新版本",
|
||||
"description": "应用已更新,确认后将重新加载并登录。",
|
||||
"confirm": "确认",
|
||||
"cancel": "取消"
|
||||
}
|
||||
}
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"code": "查看用法",
|
||||
"templateIntro": "模板 Hooks:每个示例都调用真实接口。主题、布局和首页偏好会自动保存,可通过相应按钮恢复。",
|
||||
"templateIntro": "模板 Hooks:每个示例都调用真实接口。主题和布局偏好会自动保存,可通过相应按钮恢复。",
|
||||
"webIntro": "Web 与组件 Hooks:交互演示、响应式结果和可复制的最小用法。",
|
||||
"dark": "暗色",
|
||||
"light": "亮色",
|
||||
@ -18,13 +18,11 @@
|
||||
"openWeb": "打开 Web Hooks",
|
||||
"openNested": "跳转到嵌套菜单",
|
||||
"firstMenu": "导航到第一个菜单",
|
||||
"useCurrentHome": "将本页设为首页",
|
||||
"restoreHome": "恢复仪表盘首页",
|
||||
"closeOther": "关闭其他标签",
|
||||
"closeLeft": "关闭左侧标签",
|
||||
"closeRight": "关闭右侧标签",
|
||||
"closeCurrent": "关闭当前标签",
|
||||
"closeAll": "关闭全部并返回首页",
|
||||
"closeAll": "关闭全部并进入工作区",
|
||||
"contentTop": "内容滚动到顶部",
|
||||
"content300": "内容滚动到 300px",
|
||||
"siderTop": "侧栏滚动到顶部",
|
||||
@ -56,7 +54,6 @@
|
||||
"useBadge": "按菜单路径显示、更新和隐藏徽标,也可以更新标记图标。",
|
||||
"useWatermark": "更新全局水印文本并控制显示。空字符串沿用上一次内容。",
|
||||
"useAppNavigation": "支持菜单对象、完整路径和从 0 开始的一级菜单索引,返回可等待的导航结果。",
|
||||
"useAppRoot": "读取和更新应用首页;关闭所有标签后会导航至此。",
|
||||
"useSiderBar": "按路径、索引或标签对象关闭指定标签及其相邻标签。",
|
||||
"useContentScroll": "在 setup 中获取滚动方法,执行时使用当前布局实例。",
|
||||
"useSiderScroll": "滚动当前侧栏;顶部导航没有侧栏,调用时会安全忽略。",
|
||||
|
||||
38
apps/admin/src/locales/lang/zh-CN/workspaceStates.json
Normal file
38
apps/admin/src/locales/lang/zh-CN/workspaceStates.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"welcome": {
|
||||
"eyebrow": "你的工作区",
|
||||
"title": "工作区已就绪",
|
||||
"description": "选择一个入口,或从导航菜单打开页面,开始下一项工作。",
|
||||
"shortcuts": "选择一个页面",
|
||||
"recent": "最近访问",
|
||||
"openPage": "打开页面",
|
||||
"navigationHint": "这里展示当前可用的入口,最近访问的页面会优先出现。",
|
||||
"noPagesTitle": "暂时没有可用的入口",
|
||||
"noPagesDescription": "当前没有可显示的导航入口。请联系管理员确认页面配置或访问权限。"
|
||||
},
|
||||
"forbidden": {
|
||||
"eyebrow": "访问受限",
|
||||
"title": "暂时无法访问此页面",
|
||||
"description": "当前账号没有访问权限。你可以返回工作区选择其他页面,或联系管理员开通权限。"
|
||||
},
|
||||
"notFound": {
|
||||
"eyebrow": "页面未找到",
|
||||
"title": "找不到这个页面",
|
||||
"description": "链接可能已失效,或页面地址发生了变化。返回工作区,重新选择一个可用的页面。"
|
||||
},
|
||||
"serverError": {
|
||||
"eyebrow": "加载中断",
|
||||
"title": "页面暂时无法加载",
|
||||
"description": "这次加载没有完成。可以重新尝试,或返回工作区继续其他工作。"
|
||||
},
|
||||
"unavailable": {
|
||||
"eyebrow": "页面状态",
|
||||
"title": "暂时无法显示此内容",
|
||||
"description": "你可以返回工作区,选择其他可用的页面。"
|
||||
},
|
||||
"actions": {
|
||||
"workspace": "返回工作区",
|
||||
"back": "返回上一页",
|
||||
"retry": "重试加载"
|
||||
}
|
||||
}
|
||||
@ -1,12 +1,12 @@
|
||||
import App from './App'
|
||||
import './styles/entry'
|
||||
import type { App as AppType } from 'vue'
|
||||
import { setupRayTemplateCore } from './__ray-template'
|
||||
import { apiMockEnabled } from './api/admin/client'
|
||||
import { installAutocompleteDefaults } from './app-components/provider/AppAutocompleteDefaults'
|
||||
import { GLOBAL_CLASS_NAMES } from './app-config'
|
||||
import { setupDayjs } from './dayjs'
|
||||
import { setupDirectives } from './directives'
|
||||
import { runAppDoctor } from './doctor'
|
||||
import { setupI18n } from './locales'
|
||||
import { setupRouter } from './router'
|
||||
import { setupStore } from './store'
|
||||
@ -56,7 +56,8 @@ const setupTemplate = async () => {
|
||||
await setupPlugins(app)
|
||||
app.mount('#app')
|
||||
bootSplash()?.remove()
|
||||
await setupRayTemplateCore()
|
||||
|
||||
if (__DEV__) runAppDoctor()
|
||||
}
|
||||
|
||||
/**
|
||||
@ -76,7 +77,8 @@ const setupWujieTemplate = async () => {
|
||||
await setupPlugins(instance)
|
||||
instance.mount('#app')
|
||||
bootSplash()?.remove()
|
||||
await setupRayTemplateCore()
|
||||
|
||||
if (__DEV__) runAppDoctor()
|
||||
} catch (error) {
|
||||
showBootError(error)
|
||||
throw error
|
||||
|
||||
@ -9,11 +9,21 @@ After login, open **路由管理** (Route management). Both child pages are regi
|
||||
|
||||
| Source | Read behavior | Applying changes |
|
||||
| ------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Static routes | Read TypeScript files under [modules](modules) | Select static routes and apply |
|
||||
| Static routes | Read the bundled [initial JSON](../mocks/data/routes.json) | Select static routes and apply |
|
||||
| Local JSON | Read configuration saved in the current browser | Import a file or edit JSON, validate, then apply |
|
||||
| Backend API | Request deployment-configured `VITE_ROUTE_CONFIG_URL` at startup | Select the backend source and apply. The URL comes from frontend deployment configuration. |
|
||||
|
||||
Applying reloads the page and rebuilds route matching, menus, and tabs. With an API URL configured, a new browser defaults to the backend source. Explicit source choices are stored in the current browser. API errors, timeouts, or validation failures fall back to static routes and display the reason on the management page. The shell retains login, management, and 404 pages. An internal home page is added when `/dashboard` is absent.
|
||||
Applying reloads the page and rebuilds route matching, menus, and tabs. With an API URL configured, a new browser defaults to the backend source. Explicit source choices are stored in the current browser. In real-backend mode, a failed configured remote source stops startup and shows the boot error; it does not silently substitute demo routes. The shell retains login, management, `/welcome`, `/403`, `/404`, and `/500`. No dashboard or other business page is injected into a custom source.
|
||||
|
||||
## Neutral workspace and recovery
|
||||
|
||||
`/welcome` is the shell's state with no active business route. It is not a protected home tab and is never stored in business tabs, menu selection, navigation history, or KeepAlive. An authenticated visit to `/` opens it unless the login URL contains a valid authorized `redirect` target. That explicit target retains its query and hash. External, missing, denied, and error-page redirect targets fall back to `/welcome`.
|
||||
|
||||
All business tabs, including the former home and the final tab, can close. Closing an active tab selects its adjacent remaining tab; closing the final tab or all tabs opens `/welcome` and removes their cached component names. One tab is retained per concrete pathname, with its latest full URL for query/hash restoration. System states clear active menu/breadcrumb state without fabricating a first-menu selection.
|
||||
|
||||
Authenticated forbidden direct links go to `/403`; unknown paths go to `/404`; route resolution or lazy-loader failures go to `/500`. Status routes carry the attempted URL in `query.from`. Recovery actions validate it through `resolveLandingPath` before navigating, and error-page failures do not create redirect loops. Role changes prune unauthorized tags/cache entries and show `/403` for a revoked current page.
|
||||
|
||||
System paths (including descendants and aliases) and route names are reserved by the application contract. The generic contract accepts `reservedPaths` and `reservedNames` supplied by its host. `homePath` is retained only as an ignored deprecated catalog option. Application `useAppRoot`/`appRootRoute` remain inert legacy preference accessors to avoid breaking stored settings and old consumers; they no longer affect landing, closing, permissions, or startup validation. The root-setting demo controls were removed. The old `redirectRouterToDashboard` export is a deprecated alias for neutral `redirectRouterToWorkspace`.
|
||||
|
||||
## Backend and AI contract
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import initialRoutes from '@/mocks/data/routes.json'
|
||||
import { parseRouteConfig, toRuntimeRoutes } from './config/contract'
|
||||
import { DEFAULT_HOME_PATH, ROUTE_MANAGEMENT_PATH } from './constant'
|
||||
import { ROUTE_MANAGEMENT_PATH } from './constant'
|
||||
import type { AppRouteRecordRaw } from './types'
|
||||
import { expandRoutes } from './utils/expand-routes'
|
||||
import { orderRoutes } from './utils/order-routes'
|
||||
@ -35,16 +35,7 @@ export const getStaticAppRoutes = () =>
|
||||
let activeRoutes: AppRouteRecordRaw[] | undefined
|
||||
|
||||
export function setAppRouteModules(routes: AppRouteRecordRaw[]) {
|
||||
const fallback = getStaticAppRoutes().find(
|
||||
({ path }) => path === DEFAULT_HOME_PATH,
|
||||
)
|
||||
const hasHome = expandRoutes(routes).some(
|
||||
({ path }) => path === DEFAULT_HOME_PATH,
|
||||
)
|
||||
|
||||
activeRoutes = orderRoutes(
|
||||
hasHome || !fallback ? routes : [...routes, fallback],
|
||||
)
|
||||
activeRoutes = orderRoutes(routes)
|
||||
}
|
||||
|
||||
export const getAppRawRoutes = () => [
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import {
|
||||
DEFAULT_HOME_PATH,
|
||||
LAYOUT,
|
||||
ROUTE_MANAGEMENT_PATH,
|
||||
SYSTEM_ROUTE_NAMES,
|
||||
SYSTEM_ROUTE_PATHS,
|
||||
} from '@/router/constant'
|
||||
import { createRouteContract } from '@ray-template/routing/contract'
|
||||
import { findRouteView, findRouteViewId } from './views'
|
||||
@ -9,11 +10,12 @@ import { findRouteView, findRouteViewId } from './views'
|
||||
export const { parseRouteConfig, toRuntimeRoutes, exportRouteConfig } =
|
||||
createRouteContract({
|
||||
layout: LAYOUT,
|
||||
homePath: DEFAULT_HOME_PATH,
|
||||
findRouteView,
|
||||
findRouteViewId,
|
||||
managementPath: ROUTE_MANAGEMENT_PATH,
|
||||
reservedPaths: SYSTEM_ROUTE_PATHS,
|
||||
reservedNames: [
|
||||
...SYSTEM_ROUTE_NAMES,
|
||||
'RLogin',
|
||||
'RLayout',
|
||||
'RNotFound',
|
||||
|
||||
@ -2,6 +2,33 @@ export const LAYOUT = () => import('@/layout/default/ContentWrapper')
|
||||
|
||||
export const NOT_FOUND_ROUTE_PATH = '/:catchAll(.*)'
|
||||
|
||||
export const DEFAULT_HOME_PATH = '/dashboard'
|
||||
export const WELCOME_ROUTE_PATH = '/welcome'
|
||||
export const FORBIDDEN_ROUTE_PATH = '/403'
|
||||
export const NOT_FOUND_PAGE_PATH = '/404'
|
||||
export const SERVER_ERROR_ROUTE_PATH = '/500'
|
||||
export const SYSTEM_ROUTE_PATHS = [
|
||||
WELCOME_ROUTE_PATH,
|
||||
FORBIDDEN_ROUTE_PATH,
|
||||
NOT_FOUND_PAGE_PATH,
|
||||
SERVER_ERROR_ROUTE_PATH,
|
||||
] as const
|
||||
export const SYSTEM_ROUTE_NAMES = [
|
||||
'RWelcome',
|
||||
'ErrorPage403',
|
||||
'ErrorPage404',
|
||||
'ErrorPage500',
|
||||
'RNotFound',
|
||||
] as const
|
||||
|
||||
/**
|
||||
*
|
||||
* @param route 已解析的路由或路由记录
|
||||
*
|
||||
* @returns 是否属于不进入业务菜单、标签和缓存的工作区状态页。
|
||||
*/
|
||||
export const isSystemRoute = (route: { name?: unknown; path?: string }) =>
|
||||
SYSTEM_ROUTE_NAMES.some((name) => name === route.name) ||
|
||||
SYSTEM_ROUTE_PATHS.some((path) => path === route.path) ||
|
||||
route.path === NOT_FOUND_ROUTE_PATH
|
||||
export const ROUTE_MANAGEMENT_PATH = '/route-management'
|
||||
export const ROUTE_MANAGEMENT_JSON_PATH = `${ROUTE_MANAGEMENT_PATH}/json`
|
||||
|
||||
@ -28,7 +28,11 @@ export async function setupRouter(app: App<Element>) {
|
||||
for (const route of getLayoutRoutes()) router.addRoute('RLayout', route)
|
||||
|
||||
vueRouterRegister(router)
|
||||
})()
|
||||
})().catch((error: unknown) => {
|
||||
// 同页重挂载可以重试暂时失败的配置加载;成功初始化仍只注册一次守卫。
|
||||
initialize = void 0
|
||||
throw error
|
||||
})
|
||||
await initialize
|
||||
app.use(router)
|
||||
}
|
||||
|
||||
@ -2,9 +2,13 @@ import Layout from '@/layout'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { appExpandRoutes } from './app-route-modules'
|
||||
import {
|
||||
FORBIDDEN_ROUTE_PATH,
|
||||
NOT_FOUND_PAGE_PATH,
|
||||
NOT_FOUND_ROUTE_PATH,
|
||||
ROUTE_MANAGEMENT_JSON_PATH,
|
||||
ROUTE_MANAGEMENT_PATH,
|
||||
SERVER_ERROR_ROUTE_PATH,
|
||||
WELCOME_ROUTE_PATH,
|
||||
} from './constant'
|
||||
|
||||
const legacyRedirects = [
|
||||
@ -36,16 +40,45 @@ export function getLayoutRoutes(): RouteRecordRaw[] {
|
||||
!occupiedPaths.has(path) && occupiedPaths.has(redirect),
|
||||
),
|
||||
{ path: ROUTE_MANAGEMENT_PATH, redirect: ROUTE_MANAGEMENT_JSON_PATH },
|
||||
{
|
||||
path: NOT_FOUND_ROUTE_PATH,
|
||||
name: 'RNotFound',
|
||||
component: () => import('@/views/error/views/Error404'),
|
||||
meta: {
|
||||
i18nKey: 'menu.Error',
|
||||
icon: 'status/error',
|
||||
hidden: true,
|
||||
sameLevel: true,
|
||||
},
|
||||
},
|
||||
...getSystemRoutes(),
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 不进入业务菜单与标签的工作区状态路由,供应用与隔离文档示例复用。
|
||||
*/
|
||||
export const getSystemRoutes = (): RouteRecordRaw[] => [
|
||||
{
|
||||
path: WELCOME_ROUTE_PATH,
|
||||
name: 'RWelcome',
|
||||
component: () => import('@/views/welcome'),
|
||||
meta: { i18nKey: 'workspaceStates.welcome.title', hidden: true },
|
||||
},
|
||||
{
|
||||
path: FORBIDDEN_ROUTE_PATH,
|
||||
name: 'ErrorPage403',
|
||||
component: () => import('@/views/error/views/Error403'),
|
||||
meta: { i18nKey: 'workspaceStates.forbidden.title', hidden: true },
|
||||
},
|
||||
{
|
||||
path: NOT_FOUND_PAGE_PATH,
|
||||
name: 'ErrorPage404',
|
||||
component: () => import('@/views/error/views/Error404'),
|
||||
meta: { i18nKey: 'workspaceStates.notFound.title', hidden: true },
|
||||
},
|
||||
{
|
||||
path: SERVER_ERROR_ROUTE_PATH,
|
||||
name: 'ErrorPage500',
|
||||
component: () => import('@/views/error/views/Error500'),
|
||||
meta: { i18nKey: 'workspaceStates.serverError.title', hidden: true },
|
||||
},
|
||||
{
|
||||
path: NOT_FOUND_ROUTE_PATH,
|
||||
name: 'RNotFound',
|
||||
redirect: (to) => ({
|
||||
path: NOT_FOUND_PAGE_PATH,
|
||||
query: { from: to.fullPath },
|
||||
}),
|
||||
},
|
||||
]
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { APP_CATCH_KEY, WHITE_ROUTES } from '@/app-config'
|
||||
import { useAppRoot } from '@/hooks'
|
||||
import { getStorage, setStorage } from '@/utils/cache'
|
||||
import { FORBIDDEN_ROUTE_PATH, NOT_FOUND_PAGE_PATH } from '@/router/constant'
|
||||
import { getStorage } from '@/utils/cache'
|
||||
import type { Router } from 'vue-router'
|
||||
import { resolveLandingPath } from './resolve-landing-path'
|
||||
import { validRole } from './valid-role'
|
||||
@ -18,25 +18,42 @@ export const permissionRouter = (router: Router) => {
|
||||
const token = getStorage<string>(APP_CATCH_KEY.token, 'localStorage')
|
||||
const isLogin = to.path === '/'
|
||||
|
||||
if (token === null) {
|
||||
return isLogin ? true : { path: '/', replace: true }
|
||||
if (typeof token !== 'string' || !token) {
|
||||
return isLogin
|
||||
? true
|
||||
: { path: '/', query: { redirect: to.fullPath }, replace: true }
|
||||
}
|
||||
|
||||
const isWhiteRoute =
|
||||
typeof to.name === 'string' && WHITE_ROUTES.includes(to.name)
|
||||
|
||||
if (isLogin || (!isWhiteRoute && !validRole(to.meta))) {
|
||||
const { getRootPath } = useAppRoot()
|
||||
const rootPath = resolveLandingPath(router, getRootPath.value)
|
||||
if (isLogin) {
|
||||
const target = router.resolve(
|
||||
resolveLandingPath(router, to.query.redirect),
|
||||
)
|
||||
|
||||
// 保留既有重定向时的缓存行为;若首页本身无权限,取消导航以免循环。
|
||||
setStorage(APP_CATCH_KEY.appMenuKey, rootPath, 'localStorage')
|
||||
|
||||
return to.fullPath === rootPath
|
||||
? false
|
||||
: { path: rootPath, replace: true }
|
||||
return {
|
||||
path: target.path,
|
||||
query: target.query,
|
||||
hash: target.hash,
|
||||
replace: true,
|
||||
}
|
||||
}
|
||||
|
||||
if (!to.matched.length)
|
||||
return {
|
||||
path: NOT_FOUND_PAGE_PATH,
|
||||
query: { from: to.fullPath },
|
||||
replace: true,
|
||||
}
|
||||
|
||||
if (!isWhiteRoute && !validRole(to.meta))
|
||||
return {
|
||||
path: FORBIDDEN_ROUTE_PATH,
|
||||
query: { from: to.fullPath },
|
||||
replace: true,
|
||||
}
|
||||
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
@ -1,24 +1,25 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { useAppRoot, useVueRouter } from '@/hooks'
|
||||
import { setStorage } from '@/utils/cache'
|
||||
import { resolveLandingPath } from './resolve-landing-path'
|
||||
import { useVueRouter } from '@/hooks/template/useVueRouter'
|
||||
import { WELCOME_ROUTE_PATH } from '@/router/constant'
|
||||
|
||||
/**
|
||||
*
|
||||
* @param replace 是否使用
|
||||
* @param isReplace 是否替换当前历史记录,默认 true
|
||||
*
|
||||
* @description
|
||||
* 重定向路由至首页,默认采用替换方法重定向。
|
||||
* 进入没有活动业务路由的工作区,不创建或激活业务标签。
|
||||
*
|
||||
* @returns Router 导航结果。
|
||||
*/
|
||||
export const redirectRouterToDashboard = (isReplace = true) => {
|
||||
export const redirectRouterToWorkspace = (isReplace = true) => {
|
||||
const { router } = useVueRouter()
|
||||
|
||||
const { push, replace } = router
|
||||
const { getRootPath } = useAppRoot()
|
||||
|
||||
const path = resolveLandingPath(router, getRootPath.value)
|
||||
|
||||
setStorage(APP_CATCH_KEY.appMenuKey, path, 'localStorage')
|
||||
|
||||
return isReplace ? replace(path) : push(path)
|
||||
return isReplace
|
||||
? router.replace(WELCOME_ROUTE_PATH)
|
||||
: router.push(WELCOME_ROUTE_PATH)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @deprecated 兼容旧导出名;现在进入空工作区,请改用 redirectRouterToWorkspace。
|
||||
*/
|
||||
export const redirectRouterToDashboard = redirectRouterToWorkspace
|
||||
|
||||
@ -1,19 +1,57 @@
|
||||
import { DEFAULT_HOME_PATH, NOT_FOUND_ROUTE_PATH } from '@/router/constant'
|
||||
import { WHITE_ROUTES } from '@/app-config'
|
||||
import { isSystemRoute, WELCOME_ROUTE_PATH } from '@/router/constant'
|
||||
import type { Router } from 'vue-router'
|
||||
import { validRole } from './valid-role'
|
||||
|
||||
export function resolveLandingPath(router: Router, preferredPath: string) {
|
||||
const home = router.resolve(preferredPath)
|
||||
const record = home.matched.at(-1)
|
||||
|
||||
/**
|
||||
*
|
||||
* @param router 当前已注册业务与系统页面的 Router
|
||||
* @param requested 登录返回或错误恢复时请求的站内地址,可来自不可信查询参数
|
||||
*
|
||||
* @description
|
||||
* 只恢复仍存在且当前角色有权访问的业务地址,保留原查询参数和片段。
|
||||
* 不选择首页、缓存菜单或第一个菜单;无有效目标时进入空工作区。
|
||||
*
|
||||
* @returns 可安全导航的原始站内完整路径,或 /welcome。
|
||||
*/
|
||||
export function resolveLandingPath(router: Router, requested?: unknown) {
|
||||
if (
|
||||
home.path === '/' ||
|
||||
!record ||
|
||||
record.path === NOT_FOUND_ROUTE_PATH ||
|
||||
record.redirect ||
|
||||
(home.path !== DEFAULT_HOME_PATH && !validRole(home.meta))
|
||||
typeof requested !== 'string' ||
|
||||
!requested.startsWith('/') ||
|
||||
requested.startsWith('//') ||
|
||||
/[\\\p{Cc}]/u.test(requested)
|
||||
)
|
||||
return DEFAULT_HOME_PATH
|
||||
return WELCOME_ROUTE_PATH
|
||||
|
||||
return home.fullPath
|
||||
const original = router.resolve(requested)
|
||||
let current = original
|
||||
const visited = new Set<string>()
|
||||
|
||||
while (!visited.has(current.fullPath)) {
|
||||
visited.add(current.fullPath)
|
||||
const record = current.matched.at(-1)
|
||||
|
||||
if (!record || current.path === '/' || isSystemRoute(current))
|
||||
return WELCOME_ROUTE_PATH
|
||||
|
||||
if (record.redirect) {
|
||||
if (typeof record.redirect !== 'string') return WELCOME_ROUTE_PATH
|
||||
|
||||
current = router.resolve({
|
||||
path: record.redirect,
|
||||
query: current.query,
|
||||
hash: current.hash,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
const allowed =
|
||||
(typeof current.name === 'string' &&
|
||||
WHITE_ROUTES.includes(current.name)) ||
|
||||
validRole(current.meta)
|
||||
|
||||
return allowed ? original.fullPath : WELCOME_ROUTE_PATH
|
||||
}
|
||||
|
||||
return WELCOME_ROUTE_PATH
|
||||
}
|
||||
|
||||
39
apps/admin/src/router/utils/setup-router-errors.ts
Normal file
39
apps/admin/src/router/utils/setup-router-errors.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { SERVER_ERROR_ROUTE_PATH } from '@/router/constant'
|
||||
import { isNavigationFailure, NavigationFailureType } from 'vue-router'
|
||||
import type { RouteLocationNormalized, Router } from 'vue-router'
|
||||
|
||||
/**
|
||||
*
|
||||
* @param router 当前 Router 实例
|
||||
*
|
||||
* @description
|
||||
* 当前导航通过本全局守卫后失败时显示 500 并保留重试目标,过期懒加载失败不改变页面。
|
||||
* 先于本守卫抛出的离开守卫异常沿用 Router 拒绝,避免无法确认归属时抢占新导航。
|
||||
*/
|
||||
export const setupRouterErrors = (router: Router) => {
|
||||
let latestTarget: RouteLocationNormalized | undefined
|
||||
|
||||
router.beforeEach((to) => {
|
||||
latestTarget = to
|
||||
})
|
||||
router.afterEach((to, _, failure) => {
|
||||
// 重复或离开守卫中止的导航可能不经过 beforeEach;旧导航被取消则不能夺回归属。
|
||||
if (!isNavigationFailure(failure, NavigationFailureType.cancelled))
|
||||
latestTarget = to
|
||||
})
|
||||
|
||||
router.onError((error, to) => {
|
||||
if (latestTarget !== to) return
|
||||
|
||||
console.error('[Router] Navigation failed.', error)
|
||||
window.$loadingBar?.error()
|
||||
|
||||
if (to.path === SERVER_ERROR_ROUTE_PATH) return
|
||||
|
||||
void router
|
||||
.replace({ path: SERVER_ERROR_ROUTE_PATH, query: { from: to.fullPath } })
|
||||
.catch(() => {
|
||||
// 500 页面也无法加载时保留原错误,避免创建无限重定向。
|
||||
})
|
||||
})
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
import { SETUP_ROUTER_ACTION } from '@/app-config'
|
||||
import type { Router } from 'vue-router'
|
||||
import { permissionRouter } from './permission'
|
||||
import { setupRouterErrors } from './setup-router-errors'
|
||||
import { setupRouterLoadingBar } from './setup-router-loading-bar'
|
||||
|
||||
/**
|
||||
@ -11,6 +12,7 @@ import { setupRouterLoadingBar } from './setup-router-loading-bar'
|
||||
* 统一的路由相关功能配置,虽然该方法有点蠢。
|
||||
*/
|
||||
export const vueRouterRegister = (router: Router) => {
|
||||
setupRouterErrors(router)
|
||||
const { setupRouterLoadingBar: cfgSetupRouterLoadingBar, setupRouterGuard } =
|
||||
SETUP_ROUTER_ACTION
|
||||
|
||||
|
||||
@ -93,8 +93,10 @@ 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.
|
||||
- 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.
|
||||
- Update KeepAlive in recent-access order, deduplicate, and trim to its limit. Merge themes only when the effective theme changes; observe color-weakness mode and document titles independently.
|
||||
- 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.
|
||||
|
||||
## Recent navigation and favorites
|
||||
|
||||
|
||||
@ -16,10 +16,12 @@ export const useKeepAliveGetters = () => {
|
||||
}
|
||||
|
||||
export const useKeepAliveActions = () => {
|
||||
const { setKeepAliveInclude, getKeepAliveInclude } = piniaKeepAliveStore()
|
||||
const { setKeepAliveInclude, getKeepAliveInclude, retainKeepAliveInclude } =
|
||||
piniaKeepAliveStore()
|
||||
|
||||
return {
|
||||
setKeepAliveInclude,
|
||||
getKeepAliveInclude,
|
||||
retainKeepAliveInclude,
|
||||
}
|
||||
}
|
||||
|
||||
@ -85,7 +85,7 @@ export const useSettingGetters = () => {
|
||||
/**
|
||||
*
|
||||
* @description
|
||||
* 获取 app 根路由。
|
||||
* 获取历史首页偏好,仅用于兼容,不影响工作区导航。
|
||||
*/
|
||||
const getAppRootRoute = computed(() => variable.appRootRoute)
|
||||
|
||||
|
||||
@ -41,10 +41,24 @@ export const piniaKeepAliveStore = defineStore(
|
||||
// 获取当前缓存队列
|
||||
const getKeepAliveInclude = () => state.keepAliveInclude
|
||||
|
||||
/**
|
||||
*
|
||||
* @param names 当前仍打开且允许访问的业务组件名称
|
||||
*
|
||||
* @description
|
||||
* 移除已关闭或失去权限的页面缓存,空工作区不会保留隐式首页。
|
||||
*/
|
||||
const retainKeepAliveInclude = (names: ReadonlySet<string>) => {
|
||||
state.keepAliveInclude = state.keepAliveInclude.filter((name) =>
|
||||
names.has(name),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
...toRefs(state),
|
||||
setKeepAliveInclude,
|
||||
getKeepAliveInclude,
|
||||
retainKeepAliveInclude,
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@ -1,7 +1,8 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { getAppRawRoutes } from '@/router/app-route-modules'
|
||||
import { canSkipRoute, validMenuItemShow, validRole } from '@/router/utils'
|
||||
import { FORBIDDEN_ROUTE_PATH, isSystemRoute } from '@/router/constant'
|
||||
import { validMenuItemShow, validRole } from '@/router/utils'
|
||||
import { joinRoutePath } from '@/router/utils/join-route-path'
|
||||
import { useKeepAliveActions } from '@/store'
|
||||
import type { MenuState } from '@/store/modules/menu/types'
|
||||
@ -18,7 +19,6 @@ import { pickRouteRecordNormalizedConstant } from './constant'
|
||||
import {
|
||||
createMenuExtra,
|
||||
createMenuIcon,
|
||||
getCatchMenuKey,
|
||||
getCatchMenuTagOptions,
|
||||
updateDocumentTitle,
|
||||
} from './utils'
|
||||
@ -47,13 +47,14 @@ export const depthSearchAppMenu = (
|
||||
export const piniaMenuStore = defineStore(
|
||||
'menu',
|
||||
() => {
|
||||
const { push, resolve } = useRouter()
|
||||
const { push, replace, resolve } = useRouter()
|
||||
const route = useRoute()
|
||||
const { t } = useI18n()
|
||||
const { setKeepAliveInclude } = useKeepAliveActions()
|
||||
const { setKeepAliveInclude, retainKeepAliveInclude } =
|
||||
useKeepAliveActions()
|
||||
|
||||
const menuState = reactive<MenuState>({
|
||||
menuKey: getCatchMenuKey(), // 当前菜单 `key`
|
||||
menuKey: null, // 当前菜单由实际 URL 决定,不从缓存选择首页。
|
||||
options: [], // 菜单列表
|
||||
collapsed: false, // 是否折叠菜单
|
||||
menuTagOptions: getCatchMenuTagOptions(), // tag 标签菜单
|
||||
@ -66,7 +67,10 @@ export const piniaMenuStore = defineStore(
|
||||
string,
|
||||
{ option: AppMenuOption; parentPath: string }
|
||||
>()
|
||||
const cacheTags = () =>
|
||||
const cacheTags = () => {
|
||||
retainKeepAliveInclude(
|
||||
new Set(menuState.menuTagOptions.map(({ name }) => name)),
|
||||
)
|
||||
setStorage(
|
||||
APP_CATCH_KEY.appMenuTagOptions,
|
||||
menuState.menuTagOptions.map(
|
||||
@ -91,6 +95,14 @@ export const piniaMenuStore = defineStore(
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const clearActiveMenu = () => {
|
||||
menuState.menuKey = null
|
||||
menuState.currentMenuOption = null
|
||||
menuState.breadcrumbOptions = []
|
||||
setStorage(APP_CATCH_KEY.appMenuKey, null)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
@ -180,13 +192,21 @@ export const piniaMenuStore = defineStore(
|
||||
isAppend = true,
|
||||
) => {
|
||||
const isArray = Array.isArray(options)
|
||||
const arr = isArray ? [...options] : [options]
|
||||
const arr = (isArray ? [...options] : [options]).filter(
|
||||
(option) =>
|
||||
option.fullPath !== '/' &&
|
||||
!isSystemRoute({ ...option, path: resolve(option.fullPath).path }) &&
|
||||
!option.meta.sameLevel &&
|
||||
!option.meta.windowOpen,
|
||||
)
|
||||
|
||||
isAppend
|
||||
? menuState.menuTagOptions.push(...arr)
|
||||
: (menuState.menuTagOptions = arr)
|
||||
|
||||
cacheTags()
|
||||
|
||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||
}
|
||||
|
||||
const updateActiveMenu = (option: AppMenuOption) => {
|
||||
@ -194,22 +214,29 @@ export const piniaMenuStore = defineStore(
|
||||
updateDocumentTitle(option)
|
||||
|
||||
if (option.meta.sameLevel) {
|
||||
if (
|
||||
!menuState.breadcrumbOptions.some(({ key }) => key === option.key)
|
||||
) {
|
||||
menuState.breadcrumbOptions.push(option)
|
||||
}
|
||||
const existing = menuState.breadcrumbOptions.findIndex(
|
||||
({ key }) => key === option.key,
|
||||
)
|
||||
|
||||
if (existing < 0) menuState.breadcrumbOptions.push(option)
|
||||
else menuState.breadcrumbOptions[existing] = option
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (
|
||||
!menuState.menuTagOptions.some(
|
||||
({ fullPath }) => fullPath === option.fullPath,
|
||||
)
|
||||
) {
|
||||
const pathname = resolve(option.fullPath).path
|
||||
const tagIndex = menuState.menuTagOptions.findIndex(
|
||||
({ fullPath }) => resolve(fullPath).path === pathname,
|
||||
)
|
||||
|
||||
if (tagIndex < 0) {
|
||||
menuState.menuTagOptions.push(option)
|
||||
cacheTags()
|
||||
} else if (
|
||||
menuState.menuTagOptions[tagIndex].fullPath !== option.fullPath
|
||||
) {
|
||||
menuState.menuTagOptions[tagIndex] = option
|
||||
cacheTags()
|
||||
}
|
||||
|
||||
setBreadcrumbOptions(option.key)
|
||||
@ -224,7 +251,7 @@ export const piniaMenuStore = defineStore(
|
||||
!option.children?.length &&
|
||||
!option.fullPath.includes(':')
|
||||
) {
|
||||
navigationHistory.recordVisit(option.fullPath)
|
||||
navigationHistory.recordVisit(pathname)
|
||||
}
|
||||
|
||||
if (menuState.menuKey !== option.key) {
|
||||
@ -247,26 +274,47 @@ export const piniaMenuStore = defineStore(
|
||||
const path = String(key)
|
||||
|
||||
if (route.fullPath === path && !query) updateActiveMenu(option)
|
||||
else return push({ path, query })
|
||||
else {
|
||||
const target = resolve(path)
|
||||
|
||||
return push({
|
||||
path: target.path,
|
||||
hash: target.hash,
|
||||
query: { ...target.query, ...query },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const optionForRoute = (path: string, matched: RouteRecordNormalized[]) => {
|
||||
const record = matched.at(-1)
|
||||
|
||||
if (!record || record.path === '/' || record.redirect) return
|
||||
if (
|
||||
!record ||
|
||||
record.path === '/' ||
|
||||
record.redirect ||
|
||||
isSystemRoute(record) ||
|
||||
!validRole(record.meta)
|
||||
)
|
||||
return
|
||||
|
||||
const canonicalPath = record.aliasOf?.path ?? record.path
|
||||
const menuOption = menuIndex.get(canonicalPath)?.option
|
||||
|
||||
if (menuOption && !canonicalPath.includes(':')) return menuOption
|
||||
if (menuOption && !canonicalPath.includes(':'))
|
||||
return menuOption.fullPath === path
|
||||
? menuOption
|
||||
: { ...menuOption, fullPath: path }
|
||||
|
||||
return resolveOption({
|
||||
...(pick(
|
||||
record,
|
||||
pickRouteRecordNormalizedConstant,
|
||||
) as unknown as AppMenuOption),
|
||||
fullPath: path,
|
||||
})
|
||||
return {
|
||||
...resolveOption({
|
||||
...(pick(
|
||||
record,
|
||||
pickRouteRecordNormalizedConstant,
|
||||
) as unknown as AppMenuOption),
|
||||
fullPath: path,
|
||||
}),
|
||||
key: resolve(path).path,
|
||||
}
|
||||
}
|
||||
|
||||
const setupAppMenu = async () => {
|
||||
@ -313,34 +361,44 @@ export const piniaMenuStore = defineStore(
|
||||
const restored = resolve(fullPath)
|
||||
const record = restored.matched.at(-1)
|
||||
|
||||
if (!record || !validRole(record.meta, currentRole)) return []
|
||||
if (
|
||||
!record ||
|
||||
!validRole(restored.meta, currentRole) ||
|
||||
isSystemRoute(record)
|
||||
)
|
||||
return []
|
||||
|
||||
const option = optionForRoute(restored.path, restored.matched)
|
||||
const option = optionForRoute(restored.fullPath, restored.matched)
|
||||
|
||||
return option && !option.meta.sameLevel && !option.meta.windowOpen
|
||||
? [option]
|
||||
: []
|
||||
})
|
||||
|
||||
menuState.menuTagOptions = restoredTags
|
||||
menuState.menuTagOptions = [
|
||||
...new Map(
|
||||
restoredTags.map((option) => [resolve(option.fullPath).path, option]),
|
||||
).values(),
|
||||
]
|
||||
cacheTags()
|
||||
|
||||
const active = optionForRoute(route.path, route.matched)
|
||||
|
||||
if (!active || active.meta.sameLevel) {
|
||||
const cached = menuIndex.get(String(menuState.menuKey))?.option
|
||||
const first =
|
||||
cached &&
|
||||
!cached.children &&
|
||||
cached.show !== false &&
|
||||
!cached.meta.windowOpen
|
||||
? cached
|
||||
: canSkipRoute(menuState.options)
|
||||
|
||||
if (first) updateActiveMenu(first as AppMenuOption)
|
||||
}
|
||||
const active = optionForRoute(route.fullPath, route.matched)
|
||||
|
||||
if (active) updateActiveMenu(active)
|
||||
else {
|
||||
clearActiveMenu()
|
||||
|
||||
if (
|
||||
route.path !== '/' &&
|
||||
!isSystemRoute(route) &&
|
||||
route.matched.length &&
|
||||
!validRole(route.meta, currentRole)
|
||||
)
|
||||
await replace({
|
||||
path: FORBIDDEN_ROUTE_PATH,
|
||||
query: { from: route.fullPath },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@ -368,26 +426,55 @@ export const piniaMenuStore = defineStore(
|
||||
|
||||
cacheTags()
|
||||
|
||||
if (!menuState.menuTagOptions.length) clearActiveMenu()
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
watch(() => signing.signingCallback.role, setupAppMenu, { immediate: true })
|
||||
watch(
|
||||
() => [
|
||||
signing.signingCallback.role,
|
||||
signing.signingCallback.id || signing.signingCallback.name,
|
||||
],
|
||||
(current, previous) => {
|
||||
if (previous?.[1] && current[1] !== previous[1]) {
|
||||
menuState.menuTagOptions = []
|
||||
|
||||
if (!current[1]) {
|
||||
cacheTags()
|
||||
clearActiveMenu()
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
void setupAppMenu()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(
|
||||
() => route.path,
|
||||
() => route.fullPath,
|
||||
(path) => {
|
||||
const option = optionForRoute(path, route.matched)
|
||||
|
||||
if (option) updateActiveMenu(option)
|
||||
else clearActiveMenu()
|
||||
},
|
||||
)
|
||||
|
||||
watch(
|
||||
() => menuState.currentMenuOption?.breadcrumbLabel,
|
||||
() => {
|
||||
if (menuState.currentMenuOption)
|
||||
updateDocumentTitle(menuState.currentMenuOption)
|
||||
const { i18nKey, noLocalTitle } = route.meta
|
||||
|
||||
return i18nKey
|
||||
? t(i18nKey)
|
||||
: (noLocalTitle ?? menuState.currentMenuOption?.breadcrumbLabel)
|
||||
},
|
||||
(label) => {
|
||||
if (label) updateDocumentTitle({ breadcrumbLabel: String(label) })
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
return {
|
||||
@ -405,7 +492,7 @@ export const piniaMenuStore = defineStore(
|
||||
persist: {
|
||||
key: APP_CATCH_KEY.appPiniaMenuStore,
|
||||
storage: window.localStorage,
|
||||
pick: ['menuKey', 'collapsed'],
|
||||
pick: ['collapsed'],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { RIcon } from '@/components'
|
||||
import { useAppRoot, useI18n } from '@/hooks'
|
||||
import { useI18n } from '@/hooks'
|
||||
import { resolveIconName } from '@/icons'
|
||||
import type { AppMenuKey, AppMenuOption } from '@/types/modules/app'
|
||||
import { getStorage } from '@/utils/cache'
|
||||
@ -107,7 +107,9 @@ export const parseAndFindMatchingNodes = (
|
||||
* 动态修改浏览器标题。
|
||||
* 会自动拼接 sideBarLogo.title。
|
||||
*/
|
||||
export const updateDocumentTitle = (option: AppMenuOption) => {
|
||||
export const updateDocumentTitle = (
|
||||
option: Pick<AppMenuOption, 'breadcrumbLabel'>,
|
||||
) => {
|
||||
const { dynamicDocumentTitle } = piniaSettingStore()
|
||||
|
||||
if (!dynamicDocumentTitle) {
|
||||
@ -210,22 +212,12 @@ export const createMenuExtra = (option: AppMenuOption) => {
|
||||
|
||||
/**
|
||||
*
|
||||
* @returns 获取缓存的菜单 key
|
||||
*
|
||||
* @description
|
||||
* 获取缓存的菜单 key,如果没有缓存,则返回根路径
|
||||
*
|
||||
* @example
|
||||
* getCatchMenuKey() // '/dashboard'
|
||||
* @returns 缓存中的业务菜单 key;缺少缓存时返回 null,不选择默认菜单。
|
||||
*/
|
||||
export const getCatchMenuKey = () => {
|
||||
const { getRootPath } = useAppRoot()
|
||||
const cacheMenuKey = getStorage<AppMenuKey>(
|
||||
APP_CATCH_KEY.appMenuKey,
|
||||
'sessionStorage',
|
||||
{
|
||||
defaultValue: getRootPath.value,
|
||||
},
|
||||
)
|
||||
|
||||
return cacheMenuKey
|
||||
|
||||
@ -1,4 +1,5 @@
|
||||
import { APP_CATCH_KEY } from '@/app-config'
|
||||
import { isSystemRoute } from '@/router/constant'
|
||||
import { getStorageInstance } from '@/utils/cache-backend'
|
||||
import { piniaSigningStore } from '../signing'
|
||||
|
||||
@ -6,6 +7,7 @@ const validPath = (value: unknown): value is string =>
|
||||
typeof value === 'string' &&
|
||||
value.startsWith('/') &&
|
||||
!value.startsWith('//') &&
|
||||
!isSystemRoute({ path: value }) &&
|
||||
value.length <= 512 &&
|
||||
!/[?#:]/u.test(value)
|
||||
|
||||
|
||||
@ -3,6 +3,7 @@ import { useDayjs, useI18n } from '@/hooks'
|
||||
import type { LocalKey } from '@/hooks'
|
||||
import { resolveIconName } from '@/icons'
|
||||
import { getAppDefaultLanguage } from '@/locales/utils'
|
||||
import { WELCOME_ROUTE_PATH } from '@/router/constant'
|
||||
import type { SettingState } from '@/store/modules/setting/types'
|
||||
import type { AnyFn } from '@/types'
|
||||
import { setStorage } from '@/utils/cache'
|
||||
@ -34,16 +35,16 @@ export const piniaSettingStore = defineStore(
|
||||
localeLanguage: getAppDefaultLanguage(),
|
||||
// 锁屏开关
|
||||
lockScreenSwitch: false,
|
||||
// 根路由信息
|
||||
// 仅供旧版 useAppRoot 调用方读取;不再控制路由跳转或标签保护。
|
||||
appRootRoute: {
|
||||
name: 'Dashboard',
|
||||
path: '/dashboard',
|
||||
name: 'RWelcome',
|
||||
path: WELCOME_ROUTE_PATH,
|
||||
},
|
||||
// 侧边栏设置
|
||||
sideBarLogo: {
|
||||
icon: 'logo/ray',
|
||||
title: 'Ray Admin',
|
||||
url: '/dashboard',
|
||||
url: WELCOME_ROUTE_PATH,
|
||||
jumpType: 'station',
|
||||
},
|
||||
...cloneDeep(getDefaultSettingConfig()),
|
||||
@ -209,15 +210,31 @@ export const piniaSettingStore = defineStore(
|
||||
storage: window.localStorage,
|
||||
serializer: {
|
||||
serialize: (state) =>
|
||||
JSON.stringify({ ...state, menuIconSizesUpdated: true }),
|
||||
JSON.stringify({
|
||||
...state,
|
||||
menuIconSizesUpdated: true,
|
||||
workspaceLandingMigrated: true,
|
||||
}),
|
||||
deserialize: (json) => {
|
||||
const { menuIconSizesUpdated, ...state } = JSON.parse(
|
||||
json,
|
||||
) as Partial<SettingState> & {
|
||||
menuIconSizesUpdated?: boolean
|
||||
}
|
||||
const { menuIconSizesUpdated, workspaceLandingMigrated, ...state } =
|
||||
JSON.parse(json) as Partial<SettingState> & {
|
||||
menuIconSizesUpdated?: boolean
|
||||
workspaceLandingMigrated?: boolean
|
||||
}
|
||||
const { menuConfig } = state
|
||||
|
||||
// 只迁移旧版整套默认 Logo;自定义目标保持显式导航语义。
|
||||
if (
|
||||
!workspaceLandingMigrated &&
|
||||
state.sideBarLogo?.url === '/dashboard' &&
|
||||
state.sideBarLogo.title === 'Ray Admin' &&
|
||||
typeof state.sideBarLogo.icon === 'string' &&
|
||||
resolveIconName(state.sideBarLogo.icon) === 'logo/ray' &&
|
||||
state.sideBarLogo.jumpType === 'station'
|
||||
) {
|
||||
state.sideBarLogo.url = WELCOME_ROUTE_PATH
|
||||
}
|
||||
|
||||
// 旧缓存写入了整组默认值。仅升级旧的尺寸组合,保留此后保存的自定义值。
|
||||
if (
|
||||
!menuIconSizesUpdated &&
|
||||
|
||||
@ -44,6 +44,7 @@ export interface SettingState {
|
||||
copyrightSwitch: boolean
|
||||
contentTransition: string
|
||||
watermarkConfig: WatermarkConfig
|
||||
/** 历史兼容偏好,不参与默认导航或标签保护。 */
|
||||
appRootRoute: AppRootRoute
|
||||
/**
|
||||
*
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user