AI-native design editor. Open-source Figma alternative.
fix(fig): open text bound to a number variable through STRINGIFY (#1122)
Danila Poyarkov8f0238b26e02
diff --git a/changes/1122/fixed.md b/changes/1122/fixed.mdnew file mode 100644index 000000000..3bf47f328--- /dev/null+++ b/changes/1122/fixed.md@@ -0,0 +1 @@+- `.fig` files whose text content is bound to a number or boolean variable, as Figma's UI binds one, open instead of failing with "Unsupported variable expression STRINGIFY". The text follows the variable as Figma writes it, a whole number as an integer and others with two decimals, and saving keeps the binding (#1110).diff --git a/packages/core/tests/io/formats/fig/roundtrip/text-lists.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/lists.test.tssimilarity index 100%rename from packages/core/tests/io/formats/fig/roundtrip/text-lists.test.tsrename to packages/core/tests/io/formats/fig/roundtrip/text/lists.test.tsdiff --git a/packages/core/tests/io/formats/fig/roundtrip/text-styles.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/styles.test.tssimilarity index 100%rename from packages/core/tests/io/formats/fig/roundtrip/text-styles.test.tsrename to packages/core/tests/io/formats/fig/roundtrip/text/styles.test.tsdiff --git a/packages/core/tests/io/formats/fig/roundtrip/text/variables.test.ts b/packages/core/tests/io/formats/fig/roundtrip/text/variables.test.tsnew file mode 100644index 000000000..f2f01f7f3--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/text/variables.test.ts@@ -0,0 +1,46 @@+import { beforeAll, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'+import { parseFigBuffer } from '@open-pencil/fig'+import { reconcileVariableBindings } from '@open-pencil/scene-graph'++beforeAll(async () => {+ await initCodec()+})++// Figma binds a number variable to text content through STRINGIFY (#1110).+test('text bound to a number variable saves as STRINGIFY and reopens following the variable', async () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Sizes')+ const small = graph.createMode(collection.id, 'Small')+ if (!small) throw new Error('Missing mode')+ const size = graph.createVariable('Body', 'FLOAT', collection.id, 16)+ size.valuesByMode[small] = 12.5+ const label = graph.createNode('TEXT', graph.getPages()[0].id, { name: 'Size', text: '16' })+ graph.updateNode(label.id, { boundVariables: { text: size.id } })++ const bytes = await exportFigFile(graph)+ const change = parseFigBuffer(bytes.slice().buffer).nodeChanges.find(+ (node) => node.name === 'Size'+ )+ const [entry] = change?.variableConsumptionMap?.entries ?? []+ expect(entry?.variableField).toBe('TEXT_DATA')+ expect(entry?.variableData?.value?.expressionValue?.expressionFunction).toBe('STRINGIFY')++ const reopened = await parseFigFile(bytes.slice().buffer)+ const copy = [...reopened.getAllNodes()].find((node) => node.name === 'Size')+ if (!copy) throw new Error('Missing text')+ expect(copy.text).toBe('16')+ const variableId = copy.boundVariables.text+ const variable = variableId ? reopened.variables.get(variableId) : undefined+ expect(variable?.name).toBe('Body')++ const page = reopened.getPages()[0]+ const collectionId = variable?.collectionId ?? ''+ const smallMode = reopened.variableCollections+ .get(collectionId)+ ?.modes.find((mode) => mode.name === 'Small')+ reopened.updateNode(page.id, { variableModes: { [collectionId]: smallMode?.modeId ?? '' } })+ reconcileVariableBindings(reopened)+ expect(copy.text).toBe('12.50')+})diff --git a/packages/fig/src/document/bindings/text.ts b/packages/fig/src/document/bindings/text.tsindex e9f6ed9f8..ad995330b 100644--- a/packages/fig/src/document/bindings/text.ts+++ b/packages/fig/src/document/bindings/text.ts@@ -1,7 +1,7 @@-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { variableText, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'/**- * Resolve text bound to a string variable once occurrence hierarchy and modes exist; later+ * Resolve text bound to a variable once occurrence hierarchy and modes exist; later* variable and mode changes re-resolve it through the editor's binding reconcile. Figma stores a bound layer's resolved characters, but an instance override carries the* binding alone, and a literal override of a bound layer is retired rather than applied —* so the binding, not the claim, decides what a bound layer reads.@@ -14,7 +14,7 @@ export function applyDocumentTextBindings(if (node.type !== 'TEXT') continueconst variableId = node.boundVariables.textif (!variableId) continue- const text = graph.resolveStringVariableForNode(node.id, variableId)+ const text = variableText(graph.resolveVariableForNode(node.id, variableId))if (text === undefined || text === node.text) continuegraph.updateNode(node.id, { text })}diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.tsindex 936977580..77a93fcb5 100644--- a/packages/fig/src/node-change/variable/bindings.ts+++ b/packages/fig/src/node-change/variable/bindings.ts@@ -194,6 +194,19 @@ function consumptionEntry(resolvedDataType: variable.type,value: { alias: variableAlias(graph, variableId, ids) }}+ // Text content takes a number or boolean as its text, which Figma writes as STRINGIFY.+ if (variableField === 'TEXT_DATA' && variable.type !== 'STRING') {+ return {+ variableField,+ variableData: {+ dataType: 'EXPRESSION',+ resolvedDataType: 'STRING',+ value: {+ expressionValue: { expressionFunction: 'STRINGIFY', expressionArguments: [alias] }+ }+ }+ }+ }if (variable.type !== 'FLOAT' || (!expression && multiplier === 1))return { variableField, variableData: alias }return {diff --git a/packages/fig/src/node-change/variable/expression.ts b/packages/fig/src/node-change/variable/expression.tsindex 51c0351f9..1acf962f5 100644--- a/packages/fig/src/node-change/variable/expression.ts+++ b/packages/fig/src/node-change/variable/expression.ts@@ -7,7 +7,10 @@ interface LinearValue {}const MAX_EXPRESSION_DEPTH = 64-/** Decode only exactly representable constant × alias expressions, never approximate. */+/**+ * Decode only exactly representable expressions, never approximate: a constant × alias, or an+ * alias Figma turns into text.+ */export function linearVariableExpression(data: VariableDataEntry | undefined,depth = 0@@ -22,12 +25,23 @@ export function linearVariableExpression(return { multiplier: value.floatValue }const expression = value.expressionValueif (!expression) return undefined+ // Figma binds a number or boolean to text content as its text: the variable itself.+ if (expression.expressionFunction === 'STRINGIFY') return stringifiedVariable(expression)if (expression.expressionFunction !== 'MULTIPLY' || !expression.expressionArguments?.length) {throw new Error(`Unsupported variable expression ${expression.expressionFunction}`)}return multiplyLinearValues(expression.expressionArguments, depth)}+function stringifiedVariable(+ expression: NonNullable<NonNullable<VariableDataEntry['value']>['expressionValue']>+): LinearValue {+ const args = expression.expressionArguments ?? []+ const reference = args.length === 1 ? args[0].value?.alias : undefined+ if (!reference) throw new Error('Variable expression STRINGIFY must wrap one alias')+ return { multiplier: 1, reference }+}+function multiplyLinearValues(factors: VariableDataEntry[], depth: number): LinearValue {const result: LinearValue = { multiplier: 1 }for (const argument of factors) {diff --git a/packages/fig/tests/document/bindings/expression.test.ts b/packages/fig/tests/document/bindings/expression.test.tsindex 3213d4922..8faed1181 100644--- a/packages/fig/tests/document/bindings/expression.test.ts+++ b/packages/fig/tests/document/bindings/expression.test.ts@@ -70,3 +70,22 @@ test('nonlinear, unsupported, overflowing, and unbounded expressions fail ratherfor (let index = 0; index < 66; index++) deep = multiply(literal(1), deep)expect(() => linearVariableExpression(deep)).toThrow('maximum depth')})++test('STRINGIFY of one alias is that alias, as Figma binds a number to text content', () => {+ const stringify = (...expressionArguments: VariableDataEntry[]): VariableDataEntry => ({+ dataType: 'EXPRESSION',+ value: { expressionValue: { expressionFunction: 'STRINGIFY', expressionArguments } }+ })+ expect(linearVariableExpression(stringify(alias))).toEqual({+ reference: alias.value?.alias,+ multiplier: 1+ })+ expect(() => linearVariableExpression(stringify(multiply(literal(2), alias)))).toThrow(+ 'STRINGIFY'+ )+ expect(() => linearVariableExpression(stringify(alias, alias))).toThrow('STRINGIFY')+ // Reads as a multiplier of 1, but saving it as a plain binding would drop the product.+ expect(() =>+ linearVariableExpression(stringify(multiply(literal(2), literal(0.5), alias)))+ ).toThrow('STRINGIFY')+})diff --git a/packages/fig/tests/document/bindings/text.test.ts b/packages/fig/tests/document/bindings/text.test.tsindex 349bb7199..4e3b3c7d6 100644--- a/packages/fig/tests/document/bindings/text.test.ts+++ b/packages/fig/tests/document/bindings/text.test.ts@@ -134,3 +134,55 @@ test('an override that only binds a variable supplies the text', () => {if (!instance) throw new Error('Missing instance')expect(graph.getChildren(instance.id)[0].text).toBe('9+')})++test('reads a layer whose text is a number variable, as Figma binds one through STRINGIFY', () => {+ // As the ChatGPT 5 Web UI kit binds its size labels (#1110).+ const changes = [+ { guid: collection, type: 'VARIABLE_SET', variableSetModes: [{ id: mode, name: 'Default' }] },+ {+ guid: variable,+ type: 'VARIABLE',+ variableResolvedType: 'FLOAT',+ variableSetID: { guid: collection },+ variableDataValues: {+ entries: [+ { modeID: mode, variableData: { dataType: 'FLOAT', value: { floatValue: 12.5 } } }+ ]+ }+ },+ { guid: page, type: 'CANVAS' },+ {+ guid: label,+ type: 'TEXT',+ name: 'Size',+ parentIndex: { guid: page, position: '!' },+ textData: { characters: '16' },+ variableConsumptionMap: {+ entries: [+ {+ variableField: 'TEXT_DATA',+ variableData: {+ dataType: 'EXPRESSION',+ resolvedDataType: 'STRING',+ value: {+ expressionValue: {+ expressionFunction: 'STRINGIFY',+ expressionArguments: [+ {+ dataType: 'ALIAS',+ resolvedDataType: 'FLOAT',+ value: { alias: { guid: variable } }+ }+ ]+ }+ }+ }+ }+ ]+ }+ }+ ] as NodeChange[]+ const { graph } = materializeDocument(changes)+ const node = [...graph.getAllNodes()].find((candidate) => candidate.name === 'Size')+ expect([node?.text, node?.boundVariables.text]).toEqual(['12.50', '1:12'])+})diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex f82ef6d41..a46a63bd9 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -2,7 +2,7 @@ import { copyFills, copyStrokes } from '../copy'import type { SceneGraph } from '../index'import { hasInstanceOverride } from '../instances'import type { Color } from '../primitives'-import type { Fill, SceneNode, Stroke, StyleRun } from '../types'+import type { Fill, SceneNode, Stroke, StyleRun, VariableValue } from '../types'import type { VariableModeFallback } from '../variables'import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'export { isNumericVariableBindingField } from './fields'@@ -57,6 +57,41 @@ export function resolvedNumericBindings(return updates}+/**+ * The text a variable bound to text content shows: a string as it is, and a number or boolean+ * as Figma writes it, since Figma lets either be text content.+ */+export function variableText(value: VariableValue | undefined): string | undefined {+ if (typeof value === 'string') return value+ if (typeof value === 'boolean') return String(value)+ if (typeof value === 'number' && Number.isFinite(value)) return numberText(value)+ return undefined+}++const INT32_MIN = -2_147_483_648+const INT32_MAX = 2_147_483_647++/** How near a whole number a value must be for Figma to write it as one. */+const WHOLE_NUMBER_TOLERANCE = 1e-6++/**+ * A number as Figma desktop 126 writes it as text: one within a millionth of a whole number as+ * that integer, clamped to 32 bits, and anything else with two decimals, its sign kept and an+ * exact tie rounded to even, as C's `%.2f` does (0.125 is "0.12", 0.999 is "1.00", -0.004 is+ * "-0.00").+ */+function numberText(value: number): string {+ const whole = Math.round(value)+ if (Math.abs(value - whole) < WHOLE_NUMBER_TOLERANCE)+ return String(Math.min(INT32_MAX, Math.max(INT32_MIN, whole)) || 0)+ const scaled = Math.abs(value) * 100+ const floor = Math.floor(scaled)+ const tie = scaled - floor === 0.5+ const cents = tie ? floor + (floor % 2) : Math.round(scaled)+ const sign = value < 0 ? '-' : ''+ return `${sign}${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`+}+/*** The text and visibility a node's string and boolean bindings resolve to in its mode, for the* fields whose stored value differs. Text or visibility an instance overrides, which typing in a@@ -75,8 +110,8 @@ export function resolvedValueBindings(if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefinedreturn graph.resolveVariableForNode(node.id, variableId, fallback)}- const text = node.type === 'TEXT' ? resolve('text') : undefined- if (typeof text === 'string' && text !== node.text) updates.text = text+ const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined+ if (text !== undefined && text !== node.text) updates.text = textconst visible = resolve('visible')if (typeof visible === 'boolean' && visible !== node.visible) updates.visible = visiblereturn updatesdiff --git a/packages/scene-graph/tests/variable/binding/value-text.test.ts b/packages/scene-graph/tests/variable/binding/value-text.test.tsnew file mode 100644index 000000000..e7d854c47--- /dev/null+++ b/packages/scene-graph/tests/variable/binding/value-text.test.ts@@ -0,0 +1,47 @@+import { expect, test } from 'bun:test'++import { variableText } from '@open-pencil/scene-graph'++// What Figma desktop 126 showed for text bound to each float32 variable value.+const FIGMA_TEXT: Array<[number, string]> = [+ [16, '16'],+ [100000, '100000'],+ [12.5, '12.50'],+ [-0.5, '-0.50'],+ [0.3333333432674408, '0.33'],+ [0.6666666865348816, '0.67'],+ [0.10000000149011612, '0.10'],+ [0.30000001192092896, '0.30'],+ [1234567.875, '1234567.88'],+ [1.0000000116860974e-7, '0'],+ [9.999999974752427e-7, '0'],+ [-9.999999974752427e-7, '0'],+ [1.0999999631167157e-6, '0.00'],+ [-1.9999999494757503e-5, '-0.00'],+ [0.9999989867210388, '1.00'],+ [7.000010013580322, '7.00'],+ [0.9990000128746033, '1.00'],+ [-0.004000000189989805, '-0.00'],+ [0.125, '0.12'],+ [0.13500000536441803, '0.14'],+ [2.005000114440918, '2.01'],+ [99999.9921875, '99999.99'],+ [16777216, '16777216'],+ [1.0000000200408773e21, '2147483647'],+ [-3000000000, '-2147483648'],+ [-7.25, '-7.25']+]++test('a number bound to text reads as Figma writes it', () => {+ expect(FIGMA_TEXT.map(([value]) => variableText(value))).toEqual(+ FIGMA_TEXT.map(([, text]) => text)+ )+})++test('a string reads as it is, and a boolean as true or false', () => {+ expect([variableText('Hello'), variableText(true), variableText(false)]).toEqual([+ 'Hello',+ 'true',+ 'false'+ ])+})