AI-native design editor. Open-source Figma alternative.
fix(fig): live edits to instance-descendant fields discarded on save
xemcff54a222d8bc
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.tsindex e07a0264b..30a79841a 100644--- a/packages/core/src/figma-api/accessor-utils.ts+++ b/packages/core/src/figma-api/accessor-utils.ts@@ -1,3 +1,4 @@+import { recordInstanceOverride } from '@open-pencil/scene-graph'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { assertNodeEditable } from '#core/editor/capabilities'@@ -35,5 +36,8 @@ export function updateNode(changes: Partial<SceneNode>): void {assertProxyEditable(target, internals)- graph(target, internals).updateNode(nodeId(target, internals), changes)+ const g = graph(target, internals)+ const id = nodeId(target, internals)+ g.updateNode(id, changes)+ recordInstanceOverride(g, id, Object.keys(changes))}diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.tsindex b6c49cfab..70c262894 100644--- a/packages/fig/src/instance-overrides/index.ts+++ b/packages/fig/src/instance-overrides/index.ts@@ -33,6 +33,7 @@ import {applyGeneratedFreeformStretch,reconcileEffectiveCloneGeometry} from './derived-symbol-data/propagate'+import { hasLiveOverride } from './live-overrides'import { populateInstances } from './populate'import { preComputeRoots } from './resolve'import { applySymbolOverrides } from './symbol/overrides'@@ -129,6 +130,7 @@ function propagateResolvedFills(const source = graph.getNode(node.componentId)if (!source || isEqual(source.fills, node.fills)) continueif (protectedNodes.has(node.id) && !protectedNodes.has(source.id)) continue+ if (hasLiveOverride(graph, node.id, 'fills')) continuegraph.updateNode(node.id, { fills: copyFills(source.fills) })changed = true}diff --git a/packages/fig/src/instance-overrides/live-overrides.ts b/packages/fig/src/instance-overrides/live-overrides.tsnew file mode 100644index 000000000..a048922a8--- /dev/null+++ b/packages/fig/src/instance-overrides/live-overrides.ts@@ -0,0 +1,16 @@+import { findInstanceAncestor } from '@open-pencil/scene-graph'+import type { SceneGraph } from '@open-pencil/scene-graph'++/**+ * True when `nodeId`'s `field` was recorded as a live instance override+ * (via recordInstanceOverride) — i.e. the field was edited after the file+ * was last imported/saved. Lazy-population resync (re-cloning instance+ * children, reapplying the stored symbol overrides) must not clobber these,+ * since the stored data predates the edit.+ */+export function hasLiveOverride(graph: SceneGraph, nodeId: string, field: string): boolean {+ const instance = findInstanceAncestor(graph, nodeId)+ if (!instance) return false+ const key = nodeId === instance.id ? field : `${nodeId}:${field}`+ return key in instance.overrides+}diff --git a/packages/fig/src/instance-overrides/symbol/overrides.ts b/packages/fig/src/instance-overrides/symbol/overrides.tsindex 6f2e5de88..cb9f6d56a 100644--- a/packages/fig/src/instance-overrides/symbol/overrides.ts+++ b/packages/fig/src/instance-overrides/symbol/overrides.ts@@ -1,8 +1,26 @@+import { hasLiveOverride } from '../live-overrides'import { applyOverridePatch } from '../patches'import { resolveOverrideTarget } from '../resolve'import type { OverrideContext } from '../types'import { patchFromSymbolOverride } from './patches'+/**+ * Strips fields from a stored-override patch that were since live-edited+ * (recordInstanceOverride) — reapplying the stale stored value on every+ * lazy-population pass would otherwise silently discard the edit.+ */+function dropLiveOverriddenFields(+ ctx: OverrideContext,+ targetId: string,+ patch: ReturnType<typeof patchFromSymbolOverride>+): void {+ if (!patch?.props) return+ const kept = Object.fromEntries(+ Object.entries(patch.props).filter(([field]) => !hasLiveOverride(ctx.graph, targetId, field))+ )+ patch.props = Object.keys(kept).length > 0 ? (kept as typeof patch.props) : undefined+}+function isActiveInstance(ctx: OverrideContext, nodeId: string | undefined): nodeId is string {return nodeId !== undefined && (!ctx.activeNodeIds || ctx.activeNodeIds.has(nodeId))}@@ -51,6 +69,7 @@ export function applySymbolOverrides(ctx: OverrideContext, propertiesOnly = falsconst patch = patchFromSymbolOverride(ctx, targetId, ov)if (!patch) continue+ dropLiveOverriddenFields(ctx, targetId, patch)preserveInstanceRootBounds(nc.size !== undefined, nodeId, targetId, patch)if (propertiesOnly) patch.swapComponentId = undefinedif (!patch.swapComponentId && !patch.props) continuediff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export-node.tsindex 1596b9547..58aa52030 100644--- a/packages/fig/src/node-change/export-node.ts+++ b/packages/fig/src/node-change/export-node.ts@@ -29,6 +29,7 @@ type KiwiBooleanOperation = NonNullable<NodeChange['booleanOperation']>interface KiwiSymbolOverridePayload {guidPath?: { guids?: GUID[] }textData?: { characters?: string }+ fillPaints?: Paint[][key: string]: unknown}@@ -372,11 +373,7 @@ function serializeTextOverrides(const target = context.graph.getNode(targetId)if (!target || !isDescendantOf(context, targetId, instance.id)) continue- const sourceId = target.componentId- if (!sourceId) continue- const source = context.graph.getNode(sourceId)- const overrideGuid = source?.overrideKey ? parseGuidOrNull(source.overrideKey) : null- const targetGuid = overrideGuid ?? getOrCreateNodeGuid(context, sourceId, localIdCounter)+ const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)if (!targetGuid) continueresult.push({@@ -387,6 +384,46 @@ function serializeTextOverrides(return result}+/**+ * Resolves the descendant-node identity a symbol override applies to: the+ * GUID of the corresponding node inside the target's own main component+ * (cloneNodeProps stamps componentId with that node's id on every clone).+ */+function resolveOverrideTargetGuid(+ context: SceneNodeToKiwiContext,+ target: SceneNode,+ localIdCounter: { value: number }+): GUID | undefined {+ const sourceId = target.componentId+ if (!sourceId) return undefined+ const source = context.graph.getNode(sourceId)+ const overrideGuid = source?.overrideKey ? parseGuidOrNull(source.overrideKey) : null+ return overrideGuid ?? getOrCreateNodeGuid(context, sourceId, localIdCounter)+}++function serializeFillOverrides(+ context: SceneNodeToKiwiContext,+ instance: SceneNode,+ localIdCounter: { value: number }+): KiwiSymbolOverridePayload[] {+ const result: KiwiSymbolOverridePayload[] = []+ for (const key of Object.keys(instance.overrides)) {+ if (!key.endsWith(':fills')) continue+ const targetId = key.slice(0, -':fills'.length)+ const target = context.graph.getNode(targetId)+ if (!target || !isDescendantOf(context, targetId, instance.id)) continue++ const targetGuid = resolveOverrideTargetGuid(context, target, localIdCounter)+ if (!targetGuid) continue++ result.push({+ guidPath: { guids: [targetGuid] },+ fillPaints: target.fills.map((fill) => context.fillToKiwiPaint(fill))+ })+ }+ return result+}+function overridePathKey(payload: KiwiSymbolOverridePayload): string | null {const guids = payload.guidPath?.guidsreturn guids?.length@@ -394,12 +431,12 @@ function overridePathKey(payload: KiwiSymbolOverridePayload): string | null {: null}-function mergeTextOverrides(+function mergeOverrides(symbolOverrides: KiwiSymbolOverridePayload[],- textOverrides: KiwiSymbolOverridePayload[]+ newOverrides: KiwiSymbolOverridePayload[]): void {- for (const textOverride of textOverrides) {- const pathKey = overridePathKey(textOverride)+ for (const override of newOverrides) {+ const pathKey = overridePathKey(override)let existingIndex = -1if (pathKey) {for (let index = symbolOverrides.length - 1; index >= 0; index--) {@@ -408,13 +445,8 @@ function mergeTextOverrides(break}}- if (existingIndex < 0) symbolOverrides.push(textOverride)- else {- symbolOverrides[existingIndex] = {- ...symbolOverrides[existingIndex],- textData: textOverride.textData- }- }+ if (existingIndex < 0) symbolOverrides.push(override)+ else symbolOverrides[existingIndex] = { ...symbolOverrides[existingIndex], ...override }}}@@ -589,7 +621,8 @@ function applyInstancePayload(}) as KiwiSymbolOverridePayload[]))}- mergeTextOverrides(symbolOverrides, serializeTextOverrides(context, node, localIdCounter))+ mergeOverrides(symbolOverrides, serializeTextOverrides(context, node, localIdCounter))+ mergeOverrides(symbolOverrides, serializeFillOverrides(context, node, localIdCounter))if (symbolOverrides.length > 0) symbolData.symbolOverrides = symbolOverridesif (node.source.fig.uniformScaleFactor != null) {symbolData.uniformScaleFactor = node.source.fig.uniformScaleFactordiff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex d9e6f97e0..4265de387 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -1,7 +1,12 @@/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */export * from './images'export * from './copy'-export { copyInstanceComponentProps } from './instances'+export {+ copyInstanceComponentProps,+ findInstanceAncestor,+ INSTANCE_SYNC_PROPS,+ recordInstanceOverride+} from './instances'export * from './snap'export * from './export-scale'export * from './coordinate'diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.tsindex 988e9db04..4d37ebfa1 100644--- a/packages/scene-graph/src/instances.ts+++ b/packages/scene-graph/src/instances.ts@@ -4,7 +4,7 @@ import type { NodeCloneMode } from './copy'export type { NodeCloneMode } from './copy'-const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = [+export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = ['width','height','minWidth',@@ -284,3 +284,37 @@ export function getInstances(graph: SceneGraph, componentId: string): SceneNode[}return instances}++/** Nearest INSTANCE at or above `nodeId` — self, parent, grandparent, etc. */+export function findInstanceAncestor(graph: SceneGraph, nodeId: string): SceneNode | undefined {+ let current = graph.nodes.get(nodeId)+ while (current) {+ if (current.type === 'INSTANCE') return current+ current = current.parentId ? graph.nodes.get(current.parentId) : undefined+ }+ return undefined+}++/**+ * Marks `nodeId`'s `fields` as instance overrides so resync (swapInstanceComponent,+ * syncInstances) won't clobber them, and — if `nodeId` sits inside an INSTANCE —+ * so the .fig exporter knows to write the diff out as a symbol override. A no-op+ * for fields outside INSTANCE_SYNC_PROPS or nodes with no INSTANCE ancestor.+ */+export function recordInstanceOverride(+ graph: SceneGraph,+ nodeId: string,+ fields: Iterable<string>+): void {+ const instance = findInstanceAncestor(graph, nodeId)+ if (!instance) return++ const relevant = [...fields].filter((field) => (INSTANCE_SYNC_PROPS as string[]).includes(field))+ if (relevant.length === 0) return++ const overrides = { ...instance.overrides }+ for (const field of relevant) {+ overrides[nodeId === instance.id ? field : `${nodeId}:${field}`] = true+ }+ graph.updateNode(instance.id, { overrides })+}diff --git a/tests/engine/figma/api/create/instance-fill-override.test.ts b/tests/engine/figma/api/create/instance-fill-override.test.tsnew file mode 100644index 000000000..8d4e51422--- /dev/null+++ b/tests/engine/figma/api/create/instance-fill-override.test.ts@@ -0,0 +1,31 @@+import { describe, expect, test } from 'bun:test'++import { createAPI } from '../helpers'++describe('setting fills on an instance descendant', () => {+ test('records an instance override so the change survives resync', () => {+ const api = createAPI()+ const icon = api.createComponent()+ icon.resize(16, 16)++ const instance = icon.createInstance()+ const vector = api.graph.createNode('VECTOR', instance.id, { width: 16, height: 16 })+ api.graph.updateNode(vector.id, { componentId: icon.id })++ const vectorProxy = api.getNodeById(vector.id)+ if (!vectorProxy) throw new Error('vector proxy not found')+ vectorProxy.fills = [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]++ const raw = api.graph.getNode(instance.id)+ expect(raw?.overrides[`${vector.id}:fills`]).toBe(true)+ })++ test('does not record an override for a node with no instance ancestor', () => {+ const api = createAPI()+ const frame = api.createFrame()+ frame.fills = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]++ const raw = api.graph.getNode(frame.id)+ expect(raw?.overrides ?? {}).toEqual({})+ })+})diff --git a/tests/engine/io/fig/instance-fill-override-resave.test.ts b/tests/engine/io/fig/instance-fill-override-resave.test.tsnew file mode 100644index 000000000..54154410b--- /dev/null+++ b/tests/engine/io/fig/instance-fill-override-resave.test.ts@@ -0,0 +1,61 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core'+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'+import { initCodec } from '@open-pencil/core/kiwi'+import { SceneGraph } from '@open-pencil/scene-graph'++const BLUE = { r: 0, g: 0, b: 1, a: 1 }+const RED = { r: 1, g: 0, b: 0, a: 1 }++function findInstanceAndVector(graph: SceneGraph) {+ const instance = graph.getAllNodes().find((n) => n.type === 'INSTANCE')+ if (!instance) throw new Error('instance not found')+ const vector = graph.getChildren(instance.id)[0]+ return { instance, vector }+}++describe('re-editing an instance fill across multiple save/reload cycles', () => {+ test('a second live edit overrides the first, not the other way around', async () => {+ await initCodec()++ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const icon = graph.createNode('COMPONENT', page.id, { name: 'Icon' })+ graph.createNode('VECTOR', icon.id, {+ name: 'path',+ width: 16,+ height: 16,+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ })++ const instance = graph.createInstance(icon.id, page.id)+ if (!instance) throw new Error('failed to create instance')+ const figma1 = new FigmaAPI(graph)+ const vectorProxy1 = figma1.getNodeById(graph.getChildren(instance.id)[0].id)+ if (!vectorProxy1) throw new Error('vector proxy not found')+ vectorProxy1.fills = [{ type: 'SOLID', color: BLUE, opacity: 1, visible: true }]++ // Round 1: export the blue edit, reimport it — this is the state a+ // freshly-reopened file would be in, with `blue` baked into the stored+ // symbolOverride but no live `overrides` bookkeeping (per §1 of the fix).+ const bytes1 = await exportFigFile(graph)+ const graph2 = await parseFigFile(bytes1.buffer as ArrayBuffer)+ const { vector: vector2 } = findInstanceAndVector(graph2)+ expect(vector2.fills[0]?.color).toEqual(BLUE)++ // Round 2: live-edit the reimported instance's icon to red, then export+ // and reimport again. Without the fix, `applySymbolOverrides` reapplies+ // the STALE stored (blue) override on this same export pass, silently+ // discarding the fresh (red) edit.+ const figma2 = new FigmaAPI(graph2)+ const vectorProxy2 = figma2.getNodeById(vector2.id)+ if (!vectorProxy2) throw new Error('vector proxy not found')+ vectorProxy2.fills = [{ type: 'SOLID', color: RED, opacity: 1, visible: true }]++ const bytes2 = await exportFigFile(graph2)+ const graph3 = await parseFigFile(bytes2.buffer as ArrayBuffer)+ const { vector: vector3 } = findInstanceAndVector(graph3)+ expect(vector3.fills[0]?.color).toEqual(RED)+ })+})diff --git a/tests/engine/io/fig/instance-fill-override-roundtrip.test.ts b/tests/engine/io/fig/instance-fill-override-roundtrip.test.tsnew file mode 100644index 000000000..2b74b175c--- /dev/null+++ b/tests/engine/io/fig/instance-fill-override-roundtrip.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, parseFigFile } from '@open-pencil/core/io'+import { initCodec } from '@open-pencil/core/kiwi'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('instance descendant fill override round trip', () => {+ test('a recolored nested instance child keeps its color after a save/reload cycle', async () => {+ await initCodec()++ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const icon = graph.createNode('COMPONENT', page.id, { name: 'Icon' })+ const path = graph.createNode('VECTOR', icon.id, {+ name: 'path',+ width: 16,+ height: 16,+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]+ })++ const instance = graph.createInstance(icon.id, page.id)+ if (!instance) throw new Error('failed to create instance')+ const instancePath = graph.getChildren(instance.id)[0]+ expect(instancePath.componentId).toBe(path.id)++ graph.updateNode(instancePath.id, {+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 1, a: 1 }, opacity: 1, visible: true }]+ })+ const { recordInstanceOverride } = await import('@open-pencil/scene-graph')+ recordInstanceOverride(graph, instancePath.id, ['fills'])++ const exported = await exportFigFile(graph)+ const reloaded = await parseFigFile(exported.buffer as ArrayBuffer)++ const reloadedInstance = reloaded.getAllNodes().find((n) => n.type === 'INSTANCE')+ expect(reloadedInstance).toBeDefined()+ const reloadedPath = reloadedInstance ? reloaded.getChildren(reloadedInstance.id)[0] : undefined+ expect(reloadedPath?.fills[0]?.color).toEqual({ r: 0, g: 0, b: 1, a: 1 })++ const reloadedIcon = reloaded.getAllNodes().find((n) => n.type === 'COMPONENT' && n.name === 'Icon')+ const reloadedIconPath = reloadedIcon ? reloaded.getChildren(reloadedIcon.id)[0] : undefined+ expect(reloadedIconPath?.fills[0]?.color).toEqual({ r: 0, g: 0, b: 0, a: 1 })+ })+})