Skip to content

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

perf(fig): share unchanged values between instance layers and their components (#990)

Danila Poyarkov4ecea5897b79
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b4ad1487d..a1fcb4b79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -235,6 +235,7 @@
### Performance
+- Open `.fig` design kits with less memory: layers inside instances hold their component layers' paints, glyphs, and other unchanged values instead of a copy each, about a third fewer objects and an eighth less memory per loaded page.
- 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.
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
new file mode 100644
index 000000000..559eee4e0
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/import/shared-instance-values.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+const red = { r: 1, g: 0, b: 0, a: 1 }
+const blue = { r: 0, g: 0, b: 1, a: 1 }
+
+async function reopenedInstance() {
+ await initCodec()
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const component = graph.createNode('COMPONENT', page, { name: 'Card', width: 100, height: 50 })
+ graph.createNode('RECTANGLE', component.id, {
+ name: 'Surface',
+ width: 100,
+ height: 50,
+ fills: [{ type: 'SOLID', color: red, opacity: 1, visible: true }]
+ })
+ graph.createInstance(component.id, page, { x: 200 })
+ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)
+ const instance = [...reopened.nodes.values()].find((node) => node.type === 'INSTANCE')
+ const [layer] = reopened.getChildren(instance?.id ?? '')
+ const source = reopened.getNode(layer?.componentId ?? '')
+ if (!layer || !source) throw new Error('Missing instance layer or its component layer')
+ return { graph: reopened, layer, source }
+}
+
+// A design kit holds many instances of each component; their layers hold the component layers'
+// own objects for what no override changed, rather than one copy each.
+test('a layer inside an instance holds its component layer’s unchanged values', async () => {
+ const { layer, source } = await reopenedInstance()
+
+ expect(layer.fills).toBe(source.fills)
+ expect(layer.effects).toBe(source.effects)
+ expect(layer.source).not.toBe(source.source)
+ expect(layer.instanceOverrides).not.toBe(source.instanceOverrides)
+})
+
+test('changing a layer inside an instance leaves its component layer as it was', async () => {
+ const { graph, layer, source } = await reopenedInstance()
+ const before: SceneNode = structuredClone(source)
+
+ graph.updateNode(layer.id, { fills: [{ type: 'SOLID', color: blue, opacity: 1, visible: true }] })
+
+ expect(graph.getNode(layer.id)?.fills[0].color).toEqual(blue)
+ expect(graph.getNode(source.id)).toEqual(before)
+})
diff --git a/packages/fig/src/document/component/values.ts b/packages/fig/src/document/component/values.ts
index f5fea9346..49b7ca26b 100644
--- a/packages/fig/src/document/component/values.ts
+++ b/packages/fig/src/document/component/values.ts
@@ -18,21 +18,31 @@ export function linkComponentPropertyValues(
for (const node of graph.getAllNodes())
for (const definition of node.componentPropertyDefinitions)
definitions.set(definition.id, definition.type)
+ // Linked values replace the definitions and assignments rather than writing into them: a layer
+ // inside an instance holds its component layer's own objects until an override changes them.
for (const node of materialized) {
- for (const definition of node.componentPropertyDefinitions) {
+ let linked: typeof node.componentPropertyDefinitions | undefined
+ node.componentPropertyDefinitions.forEach((definition, index) => {
definitions.set(definition.id, definition.type)
- if (definition.type !== 'INSTANCE_SWAP') continue
+ if (definition.type !== 'INSTANCE_SWAP') return
const target = sources.get(definition.defaultValue)
- if (target) definition.defaultValue = target
- }
+ if (!target) return
+ linked ??= [...node.componentPropertyDefinitions]
+ linked[index] = { ...definition, defaultValue: target }
+ })
+ if (linked) node.componentPropertyDefinitions = linked
}
for (const node of materialized) {
+ let linked: typeof node.componentPropertyAssignments | undefined
// for-in skips the entry array that most nodes, which assign nothing, never need.
for (const propertyId in node.componentPropertyAssignments) {
if (definitions.get(propertyId) !== 'INSTANCE_SWAP') continue
const target = sources.get(node.componentPropertyAssignments[propertyId])
- if (target) node.componentPropertyAssignments[propertyId] = target
+ if (!target) continue
+ linked ??= { ...node.componentPropertyAssignments }
+ linked[propertyId] = target
}
+ if (linked) node.componentPropertyAssignments = linked
}
}
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index 09449af51..d6d6a551a 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -1,3 +1,5 @@
+import { isEqual } from 'es-toolkit/predicate'
+
import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
import { setInstanceOverride, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
@@ -26,6 +28,36 @@ function occurrenceMetadata(
return metadata
}
+/**
+ * Fields a layer keeps its own: its children, and state written in place, such as its source
+ * metadata and its override maps.
+ */
+const OWN_FIELDS = new Set(['childIds', 'source', 'instanceOverrides'])
+
+/** Maps and sets are written in place, so values holding them are never shared. */
+function holdsCollections(value: unknown): boolean {
+ if (value instanceof Map || value instanceof Set) return true
+ if (value === null || typeof value !== 'object' || ArrayBuffer.isView(value)) return false
+ return Object.values(value).some(holdsCollections)
+}
+
+/**
+ * A layer inside an instance holds what its component's layer holds unless an override changed
+ * it. Each equal value is the component layer's own object rather than a copy, so a design kit's
+ * many instances do not each repeat their components' paints, glyphs, and defaults. Values are
+ * replaced, never written into, once loaded; loading writes only into fields a layer keeps.
+ */
+function shareUnchanged(node: SceneNode, source: SceneNode): void {
+ for (const field of Object.keys(node)) {
+ if (OWN_FIELDS.has(field)) continue
+ const value: unknown = Reflect.get(node, field)
+ const original: unknown = Reflect.get(source, field)
+ if (value === original || value === null || typeof value !== 'object') continue
+ if (holdsCollections(value) || !isEqual(value, original)) continue
+ Reflect.set(node, field, original)
+ }
+}
+
export interface MaterializedInstance {
root: SceneNode
/** Occurrence object identity distinguishes repeated uses of a source node. */
@@ -133,6 +165,8 @@ export function materializeInstance(
}
const node = existing ?? graph.createNode(nodeType, parent, propsWithIdentity)
if (existing) graph.updateNode(existing.id, propsWithIdentity)
+ const sharedSource = graph.getNode(sourceChildren.get(current) ?? '')
+ if (sharedSource) shareUnchanged(node, sharedSource)
nodes.set(current, node)
if (existing && current !== occurrence && node.type === 'COMPONENT') return node
applyBindingClaims(current, node, owner)
diff --git a/packages/fig/tests/document/component-dependencies.test.ts b/packages/fig/tests/document/component/dependencies.test.ts
similarity index 100%
rename from packages/fig/tests/document/component-dependencies.test.ts
rename to packages/fig/tests/document/component/dependencies.test.ts
diff --git a/packages/fig/tests/document/component/values.test.ts b/packages/fig/tests/document/component/values.test.ts
new file mode 100644
index 000000000..359dffdc7
--- /dev/null
+++ b/packages/fig/tests/document/component/values.test.ts
@@ -0,0 +1,37 @@
+import { expect, test } from 'bun:test'
+
+import { linkComponentPropertyValues } from '#fig/document/component/values'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Layers inside instances hold their component layers' own objects, so linking replaces a
+// layer's definitions and assignments instead of writing into objects other layers hold.
+test('linking component property values leaves objects other layers hold untouched', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const definitions = [
+ { id: 'swap', name: 'Icon', type: 'INSTANCE_SWAP' as const, defaultValue: '1:2' }
+ ]
+ const assignments = { swap: '1:2' }
+ const component = graph.createNode('COMPONENT', page, {
+ componentPropertyDefinitions: definitions,
+ componentPropertyAssignments: assignments
+ })
+ const copy = graph.createNode('FRAME', page, {
+ componentPropertyDefinitions: definitions,
+ componentPropertyAssignments: assignments
+ })
+ // Held, not copied: as a layer inside an instance holds its component layer's objects.
+ const node = graph.getNode(copy.id)
+ if (!node) throw new Error('Missing copy')
+ node.componentPropertyDefinitions = definitions
+ node.componentPropertyAssignments = assignments
+
+ linkComponentPropertyValues(graph, new Map([['1:2', 'linked']]), [node])
+
+ expect(node.componentPropertyDefinitions[0].defaultValue).toBe('linked')
+ expect(node.componentPropertyAssignments.swap).toBe('linked')
+ expect(definitions[0].defaultValue).toBe('1:2')
+ expect(assignments.swap).toBe('1:2')
+ expect(graph.getNode(component.id)?.componentPropertyAssignments.swap).toBe('1:2')
+})