Skip to content

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

fix(fig): load .fig pages without resyncing instances or abandoning slow loads (#1273)

Danila Poyarkovec75da3a0f1c
diff --git a/changes/1273/fixed.md b/changes/1273/fixed.md
new file mode 100644
index 000000000..ecca0259d
--- /dev/null
+++ b/changes/1273/fixed.md
@@ -0,0 +1,2 @@
+- Pages of a `.fig` file opened after the first keep their instance swaps, theme colours, and exact positions instead of resetting some of them to their component's.
+- Large pages of a `.fig` file, such as those of big design kits, load once in the background instead of timing out and loading again while the editor waits.
diff --git a/changes/1273/performance.md b/changes/1273/performance.md
new file mode 100644
index 000000000..2890d4005
--- /dev/null
+++ b/changes/1273/performance.md
@@ -0,0 +1,3 @@
+- Pages of a `.fig` file opened after the first load faster, about a quarter faster on a large design kit page.
+- A `.fig` document read without the background worker, as the CLI and the MCP server read it, frees the file's decoded records once every page is loaded and the document is saved, instead of keeping them while it stays open; on a large design kit that was hundreds of megabytes.
+- Layers inside instances share the layout settings Figma saved with their component's layers, so a large design kit page takes less memory.
diff --git a/packages/core/src/kiwi/fig/population/client.ts b/packages/core/src/kiwi/fig/population/client.ts
index 468e9df8a..38748e0c5 100644
--- a/packages/core/src/kiwi/fig/population/client.ts
+++ b/packages/core/src/kiwi/fig/population/client.ts
@@ -8,11 +8,18 @@ import type { FigSessionResponse } from '#core/kiwi/fig/session/protocol'
import { applyFigPopulationDelta } from './delta'
-/** The two responses this client acts on, taken from the session protocol itself. */
-type WorkerResult = Extract<FigSessionResponse, { type: 'population-result' | 'population-error' }>
+/** The responses this client acts on, taken from the session protocol itself. */
+type WorkerResult = Extract<
+ FigSessionResponse,
+ { type: 'population-result' | 'population-error' | 'population-progress' }
+>
const MAX_FIG_POPULATION_WORKER_NODES = 200_000
-const FIG_POPULATION_WORKER_TIMEOUT_MS = 30_000
+/**
+ * How long a page load may go without reporting progress before the worker counts as stuck. A
+ * large page legitimately takes longer than this; it reports progress as it goes.
+ */
+const FIG_POPULATION_WORKER_STALL_MS = 30_000
const populationWorkers = new WeakMap<SceneGraph, FigPopulationWorker>()
interface OriginalArchiveRequest {
request: () => Promise<Uint8Array>
@@ -170,6 +177,15 @@ export function createPopulationWorkerClient(
let stale = false
let disposed = false
let applyingDelta = false
+ /** Answer every load in flight with null, so its page loads on the main thread instead. */
+ const settlePending = () => {
+ for (const request of pending.values()) {
+ clearTimeout(request.timeout)
+ request.abort?.()
+ request.resolve(null)
+ }
+ pending.clear()
+ }
const invalidate = () => {
// Layout recomputation (import-time or after a switch) is derived from the
// same scene graph the worker deltas were built from; it must not count as
@@ -178,6 +194,8 @@ export function createPopulationWorkerClient(
revision++
stale = true
emitTelemetry({ event: 'stale', reason: 'graph-mutation' })
+ // A load in flight can no longer apply, however long the worker keeps reporting progress.
+ settlePending()
}
let unbind: (() => void) | undefined
const releaseSubscription = () => {
@@ -191,12 +209,7 @@ export function createPopulationWorkerClient(
const fail = (emit = true, stop = true) => {
stale = true
if (emit) emitTelemetry({ event: 'fallback', reason: 'worker-error' })
- for (const request of pending.values()) {
- clearTimeout(request.timeout)
- request.abort?.()
- request.resolve(null)
- }
- pending.clear()
+ settlePending()
releaseSubscription()
if (stop || !sharedWorker) stopWorkerNow()
else port?.postMessage({ type: 'retire' })
@@ -209,8 +222,16 @@ export function createPopulationWorkerClient(
reparented: invalidate,
reordered: invalidate
})
+ const watchForStall = () => setTimeout(() => fail(), FIG_POPULATION_WORKER_STALL_MS)
const receive = (result: WorkerResult) => {
if (result.type === 'population-error') return fail(true, false)
+ if (result.type === 'population-progress') {
+ const request = pending.get(result.requestId)
+ if (!request) return
+ clearTimeout(request.timeout)
+ request.timeout = watchForStall()
+ return
+ }
const request = pending.get(result.requestId)
if (!request) return
clearTimeout(request.timeout)
@@ -265,13 +286,12 @@ export function createPopulationWorkerClient(
reject(new DOMException('Aborted', 'AbortError'))
}
signal?.addEventListener('abort', abort, { once: true })
- const timeout = setTimeout(() => fail(), FIG_POPULATION_WORKER_TIMEOUT_MS)
pending.set(requestId, {
resolve,
abort: () => signal?.removeEventListener('abort', abort),
revision: baseRevision,
startedAt: performance.now(),
- timeout
+ timeout: watchForStall()
})
if (port) port.postMessage({ type: 'populate', requestId, baseRevision, pageId })
else worker.postMessage({ type: 'populate', requestId, baseRevision, pageId }, [])
diff --git a/packages/core/src/kiwi/fig/session/protocol.ts b/packages/core/src/kiwi/fig/session/protocol.ts
index 03a791970..3156e235f 100644
--- a/packages/core/src/kiwi/fig/session/protocol.ts
+++ b/packages/core/src/kiwi/fig/session/protocol.ts
@@ -91,6 +91,8 @@ export type FigSessionResponse =
checkpoint?: FigSessionCheckpoint
delta: FigPopulationDelta
}
+ /** A page load is still advancing; sent at most once a second while it runs. */
+ | { type: 'population-progress'; requestId: string }
| { type: 'population-error'; requestId?: string; error: string }
| { type: 'original-archive-result'; requestId: string; bytes: Uint8Array }
| { type: 'archive-info-result'; requestId: string; info: FigArchiveRecordInfo }
diff --git a/packages/core/src/kiwi/fig/session/reader.ts b/packages/core/src/kiwi/fig/session/reader.ts
index e8a8ddde6..ec1224d98 100644
--- a/packages/core/src/kiwi/fig/session/reader.ts
+++ b/packages/core/src/kiwi/fig/session/reader.ts
@@ -40,13 +40,15 @@ export function openReaderSession(
checkpoint: () => session.checkpoint(),
graph: session.graph,
pages,
- populate(pageId: string) {
+ /** `onProgress` is called as the load advances, as `loadPage` calls it. */
+ populate(pageId: string, onProgress?: () => void) {
const sourceId = sourceByGraph.get(pageId)
if (!sourceId) throw new Error(`Unknown graph page ${pageId}`)
const populated = !session.loadedPageIds.has(sourceId)
const journal = installFigMutationJournal(session.graph)
try {
- session.loadPage(sourceId)
+ session.loadPage(sourceId, onProgress)
+ onProgress?.()
return {
checkpoint: session.checkpoint(),
populated,
diff --git a/packages/core/src/kiwi/fig/session/worker.ts b/packages/core/src/kiwi/fig/session/worker.ts
index cb1182eed..62563ce3d 100644
--- a/packages/core/src/kiwi/fig/session/worker.ts
+++ b/packages/core/src/kiwi/fig/session/worker.ts
@@ -11,13 +11,23 @@ let session: ReturnType<typeof openReaderSession> | undefined
let archive: ReturnType<typeof createFigArchiveOperations> | undefined
let port: MessagePort | undefined
+/** How often a page load reports that it is still advancing. */
+const PROGRESS_INTERVAL_MS = 1000
+
function respond(message: FigSessionResponse): void {
port?.postMessage(message)
}
function populate(request: Extract<FigSessionRequest, { type: 'populate' }>): void {
if (!session) throw new Error('FIG session has no retained reader')
- const result = session.populate(request.pageId)
+ const { requestId } = request
+ let reportedAt = performance.now()
+ const result = session.populate(request.pageId, () => {
+ const now = performance.now()
+ if (now - reportedAt < PROGRESS_INTERVAL_MS) return
+ reportedAt = now
+ respond({ type: 'population-progress', requestId })
+ })
respond({
type: 'population-result',
requestId: request.requestId,
diff --git a/packages/core/tests/io/formats/fig/import/shared-instance-values.test.ts b/packages/core/tests/io/formats/fig/import/shared-instance-values.test.ts
index 559eee4e0..bb900f431 100644
--- a/packages/core/tests/io/formats/fig/import/shared-instance-values.test.ts
+++ b/packages/core/tests/io/formats/fig/import/shared-instance-values.test.ts
@@ -35,6 +35,9 @@ test('a layer inside an instance holds its component layer’s unchanged values'
expect(layer.effects).toBe(source.effects)
expect(layer.source).not.toBe(source.source)
expect(layer.instanceOverrides).not.toBe(source.instanceOverrides)
+ // The layout Figma saved is part of the layer's own source metadata, yet still the same.
+ expect(layer.source.fig.layout).not.toBeNull()
+ expect(layer.source.fig.layout).toBe(source.source.fig.layout)
})
test('changing a layer inside an instance leaves its component layer as it was', async () => {
diff --git a/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts b/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts
index 6dbd2cf21..0d5fff1cb 100644
--- a/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts
+++ b/packages/core/tests/io/formats/fig/session/page-instance-sync.test.ts
@@ -69,12 +69,7 @@ test('loading a later page keeps a live edit to a nested instance layer over its
expect(session.graph.getChildren(loadedPlaced.id)[0].width).toBe(120)
})
-/**
- * Syncing a whole component visits every instance of it in the graph, including those earlier
- * pages placed, whose sizes Figma derived. A resumed page syncs only the instances it places,
- * each once.
- */
-test('a resumed page load syncs each instance it places once, never a whole component', async () => {
+async function sessionWithPlacedInstances() {
await initCodec()
const source = new SceneGraph()
const library = source.getPages()[0]
@@ -97,16 +92,61 @@ test('a resumed page load syncs each instance it places once, never a whole comp
wholeComponents.push(componentId)
return syncInstances(componentId)
}
- const placed = session.pages.find((candidate) => candidate.name === 'Placed')
- if (!placed) throw new Error('Missing placed page')
- session.loadPage(placed.id)
+ const pageNamed = (name: string) => {
+ const found = session.pages.find((candidate) => candidate.name === name)
+ if (!found) throw new Error(`Missing page ${name}`)
+ return found
+ }
+ const loadPlaced = () => {
+ const placed = pageNamed('Placed')
+ session.loadPage(placed.id)
+ const pageId = session.graphPageId(placed.id)
+ if (!pageId) throw new Error('Missing materialized page')
+ return session.graph.getChildren(pageId)
+ }
+ return { session, synced, wholeComponents, pageNamed, loadPlaced }
+}
+
+/**
+ * Syncing a whole component visits every instance of it in the graph, including those earlier
+ * pages placed, whose sizes Figma derived. A page loaded into an edited graph syncs only the
+ * instances it places, each once.
+ */
+test('a page load into an edited graph syncs each instance it places once, never a whole component', async () => {
+ const { session, synced, wholeComponents, pageNamed, loadPlaced } =
+ await sessionWithPlacedInstances()
+ session.loadPage(pageNamed('Page 1').id)
+ const libraryId = session.graphPageId(pageNamed('Page 1').id) ?? ''
+ const component = session.graph.getChildren(libraryId)[0]
+ session.graph.updateNode(component.id, { name: 'Badge 2' })
- const pageId = session.graphPageId(placed.id)
- if (!pageId) throw new Error('Missing materialized page')
- const instances = session.graph.getChildren(pageId)
+ const instances = loadPlaced()
expect(instances).toHaveLength(8)
expect(wholeComponents).toEqual([])
expect(synced.toSorted()).toEqual(instances.map((instance) => instance.id).toSorted())
for (const instance of instances)
expect(session.graph.getChildren(instance.id)[0].text).toBe('Badge')
})
+
+/**
+ * Nothing in a graph only page loads and their layout wrote can differ from the file, so a
+ * page load has nothing to reconcile its instances with; on a design kit that sync was most
+ * of the time a large page took to load.
+ */
+test('a page load into a graph only loads and derived layout wrote syncs no instances', async () => {
+ const { session, synced, wholeComponents, pageNamed, loadPlaced } =
+ await sessionWithPlacedInstances()
+ session.loadPage(pageNamed('Page 1').id)
+ const libraryId = session.graphPageId(pageNamed('Page 1').id) ?? ''
+ const component = session.graph.getChildren(libraryId)[0]
+ session.graph.applyDerivedLayoutDuring(() =>
+ session.graph.updateNode(component.id, { height: component.height + 1 })
+ )
+
+ const instances = loadPlaced()
+ expect(instances).toHaveLength(8)
+ expect(synced).toEqual([])
+ expect(wholeComponents).toEqual([])
+ for (const instance of instances)
+ expect(session.graph.getChildren(instance.id)[0].text).toBe('Badge')
+})
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
similarity index 100%
rename from packages/core/tests/io/formats/fig/session/worker-original-archive.test.ts
rename to packages/core/tests/io/formats/fig/session/worker/original-archive.test.ts
diff --git a/packages/core/tests/io/formats/fig/session/worker-reader.test.ts b/packages/core/tests/io/formats/fig/session/worker/reader.test.ts
similarity index 100%
rename from packages/core/tests/io/formats/fig/session/worker-reader.test.ts
rename to packages/core/tests/io/formats/fig/session/worker/reader.test.ts
diff --git a/packages/core/tests/io/formats/fig/session/worker/stall.test.ts b/packages/core/tests/io/formats/fig/session/worker/stall.test.ts
new file mode 100644
index 000000000..54b06f562
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/worker/stall.test.ts
@@ -0,0 +1,93 @@
+import { afterEach, expect, jest, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { createPopulationWorkerClient } from '#core/kiwi/fig/population/client'
+import type { FigSessionPopulateRequest, FigSessionResponse } from '#core/kiwi/fig/session/protocol'
+
+afterEach(() => {
+ jest.useRealTimers()
+})
+
+function workerClient() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ let request: FigSessionPopulateRequest | undefined
+ let terminated = false
+ const port = {
+ onmessage: null as ((event: MessageEvent<FigSessionResponse>) => void) | null,
+ start: () => undefined,
+ close: () => undefined,
+ postMessage(message: FigSessionPopulateRequest) {
+ request = message
+ }
+ }
+ const worker = {
+ terminate: () => {
+ terminated = true
+ },
+ postMessage: () => undefined,
+ onerror: null,
+ onmessage: null
+ }
+ const client = createPopulationWorkerClient(graph, worker, port)
+ const send = (data: FigSessionResponse) =>
+ port.onmessage?.(new MessageEvent<FigSessionResponse>('message', { data }))
+ const sent = () => {
+ if (!request) throw new Error('Missing request')
+ return request
+ }
+ return { client, graph, page, send, sent, terminated: () => terminated }
+}
+
+/**
+ * A large page of a design kit takes the worker longer than the stall window, and loading it
+ * again on the main thread after giving up costs as much again. Progress keeps the load alive.
+ */
+test('a page load that keeps reporting progress outlives the stall window', async () => {
+ jest.useFakeTimers()
+ const { client, page, send, sent, terminated } = workerClient()
+ const pending = client.populate(page.id)
+ for (let second = 0; second < 90; second++) {
+ jest.advanceTimersByTime(1000)
+ send({ type: 'population-progress', requestId: sent().requestId })
+ }
+ expect(terminated()).toBe(false)
+ send({
+ type: 'population-result',
+ requestId: sent().requestId,
+ baseRevision: sent().baseRevision,
+ populated: true,
+ delta: { created: [], updated: [], deleted: [], instanceIndex: [], populatedRootIds: [] }
+ })
+ expect(await pending).toBe(true)
+ client.terminate()
+})
+
+test('a page load that stops reporting progress falls back once the stall window passes', async () => {
+ jest.useFakeTimers()
+ const { client, page, send, sent, terminated } = workerClient()
+ const pending = client.populate(page.id)
+ jest.advanceTimersByTime(10_000)
+ send({ type: 'population-progress', requestId: sent().requestId })
+ jest.advanceTimersByTime(29_999)
+ expect(terminated()).toBe(false)
+ jest.advanceTimersByTime(1)
+ expect(terminated()).toBe(true)
+ expect(await pending).toBeNull()
+})
+
+/**
+ * An edit makes the worker's result unusable, so progress no longer keeps the load waiting: the
+ * page loads on the main thread at once instead of after the worker finishes for nothing.
+ */
+test('an edit during a page load that keeps reporting progress ends the wait at once', async () => {
+ jest.useFakeTimers()
+ const { client, graph, page, send, sent } = workerClient()
+ const pending = client.populate(page.id)
+ send({ type: 'population-progress', requestId: sent().requestId })
+ graph.createNode('RECTANGLE', page.id)
+ send({ type: 'population-progress', requestId: sent().requestId })
+ expect(await pending).toBeNull()
+ client.terminate()
+})
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index eb0f5ab71..93c8fe311 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -150,6 +150,7 @@ export function createFigDocumentSession(
state.graph.figKiwiVersion = archive.figKiwiVersion
state.graph.figSchemaDeflated = archive.figSchemaDeflated
const loaded = new Set<string>(resume?.checkpoint.loadedPageIds)
+ const edits = watchGraphEdits(state.graph, resume !== undefined)
let recordInfo: FigArchiveRecordInfo | undefined
return {
checkpoint(): FigSessionCheckpoint {
@@ -181,11 +182,15 @@ export function createFigDocumentSession(
})
return recordInfo
},
- loadPage(id: string): void {
+ /** `onProgress` is called as the load advances, so a caller can tell a slow load from a stuck one. */
+ loadPage(id: string, onProgress?: () => void): void {
if (loaded.has(id)) return
const reader = archive.reader.selectPages(new Set([id]))
loadPageTransaction(state, reader.dependencyClosure, () => {
- materializeReader(reader, archive.blobs, sessionOptions, state)
+ materializeReader(reader, archive.blobs, sessionOptions, state, {
+ edited: edits.edited,
+ onProgress
+ })
loaded.add(id)
})
},
@@ -195,6 +200,28 @@ export function createFigDocumentSession(
}
}
+/**
+ * Whether the graph may hold edits made since the file loaded, which a page load has to
+ * reconcile its new instances with. A resumed session's graph may; a fresh one's does once a
+ * layer changes outside page loads and derived layout, the edits the archive tracker counts.
+ */
+function watchGraphEdits(graph: SceneGraph, resumed: boolean): { readonly edited: boolean } {
+ let edited = resumed
+ if (edited) return { edited }
+ const isEdit = () => !graph.isApplyingImportedState && !graph.isApplyingDerivedLayout
+ const markEdited = () => {
+ if (!isEdit()) return
+ edited = true
+ stop()
+ }
+ const stop = graph.observeNodeChanges({ before: markEdited, created: markEdited })
+ return {
+ get edited() {
+ return edited
+ }
+ }
+}
+
/** Definition types already in the graph; only needed once, or after a resume. */
function seedDefinitionTypes(graph: SceneGraph): Map<string, string> {
const types = new Map<string, string>()
@@ -204,18 +231,28 @@ function seedDefinitionTypes(graph: SceneGraph): Map<string, string> {
return types
}
+/**
+ * A graph whose own root and first page take imported ids, and every later entity the production
+ * allocator's. The graph keeps its generator for life, and a closure keeps every variable its
+ * scope shares with other closures, so the generator lives here, away from the archive reader.
+ */
+function createImportedGraph(): { graph: SceneGraph; nextImportedId: number } {
+ let initializing = true
+ let nextImportedId = 1
+ const graph = new SceneGraph(() => (initializing ? `0:${nextImportedId++}` : generateId()))
+ initializing = false
+ return { graph, nextImportedId }
+}
+
function createAssemblyState(
reader: ReturnType<typeof createDocumentReader>,
options: DocumentAssemblyOptions
): AssemblyState {
// Imported runtime handles remain reproducible for CLI inspection and patches. Authored
// entities use the production allocator even when created in a previously imported graph.
- let initializing = true
- let nextImportedId = 1
- const graph: SceneGraph = new SceneGraph(() =>
- initializing ? `0:${nextImportedId++}` : generateId()
- )
- initializing = false
+ const imported = createImportedGraph()
+ const { graph } = imported
+ let { nextImportedId } = imported
applyDocumentMetadata(graph, reader.documentRecord)
for (const [hash, bytes] of options.images ?? []) graph.images.set(hash, bytes.slice())
graph.applyImportedStateDuring(
@@ -252,7 +289,7 @@ function inferNextImportedId(graph: SceneGraph): number {
}
/**
- * Syncing a resumed load's new instances copies their component's sizes over the sizes Figma
+ * Syncing an edited graph's new instances copies their component's sizes over the sizes Figma
* derived for them, such as a field filling its resized instance. Puts the derived sizes back,
* except along an axis whose component layer was edited live, which syncing rightly carried over:
* the layer an owning instance maps it to, or its own component.
@@ -276,22 +313,32 @@ function restoreDerivedSizes(
})
}
+/** How a page load joins a graph that earlier loads built. */
+interface PageLoad {
+ /** The graph may hold edits made since the file loaded, which new instances must take. */
+ edited: boolean
+ onProgress?: () => void
+}
+
function materializeReader(
reader: ReturnType<typeof createDocumentReader>,
blobs: Uint8Array[],
options: DocumentAssemblyOptions,
- previous?: AssemblyState
+ previous?: AssemblyState,
+ load: PageLoad = { edited: false }
): AssemblyState {
for (const diagnostic of reader.bindingDiagnostics) {
if (!options.onUnresolvedBinding)
throw new Error(`Unresolved binding ${diagnostic.sourceId}: ${diagnostic.field}`)
options.onUnresolvedBinding(diagnostic)
}
- const pages = reader.pages.map((page) => reader.readPage(page.id, options))
+ // Reading a large page and the components it places takes a while on its own.
+ const readOptions = load.onProgress ? { ...options, onProgress: load.onProgress } : options
+ const pages = reader.pages.map((page) => reader.readPage(page.id, readOptions))
const state = previous ?? createAssemblyState(reader, options)
- const plan = reader.planComponents(pages, options, (id) => state.components.has(id))
+ const plan = reader.planComponents(pages, readOptions, (id) => state.components.has(id))
return state.graph.applyImportedStateDuring(
- () => materializeReaderInto(pages, plan, blobs, state, previous !== undefined),
+ () => materializeReaderInto(pages, plan, blobs, state, load),
() => `0:${state.nextImportedId++}`
)
}
@@ -301,7 +348,7 @@ function materializeReaderInto(
plan: ComponentConstruction[],
blobs: Uint8Array[],
state: AssemblyState,
- resumed: boolean
+ { edited, onProgress }: PageLoad
): AssemblyState {
const { graph, sources, components, savedSizeNodes, componentIds } = state
const existingNodeIds = new Set(graph.nodes.keys())
@@ -339,6 +386,7 @@ function materializeReaderInto(
}
for (const page of pages) createShells(page, graph.rootId)
for (const item of plan) {
+ onProgress?.()
if (components.has(item.sourceId)) continue
const parentId = sources.get(item.parentSourceId)
if (!parentId) throw new Error(`Unmaterialized component parent ${item.parentSourceId}`)
@@ -362,8 +410,8 @@ function materializeReaderInto(
sources.set(item.sourceId, materialized.root.id)
}
/**
- * Instances a resumed load must sync with their components, which may have changed live since
- * the file loaded. Only this page's new instances: syncing a whole component would copy its
+ * Instances a load into an edited graph must sync with their components, which may have
+ * changed live since the file loaded. Only this page's new instances: syncing a whole component would copy its
* sizes over the sizes Figma derived for instances earlier pages already placed.
*/
const resync = new Set<string>()
@@ -373,15 +421,16 @@ function materializeReaderInto(
if (!parentId) throw new Error(`Missing source container ${occurrence.sourceId}`)
const ordered: string[] = []
for (const child of occurrence.children) {
- if (resumed) reconcileOccurrenceStructure(child, graph, components)
+ if (edited) reconcileOccurrenceStructure(child, graph, components)
if (child.mainComponentId !== null && !sources.has(child.sourceId)) {
+ onProgress?.()
const materialized = materializeInstance(graph, parentId, child, componentIds, {
blobs,
sourceChildren: mapInstanceSourceChildren(child, components)
})
rememberDerivedSizes(materialized.nodes)
linkInstanceSourceChildren(child, materialized, components)
- if (resumed) {
+ if (edited) {
reconcileLiveComponentEdits(graph, materialized)
if (materialized.root.componentId) resync.add(materialized.root.id)
}
diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.ts
index d5b80b342..9ebc82ef1 100644
--- a/packages/fig/src/instance-overrides/interpret.ts
+++ b/packages/fig/src/instance-overrides/interpret.ts
@@ -364,6 +364,7 @@ function interpretRoot(
rank: number
): InstanceOccurrence => {
if (expanding.has(id)) throw new Error(`Cyclic component expansion at ${id}`)
+ options.onProgress?.()
const raw = sources.get(id)
if (!raw) throw new Error(`Missing source node ${id}`)
const record = bindRecord(raw, bindings)
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index d6d6a551a..4d3fb6c24 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -56,6 +56,12 @@ function shareUnchanged(node: SceneNode, source: SceneNode): void {
if (holdsCollections(value) || !isEqual(value, original)) continue
Reflect.set(node, field, original)
}
+ // The layer's source metadata is its own, but the layout Figma saved for it is replaced whole,
+ // never written into, and nearly always the component layer's.
+ const layout = node.source.fig.layout
+ const originalLayout = source.source.fig.layout
+ if (layout && layout !== originalLayout && isEqual(layout, originalLayout))
+ node.source.fig.layout = originalLayout
}
export interface MaterializedInstance {
diff --git a/packages/fig/src/instance-overrides/occurrence/types.ts b/packages/fig/src/instance-overrides/occurrence/types.ts
index fee79140b..3584ff33f 100644
--- a/packages/fig/src/instance-overrides/occurrence/types.ts
+++ b/packages/fig/src/instance-overrides/occurrence/types.ts
@@ -79,4 +79,6 @@ export interface InterpretInstanceOptions {
onMissingComponent?: (diagnostic: MissingComponentDiagnostic) => void
/** Keep the component's own slot content where the assigned content frame is gone. */
onMissingSlotContent?: (diagnostic: MissingSlotContentDiagnostic) => void
+ /** Called as each layer expands, so a caller can tell a long read from a stuck one. */
+ onProgress?: () => void
}
diff --git a/packages/fig/tests/instance-overrides/progress.test.ts b/packages/fig/tests/instance-overrides/progress.test.ts
new file mode 100644
index 000000000..0b2203823
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/progress.test.ts
@@ -0,0 +1,29 @@
+import { expect, test } from 'bun:test'
+
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const component = { sessionID: 1, localID: 1 }
+const label = { sessionID: 1, localID: 2 }
+const icon = { sessionID: 1, localID: 3 }
+const placed = { sessionID: 2, localID: 1 }
+
+/**
+ * Reading a large design kit page and the components it places can outlast the population
+ * worker's stall window by itself, so the read reports progress as it goes, not only once done.
+ */
+test('interpreting an instance reports progress for every layer it expands', () => {
+ const changes = [
+ { guid: component, type: 'SYMBOL' },
+ { guid: label, type: 'TEXT', parentIndex: { guid: component, position: '!' } },
+ { guid: icon, type: 'VECTOR', parentIndex: { guid: component, position: '"' } },
+ { guid: placed, type: 'INSTANCE', symbolData: { symbolID: component } }
+ ] as NodeChange[]
+ let reports = 0
+ const occurrence = interpretInstance(changes, '2:1', { onProgress: () => reports++ })
+
+ expect(occurrence.children.map((child) => child.sourceId)).toEqual(['1:2', '1:3'])
+ // The instance, the component it expands, and the component's two layers.
+ expect(reports).toBe(4)
+})