Skip to content

AI-native design editor. Open-source Figma alternative.

fix: load pages not yet visited before tools and scripts read them (#1742)

Danila Poyarkovcd0f665432bd
diff --git a/changes/1742/fixed.md b/changes/1742/fixed.md
new file mode 100644
index 000000000..5c83d5bbf
--- /dev/null
+++ b/changes/1742/fixed.md
@@ -0,0 +1 @@
+- MCP tools and scripts read pages that have not been opened yet, such as `get_page_tree` on a page's ID or `query_nodes` by page name, instead of finding them empty, and `page.loadAsync()` and `figma.loadAllPagesAsync()` load pages as in Figma.
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 2133b52de..1b403c4af 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -61,7 +61,15 @@ import type {
FigmaVectorNode
} from './node-types'
import { startPendingLayout } from './pending-layout'
-import { FigmaNodeProxy, INTERNAL_ID, MIXED, type FigmaFont, type NodeProxyHost } from './proxy'
+import {
+ FigmaNodeProxy,
+ INTERNAL_ID,
+ loadPage,
+ MIXED,
+ setPageLoader,
+ type FigmaFont,
+ type NodeProxyHost
+} from './proxy'
import { newShapeWithText } from './shape-with-text'
import { FigmaStyleMethods } from './styles/api'
import type { ExportImageOptions } from './types'
@@ -75,6 +83,12 @@ const noop = () => undefined
export interface FigmaAPIOptions {
/** Fetches the HTTP(S) URLs `figma.createImageAsync` loads; the global `fetch` by default. */
fetch?: images.ImageFetch
+ /**
+ * Loads a page's layers, for a host that loads pages as they are visited, as the editor does a
+ * file it opens: `page.loadAsync`, `figma.loadAllPagesAsync`, and `setCurrentPageAsync` call
+ * it, as they load pages in Figma's dynamic-page mode. Without one every page is in memory.
+ */
+ loadPage?: (pageId: string) => Promise<void>
}
export { FigmaNodeProxy } from './proxy'
@@ -119,6 +133,8 @@ export type { FigmaVariationSettings } from './fonts/variations'
export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
readonly graph: SceneGraph
private _currentPageId: string
+ /** Counts page switches, so a switch whose page loads after a later one does not undo it. */
+ #pageSwitch = 0
private _selection: FigmaNodeProxy[] = []
private _nodeCache = new Map<string, FigmaNodeProxy>()
private _nodeTypes = new Map<string, string | undefined>()
@@ -141,6 +157,7 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
super()
this.graph = graph
this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
+ if (options.loadPage) setPageLoader(this, options.loadPage)
this.variables = new FigmaVariablesAPI(graph)
startPendingLayout(graph)
const pages = graph.getPages()
@@ -232,6 +249,7 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
}
set currentPage(page: FigmaNodeProxy) {
+ this.#pageSwitch++
this._currentPageId = page[INTERNAL_ID]
}
@@ -257,8 +275,15 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
if (this._rawNode(page).type !== 'CANVAS') {
return Promise.reject(new Error('figma.setCurrentPageAsync expects a PageNode'))
}
- this._currentPageId = this._nodeId(page)
- return Promise.resolve()
+ const pageId = this._nodeId(page)
+ const pageSwitch = ++this.#pageSwitch
+ return loadPage(this, pageId).then(() => {
+ if (pageSwitch !== this.#pageSwitch) return undefined
+ if (this.graph.getNode(pageId)?.type !== 'CANVAS')
+ throw new Error('in setCurrentPageAsync: The page was removed while it loaded')
+ this._currentPageId = pageId
+ return undefined
+ })
}
// --- Node Creation ---
@@ -643,9 +668,9 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
if (message) this.notify(message)
}
- /** Every page is already in memory. */
+ /** Loads every page's layers, one page after another, as Figma does in dynamic-page mode. */
async loadAllPagesAsync(): Promise<void> {
- return undefined
+ for (const page of this.graph.getPages()) await loadPage(this, page.id)
}
commitUndo(): void {
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 948813479..05d18c23d 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -48,6 +48,20 @@ export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
export const INTERNAL_API = Symbol('api')
+/**
+ * How each API loads a page's layers, a host's hook kept off `figma`, which has only Figma's
+ * members; see `FigmaAPIOptions.loadPage`. Without one every page is in memory.
+ */
+const pageLoaders = new WeakMap<NodeProxyHost, (pageId: string) => Promise<void>>()
+
+export function setPageLoader(api: NodeProxyHost, load: (pageId: string) => Promise<void>): void {
+ pageLoaders.set(api, load)
+}
+
+export function loadPage(api: NodeProxyHost, pageId: string): Promise<void> {
+ return pageLoaders.get(api)?.(pageId) ?? Promise.resolve()
+}
+
export interface NodeProxyHost extends ExportHost {
wrapNode(id: string): FigmaNodeProxy
readonly currentPageId: string
@@ -93,9 +107,9 @@ export class FigmaNodeProxy extends FigmaNodeMembers {
if (type && id !== graph.rootId) installExportAccessors(this, internals)
if (type) installGeometryAccessors(this, internals, type)
// Figma loads a page's layers on demand in dynamic-page mode and has `loadAsync` on pages
- // alone; every page here is already loaded.
+ // alone, as the editor loads a page's layers when it is first visited.
if (type === 'CANVAS')
- Object.defineProperty(this, 'loadAsync', { value: () => Promise.resolve() })
+ Object.defineProperty(this, 'loadAsync', { value: () => loadPage(api, id) })
if (id === graph.rootId)
Object.defineProperty(this, 'documentColorProfile', {
get: () => (graph.documentColorSpace === 'display-p3' ? 'DISPLAY_P3' : 'SRGB')
diff --git a/packages/core/src/tools/analyze/overlaps/index.ts b/packages/core/src/tools/analyze/overlaps/index.ts
index 4bc7575a0..357eb122c 100644
--- a/packages/core/src/tools/analyze/overlaps/index.ts
+++ b/packages/core/src/tools/analyze/overlaps/index.ts
@@ -333,7 +333,7 @@ export const analyzeOverlaps = defineTool({
name: 'analyze_overlaps',
description:
'Detect visual overlaps and layout overflows across the current page. Useful for finding content that covers footers, text that bleeds outside frames, and accidental sibling overlaps.',
- execution: { kind: 'sync', mutation: 'none' },
+ execution: { kind: 'async', mutation: 'none' },
exposure: { webmcp: false },
input: v.strictObject({
scope: v.optional(
@@ -403,8 +403,19 @@ export const analyzeOverlaps = defineTool({
100
)
}),
- execute: (figma: FigmaAPI, args) => {
- const page_id = args.page_id ?? (args.page ? undefined : figma.currentPageId)
- return computeOverlaps(figma.graph, { ...(args as AnalyzeOverlapsArgs), page_id })
+ execute: async (figma: FigmaAPI, args) => {
+ // A blank page argument is no page argument, so the current page is analyzed.
+ const pageName = args.page?.trim() || undefined
+ const page_id = args.page_id?.trim() || (pageName ? undefined : figma.currentPageId)
+ // A page not yet visited has no layers until it loads.
+ const page = page_id
+ ? figma.getNodeById(page_id)
+ : figma.root.children.find((candidate) => candidate.name === pageName)
+ if (page && figma.graph.getNode(page.id)?.type === 'CANVAS') await page.loadAsync()
+ return computeOverlaps(figma.graph, {
+ ...(args as AnalyzeOverlapsArgs),
+ page: pageName,
+ page_id
+ })
}
})
diff --git a/packages/core/src/tools/codegen/component-map.ts b/packages/core/src/tools/codegen/component-map.ts
index cd57bc590..dce31346d 100644
--- a/packages/core/src/tools/codegen/component-map.ts
+++ b/packages/core/src/tools/codegen/component-map.ts
@@ -114,16 +114,16 @@ export const designToComponentMap = defineTool({
name: 'design_to_component_map',
description:
'Analyze the document and return a structured component decomposition: components (with variants, props, instance counts), screens, and a dependency overview.',
- execution: { kind: 'sync', mutation: 'none' },
+ execution: { kind: 'async', mutation: 'none' },
input: v.strictObject({
page: v.optional(
v.pipe(v.string(), v.description('Page name to analyze (default: current page)'))
)
}),
- execute: (figma, args) => {
+ execute: async (figma, args) => {
if (args.page) {
const target = figma.root.children.find((page) => page.name === args.page)
- if (target) figma.currentPage = target
+ if (target) await figma.setCurrentPageAsync(target)
else return { error: `Page "${args.page}" not found` }
}
diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.ts
index b918a9014..44a17e100 100644
--- a/packages/core/src/tools/read/components.ts
+++ b/packages/core/src/tools/read/components.ts
@@ -2,6 +2,7 @@ import * as v from 'valibot'
import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'
+import type { FigmaAPI } from '#core/figma-api'
import { getComponentCatalog } from '#core/tools/component-catalog'
import { toolNumber, defineTool } from '#core/tools/schema'
@@ -27,6 +28,32 @@ interface LibraryComponentResult {
priority: number
}
+/** The enabled library components the document's catalog has, matching `name` and `libraryId`. */
+async function listLibraryComponents(
+ figma: FigmaAPI,
+ args: { name?: string; library_id?: string }
+): Promise<LibraryComponentResult[]> {
+ const catalog = getComponentCatalog(figma.graph)
+ if (!catalog) return []
+ const assets = await catalog.listComponents({
+ name: args.name,
+ libraryId: args.library_id,
+ enabledOnly: true
+ })
+ return assets.map(({ libraryId, libraryName, revisionId, enabled, priority, asset }) => ({
+ libraryId,
+ libraryName,
+ revisionId,
+ assetKey: asset.key,
+ name: asset.name,
+ type: asset.type,
+ description: asset.description,
+ source: 'library',
+ enabled,
+ priority
+ }))
+}
+
export const getComponents = defineTool({
name: 'get_components',
description:
@@ -54,10 +81,15 @@ export const getComponents = defineTool({
const source = args.source
const nameFilter = args.name?.toLowerCase()
const documentComponents: DocumentComponentResult[] = []
+ const libraryComponents = source === 'document' ? [] : await listLibraryComponents(figma, args)
+ // Library components sort ahead of the document's, so when they fill the list no page loads.
+ const libraryFilled = libraryComponents.filter(({ priority }) => priority > -1).length >= limit
- if (source !== 'libraries') {
+ if (source !== 'libraries' && !libraryFilled) {
for (const page of figma.root.children) {
if (documentComponents.length >= limit) break
+ // Pages load as the search reaches them, so a short list loads only the pages it needs.
+ await page.loadAsync()
page.findAll((node) => {
if (documentComponents.length >= limit) return false
if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return false
@@ -80,30 +112,6 @@ export const getComponents = defineTool({
}
}
- const catalog = getComponentCatalog(figma.graph)
- const libraryComponents: LibraryComponentResult[] = []
- if (source !== 'document' && catalog) {
- const assets = await catalog.listComponents({
- name: args.name,
- libraryId: args.library_id,
- enabledOnly: true
- })
- libraryComponents.push(
- ...assets.map(({ libraryId, libraryName, revisionId, enabled, priority, asset }) => ({
- libraryId,
- libraryName,
- revisionId,
- assetKey: asset.key,
- name: asset.name,
- type: asset.type,
- description: asset.description,
- source: 'library' as const,
- enabled,
- priority
- }))
- )
- }
-
const components = [...libraryComponents, ...documentComponents]
.sort((left, right) => {
const leftPriority = 'priority' in left ? left.priority : -1
diff --git a/packages/core/src/tools/read/nodes.ts b/packages/core/src/tools/read/nodes.ts
index be32d7141..b536df3b7 100644
--- a/packages/core/src/tools/read/nodes.ts
+++ b/packages/core/src/tools/read/nodes.ts
@@ -52,7 +52,7 @@ export const getPageTree = defineTool({
name: 'get_page_tree',
description:
'Get the node tree of the current page. Returns lightweight hierarchy: id, type, name, size, and text for TEXT nodes. Use depth, root_id, or node_types to keep large pages small. Use get_node for full properties of a specific node.',
- execution: { kind: 'sync', mutation: 'none' },
+ execution: { kind: 'async', mutation: 'none' },
input: v.strictObject({
depth: v.optional(
toolNumber(
@@ -79,12 +79,18 @@ export const getPageTree = defineTool({
)
)
}),
- execute: (figma, { depth, root_id, node_types }) => {
+ execute: async (figma, { depth, root_id, node_types }) => {
const typeFilter = node_types && node_types.length > 0 ? new Set(node_types) : undefined
if (root_id !== undefined) {
const root = figma.getNodeById(root_id)
- if (!root) return { error: `Node "${root_id}" not found` }
+ // Layers of a page not yet visited are not in the document until it loads.
+ if (!root)
+ return {
+ error: `Node "${root_id}" not found. A node on a page not yet opened is found once that page loads: switch_page to it first.`
+ }
+ // A page not yet visited has no layers until it loads.
+ if (figma.graph.getNode(root.id)?.type === 'CANVAS') await root.loadAsync()
return { root: root.id, tree: nodeToTreeEntry(root, 1, depth, typeFilter) }
}
diff --git a/packages/core/src/tools/read/pages.ts b/packages/core/src/tools/read/pages.ts
index 8c1afe4e1..052a4cdd7 100644
--- a/packages/core/src/tools/read/pages.ts
+++ b/packages/core/src/tools/read/pages.ts
@@ -22,15 +22,17 @@ export const switchPage = defineTool({
name: 'switch_page',
description: 'Switch to a different page by name or ID.',
- execution: { kind: 'sync', mutation: 'view' },
+ execution: { kind: 'async', mutation: 'view' },
input: v.strictObject({
page: v.pipe(v.string(), v.description('Page name or ID'))
}),
- execute: (figma, { page }) => {
+ execute: async (figma, { page }) => {
const target =
figma.root.children.find((candidate) => candidate.name === page) ?? figma.getNodeById(page)
- if (!target) return { error: `Page "${page}" not found` }
- figma.currentPage = target
+ if (!target || figma.graph.getNode(target.id)?.type !== 'CANVAS')
+ return { error: `Page "${page}" not found` }
+ // A page not yet visited has its layers loaded first, so the calls after see them.
+ await figma.setCurrentPageAsync(target)
return { page: target.name, id: target.id }
}
})
diff --git a/packages/core/src/tools/read/query.ts b/packages/core/src/tools/read/query.ts
index 65335b928..b36a8d38d 100644
--- a/packages/core/src/tools/read/query.ts
+++ b/packages/core/src/tools/read/query.ts
@@ -24,6 +24,8 @@ Examples:
limit: v.optional(toolNumber(v.pipe(v.number(), v.description('Max results (default: 1000)'))))
}),
execute: async (figma, args) => {
+ if (args.page !== undefined)
+ await figma.root.children.find((page) => page.name === args.page)?.loadAsync()
try {
const nodes = await queryByXPath(figma.graph, args.selector, {
page: args.page ?? figma.currentPage.name,
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index 417c62313..4311b2f55 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -17,7 +17,15 @@ export function makeFigmaFromStore(
store: EditorStore,
pageId = store.state.currentPageId
): FigmaAPI {
- const api = new FigmaAPI(store.graph, { fetch: imageFetch })
+ const api = new FigmaAPI(store.graph, {
+ fetch: imageFetch,
+ // A page not yet visited has no layers until the editor prepares it, as it does a page it
+ // switches to: with its fonts and layout.
+ loadPage: async (id) => {
+ if (!(await store.preparePageNodes(id)))
+ throw new Error(`Page "${id}" was closed before it finished loading`)
+ }
+ })
api.setRenderer(store.renderer ?? null)
api.icons = store.iconProvider
api.theme = store.state.theme ?? 'light'
diff --git a/tests/engine/mcp/tools.test.ts b/tests/engine/mcp/tools.test.ts
index fdfa4ab91..8255c6f26 100644
--- a/tests/engine/mcp/tools.test.ts
+++ b/tests/engine/mcp/tools.test.ts
@@ -54,14 +54,14 @@ describe('MCP tool execution', () => {
expect(new Set(names).size).toBe(names.length)
})
- test('get_page_tree returns page hierarchy', () => {
+ test('get_page_tree returns page hierarchy', async () => {
const { api } = setup()
- const result = findTool('get_page_tree').execute(api, {}) as PageTreeResult
+ const result = (await findTool('get_page_tree').execute(api, {})) as PageTreeResult
expect(result.page).toBe('Page 1')
expect(result.children).toBeArray()
})
- test('get_page_tree supports depth, root_id, and node_types filters', () => {
+ test('get_page_tree supports depth, root_id, and node_types filters', async () => {
const { api } = setup()
const parent = findTool('create_shape').execute(api, {
type: 'FRAME',
@@ -89,23 +89,23 @@ describe('MCP tool execution', () => {
name: 'Other rect'
})
- const depthTree = findTool('get_page_tree').execute(api, { depth: 1 }) as PageTreeResult
+ const depthTree = (await findTool('get_page_tree').execute(api, { depth: 1 })) as PageTreeResult
const depthParent = expectDefined(
depthTree.children.find((node) => node.id === parent.id),
'depth-limited parent'
)
expect(depthParent.children).toBeUndefined()
- const subtree = findTool('get_page_tree').execute(api, { root_id: parent.id }) as {
+ const subtree = (await findTool('get_page_tree').execute(api, { root_id: parent.id })) as {
root: string
tree: PageTreeNode
}
expect(subtree.root).toBe(parent.id)
expect(subtree.tree.children?.[0]?.id).toBe(text.id)
- const filtered = findTool('get_page_tree').execute(api, {
+ const filtered = (await findTool('get_page_tree').execute(api, {
node_types: ['TEXT']
- }) as PageTreeResult
+ })) as PageTreeResult
expect(filtered.children.some((node) => node.type === 'RECTANGLE')).toBe(false)
const filteredParent = expectDefined(
filtered.children.find((node) => node.id === parent.id),
@@ -174,7 +174,7 @@ describe('MCP tool execution', () => {
expect(node.paddingLeft).toBe(24)
})
- test('create_shape with parent_id nests correctly', () => {
+ test('create_shape with parent_id nests correctly', async () => {
const { api } = setup()
const parent = findTool('create_shape').execute(api, {
type: 'FRAME',
@@ -195,7 +195,7 @@ describe('MCP tool execution', () => {
parent_id: parent.id
})
- const tree = findTool('get_page_tree').execute(api, {}) as PageTreeResult
+ const tree = (await findTool('get_page_tree').execute(api, {})) as PageTreeResult
const parentNode = expectDefined(
tree.children.find((c: { id: string }) => c.id === parent.id),
'parent tree node'
diff --git a/tests/engine/tools/analyze/overlaps/index.test.ts b/tests/engine/tools/analyze/overlaps/index.test.ts
index a7072e8de..11df1ced6 100644
--- a/tests/engine/tools/analyze/overlaps/index.test.ts
+++ b/tests/engine/tools/analyze/overlaps/index.test.ts
@@ -335,7 +335,7 @@ describe('analyze overlaps', () => {
expect(severityCapped.overlaps.length).toBe(scoped.overlaps.length)
})
- test('ToolDef defaults to current page and does not report overlaps on other pages', () => {
+ test('ToolDef defaults to current page and does not report overlaps on other pages', async () => {
const graph = new SceneGraph()
const page2 = graph.addPage('Page 2')
@@ -343,12 +343,12 @@ describe('analyze overlaps', () => {
rect(graph, 'B', page2.id, 50, 50, 100, 100)
const api = new FigmaAPI(graph)
- const result = analyzeOverlaps.execute(api, {}) as AnalyzeOverlapsResult
+ const result = (await analyzeOverlaps.execute(api, {})) as AnalyzeOverlapsResult
expect(result.summary.overlapCount).toBe(0)
expect(result.overlaps).toHaveLength(0)
})
- test('ToolDef respects explicit page argument', () => {
+ test('ToolDef respects explicit page argument', async () => {
const graph = new SceneGraph()
const page2 = graph.addPage('Page 2')
@@ -356,7 +356,7 @@ describe('analyze overlaps', () => {
rect(graph, 'B', page2.id, 50, 50, 100, 100)
const api = new FigmaAPI(graph)
- const result = analyzeOverlaps.execute(api, { page: 'Page 2' }) as AnalyzeOverlapsResult
+ const result = (await analyzeOverlaps.execute(api, { page: 'Page 2' })) as AnalyzeOverlapsResult
expect(result.summary.overlapCount).toBeGreaterThan(0)
})
diff --git a/tests/engine/tools/analyze/overlaps/page-scope.test.ts b/tests/engine/tools/analyze/overlaps/page-scope.test.ts
index af9533c51..c9e9dd87c 100644
--- a/tests/engine/tools/analyze/overlaps/page-scope.test.ts
+++ b/tests/engine/tools/analyze/overlaps/page-scope.test.ts
@@ -52,7 +52,7 @@ describe('analyze overlaps page scope', () => {
expect(result.overlaps).toHaveLength(0)
})
- test('ToolDef currentPage default uses page ID so duplicate page names do not leak', () => {
+ test('ToolDef currentPage default uses page ID so duplicate page names do not leak', async () => {
const graph = new SceneGraph()
const page1 = pageId(graph)
const page2 = graph.addPage('Page 1')
@@ -63,13 +63,20 @@ describe('analyze overlaps page scope', () => {
const api = new FigmaAPI(graph)
expect(api.currentPageId).toBe(page1)
- const defaultResult = analyzeOverlaps.execute(api, {}) as AnalyzeOverlapsResult
+ const defaultResult = (await analyzeOverlaps.execute(api, {})) as AnalyzeOverlapsResult
expect(defaultResult.summary.overlapCount).toBe(0)
expect(defaultResult.overlaps).toHaveLength(0)
api.currentPage = api.wrapNode(page2.id)
- const currentResult = analyzeOverlaps.execute(api, {}) as AnalyzeOverlapsResult
+ const currentResult = (await analyzeOverlaps.execute(api, {})) as AnalyzeOverlapsResult
expect(currentResult.summary.overlapCount).toBeGreaterThan(0)
+
+ // Blank page arguments are none, so the current page is analyzed, not the first.
+ const blankResult = (await analyzeOverlaps.execute(api, {
+ page: ' ',
+ page_id: ' '
+ })) as AnalyzeOverlapsResult
+ expect(blankResult.summary.overlapCount).toBe(currentResult.summary.overlapCount)
})
test('page_id argument disambiguates duplicate page names', () => {
diff --git a/tests/engine/tools/read.test.ts b/tests/engine/tools/read.test.ts
index dabf81990..a3c21db63 100644
--- a/tests/engine/tools/read.test.ts
+++ b/tests/engine/tools/read.test.ts
@@ -212,7 +212,7 @@ describe('get_node', () => {
})
describe('get_page_tree', () => {
- test('includes the text of TEXT nodes', () => {
+ test('includes the text of TEXT nodes', async () => {
const { figma } = setupToolTest()
const card = figma.createFrame()
const label = figma.createText()
@@ -220,7 +220,7 @@ describe('get_page_tree', () => {
card.appendChild(label)
const tool = getTool('get_page_tree')
- const result = tool.execute(figma, { root_id: card.id, node_types: ['TEXT'] })
+ const result = await tool.execute(figma, { root_id: card.id, node_types: ['TEXT'] })
expect(result).toMatchObject({
root: card.id,
tree: { id: card.id, children: [{ id: label.id, text: 'Saldo disponível' }] }
@@ -229,6 +229,97 @@ describe('get_page_tree', () => {
})
})
+describe('pages not yet visited', () => {
+ /** A document whose second page has no layers until the host loads it, as the editor's do. */
+ function lazyDocument() {
+ const { graph } = setupToolTest()
+ const later = graph.addPage('Later')
+ const loads: string[] = []
+ const figma = new FigmaAPI(graph, {
+ loadPage: async (id) => {
+ loads.push(id)
+ if (id === later.id && graph.getChildren(id).length === 0)
+ graph.createNode('COMPONENT', id, { name: 'Loaded button' })
+ }
+ })
+ return { figma, later, loads }
+ }
+
+ test('load before a tool reads them', async () => {
+ const tree = lazyDocument()
+ expect(
+ await getTool('get_page_tree').execute(tree.figma, { root_id: tree.later.id })
+ ).toMatchObject({ tree: { children: [{ name: 'Loaded button' }] } })
+ const query = lazyDocument()
+ expect(
+ await getTool('query_nodes').execute(query.figma, { selector: '//COMPONENT', page: 'Later' })
+ ).toMatchObject({ count: 1 })
+ const components = lazyDocument()
+ expect(await getTool('get_components').execute(components.figma, {})).toMatchObject({
+ components: [{ name: 'Loaded button', page: 'Later' }]
+ })
+ })
+
+ test('switch to the page asked for last, whichever loads last', async () => {
+ const { graph } = setupToolTest()
+ const [first] = graph.getPages()
+ const slow = graph.addPage('Slow')
+ const fast = graph.addPage('Fast')
+ const slowLoad = Promise.withResolvers<undefined>()
+ const figma = new FigmaAPI(graph, {
+ loadPage: async (id) => {
+ if (id === slow.id) await slowLoad.promise
+ }
+ })
+ const slowSwitch = figma.setCurrentPageAsync(figma.wrapNode(slow.id))
+ await figma.setCurrentPageAsync(figma.wrapNode(fast.id))
+ slowLoad.resolve(undefined)
+ await slowSwitch
+ expect(figma.currentPage.id).toBe(fast.id)
+
+ // A page set directly counts as asked for last too.
+ const pending = Promise.withResolvers<undefined>()
+ const later = new FigmaAPI(graph, { loadPage: () => pending.promise })
+ const switching = later.setCurrentPageAsync(later.wrapNode(slow.id))
+ later.currentPage = later.wrapNode(first.id)
+ pending.resolve(undefined)
+ await switching
+ expect(later.currentPage.id).toBe(first.id)
+ })
+
+ test('refuse to switch to a page removed while it loaded', async () => {
+ const { graph } = setupToolTest()
+ const doomed = graph.addPage('Doomed')
+ const figma = new FigmaAPI(graph, {
+ loadPage: async () => {
+ graph.deleteNode(doomed.id)
+ }
+ })
+ await expect(figma.setCurrentPageAsync(figma.wrapNode(doomed.id))).rejects.toThrow(
+ 'removed while it loaded'
+ )
+
+ const later = graph.addPage('Later')
+ const removing = new FigmaAPI(graph, {
+ loadPage: async () => {
+ await Promise.resolve()
+ graph.deleteNode(later.id)
+ }
+ })
+ await expect(removing.setCurrentPageAsync(removing.wrapNode(later.id))).rejects.toThrow(
+ 'removed while it loaded'
+ )
+ })
+
+ test('load when a script or a tool switches to them', async () => {
+ const { figma, later, loads } = lazyDocument()
+ await getTool('switch_page').execute(figma, { page: 'Later' })
+ expect(figma.currentPage.children.map((node) => node.name)).toEqual(['Loaded button'])
+ await figma.loadAllPagesAsync()
+ expect(loads).toContain(later.id)
+ })
+})
+
describe('page tools', () => {
test('list_pages returns pages', () => {
const { figma } = setupToolTest()
@@ -237,18 +328,18 @@ describe('page tools', () => {
expect(result.pages.length).toBeGreaterThanOrEqual(1)
})
- test('switch_page changes page', () => {
+ test('switch_page changes page', async () => {
const { figma } = setupToolTest()
const page2 = figma.createPage()
page2.name = 'Page 2'
const tool = getTool('switch_page')
- tool.execute(figma, { page: 'Page 2' })
+ await tool.execute(figma, { page: 'Page 2' })
expect(figma.currentPage.name).toBe('Page 2')
})
- test('switch_page persists across separate FigmaAPI instances (RPC simulation)', () => {
+ test('switch_page persists across separate FigmaAPI instances (RPC simulation)', async () => {
const { graph } = setupToolTest()
const switchPage = getTool('switch_page')
const getCurrentPage = getTool('get_current_page')
@@ -256,19 +347,19 @@ describe('page tools', () => {
let currentPageId = graph.getPages()[0].id
- function rpcCall(tool: (typeof ALL_TOOLS)[number], args: Record<string, unknown>) {
+ async function rpcCall(tool: (typeof ALL_TOOLS)[number], args: Record<string, unknown>) {
const figma = new FigmaAPI(graph)
figma.currentPage = figma.wrapNode(currentPageId)
- const result = tool.execute(figma, args)
+ const result = await tool.execute(figma, args)
if (figma.currentPageId !== currentPageId) {
currentPageId = figma.currentPageId
}
return result
}
- rpcCall(createPage, { name: 'Second' })
- rpcCall(switchPage, { page: 'Second' })
- const result = rpcCall(getCurrentPage, {}) as { id: string; name: string }
+ await rpcCall(createPage, { name: 'Second' })
+ await rpcCall(switchPage, { page: 'Second' })
+ const result = (await rpcCall(getCurrentPage, {})) as { id: string; name: string }
expect(result.name).toBe('Second')
})