AI-native design editor. Open-source Figma alternative.
fix(fig): keep a literal paint over a variable-bound paint in an instance (#1467)
Marcos Velásquez90b91a346386
diff --git a/changes/1467/fixed.md b/changes/1467/fixed.mdnew file mode 100644index 000000000..21c85fb8c--- /dev/null+++ b/changes/1467/fixed.md@@ -0,0 +1 @@+- A plain colour set over a variable-bound paint in an instance stays after the `.fig` file is reopened.diff --git a/packages/core/src/figma-api/variables/bindings.ts b/packages/core/src/figma-api/variables/bindings.tsindex 8fb301b31..9dc5e79c3 100644--- a/packages/core/src/figma-api/variables/bindings.ts+++ b/packages/core/src/figma-api/variables/bindings.ts@@ -10,7 +10,7 @@ import {type VariableType} from '@open-pencil/scene-graph'import { recordInstanceOverride } from '@open-pencil/scene-graph/instances'-import { independentCornerChanges } from '@open-pencil/scene-graph/variables'+import { independentCornerChanges, paintBindingTarget } from '@open-pencil/scene-graph/variables'import type { FigmaPaint } from '#core/figma-api/paints'import { reconcileVariableLayouts } from '#core/layout/variables'@@ -204,14 +204,12 @@ const FIGMA_FIELD_BY_DOCUMENT_FIELD = new Map<string, string>(.map(([figma, field]) => [field, figma]))-const PAINT_FIELD = /^(fills|strokes)\/(\d+)\/color$/-/** The variable bound to each paint's colour, by paint index, for `fills` or `strokes`. */export function paintBindings(node: SceneNode, key: 'fills' | 'strokes'): Map<number, string> {const bindings = new Map<number, string>()for (const [field, id] of Object.entries(node.boundVariables)) {- const match = PAINT_FIELD.exec(field)- if (match?.[1] === key) bindings.set(Number(match[2]), id)+ const paint = paintBindingTarget(field)+ if (paint?.list === key) bindings.set(paint.index, id)}return bindings}diff --git a/packages/core/src/lint/fixes.ts b/packages/core/src/lint/fixes.tsindex 29e6c9eae..643863c7e 100644--- a/packages/core/src/lint/fixes.ts+++ b/packages/core/src/lint/fixes.ts@@ -2,6 +2,7 @@ import { isEmptyObject } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { colorToHex } from '@open-pencil/scene-graph/color'+import { paintBindingTarget } from '@open-pencil/scene-graph/variables'import type { LintFix, LintMessage } from './types'import { ownsComponentTree } from './utils'@@ -42,18 +43,15 @@ export function safeFixes(messages: readonly LintMessage[]): LintFixRequest[] {return messages.flatMap(({ nodeId, fix }) => (fix ? [{ nodeId, fix }] : []))}-const PAINT_PATH = /^(fills|strokes)\/(\d+)\/color$/-/*** Binding is safe only while the paint still shows the variable's color: a paint edited since* the lint run would change appearance, so its fix is skipped.*/function canBind(graph: SceneGraph, node: SceneNode, path: string, variableId: string): boolean {if (node.boundVariables[path] === variableId) return false- const match = PAINT_PATH.exec(path)- if (!match) return false- const index = Number(match[2])- const paint = match[1] === 'fills' ? node.fills.at(index) : node.strokes.at(index)+ const target = paintBindingTarget(path)+ if (!target) return false+ const paint = node[target.list].at(target.index)const color = graph.resolveColorVariableForNode(node.id, variableId)if (!paint || !color || ('type' in paint && paint.type !== 'SOLID')) return falsereturn colorToHex({ ...paint.color, a: 1 }) === colorToHex({ ...color, a: 1 })diff --git a/packages/core/src/openpencil-api/variables.ts b/packages/core/src/openpencil-api/variables.tsindex 4ede20375..80b06b718 100644--- a/packages/core/src/openpencil-api/variables.ts+++ b/packages/core/src/openpencil-api/variables.ts@@ -1,12 +1,10 @@import type { SceneGraph } from '@open-pencil/scene-graph'-import { resolvedPaintBindings } from '@open-pencil/scene-graph/variables'+import { paintBindingTarget, resolvedPaintBindings } from '@open-pencil/scene-graph/variables'import { reconcileVariableLayouts } from '#core/layout/variables'import { nodeOf, type NodeRef } from './behaviours'-const PAINT_FIELD = /^(fills|strokes)\/\d+\/color$/-/** A variable as `figma` hands it out, such as from `figma.variables.getLocalVariables()`. */export type VariableRef = { readonly id: string }@@ -37,7 +35,7 @@ export function unbindVariable(graph: SceneGraph, node: NodeRef, field: string):if (!(field in target.boundVariables))throw new Error(`${target.name} has no variable bound to ${field}`)// A paint keeps the color its variable last gave it, as values do and as Figma's detach does.- if (PAINT_FIELD.test(field)) graph.updateNode(target.id, resolvedPaintBindings(graph, target))+ if (paintBindingTarget(field)) graph.updateNode(target.id, resolvedPaintBindings(graph, target))graph.unbindVariable(target.id, field)reconcileVariableLayouts(graph, { subtrees: [target.id] })}diff --git a/packages/fig/src/instance-overrides/bindings/variables.ts b/packages/fig/src/instance-overrides/bindings/variables.tsindex 7ddee40af..273a0828f 100644--- a/packages/fig/src/instance-overrides/bindings/variables.ts+++ b/packages/fig/src/instance-overrides/bindings/variables.ts@@ -7,7 +7,10 @@ import { linearVariableExpression } from '#fig/node-change/variable/expression'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import type { SceneNode } from '@open-pencil/scene-graph'-import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'+import {+ bindingOverrideField,+ setInstanceOverride+} from '@open-pencil/scene-graph/instances/overrides'import type { InstanceOccurrence } from '../occurrence/types'import { uniformScaleOf } from '../types'@@ -36,7 +39,7 @@ export function recordVariableBindingClaims(owner.instanceOverrides,owner.id,target.id,- `boundVariables/${field}`,+ bindingOverrideField(field),target.boundVariables[field] ?? null)setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.tsindex e18f57650..af6f9ef46 100644--- a/packages/fig/src/instance-overrides/materialize-instance.ts+++ b/packages/fig/src/instance-overrides/materialize-instance.ts@@ -2,7 +2,10 @@ import { isEqual } from 'es-toolkit/predicate'import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'+import {+ bindingOverrideField,+ setInstanceOverride+} from '@open-pencil/scene-graph/instances/overrides'import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'import { nodeChangeToProps } from '../node-change'@@ -249,7 +252,7 @@ function recordPaintBindingClaims(for (const [index, paint] of paints.entries()) {const alias = (paint as Paint).colorVar?.value?.aliasif (!alias) continue- const field = `boundVariables/${scene}/${index}/color`+ const field = bindingOverrideField(`${scene}/${index}/color`)setInstanceOverride(owner.instanceOverrides,owner.id,diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.tsindex 654248038..bcc2d4e86 100644--- a/packages/fig/src/node-change/export/override-claims.ts+++ b/packages/fig/src/node-change/export/override-claims.ts@@ -6,10 +6,14 @@ import {import { compact } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { forEachInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'+import {+ forEachInstanceOverride,+ overriddenBindingField+} from '@open-pencil/scene-graph/instances/overrides'import type { GUID, Vector } from '@open-pencil/scene-graph/primitives'import { scaleNodeChanges } from '@open-pencil/scene-graph/scaling'import { ownsSlotContent } from '@open-pencil/scene-graph/slots'+import { paintBindingTarget } from '@open-pencil/scene-graph/variables'import { instanceExportAddress } from '../instance/geometry'import { mergeVariableConsumptionMaps, overrideVariableBindingEntry } from '../variable/bindings'@@ -164,19 +168,17 @@ function paintBindingOverride(target: SceneNode,bindingField: string): Partial<Pick<KiwiSymbolOverridePayload, 'fillPaints' | 'strokePaints'>> | undefined {- if (/^fills\/\d+\/color$/.test(bindingField))- return { fillPaints: createFillPaints(context, target) }- if (/^strokes\/\d+\/color$/.test(bindingField))- return { strokePaints: createStrokePaints(context, target) }+ const paint = paintBindingTarget(bindingField)+ if (paint?.list === 'fills') return { fillPaints: createFillPaints(context, target) }+ if (paint?.list === 'strokes') return { strokePaints: createStrokePaints(context, target) }return undefined}/** A binding override is a paint claim for paint colours and a consumption entry otherwise. */function bindingClaim({ context, instance, target }: ClaimInput,- field: string+ bindingField: string): Omit<KiwiSymbolOverridePayload, 'guidPath'> | undefined {- const bindingField = field.slice('boundVariables/'.length)const paints = paintBindingOverride(context, target, bindingField)if (paints) return paintsconst entry = overrideVariableBindingEntry(@@ -210,9 +212,9 @@ function overrideClaim(const input: ClaimInput = { ...claimed, target, nodeFields }if (field === 'componentId')return exportedSwapOverride(input.context, input.target, path, counter)- const claim = field.startsWith('boundVariables/')- ? bindingClaim(input, field)- : registryClaim(field as keyof SceneNode, input)+ const binding = overriddenBindingField(field)+ const claim =+ binding === null ? registryClaim(field as keyof SceneNode, input) : bindingClaim(input, binding)return claim && { guidPath: { guids: path }, ...claim }}diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.tsindex 4cee2e168..e77b6ea5e 100644--- a/packages/fig/src/node-change/plugin-data.ts+++ b/packages/fig/src/node-change/plugin-data.ts@@ -18,6 +18,7 @@ import {type PluginDataField} from '@open-pencil/scene-graph/plugin-data'import type { Rect } from '@open-pencil/scene-graph/primitives'+import { paintBindingTarget } from '@open-pencil/scene-graph/variables'import { readEffectiveFigmaRawField } from '../source-metadata'import {@@ -91,6 +92,17 @@ export function extractTextPathBox(nc: NodeChange): Rect | null {export function extractBoundVariables(nc: NodeChange): Record<string, string> {let bindings = readNodeChangePluginData(nc, boundVariables) ?? {}+ // Each paint carries its colour's alias. An instance's copy pairs its component's plugin data+ // with paints an override set, so the plugin data can name a binding those paints dropped.+ const decidedByPaints = (field: string) => {+ const list = paintBindingTarget(field)?.list+ return list === 'fills'+ ? nc.fillPaints !== undefined+ : list === 'strokes' && nc.strokePaints !== undefined+ }+ bindings = Object.fromEntries(+ Object.entries(bindings).filter(([field]) => !decidedByPaints(field))+ )for (const entry of variableConsumptionEntries(nc)) {const binding = resolveVariableConsumptionEntry(entry)if (binding) bindings[binding.field] = binding.variableIddiff --git a/packages/scene-graph/src/instances/main-component.ts b/packages/scene-graph/src/instances/main-component.tsindex 72ebbb54e..a68543c60 100644--- a/packages/scene-graph/src/instances/main-component.ts+++ b/packages/scene-graph/src/instances/main-component.ts@@ -1,5 +1,7 @@import type { SceneGraph } from '../graph'import type { SceneNode } from '../types'+import { paintBindingTarget } from '../variables/fields'+import { overriddenBindingField } from './overrides'/*** The main component an instance shows. An instance nested in another instance points at the@@ -23,8 +25,10 @@ export function ownsSelfFillField(target: SceneNode, field: string): boolean {const own = target.instanceOverrides.selfif (field === 'fills' || field === 'fillStyleId') return own.has(field) || own.has('fills')// A paint the layer set itself owns its bindings too, bound or not.+ const binding = overriddenBindingField(field)return (- field.startsWith('boundVariables/fills/') &&+ binding !== null &&+ paintBindingTarget(binding)?.list === 'fills' &&(own.has(field) || own.has('boundVariables') || own.has('fills')))}diff --git a/packages/scene-graph/src/instances/overrides.ts b/packages/scene-graph/src/instances/overrides.tsindex 8b880a5f7..8d1387b5c 100644--- a/packages/scene-graph/src/instances/overrides.ts+++ b/packages/scene-graph/src/instances/overrides.ts@@ -5,6 +5,23 @@ export interface InstanceOverrideState {descendants: Map<string, Map<InstanceOverrideField, unknown>>}+const BINDING_OVERRIDE_PREFIX = 'boundVariables/'++/**+ * The override field that claims a layer's binding of `field`, which keeps that binding, or its+ * absence, through a sync. `boundVariables` alone claims every binding of the layer.+ */+export function bindingOverrideField(field: string): InstanceOverrideField {+ return `${BINDING_OVERRIDE_PREFIX}${field}`+}++/** The binding field an override field claims, or null for an override of anything else. */+export function overriddenBindingField(field: InstanceOverrideField): string | null {+ return field.startsWith(BINDING_OVERRIDE_PREFIX)+ ? field.slice(BINDING_OVERRIDE_PREFIX.length)+ : null+}+export function createInstanceOverrideState(): InstanceOverrideState {return { self: new Map(), descendants: new Map() }}@@ -102,7 +119,7 @@ export function remapInstanceOverrideState(const remapValue = (field: string, value: unknown): unknown => {if (typeof value !== 'string') return structuredClone(value)if (field === 'componentId' || field === 'sourceComponentId') return references.node(value)- if (field.startsWith('boundVariables/')) return references.variable(value)+ if (overriddenBindingField(field) !== null) return references.variable(value)return value}const fields = (entries: ReadonlyMap<string, unknown>) =>diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex 42f858567..d5f92d9f9 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -20,8 +20,10 @@ import {import { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'import { ownsSelfFillField, sourceWithEffectiveFill } from './main-component'import {+ bindingOverrideField,getInstanceOverride,hasInstanceOverride as hasNodeInstanceOverride,+ overriddenBindingField,setInstanceOverride,type InstanceOverrideState} from './overrides'@@ -69,7 +71,7 @@ export function copyProp(export function bindingProtection(scopes: ReadonlySet<string>[]): (field: string) => boolean {const fields = new Set<string>()for (const scope of scopes) {- const perField = [...scope].some((field) => field.startsWith('boundVariables/'))+ const perField = [...scope].some((field) => overriddenBindingField(field) !== null)for (const field of scope) {if (field !== 'boundVariables' || !perField) fields.add(field)}@@ -91,7 +93,7 @@ export function syncBindingFields(...Object.keys(target.boundVariables),...Object.keys(target.variableBindingScales)])) {- if (!protectedField(`boundVariables/${field}`)) continue+ if (!protectedField(bindingOverrideField(field))) continueif (!Object.hasOwn(target.boundVariables, field)) Reflect.deleteProperty(bindings, field)else bindings[field] = target.boundVariables[field]if (target.variableBindingScales[field] === undefined) Reflect.deleteProperty(scales, field)@@ -109,7 +111,7 @@ export function isProtectedSyncField(return (protectedField(key) ||(key in node.boundVariables &&- (protectedField('boundVariables') || protectedField(`boundVariables/${key}`)))+ (protectedField('boundVariables') || protectedField(bindingOverrideField(key)))))}diff --git a/packages/scene-graph/src/transfer/nodes.ts b/packages/scene-graph/src/transfer/nodes.tsindex 49b945b57..061dfcbd3 100644--- a/packages/scene-graph/src/transfer/nodes.ts+++ b/packages/scene-graph/src/transfer/nodes.ts@@ -1,5 +1,5 @@import { cloneNodeProps } from '../copy'-import { remapInstanceOverrideState } from '../instances/overrides'+import { overriddenBindingField, remapInstanceOverrideState } from '../instances/overrides'import { remapStyleRunReferences, styleRunReferences } from '../text/references'import type { ComponentPropertyType, SceneNode } from '../types'import { requireTransferReference as required } from './references'@@ -37,7 +37,7 @@ export function semanticTransferReferences(node: SceneNode): string[] {typeof value === 'string' &&(field === 'componentId' ||field === 'sourceComponentId' ||- field.startsWith('boundVariables/'))+ overriddenBindingField(field) !== null)? [value]: [])diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex e1498fd76..e31809387 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -7,13 +7,15 @@ import { hasInstanceOverride } from '../instances'import type { Color } from '../primitives'import { pixelLength } from '../text/lengths'import type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'-import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'+import { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'import { variableText, variableTruthy } from './text'import { variableValueReferences } from './value'export {isNumericVariableBindingField,+ paintBindingTarget,TEXT_CONTENT_VARIABLE_TYPES,- VISIBILITY_VARIABLE_TYPES+ VISIBILITY_VARIABLE_TYPES,+ type PaintBindingList} from './fields'/** New declarations belong to the outermost occurrence, bounded by a component definition. */@@ -161,12 +163,12 @@ export function resolvedPaintBindings(const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}for (const field in node.boundVariables) {if (!field.endsWith('/color')) continue- const match = /^(fills|strokes)\/(\d+)\/color$/.exec(field)- if (!match) continue+ const paint = paintBindingTarget(field)+ if (!paint) continueconst color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)- const index = Number(match[2])+ const { index } = paintif (!color) continue- if (match[1] === 'fills') {+ if (paint.list === 'fills') {if (!node.fills[index]) continuechanges.fills ??= copyFills(node.fills)applyBoundColor(changes.fills[index], color)diff --git a/packages/scene-graph/src/variables/fields.ts b/packages/scene-graph/src/variables/fields.tsindex d502e9c0b..6831fd284 100644--- a/packages/scene-graph/src/variables/fields.ts+++ b/packages/scene-graph/src/variables/fields.ts@@ -61,3 +61,21 @@ export const VISIBILITY_VARIABLE_TYPES = ['BOOLEAN','STRING'] as const satisfies readonly VariableType[]++/** The paint lists whose colours bind to variables, one binding field per paint. */+export type PaintBindingList = 'fills' | 'strokes'++const PAINT_BINDING_FIELD = /^(fills|strokes)\/(\d+)\/color$/++/**+ * The paint a binding field names the colour of, such as the second fill for `fills/1/color`, or+ * null for a field that binds anything else.+ */+export function paintBindingTarget(+ field: string+): { list: PaintBindingList; index: number } | null {+ if (!field.endsWith('/color')) return null+ const match = PAINT_BINDING_FIELD.exec(field)+ if (!match) return null+ return { list: match[1] === 'fills' ? 'fills' : 'strokes', index: Number(match[2]) }+}diff --git a/packages/scene-graph/src/variables/index.ts b/packages/scene-graph/src/variables/index.tsindex 3fbb582f4..8bf0875e1 100644--- a/packages/scene-graph/src/variables/index.ts+++ b/packages/scene-graph/src/variables/index.ts@@ -4,7 +4,7 @@ import { omit, omitBy } from 'es-toolkit/object'import { BLACK } from '../constants'import type { SceneGraph } from '../graph'import { findInstanceAncestor } from '../instances'-import { setInstanceOverride } from '../instances/overrides'+import { bindingOverrideField, setInstanceOverride } from '../instances/overrides'import type {Variable,VariableCollection,@@ -19,6 +19,7 @@ import {} from './bindings'import {BOOLEAN_BINDING_FIELDS,+ paintBindingTarget,STRING_BINDING_FIELDS,TEXT_CONTENT_VARIABLE_TYPES,VISIBILITY_VARIABLE_TYPES@@ -243,22 +244,21 @@ export function bindVariable(}// Color fields require COLOR variable type- const colorFieldMatch = field.match(/^(fills|strokes)\/(\d+)\/color$/)- if (colorFieldMatch) {+ const paint = paintBindingTarget(field)+ if (paint) {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})`)+ const currentLength = node[paint.list].length+ if (paint.index >= currentLength) {+ throw new Error(+ `Index ${paint.index} out of range for ${paint.list} (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 (paint.list in node.boundVariables) {+ node.boundVariables = omit(node.boundVariables, [paint.list])}}@@ -283,7 +283,7 @@ export function bindVariable(isNumericVariableBindingField(field) ||STRING_BINDING_FIELDS.has(field) ||BOOLEAN_BINDING_FIELDS.has(field) ||- colorFieldMatch+ paint !== nullif (!isKnownField) {throw new Error(`Unknown binding field "${field}"`)@@ -331,7 +331,7 @@ function markBoundVariablesOverrideOnInstance(owner.instanceOverrides,owner.id,nodeId,- `boundVariables/${field}`,+ bindingOverrideField(field),node.boundVariables[field] ?? null)}diff --git a/packages/scene-graph/tests/instances/overrides.test.ts b/packages/scene-graph/tests/instances/overrides.test.tsnew file mode 100644index 000000000..b5d1fee46--- /dev/null+++ b/packages/scene-graph/tests/instances/overrides.test.ts@@ -0,0 +1,18 @@+import { describe, expect, test } from 'bun:test'++import {+ bindingOverrideField,+ overriddenBindingField+} from '@open-pencil/scene-graph/instances/overrides'++describe('binding override fields', () => {+ test('claim one binding of the layer, which they name', () => {+ expect(bindingOverrideField('fills/0/color')).toBe('boundVariables/fills/0/color')+ expect(overriddenBindingField(bindingOverrideField('opacity'))).toBe('opacity')+ })++ test('are not overrides of the layer’s fields, nor of all its bindings', () => {+ for (const field of ['fills', 'opacity', 'boundVariables'])+ expect(overriddenBindingField(field)).toBeNull()+ })+})diff --git a/packages/scene-graph/tests/variables/fields.test.ts b/packages/scene-graph/tests/variables/fields.test.tsnew file mode 100644index 000000000..8ead03df6--- /dev/null+++ b/packages/scene-graph/tests/variables/fields.test.ts@@ -0,0 +1,21 @@+import { describe, expect, test } from 'bun:test'++import { paintBindingTarget } from '@open-pencil/scene-graph/variables'++describe('paint binding fields', () => {+ test('name the fill or stroke whose colour they bind', () => {+ expect(paintBindingTarget('fills/1/color')).toEqual({ list: 'fills', index: 1 })+ expect(paintBindingTarget('strokes/0/color')).toEqual({ list: 'strokes', index: 0 })+ })++ test('are not any other binding field', () => {+ for (const field of [+ 'fills',+ 'opacity',+ 'effects/0/color',+ 'fills/first/color',+ 'fills/0/opacity'+ ])+ expect(paintBindingTarget(field)).toBeNull()+ })+})diff --git a/tests/engine/io/fig/instance/override-roundtrip.test.ts b/tests/engine/io/fig/instance/override-roundtrip.test.tsindex 2a8bde51b..8c16cc53d 100644--- a/tests/engine/io/fig/instance/override-roundtrip.test.ts+++ b/tests/engine/io/fig/instance/override-roundtrip.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'import { initCodec } from '@open-pencil/kiwi/fig/codec'import { SceneGraph } from '@open-pencil/scene-graph'+import type { Color } from '@open-pencil/scene-graph/primitives'describe('instance descendant fill override round trip', () => {test('a recolored nested instance child keeps its color after a save/reload cycle', async () => {@@ -43,4 +44,102 @@ describe('instance descendant fill override round trip', () => {const reloadedIconPath = reloadedIcon ? reloaded.getChildren(reloadedIcon.id)[0] : undefinedexpect(reloadedIconPath?.fills[0]?.color).toEqual({ r: 0, g: 0, b: 0, a: 1 })})++ test('a literal fill over a nested instance fill bound to a variable stays after reload', async () => {+ await initCodec()++ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const collection = graph.createCollection('Tokens')+ const accent = graph.createVariable('accent-soft', 'COLOR', collection.id, {+ r: 0.84,+ g: 0.93,+ b: 0.91,+ a: 1+ })+ const solid = (color: Color, opacity = 1) => [+ { type: 'SOLID' as const, color, opacity, visible: true }+ ]+ const button = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ width: 80,+ height: 30,+ fills: solid({ r: 0.13, g: 0.33, b: 0.8, a: 1 })+ })+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card', x: 200 })+ const nested = graph.createInstance(button.id, card.id)+ if (!nested) throw new Error('failed to create the nested instance')+ graph.bindVariable(nested.id, 'fills/0/color', accent.id)+ const use = graph.createInstance(card.id, page.id, { name: 'Use', y: 100 })+ if (!use) throw new Error('failed to create the instance')+ const copy = graph.getChildren(use.id)[0]+ graph.updateNode(copy.id, {+ fills: solid({ r: 0, g: 0, b: 0, a: 0 }, 0),+ boundVariables: {}+ })+ const { recordInstanceOverride } = await import('@open-pencil/scene-graph/instances')+ recordInstanceOverride(graph, copy.id, ['fills', 'boundVariables'])++ const reloaded = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const reloadedUse = [...reloaded.getAllNodes()].find((node) => node.name === 'Use')+ const reloadedCopy = reloadedUse ? reloaded.getChildren(reloadedUse.id)[0] : undefined+ if (!reloadedUse || !reloadedCopy) throw new Error('Missing the reloaded copy')+ // A sync, as editing the component would run, keeps the claim too.+ reloaded.syncInstance(reloadedUse.id)+ const synced = reloaded.getNode(reloadedCopy.id)+ expect(synced?.fills[0]).toMatchObject({ color: { r: 0, g: 0, b: 0, a: 0 }, opacity: 0 })+ expect(synced?.boundVariables['fills/0/color']).toBeUndefined()+ // Resetting the overrides brings back the binding the card gives its button.+ reloaded.updateNode(reloadedUse.id, {+ instanceOverrides: { self: new Map(), descendants: new Map() }+ })+ reloaded.updateNode(reloadedCopy.id, {+ instanceOverrides: { self: new Map(), descendants: new Map() }+ })+ reloaded.syncInstance(reloadedUse.id)+ const reset = reloaded.getNode(reloadedCopy.id)?.boundVariables['fills/0/color']+ expect(reset ? reloaded.variables.get(reset)?.name : reset).toBe('accent-soft')+ })++ test('a variable an outer instance binds over a nested literal fill stays after reload', async () => {+ await initCodec()++ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const collection = graph.createCollection('Tokens')+ const accent = graph.createVariable('accent-soft', 'COLOR', collection.id, {+ r: 0.84,+ g: 0.93,+ b: 0.91,+ a: 1+ })+ const solid = (color: Color) => [{ type: 'SOLID' as const, color, opacity: 1, visible: true }]+ const button = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ width: 80,+ height: 30,+ fills: solid({ r: 0.13, g: 0.33, b: 0.8, a: 1 })+ })+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card', x: 200 })+ const nested = graph.createInstance(button.id, card.id)+ if (!nested) throw new Error('failed to create the nested instance')+ const { recordInstanceOverride } = await import('@open-pencil/scene-graph/instances')+ // The card's button is red; the instance of the card binds that button to a token.+ graph.updateNode(nested.id, { fills: solid({ r: 0.9, g: 0.1, b: 0.1, a: 1 }) })+ recordInstanceOverride(graph, nested.id, ['fills'])+ const use = graph.createInstance(card.id, page.id, { name: 'Use', y: 100 })+ if (!use) throw new Error('failed to create the instance')+ const copy = graph.getChildren(use.id)[0]+ graph.updateNode(copy.id, { fills: solid({ r: 0.84, g: 0.93, b: 0.91, a: 1 }) })+ graph.bindVariable(copy.id, 'fills/0/color', accent.id)+ recordInstanceOverride(graph, copy.id, ['fills', 'boundVariables'])++ const reloaded = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const reloadedUse = [...reloaded.getAllNodes()].find((node) => node.name === 'Use')+ const reloadedCopy = reloadedUse ? reloaded.getChildren(reloadedUse.id)[0] : undefined+ if (!reloadedUse || !reloadedCopy) throw new Error('Missing the reloaded copy')+ reloaded.syncInstance(reloadedUse.id)+ const bound = reloaded.getNode(reloadedCopy.id)?.boundVariables['fills/0/color']+ expect(bound ? reloaded.variables.get(bound)?.name : undefined).toBe('accent-soft')+ })})