Skip to content

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

feat: find a layer by its ID on a page not loaded yet, as Figma's getNodeByIdAsync does (#1746)

Danila Poyarkov5dc7dd4a5cb1
diff --git a/changes/1746/fixed.md b/changes/1746/fixed.md
new file mode 100644
index 000000000..8b75b35a6
--- /dev/null
+++ b/changes/1746/fixed.md
@@ -0,0 +1 @@
+- `figma.getNodeByIdAsync()`, `get_node`, and `get_page_tree` find a layer by its ID on a page not opened yet, loading that page as Figma does.
diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.ts
index d7abb6fc0..0be53b452 100644
--- a/packages/core/src/editor/pages.ts
+++ b/packages/core/src/editor/pages.ts
@@ -11,7 +11,11 @@ import {
canUseFigPopulationWorker,
createFigPopulationWorker
} from '#core/kiwi/fig/population/client'
-import { isReaderPagePending, recoverReaderPage } from '#core/kiwi/fig/session/document-state'
+import {
+ isReaderPagePending,
+ pendingReaderPageOfNode,
+ recoverReaderPage
+} from '#core/kiwi/fig/session/document-state'
import { computeAllLayouts } from '#core/layout'
import { prepareGraphFonts } from '#core/text/prepare'
@@ -218,6 +222,13 @@ export function createPageActions(ctx: EditorContext, drawing?: PageDrawing) {
if (ctx.graph.getNode(pageId)?.type === 'CANVAS') await populatePage(pageId, null)
}
+ /** The page holding a layer not in the document yet because its page has not loaded. */
+ function pageHoldingNode(nodeId: string): Promise<string | null> {
+ return ctx.graph.getNode(nodeId)
+ ? Promise.resolve(null)
+ : pendingReaderPageOfNode(ctx.graph, nodeId)
+ }
+
async function prepareOffscreenPage(graph: SceneGraph, page: SceneNode): Promise<boolean> {
const populated = await populatePage(page.id, null)
if (populated === null || graph !== ctx.graph) return false
@@ -336,6 +347,7 @@ export function createPageActions(ctx: EditorContext, drawing?: PageDrawing) {
return {
loadPageNodes,
+ pageHoldingNode,
preparePageNodes,
pageSwitchCount,
preparePage,
diff --git a/packages/core/src/editor/read-only/actions.ts b/packages/core/src/editor/read-only/actions.ts
index 6c7eb052b..2e6929a9b 100644
--- a/packages/core/src/editor/read-only/actions.ts
+++ b/packages/core/src/editor/read-only/actions.ts
@@ -103,6 +103,7 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
'preparePage',
'preparePageNodes',
'loadPageNodes',
+ 'pageHoldingNode',
'revealNodes',
'setZoomAroundPoint',
'switchPage',
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 1b403c4af..e9ef5b400 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -66,7 +66,8 @@ import {
INTERNAL_ID,
loadPage,
MIXED,
- setPageLoader,
+ pageOfNode,
+ setPageHost,
type FigmaFont,
type NodeProxyHost
} from './proxy'
@@ -89,6 +90,8 @@ export interface FigmaAPIOptions {
* it, as they load pages in Figma's dynamic-page mode. Without one every page is in memory.
*/
loadPage?: (pageId: string) => Promise<void>
+ /** The page holding a layer not loaded yet, which `getNodeByIdAsync` loads to find it. */
+ pageOfNode?: (nodeId: string) => Promise<string | null>
}
export { FigmaNodeProxy } from './proxy'
@@ -157,7 +160,8 @@ 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)
+ if (options.loadPage)
+ setPageHost(this, { load: options.loadPage, pageOfNode: options.pageOfNode })
this.variables = new FigmaVariablesAPI(graph)
startPendingLayout(graph)
const pages = graph.getPages()
@@ -259,7 +263,13 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {
}
/** The async lookup that Figma requires in dynamic-page mode; same result as getNodeById. */
+ /** As in Figma's dynamic-page mode, a layer on a page not loaded yet loads that page. */
async getNodeByIdAsync(id: string): Promise<FigmaNodeProxy | null> {
+ const node = this.getNodeById(id)
+ if (node) return node
+ const pageId = await pageOfNode(this, id)
+ if (!pageId) return null
+ await loadPage(this, pageId)
return this.getNodeById(id)
}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index b861e0cac..b655361c8 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -49,18 +49,29 @@ export const INTERNAL_ID = Symbol('id')
export const INTERNAL_GRAPH = Symbol('graph')
export const INTERNAL_API = Symbol('api')
+/** How a host loads pages as they are visited; see `FigmaAPIOptions`. */
+export interface PageHost {
+ load: (pageId: string) => Promise<void>
+ pageOfNode?: (nodeId: string) => Promise<string | null>
+}
+
/**
* 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.
+ * members. Without one every page is in memory.
*/
-const pageLoaders = new WeakMap<NodeProxyHost, (pageId: string) => Promise<void>>()
+const pageHosts = new WeakMap<NodeProxyHost, PageHost>()
-export function setPageLoader(api: NodeProxyHost, load: (pageId: string) => Promise<void>): void {
- pageLoaders.set(api, load)
+export function setPageHost(api: NodeProxyHost, host: PageHost): void {
+ pageHosts.set(api, host)
}
export function loadPage(api: NodeProxyHost, pageId: string): Promise<void> {
- return pageLoaders.get(api)?.(pageId) ?? Promise.resolve()
+ return pageHosts.get(api)?.load(pageId) ?? Promise.resolve()
+}
+
+/** The page holding a layer not loaded yet, which loading that page brings in. */
+export function pageOfNode(api: NodeProxyHost, nodeId: string): Promise<string | null> {
+ return pageHosts.get(api)?.pageOfNode?.(nodeId) ?? Promise.resolve(null)
}
export interface NodeProxyHost extends ExportHost {
diff --git a/packages/core/src/kiwi/fig/session/archive/access.ts b/packages/core/src/kiwi/fig/session/archive/access.ts
index a3474c528..906d2ac2f 100644
--- a/packages/core/src/kiwi/fig/session/archive/access.ts
+++ b/packages/core/src/kiwi/fig/session/archive/access.ts
@@ -1,5 +1,6 @@
import {
figArchiveComponentUsePages,
+ figArchiveRecordPages,
patchFigArchive,
type FigArchiveRecordInfo,
type FigPatchedArchiveInput,
@@ -21,6 +22,8 @@ export interface FigArchiveAccess {
info(): Promise<FigArchiveRecordInfo>
/** Archive GUIDs of the pages whose instances use these components. */
componentPages(componentIds: string[]): Promise<string[]>
+ /** The archive GUID of the page each record is on, `null` for one on no page. */
+ recordPages(recordIds: string[]): Promise<(string | null)[]>
patch(patch: FigRecordPatch, input: FigPatchedArchiveInput): Promise<Uint8Array>
/** The document closed: release whatever holds the archive. */
close(): void
@@ -51,6 +54,8 @@ export function createFigArchiveOperations(bytes: ArrayBuffer, info: () => FigAr
original: () => new Uint8Array(bytes.slice(0)),
info,
componentPages: (componentIds: string[]) => figArchiveComponentUsePages(bytes, componentIds),
+ recordPages: (recordIds: string[]) =>
+ figArchiveRecordPages(bytes, recordIds).map((pageId) => pageId ?? null),
patch: async (patch: FigRecordPatch, input: FigPatchedArchiveInput) =>
patchFigArchive(bytes, patch, input, await loadFigDataCompressor(input.compressionLevel))
}
@@ -65,6 +70,7 @@ export function localFigArchive(
original: async () => operations.original(),
info: async () => operations.info(),
componentPages: async (componentIds) => operations.componentPages(componentIds),
+ recordPages: async (recordIds) => operations.recordPages(recordIds),
patch: (patch, input) => operations.patch(patch, input),
close: () => undefined
}
@@ -77,6 +83,7 @@ type ArchiveResponse = Extract<
| 'original-archive-result'
| 'archive-info-result'
| 'component-pages-result'
+ | 'record-pages-result'
| 'patch-archive-result'
| 'archive-error'
}
@@ -86,6 +93,7 @@ const ARCHIVE_RESPONSES = new Set<FigSessionResponse['type']>([
'original-archive-result',
'archive-info-result',
'component-pages-result',
+ 'record-pages-result',
'patch-archive-result',
'archive-error'
])
@@ -181,6 +189,13 @@ export function workerFigArchive(
(response) => response.pageIds,
(access) => access.componentPages(componentIds)
),
+ recordPages: (recordIds) =>
+ ask(
+ { type: 'record-pages', recordIds },
+ 'record-pages-result',
+ (response) => response.pageIds,
+ (access) => access.recordPages(recordIds)
+ ),
patch: (patch, input) =>
ask(
{ type: 'patch-archive', patch, input },
diff --git a/packages/core/src/kiwi/fig/session/document-state.ts b/packages/core/src/kiwi/fig/session/document-state.ts
index 1000b426e..be78f1754 100644
--- a/packages/core/src/kiwi/fig/session/document-state.ts
+++ b/packages/core/src/kiwi/fig/session/document-state.ts
@@ -1,6 +1,11 @@
-import { createFigDocumentSession, type FigSessionCheckpoint } from '@open-pencil/fig'
+import {
+ createFigDocumentSession,
+ figCheckpointRecords,
+ type FigSessionCheckpoint
+} from '@open-pencil/fig'
import type { SceneGraph } from '@open-pencil/scene-graph'
+import { figArchive } from '#core/kiwi/fig/session/archive/access'
import { readerSessionOptions, type FigReaderDiagnostic } from '#core/kiwi/fig/session/options'
/**
@@ -52,6 +57,23 @@ export function isReaderPagePending(graph: SceneGraph, pageId: string): boolean
: !checkpoint.loadedPageIds.includes(sourceId)
}
+/**
+ * The page holding a layer of the file while that page has not loaded, so a layer named by its
+ * ID, as a link to it names it, is found by loading its page. A layer's ID is its record's GUID;
+ * the archive answers which page holds it, in the reader's worker when there is one.
+ */
+export async function pendingReaderPageOfNode(
+ graph: SceneGraph,
+ nodeId: string
+): Promise<string | null> {
+ const archive = figArchive(graph)
+ const checkpoint = readerCheckpoint(graph)
+ if (!archive || !checkpoint || states.get(graph)?.complete) return null
+ const [pageGuid] = await archive.recordPages([nodeId])
+ const pageId = pageGuid ? figCheckpointRecords(checkpoint).get(pageGuid) : undefined
+ return pageId && isReaderPagePending(graph, pageId) ? pageId : null
+}
+
/** Where the reader stands: which records became which layers, and which pages it loaded. */
export function readerCheckpoint(graph: SceneGraph): FigSessionCheckpoint | undefined {
const state = states.get(graph)
diff --git a/packages/core/src/kiwi/fig/session/protocol.ts b/packages/core/src/kiwi/fig/session/protocol.ts
index 3156e235f..dca2209a8 100644
--- a/packages/core/src/kiwi/fig/session/protocol.ts
+++ b/packages/core/src/kiwi/fig/session/protocol.ts
@@ -42,6 +42,13 @@ export interface FigSessionComponentPagesRequest {
componentIds: string[]
}
+export interface FigSessionRecordPagesRequest {
+ type: 'record-pages'
+ requestId: string
+ /** Archive GUIDs of the records, as `session:local`. */
+ recordIds: string[]
+}
+
export interface FigSessionPatchArchiveRequest {
type: 'patch-archive'
requestId: string
@@ -68,6 +75,7 @@ export type FigSessionRequest =
| FigSessionOriginalArchiveRequest
| FigSessionArchiveInfoRequest
| FigSessionComponentPagesRequest
+ | FigSessionRecordPagesRequest
| FigSessionPatchArchiveRequest
| FigSessionRetireRequest
| FigSessionCancelRequest
@@ -97,6 +105,7 @@ export type FigSessionResponse =
| { type: 'original-archive-result'; requestId: string; bytes: Uint8Array }
| { type: 'archive-info-result'; requestId: string; info: FigArchiveRecordInfo }
| { type: 'component-pages-result'; requestId: string; pageIds: string[] }
+ | { type: 'record-pages-result'; requestId: string; pageIds: (string | null)[] }
| { type: 'patch-archive-result'; requestId: string; bytes: Uint8Array }
| { type: 'archive-error'; requestId: string; error: string }
| { type: 'disposed' }
diff --git a/packages/core/src/kiwi/fig/session/worker.ts b/packages/core/src/kiwi/fig/session/worker.ts
index 79b025d28..bfa7a95ba 100644
--- a/packages/core/src/kiwi/fig/session/worker.ts
+++ b/packages/core/src/kiwi/fig/session/worker.ts
@@ -40,7 +40,9 @@ function populate(request: Extract<FigSessionRequest, { type: 'populate' }>): vo
type ArchiveRequest = Extract<
FigSessionRequest,
- { type: 'original-archive' | 'archive-info' | 'component-pages' | 'patch-archive' }
+ {
+ type: 'original-archive' | 'archive-info' | 'component-pages' | 'record-pages' | 'patch-archive'
+ }
>
async function answerArchiveRequest(request: ArchiveRequest): Promise<void> {
@@ -55,6 +57,9 @@ async function answerArchiveRequest(request: ArchiveRequest): Promise<void> {
} else if (request.type === 'component-pages') {
const pageIds = archive.componentPages(request.componentIds)
respond({ type: 'component-pages-result', requestId, pageIds })
+ } else if (request.type === 'record-pages') {
+ const pageIds = archive.recordPages(request.recordIds)
+ respond({ type: 'record-pages-result', requestId, pageIds })
} else {
const bytes = await archive.patch(request.patch, request.input)
port?.postMessage({ type: 'patch-archive-result', requestId, bytes }, [bytes.buffer])
@@ -74,6 +79,7 @@ function handleRequest(request: FigSessionRequest): void {
request.type === 'original-archive' ||
request.type === 'archive-info' ||
request.type === 'component-pages' ||
+ request.type === 'record-pages' ||
request.type === 'patch-archive'
) {
void answerArchiveRequest(request)
diff --git a/packages/core/src/tools/read/nodes.ts b/packages/core/src/tools/read/nodes.ts
index b536df3b7..2fce38374 100644
--- a/packages/core/src/tools/read/nodes.ts
+++ b/packages/core/src/tools/read/nodes.ts
@@ -83,12 +83,9 @@ export const getPageTree = defineTool({
const typeFilter = node_types && node_types.length > 0 ? new Set(node_types) : undefined
if (root_id !== undefined) {
- const root = figma.getNodeById(root_id)
- // 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 layer on a page not yet visited loads that page, as in Figma's dynamic-page mode.
+ const root = await figma.getNodeByIdAsync(root_id)
+ if (!root) return { error: `Node "${root_id}" not found` }
// 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) }
@@ -108,7 +105,7 @@ export const getNode = defineTool({
name: 'get_node',
description:
'Get detailed properties of a node by ID. Use depth to limit child recursion (0 = node only, 1 = direct children, etc). Default: unlimited.',
- execution: { kind: 'sync', mutation: 'none' },
+ execution: { kind: 'async', mutation: 'none' },
input: v.strictObject({
id: nodeIdInputSchema,
depth: v.optional(
@@ -120,8 +117,9 @@ export const getNode = defineTool({
)
)
}),
- execute: (figma, { id, depth }) => {
- const node = figma.getNodeById(id)
+ execute: async (figma, { id, depth }) => {
+ // A layer on a page not yet visited loads that page, as in Figma's dynamic-page mode.
+ const node = await figma.getNodeByIdAsync(id)
if (!node) return { error: `Node "${id}" not found` }
return nodeToResult(node, depth)
}
diff --git a/packages/core/tests/io/formats/fig/session/worker/original-archive.test.ts b/packages/core/tests/io/formats/fig/session/worker/original-archive.test.ts
index 049d2b949..0dc73753d 100644
--- a/packages/core/tests/io/formats/fig/session/worker/original-archive.test.ts
+++ b/packages/core/tests/io/formats/fig/session/worker/original-archive.test.ts
@@ -7,11 +7,13 @@ import { parseFigBuffer } from '@open-pencil/fig'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { FigmaAPI } from '#core/figma-api'
import { parseFigFileViaWorker } from '#core/io/formats/fig/read'
import {
createFigPopulationWorker,
releaseFigPopulationWorker
} from '#core/kiwi/fig/population/client'
+import { pendingReaderPageOfNode } from '#core/kiwi/fig/session/document-state'
test('saving an unedited worker-opened .fig returns its original bytes', async () => {
await initCodec()
@@ -116,3 +118,28 @@ test('an abandoned page load stops the worker, and the archive is written withou
releaseFigPopulationWorker(opened)
}
}, 20000)
+
+test('a layer named by its ID on a page not loaded yet is found through the worker', async () => {
+ await initCodec()
+ const source = new SceneGraph()
+ source.createNode('TEXT', source.getPages()[0].id, { text: 'First' })
+ const later = source.createNode('TEXT', source.addPage('Second').id, { text: 'Second' })
+ const bytes = await exportFigFile(source)
+
+ const opened = await parseFigFileViaWorker(bytes.slice().buffer, { populate: 'first-page' })
+ try {
+ const second = opened.getPages()[1]
+ const figma = new FigmaAPI(opened, {
+ loadPage: async (id) => {
+ await createFigPopulationWorker(opened)?.populate(id)
+ },
+ pageOfNode: (id) => pendingReaderPageOfNode(opened, id)
+ })
+ expect(opened.getNode(later.id)).toBeUndefined()
+ expect(await pendingReaderPageOfNode(opened, later.id)).toBe(second.id)
+ expect((await figma.getNodeByIdAsync(later.id))?.characters).toBe('Second')
+ expect(opened.getChildren(second.id)).toHaveLength(1)
+ } finally {
+ releaseFigPopulationWorker(opened)
+ }
+}, 20000)
diff --git a/packages/core/tests/tools/read/nodes.test.ts b/packages/core/tests/tools/read/nodes.test.ts
index fd075cf01..d4607d3c7 100644
--- a/packages/core/tests/tools/read/nodes.test.ts
+++ b/packages/core/tests/tools/read/nodes.test.ts
@@ -10,7 +10,7 @@ function getNodeTool() {
return tool
}
-test('get_node includes component properties and layer references', () => {
+test('get_node includes component properties and layer references', async () => {
const graph = new SceneGraph()
const figma = new FigmaAPI(graph)
const definition = {
@@ -29,7 +29,7 @@ test('get_node includes component properties and layer references', () => {
componentPropertyReferences: [{ propertyId: definition.id, field: 'TEXT' }]
})
- const result = getNodeTool().execute(figma, { id: component.id })
+ const result = await getNodeTool().execute(figma, { id: component.id })
expect(result).toMatchObject({
componentPropertyDefinitions: [definition],
children: [
diff --git a/packages/fig/src/index.ts b/packages/fig/src/index.ts
index 3b7e98fff..21da891de 100644
--- a/packages/fig/src/index.ts
+++ b/packages/fig/src/index.ts
@@ -25,7 +25,9 @@ export {
export {
figArchiveComponentUsePages,
figArchiveRecordInfo,
+ figArchiveRecordPages,
figComponentUsePages,
+ figRecordPages,
patchFigArchive,
patchFigRecords,
type FigArchiveRecordInfo,
diff --git a/packages/fig/src/record-patch/index.ts b/packages/fig/src/record-patch/index.ts
index 156a48bc7..b360f49e4 100644
--- a/packages/fig/src/record-patch/index.ts
+++ b/packages/fig/src/record-patch/index.ts
@@ -492,6 +492,42 @@ export function patchFigArchive(
})
}
+/** The id of the nearest record of `type` from `id` up through its parents, itself included. */
+function nearestOfType(
+ byId: ReadonlyMap<string, NodeChange>,
+ id: string,
+ type: string
+): string | undefined {
+ const seen = new Set<string>()
+ for (let current = byId.get(id); current;) {
+ const currentId = key(current.guid)
+ if (!currentId || seen.has(currentId)) return undefined
+ seen.add(currentId)
+ if (current.type === type) return currentId
+ const parent = key(current.parentIndex?.guid)
+ current = parent ? byId.get(parent) : undefined
+ }
+ return undefined
+}
+
+function recordsById(records: readonly NodeChange[]): Map<string, NodeChange> {
+ const byId = new Map<string, NodeChange>()
+ for (const record of records) {
+ const id = key(record.guid)
+ if (id) byId.set(id, record)
+ }
+ return byId
+}
+
+/** The page each record is on, by its GUID, through its parents; undefined off every page. */
+export function figRecordPages(
+ records: readonly NodeChange[],
+ ids: readonly string[]
+): (string | undefined)[] {
+ const byId = recordsById(records)
+ return ids.map((id) => nearestOfType(byId, id, 'CANVAS'))
+}
+
/**
* The pages whose instances use these components, directly or through a component that nests
* one of them. Their records carry overrides and sizes derived from the components.
@@ -500,7 +536,7 @@ export function figComponentUsePages(
records: readonly NodeChange[],
componentIds: readonly string[]
): string[] {
- const byId = new Map<string, NodeChange>()
+ const byId = recordsById(records)
const instancesOf = new Map<string, string[]>()
const use = (componentId: string | undefined, instanceId: string) => {
if (!componentId) return
@@ -510,24 +546,11 @@ export function figComponentUsePages(
}
for (const record of records) {
const id = key(record.guid)
- if (!id) continue
- byId.set(id, record)
- if (record.type !== 'INSTANCE') continue
+ if (!id || record.type !== 'INSTANCE') continue
use(key(symbolDataOf(record)?.symbolID), id)
for (const override of symbolOverridesOf(record)) use(key(override.overriddenSymbolID), id)
}
- const nearest = (id: string, type: string): string | undefined => {
- const seen = new Set<string>()
- for (let current = byId.get(id); current;) {
- const currentId = key(current.guid)
- if (!currentId || seen.has(currentId)) return undefined
- seen.add(currentId)
- if (current.type === type) return currentId
- const parent = key(current.parentIndex?.guid)
- current = parent ? byId.get(parent) : undefined
- }
- return undefined
- }
+ const nearest = (id: string, type: string) => nearestOfType(byId, id, type)
const pages = new Set<string>()
const visited = new Set<string>()
const pending = [...componentIds]
@@ -544,15 +567,12 @@ export function figComponentUsePages(
return [...pages]
}
-/** `figComponentUsePages` over an encoded archive, reading only what it needs of each record. */
-export function figArchiveComponentUsePages(
- bytes: ArrayBuffer,
- componentIds: readonly string[]
-): string[] {
+/** An encoded archive's records with only the fields the page lookups read. */
+function scannedRecords(bytes: ArrayBuffer): NodeChange[] {
const parts = readFigArchiveParts(bytes)
const codec = archiveCodec(parts.schemaDeflated)
const scanned = scanMessage(codec, parts.dataRaw, true)
- const records = scanned.records.map(
+ return scanned.records.map(
(entry) =>
({
guid: entry.guid,
@@ -561,5 +581,29 @@ export function figArchiveComponentUsePages(
symbolData: entry.symbolData
}) as NodeChange
)
- return figComponentUsePages(records, componentIds)
+}
+
+/** `figComponentUsePages` over an encoded archive, reading only what it needs of each record. */
+export function figArchiveComponentUsePages(
+ bytes: ArrayBuffer,
+ componentIds: readonly string[]
+): string[] {
+ return figComponentUsePages(scannedRecords(bytes), componentIds)
+}
+
+/** Each archive's records by GUID, scanned once: an archive's bytes are never written to. */
+const archiveRecordIndexes = new WeakMap<ArrayBuffer, Map<string, NodeChange>>()
+
+/** `figRecordPages` over an encoded archive, reading only what it needs of each record. */
+export function figArchiveRecordPages(
+ bytes: ArrayBuffer,
+ ids: readonly string[]
+): (string | undefined)[] {
+ let byId = archiveRecordIndexes.get(bytes)
+ if (!byId) {
+ byId = recordsById(scannedRecords(bytes))
+ archiveRecordIndexes.set(bytes, byId)
+ }
+ const index = byId
+ return ids.map((id) => nearestOfType(index, id, 'CANVAS'))
}
diff --git a/packages/fig/tests/record-patch/index.test.ts b/packages/fig/tests/record-patch/index.test.ts
index 78583fa18..10731aa11 100644
--- a/packages/fig/tests/record-patch/index.test.ts
+++ b/packages/fig/tests/record-patch/index.test.ts
@@ -1,7 +1,12 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { guid } from '#fig-tests/helpers/guid'
-import { figComponentUsePages, patchFigMessage, patchFigRecords } from '#fig/record-patch/index'
+import {
+ figComponentUsePages,
+ figRecordPages,
+ patchFigMessage,
+ patchFigRecords
+} from '#fig/record-patch/index'
import { deflateSync } from 'fflate'
import {
@@ -126,6 +131,26 @@ describe('pages using components', () => {
})
})
+describe('the page a record is on', () => {
+ test('is the page above it, through its parents, whether that page is loaded or not', () => {
+ const records = [
+ record(0, null, { type: 'DOCUMENT' }),
+ record(1, 0, { type: 'CANVAS' }),
+ record(2, 1),
+ record(3, 2, { type: 'TEXT' }),
+ record(4, 0, { type: 'CANVAS' }),
+ record(5, 4)
+ ]
+ expect(figRecordPages(records, ['1:3', '1:5', '1:4', '1:0', '9:9'])).toEqual([
+ '1:1',
+ '1:4',
+ '1:4',
+ undefined,
+ undefined
+ ])
+ })
+})
+
describe('splicing an encoded message', () => {
beforeAll(() => initCodec())
diff --git a/src/app/automation/bridge/figma-factory.ts b/src/app/automation/bridge/figma-factory.ts
index 4311b2f55..06679b28d 100644
--- a/src/app/automation/bridge/figma-factory.ts
+++ b/src/app/automation/bridge/figma-factory.ts
@@ -24,7 +24,8 @@ export function makeFigmaFromStore(
loadPage: async (id) => {
if (!(await store.preparePageNodes(id)))
throw new Error(`Page "${id}" was closed before it finished loading`)
- }
+ },
+ pageOfNode: (id) => store.pageHoldingNode(id)
})
api.setRenderer(store.renderer ?? null)
api.icons = store.iconProvider
diff --git a/tests/app/automation/bridge/tool-page.test.ts b/tests/app/automation/bridge/tool-page.test.ts
index 42d22ad04..50878bf45 100644
--- a/tests/app/automation/bridge/tool-page.test.ts
+++ b/tests/app/automation/bridge/tool-page.test.ts
@@ -25,11 +25,19 @@ afterEach(() => {
})
/** A `.fig` opened like the app does: only the first page has its layers. */
-async function storeWithUnshownPage(): Promise<{ store: EditorStore; pageId: string }> {
+async function storeWithUnshownPage(): Promise<{
+ store: EditorStore
+ pageId: string
+ frameId: string
+}> {
const source = new SceneGraph()
source.createNode('FRAME', source.getPages()[0].id, { name: 'First frame' })
const second = source.addPage('Second')
- source.createNode('FRAME', second.id, { name: 'Second frame', width: 70, height: 35 })
+ const frame = source.createNode('FRAME', second.id, {
+ name: 'Second frame',
+ width: 70,
+ height: 35
+ })
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' })
@@ -38,7 +46,7 @@ async function storeWithUnshownPage(): Promise<{ store: EditorStore; pageId: str
const page = graph.getPages().find((p) => p.name === 'Second')
if (!page) throw new Error('Missing second page')
expect(graph.getChildren(page.id)).toHaveLength(0)
- return { store, pageId: page.id }
+ return { store, pageId: page.id, frameId: frame.id }
}
function target(store: EditorStore, pageId: string): AutomationTarget {
@@ -52,6 +60,31 @@ function target(store: EditorStore, pageId: string): AutomationTarget {
}
describe('automation tools on a page that has not been shown', () => {
+ test('a layer named by its ID loads its page, as in Figma', async () => {
+ const { store, pageId, frameId } = await storeWithUnshownPage()
+ const shown = store.state.currentPageId
+
+ const response = (await handleTargetCommand(target(store, shown), 'tool', {
+ name: 'get_node',
+ args: { id: frameId, depth: 0 }
+ })) as { result: { name: string } }
+
+ expect(response.result.name).toBe('Second frame')
+ expect(store.graph.getChildren(pageId)).toHaveLength(1)
+ expect(store.state.currentPageId).toBe(shown)
+ })
+
+ test('get_page_tree rooted at a layer there loads its page', async () => {
+ const { store, frameId } = await storeWithUnshownPage()
+
+ const response = (await handleTargetCommand(target(store, store.state.currentPageId), 'tool', {
+ name: 'get_page_tree',
+ args: { root_id: frameId }
+ })) as { result: { root: string; tree: { name: string } } }
+
+ expect(response.result).toMatchObject({ root: frameId, tree: { name: 'Second frame' } })
+ })
+
test('find_nodes sees the layers of the target page', async () => {
const { store, pageId } = await storeWithUnshownPage()
const shown = store.state.currentPageId
diff --git a/tests/engine/mcp/tools.test.ts b/tests/engine/mcp/tools.test.ts
index 8255c6f26..f8168b5ff 100644
--- a/tests/engine/mcp/tools.test.ts
+++ b/tests/engine/mcp/tools.test.ts
@@ -303,9 +303,11 @@ describe('MCP tool execution', () => {
expect(result.pages[0].name).toBe('Page 1')
})
- test('error on missing node', () => {
+ test('error on missing node', async () => {
const { api } = setup()
- const result = findTool('get_node').execute(api, { id: 'nonexistent' }) as { error: string }
+ const result = (await findTool('get_node').execute(api, { id: 'nonexistent' })) as {
+ error: string
+ }
expect(result.error).toContain('not found')
})
diff --git a/tests/engine/tools/create.test.ts b/tests/engine/tools/create.test.ts
index fcaf4c0dd..9da307a42 100644
--- a/tests/engine/tools/create.test.ts
+++ b/tests/engine/tools/create.test.ts
@@ -140,7 +140,7 @@ describe('render', () => {
})) as ToolResult
const textId = (card.children as string[])[0]
const getNode = getTool('get_node')
- const result = getNode.execute(figma, { id: textId, depth: 0 }) as ToolResult
+ const result = (await getNode.execute(figma, { id: textId, depth: 0 })) as ToolResult
expect(result.characters).toBe('Hello')
expect(result.fontFamily).toBe('Inter')
diff --git a/tests/engine/tools/read.test.ts b/tests/engine/tools/read.test.ts
index a3c21db63..f6cfe0dfe 100644
--- a/tests/engine/tools/read.test.ts
+++ b/tests/engine/tools/read.test.ts
@@ -197,14 +197,14 @@ describe('get_font_status', () => {
})
describe('get_node', () => {
- test('returns node details', () => {
+ test('returns node details', async () => {
const { figma } = setupToolTest()
const rect = figma.createRectangle()
rect.name = 'Test Rect'
rect.resize(100, 50)
const tool = getTool('get_node')
- const result = tool.execute(figma, { id: rect.id }) as ToolResult
+ const result = (await tool.execute(figma, { id: rect.id })) as ToolResult
expect(result.name).toBe('Test Rect')
expect(result.width).toBe(100)
expect(result.height).toBe(50)