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

Preserve embedded pages and wait for asynchronous layout renderers.

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

234 lines
6.8 KiB
TypeScript

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