Skip to content

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

fix(fig)!: clear a colour variable binding when the layer is unbound

Danila Poyarkovc48886920dd3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea291ac3f..d16389f7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Breaking changes
+- `encodeNodeChangeWithVariables`, `encodePaintWithVariableBinding`, and `encodeVarint` are removed from `@open-pencil/core` and `@open-pencil/core/kiwi`. They spliced a colour-variable binding into encoded bytes because the field had no schema entry; exports now write `colorVar`, which `fig.kiwi` defines, so nothing needs them. `parseVariableId` is unchanged.
- The desktop app now requires macOS 13 or later; the web app supports Chrome 111, Edge 111, Firefox 128, and Safari 16.4 or later.
- `.fig` reading moved to one reader, so the previous importer's exports are gone. `importNodeChanges` (`@open-pencil/core` and `@open-pencil/core/kiwi`) and `importClipboardNodes` (`@open-pencil/fig/clipboard`) are replaced by `parseFigFile` and `parseFigmaClipboard`; `populateLazyFigImportRoots` and `populateAllLazyFigImportRoots` (`@open-pencil/core/kiwi`) are replaced by `populateFigPage` and `populateAllFigPages` on `@open-pencil/core/io/formats/fig`; `populateAndApplyOverrides` (`@open-pencil/fig/instance-overrides`) is replaced by `interpretInstance` with `materializeInstance`. `FIG_PACKAGE_STATUS` now reads `document-reader`, and `assertFigPackageReady()` is gone, because `@open-pencil/fig` reads an archive into a SceneGraph itself rather than directing callers to Core.
- `sceneNodeToJSX` and `selectionToJSX` in `@open-pencil/core` produce only OpenPencil JSX, and `JSXFormat` and `JSXExportOptions` are removed. For Tailwind JSX, use `sceneNodesToTailwindJSX(graph, nodeIds)` from `@open-pencil/dom-css` or the browser-safe `@open-pencil/dom-css/export`.
@@ -31,6 +32,7 @@
### Fixed
- Keep the ordering keys a `.fig` gave its layers when saving one again, instead of renumbering every sibling, and give every layer on a canvas its own key. Shared styles, variables and the canvas's own layers were numbered in separate passes that each restarted, so Figma saw siblings claiming the same position and ordered them arbitrarily.
+- Clear a `.fig` fill or stroke's colour-variable binding when you unbind it, instead of exporting the variable the layer was imported with and rebinding it on reopen. An emptied binding record is no longer written into the file either.
- Keep an AI reply running in the chat panel, with its Stop button, when you switch pages, instead of detaching the panel from the reply in progress.
- Undo an AI edit while another page is on screen; undo previously did nothing until you returned to the page the AI changed.
- Type `parameterConsumptionMap`, `propRefValue`, and `expressionValue` in the Kiwi `NodeChange` codec, which `fig.kiwi` declares but the TypeScript definitions omitted, so reading them no longer needs a cast.
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index bee8ed2c5..35906104c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -336,8 +336,6 @@ export {
createNodeChangesMessage,
createNodeChange,
parseVariableId,
- encodePaintWithVariableBinding,
- encodeNodeChangeWithVariables,
type NodeChange,
type GUID as KiwiGUID,
type Color as KiwiColor,
diff --git a/packages/core/src/kiwi/index.ts b/packages/core/src/kiwi/index.ts
index 6ee6acf2f..ea65b1944 100644
--- a/packages/core/src/kiwi/index.ts
+++ b/packages/core/src/kiwi/index.ts
@@ -14,8 +14,6 @@ export {
createNodeChangesMessage,
createNodeChange,
parseVariableId,
- encodePaintWithVariableBinding,
- encodeNodeChangeWithVariables,
type NodeChange,
type GUID,
type Color,
diff --git a/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts b/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts
new file mode 100644
index 000000000..a71dd6ebe
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/color-variable-binding.test.ts
@@ -0,0 +1,95 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { inflateSync, unzipSync } from 'fflate'
+
+import { exportFigFile, initCodec, SceneGraph } from '@open-pencil/core'
+import { parseFigKiwiContainer } from '@open-pencil/kiwi/fig/parse'
+import { ByteBuffer, compileSchema, decodeBinarySchema } from '@open-pencil/kiwi/schema-runtime'
+import type { GUID } from '@open-pencil/scene-graph/primitives'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+interface DecodedPaint {
+ colorVar?: {
+ value?: { alias?: { guid?: GUID } }
+ dataType?: string
+ resolvedDataType?: string
+ }
+}
+
+interface DecodedNodeChange {
+ name?: string
+ guid?: GUID
+ type?: string
+ fillPaints?: DecodedPaint[]
+ strokePaints?: DecodedPaint[]
+}
+
+function decodeNodeChanges(fig: Uint8Array): DecodedNodeChange[] {
+ const canvas = expectDefined(unzipSync(fig)['canvas.fig'], 'canvas.fig')
+ const container = expectDefined(parseFigKiwiContainer(canvas), 'kiwi container')
+ const schema = decodeBinarySchema(new ByteBuffer(inflateSync(container.schemaDeflated)))
+ const decode = expectDefined(compileSchema(schema).decodeMessage, 'decodeMessage')
+ const nodeChanges = decode(container.dataRaw).nodeChanges
+ if (!Array.isArray(nodeChanges)) throw new Error('decoded message has no nodeChanges')
+ return nodeChanges as DecodedNodeChange[]
+}
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+describe('Figma export colour variable bindings', () => {
+ test('writes a bound fill or stroke colour as colorVar', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const brand = graph.createVariable('brand', 'COLOR', graph.createCollection('Tokens').id, {
+ r: 0.2,
+ g: 0.4,
+ b: 0.9,
+ a: 1
+ })
+ const color = { r: 0.2, g: 0.4, b: 0.9, a: 1 }
+ graph.createNode('RECTANGLE', page.id, {
+ name: 'Bound',
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }],
+ strokes: [
+ {
+ color,
+ weight: 1,
+ opacity: 1,
+ visible: true,
+ align: 'CENTER',
+ cap: 'NONE',
+ join: 'MITER'
+ }
+ ]
+ })
+ const rect = expectDefined(
+ graph.getChildren(page.id).find((node) => node.name === 'Bound'),
+ 'rectangle'
+ )
+ rect.boundVariables = { 'fills/0/color': brand.id, 'strokes/0/color': brand.id }
+
+ const exported = await exportFigFile(graph)
+ const nodeChanges = decodeNodeChanges(new Uint8Array(exported))
+ const variable = expectDefined(
+ nodeChanges.find((change) => change.type === 'VARIABLE'),
+ 'exported variable'
+ )
+ const bound = expectDefined(
+ nodeChanges.find((change) => change.name === 'Bound'),
+ 'bound rectangle'
+ )
+
+ for (const exportedPaint of [bound.fillPaints?.[0], bound.strokePaints?.[0]]) {
+ expect(exportedPaint?.colorVar).toEqual({
+ value: { alias: { guid: variable.guid } },
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR'
+ })
+ }
+ })
+})
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
index a5e5873fb..8ea06ff44 100644
--- a/packages/fig/src/node-change/export/context.ts
+++ b/packages/fig/src/node-change/export/context.ts
@@ -178,16 +178,19 @@ export function applyColorVariableBinding(
field: string
): Paint {
const variableId = node.boundVariables[field]
- if (!variableId) return paint
+ // An imported paint carries the binding it arrived with. Unbinding the field has to clear
+ // it, or the export hands Figma back a variable the document no longer references.
+ if (!variableId) {
+ if (!paint.colorVar && !paint.colorVariableBinding) return paint
+ const { colorVar: _unbound, colorVariableBinding: _legacy, ...unbound } = paint
+ return unbound
+ }
return {
...paint,
colorVar: {
dataType: 'ALIAS',
resolvedDataType: 'COLOR',
value: { alias: { guid: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId) } }
- },
- colorVariableBinding: {
- variableID: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId)
}
}
}
diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.ts
index 0bcc39e68..437762253 100644
--- a/packages/fig/src/node-change/plugin-data.ts
+++ b/packages/fig/src/node-change/plugin-data.ts
@@ -50,6 +50,12 @@ export function upsertPluginData(
node.pluginData = pluginData
}
+export function removePluginData(node: { pluginData: PluginDataEntry[] }, key: string): void {
+ node.pluginData = node.pluginData.filter(
+ (entry) => !(entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === key)
+ )
+}
+
export function applyExportSettingsPluginData(
node: Pick<SceneNode, 'exportSettings' | 'pluginData' | 'source'>
): void {
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 0159c757b..09980e6a7 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -11,6 +11,7 @@ import { fillToKiwiPaint, safeColor } from './paint'
import { bakeGlyphScale, encodePathCommandsBlob } from './path/commands'
import {
BOUND_VARIABLES_PLUGIN_KEY,
+ removePluginData,
LAYOUT_DIRECTION_PLUGIN_KEY,
TEXT_DIRECTION_PLUGIN_KEY,
upsertPluginData,
@@ -491,15 +492,11 @@ function serializeVariableBindings(
const varGuid = varIdToGuid?.get(varId) ?? stringToGuid(varId)
roundtripBindings[field] = guidToString(varGuid)
}
- if (
- Object.keys(roundtripBindings).length > 0 ||
- node.pluginData.some(
- (entry) =>
- entry.pluginId === OPEN_PENCIL_PLUGIN_ID && entry.key === BOUND_VARIABLES_PLUGIN_KEY
- )
- ) {
+ // An entry the node was imported with is dropped rather than emptied: nothing reads an
+ // empty map, and writing one leaves the record in every file the node is exported to.
+ if (Object.keys(roundtripBindings).length > 0)
upsertPluginData(node, BOUND_VARIABLES_PLUGIN_KEY, JSON.stringify(roundtripBindings))
- }
+ else removePluginData(node, BOUND_VARIABLES_PLUGIN_KEY)
if (entries.length > 0) {
nc.variableConsumptionMap = { entries }
Object.assign(
diff --git a/packages/fig/tests/node-change/export.test.ts b/packages/fig/tests/node-change/export.test.ts
index 917c99ee2..30941a2eb 100644
--- a/packages/fig/tests/node-change/export.test.ts
+++ b/packages/fig/tests/node-change/export.test.ts
@@ -320,4 +320,141 @@ describe('@open-pencil/fig SceneGraph export policy', () => {
expect(changes[0].componentPropDefs?.[0].id).toEqual(changes[1].componentPropRefs?.[0].defID)
})
+
+ test('keeps colorVar bindings on imported nodes with stale raw paints', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const collection = graph.createCollection('Tokens')
+ const brand = graph.createVariable('brand', 'COLOR', collection.id, {
+ r: 0.2,
+ g: 0.4,
+ b: 0.9,
+ a: 1
+ })
+ const color = { r: 0.2, g: 0.4, b: 0.9, a: 1 }
+ const node = graph.createNode('RECTANGLE', page.id, {
+ name: 'ImportedBound',
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ })
+ const current = graph.getNode(node.id)
+ if (!current) throw new Error('Expected rectangle node')
+ // Simulate an imported node whose raw paints predate the binding.
+ graph.updateNode(node.id, {
+ boundVariables: { 'fills/0/color': brand.id },
+ source: {
+ ...current.source,
+ id: '1:2',
+ fig: {
+ ...current.source.fig,
+ rawNodeFields: {
+ ...current.source.fig.rawNodeFields,
+ fillPaints: [
+ {
+ type: 'SOLID',
+ color,
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ]
+ }
+ }
+ }
+ })
+ const updated = graph.getNode(node.id)
+ if (!updated) throw new Error('Expected updated node')
+
+ const [change] = sceneNodeToKiwi(
+ updated,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ []
+ )
+
+ expect(change.fillPaints?.[0]?.colorVar?.resolvedDataType).toBe('COLOR')
+ })
+
+ test('drops a raw colorVar when the imported node is no longer bound', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const color = { r: 0.2, g: 0.4, b: 0.9, a: 1 }
+ const node = graph.createNode('RECTANGLE', page.id, {
+ name: 'ImportedUnbound',
+ width: 40,
+ height: 40,
+ fills: [{ type: 'SOLID', color, opacity: 1, visible: true }]
+ })
+ const current = graph.getNode(node.id)
+ if (!current) throw new Error('Expected rectangle node')
+ // Simulate an imported node that Figma saved with a binding the user has since removed.
+ graph.updateNode(node.id, {
+ boundVariables: {},
+ source: {
+ ...current.source,
+ id: '1:2',
+ fig: {
+ ...current.source.fig,
+ rawNodeFields: {
+ ...current.source.fig.rawNodeFields,
+ fillPaints: [
+ {
+ type: 'SOLID',
+ color,
+ opacity: 1,
+ visible: true,
+ blendMode: 'NORMAL',
+ colorVar: {
+ value: { alias: { guid: { sessionID: 0, localID: 12 } } },
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR'
+ }
+ }
+ ]
+ }
+ }
+ }
+ })
+ const updated = graph.getNode(node.id)
+ if (!updated) throw new Error('Expected updated node')
+
+ const [change] = sceneNodeToKiwi(
+ updated,
+ { sessionID: 1, localID: 1 },
+ 0,
+ { value: 2 },
+ graph,
+ []
+ )
+
+ expect(change.fillPaints?.[0]).toMatchObject({ type: 'SOLID', blendMode: 'NORMAL' })
+ expect(change.fillPaints?.[0]?.colorVar).toBeUndefined()
+ })
+
+ test('drops the OpenPencil bindings entry when an imported node is no longer bound', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const node = graph.createNode('RECTANGLE', page.id, {
+ name: 'ImportedPluginBinding',
+ width: 40,
+ height: 40,
+ boundVariables: {},
+ pluginData: [
+ { pluginId: 'open-pencil', key: 'boundVariables', value: '{"fills/0/color":"0:12"}' },
+ { pluginId: 'other-plugin', key: 'boundVariables', value: 'kept' }
+ ]
+ })
+
+ const [change] = sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])
+
+ const bindingEntries = (change.pluginData ?? []).filter(
+ (entry) => entry.key === 'boundVariables'
+ )
+ expect(bindingEntries).toEqual([
+ { pluginID: 'other-plugin', key: 'boundVariables', value: 'kept' }
+ ])
+ })
})
diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.ts
index 12b8e69b2..280e6c35d 100644
--- a/packages/kiwi/src/fig/codec.ts
+++ b/packages/kiwi/src/fig/codec.ts
@@ -12,11 +12,6 @@ import { compileSchema, encodeBinarySchema } from '../schema-runtime'
import { isZstdCompressed, getKiwiMessageType } from './protocol'
import figmaSchema from './schema'
import type { Color, GUID, Matrix, Vector } from './types'
-import {
- encodeVarint,
- encodePaintWithVariableBinding as encodePaintVariableBinding,
- encodeNodeChangeWithVariables as encodeNodeChangeVariableBindings
-} from './variable-bindings'
interface CompiledSchema {
encodeMessage(message: unknown): Uint8Array
@@ -27,14 +22,6 @@ interface CompiledSchema {
let compiledSchema: CompiledSchema | null = null
-function bytesToHex(bytes: Uint8Array | number[]): string {
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
-}
-
-function hexToBytes(hex: string): Uint8Array {
- return new Uint8Array(hex.match(/.{2}/g)?.map((byte) => Number.parseInt(byte, 16)) ?? [])
-}
-
/**
* Initialize the codec (compiles Kiwi schema)
*/
@@ -82,71 +69,7 @@ export function encodeMessage(message: FigmaMessage): Uint8Array {
if (!compiledSchema) {
throw new Error('Codec not initialized. Call initCodec() first.')
}
-
- // Check if any nodeChange has variable bindings (fill or stroke)
- const hasVariables = message.nodeChanges?.some(
- (nc) =>
- nc.fillPaints?.some((p) => p.colorVariableBinding) ||
- nc.strokePaints?.some((p) => p.colorVariableBinding)
- )
-
- if (!hasVariables) {
- // Standard encoding
- const encoded = compiledSchema.encodeMessage(message)
- return compress(encoded)
- }
-
- // Need custom encoding for variable bindings
- // Strategy: encode each nodeChange separately, then combine
- const messageWithoutNodes = { ...message, nodeChanges: [] }
- const baseEncoded = compiledSchema.encodeMessage(messageWithoutNodes)
- const baseHex = bytesToHex(baseEncoded)
-
- // Encode nodeChanges with variable support
- const nodeChangeBytes: Uint8Array[] = []
- for (const nc of message.nodeChanges || []) {
- const encoded = encodeNodeChangeWithVariables(nc)
- nodeChangeBytes.push(encoded)
- }
-
- // Combine: base message + nodeChanges
- // Message structure: type, sessionID, ackID, reconnectSeqNum, nodeChanges[]
- // nodeChanges is field 5
-
- // Message structure in kiwi:
- // - Field 1 (type): enum MessageType
- // - Field 2 (sessionID): uint
- // - Field 3 (ackID): uint
- // - Field 4 (nodeChanges): NodeChange[] - this is what we need to replace
- // - Field 25 (reconnectSequenceNumber): uint
- //
- // Empty array: "04 00" (field 4, length 0)
- // We need to replace "04 00" with "04 <count> <nodes>"
-
- const emptyArrayPattern = '0400' // field 4, length 0
- const emptyArrayIdx = baseHex.indexOf(emptyArrayPattern)
-
- if (emptyArrayIdx === -1) {
- // Fallback to standard encoding
- const encoded = compiledSchema.encodeMessage(message)
- return compress(encoded)
- }
-
- // Build nodeChanges array with our encoded nodes
- const ncBytes: number[] = [0x04] // field 4
- ncBytes.push(...encodeVarint(nodeChangeBytes.length)) // array length
- for (const ncArr of nodeChangeBytes) {
- ncBytes.push(...Array.from(ncArr))
- }
-
- // Replace "0400" with our nodeChanges
- const beforeArray = baseHex.slice(0, emptyArrayIdx)
- const afterArray = baseHex.slice(emptyArrayIdx + 4) // skip "0400"
-
- const ncHex = bytesToHex(ncBytes)
- const finalHex = beforeArray + ncHex + afterArray
-
- return compress(hexToBytes(finalHex))
+ return compress(compiledSchema.encodeMessage(message))
}
/**
@@ -576,25 +499,4 @@ export function createNodeChange(opts: {
return change
}
-/**
- * Encode a varint (variable-length integer)
- */
-export function encodePaintWithVariableBinding(
- paint: Paint,
- variableSessionID: number,
- variableLocalID: number
-): Uint8Array {
- if (!compiledSchema) {
- throw new Error('Codec not initialized. Call initCodec() first.')
- }
- return encodePaintVariableBinding(compiledSchema, paint, variableSessionID, variableLocalID)
-}
-
export { parseVariableId } from './variable-bindings'
-
-export function encodeNodeChangeWithVariables(nodeChange: NodeChange): Uint8Array {
- if (!compiledSchema) {
- throw new Error('Codec not initialized. Call initCodec() first.')
- }
- return encodeNodeChangeVariableBindings(compiledSchema, nodeChange)
-}
diff --git a/packages/kiwi/src/fig/variable-bindings.ts b/packages/kiwi/src/fig/variable-bindings.ts
index 5d84aa7f4..a78333721 100644
--- a/packages/kiwi/src/fig/variable-bindings.ts
+++ b/packages/kiwi/src/fig/variable-bindings.ts
@@ -1,58 +1,6 @@
import type { GUID } from './types'
-export interface VariableBinding {
- variableID: GUID
-}
-
-export interface PaintWithVariableBinding {
- colorVariableBinding?: VariableBinding
-}
-
-export interface NodeChangeWithVariableBindings {
- fillPaints?: PaintWithVariableBinding[]
- strokePaints?: PaintWithVariableBinding[]
-}
-
-export interface VariableBindingCodec<Paint, NodeChange> {
- encodePaint(paint: Paint): Uint8Array
- encodeNodeChange(nodeChange: NodeChange): Uint8Array
-}
-
-export function encodeVarint(value: number): number[] {
- const bytes: number[] = []
- while (value > 0x7f) {
- bytes.push((value & 0x7f) | 0x80)
- value >>>= 7
- }
- bytes.push(value)
- return bytes
-}
-
-export function encodePaintWithVariableBinding<Paint extends PaintWithVariableBinding>(
- codec: VariableBindingCodec<Omit<Paint, 'colorVariableBinding'>, unknown>,
- paint: Paint,
- variableSessionID: number,
- variableLocalID: number
-): Uint8Array {
- const { colorVariableBinding: _, ...basePaint } = paint
-
- const baseBytes = codec.encodePaint(basePaint)
- const baseArray = Array.from(baseBytes)
-
- if (baseArray[baseArray.length - 1] === 0) {
- baseArray.pop()
- }
-
- baseArray.push(0x15, 0x01)
- baseArray.push(0x04, 0x01)
- baseArray.push(...encodeVarint(variableSessionID))
- baseArray.push(...encodeVarint(variableLocalID))
- baseArray.push(0x00, 0x00, 0x02, 0x03, 0x03, 0x04)
- baseArray.push(0x00, 0x00)
-
- return new Uint8Array(baseArray)
-}
-
+/** Figma's plugin-facing variable id, as `VariableID:<session>:<local>`. */
export function parseVariableId(variableId: string): GUID | null {
const match = variableId.match(/VariableID:(\d+):(\d+)/)
if (!match) return null
@@ -61,100 +9,3 @@ export function parseVariableId(variableId: string): GUID | null {
localID: Number.parseInt(match[2] ?? '0', 10)
}
}
-
-export function encodeNodeChangeWithVariables<NodeChange extends NodeChangeWithVariableBindings>(
- codec: VariableBindingCodec<
- unknown,
- Omit<NodeChange, 'fillPaints' | 'strokePaints'> & {
- fillPaints?: Omit<PaintWithVariableBinding, 'colorVariableBinding'>[]
- strokePaints?: Omit<PaintWithVariableBinding, 'colorVariableBinding'>[]
- }
- >,
- nodeChange: NodeChange
-): Uint8Array {
- const hasFillBinding = nodeChange.fillPaints?.some((paint) => paint.colorVariableBinding)
- const hasStrokeBinding = nodeChange.strokePaints?.some((paint) => paint.colorVariableBinding)
-
- if (!hasFillBinding && !hasStrokeBinding) {
- return codec.encodeNodeChange(nodeChange)
- }
-
- const cleanNodeChange = { ...nodeChange }
- if (cleanNodeChange.fillPaints) {
- cleanNodeChange.fillPaints = cleanNodeChange.fillPaints.map(
- ({ colorVariableBinding: _, ...rest }) => rest
- )
- }
- if (cleanNodeChange.strokePaints) {
- cleanNodeChange.strokePaints = cleanNodeChange.strokePaints.map(
- ({ colorVariableBinding: _, ...rest }) => rest
- )
- }
-
- const baseBytes = codec.encodeNodeChange(cleanNodeChange)
- let hex = Buffer.from(baseBytes).toString('hex')
-
- const fillBinding = nodeChange.fillPaints?.[0]?.colorVariableBinding
- if (hasFillBinding && fillBinding) {
- hex = injectVariableBinding(hex, '2601', fillBinding)
- }
-
- const strokeBinding = nodeChange.strokePaints?.[0]?.colorVariableBinding
- if (hasStrokeBinding && strokeBinding) {
- hex = injectVariableBinding(hex, '2701', strokeBinding)
- }
-
- return hexToBytes(hex)
-}
-
-function injectVariableBinding(hex: string, marker: string, binding: VariableBinding): string {
- const markerIdx = hex.indexOf(marker)
- if (markerIdx === -1) return hex
-
- const visiblePattern = '0401'
- const patternIdx = hex.indexOf(visiblePattern, markerIdx)
- if (patternIdx === -1) return hex
-
- let insertPoint = patternIdx + visiblePattern.length
-
- if (hex.slice(insertPoint, insertPoint + 4) === '0501') {
- insertPoint += 4
- }
-
- const varBytes = [
- 0x15,
- 0x01,
- 0x04,
- 0x01,
- ...encodeVarint(binding.variableID.sessionID),
- ...encodeVarint(binding.variableID.localID),
- 0x00,
- 0x00,
- 0x02,
- 0x03,
- 0x03,
- 0x04,
- 0x00,
- 0x00
- ]
- const varHex = Buffer.from(varBytes).toString('hex')
-
- const beforeVar = hex.slice(0, insertPoint)
- let afterIdx = insertPoint
- if (hex.slice(afterIdx, afterIdx + 2) === '00') {
- afterIdx += 2
- }
- const afterVar = hex.slice(afterIdx)
-
- return beforeVar + varHex + afterVar
-}
-
-function hexToBytes(hex: string): Uint8Array {
- if (hex.length % 2 !== 0) throw new Error('Hex string must have an even length')
-
- const bytes = new Uint8Array(hex.length / 2)
- for (let index = 0; index < bytes.length; index++) {
- bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16)
- }
- return bytes
-}
diff --git a/packages/kiwi/tests/codec.test.ts b/packages/kiwi/tests/codec.test.ts
index 4f229a53c..eb1ee6ab3 100644
--- a/packages/kiwi/tests/codec.test.ts
+++ b/packages/kiwi/tests/codec.test.ts
@@ -62,7 +62,11 @@ describe('Figma Kiwi codec', () => {
{
type: 'SOLID',
color: red,
- colorVariableBinding: { variableID: { sessionID: 7, localID: 9 } }
+ colorVar: {
+ dataType: 'ALIAS',
+ resolvedDataType: 'COLOR',
+ value: { alias: { guid: { sessionID: 7, localID: 9 } } }
+ }
}
]
}
diff --git a/packages/kiwi/tests/variable-bindings.test.ts b/packages/kiwi/tests/variable-bindings.test.ts
index 04cdf8a93..099c6fc07 100644
--- a/packages/kiwi/tests/variable-bindings.test.ts
+++ b/packages/kiwi/tests/variable-bindings.test.ts
@@ -1,54 +1,8 @@
-import { describe, expect, test } from 'bun:test'
+import { expect, test } from 'bun:test'
-import {
- encodeNodeChangeWithVariables,
- encodePaintWithVariableBinding,
- encodeVarint,
- parseVariableId
-} from '../src/fig/variable-bindings'
+import { parseVariableId } from '../src/fig/variable-bindings'
-describe('variable binding codec helpers', () => {
- test('encodes varints', () => {
- expect(encodeVarint(0)).toEqual([0])
- expect(encodeVarint(127)).toEqual([127])
- expect(encodeVarint(128)).toEqual([128, 1])
- expect(encodeVarint(16_384)).toEqual([128, 128, 1])
- })
-
- test('parses Figma variable IDs', () => {
- expect(parseVariableId('VariableID:123:456')).toEqual({ sessionID: 123, localID: 456 })
- expect(parseVariableId('not-a-variable')).toBeNull()
- })
-
- test('appends paint variable binding bytes', () => {
- const codec = {
- encodePaint: () => new Uint8Array([0x01, 0x02, 0x00]),
- encodeNodeChange: () => new Uint8Array()
- }
-
- const encoded = encodePaintWithVariableBinding(
- codec,
- { colorVariableBinding: { variableID: { sessionID: 5, localID: 130 } } },
- 5,
- 130
- )
-
- expect([...encoded]).toEqual([
- 0x01, 0x02, 0x15, 0x01, 0x04, 0x01, 0x05, 0x82, 0x01, 0x00, 0x00, 0x02, 0x03, 0x03, 0x04,
- 0x00, 0x00
- ])
- })
-
- test('injects node change variable bindings after paint markers', () => {
- const codec = {
- encodePaint: () => new Uint8Array(),
- encodeNodeChange: () => new Uint8Array([0x26, 0x01, 0x04, 0x01, 0x00, 0xaa])
- }
-
- const encoded = encodeNodeChangeWithVariables(codec, {
- fillPaints: [{ colorVariableBinding: { variableID: { sessionID: 2, localID: 3 } } }]
- })
-
- expect(Buffer.from(encoded).toString('hex')).toBe('260104011501040102030000020303040000aa')
- })
+test('parses Figma variable IDs', () => {
+ expect(parseVariableId('VariableID:123:456')).toEqual({ sessionID: 123, localID: 456 })
+ expect(parseVariableId('not-a-variable')).toBeNull()
})