AI-native design editor. Open-source Figma alternative.
fix(scene-graph): deep-copy cloned nodes and validate bindings
Joseph Cumines4bc1698e9359
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7ede62163..eaeb0de22 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,9 +5,14 @@### Changed- Add JSX authoring support for components, component sets, and instances.+- Add type-validated `bindVariable`/`unbindVariable` with event emission and indexed binding format (`fills/N/color` instead of `fills[N]`).+- Add `unbind_variable` MCP tool for removing variable bindings.### Fixes+- Fix clone operations (duplicate, instance creation, clipboard copy) sharing mutable references with the original — editing fills, strokes, variable bindings, overrides, or vector networks on one no longer corrupts the other.+- Fix instance overrides shallow-copied on clone — override values containing objects are now deep-copied.+- Fix stale variable bindings not cleaned up when fills/strokes arrays shrink — any indexed sub-path is now handled, not just `/color`.- Fix tooltips around inspector dropdowns/popovers without breaking floating menu anchoring.- Harden MCP calls with bounded page-tree responses, oversized-result errors, JSON HTTP responses, and stale WebSocket cleanup.- Improve Figma boolean imports by preserving XOR operations as editable exclude nodes and falling back to imported fill geometry when boolean path reconstruction cannot produce a path.diff --git a/packages/core/src/editor/clipboard/subtree-history.ts b/packages/core/src/editor/clipboard/subtree-history.tsindex ce2641dd4..9bfee65ad 100644--- a/packages/core/src/editor/clipboard/subtree-history.ts+++ b/packages/core/src/editor/clipboard/subtree-history.ts@@ -5,7 +5,7 @@ export function collectSubtrees(graph: SceneGraph, rootIds: string[]): SceneNodefunction walk(id: string) {const node = graph.getNode(id)if (!node) return- result.push({ ...node })+ result.push(structuredClone(node))for (const childId of node.childIds) walk(childId)}for (const id of rootIds) walk(id)diff --git a/packages/core/src/editor/variable-bindings.ts b/packages/core/src/editor/variable-bindings.tsindex cb0b1c179..3498d27e8 100644--- a/packages/core/src/editor/variable-bindings.ts+++ b/packages/core/src/editor/variable-bindings.ts@@ -9,13 +9,21 @@ export function createVariableBindingActions(ctx: EditorContext) {ctx.undo.push({label: 'Bind variable',forward: () => {- ctx.graph.bindVariable(nodeId, path, variableId)- ctx.requestRender()+ try {+ ctx.graph.bindVariable(nodeId, path, variableId)+ ctx.requestRender()+ } catch (e) {+ console.warn('Redo bindVariable failed:', e instanceof Error ? e.message : String(e))+ }},inverse: () => {- if (prevVarId) ctx.graph.bindVariable(nodeId, path, prevVarId)- else ctx.graph.unbindVariable(nodeId, path)- ctx.requestRender()+ try {+ if (prevVarId) ctx.graph.bindVariable(nodeId, path, prevVarId)+ else ctx.graph.unbindVariable(nodeId, path)+ ctx.requestRender()+ } catch (e) {+ console.warn('Undo bindVariable failed:', e instanceof Error ? e.message : String(e))+ }}})ctx.requestRender()@@ -30,12 +38,20 @@ export function createVariableBindingActions(ctx: EditorContext) {ctx.undo.push({label: 'Unbind variable',forward: () => {- ctx.graph.unbindVariable(nodeId, path)- ctx.requestRender()+ try {+ ctx.graph.unbindVariable(nodeId, path)+ ctx.requestRender()+ } catch (e) {+ console.warn('Redo unbindVariable failed:', e instanceof Error ? e.message : String(e))+ }},inverse: () => {- ctx.graph.bindVariable(nodeId, path, prevVarId)- ctx.requestRender()+ try {+ ctx.graph.bindVariable(nodeId, path, prevVarId)+ ctx.requestRender()+ } catch (e) {+ console.warn('Undo unbindVariable failed:', e instanceof Error ? e.message : String(e))+ }}})ctx.requestRender()diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.tsindex 43df94e68..d53f1acc4 100644--- a/packages/core/src/figma-api/serialization.ts+++ b/packages/core/src/figma-api/serialization.ts@@ -1,7 +1,38 @@-import type { SceneGraph } from '#core/scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'import type { NodeProxyHost } from './proxy'+function resolveBindings(graph: SceneGraph, node: SceneNode): Record<string, unknown> | undefined {+ const keys = Object.keys(node.boundVariables)+ if (keys.length === 0) return undefined+ const result: Record<string, unknown> = {}+ for (const [field, varId] of Object.entries(node.boundVariables)) {+ const variable = graph.variables.get(varId)+ result[field] = {+ variableId: varId,+ variableName: variable?.name ?? varId,+ resolvedValue: variable ? graph.resolveVariable(varId) : undefined+ }+ }+ return result+}++function appendTextProps(obj: Record<string, unknown>, n: SceneNode): void {+ obj.fontFamily = n.fontFamily+ obj.fontSize = n.fontSize+ obj.fontWeight = n.fontWeight+ obj.italic = n.italic+ obj.textAlignHorizontal = n.textAlignHorizontal+ obj.textAlignVertical = n.textAlignVertical+ obj.textAutoResize = n.textAutoResize+ obj.textDirection = n.textDirection+ if (n.lineHeight != null) obj.lineHeight = n.lineHeight+ if (n.letterSpacing !== 0) obj.letterSpacing = n.letterSpacing+ if (n.textCase !== 'ORIGINAL') obj.textCase = n.textCase+ if (n.textDecoration !== 'NONE') obj.textDecoration = n.textDecoration+ if (n.maxLines != null) obj.maxLines = n.maxLines+}+export function nodeProxyToJSON(graph: SceneGraph,api: NodeProxyHost,@@ -29,25 +60,16 @@ export function nodeProxyToJSON(if (!n.visible) obj.visible = falseif (n.text) obj.characters = n.textif (n.type === 'TEXT') {- obj.fontFamily = n.fontFamily- obj.fontSize = n.fontSize- obj.fontWeight = n.fontWeight- obj.italic = n.italic- obj.textAlignHorizontal = n.textAlignHorizontal- obj.textAlignVertical = n.textAlignVertical- obj.textAutoResize = n.textAutoResize- obj.textDirection = n.textDirection- if (n.lineHeight != null) obj.lineHeight = n.lineHeight- if (n.letterSpacing !== 0) obj.letterSpacing = n.letterSpacing- if (n.textCase !== 'ORIGINAL') obj.textCase = n.textCase- if (n.textDecoration !== 'NONE') obj.textDecoration = n.textDecoration- if (n.maxLines != null) obj.maxLines = n.maxLines+ appendTextProps(obj, n)}if (n.layoutMode !== 'NONE') {obj.layoutMode = n.layoutModeobj.layoutDirection = n.layoutDirectionobj.itemSpacing = n.itemSpacing}+ // Include variable bindings with resolved values+ const bindings = resolveBindings(graph, n)+ if (bindings) obj.boundVariables = bindingsconst children = graph.getChildren(nodeId)if (children.length > 0) {if (maxDepth !== undefined && currentDepth >= maxDepth) {diff --git a/packages/core/src/io/formats/pen/convert.ts b/packages/core/src/io/formats/pen/convert.tsindex 1cd424c9f..276fb0067 100644--- a/packages/core/src/io/formats/pen/convert.ts+++ b/packages/core/src/io/formats/pen/convert.ts@@ -154,7 +154,14 @@ function varName(ref: string): string {export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {if (!isVarRef(val)) returnconst entry = ctx.byName.get(varName(val))- if (entry) node.boundVariables[field] = entry.id+ if (!entry) return+ // Directly sets boundVariables during .pen deserialization — bypasses graph.bindVariable()+ // to avoid spurious node:updated events during bulk loading and to normalize bracket+ // notation (fills[N] → fills/N/color) that the .pen format uses.+ const normalizedField = /^(fills|strokes)\[\d+]$/.test(field)+ ? field.replace(/\[(\d+)]/, '/$1/color')+ : field+ node.boundVariables[normalizedField] = entry.id}export function buildVarContext(diff --git a/packages/core/src/io/formats/pen/read.ts b/packages/core/src/io/formats/pen/read.tsindex 97e95caa9..c1d0fc912 100644--- a/packages/core/src/io/formats/pen/read.ts+++ b/packages/core/src/io/formats/pen/read.ts@@ -434,11 +434,21 @@ function resolveNodeVars(node: SceneNode, graph: SceneGraph, ctx: VarContext): vif (!variable) continueconst modeVal =variable.valuesByMode[ctx.activeModeId] ?? Object.values(variable.valuesByMode)[0]- if (key.startsWith('fills[') && typeof modeVal === 'object' && 'r' in modeVal) {- const idx = Number.parseInt(key.match(/\d+/)?.[0] ?? '0', 10)+ if (+ key.startsWith('fills/') &&+ key.endsWith('/color') &&+ typeof modeVal === 'object' &&+ 'r' in modeVal+ ) {+ const idx = Number.parseInt(key.split('/')[1] ?? '0', 10)if (node.fills[idx]) node.fills[idx].color = modeVal- } else if (key.startsWith('strokes[') && typeof modeVal === 'object' && 'r' in modeVal) {- const idx = Number.parseInt(key.match(/\d+/)?.[0] ?? '0', 10)+ } else if (+ key.startsWith('strokes/') &&+ key.endsWith('/color') &&+ typeof modeVal === 'object' &&+ 'r' in modeVal+ ) {+ const idx = Number.parseInt(key.split('/')[1] ?? '0', 10)if (node.strokes[idx]) node.strokes[idx].color = modeVal}}diff --git a/packages/core/src/kiwi/fig/node-change/convert.ts b/packages/core/src/kiwi/fig/node-change/convert.tsindex c22e0dee4..6cd07e183 100644--- a/packages/core/src/kiwi/fig/node-change/convert.ts+++ b/packages/core/src/kiwi/fig/node-change/convert.ts@@ -54,25 +54,47 @@ import type { GUID } from '#core/types'export { guidToString, stringToGuid } from './guid'export const VARIABLE_BINDING_FIELDS: Record<string, string> = {+ // Corner radiuscornerRadius: 'CORNER_RADIUS',topLeftRadius: 'RECTANGLE_TOP_LEFT_CORNER_RADIUS',topRightRadius: 'RECTANGLE_TOP_RIGHT_CORNER_RADIUS',bottomLeftRadius: 'RECTANGLE_BOTTOM_LEFT_CORNER_RADIUS',bottomRightRadius: 'RECTANGLE_BOTTOM_RIGHT_CORNER_RADIUS',+ // StrokestrokeWeight: 'STROKE_WEIGHT',+ borderTopWeight: 'BORDER_TOP_WEIGHT',+ borderBottomWeight: 'BORDER_BOTTOM_WEIGHT',+ borderLeftWeight: 'BORDER_LEFT_WEIGHT',+ borderRightWeight: 'BORDER_RIGHT_WEIGHT',+ // Auto-layout spacing & paddingitemSpacing: 'STACK_SPACING',paddingLeft: 'STACK_PADDING_LEFT',paddingTop: 'STACK_PADDING_TOP',paddingRight: 'STACK_PADDING_RIGHT',paddingBottom: 'STACK_PADDING_BOTTOM',counterAxisSpacing: 'STACK_COUNTER_SPACING',+ // Grid gaps+ gridRowGap: 'GRID_ROW_GAP',+ gridColumnGap: 'GRID_COLUMN_GAP',+ // Visibility & opacityvisible: 'VISIBLE',opacity: 'OPACITY',+ // Dimensionswidth: 'WIDTH',height: 'HEIGHT',+ minWidth: 'MIN_WIDTH',+ maxWidth: 'MAX_WIDTH',+ minHeight: 'MIN_HEIGHT',+ maxHeight: 'MAX_HEIGHT',+ // Position & rotation+ x: 'X_POSITION',+ y: 'Y_POSITION',+ rotation: 'ROTATION',+ // TextfontSize: 'FONT_SIZE',letterSpacing: 'LETTER_SPACING',- lineHeight: 'LINE_HEIGHT'+ lineHeight: 'LINE_HEIGHT',+ fontFamily: 'FONT_FAMILY'}export const VARIABLE_BINDING_FIELDS_INVERSE: Record<string, string> = Object.fromEntries(diff --git a/packages/core/src/lint/rules/color-contrast.ts b/packages/core/src/lint/rules/color-contrast.tsindex 5e855b34e..7b477e945 100644--- a/packages/core/src/lint/rules/color-contrast.ts+++ b/packages/core/src/lint/rules/color-contrast.ts@@ -10,9 +10,12 @@ export default defineRule({},match: ['TEXT'],check(node, context) {- const textFill = node.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)- const textColor = textFill?.color- if (!textColor) return+ const textFillIndex = node.fills.findIndex((f) => f.type === 'SOLID' && f.visible && f.color)+ const textColor = node.fills[textFillIndex]?.color+ if (textColor == null) return+ // When the fill color is overridden by a variable binding, the effective+ // color depends on the active mode — static contrast checks are unreliable.+ if (node.boundVariables[`fills/${textFillIndex}/color`]) returnlet parent = context.getParent(node)while (parent) {const bg = parent.fills.find((f) => f.type === 'SOLID' && f.visible && f.color)?.colordiff --git a/packages/core/src/lint/rules/no-hardcoded-colors.ts b/packages/core/src/lint/rules/no-hardcoded-colors.tsindex ba3dcedb3..7cb0b49e1 100644--- a/packages/core/src/lint/rules/no-hardcoded-colors.ts+++ b/packages/core/src/lint/rules/no-hardcoded-colors.ts@@ -27,9 +27,11 @@ export default defineRule({}>,field: 'fills' | 'strokes') => {- for (const paint of paints) {- if (paint.type !== 'SOLID' || !paint.visible || !paint.color || node.boundVariables[field])- continue+ for (let i = 0; i < paints.length; i++) {+ const paint = paints[i]+ if (paint.type !== 'SOLID' || !paint.visible || !paint.color) continue+ // Check indexed binding (e.g. "fills/0/color") — the format the renderer actually reads+ if (node.boundVariables[`${field}/${i}/color`]) continuecontext.report({node,message: `Hardcoded ${field === 'fills' ? 'fill' : 'stroke'} color detected`,diff --git a/packages/core/src/scene-graph/copy.ts b/packages/core/src/scene-graph/copy.tsindex 97ec02d79..faca4530f 100644--- a/packages/core/src/scene-graph/copy.ts+++ b/packages/core/src/scene-graph/copy.ts@@ -8,7 +8,19 @@* no shared references between source and copy.*/-import type { Effect, Fill, GeometryPath, GradientStop, Stroke, StyleRun } from './'+import type {+ ArcData,+ ComponentPropertyDefinition,+ Effect,+ FigmaDerivedTextGlyph,+ Fill,+ GeometryPath,+ GradientStop,+ SceneNode,+ Stroke,+ StyleRun+} from './'+import { cloneVectorNetwork } from './vector-network'// --- Individual copy functions ---@@ -17,6 +29,8 @@ export function copyFill(f: Fill): Fill {if (f.gradientStops) copy.gradientStops = f.gradientStops.map(copyGradientStop)if (f.gradientTransform) copy.gradientTransform = { ...f.gradientTransform }if (f.imageTransform) copy.imageTransform = { ...f.imageTransform }+ if (f.patternSpacing) copy.patternSpacing = { ...f.patternSpacing }+ if (f.noiseSize) copy.noiseSize = { ...f.noiseSize }return copy}@@ -80,6 +94,85 @@ export function copyGeometryPaths(paths: GeometryPath[]): GeometryPath[] {// --- Internal helpers ---+/** Copy an optional array: non-empty → mapped, empty → [], undefined → undefined. */+function copyOpt<T, U>(arr: T[] | undefined, fn: (arr: T[]) => U[]): U[] | undefined {+ if (arr === undefined) return undefined+ return arr.length > 0 ? fn(arr) : []+}+function copyGradientStop(gs: GradientStop): GradientStop {return { color: { ...gs.color }, position: gs.position }}++function copySpread<T extends object>(arr: T[] | undefined): T[] {+ return arr?.map((item) => ({ ...item })) ?? []+}++function copyPropertyDefs(+ defs: ComponentPropertyDefinition[] | undefined+): ComponentPropertyDefinition[] {+ return (+ defs?.map((d) => ({+ ...d,+ variantOptions: d.variantOptions ? [...d.variantOptions] : undefined+ })) ?? []+ )+}++function copyGlyphs(glyphs: FigmaDerivedTextGlyph[] | null): FigmaDerivedTextGlyph[] | null {+ return glyphs ? glyphs.map((g) => ({ ...g, commandsBlob: new Uint8Array(g.commandsBlob) })) : null+}++// --- Complex structure copy functions ---+// These replace structuredClone for known types, avoiding its ~24× overhead.++function copyArcData(a: ArcData): ArcData {+ return { startingAngle: a.startingAngle, endingAngle: a.endingAngle, innerRadius: a.innerRadius }+}++// --- Deep-copy clone props ---++/**+ * Build the init props for a deep-copy clone of `src`.+ * Shares logic between SceneGraph.cloneTree and instance child cloning.+ * Explicitly deep-copies all mutable object/array fields that `...rest`+ * would otherwise share by reference. When adding a mutable SceneNode field,+ * add its copy behavior here or document why sharing is intentional.+ */+export function cloneNodeProps(src: SceneNode, componentId: string | null): Partial<SceneNode> {+ const { id: _, parentId: _p, childIds: _c, ...rest } = src+ return {+ ...rest,+ ...(componentId !== null ? { componentId } : {}),+ boundVariables: { ...src.boundVariables },+ overrides: Object.keys(src.overrides).length > 0 ? structuredClone(src.overrides) : {},+ fills: copyOpt(src.fills, copyFills),+ strokes: copyOpt(src.strokes, copyStrokes),+ effects: copyOpt(src.effects, copyEffects),+ styleRuns: copyOpt(src.styleRuns, copyStyleRuns),+ // Source metadata preserves opaque raw Figma payloads; use structuredClone instead of+ // hand-copying partial known shapes and accidentally sharing nested raw Figma data.+ source: structuredClone(src.source),+ dashPattern: copyOpt(src.dashPattern, (a) => [...a]),+ fontVariations: copyOpt(src.fontVariations, (a) => a.map((v) => ({ ...v }))),+ fontFeatures: copyOpt(src.fontFeatures, (a) => a.map((v) => ({ ...v }))),+ textDecorationFills: copyOpt(src.textDecorationFills, copyFills),+ fillGeometry: copyOpt(src.fillGeometry, copyGeometryPaths),+ strokeGeometry: copyOpt(src.strokeGeometry, copyGeometryPaths),+ gridTemplateColumns: copySpread(src.gridTemplateColumns),+ gridTemplateRows: copySpread(src.gridTemplateRows),+ componentPropertyDefinitions: copyPropertyDefs(src.componentPropertyDefinitions),+ symbolLinks: copySpread(src.symbolLinks),+ variantPropSpecs: copySpread(src.variantPropSpecs),+ pluginData: copySpread(src.pluginData),+ pluginRelaunchData: copySpread(src.pluginRelaunchData),+ exportSettings: copySpread(src.exportSettings),+ componentPropertyValues: { ...src.componentPropertyValues },+ figmaDerivedLayout: src.figmaDerivedLayout ? { ...src.figmaDerivedLayout } : null,+ arcData: src.arcData ? copyArcData(src.arcData) : null,+ vectorNetwork: src.vectorNetwork ? cloneVectorNetwork(src.vectorNetwork) : null,+ textPicture: src.textPicture ? new Uint8Array(src.textPicture) : null,+ figmaDerivedTextGlyphs: copyGlyphs(src.figmaDerivedTextGlyphs),+ gridPosition: src.gridPosition ? { ...src.gridPosition } : null+ }+}diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.tsindex e63acdde1..a454125d9 100644--- a/packages/core/src/scene-graph/index.ts+++ b/packages/core/src/scene-graph/index.ts@@ -2,8 +2,10 @@ export * from './snap'export * from './export-scale'export { UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'+import { omit } from 'es-toolkit/object'import { createNanoEvents } from 'nanoevents'+import { cloneNodeProps } from './copy'import * as HitTest from './hit-test'import * as Instances from './instances'import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'@@ -27,6 +29,7 @@ import type {SceneGraphEventHandlers,SceneGraphEvents,SceneNode,+ SourceMetadata,Variable,VariableCollection,VariableType,@@ -35,6 +38,23 @@ import type {export { cloneVectorNetwork, normalizeVectorNetwork, validateVectorNetwork } from './vector-network'+function removeStaleBindings(+ node: SceneNode,+ field: 'fills' | 'strokes',+ changes: Partial<SceneNode>+): void {+ const len = node[field].length+ const stale = Object.keys(node.boundVariables).filter((k) => {+ if (k === field) return true+ if (!k.startsWith(`${field}/`)) return false+ const i = Number.parseInt(k.split('/')[1] ?? '', 10)+ return Number.isNaN(i) || i < 0 || i >= len+ })+ if (stale.length > 0) {+ node.boundVariables = omit(node.boundVariables, stale)+ changes.boundVariables = { ...node.boundVariables }+ }+}let nextLocalID = 1export function generateId(): string {@@ -70,7 +90,6 @@ export class SceneGraph {this.addPage('Page 1')}-addPage(name: string): SceneNode {return this.createNode('CANVAS', this.rootId, { name, width: 0, height: 0 })}@@ -80,15 +99,12 @@ export class SceneGraph {(n) => n.type === 'CANVAS' && (includeInternal || !n.internalOnly))}-getAllNodes(): Iterable<SceneNode> {return this.nodes.values()}-getNode(id: string): SceneNode | undefined {return this.nodes.get(id)}-onNodeEvents(handlers: SceneGraphEventHandlers): () => void {const unbinds = [handlers.created ? this.emitter.on('node:created', handlers.created) : null,@@ -121,21 +137,16 @@ export class SceneGraph {}return count}-// --- Variables ----addVariable(variable: Variable): void {Variables.addVariable(this, variable)}-removeVariable(id: string): void {Variables.removeVariable(this, id)}-addCollection(collection: VariableCollection): void {Variables.addCollection(this, collection)}-createVariable(name: string,type: VariableType,@@ -394,6 +405,8 @@ export class SceneGraph {changes = { ...changes, vectorNetwork: normalizeVectorNetwork(changes.vectorNetwork) }}Object.assign(node, changes)+ if (changes.fills) removeStaleBindings(node, 'fills', changes)+ if (changes.strokes) removeStaleBindings(node, 'strokes', changes)this.emitter.emit('node:updated', id, changes)}@@ -525,8 +538,12 @@ export class SceneGraph {const src = this.nodes.get(sourceId)if (!src) return null- const { id: _srcId, parentId: _srcParent, childIds: _srcChildren, ...rest } = src- const clone = this.createNode(src.type, parentId, { ...rest, ...overrides })+ const props = cloneNodeProps(src, null)+ // Null out Figma source identifiers so the clone is treated as local.+ // `as SourceMetadata` required: cloneNodeProps returns Partial<SceneNode>,+ // so props.source is SourceMetadata | undefined, but we know it's always set.+ props.source = { ...(props.source as SourceMetadata), id: null, orderKey: null }+ const clone = this.createNode(src.type, parentId, { ...props, ...overrides })for (const childId of src.childIds) {this.cloneTree(childId, clone.id)@@ -571,7 +588,6 @@ export class SceneGraph {const id = parentId ?? this.rootIdconst parent = this.nodes.get(id)if (!parent) return []-const result: Array<{ node: SceneNode; depth: number }> = []for (const childId of parent.childIds) {const child = this.nodes.get(childId)diff --git a/packages/core/src/scene-graph/instances.ts b/packages/core/src/scene-graph/instances.tsindex 8b8b11901..c11709aec 100644--- a/packages/core/src/scene-graph/instances.ts+++ b/packages/core/src/scene-graph/instances.ts@@ -1,5 +1,5 @@import type { SceneGraph, SceneNode } from './'-import { copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'+import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from './copy'const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = ['width',@@ -37,7 +37,8 @@ const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = ['borderTopWeight','borderRightWeight','borderBottomWeight',- 'borderLeftWeight'+ 'borderLeftWeight',+ 'boundVariables']function setSceneProp<K extends keyof SceneNode>(@@ -61,6 +62,12 @@ function copyProp(setSceneProp(target, key, copyEffects(source.effects))} else if (key === 'styleRuns') {setSceneProp(target, key, copyStyleRuns(source.styleRuns))+ } else if (key === 'boundVariables') {+ // Shallow copy the binding map — values are variable IDs (strings), not objects+ setSceneProp(target, key, { ...source.boundVariables })+ } else if (key === 'gridPosition') {+ // Shallow copy the grid position object — all fields are primitives+ setSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)} else {const value = source[key]setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)@@ -79,11 +86,7 @@ function cloneChildrenWithMapping(const src = graph.nodes.get(childId)if (!src) continue- const { id: _, parentId: _p, childIds: _c, ...rest } = src- const clone = graph.createNode(src.type, destParentId, {- ...rest,- componentId: childId- })+ const clone = graph.createNode(src.type, destParentId, cloneNodeProps(src, childId))if (src.childIds.length > 0) {cloneChildrenWithMapping(graph, childId, clone.id)@@ -111,11 +114,7 @@ function syncChildren(if (!instChildMap.has(compChildId)) {const src = graph.nodes.get(compChildId)if (!src) continue- const { id: _, parentId: _p, childIds: _c, ...rest } = src- const clone = graph.createNode(src.type, instParentId, {- ...rest,- componentId: compChildId- })+ const clone = graph.createNode(src.type, instParentId, cloneNodeProps(src, compChildId))if (src.childIds.length > 0) {cloneChildrenWithMapping(graph, compChildId, clone.id)}diff --git a/packages/core/src/scene-graph/variables.ts b/packages/core/src/scene-graph/variables.tsindex 4c061a67b..2b60fdc9b 100644--- a/packages/core/src/scene-graph/variables.ts+++ b/packages/core/src/scene-graph/variables.ts@@ -23,10 +23,14 @@ export function removeVariable(graph: SceneGraph, id: string): void {collection.variableIds = collection.variableIds.filter((vid) => vid !== id)}for (const node of graph.nodes.values()) {+ const hadBinding = Object.values(node.boundVariables).includes(id)+ if (!hadBinding) continuenode.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<string,string>+ graph.emitter.emit('node:updated', node.id, { boundVariables: { ...node.boundVariables } })+ markBoundVariablesOverrideOnInstance(graph, node.id)}}@@ -223,6 +227,44 @@ export function getVariablesByType(graph: SceneGraph, type: VariableType): Variareturn [...graph.variables.values()].filter((v) => v.type === type)}+const SCALAR_BINDING_FIELDS: ReadonlySet<string> = new Set([+ 'opacity',+ 'width',+ 'height',+ 'cornerRadius',+ 'fontSize',+ 'letterSpacing',+ 'lineHeight',+ 'itemSpacing',+ 'strokeWeight',+ 'paddingLeft',+ 'paddingRight',+ 'paddingTop',+ 'paddingBottom',+ 'counterAxisSpacing',+ 'topLeftRadius',+ 'topRightRadius',+ 'bottomLeftRadius',+ 'bottomRightRadius',+ 'rotation',+ 'x',+ 'y',+ 'minWidth',+ 'maxWidth',+ 'minHeight',+ 'maxHeight',+ 'borderTopWeight',+ 'borderBottomWeight',+ 'borderLeftWeight',+ 'borderRightWeight',+ 'gridRowGap',+ 'gridColumnGap'+])++const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['fontFamily'])++const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])+export function bindVariable(graph: SceneGraph,nodeId: string,@@ -230,10 +272,91 @@ export function bindVariable(variableId: string): void {const node = graph.nodes.get(nodeId)- if (node) node.boundVariables[field] = variableId+ if (!node) return++ // Validate variable exists+ const variable = graph.variables.get(variableId)+ if (!variable) {+ throw new Error(`Variable "${variableId}" not found`)+ }++ // Color fields require COLOR variable type+ const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/)+ if (colorFieldMatch) {+ if (variable.type !== 'COLOR') {+ throw new Error(`Cannot bind ${variable.type} variable to color field "${field}"`)+ }+ // Validate index is within current array bounds+ const arrayKey = colorFieldMatch[1] as 'fills' | 'strokes'+ const index = Number.parseInt(colorFieldMatch[2], 10)+ const currentLength = (node[arrayKey] as unknown[] | undefined)?.length ?? 0+ if (index >= currentLength) {+ throw new Error(`Index ${index} out of range for ${arrayKey} (length ${currentLength})`)+ }+ // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding+ const topLevelKey = colorFieldMatch[1]+ if (topLevelKey in node.boundVariables) {+ node.boundVariables = omit(node.boundVariables, [topLevelKey])+ }+ }++ if (SCALAR_BINDING_FIELDS.has(field) && variable.type !== 'FLOAT') {+ throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`)+ }++ if (STRING_BINDING_FIELDS.has(field) && variable.type !== 'STRING') {+ throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`)+ }++ if (BOOLEAN_BINDING_FIELDS.has(field) && variable.type !== 'BOOLEAN') {+ throw new Error(`Cannot bind ${variable.type} variable to boolean field "${field}"`)+ }++ const isKnownField =+ SCALAR_BINDING_FIELDS.has(field) ||+ STRING_BINDING_FIELDS.has(field) ||+ BOOLEAN_BINDING_FIELDS.has(field) ||+ colorFieldMatch++ if (!isKnownField) {+ throw new Error(`Unknown binding field "${field}"`)+ }++ node.boundVariables = { ...node.boundVariables, [field]: variableId }+ graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })+ markBoundVariablesOverrideOnInstance(graph, nodeId)}export function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {const node = graph.nodes.get(nodeId)- if (node) node.boundVariables = omit(node.boundVariables, [field])+ if (!node) return+ if (!(field in node.boundVariables)) return+ node.boundVariables = omit(node.boundVariables, [field])+ graph.emitter.emit('node:updated', nodeId, { boundVariables: { ...node.boundVariables } })+ markBoundVariablesOverrideOnInstance(graph, nodeId)+}++function markBoundVariablesOverrideOnInstance(graph: SceneGraph, nodeId: string): void {+ 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)+ if (node.type === 'INSTANCE') {+ node.overrides['boundVariables'] = true+ return+ }++ // Otherwise walk up to find an INSTANCE parent and set the child-key override+ // (syncChildren checks `${instChild.id}:${key}` format)+ 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+ break+ }+ current = parent+ }}diff --git a/packages/core/src/tools/analyze/colors.ts b/packages/core/src/tools/analyze/colors.tsindex 60ce0e9f8..3e51e21ef 100644--- a/packages/core/src/tools/analyze/colors.ts+++ b/packages/core/src/tools/analyze/colors.ts@@ -48,18 +48,20 @@ export const analyzeColors = defineTool({if (!raw) return falseconst boundVars = raw.boundVariables- for (const fill of raw.fills) {+ for (let i = 0; i < raw.fills.length; i++) {+ const fill = raw.fills[i]if (fill.type === 'SOLID' && fill.visible) {- trackColor(colorMap, fill.color, boundVars['fills'] ? String(boundVars['fills']) : null)+ const varId = boundVars[`fills/${i}/color`]+ const variable = varId ? figma.graph.variables.get(varId) : undefined+ trackColor(colorMap, fill.color, variable?.name ?? null)}}- for (const stroke of raw.strokes) {+ for (let i = 0; i < raw.strokes.length; i++) {+ const stroke = raw.strokes[i]if (stroke.visible) {- trackColor(- colorMap,- stroke.color,- boundVars['strokes'] ? String(boundVars['strokes']) : null- )+ const varId = boundVars[`strokes/${i}/color`]+ const variable = varId ? figma.graph.variables.get(varId) : undefined+ trackColor(colorMap, stroke.color, variable?.name ?? null)}}return falsediff --git a/packages/core/src/tools/describe/summaries.ts b/packages/core/src/tools/describe/summaries.tsindex 403e052fd..e846126e5 100644--- a/packages/core/src/tools/describe/summaries.ts+++ b/packages/core/src/tools/describe/summaries.ts@@ -1,10 +1,27 @@import { colorToHex } from '#core/color'-import type { SceneNode } from '#core/scene-graph'+import type { SceneGraph, SceneNode } from '#core/scene-graph'-export function describeVisual(node: SceneNode): string {+function boundFillSuffix(node: SceneNode, fillIndex: number, graph?: SceneGraph): string {+ const varId = node.boundVariables[`fills/${fillIndex}/color`]+ if (!varId) return ''+ if (graph) {+ const variable = graph.variables.get(varId)+ if (variable) return ` (bound: ${variable.name})`+ }+ return ' (bound: variable)'+}++function findSolidFillIndex(node: SceneNode): number {+ return node.fills.findIndex((candidate) => candidate.type === 'SOLID' && candidate.visible)+}++export function describeVisual(node: SceneNode, graph?: SceneGraph): string {const parts: string[] = []- const fill = node.fills.find((candidate) => candidate.type === 'SOLID' && candidate.visible)- if (fill) parts.push(`${colorToHex(fill.color)} fill`)+ const fillIndex = findSolidFillIndex(node)+ if (fillIndex !== -1) {+ const fill = node.fills[fillIndex]+ parts.push(`${colorToHex(fill.color)}${boundFillSuffix(node, fillIndex, graph)} fill`)+ }if (node.strokes.length > 0 && node.strokes[0]?.visible) parts.push('bordered')if (node.cornerRadius > 0) parts.push('rounded')if (node.clipsContent) parts.push('clipped')@@ -58,23 +75,29 @@ export function describeLayout(node: SceneNode): string | null {return parts.join(', ')}-export function summarizeContainer(node: SceneNode): string {+export function summarizeContainer(node: SceneNode, graph?: SceneGraph): string {const parts = [`${node.width}×${node.height}`]- const fill = node.fills.find((candidate) => candidate.type === 'SOLID' && candidate.visible)- if (fill) parts.push(colorToHex(fill.color))+ const fillIndex = findSolidFillIndex(node)+ if (fillIndex !== -1) {+ const fill = node.fills[fillIndex]+ parts.push(`${colorToHex(fill.color)}${boundFillSuffix(node, fillIndex, graph)}`)+ }if (node.cornerRadius > 0) parts.push('rounded')const layout = describeLayout(node)if (layout) parts.push(layout)return parts.join(', ')}-export function summarizeText(node: SceneNode): string {+export function summarizeText(node: SceneNode, graph?: SceneGraph): string {const text = node.text.slice(0, 60)let summary = `"${text}" ${node.fontSize}px ${node.fontFamily}`if (node.fontWeight >= 700) summary += ' bold'else if (node.fontWeight >= 500) summary += ' medium'- const textColor = node.fills.find((fill) => fill.type === 'SOLID' && fill.visible)- if (textColor) summary += `, ${colorToHex(textColor.color)}`+ const textColorIndex = findSolidFillIndex(node)+ if (textColorIndex !== -1) {+ const textColor = node.fills[textColorIndex]+ summary += `, ${colorToHex(textColor.color)}${boundFillSuffix(node, textColorIndex, graph)}`+ }if (node.textAutoResize === 'HEIGHT') summary += ', wraps'else if (node.textAutoResize === 'NONE') summary += ', fixed-size'if (node.maxLines !== null && node.maxLines > 0) summary += `, max ${node.maxLines} lines`diff --git a/packages/core/src/tools/describe/tree.ts b/packages/core/src/tools/describe/tree.tsindex 059e89ee7..50f78f34c 100644--- a/packages/core/src/tools/describe/tree.ts+++ b/packages/core/src/tools/describe/tree.ts@@ -21,7 +21,8 @@ function describeChild(gridSize: number): ChildDescription {const role = detectRole(node)- const summary = node.type === 'TEXT' ? summarizeText(node) : summarizeContainer(node)+ const summary =+ node.type === 'TEXT' ? summarizeText(node, graph) : summarizeContainer(node, graph)const result: ChildDescription = { role, name: node.name, summary, id: node.id }const issues = detectIssues(node, gridSize, graph)@@ -49,7 +50,7 @@ export function describeOneNode(if (!raw) return { id: nodeId, error: `Node "${nodeId}" not found` }const role = detectRole(raw)- const visual = describeVisual(raw)+ const visual = describeVisual(raw, figma.graph)const layout = describeLayout(raw)const issues = detectIssues(raw, gridSize, figma.graph)diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex 05ba78fc2..fd0435bd8 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -75,7 +75,8 @@ import {getVariable,listCollections,listVariables,- setVariable+ setVariable,+ unbindVariable} from './variables'import {booleanExclude,@@ -160,6 +161,7 @@ export const EXTENDED_TOOLS: ToolDef[] = [setVariable,deleteVariable,bindVariable,+ unbindVariable,getCollection,createCollection,deleteCollection,diff --git a/packages/core/src/tools/variables.ts b/packages/core/src/tools/variables.tsindex 4226c87dc..11c806a96 100644--- a/packages/core/src/tools/variables.ts+++ b/packages/core/src/tools/variables.ts@@ -1,4 +1,5 @@export { bindVariable } from './variables/bindings'+export { unbindVariable } from './variables/unbind'export {createCollection,deleteCollection,diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.tsindex c73204452..0b25c813d 100644--- a/packages/core/src/tools/variables/bindings.ts+++ b/packages/core/src/tools/variables/bindings.ts@@ -3,12 +3,21 @@ import { defineTool } from '#core/tools/schema'export const bindVariable = defineTool({name: 'bind_variable',mutates: true,- description: 'Bind a variable to a node property (fills, strokes, opacity, width, height, etc.).',+ description:+ 'Bind a variable to a node property. For fills/strokes color bindings use indexed format like "fills/0/color".',params: {node_id: { type: 'string', description: 'Node ID', required: true },field: {type: 'string',- description: 'Property field (fills, strokes, opacity, width, height, etc.)',+ description:+ 'Property field path. For fills/strokes use indexed format: "fills/0/color", "strokes/0/color". ' ++ 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' ++ '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' ++ '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' ++ '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' ++ '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' ++ '"gridRowGap", "gridColumnGap". ' ++ 'For STRING: "fontFamily". For BOOLEAN: "visible".',required: true},variable_id: { type: 'string', description: 'Variable ID', required: true }@@ -18,7 +27,11 @@ export const bindVariable = defineTool({if (!node) return { error: `Node "${args.node_id}" not found` }const variable = figma.getVariableById(args.variable_id)if (!variable) return { error: `Variable "${args.variable_id}" not found` }- figma.bindVariable(args.node_id, args.field, args.variable_id)+ try {+ figma.bindVariable(args.node_id, args.field, args.variable_id)+ } catch (err) {+ return { error: err instanceof Error ? err.message : String(err) }+ }return { node_id: args.node_id, field: args.field, variable_id: args.variable_id }}})diff --git a/packages/core/src/tools/variables/collections.ts b/packages/core/src/tools/variables/collections.tsindex 3ec5660b9..30b206b29 100644--- a/packages/core/src/tools/variables/collections.ts+++ b/packages/core/src/tools/variables/collections.ts@@ -19,7 +19,10 @@ export const getCollection = defineTool({execute: (figma, { id }) => {const collection = figma.getVariableCollectionById(id)if (!collection) return { error: `Collection "${id}" not found` }- return collection+ return {+ ...collection,+ activeModeId: figma.graph.getActiveModeId(id)+ }}})diff --git a/packages/core/src/tools/variables/unbind.ts b/packages/core/src/tools/variables/unbind.tsnew file mode 100644index 000000000..a22ba350c--- /dev/null+++ b/packages/core/src/tools/variables/unbind.ts@@ -0,0 +1,34 @@+import { defineTool } from '#core/tools/schema'++export const unbindVariable = defineTool({+ name: 'unbind_variable',+ mutates: true,+ description: 'Remove a variable binding from a node property.',+ params: {+ node_id: { type: 'string', description: 'Node ID', required: true },+ field: {+ type: 'string',+ description:+ 'Property field path to unbind. For fills/strokes use indexed format: "fills/0/color", "strokes/0/color". ' ++ 'For FLOAT scalars: "opacity", "width", "height", "cornerRadius", "fontSize", "letterSpacing", ' ++ '"lineHeight", "itemSpacing", "strokeWeight", "paddingLeft/Right/Top/Bottom", "counterAxisSpacing", ' ++ '"rotation", "x", "y", "minWidth", "maxWidth", "minHeight", "maxHeight", ' ++ '"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' ++ '"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' ++ '"gridRowGap", "gridColumnGap". ' ++ 'For STRING: "fontFamily". For BOOLEAN: "visible".',+ required: true+ }+ },+ execute: (figma, args) => {+ // Access raw scene node for boundVariables (not exposed on the proxy)+ const rawNode = figma.graph.getNode(args.node_id)+ if (!rawNode) return { error: `Node "${args.node_id}" not found` }+ const boundValue = rawNode.boundVariables[args.field]+ if (!boundValue) {+ return { error: `No binding found for field "${args.field}" on node "${args.node_id}"` }+ }+ figma.unbindVariable(args.node_id, args.field)+ return { unbound: true, node_id: args.node_id, field: args.field }+ }+})diff --git a/tests/engine/editor/variable-bindings-undo.test.ts b/tests/engine/editor/variable-bindings-undo.test.tsnew file mode 100644index 000000000..7eb0141bb--- /dev/null+++ b/tests/engine/editor/variable-bindings-undo.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++function pageId(editor: ReturnType<typeof createEditor>): string {+ return editor.graph.getPages()[0].id+}++function setupColorVar(editor: ReturnType<typeof createEditor>, id: string): void {+ editor.graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ editor.graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+}++describe('variable-bindings undo resilience', () => {+ test('bindVariable undo restores previous binding when variable still exists', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ setupColorVar(editor, 'v2')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')++ editor.bindVariable(node.id, 'fills/0/color', 'v2')+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v2')++ editor.undo.undo()+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')+ })++ test('bindVariable undo gracefully degrades when variable was deleted', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')++ // Delete the variable after binding — binding entry remains on the node+ editor.graph.removeVariable('v1')++ editor.undo.undo()+ // Undo should not throw — graceful degradation: binding is simply not restored+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('unbindVariable undo gracefully degrades when variable was deleted', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ editor.unbindVariable(node.id, 'fills/0/color')+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()++ // Delete the variable after unbinding — the undo inverse will try to rebind it+ editor.graph.removeVariable('v1')++ editor.undo.undo()+ // Undo should not throw — graceful degradation: binding is simply not restored+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('bindVariable undo with prev binding restore when variable still exists', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0, g: 1, b: 0, a: 1 }, visible: true, opacity: 1 }+ ]+ })++ // Pre-bind the second fill+ editor.bindVariable(node.id, 'fills/1/color', 'v1')+ expect(editor.graph.getNode(node.id).boundVariables['fills/1/color']).toBe('v1')++ // Bind the first fill (no previous binding)+ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')++ editor.undo.undo()+ // Should restore the pre-existing binding on fills/1+ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ expect(editor.graph.getNode(node.id).boundVariables['fills/1/color']).toBe('v1')+ })++ test('bindVariable redo gracefully degrades when variable was deleted', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ editor.undo.undo()++ editor.graph.removeVariable('v1')++ editor.undo.redo()++ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('unbindVariable redo gracefully degrades when variable was deleted', () => {+ const editor = createEditor()+ setupColorVar(editor, 'v1')+ const page = pageId(editor)+ const node = editor.graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ editor.bindVariable(node.id, 'fills/0/color', 'v1')+ editor.unbindVariable(node.id, 'fills/0/color')+ editor.undo.undo()++ editor.graph.removeVariable('v1')++ editor.undo.redo()++ expect(editor.graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })+})diff --git a/tests/engine/io/subgraph.test.ts b/tests/engine/io/subgraph.test.tsindex 7bbfe3f86..7e3c5c499 100644--- a/tests/engine/io/subgraph.test.ts+++ b/tests/engine/io/subgraph.test.ts@@ -113,5 +113,5 @@ describe('export subgraph extraction', () => {expect(input?.symbolData?.symbolOverrides?.length).toBe(9)expect(input?.symbolData?.uniformScaleFactor).toBeCloseTo(0.8908441662788391)expect(lists?.symbolData?.symbolOverrides?.length).toBe(5)- })+ }, 15000)})diff --git a/tests/engine/scene-graph/basic/variables.test.ts b/tests/engine/scene-graph/basic/variables.test.tsindex 7986ad127..d5520b57a 100644--- a/tests/engine/scene-graph/basic/variables.test.ts+++ b/tests/engine/scene-graph/basic/variables.test.ts@@ -181,7 +181,27 @@ describe('Variables', () => {test('bind and unbind variable to node', () => {const graph = new SceneGraph()- const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })++ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })graph.bindVariable(node.id, 'fills/0/color', 'v1')expect(node.boundVariables['fills/0/color']).toBe('v1')@@ -209,7 +229,10 @@ describe('Variables', () => {hiddenFromPublishing: false})- const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })graph.bindVariable(node.id, 'fills/0/color', 'v1')expect(node.boundVariables['fills/0/color']).toBe('v1')diff --git a/tests/engine/scene-graph/clone-binding-corruption.test.ts b/tests/engine/scene-graph/clone-binding-corruption.test.tsnew file mode 100644index 000000000..cbbd3ef70--- /dev/null+++ b/tests/engine/scene-graph/clone-binding-corruption.test.ts@@ -0,0 +1,394 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/core'+import { collectSubtrees } from '@open-pencil/core/editor/clipboard/subtree-history'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++function setupColorVars(graph: SceneGraph, ...ids: string[]): void {+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ for (const id of ids) {+ graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ }+}++// ─── cloneTree deep-copies boundVariables, overrides, styleRuns ─────────────++describe('cloneTree deep-copies boundVariables, overrides, and styleRuns', () => {+ test('clone.boundVariables is not the same reference as original', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const original = graph.getNode(node.id)++ const clone =+ graph.cloneTree(node.id, pageId(graph)) ??+ (() => {+ throw new Error('clone failed')+ })()+ expect(clone).not.toBeNull()+ expect(clone.boundVariables).not.toBe(original.boundVariables)+ })++ test('binding on clone does not corrupt original node', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const original = graph.getNode(node.id)++ const clone =+ graph.cloneTree(node.id, pageId(graph)) ??+ (() => {+ throw new Error('clone failed')+ })()+ graph.bindVariable(clone.id, 'fills/0/color', 'v2')++ // Original must still have v1+ expect(original.boundVariables['fills/0/color']).toBe('v1')+ // Clone must have v2+ expect(clone.boundVariables['fills/0/color']).toBe('v2')+ })++ test('clone.overrides is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ overrides: { someKey: 'someValue' }+ })+ const original = graph.getNode(node.id)++ const clone =+ graph.cloneTree(node.id, pageId(graph)) ??+ (() => {+ throw new Error('clone failed')+ })()+ expect(clone.overrides).not.toBe(original.overrides)+ })++ test('clone.styleRuns is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', pageId(graph), {+ name: 'Original',+ text: 'Hello',+ fontSize: 14,+ fontFamily: 'Inter',+ styleRuns: [{ start: 0, length: 5, style: { fontWeight: 700 } }]+ })+ const original = graph.getNode(node.id)++ const clone =+ graph.cloneTree(node.id, pageId(graph)) ??+ (() => {+ throw new Error('clone failed')+ })()+ expect(clone.styleRuns).not.toBe(original.styleRuns)+ // Deep check: styleRuns elements must also be independent+ if (original.styleRuns.length > 0 && clone.styleRuns.length > 0) {+ expect(clone.styleRuns[0]).not.toBe(original.styleRuns[0])+ }+ })++ test('clone.fills is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })+ const original = graph.getNode(node.id)++ const clone =+ graph.cloneTree(node.id, pageId(graph)) ??+ (() => {+ throw new Error('clone failed')+ })()+ expect(clone.fills).not.toBe(original.fills)+ // Fill elements should also be independent+ if (original.fills.length > 0 && clone.fills.length > 0) {+ expect(clone.fills[0]).not.toBe(original.fills[0])+ }+ })+})++// ─── instance child binding independence ──────────────────────────────────++describe('instance child bindings are independent from component', () => {+ test('instance child boundVariables is not shared with component child', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ // Create component with child+ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })++ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ // Instance child's boundVariables must be independent+ const componentChild = graph.getNode(child.id)?.boundVariables+ expect(componentChild).toBeDefined()+ expect(instanceChild.boundVariables).not.toBe(componentChild)+ })++ test('binding on instance child does not corrupt component child', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })++ graph.bindVariable(child.id, 'fills/0/color', 'v1')+ const compChild = graph.getNode(child.id)++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ // Bind different variable on instance child+ graph.bindVariable(instanceChild.id, 'fills/0/color', 'v2')++ // Component child must still have v1+ expect(compChild.boundVariables['fills/0/color']).toBe('v1')+ // Instance child must have v2+ expect(instanceChild.boundVariables['fills/0/color']).toBe('v2')+ })++ test('instance child overrides is not shared with component child', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40+ })++ const compChild = graph.getNode(child.id)++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ expect(instanceChild.overrides).not.toBe(compChild.overrides)+ })++ test('instance child source.fig is not shared with component child', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40+ })++ // Set source.fig on component child+ graph.updateNode(child.id, {+ source: {+ ...graph.getNode(child.id).source,+ format: 'fig',+ fig: {+ rawSize: { x: 100, y: 40 },+ rawTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },+ rawNodeFields: { visible: true, opacity: 1 },+ layout: null,+ symbolOverrides: [],+ componentPropAssignments: [],+ derivedSymbolData: [],+ derivedSymbolDataLayoutVersion: null,+ uniformScaleFactor: null+ }+ }+ })++ const compChild = graph.getNode(child.id)+ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ // source.fig must be deep-copied, not shared+ if (compChild.source.fig && instanceChild.source.fig) {+ expect(instanceChild.source.fig).not.toBe(compChild.source.fig)+ // Mutating instance source.fig must not affect component+ instanceChild.source.fig.rawSize = { x: 999, y: 999 }+ expect(compChild.source.fig.rawSize).toEqual({ x: 100, y: 40 })+ }+ })+})++// ─── set_fill/set_stroke clean up stale bindings ─────────────────────────++describe('set_fill/set_stroke clean up stale bindings', () => {+ test('set_fill removes fills/N/color bindings that are out of range', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ // Bind both fills+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ graph.bindVariable(node.id, 'fills/1/color', 'v2')++ const n = graph.getNode(node.id)+ expect(n.boundVariables['fills/0/color']).toBe('v1')+ expect(n.boundVariables['fills/1/color']).toBe('v2')++ // Replace fills with an empty array via updateNode (same path tools use)+ graph.updateNode(node.id, { fills: [] })++ // fills/1/color binding must be removed (index 1 > length 0)+ expect(n.boundVariables['fills/1/color']).toBeUndefined()+ })++ test('set_fill removes top-level fills binding (dead data)', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ const n = graph.getNode(node.id)++ // Set a top-level 'fills' binding (dead data — renderer never reads this)+ n.boundVariables['fills'] = 'v1'++ // Replace fills via updateNode (same path tools use)+ graph.updateNode(node.id, {+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ // Top-level 'fills' binding should be cleaned up+ expect(n.boundVariables['fills']).toBeUndefined()+ })+})++// ─── collectSubtrees uses structuredClone ──────────────────────────────────++describe('collectSubtrees deep-copies nodes', () => {+ test('collectSubtrees does not share boundVariables reference', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const original = graph.getNode(node.id)++ const collected = collectSubtrees(graph, [node.id])+ expect(collected.length).toBe(1)+ expect(collected[0].boundVariables).not.toBe(original.boundVariables)+ })+})++// ─── undo of binding on clone restores original correctly ──────────────────++describe('undo of binding on clone restores original state', () => {+ test('bind on clone, then undo restores original binding state', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const clone = graph.cloneTree(node.id, pageId(graph))+ graph.bindVariable(clone.id, 'fills/0/color', 'v2')+ expect(graph.getNode(clone.id).boundVariables['fills/0/color']).toBe('v2')+ // Original should be unaffected+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')+ })+})++// ─── variable deletion and re-clone safety ──────────────────────────────++describe('variable deletion and re-clone safety', () => {+ test('deleting a variable removes bindings and re-cloning works safely', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Original',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const clone1 = graph.cloneTree(node.id, pageId(graph))+ expect(graph.getNode(clone1.id).boundVariables['fills/0/color']).toBe('v1')+ // Delete the variable — this cleans up bindings on all nodes+ graph.removeVariable('v1')+ // Bindings are removed from both original and clone+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ expect(graph.getNode(clone1.id).boundVariables['fills/0/color']).toBeUndefined()+ // Clone again — should not crash, clone has no stale binding+ const clone2 = graph.cloneTree(node.id, pageId(graph))+ expect(clone2).toBeDefined()+ expect(graph.getNode(clone2.id).boundVariables['fills/0/color']).toBeUndefined()+ })+})diff --git a/tests/engine/scene-graph/clone-node-props.test.ts b/tests/engine/scene-graph/clone-node-props.test.tsnew file mode 100644index 000000000..05e248697--- /dev/null+++ b/tests/engine/scene-graph/clone-node-props.test.ts@@ -0,0 +1,212 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph, type SceneNode } from '@open-pencil/core'+import { cloneNodeProps } from '@open-pencil/core/scene-graph/copy'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++describe('cloneNodeProps deep-copies vectorNetwork', () => {+ test('cloned vectorNetwork is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Vector',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 0 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: [{ windingRule: 'NONZERO', loops: [[0, 1]] }]+ }+ })+ const original = graph.getNode(node.id)+ const clone = graph.cloneTree(node.id, pageId(graph))+ const clonedNode = graph.getNode(clone.id)++ expect(clonedNode.vectorNetwork).not.toBe(original.vectorNetwork)+ if (original.vectorNetwork && clonedNode.vectorNetwork) {+ expect(clonedNode.vectorNetwork.vertices).not.toBe(original.vectorNetwork.vertices)+ expect(clonedNode.vectorNetwork.segments).not.toBe(original.vectorNetwork.segments)+ expect(clonedNode.vectorNetwork.regions).not.toBe(original.vectorNetwork.regions)+ }+ })++ test('mutating clone vectorNetwork does not affect original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Vector',+ vectorNetwork: {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 50 }+ ],+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: []+ }+ })+ const original = graph.getNode(node.id)+ const clone = graph.cloneTree(node.id, pageId(graph))+ const clonedNode = graph.getNode(clone.id)++ if (clonedNode.vectorNetwork) clonedNode.vectorNetwork.vertices[0].x = 999+ expect(original.vectorNetwork?.vertices[0].x).toBe(0)+ })+})++describe('cloneNodeProps deep-copies textPicture and figmaDerivedTextGlyphs', () => {+ test('cloned textPicture is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', pageId(graph), {+ name: 'Text',+ text: 'Hello',+ fontSize: 14,+ fontFamily: 'Inter',+ textPicture: new Uint8Array([1, 2, 3, 4])+ })+ const original = graph.getNode(node.id)+ const clone = graph.cloneTree(node.id, pageId(graph))+ const clonedNode = graph.getNode(clone.id)++ expect(clonedNode.textPicture).not.toBe(original.textPicture)+ if (original.textPicture && clonedNode.textPicture) {+ clonedNode.textPicture[0] = 99+ expect(original.textPicture[0]).toBe(1)+ }+ })++ test('cloned figmaDerivedTextGlyphs is not the same reference as original', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('TEXT', pageId(graph), {+ name: 'Text',+ text: 'Hi',+ fontSize: 14,+ fontFamily: 'Inter',+ figmaDerivedTextGlyphs: [+ { commandsBlob: new Uint8Array([10, 20]), x: 0, y: 0, fontSize: 14 },+ { commandsBlob: new Uint8Array([30, 40]), x: 10, y: 0, fontSize: 14 }+ ]+ })+ const original = graph.getNode(node.id)+ const clone = graph.cloneTree(node.id, pageId(graph))+ const clonedNode = graph.getNode(clone.id)++ expect(clonedNode.figmaDerivedTextGlyphs).not.toBe(original.figmaDerivedTextGlyphs)+ if (original.figmaDerivedTextGlyphs && clonedNode.figmaDerivedTextGlyphs) {+ expect(clonedNode.figmaDerivedTextGlyphs[0]).not.toBe(original.figmaDerivedTextGlyphs[0])+ expect(clonedNode.figmaDerivedTextGlyphs[0].commandsBlob).not.toBe(+ original.figmaDerivedTextGlyphs[0].commandsBlob+ )+ clonedNode.figmaDerivedTextGlyphs[0].commandsBlob[0] = 99+ expect(original.figmaDerivedTextGlyphs[0].commandsBlob[0]).toBe(10)+ }+ })+})++describe('cloneNodeProps deep-copies overrides values', () => {+ test('mutating clone overrides does not affect original', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const component = graph.createNode('COMPONENT', page, { name: 'Comp', width: 100, height: 40 })+ graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ 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`] = [+ { 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<{+ color: { r: number }+ }>+ if (cloneOverrideVal) cloneOverrideVal[0].color.r = 0.5++ const origOverrideVal = instance.overrides[overrideKey] as Array<{ color: { r: number } }>+ if (origOverrideVal) expect(origOverrideVal[0].color.r).toBe(0)+ })+})++describe('cloneNodeProps coverage guard', () => {+ test('cloneNodeProps does not crash when array fields are undefined', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const node = graph.createNode('RECTANGLE', page, { name: 'Rect' })+ const raw = graph.getNode(node.id)+ const patch: Partial<+ Pick<+ SceneNode,+ | 'componentPropertyDefinitions'+ | 'symbolLinks'+ | 'exportSettings'+ | 'pluginData'+ | 'pluginRelaunchData'+ >+ > = {+ componentPropertyDefinitions: undefined,+ symbolLinks: undefined,+ exportSettings: undefined,+ pluginData: undefined,+ pluginRelaunchData: undefined+ }+ Object.assign(raw, patch)+ expect(() => graph.cloneTree(node.id, page)).not.toThrow()+ })++ test('cloneNodeProps does not share mutable object fields by default', () => {+ const graph = new SceneGraph()+ const page = pageId(graph)+ const node = graph.createNode('RECTANGLE', page, {+ name: 'Rich node',+ boundVariables: { 'fills/0/color': 'v1' },+ overrides: { nested: { value: true } },+ vectorNetwork: {+ vertices: [{ x: 0, y: 0 }],+ segments: [{ start: 0, end: 0, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],+ regions: [{ windingRule: 'NONZERO', loops: [[0]] }]+ },+ source: {+ format: 'fig',+ id: 'source-node',+ orderKey: 'a',+ fig: {+ rawSize: { x: 1, y: 2 },+ rawTransform: null,+ rawNodeFields: { nested: { survives: true } },+ layout: null,+ symbolOverrides: [],+ componentPropAssignments: [],+ derivedSymbolData: [],+ derivedSymbolDataLayoutVersion: 1,+ uniformScaleFactor: 1+ }+ },+ textPicture: new Uint8Array([1, 2, 3]),+ figmaDerivedTextGlyphs: [{ commandsBlob: new Uint8Array([4, 5]), x: 0, y: 0, fontSize: 12 }],+ gridPosition: { column: 1, row: 1, columnSpan: 1, rowSpan: 1 }+ })++ const cloneProps = cloneNodeProps(node, null)+ for (const [key, value] of Object.entries(node) as Array<[keyof SceneNode, unknown]>) {+ if (key === 'id' || key === 'parentId' || key === 'childIds') continue+ if (value && typeof value === 'object') {+ expect(cloneProps[key], `field ${String(key)} should be copied`).not.toBe(value)+ }+ }++ const clonedNestedRaw = cloneProps.source?.fig.rawNodeFields.nested as { survives: boolean }+ clonedNestedRaw.survives = false+ const originalNestedRaw = node.source.fig.rawNodeFields.nested as { survives: boolean }+ expect(originalNestedRaw.survives).toBe(true)+ })+})diff --git a/tests/engine/scene-graph/variable/binding/extended.test.ts b/tests/engine/scene-graph/variable/binding/extended.test.tsnew file mode 100644index 000000000..9dd09aef5--- /dev/null+++ b/tests/engine/scene-graph/variable/binding/extended.test.ts@@ -0,0 +1,512 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { nodeProxyToJSON } from '@open-pencil/core/figma-api/serialization'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++function setupColorVars(graph: SceneGraph, ...ids: string[]): void {+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ for (const id of ids) {+ graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ }+}++// ─── boundVariables sync from component to instance ──────────────────────++describe('INSTANCE_SYNC_PROPS includes boundVariables', () => {+ function setupGraph(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ graph.addVariable({+ id: 'v2',+ name: 'Secondary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0, g: 0, b: 1, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ return graph+ }++ test('syncInstances propagates boundVariables from component to instance', () => {+ const graph = setupGraph()+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ // Bind variable on component child+ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ // Create instance+ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ // Change component child's binding+ graph.bindVariable(child.id, 'fills/0/color', 'v2')+ // Sync+ graph.syncInstances(component.id)++ // Instance child should now have the updated binding+ expect(instanceChild.boundVariables['fills/0/color']).toBe('v2')+ })++ test('synced boundVariables is an independent copy', () => {+ const graph = setupGraph()+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]+ const compChild = graph.getNode(child.id)++ graph.syncInstances(component.id)++ // After sync, boundVariables must still be independent objects+ expect(instanceChild.boundVariables).not.toBe(compChild.boundVariables)+ })++ test('instance override blocks boundVariables sync', () => {+ const graph = setupGraph()+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })++ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ // Set an override to block boundVariables sync+ instance.overrides[`${instanceChild.id}:boundVariables`] = true++ // Change component child's binding+ graph.bindVariable(child.id, 'fills/0/color', 'v2')++ // Sync+ graph.syncInstances(component.id)++ // Instance child binding should NOT be overwritten (override takes precedence)+ expect(instanceChild.boundVariables['fills/0/color']).toBe('v1')+ })+})++// ─── bindVariable validation continued ────────────────────────────────────++describe('bindVariable validation continued', () => {+ function setupGraph(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v-float',+ name: 'Spacing',+ type: 'FLOAT',+ collectionId: 'col1',+ valuesByMode: { m1: 16 },+ description: '',+ hiddenFromPublishing: false+ })+ return graph+ }++ test('bindVariable rejects unknown field names', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ expect(() => {+ graph.bindVariable(node.id, 'customPluginField', 'v-float')+ }).toThrow(/Unknown binding field/)+ })+})++// ─── unbindVariable removes binding correctly ────────────────────────────++describe('unbindVariable', () => {+ function setupGraph(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ return graph+ }++ test('unbindVariable removes the binding from node', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBe('v1')+ graph.unbindVariable(node.id, 'fills/0/color')+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('unbindVariable emits node:updated event', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []+ graph.onNodeEvents({+ updated: (nodeId, changes) => events.push({ nodeId, changes })+ })+ graph.unbindVariable(node.id, 'fills/0/color')+ expect(events.length).toBe(1)+ expect(events[0].nodeId).toBe(node.id)+ expect('boundVariables' in events[0].changes).toBe(true)+ })++ test('unbindVariable on non-existent binding is a no-op', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ // Should not throw when unbinding a field that was never bound+ expect(() => graph.unbindVariable(node.id, 'opacity')).not.toThrow()+ })++ test('unbindVariable does not emit event for non-existent binding', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []+ graph.onNodeEvents({+ updated: (nodeId, changes) => events.push({ nodeId, changes })+ })+ graph.unbindVariable(node.id, 'opacity')+ expect(events).toHaveLength(0)+ })+})++// ─── nodeProxyToJSON includes boundVariables ─────────────────────────────++describe('nodeProxyToJSON boundVariables', () => {+ test('nodeProxyToJSON includes boundVariables with resolved info', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const api = new FigmaAPI(graph)+ const json = nodeProxyToJSON(graph, api, node.id)+ expect(json.boundVariables).toBeDefined()+ expect(json.boundVariables['fills/0/color']).toBeDefined()+ expect(json.boundVariables['fills/0/color'].variableId).toBe('v1')+ expect(json.boundVariables['fills/0/color'].variableName).toBe('Var v1')+ })++ test('nodeProxyToJSON omits boundVariables when none exist', () => {+ const graph = new SceneGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ const api = new FigmaAPI(graph)+ const json = nodeProxyToJSON(graph, api, node.id)+ expect(json.boundVariables).toBeUndefined()+ })+})++// ─── Scope expansion: bindVariable range validation tests ────────────────++describe('bindVariable out-of-range index validation', () => {+ function setupGraph(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v1',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ return graph+ }++ test('bindVariable rejects index beyond current fills length', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ // Node has 2 fills (indices 0, 1). Index 5 is out of range.+ expect(() => {+ graph.bindVariable(node.id, 'fills/5/color', 'v1')+ }).toThrow(/out of range/)+ })++ test('bindVariable rejects next-index binding (index == currentLength)', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ // Node has 2 fills (indices 0, 1). Index 2 is out of range (index >= length).+ expect(() => {+ graph.bindVariable(node.id, 'fills/2/color', 'v1')+ }).toThrow(/out of range/)+ })++ test('bindVariable rejects binding to empty fills array (index 0, length 0)', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: []+ })+ // No fills exist. Index 0 is out of range (0 >= 0).+ expect(() => {+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ }).toThrow(/out of range/)+ })++ test('bindVariable rejects out-of-range stroke index', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ strokes: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, visible: true, opacity: 1 }]+ })+ // Node has 1 stroke. Index 3 is out of range.+ expect(() => {+ graph.bindVariable(node.id, 'strokes/3/color', 'v1')+ }).toThrow(/out of range/)+ })++ test('bindVariable rejects unknown field names', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ expect(() => {+ graph.bindVariable(node.id, 'someRandomField', 'v1')+ }).toThrow(/Unknown binding field/)+ })+})++// ─── cleanupStaleBindings handles any indexed sub-path ──────────────────────++describe('cleanupStaleBindings handles any indexed sub-path', () => {+ test('cleans up fills/N/something bindings when fills shrink past the index', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ const n = graph.getNode(node.id)+ // Bind a hypothetical non-color sub-path at index 1+ n.boundVariables['fills/1/somethingElse'] = 'v1'++ // Remove all fills — index 1 is now beyond the array (1 > 0)+ graph.updateNode(node.id, { fills: [] })++ // fills/1/somethingElse binding must be removed (index 1 > length 0)+ expect(n.boundVariables['fills/1/somethingElse']).toBeUndefined()+ })++ test('fills/0/color binding is cleaned up when fills shrink to empty', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')++ // Shrink fills to empty — fills/0/color must be removed (0 >= 0 is true)+ graph.updateNode(node.id, { fills: [] })+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('malformed non-numeric indexed keys are cleaned up on fills change', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ const n = graph.getNode(node.id)+ // Simulate a malformed binding key from legacy data — non-numeric index portion+ n.boundVariables['fills/blendMode'] = 'v1'++ // Any fills change triggers cleanup — malformed key must be removed+ graph.updateNode(node.id, {+ fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }]+ })+ expect(n.boundVariables['fills/blendMode']).toBeUndefined()+ })++ test('negative indexed keys are cleaned up on fills change', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ const n = graph.getNode(node.id)+ // Simulate a malformed binding key from legacy data — negative index+ n.boundVariables['fills/-1/color'] = 'v1'++ // Any fills change triggers cleanup — negative index must be removed+ graph.updateNode(node.id, {+ fills: [{ type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }]+ })+ expect(n.boundVariables['fills/-1/color']).toBeUndefined()+ })+})++// ─── cleanupStaleBindings includes boundVariables in changes payload ──────++describe('cleanupStaleBindings includes boundVariables in changes payload', () => {+ test('updateNode emits boundVariables in changes when stale bindings are cleaned', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [+ { type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 },+ { type: 'SOLID', color: { r: 0.2, g: 0.2, b: 0.2, a: 1 }, visible: true, opacity: 1 }+ ]+ })+ graph.bindVariable(node.id, 'fills/1/color', 'v2')++ const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []+ graph.onNodeEvents({+ updated: (nodeId, changes) => events.push({ nodeId, changes })+ })++ graph.updateNode(node.id, { fills: [] })++ const updateEvent = events.find((e) => e.nodeId === node.id)+ expect(updateEvent).toBeDefined()+ if (updateEvent) {+ expect('boundVariables' in updateEvent.changes).toBe(true)+ }+ })+})++// ─── bindVariable creates new reference (immutability) ──────────────────++describe('bindVariable creates new boundVariables reference', () => {+ test('binding a variable replaces the boundVariables object reference', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ const originalBV = graph.getNode(node.id).boundVariables+ graph.bindVariable(node.id, 'fills/0/color', 'v1')+ const newBV = graph.getNode(node.id).boundVariables+ expect(newBV).not.toBe(originalBV)+ })+})diff --git a/tests/engine/scene-graph/variable/binding/instance-override.test.ts b/tests/engine/scene-graph/variable/binding/instance-override.test.tsnew file mode 100644index 000000000..596a5632c--- /dev/null+++ b/tests/engine/scene-graph/variable/binding/instance-override.test.ts@@ -0,0 +1,247 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/core'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++function setupColorVars(graph: SceneGraph, ...ids: string[]): void {+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ for (const id of ids) {+ graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ }+}++function setupFloatVars(graph: SceneGraph, ...ids: string[]): void {+ graph.addCollection({+ id: 'col-f',+ name: 'Floats',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ for (const id of ids) {+ graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'FLOAT',+ collectionId: 'col-f',+ valuesByMode: { m1: 1 },+ description: '',+ hiddenFromPublishing: false+ })+ }+}++// ─── bindVariable on instance child sets override flag ──────────────────++describe('bindVariable on instance child sets override flag', () => {+ test('binding on instance child sets boundVariables override on parent instance', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ graph.bindVariable(instanceChild.id, 'fills/0/color', 'v2')++ expect(instance.overrides[`${instanceChild.id}:boundVariables`]).toBe(true)+ })++ test('binding on instance child survives syncInstances', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const child = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(child.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ graph.bindVariable(instanceChild.id, 'fills/0/color', 'v2')++ graph.syncInstances(component.id)++ expect(instanceChild.boundVariables['fills/0/color']).toBe('v2')+ })+})++// ─── bindVariable on INSTANCE node itself sets override ──────────────────++describe('bindVariable on INSTANCE node itself sets override', () => {+ test('binding on INSTANCE node sets bare boundVariables override key', () => {+ const graph = new SceneGraph()+ setupFloatVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40,+ opacity: 1+ })+ graph.bindVariable(component.id, 'opacity', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()++ graph.bindVariable(instance.id, 'opacity', 'v2')++ expect(instance.overrides['boundVariables']).toBe(true)+ })++ test('binding on INSTANCE node survives syncInstances', () => {+ const graph = new SceneGraph()+ setupFloatVars(graph, 'v1', 'v2')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40,+ opacity: 1+ })+ graph.bindVariable(component.id, 'opacity', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()++ graph.bindVariable(instance.id, 'opacity', 'v2')++ graph.bindVariable(component.id, 'opacity', 'v1')+ graph.syncInstances(component.id)++ expect(instance.boundVariables['opacity']).toBe('v2')+ })+})++// ─── removeVariable emits events and sets overrides ────────────────────++describe('removeVariable emits events and sets overrides', () => {+ test('removeVariable emits node:updated for affected nodes', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const page = pageId(graph)+ const node = graph.createNode('RECTANGLE', page, {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(node.id, 'fills/0/color', 'v1')++ const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []+ graph.onNodeEvents({+ updated: (nodeId, changes) => events.push({ nodeId, changes })+ })++ graph.removeVariable('v1')++ const updateEvent = events.find((e) => e.nodeId === node.id)+ expect(updateEvent).toBeDefined()+ if (updateEvent) {+ expect('boundVariables' in updateEvent.changes).toBe(true)+ }+ })++ test('removeVariable sets instance override on affected instance child', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const page = pageId(graph)++ const component = graph.createNode('COMPONENT', page, {+ name: 'Button',+ width: 100,+ height: 40+ })+ const compChild = graph.createNode('RECTANGLE', component.id, {+ name: 'Bg',+ width: 100,+ height: 40,+ fills: [{ type: 'SOLID', color: { r: 0.1, g: 0.1, b: 0.1, a: 1 }, visible: true, opacity: 1 }]+ })+ graph.bindVariable(compChild.id, 'fills/0/color', 'v1')++ const instance =+ graph.createInstance(component.id, page) ??+ (() => {+ throw new Error('instance failed')+ })()+ const instanceChild = graph.getChildren(instance.id)[0]++ graph.removeVariable('v1')++ expect(instance.overrides[`${instanceChild.id}:boundVariables`]).toBe(true)+ })++ test('removeVariable does not emit for unaffected nodes', () => {+ const graph = new SceneGraph()+ setupFloatVars(graph, 'v1')+ const page = pageId(graph)+ const nodeA = graph.createNode('RECTANGLE', page, { name: 'A' })+ const nodeB = graph.createNode('RECTANGLE', page, { name: 'B' })+ graph.bindVariable(nodeA.id, 'opacity', 'v1')++ const events: Array<{ nodeId: string }> = []+ graph.onNodeEvents({+ updated: (nodeId) => events.push({ nodeId })+ })++ graph.removeVariable('v1')++ expect(events.some((e) => e.nodeId === nodeA.id)).toBe(true)+ expect(events.some((e) => e.nodeId === nodeB.id)).toBe(false)+ })+})diff --git a/tests/engine/scene-graph/variable/binding/validation.test.ts b/tests/engine/scene-graph/variable/binding/validation.test.tsnew file mode 100644index 000000000..8f7e8b259--- /dev/null+++ b/tests/engine/scene-graph/variable/binding/validation.test.ts@@ -0,0 +1,228 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/core'+import noHardcodedColors from '@open-pencil/core/lint/rules/no-hardcoded-colors'++function pageId(graph: SceneGraph): string {+ return graph.getPages()[0].id+}++function setupColorVars(graph: SceneGraph, ...ids: string[]): void {+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ for (const id of ids) {+ graph.addVariable({+ id,+ name: `Var ${id}`,+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ }+}++// ─── bindVariable emits node:updated event ──────────────────────────────────++describe('bindVariable emits node:updated event', () => {+ test('bindVariable emits node:updated event', () => {+ const graph = new SceneGraph()+ setupColorVars(graph, 'v1')+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })++ const events: Array<{ nodeId: string; changes: Record<string, unknown> }> = []+ graph.onNodeEvents({+ updated: (nodeId, changes) => {+ events.push({ nodeId, changes })+ }+ })++ graph.bindVariable(node.id, 'fills/0/color', 'v1')++ expect(events.length).toBeGreaterThanOrEqual(1)+ expect(events[0].nodeId).toBe(node.id)+ expect(events[0].changes).toHaveProperty('boundVariables')+ })+})++// ─── no-hardcoded-colors lint checks indexed bindings ──────────────────────++describe('no-hardcoded-colors lint checks indexed bindings', () => {+ test('node with fills/0/color binding passes lint (no false positive)', () => {+ const node = {+ id: 'n1',+ name: 'Rect',+ type: 'RECTANGLE',+ width: 100,+ height: 100,+ x: 0,+ y: 0,+ rotation: 0,+ visible: true,+ locked: false,+ layoutMode: 'NONE',+ itemSpacing: 0,+ paddingTop: 0,+ paddingRight: 0,+ paddingBottom: 0,+ paddingLeft: 0,+ cornerRadius: 0,+ childIds: [],+ text: '',+ fontSize: 14,+ styleRunCount: 0,+ boundVariables: { 'fills/0/color': 'v1' },+ fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],+ strokes: [],+ effects: []+ }++ const messages: Array<{ message: string }> = []+ const context = {+ report: (issue: { message: string }) => messages.push(issue),+ getConfig: () => ({}),+ getParent: () => null,+ getChildren: () => []+ }++ noHardcodedColors.check(node, context)+ // Should NOT report a violation — the color is bound to a variable+ expect(messages.length).toBe(0)+ })++ test('node with top-level fills binding still reports violation (no false negative)', () => {+ const node = {+ id: 'n2',+ name: 'Rect',+ type: 'RECTANGLE',+ width: 100,+ height: 100,+ x: 0,+ y: 0,+ rotation: 0,+ visible: true,+ locked: false,+ layoutMode: 'NONE',+ itemSpacing: 0,+ paddingTop: 0,+ paddingRight: 0,+ paddingBottom: 0,+ paddingLeft: 0,+ cornerRadius: 0,+ childIds: [],+ text: '',+ fontSize: 14,+ styleRunCount: 0,+ boundVariables: { fills: 'v1' }, // top-level — renderer-ignored+ fills: [{ type: 'SOLID', visible: true, opacity: 1, color: { r: 0.5, g: 0.5, b: 0.5 } }],+ strokes: [],+ effects: []+ }++ const messages: Array<{ message: string }> = []+ const context = {+ report: (issue: { message: string }) => messages.push(issue),+ getConfig: () => ({}),+ getParent: () => null,+ getChildren: () => []+ }++ noHardcodedColors.check(node, context)+ // SHOULD report a violation — top-level 'fills' binding is renderer-ignored+ expect(messages.length).toBeGreaterThanOrEqual(1)+ })+})++// ─── bindVariable validation ──────────────────────────────────────────────++describe('bindVariable validation', () => {+ function setupGraph(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'col1',+ name: 'Colors',+ modes: [{ modeId: 'm1', name: 'Light' }],+ defaultModeId: 'm1',+ variableIds: []+ })+ graph.addVariable({+ id: 'v-color',+ name: 'Primary',+ type: 'COLOR',+ collectionId: 'col1',+ valuesByMode: { m1: { r: 1, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ graph.addVariable({+ id: 'v-float',+ name: 'Spacing',+ type: 'FLOAT',+ collectionId: 'col1',+ valuesByMode: { m1: 16 },+ description: '',+ hiddenFromPublishing: false+ })+ return graph+ }++ test('bindVariable rejects nonexistent variable', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ expect(() => {+ graph.bindVariable(node.id, 'fills/0/color', 'nonexistent')+ }).toThrow()+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('bindVariable rejects FLOAT variable on color field', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ expect(() => {+ graph.bindVariable(node.id, 'fills/0/color', 'v-float')+ }).toThrow()+ expect(graph.getNode(node.id).boundVariables['fills/0/color']).toBeUndefined()+ })++ test('bindVariable rejects COLOR variable on scalar field', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ expect(() => {+ graph.bindVariable(node.id, 'opacity', 'v-color')+ }).toThrow()+ expect(graph.getNode(node.id).boundVariables['opacity']).toBeUndefined()+ })++ test('bindVariable rejects binding to fills that do not yet exist', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })+ // Rect has 0 fills — binding to fills/0/color must be rejected (index >= length)+ expect(() => {+ graph.bindVariable(node.id, 'fills/0/color', 'v-color')+ }).toThrow(/out of range/)+ })++ test('bindVariable auto-removes top-level fills binding when indexed binding is set', () => {+ const graph = setupGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ name: 'Rect',+ fills: [{ type: 'SOLID', color: { r: 0.5, g: 0.5, b: 0.5, a: 1 }, visible: true, opacity: 1 }]+ })+ const n = graph.getNode(node.id)+ // Set top-level dead data first+ n.boundVariables['fills'] = 'v-color'+ // Now set a proper indexed binding — should auto-remove top-level+ graph.bindVariable(node.id, 'fills/0/color', 'v-color')+ expect(n.boundVariables['fills']).toBeUndefined()+ expect(n.boundVariables['fills/0/color']).toBe('v-color')+ })+})