AI-native design editor. Open-source Figma alternative.
fix(fig): keep a copy's edits to the slot content of an instance it holds (#1270)
Niraj Sangani0fe6c3979fb6
diff --git a/changes/1270/fixed.md b/changes/1270/fixed.mdnew file mode 100644index 000000000..f2c37a909--- /dev/null+++ b/changes/1270/fixed.md@@ -0,0 +1 @@+- A copy of a component that holds an instance keeps what it sets on that instance after the file is saved and reopened: edits to its slot content, such as a hidden or recoloured layer, and its text, boolean, and swap property values, such as an exposed button's label.diff --git a/packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.ts b/packages/core/tests/io/formats/fig/roundtrip/overrides/instance.test.tssimilarity index 100%rename from packages/core/tests/io/formats/fig/roundtrip/instance-overrides.test.tsrename to packages/core/tests/io/formats/fig/roundtrip/overrides/instance.test.tsdiff --git a/packages/core/tests/io/formats/fig/roundtrip/overrides/nested-properties.test.ts b/packages/core/tests/io/formats/fig/roundtrip/overrides/nested-properties.test.tsnew file mode 100644index 000000000..c0e84415d--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/overrides/nested-properties.test.ts@@ -0,0 +1,122 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'+import { initCodec } from '@open-pencil/kiwi/fig/codec'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { createEditor } from '@open-pencil/core/editor'+import { parseFigBuffer } from '@open-pencil/fig'+import {+ componentPropertyDefinitions,+ createComponentPropertyId+} from '@open-pencil/scene-graph/components'++import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'++interface OverrideRecord {+ name?: string+ symbolData?: { symbolOverrides?: Array<{ componentPropAssignments?: unknown[] }> }+}++function find(graph: SceneGraph, root: string, name: string): SceneNode {+ const visit = (id: string): SceneNode | undefined => {+ for (const child of graph.getChildren(id)) {+ if (child.name === name) return child+ const found = visit(child.id)+ if (found) return found+ }+ return undefined+ }+ return expectDefined(visit(root))+}++const firstPage = (graph: SceneGraph) => expectDefined(graph.getPages().at(0)).id++async function reopen(graph: SceneGraph) {+ // Without its archive the export encodes every record, which is what this checks.+ releaseFigPopulationWorker(graph)+ const bytes = await exportFigFile(graph)+ return {+ reopened: await parseFigFile(bytes.slice().buffer),+ records: parseFigBuffer(bytes.slice().buffer).nodeChanges as OverrideRecord[]+ }+}++/** The values a record's overrides give the instances it holds. */+function nestedAssignmentCount(records: OverrideRecord[], name: string): number {+ const record = expectDefined(records.find((item) => item.name === name))+ return (record.symbolData?.symbolOverrides ?? []).filter(+ (override) => (override.componentPropAssignments?.length ?? 0) > 0+ ).length+}++beforeAll(async () => {+ await initCodec()+})++describe('a copy of a component that holds an instance with properties', () => {+ /** A Button with a Label and a Shown icon, held by a Card, and a copy of the Card. */+ function authored(edit: (editor: ReturnType<typeof createEditor>, button: SceneNode) => void) {+ const editor = createEditor()+ const { graph } = editor+ const page = editor.state.currentPageId+ const label = createComponentPropertyId()+ const shown = createComponentPropertyId()+ const button = graph.createNode('COMPONENT', page, {+ name: 'Button',+ componentPropertyDefinitions: [+ { id: label, name: 'Label', type: 'TEXT', defaultValue: 'Continue' },+ { id: shown, name: 'Shown', type: 'BOOLEAN', defaultValue: 'true' }+ ]+ })+ graph.createNode('TEXT', button.id, {+ name: 'Text',+ text: 'Continue',+ componentPropertyReferences: [{ propertyId: label, field: 'TEXT' }]+ })+ graph.createNode('FRAME', button.id, {+ name: 'Icon',+ width: 10,+ height: 10,+ componentPropertyReferences: [{ propertyId: shown, field: 'VISIBLE' }]+ })+ const card = graph.createNode('COMPONENT', page, { name: 'Card', width: 300, height: 200 })+ const action = expectDefined(graph.createInstance(button.id, card.id))+ graph.updateNode(action.id, { name: 'Action', isExposedInstance: true })+ const copy = expectDefined(graph.createInstance(card.id, page))+ copy.name = 'Copy'+ edit(editor, find(graph, copy.id, 'Action'))+ return graph+ }++ function propertyId(graph: SceneGraph, instance: SceneNode, name: string): string {+ return expectDefined(+ componentPropertyDefinitions(graph, instance).find((item) => item.name === name)+ ).id+ }++ test('keeps the text and boolean values the copy gives its Action after reopening', async () => {+ const graph = authored((editor, action) => {+ editor.setInstanceComponentProperty(action.id, propertyId(editor.graph, action, 'Label'), 'Save')+ editor.setInstanceComponentProperty(action.id, propertyId(editor.graph, action, 'Shown'), 'false')+ })+ const { reopened } = await reopen(graph)+ const copy = find(reopened, firstPage(reopened), 'Copy')+ const action = find(reopened, copy.id, 'Action')+ expect(find(reopened, action.id, 'Text').text).toBe('Save')+ expect(find(reopened, action.id, 'Icon').visible).toBe(false)+ expect(action.componentPropertyAssignments).toEqual({+ [propertyId(reopened, action, 'Label')]: 'Save',+ [propertyId(reopened, action, 'Shown')]: 'false'+ })+ // The Card's own Action keeps the Button's defaults.+ const card = find(reopened, firstPage(reopened), 'Card')+ expect(find(reopened, find(reopened, card.id, 'Action').id, 'Text').text).toBe('Continue')+ })++ test('writes no values for a copy that left its Action as it was', async () => {+ const { records } = await reopen(authored(() => undefined))+ expect(nestedAssignmentCount(records, 'Copy')).toBe(0)+ })+})diff --git a/packages/core/tests/io/formats/fig/roundtrip/overrides/slot-copies.test.ts b/packages/core/tests/io/formats/fig/roundtrip/overrides/slot-copies.test.tsnew file mode 100644index 000000000..9864bc0b8--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/overrides/slot-copies.test.ts@@ -0,0 +1,203 @@+import { beforeAll, describe, expect, test } from 'bun:test'++import { expectDefined } from '#core-tests/helpers/assert'++import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'+import { initCodec } from '@open-pencil/kiwi/fig/codec'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { createEditor } from '@open-pencil/core/editor'+import { parseFigBuffer } from '@open-pencil/fig'+import { createComponentPropertyId } from '@open-pencil/scene-graph/components'+import { rescaleNodeTree } from '@open-pencil/scene-graph/scaling'+import { slotPropertyId } from '@open-pencil/scene-graph/slots'++import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'++interface SlotRecord {+ isSlotContent?: boolean+}++function find(graph: SceneGraph, root: string, name: string): SceneNode {+ const visit = (id: string): SceneNode | undefined => {+ for (const child of graph.getChildren(id)) {+ if (child.name === name) return child+ const found = visit(child.id)+ if (found) return found+ }+ return undefined+ }+ return expectDefined(visit(root))+}++const firstPage = (graph: SceneGraph) => expectDefined(graph.getPages().at(0)).id++async function reopen(graph: SceneGraph) {+ // Without its archive the export encodes every record, which is what this checks.+ releaseFigPopulationWorker(graph)+ const bytes = await exportFigFile(graph)+ return {+ reopened: await parseFigFile(bytes.slice().buffer),+ records: parseFigBuffer(bytes.slice().buffer).nodeChanges+ }+}++function slotContentCount(records: unknown[]): number {+ return records.filter((record) => (record as SlotRecord).isSlotContent).length+}++beforeAll(async () => {+ await initCodec()+})++describe('a copy of a component that holds an instance with slot content', () => {+ function authored(+ edit: (editor: ReturnType<typeof createEditor>, copy: SceneNode, slot: string) => void,+ withLeaf = false+ ) {+ const editor = createEditor()+ const { graph } = editor+ const page = editor.state.currentPageId+ const slot = createComponentPropertyId()+ const inner = graph.createNode('COMPONENT', page, {+ name: 'Inner',+ componentPropertyDefinitions: [{ id: slot, name: 'Body', type: 'SLOT', defaultValue: '' }]+ })+ graph.createNode('FRAME', inner.id, {+ name: 'Body',+ width: 200,+ height: 100,+ componentPropertyReferences: [{ propertyId: slot, field: 'SLOT_CONTENT' }]+ })+ const outer = graph.createNode('COMPONENT', page, { name: 'Outer', width: 300, height: 200 })+ const nested = expectDefined(graph.createInstance(inner.id, outer.id))+ const nestedSlot = expectDefined(+ graph.getChildren(nested.id).find((child) => slotPropertyId(child))+ )+ editor.createShape('RECTANGLE', 0, 0, 20, 20, nestedSlot.id, 'A')+ editor.createShape('RECTANGLE', 0, 0, 20, 20, nestedSlot.id, 'B')+ if (withLeaf) {+ const leaf = graph.createNode('COMPONENT', page, { name: 'Leaf', width: 10, height: 10 })+ expectDefined(graph.createInstance(leaf.id, nestedSlot.id)).name = 'L'+ }+ const copy = expectDefined(graph.createInstance(outer.id, page))+ copy.name = 'Copy'+ edit(editor, copy, slot)+ return graph+ }++ async function slotContentWithoutCopy(withLeaf = false): Promise<number> {+ const { records } = await reopen(+ authored((editor, copy) => editor.graph.deleteNode(copy.id), withLeaf)+ )+ return slotContentCount(records)+ }++ test('keeps a slot layer hidden and another recoloured in the copy', async () => {+ const red = {+ type: 'SOLID' as const,+ color: { r: 1, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ blendMode: 'NORMAL' as const+ }+ const graph = authored((editor, copy) => {+ editor.graph.updateNode(find(editor.graph, copy.id, 'A').id, { visible: false })+ editor.graph.updateNode(find(editor.graph, copy.id, 'B').id, { fills: [red] })+ })+ const { reopened } = await reopen(graph)+ const copy = find(reopened, firstPage(reopened), 'Copy')+ expect(find(reopened, copy.id, 'A').visible).toBe(false)+ expect(find(reopened, copy.id, 'B').visible).toBe(true)+ expect(find(reopened, copy.id, 'B').fills).toEqual([red])+ // The component's own slot content keeps its layers as they were.+ const outer = find(reopened, firstPage(reopened), 'Outer')+ expect(find(reopened, outer.id, 'A').visible).toBe(true)+ expect(find(reopened, outer.id, 'B').fills).not.toEqual([red])+ })++ test('writes no slot content for a copy that left the slot as it was', async () => {+ const { records } = await reopen(authored(() => undefined))+ // The untouched copy adds nothing to what Outer's own nested instance writes.+ expect(slotContentCount(records)).toBe(await slotContentWithoutCopy())+ })++ test('writes no slot content for a copy whose nested instance was swapped but kept its slot', async () => {+ const { records } = await reopen(+ authored((editor, copy, slot) => {+ const page = editor.state.currentPageId+ const other = editor.graph.createNode('COMPONENT', page, {+ name: 'Other',+ componentPropertyDefinitions: [{ id: slot, name: 'Body', type: 'SLOT', defaultValue: '' }]+ })+ editor.graph.createNode('FRAME', other.id, {+ name: 'Body',+ width: 200,+ height: 100,+ componentPropertyReferences: [{ propertyId: slot, field: 'SLOT_CONTENT' }]+ })+ const nested = expectDefined(editor.graph.getChildren(copy.id).at(0))+ editor.graph.swapInstanceComponent(nested.id, other.id)+ })+ )+ expect(slotContentCount(records)).toBe(await slotContentWithoutCopy())+ })++ test('writes no slot content for a copy that was only rescaled', async () => {+ const { records } = await reopen(+ authored((editor, copy) => rescaleNodeTree(editor.graph, copy.id, 1.5))+ )+ expect(slotContentCount(records)).toBe(await slotContentWithoutCopy())+ })++ test('keeps a slot edit made in a rescaled copy', async () => {+ const graph = authored((editor, copy) => {+ rescaleNodeTree(editor.graph, copy.id, 1.5)+ editor.graph.updateNode(find(editor.graph, copy.id, 'A').id, { visible: false })+ })+ const { reopened } = await reopen(graph)+ const copy = find(reopened, firstPage(reopened), 'Copy')+ expect(find(reopened, copy.id, 'A').visible).toBe(false)+ expect(find(reopened, copy.id, 'B').visible).toBe(true)+ })+ test('writes no slot content for a rescaled copy whose slot holds an instance', async () => {+ const { records } = await reopen(+ authored((editor, copy) => rescaleNodeTree(editor.graph, copy.id, 1.5), true)+ )+ expect(slotContentCount(records)).toBe(await slotContentWithoutCopy(true))+ })++ test('keeps an instance in the slot swapped to another component in the copy', async () => {+ const { records } = await reopen(+ authored((editor, copy) => {+ const other = editor.graph.createNode('COMPONENT', editor.state.currentPageId, {+ name: 'Leaf2',+ width: 10,+ height: 10+ })+ editor.graph.swapInstanceComponent(find(editor.graph, copy.id, 'L').id, other.id)+ }, true)+ )+ expect(slotContentCount(records)).toBeGreaterThan(await slotContentWithoutCopy(true))+ })++ test('writes no slot content when a replacement component names the slot with an id of its own', async () => {+ const { records } = await reopen(+ authored((editor, copy) => {+ const slot = createComponentPropertyId()+ const other = editor.graph.createNode('COMPONENT', editor.state.currentPageId, {+ name: 'Other',+ componentPropertyDefinitions: [{ id: slot, name: 'Body', type: 'SLOT', defaultValue: '' }]+ })+ editor.graph.createNode('FRAME', other.id, {+ name: 'Body',+ width: 200,+ height: 100,+ componentPropertyReferences: [{ propertyId: slot, field: 'SLOT_CONTENT' }]+ })+ const nested = expectDefined(editor.graph.getChildren(copy.id).at(0))+ editor.graph.swapInstanceComponent(nested.id, other.id)+ })+ )+ expect(slotContentCount(records)).toBe(await slotContentWithoutCopy())+ })+})diff --git a/packages/fig/src/instance-overrides/live-component-edits.ts b/packages/fig/src/instance-overrides/live-component-edits.tsindex bef2b0fdc..758ff2044 100644--- a/packages/fig/src/instance-overrides/live-component-edits.ts+++ b/packages/fig/src/instance-overrides/live-component-edits.ts@@ -1,6 +1,6 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { INSTANCE_SYNC_FIELDS } from '@open-pencil/scene-graph/instances'-import { getInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'+import { copiedComponentLayerId } from '@open-pencil/scene-graph/instances/overrides'import type { MaterializedInstance } from './materialize-instance'@@ -23,13 +23,7 @@ function owningInstances(graph: SceneGraph, target: SceneNode): SceneNode[] {export function syncSourceLayers(graph: SceneGraph, target: SceneNode): SceneNode[] {const sources: SceneNode[] = []for (const owner of owningInstances(graph, target)) {- const mapped = getInstanceOverride(- owner.instanceOverrides,- owner.id,- target.id,- 'sourceComponentId'- )- const sourceId = typeof mapped === 'string' ? mapped : target.componentId+ const sourceId = copiedComponentLayerId(owner.instanceOverrides, owner.id, target)const source = sourceId ? graph.getNode(sourceId) : undefinedif (source) sources.push(source)}diff --git a/packages/fig/src/node-change/export/assignments/nested.ts b/packages/fig/src/node-change/export/assignments/nested.tsnew file mode 100644index 000000000..bf2558e2b--- /dev/null+++ b/packages/fig/src/node-change/export/assignments/nested.ts@@ -0,0 +1,194 @@+import { compact, isEqual, isPlainObject } from 'es-toolkit'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { findInstanceAncestor } from '@open-pencil/scene-graph/instances'+import { copiedComponentLayerId } from '@open-pencil/scene-graph/instances/overrides'+import { scaleNodeChanges } from '@open-pencil/scene-graph/scaling'+import { instanceSlotFrames, slotPropertyId } from '@open-pencil/scene-graph/slots'++import type { SceneNodeToKiwiContext } from '../context'+import { componentPropAssignment } from './values'++/** Fields that identify a layer or link it to its source rather than describe how it looks. */+const IDENTITY_FIELDS = new Set([+ 'id',+ 'parentId',+ 'childIds',+ 'source',+ 'componentId',+ 'overrideKey',+ 'instanceOverrides'+])++/** Scale maps hold `1` for a field that was never rescaled, which is the same as no entry. */+function withoutUnitScales(+ scales: Partial<Record<string, number>>+): Partial<Record<string, number>> {+ return Object.fromEntries(+ Object.entries(scales).filter(([, value]) => value === undefined || !sameValue(value, 1))+ )+}++/**+ * Whether two field values match, where numbers that differ only by the rounding of a rescale+ * are the same and a field a rescale left undefined is the same as one that is missing.+ */+function sameValue(a: unknown, b: unknown): boolean {+ if (typeof a === 'number' && typeof b === 'number')+ return Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b))+ if (Array.isArray(a) && Array.isArray(b))+ return a.length === b.length && a.every((item, index) => sameValue(item, b[index]))+ if (isPlainObject(a) && isPlainObject(b)) {+ const keys = new Set([...Object.keys(a), ...Object.keys(b)])+ return [...keys].every((key) => sameValue(a[key], b[key]))+ }+ return isEqual(a, b)+}++/**+ * A layer as it looks at the source's scale. A copy rescaled with its instance holds every+ * layer scaled, which is not an edit of the slot.+ */+function atSourceScale(node: SceneNode, ratio: number): SceneNode {+ if (ratio === 1) return node+ const unscale = (scales: Partial<Record<string, number>>) =>+ Object.fromEntries(+ Object.entries(scales).map(([field, value]) => [field, value && value / ratio])+ )+ return {+ ...node,+ ...scaleNodeChanges(node, 1 / ratio, true),+ // A rescale also changes the units its variable bindings and assignments resolve in.+ variableBindingScales: unscale(node.variableBindingScales),+ variableAssignmentScales: unscale(node.variableAssignmentScales),+ componentScale: node.componentScale / ratio+ }+}++/**+ * Whether a layer and its source match, descendants included. It stops at the first difference+ * and only visits one slot's layers, so its cost follows the size of that slot's content.+ */+function sameLayer(+ graph: SceneGraph,+ layer: SceneNode,+ source: SceneNode,+ ratio: number,+ slotProperty?: { from: string; to: string }+): boolean {+ const scaled = atSourceScale(layer, ratio)+ const a: SceneNode = {+ ...scaled,+ variableBindingScales: withoutUnitScales(scaled.variableBindingScales),+ variableAssignmentScales: withoutUnitScales(scaled.variableAssignmentScales),+ // A replacement component gives the slot a property id of its own; the layers match by name.+ componentPropertyReferences: scaled.componentPropertyReferences.map((reference) =>+ reference.propertyId === slotProperty?.from+ ? { ...reference, propertyId: slotProperty.to }+ : reference+ )+ }+ const b: SceneNode = {+ ...source,+ variableBindingScales: withoutUnitScales(source.variableBindingScales),+ variableAssignmentScales: withoutUnitScales(source.variableAssignmentScales)+ }+ const keys = new Set([...Object.keys(a), ...Object.keys(b)] as Array<keyof SceneNode>)+ for (const key of keys) {+ if (!IDENTITY_FIELDS.has(key) && !sameValue(a[key], b[key])) return false+ }+ // A copy's clone of an instance points at the layer it clones; a swap points it at another+ // component, which is an edit of the slot.+ if (+ layer.type === 'INSTANCE' &&+ layer.componentId !== source.id &&+ layer.componentId !== source.componentId+ )+ return false+ const aChildren = graph.getChildren(layer.id)+ const bChildren = graph.getChildren(source.id)+ return (+ aChildren.length === bChildren.length &&+ aChildren.every((child, index) => sameLayer(graph, child, bChildren[index], ratio))+ )+}++/** An instance's slot frames, by slot property. */+function slotFrames(graph: SceneGraph, instance: SceneNode): Map<string, SceneNode> {+ return new Map(+ instanceSlotFrames(graph, instance).flatMap((frame) => {+ const propertyId = slotPropertyId(frame)+ return propertyId ? [[propertyId, frame] as const] : []+ })+ )+}++/** The layer a nested instance copies: its component's, or the one a swap left in its owner. */+function nestedSource(+ graph: SceneGraph,+ owner: SceneNode,+ nested: SceneNode+): SceneNode | undefined {+ // A swap replaces the nested instance's component and keeps the one it copied in the owner.+ const sourceOwner = (nested.parentId && findInstanceAncestor(graph, nested.parentId)) || owner+ const sourceId = copiedComponentLayerId(sourceOwner.instanceOverrides, sourceOwner.id, nested)+ return sourceId ? graph.getNode(sourceId) : undefined+}++/** Whether a nested instance's slot holds something other than what the instance it copies shows. */+function slotDiffersFromSource(+ context: SceneNodeToKiwiContext,+ source: SceneNode | undefined,+ frame: SceneNode,+ propertyId: string+): boolean {+ const graph = context.graph+ // A replacement component names its slot the same but gives it a property id of its own.+ const slotName = context.componentPropertyDefinitionsById.get(propertyId)?.name+ const match =+ source?.type === 'INSTANCE' && slotName !== undefined+ ? [...slotFrames(graph, source)].find(([sourcePropertyId]) => {+ const definition = context.componentPropertyDefinitionsById.get(sourcePropertyId)+ return definition?.type === 'SLOT' && definition.name === slotName+ })+ : undefined+ if (!match) return true+ const [sourcePropertyId, counterpart] = match+ return !sameLayer(graph, frame, counterpart, frame.componentScale / counterpart.componentScale, {+ from: propertyId,+ to: sourcePropertyId+ })+}++/**+ * The component property values a copy gives an instance it holds, which Figma stores on an+ * override at that instance's path. A copy keeps the nested instance's slot content as its own+ * layers, and its text, boolean, and swap values on the instance; only those that differ from+ * what the instance it copies shows are written, so a copy left as it was writes none.+ */+export function nestedPropertyAssignments(+ context: SceneNodeToKiwiContext,+ owner: SceneNode,+ nested: SceneNode,+ localIdCounter: { value: number }+) {+ const source = nestedSource(context.graph, owner, nested)+ const frames = slotFrames(context.graph, nested)+ return compact(+ Object.entries(nested.componentPropertyAssignments).map(([propertyId, value]) => {+ const definition = context.componentPropertyDefinitionsById.get(propertyId)+ if (!definition) return null+ if (definition.type === 'SLOT') {+ const frame = frames.get(propertyId)+ if (!frame || !slotDiffersFromSource(context, source, frame, propertyId)) return null+ } else {+ const shown =+ source?.type === 'INSTANCE'+ ? (source.componentPropertyAssignments[propertyId] ?? definition.defaultValue)+ : definition.defaultValue+ if (value === shown) return null+ }+ return componentPropAssignment(context, nested, propertyId, value, localIdCounter)+ })+ )+}diff --git a/packages/fig/src/node-change/export/assignments/values.ts b/packages/fig/src/node-change/export/assignments/values.tsnew file mode 100644index 000000000..9ddfc0b00--- /dev/null+++ b/packages/fig/src/node-change/export/assignments/values.ts@@ -0,0 +1,73 @@+import type { SceneNode } from '@open-pencil/scene-graph'++import {+ getOrCreateNodeGuid,+ getOrCreatePropertyGuid,+ parseGuidOrNull,+ type SceneNodeToKiwiContext+} from '../context'+import { slotContentAssignment } from '../slots'++export function componentPropertyValue(+ type: string,+ value: string,+ context: SceneNodeToKiwiContext,+ localIdCounter: { value: number }+) {+ if (type === 'BOOLEAN') return { boolValue: value === 'true' }+ if (type === 'INSTANCE_SWAP') {+ const target = context.graph.getNode(value)+ const guid = target+ ? getOrCreateNodeGuid(context, target.id, localIdCounter)+ : parseGuidOrNull(value)+ return guid ? { guidValue: guid } : { textValue: { characters: value } }+ }+ return { textValue: { characters: value } }+}++export function componentPropertyVariableValue(+ type: string,+ value: string,+ context: SceneNodeToKiwiContext,+ localIdCounter: { value: number }+) {+ const legacy = componentPropertyValue(type, value, context, localIdCounter)+ if (type === 'BOOLEAN')+ return {+ value: { boolValue: value === 'true' },+ dataType: 'BOOLEAN',+ resolvedDataType: 'BOOLEAN'+ }+ if (type === 'INSTANCE_SWAP' && 'guidValue' in legacy) {+ return {+ value: { symbolIdValue: { guid: legacy.guidValue } },+ dataType: 'SYMBOL_ID',+ resolvedDataType: 'SYMBOL_ID'+ }+ }+ return { value: { textValue: value }, dataType: 'STRING', resolvedDataType: 'STRING' }+}++/**+ * An instance's value for one component property, as `componentPropAssignments` holds it: on+ * the instance's own record, or on the override at a nested instance's path. `null` for a+ * property the export knows no definition of.+ */+export function componentPropAssignment(+ context: SceneNodeToKiwiContext,+ instance: SceneNode,+ propertyId: string,+ value: string,+ localIdCounter: { value: number }+) {+ const definition = context.componentPropertyDefinitionsById.get(propertyId)+ if (!definition) return null+ const defID = getOrCreatePropertyGuid(context, propertyId, localIdCounter)+ if (definition.type === 'SLOT')+ return slotContentAssignment(context, instance, propertyId, defID, localIdCounter)+ return {+ defID,+ value: componentPropertyValue(definition.type, value, context, localIdCounter),+ varValue: componentPropertyVariableValue(definition.type, value, context, localIdCounter)+ }+}diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex 50ca80e06..8b8cf8457 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -1,5 +1,6 @@import type { DerivedSymbolOverride } from '#fig/instance-overrides/types'import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '#fig/source-metadata'+import { compact } from 'es-toolkit/array'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { stringToGuid } from '@open-pencil/kiwi/fig/guid'@@ -32,6 +33,11 @@ import {serializePluginRelaunchData} from '../plugin-data'import { serializeNodeStatus } from '../status'+import {+ componentPropAssignment,+ componentPropertyValue,+ componentPropertyVariableValue+} from './assignments/values'import {applyColorVariableBinding,createFillPaints,@@ -49,7 +55,7 @@ import {import { generatedFrameRecord, writesGeneratedFrame } from './generated'import { mergeOverrides, serializeRuntimePropertyOverrides } from './override-claims'import { exportedNode } from './resolved-bindings'-import { slotContentAssignment, slotDefinitionFields } from './slots'+import { slotDefinitionFields } from './slots'import { serializeText } from './text'export type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'@@ -118,46 +124,6 @@ function componentPropertyTypeForKiwi(type: string) {return type}-function componentPropertyValue(- type: string,- value: string,- context: SceneNodeToKiwiContext,- localIdCounter: { value: number }-) {- if (type === 'BOOLEAN') return { boolValue: value === 'true' }- if (type === 'INSTANCE_SWAP') {- const target = context.graph.getNode(value)- const guid = target- ? getOrCreateNodeGuid(context, target.id, localIdCounter)- : parseGuidOrNull(value)- return guid ? { guidValue: guid } : { textValue: { characters: value } }- }- return { textValue: { characters: value } }-}--function componentPropertyVariableValue(- type: string,- value: string,- context: SceneNodeToKiwiContext,- localIdCounter: { value: number }-) {- const legacy = componentPropertyValue(type, value, context, localIdCounter)- if (type === 'BOOLEAN')- return {- value: { boolValue: value === 'true' },- dataType: 'BOOLEAN',- resolvedDataType: 'BOOLEAN'- }- if (type === 'INSTANCE_SWAP' && 'guidValue' in legacy) {- return {- value: { symbolIdValue: { guid: legacy.guidValue } },- dataType: 'SYMBOL_ID',- resolvedDataType: 'SYMBOL_ID'- }- }- return { value: { textValue: value }, dataType: 'STRING', resolvedDataType: 'STRING' }-}-function serializeVariableModes(node: SceneNode,variableIdToGuid?: Map<string, GUID>,@@ -721,25 +687,11 @@ function applyComponentMetadata(}applyParameterReferences(nc, parameterRefs)- const componentPropAssignments = Object.entries(node.componentPropertyAssignments)- .map(([propertyId, value]) => {- const definition = context.componentPropertyDefinitionsById.get(propertyId)- if (!definition) return null- if (definition.type === 'SLOT')- return slotContentAssignment(- context,- node,- propertyId,- getOrCreatePropertyGuid(context, propertyId, localIdCounter),- localIdCounter- )- return {- defID: getOrCreatePropertyGuid(context, propertyId, localIdCounter),- value: componentPropertyValue(definition.type, value, context, localIdCounter),- varValue: componentPropertyVariableValue(definition.type, value, context, localIdCounter)- }- })- .filter((assignment): assignment is NonNullable<typeof assignment> => assignment !== null)+ const componentPropAssignments = compact(+ Object.entries(node.componentPropertyAssignments).map(([propertyId, value]) =>+ componentPropAssignment(context, node, propertyId, value, localIdCounter)+ )+ )if (shouldSerializeRawBackedField(node,diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.tsindex bcc2d4e86..1f01242ee 100644--- a/packages/fig/src/node-change/export/override-claims.ts+++ b/packages/fig/src/node-change/export/override-claims.ts@@ -17,6 +17,7 @@ import { paintBindingTarget } from '@open-pencil/scene-graph/variables'import { instanceExportAddress } from '../instance/geometry'import { mergeVariableConsumptionMaps, overrideVariableBindingEntry } from '../variable/bindings'+import { nestedPropertyAssignments } from './assignments/nested'import {createFillPaints,createStrokePaints,@@ -256,6 +257,14 @@ export function serializeRuntimePropertyOverrides()if (claim) result.push(claim)})+ if (node.type === 'INSTANCE' && node.id !== instance.id) {+ const resolved = resolveTarget(node, node.id)+ const assignments = resolved+ ? nestedPropertyAssignments(context, instance, node, localIdCounter)+ : []+ if (resolved && assignments.length > 0)+ result.push({ guidPath: { guids: resolved.path }, componentPropAssignments: assignments })+ }// Slot content the instance owns carries its own values; it has no component address.if (ownsSlotContent(context.graph, node)) returnfor (const child of context.graph.getChildren(node.id)) visit(child)diff --git a/packages/fig/src/node-change/instance/geometry.ts b/packages/fig/src/node-change/instance/geometry.tsindex 3dabbb6e3..06cc01962 100644--- a/packages/fig/src/node-change/instance/geometry.ts+++ b/packages/fig/src/node-change/instance/geometry.ts@@ -3,7 +3,7 @@ import type { DerivedSymbolOverride } from '#fig/instance-overrides/types'import type { GUID } from '@open-pencil/kiwi/fig'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { findInstanceAncestor } from '@open-pencil/scene-graph/instances'-import { getInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'+import { copiedComponentLayerId } from '@open-pencil/scene-graph/instances/overrides'import { ownsSlotContent } from '@open-pencil/scene-graph/slots'type ResolveGuid = (id: string) => GUID | undefined@@ -39,13 +39,7 @@ export function instanceExportAddress(}function sourceOf(scope: SceneNode, node: SceneNode): string | null {- const mapped = getInstanceOverride(- scope.instanceOverrides,- scope.id,- node.id,- 'sourceComponentId'- )- return typeof mapped === 'string' ? mapped : node.componentId+ return copiedComponentLayerId(scope.instanceOverrides, scope.id, node) ?? null}/**diff --git a/packages/fig/tests/node-change/export/assignments/nested.test.ts b/packages/fig/tests/node-change/export/assignments/nested.test.tsnew file mode 100644index 000000000..90c28fabd--- /dev/null+++ b/packages/fig/tests/node-change/export/assignments/nested.test.ts@@ -0,0 +1,99 @@+import { describe, expect, test } from 'bun:test'++import { expectDefined } from '#fig-tests/helpers/assert'+import { sceneNodeToKiwi } from '#fig/node-change/index'++import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import {+ applyComponentPropertyValue,+ componentPropertyDefinitions+} from '@open-pencil/scene-graph/components'++interface Assignment {+ defID?: unknown+ value?: { textValue?: { characters?: string }; boolValue?: boolean }+}++interface InstanceRecord {+ name?: string+ symbolData?: {+ symbolOverrides?: Array<{+ guidPath?: { guids: unknown[] }+ componentPropAssignments?: Assignment[]+ }>+ }+}++/** A Button with a Label and a Shown icon, held by a Card as Action, and a copy of the Card. */+function cardWithButton() {+ const graph = new SceneGraph()+ const [page] = graph.getPages()+ const button = graph.createNode('COMPONENT', page.id, {+ name: 'Button',+ componentPropertyDefinitions: [+ { id: 'prop:label', name: 'Label', type: 'TEXT', defaultValue: 'Continue' },+ { id: 'prop:shown', name: 'Shown', type: 'BOOLEAN', defaultValue: 'true' }+ ]+ })+ graph.createNode('TEXT', button.id, {+ name: 'Text',+ text: 'Continue',+ componentPropertyReferences: [{ propertyId: 'prop:label', field: 'TEXT' }]+ })+ graph.createNode('FRAME', button.id, {+ name: 'Icon',+ componentPropertyReferences: [{ propertyId: 'prop:shown', field: 'VISIBLE' }]+ })+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card' })+ const action = expectDefined(graph.createInstance(button.id, card.id))+ graph.updateNode(action.id, { name: 'Action', isExposedInstance: true })+ const copy = expectDefined(graph.createInstance(card.id, page.id))+ graph.updateNode(copy.id, { name: 'Copy' })+ const copied = expectDefined(graph.getChildren(copy.id).find((child) => child.name === 'Action'))+ return { graph, copy, copied }+}++function assign(graph: SceneGraph, instance: SceneNode, name: string, value: string) {+ const definition = expectDefined(+ componentPropertyDefinitions(graph, instance).find((item) => item.name === name)+ )+ applyComponentPropertyValue(graph, instance.id, definition, value)+}++/** The property values the copy's record gives the instances it holds, by override path. */+function nestedAssignments(graph: SceneGraph, copy: SceneNode): Assignment[][] {+ const records = sceneNodeToKiwi(+ expectDefined(graph.getNode(copy.id)),+ { sessionID: 1, localID: 1 },+ 0,+ { value: 2 },+ graph,+ []+ ) as InstanceRecord[]+ const record = expectDefined(records.find((item) => item.name === 'Copy'))+ return (record.symbolData?.symbolOverrides ?? []).flatMap((override) =>+ override.componentPropAssignments ? [override.componentPropAssignments] : []+ )+}++describe('the values a copy gives an instance it holds', () => {+ test('are written on the override at that instance, as Figma stores them', () => {+ const { graph, copy, copied } = cardWithButton()+ assign(graph, copied, 'Label', 'Save')+ assign(graph, copied, 'Shown', 'false')+ const [assignments, ...others] = nestedAssignments(graph, copy)+ expect(others).toEqual([])+ expect(assignments.map((assignment) => assignment.value)).toEqual([+ { textValue: { characters: 'Save' } },+ { boolValue: false }+ ])+ })++ test('are left out when they are what the instance it copies shows', () => {+ const { graph, copy, copied } = cardWithButton()+ expect(nestedAssignments(graph, copy)).toEqual([])+ // Setting the default again is no change either.+ assign(graph, copied, 'Label', 'Continue')+ expect(nestedAssignments(graph, copy)).toEqual([])+ })+})diff --git a/packages/scene-graph/src/instances/copies.ts b/packages/scene-graph/src/instances/copies.tsindex 983720c08..e792ff2c3 100644--- a/packages/scene-graph/src/instances/copies.ts+++ b/packages/scene-graph/src/instances/copies.ts@@ -4,7 +4,7 @@ import { ownsSlotContent, slotPropertyId } from '../slots/frames'import type { SceneNode } from '../types'import { DEFAULT_HISTORY_LIMIT } from '../undo'import {- getInstanceOverride,+ copiedComponentLayerId,hasInstanceOverride as hasNodeInstanceOverride,type InstanceOverrideState} from './overrides'@@ -33,11 +33,7 @@ export function createInstanceSyncContext(/** The component layer a copy in the instance stands for. */function copiedLayerId(node: SceneNode, context: InstanceSyncContext): string | undefined {- const source =- node.type === 'INSTANCE'- ? getInstanceOverride(context.overrides, context.instanceId, node.id, 'sourceComponentId')- : undefined- return typeof source === 'string' ? source : (node.componentId ?? undefined)+ return copiedComponentLayerId(context.overrides, context.instanceId, node)}/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */diff --git a/packages/scene-graph/src/instances/overrides.ts b/packages/scene-graph/src/instances/overrides.tsindex 8d1387b5c..6cf281508 100644--- a/packages/scene-graph/src/instances/overrides.ts+++ b/packages/scene-graph/src/instances/overrides.ts@@ -142,6 +142,19 @@ export function getInstanceOverride(return nodeId === instanceId ? state.self.get(field) : state.descendants.get(nodeId)?.get(field)}+/**+ * The component layer a layer of an instance copies: the one its instance recorded for it, as+ * a swapped nested instance keeps, or else the one it was cloned from.+ */+export function copiedComponentLayerId(+ state: InstanceOverrideState,+ instanceId: string,+ node: { id: string; componentId: string | null }+): string | undefined {+ const recorded = getInstanceOverride(state, instanceId, node.id, 'sourceComponentId')+ return typeof recorded === 'string' ? recorded : (node.componentId ?? undefined)+}+export function hasInstanceOverride(state: InstanceOverrideState,instanceId: string,diff --git a/packages/scene-graph/src/instances/source-walk.ts b/packages/scene-graph/src/instances/source-walk.tsindex 8c7795ad5..d99f2d8b8 100644--- a/packages/scene-graph/src/instances/source-walk.ts+++ b/packages/scene-graph/src/instances/source-walk.ts@@ -1,6 +1,6 @@import type { SceneGraph } from '../graph'import type { SceneNode } from '../types'-import { getInstanceOverride } from './overrides'+import { copiedComponentLayerId } from './overrides'/*** Walk an instance's layers beside the component layers they copy, matched the way instance@@ -19,13 +19,7 @@ export function walkInstanceSources(const walk = (sourceParent: SceneNode, instanceParent: SceneNode): void => {const bySource = new Map<string, SceneNode>()for (const child of graph.getChildren(instanceParent.id)) {- const mapped = getInstanceOverride(- instance.instanceOverrides,- instance.id,- child.id,- 'sourceComponentId'- )- const sourceId = typeof mapped === 'string' ? mapped : child.componentId+ const sourceId = copiedComponentLayerId(instance.instanceOverrides, instance.id, child)if (!sourceId) continueif (strict && bySource.has(sourceId))throw new Error(`Ambiguous component-property target ${sourceId}`)diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex d5f92d9f9..5186b8d30 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -21,7 +21,7 @@ import { INSTANCE_SYNC_FIELD_OWNERS, INSTANCE_SYNC_FIELDS } from './fields'import { ownsSelfFillField, sourceWithEffectiveFill } from './main-component'import {bindingOverrideField,- getInstanceOverride,+ copiedComponentLayerId,hasInstanceOverride as hasNodeInstanceOverride,overriddenBindingField,setInstanceOverride,@@ -320,10 +320,7 @@ function sortInstanceChildren(for (let index = 0; index < instParent.childIds.length; index++) {const childId = instParent.childIds[index]const node = graph.nodes.get(childId)- const source = node- ? getInstanceOverride(overrides, instParentId, node.id, 'sourceComponentId')- : undefined- const mapped = typeof source === 'string' ? source : node?.componentId+ const mapped = node && copiedComponentLayerId(overrides, instParentId, node)const componentIndex = mapped ? orderMap.get(mapped) : undefinedranks.set(childId, componentIndex ?? compChildOrder.length + index)}@@ -354,14 +351,7 @@ function matchLinkedChildren(for (const childId of instParent.childIds) {const child = graph.nodes.get(childId)if (!child) continue- const sourceComponentId = getInstanceOverride(- overrides,- instParentId,- child.id,- 'sourceComponentId'- )- const mappedComponentId =- typeof sourceComponentId === 'string' ? sourceComponentId : child.componentId+ const mappedComponentId = copiedComponentLayerId(overrides, instParentId, child)if (mappedComponentId && compChildIdSet.has(mappedComponentId)) {instChildMap.set(mappedComponentId, child)usedInstChildIds.add(child.id)