Skip to content

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

fix(fig): preserve visibility bindings and instance modes (#1226)

GitttHomie2bae5413050a
diff --git a/changes/1226/fixed.md b/changes/1226/fixed.md
new file mode 100644
index 000000000..03ddec624
--- /dev/null
+++ b/changes/1226/fixed.md
@@ -0,0 +1 @@
+- `.fig` files open when a layer's visibility is bound to a boolean or text variable, and the binding keeps working through page loading, variable edits, instance-specific variable modes, and saving; text shows the layer unless it is empty, "false", "no" or "off", as in Figma.
diff --git a/packages/core/tests/io/formats/fig/roundtrip/boolean-visibility.test.ts b/packages/core/tests/io/formats/fig/roundtrip/boolean-visibility.test.ts
new file mode 100644
index 000000000..4f8a3e1a6
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/boolean-visibility.test.ts
@@ -0,0 +1,180 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { createEditor } from '#core/editor/create'
+import { FigmaAPI } from '#core/figma-api'
+import { exportFigFile, parseFigFile } from '#core/io'
+import { populateFigPage, readerDiagnostics } from '#core/kiwi/fig/session/document-state'
+import { getComponents } from '#core/tools/read/components'
+
+import { parseFigBuffer } from '@open-pencil/fig'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/**
+ * A component whose icon shows by a boolean variable and whose badge shows by a text variable,
+ * placed twice. Figma's layer panel binds visibility to either type; the plugin API, which
+ * `bindVariable` follows, takes booleans only, so the text binding is set directly.
+ */
+async function buttonFile(): Promise<Uint8Array> {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const collection = graph.createCollection('Visibility')
+ const shown = graph.createVariable('visible_1', 'BOOLEAN', collection.id, false)
+ const state = graph.createVariable('state', 'STRING', collection.id, 'off')
+ const button = graph.createNode('COMPONENT', page, { name: 'Button', width: 120, height: 40 })
+ const icon = graph.createNode('FRAME', button.id, { name: 'Icon_2', width: 16, height: 16 })
+ graph.bindVariable(icon.id, 'visible', shown.id)
+ graph.updateNode(icon.id, { visible: false })
+ graph.createNode('FRAME', button.id, {
+ name: 'Badge',
+ width: 8,
+ height: 8,
+ visible: false,
+ boundVariables: { visible: state.id }
+ })
+ graph.createNode('TEXT', button.id, { name: 'Label', text: 'Button' })
+ expectDefined(graph.createInstance(button.id, page))
+ expectDefined(graph.createInstance(button.id, page))
+ return exportFigFile(graph)
+}
+
+function reopen(file: Uint8Array) {
+ return parseFigFile(file.slice().buffer)
+}
+
+function layers(graph: SceneGraph, name: string) {
+ return [...graph.getAllNodes()].filter((node) => node.name === name)
+}
+
+function variable(graph: SceneGraph, name: string) {
+ const found = expectDefined([...graph.variables.values()].find((value) => value.name === name))
+ const collection = expectDefined(graph.variableCollections.get(found.collectionId))
+ return { variable: found, mode: collection.defaultModeId, collection }
+}
+
+test('visibility bound to a boolean or text variable is written as IS_TRUTHY, as Figma does', async () => {
+ const records = parseFigBuffer((await buttonFile()).slice().buffer).nodeChanges
+ const visibility = records.flatMap((record) =>
+ (record.parameterConsumptionMap?.entries ?? [])
+ .filter((entry) => entry.variableField === 'VISIBLE')
+ .map((entry) => ({ name: record.name, data: entry.variableData }))
+ )
+ expect(visibility.map(({ name, data }) => [name, data?.resolvedDataType])).toEqual([
+ ['Icon_2', 'BOOLEAN'],
+ ['Badge', 'BOOLEAN']
+ ])
+ expect(
+ visibility.map(({ data }) => {
+ const expression = data?.value?.expressionValue
+ return [expression?.expressionFunction, expression?.expressionArguments?.[0]?.resolvedDataType]
+ })
+ ).toEqual([
+ ['IS_TRUTHY', 'BOOLEAN'],
+ ['IS_TRUTHY', 'STRING']
+ ])
+})
+
+test('an IS_TRUTHY binding survives lazy page loading and repeated component discovery', async () => {
+ const graph = await parseFigFile((await buttonFile()).slice().buffer, { populate: 'none' })
+ expect(layers(graph, 'Icon_2')).toHaveLength(0)
+ expect(populateFigPage(graph, graph.getPages()[0].id)).toBe(true)
+ const figma = new FigmaAPI(graph)
+ for (let index = 0; index < 2; index++) {
+ expect(await getComponents.execute(figma, { name: 'Button' })).toMatchObject({
+ count: 1,
+ components: [{ name: 'Button', type: 'COMPONENT' }]
+ })
+ }
+ expect(readerDiagnostics(graph)).toEqual([])
+ const shown = variable(graph, 'visible_1').variable
+ const state = variable(graph, 'state').variable
+ expect(layers(graph, 'Icon_2').map((node) => [node.boundVariables.visible, node.visible])).toEqual(
+ Array.from({ length: 3 }, () => [shown.id, false])
+ )
+ expect(layers(graph, 'Badge').map((node) => [node.boundVariables.visible, node.visible])).toEqual(
+ Array.from({ length: 3 }, () => [state.id, false])
+ )
+})
+
+test('boolean visibility updates the definition and both instances, with undo and save/reopen', async () => {
+ let graph = await reopen(await buttonFile())
+ const editor = createEditor({ graph })
+ try {
+ const { variable: shown, mode } = variable(graph, 'visible_1')
+ editor.updateVariableValue(shown.id, mode, true)
+ expect(layers(graph, 'Icon_2').map((node) => node.visible)).toEqual([true, true, true])
+ editor.undo.undo()
+ expect(layers(graph, 'Icon_2').map((node) => node.visible)).toEqual([false, false, false])
+ editor.undo.redo()
+ expect(layers(graph, 'Icon_2').map((node) => node.visible)).toEqual([true, true, true])
+ expect(layers(graph, 'Label').map((node) => node.visible)).toEqual([true, true, true])
+
+ for (let cycle = 0; cycle < 2; cycle++) {
+ graph = await reopen(await exportFigFile(graph))
+ const restored = variable(graph, 'visible_1').variable
+ expect(
+ layers(graph, 'Icon_2').map((node) => [node.boundVariables.visible, node.visible])
+ ).toEqual(Array.from({ length: 3 }, () => [restored.id, true]))
+ }
+ } finally {
+ editor.dispose()
+ }
+})
+
+test('text visibility shows the layer when the text reads as true, as Figma does', async () => {
+ let graph = await reopen(await buttonFile())
+ const editor = createEditor({ graph })
+ try {
+ const { variable: state, mode } = variable(graph, 'state')
+ const badges = () => layers(graph, 'Badge').map((node) => node.visible)
+ for (const [text, visible] of [
+ ['yes', true],
+ [' No ', false],
+ ['0', true],
+ ['', false],
+ [' ', true],
+ ['FALSE', false],
+ ['on', true]
+ ] as const) {
+ editor.updateVariableValue(state.id, mode, text)
+ expect(badges()).toEqual([visible, visible, visible])
+ }
+ graph = await reopen(await exportFigFile(graph))
+ expect(badges()).toEqual([true, true, true])
+ } finally {
+ editor.dispose()
+ }
+})
+
+test('an instance-specific mode survives save/reopen independently of its definition', async () => {
+ const graph = await reopen(await buttonFile())
+ const editor = createEditor({ graph })
+ try {
+ const { variable: shown, collection } = variable(graph, 'visible_1')
+ graph.addMode(collection.id, 'shown', 'Shown')
+ editor.updateVariableValue(shown.id, 'shown', true)
+ const instance = expectDefined([...graph.getAllNodes()].find((node) => node.type === 'INSTANCE'))
+ editor.updateNodeWithUndo(instance.id, { variableModes: { [collection.id]: 'shown' } })
+ const visibility = (target: SceneGraph) =>
+ layers(target, 'Icon_2')
+ .map((node) => node.visible)
+ .sort()
+ expect(visibility(graph)).toEqual([false, false, true])
+ const restored = await reopen(await exportFigFile(graph))
+ expect(visibility(restored)).toEqual([false, false, true])
+ expect(layers(restored, 'Icon_2').every((node) => node.boundVariables.visible)).toBe(true)
+ const restoredEditor = createEditor({ graph: restored })
+ try {
+ const shownIcon = expectDefined(layers(restored, 'Icon_2').find((node) => node.visible))
+ restoredEditor.updateNodeWithUndo(expectDefined(shownIcon.parentId), { variableModes: {} })
+ expect(visibility(restored)).toEqual([false, false, false])
+ const cleared = await reopen(await exportFigFile(restored))
+ expect(visibility(cleared)).toEqual([false, false, false])
+ } finally {
+ restoredEditor.dispose()
+ }
+ } finally {
+ editor.dispose()
+ }
+})
diff --git a/packages/fig/src/document/bindings/text.ts b/packages/fig/src/document/bindings/text.ts
deleted file mode 100644
index ad995330b..000000000
--- a/packages/fig/src/document/bindings/text.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { variableText, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-
-/**
- * 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.
- */
-export function applyDocumentTextBindings(
- graph: SceneGraph,
- materialized: readonly SceneNode[]
-): void {
- for (const node of materialized) {
- if (node.type !== 'TEXT') continue
- const variableId = node.boundVariables.text
- if (!variableId) continue
- const text = variableText(graph.resolveVariableForNode(node.id, variableId))
- if (text === undefined || text === node.text) continue
- graph.updateNode(node.id, { text })
- }
-}
diff --git a/packages/fig/src/document/bindings/values.ts b/packages/fig/src/document/bindings/values.ts
new file mode 100644
index 000000000..abb8d640c
--- /dev/null
+++ b/packages/fig/src/document/bindings/values.ts
@@ -0,0 +1,30 @@
+import {
+ resolvedValueBindings,
+ variableText,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+
+/**
+ * Resolve values once occurrence hierarchy and modes exist. Visibility uses the
+ * shared override-aware resolver. Text bindings supersede literal text overrides:
+ * Figma saves resolved characters on a bound layer, but only the binding on an override.
+ * Later variable and mode changes re-resolve these values through the editor.
+ */
+export function applyDocumentValueBindings(
+ graph: SceneGraph,
+ materialized: readonly SceneNode[]
+): void {
+ for (const node of materialized) {
+ if (node.boundVariables.visible) {
+ const { visible } = resolvedValueBindings(graph, node)
+ if (visible !== undefined) graph.updateNode(node.id, { visible })
+ }
+ if (node.type !== 'TEXT') continue
+ const variableId = node.boundVariables.text
+ if (!variableId) continue
+ const text = variableText(graph.resolveVariableForNode(node.id, variableId))
+ if (text === undefined || text === node.text) continue
+ graph.updateNode(node.id, { text })
+ }
+}
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index 3c8858a4f..da2cb2e51 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -27,7 +27,7 @@ import { figArchiveRecordInfo, type FigArchiveRecordInfo } from '../record-patch
import { applyDocumentLayoutBindings } from './bindings/layout'
import { applyDocumentPaintBindings } from './bindings/paint'
import type { BindingReferenceDiagnostic } from './bindings/references'
-import { applyDocumentTextBindings } from './bindings/text'
+import { applyDocumentValueBindings } from './bindings/values'
import {
checkpointComponent,
restoreComponentCheckpoint,
@@ -483,7 +483,7 @@ function materializeReaderInto(
resolveVariantPropertyValues(graph, materialized)
applyDocumentLayoutBindings(graph, savedSizeNodes, materialized, layoutScales)
applyDocumentPaintBindings(graph, materialized)
- applyDocumentTextBindings(graph, materialized)
+ applyDocumentValueBindings(graph, materialized)
})
return state
}
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index 77967a24d..2cb1d2d5c 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -38,6 +38,7 @@ export const OVERRIDE_FIELDS = {
opacity: { scene: ['opacity'], kind: 'scalar' },
fontSize: { scene: ['fontSize'], kind: 'scalar', length: true },
visible: { scene: ['visible'], kind: 'visible' },
+ variableModeBySetMap: { scene: ['variableModes'], kind: 'node', absent: { entries: [] } },
// Figma claims styled ranges and list lines with the characters (desktop 126).
textData: { scene: ['text', 'styleRuns', 'textParagraphs'], kind: 'text' },
styleIdForText: { scene: ['textStyleId'], kind: 'text-style' },
diff --git a/packages/fig/src/instance-overrides/layers.ts b/packages/fig/src/instance-overrides/layers.ts
index 7a7cc981f..6c38fcf49 100644
--- a/packages/fig/src/instance-overrides/layers.ts
+++ b/packages/fig/src/instance-overrides/layers.ts
@@ -49,6 +49,14 @@ export function ownLayers(
): { structural: StructuralLayer[]; claims: PropertyLayer[] } {
const structural: StructuralLayer[] = []
const claims: PropertyLayer[] = []
+ // A mode on the placed record belongs to this instance, even when it is not repeated
+ // in symbolOverrides. Record that ownership before later component synchronization.
+ if (source.type === 'INSTANCE' && source.symbolData?.symbolID && source.variableModeBySetMap) {
+ claims.push({
+ path: [source.symbolData.symbolID],
+ props: { variableModeBySetMap: source.variableModeBySetMap }
+ })
+ }
for (const override of symbolOverridesOf(source)) {
const { guidPath, overriddenSymbolID: swap, componentPropAssignments, ...props } = override
const path = guidPath?.guids ?? []
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index b1d1d9c90..25ea85191 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -173,6 +173,15 @@ function serializeVariableModes(
return entries.length > 0 ? { entries } : undefined
}
+function applyVariableModes(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ record: KiwiNodeChange
+): void {
+ const modes = serializeVariableModes(node, context.varIdToGuid, context.modeIdToGuid)
+ if (modes) record.variableModeBySetMap = modes
+}
+
const FIGMA_PAYLOAD_VARIABLE_MAP_FIELDS = new Set([
'variableConsumptionMap',
'parameterConsumptionMap'
@@ -993,6 +1002,7 @@ export function overridableNodeFields(
applyNodeStateProps(node, nc)
applyNodeVisualProps({ ...context, fontDigestMap: undefined }, node, nc)
context.serializeLayoutProps(node, nc)
+ applyVariableModes(context, node, nc)
return nc
}
@@ -1049,12 +1059,7 @@ export function sceneNodeToKiwiWithContext(
context.serializeVariableBindings(node, nc, context.graph, context.varIdToGuid)
mergeParameterBindings(nc)
applyRawFigmaNodeFields(context, node, nc)
- const variableModeBySetMap = serializeVariableModes(
- node,
- context.varIdToGuid,
- context.modeIdToGuid
- )
- if (variableModeBySetMap) nc.variableModeBySetMap = variableModeBySetMap
+ applyVariableModes(context, node, nc)
applyExportSettingsPluginData(node)
applyLibrarySourcePluginData(node)
diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.ts
index 77a93fcb5..96641b504 100644
--- a/packages/fig/src/node-change/variable/bindings.ts
+++ b/packages/fig/src/node-change/variable/bindings.ts
@@ -194,15 +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') {
+ // Figma's layer panel tests a variable bound to visibility with IS_TRUTHY, and writes a number
+ // or boolean bound to text content as STRINGIFY.
+ let conversion: 'IS_TRUTHY' | 'STRINGIFY' | undefined
+ if (variableField === 'VISIBLE') conversion = 'IS_TRUTHY'
+ else if (variableField === 'TEXT_DATA' && variable.type !== 'STRING') conversion = 'STRINGIFY'
+ if (conversion) {
return {
variableField,
variableData: {
dataType: 'EXPRESSION',
- resolvedDataType: 'STRING',
+ resolvedDataType: conversion === 'IS_TRUTHY' ? 'BOOLEAN' : 'STRING',
value: {
- expressionValue: { expressionFunction: 'STRINGIFY', expressionArguments: [alias] }
+ expressionValue: { expressionFunction: conversion, expressionArguments: [alias] }
}
}
}
diff --git a/packages/fig/src/node-change/variable/expression.ts b/packages/fig/src/node-change/variable/expression.ts
index 1acf962f5..0574dbaed 100644
--- a/packages/fig/src/node-change/variable/expression.ts
+++ b/packages/fig/src/node-change/variable/expression.ts
@@ -9,7 +9,7 @@ const MAX_EXPRESSION_DEPTH = 64
/**
* Decode only exactly representable expressions, never approximate: a constant × alias, or an
- * alias Figma turns into text.
+ * alias Figma turns into text or tests for visibility.
*/
export function linearVariableExpression(
data: VariableDataEntry | undefined,
@@ -25,20 +25,26 @@ export function linearVariableExpression(
return { multiplier: value.floatValue }
const expression = value.expressionValue
if (!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)
+ // Figma binds a number or boolean to text content as its text, and a boolean or text to
+ // visibility as its truth: the variable itself, converted when the binding resolves.
+ if (
+ expression.expressionFunction === 'STRINGIFY' ||
+ expression.expressionFunction === 'IS_TRUTHY'
+ )
+ return wrappedVariable(expression)
if (expression.expressionFunction !== 'MULTIPLY' || !expression.expressionArguments?.length) {
throw new Error(`Unsupported variable expression ${expression.expressionFunction}`)
}
return multiplyLinearValues(expression.expressionArguments, depth)
}
-function stringifiedVariable(
+function wrappedVariable(
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')
+ const operation = expression.expressionFunction
+ if (!reference) throw new Error(`Variable expression ${operation} must wrap one alias`)
return { multiplier: 1, reference }
}
diff --git a/packages/fig/tests/document/bindings/expression.test.ts b/packages/fig/tests/document/bindings/expression.test.ts
index 8faed1181..c3d442ddd 100644
--- a/packages/fig/tests/document/bindings/expression.test.ts
+++ b/packages/fig/tests/document/bindings/expression.test.ts
@@ -89,3 +89,35 @@ test('STRINGIFY of one alias is that alias, as Figma binds a number to text cont
linearVariableExpression(stringify(multiply(literal(2), literal(0.5), alias)))
).toThrow('STRINGIFY')
})
+
+test('IS_TRUTHY of one alias is that alias, as Figma binds a boolean or text to visibility', () => {
+ const truthy = (...expressionArguments: VariableDataEntry[]): VariableDataEntry => ({
+ dataType: 'EXPRESSION',
+ resolvedDataType: 'BOOLEAN',
+ value: { expressionValue: { expressionFunction: 'IS_TRUTHY', expressionArguments } }
+ })
+ const booleanAlias = { ...alias, resolvedDataType: 'BOOLEAN' }
+ expect(linearVariableExpression(truthy(booleanAlias))).toEqual({
+ reference: alias.value?.alias,
+ multiplier: 1
+ })
+ const props = nodeChangeToProps(
+ {
+ type: 'FRAME',
+ parameterConsumptionMap: {
+ entries: [{ variableField: 'VISIBLE', variableData: truthy(booleanAlias) }]
+ }
+ },
+ []
+ )
+ expect(props.boundVariables).toEqual({ visible: '1:2' })
+ expect(props.variableBindingScales).toEqual({})
+ expect(() => linearVariableExpression(truthy())).toThrow('one alias')
+ expect(() => linearVariableExpression(truthy(booleanAlias, booleanAlias))).toThrow('one alias')
+ expect(() => linearVariableExpression(truthy(multiply(literal(2), alias)))).toThrow('one alias')
+ // The binding resolves through Figma's truthiness, so a text alias reads the same way.
+ expect(linearVariableExpression(truthy({ ...alias, resolvedDataType: 'STRING' }))).toEqual({
+ reference: alias.value?.alias,
+ multiplier: 1
+ })
+})
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 711175eef..71fbe92ce 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -5,7 +5,7 @@ import type { Color } from '../primitives'
import type { Fill, SceneNode, Stroke, StyleRun } from '../types'
import type { VariableModeFallback } from '../variables'
import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
-import { variableText } from './text'
+import { variableText, variableTruthy } from './text'
import { variableValueReferences } from './value'
export { isNumericVariableBindingField } from './fields'
@@ -79,8 +79,9 @@ export function resolvedValueBindings(
}
const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined
if (text !== undefined && text !== node.text) updates.text = text
- const visible = resolve('visible')
- if (typeof visible === 'boolean' && visible !== node.visible) updates.visible = visible
+ // Figma binds visibility to text too, and shows the layer when the text reads as true.
+ const visible = variableTruthy(resolve('visible'))
+ if (visible !== undefined && visible !== node.visible) updates.visible = visible
return updates
}
diff --git a/packages/scene-graph/src/variables/formula/signatures.ts b/packages/scene-graph/src/variables/formula/signatures.ts
index cd872e1af..d9c957166 100644
--- a/packages/scene-graph/src/variables/formula/signatures.ts
+++ b/packages/scene-graph/src/variables/formula/signatures.ts
@@ -4,7 +4,7 @@ import type {
VariableType
} from '@open-pencil/scene-graph'
-import { variableText } from '../text'
+import { variableText, variableTruthy } from '../text'
import { VariableFormulaError } from './tree'
export type FormulaValueType = VariableType
@@ -109,7 +109,7 @@ const SIGNATURES: Record<VariableFormulaOperator, OperatorSignature> = {
arity: 1,
overloads: TEXT_TYPES.map((type) => ({ operands: [type], result: 'BOOLEAN' })),
needs: 'needs a number, text, or true or false',
- apply: ([a]) => isTruthy(a)
+ apply: ([a]) => variableTruthy(a) ?? false
},
TERNARY: {
spellings: ['if'],
@@ -182,17 +182,6 @@ function logic(
}
}
-/** Text Figma reads as false besides the empty string, ignoring case and surrounding spaces. */
-const FALSE_WORDS = new Set(['false', 'no', 'off'])
-
-/** Figma's truth: a number other than 0, and text other than "", "false", "no" or "off". */
-function isTruthy(value: VariableLiteral): boolean {
- if (typeof value === 'boolean') return value
- if (typeof value === 'number') return value !== 0
- if (typeof value === 'string') return value !== '' && !FALSE_WORDS.has(value.trim().toLowerCase())
- return false
-}
-
const OPERATORS = Object.keys(SIGNATURES) as VariableFormulaOperator[]
/** Each spelling written between operands, or before one, and the operator it reads as. */
diff --git a/packages/scene-graph/src/variables/text.ts b/packages/scene-graph/src/variables/text.ts
index 69eab81cb..e5eb92c01 100644
--- a/packages/scene-graph/src/variables/text.ts
+++ b/packages/scene-graph/src/variables/text.ts
@@ -35,3 +35,17 @@ function numberText(input: number): string {
const sign = value < 0 ? '-' : ''
return `${sign}${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, '0')}`
}
+
+/** Text Figma reads as false besides the empty string, ignoring case and surrounding spaces. */
+const FALSE_WORDS = new Set(['false', 'no', 'off'])
+
+/**
+ * Whether Figma reads a value as true, as a formula's `truthy()` and a visibility binding do: a
+ * number other than 0, and text other than "", "false", "no" or "off".
+ */
+export function variableTruthy(value: VariableValue | undefined): boolean | undefined {
+ if (typeof value === 'boolean') return value
+ if (typeof value === 'number') return value !== 0
+ if (typeof value === 'string') return value !== '' && !FALSE_WORDS.has(value.trim().toLowerCase())
+ return undefined
+}