AI-native design editor. Open-source Figma alternative.
feat: text, truthiness and if() in variable formulas (#1315)
Danila Poyarkov3cd86944feae
diff --git a/changes/1284/fixed.md b/changes/1284/fixed.mdindex 6f859436d..1b9c6fc68 100644--- a/changes/1284/fixed.md+++ b/changes/1284/fixed.md@@ -1 +1 @@-- `.fig` files whose variables use expressions OpenPencil cannot evaluate yet, such as `TERNARY` or `VAR_MODE_LOOKUP`, open with the values saved in the file and keep those expressions when saved, instead of failing to open.+- `.fig` files whose variables use expressions OpenPencil cannot evaluate yet, such as `VAR_MODE_LOOKUP`, open with the values saved in the file and keep those expressions when saved, instead of failing to open.diff --git a/changes/1315/added.md b/changes/1315/added.mdnew file mode 100644index 000000000..9cf18224d--- /dev/null+++ b/changes/1315/added.md@@ -0,0 +1 @@+- Variable formulas can use text and colors, join text with `+`, and call `if()`, `text()` and `truthy()`, which Figma files save as `TERNARY`, `STRINGIFY` and `IS_TRUTHY`; text and color variables can hold formulas, and formula completion lists the functions.diff --git a/changes/1315/fixed.md b/changes/1315/fixed.mdnew file mode 100644index 000000000..8ef0ddf07--- /dev/null+++ b/changes/1315/fixed.md@@ -0,0 +1 @@+- Text bound to a number variable shows values just off a whole number, such as 2.0000002, with two decimals, as Figma does.diff --git a/packages/core/src/io/formats/design-tokens/export.ts b/packages/core/src/io/formats/design-tokens/export.tsindex d1753862b..738979dc1 100644--- a/packages/core/src/io/formats/design-tokens/export.ts+++ b/packages/core/src/io/formats/design-tokens/export.ts@@ -101,7 +101,9 @@ function variableToken(context.issues.push({ kind: 'missing-alias', ...where })return undefined}- formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []))+ formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []), {+ type: (id) => context.graph.variables.get(id)?.type+ })$value = literalTokenValue(variable, resolved)} else if (typeof value === 'object' && 'expression' in value) {context.issues.push({ kind: 'unsupported-expression', ...where })diff --git a/packages/core/src/io/formats/fig/export/variables.ts b/packages/core/src/io/formats/fig/export/variables.tsindex df7c34995..d491f66d9 100644--- a/packages/core/src/io/formats/fig/export/variables.ts+++ b/packages/core/src/io/formats/fig/export/variables.ts@@ -13,8 +13,9 @@ import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'import {modesDefaultFirst,isUnsupportedVariableValue,- MAX_FORMULA_DEPTH,- formulaResultType,+ foldFormula,+ formulaValueType,+ inferFormulaType,variableFormulaSchema,variableColorExpressionSchema,type SceneGraph,@@ -206,30 +207,27 @@ function variableValueToKiwi(function formulaToKiwi(graph: SceneGraph,node: VariableFormulaNode,- ids: Map<string, GUID>,- depth = 0+ ids: Map<string, GUID>): VariableDataEntry {- if (depth > MAX_FORMULA_DEPTH) throw new Error('Variable formula is too deeply nested')- if (typeof node === 'number') return variableValueToKiwi(graph, node, 'FLOAT', ids)- if (typeof node === 'boolean') return variableValueToKiwi(graph, node, 'BOOLEAN', ids)- if ('aliasId' in node) {- const type = graph.variables.get(node.aliasId)?.type- if (type !== 'FLOAT' && type !== 'BOOLEAN')- throw new Error('Formula references a missing variable')- return variableValueToKiwi(graph, node, type, ids)+ const typeOf = (id: string) => graph.variables.get(id)?.type+ const known = <T>(type: T | undefined) => {+ if (!type) throw new Error('Formula references a missing variable')+ return type}- return {- dataType: 'EXPRESSION',- resolvedDataType: formulaResultType(node.operator),- value: {- expressionValue: {- expressionFunction: node.operator,- expressionArguments: node.operands.map((operand) =>- formulaToKiwi(graph, operand, ids, depth + 1)- )+ return foldFormula<VariableDataEntry>(node, {+ literal: (value) => variableValueToKiwi(graph, value, formulaValueType(value), ids),+ reference: (id) => variableValueToKiwi(graph, { aliasId: id }, known(typeOf(id)), ids),+ operation: (operation, operands) => ({+ dataType: 'EXPRESSION',+ resolvedDataType: known(inferFormulaType(operation, typeOf)),+ value: {+ expressionValue: {+ expressionFunction: operation.operator,+ expressionArguments: operands+ }}- }- }+ })+ })}/**diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.tsindex 4d4b5de7e..cdbb988de 100644--- a/packages/core/src/openpencil-api/index.ts+++ b/packages/core/src/openpencil-api/index.ts@@ -3,7 +3,8 @@ import {BEHAVIOUR_KINDS,parseVariableFormula,type BehaviourKind,- type BehaviourSpec+ type BehaviourSpec,+ type VariableLiteral} from '@open-pencil/scene-graph'import type { FigmaAPI } from '#core/figma-api/index'@@ -43,16 +44,18 @@ export class OpenPencilAPI {constructor(private readonly figma: FigmaAPI) {}/**- * Set a numeric or Boolean token formula by collection, variable and optional mode names.- * References use `{variable/name}` or `{Collection::variable/name}` and persist by ID; a- * true/false formula can compare numbers, as in `{width} > 600 and not {loading}`.+ * Set a token formula by collection, variable and optional mode names. References use+ * `{variable/name}` or `{Collection::variable/name}` and persist by ID; a true/false formula+ * can compare numbers, as in `{width} > 600 and not {loading}`, and `if()`, `text()` and+ * `truthy()` pick values, write text, and test text or numbers, as in+ * `if({compact}, "Hi", "Hello, " + {name})`.*/setVariableFormula(collectionName: string,variableName: string,source: string,modeName?: string- ): number | boolean {+ ): VariableLiteral {const graph = this.figma.graphconst collections = [...graph.variableCollections.values()].filter((item) => item.name === collectionNamediff --git a/packages/core/tests/io/formats/fig/export/formula.test.ts b/packages/core/tests/io/formats/fig/export/formula.test.tsindex 85869b08b..b0f9f1cd2 100644--- a/packages/core/tests/io/formats/fig/export/formula.test.ts+++ b/packages/core/tests/io/formats/fig/export/formula.test.ts@@ -1,6 +1,7 @@import { expect, test } from 'bun:test'import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'+import { parseFigBuffer } from '@open-pencil/fig'import { FigmaAPI } from '@open-pencil/core/figma-api'import { parseVariableFormula } from '@open-pencil/scene-graph'@@ -68,3 +69,41 @@ test.each([})await expect(exportFigFile(graph)).rejects.toThrow()})++test('text, truthiness and if() formulas survive a .fig save, written with the functions Figma uses', async () => {+ await initCodec()+ const graph = new SceneGraph()+ const collection = graph.createCollection('Tokens')+ const mode = collection.defaultModeId+ graph.createVariable('count', 'FLOAT', collection.id, 3)+ graph.createVariable('name', 'STRING', collection.id, 'Ada')+ graph.createVariable('dark', 'BOOLEAN', collection.id, true)+ graph.createVariable('ink', 'COLOR', collection.id, { r: 0, g: 0, b: 0, a: 1 })+ const formulas = {+ label: ['STRING', 'if({dark}, "Hi, " + {name}, text({count}) + " items")'],+ named: ['BOOLEAN', 'truthy({name})'],+ gap: ['FLOAT', 'if({count} > 2, 16, 8)'],+ surface: ['COLOR', 'if(not {dark}, {ink}, #FFFFFF)']+ } as const+ for (const [name, [type, source]] of Object.entries(formulas)) {+ const variable = graph.createVariable(name, type, collection.id, type === 'FLOAT' ? 0 : '')+ variable.valuesByMode[mode] = parseVariableFormula(graph, variable.id, mode, source).value+ }+ const bytes = await exportFigFile(graph)+ const reopened = await parseFigFile(Uint8Array.from(bytes).buffer)+ const resolved = (name: string) =>+ reopened.resolveVariable(+ [...reopened.variables.values()].find((variable) => variable.name === name)?.id ?? ''+ )+ expect(['label', 'named', 'gap', 'surface'].map(resolved)).toEqual([+ 'Hi, Ada',+ true,+ 16,+ { r: 1, g: 1, b: 1, a: 1 }+ ])+ const functions = parseFigBuffer(Uint8Array.from(bytes).buffer)+ .nodeChanges.filter((node) => node.type === 'VARIABLE')+ .map((node) => node.variableDataValues?.entries?.[0].variableData.value?.expressionValue)+ .flatMap((expression) => (expression ? [expression.expressionFunction] : []))+ expect(functions).toEqual(['TERNARY', 'IS_TRUTHY', 'TERNARY', 'TERNARY'])+})diff --git a/packages/docs/development/architecture.md b/packages/docs/development/architecture.mdindex c4854c201..918015fc9 100644--- a/packages/docs/development/architecture.md+++ b/packages/docs/development/architecture.md@@ -54,11 +54,11 @@ See [Scene Graph Reference](/reference/scene-graph) for internals.### Variable expressions-Scene Graph owns the canonical variable definitions: literals, stable-ID aliases, bounded numeric and Boolean formula trees, and composed colors. Shared Valibot schemas validate expression structure on FIG import, FIG export, and resolution. The resolver owns mode selection, dependency traversal, cycles, and evaluation; draft validation supplies an override without mutating the document. Canvas callers treat resolution failures as unresolved values, while the inspector retains diagnostics. Core applies edits, undo, binding reconciliation, and layout.+Scene Graph owns the canonical variable definitions: literals, stable-ID aliases, bounded formula trees that give numbers, Booleans, text or colors, and composed colors. Shared Valibot schemas validate expression structure on FIG import, FIG export, and resolution. The resolver owns mode selection, dependency traversal, cycles, and evaluation; draft validation supplies an override without mutating the document. Canvas callers treat resolution failures as unresolved values, while the inspector retains diagnostics. Core applies edits, undo, binding reconciliation, and layout.-Formula trees use Figma's `ExpressionFunction` operators, so `.fig` files carry them as they are. Scene Graph parses formula text into a tree, checking operand types as it goes, and prints a tree back with only the parentheses precedence needs; references are `{name}` in text and IDs in the tree. Editors show references as pills and never ask users to type braces.+Formula trees use Figma's `ExpressionFunction` operators and its operand signatures, so `.fig` files carry them as they are: `+` joins text, `STRINGIFY`, `IS_TRUTHY` and `TERNARY` are written `text()`, `truthy()` and `if()`, and number text follows Figma's two-decimal format. An expression the reader cannot hold as a formula, such as one naming a variable the file lacks, is kept as the file wrote it. Scene Graph parses formula text into a tree, checking operand types as it goes, and prints a tree back with only the parentheses precedence needs; references are `{name}` in text and IDs in the tree. Editors show references as pills and never ask users to type braces.-A formula in `valuesByMode` is live document behavior. `expressions[modeId].css` is separate, target-specific CSS that replaces the value in CSS alone, edited in its own field. The token stylesheet writes number formulas as `calc()` over `var()` references, checking that units add and multiply as CSS allows, and declares a formula again in each mode scope that changes a variable it uses. Design-token files hold each mode's result with the formula in `$extensions`. Design JSX preserves node bindings through `designVar`, but does not yet bundle the referenced formula definitions; Boolean formulas have no CSS form.+A formula in `valuesByMode` is live document behavior. `expressions[modeId].css` is separate, target-specific CSS that replaces the value in CSS alone, edited in its own field. The token stylesheet writes number formulas as `calc()` over `var()` references, checking that units add and multiply as CSS allows, and declares a formula again in each mode scope that changes a variable it uses. Design-token files hold each mode's result with the formula in `$extensions`. Design JSX preserves node bindings through `designVar`, but does not yet bundle the referenced formula definitions; formulas that give Booleans, text or colors, or use `if()`, have no CSS form.### Layout Engine (Yoga WASM)diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex 5a63c83a9..4daa28dd8 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -28,11 +28,12 @@ openpencil eval design.fig -c "## Variable formulas-Use `openpencil.setVariableFormula(collectionName, variableName, source, modeName?)` to replace a number or Boolean variable's definition. It validates before changing the document and returns the resolved value. Omitting the mode name edits the collection's default mode.+Use `openpencil.setVariableFormula(collectionName, variableName, source, modeName?)` to replace a variable's definition with a formula. It validates before changing the document and returns the resolved value. Omitting the mode name edits the collection's default mode.```jsopenpencil.setVariableFormula('Spacing', 'large', '{base} * 2')openpencil.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')+openpencil.setVariableFormula('Copy', 'greeting', 'if({compact}, "Hi", "Hello, " + {name})')```References use variable names or `{Collection::variable}` and are stored as stable IDs. Formulas use stored units, so lengths are in pixels. See [Variables](/user-guide/variables) for operators and export limitations.diff --git a/packages/docs/user-guide/variables.md b/packages/docs/user-guide/variables.mdindex 60d592825..d27c2d6eb 100644--- a/packages/docs/user-guide/variables.md+++ b/packages/docs/user-guide/variables.md@@ -48,15 +48,18 @@ On the canvas, a layer shows a mode when you set the layer to it, whatever the c### Formula values-A number variable's value field takes a number, another variable, or a formula. Start typing a variable's name and pick it from the list, or choose **Use a variable**: it appears as a pill, and the field shows what the formula gives, such as `= 16px`. Pills are stored by ID, so renaming a variable keeps the formula working. A true/false variable keeps its switch; choose **Use a formula** in the **⋯** menu beside it to write one.+A number variable's value field takes a number, another variable, or a formula. Start typing a variable's name and pick it from the list, or choose **Use a variable**: it appears as a pill, and the field shows what the formula gives, such as `= 16px`. Pills are stored by ID, so renaming a variable keeps the formula working. True/false, text and color variables keep their switch, text field or color picker; choose **Use a formula** beside one to write a formula instead.- Numbers use `+`, `-`, `*`, `/` and parentheses: `space/base * 4`.-- True/false values use `and`, `or` and `not`, and compare numbers with `==`, `!=`, `<`, `<=`, `>` and `>=`: `viewport > 1024 and not loading`.+- True/false values use `and`, `or` and `not`, and compare numbers with `==`, `!=`, `<`, `<=`, `>` and `>=`: `viewport > 1024 and not loading`. `==` and `!=` also compare text.+- Text is written in double quotes, and `+` joins it with other text, a number or a true/false value: `"Hello, " + name`. `text(count)` writes a number as Figma does, with two decimals unless it is whole: `3`, `1.50`.+- `if(condition, then, otherwise)` picks between two numbers, texts, true/false values or colors: `if(compact, 8, 16)`, `if(dark, gray/900, #FFFFFF)`. Colors are written as `#RRGGBB`, or `#RRGGBBAA` with opacity.+- `truthy(value)` is false for `0`, empty text, and the words `false`, `no` and `off`, and true for anything else, as Figma reads them.- Unknown variables, circular references, mixed types and division by zero are reported when you leave the field, and the saved value stays as it was.The result follows each layer's variable modes and updates bound layers when a variable it uses changes. Formulas use stored units, so lengths are in pixels. The list shows each formula's result; hover the formula icon to read the formula.-In the stylesheet, a number formula is written as `calc()` over the variables it uses, such as `calc(var(--spacing-md) * 2 - var(--spacing-base))`, and is declared again in each mode that changes one of them. A **CSS expression** replaces the value in CSS alone. Design token files hold each formula's result, with the formula under `$extensions`. Formulas survive copy and paste, sharing, undo and `.fig` saves, and Figma color and opacity expressions keep their variable references.+In the stylesheet, a number formula is written as `calc()` over the variables it uses, such as `calc(var(--spacing-md) * 2 - var(--spacing-base))`, and is declared again in each mode that changes one of them. Formulas that use `if()`, text or true/false values have no CSS form and are left out of the stylesheet. A **CSS expression** replaces the value in CSS alone. Design token files hold each formula's result, with the formula under `$extensions`. Formulas survive copy and paste, sharing, undo and `.fig` saves, and Figma color and opacity expressions keep their variable references.Variables are grouped by the folders in their names (`Brand/Primary` appears as *Primary* under *Brand*), with their CSS name and one value per mode.diff --git a/packages/dom-css/src/tokens/formula.ts b/packages/dom-css/src/tokens/formula.tsindex ec505386f..1307ced06 100644--- a/packages/dom-css/src/tokens/formula.ts+++ b/packages/dom-css/src/tokens/formula.ts@@ -1,4 +1,4 @@-import type { Variable, VariableFormulaNode } from '@open-pencil/scene-graph'+import { foldFormula, type Variable, type VariableFormulaNode } from '@open-pencil/scene-graph'import { tokenNumberToCSS, variableUnit } from './values'@@ -53,17 +53,24 @@ export function formulaToCSS(}function convert(node: VariableFormulaNode, context: FormulaContext): Term {- if (typeof node === 'number') return { kind: 'literal', value: node }- if (typeof node === 'boolean') throw new UnsupportedFormulaError('mixes true/false into a number')- if ('aliasId' in node) return reference(node.aliasId, context)- const operands = node.operands.map((operand) => convert(operand, context))- const [a, b] = operands- if (node.operator === 'NEGATE' && operands.length === 1) return negate(a, context)- if (operands.length !== 2 || !isArithmetic(node.operator))- throw new UnsupportedFormulaError('uses logic that CSS has no form for')- if (a.kind === 'literal' && b.kind === 'literal')- return { kind: 'literal', value: fold(node.operator, a.value, b.value) }- return binary(node.operator, a, b, context)+ return foldFormula<Term>(node, {+ literal: (value) => {+ if (typeof value === 'number') return { kind: 'literal', value }+ if (typeof value === 'boolean')+ throw new UnsupportedFormulaError('mixes true/false into a number')+ throw new UnsupportedFormulaError('mixes text or a color into a number')+ },+ reference: (id) => reference(id, context),+ operation: ({ operator }, operands) => {+ const [a, b] = operands+ if (operator === 'NEGATE' && operands.length === 1) return negate(a, context)+ if (operands.length !== 2 || !isArithmetic(operator))+ throw new UnsupportedFormulaError('uses logic that CSS has no form for')+ if (a.kind === 'literal' && b.kind === 'literal')+ return { kind: 'literal', value: fold(operator, a.value, b.value) }+ return binary(operator, a, b, context)+ }+ })}function reference(id: string, { variables, names }: FormulaContext): Term {@@ -71,6 +78,8 @@ function reference(id: string, { variables, names }: FormulaContext): Term {const name = names.get(id)if (!target || !name)throw new UnsupportedFormulaError('refers to a variable that does not exist')+ if (target.type !== 'FLOAT')+ throw new UnsupportedFormulaError('uses a variable that is not a number')const dimension = variableUnit(target) !== 'none'return { kind: 'css', text: `var(--${name})`, precedence: ATOM, dimension }}diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.tsindex 5bac3ba68..25037a16e 100644--- a/packages/fig/src/document/variables.ts+++ b/packages/fig/src/document/variables.ts@@ -6,9 +6,10 @@ import {VARIABLE_FORMULA_OPERATORS,variableFormulaSchema,variableColorExpressionSchema,- formulaResultType,+ inferFormulaType,MAX_FORMULA_DEPTH,type SceneGraph,+ type VariableFormulaNode,type VariableValue,type VariableColorExpression} from '@open-pencil/scene-graph'@@ -75,22 +76,41 @@ function expressionValue()}const operator = parsed.output- const type = formulaResultType(operator)- if (entry.resolvedDataType && entry.resolvedDataType !== type)- throw new Error(`Expression result type does not match ${entry.resolvedDataType}`)const operands = (expression?.expressionArguments ?? []).map((arg) => {- const operand = valueOf(arg, resolve, depth + 1)- return typeof operand === 'object' &&- 'expression' in operand &&- operand.expression === 'FORMULA'- ? operand.value- : operand+ // A formula needs every variable it uses; one the document lacks keeps the file's tree.+ if ((arg.dataType ?? arg.resolvedDataType) === 'ALIAS' && !resolve(arg.value?.alias))+ throw new UnsupportedExpressionError(`${operator} uses a variable this document lacks`)+ return formulaOperand(valueOf(arg, resolve, depth + 1))})- return v.parse(variableFormulaSchema, {+ const node = { operator, operands }+ // Figma writes the result type; a formula of references alone would otherwise leave it open.+ const written = v.safeParse(+ v.picklist(['FLOAT', 'BOOLEAN', 'STRING', 'COLOR']),+ entry.resolvedDataType+ )+ const formula = v.safeParse(variableFormulaSchema, {expression: 'FORMULA',- type,- value: { operator, operands }+ type: written.success ? written.output : inferredType(node),+ value: node})+ // Operands Figma itself would not resolve are kept as written rather than refused.+ if (!formula.success) throw new UnsupportedExpressionError(`Invalid ${operator} expression`)+ return formula.output+}++function inferredType(node: VariableFormulaNode) {+ try {+ return inferFormulaType(node)+ } catch {+ return undefined+ }+}++/** An operand as a formula holds it; a color expression inside a formula is not one it can. */+function formulaOperand(operand: VariableValue): VariableFormulaNode {+ if (typeof operand !== 'object' || !('expression' in operand)) return operand+ if (operand.expression === 'FORMULA') return operand.value+ throw new UnsupportedExpressionError(`Unsupported nested ${operand.expression} expression`)}function colorExpression(diff --git a/packages/fig/tests/document/unsupported-expressions.test.ts b/packages/fig/tests/document/unsupported-expressions.test.tsindex 98effe6a3..d8f528a2e 100644--- a/packages/fig/tests/document/unsupported-expressions.test.ts+++ b/packages/fig/tests/document/unsupported-expressions.test.ts@@ -62,7 +62,8 @@ function expression(}}-const ternary = expression('TERNARY', [+/** A function OpenPencil does not evaluate, over one alias it has and one it does not. */+const keyframe = expression('KEYFRAME', [{ dataType: 'ALIAS', value: { alias: { guid: guid(4) } } },{ dataType: 'FLOAT', value: { floatValue: 8 } },{ dataType: 'ALIAS', value: { alias: { assetRef: { key: 'missing-library-variable' } } } }@@ -74,24 +75,24 @@ function open(source: NodeChange[], options: DocumentAssemblyOptions = {}) {}test('a strict read still rejects an expression it cannot evaluate', () => {- expect(() => materializeDocument(resources(ternary))).toThrow(- 'Unsupported variable expression TERNARY'+ expect(() => materializeDocument(resources(keyframe))).toThrow(+ 'Unsupported variable expression KEYFRAME')})test('a tolerant read keeps the expression with one reference slot per alias', () => {- const graph = open(resources(ternary))+ const graph = open(resources(keyframe))expect(graph.variables.get(VARIABLE)?.valuesByMode[DEFAULT_MODE]).toEqual({expression: 'UNSUPPORTED',- function: 'TERNARY',- value: { ...ternary },+ function: 'KEYFRAME',+ value: { ...keyframe },references: [TARGET, null],modes: []})})test('a kept expression has no value, while the variable’s other modes still resolve', () => {- const graph = open(resources(ternary))+ const graph = open(resources(keyframe))expect(graph.resolveVariable(VARIABLE, DEFAULT_MODE)).toBeUndefined()expect(graph.resolveVariable(VARIABLE, OTHER_MODE)).toBe(42)expect(graph.variableCollections.get(COLLECTION)?.modes).toHaveLength(2)@@ -99,7 +100,7 @@ test('a kept expression has no value, while the variable’s other modes still rtest('each kept expression is reported with its variable and mode', () => {const diagnostics: unknown[] = []- open(resources(ternary), {+ open(resources(keyframe), {onUnsupportedVariableExpression: (diagnostic) => diagnostics.push(diagnostic)})expect(diagnostics).toEqual([@@ -107,7 +108,7 @@ test('each kept expression is reported with its variable and mode', () => {])})-test.each(['STRINGIFY', 'VAR_MODE_LOOKUP', 'IS_TRUTHY', 'RESOLVE_VARIANT', 'KEYFRAME', 'UNKNOWN'])(+test.each(['VAR_MODE_LOOKUP', 'RESOLVE_VARIANT', 'KEYFRAME', 'UNKNOWN'])('%s is kept rather than evaluated',(name) => {const value = open(resources(expression(name))).variables.get(VARIABLE)?.valuesByMode[@@ -119,13 +120,35 @@ test.each(['STRINGIFY', 'VAR_MODE_LOOKUP', 'IS_TRUTHY', 'RESOLVE_VARIANT', 'KEYFtest('a color composed from another expression is kept whole', () => {const nested = {- ...expression('COMPOSE_COLOR', [expression('TERNARY'), { dataType: 'FLOAT', value: {} }]),+ ...expression('COMPOSE_COLOR', [expression('KEYFRAME'), { dataType: 'FLOAT', value: {} }]),resolvedDataType: 'COLOR'}const value = open(resources(nested)).variables.get(VARIABLE)?.valuesByMode[DEFAULT_MODE]expect(value).toMatchObject({ expression: 'UNSUPPORTED', function: 'COMPOSE_COLOR' })})+test.each([+ [+ 'a variable the document lacks',+ expression('TERNARY', [+ { dataType: 'BOOLEAN', value: { boolValue: true } },+ { dataType: 'FLOAT', value: { floatValue: 8 } },+ { dataType: 'ALIAS', value: { alias: { assetRef: { key: 'missing-library-variable' } } } }+ ])+ ],+ [+ 'operands Figma would not resolve',+ expression('TERNARY', [+ { dataType: 'FLOAT', value: { floatValue: 5 } },+ { dataType: 'FLOAT', value: { floatValue: 1 } },+ { dataType: 'FLOAT', value: { floatValue: 2 } }+ ])+ ]+])('a formula with %s is kept as the file wrote it', (_, data) => {+ const value = open(resources(data)).variables.get(VARIABLE)?.valuesByMode[DEFAULT_MODE]+ expect(value).toMatchObject({ expression: 'UNSUPPORTED', function: 'TERNARY' })+})+test('formulas OpenPencil evaluates are not kept opaque', () => {const sum = expression('ADDITION', [{ dataType: 'FLOAT', value: { floatValue: 2 } },@@ -139,7 +162,7 @@ test('a kept expression is written back with fields the codec does not know', ()dataType: 'EXPRESSION',value: {expressionValue: {- expressionFunction: 'TERNARY',+ expressionFunction: 'KEYFRAME',expressionArguments: [{ value: { colorValue: { r: 1, g: 0, b: 0, a: 1, colorSpace: 'DISPLAY_P3' } } },{ value: { alias: { assetRef: { key: 'remote', version: 'v1', futureField: true } } } }diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex eae57ca96..7b0b4a527 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -1,6 +1,7 @@/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */export * from './mutation-impact'export * from './variables/bindings'+export * from './variables/text'export type { VariableModeFallback } from './variables'export { modesDefaultFirst } from './variables'export * from './variables/token'diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex 4bdc1328e..37c67f369 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -848,7 +848,7 @@ export interface VariableColorExpression {}export type VariableLiteral = Color | number | string | boolean-/** Figma's `ExpressionFunction` names for the arithmetic, comparison and logic a formula uses. */+/** Figma's `ExpressionFunction` names for the arithmetic, comparison, logic and text a formula uses. */export const VARIABLE_FORMULA_OPERATORS = ['ADDITION','SUBTRACTION',@@ -863,20 +863,20 @@ export const VARIABLE_FORMULA_OPERATORS = ['GREATER_THAN_OR_EQUAL','AND','OR',- 'NOT'+ 'NOT',+ 'STRINGIFY',+ 'IS_TRUTHY',+ 'TERNARY'] as constexport type VariableFormulaOperator = (typeof VARIABLE_FORMULA_OPERATORS)[number]-export type VariableFormulaNode =- | number- | boolean- | VariableAlias- | {- operator: VariableFormulaOperator- operands: VariableFormulaNode[]- }+export interface VariableFormulaOperation {+ operator: VariableFormulaOperator+ operands: VariableFormulaNode[]+}+export type VariableFormulaNode = VariableLiteral | VariableAlias | VariableFormulaOperationexport interface VariableFormula {expression: 'FORMULA'- type: 'FLOAT' | 'BOOLEAN'+ type: VariableTypevalue: VariableFormulaNode}/**diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.tsindex 0a34eb25d..711175eef 100644--- a/packages/scene-graph/src/variables/bindings.ts+++ b/packages/scene-graph/src/variables/bindings.ts@@ -2,9 +2,10 @@ 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, VariableValue } from '../types'+import type { Fill, SceneNode, Stroke, StyleRun } from '../types'import type { VariableModeFallback } from '../variables'import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'+import { variableText } from './text'import { variableValueReferences } from './value'export { isNumericVariableBindingField } from './fields'@@ -58,41 +59,6 @@ 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 adiff --git a/packages/scene-graph/src/variables/formula/check.ts b/packages/scene-graph/src/variables/formula/check.tsnew file mode 100644index 000000000..d781486e9--- /dev/null+++ b/packages/scene-graph/src/variables/formula/check.ts@@ -0,0 +1,99 @@+import type {+ Color,+ VariableFormulaNode,+ VariableFormulaOperator,+ VariableLiteral+} from '@open-pencil/scene-graph'++import {+ formulaArity,+ formulaNeeds,+ formulaOverloads,+ isFormulaCall,+ type FormulaValueType+} from './signatures'+import { foldFormula, VariableFormulaError } from './tree'++/** The types an operator can give when some operand types are unknown, written as `undefined`. */+export function formulaResultTypes(+ operator: VariableFormulaOperator,+ types: readonly (FormulaValueType | undefined)[]+): FormulaValueType[] {+ const results: FormulaValueType[] = []+ if (types.length !== formulaArity(operator)) return results+ for (const { operands, result } of formulaOverloads(operator)) {+ let fits = true+ for (let index = 0; fits && index < operands.length; index++)+ fits = types[index] === undefined || types[index] === operands[index]+ if (fits && !results.includes(result)) results.push(result)+ }+ return results+}++/** The first overload whose operand types are `types`, checked on every operation evaluated. */+function matchingOverload(operator: VariableFormulaOperator, types: readonly FormulaValueType[]) {+ for (const overload of formulaOverloads(operator)) {+ const { operands } = overload+ let fits = operands.length === types.length+ for (let index = 0; fits && index < operands.length; index++)+ fits = operands[index] === types[index]+ if (fits) return overload+ }+ return undefined+}++/** Check operand types against an operator's signatures; the message says what it needs. */+export function checkFormulaOperands(+ operator: VariableFormulaOperator,+ types: readonly FormulaValueType[]+): FormulaValueType {+ const match = matchingOverload(operator, types)+ if (match) return match.result+ const arity = formulaArity(operator)+ const { name, needs } = formulaNeeds(operator)+ if (types.length !== arity) {+ if (!isFormulaCall(operator))+ throw new VariableFormulaError(`Wrong number of operands for ${operator}`)+ throw new VariableFormulaError(`${name} takes ${arity} ${arity === 1 ? 'value' : 'values'}`)+ }+ throw new VariableFormulaError(`${name} ${needs}`)+}++function isColor(value: object): value is Color {+ const channels: Record<string, unknown> = { ...value }+ return ['r', 'g', 'b', 'a'].every((channel) => Number.isFinite(channels[channel]))+}++/** The type of a value a formula holds or a variable gives. */+export function formulaValueType(value: VariableLiteral): FormulaValueType {+ if (typeof value === 'number') return 'FLOAT'+ if (typeof value === 'boolean') return 'BOOLEAN'+ if (typeof value === 'string') return 'STRING'+ if (isColor(value)) return 'COLOR'+ throw new VariableFormulaError('Formulas use numbers, text, true or false, and colors')+}++/**+ * The type a formula gives, checking each operator's operands on the way. `reference` gives a+ * variable's type, or nothing where it is not known, which any operand type then fits; the+ * result is nothing when it depends on such a reference.+ */+export function inferFormulaType(+ node: VariableFormulaNode,+ reference: (id: string) => FormulaValueType | undefined = () => undefined+): FormulaValueType | undefined {+ return foldFormula<FormulaValueType | undefined>(node, {+ literal: formulaValueType,+ reference,+ operation: ({ operator }, types) => {+ if (types.every((type) => type !== undefined)) return checkFormulaOperands(operator, types)+ const results = formulaResultTypes(operator, types)+ if (!results.length)+ checkFormulaOperands(+ operator,+ types.map((type) => type ?? 'FLOAT')+ )+ return results.length === 1 ? results[0] : undefined+ }+ })+}diff --git a/packages/scene-graph/src/variables/formula/evaluate.ts b/packages/scene-graph/src/variables/formula/evaluate.tsindex d5c8dea4c..91ee83fbf 100644--- a/packages/scene-graph/src/variables/formula/evaluate.ts+++ b/packages/scene-graph/src/variables/formula/evaluate.ts@@ -1,169 +1,33 @@-import type {- VariableFormulaNode,- VariableFormulaOperator,- VariableLiteral-} from '@open-pencil/scene-graph'+import type { VariableFormulaNode, VariableLiteral } from '@open-pencil/scene-graph'-export const MAX_FORMULA_DEPTH = 64-export const MAX_FORMULA_LENGTH = 4096+import { checkFormulaOperands, formulaValueType } from './check'+import { applyFormulaOperator, isFormulaOperator } from './signatures'+import { foldFormula, VariableFormulaError } from './tree'-export class VariableFormulaError extends Error {- override name = 'VariableFormulaError'+/** A finite number, or any other value a formula holds; anything else is refused. */+function checked(value: VariableLiteral): VariableLiteral {+ if (typeof value !== 'number') formulaValueType(value)+ else if (!Number.isFinite(value)) throw new VariableFormulaError('Formula result must be finite')+ return value}-export type FormulaValueType = 'FLOAT' | 'BOOLEAN'--/**- * What each operator takes and gives. `EQUALS` and `NOT_EQUAL` compare two values of either- * type, so long as both are the same; the others take one type only.- */-interface OperatorSignature {- operands: FormulaValueType | 'SAME'- result: FormulaValueType- arity: 1 | 2- /** How the operator is written, and the spelling the parser reads. */- symbol: string- /** Operands are checked against `operands` before this runs. */- apply: (a: number | boolean, b: number | boolean) => number | boolean-}--const SIGNATURES: Record<VariableFormulaOperator, OperatorSignature> = {- ADDITION: arithmetic('+', (a, b) => a + b),- SUBTRACTION: arithmetic('-', (a, b) => a - b),- MULTIPLY: arithmetic('*', (a, b) => a * b),- DIVIDE: arithmetic('/', (a, b) => {- if (b === 0) throw new VariableFormulaError('Cannot divide by zero')- return a / b- }),- NEGATE: { operands: 'FLOAT', result: 'FLOAT', arity: 1, symbol: '-', apply: (a) => -Number(a) },- EQUALS: { operands: 'SAME', result: 'BOOLEAN', arity: 2, symbol: '==', apply: (a, b) => a === b },- NOT_EQUAL: {- operands: 'SAME',- result: 'BOOLEAN',- arity: 2,- symbol: '!=',- apply: (a, b) => a !== b- },- LESS_THAN: comparison('<', (a, b) => a < b),- LESS_THAN_OR_EQUAL: comparison('<=', (a, b) => a <= b),- GREATER_THAN: comparison('>', (a, b) => a > b),- GREATER_THAN_OR_EQUAL: comparison('>=', (a, b) => a >= b),- AND: logic('and', (a, b) => a && b),- OR: logic('or', (a, b) => a || b),- NOT: { operands: 'BOOLEAN', result: 'BOOLEAN', arity: 1, symbol: 'not', apply: (a) => a !== true }-}--function arithmetic(symbol: string, apply: (a: number, b: number) => number): OperatorSignature {- return {- operands: 'FLOAT',- result: 'FLOAT',- arity: 2,- symbol,- apply: (a, b) => apply(Number(a), Number(b))- }-}--function comparison(symbol: string, apply: (a: number, b: number) => boolean): OperatorSignature {- return {- operands: 'FLOAT',- result: 'BOOLEAN',- arity: 2,- symbol,- apply: (a, b) => apply(Number(a), Number(b))- }-}--function logic(symbol: string, apply: (a: boolean, b: boolean) => boolean): OperatorSignature {- return {- operands: 'BOOLEAN',- result: 'BOOLEAN',- arity: 2,- symbol,- apply: (a, b) => apply(a === true, b === true)- }-}--export function formulaArity(operator: VariableFormulaOperator): number {- return SIGNATURES[operator].arity-}--/** The operand type, or `SAME` for equality, which compares either type with itself. */-export function formulaOperandType(operator: VariableFormulaOperator): FormulaValueType | 'SAME' {- return SIGNATURES[operator].operands-}--export function formulaResultType(operator: VariableFormulaOperator): FormulaValueType {- return SIGNATURES[operator].result-}--export function formulaSymbol(operator: VariableFormulaOperator): string {- return SIGNATURES[operator].symbol-}--export function formulaTypeName(type: FormulaValueType) {- return type === 'FLOAT' ? 'numbers' : 'true or false'-}--/** Check operand types against an operator's signature; the message says what it needs. */-export function checkFormulaOperands(- operator: VariableFormulaOperator,- types: readonly FormulaValueType[]-) {- const { operands, arity, symbol } = SIGNATURES[operator]- if (types.length !== arity)- throw new VariableFormulaError(`Wrong number of operands for ${operator}`)- if (operands === 'SAME') {- if (types[0] !== types[1])- throw new VariableFormulaError(`${symbol} compares two numbers or two true/false values`)- return- }- if (types.some((type) => type !== operands))- throw new VariableFormulaError(`${symbol} needs ${formulaTypeName(operands)}`)-}--/** Both sides are evaluated before Boolean logic, so `false and` an invalid operand still fails. */+/** Every operand is evaluated, so `false and` or `if()` with an invalid operand still fails. */export function evaluateVariableFormula(node: VariableFormulaNode,- resolve: (id: string) => VariableLiteral | undefined,- depth = 0-): number | boolean {- if (depth > MAX_FORMULA_DEPTH) throw new VariableFormulaError('Formula is too deeply nested')- let result: VariableLiteral | undefined- if (typeof node !== 'object') result = node- else if ('aliasId' in node) {- result = resolve(node.aliasId)- if (result === undefined)- throw new VariableFormulaError(`Cannot resolve variable ${node.aliasId}`)- } else {- if (!Object.hasOwn(SIGNATURES, node.operator))- throw new VariableFormulaError(`Unknown formula operator ${String(node.operator)}`)- const args = node.operands.map((operand) =>- evaluateVariableFormula(operand, resolve, depth + 1)- )- checkFormulaOperands(- node.operator,- args.map((arg) => (typeof arg === 'number' ? 'FLOAT' : 'BOOLEAN'))- )- const [a, b] = args- result = SIGNATURES[node.operator].apply(a, b)- }- if (typeof result !== 'number' && typeof result !== 'boolean')- throw new VariableFormulaError('Formulas use number and Boolean variables only')- if (typeof result === 'number' && !Number.isFinite(result))- throw new VariableFormulaError('Formula result must be finite')- return result-}--export function mapFormulaReferences(- node: VariableFormulaNode,- map: (id: string) => string,- depth = 0-): VariableFormulaNode {- if (depth > MAX_FORMULA_DEPTH) throw new VariableFormulaError('Formula is too deeply nested')- if (typeof node !== 'object') return node- if ('aliasId' in node) return { aliasId: map(node.aliasId) }- return {- operator: node.operator,- operands: node.operands.map((n) => mapFormulaReferences(n, map, depth + 1))- }+ resolve: (id: string) => VariableLiteral | undefined+): VariableLiteral {+ return foldFormula<VariableLiteral>(node, {+ literal: checked,+ reference: (id) => {+ const value = resolve(id)+ if (value === undefined) throw new VariableFormulaError(`Cannot resolve variable ${id}`)+ return checked(value)+ },+ operation: ({ operator }, operands) => {+ if (!isFormulaOperator(operator))+ throw new VariableFormulaError(`Unknown formula operator ${String(operator)}`)+ checkFormulaOperands(operator, operands.map(formulaValueType))+ return checked(applyFormulaOperator(operator, operands))+ }+ })}diff --git a/packages/scene-graph/src/variables/formula/index.ts b/packages/scene-graph/src/variables/formula/index.tsindex 112a8a276..8cd1ad989 100644--- a/packages/scene-graph/src/variables/formula/index.ts+++ b/packages/scene-graph/src/variables/formula/index.ts@@ -1,9 +1,10 @@-import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'+import type { SceneGraph, VariableLiteral, VariableValue } from '@open-pencil/scene-graph'import { resolveVariableInModes } from '../resolution'-import { VariableFormulaError } from './evaluate'import { parseFormulaSyntax, type FormulaReference } from './parse'import { printFormula, type PrintFormulaOptions } from './print'+import type { FormulaValueType } from './signatures'+import { isFormulaOperation, VariableFormulaError } from './tree'export { printFormula, type PrintFormulaOptions } from './print'export {@@ -14,14 +15,17 @@ export {type FormulaTokenKind} from './tokens'+export { evaluateVariableFormula } from './evaluate'+export { formulaValueType, inferFormulaType } from './check'+export { formulaArity, formulaSymbol, type FormulaValueType } from './signatures'export {- evaluateVariableFormula,- formulaArity,- formulaOperandType,- formulaResultType,+ foldFormula,+ isFormulaOperation,+ isFormulaReference,MAX_FORMULA_DEPTH,- VariableFormulaError-} from './evaluate'+ VariableFormulaError,+ type FormulaFold+} from './tree'function qualifiedName(graph: SceneGraph, id: string) {const variable = graph.variables.get(id)@@ -49,22 +53,17 @@ export function variableFormulaReference(graph: SceneGraph, id: string): string: `{${qualified}}`}-/** The formula's source text, with `{name}` for each reference, as the clipboard and scripts write it. */+/** The formula's source text, with `{name}` for each reference, as the clipboard and scripts write it; text is quoted. */export function formatVariableFormula(graph: SceneGraph,value: VariableValue,options?: PrintFormulaOptions): string {const reference = (id: string) => variableFormulaReference(graph, id)- if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA')- return printFormula(value.value, reference, options)- if (- typeof value === 'number' ||- typeof value === 'boolean' ||- (typeof value === 'object' && 'aliasId' in value)- )- return printFormula(value, reference, options)- return ''+ const typed = { type: (id: string) => graph.variables.get(id)?.type, ...options }+ if (typeof value !== 'object' || !('expression' in value))+ return printFormula(value, reference, typed)+ return value.expression === 'FORMULA' ? printFormula(value.value, reference, typed) : ''}/**@@ -84,37 +83,38 @@ function resolveReference(graph: SceneGraph, collectionId: string, name: string)if (!match) throw new VariableFormulaError(`No variable named ${name}`)if (matches.length !== 1)throw new VariableFormulaError(`More than one variable is named ${name}`)- if (match.type !== 'FLOAT' && match.type !== 'BOOLEAN')- throw new VariableFormulaError(`${match.name} is not a number or true/false variable`)return { id: match.id, type: match.type }}+const TYPE_NAMES: Record<FormulaValueType, string> = {+ FLOAT: 'a number',+ BOOLEAN: 'true or false',+ STRING: 'text',+ COLOR: 'a color'+}+/** Validate a draft without changing the document. Formulas operate on stored units. */export function parseVariableFormula(graph: SceneGraph,variableId: string,modeId: string,source: string-): { value: VariableValue; resolved: number | boolean } {+): { value: VariableValue; resolved: VariableLiteral } {const variable = graph.variables.get(variableId)- if (!variable || (variable.type !== 'FLOAT' && variable.type !== 'BOOLEAN'))- throw new VariableFormulaError('Select a number or Boolean variable')+ if (!variable) throw new VariableFormulaError('Select a variable')const collection = graph.variableCollections.get(variable.collectionId)if (!collection?.modes.some((mode) => mode.modeId === modeId))throw new VariableFormulaError('Unknown variable mode')const { node, type } = parseFormulaSyntax(source, (name) =>resolveReference(graph, variable.collectionId, name))- if (type !== variable.type) {- const kind = (of: string) => (of === 'FLOAT' ? 'a number' : 'true or false')+ if (type !== variable.type)throw new VariableFormulaError(- `This gives ${kind(type)}, but ${variable.name} holds ${kind(variable.type)}`+ `This gives ${TYPE_NAMES[type]}, but ${variable.name} holds ${TYPE_NAMES[variable.type]}`)- }- const value: VariableValue =- typeof node === 'object' && 'operator' in node- ? { expression: 'FORMULA', type: variable.type, value: node }- : node+ const value: VariableValue = isFormulaOperation(node)+ ? { expression: 'FORMULA', type: variable.type, value: node }+ : nodeconst resolved = resolveVariableInModes(graph,variableId,@@ -124,7 +124,5 @@ export function parseVariableFormula(new Map(),new Map([[variableId, value]]))- if (typeof resolved !== 'number' && typeof resolved !== 'boolean')- throw new VariableFormulaError('Expected a number or Boolean result')return { value, resolved }}diff --git a/packages/scene-graph/src/variables/formula/parse.ts b/packages/scene-graph/src/variables/formula/parse.tsindex 036e27dbe..4dbc3975a 100644--- a/packages/scene-graph/src/variables/formula/parse.ts+++ b/packages/scene-graph/src/variables/formula/parse.ts@@ -1,14 +1,20 @@-import type { VariableFormulaNode, VariableFormulaOperator } from '@open-pencil/scene-graph'+import * as v from 'valibot'+import type { Color, VariableFormulaNode, VariableFormulaOperator } from '@open-pencil/scene-graph'+import { tryParseColor } from '@open-pencil/scene-graph/color'++import { checkFormulaOperands } from './check'import {- checkFormulaOperands,- formulaResultType,- MAX_FORMULA_DEPTH,- MAX_FORMULA_LENGTH,- VariableFormulaError,+ binaryFormulaOperator,+ formulaCallOperator,+ formulaPrecedence,+ FORMULA_NON_ASSOCIATIVE,+ FORMULA_PREFIX_PRECEDENCE,+ prefixFormulaOperator,type FormulaValueType-} from './evaluate'+} from './signatures'import { formulaTokenName, formulaTokens, type FormulaToken } from './tokens'+import { MAX_FORMULA_DEPTH, MAX_FORMULA_LENGTH, VariableFormulaError } from './tree'/** A small Pratt parser rather than a library. jsep configures operators globally, which the calc@@ -17,47 +23,13 @@ import { formulaTokenName, formulaTokens, type FormulaToken } from './tokens'* consumer, and its generic error recovery would still need these type and arity messages.*/-/** Binding strength of each binary operator; prefix operators bind tighter than all of them. */-export const FORMULA_PRECEDENCE: Partial<Record<VariableFormulaOperator, number>> = {- OR: 1,- AND: 2,- EQUALS: 3,- NOT_EQUAL: 3,- LESS_THAN: 4,- LESS_THAN_OR_EQUAL: 4,- GREATER_THAN: 4,- GREATER_THAN_OR_EQUAL: 4,- ADDITION: 5,- SUBTRACTION: 5,- MULTIPLY: 6,- DIVIDE: 6-}-export const FORMULA_PREFIX_PRECEDENCE = 7-/** Comparisons do not chain: `a < b < c` reads as a mistake, not as `(a < b) < c`. */-export const FORMULA_NON_ASSOCIATIVE = new Set([3, 4])--const BINARY = new Map<string, VariableFormulaOperator>([- ['+', 'ADDITION'],- ['-', 'SUBTRACTION'],- ['*', 'MULTIPLY'],- ['/', 'DIVIDE'],- ['==', 'EQUALS'],- ['!=', 'NOT_EQUAL'],- ['<', 'LESS_THAN'],- ['<=', 'LESS_THAN_OR_EQUAL'],- ['>', 'GREATER_THAN'],- ['>=', 'GREATER_THAN_OR_EQUAL'],- ['and', 'AND'],- ['&&', 'AND'],- ['or', 'OR'],- ['||', 'OR']-])-/** Check what the editor may leave open while typing, which a saved formula cannot hold. */function checkedTokens(source: string): FormulaToken[] {const tokens = formulaTokens(source)for (const token of tokens) {if (token.kind === 'invalid') throw new VariableFormulaError(`Unexpected ${token.text}`)+ if (token.kind === 'string' && (token.text.length < 2 || !token.text.endsWith('"')))+ throw new VariableFormulaError('A text is missing its closing "')if (token.kind !== 'reference') continueif (!token.text.endsWith('}'))throw new VariableFormulaError('A reference is missing its closing }')@@ -66,6 +38,20 @@ function checkedTokens(source: string): FormulaToken[] {return tokens}+/** A quoted string's text, read with JSON's escapes, as Figma reads it. */+function stringValue(token: FormulaToken): string {+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), v.string()), token.text)+ if (!parsed.success) throw new VariableFormulaError(`Invalid text ${token.text}`)+ return parsed.output+}++/** `#RRGGBB`, or `#RRGGBBAA` with opacity. */+function colorValue(token: FormulaToken): Color {+ const color = tryParseColor(token.text)+ if (!color) throw new VariableFormulaError(`Invalid color ${token.text}`)+ return color+}+export interface FormulaReference {id: stringtype: FormulaValueType@@ -96,14 +82,26 @@ export function parseFormulaSyntax(: ''function operation(operator: VariableFormulaOperator, operands: ParsedFormula[]): ParsedFormula {- checkFormulaOperands(+ const type = checkFormulaOperands(operator,operands.map((operand) => operand.type))- return {- node: { operator, operands: operands.map((operand) => operand.node) },- type: formulaResultType(operator)+ return { node: { operator, operands: operands.map((operand) => operand.node) }, type }+ }++ /** A call's operands, `(a, b)`, after its name. */+ function call(operator: VariableFormulaOperator, name: string, depth: number): ParsedFormula {+ if (symbolAt(tokens.at(index++)) !== '(') throw new VariableFormulaError(`Write ${name}(…)`)+ const operands: ParsedFormula[] = []+ if (symbolAt(peek()) !== ')') {+ operands.push(expression(0, depth + 1))+ while (peek()?.kind === 'comma') {+ index+++ operands.push(expression(0, depth + 1))+ }}+ if (symbolAt(tokens.at(index++)) !== ')') throw new VariableFormulaError('Missing )')+ return operation(operator, operands)}function prefix(depth: number): ParsedFormula {@@ -111,6 +109,10 @@ export function parseFormulaSyntax(const token = tokens.at(index++)if (!token) throw new VariableFormulaError('The formula ends too early')if (token.kind === 'number') return { node: Number(token.text), type: 'FLOAT' }+ if (token.kind === 'string') return { node: stringValue(token), type: 'STRING' }+ if (token.kind === 'color') return { node: colorValue(token), type: 'COLOR' }+ const callee = token.kind === 'function' ? formulaCallOperator(token.text) : undefined+ if (callee) return call(callee, token.text.toLowerCase(), depth)if (token.kind === 'reference' || token.kind === 'name') {const { id, type } = reference(formulaTokenName(token))return { node: { aliasId: id }, type }@@ -126,33 +128,27 @@ export function parseFormulaSyntax(}case '+':return prefix(depth + 1)- case '-': {- const operand = expression(FORMULA_PREFIX_PRECEDENCE, depth + 1)- if (typeof operand.node === 'number') return { node: -operand.node, type: 'FLOAT' }- return operation('NEGATE', [operand])- }- case 'not':- case '!':- return operation('NOT', [expression(FORMULA_PREFIX_PRECEDENCE, depth + 1)])}- throw new VariableFormulaError(`Unexpected ${token.text}`)+ const operator = prefixFormulaOperator(symbolAt(token))+ if (!operator) throw new VariableFormulaError(`Unexpected ${token.text}`)+ const operand = expression(FORMULA_PREFIX_PRECEDENCE, depth + 1)+ // A negative number is a literal, not the negation of one.+ if (operator === 'NEGATE' && typeof operand.node === 'number')+ return { node: -operand.node, type: 'FLOAT' }+ return operation(operator, [operand])}function expression(minimum: number, depth: number): ParsedFormula {let left = prefix(depth)for (;;) {- const operator = BINARY.get(symbolAt(peek()))- const precedence = operator ? (FORMULA_PRECEDENCE[operator] ?? 0) : 0+ const operator = binaryFormulaOperator(symbolAt(peek()))+ const precedence = operator ? (formulaPrecedence(operator) ?? 0) : 0if (!operator || precedence <= minimum) return leftindex++const right = expression(precedence, depth + 1)left = operation(operator, [left, right])- const next = BINARY.get(symbolAt(peek()))- if (- next &&- FORMULA_NON_ASSOCIATIVE.has(precedence) &&- FORMULA_PRECEDENCE[next] === precedence- )+ const next = binaryFormulaOperator(symbolAt(peek()))+ if (next && FORMULA_NON_ASSOCIATIVE.has(precedence) && formulaPrecedence(next) === precedence)throw new VariableFormulaError('Join comparisons with and or or')}}diff --git a/packages/scene-graph/src/variables/formula/print.ts b/packages/scene-graph/src/variables/formula/print.tsindex c0b270e2f..c3c7a29a1 100644--- a/packages/scene-graph/src/variables/formula/print.ts+++ b/packages/scene-graph/src/variables/formula/print.ts@@ -1,13 +1,28 @@-import type { VariableFormulaNode, VariableFormulaOperator } from '@open-pencil/scene-graph'+import type {+ VariableFormulaNode,+ VariableFormulaOperation,+ VariableFormulaOperator+} from '@open-pencil/scene-graph'+import { colorToHex8 } from '@open-pencil/scene-graph/color'-import { formulaArity, formulaSymbol, MAX_FORMULA_DEPTH } from './evaluate'-import { FORMULA_NON_ASSOCIATIVE, FORMULA_PRECEDENCE, FORMULA_PREFIX_PRECEDENCE } from './parse'+import { inferFormulaType } from './check'+import {+ formulaArity,+ formulaPrecedence,+ formulaSymbol,+ FORMULA_NON_ASSOCIATIVE,+ FORMULA_PREFIX_PRECEDENCE,+ isFormulaAssociative,+ isFormulaCall,+ type FormulaValueType+} from './signatures'+import { isFormulaOperation, isFormulaReference, MAX_FORMULA_DEPTH } from './tree'const ATOM = FORMULA_PREFIX_PRECEDENCE + 1-/** Grouping these differently gives the same value, so `a + (b + c)` prints as `a + b + c`. */-const ASSOCIATIVE = new Set<VariableFormulaOperator>(['ADDITION', 'MULTIPLY', 'AND', 'OR'])/** A long formula breaks before these: `or`, `and`, and `+` and `-`. */-const BREAKABLE = new Set([1, 2, 5])+const BREAKABLE = new Set(+ (['OR', 'AND', 'ADDITION'] satisfies VariableFormulaOperator[]).map(formulaPrecedence)+)const CONTINUATION = '\n 'interface Printed {@@ -26,40 +41,59 @@ export interface PrintFormulaOptions {* counts in place of the source spelling.*/display?: (id: string) => string+ /**+ * A referenced variable's type. `+` adds numbers but joins text, so `a + (b + c)` drops its+ * parentheses only when both sides are known to be the same type.+ */+ type?: (id: string) => FormulaValueType | undefined}function nodePrecedence(node: VariableFormulaNode) {- if (typeof node !== 'object' || 'aliasId' in node) return ATOM+ if (!isFormulaOperation(node) || isFormulaCall(node.operator)) return ATOMif (formulaArity(node.operator) === 1) return FORMULA_PREFIX_PRECEDENCE- return FORMULA_PRECEDENCE[node.operator] ?? 0+ return formulaPrecedence(node.operator) ?? 0}-type Operation = Exclude<VariableFormulaNode, number | boolean | { aliasId: string }>+type Operation = VariableFormulaOperationtype Print = (node: VariableFormulaNode, depth: number, breakAt?: number) => Printed+/** Whether `a + (b + c)` may print as `a + b + c` and still read back as the same value. */+type Regroups = (node: Operation) => booleanconst group = ({ text }: Printed) => `(${text})`+function printCall(node: Operation, depth: number, print: Print): Printed {+ const operands = node.operands.map((operand) => print(operand, depth + 1).text)+ return { text: `${formulaSymbol(node.operator)}(${operands.join(', ')})`, precedence: ATOM }+}+function printUnary(node: Operation, depth: number, print: Print): Printed {const [operandNode] = node.operandsconst operand = print(operandNode, depth + 1)const text = operand.precedence < ATOM ? group(operand) : operand.textconst symbol = formulaSymbol(node.operator)+ // A word, such as `not`, needs a space before its operand; a sign, such as `-`, does not.return {- text: node.operator === 'NOT' ? `${symbol} ${text}` : `${symbol}${text}`,+ text: /^\p{L}/u.test(symbol) ? `${symbol} ${text}` : `${symbol}${text}`,precedence: FORMULA_PREFIX_PRECEDENCE}}/** `breakAt` is the precedence of the outermost chain while it is printed on several lines. */-function printBinary(node: Operation, depth: number, print: Print, breakAt?: number): Printed {- const precedence = FORMULA_PRECEDENCE[node.operator] ?? 0+function printBinary(+ node: Operation,+ depth: number,+ print: Print,+ regroups: Regroups,+ breakAt?: number+): Printed {+ const precedence = formulaPrecedence(node.operator) ?? 0const chained = FORMULA_NON_ASSOCIATIVE.has(precedence)const [leftNode, rightNode] = node.operandsconst sameAssociative =- ASSOCIATIVE.has(node.operator) &&- typeof rightNode === 'object' &&- 'operator' in rightNode &&- rightNode.operator === node.operator+ isFormulaAssociative(node.operator) &&+ isFormulaOperation(rightNode) &&+ rightNode.operator === node.operator &&+ (node.operator !== 'ADDITION' || regroups(node))// The chain continues through a left operand and an unparenthesized right one of its level.const breaking = breakAt === precedenceconst left = print(leftNode, depth + 1, breaking ? breakAt : undefined)@@ -80,21 +114,36 @@ function printBinary(node: Operation, depth: number, print: Print, breakAt?: numexport function printFormula(node: VariableFormulaNode,reference: (id: string) => string,- { width, display }: PrintFormulaOptions = {}+ { width, display, type }: PrintFormulaOptions = {}): string {- const line = printLine(node, reference)+ const typeOf = (of: VariableFormulaNode) => {+ try {+ return inferFormulaType(of, type)+ } catch {+ return undefined+ }+ }+ // Text printed without parentheses reads left to right, so `"a" + (1 + 2)` would read as+ // `"a" + 1 + 2`: regroup only when every operand of the chain gives the sum's type.+ const chain = (of: VariableFormulaNode): VariableFormulaNode[] =>+ isFormulaOperation(of) && of.operator === 'ADDITION'+ ? [...chain(of.operands[0]), of.operands[1]]+ : [of]+ const regroups: Regroups = (sum) => {+ const result = typeOf(sum)+ const [left, right] = sum.operands+ return result !== undefined && [left, ...chain(right)].every((of) => typeOf(of) === result)+ }+ const line = printWith(reference, regroups, node)const outer = nodePrecedence(node)- const shown = display ? printLine(node, display) : line+ const shown = display ? printWith(display, regroups, node) : lineif (width === undefined || shown.length <= width || !BREAKABLE.has(outer)) return line- return printWith(reference, node, outer)-}--function printLine(node: VariableFormulaNode, reference: (id: string) => string) {- return printWith(reference, node)+ return printWith(reference, regroups, node, outer)}function printWith(reference: (id: string) => string,+ regroups: Regroups,root: VariableFormulaNode,rootBreak?: number): string {@@ -103,10 +152,16 @@ function printWith(if (typeof node === 'number')return { text: String(node), precedence: node < 0 ? FORMULA_PREFIX_PRECEDENCE : ATOM }if (typeof node === 'boolean') return { text: String(node), precedence: ATOM }- if ('aliasId' in node) return { text: reference(node.aliasId), precedence: ATOM }+ if (typeof node === 'string') return { text: JSON.stringify(node), precedence: ATOM }+ if (!isFormulaOperation(node))+ return {+ text: isFormulaReference(node) ? reference(node.aliasId) : colorToHex8(node),+ precedence: ATOM+ }+ if (isFormulaCall(node.operator)) return printCall(node, depth, print)return formulaArity(node.operator) === 1? printUnary(node, depth, print)- : printBinary(node, depth, print, breakAt)+ : printBinary(node, depth, print, regroups, breakAt)}return print(root, 0, rootBreak).text}diff --git a/packages/scene-graph/src/variables/formula/schema.ts b/packages/scene-graph/src/variables/formula/schema.tsindex dd8a24713..18dfa3051 100644--- a/packages/scene-graph/src/variables/formula/schema.ts+++ b/packages/scene-graph/src/variables/formula/schema.ts@@ -2,72 +2,72 @@ import * as v from 'valibot'import {VARIABLE_FORMULA_OPERATORS,+ type VariableFormula,type VariableFormulaNode} from '@open-pencil/scene-graph/types'import { variableAliasSchema } from '../schema'-import {- MAX_FORMULA_DEPTH,- formulaArity,- formulaOperandType,- formulaResultType,- type FormulaValueType-} from './evaluate'+import { inferFormulaType } from './check'+import { formulaArity } from './signatures'+import { MAX_FORMULA_DEPTH } from './tree'type NodeSchema = v.GenericSchema<unknown, VariableFormulaNode>+const finiteNumber = v.pipe(v.number(), v.finite())+const boolean = v.boolean()+const string = v.string()+const color = v.object({ r: finiteNumber, g: finiteNumber, b: finiteNumber, a: finiteNumber })+/**- * A bounded recursive schema rejects excessively deep data before traversing it. A Boolean- * tree may compare numbers, so its schema reaches into the number tree one level down.+ * A bounded recursive schema rejects excessively deep data before traversing it. Each node's+ * schema is picked by its shape rather than tried in turn, which would build an issue for+ * every literal kind an operation is not.*/-function nodeSchema(type: FormulaValueType, depth: number, cache: Map<string, NodeSchema>) {- const key = `${type}:${depth}`- const cached = cache.get(key)+function nodeSchema(depth: number, cache: Map<number, NodeSchema>): NodeSchema {+ const cached = cache.get(depth)if (cached) return cached- const literal = v.union([- type === 'FLOAT' ? v.pipe(v.number(), v.finite()) : v.boolean(),- variableAliasSchema- ])- const operation = (operandType: FormulaValueType) =>- v.pipe(- v.object({- operator: v.picklist(- VARIABLE_FORMULA_OPERATORS.filter(- (operator) =>- formulaResultType(operator) === type &&- [operandType, 'SAME'].includes(formulaOperandType(operator))+ const operation =+ depth > 0+ ? v.pipe(+ v.object({+ operator: v.picklist(VARIABLE_FORMULA_OPERATORS),+ operands: v.pipe(v.array(nodeSchema(depth - 1, cache)), v.minLength(1), v.maxLength(3))+ }),+ v.check(+ (node) => node.operands.length === formulaArity(node.operator),+ 'Wrong number of operands')- ),- operands: v.pipe(- v.array(nodeSchema(operandType, depth - 1, cache)),- v.minLength(1),- v.maxLength(2))- }),- v.check(- (node) => node.operands.length === formulaArity(node.operator),- 'Wrong number of operands'- )- )- const schema: NodeSchema =- depth === 0- ? literal- : v.union([literal, operation(type), ...(type === 'BOOLEAN' ? [operation('FLOAT')] : [])])- cache.set(key, schema)+ : undefined+ const schema: NodeSchema = v.lazy((input) => {+ if (typeof input === 'number') return finiteNumber+ if (typeof input === 'boolean') return boolean+ if (typeof input === 'string') return string+ if (typeof input === 'object' && input !== null && 'operator' in input && operation)+ return operation+ if (typeof input === 'object' && input !== null && 'aliasId' in input)+ return variableAliasSchema+ return color+ })+ cache.set(depth, schema)return schema}-const cache = new Map<string, NodeSchema>()+/** Operand types are checked where the data shows them; a reference fits any operand. */+function fitsType(formula: VariableFormula) {+ try {+ const type = inferFormulaType(formula.value)+ return type === undefined || type === formula.type+ } catch {+ return false+ }+}-export const variableFormulaSchema = v.variant('type', [+export const variableFormulaSchema: v.GenericSchema<unknown, VariableFormula> = v.pipe(v.object({expression: v.literal('FORMULA'),- type: v.literal('FLOAT'),- value: nodeSchema('FLOAT', MAX_FORMULA_DEPTH, cache)+ type: v.picklist(['FLOAT', 'BOOLEAN', 'STRING', 'COLOR']),+ value: nodeSchema(MAX_FORMULA_DEPTH, new Map())}),- v.object({- expression: v.literal('FORMULA'),- type: v.literal('BOOLEAN'),- value: nodeSchema('BOOLEAN', MAX_FORMULA_DEPTH, cache)- })-])+ v.check(fitsType, 'Formula operands do not fit their operators')+)diff --git a/packages/scene-graph/src/variables/formula/signatures.ts b/packages/scene-graph/src/variables/formula/signatures.tsnew file mode 100644index 000000000..cd872e1af--- /dev/null+++ b/packages/scene-graph/src/variables/formula/signatures.ts@@ -0,0 +1,281 @@+import type {+ VariableFormulaOperator,+ VariableLiteral,+ VariableType+} from '@open-pencil/scene-graph'++import { variableText } from '../text'+import { VariableFormulaError } from './tree'++export type FormulaValueType = VariableType++/** One set of operand types an operator takes, and the type it then gives. */+export interface FormulaOverload {+ operands: readonly FormulaValueType[]+ result: FormulaValueType+}++/**+ * Everything about one operator: how it is written and binds, which operand types it takes as+ * Figma's expression signatures list them, and what it computes. The parser, printer, tokenizer,+ * type checker and evaluator all read this table.+ */+interface OperatorSignature {+ /** How the operator is written; the parser reads every spelling, the printer the first. */+ spellings: readonly [string, ...string[]]+ /** Written as a function call, `name(operands)`, rather than around its operands. */+ call?: boolean+ arity: 1 | 2 | 3+ /** How tightly an operator written around its operands binds; calls need none. */+ precedence?: number+ /** Grouping it differently gives the same value, so `a + (b + c)` may print as `a + b + c`. */+ associative?: boolean+ /** Its operations do not chain: `a < b < c` reads as a mistake, not as `(a < b) < c`. */+ nonAssociative?: boolean+ overloads: readonly FormulaOverload[]+ /** What the error says when no overload takes the operands. */+ needs: string+ /** Operands are checked against `overloads` before this runs. */+ apply: (operands: VariableLiteral[]) => VariableLiteral+}++/** Prefix operators bind tighter than every operator written between two operands. */+export const FORMULA_PREFIX_PRECEDENCE = 7++const FLOAT_FLOAT = ['FLOAT', 'FLOAT'] as const+const TEXT_TYPES = ['FLOAT', 'BOOLEAN', 'STRING'] as const++const SIGNATURES: Record<VariableFormulaOperator, OperatorSignature> = {+ ADDITION: {+ spellings: ['+'],+ arity: 2,+ precedence: 5,+ associative: true,+ overloads: [+ { operands: FLOAT_FLOAT, result: 'FLOAT' },+ { operands: ['STRING', 'STRING'], result: 'STRING' },+ ...(['FLOAT', 'BOOLEAN'] as const).flatMap((other) => [+ { operands: ['STRING', other], result: 'STRING' } as const,+ { operands: [other, 'STRING'], result: 'STRING' } as const+ ])+ ],+ needs: 'adds numbers or joins text',+ apply: ([a, b]) =>+ typeof a === 'number' && typeof b === 'number'+ ? a + b+ : `${variableText(a) ?? ''}${variableText(b) ?? ''}`+ },+ SUBTRACTION: arithmetic('-', 5, (a, b) => a - b),+ MULTIPLY: { ...arithmetic('*', 6, (a, b) => a * b), associative: true },+ DIVIDE: arithmetic('/', 6, (a, b) => {+ if (b === 0) throw new VariableFormulaError('Cannot divide by zero')+ return a / b+ }),+ NEGATE: {+ spellings: ['-'],+ arity: 1,+ precedence: FORMULA_PREFIX_PRECEDENCE,+ overloads: [{ operands: ['FLOAT'], result: 'FLOAT' }],+ needs: 'needs numbers',+ apply: ([a]) => -Number(a)+ },+ EQUALS: equality('==', (a, b) => a === b),+ NOT_EQUAL: equality('!=', (a, b) => a !== b),+ LESS_THAN: comparison('<', (a, b) => a < b),+ LESS_THAN_OR_EQUAL: comparison('<=', (a, b) => a <= b),+ GREATER_THAN: comparison('>', (a, b) => a > b),+ GREATER_THAN_OR_EQUAL: comparison('>=', (a, b) => a >= b),+ AND: logic(['and', '&&'], 2, (a, b) => a && b),+ OR: logic(['or', '||'], 1, (a, b) => a || b),+ NOT: {+ spellings: ['not', '!'],+ arity: 1,+ precedence: FORMULA_PREFIX_PRECEDENCE,+ overloads: [{ operands: ['BOOLEAN'], result: 'BOOLEAN' }],+ needs: 'needs true or false',+ apply: ([a]) => a !== true+ },+ STRINGIFY: {+ spellings: ['text'],+ call: true,+ arity: 1,+ overloads: TEXT_TYPES.map((type) => ({ operands: [type], result: 'STRING' })),+ needs: 'needs a number, text, or true or false',+ apply: ([a]) => variableText(a) ?? ''+ },+ IS_TRUTHY: {+ spellings: ['truthy'],+ call: true,+ arity: 1,+ overloads: TEXT_TYPES.map((type) => ({ operands: [type], result: 'BOOLEAN' })),+ needs: 'needs a number, text, or true or false',+ apply: ([a]) => isTruthy(a)+ },+ TERNARY: {+ spellings: ['if'],+ call: true,+ arity: 3,+ overloads: (['FLOAT', 'BOOLEAN', 'STRING', 'COLOR'] as const).map((type) => ({+ operands: ['BOOLEAN', type, type],+ result: type+ })),+ needs: 'needs true or false, then two values of the same type',+ apply: ([condition, then, otherwise]) => (condition === true ? then : otherwise)+ }+}++function arithmetic(+ symbol: string,+ precedence: number,+ apply: (a: number, b: number) => number+): OperatorSignature {+ return {+ spellings: [symbol],+ arity: 2,+ precedence,+ overloads: [{ operands: FLOAT_FLOAT, result: 'FLOAT' }],+ needs: 'needs numbers',+ apply: ([a, b]) => apply(Number(a), Number(b))+ }+}++function comparison(symbol: string, apply: (a: number, b: number) => boolean): OperatorSignature {+ return {+ spellings: [symbol],+ arity: 2,+ precedence: 4,+ nonAssociative: true,+ overloads: [{ operands: FLOAT_FLOAT, result: 'BOOLEAN' }],+ needs: 'needs numbers',+ apply: ([a, b]) => apply(Number(a), Number(b))+ }+}++function equality(+ symbol: string,+ apply: (a: VariableLiteral, b: VariableLiteral) => boolean+): OperatorSignature {+ return {+ spellings: [symbol],+ arity: 2,+ precedence: 3,+ nonAssociative: true,+ overloads: TEXT_TYPES.map((type) => ({ operands: [type, type], result: 'BOOLEAN' })),+ needs: 'compares two numbers, two texts, or two true or false values',+ apply: ([a, b]) => apply(a, b)+ }+}++function logic(+ spellings: readonly [string, ...string[]],+ precedence: number,+ apply: (a: boolean, b: boolean) => boolean+): OperatorSignature {+ return {+ spellings,+ arity: 2,+ precedence,+ associative: true,+ overloads: [{ operands: ['BOOLEAN', 'BOOLEAN'], result: 'BOOLEAN' }],+ needs: 'needs true or false',+ apply: ([a, b]) => apply(a === true, b === true)+ }+}++/** 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. */+function spellingIndex(written: (signature: OperatorSignature) => boolean) {+ return new Map(+ OPERATORS.filter((operator) => written(SIGNATURES[operator])).flatMap((operator) =>+ SIGNATURES[operator].spellings.map((spelling) => [spelling, operator] as const)+ )+ )+}+const BINARY = spellingIndex(({ arity, call }) => arity === 2 && !call)+const PREFIX = spellingIndex(({ arity, call }) => arity === 1 && !call)+const CALLS = spellingIndex(({ call }) => call === true)++/** Operators spelled as words, such as `and` and `not`, which read as keywords, not names. */+export const FORMULA_KEYWORDS: ReadonlySet<string> = new Set(+ [...BINARY.keys(), ...PREFIX.keys()].filter((spelling) => /^\p{L}+$/u.test(spelling))+)++export function isFormulaOperator(name: string): name is VariableFormulaOperator {+ return Object.hasOwn(SIGNATURES, name)+}++export function formulaArity(operator: VariableFormulaOperator): number {+ return SIGNATURES[operator].arity+}++/** How the operator is printed: its first spelling. */+export function formulaSymbol(operator: VariableFormulaOperator): string {+ return SIGNATURES[operator].spellings[0]+}++export function formulaPrecedence(operator: VariableFormulaOperator): number | undefined {+ return SIGNATURES[operator].precedence+}++/** Written as a function call, such as `if(a, b, c)`, rather than around its operands. */+export function isFormulaCall(operator: VariableFormulaOperator): boolean {+ return SIGNATURES[operator].call === true+}++export function isFormulaAssociative(operator: VariableFormulaOperator): boolean {+ return SIGNATURES[operator].associative === true+}++/** Precedence levels whose operations do not chain, such as the comparisons. */+export const FORMULA_NON_ASSOCIATIVE: ReadonlySet<number> = new Set(+ OPERATORS.flatMap((operator) => {+ const { nonAssociative, precedence } = SIGNATURES[operator]+ return nonAssociative && precedence !== undefined ? [precedence] : []+ })+)++/** The operator written between operands as `spelling`, such as `AND` for `&&`. */+export function binaryFormulaOperator(spelling: string): VariableFormulaOperator | undefined {+ return BINARY.get(spelling.toLowerCase())+}++/** The operator written before an operand as `spelling`, such as `NOT` for `!`. */+export function prefixFormulaOperator(spelling: string): VariableFormulaOperator | undefined {+ return PREFIX.get(spelling.toLowerCase())+}++/** The operator a function call names, such as `TERNARY` for `if`. */+export function formulaCallOperator(name: string): VariableFormulaOperator | undefined {+ return CALLS.get(name.toLowerCase())+}++export function formulaOverloads(operator: VariableFormulaOperator): readonly FormulaOverload[] {+ return SIGNATURES[operator].overloads+}++/** The name an error gives the operator, `if()` for a call, and what it needs. */+export function formulaNeeds(operator: VariableFormulaOperator): { name: string; needs: string } {+ const { call, needs } = SIGNATURES[operator]+ const symbol = formulaSymbol(operator)+ return { name: call ? `${symbol}()` : symbol, needs }+}++/** Compute an operation whose operands have been checked against its overloads. */+export function applyFormulaOperator(+ operator: VariableFormulaOperator,+ operands: VariableLiteral[]+): VariableLiteral {+ return SIGNATURES[operator].apply(operands)+}diff --git a/packages/scene-graph/src/variables/formula/tokens.ts b/packages/scene-graph/src/variables/formula/tokens.tsindex e946ed5fd..d46ecaec2 100644--- a/packages/scene-graph/src/variables/formula/tokens.ts+++ b/packages/scene-graph/src/variables/formula/tokens.ts@@ -1,16 +1,23 @@+import { formulaCallOperator, FORMULA_KEYWORDS } from './signatures'+/**- * What a piece of formula text is. `reference` is a braced `{name}`, which may still be open- * while it is typed; `name` is a bare word that names a variable; `invalid` is any character- * the syntax has no place for.+ * What a piece of formula text is. `reference` is a braced `{name}` and `string` a quoted+ * `"text"`, either of which may still be open while it is typed; `name` is a bare word that+ * names a variable; `function` is a call's name, such as `if`; `invalid` is any character the+ * syntax has no place for.*/export type FormulaTokenKind =| 'number'+ | 'string'+ | 'color'| 'reference'| 'name'+ | 'function'| 'keyword'| 'bool'| 'operator'| 'paren'+ | 'comma'| 'invalid'export interface FormulaToken {@@ -24,7 +31,7 @@ const NUMBER = /(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/yconst WORD = /[\p{L}_$][\p{L}\p{N}_$]*/uyconst OPERATOR = /<=|>=|==|!=|&&|\|\||[-+*/<>!]/yconst SPACE = /\s+/y-const KEYWORDS = new Set(['and', 'or', 'not'])+const COLOR = /#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6})(?![\p{L}\p{N}_$])/uyconst BOOLEANS = new Set(['true', 'false'])function matchAt(pattern: RegExp, source: string, at: number) {@@ -32,6 +39,15 @@ function matchAt(pattern: RegExp, source: string, at: number) {return pattern.exec(source)?.[0]}+/** A string runs to its unescaped closing quote, or, while it is still being typed, to the end. */+function stringEnd(source: string, at: number) {+ for (let index = at + 1; index < source.length; index++) {+ if (source[index] === '\\') index+++ else if (source[index] === '"') return index + 1+ }+ return source.length+}+/** A reference runs to its `}`, or, while it is still being typed, to the next `{` or the end. */function referenceEnd(source: string, at: number) {for (let index = at + 1; index < source.length; index++) {@@ -43,7 +59,8 @@ function referenceEnd(source: string, at: number) {function wordKind(word: string): FormulaTokenKind {const lower = word.toLowerCase()- if (KEYWORDS.has(lower)) return 'keyword'+ if (FORMULA_KEYWORDS.has(lower)) return 'keyword'+ if (formulaCallOperator(lower)) return 'function'return BOOLEANS.has(lower) ? 'bool' : 'name'}@@ -60,7 +77,11 @@ export function readFormulaToken(source: string, at: number): FormulaToken {})const char = source[at] ?? ''if (char === '{') return token('reference', referenceEnd(source, at) - at)+ if (char === '"') return token('string', stringEnd(source, at) - at)if (char === '(' || char === ')') return token('paren', 1)+ if (char === ',') return token('comma', 1)+ const color = matchAt(COLOR, source, at)+ if (color) return token('color', color.length)const number = matchAt(NUMBER, source, at)if (number) return token('number', number.length)const word = matchAt(WORD, source, at)diff --git a/packages/scene-graph/src/variables/formula/tree.ts b/packages/scene-graph/src/variables/formula/tree.tsnew file mode 100644index 000000000..f13319899--- /dev/null+++ b/packages/scene-graph/src/variables/formula/tree.ts@@ -0,0 +1,53 @@+import type {+ VariableAlias,+ VariableFormulaNode,+ VariableFormulaOperation,+ VariableLiteral+} from '@open-pencil/scene-graph'++export const MAX_FORMULA_DEPTH = 64+export const MAX_FORMULA_LENGTH = 4096++export class VariableFormulaError extends Error {+ override name = 'VariableFormulaError'+}++export function isFormulaOperation(node: VariableFormulaNode): node is VariableFormulaOperation {+ return typeof node === 'object' && 'operator' in node+}++export function isFormulaReference(node: VariableFormulaNode): node is VariableAlias {+ return typeof node === 'object' && 'aliasId' in node+}++/** What a fold makes of each kind of node; an operation gets its operands' results. */+export interface FormulaFold<T> {+ literal: (value: VariableLiteral) => T+ reference: (id: string) => T+ operation: (node: VariableFormulaOperation, operands: T[]) => T+}++/**+ * Walk a formula bottom-up, as evaluating, type checking, remapping and writing it to another+ * format all do. A tree deeper than `MAX_FORMULA_DEPTH` is refused rather than walked.+ */+export function foldFormula<T>(node: VariableFormulaNode, fold: FormulaFold<T>, depth = 0): T {+ if (depth > MAX_FORMULA_DEPTH) throw new VariableFormulaError('Formula is too deeply nested')+ if (isFormulaOperation(node))+ return fold.operation(+ node,+ node.operands.map((operand) => foldFormula(operand, fold, depth + 1))+ )+ return isFormulaReference(node) ? fold.reference(node.aliasId) : fold.literal(node)+}++export function mapFormulaReferences(+ node: VariableFormulaNode,+ map: (id: string) => string+): VariableFormulaNode {+ return foldFormula<VariableFormulaNode>(node, {+ literal: (value) => (typeof value === 'object' ? { ...value } : value),+ reference: (id) => ({ aliasId: map(id) }),+ operation: ({ operator }, operands) => ({ operator, operands })+ })+}diff --git a/packages/scene-graph/src/variables/resolution.ts b/packages/scene-graph/src/variables/resolution.tsindex 36fa84898..a250ae27c 100644--- a/packages/scene-graph/src/variables/resolution.ts+++ b/packages/scene-graph/src/variables/resolution.ts@@ -1,7 +1,7 @@import type { SceneGraph } from '../index'import type { Color } from '../primitives'import type { Variable, VariableLiteral, VariableValue } from '../types'-import { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/evaluate'+import { MAX_FORMULA_DEPTH, VariableFormulaError } from './formula/tree'import { resolveVariableValue } from './value'export function getActiveModeId(graph: SceneGraph, collectionId: string): string {diff --git a/packages/scene-graph/src/variables/text.ts b/packages/scene-graph/src/variables/text.tsnew file mode 100644index 000000000..69eab81cb--- /dev/null+++ b/packages/scene-graph/src/variables/text.ts@@ -0,0 +1,37 @@+import type { VariableValue } from '../types'++/**+ * 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. A formula's `text()` and a `+`+ * that joins text write numbers the same way.+ */+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 zero a value must be for Figma to write it as 0. */+const ZERO_TOLERANCE = 1e-6++/**+ * A number as Figma writes it as text, read at the 32-bit precision Figma stores: within a+ * millionth of zero as 0, 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", 2.0000002 is "2.00").+ */+function numberText(input: number): string {+ const value = Math.fround(input)+ if (Math.abs(value) < ZERO_TOLERANCE) return '0'+ if (Number.isInteger(value)) return String(Math.min(INT32_MAX, Math.max(INT32_MIN, value)))+ 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')}`+}diff --git a/packages/scene-graph/src/variables/value.ts b/packages/scene-graph/src/variables/value.tsindex ecce12bf8..93bcc0424 100644--- a/packages/scene-graph/src/variables/value.ts+++ b/packages/scene-graph/src/variables/value.ts@@ -2,11 +2,9 @@ import { compact } from 'es-toolkit/array'import * as v from 'valibot'import type { VariableLiteral, VariableValue, VariableUnsupportedExpression } from '../types'-import {- evaluateVariableFormula,- mapFormulaReferences,- VariableFormulaError-} from './formula/evaluate'+import { formulaValueType } from './formula/check'+import { evaluateVariableFormula } from './formula/evaluate'+import { mapFormulaReferences, VariableFormulaError } from './formula/tree'import { variableColorExpressionSchema } from './schema'export function isUnsupportedVariableValue(@@ -72,7 +70,7 @@ export function resolveVariableValue(// Evaluation checks every node it visits, so drawing never walks the tree twice; files are// checked against the full schema where they are read.const result = evaluateVariableFormula(value.value, resolve)- if (typeof result !== (value.type === 'FLOAT' ? 'number' : 'boolean'))+ if (formulaValueType(result) !== value.type)throw new VariableFormulaError('Wrong formula result type')return result}diff --git a/packages/scene-graph/tests/variable/binding/value-text.test.ts b/packages/scene-graph/tests/variable/binding/value-text.test.tsindex e7d854c47..a3a0140c5 100644--- a/packages/scene-graph/tests/variable/binding/value-text.test.ts+++ b/packages/scene-graph/tests/variable/binding/value-text.test.ts@@ -29,7 +29,11 @@ const FIGMA_TEXT: Array<[number, string]> = [[16777216, '16777216'],[1.0000000200408773e21, '2147483647'],[-3000000000, '-2147483648'],- [-7.25, '-7.25']+ [-7.25, '-7.25'],+ // Measured on 2026-10-20: only values near zero round to a whole number.+ [2.000000238418579, '2.00'],+ [2.999999046325684, '3.00'],+ [7.000004291534424, '7.00']]test('a number bound to text reads as Figma writes it', () => {diff --git a/packages/scene-graph/tests/variables/functions.test.ts b/packages/scene-graph/tests/variables/functions.test.tsnew file mode 100644index 000000000..4eae8f075--- /dev/null+++ b/packages/scene-graph/tests/variables/functions.test.ts@@ -0,0 +1,158 @@+import { expect, test } from 'bun:test'++import * as v from 'valibot'++import {+ SceneGraph,+ formatVariableFormula,+ formulaTokens,+ parseVariableFormula,+ variableFormulaSchema,+ type VariableType+} from '@open-pencil/scene-graph'++/** A variable of each type to refer to, and one of `type` whose formula is parsed. */+function setup(type: VariableType) {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Tokens')+ const mode = collection.defaultModeId+ graph.createVariable('count', 'FLOAT', collection.id, 3)+ graph.createVariable('width', 'FLOAT', collection.id, 640)+ graph.createVariable('dark', 'BOOLEAN', collection.id, true)+ graph.createVariable('name', 'STRING', collection.id, 'Ada')+ graph.createVariable('ink', 'COLOR', collection.id, { r: 0, g: 0, b: 0, a: 1 })+ const placeholder = { FLOAT: 0, BOOLEAN: false, STRING: '', COLOR: { r: 1, g: 1, b: 1, a: 1 } }+ const derived = graph.createVariable('derived', type, collection.id, placeholder[type])+ const parse = (source: string) => parseVariableFormula(graph, derived.id, mode, source)+ const print = (source: string) => formatVariableFormula(graph, parse(source).value)+ return { graph, parse, print }+}++// What Figma resolved for each expression, pasted into Figma desktop on 2026-10-20.+test.each([+ ['text(1.5)', '1.50'],+ ['text(0.125)', '0.12'],+ ['text(100)', '100'],+ ['text(true)', 'true'],+ ['text("abc")', 'abc'],+ ['"a" + "b"', 'ab'],+ ['"a" + 1.5', 'a1.50'],+ ['1 + "b"', '1b'],+ ['true + "x"', 'truex'],+ ['"n=" + 3', 'n=3'],+ ['text({count}) + " items"', '3 items'],+ ['if({dark}, "Dark", "Light")', 'Dark']+] as const)('text formulas give what Figma gives: %s', (source, expected) => {+ expect(setup('STRING').parse(source).resolved).toBe(expected)+})++test.each([+ ['0', false],+ ['1', true],+ ['-1', true],+ ['""', false],+ ['"a"', true],+ ['"0"', true],+ ['"false"', false],+ ['"False"', false],+ ['" false"', false],+ ['"no"', false],+ ['"OFF"', false],+ ['"null"', true],+ ['" "', true],+ ['"n o"', true],+ ['true', true],+ ['false', false]+] as const)('truthy(%s) is what Figma reads it as', (operand, expected) => {+ expect(setup('BOOLEAN').parse(`truthy(${operand})`).resolved).toBe(expected)+})++test('if() picks a number, a value of a variable, or a color', () => {+ expect(setup('FLOAT').parse('if(true, 1, 2)').resolved).toBe(1)+ expect(setup('FLOAT').parse('if({width} > 600, {count} * 2, 0)').resolved).toBe(6)+ expect(setup('BOOLEAN').parse('if(truthy({name}), {dark}, false)').resolved).toBe(true)+ expect(setup('COLOR').parse('if({dark}, {ink}, #FFFFFF)').resolved).toEqual({+ r: 0,+ g: 0,+ b: 0,+ a: 1+ })+ expect(setup('COLOR').parse('if(not {dark}, {ink}, #FF000080)').resolved).toMatchObject({+ r: 1,+ g: 0,+ b: 0+ })+})++test.each([+ ['FLOAT', 'if(5, 1, 2)', 'if() needs true or false, then two values of the same type'],+ ['FLOAT', 'if(true, 1, "a")', 'if() needs true or false, then two values of the same type'],+ ['FLOAT', 'if(true, 1)', 'if() takes 3 values'],+ ['STRING', 'text()', 'text() takes 1 value'],+ ['STRING', 'text({ink})', 'text() needs a number, text, or true or false'],+ ['FLOAT', '"a" - 1', '- needs numbers'],+ ['BOOLEAN', '"1" == 1', '== compares two numbers, two texts, or two true or false values'],+ ['FLOAT', 'true + 1', '+ adds numbers or joins text'],+ ['STRING', '"abc', 'A text is missing its closing "'],+ ['STRING', 'if true', 'Write if(…)'],+ ['FLOAT', '"a" + 1', 'This gives text, but derived holds a number'],+ ['COLOR', '#12345', 'Unexpected #']+] as const)('%s formula %s is refused: %s', (type, source, message) => {+ expect(() => setup(type).parse(source)).toThrow(message)+})++test.each([+ ['"a" + (1 + 2)', '"a" + (1 + 2)'],+ ['"a" + ("b" + "c")', '"a" + "b" + "c"'],+ ['{name} + ({count} + 1)', '{name} + ({count} + 1)'],+ ['"a" + (1 + 2 + "b")', '"a" + (1 + 2 + "b")'],+ ['1 + (2 + "b")', '1 + (2 + "b")'],+ ['"a" + ("b" + 1 + "c")', '"a" + ("b" + 1 + "c")'],+ ['IF({dark}, "Hi", "Hello, " + {name})', 'if({dark}, "Hi", "Hello, " + {name})'],+ ['"say \\"hi\\"" + text({count})', '"say \\"hi\\"" + text({count})']+] as const)('text formulas print so that they read back the same: %s', (source, printed) => {+ const { parse, print } = setup('STRING')+ expect(print(source)).toBe(printed)+ expect(parse(printed).resolved).toBe(parse(source).resolved)+})++test('colors print as hex, with opacity only when they have it', () => {+ const { print } = setup('COLOR')+ expect(print('if({dark}, #ff0000, #00FF0080)')).toBe('if({dark}, #FF0000, #00FF0080)')+})++test('literal text and colors print as the field reads them back', () => {+ const { graph } = setup('STRING')+ expect(formatVariableFormula(graph, 'Hello "you"')).toBe('"Hello \\"you\\""')+ expect(formatVariableFormula(graph, { r: 1, g: 0, b: 0, a: 1 })).toBe('#FF0000')+})++test('the schema takes text and color formulas, and refuses operands that do not fit', () => {+ const formula = (type: VariableType, value: unknown) =>+ v.safeParse(variableFormulaSchema, { expression: 'FORMULA', type, value }).success+ const ternary = (operands: unknown[]) => ({ operator: 'TERNARY', operands })+ const red = { r: 1, g: 0, b: 0, a: 1 }+ expect(formula('STRING', { operator: 'STRINGIFY', operands: [1.5] })).toBe(true)+ expect(formula('COLOR', ternary([{ aliasId: 'flag' }, red, { aliasId: 'ink' }]))).toBe(true)+ expect(formula('FLOAT', ternary([true, 1, 2]))).toBe(true)+ expect(formula('FLOAT', ternary([1, 1, 2]))).toBe(false)+ expect(formula('STRING', ternary([true, 1, 2]))).toBe(false)+ expect(formula('FLOAT', { operator: 'STRINGIFY', operands: [1] })).toBe(false)+ expect(formula('FLOAT', { operator: 'TERNARY', operands: [true, 1] })).toBe(false)+})++test('the tokenizer reads text, colors, calls and commas, and text still being typed', () => {+ expect(formulaTokens('if({a}, "x, y", #FF0000)').map(({ kind }) => kind)).toEqual([+ 'function',+ 'paren',+ 'reference',+ 'comma',+ 'string',+ 'comma',+ 'color',+ 'paren'+ ])+ expect(formulaTokens('"Hello, {na').map(({ kind, text }) => [kind, text])).toEqual([+ ['string', '"Hello, {na']+ ])+})diff --git a/packages/vue/src/i18n/locales/de/variables/panel.json b/packages/vue/src/i18n/locales/de/variables/panel.jsonindex 32acdb157..1e8e48320 100644--- a/packages/vue/src/i18n/locales/de/variables/panel.json+++ b/packages/vue/src/i18n/locales/de/variables/panel.json@@ -129,5 +129,9 @@"formula": "Formel","useFormula": "Formel verwenden","formulaPlaceholder": "Wert oder Formel",+ "formulaFunctions": "Funktionen",+ "formulaIf": "Bedingung, dann, sonst",+ "formulaText": "Zahl als Text",+ "formulaTruthy": "Wert als wahr oder falsch","unsupportedExpression": "OpenPencil kann {name} noch nicht auswerten. Beim Speichern bleibt es unverändert."}diff --git a/packages/vue/src/i18n/locales/es/variables/panel.json b/packages/vue/src/i18n/locales/es/variables/panel.jsonindex cbe91a45d..4049fd547 100644--- a/packages/vue/src/i18n/locales/es/variables/panel.json+++ b/packages/vue/src/i18n/locales/es/variables/panel.json@@ -129,5 +129,9 @@"formula": "Fórmula","useFormula": "Usar una fórmula","formulaPlaceholder": "Valor o fórmula",+ "formulaFunctions": "Funciones",+ "formulaIf": "condición, entonces, si no",+ "formulaText": "número como texto",+ "formulaTruthy": "valor como verdadero o falso","unsupportedExpression": "OpenPencil aún no puede evaluar {name}. Al guardar se conserva tal cual."}diff --git a/packages/vue/src/i18n/locales/fr/variables/panel.json b/packages/vue/src/i18n/locales/fr/variables/panel.jsonindex cdfdb7349..05b2d4e16 100644--- a/packages/vue/src/i18n/locales/fr/variables/panel.json+++ b/packages/vue/src/i18n/locales/fr/variables/panel.json@@ -129,5 +129,9 @@"formula": "Formule","useFormula": "Utiliser une formule","formulaPlaceholder": "Valeur ou formule",+ "formulaFunctions": "Fonctions",+ "formulaIf": "condition, alors, sinon",+ "formulaText": "nombre en texte",+ "formulaTruthy": "valeur en vrai ou faux","unsupportedExpression": "OpenPencil ne sait pas encore évaluer {name}. L’enregistrement le conserve tel quel."}diff --git a/packages/vue/src/i18n/locales/it/variables/panel.json b/packages/vue/src/i18n/locales/it/variables/panel.jsonindex 8651a1aae..6ae435daa 100644--- a/packages/vue/src/i18n/locales/it/variables/panel.json+++ b/packages/vue/src/i18n/locales/it/variables/panel.json@@ -129,5 +129,9 @@"formula": "Formula","useFormula": "Usa una formula","formulaPlaceholder": "Valore o formula",+ "formulaFunctions": "Funzioni",+ "formulaIf": "condizione, allora, altrimenti",+ "formulaText": "numero come testo",+ "formulaTruthy": "valore come vero o falso","unsupportedExpression": "OpenPencil non sa ancora valutare {name}. Il salvataggio lo mantiene invariato."}diff --git a/packages/vue/src/i18n/locales/ja/variables/panel.json b/packages/vue/src/i18n/locales/ja/variables/panel.jsonindex 84397c655..c0781533d 100644--- a/packages/vue/src/i18n/locales/ja/variables/panel.json+++ b/packages/vue/src/i18n/locales/ja/variables/panel.json@@ -129,5 +129,9 @@"formula": "数式","useFormula": "数式を使用","formulaPlaceholder": "値または数式",+ "formulaFunctions": "関数",+ "formulaIf": "条件、真のとき、偽のとき",+ "formulaText": "数値をテキストに",+ "formulaTruthy": "値を真偽値に","unsupportedExpression": "OpenPencil はまだ {name} を評価できません。保存してもそのまま残ります。"}diff --git a/packages/vue/src/i18n/locales/pl/variables/panel.json b/packages/vue/src/i18n/locales/pl/variables/panel.jsonindex aaaa5b11b..03bdb9451 100644--- a/packages/vue/src/i18n/locales/pl/variables/panel.json+++ b/packages/vue/src/i18n/locales/pl/variables/panel.json@@ -129,5 +129,9 @@"formula": "Formuła","useFormula": "Użyj formuły","formulaPlaceholder": "Wartość lub formuła",+ "formulaFunctions": "Funkcje",+ "formulaIf": "warunek, wtedy, w przeciwnym razie",+ "formulaText": "liczba jako tekst",+ "formulaTruthy": "wartość jako prawda lub fałsz","unsupportedExpression": "OpenPencil nie potrafi jeszcze obliczyć {name}. Zapis zachowuje je bez zmian."}diff --git a/packages/vue/src/i18n/locales/ru/variables/panel.json b/packages/vue/src/i18n/locales/ru/variables/panel.jsonindex 86ef29476..be0489fbe 100644--- a/packages/vue/src/i18n/locales/ru/variables/panel.json+++ b/packages/vue/src/i18n/locales/ru/variables/panel.json@@ -129,5 +129,9 @@"formula": "Формула","useFormula": "Использовать формулу","formulaPlaceholder": "Значение или формула",+ "formulaFunctions": "Функции",+ "formulaIf": "условие, тогда, иначе",+ "formulaText": "число как текст",+ "formulaTruthy": "значение как истина или ложь","unsupportedExpression": "OpenPencil пока не умеет вычислять {name}. При сохранении оно остаётся как есть."}diff --git a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json b/packages/vue/src/i18n/locales/zh-cn/variables/panel.jsonindex a3483fba2..daeab0c9b 100644--- a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json+++ b/packages/vue/src/i18n/locales/zh-cn/variables/panel.json@@ -129,5 +129,9 @@"formula": "公式","useFormula": "使用公式","formulaPlaceholder": "值或公式",+ "formulaFunctions": "函数",+ "formulaIf": "条件、为真时、为假时",+ "formulaText": "数字转为文本",+ "formulaTruthy": "值转为真或假","unsupportedExpression": "OpenPencil 暂不能计算 {name}。保存时会原样保留。"}diff --git a/packages/vue/src/i18n/messages/variables/panel.ts b/packages/vue/src/i18n/messages/variables/panel.tsindex 94427008b..adc802a24 100644--- a/packages/vue/src/i18n/messages/variables/panel.ts+++ b/packages/vue/src/i18n/messages/variables/panel.ts@@ -138,6 +138,10 @@ export const variablesMessageDefaults = {formula: 'Formula',useFormula: 'Use a formula',formulaPlaceholder: 'Value or formula',+ formulaFunctions: 'Functions',+ formulaIf: 'condition, then, otherwise',+ formulaText: 'number as text',+ formulaTruthy: 'value as true or false',unsupportedExpression: params('OpenPencil can’t evaluate {name} yet. Saving keeps it as it is.')} as constdiff --git a/src/app/editor/tokens/model.ts b/src/app/editor/tokens/model.tsindex 36601102b..29a48e63d 100644--- a/src/app/editor/tokens/model.ts+++ b/src/app/editor/tokens/model.ts@@ -18,6 +18,8 @@ import {type Variable,type VariableCollection,type VariableColorExpression,+ type VariableFormula,+ type VariableLiteral,type VariableValue} from '@open-pencil/scene-graph'import { colorToHex } from '@open-pencil/scene-graph/color'@@ -49,9 +51,9 @@ export interface TokenRow {}export interface TokenFormulaActions {- /** Variables a formula can use; a true/false formula can also compare numbers. */+ /** Variables a formula can use, which may be of other types than the one it gives. */candidates: AliasCandidate[]- parse: (modeId: string, source: string) => { value: VariableValue; resolved: number | boolean }+ parse: (modeId: string, source: string) => { value: VariableValue; resolved: VariableLiteral }format: (value: VariableValue) => stringreference: (id: string) => string}@@ -88,6 +90,25 @@ function aliasResult(variable: Variable, resolved: VariableValue | undefined) {return undefined}+/** A formula's result in this mode, a color's as its hex, with the formula as it reads. */+function formulaMode(+ graph: SceneGraph,+ variable: Variable,+ modeId: string,+ value: VariableFormula+): TokenModeValue {+ const resolved = graph.resolveVariable(variable.id, modeId)+ const color = typeof resolved === 'object' && 'r' in resolved ? resolved : undefined+ return {+ modeId,+ css: (color ? colorToHex(color) : aliasResult(variable, resolved)) ?? '',+ color,+ formula: printFormula(value.value, (id) => graph.variables.get(id)?.name ?? id, {+ type: (id) => graph.variables.get(id)?.type+ })+ }+}+function modeValue(graph: SceneGraph,variable: Variable,@@ -99,16 +120,7 @@ function modeValue(if (value.expression === 'UNSUPPORTED') return { modeId, css: '', unsupported: value.function }if (value.expression === 'COMPOSE_COLOR')return colorExpressionMode(graph, variable, modeId, value)- const resolved = graph.resolveVariable(variable.id, modeId)- let result: string | undefined- if (typeof resolved === 'number') result = tokenNumberToCSS(resolved, variableUnit(variable))- if (typeof resolved === 'boolean') result = String(resolved)- return {- modeId,- css: result ?? '',- formula: printFormula(value.value, (id) => graph.variables.get(id)?.name ?? id),- expression- }+ return { ...formulaMode(graph, variable, modeId, value), expression }}if (typeof value === 'object' && 'aliasId' in value) {const target = graph.variables.get(value.aliasId)@@ -360,12 +372,16 @@ export function aliasCandidates(graph: SceneGraph, variable: Variable): AliasCanreturn referenceCandidates(graph, variable, [variable.type])}-/** Variables a number or true/false formula can refer to: a true/false one compares numbers too. */+/**+ * Variables a formula can refer to. Numbers, text and true/false values mix through comparisons,+ * `+`, `text()`, `truthy()` and `if()`; colors only fill an `if()` that gives a color.+ */export function formulaCandidates(graph: SceneGraph, variable: Variable): AliasCandidate[] {+ const mixed = ['FLOAT', 'BOOLEAN', 'STRING'] as constreturn referenceCandidates(graph,variable,- variable.type === 'BOOLEAN' ? ['BOOLEAN', 'FLOAT'] : [variable.type]+ variable.type === 'COLOR' ? [...mixed, 'COLOR'] : mixed)}diff --git a/src/app/editor/tokens/value-editor.ts b/src/app/editor/tokens/value-editor.tsindex e00e5e264..a15d33d4d 100644--- a/src/app/editor/tokens/value-editor.ts+++ b/src/app/editor/tokens/value-editor.ts@@ -1,17 +1,22 @@-import type { Variable, VariableValue } from '@open-pencil/scene-graph'+import type { Variable, VariableLiteral, VariableValue } from '@open-pencil/scene-graph'import { parseTokenValueText, tokenValueText, type TokenFormulaActions } from './model'export interface TokenValueEdit {value: VariableValue- resolved: number | boolean+ resolved: VariableLiteralkind: 'literal' | 'reference' | 'formula'}-/** A value as the field shows it: a number in the token's unit, or the formula's source. */+/**+ * A value as the field shows it: a number in the token's unit, or formula source, where text is+ * quoted and a color is `#RRGGBB`, so that the field reads it back as the same value.+ */export function tokenEditorText(variable: Variable, modeId: string, formula: TokenFormulaActions) {const value = variable.valuesByMode[modeId]- return typeof value === 'object' ? formula.format(value) : tokenValueText(variable, value)+ return typeof value === 'object' || variable.type === 'STRING'+ ? formula.format(value)+ : tokenValueText(variable, value)}/**@@ -28,6 +33,8 @@ export function parseTokenEditorText(const literal = parseTokenValueText(variable, text)if (typeof literal === 'number') return { value: literal, resolved: literal, kind: 'literal' }const result = formula.parse(modeId, text)- if (typeof result.value !== 'object') return { ...result, kind: 'literal' }- return { ...result, kind: 'aliasId' in result.value ? 'reference' : 'formula' }+ if (typeof result.value === 'object' && 'aliasId' in result.value)+ return { ...result, kind: 'reference' }+ const operation = typeof result.value === 'object' && 'expression' in result.value+ return { ...result, kind: operation ? 'formula' : 'literal' }}diff --git a/src/components/variables/TokenInspector.vue b/src/components/variables/TokenInspector.vueindex dd0bb8687..72ad14aee 100644--- a/src/components/variables/TokenInspector.vue+++ b/src/components/variables/TokenInspector.vue@@ -256,10 +256,19 @@ function clearExpression(modeId: string) {commitExpression(modeId, '')}-/** Numbers and true/false values edit in the value editor, which takes formulas. */-const editsValues = computed(- () => Boolean(formula) && (variable.value.type === 'FLOAT' || variable.value.type === 'BOOLEAN')-)+/**+ * Values edit in the value editor, which takes formulas: numbers and true/false values always,+ * and text and colors when they are written as they are or as a formula, since a text or color+ * variable keeps its pill and a composed color its swatch.+ */+function usesValueEditor(modeId: string) {+ if (!formula) return false+ if (variable.value.type === 'FLOAT' || variable.value.type === 'BOOLEAN') return true+ const value = variable.value.valuesByMode[modeId]+ if (value === undefined || typeof value !== 'object') return value !== undefined+ if ('aliasId' in value) return false+ return !('expression' in value) || value.expression === 'FORMULA'+}function hasScope(scope: VariableScope) {return variable.value.scopes?.includes(scope) ?? false@@ -362,12 +371,12 @@ function cssNameDone(event: KeyboardEvent) {<section :class="ui.section()"><!-- A value editor heads itself, its tools on its label's row; the section title is for several. -->- <h3 v-if="!editsValues || !singleMode" :class="ui.title()">+ <h3 v-if="!singleMode || !usesValueEditor(collection.defaultModeId)" :class="ui.title()">{{ singleMode ? variables.value : variables.values }}</h3><div v-for="mode in collection.modes" :key="mode.modeId" :class="ui.value()"><span- v-if="!singleMode && (!editsValues || unsupported(mode.modeId))"+ v-if="!singleMode && (!usesValueEditor(mode.modeId) || unsupported(mode.modeId))":class="ui.label()">{{ mode.name }}</span>@@ -378,7 +387,7 @@ function cssNameDone(event: KeyboardEvent) {<span :class="ui.hint()">{{ unsupported(mode.modeId) }}(…)</span></Tip><TokenValueEditor- v-else-if="editsValues && formula"+ v-else-if="usesValueEditor(mode.modeId) && formula":variable="variable":mode-id="mode.modeId":label="singleMode ? variables.value : mode.name"@@ -391,6 +400,23 @@ function cssNameDone(event: KeyboardEvent) {@add-expression="addExpression(mode.modeId)"@remove-expression="clearExpression(mode.modeId)">+ <template #control>+ <ColorInput+ v-if="color(mode.modeId)"+ :color="color(mode.modeId) ?? { r: 0, g: 0, b: 0, a: 1 }"+ editable+ @update="emit('updateValue', mode.modeId, $event, colorGesture(mode.modeId))"+ @open-change="setPickerOpen(mode.modeId, $event)"+ />+ <AppInput+ v-else+ v-model="draft.values[mode.modeId]"+ :aria-label="singleMode ? variables.value : mode.name"+ size="sm"+ @change="commitValue(mode.modeId)"+ @enter="done"+ />+ </template><template #below><TokenCSSExpressionv-if="showsExpression(mode.modeId)"diff --git a/src/components/variables/TokenValueEditor.vue b/src/components/variables/TokenValueEditor.vueindex 98e81b621..e9dede2b2 100644--- a/src/components/variables/TokenValueEditor.vue+++ b/src/components/variables/TokenValueEditor.vue@@ -3,7 +3,13 @@ import { tv } from 'tailwind-variants'import { computed, nextTick, ref, useId, useTemplateRef, watch } from 'vue'import { tokenNumberToCSS, variableUnit } from '@open-pencil/dom-css/export'-import type { Variable, VariableValue } from '@open-pencil/scene-graph'+import {+ formulaSymbol,+ type Variable,+ type VariableLiteral,+ type VariableValue+} from '@open-pencil/scene-graph'+import { colorToHex8 } from '@open-pencil/scene-graph/color'import { useI18n } from '@open-pencil/vue'import {@@ -57,13 +63,20 @@ const insertionCaret = ref<number | null>(null)/** Errors show once a value is committed, not while it is being typed. */const committed = ref(false)const commitError = ref('')-/** A true/false value shows a switch until the user asks to write a formula instead. */+/**+ * A true/false, text or color value shows its own control, a switch or the `control` slot, until+ * the user asks to write a formula instead.+ */const writingFormula = ref(false)const value = computed(() => variable.valuesByMode[modeId])const saved = computed(() => tokenEditorText(variable, modeId, formula))-const showsSwitch = computed(- () => variable.type === 'BOOLEAN' && typeof value.value === 'boolean' && !writingFormula.value+/** A value written as it is: not a variable and not a formula. */+function isLiteral(of: VariableValue | undefined) {+ return of !== undefined && (typeof of !== 'object' || !('aliasId' in of || 'expression' in of))+}+const showsControl = computed(+ () => variable.type !== 'FLOAT' && isLiteral(value.value) && !writingFormula.value)const alias = computed(() =>typeof value.value === 'object' && 'aliasId' in value.value ? value.value.aliasId : undefined@@ -86,10 +99,12 @@ watch(draft, () => {commitError.value = ''})-/** A resolved value as the list shows it: a number with its unit, or true and false. */-function resultText(resolved: VariableValue | undefined) {+/** A resolved value as the list shows it: a number with its unit, true and false, quoted text, or a hex color. */+function resultText(resolved: VariableLiteral | undefined) {if (typeof resolved === 'number') return tokenNumberToCSS(resolved, variableUnit(variable))if (typeof resolved === 'boolean') return String(resolved)+ if (typeof resolved === 'string') return JSON.stringify(resolved)+ if (typeof resolved === 'object') return colorToHex8(resolved)return '—'}@@ -104,14 +119,31 @@ function withValue(candidate: AliasCandidate) {}const pickerItems = computed(() => candidates.map(withValue))const referenceItems = computed(() => formula.candidates.map(withValue))-const completions = computed(() =>- referenceItems.value.map((item) => ({+/** The functions a formula calls, after the variables, each with what it takes. */+const functionCompletions = computed(() =>+ (+ [+ ['TERNARY', variables.value.formulaIf],+ ['STRINGIFY', variables.value.formulaText],+ ['IS_TRUTHY', variables.value.formulaTruthy]+ ] as const+ ).map(([operator, detail]) => ({+ label: formulaSymbol(operator),+ section: variables.value.formulaFunctions,+ detail,+ insert: `${formulaSymbol(operator)}(`,+ kind: 'function' as const+ }))+)+const completions = computed(() => [+ ...referenceItems.value.map((item) => ({label: item.name,section: item.collection,detail: item.text,insert: formula.reference(item.id)- }))-)+ })),+ ...functionCompletions.value+])const candidatesBySource = computed(() => new Map(referenceItems.value.map((item) => [formula.reference(item.id), item])))@@ -160,13 +192,13 @@ const unit = computed(() => {function apply() {committed.value = trueif (draft.value === saved.value) {- if (typeof value.value === 'boolean') writingFormula.value = false+ if (isLiteral(value.value)) writingFormula.value = falsereturn true}const edit = preview.value.editif (!edit) return falseemit('apply', edit.value)- if (typeof edit.value === 'boolean') writingFormula.value = false+ if (isLiteral(edit.value)) writingFormula.value = falsereturn true}function done() {@@ -180,7 +212,7 @@ function cancel() {field.value?.blur()}-const offersFormula = computed(() => showsSwitch.value)+const offersFormula = computed(() => showsControl.value)async function writeFormula() {writingFormula.value = trueawait nextTick()@@ -196,7 +228,7 @@ function toggleExpression() {/** A literal is replaced by the variable; inside a formula, the variable goes at the caret. */function insert(id: string) {const reference = formula.reference(id)- if (showsSwitch.value || preview.value.edit?.kind === 'literal' || !selection.value) {+ if (showsControl.value || preview.value.edit?.kind === 'literal' || !selection.value) {const parsed = formula.parse(modeId, reference)emit('apply', parsed.value)return@@ -214,7 +246,7 @@ function restoreInputFocus(event: Event) {field.value?.setSelectionRange(caret, caret)selection.value = { start: caret, end: caret }}-/** The variable button sits at the field's end, or beside the switch, as in the properties panel. */+/** The variable button sits at the field's end, or beside the control, as in the properties panel. */const picker = computed(() => ({items: pickerItems.value,selected: alias.value,@@ -262,12 +294,15 @@ function detach() {</IconButton></span></div>- <div v-if="showsSwitch" :class="ui.control()">+ <div v-if="showsControl" :class="ui.control()"><AppSwitch+ v-if="variable.type === 'BOOLEAN'":model-value="value === true":label="label"@update:model-value="emit('apply', $event)"/>+ <!-- Text and colors edit in the inspector's own field and color picker. -->+ <slot v-else name="control" /><VariablePicker v-bind="picker" /></div><TokenFormulaFielddiff --git a/src/components/variables/formula-field/dialects/formula.ts b/src/components/variables/formula-field/dialects/formula.tsindex 76c2c4a91..22c7fc71b 100644--- a/src/components/variables/formula-field/dialects/formula.ts+++ b/src/components/variables/formula-field/dialects/formula.ts@@ -27,7 +27,11 @@ const formulaLanguage = StreamLanguage.define<null>({},tokenTable: {reference: tags.special(tags.variableName),- name: tags.variableName+ name: tags.variableName,+ string: tags.string,+ color: tags.color,+ function: tags.function(tags.variableName),+ comma: tags.separator} satisfies Partial<Record<FormulaTokenKind, unknown>>,// Adjacent operators or parentheses stay separate nodes, as the parser reads them.mergeTokens: false@@ -35,10 +39,12 @@ const formulaLanguage = StreamLanguage.define<null>({/*** A variable path being typed, such as `space/ba`, reads as names joined by `/` operators; its- * start is the first name of the run of touching tokens that ends at the caret.+ * start is the first name of the run of touching tokens that ends at the caret. A function's+ * name, such as `text`, is still a word being typed until a `(` follows it.*/function pathStart(state: EditorState, last: SyntaxNode): number | undefined {const isSlash = (node: SyntaxNode) => node.name === 'operator' && nodeText(state, node) === '/'+ if (last.name === 'function') return last.fromif (last.name !== 'name' && !isSlash(last)) return undefinedlet first = lastfor (let node = last.prevSibling; node && node.to === first.from; node = node.prevSibling) {@@ -61,14 +67,15 @@ function completionRange(context: CompletionContext) {const operand =!token ||token.name === 'operator' ||+ token.name === 'comma' ||(token.name === 'keyword' && token.to < pos) ||(token.name === 'paren' && nodeText(state, token) === '(')return operand || context.explicit ? { from: pos, braced: false } : undefined}/**- * Variables complete wherever an operand goes: while a name or `{` reference is typed, and- * after an operator, `(`, or a logic word. The syntax tree says which, so completion agrees+ * Variables and functions complete wherever an operand goes: while a name or `{` reference is+ * typed, and after an operator, `(`, `,` or a logic word; inside braces only variables do. The syntax tree says which, so completion agrees* with the parser about what each piece of text is.*/function completeFormula(references: () => readonly ReferenceCompletion[]) {@@ -79,19 +86,23 @@ function completeFormula(references: () => readonly ReferenceCompletion[]) {return {from,validFor: braced ? /^[^{}]*$/ : /^[\p{L}\p{N}_$/]*$/u,- options: references().map(- ({ label, section, detail, insert }) =>- ({- label,- section,- detail,- type: 'variable',- apply(view, _completion, _from, to) {- const start = braced ? from - 1 : from- const end = braced && view.state.sliceDoc(to, to + 1) === '}' ? to + 1 : to- view.dispatch(insertCompletionText(view.state, insert, start, end))- }- }) satisfies Completion+ options: references().flatMap(({ label, section, detail, insert, kind = 'variable' }) =>+ braced && kind === 'function'+ ? []+ : ({+ label,+ section,+ detail,+ type: kind,+ apply(view, _completion, _from, to) {+ const start = braced ? from - 1 : from+ const next = view.state.sliceDoc(to, to + 1)+ const end = braced && next === '}' ? to + 1 : to+ // A call whose `(` is already there takes its name alone.+ const text = kind === 'function' && next === '(' ? label : insert+ view.dispatch(insertCompletionText(view.state, text, start, end))+ }+ } satisfies Completion))}}diff --git a/src/components/variables/formula-field/dialects/types.ts b/src/components/variables/formula-field/dialects/types.tsindex 8118367c3..282e42255 100644--- a/src/components/variables/formula-field/dialects/types.ts+++ b/src/components/variables/formula-field/dialects/types.ts@@ -1,15 +1,20 @@import type { CompletionSource } from '@codemirror/autocomplete'import type { Extension } from '@codemirror/state'-/** A variable the field can refer to, as its completion list shows it. */+/** A variable the field can refer to, or a function it can call, as its completion list shows it. */export interface ReferenceCompletion {label: string- /** The collection, which groups the list as the variable picker does. */+ /** The collection, which groups the list as the variable picker does, or the functions' heading. */section: string- /** The variable's current value, shown at the row's end. */+ /** The variable's current value, or what the function takes, shown at the row's end. */detail: string- /** The reference as the field's text spells it, such as `{space/md}` or `var(--space-md)`. */+ /**+ * The text inserted: a reference as the field spells it, such as `{space/md}` or+ * `var(--space-md)`, or a call's opening, such as `if(`.+ */insert: string+ /** A function is offered only where a bare name goes, never inside a `{` reference. */+ kind?: 'variable' | 'function'}/** A finished reference in the text, which the field shows as a pill. */diff --git a/src/theme/code/formula.ts b/src/theme/code/formula.tsindex 0e4909c3e..5d690f03a 100644--- a/src/theme/code/formula.ts+++ b/src/theme/code/formula.ts@@ -15,7 +15,7 @@ export function formulaEditorTheme(dark: boolean) {const formulaHighlighting = syntaxHighlighting(HighlightStyle.define([{ tag: tags.keyword, color: 'var(--color-code-keyword)' },- { tag: [tags.number, tags.bool], color: 'var(--color-code-number)' },+ { tag: [tags.number, tags.bool, tags.color], color: 'var(--color-code-number)' },{ tag: tags.string, color: 'var(--color-code-string)' },{ tag: tags.function(tags.variableName), color: 'var(--color-code-tag)' },{diff --git a/tests/app/editor/tokens/value-editor.test.ts b/tests/app/editor/tokens/value-editor.test.tsindex b890d89ca..9e6b8522a 100644--- a/tests/app/editor/tokens/value-editor.test.ts+++ b/tests/app/editor/tokens/value-editor.test.ts@@ -59,3 +59,31 @@ test('true/false values read words, references, logic and number comparisons', (expect(() => read('{width}')).toThrow('This gives a number, but visible holds true or false')expect(() => read('var(--enabled)')).toThrow()})++test('text and color values read quoted text, hex colors and formulas, and show as they read', () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Copy')+ const mode = collection.defaultModeId+ graph.createVariable('count', 'FLOAT', collection.id, 3)+ graph.createVariable('dark', 'BOOLEAN', collection.id, true)+ const label = graph.createVariable('label', 'STRING', collection.id, 'Say "hi"')+ const surface = graph.createVariable('surface', 'COLOR', collection.id, {+ r: 1,+ g: 0,+ b: 0,+ a: 1+ })+ const text = (value: string) => parseTokenEditorText(label, mode, value, actions(graph, label))+ const color = (value: string) =>+ parseTokenEditorText(surface, mode, value, actions(graph, surface))++ expect(tokenEditorText(label, mode, actions(graph, label))).toBe('"Say \\"hi\\""')+ expect(tokenEditorText(surface, mode, actions(graph, surface))).toBe('#FF0000')+ expect(text('"Hello"')).toMatchObject({ value: 'Hello', kind: 'literal' })+ expect(text('text({count}) + " items"')).toMatchObject({ resolved: '3 items', kind: 'formula' })+ expect(color('#00FF00')).toMatchObject({ value: { r: 0, g: 1, b: 0, a: 1 }, kind: 'literal' })+ expect(color('if({dark}, #000000, #FFFFFF)')).toMatchObject({+ resolved: { r: 0, g: 0, b: 0, a: 1 },+ kind: 'formula'+ })+})diff --git a/tests/e2e/variables/formula.webkit.spec.ts b/tests/e2e/variables/formula.webkit.spec.tsindex 28d942ae1..9d093892a 100644--- a/tests/e2e/variables/formula.webkit.spec.ts+++ b/tests/e2e/variables/formula.webkit.spec.ts@@ -243,6 +243,31 @@ test('completion inserts a reference and the table shows the result', async ({ pcanvas.assertNoErrors()})+test('completion offers functions where a name goes and inserts the call', async ({ page }) => {+ const canvas = new CanvasHelper(page)+ await page.goto('/?test')+ await canvas.waitForInit()+ const ids = await seedFormulaScene(page)+ const { dialog, inspector } = await openToken(page, ids.width)+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })+ const completion = dialog.locator('.cm-tooltip-autocomplete')+ await value.fill('2 * ')+ await value.press('End')+ await value.pressSequentially('i')+ await expect(completion.getByRole('option', { name: /^if/ })).toBeVisible()+ await value.press('Enter')+ await expect(value).toHaveText('2 * if(')+ await value.fill('tex')+ await value.press('End')+ await value.pressSequentially('t')+ await expect(completion.getByRole('option', { name: /^text/ })).toBeVisible()+ await value.fill('{tru')+ await value.press('End')+ await value.pressSequentially('t')+ await expect(completion.getByRole('option', { name: /^truthy/ })).toHaveCount(0)+ canvas.assertNoErrors()+})+test('a CSS expression completes token names as var() pills and functions', async ({ page }) => {const canvas = new CanvasHelper(page)await page.goto('/?test')