Skip to content

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

fix(fig): target nested instance overrides

Danila Poyarkov74d662d560ec
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20bf87c50..8f9ab5739 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@
- Keep desktop text visible across the scene and overlay canvases, refresh it after local fonts load, and preserve rendering when a requested italic face is unavailable (#395).
- Honor node-scoped variable modes in `.fig` files so light and dark component examples keep their intended colors.
+- Preserve nested instance text, visibility, and paint overrides across repeated children and component swaps in `.fig` files.
- Improve `.fig` import and rendering fidelity for groups, booleans, instances, rotated vectors, complex text fills, auto-sized text, layout grids, page guides, patterns, noise effects, masks, and canvas backgrounds.
- Preserve pages, components, prototype and library metadata, export settings, unsupported effects, and other unrelated Figma data when editing and resaving `.fig` files.
- Prevent duplicate generated IDs from corrupting `.fig` round trips.
diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.ts
index a97276514..b953af000 100644
--- a/packages/fig/src/instance-overrides/index.ts
+++ b/packages/fig/src/instance-overrides/index.ts
@@ -32,7 +32,7 @@ import { applyDerivedSymbolData } from './derived-symbol-data'
import { populateInstances } from './populate'
import { preComputeRoots } from './resolve'
import { applySymbolOverrides } from './symbol/overrides'
-import { propagateOverridesTransitively } from './sync'
+import { propagateNodePropsTransitively, propagateOverridesTransitively } from './sync'
import type { InstanceNodeChange, OverrideContext, ComponentPropValue } from './types'
/**
@@ -233,6 +233,7 @@ function buildOverrideContext(
propDefaults,
propNames,
preComputedRoot: new Map(),
+ preComputedClones: new Map(),
componentIdRoot: new Map(),
swappedInstances: new Set(),
protectedFields: new Map(),
@@ -327,4 +328,16 @@ export function populateAndApplyOverrides(
propagateResolvedTextClones(graph)
applyConstraintScaling(ctx)
applyComponentProperties(ctx)
+
+ // Final component-property swaps can replace descendants targeted by earlier
+ // symbol overrides. Replay property-only overrides against the final clone
+ // tree, then propagate those final targets without performing swaps again.
+ const replayedOverrides = applySymbolOverrides(ctx, true)
+ propagateNodePropsTransitively(
+ graph,
+ replayedOverrides,
+ ctx.activeNodeIds,
+ ctx.protectedFields,
+ ctx.preComputedClones
+ )
}
diff --git a/packages/fig/src/instance-overrides/resolve.ts b/packages/fig/src/instance-overrides/resolve.ts
index 51b17460b..f04f4dd42 100644
--- a/packages/fig/src/instance-overrides/resolve.ts
+++ b/packages/fig/src/instance-overrides/resolve.ts
@@ -10,6 +10,8 @@ const siblingIndexCache = new WeakMap<OverrideContext, Map<string, number | null
const siblingGroupCache = new WeakMap<OverrideContext, Map<string, string[]>>()
const candidateCache = new WeakMap<OverrideContext, Map<string, string[]>>()
const componentFindCache = new WeakMap<OverrideContext, Map<string, string | null>>()
+const sourcePathCache = new WeakMap<OverrideContext, Map<string, number[] | null>>()
+const overridePathTargetCache = new WeakMap<OverrideContext, Map<string, string>>()
/**
* Pre-compute componentId root for every node.
@@ -35,7 +37,11 @@ export function preComputeRoots(ctx: OverrideContext): void {
}
for (const node of ctx.graph.getAllNodes()) {
- if (node.componentId) resolve(node.id)
+ if (!node.componentId) continue
+ resolve(node.id)
+ const clones = ctx.preComputedClones.get(node.componentId)
+ if (clones) clones.push(node.id)
+ else ctx.preComputedClones.set(node.componentId, [node.id])
}
}
@@ -142,6 +148,56 @@ function sourceSiblingIndex(ctx: OverrideContext, sourceId: string): number | nu
return result
}
+function sourcePathToNode(
+ ctx: OverrideContext,
+ sourceRootId: string,
+ targetId: string
+): number[] | null {
+ let cache = sourcePathCache.get(ctx)
+ if (!cache) {
+ cache = new Map()
+ sourcePathCache.set(ctx, cache)
+ }
+ const cacheKey = `${sourceRootId}\0${targetId}`
+ if (cache.has(cacheKey)) return cache.get(cacheKey) ?? null
+
+ const visit = (nodeId: string, path: number[]): number[] | null => {
+ const node = ctx.graph.getNode(nodeId)
+ if (!node) return null
+ if (nodeId === targetId || node.componentId === targetId) return path
+ for (let index = 0; index < node.childIds.length; index++) {
+ const result = visit(node.childIds[index], [...path, index])
+ if (result) return result
+ }
+ return null
+ }
+
+ const result = visit(sourceRootId, [])
+ cache.set(cacheKey, result)
+ return result
+}
+
+function findNodeBySourcePath(
+ ctx: OverrideContext,
+ currentId: string,
+ targetId: string
+): string | null {
+ const current = ctx.graph.getNode(currentId)
+ if (!current?.componentId) return null
+ const path = sourcePathToNode(ctx, current.componentId, targetId)
+ if (!path) return null
+
+ let target = current
+ for (const index of path) {
+ const childId = target.childIds[index]
+ if (!childId) return null
+ const child = ctx.graph.getNode(childId)
+ if (!child) return null
+ target = child
+ }
+ return target.id
+}
+
function findNodeByNameAndType(
ctx: OverrideContext,
parentId: string,
@@ -281,6 +337,7 @@ function resolveOverrideStep(
if (current?.componentId === remapped) return currentId
return (
+ findNodeBySourcePath(ctx, currentId, remapped) ??
findNodeByComponentId(ctx, currentId, remapped) ??
findNodeBySourceSiblingIndex(ctx, currentId, remapped, sourceId) ??
findNodeByNameAndType(ctx, currentId, targetNc?.name, targetNc?.type)
@@ -292,9 +349,25 @@ export function resolveOverrideTarget(
instanceId: string,
guids: GUID[]
): string | null {
+ let pathTargets = overridePathTargetCache.get(ctx)
+ if (!pathTargets) {
+ pathTargets = new Map()
+ overridePathTargetCache.set(ctx, pathTargets)
+ }
+
let currentId = instanceId
+ const path: string[] = []
for (let index = 0; index < guids.length; index++) {
const key = guidToString(guids[index])
+ path.push(key)
+ const pathKey = `${instanceId}\0${path.join('/')}`
+ const cachedTarget = pathTargets.get(pathKey)
+ if (cachedTarget && ctx.graph.getNode(cachedTarget)) {
+ currentId = cachedTarget
+ continue
+ }
+ if (cachedTarget) pathTargets.delete(pathKey)
+
const sourceId = ctx.overrideKeyToGuid.get(key) ?? key
const targetNc = ctx.changeMap.get(sourceId)
const symbolGuid = targetNc?.symbolData?.symbolID
@@ -305,6 +378,7 @@ export function resolveOverrideTarget(
const resolved = resolveOverrideStep(ctx, currentId, sourceId, remapped, targetNc)
if (resolved) {
currentId = resolved
+ pathTargets.set(pathKey, resolved)
continue
}
@@ -312,6 +386,7 @@ export function resolveOverrideTarget(
if (parent?.childIds.length === 1) {
currentId = parent.childIds[0]
index--
+ path.pop()
continue
}
diff --git a/packages/fig/src/instance-overrides/symbol/overrides.ts b/packages/fig/src/instance-overrides/symbol/overrides.ts
index 280aa644b..ac470c163 100644
--- a/packages/fig/src/instance-overrides/symbol/overrides.ts
+++ b/packages/fig/src/instance-overrides/symbol/overrides.ts
@@ -14,7 +14,7 @@ function isActiveInstance(ctx: OverrideContext, nodeId: string | undefined): nod
* (fills, text, visibility, etc.). Returns the set of directly
* overridden node IDs (used as seeds for transitive sync).
*/
-export function applySymbolOverrides(ctx: OverrideContext): Set<string> {
+export function applySymbolOverrides(ctx: OverrideContext, propertiesOnly = false): Set<string> {
const overriddenNodes = new Set<string>()
ctx.componentIdRoot.clear()
@@ -37,6 +37,8 @@ export function applySymbolOverrides(ctx: OverrideContext): Set<string> {
const patch = patchFromSymbolOverride(ctx, targetId, ov)
if (!patch) continue
+ if (propertiesOnly) patch.swapComponentId = undefined
+ if (!patch.swapComponentId && !patch.props) continue
overriddenNodes.add(targetId)
applyOverridePatch(ctx, patch)
}
diff --git a/packages/fig/src/instance-overrides/sync/index.ts b/packages/fig/src/instance-overrides/sync/index.ts
index 74de0c4a1..ec8325771 100644
--- a/packages/fig/src/instance-overrides/sync/index.ts
+++ b/packages/fig/src/instance-overrides/sync/index.ts
@@ -1,3 +1,3 @@
export { syncNodeProps } from './fields'
export { buildClonesMap, recloneChildren, syncChildrenDeep } from './clones'
-export { propagateOverridesTransitively } from './propagate'
+export { propagateNodePropsTransitively, propagateOverridesTransitively } from './propagate'
diff --git a/packages/fig/src/instance-overrides/sync/propagate.ts b/packages/fig/src/instance-overrides/sync/propagate.ts
index a56abb009..a50cbad8a 100644
--- a/packages/fig/src/instance-overrides/sync/propagate.ts
+++ b/packages/fig/src/instance-overrides/sync/propagate.ts
@@ -36,6 +36,63 @@ function buildNeedsSyncSet(
return needsSync
}
+interface NodePropPropagationEntry {
+ lineageId: string
+ sourceId: string
+}
+
+function mergeCloneLineage(
+ current: Map<string, string[]>,
+ preComputed?: Map<string, string[]>
+): Map<string, string[]> {
+ if (!preComputed) return current
+ const merged = new Map<string, string[]>()
+ for (const source of [preComputed, current]) {
+ for (const [sourceId, cloneIds] of source) {
+ const existing = merged.get(sourceId)
+ if (existing) {
+ for (const cloneId of cloneIds) {
+ if (!existing.includes(cloneId)) existing.push(cloneId)
+ }
+ } else {
+ merged.set(sourceId, [...cloneIds])
+ }
+ }
+ }
+ return merged
+}
+
+export function propagateNodePropsTransitively(
+ graph: SceneGraph,
+ seeds: Set<string>,
+ activeNodeIds?: Set<string>,
+ protections?: ProtectionMap,
+ preComputedClones?: Map<string, string[]>
+): void {
+ if (seeds.size === 0) return
+
+ const clonesOf = mergeCloneLineage(buildClonesMap(graph, activeNodeIds), preComputedClones)
+ const visited = new Set(seeds)
+ const queue: NodePropPropagationEntry[] = [...seeds].map((id) => ({
+ lineageId: id,
+ sourceId: id
+ }))
+ let index = 0
+ while (index < queue.length) {
+ const { lineageId, sourceId } = queue[index]
+ index++
+ const source = graph.getNode(sourceId)
+ if (!source) continue
+ for (const cloneId of clonesOf.get(lineageId) ?? []) {
+ if (visited.has(cloneId)) continue
+ visited.add(cloneId)
+ const clone = graph.getNode(cloneId)
+ if (clone) syncNodeProps(graph, source, clone, protections)
+ queue.push({ lineageId: cloneId, sourceId: clone?.id ?? sourceId })
+ }
+ }
+}
+
export function propagateOverridesTransitively(
graph: SceneGraph,
seeds: Set<string>,
diff --git a/packages/fig/src/instance-overrides/types.ts b/packages/fig/src/instance-overrides/types.ts
index 37416da8a..7f4b39c9c 100644
--- a/packages/fig/src/instance-overrides/types.ts
+++ b/packages/fig/src/instance-overrides/types.ts
@@ -113,6 +113,7 @@ export interface OverrideContext {
componentPropRefsMap?: Map<string, ComponentPropRef[]>
componentPropAssignmentsMap?: Map<string, ComponentPropAssignment[]>
preComputedRoot: Map<string, string>
+ preComputedClones: Map<string, string[]>
componentIdRoot: Map<string, string>
swappedInstances: Set<string>
protectedFields: ProtectionMap
diff --git a/tests/engine/io/fig/import/edge-cases.test.ts b/tests/engine/io/fig/import/edge-cases.test.ts
index afbfe0733..1d6242799 100644
--- a/tests/engine/io/fig/import/edge-cases.test.ts
+++ b/tests/engine/io/fig/import/edge-cases.test.ts
@@ -251,6 +251,16 @@ describe('edge cases', () => {
size: { x: 24, y: 12 },
transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
} as NodeChange,
+ {
+ guid: { sessionID: 1, localID: 33 },
+ parentIndex: { guid: { sessionID: 1, localID: 3 }, position: '#' },
+ type: 'TEXT',
+ name: 'Icon label',
+ textData: { characters: 'Default' },
+ phase: 'CREATED',
+ size: { x: 24, y: 12 },
+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ } as NodeChange,
// Button component with instance of IconA
{
guid: { sessionID: 1, localID: 5 },
@@ -262,10 +272,28 @@ describe('edge cases', () => {
size: { x: 40, y: 40 },
transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
} as NodeChange,
+ {
+ guid: { sessionID: 1, localID: 62 },
+ parentIndex: { guid: { sessionID: 1, localID: 5 }, position: '!' },
+ type: 'FRAME',
+ name: 'first icon wrapper',
+ phase: 'CREATED',
+ size: { x: 24, y: 24 },
+ transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+ } as NodeChange,
+ {
+ guid: { sessionID: 1, localID: 63 },
+ parentIndex: { guid: { sessionID: 1, localID: 5 }, position: '"' },
+ type: 'FRAME',
+ name: 'second icon wrapper',
+ phase: 'CREATED',
+ size: { x: 24, y: 24 },
+ transform: { m00: 1, m01: 0, m02: 24, m10: 0, m11: 1, m12: 0 }
+ } as NodeChange,
{
guid: { sessionID: 1, localID: 6 },
overrideKey: { sessionID: 90, localID: 6 },
- parentIndex: { guid: { sessionID: 1, localID: 5 }, position: '!' },
+ parentIndex: { guid: { sessionID: 1, localID: 62 }, position: '!' },
type: 'INSTANCE',
name: 'icon',
phase: 'CREATED',
@@ -273,6 +301,17 @@ describe('edge cases', () => {
transform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },
symbolData: { symbolID: { sessionID: 1, localID: 1 } }
} as NodeChange,
+ {
+ guid: { sessionID: 1, localID: 61 },
+ overrideKey: { sessionID: 90, localID: 61 },
+ parentIndex: { guid: { sessionID: 1, localID: 63 }, position: '!' },
+ type: 'INSTANCE',
+ name: 'icon',
+ phase: 'CREATED',
+ size: { x: 24, y: 24 },
+ transform: { m00: 1, m01: 0, m02: 24, m10: 0, m11: 1, m12: 0 },
+ symbolData: { symbolID: { sessionID: 1, localID: 1 } }
+ } as NodeChange,
// Toolbar component with instance of Button, swapping icon to IconB
{
guid: { sessionID: 1, localID: 7 },
@@ -297,8 +336,17 @@ describe('edge cases', () => {
symbolID: { sessionID: 1, localID: 5 },
symbolOverrides: [
{
- guidPath: { guids: [{ sessionID: 90, localID: 6 }] },
+ guidPath: { guids: [{ sessionID: 90, localID: 61 }] },
overriddenSymbolID: { sessionID: 1, localID: 3 }
+ },
+ {
+ guidPath: {
+ guids: [
+ { sessionID: 90, localID: 61 },
+ { sessionID: 1, localID: 33 }
+ ]
+ },
+ textData: { characters: 'Changed after swap' }
}
]
}
@@ -322,19 +370,28 @@ describe('edge cases', () => {
const toolbarUse = graph.getChildren(page.id).find((n) => n.name === 'ToolbarUse')
expect(toolbarUse).toBeDefined()
- // ToolbarUse > btn clone > icon clone
+ // ToolbarUse > btn clone > second wrapped repeated icon clone
const btnClone = graph.getChildren(toolbarUse?.id ?? '')[0]
expect(btnClone).toBeDefined()
expect(btnClone.name).toBe('btn')
- const iconClone = graph.getChildren(btnClone.id)[0]
+ const buttonChildren = graph.getChildren(btnClone.id)
+ expect(buttonChildren.map((child) => child.name)).toEqual([
+ 'first icon wrapper',
+ 'second icon wrapper'
+ ])
+ const iconClone = graph.getChildren(buttonChildren[1].id)[0]
expect(iconClone).toBeDefined()
expect(iconClone.name).toBe('icon')
- // Icon should have IconB's 2 children, not IconA's 1 child
+ // Icon should have IconB's children, not IconA's child. The later text
+ // override must resolve through the same path prefix after the swap.
const iconChildren = graph.getChildren(iconClone.id)
- expect(iconChildren).toHaveLength(2)
- expect(iconChildren.map((c) => c.name).sort()).toEqual(['PathB1', 'PathB2'])
+ expect(iconChildren).toHaveLength(3)
+ expect(iconChildren.map((c) => c.name).sort()).toEqual(['Icon label', 'PathB1', 'PathB2'])
+ expect(iconChildren.find((child) => child.name === 'Icon label')?.text).toBe(
+ 'Changed after swap'
+ )
})
test('DSD propagates through intermediate clones that are also DSD-targeted', async () => {