Skip to content

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

fix(scene-graph): leave a field a component property drives to its instance (#843)

Danila Poyarkovaeba9a6bd5a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec10f8677..df730ac29 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,7 @@
- Stop showing a “signal is aborted without reason” error when you switch pages again before the previous page has finished loading.
- Export layers with two shadows as one `effects` prop instead of repeating the `shadow` attribute, background blurs as `backgroundBlur` instead of a layer blur, hidden children with `visible={false}` instead of leaving them out, and per-corner radii even when the uniform radius is 0.
- Apply `strokeAlign`, `strokeDash`, `minH`, and `maxH` in design JSX, which were accepted but ignored, and make `minW` and `maxW` set the layer's minimum and maximum width rather than only clamping its initial width.
+- Keep the text, visibility, or swapped component an instance sets through a component property when a page it appears on loads on its own, instead of resetting it to the component's default.
- Render the canvas with the Vue SDK's `CanvasRoot` and `CanvasSurface`; CanvasKit never started there and the canvas stayed blank.
- Keep the view centered on what you were looking at when zooming to 100% or another fixed level, instead of jumping elsewhere whenever the zoom changes.
- Draw collaborators' names on their cursors with proper letter spacing and fallback fonts, and end long names with an ellipsis.
diff --git a/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts b/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts
new file mode 100644
index 000000000..8a6ff6b03
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/session/property-driven-text.test.ts
@@ -0,0 +1,89 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { createFigDocumentSession, materializeFigArchive } from '@open-pencil/fig'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * The component lives on one page and the instance that assigns its properties on another, so
+ * loading the second page alone has to interpret the assignments and keep them: the resumed
+ * load synchronises each component it places, which used to reset them to the defaults.
+ */
+async function archiveWithCrossPageAssignment() {
+ const source = new SceneGraph()
+ const library = source.getPages()[0]
+ source.updateNode(library.id, { name: 'Library' })
+ const iconA = source.createNode('COMPONENT', library.id, { name: 'IconA' })
+ const iconB = source.createNode('COMPONENT', library.id, { name: 'IconB' })
+ const item = source.createNode('COMPONENT', library.id, {
+ name: 'NavItem',
+ componentPropertyDefinitions: [
+ { id: '207:1', name: 'Label', type: 'TEXT', defaultValue: 'Default' },
+ { id: '207:2', name: 'Badge', type: 'BOOLEAN', defaultValue: 'true' },
+ { id: '207:3', name: 'Icon', type: 'INSTANCE_SWAP', defaultValue: iconA.id }
+ ]
+ })
+ source.createNode('TEXT', item.id, {
+ name: 'Label',
+ text: 'Default',
+ componentPropertyReferences: [{ propertyId: '207:1', field: 'TEXT' }]
+ })
+ source.createNode('RECTANGLE', item.id, {
+ name: 'Badge',
+ visible: true,
+ componentPropertyReferences: [{ propertyId: '207:2', field: 'VISIBLE' }]
+ })
+ const icon = source.createInstance(iconA.id, item.id)
+ source.updateNode(icon.id, {
+ name: 'Icon',
+ componentPropertyReferences: [{ propertyId: '207:3', field: 'INSTANCE_SWAP' }]
+ })
+ const page = source.addPage('Dashboard')
+ const instance = source.createInstance(item.id, page.id)
+ source.updateNode(instance.id, {
+ componentPropertyAssignments: { '207:1': 'Assigned', '207:2': 'false', '207:3': iconB.id }
+ })
+ const bytes = await exportFigFile(source)
+ return { archive: bytes.buffer as ArrayBuffer, swappedTo: iconB.name }
+}
+
+function childNamed(graph: SceneGraph, parent: SceneNode, name: string): SceneNode {
+ const child = graph.getChildren(parent.id).find((candidate) => candidate.name === name)
+ if (!child) throw new Error(`Missing child ${name}`)
+ return child
+}
+
+/**
+ * What the three property-driven fields read as on the placed instance. The swapped child is
+ * found by type, because a whole-document read renames it after the component it swapped to.
+ */
+function drivenFields(graph: SceneGraph) {
+ const page = graph.getPages().find((candidate) => candidate.name === 'Dashboard')
+ if (!page) throw new Error('Missing page')
+ const instance = graph.getChildren(page.id)[0]
+ const icon = graph.getChildren(instance.id).find((child) => child.type === 'INSTANCE')
+ if (!icon) throw new Error('Missing swapped child')
+ return {
+ text: childNamed(graph, instance, 'Label').text,
+ visible: childNamed(graph, instance, 'Badge').visible,
+ swappedTo: icon.componentId ? graph.getNode(icon.componentId)?.name : undefined
+ }
+}
+
+test('a page loaded on its own keeps the fields its instance assigns', async () => {
+ await initCodec()
+ const { archive, swappedTo } = await archiveWithCrossPageAssignment()
+ const session = createFigDocumentSession(archive)
+ const placed = session.pages.find((page) => page.name === 'Dashboard')
+ if (!placed) throw new Error('Missing source page')
+ session.loadPage(placed.id)
+ expect(drivenFields(session.graph)).toEqual({ text: 'Assigned', visible: false, swappedTo })
+})
+
+test('the whole document reads the same fields', async () => {
+ await initCodec()
+ const { archive, swappedTo } = await archiveWithCrossPageAssignment()
+ const { graph } = materializeFigArchive(archive)
+ expect(drivenFields(graph)).toEqual({ text: 'Assigned', visible: false, swappedTo })
+})
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index 80f27ff4f..c20fbafc1 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -1,7 +1,7 @@
// Child cloning and property synchronization shared by instance creation, swap, and sync.
import { isEqual } from 'es-toolkit/predicate'
-import type { SceneGraph, SceneNode } from '../'
+import type { ComponentPropertyReferenceField, SceneGraph, SceneNode } from '../'
import { ownsSlotContent, slotPropertyId } from '../components/slots'
import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'
import type { NodeCloneMode } from '../copy'
@@ -176,6 +176,45 @@ export function enclosingInstanceOverrideFields(graph: SceneGraph, node: SceneNo
return fields
}
+/** SLOT_CONTENT is absent because it drives children, which `ownsSlotContent` keeps instead. */
+const PROPERTY_REFERENCE_FIELDS: Partial<Record<ComponentPropertyReferenceField, string>> = {
+ VISIBLE: 'visible',
+ TEXT: 'text',
+ INSTANCE_SWAP: 'componentId'
+}
+
+/** The nearest enclosing instance that assigns `propertyId`, if any does. */
+function hasEnclosingAssignment(graph: SceneGraph, node: SceneNode, propertyId: string): boolean {
+ let current: SceneNode | undefined = node
+ while (current) {
+ if (
+ current.type === 'INSTANCE' &&
+ Object.hasOwn(current.componentPropertyAssignments, propertyId)
+ )
+ return true
+ current = current.parentId ? graph.nodes.get(current.parentId) : undefined
+ }
+ return false
+}
+
+/**
+ * Fields a component property drives on this child. The component states the default, but
+ * an enclosing instance's assignment decides the value, so synchronising must not copy the
+ * default over it — a page loaded later would otherwise reset the instance to the default.
+ */
+function propertyDrivenFields(
+ graph: SceneGraph,
+ instChild: SceneNode,
+ compChild: SceneNode
+): Set<string> {
+ const driven = new Set<string>()
+ for (const reference of compChild.componentPropertyReferences) {
+ const field = PROPERTY_REFERENCE_FIELDS[reference.field]
+ if (field && hasEnclosingAssignment(graph, instChild, reference.propertyId)) driven.add(field)
+ }
+ return driven
+}
+
function childBindingProtection(
graph: SceneGraph,
child: SceneNode,
@@ -368,6 +407,7 @@ export function syncChildren(
if (!compChild || !instChild) continue
const protectedField = childBindingProtection(graph, instChild, overrides)
+ const driven = propertyDrivenFields(graph, instChild, compChild)
const componentScale =
(compChild.componentScale * instParent.componentScale) / compParent.componentScale
const source = sourceInTargetCoordinates(compChild, componentScale)
@@ -375,6 +415,7 @@ export function syncChildren(
syncBindingFields(instChild, source, updates, protectedField)
for (const key of INSTANCE_SYNC_FIELDS) {
if (key === 'boundVariables') continue
+ if (driven.has(key)) continue
if (isProtectedSyncField(instChild, key, protectedField)) continue
copyProp(updates, source, key)
diff --git a/packages/scene-graph/tests/components/property-driven-sync.test.ts b/packages/scene-graph/tests/components/property-driven-sync.test.ts
new file mode 100644
index 000000000..234a34c19
--- /dev/null
+++ b/packages/scene-graph/tests/components/property-driven-sync.test.ts
@@ -0,0 +1,84 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function graphWithAssignedLabel() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id, {
+ name: 'NavItem',
+ componentPropertyDefinitions: [
+ { id: '207:1', name: 'Label', type: 'TEXT', defaultValue: 'Default' }
+ ]
+ })
+ const label = graph.createNode('TEXT', component.id, {
+ name: 'Label',
+ text: 'Default',
+ componentPropertyReferences: [{ propertyId: '207:1', field: 'TEXT' }]
+ })
+ const instance = graph.createInstance(component.id, page.id)
+ return { graph, component, label, instance }
+}
+
+/**
+ * A component states the default for a field a property drives; the enclosing instance's
+ * assignment decides the value. Synchronising must not copy the default over it.
+ */
+test('synchronizing leaves a field the enclosing instance assigns alone', () => {
+ const { graph, component, instance } = graphWithAssignedLabel()
+ const clone = graph.getChildren(instance.id)[0]
+ graph.updateNode(instance.id, { componentPropertyAssignments: { '207:1': 'Assigned' } })
+ graph.updateNode(clone.id, { text: 'Assigned' })
+
+ graph.syncInstances(component.id)
+
+ expect(graph.getNode(clone.id)?.text).toBe('Assigned')
+})
+
+test('synchronizing still carries the default to an instance that assigns nothing', () => {
+ const { graph, component, label, instance } = graphWithAssignedLabel()
+ const clone = graph.getChildren(instance.id)[0]
+
+ graph.updateNode(label.id, { text: 'Edited default' })
+ graph.syncInstances(component.id)
+
+ expect(graph.getNode(clone.id)?.text).toBe('Edited default')
+})
+
+/** Only the referenced field is left alone; the rest of the component edit still lands. */
+test('synchronizing carries other fields of a property-driven layer', () => {
+ const { graph, component, label, instance } = graphWithAssignedLabel()
+ const clone = graph.getChildren(instance.id)[0]
+ graph.updateNode(instance.id, { componentPropertyAssignments: { '207:1': 'Assigned' } })
+ graph.updateNode(clone.id, { text: 'Assigned' })
+
+ graph.updateNode(label.id, { opacity: 0.5 })
+ graph.syncInstances(component.id)
+
+ expect(graph.getNode(clone.id)?.text).toBe('Assigned')
+ expect(graph.getNode(clone.id)?.opacity).toBe(0.5)
+})
+
+/** Property IDs are document-authored strings, so one may collide with an Object prototype key. */
+test('a property id shared with an Object prototype key is not read as an assignment', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id, {
+ name: 'NavItem',
+ componentPropertyDefinitions: [
+ { id: 'toString', name: 'Label', type: 'TEXT', defaultValue: 'Default' }
+ ]
+ })
+ const label = graph.createNode('TEXT', component.id, {
+ name: 'Label',
+ text: 'Default',
+ componentPropertyReferences: [{ propertyId: 'toString', field: 'TEXT' }]
+ })
+ const instance = graph.createInstance(component.id, page.id)
+ const clone = graph.getChildren(instance.id)[0]
+
+ graph.updateNode(label.id, { text: 'Edited default' })
+ graph.syncInstances(component.id)
+
+ expect(graph.getNode(clone.id)?.text).toBe('Edited default')
+})