Skip to content

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

Live component-instance sync with override support

Danila Poyarkovf77ad708b85a
diff --git a/src/demo.ts b/src/demo.ts
index 71469b363..b5aa98801 100644
--- a/src/demo.ts
+++ b/src/demo.ts
@@ -35,6 +35,12 @@ function thinStroke(color: Color) {
return [{ color, weight: 1, opacity: 1, visible: true, align: 'INSIDE' as const }]
}
+function makeComponent(store: EditorStore, ids: string[]): string {
+ store.select(ids)
+ store.createComponentFromSelection()
+ return [...store.state.selectedIds][0]
+}
+
export function createDemoShapes(store: EditorStore) {
const { graph } = store
@@ -63,8 +69,7 @@ export function createDemoShapes(store: EditorStore) {
fontWeight: 600,
fills: [solid(WHITE)]
})
- store.select([btnId])
- store.createComponentFromSelection()
+ const btnCompId = makeComponent(store, [btnId])
// Secondary button
const btn2Id = store.createShape('FRAME', 176, 48, 100, 40, compSectionId)
@@ -88,8 +93,7 @@ export function createDemoShapes(store: EditorStore) {
fontWeight: 500,
fills: [solid(BLACK)]
})
- store.select([btn2Id])
- store.createComponentFromSelection()
+ makeComponent(store, [btn2Id])
// Chip / Tag component
const chipId = store.createShape('FRAME', 304, 52, 80, 28, compSectionId)
@@ -112,8 +116,7 @@ export function createDemoShapes(store: EditorStore) {
fontWeight: 500,
fills: [solid(INDIGO)]
})
- store.select([chipId])
- store.createComponentFromSelection()
+ makeComponent(store, [chipId])
// Avatar component
const avatarId = store.createShape('ELLIPSE', 416, 48, 40, 40, compSectionId)
@@ -124,8 +127,7 @@ export function createDemoShapes(store: EditorStore) {
{ color: BLUE, position: 1 }
])]
})
- store.select([avatarId])
- store.createComponentFromSelection()
+ makeComponent(store, [avatarId])
// Card component (auto layout)
const cardId = store.createShape('FRAME', 32, 128, 280, 160, compSectionId)
@@ -171,8 +173,7 @@ export function createDemoShapes(store: EditorStore) {
{ color: TEAL, position: 1 }
])]
})
- store.select([cardId])
- store.createComponentFromSelection()
+ const cardCompId = makeComponent(store, [cardId])
// Input component
const inputId = store.createShape('FRAME', 344, 128, 240, 40, compSectionId)
@@ -196,8 +197,7 @@ export function createDemoShapes(store: EditorStore) {
fontWeight: 400,
fills: [solid(GRAY_500)]
})
- store.select([inputId])
- store.createComponentFromSelection()
+ makeComponent(store, [inputId])
// Badge component
const badgeId = store.createShape('FRAME', 344, 196, 48, 24, compSectionId)
@@ -225,8 +225,7 @@ export function createDemoShapes(store: EditorStore) {
fontWeight: 600,
fills: [solid(GREEN)]
})
- store.select([badgeId])
- store.createComponentFromSelection()
+ const badgeCompId = makeComponent(store, [badgeId])
// Color swatches row
const swatches = [
@@ -289,6 +288,14 @@ export function createDemoShapes(store: EditorStore) {
fills: [solid(BLACK)]
})
+ // Button instance in the header
+ const headerBtn = graph.createInstance(btnCompId, frameId, { x: 400, y: 8 })
+ if (headerBtn) graph.updateNode(headerBtn.id, { x: 400, y: 8 })
+
+ // Badge instance next to title
+ const headerBadge = graph.createInstance(badgeCompId, frameId, { x: 200, y: 18 })
+ if (headerBadge) graph.updateNode(headerBadge.id, { x: 200, y: 18 })
+
// Stat cards row (instances from Card component, simulated as frames)
const stats = [
{ title: 'Revenue', value: '$12,480', badge: '+14%', color: GREEN },
diff --git a/src/engine/scene-graph.ts b/src/engine/scene-graph.ts
index 95715ef31..7bf140914 100644
--- a/src/engine/scene-graph.ts
+++ b/src/engine/scene-graph.ts
@@ -559,48 +559,143 @@ export class SceneGraph {
return clone
}
+ private static readonly INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [
+ 'width', 'height', 'fills', 'strokes', 'effects', 'opacity',
+ 'cornerRadius', 'topLeftRadius', 'topRightRadius', 'bottomRightRadius', 'bottomLeftRadius',
+ 'independentCorners', 'layoutMode', 'layoutWrap', 'primaryAxisAlign', 'counterAxisAlign',
+ 'primaryAxisSizing', 'counterAxisSizing', 'itemSpacing', 'counterAxisSpacing',
+ 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'clipsContent'
+ ]
+
createInstance(componentId: string, parentId: string, overrides: Partial<SceneNode> = {}): SceneNode | null {
const component = this.nodes.get(componentId)
if (!component || component.type !== 'COMPONENT') return null
- const instance = this.createNode('INSTANCE', parentId, {
- name: component.name,
- width: component.width,
- height: component.height,
- fills: component.fills.map((f) => ({ ...f })),
- strokes: component.strokes.map((s) => ({ ...s })),
- effects: component.effects.map((e) => ({ ...e })),
- opacity: component.opacity,
- cornerRadius: component.cornerRadius,
- topLeftRadius: component.topLeftRadius,
- topRightRadius: component.topRightRadius,
- bottomRightRadius: component.bottomRightRadius,
- bottomLeftRadius: component.bottomLeftRadius,
- independentCorners: component.independentCorners,
- layoutMode: component.layoutMode,
- layoutWrap: component.layoutWrap,
- primaryAxisAlign: component.primaryAxisAlign,
- counterAxisAlign: component.counterAxisAlign,
- primaryAxisSizing: component.primaryAxisSizing,
- counterAxisSizing: component.counterAxisSizing,
- itemSpacing: component.itemSpacing,
- counterAxisSpacing: component.counterAxisSpacing,
- paddingTop: component.paddingTop,
- paddingRight: component.paddingRight,
- paddingBottom: component.paddingBottom,
- paddingLeft: component.paddingLeft,
- clipsContent: component.clipsContent,
- componentId,
- ...overrides
- })
-
- for (const childId of component.childIds) {
- this.cloneTree(childId, instance.id)
+ const props: Partial<SceneNode> = { name: component.name, componentId }
+ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {
+ const val = component[key]
+ ;(props as Record<string, unknown>)[key] = Array.isArray(val)
+ ? val.map((v: Record<string, unknown>) => ({ ...v }))
+ : val
}
+ const instance = this.createNode('INSTANCE', parentId, { ...props, ...overrides })
+
+ this.cloneChildrenWithMapping(component.id, instance.id)
+
return instance
}
+ private cloneChildrenWithMapping(sourceParentId: string, destParentId: string): void {
+ const sourceParent = this.nodes.get(sourceParentId)
+ if (!sourceParent) return
+
+ for (const childId of sourceParent.childIds) {
+ const src = this.nodes.get(childId)
+ if (!src) continue
+
+ const { id: _, parentId: _p, childIds: _c, ...rest } = src
+ const clone = this.createNode(src.type, destParentId, {
+ ...rest,
+ componentId: childId
+ })
+
+ if (src.childIds.length > 0) {
+ this.cloneChildrenWithMapping(childId, clone.id)
+ }
+ }
+ }
+
+ syncInstances(componentId: string): void {
+ const component = this.nodes.get(componentId)
+ if (!component || component.type !== 'COMPONENT') return
+
+ for (const instance of this.getInstances(componentId)) {
+ // Sync instance-level props (unless overridden)
+ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {
+ const overrideKey = `${key}`
+ if (overrideKey in instance.overrides) continue
+ const val = component[key]
+ ;(instance as Record<string, unknown>)[key] = Array.isArray(val)
+ ? val.map((v: Record<string, unknown>) => ({ ...v }))
+ : val
+ }
+
+ // Sync children: match by componentId
+ this.syncChildren(component.id, instance.id, instance.overrides)
+ }
+ }
+
+ private syncChildren(
+ compParentId: string,
+ instParentId: string,
+ overrides: Record<string, unknown>
+ ): void {
+ const compParent = this.nodes.get(compParentId)
+ const instParent = this.nodes.get(instParentId)
+ if (!compParent || !instParent) return
+
+ const instChildMap = new Map<string, SceneNode>()
+ for (const childId of instParent.childIds) {
+ const child = this.nodes.get(childId)
+ if (child?.componentId) instChildMap.set(child.componentId, child)
+ }
+
+ // Add new children from component that don't exist in instance
+ for (const compChildId of compParent.childIds) {
+ if (!instChildMap.has(compChildId)) {
+ const src = this.nodes.get(compChildId)
+ if (!src) continue
+ const { id: _, parentId: _p, childIds: _c, ...rest } = src
+ const clone = this.createNode(src.type, instParentId, {
+ ...rest,
+ componentId: compChildId
+ })
+ if (src.childIds.length > 0) {
+ this.cloneChildrenWithMapping(compChildId, clone.id)
+ }
+ instChildMap.set(compChildId, clone)
+ }
+ }
+
+ // Sync existing children
+ for (const compChildId of compParent.childIds) {
+ const compChild = this.nodes.get(compChildId)
+ const instChild = instChildMap.get(compChildId)
+ if (!compChild || !instChild) continue
+
+ for (const key of SceneGraph.INSTANCE_SYNC_PROPS) {
+ const overrideKey = `${instChild.id}:${key}`
+ if (overrideKey in overrides) continue
+ const val = compChild[key]
+ ;(instChild as Record<string, unknown>)[key] = Array.isArray(val)
+ ? val.map((v: Record<string, unknown>) => ({ ...v }))
+ : val
+ }
+
+ // Sync name and text unless overridden
+ for (const key of ['name', 'text', 'fontSize', 'fontWeight', 'fontFamily'] as const) {
+ const overrideKey = `${instChild.id}:${key}`
+ if (overrideKey in overrides) continue
+ ;(instChild as Record<string, unknown>)[key] = compChild[key]
+ }
+
+ if (compChild.childIds.length > 0) {
+ this.syncChildren(compChildId, instChild.id, overrides)
+ }
+ }
+
+ // Reorder instance children to match component order
+ const compChildOrder = compParent.childIds
+ instParent.childIds.sort((a, b) => {
+ const nodeA = this.nodes.get(a)
+ const nodeB = this.nodes.get(b)
+ const idxA = nodeA?.componentId ? compChildOrder.indexOf(nodeA.componentId) : -1
+ const idxB = nodeB?.componentId ? compChildOrder.indexOf(nodeB.componentId) : -1
+ return idxA - idxB
+ })
+ }
+
detachInstance(instanceId: string): void {
const node = this.nodes.get(instanceId)
if (!node || node.type !== 'INSTANCE') return
diff --git a/src/stores/editor.ts b/src/stores/editor.ts
index 6399c11f6..9224ce844 100644
--- a/src/stores/editor.ts
+++ b/src/stores/editor.ts
@@ -546,9 +546,21 @@ export function createEditorStore() {
function updateNode(id: string, changes: Partial<SceneNode>) {
graph.updateNode(id, changes)
runLayoutForNode(id)
+ syncIfInsideComponent(id)
requestRender()
}
+ function syncIfInsideComponent(nodeId: string) {
+ let current = graph.getNode(nodeId)
+ while (current) {
+ if (current.type === 'COMPONENT') {
+ graph.syncInstances(current.id)
+ return
+ }
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
+ }
+ }
+
function updateNodeWithUndo(id: string, changes: Partial<SceneNode>, label = 'Update') {
const node = graph.getNode(id)
if (!node) return
@@ -558,16 +570,19 @@ export function createEditorStore() {
}
graph.updateNode(id, changes)
runLayoutForNode(id)
+ syncIfInsideComponent(id)
undo.push({
label,
forward: () => {
graph.updateNode(id, changes)
runLayoutForNode(id)
+ syncIfInsideComponent(id)
requestRender()
},
inverse: () => {
graph.updateNode(id, previous)
runLayoutForNode(id)
+ syncIfInsideComponent(id)
requestRender()
}
})
@@ -1425,6 +1440,7 @@ export function createEditorStore() {
const n = graph.getNode(id)
if (n) finals.set(id, { x: n.x, y: n.y })
}
+ for (const [id] of finals) syncIfInsideComponent(id)
undo.push({
label: 'Move',
forward: () => {
@@ -1432,6 +1448,7 @@ export function createEditorStore() {
graph.updateNode(id, pos)
runLayoutForNode(id)
}
+ for (const [id] of finals) syncIfInsideComponent(id)
requestRender()
},
inverse: () => {
@@ -1439,6 +1456,7 @@ export function createEditorStore() {
graph.updateNode(id, pos)
runLayoutForNode(id)
}
+ for (const [id] of originals) syncIfInsideComponent(id)
requestRender()
}
})
@@ -1451,16 +1469,19 @@ export function createEditorStore() {
const node = graph.getNode(nodeId)
if (!node) return
const finalRect = { x: node.x, y: node.y, width: node.width, height: node.height }
+ syncIfInsideComponent(nodeId)
undo.push({
label: 'Resize',
forward: () => {
graph.updateNode(nodeId, finalRect)
runLayoutForNode(nodeId)
+ syncIfInsideComponent(nodeId)
requestRender()
},
inverse: () => {
graph.updateNode(nodeId, origRect)
runLayoutForNode(nodeId)
+ syncIfInsideComponent(nodeId)
requestRender()
}
})
diff --git a/tests/engine/scene-graph.test.ts b/tests/engine/scene-graph.test.ts
index 9cdd9ed97..20165bdc4 100644
--- a/tests/engine/scene-graph.test.ts
+++ b/tests/engine/scene-graph.test.ts
@@ -66,4 +66,81 @@ describe('SceneGraph', () => {
expect(node.x).toBe(200)
expect(node.name).toBe('Updated')
})
+
+ test('create instance clones children with componentId mapping', () => {
+ const graph = new SceneGraph()
+ const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Btn', width: 100, height: 40 })
+ const child = graph.createNode('RECTANGLE', comp.id, { name: 'BG', width: 100, height: 40 })
+ const instance = graph.createInstance(comp.id, pageId(graph))!
+ expect(instance.type).toBe('INSTANCE')
+ expect(instance.componentId).toBe(comp.id)
+ const instChildren = graph.getChildren(instance.id)
+ expect(instChildren).toHaveLength(1)
+ expect(instChildren[0].componentId).toBe(child.id)
+ expect(instChildren[0].name).toBe('BG')
+ })
+
+ test('syncInstances propagates changes from component to instance', () => {
+ const graph = new SceneGraph()
+ const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ const label = graph.createNode('TEXT', comp.id, { name: 'Title', text: 'Hello', fontSize: 14 })
+ const instance = graph.createInstance(comp.id, pageId(graph))!
+ const instLabel = graph.getChildren(instance.id)[0]
+ expect(instLabel.text).toBe('Hello')
+
+ graph.updateNode(label.id, { text: 'Updated', fontSize: 18 })
+ graph.syncInstances(comp.id)
+
+ expect(instLabel.text).toBe('Updated')
+ expect(instLabel.fontSize).toBe(18)
+ })
+
+ test('syncInstances preserves overrides', () => {
+ const graph = new SceneGraph()
+ const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ graph.createNode('TEXT', comp.id, { name: 'Title', text: 'Default', fontSize: 14 })
+ const instance = graph.createInstance(comp.id, pageId(graph))!
+ const instLabel = graph.getChildren(instance.id)[0]
+
+ // Override the text on the instance child
+ graph.updateNode(instLabel.id, { text: 'Custom' })
+ instance.overrides[`${instLabel.id}:text`] = 'Custom'
+
+ // Change component
+ graph.updateNode(graph.getChildren(comp.id)[0].id, { text: 'New Default', fontSize: 20 })
+ graph.syncInstances(comp.id)
+
+ // Text preserved (overridden), fontSize synced (not overridden)
+ expect(instLabel.text).toBe('Custom')
+ expect(instLabel.fontSize).toBe(20)
+ })
+
+ test('syncInstances adds new children from component', () => {
+ const graph = new SceneGraph()
+ const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Card', width: 200, height: 100 })
+ graph.createNode('RECTANGLE', comp.id, { name: 'BG' })
+ const instance = graph.createInstance(comp.id, pageId(graph))!
+ expect(graph.getChildren(instance.id)).toHaveLength(1)
+
+ graph.createNode('TEXT', comp.id, { name: 'Label', text: 'New' })
+ graph.syncInstances(comp.id)
+
+ const instChildren = graph.getChildren(instance.id)
+ expect(instChildren).toHaveLength(2)
+ expect(instChildren[1].name).toBe('Label')
+ expect(instChildren[1].text).toBe('New')
+ })
+
+ test('detachInstance breaks link', () => {
+ const graph = new SceneGraph()
+ const comp = graph.createNode('COMPONENT', pageId(graph), { name: 'Btn', width: 100, height: 40 })
+ graph.createNode('RECTANGLE', comp.id, { name: 'BG' })
+ const instance = graph.createInstance(comp.id, pageId(graph))!
+ expect(instance.type).toBe('INSTANCE')
+
+ graph.detachInstance(instance.id)
+ expect(instance.type).toBe('FRAME')
+ expect(instance.componentId).toBeNull()
+ expect(graph.getInstances(comp.id)).toHaveLength(0)
+ })
})