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.
This commit is contained in:
XiaoDaiGua-Ray 2026-12-01 17:34:27 +08:00
parent 911c403434
commit 22dfe441e0
No known key found for this signature in database
83 changed files with 5794 additions and 808 deletions

View File

@ -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<typeof createPinia>
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<Component>()
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<HTMLButtonElement>('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)
})

View File

@ -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: '<input>' })
: 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<Component>()
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()
}
},
)

View File

@ -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()
}
},
)

View File

@ -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: () => <LayoutFooter />')).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'
? '<LayoutNavigation end />'
: '<LayoutNavigation />',
)
}
}
}
},
)
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]*<LayoutTopNavigation \/>[\s\S]*<LayoutHeaderActions \/>\s+<LayoutTabs \/>/,
)
})

View File

@ -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()
}
})

View File

@ -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()
}
})

View File

@ -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(/<LayoutRow>/g)).toHaveLength(2)
expect(source).toMatch(
/<LayoutTabs \/>\s+<LayoutHeaderActions \/>\s+<\/LayoutRow>\s+<LayoutRow>\s+<LayoutTopNavigation \/>/,
)
expect(source.match(/<LayoutOutlet \/>/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<void>
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<string, string> = {},
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<string, string>[] = [
{ 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 })
}
})

View File

@ -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<boolean>,
smaller: null as unknown as Ref<boolean>,
options: null as unknown as Ref<AppMenuOption[]>,
menuKey: null as unknown as Ref<string>,
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<LayoutInst | null>
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<LayoutInst | null>
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({

View File

@ -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<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)
@ -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: '<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)
}
},
)

View File

@ -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')
})

View File

@ -40,6 +40,7 @@ const examplePaths = new Set([
'/draggable-card',
'/svg-icons',
'/directive',
'/layout-demo',
'/template-hooks',
'/web-hooks',
'/multi',

View File

@ -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/<id>.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.

View File

@ -0,0 +1,3 @@
export { useLayout } from './useLayout'
export type { LayoutDefinition } from './types'
export * from './blocks'

View File

@ -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 && <Breadcrumb />
},
})

View File

@ -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 && <FooterWrapper />
},
})

View File

@ -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<HTMLElement>('marker')
const inline = ref(false)
const sharedVNode = shallowRef<VNode>()
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 (
<AdminShell
{...attrs}
class={[attrs.class, props.embedded && 'r-layout-embedded']}
layout={getLayoutConfig.value}
sidebarPlacement={slots.sidebar ? props.sidebarPlacement : 'none'}
wideHeader={props.wideHeader}
showTabs={!!slots.tabs && getMenuTagSwitch.value}
showFooter={!!slots.bottom || !!footer}
busy={
!overrides?.default &&
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restoreOnUnmount={false}
restore={() => 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 ?? (() => <OutletTarget />),
loading: overrides?.default ? void 0 : () => <ContentLoading />,
}}
</AdminShell>
)
}
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 <span ref="marker" hidden aria-hidden="true" />
}
},
})

View File

@ -0,0 +1,26 @@
import { useElementSize } from '@vueuse/core'
import { layoutFrameKey } from '../host-context'
import LayoutFrame from './LayoutFrame'
import OutletTarget from './OutletTarget'
export default defineComponent({
name: 'LayoutOutlet',
setup() {
if (inject(layoutFrameKey, false)) return () => <OutletTarget />
const frame = useTemplateRef<InstanceType<typeof LayoutFrame>>('frame')
const { height } = useElementSize(frame)
return () => (
<LayoutFrame
ref="frame"
embedded
style={
height.value
? { '--layout-content-height': `${height.value}px` }
: void 0
}
/>
)
},
})

View File

@ -0,0 +1,6 @@
export default defineComponent({
name: 'LayoutRow',
setup(_, { slots }) {
return () => <div class="r-layout-row">{slots.default?.()}</div>
},
})

View File

@ -0,0 +1,13 @@
import { useSettingGetters } from '@/store'
import MenuTag from '../components/MenuTag'
import { layoutHostKey } from '../host-context'
export default defineComponent({
name: 'LayoutTabs',
setup() {
const { getMenuTagSwitch } = useSettingGetters()
const host = inject(layoutHostKey)
return () => getMenuTagSwitch.value && (host?.slots.tabs?.() ?? <MenuTag />)
},
})

View File

@ -0,0 +1,18 @@
import { layoutHostKey } from '../host-context'
export default defineComponent({
name: 'LayoutOutletTarget',
setup() {
const host = inject(layoutHostKey)
if (!host)
throw new Error('LayoutOutlet requires the application layout host.')
const element = useTemplateRef<HTMLDivElement>('element')
onMounted(() => host.addOutlet(element.value!))
onBeforeUnmount(() => host.removeOutlet(element.value!))
return () => <div ref="element" class="r-layout-outlet" />
},
})

View File

@ -0,0 +1,65 @@
import { AdminShell } from '@ray-template/admin-shell'
import type { LayoutConfig } from '@ray-template/admin-shell'
import { cloneVNode } from 'vue'
import type { PropType } from 'vue'
import { layoutFrameKey, layoutHostKey } from '../host-context'
import OutletTarget from './OutletTarget'
export default defineComponent({
name: 'SharedFrame',
props: {
onFailure: {
type: Function as PropType<(error: unknown) => void>,
required: true,
},
},
setup(props) {
const host = inject(layoutHostKey)!
provide(layoutFrameKey, true)
let lastLayout: LayoutConfig | undefined
let mountedRenderer: typeof host.sharedFrame.value
const markReady = () => {
mountedRenderer = host.sharedFrame.value
}
onMounted(markReady)
onUpdated(markReady)
onErrorCaptured((error) => {
if (!host.sharedFrame.value || mountedRenderer === host.sharedFrame.value)
return
props.onFailure(error)
return false
})
return () => {
const render = host.sharedFrame.value
if (render) {
const frame = render()
lastLayout = frame.props!.layout as LayoutConfig
return cloneVNode(frame, { 'data-shared-layout-frame': '' })
}
if (!lastLayout) return null
// 验证候选布局期间保留同一内容节点,回退时 iframe 的浏览上下文仍在。
return h(
AdminShell,
{
layout: lastLayout,
'data-shared-layout-frame': '',
style: { display: 'none' },
inert: true,
sidebarPlacement: 'none',
restoreOnUnmount: false,
},
{ default: () => <OutletTarget /> },
)
}
},
})

View File

@ -0,0 +1,63 @@
.r-layout-host {
position: fixed;
inset: 0;
display: grid;
grid-template: minmax(0, 1fr) / minmax(0, 1fr);
}
.r-layout-outlet {
display: contents;
}
.r-layout-switch-notice {
position: fixed;
z-index: 4;
inset-inline: 1rem;
inset-block-end: 1rem;
width: fit-content;
max-width: calc(100% - 2rem);
margin: 0 auto;
padding: 8px 14px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface);
color: var(--r-text);
box-shadow: var(--r-shadow-soft);
pointer-events: none;
}
.r-layout-embedded.r-layout-full {
position: relative;
inset: auto;
block-size: 100%;
min-block-size: 0;
}
.r-layout-row {
display: flex;
align-items: center;
min-inline-size: 0;
padding-inline: $layoutRouterViewContainer;
background: var(--r-surface);
color: var(--r-text);
> * {
flex: 1 1 0;
min-inline-size: 0;
}
> .layout-header__actions {
flex: none;
margin-inline-start: auto;
}
> .menu-tag {
--ray-shell-tab-gutter: 0px;
border: 0;
}
&:has(> *) {
min-block-size: $layoutHeaderHeight;
border-block-end: 1px solid var(--r-line);
}
}

View File

@ -0,0 +1,13 @@
import './index.scss'
export { default as LayoutFrame } from './LayoutFrame'
export { default as LayoutOutlet } from './LayoutOutlet'
export { default as LayoutHeader } from '../components/SiderBar'
export { default as LayoutHeaderActions } from '../components/SiderBar/HeaderActions'
export { default as LayoutBreadcrumb } from './LayoutBreadcrumb'
export { default as LayoutTopNavigation } from '../components/TopNavigation'
export { default as LayoutNavigation } from '../components/Menu'
export { default as LayoutTabs } from './LayoutTabs'
export { default as LayoutFooter } from './LayoutFooter'
export { default as LayoutRow } from './LayoutRow'

View File

@ -1,23 +1,59 @@
import { useI18n } from '@/hooks'
import { useSettingActions, useSettingGetters } from '@/store'
import { getDefaultSettingConfig } from '@/store/modules/setting/constant'
import { LayoutSettings } from '@ray-template/admin-shell'
import { LAYOUT_MODES, LayoutSettings } from '@ray-template/admin-shell'
import { layoutHostKey } from '../host-context'
import { useLayout } from '../useLayout'
export default defineComponent({
name: 'LayoutSettings',
props: { showDescription: Boolean },
setup(props) {
const { t } = useI18n('layout')
const { getLayoutConfig } = useSettingGetters()
const { layouts, activeLayoutId, updateLayout } = useLayout()
const { getLayoutConfig, getLocaleLanguage } = useSettingGetters()
const { updateSettingState } = useSettingActions()
const host = inject(layoutHostKey, null)
return () => (
<LayoutSettings
showDescription={props.showDescription}
selectionNotice={
host?.deferredFromId.value ? t('deferredForEmbed') : void 0
}
selectedId={
host?.deferredFromId.value ??
(host?.draftRenderer.value ? '' : activeLayoutId.value)
}
onSelect={(id) => {
if (updateLayout(id) && host) host.draftRenderer.value = void 0
}}
choices={layouts.value.map((definition) => {
const mode = LAYOUT_MODES.find((id) => id === definition.id)
const label =
typeof definition.label === 'string'
? definition.label
: definition.label[
getLocaleLanguage.value === 'zh-CN' ? 'zh-CN' : 'en-US'
]
return {
id: definition.id,
label,
preview:
definition.preview ?? mode ?? definition.fallbackMode ?? 'side',
disabled: definition.selectable === false,
hint: mode ? t(`modeHint.${mode}`) : void 0,
}
})}
layout={getLayoutConfig.value}
defaults={getDefaultSettingConfig().layoutConfig}
translate={t}
update={(value) => updateSettingState('layoutConfig', value)}
update={(value) => {
updateSettingState('layoutConfig', value)
if (value.mode && host) host.draftRenderer.value = void 0
}}
/>
)
},

View File

@ -33,7 +33,7 @@ export default defineComponent({
const { t } = useI18n('layout')
const { getAppTheme, getMenuConfig } = useSettingGetters()
const { getMenuOptions, getCollapsed, getMenuKey } = useMenuGetters()
const { globalDrawerValue } = useRuntimeGetters()
const { globalDrawerValue, layoutContentMaximize } = useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions()
const { isTabletOrSmaller, width } = useDevice({
observer: (isSmaller) => {
@ -71,7 +71,7 @@ export default defineComponent({
const basicMenu = () => (
<NLayoutSider
class={['app-menu__sider', { 'app-menu__sider--end': props.end }]}
{...{ inert: props.inert }}
{...{ inert: props.inert || layoutContentMaximize.value }}
showTrigger={!isTabletOrSmaller.value}
triggerStyle={triggerStyle}
collapsedTriggerStyle={triggerStyle}

View File

@ -16,7 +16,7 @@ import {
useResizeObserver,
useTimeoutFn,
} from '@vueuse/core'
import { NDropdown, NFlex, NLayoutHeader, NScrollbar } from 'naive-ui'
import { NDropdown, NFlex, NScrollbar } from 'naive-ui'
import type { ScrollbarInst } from 'naive-ui'
import { TransitionGroup, useTemplateRef } from 'vue'
import { useTagReorder } from './use-tag-reorder'
@ -499,181 +499,179 @@ export default defineComponent({
} = this
return (
<NLayoutHeader>
<div class="menu-tag">
<NDropdown
class="menu-tag__dropdown"
options={this.moreOptions}
x={this.actionState.x}
y={this.actionState.y}
show={this.actionState.actionDropdownShow}
trigger="manual"
placement="bottom-start"
onSelect={actionDropdownSelect}
onUpdateShow={(show) => {
this.actionState.actionDropdownShow = show
}}
onClickoutside={this.dismissContextMenu}
/>
<NFlex
class="menu-tag-space"
size={4}
wrap={false}
align="center"
justify="space-between"
inline
<div class="menu-tag">
<NDropdown
class="menu-tag__dropdown"
options={this.moreOptions}
x={this.actionState.x}
y={this.actionState.y}
show={this.actionState.actionDropdownShow}
trigger="manual"
placement="bottom-start"
onSelect={actionDropdownSelect}
onUpdateShow={(show) => {
this.actionState.actionDropdownShow = show
}}
onClickoutside={this.dismissContextMenu}
/>
<NFlex
class="menu-tag-space"
size={4}
wrap={false}
align="center"
justify="space-between"
inline
>
<button
type="button"
class="menu-tag__control menu-tag__control--scroll"
aria-label={$t('menuTag.scrollLeft')}
aria-disabled={!this.scrollState.left}
title={$t('menuTag.scrollLeft')}
onClick={() => this.scrollX('left')}
>
<button
type="button"
class="menu-tag__control menu-tag__control--scroll"
aria-label={$t('menuTag.scrollLeft')}
aria-disabled={!this.scrollState.left}
title={$t('menuTag.scrollLeft')}
onClick={() => this.scrollX('left')}
<Chevron direction="left" />
</button>
<NScrollbar
xScrollable
onScroll={this.syncScroll}
ref="scrollRef"
class="menu-tag__scroll"
themeOverrides={{ width: '0px', height: '0px' }}
>
<div
ref="tags"
class="menu-tag-wrapper"
data-menu-tag-sortable={this.getMenuTagDrag ? '' : void 0}
role="group"
aria-label={$t('menuTag.pages')}
onKeydown={this.moveTagWithKey}
>
<Chevron direction="left" />
</button>
<NScrollbar
xScrollable
onScroll={this.syncScroll}
ref="scrollRef"
class="menu-tag__scroll"
themeOverrides={{ width: '0px', height: '0px' }}
>
<div
ref="tags"
class="menu-tag-wrapper"
data-menu-tag-sortable={this.getMenuTagDrag ? '' : void 0}
role="group"
aria-label={$t('menuTag.pages')}
onKeydown={this.moveTagWithKey}
>
<TransitionGroup name="menu-tag" css={false}>
{getMenuTagOptions.map((curr, idx) => {
const active = curr.fullPath === this.getMenuKey
const label = this.tagLabel(curr)
const topped = this.isMenuTagTopped(curr)
const fixed = this.isMenuTagFixed(curr)
const topLabel = topped ? $t('menuTag.topped') : ''
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
<TransitionGroup name="menu-tag" css={false}>
{getMenuTagOptions.map((curr, idx) => {
const active = curr.fullPath === this.getMenuKey
const label = this.tagLabel(curr)
const topped = this.isMenuTagTopped(curr)
const fixed = this.isMenuTagFixed(curr)
const topLabel = topped ? $t('menuTag.topped') : ''
const fixedLabel = fixed ? $t('menuTag.fixed') : ''
return (
<ShellTab
key={curr.fullPath}
label={label}
active={active}
data-menu-tag-path={curr.fullPath}
data-menu-tag-top={topped ? '' : void 0}
statusLabel={
topLabel && fixedLabel
? `${topLabel} · ${fixedLabel}`
: topLabel || fixedLabel
}
round={this.getMenuTagRound}
keyShortcuts={
this.getMenuTagDrag
? 'Shift+ArrowLeft Shift+ArrowRight'
: void 0
}
select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })}
close={
!fixed
? (restoreFocus) =>
closeCurrentMenuTag(idx, restoreFocus)
: void 0
}
contextMenu={(event) =>
menuTagContextMenu(curr.fullPath, event)
}
>
{{
prefix: fixed
? () => (
<RIcon
name="action/pin"
size={14}
aria-hidden="true"
/>
)
: void 0,
}}
</ShellTab>
)
})}
</TransitionGroup>
</div>
</NScrollbar>
<span ref="reorderStatus" class="menu-tag__status" role="status" />
return (
<ShellTab
key={curr.fullPath}
label={label}
active={active}
data-menu-tag-path={curr.fullPath}
data-menu-tag-top={topped ? '' : void 0}
statusLabel={
topLabel && fixedLabel
? `${topLabel} · ${fixedLabel}`
: topLabel || fixedLabel
}
round={this.getMenuTagRound}
keyShortcuts={
this.getMenuTagDrag
? 'Shift+ArrowLeft Shift+ArrowRight'
: void 0
}
select={() => menuTagClick(curr)}
closeLabel={$t('menuTag.closeNamed', { name: label })}
close={
!fixed
? (restoreFocus) =>
closeCurrentMenuTag(idx, restoreFocus)
: void 0
}
contextMenu={(event) =>
menuTagContextMenu(curr.fullPath, event)
}
>
{{
prefix: fixed
? () => (
<RIcon
name="action/pin"
size={14}
aria-hidden="true"
/>
)
: void 0,
}}
</ShellTab>
)
})}
</TransitionGroup>
</div>
</NScrollbar>
<span ref="reorderStatus" class="menu-tag__status" role="status" />
<button
type="button"
class="menu-tag__control menu-tag__control--scroll"
aria-label={$t('menuTag.scrollRight')}
aria-disabled={!this.scrollState.right}
title={$t('menuTag.scrollRight')}
onClick={() => this.scrollX('right')}
>
<Chevron direction="right" />
</button>
<div class="menu-tag__tools">
{this.showingForbidden && (
<button
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.closeCurrent')}
title={$t('menuTag.closeCurrent')}
onClick={(event) => this.closeStatus(event.detail === 0)}
>
<RIcon name="action/close" size={16} aria-hidden="true" />
</button>
)}
<button
type="button"
class="menu-tag__control menu-tag__control--scroll"
aria-label={$t('menuTag.scrollRight')}
aria-disabled={!this.scrollState.right}
title={$t('menuTag.scrollRight')}
onClick={() => this.scrollX('right')}
class="menu-tag__control"
aria-label={$t('layout.maximize')}
title={$t('layout.maximize')}
onClick={() => this.maximize(true)}
>
<Chevron direction="right" />
<RIcon name="action/maximize-workspace" size={16} />
</button>
<div class="menu-tag__tools">
{this.showingForbidden && (
<button
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.closeCurrent')}
title={$t('menuTag.closeCurrent')}
onClick={(event) => this.closeStatus(event.detail === 0)}
>
<RIcon name="action/close" size={16} aria-hidden="true" />
</button>
)}
<button
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.reload')}
title={$t('menuTag.reload')}
onClick={() => reload()}
>
<RIcon
name="action/reload"
size={16}
customClassName={
globalMainLayoutLoad
? ''
: 'menu-tag__right-setting--spinning'
}
/>
</button>
<RMoreDropdown
class="menu-tag__dropdown"
options={this.moreOptions}
trigger="click"
onSelect={actionDropdownSelect}
>
<button
ref="actionsButton"
type="button"
class="menu-tag__control"
aria-label={$t('layout.maximize')}
title={$t('layout.maximize')}
onClick={() => this.maximize(true)}
aria-label={$t('menuTag.actions')}
title={$t('menuTag.actions')}
onClick={this.selectActiveContext}
>
<RIcon name="action/maximize-workspace" size={16} />
<RIcon name="action/more" size={16} />
</button>
<button
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.reload')}
title={$t('menuTag.reload')}
onClick={() => reload()}
>
<RIcon
name="action/reload"
size={16}
customClassName={
globalMainLayoutLoad
? ''
: 'menu-tag__right-setting--spinning'
}
/>
</button>
<RMoreDropdown
class="menu-tag__dropdown"
options={this.moreOptions}
trigger="click"
onSelect={actionDropdownSelect}
>
<button
ref="actionsButton"
type="button"
class="menu-tag__control"
aria-label={$t('menuTag.actions')}
title={$t('menuTag.actions')}
onClick={this.selectActiveContext}
>
<RIcon name="action/more" size={16} />
</button>
</RMoreDropdown>
</div>
</NFlex>
</div>
</NLayoutHeader>
</RMoreDropdown>
</div>
</NFlex>
</div>
)
},
})

View File

@ -0,0 +1,209 @@
import './index.scss'
import AppAvatar from '@/app-components/app/AppAvatar'
import { LOCAL_OPTIONS } from '@/app-config'
import { useDevice, useI18n } from '@/hooks'
import { useSettingActions, useSigningGetters } from '@/store'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex } from 'naive-ui'
import type { PropType } from 'vue'
import { useFullscreen } from 'vue-hooks-plus'
import { layoutHostKey } from '../../host-context'
import GlobalSearch from '../Search/GlobalSearch'
import GlobalSearchButton from '../Search/GlobalSearchButton'
import {
avatarDropdownClick,
createAvatarOptions,
createRightIconOptions,
} from './shared'
import type { IconEventMapOptions } from './type'
export default defineComponent({
name: 'LayoutHeaderActions',
props: {
onOpenSettings: { type: Function as PropType<() => void>, default: void 0 },
},
setup(props) {
// 获取 setting 相关值
const { updateLocale, updateSettingState } = useSettingActions()
const { t } = useI18n()
// 获取全屏相关方法
const [isFullscreen, { toggleFullscreen, isEnabled }] = useFullscreen(
document.getElementsByTagName('html')[0],
)
const host = inject(layoutHostKey, null)
const accountMenuShown = ref(false)
const { getSigningCallback } = useSigningGetters()
// 是否展示全局搜索
const globalSearchShown = ref(false)
// 当前是否为平板或者更小的设备
const { isTabletOrSmaller } = useDevice()
/**
*
* @description
* 顶部右边提示框操作栏。
*/
const rightTooltipIconOptions = computed(() =>
createRightIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
const iconEventMap: IconEventMapOptions = {
search: () => {
globalSearchShown.value = true
},
setting: () => (props.onOpenSettings ?? host?.openSettings)?.(),
github: () => {
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
},
fullscreen: () => {
if (!isEnabled) {
window.$message.warning(t('globalMessage.isEnabledFullscreen'))
}
toggleFullscreen()
},
lock: () => {
updateSettingState('lockScreenSwitch', true)
},
}
const toolIconClick = (key: keyof typeof iconEventMap) => {
iconEventMap[key]?.()
}
return {
t,
isFullscreen,
rightTooltipIconOptions,
toolIconClick,
updateLocale,
globalSearchShown,
isTabletOrSmaller,
accountMenuShown,
getSigningCallback,
}
},
render() {
const { rightTooltipIconOptions, toolIconClick, updateLocale } = this
return (
<>
<GlobalSearch v-model:show={this.globalSearchShown} />
<NFlex
class="layout-header__actions"
justify="end"
align="center"
size={[4, 0]}
wrap={false}
>
{this.isTabletOrSmaller ? (
<NButton
quaternary
class="override-button__layout"
aria-label={this.t<string>('headerTooltip.Search')}
onClick={() => {
this.globalSearchShown = true
}}
>
<RIcon name="action/search" size={20} />
</NButton>
) : (
<GlobalSearchButton
onClick={(e) => {
e.stopPropagation()
this.globalSearchShown = true
}}
/>
)}
{rightTooltipIconOptions.map((curr) => (
<NButton
class={[
'override-button__layout',
{ 'layout-header__settings': curr.eventKey === 'setting' },
]}
quaternary
size="medium"
key={curr.eventKey ?? curr.name}
aria-label={this.t<string>(
curr.eventKey === 'setting'
? 'headerTooltip.Setting'
: curr.eventKey === 'github'
? 'headerTooltip.Github'
: this.isFullscreen
? 'headerTooltip.CancelFullScreen'
: 'headerTooltip.FullScreen',
)}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
>
<RIcon name={curr.name} size={20} />
</NButton>
))}
<NDropdown
options={LOCAL_OPTIONS}
onSelect={(key: string | number) => updateLocale(String(key))}
trigger="click"
>
<NButton
quaternary
aria-label={this.t<string>('layout.language')}
class="override-button__layout"
>
<RIcon name="system/language" size={20} />
</NButton>
</NDropdown>
<NDropdown
class="layout-account-menu"
placement="bottom-end"
show={this.accountMenuShown}
onUpdateShow={(show) => {
this.accountMenuShown = show
}}
options={[
{
key: 'identity',
type: 'render',
render: () => (
<div class="layout-account-menu__identity">
<span>{this.t('account.eyebrow')}</span>
<strong>{this.getSigningCallback.name}</strong>
</div>
),
},
{ key: 'identity-divider', type: 'divider' },
...createAvatarOptions(this.t),
]}
onSelect={(key) => void avatarDropdownClick(key)}
trigger="click"
>
<AppAvatar
avatarSize={30}
cursor="pointer"
aria-label={this.t<string>('account.menu', {
name: this.getSigningCallback.name,
})}
aria-haspopup="menu"
aria-expanded={this.accountMenuShown}
spaceSize={[8, 0]}
class={[
'layout-header__account',
{ 'is-open': this.accountMenuShown },
]}
>
{{
suffix: () => (
<RIcon
class="layout-header__account-chevron"
name="directional/expanded"
size={14}
/>
),
}}
</AppAvatar>
</NDropdown>
</NFlex>
</>
)
},
})

View File

@ -1,5 +1,5 @@
import { LAYOUT_SIDER_REF } from '@/app-config'
import { useDevice, useI18n, useSiderScroll } from '@/hooks'
import { findMenuRoot } from '@/layout/navigation'
import {
useMenuActions,
useMenuGetters,
@ -52,28 +52,17 @@ export default defineComponent({
name: 'SegmentViewsCustomMenu',
setup() {
const { t } = useI18n('preferences')
const { getMenuConfig, getLayoutConfig } = useSettingGetters()
const { getCollapsed, getMenuOptions, getMenuKey } = useMenuGetters()
const { getMenuConfig } = useSettingGetters()
const { getCollapsed } = useMenuGetters()
const { updateSettingState } = useSettingActions()
const { setupAppMenu, collapsedMenu } = useMenuActions()
const { isTabletOrSmaller } = useDevice()
const scrollSider = useSiderScroll()
const refreshing = ref(false)
const id = useId()
const hasDesktopSidebar = computed(() => {
if (isTabletOrSmaller.value) return false
const { mode } = getLayoutConfig.value
if (mode === 'side' || mode === 'right') return true
if (mode === 'top') return false
return !!findMenuRoot(
getMenuOptions.value,
String(getMenuKey.value),
)?.children?.some((option) => option.show !== false)
})
const hasDesktopSidebar = computed(
() => !isTabletOrSmaller.value && !!LAYOUT_SIDER_REF.value,
)
const refreshMenu = async () => {
if (refreshing.value) return

View File

@ -20,13 +20,16 @@
&__actions {
flex-shrink: 0;
}
}
.layout-header,
.r-layout-row {
.n-breadcrumb {
font-size: 13px;
}
.override-button__layout,
&__menu-toggle {
.layout-header__menu-toggle {
inline-size: 36px;
padding: 0;
border-radius: var(--r-control-radius);
@ -51,7 +54,7 @@
}
}
&__account {
.layout-header__account {
block-size: 40px;
margin-inline-start: 8px;
padding-inline: 8px;
@ -67,12 +70,12 @@
}
}
&__account-chevron {
.layout-header__account-chevron {
color: var(--r-text-muted);
transition: transform 160ms ease;
}
&__account.is-open &__account-chevron {
.layout-header__account.is-open .layout-header__account-chevron {
transform: rotate(180deg);
}
}
@ -110,14 +113,14 @@
}
.override-button__layout,
&__menu-toggle,
&__account {
.layout-header__menu-toggle,
.layout-header__account {
inline-size: 44px;
block-size: 44px;
padding: 0;
}
&__account {
.layout-header__account {
margin-inline-start: 0;
.r-app-avatar__name,

View File

@ -1,129 +1,25 @@
import { useRuntimeActions, useRuntimeGetters } from '@/store'
import './index.scss'
import AppAvatar from '@/app-components/app/AppAvatar'
import { LOCAL_OPTIONS } from '@/app-config'
import { useDevice, useI18n } from '@/hooks'
import {
useSettingActions,
useSettingGetters,
useSigningGetters,
} from '@/store'
import { useRuntimeActions, useRuntimeGetters } from '@/store'
import { RIcon } from '@ray-template/ui/icon'
import { NButton, NDropdown, NFlex, NLayoutHeader } from 'naive-ui'
import { NButton, NFlex, NLayoutHeader } from 'naive-ui'
import type { PropType } from 'vue'
import { useFullscreen } from 'vue-hooks-plus'
import {
Breadcrumb,
GlobalSearch,
GlobalSearchButton,
TooltipIcon,
} from './components'
import {
avatarDropdownClick,
createAvatarOptions,
createLeftIconOptions,
createRightIconOptions,
} from './shared'
import type { IconEventMapOptions } from './type'
import LayoutBreadcrumb from '../../blocks/LayoutBreadcrumb'
import HeaderActions from './HeaderActions'
export default defineComponent({
name: 'AppSiderBar',
name: 'LayoutHeader',
props: {
onOpenSettings: { type: Function as PropType<() => void>, required: true },
onOpenSettings: { type: Function as PropType<() => void>, default: void 0 },
},
setup(props) {
// 获取 setting 相关值
const { updateLocale, updateSettingState } = useSettingActions()
const { t } = useI18n()
// 获取全屏相关方法
const [isFullscreen, { toggleFullscreen, isEnabled }] = useFullscreen(
document.getElementsByTagName('html')[0],
)
// 获取设置相关方法
const { getBreadcrumbSwitch } = useSettingGetters()
const accountMenuShown = ref(false)
const { getSigningCallback } = useSigningGetters()
// 是否展示全局搜索
const globalSearchShown = ref(false)
// 当前是否为平板或者更小的设备
setup(props, { slots }) {
const { t } = useI18n('layout')
const { isTabletOrSmaller } = useDevice()
// 获取全局 drawer 的值
const globalDrawerValue = useRuntimeGetters().globalDrawerValue
const { globalDrawerValue } = useRuntimeGetters()
const { setRuntimeState } = useRuntimeActions()
/**
*
* @description
* 顶部左边操作栏。
*/
const leftIconOptions = computed(() =>
createLeftIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
/**
*
* @description
* 顶部右边提示框操作栏。
*/
const rightTooltipIconOptions = computed(() =>
createRightIconOptions({
isFullscreen,
isTabletOrSmaller,
}),
)
const iconEventMap: IconEventMapOptions = {
search: () => {
globalSearchShown.value = true
},
setting: props.onOpenSettings,
github: () => {
window.open('https://github.com/XiaoDaiGua-Ray/ray-template')
},
fullscreen: () => {
if (!isEnabled) {
window.$message.warning(t('globalMessage.isEnabledFullscreen'))
}
toggleFullscreen()
},
lock: () => {
updateSettingState('lockScreenSwitch', true)
},
menu: () => {
useRuntimeActions().setRuntimeState(
'globalDrawerValue',
!globalDrawerValue.value,
)
},
}
const toolIconClick = (key: keyof typeof iconEventMap) => {
iconEventMap[key]?.()
}
return {
t,
isFullscreen,
leftIconOptions,
rightTooltipIconOptions,
toolIconClick,
updateLocale,
getBreadcrumbSwitch,
globalSearchShown,
isTabletOrSmaller,
accountMenuShown,
getSigningCallback,
}
},
render() {
const { rightTooltipIconOptions, leftIconOptions, getBreadcrumbSwitch } =
this
const { toolIconClick, updateLocale } = this
return (
return () => (
<NLayoutHeader class="layout-header">
<GlobalSearch v-model:show={this.globalSearchShown} />
<NFlex
class="layout-header__method"
align="center"
@ -133,141 +29,28 @@ export default defineComponent({
<NFlex
class="layout-header__navigation"
align="center"
size={this.isTabletOrSmaller ? 4 : 12}
size={isTabletOrSmaller.value ? 4 : 12}
wrap={false}
>
{leftIconOptions.map((curr) => (
{isTabletOrSmaller.value && (
<NButton
quaternary
class="layout-header__menu-toggle"
key={curr.name}
aria-label={this.t<string>('layout.toggleMenu')}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
aria-label={t('toggleMenu')}
onClick={() =>
setRuntimeState('globalDrawerValue', !globalDrawerValue.value)
}
>
<TooltipIcon
iconName={curr.name}
tooltipText={
isRef(curr.tooltip) ? curr.tooltip.value : curr.tooltip
}
customClassName={curr.iconClass}
/>
<RIcon name="navigation/menu" size={18} />
</NButton>
))}
{getBreadcrumbSwitch ? <Breadcrumb /> : null}
</NFlex>
<NFlex
class="layout-header__actions"
justify="end"
align="center"
size={[4, 0]}
wrap={false}
>
{this.isTabletOrSmaller ? (
<NButton
quaternary
class="override-button__layout"
aria-label={this.t<string>('headerTooltip.Search')}
onClick={() => {
this.globalSearchShown = true
}}
>
<RIcon name="action/search" size={20} />
</NButton>
) : (
<GlobalSearchButton
onClick={(e) => {
e.stopPropagation()
this.globalSearchShown = true
}}
/>
)}
{rightTooltipIconOptions.map((curr) => (
<NButton
class={[
'override-button__layout',
{ 'layout-header__settings': curr.eventKey === 'setting' },
]}
quaternary
size="medium"
key={curr.eventKey ?? curr.name}
aria-label={this.t<string>(
curr.eventKey === 'setting'
? 'headerTooltip.Setting'
: curr.eventKey === 'github'
? 'headerTooltip.Github'
: this.isFullscreen
? 'headerTooltip.CancelFullScreen'
: 'headerTooltip.FullScreen',
)}
onClick={toolIconClick.bind(this, curr.eventKey ?? curr.name)}
>
<RIcon name={curr.name} size={20} />
</NButton>
))}
<NDropdown
options={LOCAL_OPTIONS}
onSelect={(key: string | number) => updateLocale(String(key))}
trigger="click"
>
<NButton
quaternary
aria-label={this.t<string>('layout.language')}
class="override-button__layout"
>
<RIcon name="system/language" size={20} />
</NButton>
</NDropdown>
<NDropdown
class="layout-account-menu"
placement="bottom-end"
show={this.accountMenuShown}
onUpdateShow={(show) => {
this.accountMenuShown = show
}}
options={[
{
key: 'identity',
type: 'render',
render: () => (
<div class="layout-account-menu__identity">
<span>{this.t('account.eyebrow')}</span>
<strong>{this.getSigningCallback.name}</strong>
</div>
),
},
{ key: 'identity-divider', type: 'divider' },
...createAvatarOptions(this.t),
]}
onSelect={(key) => void avatarDropdownClick(key)}
trigger="click"
>
<AppAvatar
avatarSize={30}
cursor="pointer"
aria-label={this.t<string>('account.menu', {
name: this.getSigningCallback.name,
})}
aria-haspopup="menu"
aria-expanded={this.accountMenuShown}
spaceSize={[8, 0]}
class={[
'layout-header__account',
{ 'is-open': this.accountMenuShown },
]}
>
{{
suffix: () => (
<RIcon
class="layout-header__account-chevron"
name="directional/expanded"
size={14}
/>
),
}}
</AppAvatar>
</NDropdown>
{slots.default ? slots.default() : <LayoutBreadcrumb />}
</NFlex>
{slots.actions ? (
slots.actions()
) : (
<HeaderActions onOpenSettings={props.onOpenSettings} />
)}
</NFlex>
</NLayoutHeader>
)

View File

@ -5,20 +5,18 @@ import SiderBarLogo from '../Menu/components/SiderBarLogo'
export default defineComponent({
name: 'TopNavigation',
setup() {
props: { grouped: Boolean },
setup(props) {
const { t } = useI18n()
const { getMenuOptions, getMenuKey } = useMenuGetters()
const { getLayoutConfig, getMenuConfig } = useSettingGetters()
const { getMenuConfig } = useSettingGetters()
const { changeMenuModelValue } = useMenuActions()
return () => (
<ShellTopNavigation
items={getMenuOptions.value}
active={getMenuKey.value}
grouped={
getLayoutConfig.value.mode === 'mixed' ||
getLayoutConfig.value.mode === 'split'
}
grouped={props.grouped}
label={t('layout.navigation')}
iconSize={getMenuConfig.value.iconSize}
select={(option) => changeMenuModelValue(option.fullPath, option)}

View File

@ -0,0 +1,19 @@
import { builtinLayoutPreviews } from '@ray-template/admin-shell'
import type { LayoutMode } from '@ray-template/admin-shell'
import { createBuiltinLayout } from './renderers/BuiltinLayout'
import type { LayoutDefinition } from './types'
export function defineBuiltinLayout(
id: LayoutMode,
label: LayoutDefinition['label'],
regions: Parameters<typeof createBuiltinLayout>[0],
): LayoutDefinition {
return {
id,
label,
component: createBuiltinLayout(regions),
sharedFrame: true,
preview: builtinLayoutPreviews[id],
fallbackMode: id,
}
}

View File

@ -0,0 +1,15 @@
import CustomTopLayout from '../renderers/CustomTopLayout'
import type { LayoutDefinition } from '../types'
export default {
id: 'custom-top',
label: { 'zh-CN': '双行顶部', 'en-US': 'Two-row top' },
component: CustomTopLayout,
sharedFrame: true,
preview: {
rows: [['tabs', 'actions'], ['navigation']],
sidebar: 'none',
footer: true,
},
fallbackMode: 'top',
} satisfies LayoutDefinition

View File

@ -0,0 +1,10 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'mixed',
{ 'zh-CN': '混合导航', 'en-US': 'Mixed' },
{
topNavigation: 'groups',
sidebar: 'children',
},
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'right',
{ 'zh-CN': '右侧导航', 'en-US': 'Right sidebar' },
{ sidebar: 'right' },
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'side',
{ 'zh-CN': '侧边导航', 'en-US': 'Sidebar' },
{ sidebar: 'left' },
)

View File

@ -0,0 +1,11 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'split',
{ 'zh-CN': '通栏分组', 'en-US': 'Wide top' },
{
topNavigation: 'groups',
sidebar: 'children',
wideHeader: true,
},
)

View File

@ -0,0 +1,7 @@
import { defineBuiltinLayout } from '../define-builtin-layout'
export default defineBuiltinLayout(
'top',
{ 'zh-CN': '顶部导航', 'en-US': 'Top' },
{ topNavigation: 'all' },
)

View File

@ -0,0 +1,176 @@
import * as v from 'valibot'
import { layoutIdMaxLength, layoutIdPattern } from './id.ts'
import { layoutBlocks, layoutRowsSchema, sidebarSchema } from './preview.ts'
export const layoutDefinitionsDirectory = 'apps/admin/src/layout/definitions'
export const layoutWriteEndpoint = '/__ray-layout-lab/write'
export { layoutBlocks }
export type LayoutBlock = (typeof layoutBlocks)[number]
const idSchema = v.pipe(
v.string(),
v.maxLength(layoutIdMaxLength),
v.regex(layoutIdPattern),
)
const layoutDesignSchema = v.pipe(
v.strictObject({
id: idSchema,
label: v.pipe(v.string(), v.trim(), v.minLength(1), v.maxLength(80)),
selectable: v.boolean(),
autoRegister: v.optional(v.boolean(), true),
sidebar: v.optional(sidebarSchema, 'none'),
footer: v.optional(v.boolean(), false),
rows: layoutRowsSchema,
bottomRows: v.optional(layoutRowsSchema, []),
}),
v.check(({ rows, bottomRows }) => {
const blocks = [...rows.flat(), ...bottomRows.flat()]
return new Set(blocks).size === blocks.length
}),
)
export type LayoutDesign = v.InferInput<typeof layoutDesignSchema>
const components = {
actions: 'LayoutHeaderActions',
breadcrumb: 'LayoutBreadcrumb',
navigation: 'LayoutTopNavigation',
tabs: 'LayoutTabs',
} satisfies Record<LayoutBlock, string>
export function layoutFileName(id: string) {
return `${v.parse(idSchema, id)}.layout.tsx`
}
export function parseLayoutDesign(input: unknown) {
return v.parse(layoutDesignSchema, input)
}
function labelLiteral(value: string) {
// 模板字符串在长名称与宽字符下都保持单行;插值符号和不可见字符需要显式转义。
const escaped = JSON.stringify(value)
.slice(1, -1)
.replaceAll('\\"', '"')
.replaceAll('`', '\\`')
.replaceAll('${', '\\${')
.replace(
/[^\S ]|[\p{Cc}\p{Cf}]/gu,
(char) => `\\u{${char.codePointAt(0)!.toString(16)}}`,
)
return '`' + escaped + '`'
}
export function generateLayoutSource(input: unknown): string {
const design = parseLayoutDesign(input)
const placedBlocks = [...design.rows.flat(), ...design.bottomRows.flat()]
const imports = [
'LayoutFrame',
'LayoutOutlet',
...(placedBlocks.length ? ['LayoutRow'] : []),
...(design.sidebar === 'none' ? [] : ['LayoutNavigation']),
...(design.footer ? ['LayoutFooter'] : []),
...placedBlocks.map((block) => components[block]),
].sort()
const symbols = imports.join(', ')
const compactImport = `import { ${symbols} } from '@/layout/blocks'`
const blockImport =
compactImport.length <= 80
? compactImport
: `import {\n${imports.map((item) => ` ${item},`).join('\n')}\n} from '@/layout/blocks'`
const name =
design.id
.split('-')
.map((part) => part[0].toUpperCase() + part.slice(1))
.join('') + 'Layout'
const slots: string[] = []
const rowRegions = [
['header', design.rows],
['bottom', design.bottomRows],
] as const
for (const [region, rows] of rowRegions) {
if (!rows.length) continue
const markup = rows
.map((row) =>
[
' <LayoutRow>',
...row.map((block) => ` <${components[block]} />`),
' </LayoutRow>',
].join('\n'),
)
.join('\n')
slots.push(` ${region}: () => (
<>
${markup}
</>
),`)
}
let frameAttributes = ''
let fallbackMode = 'top'
if (design.sidebar !== 'none') {
frameAttributes = ` sidebarPlacement="${design.sidebar}"`
fallbackMode = design.sidebar === 'right' ? 'right' : 'side'
const end = design.sidebar === 'right' ? ' end' : ''
slots.push(` sidebar: () => <LayoutNavigation${end} />,`)
}
if (design.footer) slots.push(' footer: () => <LayoutFooter />,')
slots.push(' default: () => <LayoutOutlet />,')
const rowLiteral = (rows: LayoutBlock[][]) => {
const lines = rows.map((row) => {
const blocks = row.map((block) => `'${block}'`)
return `[${blocks.join(', ')}]`
})
return `[${lines.join(', ')}]`
}
const preview = [
` rows: ${rowLiteral(design.rows)},`,
...(design.bottomRows.length
? [` bottomRows: ${rowLiteral(design.bottomRows)},`]
: []),
` sidebar: '${design.sidebar}',`,
` footer: ${design.footer},`,
].join('\n')
return `${blockImport}
import type { LayoutDefinition } from '@/layout/types'
import { defineComponent } from 'vue'
export default {
id: '${design.id}',
label: ${labelLiteral(design.label)},
selectable: ${design.selectable},
autoRegister: ${design.autoRegister},
sharedFrame: true,
fallbackMode: '${fallbackMode}',
preview: {
${preview}
},
component: defineComponent({
name: '${name}',
setup() {
return () => (
<LayoutFrame${frameAttributes}>
{{
${slots.join('\n')}
}}
</LayoutFrame>
)
},
}),
} satisfies LayoutDefinition
`
}

View File

@ -0,0 +1,103 @@
import { LAYOUT_MODES } from '@ray-template/admin-shell'
import { shallowRef, toRaw } from 'vue'
import type { ShallowRef } from 'vue'
import { isLayoutId } from './id'
import { readLayoutPreview } from './preview'
import type { LayoutDefinition } from './types'
const validText = (value: unknown) =>
typeof value === 'string' && value.trim().length > 0
export function layoutEntry(definition: LayoutDefinition): LayoutDefinition {
if (!isLayoutId(definition?.id)) throw new TypeError('Invalid layout ID')
const { id, label, component, fallbackMode, autoRegister, selectable } =
definition
if (
!validText(label) &&
!(
typeof label === 'object' &&
label &&
validText(label['zh-CN']) &&
validText(label['en-US'])
)
)
throw new TypeError(`Invalid label for layout "${id}"`)
if (
!component ||
(typeof component !== 'object' && typeof component !== 'function') ||
(fallbackMode !== void 0 && !LAYOUT_MODES.includes(fallbackMode)) ||
(autoRegister !== void 0 && typeof autoRegister !== 'boolean') ||
(definition.sharedFrame !== void 0 &&
typeof definition.sharedFrame !== 'boolean') ||
(selectable !== void 0 && typeof selectable !== 'boolean')
)
throw new TypeError(`Invalid layout definition "${id}"`)
return Object.freeze({
id,
label: typeof label === 'string' ? label : Object.freeze({ ...label }),
component: toRaw(component),
sharedFrame: definition.sharedFrame,
preview:
definition.preview === void 0
? void 0
: readLayoutPreview(definition.preview),
fallbackMode,
autoRegister,
get selectable() {
return definition.selectable
},
})
}
export function collectLayoutDefinitions(
modules: Record<string, LayoutDefinition>,
) {
const builtins = LAYOUT_MODES.map((id) => `./definitions/${id}.layout.ts`)
const paths = [
...builtins.filter((path) => Object.hasOwn(modules, path)),
...Object.keys(modules).filter((path) => !builtins.includes(path)),
]
const catalog = new Map<string, LayoutDefinition>()
for (const path of paths) {
const definition = modules[path]
if (definition?.autoRegister === false) continue
try {
const entry = layoutEntry(definition)
if (catalog.has(entry.id))
throw new Error(`Duplicate layout ID "${entry.id}"`)
catalog.set(entry.id, entry)
} catch (error) {
console.error(`[useLayout] ${path}`, error)
}
}
return catalog
}
const catalog = collectLayoutDefinitions(
import.meta.glob<LayoutDefinition>('./definitions/*.layout.{js,ts,jsx,tsx}', {
eager: true,
import: 'default',
}),
)
// 文件增删会重载本模块。保留 ref,使现有 Pinia 实例和实验室无需重新挂载。
export const discoveredLayouts: ShallowRef<
ReadonlyMap<string, LayoutDefinition>
> = import.meta.hot?.data.discoveredLayouts ?? shallowRef(catalog)
discoveredLayouts.value = catalog
if (import.meta.hot) {
import.meta.hot.data.discoveredLayouts = discoveredLayouts
import.meta.hot.accept()
}

View File

@ -0,0 +1,25 @@
import type {
Component,
InjectionKey,
Ref,
ShallowRef,
Slots,
VNode,
} from 'vue'
export type SharedFrameRenderer = () => VNode
export interface LayoutHost {
frameRoot: Readonly<Ref<HTMLElement | null>>
sharedFrame: ShallowRef<SharedFrameRenderer | undefined>
slots: Slots
draftRenderer: ShallowRef<Component | undefined>
deferredFromId: Readonly<Ref<string | undefined>>
openSettings: () => void
addOutlet: (outlet: HTMLElement) => void
removeOutlet: (outlet: HTMLElement) => void
}
export const layoutHostKey: InjectionKey<LayoutHost> = Symbol('LayoutHost')
export const layoutFrameKey: InjectionKey<boolean> = Symbol('LayoutFrame')

View File

@ -0,0 +1,10 @@
export const layoutIdPattern = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/
export const layoutIdMaxLength = 64
export function isLayoutId(value: unknown): value is string {
return (
typeof value === 'string' &&
value.length <= layoutIdMaxLength &&
layoutIdPattern.test(value)
)
}

View File

@ -1,123 +1,317 @@
import { apiMockEnabled } from '@/api/admin/client'
import useAppLockScreen from '@/app-components/app/AppLockScreen/appLockVar'
import UnlockScreen from '@/app-components/app/AppLockScreen/components/UnlockScreen'
import { LAYOUT_CONTENT_REF } from '@/app-config'
import { useDevice, useI18n, useMaximize } from '@/hooks'
import { useMenuGetters, useRuntimeGetters, useSettingGetters } from '@/store'
import { AdminShell } from '@ray-template/admin-shell'
import Menu from './components/Menu'
import { useSettingGetters } from '@/store'
import { LAYOUT_MODES } from '@ray-template/admin-shell'
import { Suspense, Teleport } from 'vue'
import type { Component } from 'vue'
import SharedFrame from './blocks/SharedFrame'
import SettingDrawer from './components/SiderBar/components/SettingDrawer'
import TopNavigation from './components/TopNavigation'
import {
ContentWrapper,
FeatureWrapper,
FooterWrapper,
HeaderWrapper,
} from './default'
import ContentLoading from './default/ContentWrapper/ContentLoading'
import { findMenuRoot } from './navigation'
import ContentWrapper from './default/ContentWrapper'
import { layoutHostKey } from './host-context'
import type { SharedFrameRenderer } from './host-context'
import CompactLayout from './renderers/BuiltinLayout'
import LayoutPresentation, {
ignoreAbandonedLayoutErrors,
} from './renderers/LayoutPresentation'
import { useDeferredLayout } from './useDeferredLayout'
import { useLayout } from './useLayout'
export default defineComponent({
name: 'RLayout',
inheritAttrs: false,
setup(_, { attrs, slots }) {
const {
getMenuTagSwitch,
getCopyrightSwitch,
getLayoutConfig,
getDrawerPlacement,
} = useSettingGetters()
const { getMenuOptions, getMenuKey } = useMenuGetters()
const {
globalMainLayoutLoad,
layoutContentSpinning,
layoutContentMaximize,
layoutContentMaximizeStyle,
} = useRuntimeGetters()
ignoreAbandonedLayoutErrors()
const { activeLayout, layouts, updateLayout } = useLayout()
const { getDrawerPlacement } = useSettingGetters()
const { isTabletOrSmaller } = useDevice()
const { maximize } = useMaximize()
const { t } = useI18n('layout')
const { isTabletOrSmaller } = useDevice()
const { getLockAppScreen } = useAppLockScreen()
const locked = computed(() => apiMockEnabled && getLockAppScreen())
const settingsShown = ref(false)
const shell = useTemplateRef<InstanceType<typeof AdminShell>>('shell')
const root = useTemplateRef<HTMLElement>('root')
const parking = useTemplateRef<HTMLElement>('parking')
const sharedFrame = shallowRef<SharedFrameRenderer>()
let settingsTrigger: HTMLElement | null = null
const openSettings = () => {
settingsTrigger =
document.activeElement instanceof HTMLElement
? document.activeElement
: null
settingsShown.value = true
}
const restoreSettingsFocus = () => {
const root = shell.value?.$el
const trigger =
settingsTrigger?.isConnected && settingsTrigger !== document.body
? settingsTrigger
: root.value?.querySelector<HTMLElement>('.layout-header__settings')
if (root instanceof HTMLElement)
root
.querySelector<HTMLButtonElement>('.layout-header__settings')
?.focus({ preventScroll: true })
trigger?.focus({ preventScroll: true })
settingsTrigger = null
}
watch(locked, (value) => {
if (value) settingsShown.value = false
const emergency = ref(false)
const draftRenderer = shallowRef<Component>()
const compact = computed(() => isTabletOrSmaller.value || emergency.value)
const renderer = computed(() =>
compact.value
? CompactLayout
: (draftRenderer.value ?? activeLayout.value.component),
)
const requestedId = computed(() =>
compact.value
? 'side'
: draftRenderer.value
? '_preview'
: activeLayout.value.id,
)
const requested = computed(() => ({
id: requestedId.value,
renderer: renderer.value,
shared:
compact.value ||
!!draftRenderer.value ||
activeLayout.value.sharedFrame === true,
key: Symbol('LayoutPresentation'),
}))
let mountedPresentation: symbol | undefined
const outlets = new Set<HTMLElement>()
const target = shallowRef<HTMLElement>()
const page = document.createElement('div')
const { presentation, deferred, reconcile, guardPending, markMounted } =
useDeferredLayout(requested, page)
const renderedId = computed(() => presentation.value.id)
page.className = 'r-layout-outlet'
const placePage = (parent: HTMLElement) => {
if (page.parentElement === parent) return
if (page.isConnected && parent.isConnected && parent.moveBefore)
parent.moveBefore(page, null)
else parent.appendChild(page)
}
const rejected = new Set<string>()
let lastGood = 'side'
let disposed = false
let pending = false
let pendingFocus: HTMLElement | null = null
let pendingScroll:
{ container: HTMLElement; left: number; top: number } | undefined
const scrollContainer = () =>
target.value?.closest('.r-layout-content-scroll')?.parentElement
const capturePagePosition = () => {
if (
disposed ||
locked.value ||
!page.isConnected ||
!target.value?.contains(page)
)
return
const focused = document.activeElement
const container = scrollContainer()
if (focused instanceof HTMLElement && page.contains(focused))
pendingFocus = focused
if (!pendingScroll && container)
pendingScroll = {
container,
left: container.scrollLeft,
top: container.scrollTop,
}
}
const rejectLayout = (id: string, error: unknown) => {
if (disposed || locked.value || renderedId.value !== id || compact.value)
return
console.error(`[useLayout] Layout "${id}" could not be rendered.`, error)
if (draftRenderer.value) {
draftRenderer.value = void 0
return
}
rejected.add(id)
const fallback = [lastGood, ...LAYOUT_MODES].find(
(candidate) =>
!rejected.has(candidate) &&
layouts.value.some(
(item) => item.id === candidate && item.selectable !== false,
),
)
if (fallback) updateLayout(fallback)
else emergency.value = true
}
const checkOutlets = () => {
if (pending || disposed) return
pending = true
void nextTick(() => {
pending = false
if (
disposed ||
locked.value ||
mountedPresentation !== presentation.value.key
)
return
const activeOutlets = [...outlets].filter(
(outlet) =>
sharedFrame.value || !outlet.closest('[data-shared-layout-frame]'),
)
if (activeOutlets.length !== 1) {
rejectLayout(
renderedId.value,
'A layout must mount exactly one LayoutOutlet.',
)
return
}
const outlet = activeOutlets[0]
placePage(outlet)
target.value = outlet
markMounted()
if (!compact.value && !draftRenderer.value) {
lastGood = renderedId.value
rejected.clear()
}
if (pendingScroll) {
const container = scrollContainer()
if (container && container !== pendingScroll.container) {
container.scrollLeft = pendingScroll.left
container.scrollTop = pendingScroll.top
}
pendingScroll = void 0
}
if (
pendingFocus?.isConnected &&
(document.activeElement === document.body ||
document.activeElement ===
outlet
.closest('.r-layout-content-viewport')
?.querySelector(':scope > .r-layout-content-restore__button'))
)
pendingFocus.focus({ preventScroll: true })
pendingFocus = null
})
}
provide(layoutHostKey, {
frameRoot: root,
sharedFrame,
deferredFromId: computed(() =>
deferred.value ? renderedId.value : void 0,
),
slots,
draftRenderer,
openSettings,
addOutlet: (element) => {
outlets.add(element)
checkOutlets()
},
removeOutlet: (element) => {
if (
!disposed &&
!locked.value &&
page.parentElement === element &&
parking.value
) {
capturePagePosition()
placePage(parking.value)
}
outlets.delete(element)
checkOutlets()
},
})
const mode = computed(() =>
isTabletOrSmaller.value ? 'side' : getLayoutConfig.value.mode,
)
const mixedChildren = computed(
() =>
findMenuRoot(
getMenuOptions.value,
String(getMenuKey.value),
)?.children?.filter((option) => option.show !== false) ?? [],
watch(
activeLayout,
() => {
emergency.value = false
draftRenderer.value = void 0
},
{ flush: 'sync' },
)
watch(locked, (value) => {
if (value) {
mountedPresentation = void 0
maximize(false)
settingsShown.value = false
pendingScroll = void 0
pendingFocus = null
target.value = void 0
void nextTick(reconcile)
}
})
onBeforeUnmount(() => {
disposed = true
maximize(false)
})
return () => {
if (locked.value) return <UnlockScreen {...attrs} />
const grouped = mode.value === 'mixed' || mode.value === 'split'
const attempt = presentation.value
const id = attempt.id
return (
<>
<AdminShell
{...attrs}
ref="shell"
layout={getLayoutConfig.value}
mode={mode.value}
groupedSidebar={mixedChildren.value.length > 0}
showTabs={getMenuTagSwitch.value}
showFooter={getCopyrightSwitch.value}
busy={
!slots.default &&
(!globalMainLayoutLoad.value || layoutContentSpinning.value)
}
maximized={layoutContentMaximize.value}
maximizedStyle={layoutContentMaximizeStyle.value}
contentRef={LAYOUT_CONTENT_REF}
restore={() => maximize(false)}
skipContentLabel={t('skipToContent')}
restoreLabel={t('restore')}
>
{{
header:
slots.header ??
(() => (
<>
<HeaderWrapper onOpenSettings={openSettings} />
{mode.value === 'top' || grouped ? <TopNavigation /> : null}
</>
)),
sidebar:
slots.sidebar ??
(() => (
<Menu
options={grouped ? mixedChildren.value : void 0}
showLogo={!grouped}
end={mode.value === 'right'}
inert={layoutContentMaximize.value}
/>
)),
tabs: slots.tabs ?? (() => <FeatureWrapper />),
footer: slots.footer ?? (() => <FooterWrapper />),
default: slots.default ?? (() => <ContentWrapper />),
loading: slots.default ? void 0 : () => <ContentLoading />,
<div ref="root" class="r-layout-host" data-layout={id}>
<Suspense onPending={guardPending}>
<LayoutPresentation
{...attrs}
key={attempt.key}
renderer={attempt.renderer}
onVnodeBeforeUnmount={() => {
if (mountedPresentation === attempt.key) capturePagePosition()
}}
onReady={() => {
if (attempt !== presentation.value) return
mountedPresentation = attempt.key
checkOutlets()
}}
onFailure={(error) => {
void nextTick(() => {
if (attempt === presentation.value) rejectLayout(id, error)
})
}}
/>
</Suspense>
<SharedFrame
onFailure={(error: unknown) => {
void nextTick(() => {
if (attempt === presentation.value) rejectLayout(id, error)
})
}}
</AdminShell>
/>
<div hidden ref="parking" />
{deferred.value && (
<p class="r-layout-switch-notice" role="status">
{t('deferredForEmbed')}
</p>
)}
{target.value && (
<Teleport to={page}>
{slots.default ? slots.default() : <ContentWrapper />}
</Teleport>
)}
{!slots.header && (
<SettingDrawer
v-model:show={settingsShown.value}
@ -125,7 +319,7 @@ export default defineComponent({
onAfterLeave={restoreSettingsFocus}
/>
)}
</>
</div>
)
}
},

View File

@ -0,0 +1,44 @@
import * as v from 'valibot'
export const layoutBlocks = [
'breadcrumb',
'actions',
'tabs',
'navigation',
] as const
export const layoutRowsSchema = v.pipe(
v.array(
v.pipe(
v.array(v.picklist(layoutBlocks)),
v.minLength(1),
v.maxLength(layoutBlocks.length),
),
),
v.maxLength(layoutBlocks.length),
)
export const sidebarSchema = v.picklist(['none', 'left', 'right'])
const previewSchema = v.pipe(
v.strictObject({
rows: layoutRowsSchema,
bottomRows: v.optional(layoutRowsSchema),
sidebar: sidebarSchema,
footer: v.optional(v.boolean()),
wideHeaderRows: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
}),
v.check(({ wideHeaderRows, rows }) => (wideHeaderRows ?? 0) <= rows.length),
)
const freezeRows = (rows: v.InferOutput<typeof layoutRowsSchema>) =>
Object.freeze(rows.map((row) => Object.freeze(row)))
export function readLayoutPreview(value: unknown) {
const preview = v.parse(previewSchema, value)
return Object.freeze({
...preview,
rows: freezeRows(preview.rows),
bottomRows: preview.bottomRows && freezeRows(preview.bottomRows),
})
}

View File

@ -0,0 +1,70 @@
import { useMenuGetters, useRuntimeGetters } from '@/store'
import {
LayoutFooter,
LayoutFrame,
LayoutHeader,
LayoutNavigation,
LayoutTabs,
LayoutTopNavigation,
} from '../blocks'
import { findMenuRoot } from '../navigation'
interface BuiltinRegions {
sidebar?: 'left' | 'right' | 'children'
topNavigation?: 'all' | 'groups'
wideHeader?: boolean
}
export function createBuiltinLayout({
sidebar,
topNavigation,
wideHeader,
}: BuiltinRegions) {
return defineComponent({
name: 'BuiltinLayout',
setup() {
const { getMenuOptions, getMenuKey } = useMenuGetters()
const { layoutContentMaximize } = useRuntimeGetters()
const children = computed(
() =>
findMenuRoot(
getMenuOptions.value,
String(getMenuKey.value),
)?.children?.filter((option) => option.show !== false) ?? [],
)
return () => (
<LayoutFrame
sidebarPlacement={sidebar === 'right' ? 'right' : 'left'}
wideHeader={wideHeader}
>
{{
header: () => (
<>
<LayoutHeader />
{topNavigation && (
<LayoutTopNavigation grouped={topNavigation === 'groups'} />
)}
</>
),
sidebar:
sidebar && (sidebar !== 'children' || children.value.length)
? () => (
<LayoutNavigation
options={sidebar === 'children' ? children.value : void 0}
showLogo={sidebar !== 'children'}
end={sidebar === 'right'}
inert={layoutContentMaximize.value}
/>
)
: void 0,
tabs: () => <LayoutTabs />,
footer: () => <LayoutFooter />,
}}
</LayoutFrame>
)
},
})
}
export default createBuiltinLayout({ sidebar: 'left' })

View File

@ -0,0 +1,30 @@
import {
LayoutFooter,
LayoutFrame,
LayoutHeaderActions,
LayoutRow,
LayoutTabs,
LayoutTopNavigation,
} from '../blocks'
export default defineComponent({
name: 'CustomTopLayout',
setup() {
return () => (
<LayoutFrame>
{{
header: () => (
<>
<LayoutRow>
<LayoutTabs />
<LayoutHeaderActions />
</LayoutRow>
<LayoutTopNavigation />
</>
),
footer: () => <LayoutFooter />,
}}
</LayoutFrame>
)
},
})

View File

@ -0,0 +1,59 @@
import type { Component, ComponentPublicInstance, PropType } from 'vue'
// Vue 跳过已卸载分支的错误钩子,迟到的加载错误由仍在挂载的宿主识别。
const abandoned = new WeakSet<ComponentPublicInstance>()
export function ignoreAbandonedLayoutErrors() {
onErrorCaptured((_error, source) => {
for (let owner = source; owner; owner = owner.$parent) {
if (abandoned.has(owner)) return false
}
})
}
export default defineComponent({
name: 'LayoutPresentation',
props: {
renderer: {
type: [Object, Function] as PropType<Component>,
required: true,
},
onReady: { type: Function as PropType<() => void>, required: true },
onFailure: {
type: Function as PropType<(error: unknown) => void>,
required: true,
},
},
setup(props) {
const owner = getCurrentInstance()!.proxy!
let mounted = false
onBeforeUnmount(() => {
if (!mounted) abandoned.add(owner)
})
onErrorCaptured((error) => {
// 首次装配失败由宿主回退;已挂载后的事件错误沿用应用错误处理。
if (mounted) return
props.onFailure(error)
return false
})
return () =>
h(props.renderer, {
onVnodeMounted: () => {
// Vue 将相同的 vnode 挂载钩子转发给非 Suspense 加载占位及最终组件。
if (
'__asyncResolved' in props.renderer &&
!props.renderer.__asyncResolved
)
return
mounted = true
props.onReady()
},
})
},
})

View File

@ -0,0 +1,16 @@
import type { LayoutMode, LayoutPreview } from '@ray-template/admin-shell'
import type { Component } from 'vue'
export interface LayoutDefinition {
readonly id: string
readonly label: string | Readonly<Record<'zh-CN' | 'en-US', string>>
readonly component: Component
/** 渲染器固定以单一 LayoutFrame 为根,沿用宿主的页面容器。 */
readonly sharedFrame?: boolean
/** 设置卡片展示的积木、行顺序与侧栏位置。 */
readonly preview?: LayoutPreview
/** 用于兼容偏好文件 v1 的内置导航模式,默认使用 side。 */
readonly fallbackMode?: LayoutMode
readonly selectable?: boolean
readonly autoRegister?: boolean
}

View File

@ -0,0 +1,161 @@
import { computed, onScopeDispose, shallowRef, watch } from 'vue'
import type { Component, ComputedRef } from 'vue'
interface Presentation {
id: string
renderer: Component
shared: boolean
key: symbol
}
// 开放 Shadow DOM 内的 iframe 也有独立文档;封闭组件可以用属性声明其内嵌内容。
function findEmbeddedDocuments(page: HTMLElement) {
const roots: (Element | ShadowRoot)[] = [page]
let found = false
for (const root of roots) {
if (root.querySelector('iframe, [data-layout-preserve-embed]')) found = true
for (const element of root.querySelectorAll('*')) {
if (element.shadowRoot) roots.push(element.shadowRoot)
}
}
return { found, roots }
}
export function useDeferredLayout(
requested: ComputedRef<Presentation>,
page: HTMLElement,
) {
const presentation = shallowRef(requested.value)
const same = (a: Presentation, b: Presentation) =>
a.id === b.id && a.renderer === b.renderer
const preparing = shallowRef<symbol>()
const deferred = computed(
() =>
preparing.value !== requested.value.key &&
!same(requested.value, presentation.value),
)
let mounted = presentation.value
let settled: symbol | undefined
let disposed = false
let observer: MutationObserver | undefined
const stopWatching = () => {
observer?.disconnect()
observer = void 0
}
const needsMoveGuard = (next: Presentation) => {
const source = page.parentElement
return (
source?.isConnected &&
typeof source.moveBefore !== 'function' &&
!(source.closest('[data-shared-layout-frame]') && next.shared)
)
}
const observePage = (
roots: (Element | ShadowRoot)[],
callback: () => void,
) => {
stopWatching()
observer = new MutationObserver(callback)
for (const root of roots)
observer.observe(root, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['data-layout-preserve-embed'],
})
}
const reconcile = () => {
stopWatching()
if (disposed) return
const next = requested.value
if (same(next, presentation.value)) return
if (same(next, mounted)) {
presentation.value = mounted
return
}
if (needsMoveGuard(next)) {
const { found, roots } = findEmbeddedDocuments(page)
if (found) {
observePage(roots, reconcile)
return
}
// 自管占位的异步组件会立即卸载自由布局。预先等待同一个加载任务,
// 使等待期间新出现的 iframe 始终留在其原始、可见的容器内。
const component = next.renderer
if (
!page.closest('[data-shared-layout-frame]') &&
settled !== next.key &&
'__asyncLoader' in component &&
typeof component.__asyncLoader === 'function' &&
!component.__asyncResolved
) {
if (preparing.value === next.key) return
preparing.value = next.key
const resume = () => {
if (disposed || requested.value !== next) return
settled = next.key
preparing.value = void 0
reconcile()
}
// 拒绝也交还 Vue 的原有错误边界处理。
void component.__asyncLoader().then(resume, resume)
return
}
}
presentation.value = next
}
const guardPending = () => {
if (same(presentation.value, mounted) || !needsMoveGuard(requested.value))
return
const { found, roots } = findEmbeddedDocuments(page)
if (found) {
// 加载期间旧页面仍可操作。新建的内嵌文档必须跟随旧的已挂载分支。
presentation.value = mounted
reconcile()
} else observePage(roots, guardPending)
}
watch(requested, reconcile, { flush: 'pre' })
onScopeDispose(() => {
disposed = true
stopWatching()
})
return {
presentation,
deferred,
reconcile,
guardPending,
markMounted: () => {
mounted = presentation.value
if (!deferred.value) stopWatching()
},
}
}

View File

@ -0,0 +1,112 @@
import {
useSettingActions,
useSettingGetters,
} from '@/store/hooks/useSettingStore'
import { defineStore, storeToRefs } from 'pinia'
import { computed, shallowReactive, watch } from 'vue'
import sideLayout from './definitions/side.layout'
import { discoveredLayouts, layoutEntry } from './discovery'
import type { LayoutDefinition } from './types'
const layoutStore = defineStore('workspace-layouts', () => {
const manual = shallowReactive(new Map<string, LayoutDefinition>())
const definitions = computed(
() => new Map([...discoveredLayouts.value, ...manual]),
)
if (import.meta.hot) {
watch(discoveredLayouts, (current, previous) => {
for (const id of manual.keys()) {
if (current.has(id) && !previous.has(id))
console.error(
`[useLayout] Ignoring discovered duplicate of registered layout "${id}"`,
)
}
})
}
const { getCustomLayoutId, getLayoutConfig } = useSettingGetters()
const { selectLayout } = useSettingActions()
/**
*
* @param definition 布局标识、名称和 Vue 组件
*
* @description
* 注册到当前应用实例。显式注册忽略自动发现开关,切换时仍检查 selectable。
*
* @throws 布局定义无效或 ID 已被注册。
*/
const registerLayout = (definition: LayoutDefinition) => {
const entry = layoutEntry(definition)
if (definitions.value.has(entry.id))
throw new Error(`Duplicate layout ID "${entry.id}"`)
manual.set(entry.id, entry)
}
const layouts = computed(() => Object.freeze([...definitions.value.values()]))
const selectedLayoutId = computed(
() => getCustomLayoutId.value ?? getLayoutConfig.value.mode,
)
const activeLayout = computed<LayoutDefinition>((previous) => {
const selected = definitions.value.get(selectedLayoutId.value)
// 当前布局可以继续使用;刷新恢复及进入另一布局都需要允许切换。
if (
selected &&
(selected.selectable !== false || selected.id === previous?.id)
)
return selected
return (
layouts.value.find((layout) => layout.selectable !== false) ?? sideLayout
)
})
const activeLayoutId = computed(() => activeLayout.value.id)
/**
*
* @param id 已注册的布局标识
* @returns 成功选中时返回 true;未知或已关闭的布局保留当前偏好。
*/
const updateLayout = (id: string) => {
const layout = definitions.value.get(id)
if (!layout || layout.selectable === false) return false
selectLayout(id, layout.fallbackMode ?? 'side')
return true
}
return {
layouts,
selectedLayoutId,
activeLayout,
activeLayoutId,
registerLayout,
updateLayout,
}
})
/**
*
* @description
* 获取当前 Pinia 实例的工作区布局。首次调用时按文件约定收集布局定义。
*/
export function useLayout() {
const store = layoutStore()
const { layouts, selectedLayoutId, activeLayout, activeLayoutId } =
storeToRefs(store)
return {
layouts,
selectedLayoutId,
activeLayout,
activeLayoutId,
registerLayout: store.registerLayout,
updateLayout: store.updateLayout,
}
}

View File

@ -1,5 +1,6 @@
{
"title": "Layout playground",
"deferredForEmbed": "Your embedded page is still open. The layout will change when you leave it or reload.",
"description": "Changes apply immediately and are saved automatically. Small screens use a menu drawer and keep your desktop layout preference.",
"side": "Sidebar",
"top": "Top",
@ -33,5 +34,58 @@
"tab": "Layout",
"closeMenu": "Close navigation menu",
"toggleMenu": "Open navigation menu",
"language": "Change language"
"language": "Change language",
"designer": {
"title": "Custom layout designer",
"defaultName": "My workspace",
"position": "Placement",
"actions": "Actions",
"tabs": "Page tabs",
"navigation": "Top navigation",
"breadcrumb": "Breadcrumb",
"left": "Move left",
"right": "Move right",
"id": "Layout ID",
"name": "Display name",
"selectable": "Allow switching to this layout",
"preview": "Layout canvas",
"content": "Route content",
"placed": "Moved {block} to {row}, position {position}",
"removed": "Removed {block}",
"local": "Generating into the project running this development server.",
"generate": "Generate into project",
"source": "View generated source",
"written": "Created {path}",
"exists": "A file with this ID already exists. Choose another ID.",
"invalid": "Use a 1–64 character ID starting with a lowercase letter, using lowercase letters, digits and hyphens. Enter a 1–80 character display name.",
"writeError": "Could not write the file. Check the local development server and its write permission.",
"layoutOptions": "Layout and workspace settings",
"downloadHint": "Download the source and place it in your project’s layout definitions directory.",
"download": "Download layout source",
"downloaded": "Download started for {name}",
"autoRegister": "Register automatically",
"tryExample": "Try the two-row top layout",
"duplicate": "This layout ID is already registered. Choose another ID.",
"sidebar": "Sidebar",
"footer": "Footer",
"library": "Block library",
"libraryHint": "Click a block to add it or drag it onto the canvas. Select a placed block to move or remove it.",
"addBlock": "Add {block}",
"selectBlock": "Select {block}",
"contentHint": "Always present in the layout",
"aboveContent": "Above content",
"belowContent": "Below content",
"topRow": "Top row {row}",
"bottomRow": "Bottom row {row}",
"newTop": "New row above content",
"newBottom": "New row below content",
"rowUp": "Move row up",
"rowDown": "Move row down",
"remove": "Remove block",
"sidebarLeft": "Sidebar on left",
"sidebarRight": "Sidebar on right",
"added": "Added {block}",
"tryPreview": "Try layout",
"endPreview": "End preview"
}
}

View File

@ -1,5 +1,6 @@
{
"title": "布局实验室",
"deferredForEmbed": "当前内嵌页面仍在使用,离开内嵌页面或刷新后将切换布局。",
"description": "配置即时生效并自动保存。窄屏使用菜单抽屉,保留桌面布局偏好。",
"side": "侧边导航",
"top": "顶部导航",
@ -33,5 +34,58 @@
"tab": "布局",
"closeMenu": "关闭导航菜单",
"toggleMenu": "打开导航菜单",
"language": "切换语言"
"language": "切换语言",
"designer": {
"title": "自定义布局",
"defaultName": "我的工作区",
"position": "放置位置",
"actions": "操作栏",
"tabs": "页面标签",
"navigation": "顶部导航",
"breadcrumb": "面包屑",
"left": "向左移",
"right": "向右移",
"id": "布局 ID",
"name": "显示名称",
"selectable": "允许切换到此布局",
"preview": "布局画布",
"content": "路由页面",
"placed": "已将{block}移到{row}第 {position} 位",
"removed": "已移除{block}",
"local": "生成目标为当前开发服务所在工程。",
"generate": "生成到工程",
"source": "查看生成源码",
"written": "已写入 {path}",
"exists": "同名文件已存在,请更换布局 ID。",
"invalid": "布局 ID 长度为 1–64 位,以小写字母开头,可含数字与连字符。显示名称长度为 1–80 字。",
"writeError": "写入失败,请确认本机开发服务仍在运行并有工程写入权限。",
"layoutOptions": "布局与工作区设置",
"downloadHint": "下载源码后放入工程的布局定义目录。",
"download": "下载布局源码",
"downloaded": "已发起下载 {name}",
"autoRegister": "自动注册",
"tryExample": "切换到双行顶部示例",
"duplicate": "此布局 ID 已注册,请使用新 ID。",
"sidebar": "侧栏",
"footer": "页脚",
"library": "积木库",
"libraryHint": "点击添加积木,或拖入画布。选中画布上的积木可调整位置或移除。",
"addBlock": "添加{block}",
"selectBlock": "选中{block}",
"contentHint": "始终保留的页面内容区",
"aboveContent": "内容上方",
"belowContent": "内容下方",
"topRow": "上方第 {row} 行",
"bottomRow": "下方第 {row} 行",
"newTop": "在内容上方新建一行",
"newBottom": "在内容下方新建一行",
"rowUp": "整行上移",
"rowDown": "整行下移",
"remove": "移除积木",
"sidebarLeft": "侧栏靠左",
"sidebarRight": "侧栏靠右",
"added": "已添加{block}",
"tryPreview": "试用布局",
"endPreview": "结束试用"
}
}

View File

@ -76,6 +76,7 @@ import { useDemoGetters, useMenuActions } from '@/store'
- `runtime`: Global loading, mobile drawers, page refresh, content maximization, and content loading animations. Read/write through `useRuntimeGetters` / `useRuntimeActions`. Do not persist it; release the store and timers on application unmount.
- `lock-screen`: Lock-screen state also belongs to Pinia. Preserve its historical boolean format, cache key, and cross-tab synchronization.
- `setting.layoutConfig`: Layout mode, content width/spacing, and header/footer positioning. Use existing `useSettingGetters` / `useSettingActions` and the existing settings cache key. Add defaults to old caches without clearing historical preferences.
- `setting.customLayoutId`: Browser-only selection for a registered custom layout. Its built-in fallback is stored in `layoutConfig.mode` and exported by preference-file v1. Updating an explicit built-in mode or importing v1 selects that mode. Updating geometry preserves the custom selection. The workspace resolves the saved ID against its layout registry.
- The separate `global-variable` module was removed. Its original five state names remain in runtime; callers use store hooks. Add global state by responsibility in `src/store/modules`, rather than creating shared reactive singletons in ordinary modules.
```ts

View File

@ -2,6 +2,7 @@ import { piniaSettingStore } from '../modules/setting'
export const useSettingGetters = () => {
const variable = piniaSettingStore()
const getCustomLayoutId = computed(() => variable.customLayoutId)
const getLayoutConfig = computed(() => variable.layoutConfig)
/**
@ -133,6 +134,7 @@ export const useSettingGetters = () => {
const getDynamicDocumentTitle = computed(() => variable.dynamicDocumentTitle)
return {
getCustomLayoutId,
getLayoutConfig,
getDrawerPlacement,
getPrimaryColorOverride,
@ -165,6 +167,7 @@ export const useSettingGetters = () => {
export const useSettingActions = () => {
const {
selectLayout,
updateLocale,
changePrimaryColor,
updateSettingState,
@ -174,6 +177,7 @@ export const useSettingActions = () => {
} = piniaSettingStore()
return {
selectLayout,
updateLocale,
changePrimaryColor,
updateSettingState,

View File

@ -2,9 +2,10 @@ import { APP_CATCH_KEY, APP_THEME } from '@/app-config'
import { useDayjs, useI18n } from '@/hooks'
import type { LocalKey } from '@/hooks'
import { resolveIconName } from '@/icons'
import { isLayoutId } from '@/layout/id'
import { getAppDefaultLanguage } from '@/locales/utils'
import { WELCOME_ROUTE_PATH } from '@/router/constant'
import type { SettingState } from '@/store/modules/setting/types'
import type { LayoutConfig, SettingState } from '@/store/modules/setting/types'
import type { AnyFn } from '@/types'
import { setStorage } from '@/utils/cache'
import { colorToRgba, setStyle } from '@/utils/element'
@ -52,6 +53,17 @@ export const piniaSettingStore = defineStore(
...cloneDeep(getDefaultSettingConfig()),
})
// 内置模式沿用历史字段;自定义布局另存 ID,偏好文件 v1 导出其内置回退模式。
const customLayoutId = ref<string | null>(null)
const selectLayout = (id: string, fallbackMode: LayoutConfig['mode']) => {
// 先写决定当前选项的字段,避免同步订阅读到自定义布局的回退模式。
if (id !== fallbackMode) customLayoutId.value = id
settingState.layoutConfig.mode = fallbackMode
if (id === fallbackMode) customLayoutId.value = null
}
// 修改当前语言
const updateLocale = (key: string) => {
locale(key)
@ -151,6 +163,10 @@ export const piniaSettingStore = defineStore(
...settingState.layoutConfig,
...(value as object),
})
if (value && typeof value === 'object' && Object.hasOwn(value, 'mode'))
customLayoutId.value = null
cb?.()
return
@ -176,6 +192,7 @@ export const piniaSettingStore = defineStore(
const { primaryColor, ...preferences } = parsePreferenceFile(text)
Object.assign(settingState, preferences)
customLayoutId.value = null
changePrimaryColor(primaryColor)
}
@ -210,6 +227,8 @@ export const piniaSettingStore = defineStore(
return {
...toRefs(settingState),
customLayoutId,
selectLayout,
themeOverrides,
syncAppTheme,
updateLocale,
@ -269,6 +288,9 @@ export const piniaSettingStore = defineStore(
},
afterHydrate: ({ store }) => {
store.layoutConfig = normalizeLayoutConfig(store.layoutConfig)
if (!isLayoutId(store.customLayoutId)) store.customLayoutId = null
store.themeStyle = normalizeThemeStyle(store.themeStyle)
store.syncAppTheme()

View File

@ -30,6 +30,7 @@ declare global {
}
declare const __DEV__: boolean
declare const __LAYOUT_PROJECT_WRITER__: boolean
declare const __APP_CFG__: AppConfig

View File

@ -1,40 +1,65 @@
import './hooks/index.scss'
import { useI18n } from '@/hooks'
import LayoutSettings from '@/layout/components/LayoutSettings'
import { useSettingGetters } from '@/store'
import { NCard } from 'naive-ui'
import { useLayout } from '@/layout/useLayout'
import { useSettingGetters } from '@/store/hooks/useSettingStore'
import { NButton, NCard } from 'naive-ui'
import DemoPage from './components/DemoPage'
import LayoutDesigner from './layout-lab/LayoutDesigner'
export default defineComponent({
name: 'LayoutDemo',
setup() {
const { t } = useI18n('layout')
const { t: showcaseT } = useI18n('showcase')
const { getLayoutConfig } = useSettingGetters()
const { updateLayout, activeLayoutId, layouts } = useLayout()
return () => (
<DemoPage
title={t<string>('title')}
eyebrow={showcaseT<string>('layoutEyebrow')}
meta={showcaseT<string>('livePreferences')}
>
<div class="r-layout-playground">
<NCard title={showcaseT<string>('layoutControls')}>
<LayoutSettings showDescription={false} />
</NCard>
<div class="r-layout-playground__aside">
<NCard title={t<string>('current')}>
<pre class="r-demo-code">
<code>{JSON.stringify(getLayoutConfig.value, null, 2)}</code>
</pre>
</NCard>
<NCard title={t<string>('extension')}>
<pre class="r-demo-code">
<code>{`const { updateSettingState } = useSettingActions()\n\nupdateSettingState('layoutConfig', {\n mode: 'mixed',\n contentWidth: 'fixed',\n})\n\n<RLayout>\n {{\n header: () => <CustomHeader />,\n footer: () => <CustomFooter />,\n }}\n</RLayout>`}</code>
</pre>
</NCard>
</div>
</div>
{{
actions: () => (
<NButton
disabled={
activeLayoutId.value === 'custom-top' ||
!layouts.value.some(
(item) =>
item.id === 'custom-top' && item.selectable !== false,
)
}
onClick={() => updateLayout('custom-top')}
>
{t('designer.tryExample')}
</NButton>
),
default: () => (
<>
<LayoutDesigner />
<NCard title={t('designer.layoutOptions')}>
<LayoutSettings showDescription />
<details>
<summary>{t('current')}</summary>
<pre class="r-demo-code">
<code>
{JSON.stringify(
{
layoutId: activeLayoutId.value,
...getLayoutConfig.value,
},
null,
2,
)}
</code>
</pre>
</details>
</NCard>
</>
),
}}
</DemoPage>
)
},

View File

@ -0,0 +1,530 @@
import { useI18n } from '@/hooks/template/useI18n'
import { layoutBlocks } from '@/layout/designer'
import type { LayoutBlock, LayoutDesign } from '@/layout/designer'
import { NButton } from 'naive-ui'
import type { PropType } from 'vue'
import { useLayoutDraftPreview } from './useLayoutDraftPreview'
type Brick = LayoutBlock | 'sidebar' | 'footer'
type Region = 'rows' | 'bottomRows'
const bricks: readonly Brick[] = [...layoutBlocks, 'sidebar', 'footer']
const regions: Region[] = ['rows', 'bottomRows']
const isRowBrick = (brick: Brick | undefined): brick is LayoutBlock =>
!!brick && brick !== 'sidebar' && brick !== 'footer'
type Arrangement = Pick<
LayoutDesign,
'rows' | 'bottomRows' | 'sidebar' | 'footer'
>
function withoutBrick(rows: LayoutBlock[][], brick: LayoutBlock) {
return rows
.map((row) => row.filter((item) => item !== brick))
.filter((row) => row.length)
}
export default defineComponent({
name: 'LayoutCanvas',
props: {
design: { type: Object as PropType<LayoutDesign>, required: true },
onArrange: {
type: Function as PropType<(patch: Partial<Arrangement>) => void>,
required: true,
},
},
setup(props) {
const { t } = useI18n('layout.designer')
const design = props.design
const { canPreview, previewing, togglePreview } =
useLayoutDraftPreview(design)
const selected = ref<Brick>()
const dragging = ref<Brick>()
const dropHint = ref('')
const dropAfter = ref(false)
const announcement = ref('')
const editor = useTemplateRef<HTMLElement>('editor')
const rowsOf = (region: Region) => design[region] ?? []
const positionOf = (brick: LayoutBlock) => {
for (const region of regions) {
const row = rowsOf(region).findIndex((items) => items.includes(brick))
if (row >= 0)
return { region, row, column: rowsOf(region)[row].indexOf(brick) }
}
}
const position = computed(() =>
isRowBrick(selected.value) ? positionOf(selected.value) : void 0,
)
const isPlaced = (brick: Brick) => {
if (brick === 'sidebar') return design.sidebar !== 'none'
if (brick === 'footer') return !!design.footer
return !!positionOf(brick)
}
const rowName = (region: Region, row: number) =>
t(region === 'rows' ? 'topRow' : 'bottomRow', { row: row + 1 })
function place(
brick: LayoutBlock,
region: Region,
row: number,
before?: LayoutBlock,
) {
if (brick === before) return
const rows = rowsOf(region).map((items) =>
items.filter((b) => b !== brick),
)
const target = rows[row] ?? (rows[row] = [])
const index = before ? target.indexOf(before) : -1
target.splice(index < 0 ? target.length : index, 0, brick)
const other = region === 'rows' ? 'bottomRows' : 'rows'
props.onArrange({
[other]: withoutBrick(rowsOf(other), brick),
[region]: rows.filter((items) => items.length),
})
selected.value = brick
announcePosition(brick)
}
function announcePosition(brick: LayoutBlock) {
const pos = positionOf(brick)
if (pos)
announcement.value = t('placed', {
block: t(brick),
row: rowName(pos.region, pos.row),
position: pos.column + 1,
})
const control = document.activeElement
if (
control instanceof HTMLButtonElement &&
control.closest('.layout-designer__inspector')
) {
void nextTick(() => {
if (control.disabled)
editor.value
?.querySelector<HTMLElement>(`[data-tile="${brick}"]`)
?.focus()
})
}
}
function setSide(side: 'left' | 'right') {
props.onArrange({ sidebar: side })
selected.value = 'sidebar'
announcement.value = t(side === 'left' ? 'sidebarLeft' : 'sidebarRight')
}
function add(brick: Brick) {
selected.value = brick
if (isPlaced(brick)) return
if (brick === 'sidebar') setSide('left')
else if (brick === 'footer') {
props.onArrange({ footer: true })
announcement.value = t('added', { block: t(brick) })
} else place(brick, 'rows', design.rows.length)
}
function remove(brick: Brick) {
if (brick === 'sidebar') props.onArrange({ sidebar: 'none' })
else if (brick === 'footer') props.onArrange({ footer: false })
else {
const pos = positionOf(brick)
if (pos)
props.onArrange({
[pos.region]: withoutBrick(rowsOf(pos.region), brick),
})
}
selected.value = void 0
announcement.value = t('removed', { block: t(brick) })
void nextTick(() =>
editor.value
?.querySelector<HTMLElement>(`[data-palette="${brick}"]`)
?.focus(),
)
}
function shiftRow(offset: number) {
const pos = position.value
if (!pos || !isRowBrick(selected.value)) return
// 内容区占据一个固定位置;整行可以在移动时越过它。
const outlet = Symbol('outlet')
const sequence = [...design.rows, outlet, ...rowsOf('bottomRows')]
const index =
pos.region === 'rows' ? pos.row : design.rows.length + pos.row + 1
const next = index + offset
if (next < 0 || next >= sequence.length) return
sequence.splice(next, 0, ...sequence.splice(index, 1))
const divider = sequence.indexOf(outlet)
const rows = sequence.filter((item): item is LayoutBlock[] =>
Array.isArray(item),
)
props.onArrange({
rows: rows.slice(0, divider),
bottomRows: rows.slice(divider),
})
announcePosition(selected.value)
}
function shiftBrick(offset: number) {
const pos = position.value
if (!pos || !isRowBrick(selected.value)) return
const rows = [...rowsOf(pos.region)]
const row = [...rows[pos.row]]
const next = pos.column + offset
if (next < 0 || next >= row.length) return
row.splice(next, 0, ...row.splice(pos.column, 1))
rows[pos.row] = row
props.onArrange({ [pos.region]: rows })
announcePosition(selected.value)
}
function clearDrag() {
dragging.value = void 0
dropHint.value = ''
dropAfter.value = false
}
function dragStart(event: DragEvent, brick: Brick) {
if (!event.dataTransfer) return
event.dataTransfer.setData('text/plain', t(brick))
event.dataTransfer.effectAllowed = 'move'
dragging.value = brick
}
function dropEvents(
id: string,
accepts: boolean,
apply: (brick: Brick, after: boolean) => void,
splitAtMiddle = false,
) {
const onTrailingHalf = (event: DragEvent) => {
if (!splitAtMiddle) return false
const bounds = (
event.currentTarget as HTMLElement
).getBoundingClientRect()
return event.clientX > bounds.left + bounds.width / 2
}
return {
'data-drop-after':
(splitAtMiddle && dropHint.value === id && dropAfter.value) || void 0,
'data-drop-active':
(dropHint.value === id && dragging.value !== id) || void 0,
onDragover(event: DragEvent) {
if (!dragging.value || !accepts) return
event.preventDefault()
event.stopPropagation()
dropHint.value = id
dropAfter.value = onTrailingHalf(event)
},
onDragleave() {
if (dropHint.value === id) dropHint.value = ''
},
onDrop(event: DragEvent) {
const brick = dragging.value
if (!brick || !accepts) return
event.preventDefault()
event.stopPropagation()
clearDrag()
apply(brick, onTrailingHalf(event))
},
}
}
function tile(brick: Brick, region?: Region, row = 0) {
return (
<button
type="button"
key={brick}
class={['layout-designer__tile', `layout-designer__tile--${brick}`]}
data-tile={brick}
aria-pressed={selected.value === brick}
draggable="true"
onDragstart={(event) => dragStart(event, brick)}
onDragend={clearDrag}
onClick={() => {
selected.value = brick
}}
{...(region && isRowBrick(brick)
? dropEvents(
brick,
isRowBrick(dragging.value),
(item, after) => {
if (!isRowBrick(item) || item === brick) return
const items = rowsOf(region)[row]
const before = after ? items[items.indexOf(brick) + 1] : brick
place(item, region, row, before)
},
true,
)
: {})}
>
{t(brick)}
</button>
)
}
function renderRows(region: Region) {
const rows = rowsOf(region)
return (
<div class="layout-designer__rows" data-region={region}>
{rows.map((row, index) => (
<div
key={[...row].sort().join('-')}
class="layout-designer__row"
aria-label={rowName(region, index)}
role="group"
{...dropEvents(
`${region}-${index}`,
isRowBrick(dragging.value),
(item) => {
if (isRowBrick(item)) place(item, region, index)
},
)}
>
{row.map((brick) => tile(brick, region, index))}
</div>
))}
<button
type="button"
class="layout-designer__drop layout-designer__new-row"
aria-disabled={!isRowBrick(selected.value)}
tabindex={isRowBrick(selected.value) ? 0 : -1}
onClick={() => {
if (isRowBrick(selected.value))
place(selected.value, region, rows.length)
}}
{...dropEvents(region, isRowBrick(dragging.value), (item) => {
if (isRowBrick(item)) place(item, region, rows.length)
})}
>
{t(region === 'rows' ? 'newTop' : 'newBottom')}
</button>
</div>
)
}
function sideZone(side: 'left' | 'right') {
if (dragging.value === 'sidebar' && design.sidebar !== side)
return (
<div
class="layout-designer__drop layout-designer__rail"
data-side={side}
{...dropEvents(side, true, () => setSide(side))}
>
{t(side === 'left' ? 'sidebarLeft' : 'sidebarRight')}
</div>
)
if (design.sidebar === side) return tile('sidebar')
}
function placementControls(brick: LayoutBlock) {
const pos = positionOf(brick)
if (!pos) return
const rows = rowsOf(pos.region)
return (
<>
<label>
{t('position')}
<select
aria-label={t('position')}
value={`${pos.region}:${pos.row}`}
onChange={(event) => {
const [region, index] = (
event.currentTarget as HTMLSelectElement
).value.split(':')
if (region === 'rows' || region === 'bottomRows')
place(brick, region, Number(index))
}}
>
{regions.map((region) => (
<optgroup
key={region}
label={t(region === 'rows' ? 'aboveContent' : 'belowContent')}
>
{rowsOf(region).map((_, index) => (
<option key={index} value={`${region}:${index}`}>
{rowName(region, index)}
</option>
))}
<option value={`${region}:${rowsOf(region).length}`}>
{t(region === 'rows' ? 'newTop' : 'newBottom')}
</option>
</optgroup>
))}
</select>
</label>
<div class="layout-designer__buttons">
<NButton
size="small"
disabled={pos.column === 0}
onClick={() => shiftBrick(-1)}
>
{t('left')}
</NButton>
<NButton
size="small"
disabled={pos.column === rows[pos.row].length - 1}
onClick={() => shiftBrick(1)}
>
{t('right')}
</NButton>
<NButton
size="small"
disabled={pos.region === 'rows' && pos.row === 0}
onClick={() => shiftRow(-1)}
>
{t('rowUp')}
</NButton>
<NButton
size="small"
disabled={
pos.region === 'bottomRows' && pos.row === rows.length - 1
}
onClick={() => shiftRow(1)}
>
{t('rowDown')}
</NButton>
</div>
</>
)
}
return () => (
<section ref="editor" class="layout-designer__grid">
<div class="layout-designer__palette">
<h3>{t('library')}</h3>
<p>{t('libraryHint')}</p>
<div class="layout-designer__bricks">
{bricks.map((brick) => (
<button
key={brick}
type="button"
draggable="true"
data-palette={brick}
class="layout-designer__brick"
title={t(isPlaced(brick) ? 'selectBlock' : 'addBlock', {
block: t(brick),
})}
aria-label={t(isPlaced(brick) ? 'selectBlock' : 'addBlock', {
block: t(brick),
})}
onDragstart={(event) => dragStart(event, brick)}
onDragend={clearDrag}
onClick={() => add(brick)}
>
<span>{t(brick)}</span>
<span aria-hidden="true">{isPlaced(brick) ? '✓' : '+'}</span>
</button>
))}
</div>
</div>
<div class="layout-designer__workspace">
<div class="layout-designer__canvas-title">
<h3>{t('preview')}</h3>
{canPreview.value && (
<NButton
size="small"
aria-pressed={previewing.value}
onClick={togglePreview}
>
{t(previewing.value ? 'endPreview' : 'tryPreview')}
</NButton>
)}
</div>
<div class="layout-designer__canvas" data-sidebar={design.sidebar}>
{sideZone('left')}
<div class="layout-designer__viewer">
{renderRows('rows')}
<div class="layout-designer__outlet">
<strong>{t('content')}</strong>
<small>{t('contentHint')}</small>
</div>
{renderRows('bottomRows')}
{design.footer
? tile('footer')
: dragging.value === 'footer' && (
<div
class="layout-designer__drop layout-designer__footer-drop"
{...dropEvents('footer', true, () => add('footer'))}
>
{t('footer')}
</div>
)}
</div>
{sideZone('right')}
</div>
{selected.value && (
<div class="layout-designer__inspector">
<div class="layout-designer__selection">
<strong>{t(selected.value)}</strong>
<NButton
size="small"
onClick={() => {
if (selected.value) remove(selected.value)
}}
>
{t('remove')}
</NButton>
</div>
{isRowBrick(selected.value) && placementControls(selected.value)}
{selected.value === 'sidebar' && (
<div class="layout-designer__buttons">
{(['left', 'right'] as const).map((side) => (
<NButton
key={side}
size="small"
type={design.sidebar === side ? 'primary' : 'default'}
aria-pressed={design.sidebar === side}
onClick={() => setSide(side)}
>
{t(side === 'left' ? 'sidebarLeft' : 'sidebarRight')}
</NButton>
))}
</div>
)}
</div>
)}
</div>
<p class="layout-designer__sr" role="status">
{announcement.value}
</p>
</section>
)
},
})

View File

@ -0,0 +1,188 @@
import './index.scss'
import { useI18n } from '@/hooks/template/useI18n'
import {
generateLayoutSource,
layoutDefinitionsDirectory,
layoutFileName,
layoutWriteEndpoint,
} from '@/layout/designer'
import type { LayoutDesign } from '@/layout/designer'
import { useLayout } from '@/layout/useLayout'
import { NButton, NCard, NCheckbox, NInput } from 'naive-ui'
import LayoutCanvas from './LayoutCanvas'
const localProject =
import.meta.env.DEV &&
__LAYOUT_PROJECT_WRITER__ &&
window.self === window.top &&
['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)
export default defineComponent({
name: 'LayoutDesigner',
setup() {
const { t } = useI18n('layout.designer')
const design = reactive<LayoutDesign>({
id: 'my-workspace',
label: t('defaultName'),
rows: [],
bottomRows: [],
selectable: true,
sidebar: 'none',
footer: false,
})
const { layouts } = useLayout()
const registered = computed(() =>
layouts.value.some((layout) => layout.id === design.id),
)
const busy = ref(false)
const notice = ref('')
const writtenId = ref('')
const source = computed(() => {
try {
return generateLayoutSource(design)
} catch {
return ''
}
})
async function generate() {
if (busy.value || !source.value || registered.value) return
busy.value = true
notice.value = ''
const snapshot: LayoutDesign = {
...design,
rows: design.rows.map((row) => [...row]),
bottomRows: (design.bottomRows ?? []).map((row) => [...row]),
}
try {
if (localProject) {
const response = await fetch(layoutWriteEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Ray-Layout-Write': '1',
},
body: JSON.stringify(snapshot),
})
if (!response.ok)
throw new Error(response.status === 409 ? 'exists' : 'write')
writtenId.value = snapshot.id
notice.value = t('written', {
path:
layoutDefinitionsDirectory + '/' + layoutFileName(snapshot.id),
})
} else {
const url = URL.createObjectURL(
new Blob([generateLayoutSource(snapshot)], {
type: 'text/plain;charset=utf-8',
}),
)
const link = document.createElement('a')
link.href = url
link.download = layoutFileName(snapshot.id)
link.click()
setTimeout(() => URL.revokeObjectURL(url), 1000)
notice.value = t('downloaded', { name: link.download })
}
} catch (error) {
notice.value = t(
error instanceof Error && error.message === 'exists'
? 'exists'
: 'writeError',
)
} finally {
busy.value = false
}
}
return () => (
<NCard title={t('title')} class="layout-designer">
<LayoutCanvas
design={design}
onArrange={(patch) => Object.assign(design, patch)}
/>
<div class="layout-designer__project">
<div class="layout-designer__fields">
<label>
{t('id')}
<NInput
inputProps={{ 'aria-label': t('id') }}
value={design.id}
onUpdateValue={(value) => {
design.id = value
writtenId.value = ''
notice.value = ''
}}
/>
</label>
<label>
{t('name')}
<NInput
inputProps={{ 'aria-label': t('name') }}
value={design.label}
onUpdateValue={(value) => {
design.label = value
}}
/>
</label>
</div>
<div class="layout-designer__buttons">
<NCheckbox
checked={design.autoRegister ?? true}
onUpdateChecked={(value) => {
design.autoRegister = value
}}
>
{t('autoRegister')}
</NCheckbox>
<NCheckbox
checked={design.selectable}
onUpdateChecked={(value) => {
design.selectable = value
}}
>
{t('selectable')}
</NCheckbox>
</div>
<p>{t(localProject ? 'local' : 'downloadHint')}</p>
<code>
{layoutDefinitionsDirectory}/
{source.value ? layoutFileName(design.id) : '…'}
</code>
<div class="layout-designer__buttons">
<NButton
type="primary"
disabled={
!source.value ||
registered.value ||
writtenId.value === design.id
}
loading={busy.value}
onClick={generate}
>
{t(localProject ? 'generate' : 'download')}
</NButton>
</div>
{registered.value && writtenId.value !== design.id && (
<p>{t('duplicate')}</p>
)}
{!source.value && <p>{t('invalid')}</p>}
<p role="status">{notice.value}</p>
</div>
{source.value && (
<details>
<summary>{t('source')}</summary>
<pre class="r-demo-code">
<code>{source.value}</code>
</pre>
</details>
)}
</NCard>
)
},
})

View File

@ -0,0 +1,251 @@
.layout-designer {
container-type: inline-size;
min-inline-size: 0;
h3 {
margin: 0 0 10px;
font-size: 1rem;
color: var(--r-text);
}
&__grid,
&__workspace,
&__viewer,
&__rows,
&__inspector {
display: grid;
align-content: start;
min-inline-size: 0;
}
&__grid {
gap: 20px;
}
&__workspace {
grid-template-columns: minmax(0, 1fr);
}
&__bricks,
&__fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 120px), 1fr));
gap: 8px;
}
&__palette p,
&__project p {
color: var(--r-text-secondary);
margin: 0 0 12px;
}
&__brick,
&__tile {
min-inline-size: 0;
min-block-size: 44px;
padding: 6px 10px;
background: var(--r-surface);
border: 1px solid var(--r-control-border);
border-radius: var(--r-control-radius);
color: var(--r-text);
font: inherit;
cursor: grab;
overflow-wrap: anywhere;
&:hover {
background-color: var(--r-surface-hover);
}
}
&__brick {
display: flex;
justify-content: space-between;
align-items: center;
gap: 6px;
text-align: start;
}
&__brick span:last-child {
color: var(--r-primary-text);
}
&__tile[aria-pressed='true'] {
border-color: var(--r-theme-primary-color);
color: var(--r-selected-text);
box-shadow: inset 0 0 0 1px var(--r-theme-primary-color);
}
&__canvas {
position: relative;
display: flex;
align-items: stretch;
min-inline-size: 0;
gap: 6px;
padding: 10px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background-color: var(--r-surface-muted);
}
&__viewer {
position: relative;
flex: 1 1 0;
gap: 6px;
}
&__row {
display: flex;
gap: 4px;
min-inline-size: 0;
padding: 2px;
border-radius: var(--r-control-radius);
> * {
flex: 1 1 0;
}
}
&__rows {
gap: 4px;
}
&__outlet {
display: grid;
place-content: center;
gap: 4px;
padding: 12px;
min-block-size: 120px;
border: 1px dashed var(--r-control-border);
border-radius: var(--r-control-radius);
background-color: var(--r-canvas);
color: var(--r-text-secondary);
text-align: center;
overflow-wrap: anywhere;
}
&__tile--sidebar {
flex: 0 1 19%;
}
&__rail,
&__footer-drop {
position: absolute;
z-index: 1;
background: var(--r-surface);
}
&__rail {
inset-block: 4px;
inline-size: 22%;
&[data-side='left'] {
inset-inline-start: 4px;
}
&[data-side='right'] {
inset-inline-end: 4px;
}
}
&__footer-drop {
inset-inline: 0;
inset-block-end: 0;
}
&__new-row {
color: var(--r-text-secondary);
background: transparent;
font: inherit;
cursor: pointer;
&[aria-disabled='true'] {
cursor: default;
}
}
&__drop {
display: grid;
place-items: center;
min-inline-size: 0;
min-block-size: 36px;
border: 1px dashed var(--r-control-border);
border-radius: var(--r-control-radius);
text-align: center;
overflow-wrap: anywhere;
}
[data-drop-active] {
outline: 2px solid var(--r-theme-primary-color);
outline-offset: -2px;
}
&__tile[data-drop-after] {
--layout-drop-edge: -4px;
}
&__canvas-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-block-end: 10px;
h3 {
margin: 0;
}
}
&__tile[data-drop-active] {
outline: none;
box-shadow: inset var(--layout-drop-edge, 4px) 0
var(--r-theme-primary-color);
}
&__inspector {
gap: 10px;
margin-block-start: 10px;
padding: 10px;
border: 1px solid var(--r-line);
border-radius: var(--r-control-radius);
}
&__selection,
&__buttons {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
}
&__selection {
justify-content: space-between;
}
&__fields,
&__project > &__buttons {
margin-block-end: 12px;
}
&__fields label,
&__inspector label {
display: grid;
gap: 4px;
color: var(--r-text-secondary);
}
&__inspector select {
min-inline-size: 0;
min-block-size: 36px;
inline-size: 100%;
padding-inline: 8px;
border: 1px solid var(--r-control-border);
border-radius: var(--r-control-radius);
background: var(--r-surface);
color: var(--r-text);
font: inherit;
}
&__project {
margin-block: 20px 12px;
padding-block-start: 16px;
border-block-start: 1px solid var(--r-line);
}
&__project code {
display: block;
margin-block: 6px 12px;
overflow-wrap: anywhere;
font-family: var(--r-font-mono);
}
summary {
cursor: pointer;
color: var(--r-primary-text);
}
&__sr {
position: absolute;
inline-size: 1px;
block-size: 1px;
overflow: hidden;
clip-path: inset(50%);
}
}
@container (min-width: 760px) {
.layout-designer__grid {
grid-template-columns: minmax(160px, 1fr) minmax(0, 3fr);
}
}
@container (max-width: 420px) {
.layout-designer__canvas {
padding: 4px;
gap: 3px;
}
.layout-designer__tile {
padding-inline: 2px;
}
}

View File

@ -0,0 +1,78 @@
import { useDevice } from '@/hooks'
import {
LayoutBreadcrumb,
LayoutFooter,
LayoutFrame,
LayoutHeaderActions,
LayoutNavigation,
LayoutRow,
LayoutTabs,
LayoutTopNavigation,
} from '@/layout/blocks'
import type { LayoutBlock, LayoutDesign } from '@/layout/designer'
import { layoutHostKey } from '@/layout/host-context'
import type { Component } from 'vue'
const blocks = {
actions: LayoutHeaderActions,
breadcrumb: LayoutBreadcrumb,
navigation: LayoutTopNavigation,
tabs: LayoutTabs,
} satisfies Record<LayoutBlock, Component>
export function useLayoutDraftPreview(design: LayoutDesign) {
const host = inject(layoutHostKey, null)
const { isTabletOrSmaller } = useDevice()
const canPreview = computed(() => !!host && !isTabletOrSmaller.value)
const rows = (groups: LayoutBlock[][]) =>
groups.length
? () =>
groups.map((group) => (
<LayoutRow>
{group.map((block) => h(blocks[block], { key: block }))}
</LayoutRow>
))
: void 0
const renderer = defineComponent({
name: 'WorkspaceDraftPreview',
setup: () => () => (
<LayoutFrame
sidebarPlacement={design.sidebar === 'right' ? 'right' : 'left'}
>
{{
header: rows(design.rows),
bottom: rows(design.bottomRows ?? []),
sidebar:
design.sidebar && design.sidebar !== 'none'
? () => <LayoutNavigation end={design.sidebar === 'right'} />
: void 0,
footer: design.footer ? () => <LayoutFooter /> : void 0,
}}
</LayoutFrame>
),
})
const previewing = computed(() => host?.draftRenderer.value === renderer)
const stop = () => {
if (host?.draftRenderer.value === renderer)
host.draftRenderer.value = void 0
}
watch(
canPreview,
(available) => {
if (!available) stop()
},
{ flush: 'sync' },
)
onDeactivated(stop)
onScopeDispose(stop)
return {
canPreview,
previewing,
togglePreview: () => {
if (previewing.value) stop()
else if (host && canPreview.value) host.draftRenderer.value = renderer
},
}
}

View File

@ -1,3 +1,4 @@
import { LAYOUT_SIDER_REF } from '@/app-config'
import {
useAppNavigation,
useBadge,
@ -354,13 +355,13 @@ export default defineComponent({
() => (
<NFlex>
<NButton
disabled={settings.getLayoutConfig.value.mode === 'top'}
disabled={!LAYOUT_SIDER_REF.value}
onClick={() => siderScrollTo({ top: 0, behavior: 'smooth' })}
>
{text('siderTop')}
</NButton>
<NButton
disabled={settings.getLayoutConfig.value.mode === 'top'}
disabled={!LAYOUT_SIDER_REF.value}
onClick={() => siderScrollTo(0, 300)}
>
{text('sider300')}

View File

@ -2,6 +2,7 @@
<script setup>
import { withBase } from 'vitepress'
import AdminExample from '../../examples/AdminExample.vue'
</script>
Open the layout playground or the **Layout** tab in the top bar's Preferences drawer to switch navigation and workspace settings. Desktop modes are side (`side`), top (`top`), mixed (`mixed`), right (`right`), and split (`split`). Mixed mode puts first-level navigation at the top and displays only the active group's children in the sidebar. At widths of 768 px or less, navigation uses a drawer and preserves desktop preferences.
@ -18,6 +19,18 @@ Try a different navigation position, pin the header, or change content width. Th
Press Tab to focus menu items and Enter or Space to expand a group or open a page. Use Up and Down in the sidebar and Left and Right in the top menu. In submenus from the collapsed sidebar or top menu, use the arrow keys to select, Enter to open, and Esc to close.
## Custom layouts and source generation {#自定义布局与源码生成}
The designer starts with a fixed area for the current page. Click a block to add it or drag it into position. Place breadcrumbs, actions, tabs and navigation above or below the page. Combine blocks in a row, reorder them, or move the whole row. Add a left or right sidebar and an optional footer. Selecting a block exposes the same placement and ordering controls for keyboard and touch.
At desktop widths, try the draft to see its actual components around the current page. You can continue editing while trying it and return to your saved layout when done. If the embedded example is too narrow, choose **Run this example in a new tab** to try a desktop layout. The built-in **Two-row top** puts tabs beside the actions in the first row and navigation in the second.
Enter a unique layout ID and display name. In a top-level page on a loopback Vite development server, **Generate into project** creates `apps/admin/src/layout/definitions/<id>.layout.tsx`. Existing files are protected. Production pages, remote previews and embedded previews offer **Download layout source**. Place the downloaded file in the same directory. The next build includes the new layout in your deployment. Discovery imports layout modules as executable project code. Review third-party TSX before placing it in this directory.
`autoRegister` controls automatic registration and `selectable` controls entry into a registered layout. Both default to true. In component setup, import `useLayout` from `@/layout/api` to read `layouts` and `activeLayoutId`, call `updateLayout('custom-top')` to switch, or call `registerLayout(definition)` to register explicitly. Existing settings actions also support changes to width and spacing.
<AdminExample path="/layout-demo" title="Layout playground and source generation" layout :height="740" deferred />
## Configure the workspace {#配置工作区}
```ts

View File

@ -24,7 +24,24 @@ For routine changes, run the relevant test files or `pnpm harness verify <scope>
The root `package.json` exposes a command for each suite directory under `__test__`. `pnpm test:utils` runs the utility suites together. Use `pnpm test:run <file>` to run an individual test file.
`pnpm lint` checks the entire workspace. Run `pnpm lint:fix <file> [...]` with individual code file paths to apply fixes. The fixer replaces reads of the built-in runtime `undefined` with `void 0` and keeps `undefined` in type positions. Use `pnpm exec prettier --check <file>` to check Markdown and JSON formatting.
`pnpm lint` checks the entire workspace. Run these autofix commands from the repository root.
| Command | Scope |
| --------------------------------- | -------------------------------------------------------------------------------------------------- |
| `pnpm lint:fix` | ESLint across the repository |
| `pnpm lint:fix <file> [...]` | ESLint for the named code files |
| `pnpm format:fix` / `pnpm format` | Prettier across the repository |
| `pnpm fix` | ESLint and Prettier across the repository |
| `pnpm <workspace>:fix` | ESLint and Prettier for one workspace, such as `pnpm admin:fix`, `pnpm docs:fix`, or `pnpm ui:fix` |
| `pnpm packages:fix` | ESLint and Prettier for all shared packages |
| `pnpm fix <directory>` | ESLint and Prettier for the named directory |
<!-- fullstack:start -->
In the fullstack edition, use `pnpm server:fix` to fix the backend workspace.
<!-- fullstack:end -->
Combined commands run ESLint before Prettier. If ESLint still reports errors or warnings, the command exits with a nonzero status after formatting. ESLint replaces reads of the built-in runtime `undefined` with `void 0` and keeps `undefined` in type positions. Use `pnpm exec prettier --check <file>` to check Markdown and JSON formatting.
Full checks cover the environment, Harness, API and package boundaries, icon synchronization, types, ESLint, Prettier, Vitest, and both admin and docs builds. `pnpm harness verify` with no scope still runs the full suite. Specify a scope for routine work. Harness saves command results in `.harness-local/runs/`. Browser acceptance runs separately from these commands.

View File

@ -14,6 +14,26 @@ These APIs operate on the template's default layout. Check [layout slots and ins
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useLayout
Import `useLayout` from `@/layout/api` and call it in component setup. Each application instance owns a registry.
| Member | Behavior |
| -------------------------------- | --------------------------------------------------------------------------------- |
| `layouts` | Read-only list of registered layouts, including disabled choices. |
| `selectedLayoutId` | Saved layout ID used for restoration. |
| `activeLayout`, `activeLayoutId` | Resolved desktop selection. The compact host uses the full navigation drawer. |
| `registerLayout(definition)` | Explicit registration. Invalid definitions and duplicate IDs throw. |
| `updateLayout(id)` | Returns `true` for an available choice and `false` for an unknown or disabled ID. |
An optional `preview` describes the thumbnail in layout settings. For example, `{ rows: [['actions']], bottomRows: [['tabs']], sidebar: 'right', footer: true }` places actions above the content, tabs below it, and navigation on the right. The designer generates this metadata from the arrangement. A handwritten definition without a preview uses the thumbnail for its `fallbackMode`, which defaults to the sidebar layout.
See the [layout file conventions and playground](../../guide/layout#自定义布局与源码生成).
A layout component can use Vue’s `defineAsyncComponent`. With its default loading behavior, the previous page stays interactive. After the new layout mounts, the host checks that it has one content outlet. A loading error or an invalid outlet count restores the last working layout. If the user switches again while loading, the latest selection wins.
Built-in and designer-generated layouts share the main content container, preserving an iframe’s document and unsaved input when switching layouts. If a handwritten layout needs to move the page to a different DOM parent and the browser lacks state-preserving moves, the host keeps the embedded document open and indicates when it will apply the change.
## useMaximize
`useMaximize(defaults?)` returns `isLayoutContentMaximized`, its alias `isFullscreen`, `maximize(full, options?)`, and `toggleFullscreen()`. The page, tab menu, and exit button use the same Pinia state. For a single DOM element, use [useElementFullscreen](./browser#useelementfullscreen).

View File

@ -2,6 +2,7 @@
<script setup>
import { withBase } from 'vitepress'
import AdminExample from '../examples/AdminExample.vue'
</script>
打开「布局实验室」或顶部设置抽屉里的「布局」页签,切换导航和工作区。桌面支持侧边 `side`、顶部 `top`、混合 `mixed`、右侧 `right` 和通栏分组 `split` 导航;混合模式把一级导航放在顶部,侧栏只显示当前分组的子菜单。宽度不超过 768px 时改用抽屉,保留原桌面偏好。
@ -18,6 +19,18 @@ import { withBase } from 'vitepress'
菜单支持键盘操作。Tab 可聚焦菜单项,Enter 或空格展开分组或打开页面。侧栏用上下方向键移动焦点,顶部菜单用左右方向键。折叠侧栏和顶部菜单的子菜单可用方向键选择、Enter 打开、Esc 关闭。
## 自定义布局与源码生成
「布局实验室」从一块固定的路由内容区开始。点击积木将其加入画布,或直接拖到目标位置。面包屑、操作栏、页面标签和导航都能放在内容上方或下方,可合并到同一行、调整行内顺序或移动整行。侧栏可放在左侧或右侧,页脚可单独添加。选中画布里的积木,也可以用位置菜单和移动按钮完成这些操作。
在桌面宽度点击「试用布局」,当前页面就会使用草稿中的真实组件。可以边试用边编辑,结束试用后返回原布局。下方文档示例宽度较窄时,请点「在新标签页运行此示例」试用桌面布局。内置的「双行顶部」将页面标签和操作栏放在第一行,导航放在第二行。
填写唯一的布局 ID 和显示名称。独立打开本机回环地址的 Vite 开发页面时,「生成到工程」会在 `apps/admin/src/layout/definitions/<id>.layout.tsx` 创建源码文件,同名文件会提示冲突。生产页面、远程访问及嵌入预览提供「下载布局源码」,将文件放入该目录即可参与发现。部署站点在下次构建发布时包含新布局。布局定义会作为工程代码导入,来自其他人的 TSX 应先审阅再放入目录。
`autoRegister` 控制自动注册,`selectable` 控制是否允许进入已注册的布局。两者默认开启。在组件的 `setup()` 中调用 `useLayout()`(从 `@/layout/api` 导入)可读取 `layouts` 和 `activeLayoutId`,使用 `updateLayout('custom-top')` 切换,使用 `registerLayout(definition)` 显式注册。页面宽度和间距仍可通过原有的设置接口调整。
<AdminExample path="/layout-demo" title="布局实验室与源码生成" layout :height="740" deferred />
## 配置工作区
```ts

View File

@ -24,7 +24,24 @@
根 `package.json` 按 `__test__` 中的测试目录提供模块命令。`pnpm test:utils` 一起运行各工具测试目录。单个文件可用 `pnpm test:run <文件>` 运行。
`pnpm lint` 检查整个工作区。自动修复用 `pnpm lint:fix <文件> [...]`,逐个指定要修复的代码文件。修复会将内置 `undefined` 的运行时读取改成 `void 0`,类型位置仍使用 `undefined`。Markdown 和 JSON 的格式用 `pnpm exec prettier --check <文件>` 检查。
`pnpm lint` 检查整个工作区。以下自动修复命令均从仓库根目录运行。
| 命令 | 修复范围 |
| --------------------------------- | -------------------------------------------------------------------------------------- |
| `pnpm lint:fix` | 全仓 ESLint |
| `pnpm lint:fix <文件> [...]` | 指定代码文件的 ESLint |
| `pnpm format:fix` / `pnpm format` | 全仓 Prettier |
| `pnpm fix` | 全仓 ESLint 和 Prettier |
| `pnpm <模块>:fix` | 单个工作区的 ESLint 和 Prettier,例如 `pnpm admin:fix`、`pnpm docs:fix`、`pnpm ui:fix` |
| `pnpm packages:fix` | 所有共享包的 ESLint 和 Prettier |
| `pnpm fix <目录>` | 指定目录的 ESLint 和 Prettier |
<!-- fullstack:start -->
全栈版也可以用 `pnpm server:fix` 修复后端工作区。
<!-- fullstack:end -->
合并命令先运行 ESLint,再运行 Prettier。若仍有 lint 错误或警告,命令在格式化后返回非零退出码。ESLint 会将内置 `undefined` 的运行时读取改成 `void 0`,类型位置仍使用 `undefined`。Markdown 和 JSON 的格式用 `pnpm exec prettier --check <文件>` 检查。
全量检查包含环境、Harness、API 与包边界、图标同步、类型、ESLint、Prettier、Vitest,以及后台和文档构建。`pnpm harness verify` 省略 scope 时仍执行全量,日常使用应显式指定 scope。Harness 在 `.harness-local/runs/` 写命令结果,所有命令均不启动浏览器。

View File

@ -14,6 +14,26 @@ import AdminExample from '../../examples/AdminExample.vue'
<<< @/../admin/src/views/demo/template-hooks/index.tsx
:::
## useLayout
从 `@/layout/api` 导入,在组件的 `setup()` 中调用。每个应用实例独立管理注册表。
| 成员 | 用法 |
| -------------------------------- | --------------------------------------------------------- |
| `layouts` | 只读的已注册布局列表,包含禁止切换的布局。 |
| `selectedLayoutId` | 保存的布局 ID,用于恢复选择。 |
| `activeLayout`、`activeLayoutId` | 当前解析到的桌面布局。窄屏宿主使用完整菜单抽屉。 |
| `registerLayout(definition)` | 显式注册,重复 ID 或无效定义会抛错。 |
| `updateLayout(id)` | 选中可用布局时返回 `true`,未知或关闭的 ID 返回 `false`。 |
布局定义可提供 `preview` 描述设置卡片的缩略图。例如 `{ rows: [['actions']], bottomRows: [['tabs']], sidebar: 'right', footer: true }` 表示顶栏放操作区、内容下方放页面标签,并显示右侧导航和页脚。实验室根据积木组合自动生成这段配置。手写定义省略 `preview` 时,卡片使用 `fallbackMode` 的缩略图,默认使用侧边导航。
参见[布局文件约定与实验室](../../guide/layout#自定义布局与源码生成)。
布局组件可以使用 Vue 的 `defineAsyncComponent`。默认加载期间可以继续操作原页面。新布局挂载后,宿主会确认它提供一个内容出口;加载失败或出口数量有误时,会恢复上一个有效布局。连续切换时,以最后一次选择为准。
内置布局和设计器生成的布局共用主内容区,因此切换时会保留 iframe 的文档和未保存输入。手写布局若需要跨 DOM 容器移动页面,而浏览器缺少原子移动能力,宿主会保留正在使用的内嵌文档,并提示何时应用新布局。
## useMaximize
`useMaximize(defaults?)` 返回 `isLayoutContentMaximized`(`isFullscreen` 是同一状态的别名)、`maximize(full, options?)`、`toggleFullscreen()`。页面、标签菜单和退出按钮共享同一个 Pinia 状态。需要单独放大一个 DOM 元素时,使用 [useElementFullscreen](./browser#useelementfullscreen)。

View File

@ -311,3 +311,9 @@ Local lint passed. Rule probes rejected deprecated calls, property reads, option
`pnpm lint:fix` requires individual file paths. The local `ray-template/no-undefined` rule fixes value reads of the built-in binding and preserves TypeScript type positions. Shadowing bindings and writes require a manual edit. [Rule](../scripts/eslint-rules/no-undefined.mjs) · [Fix command](../scripts/lint-fix.mjs)
Workspace lint and the toolchain Harness passed. The scoped command fixed TS, TSX, and Vue script fixtures while preserving their type annotations and an unselected sibling file. The command rejected empty input and directories before writing. [Rule regressions](../__test__/workspace/no-undefined.spec.ts)
## 2026-12-01 Workspace autofix commands
`pnpm lint:fix` defaults to the whole workspace. Explicit file paths retain their previous scope, including paths passed by the commit hook. `pnpm fix` and the workspace aliases apply ESLint followed by Prettier. Remaining lint errors or warnings produce a nonzero exit status after formatting. [Root scripts](../package.json)
On macOS with Node.js 26.13.0 and pnpm 12.16.1, a temporary source copy verified both ESLint modes, the staged-file hook, all 13 workspace aliases, the shared-package group, and the combined and format-only commands. The combined command still formatted files when ESLint reported an error requiring manual repair. Source export verification included both editions and confirmed that `server:fix` is available in the fullstack edition. Changed-file lint and formatting, Harness index validation, and 23 targeted tests passed. Verification covered the command-line workflow and source exports. [Autofix regressions](../__test__/workspace/lint-fix.spec.ts)

View File

@ -67,7 +67,9 @@ For example, a CSV escaping fix can use `pnpm test:run __test__/components/table
`verify` runs steps sequentially, stops at the first failure, and returns a nonzero exit code. It prints the path to `.harness-local/runs/<run>/report.json` on completion. Reports contain commands, outcomes, durations, runtime, and signals; each invocation has a separate record. Full reports represent `pnpm check` as one step; consult that run's terminal output for phase details. Invalid arguments or context, and forcibly interrupted runs, may produce no report. None of these CLI commands launches a browser. Passing command checks does not establish UI/UX acceptance.
The Pages workflow runs `pnpm pages:build` on Ubuntu 24.04 for every push to `main`, then publishes the `dist/pages` artifact to GitHub Pages. It also supports manual dispatch on `main` and runs independently of cross-platform checks. Local full verification uses `pnpm check` according to the rules above. Use `pnpm lint`, `pnpm format:check`, or `pnpm typecheck` separately to diagnose failures. Use `pnpm lint:fix <file> [...]` to fix explicitly named code files and `pnpm exec prettier --check <files>` to check formatting. `pnpm check` synchronizes icon manifests and generates `dist/production`. Review generated diffs before delivery.
The Pages workflow runs `pnpm pages:build` on Ubuntu 24.04 for every push to `main`, then publishes the `dist/pages` artifact to GitHub Pages. It also supports manual dispatch on `main` and runs independently of cross-platform checks. Local full verification uses `pnpm check` according to the rules above. Use `pnpm lint`, `pnpm format:check`, or `pnpm typecheck` separately to diagnose failures. `pnpm check` synchronizes icon manifests and generates `dist/production`. Review generated diffs before delivery.
Run `pnpm lint:fix <file> [...]` to fix explicitly named code files and `pnpm exec prettier --check <files>` to check their formatting. With no file arguments, `pnpm lint:fix` applies ESLint fixes across the workspace. `pnpm fix` applies ESLint and Prettier fixes across the workspace. Root commands such as `pnpm admin:fix` and `pnpm ui:fix` apply both tools to the selected workspace.
### Browser verification

View File

@ -9,6 +9,8 @@ Use this topic for providers, navigation layouts, page caching, the settings dra
| Content area, loading, navigation, and KeepAlive | [Host content slot](../../apps/admin/src/layout/default/ContentWrapper/index.tsx), [host transition adapter](../../apps/admin/src/components/RTransitionComponent) | [Shared transitions and cached rendering](../../packages/admin-shell/src/RouteTransition.vue), [cache allowlist](../../apps/admin/src/store/modules/keep-alive/index.ts), [page request cancellation](api.md) |
| Layout preferences, JSON import/export, and transient state | [Settings store](../../apps/admin/src/store/modules/setting/index.ts), [preference-file validation](../../apps/admin/src/store/modules/setting/preference-file.ts), [runtime store](../../apps/admin/src/store/modules/runtime/index.ts) | [Host settings drawer](../../apps/admin/src/layout/components/SiderBar/components/SettingDrawer/index.tsx), [shared layout settings](../../packages/admin-shell/src/LayoutSettings.tsx), [reader guide](../../apps/docs/guide/layout.md) |
For a new layout or a generator change, start with the [layout definitions](../../apps/admin/src/layout/definitions), [registry](../../apps/admin/src/layout/useLayout.ts), [designer](../../apps/admin/src/layout/designer.ts), and [development writer](../../vite-helper/layout-writer.ts).
The layout package owns the shell and rendering; the application supplies navigation, settings, content, and runtime state. Access application stores through [hooks](../../apps/admin/src/store/hooks). See the [store conventions](../../apps/admin/src/store/README.md) for persistence scope and historical formats. Preference files contain layout settings only; route sources and route JSON belong to [routing](routing.md).
Targeted verification: `pnpm harness verify layout`, including [layout regressions](../../__test__/layout), [providers](../../__test__/app/global-provider.spec.ts), and related hooks. Select affected layout modes using the [browser dimensions](../README.md#browser-verification). Check narrow widths for sizing changes, and reload restoration/readback when cache or preference behavior changes.

View File

@ -15,6 +15,8 @@ Run `pnpm test:<suite>` from the root for a single suite under `__test__`, such
`pnpm lint` checks resolved `@deprecated` usages in TypeScript, TSX, JavaScript scripts, and Vue script blocks. ESLint uses the existing workspace TypeScript projects and the [script lint project](../../tsconfig.eslint-scripts.json). Use `void 0` for runtime values and `undefined` in type annotations.
Use `pnpm lint:fix <file> [...]` for autofixes. It requires existing individual file paths, rejects directories and patterns, and processes files covered by ESLint. The [local `ray-template/no-undefined` rule](../../scripts/eslint-rules/no-undefined.mjs) fixes reads of the built-in runtime value. Type positions keep `undefined`. Rename shadowing bindings by hand. Markdown and JSON are covered by Prettier. The commit hook runs the same lint fixer for staged code.
Run `pnpm lint:fix` for ESLint autofixes across the workspace. Use `pnpm lint:fix <file> [...]` to limit fixes to existing individual files. In file mode, the command rejects directories and patterns. The commit hook passes staged code files to the same fixer. The local rule fixes reads of the built-in runtime value. Type positions keep `undefined`. Rename shadowing bindings by hand. [ESLint rule](../../scripts/eslint-rules/no-undefined.mjs)
`pnpm fix` runs ESLint followed by Prettier across the workspace. Use `pnpm <workspace>:fix` for a single workspace, `pnpm packages:fix` for all shared packages, or `pnpm fix <directory>` for a specific directory. Run `pnpm format:fix` for Prettier alone, including Markdown and JSON. The combined command returns a nonzero status if ESLint still reports errors or warnings after the fixes. [Root scripts](../../package.json)
Targeted verification: `pnpm harness verify toolchain` runs package-boundary and type checks. For changes to dependencies, public exports, or build configuration, run `pnpm harness verify all` once at completion using the [verification scope](../README.md#choosing-the-verification-scope). Preview affected entry points when build artifacts or deployment paths change. Toolchain prose alone does not trigger these runtime checks. Passing targeted checks does not prove CI, Docker, or production publication succeeded.

View File

@ -75,6 +75,7 @@
"checks": ["packages:check", "typecheck"],
"tests": [
"__test__/workspace/boundaries.spec.ts",
"__test__/workspace/lint-fix.spec.ts",
"__test__/workspace/no-undefined.spec.ts",
"__test__/distribution/"
]

View File

@ -48,6 +48,22 @@
"lint:fix": "node scripts/lint-fix.mjs",
"format": "prettier --write .",
"format:check": "prettier --check .",
"format:fix": "pnpm format",
"fix": "node scripts/fix.mjs",
"admin:fix": "pnpm fix apps/admin",
"docs:fix": "pnpm fix apps/docs",
"server:fix": "pnpm fix apps/server",
"packages:fix": "pnpm fix packages",
"admin-shell:fix": "pnpm fix packages/admin-shell",
"api-contracts:fix": "pnpm fix packages/api-contracts",
"composables:fix": "pnpm fix packages/composables",
"demo-data:fix": "pnpm fix packages/demo-data",
"directives:fix": "pnpm fix packages/directives",
"http:fix": "pnpm fix packages/http",
"icons:fix": "pnpm fix packages/icons",
"routing:fix": "pnpm fix packages/routing",
"ui:fix": "pnpm fix packages/ui",
"utils:fix": "pnpm fix packages/utils",
"harness": "node harness/run.mjs",
"check": "pnpm check:frontend && pnpm server:check && pnpm dist:check",
"env:check": "node scripts/doctor.mjs",

View File

@ -23,6 +23,11 @@ export const AdminShell = defineComponent({
layout: { type: Object as PropType<LayoutConfig>, required: true },
mode: { type: String as PropType<LayoutMode>, default: void 0 },
groupedSidebar: Boolean,
sidebarPlacement: {
type: String as PropType<'left' | 'right' | 'none'>,
default: void 0,
},
wideHeader: { type: Boolean, default: void 0 },
showTabs: Boolean,
showFooter: Boolean,
busy: Boolean,
@ -32,6 +37,7 @@ export const AdminShell = defineComponent({
type: Object as PropType<CSSProperties>,
default: void 0,
},
restoreOnUnmount: { type: Boolean, default: true },
restore: { type: Function as PropType<() => void>, default: void 0 },
skipContentLabel: { type: String, default: 'Skip to main content' },
restoreLabel: { type: String, default: 'Restore layout' },
@ -78,7 +84,7 @@ export const AdminShell = defineComponent({
{ flush: 'post' },
)
onBeforeUnmount(() => {
if (props.maximized) props.restore?.()
if (props.restoreOnUnmount && props.maximized) props.restore?.()
})
const header = () => (
@ -110,11 +116,16 @@ export const AdminShell = defineComponent({
return () => {
const config = props.layout
const mode = props.mode ?? config.mode
const wideHeader = mode === 'split' && config.fixedHeader
const hasSider =
const wideHeader =
(props.wideHeader ?? mode === 'split') && config.fixedHeader
const legacySider =
mode === 'side' ||
mode === 'right' ||
((mode === 'mixed' || mode === 'split') && props.groupedSidebar)
const placement =
props.sidebarPlacement ??
(legacySider ? (mode === 'right' ? 'right' : 'left') : 'none')
const hasSider = placement !== 'none'
const sidebar = () => (hasSider ? slots.sidebar?.() : null)
return (
@ -143,10 +154,10 @@ export const AdminShell = defineComponent({
<NLayout
class="r-layout-full__body"
hasSider={hasSider}
siderPlacement={mode === 'right' ? 'right' : 'left'}
siderPlacement={placement === 'right' ? 'right' : 'left'}
embedded
>
{mode !== 'right' ? sidebar() : null}
{placement === 'left' ? sidebar() : null}
<NLayoutContent class="r-layout-full__viewer">
{config.fixedHeader ? (
<>
@ -206,7 +217,7 @@ export const AdminShell = defineComponent({
</div>
{config.fixedFooter ? footer() : null}
</NLayoutContent>
{mode === 'right' ? sidebar() : null}
{placement === 'right' ? sidebar() : null}
</NLayout>
</div>
)

View File

@ -15,25 +15,23 @@
.r-layout-presets {
box-sizing: border-box;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 72px), 1fr));
gap: 6px;
max-inline-size: min(100%, 410px);
padding: 5px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 124px), 1fr));
gap: 10px;
inline-size: 100%;
padding: 6px 12px;
}
.r-layout-preset {
position: relative;
box-sizing: border-box;
display: grid;
align-content: center;
place-items: center;
gap: 4px;
align-self: start;
align-content: start;
justify-items: center;
gap: 7px;
min-inline-size: 0;
min-block-size: 0;
min-block-size: 86px;
inline-size: 100%;
block-size: 68px;
padding: 4px;
padding: 10px 12px;
border: 1px solid var(--r-line);
border-radius: var(--r-radius);
background: var(--r-surface-muted);
@ -49,7 +47,13 @@
background-color 0.18s var(--r-bezier),
color 0.18s var(--r-bezier);
&:hover {
&:disabled {
cursor: not-allowed;
color: var(--r-text-muted);
border-style: dashed;
}
&:hover:enabled {
border-color: var(--r-theme-primary-color);
background: var(--r-surface-hover);
}
@ -62,95 +66,96 @@
var(--r-surface)
);
color: var(--r-selected-text);
font-weight: 600;
}
}
.r-layout-preset__label {
font-size: 11px;
max-inline-size: 100%;
font-size: 12px;
overflow-wrap: anywhere;
}
.r-layout-preview {
box-sizing: border-box;
display: grid;
grid-template: minmax(0, 1fr) minmax(0, 3fr) / minmax(0, 1fr) minmax(0, 3fr);
gap: 3px;
inline-size: min(65%, 37px);
max-inline-size: 100%;
aspect-ratio: 1;
padding: 4px;
display: flex;
flex-direction: column;
gap: 2px;
inline-size: min(100%, 62px);
block-size: 42px;
padding: 3px;
border: 1px solid var(--r-line);
border-radius: 8px;
border-radius: 5px;
background: var(--r-surface);
> span {
border-radius: 2px;
&__frame,
&__main {
display: flex;
flex: 1;
gap: 2px;
min-block-size: 0;
min-inline-size: 0;
}
&__main {
flex-direction: column;
}
&__aside,
&__body,
&__footer,
&__row > span {
border-radius: 1px;
background: currentColor;
}
&__aside {
grid-area: 1 / 1 / 3 / 2;
opacity: 0.65;
}
&__header {
grid-area: 1 / 2 / 2 / 3;
opacity: 0.28;
flex: 0 0 20%;
opacity: 0.7;
}
&__body {
grid-area: 2 / 2 / 3 / 3;
opacity: 0.2;
flex: 1;
opacity: 0.16;
}
&--top {
.r-layout-preview__aside {
display: none;
}
.r-layout-preview__header,
.r-layout-preview__body {
grid-column: 1 / -1;
}
&__footer {
block-size: 2px;
opacity: 0.4;
}
&--top .r-layout-preview__header,
&--mixed .r-layout-preview__header {
opacity: 0.65;
}
&__row {
display: flex;
gap: 2px;
block-size: 3px;
&--right {
grid-template-columns: minmax(0, 3fr) minmax(0, 1fr);
.r-layout-preview__aside {
grid-column: 2;
> span {
flex: 1;
min-inline-size: 0;
}
.r-layout-preview__header,
.r-layout-preview__body {
grid-column: 1;
}
}
&--split {
.r-layout-preview__header {
grid-column: 1 / -1;
opacity: 0.65;
.r-layout-preview__breadcrumb {
opacity: 0.38;
}
.r-layout-preview__aside {
grid-row: 2;
.r-layout-preview__actions {
flex: 0 1 9px;
margin-inline-start: auto;
background: radial-gradient(circle, currentColor 1px, transparent 1.3px)
right center / 3px 3px repeat-x;
}
}
&--mixed .r-layout-preview__header {
background: linear-gradient(
to bottom,
currentColor 30%,
transparent 30% 52%,
currentColor 52%
);
.r-layout-preview__tabs {
opacity: 0.55;
background: repeating-linear-gradient(
to right,
currentColor 0 6px,
transparent 6px 8px
);
}
.r-layout-preview__navigation {
opacity: 0.78;
}
}
}

View File

@ -11,12 +11,29 @@ import {
import { defineComponent } from 'vue'
import type { PropType } from 'vue'
import { LAYOUT_MODES } from './AdminShell'
import type { LayoutConfig } from './AdminShell'
import type { LayoutConfig, LayoutMode } from './AdminShell'
import { renderLayoutPreview } from './layout-preview'
import type { LayoutPreview } from './layout-preview'
export interface LayoutChoice {
id: string
label: string
preview: LayoutMode | LayoutPreview
disabled?: boolean
hint?: string
}
export const LayoutSettings = defineComponent({
name: 'LayoutSettings',
props: {
showDescription: Boolean,
choices: { type: Array as PropType<LayoutChoice[]>, default: void 0 },
selectedId: { type: String, default: void 0 },
selectionNotice: { type: String, default: void 0 },
onSelect: {
type: Function as PropType<(id: string) => void>,
default: void 0,
},
layout: { type: Object as PropType<LayoutConfig>, required: true },
defaults: { type: Object as PropType<LayoutConfig>, required: true },
translate: {
@ -32,104 +49,122 @@ export const LayoutSettings = defineComponent({
const text = props.translate
const update = props.update
return () => (
<NFlex vertical size={16} class="r-layout-settings">
{props.showDescription ? (
<p class="r-layout-settings__hint">{text('description')}</p>
) : null}
<div class="r-layout-presets" role="group" aria-label={text('tab')}>
{LAYOUT_MODES.map((mode) => (
<button
type="button"
class="r-layout-preset"
key={mode}
aria-label={text(mode)}
title={text(mode)}
aria-pressed={props.layout.mode === mode}
onClick={() => update({ mode })}
>
<span
class={['r-layout-preview', `r-layout-preview--${mode}`]}
aria-hidden="true"
>
<span class="r-layout-preview__header" />
<span class="r-layout-preview__aside" />
<span class="r-layout-preview__body" />
</span>
<span class="r-layout-preset__label">{text(mode)}</span>
{props.layout.mode === mode ? (
<span class="r-layout-preset__selected" aria-hidden="true">
✓
</span>
) : null}
</button>
))}
</div>
{props.showDescription ? (
<p class="r-layout-settings__hint">
{text(`modeHint.${props.layout.mode}`)}
</p>
) : null}
<NForm labelPlacement="top" showFeedback={false}>
<NFormItem label={text('contentWidth')}>
<NSelect
aria-label={text('contentWidth')}
value={props.layout.contentWidth}
options={['fluid', 'fixed'].map((value) => ({
value,
label: text(value),
}))}
onUpdateValue={(value: LayoutConfig['contentWidth']) =>
update({ contentWidth: value })
}
/>
</NFormItem>
<NFormItem label={text('maxWidth')}>
<NInputNumber
inputProps={{ 'aria-label': text('maxWidth') }}
value={props.layout.contentMaxWidth}
disabled={props.layout.contentWidth !== 'fixed'}
min={640}
max={2560}
step={40}
precision={0}
onUpdateValue={(value) => {
if (value !== null) update({ contentMaxWidth: value })
}}
/>
</NFormItem>
<NFormItem label={text('padding')}>
<NInputNumber
inputProps={{ 'aria-label': text('padding') }}
value={props.layout.contentPadding}
min={0}
max={48}
step={4}
precision={0}
onUpdateValue={(value) => {
if (value !== null) update({ contentPadding: value })
}}
/>
</NFormItem>
<NFormItem label={text('fixedHeader')}>
<NSwitch
aria-label={text('fixedHeader')}
value={props.layout.fixedHeader}
onUpdateValue={(fixedHeader) => update({ fixedHeader })}
/>
</NFormItem>
<NFormItem label={text('fixedFooter')}>
<NSwitch
aria-label={text('fixedFooter')}
value={props.layout.fixedFooter}
onUpdateValue={(fixedFooter) => update({ fixedFooter })}
/>
</NFormItem>
</NForm>
<NButton onClick={() => update({ ...props.defaults })}>
{text('reset')}
</NButton>
</NFlex>
)
return () => {
const selected = props.selectedId ?? props.layout.mode
const choices =
props.choices ??
LAYOUT_MODES.map((mode) => ({
id: mode,
preview: mode,
label: text(mode),
hint: text(`modeHint.${mode}`),
disabled: false,
}))
const hint = choices.find(({ id }) => id === selected)?.hint
return (
<NFlex vertical size={16} class="r-layout-settings">
{props.showDescription ? (
<p class="r-layout-settings__hint">{text('description')}</p>
) : null}
<div class="r-layout-presets" role="group" aria-label={text('tab')}>
{choices.map((choice) => {
const mode =
typeof choice.preview === 'string'
? choice.preview
: LAYOUT_MODES.find((item) => item === choice.id)
return (
<button
type="button"
class="r-layout-preset"
key={choice.id}
aria-label={choice.label}
title={choice.label}
aria-pressed={selected === choice.id}
disabled={choice.disabled || (!props.onSelect && !mode)}
onClick={() => {
if (props.onSelect) props.onSelect(choice.id)
else if (mode) update({ mode })
}}
>
{renderLayoutPreview(choice.preview)}
<span class="r-layout-preset__label">{choice.label}</span>
{selected === choice.id ? (
<span class="r-layout-preset__selected" aria-hidden="true">
✓
</span>
) : null}
</button>
)
})}
</div>
{props.selectionNotice || (props.showDescription && hint) ? (
<p class="r-layout-settings__hint">
{props.selectionNotice || hint}
</p>
) : null}
<NForm labelPlacement="top" showFeedback={false}>
<NFormItem label={text('contentWidth')}>
<NSelect
aria-label={text('contentWidth')}
value={props.layout.contentWidth}
options={['fluid', 'fixed'].map((value) => ({
value,
label: text(value),
}))}
onUpdateValue={(value: LayoutConfig['contentWidth']) =>
update({ contentWidth: value })
}
/>
</NFormItem>
<NFormItem label={text('maxWidth')}>
<NInputNumber
inputProps={{ 'aria-label': text('maxWidth') }}
value={props.layout.contentMaxWidth}
disabled={props.layout.contentWidth !== 'fixed'}
min={640}
max={2560}
step={40}
precision={0}
onUpdateValue={(value) => {
if (value !== null) update({ contentMaxWidth: value })
}}
/>
</NFormItem>
<NFormItem label={text('padding')}>
<NInputNumber
inputProps={{ 'aria-label': text('padding') }}
value={props.layout.contentPadding}
min={0}
max={48}
step={4}
precision={0}
onUpdateValue={(value) => {
if (value !== null) update({ contentPadding: value })
}}
/>
</NFormItem>
<NFormItem label={text('fixedHeader')}>
<NSwitch
aria-label={text('fixedHeader')}
value={props.layout.fixedHeader}
onUpdateValue={(fixedHeader) => update({ fixedHeader })}
/>
</NFormItem>
<NFormItem label={text('fixedFooter')}>
<NSwitch
aria-label={text('fixedFooter')}
value={props.layout.fixedFooter}
onUpdateValue={(fixedFooter) => update({ fixedFooter })}
/>
</NFormItem>
</NForm>
<NButton onClick={() => update({ ...props.defaults })}>
{text('reset')}
</NButton>
</NFlex>
)
}
},
})

View File

@ -1,5 +1,7 @@
export * from './AdminShell'
export * from './LayoutSettings'
export { builtinLayoutPreviews } from './layout-preview'
export type { LayoutPreview, LayoutPreviewBlock } from './layout-preview'
export * from './layout-css-vars'
export { default as RouteTransition } from './RouteTransition.vue'
export type * from './transition-types'

View File

@ -0,0 +1,69 @@
import type { LayoutMode } from './AdminShell'
export type LayoutPreviewBlock =
'breadcrumb' | 'actions' | 'tabs' | 'navigation'
type PreviewRows = readonly (readonly LayoutPreviewBlock[])[]
export interface LayoutPreview {
readonly rows: PreviewRows
readonly bottomRows?: PreviewRows
readonly sidebar: 'none' | 'left' | 'right'
readonly footer?: boolean
readonly wideHeaderRows?: number
}
const sideRows: PreviewRows = [['breadcrumb', 'actions'], ['tabs']]
const navigationRows: PreviewRows = [
['breadcrumb', 'actions'],
['navigation'],
['tabs'],
]
export const builtinLayoutPreviews: Readonly<
Record<LayoutMode, LayoutPreview>
> = {
side: { rows: sideRows, sidebar: 'left', footer: true },
top: { rows: navigationRows, sidebar: 'none', footer: true },
mixed: { rows: navigationRows, sidebar: 'left', footer: true },
right: { rows: sideRows, sidebar: 'right', footer: true },
split: {
rows: navigationRows,
sidebar: 'left',
footer: true,
wideHeaderRows: 2,
},
}
function renderRows(rows: PreviewRows) {
return rows.map((row, index) => (
<span class="r-layout-preview__row" key={index}>
{row.map((block) => (
<span class={`r-layout-preview__${block}`} key={block} />
))}
</span>
))
}
export function renderLayoutPreview(preview: LayoutMode | LayoutPreview) {
const diagram =
typeof preview === 'string' ? builtinLayoutPreviews[preview] : preview
const wideHeaderRows = diagram.wideHeaderRows ?? 0
const sidebar = <span class="r-layout-preview__aside" />
return (
<span class="r-layout-preview" aria-hidden="true">
{renderRows(diagram.rows.slice(0, wideHeaderRows))}
<span class="r-layout-preview__frame">
{diagram.sidebar === 'left' && sidebar}
<span class="r-layout-preview__main">
{renderRows(diagram.rows.slice(wideHeaderRows))}
<span class="r-layout-preview__body" />
{diagram.bottomRows && renderRows(diagram.bottomRows)}
{diagram.footer && <span class="r-layout-preview__footer" />}
</span>
{diagram.sidebar === 'right' && sidebar}
</span>
</span>
)
}

32
scripts/fix.mjs Normal file
View File

@ -0,0 +1,32 @@
import { spawnSync } from 'node:child_process'
import { statSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import prettier from 'prettier/package.json' with { type: 'json' }
import { applyLintFixes } from './lint-fix.mjs'
const [directory = '.', ...extra] = process.argv.slice(
process.argv[2] === '--' ? 3 : 2,
)
if (
extra.length ||
!statSync(directory, { throwIfNoEntry: false })?.isDirectory()
) {
console.error('Usage: pnpm fix [directory]')
process.exit(1)
}
const lintCode = await applyLintFixes([directory])
const prettierBin = new URL(
prettier.bin,
import.meta.resolve('prettier/package.json'),
)
const { error, status } = spawnSync(
process.execPath,
[fileURLToPath(prettierBin), '--write', '--', directory],
{ stdio: 'inherit' },
)
if (error) throw error
process.exitCode = (status ?? 1) || lintCode

View File

@ -1,38 +1,47 @@
import { statSync } from 'node:fs'
const files = process.argv.slice(process.argv[2] === '--' ? 3 : 2)
export async function applyLintFixes(paths, { explicitFiles = false } = {}) {
const { ESLint } = await import('eslint')
const eslint = new ESLint({
fix: true,
globInputPaths: false,
errorOnUnmatchedPattern: explicitFiles,
})
let lintablePaths = paths
if (files.length === 0) {
console.error('Usage: pnpm lint:fix <file> [<file> ...]')
process.exit(1)
}
if (explicitFiles) {
lintablePaths = []
const invalidFile = files.find(
(file) => !statSync(file, { throwIfNoEntry: false })?.isFile(),
)
for (const file of paths) {
if (!(await eslint.isPathIgnored(file))) lintablePaths.push(file)
}
}
if (invalidFile !== void 0) {
console.error(`Expected an existing file path: ${invalidFile}`)
process.exit(1)
}
if (lintablePaths.length === 0) return 0
const { ESLint } = await import('eslint')
const eslint = new ESLint({ fix: true, globInputPaths: false })
const lintableFiles = []
for (const file of files) {
if (!(await eslint.isPathIgnored(file))) lintableFiles.push(file)
}
if (lintableFiles.length > 0) {
const results = await eslint.lintFiles(lintableFiles)
const results = await eslint.lintFiles(lintablePaths)
const formatter = await eslint.loadFormatter()
await ESLint.outputFixes(results)
process.stdout.write(await formatter.format(results))
if (
results.some(({ errorCount, warningCount }) => errorCount || warningCount)
return Number(
results.some(({ errorCount, warningCount }) => errorCount || warningCount),
)
process.exitCode = 1
}
if (import.meta.main) {
const files = process.argv.slice(process.argv[2] === '--' ? 3 : 2)
const invalidFile = files.find(
(file) => !statSync(file, { throwIfNoEntry: false })?.isFile(),
)
if (invalidFile !== void 0) {
console.error(`Expected an existing file path: ${invalidFile}`)
process.exit(1)
}
process.exitCode = files.length
? await applyLintFixes(files, { explicitFiles: true })
: await applyLintFixes(['.'])
}

View File

@ -0,0 +1,179 @@
import { randomUUID } from 'node:crypto'
import { link, open, readdir, realpath, unlink } from 'node:fs/promises'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { join } from 'node:path'
import type { Plugin } from 'vite'
import {
generateLayoutSource,
layoutDefinitionsDirectory,
layoutFileName,
layoutWriteEndpoint,
parseLayoutDesign,
} from '../apps/admin/src/layout/designer.ts'
import type { LayoutDesign } from '../apps/admin/src/layout/designer.ts'
const bodyLimit = 8192
const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]'])
const localPeers = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
function localBrowserRequest(request: IncomingMessage) {
const { headers, socket } = request
if (!localPeers.has(socket.remoteAddress ?? '') || !headers.origin)
return false
try {
const origin = new URL(headers.origin)
const protocol =
'encrypted' in socket && socket.encrypted ? 'https:' : 'http:'
return (
origin.protocol === protocol &&
localHosts.has(origin.hostname) &&
origin.origin === headers.origin &&
origin.host === headers.host &&
(!headers['sec-fetch-site'] ||
headers['sec-fetch-site'] === 'same-origin') &&
headers['x-ray-layout-write'] === '1' &&
headers['content-type']?.split(';')[0].trim().toLowerCase() ===
'application/json'
)
} catch {
return false
}
}
function reply(
response: ServerResponse,
status: number,
body: { path: string } | { error: string },
) {
response.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
})
response.end(JSON.stringify(body))
}
async function writeLayout(root: string, design: LayoutDesign) {
const directory = join(await realpath(root), layoutDefinitionsDirectory)
const filename = layoutFileName(design.id)
if ((await realpath(directory)) !== directory)
throw new Error('Invalid layout directory')
const files = await readdir(directory)
if (
files.some((file) =>
['tsx', 'ts', 'jsx', 'js'].some(
(ext) => file === `${design.id}.layout.${ext}`,
),
)
)
return false
// 保证 Vite 只观察到完整源码;并发请求和已有文件由原子的硬链接创建操作仲裁。
const temp = join(directory, `.ray-layout-${randomUUID()}.tmp`)
const file = await open(temp, 'wx')
try {
try {
await file.writeFile(generateLayoutSource(design))
} finally {
await file.close()
}
await link(temp, join(directory, filename))
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
throw error
} finally {
await unlink(temp)
}
return true
}
export function layoutWriterPlugin(projectRoot: string): Plugin {
return {
name: 'ray:layout-lab-writer',
apply: 'serve',
configureServer(server) {
if (server.config.isProduction || server.config.mode === 'production')
return
server.middlewares.use(async (request, response, next) => {
if (request.url !== layoutWriteEndpoint) return next()
if (request.method !== 'POST') {
response.setHeader('Allow', 'POST')
return reply(response, 405, { error: 'method' })
}
if (!localBrowserRequest(request))
return reply(response, 403, { error: 'forbidden' })
let design: LayoutDesign
try {
const chunks: Buffer[] = []
let bytes = 0
for await (const chunk of request.iterator({
destroyOnReturn: false,
})) {
const data = Buffer.from(chunk)
bytes += data.length
if (bytes > bodyLimit) {
request.resume()
return reply(response, 413, { error: 'too-large' })
}
chunks.push(data)
}
design = parseLayoutDesign(
JSON.parse(Buffer.concat(chunks).toString('utf8')),
)
} catch {
return reply(response, 400, { error: 'invalid' })
}
try {
if (!(await writeLayout(projectRoot, design)))
return reply(response, 409, { error: 'exists' })
} catch {
return reply(response, 500, { error: 'write-failed' })
}
// 原子发布的硬链接可能没有触发系统 add 事件。主动刷新 glob 模块及已连接的客户端。
const client = server.environments.client
try {
const catalog = await client.moduleGraph.getModuleByUrl(
'/src/layout/discovery.ts',
)
if (catalog) {
if (server.config.server.hmr === false)
client.moduleGraph.invalidateModule(catalog)
else await client.reloadModule(catalog)
}
} catch (error) {
// 文件已经创建,避免客户端将通知失败当成写入失败并重试。
server.config.logger.error(`[ray:layout-lab-writer] ${String(error)}`)
}
reply(response, 201, {
path: `${layoutDefinitionsDirectory}/${layoutFileName(design.id)}`,
})
})
},
}
}

View File

@ -2,11 +2,12 @@ import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import pkg from './apps/admin/package.json' with { type: 'json' }
import workspace from './package.json' with { type: 'json' }
import { layoutWriterPlugin } from './vite-helper/layout-writer.ts'
import config from './vite.custom.config.ts'
import vitePlugins from './vite.plugin.config.ts'
// https://vite.dev/config/
export default defineConfig(({ mode }) => {
export default defineConfig(({ mode, command, isPreview }) => {
const { dependencies, name, version } = pkg
const { devDependencies } = workspace
const {
@ -39,12 +40,15 @@ export default defineConfig(({ mode }) => {
define: {
__APP_CFG__: JSON.stringify(__APP_CFG__),
__DEV__: mode === 'development',
__LAYOUT_PROJECT_WRITER__:
command === 'serve' && !isPreview && mode !== 'production',
},
resolve: {
alias: alias,
},
plugins: [
vitePlugins(mode),
layoutWriterPlugin(fileURLToPath(new URL('.', import.meta.url))),
mode === 'production' && {
name: 'ray:clean-production-output',
apply: 'build' as const,