Skip to content

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

refactor(scene-graph): model instance overrides structurally

Danila Poyarkov1e1c38182d9a
diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.ts
index 05da85019..e9f82c390 100644
--- a/packages/core/src/design-jsx/renderer.ts
+++ b/packages/core/src/design-jsx/renderer.ts
@@ -4,7 +4,7 @@ import type {
SceneNode,
NodeType
} from '@open-pencil/scene-graph'
-import type { Color } from '@open-pencil/scene-graph/primitives'
+import { setInstanceOverride } from '@open-pencil/scene-graph'
import { parseColor } from '#core/color'
import type { RenderOptions } from '#core/design-jsx/types'
@@ -452,7 +452,7 @@ function applyInstanceOverrides(
}
walk(instance.id)
- const overrides: Record<string, unknown> = { ...instance.overrides }
+ const overrides = new Map<string, unknown>()
for (const [key, value] of entries) {
const sep = key.indexOf(':')
if (sep === -1) continue
@@ -461,10 +461,10 @@ function applyInstanceOverrides(
const child = descendants.find((n) => n.name === childName)
if (!child || !(prop in child)) continue
graph.updateNode(child.id, { [prop]: value } as Partial<SceneNode>)
- overrides[`${child.id}:${prop}`] = value
+ setInstanceOverride(instance.instanceOverrides, instance.id, child.id, prop, value)
}
- if (Object.keys(overrides).length > 0) {
- graph.updateNode(instance.id, { overrides })
+ if (overrides.size > 0) {
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
}
}
diff --git a/packages/core/src/editor/components/instances.ts b/packages/core/src/editor/components/instances.ts
index 1156aa788..cd44101bc 100644
--- a/packages/core/src/editor/components/instances.ts
+++ b/packages/core/src/editor/components/instances.ts
@@ -111,7 +111,10 @@ export function createComponentInstanceActions(ctx: EditorContext) {
ctx.graph.updateNode(selectedNode.id, {
type: 'INSTANCE',
componentId: prevComponentId,
- overrides: {}
+ instanceOverrides: {
+ self: new Map(),
+ descendants: new Map()
+ }
})
}
})
diff --git a/packages/core/src/editor/components/properties.ts b/packages/core/src/editor/components/properties.ts
index 928d453db..e62ca65d3 100644
--- a/packages/core/src/editor/components/properties.ts
+++ b/packages/core/src/editor/components/properties.ts
@@ -1,5 +1,5 @@
import {
- applyComponentPropertyValue,
+ cloneInstanceOverrideState,
componentPropertyDefinitions,
findComponentPropertyTarget,
resolveComponentPropertyValue
@@ -100,7 +100,8 @@ export function createComponentPropertyActions(
}
const previousAssignments = { ...instance.componentPropertyAssignments }
- const previousOverrides = structuredClone(instance.overrides)
+ const previousOverrides = cloneInstanceOverrideState(instance.instanceOverrides)
+
const target = propertyTarget(ctx, instance, propertyId)
const assignedValue = instance.componentPropertyAssignments[propertyId]
const previousValue =
@@ -120,7 +121,7 @@ export function createComponentPropertyActions(
if (live) {
ctx.graph.updateNode(instanceId, {
componentPropertyAssignments: previousAssignments,
- overrides: previousOverrides
+ instanceOverrides: cloneInstanceOverrideState(previousOverrides)
})
const restoredTarget = propertyTarget(ctx, live, propertyId)
if (restoredTarget?.field === 'TEXT' && restoredTarget.node.type === 'TEXT') {
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index e25184e11..5d3c1dad9 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -1,4 +1,9 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
+import {
+ cloneInstanceOverrideState,
+ setInstanceOverride,
+ type InstanceOverrideState,
+ type SceneNode
+} from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'
import { weightToStyle } from '#core/text/fonts'
@@ -48,7 +53,7 @@ function snapshotPathText(
type InstanceOverridesSnapshot = {
instanceId: string
- overrides: Record<string, unknown>
+ instanceOverrides: InstanceOverrideState
}
function containingInstanceIds(ctx: EditorContext, nodeId: string): string[] {
@@ -68,7 +73,7 @@ function snapshotInstanceOverrides(
return instanceIds.flatMap((instanceId) => {
const instance = ctx.graph.getNode(instanceId)
return instance?.type === 'INSTANCE'
- ? [{ instanceId, overrides: structuredClone(instance.overrides) }]
+ ? [{ instanceId, instanceOverrides: cloneInstanceOverrideState(instance.instanceOverrides) }]
: []
})
}
@@ -76,7 +81,7 @@ function snapshotInstanceOverrides(
function restoreInstanceOverrides(ctx: EditorContext, snapshots: InstanceOverridesSnapshot[]) {
for (const snapshot of snapshots) {
ctx.graph.updateNode(snapshot.instanceId, {
- overrides: structuredClone(snapshot.overrides)
+ instanceOverrides: cloneInstanceOverrideState(snapshot.instanceOverrides)
})
}
}
@@ -90,9 +95,8 @@ function applyTextInstanceOverride(
for (const instanceId of instanceIds) {
const instance = ctx.graph.getNode(instanceId)
if (instance?.type !== 'INSTANCE') continue
- ctx.graph.updateNode(instanceId, {
- overrides: { ...instance.overrides, [`${nodeId}:text`]: text }
- })
+ setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, 'text', text)
+ ctx.graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
}
}
diff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export-node.ts
index d16461a2a..a64b1154e 100644
--- a/packages/fig/src/node-change/export-node.ts
+++ b/packages/fig/src/node-change/export-node.ts
@@ -1,12 +1,12 @@
import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
-import { DEFAULT_STROKE_MITER_LIMIT } from '@open-pencil/scene-graph'
import type {
ComponentPropertyDefinition,
ComponentPropertyReferenceField,
SceneGraph,
SceneNode
} from '@open-pencil/scene-graph'
+import { DEFAULT_STROKE_MITER_LIMIT, forEachInstanceOverride } from '@open-pencil/scene-graph'
import type { Color, GUID, Matrix, Vector } from '@open-pencil/scene-graph/primitives'
import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '../source-metadata'
@@ -400,20 +400,14 @@ function serializeTextOverrides(
localIdCounter: { value: number }
): KiwiSymbolOverridePayload[] {
const result: KiwiSymbolOverridePayload[] = []
- for (const [key, value] of Object.entries(instance.overrides)) {
- if (!key.endsWith(':text') || typeof value !== 'string') continue
- const targetId = key.slice(0, -':text'.length)
- const target = context.graph.getNode(targetId)
- if (!target || !isDescendantOf(context, targetId, instance.id)) continue
-
+ forEachInstanceOverride(instance.instanceOverrides, (nodeId, field, value) => {
+ if (field !== 'text' || typeof value !== 'string' || !nodeId) return
+ const target = context.graph.getNode(nodeId)
+ if (!target || !isDescendantOf(context, nodeId, instance.id)) return
const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)
- if (!targetGuid) continue
-
- result.push({
- guidPath: { guids: [targetGuid] },
- textData: { characters: value }
- })
- }
+ if (targetGuid)
+ result.push({ guidPath: { guids: [targetGuid] }, textData: { characters: value } })
+ })
return result
}
@@ -440,20 +434,17 @@ function serializeFillOverrides(
localIdCounter: { value: number }
): KiwiSymbolOverridePayload[] {
const result: KiwiSymbolOverridePayload[] = []
- for (const key of Object.keys(instance.overrides)) {
- if (!key.endsWith(':fills')) continue
- const targetId = key.slice(0, -':fills'.length)
- const target = context.graph.getNode(targetId)
- if (!target || !isDescendantOf(context, targetId, instance.id)) continue
-
+ forEachInstanceOverride(instance.instanceOverrides, (nodeId, field) => {
+ if (field !== 'fills' || !nodeId) return
+ const target = context.graph.getNode(nodeId)
+ if (!target || !isDescendantOf(context, nodeId, instance.id)) return
const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)
- if (!targetGuid) continue
-
- result.push({
- guidPath: { guids: [targetGuid] },
- fillPaints: target.fills.map((fill) => context.fillToKiwiPaint(fill))
- })
- }
+ if (targetGuid)
+ result.push({
+ guidPath: { guids: [targetGuid] },
+ fillPaints: target.fills.map((fill) => context.fillToKiwiPaint(fill))
+ })
+ })
return result
}
diff --git a/packages/fig/tests/export.test.ts b/packages/fig/tests/export.test.ts
index 760b84c98..e55bcbaeb 100644
--- a/packages/fig/tests/export.test.ts
+++ b/packages/fig/tests/export.test.ts
@@ -70,7 +70,10 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
opacity: 0.5
}
graph.updateNode(instance?.id ?? '', {
- overrides: { [`${targetText?.id}:text`]: 'Edited' },
+ instanceOverrides: {
+ self: new Map(),
+ descendants: new Map([[targetText?.id ?? '', new Map([['text', 'Edited']])]])
+ },
source: {
...instance?.source,
fig: {
diff --git a/packages/scene-graph/src/components/properties.ts b/packages/scene-graph/src/components/properties.ts
index 807a3d887..6344bd53a 100644
--- a/packages/scene-graph/src/components/properties.ts
+++ b/packages/scene-graph/src/components/properties.ts
@@ -1,4 +1,5 @@
import type { SceneGraph } from '../index'
+import { setInstanceOverride } from '../instance-overrides'
import type {
ComponentPropertyDefinition,
ComponentPropertyReferenceField,
@@ -87,48 +88,62 @@ export function findComponentPropertyTargets(
function applyTextProperty(
graph: SceneGraph,
targets: ComponentPropertyTarget[],
- value: string,
- overrides: Record<string, unknown>
+ value: string
): void {
for (const item of targets) {
if (item.field !== 'TEXT' || item.node.type !== 'TEXT') continue
graph.updateNode(item.node.id, { text: value })
- overrides[`${item.node.id}:text`] = value
+ setInstanceOverride(item.node.instanceOverrides, item.node.id, item.node.id, 'text', value)
}
}
function applyBooleanProperty(
graph: SceneGraph,
targets: ComponentPropertyTarget[],
- value: string,
- overrides: Record<string, unknown>
+ value: string
): void {
for (const item of targets) {
if (item.field !== 'VISIBLE') continue
graph.updateNode(item.node.id, { visible: value === 'true' })
- overrides[`${item.node.id}:visible`] = value === 'true'
+ setInstanceOverride(
+ item.node.instanceOverrides,
+ item.node.id,
+ item.node.id,
+ 'visible',
+ value === 'true'
+ )
}
}
function applyInstanceSwapProperty(
graph: SceneGraph,
targets: ComponentPropertyTarget[],
- target: SceneNode,
- overrides: Record<string, unknown>
+ target: SceneNode
): void {
for (const item of targets) {
if (item.field !== 'INSTANCE_SWAP' || item.node.type !== 'INSTANCE') continue
graph.swapInstanceComponent(item.node.id, target.id)
- graph.updateNode(item.node.id, {
- name: target.name,
- overrides: {
- ...item.node.overrides,
- [`${item.node.id}:name`]: target.name
- }
- })
- overrides[`${item.node.id}:componentId`] = target.id
- overrides[`${item.node.id}:sourceComponentId`] = item.source.id
- overrides[`${item.node.id}:name`] = target.name
+ setInstanceOverride(
+ item.node.instanceOverrides,
+ item.node.id,
+ item.node.id,
+ 'name',
+ target.name
+ )
+ setInstanceOverride(
+ item.node.instanceOverrides,
+ item.node.id,
+ item.node.id,
+ 'componentId',
+ target.id
+ )
+ setInstanceOverride(
+ item.node.instanceOverrides,
+ item.node.id,
+ item.node.id,
+ 'sourceComponentId',
+ item.source.id
+ )
}
}
@@ -145,20 +160,18 @@ export function applyComponentPropertyValue(
const target =
definition.type === 'INSTANCE_SWAP' ? resolveComponentPropertyValue(graph, value) : null
if (definition.type === 'INSTANCE_SWAP' && !target) return null
- const overrides = { ...instance.overrides }
if (definition.type === 'TEXT') {
- applyTextProperty(graph, targets, value, overrides)
+ applyTextProperty(graph, targets, value)
} else if (definition.type === 'BOOLEAN') {
- applyBooleanProperty(graph, targets, value, overrides)
+ applyBooleanProperty(graph, targets, value)
} else if (target) {
- applyInstanceSwapProperty(graph, targets, target, overrides)
+ applyInstanceSwapProperty(graph, targets, target)
}
graph.updateNode(instance.id, {
componentPropertyAssignments: {
...instance.componentPropertyAssignments,
[definition.id]: definition.type === 'INSTANCE_SWAP' && target ? target.id : value
- },
- overrides
+ }
})
return definition.type === 'INSTANCE_SWAP' ? target : instance
}
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index 56cf6c370..592a664e3 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -22,6 +22,7 @@ import type {
StyleRun
} from './'
import { geometryCommandCoordCount } from './geometry'
+import { cloneInstanceOverrideState } from './instance-overrides'
import { createDefaultSourceMetadata } from './node-defaults'
import { cloneVectorNetwork } from './vector-network'
@@ -240,8 +241,9 @@ export function cloneNodeProps(
source: createDefaultSourceMetadata(),
boundVariables: { ...src.boundVariables },
variableModes: { ...src.variableModes },
- overrides: Object.keys(src.overrides).length > 0 ? structuredClone(src.overrides) : {},
+ instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
componentPropertyAssignments: { ...src.componentPropertyAssignments },
+
componentPropertyValues: { ...src.componentPropertyValues }
}
}
@@ -250,8 +252,9 @@ export function cloneNodeProps(
...(componentId !== null ? { componentId } : {}),
boundVariables: { ...src.boundVariables },
variableModes: { ...src.variableModes },
- overrides: Object.keys(src.overrides).length > 0 ? structuredClone(src.overrides) : {},
+ instanceOverrides: cloneInstanceOverrideState(src.instanceOverrides),
fills: copyOpt(src.fills, (value) => markCopySource(value, copyFills(value))),
+
strokes: copyOpt(src.strokes, (value) => markCopySource(value, copyStrokes(value))),
effects: copyOpt(src.effects, (value) => markCopySource(value, copyEffects(value))),
layoutGrids: copyOpt(src.layoutGrids, copyLayoutGrids),
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 92f94077e..b70a31577 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -1,4 +1,5 @@
/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */
+export * from './instance-overrides'
export * from './images'
export * from './components/properties'
export * from './copy'
diff --git a/packages/scene-graph/src/instance-overrides.test.ts b/packages/scene-graph/src/instance-overrides.test.ts
new file mode 100644
index 000000000..85e68137e
--- /dev/null
+++ b/packages/scene-graph/src/instance-overrides.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ clearInstanceOverrides,
+ cloneInstanceOverrideState,
+ createInstanceOverrideState,
+ deleteInstanceOverride,
+ getInstanceOverride,
+ hasInstanceOverride,
+ setInstanceOverride
+} from './instance-overrides'
+
+describe('instance override state', () => {
+ test('stores self and descendant values structurally', () => {
+ const state = createInstanceOverrideState()
+ setInstanceOverride(state, 'instance', 'instance', 'visible', false)
+ setInstanceOverride(state, 'instance', 'child', 'text', 'Custom')
+ expect(getInstanceOverride(state, 'instance', 'instance', 'visible')).toBe(false)
+ expect(getInstanceOverride(state, 'instance', 'child', 'text')).toBe('Custom')
+ expect(hasInstanceOverride(state, 'instance', 'child', 'text')).toBe(true)
+ })
+
+ test('deletes empty descendant buckets', () => {
+ const state = createInstanceOverrideState()
+ setInstanceOverride(state, 'instance', 'child', 'text')
+ expect(deleteInstanceOverride(state, 'instance', 'child', 'text')).toBe(true)
+ expect(state.descendants.has('child')).toBe(false)
+ })
+
+ test('clones independently and clears', () => {
+ const state = createInstanceOverrideState()
+ setInstanceOverride(state, 'instance', 'child', 'text', 'Custom')
+ const clone = cloneInstanceOverrideState(state)
+ setInstanceOverride(clone, 'instance', 'child', 'text', 'Other')
+ expect(getInstanceOverride(state, 'instance', 'child', 'text')).toBe('Custom')
+ clearInstanceOverrides(state)
+ expect(state.descendants.size).toBe(0)
+ })
+})
diff --git a/packages/scene-graph/src/instance-overrides.ts b/packages/scene-graph/src/instance-overrides.ts
new file mode 100644
index 000000000..87fef49b0
--- /dev/null
+++ b/packages/scene-graph/src/instance-overrides.ts
@@ -0,0 +1,83 @@
+export type InstanceOverrideField = string
+
+export interface InstanceOverrideState {
+ self: Map<InstanceOverrideField, unknown>
+ descendants: Map<string, Map<InstanceOverrideField, unknown>>
+}
+
+export function createInstanceOverrideState(): InstanceOverrideState {
+ return { self: new Map(), descendants: new Map() }
+}
+
+export function cloneInstanceOverrideState(state: InstanceOverrideState): InstanceOverrideState {
+ return {
+ self: new Map([...state.self].map(([field, value]) => [field, structuredClone(value)])),
+ descendants: new Map(
+ [...state.descendants].map(([id, fields]) => [
+ id,
+ new Map([...fields].map(([field, value]) => [field, structuredClone(value)]))
+ ])
+ )
+ }
+}
+
+export function getInstanceOverride(
+ state: InstanceOverrideState,
+ instanceId: string,
+ nodeId: string,
+ field: InstanceOverrideField
+): unknown {
+ return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)
+}
+
+export function hasInstanceOverride(
+ state: InstanceOverrideState,
+ instanceId: string,
+ nodeId: string,
+ field: InstanceOverrideField
+): boolean {
+ return getInstanceOverride(state, instanceId, nodeId, field) !== undefined
+}
+
+export function setInstanceOverride(
+ state: InstanceOverrideState,
+ instanceId: string,
+ nodeId: string,
+ field: InstanceOverrideField,
+ value: unknown = true
+): void {
+ if (nodeId === instanceId) {
+ state.self.set(field, value)
+ return
+ }
+ const fields = state.descendants.get(nodeId) ?? new Map<string, unknown>()
+ fields.set(field, value)
+ state.descendants.set(nodeId, fields)
+}
+
+export function deleteInstanceOverride(
+ state: InstanceOverrideState,
+ instanceId: string,
+ nodeId: string,
+ field: InstanceOverrideField
+): boolean {
+ const fields = nodeId === instanceId ? state.self : state.descendants.get(nodeId)
+ if (!fields?.delete(field)) return false
+ if (nodeId !== instanceId && fields.size === 0) state.descendants.delete(nodeId)
+ return true
+}
+
+export function clearInstanceOverrides(state: InstanceOverrideState): void {
+ state.self.clear()
+ state.descendants.clear()
+}
+
+export function forEachInstanceOverride(
+ state: InstanceOverrideState,
+ callback: (nodeId: string, field: InstanceOverrideField, value: unknown) => void
+): void {
+ for (const [field, value] of state.self) callback('', field, value)
+ for (const [nodeId, fields] of state.descendants) {
+ for (const [field, value] of fields) callback(nodeId, field, value)
+ }
+}
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index 6aadc86f5..1b662f65b 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -1,6 +1,13 @@
import type { SceneGraph, SceneNode } from './'
import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'
import type { NodeCloneMode } from './copy'
+import {
+ clearInstanceOverrides,
+ getInstanceOverride,
+ hasInstanceOverride as hasNodeInstanceOverride,
+ setInstanceOverride,
+ type InstanceOverrideState
+} from './instance-overrides'
export type { NodeCloneMode } from './copy'
@@ -120,7 +127,7 @@ function syncChildren(
graph: SceneGraph,
compParentId: string,
instParentId: string,
- overrides: Record<string, unknown>
+ overrides: InstanceOverrideState
): void {
const compParent = graph.nodes.get(compParentId)
const instParent = graph.nodes.get(instParentId)
@@ -130,7 +137,13 @@ function syncChildren(
for (const childId of instParent.childIds) {
const child = graph.nodes.get(childId)
if (!child) continue
- const sourceComponentId = overrides[`${child.id}:sourceComponentId`]
+ const sourceComponentId = getInstanceOverride(
+ overrides,
+ instParentId,
+ child.id,
+ 'sourceComponentId'
+ )
+
const mappedComponentId =
typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId
if (mappedComponentId) instChildMap.set(mappedComponentId, child)
@@ -154,12 +167,15 @@ function syncChildren(
if (!compChild || !instChild) continue
for (const key of INSTANCE_SYNC_FIELDS) {
- const overrideKey = `${instChild.id}:${key}`
- if (overrideKey in overrides) continue
+ if (hasNodeInstanceOverride(overrides, instParentId, instChild.id, key)) continue
+
copyProp(instChild, compChild, key)
}
- if (compChild.childIds.length > 0 && !(`${instChild.id}:componentId` in overrides)) {
+ if (
+ compChild.childIds.length > 0 &&
+ !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId')
+ ) {
syncChildren(graph, compChildId, instChild.id, overrides)
}
}
@@ -168,8 +184,13 @@ function syncChildren(
instParent.childIds.sort((a, b) => {
const nodeA = graph.nodes.get(a)
const nodeB = graph.nodes.get(b)
- const sourceA = nodeA ? overrides[`${nodeA.id}:sourceComponentId`] : undefined
- const sourceB = nodeB ? overrides[`${nodeB.id}:sourceComponentId`] : undefined
+ const sourceA = nodeA
+ ? getInstanceOverride(overrides, instParentId, nodeA.id, 'sourceComponentId')
+ : undefined
+ const sourceB = nodeB
+ ? getInstanceOverride(overrides, instParentId, nodeB.id, 'sourceComponentId')
+ : undefined
+
const mappedA = typeof sourceA === 'string' ? sourceA : nodeA?.componentId
const mappedB = typeof sourceB === 'string' ? sourceB : nodeB?.componentId
const idxA = mappedA ? compChildOrder.indexOf(mappedA) : -1
@@ -230,9 +251,10 @@ export function swapInstanceComponent(
const previousComponent = instance.componentId ? graph.nodes.get(instance.componentId) : undefined
const updates: Partial<SceneNode> = { componentId }
for (const key of INSTANCE_SYNC_PROPS) {
- if (key in instance.overrides) continue
+ if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key)) continue
copyProp(updates, component, key)
}
+
if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
const childIds = Array.from(instance.childIds)
@@ -247,11 +269,11 @@ export function syncInstances(graph: SceneGraph, componentId: string): void {
for (const instance of getInstances(graph, componentId)) {
for (const key of INSTANCE_SYNC_PROPS) {
- if (key in instance.overrides) continue
+ if (hasNodeInstanceOverride(instance.instanceOverrides, instance.id, instance.id, key))
+ continue
copyProp(instance, component, key)
}
-
- syncChildren(graph, component.id, instance.id, instance.overrides)
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
}
}
@@ -263,7 +285,7 @@ export function detachInstance(graph: SceneGraph, instanceId: string): void {
}
node.type = 'FRAME'
node.componentId = null
- node.overrides = {}
+ clearInstanceOverrides(node.instanceOverrides)
}
export function getMainComponent(graph: SceneGraph, instanceId: string): SceneNode | undefined {
@@ -299,8 +321,7 @@ export function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNo
export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: string): boolean {
const instance = findInstanceAncestor(graph, nodeId)
if (!instance) return false
- const key = nodeId === instance.id ? field : `${nodeId}:${field}`
- return key in instance.overrides
+ return hasNodeInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
}
/*
@@ -308,6 +329,17 @@ export function hasInstanceOverride(graph: SceneGraph, nodeId: string, field: st
* so the .fig exporter knows to write the diff out as a symbol override. A no-op
* for fields outside INSTANCE_SYNC_PROPS or nodes with no INSTANCE ancestor.
*/
+export function recordInstanceOverrideValue(
+ graph: SceneGraph,
+ nodeId: string,
+ field: string,
+ value: unknown
+): void {
+ const instance = findInstanceAncestor(graph, nodeId)
+ if (!instance) return
+ setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field, value)
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
+}
export function recordInstanceOverride(
graph: SceneGraph,
nodeId: string,
@@ -322,9 +354,7 @@ export function recordInstanceOverride(
if (relevant.length === 0) return
- const overrides = { ...instance.overrides }
- for (const field of relevant) {
- overrides[nodeId === instance.id ? field : `${nodeId}:${field}`] = true
- }
- graph.updateNode(instance.id, { overrides })
+ for (const field of relevant)
+ setInstanceOverride(instance.instanceOverrides, instance.id, nodeId, field)
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
}
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index a004c8909..6f1291693 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -1,4 +1,5 @@
import { BLACK, DEFAULT_FONT_FAMILY, DEFAULT_STROKE_MITER_LIMIT } from './constants'
+import { createInstanceOverrideState } from './instance-overrides'
import type { NodeType, SceneNode, SourceMetadata } from './types'
export function createDefaultSourceMetadata(): SourceMetadata {
@@ -140,7 +141,7 @@ export function createDefaultNode(
pointCount: 5,
starInnerRadius: 0.38,
componentId: null,
- overrides: {},
+ instanceOverrides: createInstanceOverrideState(),
componentPropertyDefinitions: [],
componentPropertyReferences: [],
componentPropertyAssignments: {},
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 7c5952ebd..f6d10c1bd 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -1,4 +1,5 @@
import type { CanvasGuide } from './guides'
+import type { InstanceOverrideState } from './instance-overrides'
import type { Color, Matrix, Rect, Vector } from './primitives'
export interface SceneGraphEvents {
@@ -529,7 +530,7 @@ export interface SceneNode {
starInnerRadius: number
componentId: string | null
- overrides: Record<string, unknown>
+ instanceOverrides: InstanceOverrideState
componentPropertyDefinitions: ComponentPropertyDefinition[]
componentPropertyReferences: ComponentPropertyReference[]
componentPropertyAssignments: Record<string, string>
diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts
index 6ba4134a9..cbbbdcabc 100644
--- a/packages/scene-graph/src/variables.ts
+++ b/packages/scene-graph/src/variables.ts
@@ -2,6 +2,7 @@ import { omit, omitBy } from 'es-toolkit/object'
import { BLACK } from './constants'
import type { SceneGraph } from './index'
+import { setInstanceOverride } from './instance-overrides'
import type { Color } from './primitives'
import type { Variable, VariableCollection, VariableType, VariableValue } from './types'
@@ -378,21 +379,19 @@ function markBoundVariablesOverrideOnInstance(graph: SceneGraph, nodeId: string)
const node = graph.nodes.get(nodeId)
if (!node) return
- // If the node IS an INSTANCE itself, set the bare-key override (syncInstances
- // checks `key in instance.overrides` for INSTANCE-self properties)
+ // Mark the field on the canonical structured state.
if (node.type === 'INSTANCE') {
- node.overrides['boundVariables'] = true
+ setInstanceOverride(node.instanceOverrides, node.id, node.id, 'boundVariables')
return
}
- // Otherwise walk up to find an INSTANCE parent and set the child-key override
- // (syncChildren checks `${instChild.id}:${key}` format)
+ // Walk up to the owning instance for descendant fields.
let current = node
while (current.parentId) {
const parent = graph.nodes.get(current.parentId)
if (!parent) break
if (parent.type === 'INSTANCE') {
- parent.overrides[`${nodeId}:boundVariables`] = true
+ setInstanceOverride(parent.instanceOverrides, parent.id, nodeId, 'boundVariables')
break
}
current = parent
diff --git a/tests/engine/io/fig/export/lazy-population.test.ts b/tests/engine/io/fig/export/lazy-population.test.ts
index ceba69948..fdd9e161d 100644
--- a/tests/engine/io/fig/export/lazy-population.test.ts
+++ b/tests/engine/io/fig/export/lazy-population.test.ts
@@ -6,7 +6,7 @@ import {
setLazyFigImportContext
} from '@open-pencil/core/kiwi/fig/lazy-import'
import { cloneSceneGraphForFigExport } from '@open-pencil/core/kiwi/fig/parse/transfer'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
function lazyExportGraph() {
const graph = new SceneGraph()
@@ -38,7 +38,9 @@ function createEditedInstance(
if (!instance) throw new Error(`Could not create instance: ${name}`)
const textId = instance.childIds[0]
graph.updateNode(textId, { text })
- graph.updateNode(instance.id, { overrides: { [`${textId}:text`]: text } })
+ setInstanceOverride(instance.instanceOverrides, instance.id, textId, 'text', text)
+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
+
return { instance, textId }
}
diff --git a/tests/engine/scene-graph/basic/graph.test.ts b/tests/engine/scene-graph/basic/graph.test.ts
index 625d78fed..80b994c1c 100644
--- a/tests/engine/scene-graph/basic/graph.test.ts
+++ b/tests/engine/scene-graph/basic/graph.test.ts
@@ -397,7 +397,12 @@ describe('SceneGraph', () => {
// Override the text on the instance child
graph.updateNode(instLabel.id, { text: 'Custom' })
- instance.overrides[`${instLabel.id}:text`] = 'Custom'
+ graph.updateNode(instance.id, {
+ instanceOverrides: {
+ self: new Map(),
+ descendants: new Map([[instLabel.id, new Map([['text', 'Custom']])]])
+ }
+ })
// Change component
graph.updateNode(graph.getChildren(comp.id)[0].id, { text: 'New Default', fontSize: 20 })
diff --git a/tests/engine/scene-graph/clone/binding-corruption.test.ts b/tests/engine/scene-graph/clone/binding-corruption.test.ts
index cbbd3ef70..5be789ea0 100644
--- a/tests/engine/scene-graph/clone/binding-corruption.test.ts
+++ b/tests/engine/scene-graph/clone/binding-corruption.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/core'
import { collectSubtrees } from '@open-pencil/core/editor/clipboard/subtree-history'
+import { createInstanceOverrideState } from '@open-pencil/scene-graph'
function pageId(graph: SceneGraph): string {
return graph.getPages()[0].id
@@ -77,7 +78,7 @@ describe('cloneTree deep-copies boundVariables, overrides, and styleRuns', () =>
const graph = new SceneGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), {
name: 'Original',
- overrides: { someKey: 'someValue' }
+ instanceOverrides: createInstanceOverrideState()
})
const original = graph.getNode(node.id)
@@ -86,7 +87,7 @@ describe('cloneTree deep-copies boundVariables, overrides, and styleRuns', () =>
(() => {
throw new Error('clone failed')
})()
- expect(clone.overrides).not.toBe(original.overrides)
+ expect(clone.instanceOverrides).not.toBe(original?.instanceOverrides)
})
test('clone.styleRuns is not the same reference as original', () => {
@@ -229,7 +230,7 @@ describe('instance child bindings are independent from component', () => {
})()
const instanceChild = graph.getChildren(instance.id)[0]
- expect(instanceChild.overrides).not.toBe(compChild.overrides)
+ expect(instanceChild.instanceOverrides).not.toBe(compChild.instanceOverrides)
})
test('instance child source.fig is not shared with component child', () => {
diff --git a/tests/engine/scene-graph/clone/node-props.test.ts b/tests/engine/scene-graph/clone/node-props.test.ts
index 02a120585..a068a79ce 100644
--- a/tests/engine/scene-graph/clone/node-props.test.ts
+++ b/tests/engine/scene-graph/clone/node-props.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph, type SceneNode } from '@open-pencil/core'
+import { getInstanceOverride, setInstanceOverride } from '@open-pencil/scene-graph'
+import {
+ createInstanceOverrideState,
+ getInstanceOverride,
+ setInstanceOverride
+} from '@open-pencil/scene-graph'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
function pageId(graph: SceneGraph): string {
@@ -119,20 +125,31 @@ describe('cloneNodeProps deep-copies overrides values', () => {
const instance = graph.createInstance(component.id, page)
if (!instance) throw new Error('instance failed')
const instanceChild = graph.getChildren(instance.id)[0]
- instance.overrides[`${instanceChild.id}:fills`] = [
+ setInstanceOverride(instance.instanceOverrides, instance.id, instanceChild.id, 'fills', [
{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, visible: true, opacity: 1 }
- ]
+ ])
const clone = graph.cloneTree(instance.id, page)
if (!clone) throw new Error('clone failed')
const clonedInstance = graph.getNode(clone.id)
- const overrideKey = `${instanceChild.id}:fills`
- const cloneOverrideVal = clonedInstance.overrides[overrideKey] as Array<{
+ const overrideKey = 'fills'
+ const cloneOverrideVal = getInstanceOverride(
+ clonedInstance.instanceOverrides,
+ clonedInstance.id,
+ instanceChild.id,
+ 'fills'
+ ) as Array<{
color: { r: number }
}>
if (cloneOverrideVal) cloneOverrideVal[0].color.r = 0.5
- const origOverrideVal = instance.overrides[overrideKey] as Array<{ color: { r: number } }>
+ const origOverrideVal = getInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ instanceChild.id,
+ 'fills'
+ ) as Array<{ color: { r: number } }>
+
if (origOverrideVal) expect(origOverrideVal[0].color.r).toBe(0)
})
})
@@ -203,7 +220,7 @@ describe('cloneNodeProps coverage guard', () => {
const node = graph.createNode('RECTANGLE', page, {
name: 'Rich node',
boundVariables: { 'fills/0/color': 'v1' },
- overrides: { nested: { value: true } },
+ instanceOverrides: { self: new Map(), descendants: new Map() },
vectorNetwork: {
vertices: [{ x: 0, y: 0 }],
segments: [{ start: 0, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],