* fix(automation): export layers from a page that is not on screen The app's raster export rendered against the page on screen unless the caller passed a page, so MCP export_image with ids on any other page, or with page_id naming another page, failed with "Raster export selection must stay on a single page". Automation shares one app between clients, so the page on screen says nothing about what a request means. Render on the page that holds the requested layers instead. The user's view and selection stay where they were. * fix(cli): export the requested page from the running app `openpencil export --page` never reached the app: `exportViaApp` only forwarded `--document-id` and `--page-id`, and the app's `export` RPC exported the given nodes or the selection on screen, ignoring the target page. `--page` and `--page-id` therefore exported whatever was selected. The CLI now resolves `--page` to a page ID through `list_documents` and asks for a page-scoped export. The app answers a page-scoped export with the layers of the target page, loading a `.fig` page that has not been shown yet without switching to it. CLI tests address the package source by `#cli/`, as Core and fig tests already do, so the alias owner widens to the whole package. * fix(automation): prepare fonts and layout for a page exported off screen A page export loaded the layers of a page that had not been shown, but not its fonts or layout, so text and auto layout could render differently from the screen. preparePageNodes runs the same font and layout pass as a page switch, once per page, without switching or superseding a switch. The CLI export test now writes its own discovery file, so it no longer replaces or removes the record of an app that is running. * fix(automation): prepare a .fig page before running a tool on it A `.fig` opens with only its first page populated; the others get their layers, fonts and layout when first shown. The automation tool handler built its FigmaAPI on the target page without loading it, so MCP tools aimed at a page nobody had opened (`page_id`) saw an empty page: find_nodes found nothing, export_image reported "No visible nodes to export", and create_shape added a shape to a page that then held only that shape. Prepare the target page first with preparePageNodes, as page exports do: layers, fonts and layout, once per page. The page on screen does not change. * fix(automation): render explicit export IDs on the page that holds them Since the visual diff tools, the automation FigmaAPI passes its target page with every raster export, so export_image with IDs from another page asked to render them on the target page and failed with "Raster export selection must stay on a single page". The page now names which layers to export only when no IDs are given; an ID list is rendered on its own page. * fix(core): share one off-screen page preparation between concurrent callers Two concurrent preparePageNodes calls for the same page both populated it and resolved its fonts, and the font manager's blocked-node set has no reference count, so the first to finish unblocked text the second was still resolving. Callers now share the in-flight preparation, which is kept once it succeeds and retried after a failure. preparePageNodes also reports whether the page is ready, so a caller can refuse to run on a page whose document was closed or replaced mid-way instead of acting on a page with no layers. Its unused options are gone: one caller's signal cannot cancel a shared preparation. * fix(automation): prepare the target page once for every command Preparing an unshown .fig page lived in the page export handler, so explicit export IDs, export_jsx, eval, tools, and the RPC fallback still saw such a page as empty. The request dispatcher now prepares the resolved target page before any page-targeted command, and stops with an error when the page's document closed while it loaded. * docs(changelog): fold the off-screen page fixes into one entry * refactor(automation): rely on the dispatcher to prepare a tool's target page The request dispatcher now prepares the target page before every page-targeted command, so the tool handler no longer does it itself. The tests run tools through the dispatcher, which is where that guarantee lives. * docs(changelog): drop the tool entry now covered by the off-screen page fix --------- Co-authored-by: Jason Woltje <1139190+jetrich@users.noreply.github.com>
174 lines
6.6 KiB
TypeScript
174 lines
6.6 KiB
TypeScript
import 'fake-indexeddb/auto'
|
|
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
|
|
|
|
import { toUint8Array } from 'js-base64'
|
|
|
|
import { SkiaRenderer } from '@open-pencil/core/canvas'
|
|
import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit, parseFigFile } from '@open-pencil/core/io'
|
|
import { SceneGraph } from '@open-pencil/scene-graph'
|
|
|
|
import { makeFigmaFromStore } from '@/app/automation/bridge/figma-factory'
|
|
import { createAutomationCommandHandlers } from '@/app/automation/bridge/handlers'
|
|
import type { AutomationTarget } from '@/app/automation/bridge/target'
|
|
import { createEditorStore, type EditorStore } from '@/app/editor/session/create'
|
|
|
|
const RED = { type: 'SOLID' as const, color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
|
|
const { handleTargetCommand } = createAutomationCommandHandlers(makeFigmaFromStore)
|
|
|
|
let stores: EditorStore[] = []
|
|
|
|
beforeEach(() => {
|
|
// The automation FigmaAPI reads the viewport size from the window.
|
|
Object.assign(globalThis, { window: { innerWidth: 1024, innerHeight: 768 } })
|
|
})
|
|
|
|
afterEach(() => {
|
|
for (const store of stores) store.dispose()
|
|
stores = []
|
|
Reflect.deleteProperty(globalThis, 'window')
|
|
})
|
|
|
|
async function storeWithCanvas(graph?: SceneGraph): Promise<EditorStore> {
|
|
const store = createEditorStore(graph)
|
|
stores.push(store)
|
|
const ck = await initCanvasKit()
|
|
const surface = ck.MakeSurface(1, 1)
|
|
if (!surface) throw new Error('Failed to create CanvasKit surface')
|
|
store.setCanvasKit(ck, new SkiaRenderer(ck, surface))
|
|
return store
|
|
}
|
|
|
|
/** A `.fig` opened like the app does: only the first page has its layers. */
|
|
async function storeWithUnshownPage(): Promise<{ store: EditorStore; pageId: string }> {
|
|
const source = new SceneGraph()
|
|
source.createNode('FRAME', source.getPages()[0].id, { width: 10, height: 10, fills: [RED] })
|
|
const second = source.addPage('Second')
|
|
source.createNode('FRAME', second.id, {
|
|
name: 'Second frame',
|
|
width: 70,
|
|
height: 35,
|
|
fills: [RED]
|
|
})
|
|
const written = await new IORegistry(BUILTIN_IO_FORMATS).writeDocument('fig', source)
|
|
const bytes = written.data as Uint8Array
|
|
const graph = await parseFigFile(bytes.slice().buffer, { populate: 'first-page' })
|
|
const store = await storeWithCanvas(graph)
|
|
const page = graph.getPages().find((candidate) => candidate.name === 'Second')
|
|
if (!page) throw new Error('Missing second page')
|
|
expect(graph.getChildren(page.id)).toHaveLength(0)
|
|
return { store, pageId: page.id }
|
|
}
|
|
|
|
function target(store: EditorStore, pageId: string): AutomationTarget {
|
|
const page = store.graph.getNode(pageId)
|
|
return {
|
|
store,
|
|
documentId: 'tab-1',
|
|
documentName: 'Document',
|
|
pageId,
|
|
pageName: page?.name ?? ''
|
|
}
|
|
}
|
|
|
|
function pngSize(bytes: Uint8Array): { width: number; height: number } {
|
|
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
return { width: view.getUint32(16), height: view.getUint32(20) }
|
|
}
|
|
|
|
function resultBytes(response: unknown): Uint8Array {
|
|
const result = (response as { result?: { base64?: string } }).result
|
|
if (!result?.base64) throw new Error(`No image in ${JSON.stringify(response)}`)
|
|
return toUint8Array(result.base64)
|
|
}
|
|
|
|
describe('automation export of a page that is not on screen', () => {
|
|
test('export_image renders nodes by ID from another page', async () => {
|
|
const store = await storeWithCanvas()
|
|
const shown = store.state.currentPageId
|
|
const other = store.graph.addPage('Other').id
|
|
const frame = store.graph.createNode('FRAME', other, { width: 40, height: 30, fills: [RED] })
|
|
|
|
const response = await handleTargetCommand(target(store, shown), 'tool', {
|
|
name: 'export_image',
|
|
args: { ids: [frame.id] }
|
|
})
|
|
|
|
expect(pngSize(resultBytes(response))).toEqual({ width: 40, height: 30 })
|
|
expect(store.state.currentPageId).toBe(shown)
|
|
})
|
|
|
|
test('export_image renders the layers of the page named by page_id', async () => {
|
|
const store = await storeWithCanvas()
|
|
const shown = store.state.currentPageId
|
|
const other = store.graph.addPage('Other').id
|
|
store.graph.createNode('FRAME', other, { width: 50, height: 20, fills: [RED] })
|
|
|
|
const response = await handleTargetCommand(target(store, other), 'tool', {
|
|
name: 'export_image',
|
|
args: {}
|
|
})
|
|
|
|
expect(pngSize(resultBytes(response))).toEqual({ width: 50, height: 20 })
|
|
expect(store.state.currentPageId).toBe(shown)
|
|
})
|
|
|
|
test('a page export renders the target page, not the selection on screen', async () => {
|
|
const store = await storeWithCanvas()
|
|
const shown = store.state.currentPageId
|
|
const selected = store.graph.createNode('FRAME', shown, { width: 10, height: 10, fills: [RED] })
|
|
store.select([selected.id])
|
|
const other = store.graph.addPage('Other').id
|
|
store.graph.createNode('FRAME', other, { width: 60, height: 25, fills: [RED] })
|
|
|
|
const response = await handleTargetCommand(target(store, other), 'export', {
|
|
scope: 'page',
|
|
format: 'png'
|
|
})
|
|
|
|
expect(pngSize(resultBytes(response))).toEqual({ width: 60, height: 25 })
|
|
expect(store.state.currentPageId).toBe(shown)
|
|
})
|
|
|
|
test('a page export loads the layers of a .fig page that has not been shown', async () => {
|
|
const { store, pageId } = await storeWithUnshownPage()
|
|
const shown = store.state.currentPageId
|
|
|
|
const response = await handleTargetCommand(target(store, pageId), 'export', { scope: 'page' })
|
|
|
|
expect(pngSize(resultBytes(response))).toEqual({ width: 70, height: 35 })
|
|
expect(store.state.currentPageId).toBe(shown)
|
|
})
|
|
|
|
test('a JSX export lists the layers of a .fig page that has not been shown', async () => {
|
|
const { store, pageId } = await storeWithUnshownPage()
|
|
|
|
const response = (await handleTargetCommand(target(store, pageId), 'export_jsx', {})) as {
|
|
result: { jsx: string }
|
|
}
|
|
|
|
expect(response.result.jsx).toContain('Second frame')
|
|
})
|
|
|
|
test('a page export lays out the target page first', async () => {
|
|
const store = await storeWithCanvas()
|
|
const shown = store.state.currentPageId
|
|
const other = store.graph.addPage('Other').id
|
|
// Not laid out yet: the row hugs one 80 px child but still says 10 px, and clips.
|
|
const row = store.graph.createNode('FRAME', other, {
|
|
width: 10,
|
|
height: 20,
|
|
fills: [RED],
|
|
clipsContent: true,
|
|
layoutMode: 'HORIZONTAL',
|
|
primaryAxisSizing: 'HUG',
|
|
counterAxisSizing: 'FIXED'
|
|
})
|
|
store.graph.createNode('FRAME', row.id, { width: 80, height: 20, fills: [RED] })
|
|
|
|
const response = await handleTargetCommand(target(store, other), 'export', { scope: 'page' })
|
|
|
|
expect(pngSize(resultBytes(response))).toEqual({ width: 80, height: 20 })
|
|
expect(store.state.currentPageId).toBe(shown)
|
|
})
|
|
})
|