From 22dfe441e05eead78cd1ce6497b6db36177a128a Mon Sep 17 00:00:00 2001 From: XiaoDaiGua-Ray <51957438+XiaoDaiGua-Ray@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:34:27 +0800 Subject: [PATCH] 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. --- __test__/layout/async-layout.spec.ts | 194 +++++++ __test__/layout/deferred-layout.spec.ts | 183 ++++++ __test__/layout/layout-designer.spec.ts | 186 ++++++ .../layout/layout-generator-format.spec.ts | 138 +++++ __test__/layout/layout-picker.spec.ts | 88 +++ __test__/layout/layout-registry.spec.ts | 271 +++++++++ __test__/layout/layout-writer.spec.ts | 233 ++++++++ __test__/layout/menu-settings.spec.tsx | 47 +- __test__/layout/slots.spec.ts | 485 +++++++++++++++- __test__/workspace/lint-fix.spec.ts | 72 +++ apps/admin/src/documentation-example.tsx | 1 + apps/admin/src/layout/README.md | 20 +- apps/admin/src/layout/api.ts | 3 + .../src/layout/blocks/LayoutBreadcrumb.tsx | 11 + apps/admin/src/layout/blocks/LayoutFooter.tsx | 11 + apps/admin/src/layout/blocks/LayoutFrame.tsx | 155 +++++ apps/admin/src/layout/blocks/LayoutOutlet.tsx | 26 + apps/admin/src/layout/blocks/LayoutRow.tsx | 6 + apps/admin/src/layout/blocks/LayoutTabs.tsx | 13 + apps/admin/src/layout/blocks/OutletTarget.tsx | 18 + apps/admin/src/layout/blocks/SharedFrame.tsx | 65 +++ apps/admin/src/layout/blocks/index.scss | 63 +++ apps/admin/src/layout/blocks/index.ts | 13 + .../src/layout/components/LayoutSettings.tsx | 42 +- .../src/layout/components/Menu/index.tsx | 4 +- .../src/layout/components/MenuTag/index.tsx | 326 ++++++----- .../components/SiderBar/HeaderActions.tsx | 209 +++++++ .../segment-views/CustomMenu.tsx | 23 +- .../src/layout/components/SiderBar/index.scss | 17 +- .../src/layout/components/SiderBar/index.tsx | 265 +-------- .../layout/components/TopNavigation/index.tsx | 10 +- .../admin/src/layout/define-builtin-layout.ts | 19 + .../layout/definitions/custom-top.layout.ts | 15 + .../src/layout/definitions/mixed.layout.ts | 10 + .../src/layout/definitions/right.layout.ts | 7 + .../src/layout/definitions/side.layout.ts | 7 + .../src/layout/definitions/split.layout.ts | 11 + .../src/layout/definitions/top.layout.ts | 7 + apps/admin/src/layout/designer.ts | 176 ++++++ apps/admin/src/layout/discovery.ts | 103 ++++ apps/admin/src/layout/host-context.ts | 25 + apps/admin/src/layout/id.ts | 10 + apps/admin/src/layout/index.tsx | 374 +++++++++--- apps/admin/src/layout/preview.ts | 44 ++ .../src/layout/renderers/BuiltinLayout.tsx | 70 +++ .../src/layout/renderers/CustomTopLayout.tsx | 30 + .../layout/renderers/LayoutPresentation.ts | 59 ++ apps/admin/src/layout/types.ts | 16 + apps/admin/src/layout/useDeferredLayout.ts | 161 ++++++ apps/admin/src/layout/useLayout.ts | 112 ++++ apps/admin/src/locales/lang/en-US/layout.json | 56 +- apps/admin/src/locales/lang/zh-CN/layout.json | 56 +- apps/admin/src/store/README.md | 1 + apps/admin/src/store/hooks/useSettingStore.ts | 4 + apps/admin/src/store/modules/setting/index.ts | 24 +- apps/admin/src/types/global.d.ts | 1 + apps/admin/src/views/demo/layout-demo.tsx | 65 ++- .../views/demo/layout-lab/LayoutCanvas.tsx | 530 ++++++++++++++++++ .../views/demo/layout-lab/LayoutDesigner.tsx | 188 +++++++ .../src/views/demo/layout-lab/index.scss | 251 +++++++++ .../demo/layout-lab/useLayoutDraftPreview.tsx | 78 +++ .../src/views/demo/template-hooks/index.tsx | 5 +- apps/docs/en/guide/layout.md | 13 + apps/docs/en/guide/tooling.md | 19 +- apps/docs/en/reference/hooks/layout.md | 20 + apps/docs/guide/layout.md | 13 + apps/docs/guide/tooling.md | 19 +- apps/docs/reference/hooks/layout.md | 20 + docs/toolchain-upgrade.md | 6 + harness/README.md | 4 +- harness/context/layout.md | 2 + harness/context/toolchain.md | 4 +- harness/scopes.json | 1 + package.json | 16 + packages/admin-shell/src/AdminShell.tsx | 23 +- packages/admin-shell/src/LayoutSettings.scss | 147 ++--- packages/admin-shell/src/LayoutSettings.tsx | 235 ++++---- packages/admin-shell/src/index.ts | 2 + packages/admin-shell/src/layout-preview.tsx | 69 +++ scripts/fix.mjs | 32 ++ scripts/lint-fix.mjs | 59 +- vite-helper/layout-writer.ts | 179 ++++++ vite.config.ts | 6 +- 83 files changed, 5794 insertions(+), 808 deletions(-) create mode 100644 __test__/layout/async-layout.spec.ts create mode 100644 __test__/layout/deferred-layout.spec.ts create mode 100644 __test__/layout/layout-designer.spec.ts create mode 100644 __test__/layout/layout-generator-format.spec.ts create mode 100644 __test__/layout/layout-picker.spec.ts create mode 100644 __test__/layout/layout-registry.spec.ts create mode 100644 __test__/layout/layout-writer.spec.ts create mode 100644 __test__/workspace/lint-fix.spec.ts create mode 100644 apps/admin/src/layout/api.ts create mode 100644 apps/admin/src/layout/blocks/LayoutBreadcrumb.tsx create mode 100644 apps/admin/src/layout/blocks/LayoutFooter.tsx create mode 100644 apps/admin/src/layout/blocks/LayoutFrame.tsx create mode 100644 apps/admin/src/layout/blocks/LayoutOutlet.tsx create mode 100644 apps/admin/src/layout/blocks/LayoutRow.tsx create mode 100644 apps/admin/src/layout/blocks/LayoutTabs.tsx create mode 100644 apps/admin/src/layout/blocks/OutletTarget.tsx create mode 100644 apps/admin/src/layout/blocks/SharedFrame.tsx create mode 100644 apps/admin/src/layout/blocks/index.scss create mode 100644 apps/admin/src/layout/blocks/index.ts create mode 100644 apps/admin/src/layout/components/SiderBar/HeaderActions.tsx create mode 100644 apps/admin/src/layout/define-builtin-layout.ts create mode 100644 apps/admin/src/layout/definitions/custom-top.layout.ts create mode 100644 apps/admin/src/layout/definitions/mixed.layout.ts create mode 100644 apps/admin/src/layout/definitions/right.layout.ts create mode 100644 apps/admin/src/layout/definitions/side.layout.ts create mode 100644 apps/admin/src/layout/definitions/split.layout.ts create mode 100644 apps/admin/src/layout/definitions/top.layout.ts create mode 100644 apps/admin/src/layout/designer.ts create mode 100644 apps/admin/src/layout/discovery.ts create mode 100644 apps/admin/src/layout/host-context.ts create mode 100644 apps/admin/src/layout/id.ts create mode 100644 apps/admin/src/layout/preview.ts create mode 100644 apps/admin/src/layout/renderers/BuiltinLayout.tsx create mode 100644 apps/admin/src/layout/renderers/CustomTopLayout.tsx create mode 100644 apps/admin/src/layout/renderers/LayoutPresentation.ts create mode 100644 apps/admin/src/layout/types.ts create mode 100644 apps/admin/src/layout/useDeferredLayout.ts create mode 100644 apps/admin/src/layout/useLayout.ts create mode 100644 apps/admin/src/views/demo/layout-lab/LayoutCanvas.tsx create mode 100644 apps/admin/src/views/demo/layout-lab/LayoutDesigner.tsx create mode 100644 apps/admin/src/views/demo/layout-lab/index.scss create mode 100644 apps/admin/src/views/demo/layout-lab/useLayoutDraftPreview.tsx create mode 100644 packages/admin-shell/src/layout-preview.tsx create mode 100644 scripts/fix.mjs create mode 100644 vite-helper/layout-writer.ts diff --git a/__test__/layout/async-layout.spec.ts b/__test__/layout/async-layout.spec.ts new file mode 100644 index 00000000..343173c4 --- /dev/null +++ b/__test__/layout/async-layout.spec.ts @@ -0,0 +1,194 @@ +import Layout from '@/layout' +import { LayoutFrame, LayoutOutlet } from '@/layout/blocks' +import { useLayout } from '@/layout/useLayout' +import { flushPromises, mount } from '@vue/test-utils' +import type { VueWrapper } from '@vue/test-utils' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { defineAsyncComponent, Fragment, h, nextTick } from 'vue' +import type { Component } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' + +const loaded = { + render: () => h(LayoutFrame, { class: 'loaded-layout' }), +} + +let pinia: ReturnType +let wrapper: VueWrapper + +beforeEach(async () => { + pinia = createPinia() + setActivePinia(pinia) + const router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: '/', component: loaded }], + }) + + wrapper = mount(Layout, { + attachTo: document.body, + slots: { + default: () => [ + h('input', { 'aria-label': 'Draft' }), + h('button', { type: 'button' }, 'Save draft'), + ], + }, + global: { + plugins: [router, pinia], + stubs: { + AppMenu: true, + LayoutHeader: true, + LayoutFooter: true, + LayoutTabs: true, + TopNavigation: true, + ContentLoading: true, + SettingDrawer: true, + }, + }, + }) + await nextTick() +}) + +afterEach(() => { + wrapper.unmount() + disposePinia(pinia) + vi.restoreAllMocks() +}) + +function selectPendingLayout(suspensible = true) { + const gate = Promise.withResolvers() + const layout = useLayout() + + layout.registerLayout({ + id: 'deferred', + label: 'Deferred', + component: defineAsyncComponent({ + loader: () => gate.promise, + suspensible, + delay: 0, + loadingComponent: { render: () => h('p', { class: 'loading-layout' }) }, + }), + }) + layout.updateLayout('deferred') + + return { layout, gate } +} + +it.each([ + ['shared', loaded], + ['freeform', { render: () => h('section', [h(loaded)]) }], +] as const)( + 'keeps the old page usable and its latest state in a %s layout', + async (_, component) => { + const previous = wrapper.get('.r-layout-full').element + const field = wrapper.get('input').element + const viewport = () => + field.closest('.r-layout-content-scroll')!.parentElement! + const save = wrapper.get('main button').element + + field.focus() + + viewport().scrollTop = 150 + const { layout, gate } = selectPendingLayout() + + await flushPromises() + expect(layout.selectedLayoutId.value).toBe('deferred') + expect(wrapper.get('.r-layout-full').element).toBe(previous) + const draft = wrapper.get('input') + + expect(draft.element).toBe(field) + expect(draft.isVisible()).toBe(true) + expect(draft.element.closest('[inert]')).toBeNull() + await draft.setValue('edited while loading') + viewport().scrollTop = 320 + save.focus() + gate.resolve(component) + await flushPromises() + expect(wrapper.get('.loaded-layout input').element).toBe(field) + expect(field.value).toBe('edited while loading') + expect(viewport().scrollTop).toBe(320) + expect(document.activeElement).toBe(save) + expect(layout.selectedLayoutId.value).toBe('deferred') + }, +) + +it('accepts a layout that controls its own async loading state', async () => { + const { layout, gate } = selectPendingLayout(false) + + await flushPromises() + expect(wrapper.find('.loading-layout').exists()).toBe(true) + expect(layout.selectedLayoutId.value).toBe('deferred') + gate.resolve(loaded) + await flushPromises() + expect(wrapper.find('.loaded-layout input').exists()).toBe(true) +}) + +it('restores the last usable layout after a loader rejects', async () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const error = new Error('Layout module failed to load') + + useLayout().updateLayout('right') + await flushPromises() + const { layout, gate } = selectPendingLayout() + + await flushPromises() + gate.reject(error) + await flushPromises() + expect(report).toHaveBeenCalledWith( + expect.stringContaining('"deferred"'), + error, + ) + expect(layout.selectedLayoutId.value).toBe('right') + expect(wrapper.find('main input').exists()).toBe(true) +}) + +it.each(['success', 'failure'])( + 'ignores a stale loader after switching again (%s)', + async (outcome) => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { layout, gate } = selectPendingLayout() + + await flushPromises() + layout.updateLayout('top') + await nextTick() + + if (outcome === 'success') gate.resolve(loaded) + else gate.reject(new Error('Stale layout failed')) + + await flushPromises() + expect(layout.selectedLayoutId.value).toBe('top') + expect(wrapper.find('.loaded-layout').exists()).toBe(false) + expect(wrapper.find('main input').exists()).toBe(true) + expect(report).not.toHaveBeenCalled() + }, +) + +it.each([ + ['no outlet', () => h('section')], + [ + 'two embedded outlets', + () => h('section', [h(LayoutOutlet), h(LayoutOutlet)]), + ], + ['two root frames', () => h(Fragment, [h(LayoutFrame), h(LayoutFrame)])], +] as const)('rejects a resolved layout with %s', async (_, render) => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { layout, gate } = selectPendingLayout() + + await flushPromises() + const field = wrapper.get('input').element + const viewport = () => + field.closest('.r-layout-content-scroll')!.parentElement! + + field.focus() + viewport().scrollTop = 280 + gate.resolve({ render }) + await flushPromises() + + expect(report).toHaveBeenCalledWith( + expect.stringContaining('"deferred"'), + expect.stringContaining('exactly one'), + ) + expect(layout.selectedLayoutId.value).toBe('side') + expect(wrapper.get('input').isVisible()).toBe(true) + expect(wrapper.get('input').element).toBe(field) + expect(document.activeElement).toBe(field) + expect(viewport().scrollTop).toBe(280) +}) diff --git a/__test__/layout/deferred-layout.spec.ts b/__test__/layout/deferred-layout.spec.ts new file mode 100644 index 00000000..7c872fdb --- /dev/null +++ b/__test__/layout/deferred-layout.spec.ts @@ -0,0 +1,183 @@ +import Layout from '@/layout' +import { LayoutFrame } from '@/layout/blocks' +import { useLayout } from '@/layout/useLayout' +import { flushPromises, mount } from '@vue/test-utils' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import { defineAsyncComponent, h, nextTick, ref } from 'vue' +import type { Component } from 'vue' +import { createMemoryHistory, createRouter } from 'vue-router' + +const freeform = { render: () => h('section', [h(LayoutFrame)]) } +const originalMove = Object.getOwnPropertyDescriptor( + Element.prototype, + 'moveBefore', +) + +beforeAll(() => { + Object.defineProperty(Element.prototype, 'moveBefore', { + configurable: true, + value: void 0, + }) +}) +afterAll(() => { + if (originalMove) + Object.defineProperty(Element.prototype, 'moveBefore', originalMove) + else Reflect.deleteProperty(Element.prototype, 'moveBefore') +}) + +const stubs = { + AppMenu: true, + LayoutHeader: true, + LayoutFooter: true, + LayoutTabs: true, + LayoutHeaderActions: true, + TopNavigation: true, + ContentLoading: true, + SettingDrawer: true, +} + +async function workspace(initial = 'side') { + const pinia = createPinia() + + setActivePinia(pinia) + const layout = useLayout() + + layout.registerLayout({ + id: 'wrapped', + label: 'Wrapped frame', + component: freeform, + }) + layout.updateLayout(initial) + const embedded = ref(true) + const router = createRouter({ + history: createMemoryHistory(), + routes: [{ path: '/', component: freeform }], + }) + const wrapper = mount(Layout, { + attachTo: document.body, + slots: { + default: () => + embedded.value + ? h('iframe', { srcdoc: '' }) + : h('p', 'Next page'), + }, + global: { plugins: [router, pinia], stubs }, + }) + + await flushPromises() + + return { + wrapper, + layout, + embedded, + dispose: () => { + wrapper.unmount() + disposePinia(pinia) + }, + } +} + +it.each([ + ['side', 'wrapped'], + ['wrapped', 'top'], +])( + 'keeps the current embed connected when moving from %s to %s requires recreating its document', + async (from, to) => { + const { wrapper, layout, embedded, dispose } = await workspace(from) + + try { + const frame = wrapper.get('iframe').element + const original = frame.contentDocument + + expect(original).toBeTruthy() + layout.updateLayout(to) + await flushPromises() + expect(layout.selectedLayoutId.value).toBe(to) + expect(wrapper.attributes('data-layout')).toBe(from) + expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(true) + expect(wrapper.get('iframe').element.contentDocument).toBe(original) + + layout.updateLayout(from) + await flushPromises() + expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false) + expect(frame.contentDocument).toBe(original) + layout.updateLayout(to) + await flushPromises() + embedded.value = false + await vi.waitFor(() => expect(wrapper.attributes('data-layout')).toBe(to)) + expect(wrapper.get('main p').text()).toBe('Next page') + expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false) + } finally { + dispose() + } + }, +) + +it('uses the declared shared frame on a generated layout’s first visit with an iframe', async () => { + const { wrapper, layout, dispose } = await workspace() + + try { + const original = wrapper.get('iframe').element.contentDocument + + layout.registerLayout({ + id: 'generated', + label: 'Generated', + sharedFrame: true, + component: { render: () => h(LayoutFrame, { class: 'generated-frame' }) }, + }) + layout.updateLayout('generated') + await flushPromises() + expect(wrapper.get('.generated-frame iframe').element).toBe( + wrapper.get('iframe').element, + ) + expect(wrapper.get('iframe').element.contentDocument).toBe(original) + expect(wrapper.find('.r-layout-switch-notice').exists()).toBe(false) + } finally { + dispose() + } +}) + +it.each([ + ['side', true], + ['side', false], + ['wrapped', true], + ['wrapped', false], +] as const)( + 'protects an iframe opened from %s while a freeform async renderer loads (suspensible %s)', + async (from, suspensible) => { + const { wrapper, embedded, layout, dispose } = await workspace(from) + + try { + embedded.value = false + await nextTick() + const loader = Promise.withResolvers() + + layout.registerLayout({ + id: 'loading-shell', + label: 'Loading', + component: defineAsyncComponent({ + loader: () => loader.promise, + suspensible, + delay: 0, + }), + }) + layout.updateLayout('loading-shell') + await flushPromises() + embedded.value = true + await nextTick() + const original = wrapper.get('iframe').element.contentDocument + + loader.resolve(freeform) + await flushPromises() + expect(wrapper.attributes('data-layout')).toBe(from) + expect(wrapper.get('iframe').isVisible()).toBe(true) + expect(wrapper.get('iframe').element.contentDocument).toBe(original) + embedded.value = false + await vi.waitFor(() => + expect(wrapper.attributes('data-layout')).toBe('loading-shell'), + ) + } finally { + dispose() + } + }, +) diff --git a/__test__/layout/layout-designer.spec.ts b/__test__/layout/layout-designer.spec.ts new file mode 100644 index 00000000..0d023e09 --- /dev/null +++ b/__test__/layout/layout-designer.spec.ts @@ -0,0 +1,186 @@ +import { generateLayoutSource, layoutWriteEndpoint } from '@/layout/designer' +import { flushPromises, mount } from '@vue/test-utils' + +vi.mock('@/hooks/template/useI18n', () => ({ + useI18n: () => ({ t: (key: string) => key }), +})) +vi.mock('@/layout/useLayout', () => ({ + useLayout: () => ({ layouts: { value: [{ id: 'side' }] } }), +})) + +async function mountDesigner(writer: boolean) { + vi.stubGlobal('__LAYOUT_PROJECT_WRITER__', writer) + vi.resetModules() + const { default: Designer } = + await import('@/views/demo/layout-lab/LayoutDesigner') + + return mount(Designer) +} + +afterEach(() => { + vi.restoreAllMocks() + vi.unstubAllEnvs() + vi.unstubAllGlobals() +}) + +it('posts the edited visual design on the local development server and blocks duplicate IDs', async () => { + const post = vi.fn().mockResolvedValue(new Response(null, { status: 201 })) + + vi.stubGlobal('fetch', post) + const wrapper = await mountDesigner(true) + + try { + const button = wrapper.get('.layout-designer__project button') + + expect(button.text()).toBe('generate') + const id = wrapper.get('input[aria-label="id"]') + + await id.setValue('side') + expect(button.attributes('disabled')).toBeDefined() + await id.setValue('lab-demo') + const palette = (name: string) => wrapper.get(`[data-palette="${name}"]`) + const tile = (name: string) => wrapper.get(`[data-tile="${name}"]`) + const action = (label: string) => { + const control = wrapper + .findAll('.layout-designer__inspector button') + .find((item) => item.text() === label) + + expect.assert(control) + + return control + } + const selectRow = (value: string) => + wrapper.get('select[aria-label="position"]').setValue(value) + + expect(wrapper.find('[data-tile]').exists()).toBe(false) + expect(wrapper.find('.layout-designer__outlet').exists()).toBe(true) + await palette('actions').trigger('click') + await palette('tabs').trigger('click') + await action('rowUp').trigger('click') + expect( + wrapper + .findAll('[data-region="rows"] [data-tile]') + .map((item) => item.text()), + ).toEqual(['tabs', 'actions']) + await tile('actions').trigger('click') + await selectRow('rows:0') + await action('left').trigger('click') + await action('rowDown').trigger('click') + expect( + wrapper + .findAll('[data-region="bottomRows"] [data-tile]') + .map((item) => item.text()), + ).toEqual(['actions', 'tabs']) + await action('rowUp').trigger('click') + await palette('navigation').trigger('click') + await wrapper + .get('[data-region="bottomRows"] .layout-designer__new-row') + .trigger('click') + await palette('sidebar').trigger('click') + await action('sidebarRight').trigger('click') + await palette('footer').trigger('click') + await action('remove').trigger('click') + expect(wrapper.find('[data-tile="footer"]').exists()).toBe(false) + await palette('footer').trigger('click') + expect(tile('sidebar').element.previousElementSibling).toBe( + wrapper.get('.layout-designer__viewer').element, + ) + expect(tile('footer').element.parentElement).toBe( + wrapper.get('.layout-designer__viewer').element, + ) + const transfer = { setData: vi.fn(), effectAllowed: '' } + + const newRows = wrapper + .findAll('.layout-designer__new-row') + .map((item) => item.element) + const destination = tile('navigation').element + + expect(newRows).toHaveLength(2) + await palette('breadcrumb').trigger('dragstart', { dataTransfer: transfer }) + expect( + wrapper + .findAll('.layout-designer__new-row') + .every((item, index) => item.element === newRows[index]), + ).toBe(true) + expect(tile('navigation').element).toBe(destination) + await tile('navigation').trigger('drop', { + dataTransfer: transfer, + clientX: -10, + }) + expect( + wrapper + .findAll('[data-region="bottomRows"] [data-tile]') + .map((item) => item.text()), + ).toEqual(['breadcrumb', 'navigation']) + await button.trigger('click') + await flushPromises() + expect(post).toHaveBeenCalledTimes(1) + const [endpoint, request] = post.mock.calls[0] + + expect(endpoint).toBe(layoutWriteEndpoint) + expect(request.method).toBe('POST') + expect(request.headers['X-Ray-Layout-Write']).toBe('1') + expect(JSON.parse(request.body)).toMatchObject({ + id: 'lab-demo', + rows: [['actions', 'tabs']], + bottomRows: [['breadcrumb', 'navigation']], + sidebar: 'right', + footer: true, + }) + expect( + wrapper.get('.layout-designer__project [role="status"]').text(), + ).toBe('written') + } finally { + wrapper.unmount() + } +}) + +it.each([ + { writer: false, embedded: false, development: true }, + { writer: true, embedded: false, development: false }, + { writer: true, embedded: true, development: true }, +])( + 'downloads without requesting a project write for writer=$writer, development=$development, embedded=$embedded', + async ({ writer, embedded, development }) => { + vi.stubEnv('DEV', development) + + if (embedded) vi.stubGlobal('top', {}) + + const post = vi.fn() + + vi.stubGlobal('fetch', post) + const blobUrl = vi + .spyOn(URL, 'createObjectURL') + .mockReturnValue('blob:layout-sample') + let filename = '' + + vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function ( + this: HTMLAnchorElement, + ) { + filename = this.download + }) + const wrapper = await mountDesigner(writer) + + try { + const button = wrapper.get('.layout-designer__project button') + + expect(button.text()).toBe('download') + await button.trigger('click') + expect(filename).toBe('my-workspace.layout.tsx') + const [blob] = blobUrl.mock.calls[0] + + expect.assert(blob instanceof Blob) + expect(await blob.text()).toBe( + generateLayoutSource({ + id: 'my-workspace', + label: 'defaultName', + selectable: true, + rows: [], + }), + ) + expect(post).not.toHaveBeenCalled() + } finally { + wrapper.unmount() + } + }, +) diff --git a/__test__/layout/layout-generator-format.spec.ts b/__test__/layout/layout-generator-format.spec.ts new file mode 100644 index 00000000..e2d2c49d --- /dev/null +++ b/__test__/layout/layout-generator-format.spec.ts @@ -0,0 +1,138 @@ +// @vitest-environment node +import { generateLayoutSource } from '@/layout/designer' +import type { LayoutDesign } from '@/layout/designer' +import * as prettier from 'prettier' +import ts from 'typescript' + +it('keeps generated definitions formatted and preserves display names as literal text', async () => { + const path = 'apps/admin/src/layout/definitions/demo.layout.tsx' + const config = await prettier.resolveConfig(path) + const labels = [ + 'My workspace', + 'A'.repeat(80), + '中文布局'.repeat(20), + 'Dana\'s "Design" \\ `label` ${name} 👩‍💻', + 'Left\u2028right\u00a0edge\u0085end', + 'Direction\u2066A\u2069, control\u007f and C1\u009bend', + ['Backslashes', '\\'.repeat(3), '`', '${name}', '"', '\ud800'].join(''), + ] + const arrangements: LayoutDesign['rows'][] = [ + [['tabs']], + [['navigation']], + [['breadcrumb'], ['actions']], + [['actions', 'tabs'], ['navigation']], + [['breadcrumb'], ['actions'], ['tabs'], ['navigation']], + ] + + for (const [index, label] of labels.entries()) { + const design = { + id: 'a'.repeat(64), + label, + rows: arrangements[index % arrangements.length], + selectable: true, + } + const source = generateLayoutSource(design) + + expect(await prettier.format(source, { ...config, filepath: path })).toBe( + source, + ) + const file = ts.createSourceFile( + path, + source, + ts.ScriptTarget.Latest, + true, + ts.ScriptKind.TSX, + ) + const readLabel = (node: ts.Node): ts.StringLiteralLike | undefined => { + if ( + ts.isPropertyAssignment(node) && + node.name.getText(file) === 'label' && + ts.isStringLiteralLike(node.initializer) + ) { + return node.initializer + } + + return node.forEachChild(readLabel) + } + + const literal = readLabel(file) + + expect.assert(literal) + expect(literal.text).toBe(label) + const normalized = + source.slice(0, literal.getStart(file)) + + '`Baseline`' + + source.slice(literal.end) + + expect(normalized).toBe( + generateLayoutSource({ ...design, label: 'Baseline' }), + ) + expect(source).not.toMatch(/[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/u) + } +}) + +it.each(['none', 'left', 'right'] as const)( + 'renders only the requested sidebar and footer for %s placement', + async (sidebar) => { + const path = 'apps/admin/src/layout/definitions/demo.layout.tsx' + const config = await prettier.resolveConfig(path) + + for (const footer of [false, true]) { + for (const rows of [[], [['tabs']]]) { + const design = { + id: 'layout-demo', + label: 'Layout', + selectable: true, + rows, + sidebar, + footer, + } + + const source = generateLayoutSource(design) + + expect( + await prettier.format(source, { ...config, filepath: path }), + ).toBe(source) + expect(source.includes('header: () =>')).toBe(rows.length > 0) + expect(source.includes('footer: () => ')).toBe(footer) + + if (sidebar === 'none') { + expect(source).not.toContain('LayoutNavigation') + expect(source).not.toContain('sidebarPlacement') + } else { + expect(source).toContain(`sidebarPlacement="${sidebar}"`) + expect(source).toContain( + sidebar === 'right' + ? '' + : '', + ) + } + } + } + }, +) + +it('preserves top and bottom row order in the preview and renderer', async () => { + const path = 'apps/admin/src/layout/definitions/demo.layout.tsx' + const config = await prettier.resolveConfig(path) + const source = generateLayoutSource({ + id: 'bottom-layout', + label: 'Bottom', + selectable: true, + rows: [['breadcrumb']], + bottomRows: [['navigation'], ['actions', 'tabs']], + sidebar: 'right', + footer: true, + }) + + expect(await prettier.format(source, { ...config, filepath: path })).toBe( + source, + ) + expect(source).toContain("rows: [['breadcrumb']]") + expect(source).toContain("bottomRows: [['navigation'], ['actions', 'tabs']]") + expect(source).toContain("sidebar: 'right'") + expect(source).toContain('footer: true') + expect(source).toMatch( + /bottom: \(\) => \([\s\S]*[\s\S]*\s+/, + ) +}) diff --git a/__test__/layout/layout-picker.spec.ts b/__test__/layout/layout-picker.spec.ts new file mode 100644 index 00000000..ce445042 --- /dev/null +++ b/__test__/layout/layout-picker.spec.ts @@ -0,0 +1,88 @@ +import { + LayoutSettings, + type LayoutConfig, + type LayoutPreview, +} from '@ray-template/admin-shell' +import { mount } from '@vue/test-utils' + +const layout: LayoutConfig = { + mode: 'side', + contentWidth: 'fluid', + contentMaxWidth: 1200, + contentPadding: 16, + fixedHeader: true, + fixedFooter: true, +} + +const props = { + layout, + defaults: layout, + translate: (key: string) => key, +} + +it('draws the registered rows, sidebar and bottom blocks in reading order', async () => { + const preview: LayoutPreview = { + rows: [['actions', 'breadcrumb']], + bottomRows: [['tabs', 'navigation']], + sidebar: 'right', + } + const onSelect = vi.fn() + const wrapper = mount(LayoutSettings, { + props: { + ...props, + update: vi.fn(), + onSelect, + selectedId: 'workspace', + choices: [{ id: 'workspace', label: 'Workspace', preview }], + }, + }) + + try { + const choice = wrapper.get('button[aria-label="Workspace"]') + const diagram = choice.get('.r-layout-preview__main') + const rows = diagram.findAll('.r-layout-preview__row') + + expect(choice.attributes('aria-pressed')).toBe('true') + expect(diagram.element.nextElementSibling?.className).toBe( + 'r-layout-preview__aside', + ) + expect(rows[0].element.firstElementChild?.className).toBe( + 'r-layout-preview__actions', + ) + expect(rows[1].element.previousElementSibling?.className).toBe( + 'r-layout-preview__body', + ) + expect(rows[1].element.lastElementChild?.className).toBe( + 'r-layout-preview__navigation', + ) + expect(diagram.find('.r-layout-preview__footer').exists()).toBe(false) + await choice.trigger('click') + expect(onSelect).toHaveBeenCalledWith('workspace') + } finally { + wrapper.unmount() + } +}) + +it('retains the built-in mode selector when no registry choices are supplied', async () => { + const update = vi.fn() + const wrapper = mount(LayoutSettings, { props: { ...props, update } }) + + try { + const button = wrapper.get('button[aria-label="split"]') + + expect( + button.findAll('.r-layout-preview > .r-layout-preview__row'), + ).toHaveLength(2) + expect( + button + .get('.r-layout-preview__main') + .find('.r-layout-preview__tabs') + .exists(), + ).toBe(true) + expect(button.find('.r-layout-preview__footer').exists()).toBe(true) + await button.trigger('click') + expect(update).toHaveBeenCalledWith({ mode: 'split' }) + } finally { + wrapper.unmount() + } +}) diff --git a/__test__/layout/layout-registry.spec.ts b/__test__/layout/layout-registry.spec.ts new file mode 100644 index 00000000..a149391b --- /dev/null +++ b/__test__/layout/layout-registry.spec.ts @@ -0,0 +1,271 @@ +import { APP_CATCH_KEY } from '@/app-config' +import { collectLayoutDefinitions, discoveredLayouts } from '@/layout/discovery' +import type { LayoutDefinition } from '@/layout/types' +import { useLayout } from '@/layout/useLayout' +import { piniaSettingStore } from '@/store/modules/setting' +import { createPinia, disposePinia, setActivePinia } from 'pinia' +import piniaPluginPersistedstate from 'pinia-plugin-persistedstate' +import { createApp, defineComponent, shallowReactive, watch } from 'vue' + +const component = defineComponent({ render: () => null }) +const definition = (id: string): LayoutDefinition => ({ + id, + label: id, + component, +}) + +function mountWorkspace() { + const pinia = createPinia().use(piniaPluginPersistedstate) + + createApp(component).use(pinia) + setActivePinia(pinia) + const layout = useLayout() + const settings = piniaSettingStore() + + return { layout, settings, dispose: () => disposePinia(pinia) } +} + +const key = APP_CATCH_KEY.appPiniaSettingStore + +beforeEach(() => localStorage.removeItem(key)) +afterEach(() => localStorage.removeItem(key)) + +it('discovers built-ins and custom-top and isolates explicitly registered layouts per application', () => { + const first = mountWorkspace() + const second = mountWorkspace() + + try { + expect(first.layout.layouts.value.slice(0, 5).map(({ id }) => id)).toEqual([ + 'side', + 'top', + 'mixed', + 'right', + 'split', + ]) + expect( + first.layout.layouts.value.some(({ id }) => id === 'custom-top'), + ).toBe(true) + + first.layout.registerLayout({ + ...definition('private-workspace'), + autoRegister: false, + }) + expect(first.layout.activeLayoutId.value).toBe('side') + expect(first.layout.updateLayout('private-workspace')).toBe(true) + expect(second.layout.updateLayout('private-workspace')).toBe(false) + expect(() => first.layout.registerLayout(definition('side'))).toThrow( + /Duplicate/, + ) + expect(() => + first.layout.registerLayout(definition('invalid/name')), + ).toThrow(/ID/) + } finally { + first.dispose() + second.dispose() + } +}) + +it('retains the active layout when selection closes and prevents entry through code or cache restoration', () => { + const first = mountWorkspace() + const custom = shallowReactive({ + ...definition('optional'), + selectable: true, + }) + + first.layout.registerLayout(custom) + expect(first.layout.updateLayout('optional')).toBe(true) + expect(first.layout.activeLayoutId.value).toBe('optional') + custom.selectable = false + expect(first.layout.activeLayoutId.value).toBe('optional') + first.settings.$persist() + + const second = mountWorkspace() + + try { + second.layout.registerLayout(custom) + expect(second.layout.activeLayoutId.value).toBe('side') + expect(second.layout.updateLayout('optional')).toBe(false) + expect(first.layout.updateLayout('top')).toBe(true) + expect(first.layout.updateLayout('optional')).toBe(false) + expect(first.layout.activeLayoutId.value).toBe('top') + } finally { + first.dispose() + second.dispose() + } +}) + +it('uses the declared structure for discovered and explicitly registered previews', () => { + const workspace = mountWorkspace() + const preview = { + rows: [['tabs' as const]], + bottomRows: [['actions' as const]], + sidebar: 'right' as const, + footer: true, + } + + try { + workspace.layout.registerLayout({ ...definition('test-preview'), preview }) + const entries = workspace.layout.layouts.value + const registered = entries.find(({ id }) => id === 'test-preview')! + + expect(registered.preview).toMatchObject(preview) + preview.rows[0].pop() + expect(registered.preview?.rows).toEqual([['tabs']]) + expect( + entries.find(({ id }) => id === 'custom-top')?.preview?.rows, + ).toEqual([['tabs', 'actions'], ['navigation']]) + expect( + entries.find(({ id }) => id === 'split')?.preview?.wideHeaderRows, + ).toBe(2) + expect(() => + workspace.layout.registerLayout({ + ...definition('invalid-span'), + preview: { ...preview, rows: [['tabs']], wideHeaderRows: 2 }, + }), + ).toThrow() + } finally { + workspace.dispose() + } +}) + +it('restores a late registration only while its saved ID is still selected', () => { + localStorage.setItem( + key, + JSON.stringify({ + customLayoutId: 'late-entry', + layoutConfig: { mode: 'right' }, + }), + ) + const { layout, settings, dispose } = mountWorkspace() + + try { + expect(layout.selectedLayoutId.value).toBe('late-entry') + expect(layout.activeLayoutId.value).toBe('side') + layout.registerLayout(definition('late-entry')) + expect(layout.activeLayoutId.value).toBe('late-entry') + + settings.updateSettingState('layoutConfig', { contentPadding: 11 }) + expect(layout.activeLayoutId.value).toBe('late-entry') + settings.updateSettingState('layoutConfig', { mode: 'right' }) + expect(layout.activeLayoutId.value).toBe('right') + expect(settings.customLayoutId).toBeNull() + } finally { + dispose() + } + + localStorage.setItem(key, JSON.stringify({ customLayoutId: 'late-entry' })) + const next = mountWorkspace() + + try { + next.layout.updateLayout('top') + next.layout.registerLayout(definition('late-entry')) + expect(next.layout.activeLayoutId.value).toBe('top') + } finally { + next.dispose() + } +}) + +it('round-trips a custom selection in browser storage and maps preference v1 to its built-in mode', () => { + const first = mountWorkspace() + + first.layout.updateLayout('custom-top') + const file = first.settings.exportPreferences() + + expect(file.version).toBe(1) + expect(file.preferences.layoutConfig.mode).toBe('top') + expect(file.preferences).not.toHaveProperty('customLayoutId') + first.settings.$persist() + first.dispose() + + const next = mountWorkspace() + + try { + expect(next.layout.activeLayoutId.value).toBe('custom-top') + next.settings.importPreferences(JSON.stringify(file)) + expect(next.layout.activeLayoutId.value).toBe('top') + expect(next.settings.customLayoutId).toBeNull() + } finally { + next.dispose() + } +}) + +it('reconciles discovered files for a mounted workspace without discarding manual registrations', () => { + const original = discoveredLayouts.value + const workspace = mountWorkspace() + + try { + workspace.layout.registerLayout(definition('manual-entry')) + const fresh = new Map(original) + + fresh.set('generated-layout', definition('generated-layout')) + discoveredLayouts.value = fresh + expect(workspace.layout.updateLayout('generated-layout')).toBe(true) + expect(workspace.layout.activeLayoutId.value).toBe('generated-layout') + discoveredLayouts.value = original + expect(workspace.layout.updateLayout('generated-layout')).toBe(false) + expect(workspace.layout.activeLayoutId.value).toBe('side') + expect(workspace.layout.updateLayout('manual-entry')).toBe(true) + } finally { + discoveredLayouts.value = original + workspace.dispose() + } +}) + +it('normalizes malformed cached IDs and keeps synchronous observers on the selected layout', () => { + localStorage.setItem( + key, + JSON.stringify({ + customLayoutId: { id: 'broken' }, + layoutConfig: { mode: 'mixed' }, + }), + ) + const workspace = mountWorkspace() + + try { + expect(workspace.settings.customLayoutId).toBeNull() + const seen: string[] = [] + const stop = watch( + workspace.layout.selectedLayoutId, + (id) => seen.push(id), + { flush: 'sync' }, + ) + + workspace.layout.updateLayout('custom-top') + workspace.layout.updateLayout('right') + stop() + expect(seen).toEqual(['custom-top', 'right']) + } finally { + workspace.dispose() + } +}) + +it('skips closed auto-registration and detects duplicate definitions without dropping valid siblings', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => void 0) + + try { + const catalog = collectLayoutDefinitions({ + './definitions/other.layout.ts': definition('side'), + './definitions/side.layout.ts': { + ...definition('side'), + label: 'Built-in', + }, + './definitions/hidden.layout.js': { + ...definition('hidden'), + autoRegister: false, + }, + './definitions/closed.layout.tsx': { + ...definition('closed'), + selectable: false, + }, + }) + + expect([...catalog.keys()]).toEqual(['side', 'closed']) + expect(catalog.get('side')?.label).toBe('Built-in') + expect(report).toHaveBeenCalledExactlyOnceWith( + '[useLayout] ./definitions/other.layout.ts', + expect.any(Error), + ) + } finally { + report.mockRestore() + } +}) diff --git a/__test__/layout/layout-writer.spec.ts b/__test__/layout/layout-writer.spec.ts new file mode 100644 index 00000000..5620fed4 --- /dev/null +++ b/__test__/layout/layout-writer.spec.ts @@ -0,0 +1,233 @@ +// @vitest-environment node +import { + mkdir, + mkdtemp, + readdir, + readFile, + rm, + writeFile, +} from 'node:fs/promises' +import type { IncomingMessage, ServerResponse } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Readable } from 'node:stream' +import { createServer } from 'vite' +import type { ViteDevServer } from 'vite' +import { + generateLayoutSource, + layoutDefinitionsDirectory, + layoutWriteEndpoint, + parseLayoutDesign, +} from '../../apps/admin/src/layout/designer' +import { layoutWriterPlugin } from '../../vite-helper/layout-writer' + +const design = { + id: 'lab-top', + label: 'Research "A"', + selectable: false, + rows: [['tabs', 'actions'], ['navigation']], +} + +it('renders a standalone definition using only the selected bricks in row order', () => { + const source = generateLayoutSource(design) + + expect(source).toContain('selectable: false') + expect(source).toContain('autoRegister: true') + expect(source).toContain('sharedFrame: true') + expect(source).not.toContain('LayoutBreadcrumb') + expect(source.match(//g)).toHaveLength(2) + expect(source).toMatch( + /\s+\s+<\/LayoutRow>\s+\s+/, + ) + expect(source.match(//g)).toHaveLength(1) +}) + +it('validates file identifiers, labels, block names and uniqueness before generating code', () => { + for (const invalid of [ + { id: 'lab/test' }, + { id: 'a'.repeat(65) }, + { label: ' ' }, + { source: 'arbitrary text' }, + { rows: [[]] }, + { rows: [['footer']] }, + { rows: [['tabs'], ['tabs']] }, + { bottomRows: [['tabs']] }, + { bottomRows: [['invalid']] }, + ]) + expect(() => parseLayoutDesign({ ...design, ...invalid })).toThrow() +}) + +type Middleware = ( + req: IncomingMessage, + res: ServerResponse, + next: () => void, +) => Promise + +function handler(root: string, vite?: ViteDevServer) { + let middleware: Middleware + const configure = layoutWriterPlugin(root).configureServer as ( + server: ViteDevServer, + ) => void + + configure({ + environments: vite?.environments ?? { + client: { moduleGraph: { getModuleByUrl: async () => void 0 } }, + }, + config: vite?.config ?? { mode: 'development', isProduction: false }, + middlewares: { + use: (fn: Middleware) => { + middleware = fn + }, + }, + } as unknown as ViteDevServer) + + return async ( + data = JSON.stringify(design), + headers: Record = {}, + peer = '127.0.0.1', + ) => { + const req = Object.assign(Readable.from([Buffer.from(data)]), { + socket: { remoteAddress: peer }, + url: layoutWriteEndpoint, + method: 'POST', + headers: { + host: 'localhost:9527', + origin: 'http://localhost:9527', + 'content-type': 'application/json', + 'x-ray-layout-write': '1', + ...headers, + }, + }) + let status = 0 + let body = '' + + await middleware( + req as unknown as IncomingMessage, + { + writeHead(value: number) { + status = value + }, + end(value: string) { + body = value + }, + } as ServerResponse, + () => { + throw new Error('unexpected route') + }, + ) + + return { status, ...JSON.parse(body) } as { + status: number + path?: string + error?: string + } + } +} + +it.each([ + { mode: 'production', isProduction: false }, + { mode: 'development', isProduction: true }, +])( + 'omits the file writer when serving a production configuration', + (config) => { + const use = vi.fn() + const configure = layoutWriterPlugin('.').configureServer as ( + server: ViteDevServer, + ) => void + + configure({ config, middlewares: { use } } as unknown as ViteDevServer) + expect(use).not.toHaveBeenCalled() + }, +) + +it('publishes one complete source file, rejects collisions and restricts local writes', async () => { + const root = await mkdtemp(join(tmpdir(), 'ray-layout-lab-')) + const directory = join(root, layoutDefinitionsDirectory) + const post = handler(root) + + try { + await mkdir(directory, { recursive: true }) + + const restricted: Record[] = [ + { origin: 'http://localhost:8000' }, + { origin: '' }, + { 'x-ray-layout-write': '' }, + { 'content-type': 'text/plain' }, + ] + + for (const headers of restricted) + expect((await post(void 0, headers)).status).toBe(403) + + expect((await post(void 0, {}, '192.0.2.10')).status).toBe(403) + expect((await post('x'.repeat(8193))).status).toBe(413) + expect((await post(JSON.stringify({ ...design, id: 'a/b' }))).status).toBe( + 400, + ) + expect(await readdir(directory)).toEqual([]) + + const results = await Promise.all([post(), post()]) + + expect(results.map(({ status }) => status).sort()).toEqual([201, 409]) + expect(results.find(({ status }) => status === 201)?.path).toBe( + `${layoutDefinitionsDirectory}/lab-top.layout.tsx`, + ) + expect(await readdir(directory)).toEqual(['lab-top.layout.tsx']) + expect(await readFile(join(directory, 'lab-top.layout.tsx'), 'utf8')).toBe( + generateLayoutSource(design), + ) + + await writeFile(join(directory, 'existing.layout.js'), '// user source') + expect( + (await post(JSON.stringify({ ...design, id: 'existing' }))).status, + ).toBe(409) + } finally { + await rm(root, { recursive: true, force: true }) + } +}) + +it('refreshes the active Vite glob and sends HMR even with filesystem watching disabled', async () => { + const root = await mkdtemp(join(tmpdir(), 'ray-layout-catalog-')) + const directory = join(root, layoutDefinitionsDirectory) + const source = '/src/layout/discovery.ts' + let vite: ViteDevServer | undefined + + try { + await mkdir(directory, { recursive: true }) + await writeFile( + join(directory, '..', 'discovery.ts'), + [ + "export const layouts = Object.keys(import.meta.glob('./definitions/*.layout.tsx'))", + 'if (import.meta.hot) import.meta.hot.accept()', + ].join('\n'), + ) + vite = await createServer({ + configFile: false, + root: join(root, 'apps/admin'), + envFile: false, + logLevel: 'silent', + optimizeDeps: { noDiscovery: true, include: [] }, + server: { middlewareMode: true, watch: null, ws: false }, + }) + + const client = vite.environments.client + + expect((await client.transformRequest(source))?.code).not.toContain( + 'lab-top.layout.tsx', + ) + const send = vi.spyOn(client.hot, 'send') + + expect((await handler(root, vite)()).status).toBe(201) + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ + type: 'update', + updates: [expect.objectContaining({ type: 'js-update', path: source })], + }), + ) + expect((await client.transformRequest(source))?.code).toContain( + 'lab-top.layout.tsx', + ) + } finally { + await vite?.close() + await rm(root, { recursive: true, force: true }) + } +}) diff --git a/__test__/layout/menu-settings.spec.tsx b/__test__/layout/menu-settings.spec.tsx index 202ebb63..3822f317 100644 --- a/__test__/layout/menu-settings.spec.tsx +++ b/__test__/layout/menu-settings.spec.tsx @@ -1,9 +1,10 @@ +import { LAYOUT_SIDER_REF } from '@/app-config' import CustomMenu from '@/layout/components/SiderBar/components/SettingDrawer/segment-views/CustomMenu' import { piniaSettingStore } from '@/store/modules/setting' import { getDefaultSettingConfig } from '@/store/modules/setting/constant' -import type { AppMenuOption } from '@/types' import { flushPromises, mount } from '@vue/test-utils' import type { VueWrapper } from '@vue/test-utils' +import type { LayoutInst } from 'naive-ui' import { NButton } from 'naive-ui' import { createPinia, disposePinia, setActivePinia } from 'pinia' import { nextTick, ref } from 'vue' @@ -12,8 +13,7 @@ import type { Ref } from 'vue' const state = vi.hoisted(() => ({ collapsed: null as unknown as Ref, smaller: null as unknown as Ref, - options: null as unknown as Ref, - menuKey: null as unknown as Ref, + refresh: vi.fn(), collapse: vi.fn(), scroll: vi.fn(), @@ -35,8 +35,6 @@ vi.mock('@/store', async () => { ...settings, useMenuGetters: () => ({ getCollapsed: state.collapsed, - getMenuOptions: state.options, - getMenuKey: state.menuKey, }), useMenuActions: () => ({ setupAppMenu: state.refresh, @@ -52,8 +50,9 @@ beforeEach(() => { vi.clearAllMocks() state.collapsed = ref(false) state.smaller = ref(false) - state.options = ref([]) - state.menuKey = ref('/reports') + const sider = LAYOUT_SIDER_REF as Ref + + sider.value = null state.refresh.mockResolvedValue(void 0) vi.stubGlobal('$message', { success: state.success, error: state.error }) pinia = createPinia() @@ -92,40 +91,14 @@ it('applies size presets without replacing menu behavior or layout preferences', }) it('enables sidebar actions only when the active desktop layout has a sidebar', async () => { - const settings = piniaSettingStore() + const sider = LAYOUT_SIDER_REF as Ref - await button('menu.collapse').trigger('click') - expect(state.collapse).toHaveBeenCalledExactlyOnceWith(true) - settings.updateSettingState('layoutConfig', { mode: 'top' }) - await nextTick() expect(button('menu.collapse').props('disabled')).toBe(true) expect(button('menu.scrollTop').props('disabled')).toBe(true) - settings.updateSettingState('layoutConfig', { mode: 'mixed' }) - await nextTick() - expect(button('menu.collapse').props('disabled')).toBe(true) - state.options.value = [ - { - fullPath: '/reports', - path: '/reports', - name: 'Reports', - label: 'Reports', - key: '/reports', - meta: {}, - show: true, - children: [ - { - fullPath: '/reports/daily', - path: '/reports/daily', - name: 'Daily', - label: 'Daily', - key: '/reports/daily', - meta: {}, - show: true, - }, - ], - }, - ] + sider.value = { scrollTo: state.scroll } as unknown as LayoutInst await nextTick() + await button('menu.collapse').trigger('click') + expect(state.collapse).toHaveBeenCalledExactlyOnceWith(true) expect(button('menu.collapse').props('disabled')).toBe(false) await button('menu.scrollTop').trigger('click') expect(state.scroll).toHaveBeenCalledExactlyOnceWith({ diff --git a/__test__/layout/slots.spec.ts b/__test__/layout/slots.spec.ts index cec7dc9d..d948ee31 100644 --- a/__test__/layout/slots.spec.ts +++ b/__test__/layout/slots.spec.ts @@ -1,12 +1,51 @@ -import { shallowMount } from '@vue/test-utils' +import { flushPromises, mount, shallowMount } from '@vue/test-utils' import { createPinia, disposePinia, setActivePinia } from 'pinia' -import { h, nextTick } from 'vue' +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' -it('lets a custom header replace the complete default header and top navigation', () => { +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) @@ -14,12 +53,13 @@ it('lets a custom header replace the complete default header and top navigation' const options = { global: { renderStubDefaultSlot: true, - stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, + 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, { @@ -30,6 +70,7 @@ it('lets a custom header replace the complete default header and top navigation' }) try { + await nextTick() expect(custom.find('[data-test="custom-header"]').exists()).toBe(true) expect(custom.find('top-navigation-stub').exists()).toBe(false) } finally { @@ -47,7 +88,7 @@ it('offers a restore button for custom content and also exits with Escape', asyn attachTo: document.body, global: { renderStubDefaultSlot: true, - stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, + stubs: liveShell, plugins: [router, pinia], }, slots: { @@ -56,6 +97,7 @@ it('offers a restore button for custom content and also exits with Escape', asyn }) try { + await nextTick() expect(wrapper.find('.r-layout-content-restore__button').exists()).toBe( false, ) @@ -77,7 +119,111 @@ it('offers a restore button for custom content and also exits with Escape', asyn } }) -it('moves the full navigation to the right without adding a second menu', () => { +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({ + 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) @@ -85,12 +231,13 @@ it('moves the full navigation to the right without adding a second menu', () => const wrapper = shallowMount(Layout, { global: { renderStubDefaultSlot: true, - stubs: { RayAdminShell: false, NLayout: false, NLayoutContent: false }, + 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 { @@ -98,3 +245,327 @@ it('moves the full navigation to the right without adding a second menu', () => 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: '' }), + }, + }) + + 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) + } + }, +) diff --git a/__test__/workspace/lint-fix.spec.ts b/__test__/workspace/lint-fix.spec.ts new file mode 100644 index 00000000..27c7eb6e --- /dev/null +++ b/__test__/workspace/lint-fix.spec.ts @@ -0,0 +1,72 @@ +// @vitest-environment node + +import { spawnSync } from 'node:child_process' +import { + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +let fixture: string + +beforeEach(() => { + fixture = mkdtempSync(join(tmpdir(), 'ray-lint-fix-')) + writeFileSync( + join(fixture, 'eslint.config.mjs'), + "export default [{ rules: { 'no-var': 'error', 'no-undef': 'error' } }]\n", + ) +}) + +afterEach(() => rmSync(fixture, { recursive: true, force: true })) + +function run(script: string, ...args: string[]) { + const entry = fileURLToPath( + new URL(`../../scripts/${script}.mjs`, import.meta.url), + ) + + return spawnSync(process.execPath, [entry, ...args], { + cwd: fixture, + encoding: 'utf8', + }) +} + +it('limits explicit lint fixes to named files and defaults to the workspace', () => { + const selected = join(fixture, 'selected file.mjs') + const sibling = join(fixture, 'sibling.mjs') + + writeFileSync(selected, 'var value=1\n') + writeFileSync(sibling, 'var value=1\n') + + const scoped = run('lint-fix', '--', selected) + + expect(scoped.status, scoped.stderr).toBe(0) + expect(readFileSync(selected, 'utf8')).toBe('let value=1\n') + expect(readFileSync(sibling, 'utf8')).toBe('var value=1\n') + + const workspace = run('lint-fix') + + expect(workspace.status, workspace.stderr).toBe(0) + expect(readFileSync(sibling, 'utf8')).toBe('let value=1\n') +}) + +it('formats the selected directory and reports remaining lint errors', () => { + const scope = join(fixture, 'module') + const source = join(scope, 'source.mjs') + const sibling = join(fixture, 'sibling.mjs') + + mkdirSync(scope) + writeFileSync(source, 'var value=missing\n') + writeFileSync(sibling, 'var value=1\n') + + const result = run('fix', 'module') + + expect(result.status, result.stderr).toBe(1) + expect(result.stdout).toContain('no-undef') + expect(readFileSync(source, 'utf8')).toBe('let value = missing;\n') + expect(readFileSync(sibling, 'utf8')).toBe('var value=1\n') +}) diff --git a/apps/admin/src/documentation-example.tsx b/apps/admin/src/documentation-example.tsx index 1d9750b7..d4e9e7b9 100644 --- a/apps/admin/src/documentation-example.tsx +++ b/apps/admin/src/documentation-example.tsx @@ -40,6 +40,7 @@ const examplePaths = new Set([ '/draggable-card', '/svg-icons', '/directive', + '/layout-demo', '/template-hooks', '/web-hooks', '/multi', diff --git a/apps/admin/src/layout/README.md b/apps/admin/src/layout/README.md index 74de5a7f..e33d35a3 100644 --- a/apps/admin/src/layout/README.md +++ b/apps/admin/src/layout/README.md @@ -18,6 +18,22 @@ Interactions draw on [Vben layout preferences](https://doc.vben.pro/en/guide/essentials/settings.html), reusing existing Naive UI components without a second layout framework. +## Layout definitions and the designer + +The authenticated workspace loads `useLayout` from `@/layout/api`. Each Pinia instance owns its registry. Put a default-exported `LayoutDefinition` in `apps/admin/src/layout/definitions/.layout.tsx` (JS, JSX and TS entries are also supported). Use a stable lowercase kebab-case ID. Definitions can contain their renderer or import it from a sibling module. The five built-in definitions share navigation and frame components. The `custom-top` example composes tabs and header actions in one row above top navigation. + +Use `registerLayout(definition)` for an explicitly installed module and `updateLayout(id)` to select a registered layout. Both `autoRegister` and `selectable` default to true. A definition with `autoRegister: false` requires explicit registration. The picker and programmatic selection respect `selectable`. The saved custom ID and the built-in fallback mode serve desktop restoration and v1 preference-file portability respectively. Updating only spacing or width preserves the selected definition. + +Provide an optional `preview` to describe the settings thumbnail. For example, `{ rows: [['breadcrumb', 'actions']], bottomRows: [['tabs']], sidebar: 'right', footer: true }` places the breadcrumb and actions above the content and tabs below it. Rows also support `navigation`. Use `sidebar` to place navigation on the left or right, or set it to `none`. Set `wideHeaderRows` to the number of leading rows that span both the content and the sidebar. A definition without preview metadata uses its built-in fallback thumbnail. The designer generates this metadata from the same arrangement as its TSX renderer. + +Compose renderers with `LayoutFrame`, `LayoutRow`, `LayoutTabs`, `LayoutHeaderActions`, `LayoutBreadcrumb`, `LayoutTopNavigation` and `LayoutFooter` from `@/layout/blocks`. A frame provides the page outlet by default. When composing your own content region, render exactly one `LayoutOutlet`. The application host keeps routed pages and their cache mounted as presentation changes. The compact breakpoint uses the full-menu drawer. + +Built-in and generated layouts declare `sharedFrame: true` because their root is always a direct `LayoutFrame` with its standard page outlet. Omit this flag for layouts with an outer DOM wrapper, local providers or a custom content region. A frame or outlet with a template ref, directive, transition or scoped root style also needs its own DOM node. Browsers with state-preserving DOM moves can transfer an active iframe to a different outlet immediately. On other browsers the host keeps the visible layout and its iframe until the embedded content closes or the page reloads, then applies the most recent selection. An ordinary route change can release the iframe. Layouts sharing the existing frame can switch immediately. An encapsulated web component with a closed shadow root can mark its host with `data-layout-preserve-embed` while its embedded document is active. + +The lab generates a TSX definition from rows above and below the routed page, sidebar placement and an optional footer. The frame's `bottom` slot hosts rows below the page regardless of copyright visibility. Desktop users can try the draft around the current page and keep editing. Ending the preview or leaving the lab restores the selected layout. + +Opening the lab as a top-level page on the loopback Vite development server enables create-only writes to the definitions directory. Production, remote and embedded previews download the same source. The writer validates a declarative draft and generates the source on the server. Discovery imports matching modules before applying registration flags, so review external TSX as executable project source before placing it in this directory. Changes to deployed layout definitions take effect in the next build. + ## Configuration and extension ```tsx @@ -34,7 +50,7 @@ updateSettingState('layoutConfig', { Configuration belongs to the `setting` store and retains its persistence key. Historical caches receive defaults and normalized ranges without clearing user preferences. `src/store/modules/setting/constant.ts` owns defaults. Restoring the default layout resets only `layoutConfig`. -The settings drawer keeps its five layout previews in one row, scrolling horizontally if needed. Bottom controls export layout, appearance, menu, watermark, and general preferences as `ray-template-preferences.json`, or import the same format. Files must pass version/field validation before applying in the current browser; no reload is required. Login, lock-screen, route configuration, and page-cache data are excluded. +The settings drawer lists the registered layouts and marks unavailable choices as disabled. Bottom controls export layout, appearance, menu, watermark, and general preferences as `ray-template-preferences.json`, or import the same format. Files must pass version/field validation before applying in the current browser; no reload is required. Login, lock-screen, route configuration, and page-cache data are excluded. Use named slots to replace regions: @@ -56,4 +72,4 @@ Layout scroll references remain `LAYOUT_CONTENT_REF` for content and `LAYOUT_SID ## Style ownership -`index.scss` owns the shell, content scrolling, and maximization. Top navigation, menus, tabs, and loading-state styles stay with their components. The settings drawer and layout lab share `LayoutSettings` and `LayoutSettings.scss`. Thumbnails within square option cards indicate navigation placement; text below explains menu behavior. Card groups reserve space for keyboard focus outlines, and `aria-pressed` represents selection. +`index.scss` owns the shell, content scrolling, and maximization. Top navigation, menus, tabs, and loading-state styles stay with their components. The settings drawer and layout lab share `LayoutSettings` and `LayoutSettings.scss`. Responsive option cards show the registered layout structure. Long names wrap and expand the card height. Card groups reserve space for keyboard focus outlines, and `aria-pressed` represents selection. diff --git a/apps/admin/src/layout/api.ts b/apps/admin/src/layout/api.ts new file mode 100644 index 00000000..d8fc0cd4 --- /dev/null +++ b/apps/admin/src/layout/api.ts @@ -0,0 +1,3 @@ +export { useLayout } from './useLayout' +export type { LayoutDefinition } from './types' +export * from './blocks' diff --git a/apps/admin/src/layout/blocks/LayoutBreadcrumb.tsx b/apps/admin/src/layout/blocks/LayoutBreadcrumb.tsx new file mode 100644 index 00000000..076fe74c --- /dev/null +++ b/apps/admin/src/layout/blocks/LayoutBreadcrumb.tsx @@ -0,0 +1,11 @@ +import { useSettingGetters } from '@/store' +import Breadcrumb from '../components/SiderBar/components/Breadcrumb' + +export default defineComponent({ + name: 'LayoutBreadcrumb', + setup() { + const { getBreadcrumbSwitch } = useSettingGetters() + + return () => getBreadcrumbSwitch.value && + }, +}) diff --git a/apps/admin/src/layout/blocks/LayoutFooter.tsx b/apps/admin/src/layout/blocks/LayoutFooter.tsx new file mode 100644 index 00000000..4ee413bb --- /dev/null +++ b/apps/admin/src/layout/blocks/LayoutFooter.tsx @@ -0,0 +1,11 @@ +import { useSettingGetters } from '@/store' +import FooterWrapper from '../default/FooterWrapper' + +export default defineComponent({ + name: 'LayoutFooter', + setup() { + const { getCopyrightSwitch } = useSettingGetters() + + return () => getCopyrightSwitch.value && + }, +}) diff --git a/apps/admin/src/layout/blocks/LayoutFrame.tsx b/apps/admin/src/layout/blocks/LayoutFrame.tsx new file mode 100644 index 00000000..9020c7ff --- /dev/null +++ b/apps/admin/src/layout/blocks/LayoutFrame.tsx @@ -0,0 +1,155 @@ +import { LAYOUT_CONTENT_REF } from '@/app-config' +import { useI18n, useMaximize } from '@/hooks' +import { useRuntimeGetters, useSettingGetters } from '@/store' +import { AdminShell } from '@ray-template/admin-shell' +import type { PropType, VNode } from 'vue' +import ContentLoading from '../default/ContentWrapper/ContentLoading' +import { layoutFrameKey, layoutHostKey } from '../host-context' +import LayoutPresentation from '../renderers/LayoutPresentation' +import LayoutOutlet from './LayoutOutlet' +import OutletTarget from './OutletTarget' + +// ref、指令、过渡与作用域样式依赖原节点上的 DOM 绑定。 +function hasDomBindings(node: VNode) { + return !!(node.ref || node.dirs || node.transition || node.scopeId) +} + +export default defineComponent({ + name: 'LayoutFrame', + inheritAttrs: false, + props: { + sidebarPlacement: { + type: String as PropType<'left' | 'right'>, + default: 'left', + }, + wideHeader: Boolean, + embedded: Boolean, + }, + setup(props, { attrs, slots }) { + const instance = getCurrentInstance()! + const ancestor = instance.parent + // 渲染器的局部 provide 应继续由原组件树传递。 + const inheritsHostProviders = + !!ancestor && + 'provides' in ancestor && + !!ancestor.provides && + typeof ancestor.provides === 'object' && + Object.hasOwn(ancestor.provides, layoutHostKey) + + provide(layoutFrameKey, true) + const { getLayoutConfig, getMenuTagSwitch, getCopyrightSwitch } = + useSettingGetters() + const { + globalMainLayoutLoad, + layoutContentSpinning, + layoutContentMaximize, + layoutContentMaximizeStyle, + } = useRuntimeGetters() + const host = inject(layoutHostKey) + const { maximize } = useMaximize() + const { t } = useI18n('layout') + + const marker = useTemplateRef('marker') + const inline = ref(false) + const sharedVNode = shallowRef() + const sharedRenderer = () => sharedVNode.value! + const release = () => { + if (host?.sharedFrame.value === sharedRenderer) + host.sharedFrame.value = void 0 + } + const placeFrame = () => { + const element = marker.value + + if (!host || !element) { + release() + + return + } + + // Fragment 可能有多个顶层区域;只有单一根节点可提升,避免吞掉兄弟出口。 + let owner = ancestor + + while (owner && owner.type !== LayoutPresentation) owner = owner.parent + + if ( + element.parentElement === host.frameRoot.value && + owner?.subTree.el === element && + (!host.sharedFrame.value || host.sharedFrame.value === sharedRenderer) + ) + host.sharedFrame.value = sharedRenderer + else { + inline.value = true + release() + } + } + + onMounted(placeFrame) + onUpdated(placeFrame) + onBeforeUnmount(release) + + const renderShell = (content: (() => VNode | VNode[]) | undefined) => { + const overrides = host?.slots + const footer = + slots.footer && getCopyrightSwitch.value + ? (overrides?.footer ?? slots.footer) + : void 0 + + return ( + maximize(false)} + skipContentLabel={t('skipToContent')} + restoreLabel={t('restore')} + > + {{ + header: overrides?.header ?? slots.header, + sidebar: overrides?.sidebar ?? slots.sidebar, + tabs: overrides?.tabs ?? slots.tabs, + footer: () => [slots.bottom?.(), footer?.()], + default: content ?? (() => ), + loading: overrides?.default ? void 0 : () => , + }} + + ) + } + + return () => { + if ( + !host || + props.embedded || + inline.value || + !inheritsHostProviders || + hasDomBindings(instance.vnode) + ) + return renderShell(slots.default) + + const children = slots.default?.() + const child = children?.length === 1 ? children[0] : void 0 + + if ( + children && + (child?.type !== LayoutOutlet || child.props || hasDomBindings(child)) + ) + return renderShell(() => children) + + // 只有宿主的直接子节点能复用滚动容器;带原生外层的布局保留自身位置。 + sharedVNode.value = renderShell(void 0) + + return