Skip to content

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

fix(kiwi): resolve Figma variable aliases

Danila Poyarkov317b3469df65
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index d3b4e6d0b..25d0a7010 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -31,11 +31,13 @@ type KiwiNodeChange = NodeChange & Record<string, unknown>
function variableValueToKiwi(
value: VariableValue,
- type: string
+ type: string,
+ varIdToGuid: Map<string, GUID>
): { value: Record<string, unknown>; dataType: string; resolvedDataType: string } {
- if (typeof value === 'object' && 'aliasId' in value) {
+ if (value && typeof value === 'object' && 'aliasId' in value) {
+ const aliasGuid = varIdToGuid.get(value.aliasId) ?? stringToGuid(value.aliasId)
return {
- value: { alias: { guid: stringToGuid(value.aliasId) } },
+ value: { alias: { guid: aliasGuid } },
dataType: 'ALIAS',
resolvedDataType: { COLOR: 'COLOR', BOOLEAN: 'BOOLEAN', STRING: 'STRING' }[type] ?? 'FLOAT'
}
@@ -71,6 +73,102 @@ function collectImageEntries(graph: SceneGraph): Array<{ name: string; data: Uin
const THUMBNAIL_WIDTH = 400
const THUMBNAIL_HEIGHT = 225
+function assignVariableGuids(
+ graph: SceneGraph,
+ localIdCounter: { value: number },
+ varIdToGuid: Map<string, GUID>,
+ modeIdToGuid: Map<string, GUID>
+): void {
+ for (const [colId, col] of graph.variableCollections) {
+ varIdToGuid.set(colId, { sessionID: 0, localID: localIdCounter.value++ })
+ for (const mode of col.modes) {
+ modeIdToGuid.set(mode.modeId, { sessionID: 0, localID: localIdCounter.value++ })
+ }
+ for (const varId of col.variableIds) {
+ varIdToGuid.set(varId, { sessionID: 0, localID: localIdCounter.value++ })
+ }
+ }
+}
+
+function appendVariableNodeChanges(
+ graph: SceneGraph,
+ nodeChanges: KiwiNodeChange[],
+ internalCanvasGuid: GUID,
+ varIdToGuid: Map<string, GUID>,
+ modeIdToGuid: Map<string, GUID>
+): void {
+ let collIdx = 0
+ for (const [colId, col] of graph.variableCollections) {
+ const colGuid = varIdToGuid.get(colId) ?? stringToGuid(colId)
+ nodeChanges.push({
+ guid: colGuid,
+ parentIndex: { guid: internalCanvasGuid, position: fractionalPosition(collIdx++) },
+ type: 'VARIABLE_SET',
+ name: col.name,
+ phase: 'CREATED',
+ strokeAlign: 'CENTER',
+ strokeJoin: 'BEVEL',
+ variableSetModes: col.modes.map((m, i) => {
+ const mGuid = modeIdToGuid.get(m.modeId) ?? stringToGuid(m.modeId)
+ return { id: mGuid, name: m.name, sortPosition: fractionalPosition(i) }
+ })
+ })
+
+ appendVariablesForCollection(
+ graph,
+ nodeChanges,
+ colGuid,
+ internalCanvasGuid,
+ col.variableIds,
+ varIdToGuid,
+ modeIdToGuid
+ )
+ }
+}
+
+function appendVariablesForCollection(
+ graph: SceneGraph,
+ nodeChanges: KiwiNodeChange[],
+ colGuid: GUID,
+ parentGuid: GUID,
+ variableIds: string[],
+ varIdToGuid: Map<string, GUID>,
+ modeIdToGuid: Map<string, GUID>
+): void {
+ let varIdx = 0
+ for (const varId of variableIds) {
+ const variable = graph.variables.get(varId)
+ if (!variable) continue
+
+ const varGuid = varIdToGuid.get(varId) ?? stringToGuid(varId)
+ const typeMap: Record<string, string> = {
+ COLOR: 'COLOR',
+ BOOLEAN: 'BOOLEAN',
+ STRING: 'STRING'
+ }
+ const resolvedType = typeMap[variable.type] ?? 'FLOAT'
+
+ const entries = Object.entries(variable.valuesByMode).map(([modeId, value]) => ({
+ modeID: modeIdToGuid.get(modeId) ?? stringToGuid(modeId),
+ variableData: variableValueToKiwi(value, variable.type, varIdToGuid)
+ }))
+
+ nodeChanges.push({
+ guid: varGuid,
+ parentIndex: { guid: parentGuid, position: fractionalPosition(varIdx++) },
+ type: 'VARIABLE',
+ name: variable.name,
+ phase: 'CREATED',
+ strokeAlign: 'CENTER',
+ strokeJoin: 'BEVEL',
+ variableSetID: { guid: colGuid },
+ variableResolvedType: resolvedType,
+ variableDataValues: { entries },
+ variableScopes: ['ALL_SCOPES']
+ })
+ }
+}
+
export async function exportFigFile(
graph: SceneGraph,
ck?: CanvasKit,
@@ -90,9 +188,12 @@ export async function exportFigFile(
const pages = graph.getPages(true)
const nodeIdToGuid = new Map<string, GUID>()
const varIdToGuid = new Map<string, GUID>()
+ const modeIdToGuid = new Map<string, GUID>()
const fontDigestMap = await buildFontDigestMap(graph)
let internalCanvasGuid: GUID | null = null
+ assignVariableGuids(graph, localIdCounter, varIdToGuid, modeIdToGuid)
+
for (let p = 0; p < pages.length; p++) {
const page = pages[p]
const canvasLocalID = localIdCounter.value++
@@ -141,63 +242,7 @@ export async function exportFigFile(
)
}
- const modeIdToGuid = new Map<string, GUID>()
-
- let collIdx = 0
- for (const [colId, col] of graph.variableCollections) {
- const colGuid = { sessionID: 0, localID: localIdCounter.value++ }
- varIdToGuid.set(colId, colGuid)
- const colNc: KiwiNodeChange = {
- guid: colGuid,
- parentIndex: { guid: internalCanvasGuid, position: fractionalPosition(collIdx++) },
- type: 'VARIABLE_SET',
- name: col.name,
- phase: 'CREATED',
- strokeAlign: 'CENTER',
- strokeJoin: 'BEVEL',
- variableSetModes: col.modes.map((m, i) => {
- const mGuid = { sessionID: 0, localID: localIdCounter.value++ }
- modeIdToGuid.set(m.modeId, mGuid)
- return { id: mGuid, name: m.name, sortPosition: fractionalPosition(i) }
- })
- }
- nodeChanges.push(colNc)
-
- let varIdx = 0
- for (const varId of col.variableIds) {
- const variable = graph.variables.get(varId)
- if (!variable) continue
-
- const varGuid = { sessionID: 0, localID: localIdCounter.value++ }
- varIdToGuid.set(varId, varGuid)
- const typeMap: Record<string, string> = {
- COLOR: 'COLOR',
- BOOLEAN: 'BOOLEAN',
- STRING: 'STRING'
- }
- const resolvedType = typeMap[variable.type] ?? 'FLOAT'
-
- const entries = Object.entries(variable.valuesByMode).map(([modeId, value]) => ({
- modeID: modeIdToGuid.get(modeId) ?? stringToGuid(modeId),
- variableData: variableValueToKiwi(value, variable.type)
- }))
-
- const varNc: KiwiNodeChange = {
- guid: varGuid,
- parentIndex: { guid: internalCanvasGuid, position: fractionalPosition(varIdx++) },
- type: 'VARIABLE',
- name: variable.name,
- phase: 'CREATED',
- strokeAlign: 'CENTER',
- strokeJoin: 'BEVEL',
- variableSetID: { guid: colGuid },
- variableResolvedType: resolvedType,
- variableDataValues: { entries },
- variableScopes: ['ALL_SCOPES']
- }
- nodeChanges.push(varNc)
- }
- }
+ appendVariableNodeChanges(graph, nodeChanges, internalCanvasGuid, varIdToGuid, modeIdToGuid)
}
const msg: Record<string, unknown> = {
diff --git a/packages/core/src/kiwi/codec.ts b/packages/core/src/kiwi/codec.ts
index aeb4ba924..ee734927d 100644
--- a/packages/core/src/kiwi/codec.ts
+++ b/packages/core/src/kiwi/codec.ts
@@ -200,7 +200,7 @@ export interface Paint {
value?: {
alias?: {
guid?: GUID
- assetRef?: { key: string; version: string }
+ assetRef?: { key: string; version?: string }
}
}
dataType?: string
@@ -223,7 +223,7 @@ export interface VariableAnyValue {
textValue?: string
floatValue?: number
colorValue?: Color
- alias?: { guid: GUID }
+ alias?: { guid?: GUID; assetRef?: { key: string; version?: string } }
}
export interface VariableDataEntry {
@@ -373,7 +373,7 @@ export interface NodeChange {
variableData?: VariableDataEntry
variableConsumptionMap?: { entries?: VariableConsumptionEntry[] }
variableSetModes?: Array<{ id: GUID; name: string; sortPosition?: string }>
- variableSetID?: { guid: GUID }
+ variableSetID?: { guid?: GUID; assetRef?: { key: string; version?: string } }
variableResolvedType?: string
variableDataValues?: { entries?: VariableDataValuesEntry[] }
variableScopes?: string[]
diff --git a/packages/core/src/kiwi/convert.ts b/packages/core/src/kiwi/convert.ts
index d498585ef..4b0f74ac7 100644
--- a/packages/core/src/kiwi/convert.ts
+++ b/packages/core/src/kiwi/convert.ts
@@ -48,6 +48,8 @@ export function guidToString(guid: GUID): string {
}
export function stringToGuid(str: string): GUID {
+ const match = str.match(/^(?:VariableID:|VariableCollectionId:)?(\d+):(\d+)$/)
+ if (match) return { sessionID: parseInt(match[1], 10), localID: parseInt(match[2], 10) }
const [session, local] = str.split(':')
return { sessionID: parseInt(session, 10), localID: parseInt(local, 10) }
}
@@ -92,17 +94,20 @@ function convertGradientTransform(t?: Matrix): GradientTransform | undefined {
return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }
}
-let variableColorResolver: ((guid: GUID) => Color | null) | null = null
+type VariableAliasRef = NonNullable<NonNullable<NonNullable<Paint['colorVar']>['value']>['alias']>
-export function setVariableColorResolver(resolver: ((guid: GUID) => Color | null) | null): void {
+let variableColorResolver: ((alias: VariableAliasRef) => Color | null) | null = null
+
+export function setVariableColorResolver(
+ resolver: ((alias: VariableAliasRef) => Color | null) | null
+): void {
variableColorResolver = resolver
}
function resolveColorVar(paint: Paint): Color | undefined {
const alias = paint.colorVar?.value?.alias
if (!alias || !variableColorResolver) return undefined
- if (alias.guid) return variableColorResolver(alias.guid) ?? undefined
- return undefined
+ return variableColorResolver(alias) ?? undefined
}
export function convertFills(paints?: Paint[]): Fill[] {
@@ -149,8 +154,8 @@ export function convertStrokes(
paints?: Paint[],
weight?: number,
align?: string,
- cap?: string,
- join?: string,
+ cap?: StrokeCap,
+ join?: StrokeJoin,
dashPattern?: number[]
): Stroke[] {
if (!paints) return []
@@ -164,8 +169,8 @@ export function convertStrokes(
opacity: p.opacity ?? 1,
visible: p.visible ?? true,
align: strokeAlign,
- cap: (cap ?? 'NONE') as StrokeCap,
- join: (join ?? 'MITER') as StrokeJoin,
+ cap: cap ?? 'NONE',
+ join: join ?? 'MITER',
dashPattern: dashPattern ?? []
}))
}
@@ -242,6 +247,7 @@ export function mapStackJustify(justify?: string): LayoutAlign {
case 'MAX':
return 'MAX'
case 'SPACE_BETWEEN':
+ case 'SPACE_EVENLY':
return 'SPACE_BETWEEN'
default:
return 'MIN'
@@ -685,32 +691,29 @@ function convertLayoutProps(
}
}
-function convertVectorAndStrokeProps(
- nc: NodeChange,
- blobs: Uint8Array[]
-): Pick<
- SceneNode,
- | 'vectorNetwork'
- | 'fillGeometry'
- | 'strokeGeometry'
- | 'arcData'
- | 'strokeCap'
- | 'strokeJoin'
- | 'dashPattern'
- | 'borderTopWeight'
- | 'borderRightWeight'
- | 'borderBottomWeight'
- | 'borderLeftWeight'
- | 'independentStrokeWeights'
- | 'strokeMiterLimit'
-> {
+function getVectorStrokeCap(nc: NodeChange, vectorNetwork: VectorNetwork | null): StrokeCap {
+ return (nc.strokeCap ??
+ vectorNetwork?.vertices.find((v) => v.strokeCap)?.strokeCap ??
+ 'NONE') as StrokeCap
+}
+
+function getVectorStrokeJoin(nc: NodeChange, vectorNetwork: VectorNetwork | null): StrokeJoin {
+ return (nc.strokeJoin ??
+ vectorNetwork?.vertices.find((v) => v.strokeJoin)?.strokeJoin ??
+ 'MITER') as StrokeJoin
+}
+
+function convertVectorAndStrokeProps(nc: NodeChange, blobs: Uint8Array[]) {
+ const vectorNetwork = resolveVectorNetwork(nc, blobs)
+ const strokeCap = getVectorStrokeCap(nc, vectorNetwork)
+ const strokeJoin = getVectorStrokeJoin(nc, vectorNetwork)
return {
- vectorNetwork: resolveVectorNetwork(nc, blobs),
+ vectorNetwork,
fillGeometry: resolveGeometryPaths(nc.fillGeometry, blobs),
strokeGeometry: resolveGeometryPaths(nc.strokeGeometry, blobs),
arcData: mapArcData(nc.arcData as Partial<ArcData> | undefined),
- strokeCap: (nc.strokeCap ?? 'NONE') as StrokeCap,
- strokeJoin: (nc.strokeJoin ?? 'MITER') as StrokeJoin,
+ strokeCap,
+ strokeJoin,
dashPattern: nc.dashPattern ?? [],
borderTopWeight: (nc.borderTopWeight ?? 0) as number,
borderRightWeight: (nc.borderRightWeight ?? 0) as number,
@@ -728,6 +731,8 @@ export function nodeChangeToProps(
let nodeType = mapNodeType(nc.type)
if (nodeType === 'FRAME' && isComponentSet(nc)) nodeType = 'COMPONENT_SET'
+ const vectorAndStrokeProps = convertVectorAndStrokeProps(nc, blobs)
+
return {
nodeType,
name: nc.name ?? nodeType,
@@ -741,8 +746,8 @@ export function nodeChangeToProps(
nc.strokePaints,
nc.strokeWeight,
nc.strokeAlign,
- nc.strokeCap,
- nc.strokeJoin,
+ vectorAndStrokeProps.strokeCap,
+ vectorAndStrokeProps.strokeJoin,
nc.dashPattern ?? []
),
effects: convertEffects(nc.effects),
@@ -751,7 +756,7 @@ export function nodeChangeToProps(
horizontalConstraint: mapConstraint(nc.horizontalConstraint as string),
verticalConstraint: mapConstraint(nc.verticalConstraint as string),
...convertLayoutProps(nc),
- ...convertVectorAndStrokeProps(nc, blobs),
+ ...vectorAndStrokeProps,
minWidth: (nc.minWidth ?? null) as number | null,
maxWidth: (nc.maxWidth ?? null) as number | null,
minHeight: (nc.minHeight ?? null) as number | null,
diff --git a/packages/core/src/kiwi/fig-import.ts b/packages/core/src/kiwi/fig-import.ts
index 2e7378234..3c6af9a19 100644
--- a/packages/core/src/kiwi/fig-import.ts
+++ b/packages/core/src/kiwi/fig-import.ts
@@ -12,9 +12,37 @@ import type { VariableType, VariableValue } from '../scene-graph'
import type { NodeChange, VariableDataValuesEntry, Color, GUID } from './codec'
import type { InstanceNodeChange } from './instance-overrides'
+type AssetRef = { key: string; version?: string }
+type AliasRef = { guid?: GUID; assetRef?: AssetRef }
+
+function assetRefKey(assetRef: AssetRef): string {
+ return assetRef.version ? `${assetRef.key}@${assetRef.version}` : assetRef.key
+}
+
+function buildAssetRefMap(changeMap: Map<string, NodeChange>): Map<string, string> {
+ const refs = new Map<string, string>()
+ for (const [id, nc] of changeMap) {
+ if (typeof nc.key !== 'string') continue
+ refs.set(nc.key, id)
+ if (typeof nc.version === 'string')
+ refs.set(assetRefKey({ key: nc.key, version: nc.version }), id)
+ if (typeof nc.userFacingVersion === 'string') {
+ refs.set(assetRefKey({ key: nc.key, version: nc.userFacingVersion }), id)
+ }
+ }
+ return refs
+}
+
+function resolveAliasId(alias: AliasRef, assetRefs: Map<string, string>): string | undefined {
+ if (alias.guid) return guidToString(alias.guid)
+ if (!alias.assetRef) return undefined
+ return assetRefs.get(assetRefKey(alias.assetRef)) ?? assetRefs.get(alias.assetRef.key)
+}
+
function buildVariableColorResolver(
- changeMap: Map<string, NodeChange>
-): (guid: GUID) => Color | null {
+ changeMap: Map<string, NodeChange>,
+ assetRefs: Map<string, string>
+): (alias: AliasRef) => Color | null {
// Collect variable data: GUID → entries
const varEntries = new Map<string, VariableDataValuesEntry[]>()
const varSetId = new Map<string, string>()
@@ -35,26 +63,37 @@ function buildVariableColorResolver(
if (modes.length > 0) defaultModes.set(id, guidToString(modes[0].id))
}
- return function resolve(guid: GUID, depth = 0): Color | null {
+ function resolveById(
+ id: string,
+ preferredModeId: string | undefined,
+ depth: number
+ ): Color | null {
if (depth > 10) return null
- const id = guidToString(guid)
const entries = varEntries.get(id)
if (!entries?.length) return null
- // Find the default mode value
const setId = varSetId.get(id)
const defaultMode = setId ? defaultModes.get(setId) : undefined
- let entry = defaultMode
- ? entries.find((e) => guidToString(e.modeID) === defaultMode)
+ let entry = preferredModeId
+ ? entries.find((e) => guidToString(e.modeID) === preferredModeId)
: undefined
+ if (!entry && defaultMode) entry = entries.find((e) => guidToString(e.modeID) === defaultMode)
if (!entry) entry = entries[0]
const val = entry.variableData.value
if (!val) return null
if (val.colorValue) return val.colorValue
- if (val.alias?.guid) return resolve(val.alias.guid, depth + 1)
+ if (val.alias) {
+ const aliasId = resolveAliasId(val.alias, assetRefs)
+ if (aliasId) return resolveById(aliasId, guidToString(entry.modeID), depth + 1)
+ }
return null
}
+
+ return function resolve(alias: AliasRef): Color | null {
+ const id = resolveAliasId(alias, assetRefs)
+ return id ? resolveById(id, undefined, 0) : null
+ }
}
interface ChangeMaps {
@@ -101,7 +140,10 @@ function resolveVariableType(resolvedType: string | undefined): VariableType {
return 'FLOAT'
}
-function resolveVariableValue(entry: VariableDataValuesEntry): VariableValue | undefined {
+function resolveVariableValue(
+ entry: VariableDataValuesEntry,
+ assetRefs: Map<string, string>
+): VariableValue | undefined {
const vd = entry.variableData
if (!vd.value) return undefined
@@ -112,8 +154,10 @@ function resolveVariableValue(entry: VariableDataValuesEntry): VariableValue | u
}
if (dt === 'BOOLEAN') return vd.value.boolValue ?? false
if (dt === 'STRING') return vd.value.textValue ?? ''
- if (dt === 'ALIAS' && vd.value.alias?.guid) {
- return { aliasId: guidToString(vd.value.alias.guid) }
+ if (dt === 'ALIAS' && vd.value.alias) {
+ const aliasId = resolveAliasId(vd.value.alias, assetRefs)
+ if (aliasId) return { aliasId }
+ return undefined
}
return vd.value.floatValue ?? 0
}
@@ -145,35 +189,52 @@ function importCollections(changeMap: Map<string, NodeChange>, graph: SceneGraph
}
}
+function resolveVariableCollectionId(
+ nc: NodeChange,
+ id: string,
+ parentMap: Map<string, string>,
+ assetRefs: Map<string, string>
+): string {
+ if (nc.variableSetID?.guid) return guidToString(nc.variableSetID.guid)
+ const assetRef = nc.variableSetID?.assetRef
+ if (assetRef) return assetRefs.get(assetRefKey(assetRef)) ?? assetRefs.get(assetRef.key) ?? ''
+ return parentMap.get(id) ?? ''
+}
+
+function addFallbackCollection(
+ changeMap: Map<string, NodeChange>,
+ graph: SceneGraph,
+ collectionId: string
+): void {
+ if (graph.variableCollections.has(collectionId)) return
+ const parentNc = changeMap.get(collectionId)
+ graph.addCollection({
+ id: collectionId,
+ name: parentNc?.name ?? 'Variables',
+ modes: [{ modeId: 'default', name: 'Default' }],
+ defaultModeId: 'default',
+ variableIds: []
+ })
+}
+
function importVariableEntries(
changeMap: Map<string, NodeChange>,
parentMap: Map<string, string>,
- graph: SceneGraph
+ graph: SceneGraph,
+ assetRefs: Map<string, string>
): void {
for (const [id, nc] of changeMap) {
if (nc.type !== 'VARIABLE') continue
- const collectionId = nc.variableSetID?.guid
- ? guidToString(nc.variableSetID.guid)
- : (parentMap.get(id) ?? '')
-
- if (!graph.variableCollections.has(collectionId)) {
- const parentNc = changeMap.get(collectionId)
- graph.addCollection({
- id: collectionId,
- name: parentNc?.name ?? 'Variables',
- modes: [{ modeId: 'default', name: 'Default' }],
- defaultModeId: 'default',
- variableIds: []
- })
- }
+ const collectionId = resolveVariableCollectionId(nc, id, parentMap, assetRefs)
+ addFallbackCollection(changeMap, graph, collectionId)
const type = resolveVariableType(nc.variableResolvedType)
const valuesByMode: Record<string, VariableValue> = {}
if (nc.variableDataValues?.entries) {
for (const entry of nc.variableDataValues.entries) {
- const val = resolveVariableValue(entry)
+ const val = resolveVariableValue(entry, assetRefs)
if (val !== undefined) {
valuesByMode[guidToString(entry.modeID)] = val
}
@@ -294,6 +355,8 @@ export function importNodeChanges(
}
const { changeMap, parentMap, childrenMap } = buildChangeMaps(nodeChanges)
+ const assetRefs = buildAssetRefMap(changeMap)
+ setVariableColorResolver(buildVariableColorResolver(changeMap, assetRefs))
const canvasIdToPageId = new Map<string, string>()
const created = new Set<string>()
@@ -322,11 +385,10 @@ export function importNodeChanges(
importPages(graph, changeMap, parentMap, childrenMap, created, canvasIdToPageId, createSceneNode)
importCollections(changeMap, graph)
- importVariableEntries(changeMap, parentMap, graph)
+ importVariableEntries(changeMap, parentMap, graph, assetRefs)
importVariableBindings(changeMap, guidToNodeId, graph)
remapComponentIds(graph, guidToNodeId)
- setVariableColorResolver(buildVariableColorResolver(changeMap))
populateAndApplyOverrides(
graph,
changeMap as unknown as Map<string, InstanceNodeChange>,
diff --git a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts b/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts
index 561e2435b..b70b94153 100644
--- a/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts
+++ b/packages/core/src/kiwi/instance-overrides/symbol-overrides.ts
@@ -2,8 +2,30 @@ import { guidToString } from '../convert'
import { convertOverrideToProps } from '../convert-overrides'
import { resolveOverrideTarget, repopulateInstance } from './resolve'
+import type { SceneNode } from '../../scene-graph'
import type { OverrideContext } from './types'
+function preserveStrokeShapeProps(target: SceneNode, updates: Partial<SceneNode>): void {
+ if (!updates.strokes) return
+ updates.strokes = updates.strokes.map((stroke, index) => {
+ if (index >= target.strokes.length) {
+ return {
+ ...stroke,
+ cap: target.strokeCap,
+ join: target.strokeJoin,
+ dashPattern: target.dashPattern
+ }
+ }
+ const existing = target.strokes[index]
+ return {
+ ...stroke,
+ cap: existing.cap,
+ join: existing.join,
+ dashPattern: existing.dashPattern
+ }
+ })
+}
+
/**
* Apply symbolOverrides from kiwi data.
*
@@ -51,6 +73,8 @@ export function applySymbolOverrides(ctx: OverrideContext): Set<string> {
const updates = convertOverrideToProps(fields as Record<string, unknown>)
if (Object.keys(updates).length > 0) {
+ const target = ctx.graph.getNode(targetId)
+ if (target) preserveStrokeShapeProps(target, updates)
ctx.graph.updateNode(targetId, updates)
}
}
diff --git a/packages/core/src/scene-graph/index.ts b/packages/core/src/scene-graph/index.ts
index 817f142bc..c99e8ac5d 100644
--- a/packages/core/src/scene-graph/index.ts
+++ b/packages/core/src/scene-graph/index.ts
@@ -737,12 +737,24 @@ export class SceneGraph {
if (visited?.has(variableId)) return undefined
const variable = this.variables.get(variableId)
if (!variable) return undefined
- const resolvedModeId = modeId ?? this.getActiveModeId(variable.collectionId)
- const value = variable.valuesByMode[resolvedModeId]
- if (typeof value === 'object' && 'aliasId' in value) {
+ const collection = this.variableCollections.get(variable.collectionId)
+ const preferredModeId = modeId ?? this.getActiveModeId(variable.collectionId)
+ const fallbackModeId = collection?.defaultModeId
+ let value = Object.hasOwn(variable.valuesByMode, preferredModeId)
+ ? variable.valuesByMode[preferredModeId]
+ : undefined
+ if (
+ value === undefined &&
+ fallbackModeId &&
+ Object.hasOwn(variable.valuesByMode, fallbackModeId)
+ ) {
+ value = variable.valuesByMode[fallbackModeId]
+ }
+ value ??= Object.values(variable.valuesByMode)[0]
+ if (value && typeof value === 'object' && 'aliasId' in value) {
const seen = visited ?? new Set<string>()
seen.add(variableId)
- return this.resolveVariable(value.aliasId, undefined, seen)
+ return this.resolveVariable(value.aliasId, preferredModeId, seen)
}
return value
}
diff --git a/tests/engine/fig-export-variables.test.ts b/tests/engine/fig-export-variables.test.ts
index 161c72398..1d6ac178d 100644
--- a/tests/engine/fig-export-variables.test.ts
+++ b/tests/engine/fig-export-variables.test.ts
@@ -44,4 +44,21 @@ describe('COLOR variable alpha handling', () => {
const val = Object.values(colorVar.valuesByMode)[0] as { r: number; g: number; b: number; a: number }
expect(val.a).toBeCloseTo(0.5, 1)
})
+
+ test('alias variables export with generated target GUIDs', async () => {
+ const graph = new SceneGraph()
+ const col = graph.createCollection('Colors')
+ const target = graph.createVariable('base', 'COLOR', col.id, { r: 0.1, g: 0.2, b: 0.3, a: 1 })
+ graph.createVariable('alias', 'COLOR', col.id, { aliasId: target.id })
+
+ const exported = await exportFigFile(graph)
+ const reimported = await parseFigFile(exported.buffer as ArrayBuffer)
+
+ const alias = [...reimported.variables.values()].find((v) => v.name === 'alias')!
+ const resolved = reimported.resolveColorVariable(alias.id)!
+ expect(resolved.r).toBeCloseTo(0.1)
+ expect(resolved.g).toBeCloseTo(0.2)
+ expect(resolved.b).toBeCloseTo(0.3)
+ expect(resolved.a).toBe(1)
+ })
})
diff --git a/tests/engine/fig-import.test.ts b/tests/engine/fig-import.test.ts
index fed4fe890..9c5bcc85e 100644
--- a/tests/engine/fig-import.test.ts
+++ b/tests/engine/fig-import.test.ts
@@ -353,6 +353,102 @@ describe('fig-import: multiple fills', () => {
})
})
+describe('fig-import: auto-layout alignment', () => {
+ test('maps SPACE_EVENLY kiwi primary alignment to Figma space-between', () => {
+ const graph = importNodeChanges([
+ doc(),
+ canvas(),
+ node('FRAME', 10, 1, {
+ stackMode: 'HORIZONTAL',
+ stackPrimaryAlignItems: 'SPACE_EVENLY',
+ } as Partial<NodeChange>),
+ ])
+ const n = graph.getChildren(graph.getPages()[0].id)[0]
+ expect(n.primaryAxisAlign).toBe('SPACE_BETWEEN')
+ })
+})
+
+describe('fig-import: variable asset refs', () => {
+ test('resolves color variables and aliases by assetRef', () => {
+ const graph = importNodeChanges([
+ doc(),
+ canvas(),
+ {
+ ...node('VARIABLE_SET', 20, 1),
+ name: 'Tokens',
+ key: 'collection-key',
+ version: '1:1',
+ variableSetModes: [{ id: { sessionID: 10, localID: 1 }, name: 'Default' }],
+ } as NodeChange,
+ {
+ ...node('VARIABLE', 21, 1),
+ name: 'Blue',
+ key: 'blue-key',
+ version: '1:2',
+ variableSetID: { assetRef: { key: 'collection-key', version: '1:1' } },
+ variableResolvedType: 'COLOR',
+ variableDataValues: {
+ entries: [
+ {
+ modeID: { sessionID: 10, localID: 1 },
+ variableData: {
+ dataType: 'COLOR',
+ resolvedDataType: 'COLOR',
+ value: { colorValue: { r: 0.14, g: 0.39, b: 0.92, a: 1 } },
+ },
+ },
+ ],
+ },
+ } as NodeChange,
+ {
+ ...node('VARIABLE', 22, 1),
+ name: 'Primary',
+ key: 'primary-key',
+ version: '1:3',
+ variableSetID: { assetRef: { key: 'collection-key', version: '1:1' } },
+ variableResolvedType: 'COLOR',
+ variableDataValues: {
+ entries: [
+ {
+ modeID: { sessionID: 10, localID: 1 },
+ variableData: {
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR',
+ value: { alias: { assetRef: { key: 'blue-key', version: '1:2' } } },
+ },
+ },
+ ],
+ },
+ } as NodeChange,
+ node('TEXT', 30, 1, {
+ textData: { characters: 'browse' },
+ fillPaints: [
+ {
+ type: 'SOLID',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ colorVar: {
+ value: { alias: { assetRef: { key: 'primary-key', version: '1:3' } } },
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR',
+ },
+ },
+ ] as unknown as NodeChange['fillPaints'],
+ }),
+ ])
+
+ const primary = [...graph.variables.values()].find((v) => v.name === 'Primary')!
+ const resolved = graph.resolveColorVariable(primary.id)!
+ expect(resolved.r).toBeCloseTo(0.14)
+ expect(resolved.g).toBeCloseTo(0.39)
+ expect(resolved.b).toBeCloseTo(0.92)
+
+ const text = [...graph.getAllNodes()].find((n) => n.type === 'TEXT' && n.text === 'browse')!
+ expect(text.fills[0].color.r).toBeCloseTo(0.14)
+ expect(text.fills[0].color.g).toBeCloseTo(0.39)
+ expect(text.fills[0].color.b).toBeCloseTo(0.92)
+ })
+})
+
describe('fig-import: component set detection', () => {
test('FRAME with VARIANT componentPropDefs becomes COMPONENT_SET', () => {
const changes: NodeChange[] = [
diff --git a/tests/engine/scene-graph.test.ts b/tests/engine/scene-graph.test.ts
index 9c9753bd0..2d9b3aa03 100644
--- a/tests/engine/scene-graph.test.ts
+++ b/tests/engine/scene-graph.test.ts
@@ -282,6 +282,72 @@ describe('Variables', () => {
expect(graph.resolveColorVariable('v1')).toEqual({ r: 0, g: 0, b: 0, a: 1 })
})
+ test('missing active mode falls back to default value', () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'col1',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ graph.addVariable({
+ id: 'v1',
+ name: 'bg',
+ type: 'COLOR',
+ collectionId: 'col1',
+ valuesByMode: { light: { r: 1, g: 1, b: 1, a: 1 } },
+ description: '',
+ hiddenFromPublishing: false
+ })
+
+ graph.setActiveMode('col1', 'dark')
+ expect(graph.resolveColorVariable('v1')).toEqual({ r: 1, g: 1, b: 1, a: 1 })
+ })
+
+ test('explicit alias resolution preserves source mode', () => {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: 'col1',
+ name: 'Theme',
+ modes: [
+ { modeId: 'light', name: 'Light' },
+ { modeId: 'dark', name: 'Dark' }
+ ],
+ defaultModeId: 'light',
+ variableIds: []
+ })
+ graph.addVariable({
+ id: 'base',
+ name: 'base',
+ type: 'COLOR',
+ collectionId: 'col1',
+ valuesByMode: {
+ light: { r: 1, g: 1, b: 1, a: 1 },
+ dark: { r: 0, g: 0, b: 0, a: 1 }
+ },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ graph.addVariable({
+ id: 'alias',
+ name: 'alias',
+ type: 'COLOR',
+ collectionId: 'col1',
+ valuesByMode: {
+ light: { aliasId: 'base' },
+ dark: { aliasId: 'base' }
+ },
+ description: '',
+ hiddenFromPublishing: false
+ })
+
+ expect(graph.resolveVariable('alias', 'dark')).toEqual({ r: 0, g: 0, b: 0, a: 1 })
+ })
+
test('bind and unbind variable to node', () => {
const graph = new SceneGraph()
const node = graph.createNode('RECTANGLE', pageId(graph), { name: 'Rect' })