AI-native design editor. Open-source Figma alternative.
perf(fig): save edited documents with many instances faster (#984)
Danila Poyarkov410292d6ff50
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 81ce7a52b..1aa23e082 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -234,6 +234,8 @@### Performance+- Save large `.fig` documents with less memory: once every page is loaded, the first save releases the decoded original file, and saves write from the document instead of a copy of it, about 1.5 GB less on a 74 MB design kit.+- Save edited `.fig` documents with many component instances faster: each overridden layer is addressed and its variables resolved once, overrides merge through an index instead of a scan per override, and the components Figma keeps off-canvas are read once instead of on every save. Saving a 74 MB design kit after an edit takes about 8 seconds instead of 13, and later saves about 7.- Open and draw large pages faster: guides no longer scan every layer of the page on each frame, a layout pass only writes the layers it moved and asks for one redraw, and opening a `.fig` keeps one copy of the file on the main thread instead of three.- Edit variables in large documents without stalls: renaming, reordering, or adding a variable, or changing its CSS name, unit, scopes, or conditions, no longer redraws the canvas, and changing a value or mode updates only the layers bound to those variables or to variables aliasing them instead of re-resolving and laying out every bound layer in the document.- Open the `/demo` document like any `.fig` file, built ahead of time, instead of generating it in the browser, which froze the page for several seconds.diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex b1ede95c4..1d092ce96 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -20,6 +20,7 @@ import {readBehaviour,renameBehaviourProperties,withBehaviour,+ type PluginDataEntry,type SceneGraph} from '@open-pencil/scene-graph'import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'@@ -33,12 +34,16 @@ import { findFigThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'import { renderThumbnail } from '#core/io/formats/raster'import {sceneNodeToKiwi,- buildFontDigestMap,+ settleFontDigestMap,makeDocumentNodeChange,makeCanvasNodeChange} from '#core/kiwi/fig/node-change/serialize'import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'-import { populateReaderExport } from '#core/kiwi/fig/session/document-state'+import {+ hasPendingReaderPages,+ populateFigInternalPages,+ populateReaderExport+} from '#core/kiwi/fig/session/document-state'import { originalFigArchive } from '#core/kiwi/fig/session/original-archive'import {@@ -175,19 +180,25 @@ function assignComponentPropertyGuids(}}-/** Behaviours bind component properties by id, so they follow the ids' new GUIDs. */-function renameBehaviourPropertyIds(graph: SceneGraph, propertyIdToGuid: Map<string, GUID>): void {+/**+ * Behaviours bind component properties by id, so they follow the ids' new GUIDs. The renamed+ * plugin data is written in place of the node's own; the document keeps its ids.+ */+function renamedBehaviourPluginData(+ graph: SceneGraph,+ propertyIdToGuid: Map<string, GUID>+): Map<string, PluginDataEntry[]> {const rename = (propertyId: string) => {const guid = propertyIdToGuid.get(propertyId)return guid ? `${guid.sessionID}:${guid.localID}` : propertyId}+ const renamed = new Map<string, PluginDataEntry[]>()for (const node of graph.getAllNodes()) {const behaviour = readBehaviour(node)if (behaviour)- graph.updateNode(node.id, {- pluginData: withBehaviour(node, renameBehaviourProperties(behaviour, rename))- })+ renamed.set(node.id, withBehaviour(node, renameBehaviourProperties(behaviour, rename)))}+ return renamed}function applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {@@ -309,6 +320,7 @@ interface InternalResourceContext {assignedGuidValues: Set<string>componentPropertyDefinitionsById: ReturnType<typeof buildComponentPropIndex>propertyIdToGuid: Map<string, GUID>+ pluginDataOverrides: ReadonlyMap<string, PluginDataEntry[]>runtime: FigNodeChangeExportRuntime}@@ -356,6 +368,7 @@ function appendInternalResources(context: InternalResourceContext): void {componentPropertyDefinitionsById: context.componentPropertyDefinitionsById,modeIdToGuid: context.modeIdToGuid,propertyIdToGuid: context.propertyIdToGuid,+ pluginDataOverrides: context.pluginDataOverrides,runtime: context.runtime})@@ -395,9 +408,18 @@ async function writeFigFile(pageId: string | undefined,renderHeadlessThumbnail: boolean): Promise<Uint8Array> {- const graph = cloneSceneGraphForFigExport(sourceGraph)- populateReaderExport(sourceGraph, graph)await initCodec()+ populateFigInternalPages(sourceGraph)+ // The export reads the document itself and writes nothing to it. Only pages still in the+ // archive need a copy, which they load into instead of the document.+ let graph = sourceGraph+ if (hasPendingReaderPages(sourceGraph)) {+ graph = cloneSceneGraphForFigExport(sourceGraph)+ populateReaderExport(sourceGraph, graph)+ }+ // The last await before the records: from here to the encoded message every record comes from+ // one synchronous pass over the document, and the digests cover every font that pass reads.+ const fontDigestMap = await settleFontDigestMap(graph)// When the document was imported from a .fig file, preserve the original// kiwi schema for both encoding and embedding. For the current version of@@ -436,7 +458,6 @@ async function writeFigFile(const varIdToGuid = new Map<string, GUID>()const modeIdToGuid = new Map<string, GUID>()const propertyIdToGuid = new Map<string, GUID>()- const fontDigestMap = await buildFontDigestMap(graph)const glyphBlobMap = new Map<string, number>()const blobIndexByHex = new Map<string, number>()const componentPropertyDefinitionsById = buildComponentPropIndex(graph)@@ -477,7 +498,7 @@ async function writeFigFile(assignedGuidValues,nodeSourceGuidValues)- renameBehaviourPropertyIds(graph, propertyIdToGuid)+ const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)assignOwnLayerGuids(graph, nodeSourceGuidValues, nodeIdToGuid, assignedGuidValues)for (const entry of canvasEntries) nodeChanges.push(entry.canvasNc)@@ -497,6 +518,7 @@ async function writeFigFile(assignedGuidValues,componentPropertyDefinitionsById,propertyIdToGuid,+ pluginDataOverrides,runtime})@@ -523,6 +545,7 @@ async function writeFigFile(modeIdToGuid,propertyIdToGuid,slotContentRecords,+ pluginDataOverrides,runtime}))diff --git a/packages/core/src/kiwi/fig/node-change/font/digests.ts b/packages/core/src/kiwi/fig/node-change/font/digests.tsindex f5b57daf1..9df878724 100644--- a/packages/core/src/kiwi/fig/node-change/font/digests.ts+++ b/packages/core/src/kiwi/fig/node-change/font/digests.ts@@ -23,7 +23,8 @@ async function getFontDigest(family: string, style: string): Promise<Uint8Arrayreturn digest}-export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string, Uint8Array>> {+/** Every `family|style` the document's text uses, read synchronously. */+function documentFontKeys(graph: SceneGraph): Set<string> {const fontKeys = new Set<string>()for (const node of graph.getAllNodes()) {if (node.type !== 'TEXT') continue@@ -36,12 +37,40 @@ export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string,fontKeys.add(`${family}|${weightToStyle(weight, italic)}`)}}+ return fontKeys+}+export async function buildFontDigestMap(graph: SceneGraph): Promise<Map<string, Uint8Array>> {const result = new Map<string, Uint8Array>()- for (const key of fontKeys) {+ await addFontDigests(result, documentFontKeys(graph))+ return result+}++async function addFontDigests(+ digests: Map<string, Uint8Array>,+ keys: Iterable<string>+): Promise<void> {+ for (const key of keys) {const [family, style] = key.split('|')const digest = await getFontDigest(family, style)- if (digest) result.set(key, digest)+ if (digest) digests.set(key, digest)+ }+}++/**+ * Digests for every font the document uses, read again after each wait: an edit made while+ * digests load can bring a new font in. Resolves only when a synchronous check finds none+ * missing, so a caller that continues without awaiting writes records that every digest covers.+ * Each round looks up only fonts it has not seen, and a font with no digest is looked up once, so+ * it ends once edits stop bringing in new fonts.+ */+export async function settleFontDigestMap(graph: SceneGraph): Promise<Map<string, Uint8Array>> {+ const digests = new Map<string, Uint8Array>()+ const looked = new Set<string>()+ for (;;) {+ const missing = [...documentFontKeys(graph)].filter((key) => !looked.has(key))+ if (missing.length === 0) return digests+ for (const key of missing) looked.add(key)+ await addFontDigests(digests, missing)}- return result}diff --git a/packages/core/src/kiwi/fig/node-change/serialize.ts b/packages/core/src/kiwi/fig/node-change/serialize.tsindex 00083428f..74a1451e9 100644--- a/packages/core/src/kiwi/fig/node-change/serialize.ts+++ b/packages/core/src/kiwi/fig/node-change/serialize.ts@@ -11,4 +11,4 @@ export {type KiwiNodeChange,type SceneNodeToKiwiOptions} from '@open-pencil/fig/node-change'-export { buildFontDigestMap } from './font/digests'+export { buildFontDigestMap, settleFontDigestMap } from './font/digests'diff --git a/packages/core/src/kiwi/fig/session/document-state.ts b/packages/core/src/kiwi/fig/session/document-state.tsindex efe4c40e3..3060db059 100644--- a/packages/core/src/kiwi/fig/session/document-state.ts+++ b/packages/core/src/kiwi/fig/session/document-state.ts@@ -8,11 +8,14 @@ import { readerSessionOptions, type FigReaderDiagnostic } from '#core/kiwi/fig/s* records that session skipped. Page population, diagnostics and recovery all read it.*/interface ReaderState {- bytes: ArrayBuffer+ /** The archive, until every page is in the graph and nothing is left to read from it. */+ bytes?: ArrayBuffercheckpoint?: FigSessionCheckpointsession?: ReturnType<typeof createFigDocumentSession>/** Records skipped by sessions this recovery state has opened. */diagnostics: FigReaderDiagnostic[]+ /** Every page is loaded and the reader released; only the diagnostics remain. */+ complete?: true}const states = new WeakMap<SceneGraph, ReaderState>()@@ -39,7 +42,7 @@ export function readerDiagnostics(graph: SceneGraph): readonly FigReaderDiagnostexport function isReaderPagePending(graph: SceneGraph, pageId: string): boolean {const state = states.get(graph)- if (!state) return false+ if (!state || state.complete) return falseconst checkpoint = state.session?.checkpoint() ?? state.checkpointconst sourceId = checkpoint?.sources.find(([, graphId]) => graphId === pageId)?.[0]if (!sourceId) return false@@ -65,11 +68,60 @@ export function populateAllFigPages(graph: SceneGraph): boolean {return changed}+/**+ * Drop the session, its checkpoint, and the archive once every page is in the graph, internal+ * ones included, which the first save loads. The session keeps every record of the file decoded,+ * which for a large design kit is gigabytes, and nothing reads it again: no page is pending, and+ * later saves write from the document.+ */+function releaseLoadedReader(state: ReaderState): void {+ const session = state.session+ if (!session?.pages.every((page) => session.loadedPageIds.has(page.id))) return+ state.session = undefined+ state.checkpoint = undefined+ state.bytes = undefined+ state.complete = true+}++/**+ * Load the pages the editor never shows, such as Figma's internal canvas, into the document's own+ * graph, so a save no longer opens a second session to read them into its copy. Their layers+ * never draw and loading them is not an edit. Only a live session loads them: while a population+ * worker still fills the graph, a second session must not, and the export reads them as before.+ */+export function populateFigInternalPages(graph: SceneGraph): boolean {+ const state = states.get(graph)+ const session = state?.session+ if (!state || !session) return false+ let changed = false+ for (const page of session.pages) {+ if (!page.internalOnly || session.loadedPageIds.has(page.id)) continue+ graph.applyImportedStateDuring(() => session.loadPage(page.id))+ changed = true+ }+ releaseLoadedReader(state)+ return changed+}++/**+ * Whether a save still has pages to read from the archive, which it reads into a copy of the+ * document: a population worker still fills the graph, or a page is not loaded yet.+ */+export function hasPendingReaderPages(graph: SceneGraph): boolean {+ const state = states.get(graph)+ if (!state || state.complete) return false+ const session = state.session+ return !session || !session.pages.every((page) => session.loadedPageIds.has(page.id))+}+export function populateReaderExport(source: SceneGraph, target: SceneGraph): boolean {const state = states.get(source)- if (!state) return false- const checkpoint = state.session?.checkpoint() ?? state.checkpoint- if (!checkpoint) throw new Error('Missing reader checkpoint')+ if (!state || state.complete) return false+ const live = state.session+ // Every page is already in the graph the target was copied from.+ if (live?.pages.every((page) => live.loadedPageIds.has(page.id))) return false+ const checkpoint = live?.checkpoint() ?? state.checkpoint+ if (!checkpoint || !state.bytes) throw new Error('Missing reader checkpoint')const session = createFigDocumentSession(state.bytes, readerSessionOptions(state.diagnostics), {graph: target,checkpoint@@ -92,8 +144,9 @@ export function releaseReaderRecovery(graph: SceneGraph): void {export function recoverReaderPage(graph: SceneGraph, pageId: string): boolean {const state = states.get(graph)if (!state) throw new Error('No reader recovery state')+ if (state.complete) return falseif (!state.session) {- if (!state.checkpoint) throw new Error('Missing reader checkpoint')+ if (!state.checkpoint || !state.bytes) throw new Error('Missing reader checkpoint')state.session = createFigDocumentSession(state.bytes, readerSessionOptions(state.diagnostics), {graph,checkpoint: state.checkpoint@@ -105,5 +158,6 @@ export function recoverReaderPage(graph: SceneGraph, pageId: string): boolean {const populated = !session.loadedPageIds.has(page.id)// The layers come from the opened file, as they do through the population worker's delta.graph.applyImportedStateDuring(() => session.loadPage(page.id))+ releaseLoadedReader(state)return populated}diff --git a/packages/core/src/kiwi/fig/session/options.ts b/packages/core/src/kiwi/fig/session/options.tsindex a40bda688..2355c42fe 100644--- a/packages/core/src/kiwi/fig/session/options.ts+++ b/packages/core/src/kiwi/fig/session/options.ts@@ -10,6 +10,25 @@ export type FigReaderDiagnostic =| { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }| { kind: 'slot-content'; diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0] }+/** Each sink's entries, so a record reported again is not listed twice. */+const reported = new WeakMap<FigReaderDiagnostic[], Set<string>>()++/**+ * Opening a file, recovering a page, and every save read records through sessions that share+ * one sink, so the same skipped record can reach it more than once.+ */+function report(sink: FigReaderDiagnostic[], entry: FigReaderDiagnostic): void {+ let keys = reported.get(sink)+ if (!keys) {+ keys = new Set(sink.map((existing) => JSON.stringify(existing)))+ reported.set(sink, keys)+ }+ const key = JSON.stringify(entry)+ if (keys.has(key)) return+ keys.add(key)+ sink.push(entry)+}+/*** Figma retains override and binding records that address nodes it later deleted, and* instances of deleted components, and the reader has no replacement to guess at. Opening@@ -21,10 +40,10 @@ export type FigReaderDiagnostic =export function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemblyOptions {return {derivedBounds: true,- onUnresolvedProperty: (diagnostic) => sink.push({ kind: 'property', diagnostic }),- onUnresolvedAssignment: (diagnostic) => sink.push({ kind: 'assignment', diagnostic }),- onUnresolvedBinding: (diagnostic) => sink.push({ kind: 'binding', diagnostic }),- onMissingComponent: (diagnostic) => sink.push({ kind: 'component', diagnostic }),- onMissingSlotContent: (diagnostic) => sink.push({ kind: 'slot-content', diagnostic })+ onUnresolvedProperty: (diagnostic) => report(sink, { kind: 'property', diagnostic }),+ onUnresolvedAssignment: (diagnostic) => report(sink, { kind: 'assignment', diagnostic }),+ onUnresolvedBinding: (diagnostic) => report(sink, { kind: 'binding', diagnostic }),+ onMissingComponent: (diagnostic) => report(sink, { kind: 'component', diagnostic }),+ onMissingSlotContent: (diagnostic) => report(sink, { kind: 'slot-content', diagnostic })}}diff --git a/packages/core/tests/helpers/fig/save-contract.ts b/packages/core/tests/helpers/fig/save-contract.tsnew file mode 100644index 000000000..0e5812a00--- /dev/null+++ b/packages/core/tests/helpers/fig/save-contract.ts@@ -0,0 +1,47 @@+import { expect } from 'bun:test'++import { omit } from 'es-toolkit/object'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++function pageOf(graph: SceneGraph, node: SceneNode): string | undefined {+ let current: SceneNode | undefined = node+ while (current?.parentId && current.parentId !== graph.rootId)+ current = graph.getNode(current.parentId)+ return current?.id+}++/** The document's layers before a save, to compare with what it holds after. */+export function snapshotNodes(graph: SceneGraph): Map<string, SceneNode> {+ return new Map(structuredClone([...graph.nodes]))+}++/**+ * A save may read internal-only pages into the document, so later saves need not read them+ * again, but it never loads a visible page or changes anything the document already held. On an+ * internal page, a component set the visible pages needed in part gains its other variants.+ */+export function expectSaveLoadedOnlyInternalPages(+ graph: SceneGraph,+ before: ReadonlyMap<string, SceneNode>+): void {+ const internalPages = new Set(+ graph+ .getPages(true)+ .filter((page) => page.internalOnly)+ .map((page) => page.id)+ )+ for (const [id, node] of before) {+ const now = graph.getNode(id)+ if (!internalPages.has(id) && !internalPages.has(pageOf(graph, node) ?? '')) {+ expect(now).toEqual(node)+ continue+ }+ expect(now && omit(now, ['childIds'])).toEqual(omit(node, ['childIds']))+ // The children it held keep their order; loaded variants may sit between them.+ const kept = new Set(node.childIds)+ expect(now?.childIds.filter((id) => kept.has(id))).toEqual(node.childIds)+ }+ const added = [...graph.getAllNodes()].filter((node) => !before.has(node.id))+ expect(added.filter((node) => !internalPages.has(pageOf(graph, node) ?? ''))).toEqual([])+}diff --git a/packages/core/tests/io/formats/fig/export/live-document.test.ts b/packages/core/tests/io/formats/fig/export/live-document.test.tsnew file mode 100644index 000000000..e6691bf38--- /dev/null+++ b/packages/core/tests/io/formats/fig/export/live-document.test.ts@@ -0,0 +1,72 @@+import { expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { createEditor } from '@open-pencil/core/editor'+import { emptyBehaviour, readBehaviour, SceneGraph } from '@open-pencil/scene-graph'++import { settleFontDigestMap } from '#core/kiwi/fig/node-change/font/digests'+import { fontManager } from '#core/text/fonts'++// A save reads the document after its last wait, so the font digests it waits for must cover+// a font an edit brought in while they loaded.+test('font digests cover a font added while they load', async () => {+ const inter = expectDefined(+ await fontManager.fetchBundledFont('/Inter-Regular.ttf'),+ 'bundled Inter font'+ )+ fontManager.markLoaded('Inter', 'Regular', inter)+ fontManager.markLoaded('Inter', 'Bold', inter)+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ graph.createNode('TEXT', pageId, { text: 'Body', fontFamily: 'Inter', fontWeight: 400 })++ const settling = settleFontDigestMap(graph)+ graph.createNode('TEXT', pageId, { text: 'Heading', fontFamily: 'Inter', fontWeight: 700 })++ expect([...(await settling).keys()].toSorted()).toEqual(['Inter|Bold', 'Inter|Regular'])+})++// With nothing left to read from an archive, a save writes from the document itself, so+// nothing it writes onto a record may reach the layers it was written from.+test('saving a document leaves every layer as it was', async () => {+ await initCodec()+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const set = editor.graph.createNode('COMPONENT_SET', pageId, {+ name: 'Toggle',+ componentPropertyDefinitions: [+ { id: 'on', name: 'On', type: 'VARIANT', defaultValue: 'No', variantOptions: ['No', 'Yes'] }+ ]+ })+ for (const on of ['No', 'Yes'])+ editor.graph.createNode('COMPONENT', set.id, {+ name: `On=${on}`,+ componentPropertyValues: { On: on }+ })+ editor.setBehaviour(set.id, {+ ...emptyBehaviour('switch'),+ booleans: { checked: { propertyId: 'on', on: 'Yes', off: 'No' } }+ })+ editor.graph.createNode('RECTANGLE', pageId, {+ name: 'Exported',+ exportSettings: [{ format: 'png', scale: 2 }]+ })+ editor.graph.createNode('TEXT', pageId, {+ name: 'On a path',+ text: 'Curved',+ textPathBox: { x: 0, y: 0, width: 40, height: 20 }+ })+ const before = structuredClone([...editor.graph.nodes])++ const bytes = await exportFigFile(editor.graph)++ expect([...editor.graph.nodes]).toEqual(before)+ // The record still carries what the export added: the behaviour follows its property's GUID.+ const reopened = await parseFigFile(bytes.slice().buffer)+ const owner = [...reopened.nodes.values()].find((node) => node.name === 'Toggle')+ const property = owner?.componentPropertyDefinitions[0]?.id+ expect(property).not.toBe('on')+ expect(owner && readBehaviour(owner)?.booleans.checked?.propertyId).toBe(property)+})diff --git a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.tsindex c916bd586..2b9f9a17c 100644--- a/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/exhaustive.test.ts@@ -1,5 +1,9 @@import { beforeAll, afterAll, describe, expect, test, spyOn, setDefaultTimeout } from 'bun:test'+import {+ expectSaveLoadedOnlyInternalPages,+ snapshotNodes+} from '#core-tests/helpers/fig/save-contract'import { unzipSync } from 'fflate'import {@@ -536,16 +540,16 @@ function verifyFixture(spec: FixtureSpec): void {expect(g2Export).toEqual(g1Export)})- test('edited export re-encodes the document without mutating unloaded source pages', async () => {+ test('edited export re-encodes the document without loading unloaded visible pages', async () => {await g0Readyconst edited = await parseFigFile(g0Bytes.slice(0), { populate: 'first-page' })const page = edited.getPages()[0]const name = `${page.name} (edited)`edited.updateNode(page.id, { name })- const before = structuredClone([...edited.nodes])+ const before = snapshotNodes(edited)const bytes = await exportFigFile(edited)expect(bytes).not.toEqual(new Uint8Array(g0Bytes))- expect([...edited.nodes]).toEqual(before)+ expectSaveLoadedOnlyInternalPages(edited, before)const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)expect(reopened.getPages()[0].name).toBe(name)expect(reopened.figSchemaDeflated).toEqual(edited.figSchemaDeflated)diff --git a/packages/core/tests/io/formats/fig/session/main-thread.test.ts b/packages/core/tests/io/formats/fig/session/main-thread.test.tsindex db1a16a2e..2abe81f49 100644--- a/packages/core/tests/io/formats/fig/session/main-thread.test.ts+++ b/packages/core/tests/io/formats/fig/session/main-thread.test.ts@@ -1,5 +1,10 @@import { expect, test } from 'bun:test'+import {+ expectSaveLoadedOnlyInternalPages,+ snapshotNodes+} from '#core-tests/helpers/fig/save-contract'+import { exportFigFile } from '@open-pencil/core/io'import {parseFigFile,@@ -70,15 +75,23 @@ for (const populate of ['all', 'first-page', 'none'] as const) {})}-test('edited export loads missing pages on an isolated graph', async () => {+test('edited export loads missing visible pages on an isolated graph', async () => {const graph = await parseFigFile(await fixture(), { populate: 'first-page' })const pages = graph.getPages()const first = graph.getChildren(pages[0].id)[0]graph.updateNode(first.id, { text: 'Edited' })- const before = structuredClone([...graph.nodes])+ const before = snapshotNodes(graph)const bytes = await exportFigFile(graph)- expect([...graph.nodes]).toEqual(before)+ expectSaveLoadedOnlyInternalPages(graph, before)expect(graph.getChildren(pages[1].id)).toHaveLength(0)+ const internalPage = graph.getPages(true).find((page) => page.internalOnly)+ expect(graph.getChildren(internalPage?.id ?? '').map((node) => node.name)).toEqual([+ 'Retained internal content'+ ])+ // A second save finds the internal page already loaded and leaves the document as it was.+ const loaded = snapshotNodes(graph)+ await exportFigFile(graph)+ expect(new Map(graph.nodes)).toEqual(loaded)const reopened = await parseFigFile(bytes.slice().buffer as ArrayBuffer)const reopenedPages = reopened.getPages()expect(reopened.getChildren(reopenedPages[0].id)[0].text).toBe('Edited')@@ -94,15 +107,43 @@ test('edited export loads missing pages on an isolated graph', async () => {releaseFigPopulationWorker(reopened)})+test('after the first save, later saves keep internal content without the reader', async () => {+ const graph = await parseFigFile(await fixture(), { populate: 'first-page' })+ populateAllFigPages(graph)+ // The first save of an edit reads the internal page into the document; every page is loaded+ // after it. An unedited document is saved as the original file and reads nothing.+ graph.updateNode(graph.getPages()[0].id, { name: 'Edited page' })+ await exportFigFile(graph)+ const internal = graph.getPages(true).find((page) => page.internalOnly)+ expect(graph.getChildren(internal?.id ?? '').map((node) => node.name)).toEqual([+ 'Retained internal content'+ ])+ const second = graph.getPages()[1]+ graph.updateNode(graph.getChildren(second.id)[0].id, { text: 'Edited after loading' })++ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer as ArrayBuffer)++ const pages = reopened.getPages()+ expect(reopened.getChildren(pages[1].id)[0].text).toBe('Edited after loading')+ const reopenedInternal = reopened.getPages(true).find((page) => page.internalOnly)+ if (!reopenedInternal) throw new Error('Missing internal page')+ populateFigPage(reopened, reopenedInternal.id)+ expect(reopened.getChildren(reopenedInternal.id).map((node) => node.name)).toEqual([+ 'Retained internal content'+ ])+ releaseFigPopulationWorker(graph)+ releaseFigPopulationWorker(reopened)+})+// Figma keeps property defaults that name a deleted component; so does an edited export.-test('export tolerates a deleted internal default without changing the live graph', async () => {+test('export tolerates a deleted internal default without changing what the document held', async () => {const graph = await parseFigFile(await fixture(true), { populate: 'first-page' })const page = graph.getPages()[0]graph.updateNode(page.id, { name: 'Edited' })- const before = structuredClone([...graph.nodes])+ const before = snapshotNodes(graph)const bytes = await exportFigFile(graph)expect(bytes.byteLength).toBeGreaterThan(0)- expect([...graph.nodes]).toEqual(before)+ expectSaveLoadedOnlyInternalPages(graph, before)releaseFigPopulationWorker(graph)})diff --git a/packages/fig/docs/document-sessions.md b/packages/fig/docs/document-sessions.mdindex e3eff0b2b..aad1d0633 100644--- a/packages/fig/docs/document-sessions.md+++ b/packages/fig/docs/document-sessions.md@@ -65,6 +65,13 @@ Only an accepted delta advances the receiver's checkpoint. Original archive byteavailable for recovery and are released with session ownership. Recovery never replaces theedited graph.+An edited export writes every page. With a live session, it first reads internal-only pages into+the edited graph: their layers never draw and loading is not an edit. Once every page is loaded,+the session and the archive are released, and saves write from the document graph without a+copy. Visible pages that are still unloaded are read only into a copy of the graph made for that+save; a save never loads one into the document. While a population worker still fills the graph+there is no live session, and internal pages are read into the copy too.+Checkpoints contain source-to-node mappings, loaded pages, saved-size tracking, and componenttopology addressed by complete source-identity paths. Occurrence property payloads arereconstructed from source records when recovery is needed. Restore validates paths, componentdiff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.tsindex 51db46957..b7c06924f 100644--- a/packages/fig/src/node-change/export/context.ts+++ b/packages/fig/src/node-change/export/context.ts@@ -2,7 +2,12 @@ import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'import { stringToGuid } from '@open-pencil/kiwi/fig/guid'-import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import type {+ ComponentPropertyDefinition,+ PluginDataEntry,+ SceneGraph,+ SceneNode+} from '@open-pencil/scene-graph'import type { Color, GUID, Matrix } from '@open-pencil/scene-graph/primitives'export type KiwiNodeChange = NodeChange & Record<string, unknown>@@ -62,6 +67,10 @@ export interface SceneNodeToKiwiContext {* so the caller re-parents the `isSlotContent` roots there after serializing its nodes.*/slotContentRecords?: KiwiNodeChange[]+ /** Plugin data a node is written with instead of its own, by node ID. */+ pluginDataOverrides?: ReadonlyMap<string, PluginDataEntry[]>+ /** Nodes with their bindings resolved, kept for the length of one export. */+ resolvedNodes?: WeakMap<SceneNode, SceneNode>fractionalPosition: (index: number) => stringmapToFigmaType: (type: SceneNode['type']) => stringfillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paintdiff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex 7b4d88c40..663d40d21 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -43,7 +43,7 @@ import {type SceneNodeToKiwiContext} from './context'import { mergeOverrides, serializeRuntimePropertyOverrides } from './override-claims'-import { nodeWithResolvedBindings } from './resolved-bindings'+import { exportedNode } from './resolved-bindings'import { slotContentAssignment, slotDefinitionFields } from './slots'export type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'@@ -887,6 +887,19 @@ function exportKiwiNodeType(node: SceneNode, context: SceneNodeToKiwiContext): sreturn isPathText ? 'TEXT_PATH' : context.mapToFigmaType(node.type)}+/**+ * The node a record is written from. Serializing writes plugin data onto the node it is given,+ * and the export reads the live document, so each record gets a copy that lives only while it is+ * written, carrying any plugin data the export renamed.+ */+function nodeToSerialize(context: SceneNodeToKiwiContext, source: SceneNode): SceneNode {+ const resolved = exportedNode(context, source)+ return {+ ...resolved,+ pluginData: context.pluginDataOverrides?.get(source.id) ?? resolved.pluginData+ }+}+export function sceneNodeToKiwiWithContext(source: SceneNode,parentGuid: GUID,@@ -894,7 +907,7 @@ export function sceneNodeToKiwiWithContext(localIdCounter: { value: number },context: SceneNodeToKiwiContext): KiwiNodeChange[] {- const node = nodeWithResolvedBindings(context.graph, source)+ const node = nodeToSerialize(context, source)const guid = getOrCreateNodeGuid(context, node.id, localIdCounter) ?? {sessionID: 1,localID: localIdCounter.value++diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.tsindex aad6d4f85..92148ce92 100644--- a/packages/fig/src/node-change/export/override-claims.ts+++ b/packages/fig/src/node-change/export/override-claims.ts@@ -23,7 +23,7 @@ import {type StyleReference} from './context'import { fillsOwnSizingAxis } from './fill-sizing'-import { nodeWithResolvedBindings } from './resolved-bindings'+import { exportedNode } from './resolved-bindings'function exportedTextStyleReference(context: SceneNodeToKiwiContext, id: string): StyleReference {context.styleReferences ??= buildStyleReferences(context.graph)@@ -162,7 +162,7 @@ function overrideClaim(): KiwiSymbolOverridePayload | undefined {const input = {...claimed,- target: nodeWithResolvedBindings(claimed.context.graph, claimed.target)+ target: exportedNode(claimed.context, claimed.target)}if (field === 'componentId')return exportedSwapOverride(input.context, input.target, path, counter)@@ -180,14 +180,21 @@ export function serializeRuntimePropertyOverrides(): KiwiSymbolOverridePayload[] {const result: KiwiSymbolOverridePayload[] = []const resolveGuid = instanceGuidResolver(context, localIdCounter)- const resolveTarget = (owner: SceneNode, nodeId: string) => {- const targetId = nodeId || owner.id+ // A layer with several overridden fields is addressed once; the resolver keeps the GUIDs it makes.+ const targets = new Map<string, { target: SceneNode; path: GUID[] } | undefined>()+ const findTarget = (targetId: string) => {const target = context.graph.getNode(targetId)if (!target || (target.id !== instance.id && !isDescendantOf(context, targetId, instance.id)))return undefinedconst path = instanceExportAddress(context.graph, instance, target, resolveGuid)return path ? { target, path } : undefined}+ const resolveTarget = (owner: SceneNode, nodeId: string) => {+ const targetId = nodeId || owner.id+ if (!targets.has(targetId)) targets.set(targetId, findTarget(targetId))+ const found = targets.get(targetId)+ return found && { target: found.target, path: [...found.path] }+ }const visit = (node: SceneNode): void => {if (node.type === 'INSTANCE')forEachInstanceOverride(node.instanceOverrides, (nodeId, field, value) => {@@ -220,18 +227,19 @@ export function mergeOverrides(symbolOverrides: KiwiSymbolOverridePayload[],newOverrides: KiwiSymbolOverridePayload[]): void {+ // The last override at each path, indexed once: instances can carry thousands of overrides.+ const lastAt = new Map<string, number>()+ symbolOverrides.forEach((existing, index) => {+ const key = overridePathKey(existing)+ if (key) lastAt.set(key, index)+ })for (const override of newOverrides) {const pathKey = overridePathKey(override)- let existingIndex = -1- if (pathKey) {- for (let index = symbolOverrides.length - 1; index >= 0; index--) {- if (overridePathKey(symbolOverrides[index]) !== pathKey) continue- existingIndex = index- break- }- }- if (existingIndex < 0) symbolOverrides.push(override)- else+ const existingIndex = pathKey ? (lastAt.get(pathKey) ?? -1) : -1+ if (existingIndex < 0) {+ if (pathKey) lastAt.set(pathKey, symbolOverrides.length)+ symbolOverrides.push(override)+ } elsesymbolOverrides[existingIndex] = {...symbolOverrides[existingIndex],...override,diff --git a/packages/fig/src/node-change/export/resolved-bindings.ts b/packages/fig/src/node-change/export/resolved-bindings.tsindex 2b78d8ab2..2dbbc8e92 100644--- a/packages/fig/src/node-change/export/resolved-bindings.ts+++ b/packages/fig/src/node-change/export/resolved-bindings.ts@@ -21,3 +21,20 @@ export function nodeWithResolvedBindings(graph: SceneGraph, node: SceneNode): Sc}return Object.keys(changes).length > 0 ? { ...node, ...changes } : node}++/**+ * `nodeWithResolvedBindings` once per node for one export. Bindings do not change while a document+ * is written, and an instance's overrides claim the same layers once per overridden field.+ */+export function exportedNode(+ context: { graph: SceneGraph; resolvedNodes?: WeakMap<SceneNode, SceneNode> },+ node: SceneNode+): SceneNode {+ context.resolvedNodes ??= new WeakMap()+ let resolved = context.resolvedNodes.get(node)+ if (!resolved) {+ resolved = nodeWithResolvedBindings(context.graph, node)+ context.resolvedNodes.set(node, resolved)+ }+ return resolved+}diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex 066bdc7c6..632669a0a 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -32,7 +32,12 @@ export {} from '@open-pencil/kiwi/fig/container'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'-import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import type {+ ComponentPropertyDefinition,+ PluginDataEntry,+ SceneGraph,+ SceneNode+} from '@open-pencil/scene-graph'import type { GUID, JSONObject } from '@open-pencil/scene-graph/primitives'import {@@ -442,6 +447,8 @@ export interface SceneNodeToKiwiOptions {modeIdToGuid?: Map<string, GUID>propertyIdToGuid?: Map<string, GUID>slotContentRecords?: KiwiNodeChange[]+ /** Plugin data a node is written with instead of its own, by node ID. */+ pluginDataOverrides?: ReadonlyMap<string, PluginDataEntry[]>}export function sceneNodeToKiwi(@@ -464,7 +471,8 @@ export function sceneNodeToKiwi(componentPropertyDefinitionsById = buildComponentPropIndex(graph),modeIdToGuid,propertyIdToGuid = new Map<string, GUID>(),- slotContentRecords+ slotContentRecords,+ pluginDataOverrides} = options// Raw paints retain library asset refs; effects use this map because their// Kiwi schema accepts only GUID-backed aliases.@@ -483,6 +491,7 @@ export function sceneNodeToKiwi(componentPropertyDefinitionsById,propertyIdToGuid,slotContentRecords,+ pluginDataOverrides,fractionalPosition,mapToFigmaType,fillToKiwiPaint,diff --git a/packages/fig/tests/node-change/export/override-claims.test.ts b/packages/fig/tests/node-change/export/override-claims.test.tsnew file mode 100644index 000000000..422197aaf--- /dev/null+++ b/packages/fig/tests/node-change/export/override-claims.test.ts@@ -0,0 +1,42 @@+import { describe, expect, test } from 'bun:test'++import type { KiwiSymbolOverridePayload } from '#fig/node-change/export/context'+import { mergeOverrides } from '#fig/node-change/export/override-claims'++const at = (...ids: number[]) => ({ guids: ids.map((localID) => ({ sessionID: 1, localID })) })++describe('merging symbol overrides', () => {+ test('an override at a path already claimed merges into the last claim at that path', () => {+ const overrides: KiwiSymbolOverridePayload[] = [+ { guidPath: at(1), name: 'first' },+ { guidPath: at(2), visible: false },+ { guidPath: at(1), opacity: 0.5 }+ ]++ mergeOverrides(overrides, [{ guidPath: at(1), name: 'renamed' }])++ expect(overrides).toEqual([+ { guidPath: at(1), name: 'first' },+ { guidPath: at(2), visible: false },+ { guidPath: at(1), opacity: 0.5, name: 'renamed' }+ ])+ })++ test('new paths are added, and two new overrides at one path become one', () => {+ const overrides: KiwiSymbolOverridePayload[] = [{ guidPath: at(1), name: 'kept' }]++ mergeOverrides(overrides, [+ { guidPath: at(3, 4), visible: false },+ { guidPath: at(3, 4), opacity: 0.25 },+ { name: 'no path' },+ { name: 'no path either' }+ ])++ expect(overrides).toEqual([+ { guidPath: at(1), name: 'kept' },+ { guidPath: at(3, 4), visible: false, opacity: 0.25 },+ { name: 'no path' },+ { name: 'no path either' }+ ])+ })+})