Skip to content

AI-native design editor. Open-source Figma alternative.

fix(components): move instance copies with their layers when a component's structure changes (#1070)

Danila Poyarkovd4800def74e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b899282d..de3df4741 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -175,6 +175,7 @@
### Fixed
+- Instances follow their component's structure as in Figma: wrapping a layer of the component in auto layout or a frame, or moving it into another frame of the component, moves the layer's copy in every instance with its overrides instead of adding a fresh copy beside the old one, and moving a layer out of the component or deleting it removes its copy from every instance, while undo brings the copies back with their overrides.
- Dragging a number field in the properties panel moves its value in whole steps instead of fractions on high-density screens.
- While text is being edited, its caret and selection follow a property dragged in the panel instead of catching up when the mouse is released.
- Outline text, flatten, and boolean operations on text place glyphs where the canvas draws them; lines sat lower by about a quarter of the font size.
diff --git a/packages/core/src/editor/component-sync.ts b/packages/core/src/editor/component-sync.ts
index 23d201df5..2e1360559 100644
--- a/packages/core/src/editor/component-sync.ts
+++ b/packages/core/src/editor/component-sync.ts
@@ -83,9 +83,7 @@ export function createComponentSyncScheduler(
const component = graph.closest(id, isComponent)
if (component) componentIds.add(component.id)
}
- for (const compId of componentSyncOrder(graph, componentIds)) {
- graph.syncInstances(compId)
- }
+ graph.syncInstancesTogether(componentSyncOrder(graph, componentIds))
if (componentIds.size > 0) {
const pageIds = affectedPageIds(graph, ids, componentIds)
if (pageIds.size === 0) computeLayouts(graph)
diff --git a/packages/core/src/editor/graph-events.ts b/packages/core/src/editor/graph-events.ts
index 593c9d00d..ca7ce86eb 100644
--- a/packages/core/src/editor/graph-events.ts
+++ b/packages/core/src/editor/graph-events.ts
@@ -6,6 +6,7 @@ import {
} from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas/renderer'
+import { markFlowChanged } from '#core/layout/derived'
type EmittedGraphEventName = keyof SceneGraphEvents
@@ -131,6 +132,16 @@ export function createGraphEventSubscription(options: GraphEventOptions) {
requestRenderFor(options.getGraph())
}
+ /**
+ * An edit that adds, removes, or moves a layer changes its parent's flow, which then stops
+ * keeping the geometry a file saved for it. Loading a page and laying out are not edits.
+ */
+ function flowChanged(parentId: string | null | undefined) {
+ const graph = options.getGraph()
+ if (!parentId || graph.isApplyingImportedState || graph.isApplyingLayout) return
+ markFlowChanged(graph, parentId)
+ }
+
function subscribeToGraph() {
unbindGraphEvents?.()
unbindGraphEvents = options.getGraph().onNodeEvents({
@@ -139,18 +150,31 @@ export function createGraphEventSubscription(options: GraphEventOptions) {
created: (node) => {
options.emitEditorEvent('node:created', node)
onNodeStructureChanged(node.id)
+ flowChanged(node.parentId)
},
- deleted: (id, _parentId) => {
- options.emitEditorEvent('node:deleted', id, _parentId)
+ // A layer that leaves a component, deleted or moved out, changes the component it left;
+ // the parent it had finds that component when the sync runs.
+ deleted: (id, parentId) => {
+ options.emitEditorEvent('node:deleted', id, parentId)
onNodeStructureChanged(id)
+ flowChanged(parentId)
+ if (parentId) options.scheduleComponentSync(parentId)
},
reparented: (nodeId, oldParentId, newParentId) => {
options.emitEditorEvent('node:reparented', nodeId, oldParentId, newParentId)
onNodeStructureChanged(nodeId)
+ flowChanged(oldParentId)
+ flowChanged(newParentId)
+ if (oldParentId) options.scheduleComponentSync(oldParentId)
},
reordered: (nodeId, parentId, index, previousParentId) => {
options.emitEditorEvent('node:reordered', nodeId, parentId, index, previousParentId)
onNodeStructureChanged(nodeId)
+ flowChanged(parentId)
+ flowChanged(previousParentId)
+ if (previousParentId && previousParentId !== parentId) {
+ options.scheduleComponentSync(previousParentId)
+ }
}
})
}
diff --git a/packages/core/src/layout/derived.ts b/packages/core/src/layout/derived.ts
index fbcb17d61..11b30b187 100644
--- a/packages/core/src/layout/derived.ts
+++ b/packages/core/src/layout/derived.ts
@@ -45,16 +45,26 @@ function flowChanged(graph: SceneGraph, node: SceneNode, flow = flowOf(graph, no
}
/**
- * Whether layout still keeps the geometry a file saved for `frame` and its flow: a frame read from
- * a .fig file does until it or a layer in its flow has its layout edited, such as by adding auto
- * layout or a gap, or a layer joins, leaves, or moves in its flow, or a flow inside it changes. Other
- * frames keep geometry copied with them, as an instance's layers do.
+ * Records that a layer joined, left, or moved in `parentId`'s children, as an editor sees an edit
+ * happen, so the frame stops keeping saved geometry even if layout never ran on it before.
+ */
+export function markFlowChanged(graph: SceneGraph, parentId: string): void {
+ graphState(restructured, graph, () => new Set<string>()).add(parentId)
+}
+
+/**
+ * Whether layout still keeps the geometry saved for `frame` and its flow. Any frame stops once a
+ * layer joins, leaves, or moves in its flow or a flow inside it; a frame read from a .fig file
+ * also stops once it or a layer in its flow has its layout edited, such as by adding auto layout
+ * or a gap. Other frames otherwise keep geometry copied with them, as an instance's layers do.
*/
export function keepsSavedLayout(graph: SceneGraph, frame: SceneNode): boolean {
- if (frame.source.format !== 'fig') return true
+ const fromFig = frame.source.format === 'fig'
+ const flow = flowOf(graph, frame)
+ // Nothing saved to keep: the usual case outside documents read from files.
+ if (!fromFig && !frame.derivedLayout && !flow.some((child) => child.derivedLayout)) return true
const stale = graphState(restructured, graph, () => new Set<string>())
if (stale.has(frame.id)) return false
- const flow = flowOf(graph, frame)
// Layout runs inner frames first, so a changed flow deep inside is already marked.
if (
flowChanged(graph, frame, flow) ||
@@ -63,6 +73,8 @@ export function keepsSavedLayout(graph: SceneGraph, frame: SceneNode): boolean {
stale.add(frame.id)
return false
}
+ // Geometry copied with other layers, as an instance's are, stays until their structure changes.
+ if (!fromFig) return true
// A flow inside edited by now resizes this one, but a cancelled preview gives it back.
const last = graphState(reflowed, graph, () => new Set<string>())
const keeps =
diff --git a/packages/core/tests/editor/components/instance-structure.test.ts b/packages/core/tests/editor/components/instance-structure.test.ts
new file mode 100644
index 000000000..3dcb90835
--- /dev/null
+++ b/packages/core/tests/editor/components/instance-structure.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, test } from 'bun:test'
+import { compact } from 'es-toolkit'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+// Each case repeats a Figma desktop 126 script: the instance mirrors the component's new
+// structure, and a moved layer keeps its copy and the copy's overrides.
+
+/** Component sync runs after the edit, in a microtask. */
+const synced = () => Promise.resolve()
+
+function setup() {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const node = (type: SceneNode['type'], parentId: string, props: Partial<SceneNode> = {}) =>
+ editor.graph.createNode(type, parentId, { width: 40, height: 20, ...props })
+ /** The instance's tree, with each text's characters. */
+ const tree = (id: string): string => {
+ const n = editor.graph.getNode(id)
+ if (!n) return ''
+ const label = n.type === 'TEXT' ? `${n.name}("${n.text}")` : n.name
+ const children = compact(n.childIds.map(tree))
+ return children.length > 0 ? `${label}[${children.join(' ')}]` : label
+ }
+ const copyOf = (instance: SceneNode, layer: SceneNode): SceneNode => {
+ const find = (id: string): SceneNode | undefined => {
+ const n = editor.graph.getNode(id)
+ if (n?.componentId === layer.id) return n
+ return n?.childIds.map(find).find(Boolean)
+ }
+ const found = find(instance.id)
+ if (!found) throw new Error(`no copy of ${layer.name}`)
+ return found
+ }
+ return { editor, page, node, tree, copyOf }
+}
+
+async function instanceOf(editor: Editor, componentId: string) {
+ const instance = editor.graph.createInstance(componentId, editor.state.currentPageId)
+ if (!instance) throw new Error('no instance')
+ await synced()
+ return instance
+}
+
+describe('an instance follows its component’s structure', () => {
+ test('wrapping a layer in auto layout keeps its copy and override, through undo', async () => {
+ const { editor, page, node, tree, copyOf } = setup()
+ const button = node('COMPONENT', page, { name: 'Button', width: 120, height: 40 })
+ const badge = node('FRAME', button.id, { name: 'Badge' })
+ const number = node('TEXT', badge.id, { name: 'Number', text: '1' })
+ const instance = await instanceOf(editor, button.id)
+ editor.updateNodeWithUndo(copyOf(instance, number).id, { text: '9' })
+ await synced()
+
+ editor.select([badge.id])
+ editor.wrapInAutoLayout()
+ await synced()
+ expect(tree(instance.id)).toBe('Button[Frame[Badge[Number("9")]]]')
+ editor.undoAction()
+ await synced()
+ expect(tree(instance.id)).toBe('Button[Badge[Number("9")]]')
+ })
+
+ test('a layer moved into a sibling frame takes its copy along', async () => {
+ const { editor, page, node, tree, copyOf } = setup()
+ const tag = node('COMPONENT', page, { name: 'Tag' })
+ const badge = node('FRAME', tag.id, { name: 'Badge' })
+ const number = node('TEXT', tag.id, { name: 'Number', text: '1' })
+ const instance = await instanceOf(editor, tag.id)
+ const copy = copyOf(instance, number)
+ editor.updateNodeWithUndo(copy.id, { text: '7' })
+ editor.reorderChildWithUndo(number.id, badge.id, 0)
+ await synced()
+ expect(tree(instance.id)).toBe('Tag[Badge[Number("7")]]')
+ expect(copyOf(instance, number).id).toBe(copy.id)
+ })
+
+ test('a layer moved out of the component leaves the instance, and comes back on undo', async () => {
+ const { editor, page, node, tree, copyOf } = setup()
+ const card = node('COMPONENT', page, { name: 'Card' })
+ const title = node('TEXT', card.id, { name: 'Title', text: 'Hello' })
+ const instance = await instanceOf(editor, card.id)
+ editor.updateNodeWithUndo(copyOf(instance, title).id, { text: 'Override' })
+ editor.reorderChildWithUndo(title.id, page, 0)
+ await synced()
+ expect(tree(instance.id)).toBe('Card')
+ editor.undoAction()
+ await synced()
+ expect(tree(instance.id)).toBe('Card[Title("Override")]')
+ })
+
+ test('a layer moved into the component appears in the instance', async () => {
+ const { editor, page, node, tree } = setup()
+ const chip = node('COMPONENT', page, { name: 'Chip' })
+ node('TEXT', chip.id, { name: 'Label', text: 'A' })
+ const instance = await instanceOf(editor, chip.id)
+ const extra = node('TEXT', page, { name: 'Extra', text: 'B' })
+ editor.reorderChildWithUndo(extra.id, chip.id, 1)
+ await synced()
+ expect(tree(instance.id)).toBe('Chip[Label("A") Extra("B")]')
+ })
+
+ test('a deleted layer leaves the instance, and undo brings back its override', async () => {
+ const { editor, page, node, tree, copyOf } = setup()
+ const list = node('COMPONENT', page, { name: 'List' })
+ const a = node('TEXT', list.id, { name: 'A', text: 'a' })
+ node('TEXT', list.id, { name: 'B', text: 'b' })
+ const instance = await instanceOf(editor, list.id)
+ editor.updateNodeWithUndo(copyOf(instance, a).id, { text: 'override' })
+ editor.select([a.id])
+ editor.deleteSelected()
+ await synced()
+ expect(tree(instance.id)).toBe('List[B("b")]')
+ editor.undoAction()
+ await synced()
+ expect(tree(instance.id)).toBe('List[A("override") B("b")]')
+ editor.redoAction()
+ await synced()
+ expect(tree(instance.id)).toBe('List[B("b")]')
+ })
+})
diff --git a/packages/core/tests/layout/auto-layout/saved-geometry.test.ts b/packages/core/tests/layout/auto-layout/saved-geometry.test.ts
index 8cbc03614..2dabaaa03 100644
--- a/packages/core/tests/layout/auto-layout/saved-geometry.test.ts
+++ b/packages/core/tests/layout/auto-layout/saved-geometry.test.ts
@@ -149,3 +149,33 @@ describe('a frame read from a .fig file reflows once its layout is edited', () =
editor.dispose()
})
})
+
+test('a layer moved into a frame with saved geometry resizes it, even before it was laid out', () => {
+ const editor = createEditor()
+ const { graph } = editor
+ const hug = {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 4,
+ paddingLeft: 8,
+ paddingRight: 8,
+ paddingTop: 2,
+ paddingBottom: 2
+ } as const
+ // A component's layers as a .fig file loads them: saved sizes, no source format, not laid out.
+ const tag = graph.createNode('COMPONENT', editor.state.currentPageId, { ...hug, width: 62, height: 41 })
+ const badge = graph.createNode('FRAME', tag.id, { ...hug, width: 24, height: 12 })
+ graph.createNode('ELLIPSE', badge.id, { width: 8, height: 8 })
+ const number = graph.createNode('RECTANGLE', tag.id, { width: 6, height: 17 })
+ for (const node of [tag, badge, number]) {
+ graph.applyImportedStateDuring(() =>
+ graph.updateNode(node.id, {
+ derivedLayout: { x: node.x, y: node.y, width: node.width, height: node.height }
+ })
+ )
+ }
+ editor.reorderChildWithUndo(number.id, badge.id, 1)
+ expect([badge.width, badge.height]).toEqual([34, 21])
+ editor.dispose()
+})
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index bbb521edb..f96d49356 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -78,7 +78,7 @@ export * from './font-style'
export * from './shared-styles'
export { default as TransformMatrix } from './matrix'
export type { Mat3 } from './matrix'
-export { UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'
+export { DEFAULT_HISTORY_LIMIT, UndoManager, type UndoEntry, type UndoManagerOptions } from './undo'
import { removeStaleBindings } from './bindings'
export { CommittedGraphEventError } from './buffered-events'
@@ -876,6 +876,10 @@ export class SceneGraph {
Instances.syncInstances(this, componentId)
}
+ syncInstancesTogether(componentIds: Iterable<string>): void {
+ Instances.syncInstancesTogether(this, componentIds)
+ }
+
syncInstance(instanceId: string): void {
Instances.syncInstance(this, instanceId)
}
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index ce9b954c7..1c252f325 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -6,6 +6,11 @@ import {
hasInstanceOverride as hasNodeInstanceOverride,
setInstanceOverride
} from './instance-overrides'
+import {
+ createInstanceSyncContext,
+ groupCopyRemovals,
+ removeLeftoverCopies
+} from './instances/copies'
import { INSTANCE_SYNC_FIELDS, INSTANCE_SYNC_PROPS } from './instances/fields'
import {
bindingProtection,
@@ -139,6 +144,16 @@ export function syncInstances(graph: SceneGraph, componentId: string): void {
syncInstancesOf(graph, componentId, getInstances(graph, componentId))
}
+/**
+ * Syncs each component's instances, in order, as one edit: the copies they remove stay
+ * restorable together for as long as undo keeps that edit.
+ */
+export function syncInstancesTogether(graph: SceneGraph, componentIds: Iterable<string>): void {
+ groupCopyRemovals(graph, () => {
+ for (const id of componentIds) syncInstances(graph, id)
+ })
+}
+
/** Syncs one instance from its component, as `syncInstances` does for every instance. */
export function syncInstance(graph: SceneGraph, instanceId: string): void {
const instance = graph.nodes.get(instanceId)
@@ -161,21 +176,25 @@ function syncInstancesOf(
if (syncing.has(componentId)) return
syncing.add(componentId)
try {
- for (const instance of instances) {
- const enclosing = enclosingInstanceOverrideFields(graph, instance)
- enclosing.push(new Set(instance.instanceOverrides.self.keys()))
- const protectedField = bindingProtection(enclosing)
- const source = sourceInTargetCoordinates(component, instance.componentScale)
- const updates: Partial<SceneNode> = {}
- syncBindingFields(instance, source, updates, protectedField)
- for (const key of INSTANCE_SYNC_PROPS) {
- if (key === 'boundVariables') continue
- if (isProtectedSyncField(instance, key, protectedField)) continue
- copyProp(updates, source, key)
+ groupCopyRemovals(graph, (removals) => {
+ for (const instance of instances) {
+ const enclosing = enclosingInstanceOverrideFields(graph, instance)
+ enclosing.push(new Set(instance.instanceOverrides.self.keys()))
+ const protectedField = bindingProtection(enclosing)
+ const source = sourceInTargetCoordinates(component, instance.componentScale)
+ const updates: Partial<SceneNode> = {}
+ syncBindingFields(instance, source, updates, protectedField)
+ for (const key of INSTANCE_SYNC_PROPS) {
+ if (key === 'boundVariables') continue
+ if (isProtectedSyncField(instance, key, protectedField)) continue
+ copyProp(updates, source, key)
+ }
+ updateSyncedProps(graph, instance, updates)
+ const context = createInstanceSyncContext(instance.id, instance.instanceOverrides)
+ syncChildren(graph, component.id, instance.id, instance.instanceOverrides, context)
+ removeLeftoverCopies(graph, context, removals)
}
- updateSyncedProps(graph, instance, updates)
- syncChildren(graph, component.id, instance.id, instance.instanceOverrides)
- }
+ })
} finally {
syncing.delete(componentId)
}
diff --git a/packages/scene-graph/src/instances/copies.ts b/packages/scene-graph/src/instances/copies.ts
new file mode 100644
index 000000000..476e13a05
--- /dev/null
+++ b/packages/scene-graph/src/instances/copies.ts
@@ -0,0 +1,239 @@
+// How an instance's copies follow the component's layers when its structure changes.
+import type { SceneGraph, SceneNode } from '../'
+import {
+ getInstanceOverride,
+ hasInstanceOverride as hasNodeInstanceOverride,
+ type InstanceOverrideState
+} from '../instance-overrides'
+import { ownsSlotContent, slotPropertyId } from '../slots/frames'
+import { DEFAULT_HISTORY_LIMIT } from '../undo'
+
+/**
+ * One instance's sync: the copies it has matched to the component's layers, the parents it
+ * synced, and, built on first need, the copies the instance had before, by the layer they copy.
+ * Copies follow their layers when the component's structure changes, as Figma moves them: a
+ * layer moved inside the component keeps its copy and the copy's overrides, and a copy whose
+ * layer left or was deleted goes.
+ */
+export interface InstanceSyncContext {
+ instanceId: string
+ overrides: InstanceOverrideState
+ matched: Set<string>
+ leftovers: Set<string>
+ copies?: Map<string, SceneNode[]>
+}
+
+export function createInstanceSyncContext(
+ instanceId: string,
+ overrides: InstanceOverrideState
+): InstanceSyncContext {
+ return { instanceId, overrides, matched: new Set(), leftovers: new Set() }
+}
+
+/** 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)
+}
+
+/** Whether sync goes inside a copy: not into slot content, a swapped instance, or an instance. */
+function syncsInside(graph: SceneGraph, node: SceneNode, context: InstanceSyncContext): boolean {
+ if (node.type === 'INSTANCE') return false
+ if (hasNodeInstanceOverride(context.overrides, context.instanceId, node.id, 'componentId')) {
+ return false
+ }
+ const layer = node.componentId ? graph.nodes.get(node.componentId) : undefined
+ return !layer || !ownsSlotContent(graph, node, slotPropertyId(layer))
+}
+
+function copiesOf(graph: SceneGraph, context: InstanceSyncContext): Map<string, SceneNode[]> {
+ if (context.copies) return context.copies
+ const copies = new Map<string, SceneNode[]>()
+ const visit = (parent: SceneNode) => {
+ for (const id of parent.childIds) {
+ const child = graph.nodes.get(id)
+ if (!child) continue
+ const layerId = copiedLayerId(child, context)
+ if (layerId) copies.set(layerId, [...(copies.get(layerId) ?? []), child])
+ if (syncsInside(graph, child, context)) visit(child)
+ }
+ }
+ const instance = graph.nodes.get(context.instanceId)
+ if (instance) visit(instance)
+ context.copies = copies
+ return copies
+}
+
+/** A copy of `layerId` the sync has not placed yet, which a moved layer takes along. */
+export function unplacedCopy(
+ graph: SceneGraph,
+ context: InstanceSyncContext,
+ layerId: string,
+ instParentId: string
+): SceneNode | undefined {
+ return copiesOf(graph, context)
+ .get(layerId)
+ ?.find(
+ (copy) =>
+ !context.matched.has(copy.id) &&
+ graph.nodes.has(copy.id) &&
+ copy.id !== instParentId &&
+ !graph.isDescendant(instParentId, copy.id)
+ )
+}
+
+/** Whether any layer in the component subtree at `layerId` already has a copy to move. */
+export function hasUnplacedCopiesBelow(
+ graph: SceneGraph,
+ context: InstanceSyncContext,
+ layerId: string
+): boolean {
+ const copies = copiesOf(graph, context)
+ if (copies.size === 0) return false
+ const layer = graph.nodes.get(layerId)
+ return (layer?.childIds ?? []).some(
+ (id) =>
+ copies.get(id)?.some((copy) => !context.matched.has(copy.id)) ||
+ hasUnplacedCopiesBelow(graph, context, id)
+ )
+}
+
+/** The copies one sync of a component's instances removed, by instance and layer. */
+export interface CopyRemovals {
+ keys: Array<[instanceId: string, layerId: string]>
+}
+
+/** A copy the sync removed, kept so the layer coming back, as on undo, brings it back as it was. */
+interface RemovedCopy {
+ /** The copy and everything in it, parents first. */
+ nodes: SceneNode[]
+ overrides: Map<string, Map<string, unknown>>
+ removals: CopyRemovals
+}
+
+interface RemovedCopyStore {
+ /** Removed copies by instance, then by the layer they copied. */
+ byInstance: Map<string, Map<string, RemovedCopy>>
+ /** Syncs that removed copies, oldest first. */
+ removals: CopyRemovals[]
+}
+
+const removedCopies = new WeakMap<SceneGraph, RemovedCopyStore>()
+
+function removedCopyStore(graph: SceneGraph): RemovedCopyStore {
+ let store = removedCopies.get(graph)
+ if (!store) {
+ store = { byInstance: new Map(), removals: [] }
+ removedCopies.set(graph, store)
+ }
+ return store
+}
+
+/**
+ * Keeps one edit's removed copies restorable. Only as many edits as undo keeps are kept, so
+ * copies no undo can bring back are forgotten, oldest first.
+ */
+function keepCopyRemovals(graph: SceneGraph, removals: CopyRemovals): void {
+ if (removals.keys.length === 0) return
+ const store = removedCopyStore(graph)
+ store.removals.push(removals)
+ while (store.removals.length > DEFAULT_HISTORY_LIMIT) {
+ const oldest = store.removals.shift()
+ for (const [instanceId, layerId] of oldest?.keys ?? []) {
+ const copies = store.byInstance.get(instanceId)
+ // A later sync may have removed the same layer's copy again; that one stays.
+ if (!copies || copies.get(layerId)?.removals !== oldest) continue
+ copies.delete(layerId)
+ if (copies.size === 0) store.byInstance.delete(instanceId)
+ }
+ }
+}
+
+const activeRemovals = new WeakMap<SceneGraph, CopyRemovals>()
+
+/**
+ * Runs `fn` with every copy the syncs inside it remove kept as one group: one edit's syncs, however
+ * many components they reach, take one place in the history of removals.
+ */
+export function groupCopyRemovals<T>(graph: SceneGraph, fn: (removals: CopyRemovals) => T): T {
+ const active = activeRemovals.get(graph)
+ if (active) return fn(active)
+ const removals: CopyRemovals = { keys: [] }
+ activeRemovals.set(graph, removals)
+ try {
+ return fn(removals)
+ } finally {
+ activeRemovals.delete(graph)
+ keepCopyRemovals(graph, removals)
+ }
+}
+
+/**
+ * Brings back the copy of `layerId` the sync removed from this instance, with the same layers
+ * and overrides, as Figma restores an instance's override when the layer's deletion is undone.
+ */
+export function restoreRemovedCopy(
+ graph: SceneGraph,
+ context: InstanceSyncContext,
+ layerId: string,
+ instParentId: string
+): SceneNode | undefined {
+ const store = removedCopyStore(graph)
+ const removed = store.byInstance.get(context.instanceId)
+ const entry = removed?.get(layerId)
+ if (!removed || !entry) return undefined
+ removed.delete(layerId)
+ if (removed.size === 0) store.byInstance.delete(context.instanceId)
+ const root = entry.nodes.at(0)
+ if (!root || entry.nodes.some((node) => graph.nodes.has(node.id))) return undefined
+ for (const node of entry.nodes) {
+ const { id, type, parentId, childIds: _childIds, ...props } = structuredClone(node)
+ graph.createNodeWithId(id, type, id === root.id ? instParentId : parentId, props)
+ }
+ for (const [id, fields] of entry.overrides) context.overrides.descendants.set(id, new Map(fields))
+ return graph.nodes.get(root.id)
+}
+
+/**
+ * Deletes the copies the sync left over: ones whose layer left the component, was deleted, or
+ * now has another copy. Copies the instance owns, such as slot content, are never reached.
+ */
+export function removeLeftoverCopies(
+ graph: SceneGraph,
+ context: InstanceSyncContext,
+ removals: CopyRemovals
+): void {
+ const store = removedCopyStore(graph)
+ for (const id of context.leftovers) {
+ const node = graph.nodes.get(id)
+ const layerId = node ? copiedLayerId(node, context) : undefined
+ if (!node || !layerId || context.matched.has(id)) continue
+ const nodes: SceneNode[] = []
+ const collect = (current: SceneNode) => {
+ nodes.push(structuredClone(current))
+ for (const childId of current.childIds) {
+ const child = graph.nodes.get(childId)
+ if (child) collect(child)
+ }
+ }
+ collect(node)
+ const overrides = new Map<string, Map<string, unknown>>()
+ for (const removed of nodes) {
+ const fields = context.overrides.descendants.get(removed.id)
+ if (fields) overrides.set(removed.id, new Map(fields))
+ context.overrides.descendants.delete(removed.id)
+ }
+ let copies = store.byInstance.get(context.instanceId)
+ if (!copies) {
+ copies = new Map()
+ store.byInstance.set(context.instanceId, copies)
+ }
+ copies.set(layerId, { nodes, overrides, removals })
+ removals.keys.push([context.instanceId, layerId])
+ graph.deleteNode(id)
+ }
+ context.leftovers.clear()
+}
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index ee7e9a3a2..ca60ea8bb 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -13,6 +13,13 @@ import {
import { scaleNodeChanges } from '../scaling/node'
import { ownsSlotContent, slotPropertyId } from '../slots/frames'
import { scaleVariableBindingUnits } from '../variables/units'
+import {
+ createInstanceSyncContext,
+ hasUnplacedCopiesBelow,
+ restoreRemovedCopy,
+ unplacedCopy,
+ type InstanceSyncContext
+} from './copies'
import { INSTANCE_SYNC_FIELDS } from './fields'
function setSceneProp<K extends keyof SceneNode>(
@@ -426,11 +433,56 @@ function matchLinkedChildren(
}
}
+/**
+ * Pass 3 of a sync: bring along the copy of a layer moved here inside the component, bring back
+ * one the sync removed when its layer returns, or clone a layer the instance has no copy of. A
+ * clone takes its own subtree unless copies the instance has belong in it, which the recursion
+ * moves in instead. Children left unmatched are the sync's to remove once it finishes.
+ */
+function placeMissingChildren(
+ graph: SceneGraph,
+ compParent: SceneNode,
+ instParent: SceneNode,
+ instChildMap: Map<string, SceneNode>,
+ usedInstChildIds: Set<string>,
+ context: InstanceSyncContext
+): void {
+ for (const child of instChildMap.values()) context.matched.add(child.id)
+
+ for (const compChildId of compParent.childIds) {
+ if (instChildMap.has(compChildId)) continue
+ const moved =
+ unplacedCopy(graph, context, compChildId, instParent.id) ??
+ restoreRemovedCopy(graph, context, compChildId, instParent.id)
+ if (moved) {
+ graph.insertChildAt(moved.id, instParent.id, instParent.childIds.length)
+ instChildMap.set(compChildId, moved)
+ usedInstChildIds.add(moved.id)
+ context.matched.add(moved.id)
+ continue
+ }
+ const src = graph.nodes.get(compChildId)
+ if (!src) continue
+ const clone = cloneChildInCoordinates(graph, src, compParent, instParent)
+ if (src.childIds.length > 0 && !hasUnplacedCopiesBelow(graph, context, compChildId)) {
+ cloneChildrenWithMapping(graph, compChildId, clone.id)
+ }
+ applyEnclosingAssignments(graph, clone)
+ instChildMap.set(compChildId, clone)
+ usedInstChildIds.add(clone.id)
+ context.matched.add(clone.id)
+ }
+ for (const childId of instParent.childIds) {
+ if (!usedInstChildIds.has(childId)) context.leftovers.add(childId)
+ }
+}
+
export function syncChildren(
graph: SceneGraph,
compParentId: string,
instParentId: string,
- overrides: InstanceOverrideState
+ overrides: InstanceOverrideState,
+ context: InstanceSyncContext = createInstanceSyncContext(instParentId, overrides)
): void {
// Guard against cyclic sync: if the instance parent is inside the component's own
// subtree, syncing would clone the component into itself — a self-referential cycle
@@ -467,20 +519,7 @@ export function syncChildren(
usedInstChildIds
)
- // Pass 3: Clone only genuinely missing component children
- for (const compChildId of compParent.childIds) {
- if (!instChildMap.has(compChildId)) {
- const src = graph.nodes.get(compChildId)
- if (!src) continue
- const clone = cloneChildInCoordinates(graph, src, compParent, instParent)
- if (src.childIds.length > 0) {
- cloneChildrenWithMapping(graph, compChildId, clone.id)
- }
- applyEnclosingAssignments(graph, clone)
- instChildMap.set(compChildId, clone)
- usedInstChildIds.add(clone.id)
- }
- }
+ placeMissingChildren(graph, compParent, instParent, instChildMap, usedInstChildIds, context)
// Pass 4: Synchronize properties and recurse
for (const compChildId of compParent.childIds) {
@@ -517,7 +556,7 @@ export function syncChildren(
// its bindings are not synced.
!ownsSlotContent(graph, instChild, slotPropertyId(compChild))
) {
- syncChildren(graph, compChildId, instChild.id, overrides)
+ syncChildren(graph, compChildId, instChild.id, overrides, context)
}
}
diff --git a/packages/scene-graph/src/undo.ts b/packages/scene-graph/src/undo.ts
index c49cf6481..ca1811b1f 100644
--- a/packages/scene-graph/src/undo.ts
+++ b/packages/scene-graph/src/undo.ts
@@ -17,7 +17,8 @@ interface UndoBatch {
coalesceKey?: string
}
-const DEFAULT_HISTORY_LIMIT = 200
+/** How many edits undo keeps by default. */
+export const DEFAULT_HISTORY_LIMIT = 200
export class UndoManager {
private undoStack: UndoEntry[] = []
diff --git a/packages/scene-graph/tests/components/removed-copies.test.ts b/packages/scene-graph/tests/components/removed-copies.test.ts
new file mode 100644
index 000000000..091783ae9
--- /dev/null
+++ b/packages/scene-graph/tests/components/removed-copies.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from 'bun:test'
+
+import { DEFAULT_HISTORY_LIMIT, SceneGraph, setInstanceOverride } from '@open-pencil/scene-graph'
+
+/**
+ * A List component whose layer A an instance overrides, deleted, then `edits` other edits that
+ * each remove copies of `componentsPerEdit` components, then A coming back, as undo brings it
+ * back, with the same id. Returns whether the copy came back as it was.
+ */
+function restoreAfter(edits: number, componentsPerEdit = 1) {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const list = graph.createNode('COMPONENT', page, { name: 'List' })
+ const a = graph.createNode('TEXT', list.id, { name: 'A', text: 'a' })
+ const instance = graph.createInstance(list.id, page)
+ if (!instance) throw new Error('no instance')
+ const [copyId] = instance.childIds
+ graph.updateNode(copyId, { text: 'override' })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copyId, 'text', 'override')
+
+ graph.deleteNode(a.id)
+ graph.syncInstances(list.id)
+ expect(instance.childIds).toEqual([])
+
+ const others = Array.from({ length: componentsPerEdit }, () => {
+ const other = graph.createNode('COMPONENT', page, { name: 'Other' })
+ graph.createInstance(other.id, page)
+ return other.id
+ })
+ for (let i = 0; i < edits; i++) {
+ const layers = others.map((id) => graph.createNode('RECTANGLE', id))
+ graph.syncInstancesTogether(others)
+ for (const layer of layers) graph.deleteNode(layer.id)
+ graph.syncInstancesTogether(others)
+ }
+
+ graph.createNodeWithId(a.id, 'TEXT', list.id, { name: 'A', text: 'a' })
+ graph.syncInstances(list.id)
+ const copy = graph.getChildren(instance.id)[0]
+ return { sameCopy: copy.id === copyId, text: copy.text }
+}
+
+test('a removed copy comes back with its id and overrides while undo can still reach it', () => {
+ expect(restoreAfter(DEFAULT_HISTORY_LIMIT - 1)).toEqual({ sameCopy: true, text: 'override' })
+})
+
+test('one edit that syncs several components takes one place in what undo can bring back', () => {
+ expect(restoreAfter(DEFAULT_HISTORY_LIMIT - 1, 3)).toEqual({ sameCopy: true, text: 'override' })
+})
+
+test('a removed copy older than the undo history is forgotten, so the layer comes back fresh', () => {
+ expect(restoreAfter(DEFAULT_HISTORY_LIMIT)).toEqual({ sameCopy: false, text: 'a' })
+})