AI-native design editor. Open-source Figma alternative.
fix(fig): load nested component definitions whole, in any page order (#1598)
Kenecf46cbbfc06
diff --git a/changes/1598/fixed.md b/changes/1598/fixed.mdnew file mode 100755index 000000000..e0f6648e3--- /dev/null+++ b/changes/1598/fixed.md@@ -0,0 +1,2 @@+- Opening a `.fig` whose component contains another component with an instance inside no longer fails with a missing component error.+- A component that encloses another keeps all its layers when a page using the inner component loads first, instead of losing its instances or failing to load the enclosing component's page.diff --git a/packages/fig/src/document/components.ts b/packages/fig/src/document/components.tsindex bcaeb7b91..c5c06fd75 100644--- a/packages/fig/src/document/components.ts+++ b/packages/fig/src/document/components.ts@@ -18,7 +18,12 @@ export function planComponentConstruction(readComponent: (id: string) => InstanceOccurrence,index: ReadonlyMap<string, NodeChange>,/** Components an earlier pass already built, which are neither read nor planned again. */- isBuilt: (id: string) => boolean = () => false+ isBuilt: (id: string) => boolean = () => false,+ /**+ * Components the roots hold whole. A page read for other content keeps a definition that only+ * encloses that content, without its other layers; it is built once its own page is read.+ */+ isWhole: (id: string) => boolean = () => true): ComponentConstruction[] {const sources = indexconst pageComponents = new Map<string, InstanceOccurrence>()@@ -47,7 +52,7 @@ export function planComponentConstruction(const visit = (root: InstanceOccurrence): void => {for (const node of occurrences(root)) {if (node.mainComponentId !== null) ensure(node.mainComponentId)- if (node.properties.type === 'SYMBOL') ensure(node.sourceId)+ if (node.properties.type === 'SYMBOL' && isWhole(node.sourceId)) ensure(node.sourceId)}}const ensure = (id: string): void => {diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex ab14e427e..8b84cc659 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -16,6 +16,7 @@ import type {import {reconcileOccurrenceStructure,linkInstanceSourceChildren,+ mapMaterializedComponentNodes,mapInstanceSourceChildren,type MaterializedComponentOccurrence} from '../instance-overrides/source-children'@@ -446,20 +447,34 @@ function materializeReaderInto(const parentId = sources.get(item.parentSourceId)if (!parentId) throw new Error(`Unmaterialized component parent ${item.parentSourceId}`)const existingNodes = new Map<InstanceOccurrence, SceneNode>()+ /** Definitions an earlier step built inside this one: they keep the layers they have. */+ const nested: Array<[InstanceOccurrence, MaterializedComponentOccurrence]> = []const collectExisting = (node: InstanceOccurrence): void => {const id = sources.get(node.sourceId)const existing = id ? graph.getNode(id) : undefinedif (existing) existingNodes.set(node, existing)- if (node.mainComponentId === null) node.children.forEach(collectExisting)+ // A definition deleted since it was built is built again, like any missing layer.+ const component =+ existing && node.properties.type === 'SYMBOL' ? components.get(node.sourceId) : undefined+ if (component) nested.push([node, component])+ else if (node.mainComponentId === null) node.children.forEach(collectExisting)}collectExisting(item.occurrence)- const materialized = materializeInstance(graph, parentId, item.occurrence, componentIds, {+ const built = materializeInstance(graph, parentId, item.occurrence, componentIds, {blobs,sourceChildren: mapInstanceSourceChildren(item.occurrence, components),existingNodes,recordId})- rememberDerivedSizes(materialized.nodes)+ rememberDerivedSizes(built.nodes)+ // Linking and checkpoints address a nested definition's layers through this tree too.+ const nodes = new Map(built.nodes)+ for (const [node, component] of nested) {+ for (const [occurrence, layer] of mapMaterializedComponentNodes(node, component)) {+ nodes.set(occurrence, layer)+ }+ }+ const materialized = { root: built.root, nodes }linkInstanceSourceChildren(item.occurrence, materialized, components)components.set(item.sourceId, { occurrence: item.occurrence, materialized })componentIds.set(item.sourceId, materialized.root.id)diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.tsindex bf364af32..fa8d2c74c 100644--- a/packages/fig/src/document/read.ts+++ b/packages/fig/src/document/read.ts@@ -323,7 +323,8 @@ function createScopedReader(roots,(id) => sourceInterpreter.component(id, options),index.sources,- isBuilt+ isBuilt,+ (id) => closure.contentIds.has(id))},readComponent: sourceInterpreter.componentdiff --git a/packages/fig/src/instance-overrides/source-children.ts b/packages/fig/src/instance-overrides/source-children.tsindex ea31a6690..f9be581b2 100644--- a/packages/fig/src/instance-overrides/source-children.ts+++ b/packages/fig/src/instance-overrides/source-children.ts@@ -65,6 +65,27 @@ function* pairSourceChildren(}}+/**+ * A built definition's layers under the occurrences of an enclosing tree, which may have read the+ * definition separately on another page. Layers deleted since a resumed checkpoint are left out,+ * as the checkpoint leaves them out.+ */+export function mapMaterializedComponentNodes(+ target: InstanceOccurrence,+ component: MaterializedComponentOccurrence+): ReadonlyMap<InstanceOccurrence, SceneNode> {+ const nodes = new Map<InstanceOccurrence, SceneNode>()+ const visit = (current: InstanceOccurrence, source: InstanceOccurrence): void => {+ const node = component.materialized.nodes.get(source)+ if (!node) return+ nodes.set(current, node)+ for (const [child, counterpart] of pairSourceChildren(current, source))+ visit(child, counterpart)+ }+ visit(target, component.occurrence)+ return nodes+}+/*** Each instance owner addresses descendants in its own component expansion. A nested* instance therefore has both its own correspondence and the outer owner's; a swap endsdiff --git a/packages/fig/tests/document/checkpoint.test.ts b/packages/fig/tests/document/checkpoint.test.tsindex 72fe5733b..67682583e 100644--- a/packages/fig/tests/document/checkpoint.test.ts+++ b/packages/fig/tests/document/checkpoint.test.ts@@ -1,23 +1,16 @@import { expect, test } from 'bun:test'+import { figArchiveOf } from '#fig-tests/helpers/fig-fixtures'import { guid } from '#fig-tests/helpers/guid'import { checkpointComponent, restoreComponentCheckpoint } from '#fig/document/component/checkpoint'import { interpretComponent } from '#fig/instance-overrides/interpret'import { materializeInstance } from '#fig/instance-overrides/materialize-instance'-import { deflateSync } from 'fflate'-import { createFigDocumentSession, writeFigArchive } from '@open-pencil/fig'-import {- createNodeChangesMessage,- encodeMessage,- getSchemaBytes,- initCodec,- type NodeChange-} from '@open-pencil/kiwi/fig/codec'+import { createFigDocumentSession } from '@open-pencil/fig'+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { SceneGraph } from '@open-pencil/scene-graph'test('checkpoint recovery keeps the effective fill of a swapped instance on a lazy page', async () => {- await initCodec()const paint = (r: number): NonNullable<NodeChange['fillPaints']> => [{ type: 'SOLID', color: { r, g: 1 - r, b: 0, a: 1 }, visible: true, opacity: 1 }]@@ -60,13 +53,7 @@ test('checkpoint recovery keeps the effective fill of a swapped instance on a lacomponentPropAssignments: [{ defID: guid(90), value: { guidValue: guid(3) } }]}]- const archive = writeFigArchive({- schemaDeflated: deflateSync(getSchemaBytes()),- kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),- thumbnailPNG: new Uint8Array(),- metaJSON: '{}'- })- const bytes = new Uint8Array(archive).buffer+ const bytes = await figArchiveOf(records)const initial = createFigDocumentSession(bytes)const recovered = createFigDocumentSession(bytes,diff --git a/packages/fig/tests/document/nested-components.test.ts b/packages/fig/tests/document/nested-components.test.tsindex be1806d6f..7a9a5e307 100644--- a/packages/fig/tests/document/nested-components.test.ts+++ b/packages/fig/tests/document/nested-components.test.ts@@ -1,7 +1,9 @@import { expect, test } from 'bun:test'+import { figArchiveOf } from '#fig-tests/helpers/fig-fixtures'import { guid } from '#fig-tests/helpers/guid'-import { materializeDocument } from '#fig/document/materialize'+import { checkpointComponent } from '#fig/document/component/checkpoint'+import { createFigDocumentSession, materializeDocument } from '#fig/document/materialize'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'@@ -33,3 +35,123 @@ test('constructs nested definitions once under their actual component parent', (expect(graph.getNode(instance)?.componentId).toBe(inner)expect([...graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')).toHaveLength(2)})++function nestedComponentRecords(): NodeChange[] {+ return [+ { guid: guid(1), type: 'DOCUMENT' },+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },+ { guid: guid(3), type: 'SYMBOL', parentIndex: { guid: guid(2), position: 'a' } },+ { guid: guid(4), type: 'SYMBOL', parentIndex: { guid: guid(3), position: 'a' } },+ {+ guid: guid(5),+ type: 'INSTANCE',+ parentIndex: { guid: guid(4), position: 'a' },+ symbolData: { symbolID: guid(6) }+ },+ { guid: guid(6), type: 'SYMBOL', parentIndex: { guid: guid(2), position: 'b' } },+ {+ guid: guid(7),+ type: 'TEXT',+ parentIndex: { guid: guid(6), position: 'a' },+ textData: { characters: 'Nested instance' }+ }+ ]+}++test('keeps nested component instance descendants available to linking and checkpoints', () => {+ const { graph, components } = materializeDocument(nestedComponentRecords())+ const outer = components.get('1:3')+ const inner = components.get('1:4')+ const source = components.get('1:6')+ if (!outer || !inner || !source) throw new Error('Missing components')+ const instance = graph.getChildren(inner.materialized.root.id)[0]+ const label = graph.getChildren(instance.id)[0]+ expect(instance.type).toBe('INSTANCE')+ expect(instance.componentId).toBe(source.materialized.root.id)+ expect(label.text).toBe('Nested instance')+ expect(graph.getChildren(outer.materialized.root.id)).toEqual([inner.materialized.root])+ expect([...graph.getAllNodes()].filter((node) => node.type === 'INSTANCE')).toEqual([instance])+ expect(checkpointComponent(outer).nodes.map((node) => node.nodeId)).toEqual([+ outer.materialized.root.id,+ inner.materialized.root.id,+ instance.id,+ label.id+ ])+ const sourceLabel = graph.getChildren(source.materialized.root.id)[0]+ graph.updateNode(sourceLabel.id, { text: 'Updated' })+ graph.syncInstances(source.materialized.root.id)+ expect(graph.getChildren(instance.id)).toEqual([label])+ expect(label.text).toBe('Updated')+})++test('expands an instance of the enclosing component down to the nested instance it holds', () => {+ const { graph, components } = materializeDocument([+ ...nestedComponentRecords(),+ {+ guid: guid(8),+ type: 'INSTANCE',+ parentIndex: { guid: guid(2), position: 'c' },+ symbolData: {+ symbolID: guid(3),+ symbolOverrides: [+ { guidPath: { guids: [guid(5), guid(7)] }, textData: { characters: 'Overridden' } }+ ]+ }+ } as NodeChange+ ])+ const outer = components.get('1:3')+ const source = components.get('1:6')+ if (!outer || !source) throw new Error('Missing components')+ const placed = graph+ .getChildren(graph.getPages()[0].id)+ .find((node) => node.componentId === outer.materialized.root.id)+ if (!placed) throw new Error('Missing placed instance')+ const nested = graph.getChildren(graph.getChildren(placed.id)[0].id)[0]+ expect(nested.componentId).toBe(source.materialized.root.id)+ expect(graph.getChildren(nested.id)[0].text).toBe('Overridden')+ const sourceLabel = graph.getChildren(source.materialized.root.id)[0]+ graph.updateNode(sourceLabel.id, { text: 'Updated' })+ graph.syncInstances(source.materialized.root.id)+ expect(graph.getChildren(nested.id)[0].text).toBe('Overridden')+})++test.each([+ ['1:2', '1:8'],+ ['1:8', '1:2']+])(+ 'resumes nested definitions after loading %s, then loads %s without duplicating nodes',+ async (first, second) => {+ const records: NodeChange[] = [+ ...nestedComponentRecords(),+ { guid: guid(8), type: 'CANVAS', parentIndex: { guid: guid(1), position: 'b' } },+ {+ guid: guid(9),+ type: 'INSTANCE',+ parentIndex: { guid: guid(8), position: 'a' },+ symbolData: { symbolID: guid(4) }+ }+ ]+ const bytes = await figArchiveOf(records)+ const initial = createFigDocumentSession(bytes)+ initial.loadPage(first)+ const before = initial.checkpoint()+ const resumed = createFigDocumentSession(+ bytes,+ {},+ { graph: initial.graph, checkpoint: before }+ )+ expect(resumed.checkpoint()).toEqual(before)+ const existing = [...initial.graph.getAllNodes()]+ resumed.loadPage(second)+ for (const node of existing) expect(resumed.graph.getNode(node.id)).toBe(node)+ const source = new Map(resumed.checkpoint().sources)+ const instance = resumed.graph.getNode(source.get('1:9') ?? '')+ if (!instance) throw new Error('Missing page instance')+ const nested = resumed.graph.getChildren(instance.id)[0]+ expect(nested.type).toBe('INSTANCE')+ expect(resumed.graph.getChildren(nested.id)[0].text).toBe('Nested instance')+ expect(+ [...resumed.graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')+ ).toHaveLength(3)+ }+)diff --git a/packages/fig/tests/document/page-selection.test.ts b/packages/fig/tests/document/page-selection.test.tsindex e83139aa2..570a3abc3 100644--- a/packages/fig/tests/document/page-selection.test.ts+++ b/packages/fig/tests/document/page-selection.test.ts@@ -1,9 +1,11 @@import { expect, test } from 'bun:test'+import { figArchiveOf } from '#fig-tests/helpers/fig-fixtures'import { guid } from '#fig-tests/helpers/guid'-import { materializeDocument } from '@open-pencil/fig'+import { createFigDocumentSession, materializeDocument } from '@open-pencil/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import type { SceneGraph } from '@open-pencil/scene-graph'test('selected-page assembly excludes unrelated content but keeps cross-page components', () => {const changes: NodeChange[] = [@@ -41,3 +43,150 @@ test('selected-page assembly excludes unrelated content but keeps cross-page com'Unknown page')})++/**+ * Page 1:2 places the inner component, which Outer encloses beside other layers on page 1:3.+ * `placed` adds an instance of Outer to page 1:3; `extra` adds records.+ */+async function enclosedComponentArchive(+ placed = true,+ extra: NodeChange[] = []+): Promise<ArrayBuffer> {+ const records: NodeChange[] = [+ { guid: guid(1), type: 'DOCUMENT' },+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },+ {+ guid: guid(10),+ type: 'INSTANCE',+ parentIndex: { guid: guid(2), position: '!' },+ symbolData: { symbolID: guid(5) }+ },+ { guid: guid(3), type: 'CANVAS', parentIndex: { guid: guid(1), position: '"' } },+ { guid: guid(4), type: 'SYMBOL', name: 'Outer', parentIndex: { guid: guid(3), position: '!' } },+ { guid: guid(5), type: 'SYMBOL', name: 'Inner', parentIndex: { guid: guid(4), position: '!' } },+ {+ guid: guid(6),+ type: 'TEXT',+ parentIndex: { guid: guid(5), position: '!' },+ textData: { characters: 'Inner' }+ },+ {+ guid: guid(7),+ type: 'TEXT',+ parentIndex: { guid: guid(4), position: '"' },+ textData: { characters: 'Beside' }+ },+ {+ guid: guid(8),+ type: 'INSTANCE',+ parentIndex: { guid: guid(4), position: '#' },+ symbolData: { symbolID: guid(11) }+ },+ {+ guid: guid(11),+ type: 'SYMBOL',+ name: 'Label',+ parentIndex: { guid: guid(3), position: '"' }+ },+ {+ guid: guid(12),+ type: 'TEXT',+ parentIndex: { guid: guid(11), position: '!' },+ textData: { characters: 'Label' }+ },+ {+ guid: guid(9),+ type: 'INSTANCE',+ parentIndex: { guid: guid(3), position: '#' },+ symbolData: { symbolID: guid(4) }+ }+ ]+ if (!placed) records.pop()+ records.push(...extra)+ return figArchiveOf(records)+}++function layers(graph: SceneGraph, id: string): unknown {+ const node = graph.getNode(id)+ if (!node) throw new Error(`Missing layer ${id}`)+ return [node.type, node.text, graph.getChildren(id).map((child) => layers(graph, child.id))]+}++test.each([false, true])(+ 'builds a component enclosing a component placed on another page once its own page loads (resumed: %p)',+ async (resumed) => {+ const bytes = await enclosedComponentArchive()+ const expected = createFigDocumentSession(bytes)+ expected.loadPage('1:3')+ let session = createFigDocumentSession(bytes)+ session.loadPage('1:2')+ if (resumed) {+ session = createFigDocumentSession(+ bytes,+ {},+ { graph: session.graph, checkpoint: session.checkpoint() }+ )+ }+ session.loadPage('1:3')+ for (const id of ['1:4', '1:9']) {+ const loaded = new Map(session.checkpoint().sources).get(id)+ const reference = new Map(expected.checkpoint().sources).get(id)+ if (!loaded || !reference) throw new Error(`Missing ${id}`)+ expect(layers(session.graph, loaded)).toEqual(layers(expected.graph, reference))+ }+ const components = (graph: SceneGraph) =>+ [...graph.getAllNodes()].filter((node) => node.type === 'COMPONENT').length+ expect(components(session.graph)).toBe(components(expected.graph))+ }+)++test.each([false, true])(+ 'keeps a layer deleted from the enclosed component deleted when the enclosing page loads (resumed: %p)',+ async (resumed) => {+ const bytes = await enclosedComponentArchive(false)+ let session = createFigDocumentSession(bytes)+ session.loadPage('1:2')+ const { graph } = session+ const inner = new Map(session.checkpoint().componentIds).get('1:5')+ if (!inner) throw new Error('Missing inner component')+ graph.deleteNode(graph.getChildren(inner)[0].id)+ if (resumed) {+ session = createFigDocumentSession(bytes, {}, { graph, checkpoint: session.checkpoint() })+ }+ session.loadPage('1:3')+ // Checkpointing after a resumed deletion is #1425; read the layers from the graph instead.+ const outer = [...graph.getAllNodes()].find((node) => node.name === 'Outer')+ if (!outer) throw new Error('Missing outer component')+ expect(layers(graph, outer.id)).toEqual([+ 'COMPONENT',+ '',+ [+ ['COMPONENT', '', []],+ ['TEXT', 'Beside', []],+ ['INSTANCE', '', [['TEXT', 'Label', []]]]+ ]+ ])+ if (!resumed) expect(session.checkpoint().components.map(([id]) => id)).toContain('1:4')+ }+)++test('builds again an enclosed component deleted before its enclosing page loads', async () => {+ // Inner holds an instance, whose copied layers take fresh IDs each time they are built.+ const bytes = await enclosedComponentArchive(true, [+ {+ guid: guid(13),+ type: 'INSTANCE',+ parentIndex: { guid: guid(5), position: '"' },+ symbolData: { symbolID: guid(11) }+ }+ ])+ const session = createFigDocumentSession(bytes)+ session.loadPage('1:2')+ const inner = new Map(session.checkpoint().componentIds).get('1:5')+ if (!inner) throw new Error('Missing inner component')+ session.graph.deleteNode(inner)+ session.loadPage('1:3')+ const outer = new Map(session.checkpoint().components).get('1:4')+ if (!outer) throw new Error('Missing outer component')+ for (const { nodeId } of outer.nodes) expect(session.graph.getNode(nodeId)).toBeDefined()+})diff --git a/packages/fig/tests/document/record-headers.test.ts b/packages/fig/tests/document/record-headers.test.tsindex c1b7bbce9..f75e44b66 100644--- a/packages/fig/tests/document/record-headers.test.ts+++ b/packages/fig/tests/document/record-headers.test.ts@@ -1,22 +1,15 @@import { expect, test } from 'bun:test'-import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'-import { parseFigBuffer, writeFigArchive } from '#fig/archive'+import { figArchiveOf, readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'+import { parseFigBuffer } from '#fig/archive'import { materializeDocument, materializeFigArchive } from '#fig/document/materialize'import {createArchiveDocumentReader,createDocumentReader,RECORD_HEADER_FIELDS} from '#fig/document/read'-import { deflateSync } from 'fflate'-import {- createNodeChangesMessage,- encodeMessage,- getSchemaBytes,- initCodec,- type NodeChange-} from '@open-pencil/kiwi/fig/codec'+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { deduplicateNodeChangePluginData } from '@open-pencil/kiwi/fig/parse'import { decodeWhole } from '@open-pencil/kiwi/schema-runtime'import { setIdSession, type SceneGraph } from '@open-pencil/scene-graph'@@ -83,7 +76,6 @@ test('an archive reader with record headers builds the document records decoded// fail as a document read whole fails, not by recursing until the stack runs out. The archive// reader decodes a record when it is read, so no page reaching them lets the file open.test('an archive reader rejects a cyclic parent chain as a document read whole does', async () => {- await initCodec()const guid = (localID: number) => ({ sessionID: 0, localID })const under = (parent: number) => ({ guid: guid(parent), position: '!' })const records: NodeChange[] = [@@ -92,14 +84,9 @@ test('an archive reader rejects a cyclic parent chain as a document read whole d{ guid: guid(2), type: 'FRAME', phase: 'CREATED', name: 'A', parentIndex: under(3) },{ guid: guid(3), type: 'FRAME', phase: 'CREATED', name: 'B', parentIndex: under(2) }]- const bytes = writeFigArchive({- schemaDeflated: deflateSync(getSchemaBytes()),- kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),- thumbnailPNG: new Uint8Array([1]),- metaJSON: '{}'- })+ const bytes = await figArchiveOf(records)expect(() => createDocumentReader(records)).toThrow('Cyclic component-property ancestry')- const { reader } = createArchiveDocumentReader(bytes.slice().buffer)+ const { reader } = createArchiveDocumentReader(bytes)expect(() => reader.sourceRecords).toThrow('Cyclic component-property ancestry')})diff --git a/packages/fig/tests/helpers/fig-fixtures.ts b/packages/fig/tests/helpers/fig-fixtures.tsindex 75a351f9e..cb85cc419 100644--- a/packages/fig/tests/helpers/fig-fixtures.ts+++ b/packages/fig/tests/helpers/fig-fixtures.ts@@ -1,6 +1,17 @@import { readFileSync } from 'node:fs'import { resolve } from 'node:path'+import { writeFigArchive } from '#fig/archive'+import { deflateSync } from 'fflate'++import {+ createNodeChangesMessage,+ encodeMessage,+ getSchemaBytes,+ initCodec,+ type NodeChange+} from '@open-pencil/kiwi/fig/codec'+import { FIXTURES } from './paths'export { FIXTURES }@@ -19,3 +30,15 @@ export function readFixtureArrayBuffer(name: string): ArrayBuffer {copy.set(bytes)return copy.buffer}++/** A `.fig` archive of `records`, as a file read from disk gives it. */+export async function figArchiveOf(records: NodeChange[]): Promise<ArrayBuffer> {+ await initCodec()+ const archive = writeFigArchive({+ schemaDeflated: deflateSync(getSchemaBytes()),+ kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),+ thumbnailPNG: new Uint8Array(),+ metaJSON: '{}'+ })+ return new Uint8Array(archive).buffer+}