ray-template/__test__/layout/slots.spec.ts
XiaoDaiGua-Ray 22dfe441e0
feat(layout): add a composable workspace designer
Add layout registration, visual editing, and source generation.

Preserve embedded pages and wait for asynchronous layout renderers.

Add workspace lint and formatting commands.
2026-12-01 17:34:27 +08:00

572 lines
17 KiB
TypeScript

import { flushPromises, mount, shallowMount } from '@vue/test-utils'
import { createPinia, disposePinia, setActivePinia } from 'pinia'
import {
defineComponent,
h,
nextTick,
reactive,
ref,
vShow,
withDirectives,
} from 'vue'
import type { SetupContext } from 'vue'
import { createMemoryHistory, createRouter, RouterView } from 'vue-router'
import { LAYOUT_CONTENT_REF } from '../../apps/admin/src/app-config'
import Layout from '../../apps/admin/src/layout'
import {
LayoutFrame,
LayoutOutlet,
LayoutTabs,
} from '../../apps/admin/src/layout/blocks'
import type { LayoutDesign } from '../../apps/admin/src/layout/designer'
import { useLayout } from '../../apps/admin/src/layout/useLayout'
import { router } from '../../apps/admin/src/router'
import { piniaKeepAliveStore } from '../../apps/admin/src/store/modules/keep-alive'
import { piniaRuntimeStore } from '../../apps/admin/src/store/modules/runtime'
import { piniaSettingStore } from '../../apps/admin/src/store/modules/setting'
import { useLayoutDraftPreview } from '../../apps/admin/src/views/demo/layout-lab/useLayoutDraftPreview'
const liveShell = {
LayoutPresentation: false,
SharedFrame: false,
BuiltinLayout: false,
LayoutFrame: false,
LayoutOutlet: false,
LayoutOutletTarget: false,
RayAdminShell: false,
LayoutContent: {
setup(_: unknown, { expose, slots }: SetupContext) {
expose({ scrollTo: vi.fn() })
return () => h('div', slots.default?.())
},
},
teleport: false,
suspense: false,
}
it('lets a custom header replace the complete default header and top navigation', async () => {
const pinia = createPinia()
setActivePinia(pinia)
piniaSettingStore().updateSettingState('layoutConfig', { mode: 'top' })
const options = {
global: {
renderStubDefaultSlot: true,
stubs: liveShell,
plugins: [router, pinia],
},
}
const standard = shallowMount(Layout, options)
await nextTick()
expect(standard.find('top-navigation-stub').exists()).toBe(true)
standard.unmount()
const custom = shallowMount(Layout, {
...options,
slots: {
header: () => h('div', { 'data-test': 'custom-header' }, 'Custom'),
},
})
try {
await nextTick()
expect(custom.find('[data-test="custom-header"]').exists()).toBe(true)
expect(custom.find('top-navigation-stub').exists()).toBe(false)
} finally {
custom.unmount()
disposePinia(pinia)
}
})
it('offers a restore button for custom content and also exits with Escape', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const runtime = piniaRuntimeStore()
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
renderStubDefaultSlot: true,
stubs: liveShell,
plugins: [router, pinia],
},
slots: {
default: () => h('div', { 'data-test': 'custom-content' }, 'Custom'),
},
})
try {
await nextTick()
expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe(
false,
)
await wrapper.get('.r-layout-skip').trigger('click')
expect(document.activeElement).toBe(wrapper.get('main').element)
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
expect(wrapper.find('[data-test="custom-content"]').exists()).toBe(true)
await wrapper.get('.r-layout-content-restore__button').trigger('click')
expect(runtime.layoutContentMaximize).toBe(false)
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
expect(runtime.layoutContentMaximize).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('keeps rows below content independent of copyright and honors inline tab overrides', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
const settings = piniaSettingStore()
layout.registerLayout({
id: 'bottom-tabs',
label: 'Bottom tabs',
component: {
setup: () => () =>
h(LayoutFrame, null, {
bottom: () => h(LayoutTabs),
footer: () => h('span', 'Copyright'),
}),
},
})
layout.updateLayout('bottom-tabs')
const wrapper = mount(Layout, {
slots: {
default: () => h('article', 'Page'),
tabs: () => h('nav', 'Custom tabs'),
},
global: {
plugins: [router, pinia],
stubs: { SettingDrawer: true },
},
})
try {
await flushPromises()
const footer = () => wrapper.get('.r-layout-footer-region')
expect(footer().get('nav').text()).toBe('Custom tabs')
expect(footer().text()).toContain('Copyright')
settings.updateSettingState('copyrightSwitch', false)
await nextTick()
expect(footer().text()).toBe('Custom tabs')
settings.updateSettingState('menuTagSwitch', false)
await nextTick()
expect(footer().find('nav').exists()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('previews changes live and restores the saved workspace on exit or leaving the lab', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
layout.updateLayout('top')
const editing = ref(true)
const draft = reactive<LayoutDesign>({
id: 'untitled',
label: 'Draft',
rows: [],
selectable: true,
})
const lab = {
setup() {
const { togglePreview } = useLayoutDraftPreview(draft)
return () => h('button', { onClick: togglePreview }, 'Try')
},
}
const wrapper = mount(Layout, {
slots: {
default: () => (editing.value ? h(lab) : h('article', 'Next page')),
tabs: () => h('nav', 'Open pages'),
},
global: {
plugins: [router, pinia],
stubs: { LayoutHeader: true, TopNavigation: true, SettingDrawer: true },
},
})
try {
await flushPromises()
const toggle = wrapper.get('main button')
await toggle.trigger('click')
expect(wrapper.attributes('data-layout')).toBe('_preview')
expect(layout.selectedLayoutId.value).toBe('top')
expect(wrapper.find('.r-layout-footer-region').exists()).toBe(false)
draft.bottomRows = [['tabs']]
await nextTick()
expect(wrapper.get('.r-layout-footer-region nav').text()).toBe('Open pages')
await toggle.trigger('click')
expect(wrapper.attributes('data-layout')).toBe('top')
await toggle.trigger('click')
editing.value = false
await nextTick()
expect(wrapper.attributes('data-layout')).toBe('top')
expect(wrapper.get('main article').text()).toBe('Next page')
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('moves the full navigation to the right without adding a second menu', async () => {
const pinia = createPinia()
setActivePinia(pinia)
piniaSettingStore().updateSettingState('layoutConfig', { mode: 'right' })
const wrapper = shallowMount(Layout, {
global: {
renderStubDefaultSlot: true,
stubs: liveShell,
plugins: [router, pinia],
},
})
try {
await nextTick()
expect(wrapper.get('app-menu-stub').attributes('end')).toBe('true')
expect(wrapper.find('top-navigation-stub').exists()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it('keeps the active and cached route instances when switching layout components', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const page = (name: string) =>
defineComponent({
name,
setup() {
const draft = ref('')
return () =>
h('input', {
'aria-label': name,
value: draft.value,
onInput: (event: Event) => {
draft.value = (event.target as HTMLInputElement).value
},
})
},
})
const applicationRouter = createRouter({
history: createMemoryHistory(),
routes: [
{
path: '/',
component: Layout,
children: [
{ path: 'first', name: 'FirstDraft', component: page('FirstDraft') },
{
path: 'second',
name: 'SecondDraft',
component: page('SecondDraft'),
},
],
},
],
})
await applicationRouter.push('/first')
const wrapper = mount(RouterView, {
attachTo: document.body,
global: {
plugins: [applicationRouter, pinia],
stubs: {
AppMenu: true,
LayoutHeader: true,
LayoutFooter: true,
LayoutTabs: true,
TopNavigation: true,
ContentLoading: true,
SettingDrawer: true,
LayoutHeaderActions: true,
},
},
})
try {
piniaKeepAliveStore().keepAliveInclude = ['FirstDraft', 'SecondDraft']
const layout = useLayout()
await flushPromises()
const first = wrapper.get('input')
const sharedMain = wrapper.get('[data-shared-layout-frame] main').element
const sharedOutlet = wrapper.get('main > .r-layout-outlet').element
await first.setValue('retained cache')
await applicationRouter.push('/second')
await nextTick()
const second = wrapper.get('input')
await second.setValue('active draft')
second.element.focus()
const scrollContainer = () =>
wrapper.get('.r-layout-content-scroll').element.parentElement!
scrollContainer().scrollTop = 450
expect(layout.updateLayout('custom-top')).toBe(true)
await nextTick()
expect(wrapper.get('[data-layout]').attributes('data-layout')).toBe(
'custom-top',
)
expect(wrapper.get('input').element).toBe(second.element)
await nextTick()
expect(wrapper.get('main').element).toBe(sharedMain)
expect(document.activeElement).toBe(second.element)
expect(scrollContainer().scrollTop).toBe(450)
expect((second.element as HTMLInputElement).value).toBe('active draft')
await applicationRouter.push('/first')
await nextTick()
expect(wrapper.get('input').element).toBe(first.element)
expect((first.element as HTMLInputElement).value).toBe('retained cache')
layout.registerLayout({
id: 'explicit-outlet',
label: 'Explicit outlet',
component: {
setup: () => () =>
h(LayoutFrame, null, { default: () => h(LayoutOutlet) }),
},
})
expect(layout.updateLayout('explicit-outlet')).toBe(true)
await flushPromises()
expect(wrapper.get('[data-shared-layout-frame] main').element).toBe(
sharedMain,
)
expect(wrapper.get('main > .r-layout-outlet').element).toBe(sharedOutlet)
const runtime = piniaRuntimeStore()
runtime.setRuntimeState('layoutContentMaximize', true)
await nextTick()
expect(layout.updateLayout('side')).toBe(true)
await nextTick()
expect(wrapper.get('input').element).toBe(first.element)
expect(runtime.layoutContentMaximize).toBe(true)
window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }))
expect(runtime.layoutContentMaximize).toBe(false)
} finally {
wrapper.unmount()
applicationRouter.options.history.destroy()
disposePinia(pinia)
}
})
it.each([false, true])(
'keeps the public scroll target and focus on the active embedded outlet (maximized=%s)',
async (maximized) => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
layout.registerLayout({
id: 'wrapped-frame',
label: 'Wrapped frame',
component: {
render: () =>
h('section', { class: 'custom-frame' }, [h(LayoutOutlet)]),
},
})
const wrapper = mount(Layout, {
attachTo: document.body,
slots: { default: () => h('input', { 'aria-label': 'Draft' }) },
global: {
plugins: [router, pinia],
stubs: {
SettingDrawer: true,
LayoutHeader: true,
AppMenu: true,
LayoutTabs: true,
LayoutFooter: true,
ContentLoading: true,
},
},
})
const contentElement = () =>
(LAYOUT_CONTENT_REF.value as { $el?: HTMLElement } | null)?.$el
try {
await flushPromises()
const input = wrapper.get('input').element
const sharedContent = contentElement()
expect(sharedContent?.contains(input)).toBe(true)
piniaRuntimeStore().setRuntimeState('layoutContentMaximize', maximized)
await nextTick()
input.focus()
expect(layout.updateLayout('wrapped-frame')).toBe(true)
await flushPromises()
expect(contentElement()).toBe(
wrapper.get('.custom-frame .r-layout-full__viewer-content').element,
)
expect(contentElement()?.contains(input)).toBe(true)
expect(wrapper.get('[data-shared-layout-frame]').isVisible()).toBe(false)
expect(document.activeElement).toBe(input)
expect(layout.updateLayout('side')).toBe(true)
await flushPromises()
expect(contentElement()).toBe(sharedContent)
expect(contentElement()?.contains(input)).toBe(true)
expect(wrapper.get('[data-shared-layout-frame]').isVisible()).toBe(true)
expect(document.activeElement).toBe(input)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
},
)
it.each(['frame', 'outlet'])(
'keeps v-show on the real layout %s',
async (target) => {
const pinia = createPinia()
setActivePinia(pinia)
const layout = useLayout()
const visible = ref(true)
layout.registerLayout({
id: 'conditional-frame',
label: 'Conditional frame',
component: {
render: () =>
target === 'frame'
? withDirectives(h(LayoutFrame), [[vShow, visible.value]])
: h(LayoutFrame, null, {
default: () =>
withDirectives(h(LayoutOutlet), [[vShow, visible.value]]),
}),
},
})
layout.updateLayout('conditional-frame')
const wrapper = mount(Layout, {
attachTo: document.body,
slots: { default: () => h('article', 'Page') },
global: { plugins: [router, pinia], stubs: { SettingDrawer: true } },
})
try {
await flushPromises()
const region = wrapper.get(
target === 'frame' ? '.r-layout-full' : 'main > .r-layout-outlet',
)
expect(region.isVisible()).toBe(true)
visible.value = false
await nextTick()
expect(region.attributes('style')).toContain('display: none')
expect(region.isVisible()).toBe(false)
} finally {
wrapper.unmount()
disposePinia(pinia)
}
},
)
it('preserves the iframe document and its unsaved input across frame layouts', async () => {
const pinia = createPinia()
setActivePinia(pinia)
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
plugins: [router, pinia],
renderStubDefaultSlot: true,
stubs: { ...liveShell, CustomTopLayout: false },
},
slots: {
default: () => h('iframe', { title: 'Embedded form', srcdoc: '<input>' }),
},
})
try {
await flushPromises()
const frameDocument = wrapper.get('iframe').element.contentDocument!
const field = frameDocument.querySelector('input')!
field.value = 'unfinished draft'
const layout = useLayout()
for (const id of ['top', 'custom-top', 'mixed', 'split', 'right', 'side']) {
expect(layout.updateLayout(id)).toBe(true)
await flushPromises()
expect(wrapper.attributes('data-layout')).toBe(id)
const current = wrapper.get('iframe').element.contentDocument
expect(current).toBe(frameDocument)
expect(current?.querySelector('input')?.value).toBe('unfinished draft')
}
} finally {
wrapper.unmount()
disposePinia(pinia)
}
})
it.each([0, 2])(
'restores the last valid layout after a renderer mounts %i outlets',
async (count) => {
const pinia = createPinia()
setActivePinia(pinia)
const wrapper = shallowMount(Layout, {
attachTo: document.body,
global: {
plugins: [router, pinia],
renderStubDefaultSlot: true,
stubs: { ...liveShell, InvalidLayout: false },
},
slots: { default: () => h('input', { 'aria-label': 'Retained' }) },
})
const layout = useLayout()
const error = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
await flushPromises()
const field = wrapper.get('input').element
layout.registerLayout({
id: 'invalid',
label: 'Invalid',
component: {
name: 'InvalidLayout',
render: () =>
h(
'div',
Array.from({ length: count }, () => h(LayoutOutlet)),
),
},
})
layout.updateLayout('invalid')
await nextTick()
await nextTick()
await nextTick()
expect(error).toHaveBeenCalledWith(
expect.stringContaining('"invalid"'),
expect.stringContaining('exactly one'),
)
expect(layout.selectedLayoutId.value).toBe('side')
expect(wrapper.get('input').element).toBe(field)
} finally {
error.mockRestore()
wrapper.unmount()
disposePinia(pinia)
}
},
)