AI-native design editor. Open-source Figma alternative.
fix: keep variable bindings on their fill, stroke, or effect when the list changes (#1736)
Danila Poyarkov2736aaa1ad30
diff --git a/changes/1736/fixed.md b/changes/1736/fixed.mdnew file mode 100644index 000000000..d280267d3--- /dev/null+++ b/changes/1736/fixed.md@@ -0,0 +1 @@+- Removing a fill, stroke, or effect in the properties panel keeps each remaining item's variable binding on that item, instead of moving a binding onto the wrong paint or effect.diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex 811ee1cce..72fc9f594 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -341,3 +341,31 @@ export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScop}return relaid}++/** A layer list whose items carry their own bindings, keyed by position such as `fills/1/color`. */+export type BoundLayerList = 'fills' | 'strokes' | 'effects'++/**+ * `boundVariables` once the `list` items are rebuilt from `sources`, where `sources[i]` is the+ * position the new item `i` had before, or null for an added item. A binding moves with its item+ * and goes with a removed one, as Figma keeps a binding on its paint or effect.+ */+export function listBindingsAfterEdit(+ boundVariables: Readonly<Record<string, string>>,+ list: BoundLayerList,+ sources: readonly (number | null)[]+): Record<string, string> {+ const prefix = `${list}/`+ const moved: Record<string, string> = {}+ for (const [field, variableId] of Object.entries(boundVariables)) {+ if (!field.startsWith(prefix)) {+ moved[field] = variableId+ continue+ }+ const [index, ...property] = field.slice(prefix.length).split('/')+ const next = sources.indexOf(Number(index))+ if (next !== -1 && property.length > 0)+ moved[`${prefix}${next}/${property.join('/')}`] = variableId+ }+ return moved+}diff --git a/packages/scene-graph/tests/variable/binding/list-edits.test.ts b/packages/scene-graph/tests/variable/binding/list-edits.test.tsnew file mode 100644index 000000000..7882e4458--- /dev/null+++ b/packages/scene-graph/tests/variable/binding/list-edits.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from 'bun:test'++import { listBindingsAfterEdit } from '@open-pencil/scene-graph/variables'++const BOUND = {+ 'fills/0/color': 'red',+ 'fills/2/color': 'blue',+ 'effects/0/radius': 'blur',+ 'effects/1/color': 'shade',+ width: 'size'+}++describe('list bindings after an edit', () => {+ test('move with their fill when a fill above them is removed', () => {+ expect(listBindingsAfterEdit(BOUND, 'fills', [0, 2])).toEqual({+ 'fills/0/color': 'red',+ 'fills/1/color': 'blue',+ 'effects/0/radius': 'blur',+ 'effects/1/color': 'shade',+ width: 'size'+ })+ })++ test('go with the item removed', () => {+ expect(listBindingsAfterEdit(BOUND, 'fills', [1, 2])).toEqual({+ 'fills/1/color': 'blue',+ 'effects/0/radius': 'blur',+ 'effects/1/color': 'shade',+ width: 'size'+ })+ })++ test('follow every property of an effect that moves', () => {+ expect(listBindingsAfterEdit(BOUND, 'effects', [1, 0])).toEqual({+ 'fills/0/color': 'red',+ 'fills/2/color': 'blue',+ 'effects/0/color': 'shade',+ 'effects/1/radius': 'blur',+ width: 'size'+ })+ })++ test('stay put when an item is added after them, and go when the list is replaced', () => {+ expect(listBindingsAfterEdit(BOUND, 'fills', [0, 1, 2, null])).toEqual(BOUND)+ expect(listBindingsAfterEdit(BOUND, 'effects', [null])).toEqual({+ 'fills/0/color': 'red',+ 'fills/2/color': 'blue',+ width: 'size'+ })+ })+})diff --git a/packages/vue/src/controls/property-list/use.ts b/packages/vue/src/controls/property-list/use.tsindex ebf899901..06ab84049 100644--- a/packages/vue/src/controls/property-list/use.ts+++ b/packages/vue/src/controls/property-list/use.ts@@ -1,7 +1,7 @@import { computed } from 'vue'import type { SceneNode } from '@open-pencil/scene-graph'-import { resolvedPaintBindings } from '@open-pencil/scene-graph/variables'+import { listBindingsAfterEdit, resolvedPaintBindings } from '@open-pencil/scene-graph/variables'import { regionFillsDiffer } from '@open-pencil/scene-graph/vector-network'import { isNodeArrayMixed } from '#vue/controls/node-props/helpers'@@ -15,7 +15,7 @@ import type {PropertyListPatchFor} from '#vue/primitives/PropertyList/types.ts'-function moveItem<T>(items: T[], fromIndex: number, toIndex: number): T[] {+function moveItem<T>(items: readonly T[], fromIndex: number, toIndex: number): readonly T[] {if (fromIndex === toIndex || fromIndex < 0 || fromIndex >= items.length) return itemsconst next = [...items]const moved = next.splice(fromIndex, 1)[0]@@ -69,9 +69,27 @@ export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {return own.length === 0 && !isMixed.value ? items.value : own}- /** A text's fills colour every character, as a layer's own fills do in Figma. */- function updateArray(node: SceneNode, value: PropertyListItemFor<K>[], label: string) {- editor.updateNodeWithUndo(node.id, editor.layerChanges(node.id, { [propKey]: value }), label)+ /**+ * A text's fills colour every character, as a layer's own fills do in Figma. `sources` gives the+ * position each item had, or null for a new one, when the edit adds, removes, or moves items, so+ * their bindings follow them in the same undo step.+ */+ function updateArray(+ node: SceneNode,+ value: PropertyListItemFor<K>[],+ label: string,+ sources?: readonly (number | null)[]+ ) {+ const changes: Partial<SceneNode> = { [propKey]: value }+ if (sources) {+ changes.boundVariables = listBindingsAfterEdit(node.boundVariables, propKey, sources)+ }+ editor.updateNodeWithUndo(node.id, editor.layerChanges(node.id, changes), label)+ }++ /** The positions of a list of `length` items, as `sources` for an edit that keeps them. */+ function positions(length: number): number[] {+ return Array.from({ length }, (_, index) => index)}function add(item: PropertyListItemFor<K>) {@@ -82,8 +100,14 @@ export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {for (const node of nodes) {const nextItem = structuredClone(item)// Adding to mixed values replaces them, as Figma's "Click + to replace" does.- const next = isMulti.value || isMixed.value ? [nextItem] : [...propArray(node), nextItem]- updateArray(node, next, label)+ const replace = isMulti.value || isMixed.value+ const current = propArray(node)+ updateArray(+ node,+ replace ? [nextItem] : [...current, nextItem],+ label,+ replace ? [null] : [...positions(current.length), null]+ )}}if (nodes.length > 1) editor.undo.runBatch(label, apply)@@ -96,10 +120,13 @@ export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {const label = `Remove ${propKey}`const apply = () => {for (const node of nodes) {+ const current = propArray(node)+ const kept = positions(current.length).filter((itemIndex) => itemIndex !== index)updateArray(node,- propArray(node).filter((_, itemIndex) => itemIndex !== index),- label+ kept.map((itemIndex) => current[itemIndex]),+ label,+ kept)}}@@ -162,7 +189,14 @@ export function useEditorPropertyList<K extends PropertyListKey>(propKey: K) {if (nodes.length === 0 || fromIndex === toIndex) returnconst apply = () => {for (const node of nodes) {- updateArray(node, moveItem(propArray(node), fromIndex, toIndex), `Reorder ${propKey}`)+ const current = propArray(node)+ const order = moveItem(positions(current.length), fromIndex, toIndex)+ updateArray(+ node,+ order.map((itemIndex) => current[itemIndex]),+ `Reorder ${propKey}`,+ order+ )}}if (nodes.length > 1) editor.undo.runBatch(`Reorder ${propKey}`, apply)diff --git a/tests/e2e/properties/list-bindings.spec.ts b/tests/e2e/properties/list-bindings.spec.tsnew file mode 100644index 000000000..532ffa985--- /dev/null+++ b/tests/e2e/properties/list-bindings.spec.ts@@ -0,0 +1,41 @@+import { expect, test } from '@playwright/test'++import { CanvasHelper } from '#tests/helpers/canvas'++test('a fill’s colour binding stays with it when a fill above it is removed', async ({ page }) => {+ await page.goto('/?test')+ await new CanvasHelper(page).waitForInit()+ const { id, red, blue } = await page.evaluate(() => {+ const editor = window.openPencil?.getStore?.()+ if (!editor) throw new Error('Editor unavailable')+ const collection = editor.graph.createCollection('Theme')+ const solid = (r: number, g: number, b: number) => ({+ type: 'SOLID' as const,+ color: { r, g, b, a: 1 },+ opacity: 1,+ visible: true+ })+ const red = editor.graph.createVariable('Red', 'COLOR', collection.id, solid(1, 0, 0).color)+ const blue = editor.graph.createVariable('Blue', 'COLOR', collection.id, solid(0, 0, 1).color)+ const id = editor.createShape('RECTANGLE', 100, 100, 180, 120)+ editor.updateNode(id, { fills: [solid(1, 0, 0), solid(0, 1, 0), solid(0, 0, 1)] })+ editor.graph.bindVariable(id, 'fills/0/color', red.id)+ editor.graph.bindVariable(id, 'fills/2/color', blue.id)+ editor.select([id])+ return { id, red: red.id, blue: blue.id }+ })+ const bindings = () =>+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.boundVariables, id)+ const fillCount = () =>+ page.evaluate((id) => window.openPencil?.getStore?.().graph.getNode(id)?.fills.length, id)++ const fill = page.getByRole('region', { name: 'Fill', exact: true })+ await fill.getByRole('button', { name: 'Remove fill' }).nth(1).click()+ await expect.poll(fillCount).toBe(2)+ await expect.poll(bindings).toEqual({ 'fills/0/color': red, 'fills/1/color': blue })++ await fill.getByRole('heading', { name: 'Fill' }).click()+ await page.keyboard.press(process.platform === 'darwin' ? 'Meta+z' : 'Control+z')+ await expect.poll(fillCount).toBe(3)+ await expect.poll(bindings).toEqual({ 'fills/0/color': red, 'fills/2/color': blue })+})