Skip to content

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

Unify instance override logic between .fig import and clipboard paste

Danila Poyarkov26c14ac90381
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 8fba353c5..aa8e20525 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -8,7 +8,9 @@ import {
} from './kiwi-serialize'
import { initCodec, getCompiledSchema, getSchemaBytes } from './kiwi/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from './kiwi/kiwi-schema'
-import { nodeChangeToProps, convertFills, sortChildren } from './kiwi/kiwi-convert'
+import { nodeChangeToProps, sortChildren } from './kiwi/kiwi-convert'
+import { populateAndApplyOverrides } from './kiwi/instance-overrides'
+import type { InstanceNodeChange } from './kiwi/instance-overrides'
import type { NodeChange as KiwiNodeChange } from './kiwi/codec'
import type { SceneGraph, SceneNode } from './scene-graph'
@@ -205,65 +207,20 @@ export function importClipboardNodes(
createNode(id, targetParentId)
}
- const overrideKeyToFigmaId = new Map<string, string>()
- for (const [id, nc] of guidMap) {
- const ok = (nc as unknown as Record<string, unknown>).overrideKey as
- | { sessionID: number; localID: number }
- | undefined
- if (ok) overrideKeyToFigmaId.set(`${ok.sessionID}:${ok.localID}`, id)
- }
-
- for (const [figmaId, ourId] of created) {
+ // Remap componentId from original Figma GUIDs to our node IDs
+ for (const [, ourId] of created) {
const node = graph.getNode(ourId)
- if (!node || node.type !== 'INSTANCE' || node.childIds.length > 0) continue
-
- const figmaComponentId = node.componentId
- if (!figmaComponentId) continue
-
- const ourComponentId = created.get(figmaComponentId)
- if (!ourComponentId) continue
-
- graph.updateNode(ourId, { componentId: ourComponentId })
- graph.populateInstanceChildren(ourId, ourComponentId)
-
- const nc = guidMap.get(figmaId)
- const sd = (nc as unknown as Record<string, unknown>).symbolData as
- | { symbolOverrides?: Array<Record<string, unknown>> }
- | undefined
- if (!sd?.symbolOverrides?.length) continue
-
- const compChildIdMap = new Map<string, string>()
- for (const childId of node.childIds) {
- const child = graph.getNode(childId)
- if (child?.componentId) compChildIdMap.set(child.componentId, childId)
- }
-
- for (const ov of sd.symbolOverrides) {
- const gp = ov.guidPath as { guids?: Array<{ sessionID: number; localID: number }> } | undefined
- if (!gp?.guids?.length) continue
- const targetKey = `${gp.guids[0].sessionID}:${gp.guids[0].localID}`
-
- const figmaChildId = overrideKeyToFigmaId.get(targetKey)
- if (!figmaChildId) continue
-
- const compChildOurId = created.get(figmaChildId)
- if (!compChildOurId) continue
-
- const instanceChildId = compChildIdMap.get(compChildOurId)
- if (!instanceChildId) continue
-
- const updates: Partial<SceneNode> = {}
- const ovTd = ov.textData as { characters?: string } | undefined
- if (ovTd?.characters != null) updates.text = ovTd.characters
- if (ov.fillPaints) updates.fills = convertFills(ov.fillPaints as KiwiNodeChange['fillPaints'])
- if (ov.visible != null) updates.visible = ov.visible as boolean
- if (ov.stackChildPrimaryGrow != null) updates.layoutGrow = ov.stackChildPrimaryGrow as number
- if (ov.textAutoResize != null) updates.textAutoResize = ov.textAutoResize as SceneNode['textAutoResize']
-
- if (Object.keys(updates).length > 0) graph.updateNode(instanceChildId, updates)
- }
+ if (!node || node.type !== 'INSTANCE' || !node.componentId) continue
+ const ourComponentId = created.get(node.componentId)
+ if (ourComponentId) graph.updateNode(ourId, { componentId: ourComponentId })
}
+ populateAndApplyOverrides(
+ graph,
+ guidMap as unknown as Map<string, InstanceNodeChange>,
+ created
+ )
+
for (const figmaId of internalTopLevel) {
const ourId = created.get(figmaId)
if (ourId) graph.deleteNode(ourId)
diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.ts
index 9fe25e44c..5d0269542 100644
--- a/packages/core/src/kiwi/fig-import.ts
+++ b/packages/core/src/kiwi/fig-import.ts
@@ -1,18 +1,10 @@
import { SceneGraph } from '../scene-graph'
-import { guidToString, nodeChangeToProps, convertOverrideToProps, sortChildren } from './kiwi-convert'
+import { guidToString, nodeChangeToProps, sortChildren } from './kiwi-convert'
+import { populateAndApplyOverrides } from './instance-overrides'
+import type { InstanceNodeChange } from './instance-overrides'
-import type { NodeChange, GUID } from './codec'
-
-interface SymbolOverride {
- guidPath?: { guids?: GUID[] }
- [key: string]: unknown
-}
-
-interface SymbolData {
- symbolID?: GUID
- symbolOverrides?: SymbolOverride[]
-}
+import type { NodeChange } from './codec'
export function importNodeChanges(
nodeChanges: NodeChange[],
@@ -66,12 +58,6 @@ export function importNodeChanges(
const created = new Set<string>()
const guidToNodeId = new Map<string, string>()
- const overrideKeyToGuid = new Map<string, string>()
- for (const [id, nc] of changeMap) {
- const ok = (nc as unknown as Record<string, unknown>).overrideKey as GUID | undefined
- if (ok) overrideKeyToGuid.set(guidToString(ok), id)
- }
-
function createSceneNode(ncId: string, graphParentId: string) {
if (created.has(ncId)) return
created.add(ncId)
@@ -193,181 +179,11 @@ export function importNodeChanges(
if (remapped) node.componentId = remapped
}
- // Populate instance children from their components.
- // Multiple passes needed: cloning creates new instance nodes that
- // themselves need population.
- let populated = 1
- while (populated > 0) {
- populated = 0
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'INSTANCE' || !node.componentId || node.childIds.length > 0) continue
- const comp = graph.getNode(node.componentId)
- if (comp && comp.childIds.length > 0) {
- graph.populateInstanceChildren(node.id, node.componentId)
- populated++
- }
- }
- }
-
- // Apply symbol overrides to instance children.
- // symbolOverrides guidPaths reference nodes by overrideKey, not guid.
- const componentIdRoot = new Map<string, string>()
- function getComponentRoot(nodeId: string): string {
- if (componentIdRoot.has(nodeId)) return componentIdRoot.get(nodeId) ?? nodeId
- const node = graph.getNode(nodeId)
- if (!node?.componentId) {
- componentIdRoot.set(nodeId, nodeId)
- return nodeId
- }
- const root = getComponentRoot(node.componentId)
- componentIdRoot.set(nodeId, root)
- return root
- }
-
- function findDescendantByComponentId(parentId: string, componentId: string): string | null {
- const targetRoot = getComponentRoot(componentId)
- const parent = graph.getNode(parentId)
- if (!parent) return null
- for (const childId of parent.childIds) {
- const child = graph.getNode(childId)
- if (!child) continue
- if (child.componentId && getComponentRoot(child.componentId) === targetRoot) return childId
- const deep = findDescendantByComponentId(childId, componentId)
- if (deep) return deep
- }
- return null
- }
-
- function resolveOverrideTarget(instanceId: string, guids: GUID[]): string | null {
- let currentId = instanceId
- for (const guid of guids) {
- const key = guidToString(guid)
- const figmaGuid = overrideKeyToGuid.get(key) ?? key
- const remapped = guidToNodeId.get(figmaGuid)
- if (!remapped) return null
- const found = findDescendantByComponentId(currentId, remapped)
- if (!found) return null
- currentId = found
- }
- return currentId
- }
-
- const overriddenNodes = new Set<string>()
-
- function applySymbolOverrides() {
- componentIdRoot.clear()
-
- for (const [ncId, nc] of changeMap) {
- if (nc.type !== 'INSTANCE') continue
- const sd = (nc as unknown as Record<string, unknown>).symbolData as SymbolData | undefined
- if (!sd?.symbolOverrides?.length) continue
-
- const nodeId = guidToNodeId.get(ncId)
- if (!nodeId) continue
-
- for (const ov of sd.symbolOverrides) {
- const guids = ov.guidPath?.guids
- if (!guids?.length) continue
-
- const targetId = resolveOverrideTarget(nodeId, guids)
- if (!targetId) continue
-
- overriddenNodes.add(targetId)
-
- // Instance swap: replace target's component and re-populate children
- const swapGuid = (ov as Record<string, unknown>).overriddenSymbolID as GUID | undefined
- if (swapGuid) {
- const swapFigmaId = guidToString(swapGuid)
- const newCompId = guidToNodeId.get(swapFigmaId)
- const target = graph.getNode(targetId)
- if (newCompId && target?.type === 'INSTANCE') {
- for (const childId of [...target.childIds]) graph.deleteNode(childId)
- graph.updateNode(targetId, { componentId: newCompId })
- const newComp = graph.getNode(newCompId)
- if (newComp && newComp.childIds.length > 0) {
- graph.populateInstanceChildren(targetId, newCompId)
- }
- componentIdRoot.clear()
- }
- }
-
- const { guidPath: _, overriddenSymbolID: _s, ...fields } = ov as Record<string, unknown>
- if (Object.keys(fields).length === 0) continue
-
- const updates = convertOverrideToProps(fields as Record<string, unknown>)
- if (Object.keys(updates).length > 0) {
- graph.updateNode(targetId, updates)
- }
- }
- }
- }
-
- applySymbolOverrides()
-
- if (overriddenNodes.size > 0) {
- // Build reverse map: source → clones
- const clonesOf = new Map<string, string[]>()
- for (const node of graph.getAllNodes()) {
- if (!node.componentId) continue
- let arr = clonesOf.get(node.componentId)
- if (!arr) { arr = []; clonesOf.set(node.componentId, arr) }
- arr.push(node.id)
- }
-
- // BFS from overridden nodes to find all transitive clones
- const needsSync = new Set<string>()
- const queue = [...overriddenNodes]
- for (let id = queue.pop(); id !== undefined; id = queue.pop()) {
- const clones = clonesOf.get(id)
- if (!clones) continue
- for (const cloneId of clones) {
- if (needsSync.has(cloneId)) continue
- needsSync.add(cloneId)
- queue.push(cloneId)
- }
- }
-
- // Sync each clone from its source. Process in BFS order (closest to
- // overridden node first) so sources are updated before their clones.
- const visited = new Set<string>()
- const syncQueue = [...overriddenNodes]
- for (let sourceId = syncQueue.shift(); sourceId !== undefined; sourceId = syncQueue.shift()) {
- const clones = clonesOf.get(sourceId)
- if (!clones) continue
- const source = graph.getNode(sourceId)
- if (!source) continue
-
- for (const cloneId of clones) {
- if (!needsSync.has(cloneId) || visited.has(cloneId)) continue
- visited.add(cloneId)
- const node = graph.getNode(cloneId)
- if (!node) continue
-
- // Instance swap: re-populate children from source
- if (node.type === 'INSTANCE' && source.type === 'INSTANCE' && node.componentId) {
- for (const childId of [...node.childIds]) graph.deleteNode(childId)
- graph.populateInstanceChildren(node.id, node.componentId)
- } else {
- // Property sync
- const updates: Partial<import('../scene-graph').SceneNode> = {}
- if (source.text !== node.text) updates.text = source.text
- if (source.visible !== node.visible) updates.visible = source.visible
- if (source.opacity !== node.opacity) updates.opacity = source.opacity
- if (source.name !== node.name) updates.name = source.name
- if (source.fills !== node.fills) updates.fills = structuredClone(source.fills)
- if (source.strokes !== node.strokes) updates.strokes = structuredClone(source.strokes)
- if (source.effects !== node.effects) updates.effects = structuredClone(source.effects)
- if (source.styleRuns !== node.styleRuns) updates.styleRuns = structuredClone(source.styleRuns)
- if (source.layoutGrow !== node.layoutGrow) updates.layoutGrow = source.layoutGrow
- if (source.textAutoResize !== node.textAutoResize) updates.textAutoResize = source.textAutoResize
- if (source.locked !== node.locked) updates.locked = source.locked
- if (Object.keys(updates).length > 0) graph.updateNode(node.id, updates)
- }
-
- syncQueue.push(cloneId)
- }
- }
- }
+ populateAndApplyOverrides(
+ graph,
+ changeMap as unknown as Map<string, InstanceNodeChange>,
+ guidToNodeId
+ )
// Ensure at least one page exists
if (graph.getPages(true).length === 0) {
diff --git a/packages/core/src/kiwi/instance-overrides.ts b/packages/core/src/kiwi/instance-overrides.ts
new file mode 100644
index 000000000..47637d4f0
--- /dev/null
+++ b/packages/core/src/kiwi/instance-overrides.ts
@@ -0,0 +1,216 @@
+import type { SceneGraph, SceneNode } from '../scene-graph'
+import { guidToString, convertOverrideToProps } from './kiwi-convert'
+import type { GUID } from './codec'
+
+interface SymbolOverride {
+ guidPath?: { guids?: GUID[] }
+ [key: string]: unknown
+}
+
+interface SymbolData {
+ symbolID?: GUID
+ symbolOverrides?: SymbolOverride[]
+}
+
+export interface InstanceNodeChange {
+ type?: string
+ guid?: GUID
+ overrideKey?: GUID
+ symbolData?: SymbolData
+}
+
+/**
+ * Populate empty instances from their components and apply symbol overrides.
+ *
+ * Shared between .fig file import and clipboard paste. Both paths produce
+ * a SceneGraph with INSTANCE nodes whose componentId references have been
+ * remapped to graph node IDs but whose children may be missing and whose
+ * overrides have not yet been applied.
+ *
+ * @param graph – the SceneGraph (mutated in place)
+ * @param changeMap – figmaGuid → raw kiwi node change (for overrideKey + symbolData)
+ * @param guidToNodeId – figmaGuid → graph node ID
+ */
+export function populateAndApplyOverrides(
+ graph: SceneGraph,
+ changeMap: Map<string, InstanceNodeChange>,
+ guidToNodeId: Map<string, string>
+): void {
+ // Iterative population: cloning creates new instances that themselves need children
+ let populated = 1
+ while (populated > 0) {
+ populated = 0
+ for (const node of graph.getAllNodes()) {
+ if (node.type !== 'INSTANCE' || !node.componentId || node.childIds.length > 0) continue
+ const comp = graph.getNode(node.componentId)
+ if (comp && comp.childIds.length > 0) {
+ graph.populateInstanceChildren(node.id, node.componentId)
+ populated++
+ }
+ }
+ }
+
+ // Build overrideKey → figmaGuid map
+ const overrideKeyToGuid = new Map<string, string>()
+ for (const [id, nc] of changeMap) {
+ if (nc.overrideKey) overrideKeyToGuid.set(guidToString(nc.overrideKey), id)
+ }
+
+ // Component root resolution (walks componentId chain to the ultimate source)
+ const componentIdRoot = new Map<string, string>()
+ function getComponentRoot(nodeId: string): string {
+ if (componentIdRoot.has(nodeId)) return componentIdRoot.get(nodeId) ?? nodeId
+ const node = graph.getNode(nodeId)
+ if (!node?.componentId) {
+ componentIdRoot.set(nodeId, nodeId)
+ return nodeId
+ }
+ const root = getComponentRoot(node.componentId)
+ componentIdRoot.set(nodeId, root)
+ return root
+ }
+
+ function findDescendantByComponentId(parentId: string, componentId: string): string | null {
+ const targetRoot = getComponentRoot(componentId)
+ const parent = graph.getNode(parentId)
+ if (!parent) return null
+ for (const childId of parent.childIds) {
+ const child = graph.getNode(childId)
+ if (!child) continue
+ if (child.componentId && getComponentRoot(child.componentId) === targetRoot) return childId
+ const deep = findDescendantByComponentId(childId, componentId)
+ if (deep) return deep
+ }
+ return null
+ }
+
+ function resolveOverrideTarget(instanceId: string, guids: GUID[]): string | null {
+ let currentId = instanceId
+ for (const guid of guids) {
+ const key = guidToString(guid)
+ const figmaGuid = overrideKeyToGuid.get(key) ?? key
+ const remapped = guidToNodeId.get(figmaGuid)
+ if (!remapped) return null
+ const found = findDescendantByComponentId(currentId, remapped)
+ if (!found) return null
+ currentId = found
+ }
+ return currentId
+ }
+
+ // Apply overrides from each INSTANCE's symbolData
+ const overriddenNodes = new Set<string>()
+
+ function applySymbolOverrides() {
+ componentIdRoot.clear()
+
+ for (const [ncId, nc] of changeMap) {
+ if (nc.type !== 'INSTANCE') continue
+ const sd = nc.symbolData
+ if (!sd?.symbolOverrides?.length) continue
+
+ const nodeId = guidToNodeId.get(ncId)
+ if (!nodeId) continue
+
+ for (const ov of sd.symbolOverrides) {
+ const guids = ov.guidPath?.guids
+ if (!guids?.length) continue
+
+ const targetId = resolveOverrideTarget(nodeId, guids)
+ if (!targetId) continue
+
+ overriddenNodes.add(targetId)
+
+ // Instance swap
+ const swapGuid = (ov as Record<string, unknown>).overriddenSymbolID as GUID | undefined
+ if (swapGuid) {
+ const swapFigmaId = guidToString(swapGuid)
+ const newCompId = guidToNodeId.get(swapFigmaId)
+ const target = graph.getNode(targetId)
+ if (newCompId && target?.type === 'INSTANCE') {
+ for (const childId of [...target.childIds]) graph.deleteNode(childId)
+ graph.updateNode(targetId, { componentId: newCompId })
+ const newComp = graph.getNode(newCompId)
+ if (newComp && newComp.childIds.length > 0) {
+ graph.populateInstanceChildren(targetId, newCompId)
+ }
+ componentIdRoot.clear()
+ }
+ }
+
+ const { guidPath: _, overriddenSymbolID: _s, ...fields } = ov as Record<string, unknown>
+ if (Object.keys(fields).length === 0) continue
+
+ const updates = convertOverrideToProps(fields as Record<string, unknown>)
+ if (Object.keys(updates).length > 0) {
+ graph.updateNode(targetId, updates)
+ }
+ }
+ }
+ }
+
+ applySymbolOverrides()
+
+ if (overriddenNodes.size === 0) return
+
+ // Propagate overrides transitively through the clone chain
+ const clonesOf = new Map<string, string[]>()
+ for (const node of graph.getAllNodes()) {
+ if (!node.componentId) continue
+ let arr = clonesOf.get(node.componentId)
+ if (!arr) {
+ arr = []
+ clonesOf.set(node.componentId, arr)
+ }
+ arr.push(node.id)
+ }
+
+ const needsSync = new Set<string>()
+ const queue = [...overriddenNodes]
+ for (let id = queue.pop(); id !== undefined; id = queue.pop()) {
+ const clones = clonesOf.get(id)
+ if (!clones) continue
+ for (const cloneId of clones) {
+ if (needsSync.has(cloneId)) continue
+ needsSync.add(cloneId)
+ queue.push(cloneId)
+ }
+ }
+
+ const visited = new Set<string>()
+ const syncQueue = [...overriddenNodes]
+ for (let sourceId = syncQueue.shift(); sourceId !== undefined; sourceId = syncQueue.shift()) {
+ const clones = clonesOf.get(sourceId)
+ if (!clones) continue
+ const source = graph.getNode(sourceId)
+ if (!source) continue
+
+ for (const cloneId of clones) {
+ if (!needsSync.has(cloneId) || visited.has(cloneId)) continue
+ visited.add(cloneId)
+ const node = graph.getNode(cloneId)
+ if (!node) continue
+
+ if (node.type === 'INSTANCE' && source.type === 'INSTANCE' && node.componentId) {
+ for (const childId of [...node.childIds]) graph.deleteNode(childId)
+ graph.populateInstanceChildren(node.id, node.componentId)
+ } else {
+ const updates: Partial<SceneNode> = {}
+ if (source.text !== node.text) updates.text = source.text
+ if (source.visible !== node.visible) updates.visible = source.visible
+ if (source.opacity !== node.opacity) updates.opacity = source.opacity
+ if (source.name !== node.name) updates.name = source.name
+ if (source.fills !== node.fills) updates.fills = structuredClone(source.fills)
+ if (source.strokes !== node.strokes) updates.strokes = structuredClone(source.strokes)
+ if (source.effects !== node.effects) updates.effects = structuredClone(source.effects)
+ if (source.styleRuns !== node.styleRuns) updates.styleRuns = structuredClone(source.styleRuns)
+ if (source.layoutGrow !== node.layoutGrow) updates.layoutGrow = source.layoutGrow
+ if (source.textAutoResize !== node.textAutoResize) updates.textAutoResize = source.textAutoResize
+ if (source.locked !== node.locked) updates.locked = source.locked
+ if (Object.keys(updates).length > 0) graph.updateNode(node.id, updates)
+ }
+
+ syncQueue.push(cloneId)
+ }
+ }
+}