Skip to content

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

fix(fig): preserve variable references on export

Danila Poyarkov584400e017b9
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 8b0643573..a05584990 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -105,26 +105,55 @@ async function renderFigThumbnail(
)
}
+function assignVariableGuid(
+ id: string,
+ localIdCounter: { value: number },
+ assignedGuidValues: Set<string>,
+ nodeSourceGuidValues: Set<string>
+): GUID {
+ if (/^\d+:\d+$/.test(id) && !assignedGuidValues.has(id) && !nodeSourceGuidValues.has(id)) {
+ const guid = stringToGuid(id)
+ assignedGuidValues.add(id)
+ return guid
+ }
+ const guid = { sessionID: 0, localID: localIdCounter.value++ }
+ assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
+ return guid
+}
+
function assignVariableGuids(
graph: SceneGraph,
localIdCounter: { value: number },
varIdToGuid: Map<string, GUID>,
modeIdToGuid: Map<string, GUID>,
- assignedGuidValues: Set<string>
+ assignedGuidValues: Set<string>,
+ nodeSourceGuidValues: Set<string>
): void {
for (const [colId, col] of graph.variableCollections) {
- const colGuid = { sessionID: 0, localID: localIdCounter.value++ }
+ const colGuid = assignVariableGuid(
+ colId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
varIdToGuid.set(colId, colGuid)
- assignedGuidValues.add(`${colGuid.sessionID}:${colGuid.localID}`)
for (const mode of col.modes) {
- const modeGuid = { sessionID: 0, localID: localIdCounter.value++ }
+ const modeGuid = assignVariableGuid(
+ mode.modeId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
modeIdToGuid.set(mode.modeId, modeGuid)
- assignedGuidValues.add(`${modeGuid.sessionID}:${modeGuid.localID}`)
}
for (const varId of col.variableIds) {
- const varGuid = { sessionID: 0, localID: localIdCounter.value++ }
+ const varGuid = assignVariableGuid(
+ varId,
+ localIdCounter,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
varIdToGuid.set(varId, varGuid)
- assignedGuidValues.add(`${varGuid.sessionID}:${varGuid.localID}`)
}
}
}
@@ -407,8 +436,10 @@ export async function exportFigFile(
// node claims a new counter-based GUID — preventing collisions.
let maxLocalId0 = localIdCounter.value - 1
let maxLocalId1 = localIdCounter.value - 1
+ const nodeSourceGuidValues = new Set<string>()
for (const node of graph.nodes.values()) {
if (node.source.id) {
+ nodeSourceGuidValues.add(node.source.id)
const g = stringToGuid(node.source.id)
if (g.sessionID === 0 && g.localID > maxLocalId0) {
maxLocalId0 = g.localID
@@ -431,7 +462,14 @@ export async function exportFigFile(
// Assign variable GUIDs AFTER canvas entries so that source.id-derived
// canvas GUIDs don't collide with generated variable GUIDs.
- assignVariableGuids(graph, localIdCounter, varIdToGuid, modeIdToGuid, assignedGuidValues)
+ assignVariableGuids(
+ graph,
+ localIdCounter,
+ varIdToGuid,
+ modeIdToGuid,
+ assignedGuidValues,
+ nodeSourceGuidValues
+ )
for (const entry of canvasEntries) nodeChanges.push(entry.canvasNc)
diff --git a/packages/fig/src/node-change/export-node.ts b/packages/fig/src/node-change/export-node.ts
index f003a98b8..d478002b6 100644
--- a/packages/fig/src/node-change/export-node.ts
+++ b/packages/fig/src/node-change/export-node.ts
@@ -28,11 +28,7 @@ function toKiwiBooleanOperation(operation: SceneNode['booleanOperation']): KiwiB
return operation === 'EXCLUDE' ? 'XOR' : (operation ?? 'UNION')
}
-/**
- * Build a mapping from assetRef key strings ("key@version" or "key") to
- * variable GUIDs. This is used to convert colorVar.assetRef references in raw
- * paint data to guid references that resolveAliasId can resolve on reimport.
- */
+/** Resolve effect variable asset refs when the Kiwi effect schema requires GUID aliases. */
export function buildAssetRefToVarGuidMap(
graph: SceneGraph,
varIdToGuid: Map<string, GUID>
@@ -42,9 +38,7 @@ export function buildAssetRefToVarGuidMap(
if (!variable.key) continue
const guid = varIdToGuid.get(varId) ?? stringToGuid(varId)
map.set(variable.key, guid)
- if (variable.version) {
- map.set(`${variable.key}@${variable.version}`, guid)
- }
+ if (variable.version) map.set(`${variable.key}@${variable.version}`, guid)
}
return map
}
@@ -61,8 +55,7 @@ interface SceneNodeToKiwiContext {
glyphBlobMap?: Map<string, number>
varIdToGuid?: Map<string, GUID>
modeIdToGuid?: Map<string, GUID>
- /** Maps "key@version" or "key" (from variable.key/version) → variable GUID.
- * Used to convert colorVar.assetRef references in raw paints to guid references. */
+ /** Variable GUIDs used only where raw effect aliases cannot retain asset refs. */
assetRefToVarGuid?: Map<string, GUID>
componentPropertyDefinitionsById: ReadonlyMap<string, ComponentPropertyDefinition>
fractionalPosition: (index: number) => string
@@ -392,29 +385,16 @@ function applyRawFigmaNodeFields(
// The scene model may lose this distinction for instance children whose
// strokes are resolved from component overrides. Prefer the raw data.
if ((key === 'fillPaints' || key === 'strokePaints') && node.source.id) {
- let paints = materialized[key]
- // Convert colorVar.assetRef references to guid references so that
- // resolveAliasId can resolve them on reimport. Raw paints from the
- // original .fig file use assetRef (library key/version) to refer to
- // variables, but on reimport buildAssetRefMap won't find the key unless
- // our VARIABLE NodeChanges also have key/version set. Even with that,
- // converting to guid is more robust — it works even for local variables
- // that don't have library keys.
- if (context.assetRefToVarGuid && context.assetRefToVarGuid.size > 0) {
- paints = convertColorVarAssetRefs(paints, context.assetRefToVarGuid)
- }
- nc[key] = paints
+ nc[key] = materialized[key]
continue
}
- // Also convert colorVar.assetRef in raw effects (e.g. shadow color variables)
if (
key === 'effects' &&
node.source.id &&
context.assetRefToVarGuid &&
context.assetRefToVarGuid.size > 0
) {
- const converted = convertColorVarAssetRefs(materialized[key], context.assetRefToVarGuid)
- nc[key] = converted
+ nc[key] = convertColorVarAssetRefs(materialized[key], context.assetRefToVarGuid)
continue
}
if (key === 'derivedTextData' && node.source.id) {
@@ -431,44 +411,26 @@ function applyRawFigmaNodeFields(
}
}
-/**
- * Convert colorVar.assetRef references in paints to guid references.
- * Raw paint data from imported .fig files uses assetRef (library key) for
- * variable references. On reimport, buildAssetRefMap needs nc.key on VARIABLE
- * NodeChanges to resolve assetRefs. Converting from assetRef to guid makes the
- * reference resolvable regardless of whether key/version is present on the
- * VARIABLE NodeChange.
- */
-function convertColorVarAssetRefs<T>(paints: T, assetRefToVarGuid: Map<string, GUID>): T {
- if (!Array.isArray(paints)) return paints
- const result = paints.map((paint: ColorVarCarrier) => {
- const colorVar = paint.colorVar
- const value = colorVar?.value
- const alias = value?.alias
- if (!colorVar || !value || !alias) return paint
- if (alias.guid) return paint
+/** Convert asset refs only for payloads whose Kiwi schema rejects asset-ref aliases. */
+function convertColorVarAssetRefs<T>(values: T, assetRefToVarGuid: Map<string, GUID>): T {
+ if (!Array.isArray(values)) return values
+ const converted = values.map((value: ColorVarCarrier) => {
+ const colorVar = value.colorVar
+ const alias = colorVar?.value?.alias
+ if (!colorVar || !alias || alias.guid || !alias.assetRef?.key) return value
const assetRef = alias.assetRef
- if (!assetRef?.key) return paint
- // Look up by key@version first, then by key alone
const lookupKey = assetRef.version ? `${assetRef.key}@${assetRef.version}` : assetRef.key
const guid = assetRefToVarGuid.get(lookupKey) ?? assetRefToVarGuid.get(assetRef.key)
- if (!guid) return paint
+ if (!guid) return value
return {
- ...paint,
+ ...value,
colorVar: {
...colorVar,
- value: {
- ...value,
- alias: { guid }
- }
+ value: { ...colorVar.value, alias: { guid } }
}
}
})
- // Check if any paint was actually changed (skip expensive JSON comparison)
- for (let i = 0; i < paints.length; i++) {
- if (result[i] !== paints[i]) return result as T
- }
- return paints
+ return converted.some((value, index) => value !== values[index]) ? (converted as T) : values
}
function applyInstancePayload(
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 4950dbdcf..cb9c9d3b6 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -475,7 +475,8 @@ export function sceneNodeToKiwi(
componentPropertyDefinitionsById = buildComponentPropIndex(graph),
modeIdToGuid?: Map<string, GUID>
): KiwiNodeChange[] {
- // Build assetRef to guid mapping for converting colorVar references in raw paints
+ // Raw paints retain library asset refs; effects use this map because their
+ // Kiwi schema accepts only GUID-backed aliases.
const assetRefToVarGuid = varIdToGuid ? buildAssetRefToVarGuidMap(graph, varIdToGuid) : undefined
return sceneNodeToKiwiWithContext(node, parentGuid, childIndex, localIdCounter, {
graph,
diff --git a/tests/engine/io/fig/roundtrip/exhaustive.test.ts b/tests/engine/io/fig/roundtrip/exhaustive.test.ts
index 9997143e4..e1216bebd 100644
--- a/tests/engine/io/fig/roundtrip/exhaustive.test.ts
+++ b/tests/engine/io/fig/roundtrip/exhaustive.test.ts
@@ -64,8 +64,8 @@ const SPECS: FixtureSpec[] = [
thumbnailHeight: 239,
imageCount: 3,
figKiwiVersion: 101,
- g1ExportSize: 595516,
- g2ExportSize: 595516
+ g1ExportSize: 596988,
+ g2ExportSize: 596988
}
]
diff --git a/tests/engine/io/fig/roundtrip/variables.test.ts b/tests/engine/io/fig/roundtrip/variables.test.ts
index e41f8c003..50b6b7713 100644
--- a/tests/engine/io/fig/roundtrip/variables.test.ts
+++ b/tests/engine/io/fig/roundtrip/variables.test.ts
@@ -173,6 +173,9 @@ describe('variable roundtrip', () => {
importedCollection.modes.find((mode) => mode.name === 'Dark'),
'dark mode'
)
+ expect(importedCollection.id).toBe('4:55')
+ expect(importedBackground.id).toBe('5:1')
+ expect(importedDarkMode.modeId).toBe('4:2')
expect(importedFrame.variableModes).toEqual({
[importedCollection.id]: importedDarkMode.modeId
})