Skip to content

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

feat(variables): add numeric and Boolean formulas (#1208)

GitttHomiec6c57b12ee6f
diff --git a/changes/1208/added.md b/changes/1208/added.md
new file mode 100644
index 000000000..12580b95e
--- /dev/null
+++ b/changes/1208/added.md
@@ -0,0 +1,5 @@
+- Number and true/false variables take live formulas: references show as pills, the field shows the result, true/false formulas can compare numbers, and formulas survive undo, copy and paste, sharing and `.fig` saves.
+- The token stylesheet writes number formulas as `calc()` over the variables they use, and design-token files keep each formula beside its result.
+- CSS expressions complete token names as `var()` pills, preview what the browser computes, are checked when committed, and can be added to any number mode from the value's label row.
+- Formulas and CSS expressions are highlighted and span several lines, with Shift+Enter for a line break.
+- Imported Figma color and opacity expressions retain their variable references.
diff --git a/changes/1208/breaking.md b/changes/1208/breaking.md
new file mode 100644
index 000000000..f2de12ed4
--- /dev/null
+++ b/changes/1208/breaking.md
@@ -0,0 +1,2 @@
+- `VariableValue` includes formula and color-expression objects; API consumers should resolve variables before treating non-alias objects as colors.
+- `TokenExpression.resolved` is optional: a CSS expression on a formula or reference mode records no number, and it now outlives changes to its mode's value instead of being dropped when the value stops being a plain number.
diff --git a/changes/1208/changed.md b/changes/1208/changed.md
new file mode 100644
index 000000000..c282d9264
--- /dev/null
+++ b/changes/1208/changed.md
@@ -0,0 +1 @@
+- The variables list shows an alias as a pill sized to its target's name followed by the value it gives, and a value with a CSS expression keeps showing its value, marked CSS, with the expression on hover.
diff --git a/changes/1208/fixed.md b/changes/1208/fixed.md
new file mode 100644
index 000000000..a63d01203
--- /dev/null
+++ b/changes/1208/fixed.md
@@ -0,0 +1,2 @@
+- The variable picker no longer shows an empty divider at its bottom when nothing is bound.
+- Switching tokens in the variables dialog no longer animates the inspector.
diff --git a/packages/core/src/editor/clipboard/variables.ts b/packages/core/src/editor/clipboard/variables.ts
index d72479f1f..4c20435c2 100644
--- a/packages/core/src/editor/clipboard/variables.ts
+++ b/packages/core/src/editor/clipboard/variables.ts
@@ -1,5 +1,7 @@
import {
remapStyleRunReferences,
+ mapVariableValueReferences,
+ variableValueReferences,
styleRunReferences,
type SceneGraph,
type SceneNode,
@@ -27,7 +29,7 @@ export function captureClipboardVariables(
const collection = graph.variableCollections.get(variable.collectionId)
if (collection) collections.set(collection.id, structuredClone(collection))
for (const value of Object.values(variable.valuesByMode)) {
- if (typeof value === 'object' && 'aliasId' in value) visit(value.aliasId)
+ for (const reference of variableValueReferences(value)) visit(reference)
}
}
for (const node of nodes) {
@@ -74,9 +76,7 @@ export function importClipboardVariables(graph: SceneGraph, dependencies: Clipbo
valuesByMode: Object.fromEntries(
Object.entries(variable.valuesByMode).map(([mode, value]) => [
modeIds.get(mode) ?? mode,
- typeof value === 'object' && 'aliasId' in value
- ? { aliasId: variableIds.get(value.aliasId) ?? value.aliasId }
- : structuredClone(value)
+ mapVariableValueReferences(value, (id) => variableIds.get(id) ?? id)
])
)
}))
diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.ts
index 260d33301..5e61ea08f 100644
--- a/packages/core/src/editor/variables.ts
+++ b/packages/core/src/editor/variables.ts
@@ -3,6 +3,7 @@ import { isEmptyObject } from 'es-toolkit/predicate'
import {
isModeAttributeName,
+ tokenExpressionForValue,
type BindingScope,
type TokenExpression,
type Variable,
@@ -441,12 +442,9 @@ export function createVariableActions(ctx: EditorContext) {
const variable = ctx.graph.variables.get(id)
if (!variable) return
const previous = modeEntry(variable, modeId)
- // A number keeps its expression, which records the number it stands for; anything else drops it.
- const expression = previous.expression
const next: ModeEntry = {
value: structuredClone(value),
- expression:
- typeof value === 'number' && expression ? { ...expression, resolved: value } : undefined
+ expression: tokenExpressionForValue(previous.expression, value)
}
const apply = (entry: ModeEntry) => {
const target = ctx.graph.variables.get(id)
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 3fec36fba..ef3ed03ba 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -1,15 +1,17 @@
import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
-import { createConnector, freeEndpoint } from '@open-pencil/scene-graph'
-import type {
- GroupFitOptions,
- SceneGraph,
- SceneNode as CoreSceneNode,
- NodeType,
- Variable,
- VariableCollection,
- VariableType,
- VariableValue
+import {
+ createConnector,
+ freeEndpoint,
+ updateTokenExpression,
+ type GroupFitOptions,
+ type SceneGraph,
+ type SceneNode as CoreSceneNode,
+ type NodeType,
+ type Variable,
+ type VariableCollection,
+ type VariableType,
+ type VariableValue
} from '@open-pencil/scene-graph'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
import { computeImageHash } from '@open-pencil/scene-graph/images'
@@ -366,6 +368,7 @@ export class FigmaAPI implements NodeProxyHost {
const variable = this.graph.variables.get(variableId)
if (!variable) throw new Error(`Variable "${variableId}" not found`)
variable.valuesByMode[modeId] = structuredClone(value)
+ updateTokenExpression(variable, modeId, value)
reconcileVariableLayouts(this.graph, { variables: [variableId] })
}
diff --git a/packages/core/src/io/formats/design-tokens/export.ts b/packages/core/src/io/formats/design-tokens/export.ts
index 8022c1166..d1753862b 100644
--- a/packages/core/src/io/formats/design-tokens/export.ts
+++ b/packages/core/src/io/formats/design-tokens/export.ts
@@ -2,11 +2,13 @@ import { compact } from 'es-toolkit/array'
import { omitBy } from 'es-toolkit/object'
import { isEmptyObject } from 'es-toolkit/predicate'
-import type {
- SceneGraph,
- Variable,
- VariableCollection,
- VariableCollectionMode
+import {
+ printFormula,
+ variableValueReferences,
+ type SceneGraph,
+ type Variable,
+ type VariableCollection,
+ type VariableCollectionMode
} from '@open-pencil/scene-graph'
import { fileSegment, placeTokens, tokenPath, tokenReference, tokenTree } from './paths'
@@ -57,11 +59,12 @@ interface ExportContext {
}
/** OpenPencil's own token fields, which DTCG has no place for. */
-function openPencilFields(variable: Variable, modeId: string) {
+function openPencilFields(variable: Variable, modeId: string, formula?: string) {
const fields = omitBy(
{
unit: variable.unit,
expression: variable.expressions?.[modeId]?.css,
+ formula,
scopes: variable.scopes,
codeSyntax: variable.codeSyntax,
hiddenFromPublishing: variable.hiddenFromPublishing || undefined
@@ -89,7 +92,21 @@ function variableToken(
const value = variable.valuesByMode[mode.modeId]
const figma: Record<string, unknown> = {}
let $value: unknown
- if (typeof value === 'object' && 'aliasId' in value) {
+ let formula: string | undefined
+ if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {
+ // DTCG has no formulas: the token holds this mode's result and keeps the formula beside it.
+ const resolved = context.graph.resolveVariable(variable.id, mode.modeId)
+ const missing = variableValueReferences(value).some((id) => !context.references.has(id))
+ if (missing || resolved === undefined) {
+ context.issues.push({ kind: 'missing-alias', ...where })
+ return undefined
+ }
+ formula = printFormula(value.value, (id) => tokenReference(context.references.get(id) ?? []))
+ $value = literalTokenValue(variable, resolved)
+ } else if (typeof value === 'object' && 'expression' in value) {
+ context.issues.push({ kind: 'unsupported-expression', ...where })
+ return undefined
+ } else if (typeof value === 'object' && 'aliasId' in value) {
const path = context.references.get(value.aliasId)
const target = context.graph.variables.get(value.aliasId)
const targetCollection = context.collectionOf.get(value.aliasId)
@@ -107,7 +124,7 @@ function variableToken(
$value = literalTokenValue(variable, value)
}
if (variable.type === 'BOOLEAN') figma['com.figma.type'] = 'boolean'
- const $extensions = { ...figma, ...openPencilFields(variable, mode.modeId) }
+ const $extensions = { ...figma, ...openPencilFields(variable, mode.modeId, formula) }
const token: DesignToken = { $type: variableTokenType(variable), $value }
if (variable.description) token.$description = variable.description
if (!isEmptyObject($extensions)) token.$extensions = $extensions
diff --git a/packages/core/src/io/formats/design-tokens/types.ts b/packages/core/src/io/formats/design-tokens/types.ts
index b2310226c..8d9f7cdc4 100644
--- a/packages/core/src/io/formats/design-tokens/types.ts
+++ b/packages/core/src/io/formats/design-tokens/types.ts
@@ -34,6 +34,7 @@ export interface DesignTokenFile {
/** Why a token, mode, or style was left out or changed; the names are as the document has them. */
export type DesignTokenIssue =
+ | { kind: 'unsupported-expression'; collection: string; mode: string; token: string }
| { kind: 'missing-value'; collection: string; mode: string; token: string }
| { kind: 'missing-alias'; collection: string; mode: string; token: string }
| { kind: 'duplicate-path'; collection: string; token: string }
@@ -41,6 +42,8 @@ export type DesignTokenIssue =
/** An issue as one line of text, for the CLI and tool output. */
export function designTokenIssueMessage(issue: DesignTokenIssue): string {
+ if (issue.kind === 'unsupported-expression')
+ return `${issue.collection} / ${issue.mode}: ${issue.token} uses an expression that token export does not support`
if (issue.kind === 'missing-value')
return `${issue.collection} / ${issue.mode}: ${issue.token} has no value in this mode`
if (issue.kind === 'missing-alias')
diff --git a/packages/core/src/io/formats/fig/export/variables.ts b/packages/core/src/io/formats/fig/export/variables.ts
index 734d063eb..7e1591855 100644
--- a/packages/core/src/io/formats/fig/export/variables.ts
+++ b/packages/core/src/io/formats/fig/export/variables.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import {
collectionPluginDataNodeChange,
parseGuidOrNull,
@@ -8,8 +10,13 @@ import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/
import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
import {
modesDefaultFirst,
+ MAX_FORMULA_DEPTH,
+ formulaResultType,
+ variableFormulaSchema,
+ variableColorExpressionSchema,
type SceneGraph,
type SceneNode,
+ type VariableFormulaNode,
type VariableCollectionMode,
type VariableValue
} from '@open-pencil/scene-graph'
@@ -139,6 +146,28 @@ function variableValueToKiwi(
type: string,
ids: Map<string, GUID>
): VariableDataEntry {
+ if (typeof value === 'object' && 'expression' in value && value.expression === 'FORMULA') {
+ const formula = v.parse(variableFormulaSchema, value)
+ if (formula.type !== type) throw new Error('Formula type does not match variable type')
+ return formulaToKiwi(graph, formula.value, ids)
+ }
+ if (typeof value === 'object' && 'expression' in value) {
+ const expression = v.parse(variableColorExpressionSchema, value)
+ if (type !== 'COLOR') throw new Error('Color expression requires a color variable')
+ return {
+ dataType: 'EXPRESSION',
+ resolvedDataType: 'COLOR',
+ value: {
+ expressionValue: {
+ expressionFunction: expression.expression,
+ expressionArguments: [
+ variableValueToKiwi(graph, expression.color, 'COLOR', ids),
+ variableValueToKiwi(graph, expression.opacity, 'FLOAT', ids)
+ ]
+ }
+ }
+ }
+ }
if (typeof value === 'object' && 'aliasId' in value)
return {
value: { alias: variableAlias(graph, value.aliasId, ids) },
@@ -158,6 +187,35 @@ function variableValueToKiwi(
return { value: { floatValue: Number(value) }, dataType: 'FLOAT', resolvedDataType: 'FLOAT' }
}
+function formulaToKiwi(
+ graph: SceneGraph,
+ node: VariableFormulaNode,
+ ids: Map<string, GUID>,
+ depth = 0
+): 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)
+ }
+ return {
+ dataType: 'EXPRESSION',
+ resolvedDataType: formulaResultType(node.operator),
+ value: {
+ expressionValue: {
+ expressionFunction: node.operator,
+ expressionArguments: node.operands.map((operand) =>
+ formulaToKiwi(graph, operand, ids, depth + 1)
+ )
+ }
+ }
+ }
+}
+
/**
* Order keys for one parent, in call order. Collections, variables, shared styles and the
* canvas's own layers all append to the internal canvas, so they share one sequence rather
diff --git a/packages/core/src/io/subgraph.ts b/packages/core/src/io/subgraph.ts
index a85ad104b..0f9f36f1f 100644
--- a/packages/core/src/io/subgraph.ts
+++ b/packages/core/src/io/subgraph.ts
@@ -1,4 +1,4 @@
-import { SceneGraph, styleRunReferences } from '@open-pencil/scene-graph'
+import { SceneGraph, styleRunReferences, variableValueReferences } from '@open-pencil/scene-graph'
import type { ExportTarget } from './types'
@@ -157,9 +157,7 @@ function collectVariableClosure(source: SceneGraph, variableId: string, out: Set
if (!variable) return
out.add(variableId)
for (const value of Object.values(variable.valuesByMode)) {
- if (typeof value === 'object' && 'aliasId' in value) {
- collectVariableClosure(source, value.aliasId, out)
- }
+ for (const id of variableValueReferences(value)) collectVariableClosure(source, id, out)
}
}
diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.ts
index eeac8c26b..4d4b5de7e 100644
--- a/packages/core/src/openpencil-api/index.ts
+++ b/packages/core/src/openpencil-api/index.ts
@@ -1,11 +1,12 @@
import {
BEHAVIOUR_CONTRACTS,
BEHAVIOUR_KINDS,
+ parseVariableFormula,
type BehaviourKind,
type BehaviourSpec
} from '@open-pencil/scene-graph'
-import type { FigmaAPI } from '#core/figma-api'
+import type { FigmaAPI } from '#core/figma-api/index'
import {
getBehaviour,
@@ -41,6 +42,40 @@ export {
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}`.
+ */
+ setVariableFormula(
+ collectionName: string,
+ variableName: string,
+ source: string,
+ modeName?: string
+ ): number | boolean {
+ const graph = this.figma.graph
+ const collections = [...graph.variableCollections.values()].filter(
+ (item) => item.name === collectionName
+ )
+ const collection = collections.at(0)
+ if (!collection || collections.length !== 1)
+ throw new Error(`Unknown or ambiguous collection: ${collectionName}`)
+ const variables = [...graph.variables.values()].filter(
+ (item) => item.collectionId === collection.id && item.name === variableName
+ )
+ const variable = variables.at(0)
+ if (!variable || variables.length !== 1)
+ throw new Error(`Unknown or ambiguous variable: ${variableName}`)
+ const modes = collection.modes.filter((mode) =>
+ modeName ? mode.name === modeName : mode.modeId === collection.defaultModeId
+ )
+ const mode = modes.at(0)
+ if (!mode || modes.length !== 1) throw new Error(`Unknown or ambiguous mode: ${modeName}`)
+ const { value, resolved } = parseVariableFormula(graph, variable.id, mode.modeId, source)
+ this.figma.setVariableValue(variable.id, mode.modeId, value)
+ return resolved
+ }
+
/** The behaviour kinds, after Reka UI's primitives, with the values and parts each binds. */
get behaviourKinds() {
return BEHAVIOUR_KINDS.map((kind) => ({ kind, ...structuredClone(BEHAVIOUR_CONTRACTS[kind]) }))
diff --git a/packages/core/src/rpc/variables-command.ts b/packages/core/src/rpc/variables-command.ts
index 2ff5730a2..6830b0581 100644
--- a/packages/core/src/rpc/variables-command.ts
+++ b/packages/core/src/rpc/variables-command.ts
@@ -1,4 +1,9 @@
-import type { SceneGraph, Variable, VariableType } from '@open-pencil/scene-graph'
+import {
+ formatVariableFormula,
+ type SceneGraph,
+ type Variable,
+ type VariableType
+} from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
import { exportTokenStylesheet, type TokenExport } from '#core/tools/codegen/tokens'
@@ -24,6 +29,16 @@ function formatVariableValue(variable: Variable, graph: SceneGraph): string {
if (typeof raw === 'object' && 'r' in raw) {
return colorToHex(raw).toLowerCase()
}
+ if (typeof raw === 'object' && 'expression' in raw) {
+ // A formula reads as written, with what it gives now; a composed color by its result.
+ const resolved = graph.resolveVariable(variable.id, modeId)
+ let result = '—'
+ if (typeof resolved === 'object') result = colorToHex(resolved).toLowerCase()
+ else if (resolved !== undefined) result = String(resolved)
+ return raw.expression === 'FORMULA'
+ ? `${formatVariableFormula(graph, raw)} = ${result}`
+ : result
+ }
return String(raw)
}
diff --git a/packages/core/tests/editor/design-tokens.test.ts b/packages/core/tests/editor/design-tokens.test.ts
index be88acd22..c486b8add 100644
--- a/packages/core/tests/editor/design-tokens.test.ts
+++ b/packages/core/tests/editor/design-tokens.test.ts
@@ -1,7 +1,12 @@
import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
-import { getSharedStyles, SceneGraph, type Variable } from '@open-pencil/scene-graph'
+import {
+ getSharedStyles,
+ parseVariableFormula,
+ SceneGraph,
+ type Variable
+} from '@open-pencil/scene-graph'
import {
defaultTokenImportOptions,
@@ -256,3 +261,17 @@ describe('design token import', () => {
])
})
})
+
+test('a formula token holds its result and keeps the formula with token references', () => {
+ const graph = new SceneGraph()
+ const space = graph.createCollection('Space')
+ const mode = space.defaultModeId
+ graph.createVariable('Base', 'FLOAT', space.id, 4)
+ const large = graph.createVariable('Large', 'FLOAT', space.id, 0)
+ large.valuesByMode[mode] = parseVariableFormula(graph, large.id, mode, '{Base} * 4').value
+ const { files, issues } = exportDesignTokens(graph)
+ expect(issues).toEqual([])
+ const token = JSON.stringify(files.map((file) => file.content))
+ expect(token).toContain('"$value":{"value":16,"unit":"px"}')
+ expect(token).toContain('"formula":"{Base} * 4"')
+})
diff --git a/packages/core/tests/editor/undo/variable/tokens.test.ts b/packages/core/tests/editor/undo/variable/tokens.test.ts
index b54f8298d..2c4299007 100644
--- a/packages/core/tests/editor/undo/variable/tokens.test.ts
+++ b/packages/core/tests/editor/undo/variable/tokens.test.ts
@@ -158,7 +158,7 @@ describe('variable token undo', () => {
expect(Object.hasOwn(editor.graph.variables.get('gutter') ?? {}, 'unit')).toBe(false)
})
- test('an expression follows its number, goes with an alias, and undoes with the value', () => {
+ test('an expression follows its number, stays with an alias, and undoes with the value', () => {
const editor = themeEditor()
const gutter = () => editor.graph.variables.get('gutter')
const clamp = 'clamp(1rem, 4vw, 1.5rem)'
@@ -168,7 +168,7 @@ describe('variable token undo', () => {
expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 20 } })
editor.updateVariableValue('gutter', 'light', { aliasId: 'other' })
- expect(gutter()?.expressions).toBeUndefined()
+ expect(gutter()?.expressions).toEqual({ light: { css: clamp } })
editor.undo.undo()
expect(gutter()?.expressions).toEqual({ light: { css: clamp, resolved: 20 } })
diff --git a/packages/core/tests/editor/variables/color-expression.test.ts b/packages/core/tests/editor/variables/color-expression.test.ts
new file mode 100644
index 000000000..736d9b44b
--- /dev/null
+++ b/packages/core/tests/editor/variables/color-expression.test.ts
@@ -0,0 +1,60 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { resolveFillColor } from '#core/canvas/renderer/colors'
+import {
+ captureClipboardVariables,
+ importClipboardVariables
+} from '#core/editor/clipboard/variables'
+import { deserializeSceneGraph, serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
+
+test('100 instances repaint derived colors on a token edit, undo, and redo', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Colors')
+ const base = graph.createVariable('Base', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })
+ const derived = graph.createVariable('Derived', 'COLOR', collection.id, {
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: base.id },
+ opacity: 20
+ })
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ fills: [
+ {
+ type: 'SOLID',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ opacity: 0.2,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ ],
+ boundVariables: { 'fills/0/color': derived.id }
+ })
+ const instances = Array.from({ length: 100 }, () =>
+ graph.createInstance(component.id, graph.getPages()[0].id)
+ )
+ const editor = createEditor({ graph })
+ const colorOf = (node: typeof component | null) => {
+ if (!node) throw new Error('Missing component instance')
+ return resolveFillColor(node.fills[0], 0, node, graph, 'srgb')
+ }
+ editor.updateVariableValue(base.id, collection.defaultModeId, { r: 0, g: 0, b: 1, a: 1 })
+ for (const node of [component, ...instances]) {
+ expect(colorOf(node)).toEqual({ r: 0, g: 0, b: 1, a: 0.2 })
+ }
+ editor.undo.undo()
+ for (const node of instances) expect(colorOf(node).r).toBe(1)
+ editor.undo.redo()
+ for (const node of instances) expect(colorOf(node).b).toBe(1)
+
+ const clipboard = captureClipboardVariables(graph, [component])
+ expect(clipboard.variables).toHaveLength(2)
+ const destination = new SceneGraph()
+ const transfer = importClipboardVariables(destination, clipboard)
+ transfer.apply()
+ const copiedId = transfer.variableIds.get(derived.id) ?? ''
+ expect(destination.resolveColorVariable(copiedId)).toEqual({ r: 0, g: 0, b: 1, a: 0.2 })
+ const recovered = deserializeSceneGraph(serializeSceneGraph(destination))
+ expect(recovered.resolveColorVariable(copiedId)).toEqual({ r: 0, g: 0, b: 1, a: 0.2 })
+})
diff --git a/packages/core/tests/editor/variables/formula.test.ts b/packages/core/tests/editor/variables/formula.test.ts
new file mode 100644
index 000000000..2d74abadc
--- /dev/null
+++ b/packages/core/tests/editor/variables/formula.test.ts
@@ -0,0 +1,63 @@
+import { expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { SceneGraph, parseVariableFormula } from '@open-pencil/scene-graph'
+
+import {
+ captureClipboardVariables,
+ importClipboardVariables
+} from '#core/editor/clipboard/variables'
+import { deserializeSceneGraph, serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'
+
+test('numeric and Boolean formulas update 100 instances, layout, undo, clipboard and recovery', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ const mode = collection.defaultModeId
+ const base = graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const gap = graph.createVariable('gap', 'FLOAT', collection.id, 8)
+ const enabled = graph.createVariable('enabled', 'BOOLEAN', collection.id, true)
+ const visible = graph.createVariable('visible', 'BOOLEAN', collection.id, true)
+ gap.valuesByMode[mode] = parseVariableFormula(graph, gap.id, mode, '{base} * 2').value
+ visible.valuesByMode[mode] = parseVariableFormula(
+ graph,
+ visible.id,
+ mode,
+ '{enabled} AND true'
+ ).value
+ const component = graph.createNode('COMPONENT', graph.getPages()[0].id, {
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 8,
+ primaryAxisSizing: 'HUG',
+ boundVariables: { itemSpacing: gap.id, visible: visible.id }
+ })
+ graph.createNode('FRAME', component.id, { width: 20, height: 10 })
+ graph.createNode('FRAME', component.id, { width: 20, height: 10 })
+ const instances = Array.from({ length: 100 }, () => {
+ const instance = graph.createInstance(component.id, graph.getPages()[0].id)
+ if (!instance) throw new Error('Missing instance')
+ return instance.id
+ })
+ const editor = createEditor({ graph })
+ editor.updateVariableValue(base.id, mode, 6)
+ for (const id of instances) {
+ expect(graph.getNode(id)?.itemSpacing).toBe(12)
+ expect(graph.getNode(id)?.width).toBe(52)
+ }
+ editor.updateVariableValue(enabled.id, mode, false)
+ for (const id of instances) expect(graph.getNode(id)?.visible).toBe(false)
+ editor.undo.undo()
+ for (const id of instances) expect(graph.getNode(id)?.visible).toBe(true)
+ editor.undo.undo()
+ for (const id of instances) expect(graph.getNode(id)?.itemSpacing).toBe(8)
+ editor.undo.redo()
+ for (const id of instances) expect(graph.getNode(id)?.itemSpacing).toBe(12)
+ const clipboard = captureClipboardVariables(graph, [component])
+ expect(clipboard.variables).toHaveLength(4)
+ const destination = new SceneGraph()
+ const transfer = importClipboardVariables(destination, clipboard)
+ transfer.apply()
+ const copyId = transfer.variableIds.get(gap.id) ?? ''
+ expect(destination.resolveVariable(copyId)).toBe(12)
+ const recovered = deserializeSceneGraph(serializeSceneGraph(destination))
+ expect(recovered.resolveVariable(copyId)).toBe(12)
+})
diff --git a/packages/core/tests/io/formats/fig/export/color-expression.test.ts b/packages/core/tests/io/formats/fig/export/color-expression.test.ts
new file mode 100644
index 000000000..f5da1557d
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/color-expression.test.ts
@@ -0,0 +1,57 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { parseFigBuffer, patchFigArchive } from '@open-pencil/fig'
+
+test('color expressions survive fresh export, import, editing and patched export', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Colors')
+ const base = graph.createVariable('Base', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })
+ graph.createVariable('Derived', 'COLOR', collection.id, {
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: base.id },
+ opacity: 20
+ })
+ const exported = await exportFigFile(graph)
+ const record = parseFigBuffer(Uint8Array.from(exported).buffer).nodeChanges.find(
+ (node) => node.name === 'Derived'
+ )
+ expect(record?.variableDataValues?.entries?.[0].variableData.value?.expressionValue).toMatchObject({
+ expressionFunction: 'COMPOSE_COLOR',
+ expressionArguments: [{ dataType: 'ALIAS' }, { dataType: 'FLOAT', value: { floatValue: 20 } }]
+ })
+ if (!record) throw new Error('Missing exported expression')
+ // Fields retained by Figma but not represented in the editable variable model.
+ const archivedRecord = { ...record, sortPosition: 'preserved-order', isSoftDeleted: false }
+ const annotated = patchFigArchive(
+ Uint8Array.from(exported).buffer,
+ {
+ records: [archivedRecord],
+ blobs: [],
+ removed: [],
+ replaceVariables: false
+ },
+ { thumbnailPNG: new Uint8Array(), metaJSON: '{}', images: [] }
+ )
+ const imported = await parseFigFile(Uint8Array.from(annotated).buffer)
+ const importedBase = [...imported.variables.values()].find((v) => v.name === 'Base')
+ const importedDerived = [...imported.variables.values()].find((v) => v.name === 'Derived')
+ if (!importedBase || !importedDerived) throw new Error('Variables missing after import')
+ const mode = imported.getActiveModeId(importedBase.collectionId)
+ expect(imported.resolveColorVariable(importedDerived.id)).toEqual({ r: 1, g: 0, b: 0, a: 0.2 })
+ importedBase.valuesByMode[mode] = { r: 0, g: 1, b: 0, a: 1 }
+ const saved = await exportFigFile(imported)
+ expect(
+ parseFigBuffer(Uint8Array.from(saved).buffer).nodeChanges.find(
+ (node) => node.name === 'Derived'
+ )
+ ).toEqual(archivedRecord)
+ const reopened = await parseFigFile(Uint8Array.from(saved).buffer)
+ const derived = [...reopened.variables.values()].find((v) => v.name === 'Derived')
+ expect(reopened.resolveColorVariable(derived?.id ?? '')).toEqual({ r: 0, g: 1, b: 0, a: 0.2 })
+ expect(Object.values(derived?.valuesByMode ?? {})[0]).toMatchObject({
+ expression: 'COMPOSE_COLOR',
+ opacity: 20
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/formula.test.ts b/packages/core/tests/io/formats/fig/export/formula.test.ts
new file mode 100644
index 000000000..85869b08b
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/formula.test.ts
@@ -0,0 +1,70 @@
+import { expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { parseVariableFormula } from '@open-pencil/scene-graph'
+
+test('numeric, Boolean and comparison formulas survive fresh and patched .fig saves', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ const base = graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const derived = graph.createVariable('derived', 'FLOAT', collection.id, 0)
+ const enabled = graph.createVariable('enabled', 'BOOLEAN', collection.id, true)
+ const hidden = graph.createVariable('hidden', 'BOOLEAN', collection.id, false)
+ const wide = graph.createVariable('wide', 'BOOLEAN', collection.id, false)
+ const mode = collection.defaultModeId
+ derived.valuesByMode[mode] = parseVariableFormula(
+ graph,
+ derived.id,
+ mode,
+ '-(-{base}) + (3 * 4) / 2'
+ ).value
+ hidden.valuesByMode[mode] = parseVariableFormula(
+ graph,
+ hidden.id,
+ mode,
+ 'not ({enabled} or false)'
+ ).value
+ wide.valuesByMode[mode] = parseVariableFormula(graph, wide.id, mode, '{base} * 2 > 12').value
+ graph.createNode('FRAME', graph.getPages()[0].id, {
+ name: 'Formula consumer',
+ width: 10,
+ visible: false,
+ boundVariables: { width: derived.id, visible: hidden.id }
+ })
+ let current = graph
+ for (let i = 0; i < 2; i++) {
+ current = await parseFigFile(Uint8Array.from(await exportFigFile(current)).buffer)
+ const number = [...current.variables.values()].find((v) => v.name === 'derived')
+ const boolean = [...current.variables.values()].find((v) => v.name === 'hidden')
+ const comparison = [...current.variables.values()].find((v) => v.name === 'wide')
+ expect(current.resolveVariable(comparison?.id ?? '')).toBe(i !== 0)
+ expect(current.resolveVariable(number?.id ?? '')).toBe(i === 0 ? 10 : 16)
+ expect(current.resolveVariable(boolean?.id ?? '')).toBe(i !== 0)
+ const node = [...current.getAllNodes()].find((node) => node.name === 'Formula consumer')
+ expect(node?.width).toBe(i === 0 ? 10 : 16)
+ expect(node?.visible).toBe(i !== 0)
+ const api = new FigmaAPI(current)
+ for (const variable of current.variables.values()) {
+ const active = current.getActiveModeId(variable.collectionId)
+ if (variable.name === base.name) api.setVariableValue(variable.id, active, 10)
+ if (variable.name === enabled.name) api.setVariableValue(variable.id, active, false)
+ }
+ }
+})
+
+
+test.each([
+ { operator: 'ADDITION', operands: [true, 1] },
+ { operator: 'AND', operands: [1, false] },
+ { operator: 'NEGATE', operands: [1, 2] }
+] as const)('FIG export rejects invalid formula operands instead of coercing them: %j', async (value) => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ graph.createVariable('invalid', 'FLOAT', collection.id, {
+ expression: 'FORMULA', type: 'FLOAT', value: { ...value, operands: [...value.operands] }
+ })
+ await expect(exportFigFile(graph)).rejects.toThrow()
+})
diff --git a/packages/core/tests/openpencil-api/formula.test.ts b/packages/core/tests/openpencil-api/formula.test.ts
new file mode 100644
index 000000000..36ea44369
--- /dev/null
+++ b/packages/core/tests/openpencil-api/formula.test.ts
@@ -0,0 +1,48 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { compileScript } from '@open-pencil/core/tools'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+test('AI scripts author formulas through the same validation as the inspector', async () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const gap = graph.createVariable('gap', 'FLOAT', collection.id, 0)
+ graph.createVariable('enabled', 'BOOLEAN', collection.id, true)
+ const visible = graph.createVariable('visible', 'BOOLEAN', collection.id, false)
+ const figma = new FigmaAPI(graph)
+ const result = await compileScript(`
+ return [
+ openpencil.setVariableFormula('Tokens', 'gap', '{base} * 2'),
+ openpencil.setVariableFormula('Tokens', 'visible', 'not {enabled}'),
+ openpencil.setVariableFormula('Tokens', 'visible', '{gap} > 6 and {enabled}')
+ ]
+ `)(figma)
+ expect(result).toEqual([8, false, true])
+ expect(graph.resolveVariable(gap.id)).toBe(8)
+ expect(graph.resolveVariable(visible.id)).toBe(true)
+ await expect(
+ compileScript(`openpencil.setVariableFormula('Tokens', 'gap', '1 / 0')`)(figma)
+ ).rejects.toThrow()
+ expect(graph.resolveVariable(gap.id)).toBe(8)
+})
+
+test('a mode’s CSS expression outlives a script formula and records a script number', async () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const gap = graph.createVariable('gap', 'FLOAT', collection.id, 16)
+ graph.addMode(collection.id, 'large', 'Large')
+ gap.valuesByMode.large = 32
+ const mode = collection.defaultModeId
+ gap.expressions = {
+ [mode]: { css: '1rem', resolved: 16 },
+ large: { css: '2rem', resolved: 32 }
+ }
+ const figma = new FigmaAPI(graph)
+ await compileScript(`openpencil.setVariableFormula('Tokens', 'gap', '{base} * 4')`)(figma)
+ expect(gap.expressions).toEqual({ [mode]: { css: '1rem' }, large: { css: '2rem', resolved: 32 } })
+ figma.setVariableValue(gap.id, 'large', 40)
+ expect(gap.expressions).toEqual({ [mode]: { css: '1rem' }, large: { css: '2rem', resolved: 40 } })
+})
diff --git a/packages/core/tests/rpc/variables-command.test.ts b/packages/core/tests/rpc/variables-command.test.ts
index a0f9f8b12..297c39a5b 100644
--- a/packages/core/tests/rpc/variables-command.test.ts
+++ b/packages/core/tests/rpc/variables-command.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, test } from 'bun:test'
-import { executeRPCCommand, type TokensResult } from '@open-pencil/core/rpc'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { executeRPCCommand, type TokensResult, type VariablesResult } from '@open-pencil/core/rpc'
+import { parseVariableFormula, SceneGraph } from '@open-pencil/scene-graph'
function graphWithTokens(): SceneGraph {
const graph = new SceneGraph()
@@ -40,3 +40,22 @@ describe('tokens command', () => {
)
})
})
+
+describe('variables command', () => {
+ test('lists a formula as written, with what it gives', async () => {
+ const graph = graphWithTokens()
+ const gap = [...graph.variables.values()].find((variable) => variable.name === 'Gap')
+ const collection = [...graph.variableCollections.values()][0]
+ if (!gap || !collection) throw new Error('Missing token')
+ const large = graph.createVariable('Large', 'FLOAT', collection.id, 0)
+ large.valuesByMode[collection.defaultModeId] = parseVariableFormula(
+ graph,
+ large.id,
+ collection.defaultModeId,
+ '({Gap} * 2)'
+ ).value
+ const result = (await executeRPCCommand(graph, 'variables', {})) as VariablesResult
+ const values = result.collections.flatMap((entry) => entry.variables)
+ expect(values.find((variable) => variable.name === 'Large')?.value).toBe('{Gap} * 2 = 16')
+ })
+})
diff --git a/packages/docs/development/architecture.md b/packages/docs/development/architecture.md
index 2b3e9a982..c4854c201 100644
--- a/packages/docs/development/architecture.md
+++ b/packages/docs/development/architecture.md
@@ -52,6 +52,14 @@ The graph emits typed events via nanoevents: `node:created`, `node:updated`, `no
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.
+
+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.
+
+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.
+
### Layout Engine (Yoga WASM)
Meta's Yoga provides CSS flexbox and grid layout computation via a [fork](https://github.com/open-pencil/yoga/tree/grid) with CSS Grid support. A thin adapter maps Figma property names to Yoga equivalents:
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index f80fc16ce..5a63c83a9 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -26,6 +26,17 @@ 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.
+
+```js
+openpencil.setVariableFormula('Spacing', 'large', '{base} * 2')
+openpencil.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')
+```
+
+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.
+
## Query nodes
```sh
diff --git a/packages/docs/user-guide/variables.md b/packages/docs/user-guide/variables.md
index 1c0c62e35..60d592825 100644
--- a/packages/docs/user-guide/variables.md
+++ b/packages/docs/user-guide/variables.md
@@ -46,6 +46,18 @@ On the canvas, a layer shows a mode when you set the layer to it, whatever the c
## Managing Variables
+### 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.
+
+- 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`.
+- 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.
+
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.
- **Create variable** — click **Create variable** (or **+**) and pick a type; the new variable opens for editing
@@ -62,7 +74,7 @@ Selecting a variable edits:
- **Name** and **CSS name** — leave the CSS name empty to derive it from the name and scopes, such as `--color-brand-primary`. Type the name without its `--`; a name CSS cannot use is flagged and not saved
- **Unit** — for numbers, `px`, `rem`, `%`, `ms`, `s`, `deg`, or none; values are entered in that unit
- **Value** (or **Values**, one per mode) — a color opens the color picker. The variable button next to a value points it at another variable of the same type, an alias that follows that variable; **Detach variable** turns it back into the value it showed
-- **CSS expression** — for numbers, a value such as `clamp(1rem, 4vw, 1.5rem)` written instead of the number in CSS, while the canvas keeps drawing the number
+- **CSS expression** — for numbers, choose **Add CSS expression** in a value's **⋯** menu to write CSS such as `clamp(1rem, 4vw, var(--spacing-md))` instead of the value, while the canvas keeps drawing the value. Token names complete as `var(--name)` and show as pills, the variable button inserts one, and an unclosed function, an unknown token or a value the token's unit does not take is reported when you leave the field. The expression stays when the value changes between a number, a variable and a formula; remove it from the same menu
- **Scopes** — which properties the variable is offered for
- **Description**
- **Hide from publishing** — files that use this one as a library do not see the variable
diff --git a/packages/dom-css/src/tokens/expression.ts b/packages/dom-css/src/tokens/expression.ts
new file mode 100644
index 000000000..ca499d694
--- /dev/null
+++ b/packages/dom-css/src/tokens/expression.ts
@@ -0,0 +1,128 @@
+import valueParser, { type Node } from 'postcss-value-parser'
+
+import type { TokenUnit } from '@open-pencil/scene-graph'
+
+import { parseCSSName } from './names'
+import type { TokenValidator } from './validate'
+import { TOKEN_UNIT_PROPERTY } from './values'
+
+/**
+ * What a piece of a CSS value is. A finished `var(--name)` is one `reference`; while it is typed
+ * it reads as a `function`, a `paren` and a `property`, the custom property name.
+ */
+export type CSSValueTokenKind =
+ | 'reference'
+ | 'property'
+ | 'function'
+ | 'paren'
+ | 'number'
+ | 'operator'
+ | 'separator'
+ | 'string'
+ | 'keyword'
+
+export interface CSSValueToken {
+ kind: CSSValueTokenKind
+ text: string
+ from: number
+ to: number
+}
+
+const OPERATORS = new Set(['+', '-', '*', '/'])
+
+/** `var(--name)` with nothing else inside, which an editor can show as the variable it names. */
+function isReference(node: valueParser.FunctionNode) {
+ if (node.value !== 'var' || node.unclosed || node.nodes.length !== 1) return false
+ const [argument] = node.nodes
+ return argument.type === 'word' && argument.value.startsWith('--')
+}
+
+function wordKind(word: string): CSSValueTokenKind {
+ if (word.startsWith('--')) return 'property'
+ if (OPERATORS.has(word)) return 'operator'
+ return valueParser.unit(word) ? 'number' : 'keyword'
+}
+
+/**
+ * The tokens of one CSS value, such as `clamp(1rem, 4vw, var(--space-md))`, in order and with
+ * their source ranges. Reading tolerates half-typed values: an unclosed function still gives
+ * its name and its `(`.
+ */
+export function cssValueTokens(source: string): CSSValueToken[] {
+ const tokens: CSSValueToken[] = []
+ const push = (kind: CSSValueTokenKind, from: number, to: number) =>
+ tokens.push({ kind, text: source.slice(from, to), from, to })
+ const walk = (nodes: Node[]) => {
+ for (const node of nodes) {
+ if (node.type === 'function') {
+ if (isReference(node)) {
+ push('reference', node.sourceIndex, node.sourceEndIndex)
+ continue
+ }
+ const open = node.sourceIndex + node.value.length
+ if (node.value) push('function', node.sourceIndex, open)
+ push('paren', open, open + 1)
+ walk(node.nodes)
+ if (!node.unclosed) push('paren', node.sourceEndIndex - 1, node.sourceEndIndex)
+ } else if (node.type === 'word') {
+ push(wordKind(node.value), node.sourceIndex, node.sourceEndIndex)
+ } else if (node.type === 'div') {
+ push(node.value === '/' ? 'operator' : 'separator', node.sourceIndex, node.sourceEndIndex)
+ } else if (node.type === 'string') {
+ push('string', node.sourceIndex, node.sourceEndIndex)
+ }
+ }
+ }
+ walk(valueParser(source).nodes)
+ return tokens
+}
+
+/** The custom property a token names, in `var(--name)` or as a bare `--name`. */
+export function cssTokenProperty(token: CSSValueToken): string | undefined {
+ if (token.kind !== 'reference' && token.kind !== 'property') return undefined
+ const name = parseCSSName(token.text)
+ return name ? `--${name}` : undefined
+}
+
+function hasUnclosedFunction(nodes: Node[]): boolean {
+ return nodes.some(
+ (node) => node.type === 'function' && (node.unclosed || hasUnclosedFunction(node.nodes))
+ )
+}
+
+export type CSSExpressionProblem =
+ | { kind: 'unclosed' }
+ | { kind: 'syntax' }
+ | { kind: 'negated-reference'; property: string }
+ | { kind: 'unknown-token'; name: string }
+ | { kind: 'invalid'; property: string }
+
+/**
+ * Why a CSS expression cannot stand in for a token, if it cannot. The token validator checks it
+ * is one declaration; then it must name only tokens that exist and suit the token's unit, which
+ * `supports` checks where a browser can type values. A value holding `var()` passes that last
+ * check until it is used, so only its names are checked.
+ */
+export function cssExpressionProblem(
+ css: string,
+ unit: TokenUnit,
+ tokens: ReadonlySet<string>,
+ validator: TokenValidator,
+ supports?: (property: string, value: string) => boolean
+): CSSExpressionProblem | undefined {
+ if (!validator.declaration('token', css))
+ return hasUnclosedFunction(valueParser(css).nodes) ? { kind: 'unclosed' } : { kind: 'syntax' }
+ const parsed = cssValueTokens(css)
+ // `-var(--x)` reads as a function named `-var`: CSS negates a value only inside calc().
+ const negated = parsed.findIndex((token) => token.kind === 'function' && token.text === '-var')
+ if (negated !== -1) {
+ const property = parsed.slice(negated).map(cssTokenProperty).find(Boolean)
+ if (property) return { kind: 'negated-reference', property }
+ }
+ for (const token of parsed) {
+ const name = cssTokenProperty(token)
+ if (name && !tokens.has(name)) return { kind: 'unknown-token', name }
+ }
+ const property = TOKEN_UNIT_PROPERTY[unit]
+ return !supports || supports(property, css) ? undefined : { kind: 'invalid', property }
+}
diff --git a/packages/dom-css/src/tokens/formula.ts b/packages/dom-css/src/tokens/formula.ts
new file mode 100644
index 000000000..ec505386f
--- /dev/null
+++ b/packages/dom-css/src/tokens/formula.ts
@@ -0,0 +1,131 @@
+import type { Variable, VariableFormulaNode } from '@open-pencil/scene-graph'
+
+import { tokenNumberToCSS, variableUnit } from './values'
+
+/**
+ * A number formula as `calc()`, with each reference a `var()`. CSS adds only like with like and
+ * multiplies a length only by a plain number, so a literal takes the unit of what it is added
+ * to, and a formula CSS cannot type, such as a length times a length, has no CSS form.
+ */
+type Term =
+ | { kind: 'literal'; value: number }
+ | { kind: 'css'; text: string; precedence: number; dimension: boolean }
+
+const OPERATORS = {
+ ADDITION: { symbol: '+', precedence: 1 },
+ SUBTRACTION: { symbol: '-', precedence: 1 },
+ MULTIPLY: { symbol: '*', precedence: 2 },
+ DIVIDE: { symbol: '/', precedence: 2 }
+} as const
+type Arithmetic = keyof typeof OPERATORS
+const ATOM = 3
+
+class UnsupportedFormulaError extends Error {
+ override name = 'UnsupportedFormulaError'
+}
+
+interface FormulaContext {
+ variables: ReadonlyMap<string, Variable>
+ names: ReadonlyMap<string, string>
+ /** A literal written as a length, in the exported token's unit. */
+ length: (value: number) => string
+}
+
+export function formulaToCSS(
+ node: VariableFormulaNode,
+ variable: Variable,
+ variables: ReadonlyMap<string, Variable>,
+ names: ReadonlyMap<string, string>
+): string | { issue: string } {
+ const unit = variableUnit(variable)
+ const context = { variables, names, length: (value: number) => tokenNumberToCSS(value, unit) }
+ try {
+ const result = convert(node, context)
+ const dimension = unit !== 'none'
+ if (result.kind === 'literal') return write(result, dimension, context)
+ if (result.dimension !== dimension)
+ return { issue: dimension ? 'has a formula without a unit' : 'has a formula with a unit' }
+ return `calc(${result.text})`
+ } catch (error) {
+ if (error instanceof UnsupportedFormulaError) return { issue: error.message }
+ throw error
+ }
+}
+
+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)
+}
+
+function reference(id: string, { variables, names }: FormulaContext): Term {
+ const target = variables.get(id)
+ const name = names.get(id)
+ if (!target || !name)
+ throw new UnsupportedFormulaError('refers to a variable that does not exist')
+ const dimension = variableUnit(target) !== 'none'
+ return { kind: 'css', text: `var(--${name})`, precedence: ATOM, dimension }
+}
+
+function negate(term: Term, context: FormulaContext): Term {
+ if (term.kind === 'literal') return { kind: 'literal', value: -term.value }
+ const text = `-1 * ${grouped(term, false, OPERATORS.MULTIPLY.precedence, context)}`
+ return { kind: 'css', text, precedence: OPERATORS.MULTIPLY.precedence, dimension: term.dimension }
+}
+
+function binary(operator: Arithmetic, a: Term, b: Term, context: FormulaContext): Term {
+ const { symbol, precedence } = OPERATORS[operator]
+ // The right side of - and / keeps its parentheses even at equal precedence.
+ const rightBelow =
+ operator === 'SUBTRACTION' || operator === 'DIVIDE' ? precedence + 1 : precedence
+ const aDimension = a.kind === 'css' && a.dimension
+ const bDimension = b.kind === 'css' && b.dimension
+ if (precedence === 1) {
+ if (a.kind === 'css' && b.kind === 'css' && aDimension !== bDimension)
+ throw new UnsupportedFormulaError('adds a length to a plain number')
+ const dimension = aDimension || bDimension
+ const left = grouped(a, dimension, precedence, context)
+ const right = grouped(b, dimension, rightBelow, context)
+ return { kind: 'css', text: `${left} ${symbol} ${right}`, precedence, dimension }
+ }
+ if (bDimension && operator === 'DIVIDE') throw new UnsupportedFormulaError('divides by a length')
+ if (aDimension && bDimension) throw new UnsupportedFormulaError('multiplies two lengths')
+ const left = grouped(a, false, precedence, context)
+ const right = grouped(b, false, rightBelow, context)
+ return {
+ kind: 'css',
+ text: `${left} ${symbol} ${right}`,
+ precedence,
+ dimension: aDimension || bDimension
+ }
+}
+
+function write(term: Term, dimension: boolean, context: FormulaContext) {
+ if (term.kind === 'css') return term.text
+ return dimension ? context.length(term.value) : String(Number(term.value.toFixed(6)))
+}
+
+function grouped(term: Term, dimension: boolean, below: number, context: FormulaContext) {
+ return term.kind === 'css' && term.precedence < below
+ ? `(${term.text})`
+ : write(term, dimension, context)
+}
+
+function isArithmetic(operator: string): operator is Arithmetic {
+ return Object.hasOwn(OPERATORS, operator)
+}
+
+function fold(operator: Arithmetic, a: number, b: number) {
+ if (operator === 'ADDITION') return a + b
+ if (operator === 'SUBTRACTION') return a - b
+ if (operator === 'MULTIPLY') return a * b
+ return a / b
+}
diff --git a/packages/dom-css/src/tokens/index.ts b/packages/dom-css/src/tokens/index.ts
index 93969ab3e..d290dd44d 100644
--- a/packages/dom-css/src/tokens/index.ts
+++ b/packages/dom-css/src/tokens/index.ts
@@ -1,5 +1,13 @@
// Design tokens as CSS custom properties: names, namespaces, units, and the stylesheet.
export { featureConditionCSS, parseFeatureCondition, type FeatureCondition } from './conditions'
+export {
+ cssExpressionProblem,
+ cssTokenProperty,
+ cssValueTokens,
+ type CSSExpressionProblem,
+ type CSSValueToken,
+ type CSSValueTokenKind
+} from './expression'
export {
collectionVariables,
cssNameCodeSyntax,
@@ -23,4 +31,4 @@ export {
type TokenStylesheetOptions
} from './stylesheet'
export { createTokenValidator, type TokenValidator } from './validate'
-export { tokenNumberToCSS, variableUnit } from './values'
+export { TOKEN_UNIT_PROPERTY, tokenNumberToCSS, variableUnit } from './values'
diff --git a/packages/dom-css/src/tokens/stylesheet.ts b/packages/dom-css/src/tokens/stylesheet.ts
index 9f4f0a4ab..c41d4a75d 100644
--- a/packages/dom-css/src/tokens/stylesheet.ts
+++ b/packages/dom-css/src/tokens/stylesheet.ts
@@ -1,12 +1,14 @@
-import type {
- SceneGraph,
- Variable,
- VariableCollection,
- VariableCollectionMode,
- VariableValue
+import {
+ variableValueReferences,
+ type SceneGraph,
+ type Variable,
+ type VariableCollection,
+ type VariableCollectionMode,
+ type VariableValue
} from '@open-pencil/scene-graph'
import { cssColor } from '../export/css'
+import { formulaToCSS } from './formula'
import { collectionVariables, tokenSlug, variableCSSNames, variableNamespace } from './names'
import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
import { tokenNumberToCSS, variableUnit } from './values'
@@ -100,11 +102,18 @@ function modeValue(
variable: Variable,
value: VariableValue | undefined,
modeId: string,
- names: ReadonlyMap<string, string>
+ names: ReadonlyMap<string, string>,
+ variables: ReadonlyMap<string, Variable>
): string | { issue: string } {
const expression = variable.expressions?.[modeId]
if (expression) return expression.css
if (value === undefined) return { issue: 'has no value in this mode' }
+ if (typeof value === 'object' && 'expression' in value) {
+ if (value.expression === 'FORMULA' && variable.type === 'FLOAT')
+ return formulaToCSS(value.value, variable, variables, names)
+ if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }
+ return { issue: 'uses an expression that CSS token export does not support' }
+ }
if (typeof value === 'object' && 'aliasId' in value) {
const target = names.get(value.aliasId)
return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }
@@ -118,10 +127,6 @@ function modeValue(
return { issue: 'has a value that does not match its type' }
}
-function aliasTarget(value: VariableValue | undefined): string | undefined {
- return typeof value === 'object' && 'aliasId' in value ? value.aliasId : undefined
-}
-
function block(selector: string, declarations: Declaration[], indent = ''): string {
const body = declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join('\n')
return `${indent}${selector} {\n${body}\n${indent}}`
@@ -154,7 +159,8 @@ function variantNames(scopes: ModeScope[]): string[] {
* Variables as a stylesheet of custom properties. The default mode of every collection is the
* base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;
* every other mode overrides the values that differ, under its condition. Aliases stay `var()`
- * references and are declared again in each mode that changes what they point to.
+ * references, and number formulas `calc()` over them; both are declared again in each mode that
+ * changes what they point to.
*/
export function buildTokenStylesheet(
source: TokenSource,
@@ -175,7 +181,7 @@ export function buildTokenStylesheet(
value: VariableValue | undefined
): Declaration | undefined {
const name = names.get(variable.id) ?? variable.id
- const css = modeValue(variable, value, modeId, names)
+ const css = modeValue(variable, value, modeId, names, source.variables)
if (typeof css !== 'string') {
issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })
return undefined
@@ -205,7 +211,7 @@ export function buildTokenStylesheet(
/**
* What a mode's scope declares: the collection's values that differ from its default, and every
- * alias, in any collection, whose chain reaches one of them. Custom properties inherit as
+ * alias or formula, in any collection, whose chain reaches one of them. Custom properties inherit as
* computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue
* unless it is declared again where `--blue` changes.
*/
@@ -230,8 +236,8 @@ export function buildTokenStylesheet(
for (let grew = true; grew;) {
grew = false
for (const variable of variables) {
- const target = aliasTarget(valueIn(variable))
- if (scoped.has(variable.id) || !target || !scoped.has(target)) continue
+ const references = variableValueReferences(valueIn(variable))
+ if (scoped.has(variable.id) || !references.some((target) => scoped.has(target))) continue
const declaration = inMode.get(variable.id) ?? defaults.get(variable.id)
if (!declaration) continue
scoped.set(variable.id, declaration)
diff --git a/packages/dom-css/src/tokens/values.ts b/packages/dom-css/src/tokens/values.ts
index 547314bb2..0d33fd2a5 100644
--- a/packages/dom-css/src/tokens/values.ts
+++ b/packages/dom-css/src/tokens/values.ts
@@ -9,6 +9,20 @@ import { variableNamespace } from './names'
const UNITLESS_SCOPES = new Set<VariableScope>(['OPACITY', 'FONT_STYLE', 'FONT_VARIATIONS'])
+/**
+ * A property that takes values in each token unit, where a browser checks or computes a CSS
+ * expression written for the token: `scale` takes any plain number, `width` any length.
+ */
+export const TOKEN_UNIT_PROPERTY: Record<TokenUnit, string> = {
+ none: 'scale',
+ px: 'width',
+ rem: 'width',
+ '%': 'width',
+ ms: 'transition-duration',
+ s: 'transition-duration',
+ deg: 'rotate'
+}
+
/**
* The unit a FLOAT token is written in. An explicit unit wins; opacity and font weights are
* unitless; every other number is a pixel length, which is what the canvas draws.
diff --git a/packages/dom-css/tests/tokens/expression.test.ts b/packages/dom-css/tests/tokens/expression.test.ts
new file mode 100644
index 000000000..84dc26e8e
--- /dev/null
+++ b/packages/dom-css/tests/tokens/expression.test.ts
@@ -0,0 +1,80 @@
+import { expect, test } from 'bun:test'
+
+import { tokenValidator } from '#dom-css/tokens/cssom-validator'
+import { cssExpressionProblem, cssTokenProperty, cssValueTokens } from '#dom-css/tokens/expression'
+
+const kinds = (source: string) =>
+ cssValueTokens(source).map(({ kind, text }) => `${kind}:${text.trim()}`)
+
+test('a finished var() is one reference token; math reads as functions, numbers and operators', () => {
+ expect(kinds('clamp(1rem, 4vw, var(--space-md))')).toEqual([
+ 'function:clamp',
+ 'paren:(',
+ 'number:1rem',
+ 'separator:,',
+ 'number:4vw',
+ 'separator:,',
+ 'reference:var(--space-md)',
+ 'paren:)'
+ ])
+ expect(kinds('calc(var(--a) * 2 / 3)')).toEqual([
+ 'function:calc',
+ 'paren:(',
+ 'reference:var(--a)',
+ 'operator:*',
+ 'number:2',
+ 'operator:/',
+ 'number:3',
+ 'paren:)'
+ ])
+ const [reference] = cssValueTokens('var( --space-md )')
+ expect(reference && cssTokenProperty(reference)).toBe('--space-md')
+})
+
+test('half-typed values still give the tokens completion needs', () => {
+ expect(kinds('var(--sp')).toEqual(['function:var', 'paren:(', 'property:--sp'])
+ expect(kinds('clamp(1rem, var(')).toEqual([
+ 'function:clamp',
+ 'paren:(',
+ 'number:1rem',
+ 'separator:,',
+ 'function:var',
+ 'paren:('
+ ])
+ // A var() with a fallback is not a plain reference, so it stays editable text.
+ expect(kinds('var(--a, 4px)')).toEqual([
+ 'function:var',
+ 'paren:(',
+ 'property:--a',
+ 'separator:,',
+ 'number:4px',
+ 'paren:)'
+ ])
+})
+
+const tokens = new Set(['--space-md'])
+const problem = (css: string, unit: 'px' | 'none' = 'px') =>
+ cssExpressionProblem(css, unit, tokens, tokenValidator, supports)
+/** A stand-in for CSS.supports: lengths and numbers, and anything holding var(). */
+const supports = (property: string, value: string) =>
+ value.includes('var(') ||
+ (property === 'width' ? /^(clamp|calc)\(|^\d+(px|rem|vw)$/.test(value) : /^\d+$/.test(value))
+
+test('a CSS expression must be one well-formed value naming tokens that exist', () => {
+ expect(problem('clamp(1rem, 4vw, var(--space-md))')).toBeUndefined()
+ expect(problem('var(--space-md, 4px)')).toBeUndefined()
+ expect(problem('clamp(1rem, 4vw')).toEqual({ kind: 'unclosed' })
+ expect(problem('4px; color: red')).toEqual({ kind: 'syntax' })
+ expect(problem('calc(var(--missing) * 2)')).toEqual({ kind: 'unknown-token', name: '--missing' })
+ expect(problem('-var(--space-md)')).toEqual({
+ kind: 'negated-reference',
+ property: '--space-md'
+ })
+})
+
+test('a CSS expression must suit the property its unit stands for', () => {
+ expect(problem('4 apples')).toEqual({ kind: 'invalid', property: 'width' })
+ expect(problem('4px', 'none')).toEqual({ kind: 'invalid', property: 'scale' })
+ // Without a property check, as in the CLI, only the shape of the value is checked.
+ expect(cssExpressionProblem('4 apples', 'px', tokens, tokenValidator)).toBeUndefined()
+})
diff --git a/packages/dom-css/tests/tokens/formula.test.ts b/packages/dom-css/tests/tokens/formula.test.ts
new file mode 100644
index 000000000..9f1ca7336
--- /dev/null
+++ b/packages/dom-css/tests/tokens/formula.test.ts
@@ -0,0 +1,60 @@
+import { expect, test } from 'bun:test'
+
+import { tokenStylesheet } from '@open-pencil/dom-css/export'
+import { parseVariableFormula, SceneGraph } from '@open-pencil/scene-graph'
+
+function spacing() {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Spacing')
+ const mode = collection.defaultModeId
+ const base = graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const set = (name: string, source: string, unit?: 'none') => {
+ const variable = graph.createVariable(name, 'FLOAT', collection.id, 0)
+ if (unit) variable.unit = unit
+ variable.valuesByMode[mode] = parseVariableFormula(graph, variable.id, mode, source).value
+ return variable
+ }
+ return { graph, collection, base, set }
+}
+
+test('number formulas become calc() over var() with units on added literals', async () => {
+ const { graph, set } = spacing()
+ set('large', '{base} * 4')
+ set('inset', '({base} + 2) * 2 - -{base}')
+ set('half', '{base} / 2 + 1')
+ set('folded', '2 * 3')
+ const { css, issues } = await tokenStylesheet(graph, { format: 'css' })
+ expect(issues).toEqual([])
+ expect(css).toContain('--large: calc(var(--base) * 4);')
+ expect(css).toContain('--inset: calc((var(--base) + 2px) * 2 - -1 * var(--base));')
+ expect(css).toContain('--half: calc(var(--base) / 2 + 1px);')
+ expect(css).toContain('--folded: 6px;')
+})
+
+test('formulas CSS cannot type are reported instead of written', async () => {
+ const { graph, set } = spacing()
+ set('area', '{base} * {base}')
+ set('ratio', '{base} / {base}')
+ set('scale', '{base} * 2', 'none')
+ const { css, issues } = await tokenStylesheet(graph, { format: 'css' })
+ expect(css).not.toContain('--area')
+ expect(css).not.toContain('--ratio')
+ expect(css).not.toContain('--scale')
+ expect(issues.map((issue) => issue.message)).toEqual([
+ 'area multiplies two lengths',
+ 'ratio divides by a length',
+ 'scale has a formula with a unit'
+ ])
+})
+
+test('a formula is declared again in each mode that changes a variable it uses', async () => {
+ const { graph, collection, base, set } = spacing()
+ graph.addMode(collection.id, 'compact', 'Compact')
+ base.valuesByMode.compact = 2
+ const large = set('large', '{base} * 4')
+ large.valuesByMode.compact = large.valuesByMode[collection.defaultModeId]
+ const { css } = await tokenStylesheet(graph, { format: 'css' })
+ const scoped = css.slice(css.indexOf('Spacing: Compact'))
+ expect(scoped).toContain('--base: 2px;')
+ expect(scoped).toContain('--large: calc(var(--base) * 4);')
+})
diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts
index 279543516..e0e59b770 100644
--- a/packages/fig/src/document/variables.ts
+++ b/packages/fig/src/document/variables.ts
@@ -1,6 +1,17 @@
-import type { NodeChange, VariableDataValuesEntry } from '@open-pencil/kiwi/fig/codec'
+import * as v from 'valibot'
+
+import type { NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'
+import {
+ VARIABLE_FORMULA_OPERATORS,
+ variableFormulaSchema,
+ variableColorExpressionSchema,
+ formulaResultType,
+ MAX_FORMULA_DEPTH,
+ type SceneGraph,
+ type VariableValue,
+ type VariableColorExpression
+} from '@open-pencil/scene-graph'
import { extractPluginData } from '../node-change/plugin-data'
import { readVariableMetadata } from '../node-change/variable/metadata'
@@ -13,10 +24,12 @@ import {
import { createResourceResolver } from './resource-reference'
function valueOf(
- entry: VariableDataValuesEntry,
- resolve: ReturnType<typeof createResourceResolver>
+ entry: VariableDataEntry,
+ resolve: ReturnType<typeof createResourceResolver>,
+ depth = 0
): VariableValue {
- const { value, dataType, resolvedDataType } = entry.variableData
+ if (depth > MAX_FORMULA_DEPTH) throw new Error('Variable expression is too deeply nested')
+ const { value, dataType, resolvedDataType } = entry
if (!value) throw new Error('Missing variable value')
const type = dataType ?? resolvedDataType
if (type === 'ALIAS') {
@@ -28,9 +41,55 @@ function valueOf(
if (type === 'BOOLEAN' && value.boolValue !== undefined) return value.boolValue
if (type === 'STRING' && value.textValue !== undefined) return value.textValue
if (type === 'FLOAT' && value.floatValue !== undefined) return value.floatValue
+ if (type === 'EXPRESSION') return expressionValue(entry, resolve, depth)
throw new Error(`Unsupported variable value ${type}`)
}
+function expressionValue(
+ entry: VariableDataEntry,
+ resolve: ReturnType<typeof createResourceResolver>,
+ depth: number
+): VariableValue {
+ const value = entry.value
+ if (!value) throw new Error('Missing expression')
+ if (value.expressionValue?.expressionFunction === 'COMPOSE_COLOR')
+ return colorExpression(entry, resolve)
+ const expression = value.expressionValue
+ const operator = v.parse(v.picklist(VARIABLE_FORMULA_OPERATORS), expression?.expressionFunction)
+ 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
+ })
+ return v.parse(variableFormulaSchema, {
+ expression: 'FORMULA',
+ type,
+ value: { operator, operands }
+ })
+}
+
+function colorExpression(
+ entry: VariableDataEntry,
+ resolve: ReturnType<typeof createResourceResolver>
+): VariableColorExpression {
+ const expression = entry.value?.expressionValue
+ const args = expression?.expressionArguments
+ if (expression?.expressionFunction !== 'COMPOSE_COLOR' || args?.length !== 2)
+ throw new Error(`Unsupported variable expression ${expression?.expressionFunction}`)
+ // Only literal or alias operands are supported; other functions must not be flattened.
+ if (args.some((arg) => arg.dataType === 'EXPRESSION'))
+ throw new Error('Unsupported nested color expression')
+ const color = valueOf(args[0], resolve)
+ const opacity = valueOf(args[1], resolve)
+ return v.parse(variableColorExpressionSchema, { expression: 'COMPOSE_COLOR', color, opacity })
+}
+
function modeValues(
resource: NodeChange,
modes: readonly string[],
@@ -42,7 +101,15 @@ function modeValues(
for (const entry of entries) {
const modeId = guidToString(entry.modeID)
if (!modes.includes(modeId)) throw new Error('Unknown mode')
- values[modeId] = valueOf(entry, resolve)
+ const value = valueOf(entry.variableData, resolve)
+ if (
+ typeof value === 'object' &&
+ 'expression' in value &&
+ value.expression === 'FORMULA' &&
+ value.type !== resource.variableResolvedType
+ )
+ throw new Error(`Expression result type does not match ${resource.variableResolvedType}`)
+ values[modeId] = value
}
return values
}
diff --git a/packages/fig/src/node-change/variable/token.ts b/packages/fig/src/node-change/variable/token.ts
index a009f6f38..3276a343a 100644
--- a/packages/fig/src/node-change/variable/token.ts
+++ b/packages/fig/src/node-change/variable/token.ts
@@ -28,22 +28,25 @@ function nonEmpty<T extends object>(record: T): T | undefined {
}
/** `.fig` stores numbers as float32, so compare at that precision, not the plugin data's double. */
-function sameNumber(a: VariableValue | undefined, b: number): boolean {
- return typeof a === 'number' && Math.fround(a) === Math.fround(b)
+function sameNumber(a: number, b: number | undefined): boolean {
+ return b !== undefined && Math.fround(a) === Math.fround(b)
}
/**
- * The stored number stays authoritative: an expression whose mode value was edited elsewhere,
- * Figma included, no longer describes that value and is dropped rather than overriding it.
+ * The stored number stays authoritative: an expression whose plain number was edited elsewhere,
+ * Figma included, no longer describes that value and is dropped rather than overriding it. One
+ * written over a formula or a reference has no number to check and stays.
*/
export function readVariableToken(
nc: NodeChange,
valuesByMode: Record<string, VariableValue>
): TokenFields {
const stored = readNodeChangePluginData(nc, token) ?? {}
- const expressions = Object.entries(stored.expressions ?? {}).filter(([mode, expression]) =>
- sameNumber(valuesByMode[mode], expression.resolved)
- )
+ const expressions = Object.entries(stored.expressions ?? {}).filter(([mode, expression]) => {
+ if (!Object.hasOwn(valuesByMode, mode)) return false
+ const value = valuesByMode[mode]
+ return typeof value === 'number' ? sameNumber(value, expression.resolved) : true
+ })
return { unit: stored.unit, expressions: nonEmpty(Object.fromEntries(expressions)) }
}
diff --git a/packages/fig/tests/document/variables.test.ts b/packages/fig/tests/document/variables.test.ts
new file mode 100644
index 000000000..437085471
--- /dev/null
+++ b/packages/fig/tests/document/variables.test.ts
@@ -0,0 +1,62 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument } from '#fig/document/materialize'
+
+import type { NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
+
+function resources(operand: VariableDataEntry): NodeChange[] {
+ return [
+ { guid: guid(3), type: 'VARIABLE_SET', variableSetModes: [{ id: guid(10), name: 'Default' }] },
+ {
+ guid: guid(4),
+ type: 'VARIABLE',
+ variableResolvedType: 'FLOAT',
+ variableSetID: { guid: guid(3) },
+ variableDataValues: {
+ entries: [
+ {
+ modeID: guid(10),
+ variableData: {
+ dataType: 'EXPRESSION',
+ resolvedDataType: 'FLOAT',
+ value: {
+ expressionValue: {
+ expressionFunction: 'ADDITION',
+ expressionArguments: [operand, { dataType: 'FLOAT', value: { floatValue: 2 } }]
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+}
+
+test('FIG formulas preserve valid operands and report incompatible definitions without coercion', () => {
+ const { graph } = materializeDocument(resources({ dataType: 'FLOAT', value: { floatValue: 3 } }))
+ expect(graph.resolveVariable('1:4')).toBe(5)
+ const operands: VariableDataEntry[] = [
+ { dataType: 'BOOLEAN', value: { boolValue: true } },
+ { dataType: 'FLOAT', value: { floatValue: Infinity } },
+ {
+ dataType: 'EXPRESSION',
+ resolvedDataType: 'BOOLEAN',
+ value: {
+ expressionValue: {
+ expressionFunction: 'NOT',
+ expressionArguments: [{ dataType: 'BOOLEAN', value: { boolValue: false } }]
+ }
+ }
+ }
+ ]
+ for (const operand of operands) {
+ const reported: NodeChange[] = []
+ const { graph: invalid } = materializeDocument(resources(operand), [], {
+ onUnsupportedResource: (node) => reported.push(node)
+ })
+ expect(invalid.variables.size).toBe(0)
+ expect(reported).toEqual([resources(operand)[1]])
+ }
+})
diff --git a/packages/fig/tests/node-change/variable-token.test.ts b/packages/fig/tests/node-change/variable-token.test.ts
index 50afd6fd0..fab0d4803 100644
--- a/packages/fig/tests/node-change/variable-token.test.ts
+++ b/packages/fig/tests/node-change/variable-token.test.ts
@@ -58,4 +58,29 @@ describe('token plugin data', () => {
a: { css: 'calc(100vw / 3)', resolved: 1234.567 }
})
})
+
+ test('keep an expression written over a formula or reference, which has no number to check', () => {
+ const nc = record(
+ OPEN_PENCIL_PLUGIN_DATA.token.key,
+ JSON.stringify({
+ expressions: {
+ formula: { css: 'clamp(1rem, 4vw, 2rem)' },
+ alias: { css: 'calc(100vw / 3)' },
+ edited: { css: 'clamp(1rem, 4vw, 2rem)' }
+ }
+ })
+ )
+ const formula = {
+ expression: 'FORMULA' as const,
+ type: 'FLOAT' as const,
+ value: { operator: 'MULTIPLY' as const, operands: [{ aliasId: '1:2' }, 2] }
+ }
+ // A number now where no number was recorded was edited elsewhere: the expression goes.
+ expect(
+ readVariableToken(nc, { formula, alias: { aliasId: '1:2' }, edited: 12 }).expressions
+ ).toEqual({
+ formula: { css: 'clamp(1rem, 4vw, 2rem)' },
+ alias: { css: 'calc(100vw / 3)' }
+ })
+ })
})
diff --git a/packages/kiwi/src/fig/schema/fig.kiwi b/packages/kiwi/src/fig/schema/fig.kiwi
index 356742aa0..db045910c 100644
--- a/packages/kiwi/src/fig/schema/fig.kiwi
+++ b/packages/kiwi/src/fig/schema/fig.kiwi
@@ -4479,6 +4479,7 @@ enum ExpressionFunction {
NEGATE = 17;
IS_TRUTHY = 18;
KEYFRAME = 19;
+ COMPOSE_COLOR = 20;
}
message Expression {
diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.md
index 1424956f9..fbbb1420f 100644
--- a/packages/scene-graph/AGENTS.md
+++ b/packages/scene-graph/AGENTS.md
@@ -27,3 +27,5 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice
- Export named types and primitives (`Color`, `Vector`, `Rect`, `SceneNode`, `Effect`, `Fill`, `Stroke`) from the public entry; downstream packages reuse them instead of respelling shapes.
- A paint's `gradientTransform` follows Figma's convention, mapping the layer's unit square onto gradient space; read, build, and invert it only through `@open-pencil/scene-graph/gradient`, which renderers, handles, exporters, importers, and tools all share (`packages/scene-graph/tests/gradient.test.ts`, `tests/engine/render/canvas/gradient.test.ts`).
- `Stroke` extends `Fill`, so a stroke is a paint plus its geometry; add a paint field to `Fill` and both get it, and copy it in `copyFill`, which `copyStroke` reuses (`packages/scene-graph/src/copy.ts`).
+
+- Variable expression schemas, evaluation, mode resolution, and reference traversal belong in `src/variables/`; draft validation uses the same resolver with an override, while Core owns edit history and layout (`tests/variables/formula.test.ts`).
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 9ca7f7873..d980b2749 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -4,6 +4,10 @@ export * from './variables/bindings'
export type { VariableModeFallback } from './variables'
export { modesDefaultFirst } from './variables'
export * from './variables/token'
+export * from './variables/value'
+export * from './variables/formula'
+export * from './variables/formula/schema'
+export * from './variables/schema'
export * from './plugin-data/field'
export * from './plugin-data/fields'
export { rescaleNodeTree, scaleNodeChanges } from './scaling'
@@ -141,7 +145,8 @@ import type {
Variable,
VariableCollection,
VariableType,
- VariableValue
+ VariableValue,
+ VariableLiteral
} from './types'
export {
@@ -369,7 +374,7 @@ export class SceneGraph {
variableId: string,
modeId?: string,
visited?: Set<string>
- ): VariableValue | undefined {
+ ): VariableLiteral | undefined {
return Variables.resolveVariable(this, variableId, modeId, visited)
}
@@ -401,7 +406,7 @@ export class SceneGraph {
nodeId: string,
variableId: string,
fallback?: VariableModeFallback
- ): VariableValue | undefined {
+ ): VariableLiteral | undefined {
return Variables.resolveVariableForNode(this, nodeId, variableId, fallback)
}
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index c0cdc3c77..8f9b6312b 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -104,13 +104,16 @@ const cssText = v.pipe(v.string(), v.trim(), v.nonEmpty(), v.maxLength(1000))
/** Token fields Figma has no slot for, with mode ids as the file spells them. */
export interface StoredToken {
unit?: TokenUnit
- expressions?: Record<string, { css: string; resolved: number }>
+ expressions?: Record<string, { css: string; resolved?: number }>
}
const token: v.GenericSchema<unknown, StoredToken> = v.object({
unit: v.optional(v.picklist(TOKEN_UNITS)),
expressions: v.optional(
- v.record(v.string(), v.object({ css: cssText, resolved: v.pipe(v.number(), v.finite()) }))
+ v.record(
+ v.string(),
+ v.object({ css: cssText, resolved: v.optional(v.pipe(v.number(), v.finite())) })
+ )
)
})
diff --git a/packages/scene-graph/src/transfer/variables.ts b/packages/scene-graph/src/transfer/variables.ts
index 3e97e8b1b..7be7d0032 100644
--- a/packages/scene-graph/src/transfer/variables.ts
+++ b/packages/scene-graph/src/transfer/variables.ts
@@ -1,4 +1,5 @@
import type { Variable, VariableCollection, VariableValue } from '../types'
+import { mapVariableValueReferences } from '../variables/value'
import { requireTransferReference as mapped } from './references'
export interface VariableTransferReferences {
@@ -50,12 +51,8 @@ export function prepareVariableTransfer(
assertUniqueMappings(references.variables, 'variable')
assertUniqueMappings(references.collections, 'collection')
assertUniqueMappings(references.modes, 'mode')
- const value = (input: VariableValue): VariableValue => {
- if (typeof input === 'object' && 'aliasId' in input) {
- return { aliasId: mapped(references.variables, input.aliasId, 'variable alias') }
- }
- return structuredClone(input)
- }
+ const value = (input: VariableValue): VariableValue =>
+ mapVariableValueReferences(input, (id) => mapped(references.variables, id, 'variable alias'))
return {
collections: collections.map((collection) => ({
...structuredClone(collection),
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 7d37131e3..55fb2404c 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -816,7 +816,54 @@ export interface ComponentPropertyDefinition {
}
export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'
-export type VariableValue = Color | number | string | boolean | { aliasId: string }
+export interface VariableAlias {
+ aliasId: string
+}
+
+/** Figma's two-argument color expression; opacity is a percentage, not an alpha multiplier. */
+export interface VariableColorExpression {
+ expression: 'COMPOSE_COLOR'
+ color: Color | VariableAlias
+ opacity: number | VariableAlias
+}
+
+export type VariableLiteral = Color | number | string | boolean
+/** Figma's `ExpressionFunction` names for the arithmetic, comparison and logic a formula uses. */
+export const VARIABLE_FORMULA_OPERATORS = [
+ 'ADDITION',
+ 'SUBTRACTION',
+ 'MULTIPLY',
+ 'DIVIDE',
+ 'NEGATE',
+ 'EQUALS',
+ 'NOT_EQUAL',
+ 'LESS_THAN',
+ 'LESS_THAN_OR_EQUAL',
+ 'GREATER_THAN',
+ 'GREATER_THAN_OR_EQUAL',
+ 'AND',
+ 'OR',
+ 'NOT'
+] as const
+export type VariableFormulaOperator = (typeof VARIABLE_FORMULA_OPERATORS)[number]
+export type VariableFormulaNode =
+ | number
+ | boolean
+ | VariableAlias
+ | {
+ operator: VariableFormulaOperator
+ operands: VariableFormulaNode[]
+ }
+export interface VariableFormula {
+ expression: 'FORMULA'
+ type: 'FLOAT' | 'BOOLEAN'
+ value: VariableFormulaNode
+}
+export type VariableValue =
+ | VariableLiteral
+ | VariableAlias
+ | VariableColorExpression
+ | VariableFormula
export type VariableModeMap = Record<string, string>
/** Property pickers a variable is offered in, as Figma names them. */
@@ -857,10 +904,14 @@ export type CodeSyntaxPlatform = (typeof CODE_SYNTAX_PLATFORMS)[number]
export const TOKEN_UNITS = ['none', 'px', 'rem', '%', 'ms', 's', 'deg'] as const
export type TokenUnit = (typeof TOKEN_UNITS)[number]
-/** A mode value authored as raw CSS. `resolved` is the number the canvas drew for it. */
+/**
+ * CSS written in place of a number mode's value, such as `clamp(1rem, 4vw, 1.5rem)`. While the
+ * mode holds a plain number, `resolved` records it, so a number later edited elsewhere, Figma
+ * included, shows the CSS no longer describes it.
+ */
export interface TokenExpression {
css: string
- resolved: number
+ resolved?: number
}
export interface Variable {
diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts
index a4f8731df..730752353 100644
--- a/packages/scene-graph/src/variables.ts
+++ b/packages/scene-graph/src/variables.ts
@@ -5,7 +5,6 @@ import { BLACK } from './constants'
import type { SceneGraph } from './index'
import { setInstanceOverride } from './instance-overrides'
import { findInstanceAncestor } from './instances'
-import type { Color } from './primitives'
import type {
Variable,
VariableCollection,
@@ -20,6 +19,8 @@ import {
} from './variables/bindings'
import { BOOLEAN_BINDING_FIELDS, STRING_BINDING_FIELDS } from './variables/fields'
+export * from './variables/resolution'
+
export function addVariable(graph: SceneGraph, variable: Variable): void {
graph.variables.set(variable.id, variable)
const collection = graph.variableCollections.get(variable.collectionId)
@@ -129,36 +130,6 @@ export function removeCollection(graph: SceneGraph, id: string): void {
graph.activeMode.delete(id)
}
-export function getActiveModeId(graph: SceneGraph, collectionId: string): string {
- const mode = graph.activeMode.get(collectionId)
- if (mode) return mode
- const collection = graph.variableCollections.get(collectionId)
- return collection?.defaultModeId ?? ''
-}
-
-/**
- * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or
- * the collection's default (`default`), which is what a saved document means to other tools.
- */
-export type VariableModeFallback = 'active' | 'default'
-
-export function getNodeVariableModeId(
- graph: SceneGraph,
- nodeId: string,
- collectionId: string,
- fallback: VariableModeFallback = 'active'
-): string {
- let node = graph.nodes.get(nodeId)
- while (node) {
- const modeId = node.variableModes[collectionId]
- if (modeId) return modeId
- node = node.parentId ? graph.nodes.get(node.parentId) : undefined
- }
- if (fallback === 'default')
- return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''
- return getActiveModeId(graph, collectionId)
-}
-
export function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {
graph.activeMode.set(collectionId, modeId)
}
@@ -239,98 +210,6 @@ export function modesDefaultFirst(collection: VariableCollection): VariableColle
return [...defaults, ...rest]
}
-export function resolveVariable(
- graph: SceneGraph,
- variableId: string,
- modeId?: string,
- visited?: Set<string>
-): VariableValue | undefined {
- if (visited?.has(variableId)) return undefined
- const variable = graph.variables.get(variableId)
- if (!variable) return undefined
- const collection = graph.variableCollections.get(variable.collectionId)
- const preferredModeId = modeId ?? getActiveModeId(graph, variable.collectionId)
- const fallbackModeId = collection?.defaultModeId
- let value = Object.hasOwn(variable.valuesByMode, preferredModeId)
- ? variable.valuesByMode[preferredModeId]
- : undefined
- if (
- value === undefined &&
- fallbackModeId &&
- Object.hasOwn(variable.valuesByMode, fallbackModeId)
- ) {
- value = variable.valuesByMode[fallbackModeId]
- }
- value ??= Object.values(variable.valuesByMode)[0]
- if (value && typeof value === 'object' && 'aliasId' in value) {
- const seen = visited ?? new Set<string>()
- seen.add(variableId)
- return resolveVariable(graph, value.aliasId, preferredModeId, seen)
- }
- return value
-}
-
-export function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {
- const value = resolveVariable(graph, variableId)
- if (value && typeof value === 'object' && 'r' in value) return value
- return undefined
-}
-
-export function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {
- const value = resolveVariable(graph, variableId)
- return typeof value === 'number' ? value : undefined
-}
-
-export function resolveColorVariableForNode(
- graph: SceneGraph,
- nodeId: string,
- variableId: string,
- fallback: VariableModeFallback = 'active'
-): Color | undefined {
- const variable = graph.variables.get(variableId)
- if (!variable) return undefined
- const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
- const value = resolveVariable(graph, variableId, modeId)
- if (value && typeof value === 'object' && 'r' in value) return value
- return undefined
-}
-
-export function resolveNumberVariableForNode(
- graph: SceneGraph,
- nodeId: string,
- variableId: string,
- fallback: VariableModeFallback = 'active'
-): number | undefined {
- const variable = graph.variables.get(variableId)
- if (!variable) return undefined
- const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
- const value = resolveVariable(graph, variableId, modeId)
- return typeof value === 'number' ? value : undefined
-}
-
-/** A variable's value in the mode a node is in, aliases followed. */
-export function resolveVariableForNode(
- graph: SceneGraph,
- nodeId: string,
- variableId: string,
- fallback: VariableModeFallback = 'active'
-): VariableValue | undefined {
- const variable = graph.variables.get(variableId)
- if (!variable) return undefined
- const modeId = getNodeVariableModeId(graph, nodeId, variable.collectionId, fallback)
- return resolveVariable(graph, variableId, modeId)
-}
-
-export function resolveStringVariableForNode(
- graph: SceneGraph,
- nodeId: string,
- variableId: string,
- fallback: VariableModeFallback = 'active'
-): string | undefined {
- const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
- return typeof value === 'string' ? value : undefined
-}
-
export function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {
const collection = graph.variableCollections.get(collectionId)
if (!collection) return []
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 9f0c1e123..0a34eb25d 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -5,6 +5,7 @@ import type { Color } from '../primitives'
import type { Fill, SceneNode, Stroke, StyleRun, VariableValue } from '../types'
import type { VariableModeFallback } from '../variables'
import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
+import { variableValueReferences } from './value'
export { isNumericVariableBindingField } from './fields'
/** New declarations belong to the outermost occurrence, bounded by a component definition. */
@@ -205,8 +206,8 @@ export function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<strin
grew = false
for (const variable of graph.variables.values()) {
if (found.has(variable.id)) continue
- const aliases = Object.values(variable.valuesByMode).some(
- (value) => typeof value === 'object' && 'aliasId' in value && found.has(value.aliasId)
+ const aliases = Object.values(variable.valuesByMode).some((value) =>
+ variableValueReferences(value).some((id) => found.has(id))
)
if (aliases) {
found.add(variable.id)
@@ -243,9 +244,8 @@ export function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>):
const variable = graph.variables.get(id)
if (!variable) continue
collections.add(variable.collectionId)
- for (const value of Object.values(variable.valuesByMode)) {
- if (typeof value === 'object' && 'aliasId' in value) pending.push(value.aliasId)
- }
+ for (const value of Object.values(variable.valuesByMode))
+ pending.push(...variableValueReferences(value))
}
return collections
}
diff --git a/packages/scene-graph/src/variables/formula/evaluate.ts b/packages/scene-graph/src/variables/formula/evaluate.ts
new file mode 100644
index 000000000..d5c8dea4c
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/evaluate.ts
@@ -0,0 +1,169 @@
+import type {
+ VariableFormulaNode,
+ VariableFormulaOperator,
+ 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 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. */
+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))
+ }
+}
diff --git a/packages/scene-graph/src/variables/formula/index.ts b/packages/scene-graph/src/variables/formula/index.ts
new file mode 100644
index 000000000..112a8a276
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/index.ts
@@ -0,0 +1,130 @@
+import type { SceneGraph, 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'
+
+export { printFormula, type PrintFormulaOptions } from './print'
+export {
+ formulaTokenName,
+ formulaTokens,
+ readFormulaToken,
+ type FormulaToken,
+ type FormulaTokenKind
+} from './tokens'
+
+export {
+ evaluateVariableFormula,
+ formulaArity,
+ formulaOperandType,
+ formulaResultType,
+ MAX_FORMULA_DEPTH,
+ VariableFormulaError
+} from './evaluate'
+
+function qualifiedName(graph: SceneGraph, id: string) {
+ const variable = graph.variables.get(id)
+ if (!variable) return undefined
+ const collection = graph.variableCollections.get(variable.collectionId)
+ return `${collection?.name ?? variable.collectionId}::${variable.name}`
+}
+
+/** Qualified names disambiguate references; the stored formula uses stable IDs. */
+export function variableFormulaReference(graph: SceneGraph, id: string): string {
+ const variable = graph.variables.get(id)
+ if (!variable) return `{#${id}}`
+ const unique = (name: string, of: (id: string) => string | undefined) =>
+ [...graph.variables.keys()].filter((other) => of(other) === name).length === 1
+ const plain = variable.name
+ if (
+ !/[{}]/.test(plain) &&
+ plain.trim() === plain &&
+ unique(plain, (other) => graph.variables.get(other)?.name)
+ )
+ return `{${plain}}`
+ const qualified = qualifiedName(graph, id) ?? ''
+ return /[{}]/.test(qualified) || !unique(qualified, (other) => qualifiedName(graph, other))
+ ? `{#${id}}`
+ : `{${qualified}}`
+}
+
+/** The formula's source text, with `{name}` for each reference, as the clipboard and scripts write it. */
+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 ''
+}
+
+/**
+ * Find the variable a reference names: `#id`, `Collection::name`, or a name, preferring the
+ * edited variable's own collection when a name appears in several.
+ */
+function resolveReference(graph: SceneGraph, collectionId: string, name: string): FormulaReference {
+ const candidates = [...graph.variables.values()].filter(
+ (candidate) =>
+ name === `#${candidate.id}` ||
+ name === qualifiedName(graph, candidate.id) ||
+ name === candidate.name
+ )
+ const local = candidates.filter((candidate) => candidate.collectionId === collectionId)
+ const matches = local.length === 1 ? local : candidates
+ const match = matches.at(0)
+ 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 }
+}
+
+/** 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 } {
+ const variable = graph.variables.get(variableId)
+ if (!variable || (variable.type !== 'FLOAT' && variable.type !== 'BOOLEAN'))
+ throw new VariableFormulaError('Select a number or Boolean 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')
+ throw new VariableFormulaError(
+ `This gives ${kind(type)}, but ${variable.name} holds ${kind(variable.type)}`
+ )
+ }
+ const value: VariableValue =
+ typeof node === 'object' && 'operator' in node
+ ? { expression: 'FORMULA', type: variable.type, value: node }
+ : node
+ const resolved = resolveVariableInModes(
+ graph,
+ variableId,
+ (collectionId) =>
+ collectionId === variable.collectionId ? modeId : graph.getActiveModeId(collectionId),
+ new Set(),
+ 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.ts
new file mode 100644
index 000000000..036e27dbe
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/parse.ts
@@ -0,0 +1,164 @@
+import type { VariableFormulaNode, VariableFormulaOperator } from '@open-pencil/scene-graph'
+
+import {
+ checkFormulaOperands,
+ formulaResultType,
+ MAX_FORMULA_DEPTH,
+ MAX_FORMULA_LENGTH,
+ VariableFormulaError,
+ type FormulaValueType
+} from './evaluate'
+import { formulaTokenName, formulaTokens, type FormulaToken } from './tokens'
+
+/*
+ * A small Pratt parser rather than a library. jsep configures operators globally, which the calc
+ * tool's grammar already relies on, and gives no token stream for the editor to highlight and
+ * complete from. A Lezer grammar would add its runtime (about 18 KB gzipped) to every Scene Graph
+ * 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 !== 'reference') continue
+ if (!token.text.endsWith('}'))
+ throw new VariableFormulaError('A reference is missing its closing }')
+ if (!formulaTokenName(token)) throw new VariableFormulaError('Empty variable reference')
+ }
+ return tokens
+}
+
+export interface FormulaReference {
+ id: string
+ type: FormulaValueType
+}
+
+export interface ParsedFormula {
+ node: VariableFormulaNode
+ type: FormulaValueType
+}
+
+/**
+ * Read a formula into Figma's expression tree, checking operand types on the way. References
+ * are `{name}` or a bare name; `reference` resolves them. No code is evaluated.
+ */
+export function parseFormulaSyntax(
+ source: string,
+ reference: (name: string) => FormulaReference
+): ParsedFormula {
+ if (!source.trim()) throw new VariableFormulaError('Enter a value or formula')
+ if (source.length > MAX_FORMULA_LENGTH) throw new VariableFormulaError('Formula is too long')
+ const tokens = checkedTokens(source)
+ let index = 0
+ const peek = () => tokens.at(index)
+ /** Operators and keywords by their lowercase spelling; operands read as nothing. */
+ const symbolAt = (token: FormulaToken | undefined) =>
+ token && ['operator', 'keyword', 'paren', 'bool'].includes(token.kind)
+ ? token.text.toLowerCase()
+ : ''
+
+ function operation(operator: VariableFormulaOperator, operands: ParsedFormula[]): ParsedFormula {
+ checkFormulaOperands(
+ operator,
+ operands.map((operand) => operand.type)
+ )
+ return {
+ node: { operator, operands: operands.map((operand) => operand.node) },
+ type: formulaResultType(operator)
+ }
+ }
+
+ function prefix(depth: number): ParsedFormula {
+ if (depth > MAX_FORMULA_DEPTH) throw new VariableFormulaError('Formula is too deeply nested')
+ 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 === 'reference' || token.kind === 'name') {
+ const { id, type } = reference(formulaTokenName(token))
+ return { node: { aliasId: id }, type }
+ }
+ switch (symbolAt(token)) {
+ case 'true':
+ case 'false':
+ return { node: symbolAt(token) === 'true', type: 'BOOLEAN' }
+ case '(': {
+ const inner = expression(0, depth + 1)
+ if (symbolAt(tokens.at(index++)) !== ')') throw new VariableFormulaError('Missing )')
+ return inner
+ }
+ 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}`)
+ }
+
+ 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
+ if (!operator || precedence <= minimum) return left
+ index++
+ 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
+ )
+ throw new VariableFormulaError('Join comparisons with and or or')
+ }
+ }
+
+ const result = expression(0, 0)
+ const extra = peek()
+ if (extra) throw new VariableFormulaError(`Unexpected ${formulaTokenName(extra)}`)
+ return result
+}
diff --git a/packages/scene-graph/src/variables/formula/print.ts b/packages/scene-graph/src/variables/formula/print.ts
new file mode 100644
index 000000000..c0b270e2f
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/print.ts
@@ -0,0 +1,112 @@
+import type { VariableFormulaNode, VariableFormulaOperator } from '@open-pencil/scene-graph'
+
+import { formulaArity, formulaSymbol, MAX_FORMULA_DEPTH } from './evaluate'
+import { FORMULA_NON_ASSOCIATIVE, FORMULA_PRECEDENCE, FORMULA_PREFIX_PRECEDENCE } from './parse'
+
+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 CONTINUATION = '\n '
+
+interface Printed {
+ text: string
+ precedence: number
+}
+
+export interface PrintFormulaOptions {
+ /**
+ * Past this many characters, a formula breaks before each operator of its outermost chain of
+ * `or`, `and`, or `+` and `-`, with the lines after the first indented.
+ */
+ width?: number
+ /**
+ * How a reference reads where the formula is shown, such as a pill's name, which `width`
+ * counts in place of the source spelling.
+ */
+ display?: (id: string) => string
+}
+
+function nodePrecedence(node: VariableFormulaNode) {
+ if (typeof node !== 'object' || 'aliasId' in node) return ATOM
+ if (formulaArity(node.operator) === 1) return FORMULA_PREFIX_PRECEDENCE
+ return FORMULA_PRECEDENCE[node.operator] ?? 0
+}
+
+type Operation = Exclude<VariableFormulaNode, number | boolean | { aliasId: string }>
+type Print = (node: VariableFormulaNode, depth: number, breakAt?: number) => Printed
+
+const group = ({ text }: Printed) => `(${text})`
+
+function printUnary(node: Operation, depth: number, print: Print): Printed {
+ const [operandNode] = node.operands
+ const operand = print(operandNode, depth + 1)
+ const text = operand.precedence < ATOM ? group(operand) : operand.text
+ const symbol = formulaSymbol(node.operator)
+ return {
+ text: node.operator === 'NOT' ? `${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
+ const chained = FORMULA_NON_ASSOCIATIVE.has(precedence)
+ const [leftNode, rightNode] = node.operands
+ const sameAssociative =
+ ASSOCIATIVE.has(node.operator) &&
+ typeof rightNode === 'object' &&
+ 'operator' in rightNode &&
+ rightNode.operator === node.operator
+ // The chain continues through a left operand and an unparenthesized right one of its level.
+ const breaking = breakAt === precedence
+ const left = print(leftNode, depth + 1, breaking ? breakAt : undefined)
+ const right = print(rightNode, depth + 1, breaking && sameAssociative ? breakAt : undefined)
+ // A comparison inside another, such as `(a > 1) == b`, keeps its parentheses to read clearly.
+ const nested = (operand: Printed) => chained && FORMULA_NON_ASSOCIATIVE.has(operand.precedence)
+ const leftText = left.precedence < precedence || nested(left) ? group(left) : left.text
+ const rightGrouped =
+ right.precedence < precedence ||
+ nested(right) ||
+ (right.precedence === precedence && !sameAssociative)
+ const rightText = rightGrouped ? group(right) : right.text
+ const separator = breaking ? CONTINUATION : ' '
+ return { text: `${leftText}${separator}${formulaSymbol(node.operator)} ${rightText}`, precedence }
+}
+
+/** Print a formula with only the parentheses its precedence needs; `reference` spells a variable. */
+export function printFormula(
+ node: VariableFormulaNode,
+ reference: (id: string) => string,
+ { width, display }: PrintFormulaOptions = {}
+): string {
+ const line = printLine(node, reference)
+ const outer = nodePrecedence(node)
+ const shown = display ? printLine(node, display) : line
+ if (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)
+}
+
+function printWith(
+ reference: (id: string) => string,
+ root: VariableFormulaNode,
+ rootBreak?: number
+): string {
+ const print: Print = (node, depth, breakAt) => {
+ if (depth > MAX_FORMULA_DEPTH) return { text: '…', precedence: ATOM }
+ 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 }
+ return formulaArity(node.operator) === 1
+ ? printUnary(node, depth, print)
+ : printBinary(node, depth, print, 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.ts
new file mode 100644
index 000000000..dd8a24713
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/schema.ts
@@ -0,0 +1,73 @@
+import * as v from 'valibot'
+
+import {
+ VARIABLE_FORMULA_OPERATORS,
+ type VariableFormulaNode
+} from '@open-pencil/scene-graph/types'
+
+import { variableAliasSchema } from '../schema'
+import {
+ MAX_FORMULA_DEPTH,
+ formulaArity,
+ formulaOperandType,
+ formulaResultType,
+ type FormulaValueType
+} from './evaluate'
+
+type NodeSchema = v.GenericSchema<unknown, VariableFormulaNode>
+
+/**
+ * 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.
+ */
+function nodeSchema(type: FormulaValueType, depth: number, cache: Map<string, NodeSchema>) {
+ const key = `${type}:${depth}`
+ const cached = cache.get(key)
+ 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))
+ )
+ ),
+ 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)
+ return schema
+}
+
+const cache = new Map<string, NodeSchema>()
+
+export const variableFormulaSchema = v.variant('type', [
+ v.object({
+ expression: v.literal('FORMULA'),
+ type: v.literal('FLOAT'),
+ value: nodeSchema('FLOAT', MAX_FORMULA_DEPTH, cache)
+ }),
+ v.object({
+ expression: v.literal('FORMULA'),
+ type: v.literal('BOOLEAN'),
+ value: nodeSchema('BOOLEAN', MAX_FORMULA_DEPTH, cache)
+ })
+])
diff --git a/packages/scene-graph/src/variables/formula/tokens.ts b/packages/scene-graph/src/variables/formula/tokens.ts
new file mode 100644
index 000000000..e946ed5fd
--- /dev/null
+++ b/packages/scene-graph/src/variables/formula/tokens.ts
@@ -0,0 +1,93 @@
+/**
+ * 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.
+ */
+export type FormulaTokenKind =
+ | 'number'
+ | 'reference'
+ | 'name'
+ | 'keyword'
+ | 'bool'
+ | 'operator'
+ | 'paren'
+ | 'invalid'
+
+export interface FormulaToken {
+ kind: FormulaTokenKind
+ text: string
+ from: number
+ to: number
+}
+
+const NUMBER = /(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/y
+const WORD = /[\p{L}_$][\p{L}\p{N}_$]*/uy
+const OPERATOR = /<=|>=|==|!=|&&|\|\||[-+*/<>!]/y
+const SPACE = /\s+/y
+const KEYWORDS = new Set(['and', 'or', 'not'])
+const BOOLEANS = new Set(['true', 'false'])
+
+function matchAt(pattern: RegExp, source: string, at: number) {
+ pattern.lastIndex = at
+ return pattern.exec(source)?.[0]
+}
+
+/** 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++) {
+ if (source[index] === '}') return index + 1
+ if (source[index] === '{') return index
+ }
+ return source.length
+}
+
+function wordKind(word: string): FormulaTokenKind {
+ const lower = word.toLowerCase()
+ if (KEYWORDS.has(lower)) return 'keyword'
+ return BOOLEANS.has(lower) ? 'bool' : 'name'
+}
+
+/**
+ * The token that starts at `at`, which must not be whitespace. Reading never fails: text the
+ * syntax has no place for is an `invalid` token, so an editor can highlight what a parser rejects.
+ */
+export function readFormulaToken(source: string, at: number): FormulaToken {
+ const token = (kind: FormulaTokenKind, length: number): FormulaToken => ({
+ kind,
+ text: source.slice(at, at + length),
+ from: at,
+ to: at + length
+ })
+ const char = source[at] ?? ''
+ if (char === '{') return token('reference', referenceEnd(source, at) - at)
+ if (char === '(' || char === ')') return token('paren', 1)
+ const number = matchAt(NUMBER, source, at)
+ if (number) return token('number', number.length)
+ const word = matchAt(WORD, source, at)
+ if (word) return token(wordKind(word), word.length)
+ const operator = matchAt(OPERATOR, source, at)
+ return operator ? token('operator', operator.length) : token('invalid', 1)
+}
+
+/** Every token of a formula, in order, without the whitespace between them. */
+export function formulaTokens(source: string): FormulaToken[] {
+ const tokens: FormulaToken[] = []
+ let at = 0
+ while (at < source.length) {
+ const space = matchAt(SPACE, source, at)
+ if (space) {
+ at += space.length
+ continue
+ }
+ const token = readFormulaToken(source, at)
+ tokens.push(token)
+ at = token.to
+ }
+ return tokens
+}
+
+/** The variable a reference or bare name gives, without braces or surrounding spaces. */
+export function formulaTokenName(token: FormulaToken) {
+ if (token.kind !== 'reference') return token.text
+ return token.text.slice(1, token.text.endsWith('}') ? -1 : undefined).trim()
+}
diff --git a/packages/scene-graph/src/variables/resolution.ts b/packages/scene-graph/src/variables/resolution.ts
new file mode 100644
index 000000000..36fa84898
--- /dev/null
+++ b/packages/scene-graph/src/variables/resolution.ts
@@ -0,0 +1,293 @@
+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 { resolveVariableValue } from './value'
+
+export function getActiveModeId(graph: SceneGraph, collectionId: string): string {
+ const mode = graph.activeMode.get(collectionId)
+ if (mode) return mode
+ const collection = graph.variableCollections.get(collectionId)
+ return collection?.defaultModeId ?? ''
+}
+
+/**
+ * What a node without an explicit mode falls back to: the mode the editor shows (`active`), or
+ * the collection's default (`default`), which is what a saved document means to other tools.
+ */
+export type VariableModeFallback = 'active' | 'default'
+
+export function getNodeVariableModeId(
+ graph: SceneGraph,
+ nodeId: string,
+ collectionId: string,
+ fallback: VariableModeFallback = 'active'
+): string {
+ let node = graph.nodes.get(nodeId)
+ while (node) {
+ const modeId = node.variableModes[collectionId]
+ if (modeId) return modeId
+ node = node.parentId ? graph.nodes.get(node.parentId) : undefined
+ }
+ if (fallback === 'default')
+ return graph.variableCollections.get(collectionId)?.defaultModeId ?? ''
+ return getActiveModeId(graph, collectionId)
+}
+
+export function resolveVariable(
+ graph: SceneGraph,
+ variableId: string,
+ modeId?: string,
+ visited?: Set<string>
+): VariableLiteral | undefined {
+ const initial = graph.variables.get(variableId)
+ return resolveInModes(
+ graph,
+ variableId,
+ (collectionId) =>
+ modeId && initial?.collectionId === collectionId
+ ? modeId
+ : getActiveModeId(graph, collectionId),
+ visited
+ )
+}
+
+export class VariableResolutionError extends VariableFormulaError {
+ override name = 'VariableResolutionError'
+ constructor(
+ readonly code: 'cycle' | 'depth' | 'missing-variable' | 'missing-value' | 'type' | 'non-finite',
+ readonly variableId: string,
+ message: string
+ ) {
+ super(message)
+ }
+}
+
+const RESULT_TYPES = { FLOAT: 'number', BOOLEAN: 'boolean', STRING: 'string', COLOR: 'object' }
+
+/**
+ * Resolve a draft or saved definition with identical mode, dependency and error semantics. A
+ * memo shares values between lookups in one mode context; without one, nothing is cached.
+ */
+export function resolveVariableInModes(
+ graph: SceneGraph,
+ variableId: string,
+ modeFor: (collectionId: string) => string,
+ visiting = new Set<string>(),
+ memo?: Map<string, VariableLiteral>,
+ overrides?: ReadonlyMap<string, VariableValue>
+): VariableLiteral {
+ const cached = memo?.get(variableId)
+ if (cached !== undefined) return cached
+ if (visiting.has(variableId))
+ throw new VariableResolutionError('cycle', variableId, 'Circular variable reference')
+ if (visiting.size >= MAX_FORMULA_DEPTH)
+ throw new VariableResolutionError('depth', variableId, 'Too many linked variables')
+ const variable = graph.variables.get(variableId)
+ if (!variable)
+ throw new VariableResolutionError(
+ 'missing-variable',
+ variableId,
+ `Missing variable: ${variableId}`
+ )
+ const value =
+ overrides?.get(variableId) ??
+ variableValueInMode(graph, variable, modeFor(variable.collectionId))
+ if (value === undefined)
+ throw new VariableResolutionError(
+ 'missing-value',
+ variableId,
+ `Missing value: ${variable.name}`
+ )
+ return evaluateDefinition(graph, variable, value, modeFor, visiting, memo, overrides)
+}
+
+/** Resolve one variable's definition in its mode context, its dependencies in theirs. */
+function evaluateDefinition(
+ graph: SceneGraph,
+ variable: Variable,
+ value: VariableValue,
+ modeFor: (collectionId: string) => string,
+ visiting: Set<string>,
+ memo?: Map<string, VariableLiteral>,
+ overrides?: ReadonlyMap<string, VariableValue>
+): VariableLiteral {
+ const variableId = variable.id
+ visiting.add(variableId)
+ try {
+ const result = resolveVariableValue(value, (id) =>
+ resolveVariableInModes(graph, id, modeFor, visiting, memo, overrides)
+ )
+ if (result === undefined || typeof result !== RESULT_TYPES[variable.type])
+ throw new VariableResolutionError('type', variableId, `Wrong result type: ${variable.name}`)
+ if (typeof result === 'number' && !Number.isFinite(result))
+ throw new VariableResolutionError(
+ 'non-finite',
+ variableId,
+ `Non-finite value: ${variable.name}`
+ )
+ // Failures can depend on the current path's depth. Only completed values are reusable.
+ memo?.set(variableId, result)
+ return result
+ } finally {
+ visiting.delete(variableId)
+ }
+}
+
+/**
+ * What the canvas draws for a variable, or nothing when it cannot be resolved. Literals and alias
+ * chains, which most bindings are, resolve in a loop; an expression on the way takes the full
+ * resolver, whose diagnostics the canvas does not need.
+ */
+function resolveInModes(
+ graph: SceneGraph,
+ variableId: string,
+ modeFor: (collectionId: string) => string,
+ visiting?: Set<string>,
+ memo?: Map<string, VariableLiteral>
+): VariableLiteral | undefined {
+ const cached = memo?.get(variableId)
+ if (cached !== undefined) return cached
+ const initial = graph.variables.get(variableId)
+ if (!initial) return undefined
+ let id = variableId
+ for (let depth = visiting?.size ?? 0; depth < MAX_FORMULA_DEPTH; depth++) {
+ const variable = id === variableId ? initial : graph.variables.get(id)
+ if (!variable || visiting?.has(id)) return undefined
+ const value = variableValueInMode(graph, variable, modeFor(variable.collectionId))
+ if (typeof value === 'object' && 'aliasId' in value) {
+ id = value.aliasId
+ continue
+ }
+ const result =
+ typeof value === 'object' && 'expression' in value
+ ? resolveExpression(graph, variable, value, modeFor, visiting, memo)
+ : value
+ return drawable(result, initial.type)
+ }
+ return undefined
+}
+
+/** A formula shares its dependencies' values for the length of one resolution. */
+function resolveExpression(
+ graph: SceneGraph,
+ variable: Variable,
+ value: VariableValue,
+ modeFor: (collectionId: string) => string,
+ visiting?: Set<string>,
+ memo?: Map<string, VariableLiteral>
+): VariableLiteral | undefined {
+ try {
+ return evaluateDefinition(
+ graph,
+ variable,
+ value,
+ modeFor,
+ visiting ?? new Set(),
+ memo ?? new Map()
+ )
+ } catch {
+ return undefined
+ }
+}
+
+/** A resolved value the canvas can draw for a variable of this type, or nothing. */
+function drawable(value: VariableValue | undefined, type: Variable['type']) {
+ if (value === undefined || typeof value !== RESULT_TYPES[type]) return undefined
+ if (typeof value === 'object' && !('r' in value)) return undefined
+ return typeof value === 'number' && !Number.isFinite(value) ? undefined : value
+}
+
+/** Shared mode fallback for canvas resolution and formula draft validation. */
+export function variableValueInMode(
+ graph: SceneGraph,
+ variable: Variable,
+ modeId: string
+): VariableValue | undefined {
+ const values = variable.valuesByMode
+ if (Object.hasOwn(values, modeId)) return values[modeId]
+ const defaultMode = graph.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''
+ if (Object.hasOwn(values, defaultMode)) return values[defaultMode]
+ return Object.values(values).at(0)
+}
+
+export type NodeVariableResolver = (
+ nodeId: string,
+ variableId: string
+) => VariableLiteral | undefined
+
+/** One read/reconcile operation only: equal mode contexts share results, edits start a new cache. */
+export function createBatchVariableResolver(graph: SceneGraph): NodeVariableResolver {
+ const collections = [...graph.variableCollections.keys()]
+ const contexts = new Map<string, Map<string, VariableLiteral>>()
+ return (nodeId, variableId) => {
+ const modes = collections.map((id) => getNodeVariableModeId(graph, nodeId, id))
+ const key = JSON.stringify(modes)
+ let memo = contexts.get(key)
+ if (!memo) {
+ memo = new Map()
+ contexts.set(key, memo)
+ }
+ return resolveInModes(
+ graph,
+ variableId,
+ (id) => modes[collections.indexOf(id)] ?? '',
+ undefined,
+ memo
+ )
+ }
+}
+
+export function resolveColorVariable(graph: SceneGraph, variableId: string): Color | undefined {
+ const value = resolveVariable(graph, variableId)
+ if (value && typeof value === 'object' && 'r' in value) return value
+ return undefined
+}
+
+export function resolveNumberVariable(graph: SceneGraph, variableId: string): number | undefined {
+ const value = resolveVariable(graph, variableId)
+ return typeof value === 'number' ? value : undefined
+}
+
+export function resolveColorVariableForNode(
+ graph: SceneGraph,
+ nodeId: string,
+ variableId: string,
+ fallback: VariableModeFallback = 'active'
+): Color | undefined {
+ const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
+ if (value && typeof value === 'object' && 'r' in value) return value
+ return undefined
+}
+
+export function resolveNumberVariableForNode(
+ graph: SceneGraph,
+ nodeId: string,
+ variableId: string,
+ fallback: VariableModeFallback = 'active'
+): number | undefined {
+ const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
+ return typeof value === 'number' ? value : undefined
+}
+
+/** A variable's value in the mode a node is in, aliases followed. */
+export function resolveVariableForNode(
+ graph: SceneGraph,
+ nodeId: string,
+ variableId: string,
+ fallback: VariableModeFallback = 'active'
+): VariableLiteral | undefined {
+ return resolveInModes(graph, variableId, (collectionId) =>
+ getNodeVariableModeId(graph, nodeId, collectionId, fallback)
+ )
+}
+
+export function resolveStringVariableForNode(
+ graph: SceneGraph,
+ nodeId: string,
+ variableId: string,
+ fallback: VariableModeFallback = 'active'
+): string | undefined {
+ const value = resolveVariableForNode(graph, nodeId, variableId, fallback)
+ return typeof value === 'string' ? value : undefined
+}
diff --git a/packages/scene-graph/src/variables/schema.ts b/packages/scene-graph/src/variables/schema.ts
new file mode 100644
index 000000000..84e7e5432
--- /dev/null
+++ b/packages/scene-graph/src/variables/schema.ts
@@ -0,0 +1,13 @@
+import * as v from 'valibot'
+
+export const variableAliasSchema = v.object({ aliasId: v.string() })
+const finiteNumber = v.pipe(v.number(), v.finite())
+
+export const variableColorExpressionSchema = v.object({
+ expression: v.literal('COMPOSE_COLOR'),
+ color: v.union([
+ variableAliasSchema,
+ v.object({ r: finiteNumber, g: finiteNumber, b: finiteNumber, a: finiteNumber })
+ ]),
+ opacity: v.union([variableAliasSchema, finiteNumber])
+})
diff --git a/packages/scene-graph/src/variables/token.ts b/packages/scene-graph/src/variables/token.ts
index d8ec3560c..60af356cd 100644
--- a/packages/scene-graph/src/variables/token.ts
+++ b/packages/scene-graph/src/variables/token.ts
@@ -1,4 +1,7 @@
-import type { TokenUnit } from '../types'
+import { omit } from 'es-toolkit/object'
+import { isEmptyObject } from 'es-toolkit/predicate'
+
+import type { TokenExpression, TokenUnit, Variable, VariableValue } from '../types'
/** `rem` tokens are stored in canvas pixels and shown against this root font size. */
export const ROOT_FONT_SIZE_PX = 16
@@ -12,3 +15,26 @@ export function tokenNumberFromUnit(value: number, unit: TokenUnit): number {
export function tokenNumberInUnit(value: number, unit: TokenUnit): number {
return unit === 'rem' ? value / ROOT_FONT_SIZE_PX : value
}
+
+/**
+ * A CSS expression outlives edits to its mode's value, whatever the value becomes; it records the
+ * value only while that is a plain number.
+ */
+export function tokenExpressionForValue(
+ expression: TokenExpression | undefined,
+ value: VariableValue
+): TokenExpression | undefined {
+ if (!expression) return undefined
+ return typeof value === 'number'
+ ? { css: expression.css, resolved: value }
+ : { css: expression.css }
+}
+
+/** Keep a variable's CSS expression for one mode in step with that mode's new value. */
+export function updateTokenExpression(variable: Variable, modeId: string, value: VariableValue) {
+ const expression = tokenExpressionForValue(variable.expressions?.[modeId], value)
+ const others = omit(variable.expressions ?? {}, [modeId])
+ const expressions = expression ? { ...others, [modeId]: expression } : others
+ if (isEmptyObject(expressions)) delete variable.expressions
+ else variable.expressions = expressions
+}
diff --git a/packages/scene-graph/src/variables/value.ts b/packages/scene-graph/src/variables/value.ts
new file mode 100644
index 000000000..c66228d3d
--- /dev/null
+++ b/packages/scene-graph/src/variables/value.ts
@@ -0,0 +1,78 @@
+import * as v from 'valibot'
+
+import type { VariableLiteral, VariableValue } from '../types'
+import {
+ evaluateVariableFormula,
+ mapFormulaReferences,
+ VariableFormulaError
+} from './formula/evaluate'
+import { variableColorExpressionSchema } from './schema'
+
+/** All references in one definition, including color and opacity operands. */
+export function variableValueReferences(value: VariableValue): string[] {
+ if (typeof value !== 'object') return []
+ if ('aliasId' in value) return [value.aliasId]
+ if ('expression' in value && value.expression === 'FORMULA') {
+ const references: string[] = []
+ mapFormulaReferences(value.value, (id) => {
+ references.push(id)
+ return id
+ })
+ return references
+ }
+ if ('expression' in value)
+ return [...variableValueReferences(value.color), ...variableValueReferences(value.opacity)]
+ return []
+}
+
+/** Clone a value while remapping its references for transfer to another document. */
+export function mapVariableValueReferences(
+ value: VariableValue,
+ map: (id: string) => string
+): VariableValue {
+ if (typeof value !== 'object') return value
+ if ('aliasId' in value) return { aliasId: map(value.aliasId) }
+ if ('expression' in value && value.expression === 'FORMULA')
+ return { ...value, value: mapFormulaReferences(value.value, map) }
+ if ('expression' in value)
+ return {
+ expression: value.expression,
+ color: 'aliasId' in value.color ? { aliasId: map(value.color.aliasId) } : { ...value.color },
+ opacity:
+ typeof value.opacity === 'object' ? { aliasId: map(value.opacity.aliasId) } : value.opacity
+ }
+ return { ...value }
+}
+
+/** Resolve operands through the caller's mode context; formula failures retain their diagnostics for the caller. */
+export function resolveVariableValue(
+ value: VariableValue,
+ resolve: (id: string) => VariableLiteral | undefined
+): VariableLiteral | undefined {
+ if (typeof value !== 'object') return value
+ if ('aliasId' in value) return resolve(value.aliasId)
+ if (!('expression' in value)) return value
+ if (value.expression === 'FORMULA') {
+ // 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'))
+ throw new VariableFormulaError('Wrong formula result type')
+ return result
+ }
+ const expression = v.parse(variableColorExpressionSchema, value)
+ const color = 'aliasId' in expression.color ? resolve(expression.color.aliasId) : expression.color
+ const opacity =
+ typeof expression.opacity === 'object'
+ ? resolve(expression.opacity.aliasId)
+ : expression.opacity
+ if (
+ !color ||
+ typeof color !== 'object' ||
+ !Object.values(color).every(Number.isFinite) ||
+ typeof opacity !== 'number' ||
+ !Number.isFinite(opacity)
+ )
+ return undefined
+ return { ...color, a: Math.min(1, Math.max(0, opacity / 100)) }
+}
diff --git a/packages/scene-graph/tests/variables/color-expression.test.ts b/packages/scene-graph/tests/variables/color-expression.test.ts
new file mode 100644
index 000000000..b5fafebac
--- /dev/null
+++ b/packages/scene-graph/tests/variables/color-expression.test.ts
@@ -0,0 +1,88 @@
+import { expect, test } from 'bun:test'
+
+import {
+ SceneGraph,
+ mapVariableValueReferences,
+ variablesResolvingThrough,
+ type VariableValue
+} from '@open-pencil/scene-graph'
+
+function setup() {
+ const graph = new SceneGraph()
+ const colors = graph.createCollection('Colors')
+ const opacity = graph.createCollection('Opacity')
+ const base = graph.createVariable('Base', 'COLOR', colors.id, { r: 1, g: 0, b: 0, a: 1 })
+ const amount = graph.createVariable('Amount', 'FLOAT', opacity.id, 20)
+ const value: VariableValue = {
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: base.id },
+ opacity: { aliasId: amount.id }
+ }
+ const derived = graph.createVariable('Derived', 'COLOR', colors.id, value)
+ return { graph, colors, opacity, base, amount, derived }
+}
+
+test('derived colors retain both dependencies and follow base and opacity edits', () => {
+ const { graph, colors, opacity, base, amount, derived } = setup()
+ expect(graph.resolveColorVariable(derived.id)).toEqual({ r: 1, g: 0, b: 0, a: 0.2 })
+ base.valuesByMode[colors.defaultModeId] = { r: 0, g: 0, b: 1, a: 1 }
+ amount.valuesByMode[opacity.defaultModeId] = 70
+ expect(graph.resolveColorVariable(derived.id)).toEqual({ r: 0, g: 0, b: 1, a: 0.7 })
+ expect(variablesResolvingThrough(graph, [base.id]).has(derived.id)).toBe(true)
+ expect(variablesResolvingThrough(graph, [amount.id]).has(derived.id)).toBe(true)
+ expect(derived.valuesByMode[colors.defaultModeId]).toEqual({
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: base.id },
+ opacity: { aliasId: amount.id }
+ })
+})
+
+test('each operand follows its collection mode, including inherited node modes', () => {
+ const { graph, colors, opacity, base, amount, derived } = setup()
+ graph.addMode(colors.id, 'night', 'Night')
+ graph.addMode(opacity.id, 'strong', 'Strong')
+ base.valuesByMode.night = { r: 0, g: 0, b: 1, a: 1 }
+ amount.valuesByMode.strong = 80
+ graph.setActiveMode(opacity.id, 'strong')
+ expect(graph.resolveVariable(derived.id, 'night')).toEqual({ r: 0, g: 0, b: 1, a: 0.8 })
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ variableModes: { [colors.id]: 'night', [opacity.id]: 'strong' }
+ })
+ const node = graph.createNode('RECTANGLE', frame.id)
+ expect(graph.resolveColorVariableForNode(node.id, derived.id, 'default')).toEqual({
+ r: 0,
+ g: 0,
+ b: 1,
+ a: 0.8
+ })
+})
+
+test('cycles, missing dependencies, wrong types and nonfinite values stay unresolved', () => {
+ const { graph, colors, opacity, base, amount, derived } = setup()
+ base.valuesByMode[colors.defaultModeId] = { aliasId: derived.id }
+ expect(graph.resolveColorVariable(derived.id)).toBeUndefined()
+ base.valuesByMode[colors.defaultModeId] = 'red'
+ expect(graph.resolveColorVariable(derived.id)).toBeUndefined()
+ base.valuesByMode[colors.defaultModeId] = { r: 1, g: 0, b: 0, a: 1 }
+ amount.valuesByMode[opacity.defaultModeId] = Infinity
+ expect(graph.resolveColorVariable(derived.id)).toBeUndefined()
+ amount.valuesByMode[opacity.defaultModeId] = 0
+ expect(graph.resolveColorVariable(derived.id)?.a).toBe(0)
+ graph.removeVariable(base.id)
+ expect(graph.resolveColorVariable(derived.id)).toBeUndefined()
+})
+
+test('transfer remaps both references without changing the source definition', () => {
+ const { colors, base, amount, derived } = setup()
+ const value = derived.valuesByMode[colors.defaultModeId]
+ expect(mapVariableValueReferences(value, (id) => `copy:${id}`)).toEqual({
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: `copy:${base.id}` },
+ opacity: { aliasId: `copy:${amount.id}` }
+ })
+ expect(value).toEqual({
+ expression: 'COMPOSE_COLOR',
+ color: { aliasId: base.id },
+ opacity: { aliasId: amount.id }
+ })
+})
diff --git a/packages/scene-graph/tests/variables/formula.test.ts b/packages/scene-graph/tests/variables/formula.test.ts
new file mode 100644
index 000000000..525e6c6d1
--- /dev/null
+++ b/packages/scene-graph/tests/variables/formula.test.ts
@@ -0,0 +1,382 @@
+import { expect, test, spyOn } from 'bun:test'
+
+import * as v from 'valibot'
+
+import {
+ SceneGraph,
+ parseVariableFormula,
+ formatVariableFormula,
+ variableValueReferences,
+ mapVariableValueReferences,
+ variableFormulaSchema,
+ collectionsBoundIn,
+ formulaTokens,
+ type VariableFormulaNode,
+ type VariableValue
+} from '@open-pencil/scene-graph'
+import { createBatchVariableResolver } from '@open-pencil/scene-graph/variables'
+
+function setup(type: 'FLOAT' | 'BOOLEAN' = 'FLOAT') {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Tokens')
+ const base = graph.createVariable('base', type, collection.id, type === 'FLOAT' ? 4 : true)
+ const derived = graph.createVariable('derived', type, collection.id, type === 'FLOAT' ? 0 : false)
+ const mode = collection.defaultModeId
+ const parse = (source: string) => parseVariableFormula(graph, derived.id, mode, source)
+ const set = (source: string) => {
+ derived.valuesByMode[mode] = parse(source).value
+ }
+ return { graph, collection, base, derived, mode, parse, set }
+}
+
+test('arithmetic, precedence, unary signs, references and renaming', () => {
+ const { graph, base, derived, mode, parse, set } = setup()
+ expect(parse('{base} * 2 + 3 / (2 + 1)').resolved).toBe(9)
+ expect(parse('-{base} + +2').resolved).toBe(-2)
+ expect(parse('1e3 / 2').resolved).toBe(500)
+ set('{base} * 2')
+ base.name = 'renamed'
+ expect(graph.resolveVariable(derived.id)).toBe(8)
+ expect(formatVariableFormula(graph, derived.valuesByMode[mode])).toBe('{renamed} * 2')
+ base.valuesByMode[mode] = 6
+ expect(graph.resolveVariable(derived.id)).toBe(12)
+})
+
+test.each([
+ ['true and false', false],
+ ['true OR false', true],
+ ['not true', false],
+ ['!true || false', false],
+ ['true and not false', true],
+ ['true or true and false', true],
+ ['not ({base} and false)', true],
+ ['{base} == true', true],
+ ['{base} != false', true]
+] as const)('Boolean logic %s', (source, expected) => {
+ const { parse } = setup('BOOLEAN')
+ expect(parse(source).resolved).toBe(expected)
+})
+
+test.each([
+ ['{width} > 600', true],
+ ['{width} <= 600', false],
+ ['{width} * 2 >= 1280 and {width} < 1000', true],
+ ['{width} == 640', true],
+ ['{width} != 640 or {width} < 0', false],
+ ['not {width} > 600', 'needs true or false']
+] as const)('number comparisons give Booleans: %s', (source, expected) => {
+ const { graph, collection, parse } = setup('BOOLEAN')
+ graph.createVariable('width', 'FLOAT', collection.id, 640)
+ if (typeof expected === 'string') expect(() => parse(source)).toThrow(expected)
+ else expect(parse(source).resolved).toBe(expected)
+})
+
+test.each([
+ ['{base} * 2 + 3', '{base} * 2 + 3'],
+ ['({base} * 2) + 3', '{base} * 2 + 3'],
+ ['({base} + 2) * 3', '({base} + 2) * 3'],
+ ['{base} - ({base} - 1)', '{base} - ({base} - 1)'],
+ ['({base} - {base}) - 1', '{base} - {base} - 1'],
+ ['{base} / ({base} * 2)', '{base} / ({base} * 2)'],
+ ['{base} + ({base} + 1)', '{base} + {base} + 1'],
+ ['-({base})', '-{base}'],
+ ['-({base} + 1)', '-({base} + 1)'],
+ ['- 4 * {base}', '-4 * {base}'],
+ ['-(-{base})', '-(-{base})']
+] as const)('numbers print with only the parentheses they need: %s', (source, printed) => {
+ const { graph, parse } = setup()
+ expect(formatVariableFormula(graph, parse(source).value)).toBe(printed)
+})
+
+test.each([
+ ['NOT ({base} AND false)', 'not ({base} and false)'],
+ ['({base} OR false) AND true', '({base} or false) and true'],
+ ['{width} > 1 AND {width} < 2', '{width} > 1 and {width} < 2'],
+ ['({width} > 1) == true', '({width} > 1) == true'],
+ ['not not {base}', 'not (not {base})']
+] as const)('Booleans print with only the parentheses they need: %s', (source, printed) => {
+ const { graph, collection, parse } = setup('BOOLEAN')
+ graph.createVariable('width', 'FLOAT', collection.id, 640)
+ expect(formatVariableFormula(graph, parse(source).value)).toBe(printed)
+})
+
+test('bare names resolve like braced ones, and unknown names say so', () => {
+ const { parse } = setup()
+ expect(parse('base * 3').resolved).toBe(12)
+ expect(() => parse('md * 2')).toThrow('No variable named md')
+ expect(() => parse('{space/md}')).toThrow('No variable named space/md')
+})
+
+test('invalid drafts keep the saved definition intact and restore the shared parser grammar', () => {
+ const { parse, derived, mode } = setup()
+ for (const source of [
+ '{missing} * 2',
+ '{derived} + 1',
+ '1 / 0',
+ '1e308 * 1e308',
+ 'true + 1',
+ 'true',
+ 'Math.random()',
+ '({base}).value',
+ '[1,2]',
+ '1;2',
+ '1 ** 2',
+ 'a = 3',
+ '$reference0 + {base}',
+ '1 < 2 < 3',
+ '{base',
+ '{}',
+ '1 +',
+ '(1 + 2',
+ '1 2',
+ '('.repeat(10000)
+ ])
+ expect(() => parse(source)).toThrow()
+ expect(derived.valuesByMode[mode]).toBe(0)
+})
+
+test('cycles through other formulas are rejected even in Boolean branches that would short circuit', () => {
+ const { base, derived, mode, parse } = setup('BOOLEAN')
+ base.valuesByMode[mode] = { aliasId: derived.id }
+ expect(() => parse('false and {base}')).toThrow('Circular')
+})
+
+test.each([
+ [false, false, false, false, true, false],
+ [false, true, false, true, false, true],
+ [true, false, false, true, false, true],
+ [true, true, true, true, true, false]
+] as const)('Boolean truth table for %s and %s', (left, right, and, or, equals, notEqual) => {
+ const { parse } = setup('BOOLEAN')
+ expect(
+ ['and', 'or', '==', '!='].map((operator) => parse(`${left} ${operator} ${right}`).resolved)
+ ).toEqual([and, or, equals, notEqual])
+})
+
+test('numeric formulas can drive imported color opacity expressions', () => {
+ const { graph, collection, derived, base, mode, set } = setup()
+ set('{base} * 5')
+ const color = graph.createVariable('scrim', 'COLOR', collection.id, {
+ expression: 'COMPOSE_COLOR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: { aliasId: derived.id }
+ })
+ expect(graph.resolveColorVariable(color.id)?.a).toBe(0.2)
+ base.valuesByMode[mode] = 6
+ expect(graph.resolveColorVariable(color.id)?.a).toBe(0.3)
+})
+
+test('references with duplicate or reserved names retain editable ID fallbacks', () => {
+ const { graph, base, derived, mode, parse, set } = setup()
+ set('{base} * 2')
+ base.name = '{reserved}'
+ const text = formatVariableFormula(graph, derived.valuesByMode[mode])
+ expect(text).toContain(`{#${base.id}}`)
+ expect(parse(text).resolved).toBe(8)
+ base.valuesByMode[mode] = Infinity
+ expect(() => parse(`{#${base.id}}`)).toThrow('Non-finite')
+})
+
+test('references follow explicit, active, and inherited modes across collections', () => {
+ const { graph, collection, base, derived, mode, set } = setup()
+ graph.addMode(collection.id, 'large', 'Large')
+ base.valuesByMode.large = 10
+ set('{base} * 2')
+ derived.valuesByMode.large = derived.valuesByMode[mode]
+ expect(graph.resolveVariable(derived.id, 'large')).toBe(20)
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ variableModes: { [collection.id]: 'large' }
+ })
+ const child = graph.createNode('RECTANGLE', frame.id)
+ expect(graph.resolveNumberVariableForNode(child.id, derived.id)).toBe(20)
+ const other = graph.createCollection('Other')
+ const scalar = graph.createVariable('factor', 'FLOAT', other.id, 3)
+ graph.addMode(other.id, 'double', 'Double')
+ scalar.valuesByMode.double = 5
+ graph.setActiveMode(other.id, 'double')
+ set('{base} * {Other::factor}')
+ expect(graph.resolveVariable(derived.id)).toBe(20)
+})
+
+test('qualified names, missing dependencies, reference remapping and runtime validation', () => {
+ const { graph, collection, base, derived, mode, set, parse } = setup()
+ const other = graph.createCollection('Other')
+ graph.createVariable('base', 'FLOAT', other.id, 10)
+ expect(parse('{Other::base} + {base}').resolved).toBe(14)
+ set('{base} * 2')
+ const definition = derived.valuesByMode[mode]
+ expect(v.safeParse(variableFormulaSchema, definition).success).toBe(true)
+ expect(variableValueReferences(definition)).toEqual([base.id])
+ const remapped = mapVariableValueReferences(definition, (id) => `copy:${id}`)
+ expect(variableValueReferences(remapped)).toEqual([`copy:${base.id}`])
+ expect(graph.variableCollections.has(collection.id)).toBe(true)
+ graph.removeVariable(base.id)
+ expect(graph.resolveVariable(derived.id)).toBeUndefined()
+ expect(() => parse(formatVariableFormula(graph, definition))).toThrow()
+ expect(
+ v.safeParse(variableFormulaSchema, { expression: 'FORMULA', type: 'FLOAT', value: Infinity })
+ .success
+ ).toBe(false)
+})
+
+test('shared formula dependencies resolve once per evaluation and never cache across edits', () => {
+ const { graph, collection, base, mode } = setup()
+ let previous = base
+ for (let i = 0; i < 25; i++) {
+ const value: VariableValue = {
+ expression: 'FORMULA',
+ type: 'FLOAT',
+ value: {
+ operator: 'ADDITION',
+ operands: [{ aliasId: previous.id }, { aliasId: previous.id }]
+ }
+ }
+ previous = graph.createVariable(`level${i}`, 'FLOAT', collection.id, value)
+ }
+ expect(graph.resolveVariable(previous.id)).toBe(134217728)
+ base.valuesByMode[mode] = 2
+ expect(graph.resolveVariable(previous.id)).toBe(67108864)
+})
+
+test('100 consumers share one calculation per mode during a batch', () => {
+ const { graph, collection, base, derived, mode, set } = setup()
+ set('{base} * 2')
+ graph.addMode(collection.id, 'large', 'Large')
+ base.valuesByMode.large = 10
+ const nodes = Array.from({ length: 100 }, (_, index) =>
+ graph.createNode('FRAME', graph.getPages()[0].id, {
+ variableModes: index % 2 === 0 ? {} : { [collection.id]: 'large' }
+ })
+ )
+ const get = spyOn(graph.variables, 'get')
+ try {
+ const resolve = createBatchVariableResolver(graph)
+ for (const [index, node] of nodes.entries())
+ expect(resolve(node.id, derived.id)).toBe(index % 2 === 0 ? 8 : 20)
+ expect(get.mock.calls.filter(([id]) => id === derived.id)).toHaveLength(2)
+ base.valuesByMode[mode] = 6
+ expect(createBatchVariableResolver(graph)(nodes[0].id, derived.id)).toBe(12)
+ } finally {
+ get.mockRestore()
+ }
+})
+
+test('numeric schema and resolver reject invalid formula trees', () => {
+ const values: VariableFormulaNode[] = [
+ { operator: 'ADDITION', operands: [true, 1] },
+ { operator: 'ADDITION', operands: [1] },
+ { operator: 'NOT', operands: [true] },
+ { operator: 'MULTIPLY', operands: [1, { operator: 'OR', operands: [false, true] }] },
+ { operator: 'DIVIDE', operands: [Infinity, 2] }
+ ]
+ const { graph, derived, mode } = setup()
+ for (const value of values) {
+ const definition: VariableValue = { expression: 'FORMULA', type: 'FLOAT', value }
+ expect(v.safeParse(variableFormulaSchema, definition).success).toBe(false)
+ derived.valuesByMode[mode] = definition
+ expect(graph.resolveVariable(derived.id)).toBeUndefined()
+ }
+})
+
+test('bounded schema rejects deeply nested and cyclic input', () => {
+ const value: VariableValue = { expression: 'FORMULA', type: 'FLOAT', value: 1 }
+ if (!('expression' in value) || value.expression !== 'FORMULA')
+ throw new Error('Expected formula')
+ for (let i = 0; i < 65; i++) value.value = { operator: 'NEGATE', operands: [value.value] }
+ expect(v.safeParse(variableFormulaSchema, value).success).toBe(false)
+ const operands: VariableFormulaNode[] = [1]
+ const cyclic: VariableFormulaNode = { operator: 'NEGATE', operands }
+ operands[0] = cyclic
+ expect(
+ v.safeParse(variableFormulaSchema, { expression: 'FORMULA', type: 'FLOAT', value: cyclic })
+ .success
+ ).toBe(false)
+})
+
+test('a depth-limited batch lookup does not poison a later shallow lookup', () => {
+ const { graph, collection, base } = setup()
+ let previous = base
+ const chain = [base]
+ for (let i = 0; i < 65; i++) {
+ previous = graph.createVariable(`alias${i}`, 'FLOAT', collection.id, { aliasId: previous.id })
+ chain.push(previous)
+ }
+ const node = graph.createNode('FRAME', graph.getPages()[0].id)
+ const resolve = createBatchVariableResolver(graph)
+ expect(resolve(node.id, previous.id)).toBeUndefined()
+ expect(resolve(node.id, chain[2].id)).toBe(4)
+ expect(resolve(node.id, base.id)).toBe(4)
+})
+
+test('collection discovery follows formulas and composed color operands transitively', () => {
+ const { graph, collection, derived, set } = setup()
+ const other = graph.createCollection('Other')
+ graph.createVariable('factor', 'FLOAT', other.id, 2)
+ set('{Other::factor} * 10')
+ const colors = graph.createCollection('Colors')
+ const color = graph.createVariable('scrim', 'COLOR', colors.id, {
+ expression: 'COMPOSE_COLOR',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: { aliasId: derived.id }
+ })
+ const node = graph.createNode('FRAME', graph.getPages()[0].id, {
+ boundVariables: { fillColor: color.id }
+ })
+ expect(collectionsBoundIn(graph, [node.id])).toEqual(
+ new Set([colors.id, collection.id, other.id])
+ )
+})
+
+test('the tokenizer reads half-typed formulas without failing, as an editor needs', () => {
+ const kinds = (source: string) =>
+ formulaTokens(source).map(({ kind, text }) => `${kind}:${text}`)
+ expect(kinds('{space/md} * 2 - base')).toEqual([
+ 'reference:{space/md}',
+ 'operator:*',
+ 'number:2',
+ 'operator:-',
+ 'name:base'
+ ])
+ expect(kinds('NOT (a<=1) and True')).toEqual([
+ 'keyword:NOT',
+ 'paren:(',
+ 'name:a',
+ 'operator:<=',
+ 'number:1',
+ 'paren:)',
+ 'keyword:and',
+ 'bool:True'
+ ])
+ expect(kinds('2 * {spa {base}')).toEqual([
+ 'number:2',
+ 'operator:*',
+ 'reference:{spa ',
+ 'reference:{base}'
+ ])
+ expect(kinds('1 # 2')).toEqual(['number:1', 'invalid:#', 'number:2'])
+ expect(formulaTokens('{a} + 1').map(({ from, to }) => [from, to])).toEqual([
+ [0, 3],
+ [4, 5],
+ [6, 7]
+ ])
+})
+
+test('a long formula breaks before its outermost and, or, + and -, and reads back the same', () => {
+ const { graph, collection, parse } = setup('BOOLEAN')
+ graph.createVariable('viewport', 'FLOAT', collection.id, 1280)
+ graph.createVariable('loading', 'BOOLEAN', collection.id, false)
+ const source = '{viewport} > 1024 and not {loading} and ({base} or {viewport} < 600)'
+ const { value } = parse(source)
+ expect(formatVariableFormula(graph, value, { width: 40 })).toBe(
+ '{viewport} > 1024\n and not {loading}\n and ({base} or {viewport} < 600)'
+ )
+ expect(formatVariableFormula(graph, value, { width: 200 })).toBe(source)
+ expect(parse(formatVariableFormula(graph, value, { width: 40 })).value).toEqual(value)
+ // Width counts references as they are shown, such as pills that drop the braces.
+ const shown = (id: string) => graph.variables.get(id)?.name ?? id
+ expect(formatVariableFormula(graph, value, { width: 60, display: shown })).toBe(source)
+ // A chain inside parentheses, or an operator that does not break, stays on its line.
+ expect(formatVariableFormula(graph, parse('{viewport} * 2 > 1000').value, { width: 5 })).toBe(
+ '{viewport} * 2 > 1000'
+ )
+})
diff --git a/packages/vue/src/i18n/locales/de/variables/panel.json b/packages/vue/src/i18n/locales/de/variables/panel.json
index 421e76a69..ece518aa0 100644
--- a/packages/vue/src/i18n/locales/de/variables/panel.json
+++ b/packages/vue/src/i18n/locales/de/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Werte",
"expression": "CSS-Ausdruck",
"expressionHint": "Wird in CSS anstelle des Werts geschrieben, z. B. clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "CSS-Ausdruck hinzufügen",
+ "removeExpression": "CSS-Ausdruck entfernen",
+ "cssExpressionUnclosed": "Einer Funktion fehlt die )",
+ "cssExpressionSyntax": "Kein gültiges CSS",
+ "cssExpressionNegated": "Ein Token negierst du mit calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Kein Token heißt {name}",
+ "cssExpressionInvalid": "Kein gültiger Wert für {property}",
"scopes": "Geltungsbereiche",
"description": "Beschreibung",
"collection": "Sammlung",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} ist keine Design-Token-Datei",
"importMissingFile": "{file}, auf die {from} verweist, wurde nicht ausgewählt",
"importNothing": "Diese Dateien enthalten keine Design-Tokens.",
- "importAction": "Importieren"
+ "importAction": "Importieren",
+ "formula": "Formel",
+ "useFormula": "Formel verwenden",
+ "formulaPlaceholder": "Wert oder Formel"
}
diff --git a/packages/vue/src/i18n/locales/es/variables/panel.json b/packages/vue/src/i18n/locales/es/variables/panel.json
index ebf94dc14..40558c69c 100644
--- a/packages/vue/src/i18n/locales/es/variables/panel.json
+++ b/packages/vue/src/i18n/locales/es/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Valores",
"expression": "Expresión CSS",
"expressionHint": "Se escribe en CSS en lugar del valor, por ejemplo clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "Añadir expresión CSS",
+ "removeExpression": "Quitar la expresión CSS",
+ "cssExpressionUnclosed": "A una función le falta su )",
+ "cssExpressionSyntax": "CSS no válido",
+ "cssExpressionNegated": "Para negar un token, escribe calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Ningún token se llama {name}",
+ "cssExpressionInvalid": "No es un valor válido para {property}",
"scopes": "Ámbitos",
"description": "Descripción",
"collection": "Colección",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} no es un archivo de design tokens",
"importMissingFile": "No se eligió {file}, al que hace referencia {from}",
"importNothing": "Estos archivos no contienen design tokens.",
- "importAction": "Importar"
+ "importAction": "Importar",
+ "formula": "Fórmula",
+ "useFormula": "Usar una fórmula",
+ "formulaPlaceholder": "Valor o fórmula"
}
diff --git a/packages/vue/src/i18n/locales/fr/variables/panel.json b/packages/vue/src/i18n/locales/fr/variables/panel.json
index 63c57ed64..6662fc8ce 100644
--- a/packages/vue/src/i18n/locales/fr/variables/panel.json
+++ b/packages/vue/src/i18n/locales/fr/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Valeurs",
"expression": "Expression CSS",
"expressionHint": "Écrite à la place de la valeur en CSS, par exemple clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "Ajouter une expression CSS",
+ "removeExpression": "Supprimer l’expression CSS",
+ "cssExpressionUnclosed": "Il manque la ) d’une fonction",
+ "cssExpressionSyntax": "CSS non valide",
+ "cssExpressionNegated": "Pour inverser un jeton, écrivez calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Aucun jeton ne s’appelle {name}",
+ "cssExpressionInvalid": "Valeur non valide pour {property}",
"scopes": "Portées",
"description": "Description",
"collection": "Collection",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} n’est pas un fichier de design tokens",
"importMissingFile": "{file}, auquel {from} renvoie, n’a pas été choisi",
"importNothing": "Ces fichiers ne contiennent aucun design token.",
- "importAction": "Importer"
+ "importAction": "Importer",
+ "formula": "Formule",
+ "useFormula": "Utiliser une formule",
+ "formulaPlaceholder": "Valeur ou formule"
}
diff --git a/packages/vue/src/i18n/locales/it/variables/panel.json b/packages/vue/src/i18n/locales/it/variables/panel.json
index 9cb1857af..dec54048f 100644
--- a/packages/vue/src/i18n/locales/it/variables/panel.json
+++ b/packages/vue/src/i18n/locales/it/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Valori",
"expression": "Espressione CSS",
"expressionHint": "Scritta al posto del valore in CSS, ad esempio clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "Aggiungi espressione CSS",
+ "removeExpression": "Rimuovi l’espressione CSS",
+ "cssExpressionUnclosed": "A una funzione manca la )",
+ "cssExpressionSyntax": "CSS non valido",
+ "cssExpressionNegated": "Per negare un token, scrivi calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Nessun token si chiama {name}",
+ "cssExpressionInvalid": "Valore non valido per {property}",
"scopes": "Ambiti",
"description": "Descrizione",
"collection": "Raccolta",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} non è un file di design token",
"importMissingFile": "{file}, a cui rimanda {from}, non è stato scelto",
"importNothing": "Questi file non contengono design token.",
- "importAction": "Importa"
+ "importAction": "Importa",
+ "formula": "Formula",
+ "useFormula": "Usa una formula",
+ "formulaPlaceholder": "Valore o formula"
}
diff --git a/packages/vue/src/i18n/locales/ja/variables/panel.json b/packages/vue/src/i18n/locales/ja/variables/panel.json
index 20f45797d..3c66cf279 100644
--- a/packages/vue/src/i18n/locales/ja/variables/panel.json
+++ b/packages/vue/src/i18n/locales/ja/variables/panel.json
@@ -24,6 +24,13 @@
"values": "値",
"expression": "CSS 式",
"expressionHint": "CSS で値の代わりに記述されます。例: clamp(1rem, 4vw, 1.5rem)",
+ "addExpression": "CSS 式を追加",
+ "removeExpression": "CSS 式を削除",
+ "cssExpressionUnclosed": "関数の ) がありません",
+ "cssExpressionSyntax": "CSS として正しくありません",
+ "cssExpressionNegated": "トークンを負にするには calc(-1 * var({property})) と書きます",
+ "cssExpressionUnknownToken": "{name} という名前のトークンはありません",
+ "cssExpressionInvalid": "{property} に使えない値です",
"scopes": "スコープ",
"description": "説明",
"collection": "コレクション",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} はデザイントークンのファイルではありません",
"importMissingFile": "{from} が参照する {file} が選ばれていません",
"importNothing": "これらのファイルにデザイントークンはありません。",
- "importAction": "読み込む"
+ "importAction": "読み込む",
+ "formula": "数式",
+ "useFormula": "数式を使用",
+ "formulaPlaceholder": "値または数式"
}
diff --git a/packages/vue/src/i18n/locales/pl/variables/panel.json b/packages/vue/src/i18n/locales/pl/variables/panel.json
index 7f93a35a2..765bfbd9e 100644
--- a/packages/vue/src/i18n/locales/pl/variables/panel.json
+++ b/packages/vue/src/i18n/locales/pl/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Wartości",
"expression": "Wyrażenie CSS",
"expressionHint": "Zapisywane w CSS zamiast wartości, na przykład clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "Dodaj wyrażenie CSS",
+ "removeExpression": "Usuń wyrażenie CSS",
+ "cssExpressionUnclosed": "Funkcji brakuje nawiasu )",
+ "cssExpressionSyntax": "Niepoprawny CSS",
+ "cssExpressionNegated": "Aby zanegować token, wpisz calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Żaden token nie nazywa się {name}",
+ "cssExpressionInvalid": "Nieprawidłowa wartość dla {property}",
"scopes": "Zakresy",
"description": "Opis",
"collection": "Kolekcja",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} nie jest plikiem tokenów projektowych",
"importMissingFile": "Nie wybrano pliku {file}, do którego odwołuje się {from}",
"importNothing": "Te pliki nie zawierają tokenów projektowych.",
- "importAction": "Importuj"
+ "importAction": "Importuj",
+ "formula": "Formuła",
+ "useFormula": "Użyj formuły",
+ "formulaPlaceholder": "Wartość lub formuła"
}
diff --git a/packages/vue/src/i18n/locales/ru/variables/panel.json b/packages/vue/src/i18n/locales/ru/variables/panel.json
index 1010dd9c4..1a2775059 100644
--- a/packages/vue/src/i18n/locales/ru/variables/panel.json
+++ b/packages/vue/src/i18n/locales/ru/variables/panel.json
@@ -24,6 +24,13 @@
"values": "Значения",
"expression": "Выражение CSS",
"expressionHint": "Записывается в CSS вместо значения, например clamp(1rem, 4vw, 1.5rem).",
+ "addExpression": "Добавить CSS-выражение",
+ "removeExpression": "Удалить CSS-выражение",
+ "cssExpressionUnclosed": "У функции нет закрывающей )",
+ "cssExpressionSyntax": "Некорректный CSS",
+ "cssExpressionNegated": "Чтобы взять токен с минусом, напишите calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "Нет токена с именем {name}",
+ "cssExpressionInvalid": "Недопустимое значение для {property}",
"scopes": "Области применения",
"description": "Описание",
"collection": "Коллекция",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} — не файл дизайн-токенов",
"importMissingFile": "Не выбран {file}, на который ссылается {from}",
"importNothing": "В этих файлах нет дизайн-токенов.",
- "importAction": "Импортировать"
+ "importAction": "Импортировать",
+ "formula": "Формула",
+ "useFormula": "Использовать формулу",
+ "formulaPlaceholder": "Значение или формула"
}
diff --git a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json b/packages/vue/src/i18n/locales/zh-cn/variables/panel.json
index 3a8a3731b..0255a4871 100644
--- a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json
+++ b/packages/vue/src/i18n/locales/zh-cn/variables/panel.json
@@ -24,6 +24,13 @@
"values": "值",
"expression": "CSS 表达式",
"expressionHint": "在 CSS 中替代该值,例如 clamp(1rem, 4vw, 1.5rem)。",
+ "addExpression": "添加 CSS 表达式",
+ "removeExpression": "移除 CSS 表达式",
+ "cssExpressionUnclosed": "函数缺少 )",
+ "cssExpressionSyntax": "不是有效的 CSS",
+ "cssExpressionNegated": "要取负值,请写 calc(-1 * var({property}))",
+ "cssExpressionUnknownToken": "没有名为 {name} 的令牌",
+ "cssExpressionInvalid": "不是 {property} 的有效值",
"scopes": "范围",
"description": "描述",
"collection": "集合",
@@ -118,5 +125,8 @@
"importInvalidFile": "{file} 不是设计令牌文件",
"importMissingFile": "未选择 {from} 引用的 {file}",
"importNothing": "这些文件中没有设计令牌。",
- "importAction": "导入"
+ "importAction": "导入",
+ "formula": "公式",
+ "useFormula": "使用公式",
+ "formulaPlaceholder": "值或公式"
}
diff --git a/packages/vue/src/i18n/messages/variables/panel.ts b/packages/vue/src/i18n/messages/variables/panel.ts
index 4b2af272f..198c34308 100644
--- a/packages/vue/src/i18n/messages/variables/panel.ts
+++ b/packages/vue/src/i18n/messages/variables/panel.ts
@@ -28,6 +28,13 @@ export const variablesMessageDefaults = {
values: 'Values',
expression: 'CSS expression',
expressionHint: 'Written instead of the value in CSS, such as clamp(1rem, 4vw, 1.5rem).',
+ addExpression: 'Add CSS expression',
+ removeExpression: 'Remove CSS expression',
+ cssExpressionUnclosed: 'A function is missing its )',
+ cssExpressionSyntax: 'Not valid CSS',
+ cssExpressionNegated: params('To negate a token, write calc(-1 * var({property}))'),
+ cssExpressionUnknownToken: params('No token is named {name}'),
+ cssExpressionInvalid: params('Not a valid value for {property}'),
scopes: 'Scopes',
description: 'Description',
collection: 'Collection',
@@ -127,7 +134,10 @@ export const variablesMessageDefaults = {
importInvalidFile: params('{file} isn’t a design token file'),
importMissingFile: params('{file}, which {from} refers to, wasn’t picked'),
importNothing: 'These files hold no design tokens.',
- importAction: 'Import'
+ importAction: 'Import',
+ formula: 'Formula',
+ useFormula: 'Use a formula',
+ formulaPlaceholder: 'Value or formula'
} as const
export const variablesMessages = i18n('variables', variablesMessageDefaults)
diff --git a/packages/vue/src/variables/use.ts b/packages/vue/src/variables/use.ts
index 8da0eac84..9768f6bc7 100644
--- a/packages/vue/src/variables/use.ts
+++ b/packages/vue/src/variables/use.ts
@@ -28,12 +28,16 @@ export function useVariables() {
if (!activeCollectionId.value && cols[0]) activeCollectionId.value = cols[0].id
})
- const activeCollection = computed(() => editor.getCollection(activeCollectionId.value) ?? null)
+ const activeCollection = computed(
+ () => collections.value.find((collection) => collection.id === activeCollectionId.value) ?? null
+ )
const activeModes = computed(() => activeCollection.value?.modes ?? [])
const variables = useSceneComputed(() => {
if (!activeCollectionId.value) return [] as Variable[]
- const all = editor.getVariablesForCollection(activeCollectionId.value)
+ const all = editor
+ .getVariablesForCollection(activeCollectionId.value)
+ .map((variable) => structuredClone(variable))
return fuzzyFilter(all, ['name', 'description'], searchTerm.value)
})
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index bd0c55bfe..cc2f98998 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -22,6 +22,10 @@ openpencil tree design.fig
Use `openpencil --help`, per-command help, and the connected MCP server’s tool schemas to check the installed version’s capabilities. See the [CLI reference](https://openpencil.dev/reference/cli) and [MCP guide](https://openpencil.dev/programmable/mcp-server) for current documentation.
+## Variable formulas
+
+Inside `eval`, use `openpencil.setVariableFormula('Spacing', 'large', '{base} * 2')` for numeric formulas or `openpencil.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')` for Boolean formulas, which use `and`, `or`, `not` and number comparisons. Collections and variables must already exist. An optional fourth argument selects a mode by name; otherwise the default mode is edited. The call validates before mutation and returns the resolved value. Length formulas use stored pixels. The CSS stylesheet writes number formulas as `calc()`; design-token files hold the result with the formula in `$extensions`.
+
## Requirements
```bash
diff --git a/src/AGENTS.md b/src/AGENTS.md
index 52fb73eab..2ca41323c 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -66,7 +66,7 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and
### Layout
-- Lay a component out by the space it is given, not the window: panels, dialogs, and inspectors appear in docks, split views, and phones alike. Restyle with named Tailwind container queries (`@container/name`, `@2xl/name:`) on the element whose width matters, which for a list beside an inspector is the list itself (`src/theme/tokens-panel.ts`, `src/theme/panel/properties-tabs.ts`).
+- Lay a component out by the space it is given, not the window: panels, dialogs, and inspectors appear in docks, split views, and phones alike. Restyle with named Tailwind container queries (`@container/name`, `@2xl/name:`) on the element whose width matters, which for a list beside an inspector is the list itself (`src/theme/variables/table.ts`, `src/theme/panel/properties-tabs.ts`).
- When the width changes structure, such as a side inspector becoming a drill-in, measure the container with VueUse `useElementSize` and keep the threshold beside the theme (`TOKENS_PANEL_COMPACT_WIDTH`).
- Viewport breakpoints (`md:`, `useViewportKind`) are for app-shell decisions only: dock placement, sheets versus popovers, full-screen dialogs (`src/theme/dialog/index.ts`).
- Stories for adaptive components render fixed container widths as separate stories rather than relying on the viewport toolbar (`src/components/variables/TokensPanel.stories.ts`).
diff --git a/src/app/editor/tokens/css-expression.ts b/src/app/editor/tokens/css-expression.ts
new file mode 100644
index 000000000..b36d0c3fa
--- /dev/null
+++ b/src/app/editor/tokens/css-expression.ts
@@ -0,0 +1,50 @@
+import { cssTokenProperty, cssValueTokens, TOKEN_UNIT_PROPERTY } from '@open-pencil/dom-css/export'
+import type { TokenUnit } from '@open-pencil/scene-graph'
+
+/**
+ * Units that resolve against the window, a container or the text, which a preview can only
+ * approximate. `rem` is exact: tokens and the app both take the root as 16px.
+ */
+const APPROXIMATE_UNITS = /\d(?:[sld]?v(?:w|h|i|b|min|max)|cq\w+|em|ex|ch|lh)\b/
+
+export interface CSSExpressionPreview {
+ /** The value in stored units, as a number token holds it: pixels, milliseconds, degrees. */
+ value: number
+ /** Whether it depends on the window or the text, so it holds only where it was computed. */
+ approximate: boolean
+}
+
+/**
+ * What a CSS expression comes to, computed by the browser with the tokens it names: `measure`
+ * applies the value to `property` with those custom properties and reads the computed value.
+ * Percentages, which resolve against a container, have no preview.
+ */
+export function cssExpressionPreview(
+ css: string,
+ unit: TokenUnit,
+ tokens: ReadonlyMap<string, string>,
+ measure: (property: string, value: string, variables: ReadonlyMap<string, string>) => string
+): CSSExpressionPreview | undefined {
+ if (unit === '%' || css.includes('%')) return undefined
+ const property = TOKEN_UNIT_PROPERTY[unit]
+ const names = cssValueTokens(css).flatMap((token) => {
+ const name = cssTokenProperty(token)
+ return name ? [name] : []
+ })
+ const variables = new Map(
+ names.flatMap((name) => {
+ const value = tokens.get(name)
+ return value ? [[name, value] as const] : []
+ })
+ )
+ if (variables.size !== new Set(names).size) return undefined
+ const computed = measure(property, css, variables)
+ const number = Number.parseFloat(computed)
+ if (!Number.isFinite(number)) return undefined
+ // Durations compute in seconds; the token holds milliseconds unless its unit is seconds.
+ const value = property === 'transition-duration' && unit === 'ms' ? number * 1000 : number
+ const approximate =
+ APPROXIMATE_UNITS.test(css) ||
+ [...variables.values()].some((text) => APPROXIMATE_UNITS.test(text))
+ return { value, approximate }
+}
diff --git a/src/app/editor/tokens/model.ts b/src/app/editor/tokens/model.ts
index 4f795bc1a..4654bbfc5 100644
--- a/src/app/editor/tokens/model.ts
+++ b/src/app/editor/tokens/model.ts
@@ -11,10 +11,13 @@ import {
import {
tokenNumberFromUnit,
tokenNumberInUnit,
+ variableValueReferences,
+ printFormula,
type Color,
type SceneGraph,
type Variable,
type VariableCollection,
+ type VariableColorExpression,
type VariableValue
} from '@open-pencil/scene-graph'
import { colorToHex } from '@open-pencil/scene-graph/color'
@@ -25,8 +28,12 @@ export interface TokenModeValue {
modeId: string
css: string
color?: Color
+ /** A formula as it reads, with variable names; `css` holds what it gives in this mode. */
+ formula?: string
/** The aliased variable's name, when the value points at another token. */
alias?: string
+ /** What an alias gives in this mode, in the token's unit; a color shows as its swatch. */
+ result?: string
/** A CSS expression written instead of the stored number, such as `clamp(…)`. */
expression?: string
}
@@ -39,12 +46,46 @@ export interface TokenRow {
values: TokenModeValue[]
}
+export interface TokenFormulaActions {
+ /** Variables a formula can use; a true/false formula can also compare numbers. */
+ candidates: AliasCandidate[]
+ parse: (modeId: string, source: string) => { value: VariableValue; resolved: number | boolean }
+ format: (value: VariableValue) => string
+ reference: (id: string) => string
+}
+
export interface TokenGroup {
/** The name path above the rows, `Blue` for `Blue/500`; empty for top-level tokens. */
path: string
rows: TokenRow[]
}
+function colorExpressionMode(
+ graph: SceneGraph,
+ variable: Variable,
+ modeId: string,
+ value: VariableColorExpression
+): TokenModeValue {
+ const resolved = graph.resolveVariable(variable.id, modeId)
+ const color = typeof resolved === 'object' ? resolved : undefined
+ const base =
+ 'aliasId' in value.color
+ ? (graph.variables.get(value.color.aliasId)?.name ?? value.color.aliasId)
+ : colorToHex(value.color)
+ const opacity =
+ typeof value.opacity === 'number'
+ ? `${tokenNumberToCSS(value.opacity, 'none')}%`
+ : (graph.variables.get(value.opacity.aliasId)?.name ?? value.opacity.aliasId)
+ const label = `${base} · ${opacity}`
+ return { modeId, css: label, alias: label, color }
+}
+
+function aliasResult(variable: Variable, resolved: VariableValue | undefined) {
+ if (typeof resolved === 'number') return tokenNumberToCSS(resolved, variableUnit(variable))
+ if (typeof resolved === 'boolean' || typeof resolved === 'string') return String(resolved)
+ return undefined
+}
+
function modeValue(
graph: SceneGraph,
variable: Variable,
@@ -52,12 +93,33 @@ function modeValue(
value: VariableValue | undefined
): TokenModeValue {
const expression = variable.expressions?.[modeId]?.css
+ if (typeof value === 'object' && 'expression' in value) {
+ 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
+ }
+ }
if (typeof value === 'object' && 'aliasId' in value) {
const target = graph.variables.get(value.aliasId)
// The column's own mode, so Dark previews what the alias gives in Dark.
- const resolved = graph.resolveVariable(value.aliasId, modeId)
+ const resolved = graph.resolveVariable(variable.id, modeId)
const color = typeof resolved === 'object' && 'r' in resolved ? resolved : undefined
- return { modeId, css: target?.name ?? value.aliasId, alias: target?.name, color, expression }
+ return {
+ modeId,
+ css: target?.name ?? value.aliasId,
+ alias: target?.name,
+ result: aliasResult(variable, resolved),
+ color,
+ expression
+ }
}
if (typeof value === 'object') return { modeId, css: colorToHex(value), color: value, expression }
if (typeof value === 'number')
@@ -165,7 +227,9 @@ export function searchTokenIds(rows: readonly TokenRow[], query: string): Set<st
name: row.variable.name,
css: `--${row.cssName}`,
description: row.variable.description,
- values: row.values.flatMap((value) => compact([value.css, value.alias, value.expression]))
+ values: row.values.flatMap((value) =>
+ compact([value.css, value.alias, value.expression, value.formula])
+ )
}))
return new Set(fuzzyFilter(entries, TOKEN_SEARCH_KEYS, query).map((entry) => entry.id))
}
@@ -229,6 +293,44 @@ export interface AliasCandidate {
name: string
collection: string
color?: Color
+ text?: string
+}
+
+/** A reference pill shows the last part of a variable's name, as its group row does. */
+export function referencePillName(name: string) {
+ return name.split('/').at(-1) ?? name
+}
+
+/** A number token a CSS expression can name as `var(--name)`. */
+export interface CSSReferenceCandidate {
+ id: string
+ name: string
+ cssName: string
+ collection: string
+ /** The token's value in its unit, as the list shows it. */
+ text: string
+}
+
+/** Every other number token, by the CSS name the stylesheet declares it under. */
+export function cssReferenceCandidates(
+ graph: SceneGraph,
+ variable: Variable
+): CSSReferenceCandidate[] {
+ const names = variableCSSNames(collectionVariables(graph))
+ return [...graph.variables.values()].flatMap((candidate) => {
+ const cssName = names.get(candidate.id)
+ if (candidate.id === variable.id || candidate.type !== 'FLOAT' || !cssName) return []
+ const number = graph.resolveNumberVariable(candidate.id)
+ return [
+ {
+ id: candidate.id,
+ name: candidate.name,
+ cssName,
+ collection: graph.variableCollections.get(candidate.collectionId)?.name ?? '',
+ text: number === undefined ? '—' : tokenNumberToCSS(number, variableUnit(candidate))
+ }
+ ]
+ })
}
/** Whether `fromId` reaches `targetId` through aliases in any mode. */
@@ -242,11 +344,8 @@ function aliasesTo(
if (seen.has(fromId)) return false
seen.add(fromId)
const from = graph.variables.get(fromId)
- return Object.values(from?.valuesByMode ?? {}).some(
- (value) =>
- typeof value === 'object' &&
- 'aliasId' in value &&
- aliasesTo(graph, value.aliasId, targetId, seen)
+ return Object.values(from?.valuesByMode ?? {}).some((value) =>
+ variableValueReferences(value).some((id) => aliasesTo(graph, id, targetId, seen))
)
}
@@ -255,14 +354,34 @@ function aliasesTo(
* points back at it, which would make the two resolve to nothing.
*/
export function aliasCandidates(graph: SceneGraph, variable: Variable): AliasCandidate[] {
+ return referenceCandidates(graph, variable, [variable.type])
+}
+
+/** Variables a number or true/false formula can refer to: a true/false one compares numbers too. */
+export function formulaCandidates(graph: SceneGraph, variable: Variable): AliasCandidate[] {
+ return referenceCandidates(
+ graph,
+ variable,
+ variable.type === 'BOOLEAN' ? ['BOOLEAN', 'FLOAT'] : [variable.type]
+ )
+}
+
+function referenceCandidates(
+ graph: SceneGraph,
+ variable: Variable,
+ types: readonly Variable['type'][]
+): AliasCandidate[] {
return [...graph.variables.values()].flatMap((candidate) => {
- if (candidate.type !== variable.type || aliasesTo(graph, candidate.id, variable.id)) return []
+ if (!types.includes(candidate.type) || aliasesTo(graph, candidate.id, variable.id)) return []
+ const number =
+ candidate.type === 'FLOAT' ? graph.resolveNumberVariable(candidate.id) : undefined
return [
{
id: candidate.id,
name: candidate.name,
collection: graph.variableCollections.get(candidate.collectionId)?.name ?? '',
- color: variable.type === 'COLOR' ? graph.resolveColorVariable(candidate.id) : undefined
+ color: candidate.type === 'COLOR' ? graph.resolveColorVariable(candidate.id) : undefined,
+ text: number === undefined ? undefined : tokenNumberToCSS(number, variableUnit(candidate))
}
]
})
diff --git a/src/app/editor/tokens/value-editor.ts b/src/app/editor/tokens/value-editor.ts
new file mode 100644
index 000000000..e00e5e264
--- /dev/null
+++ b/src/app/editor/tokens/value-editor.ts
@@ -0,0 +1,33 @@
+import type { Variable, VariableValue } from '@open-pencil/scene-graph'
+
+import { parseTokenValueText, tokenValueText, type TokenFormulaActions } from './model'
+
+export interface TokenValueEdit {
+ value: VariableValue
+ resolved: number | boolean
+ kind: 'literal' | 'reference' | 'formula'
+}
+
+/** A value as the field shows it: a number in the token's unit, or the formula's source. */
+export function tokenEditorText(variable: Variable, modeId: string, formula: TokenFormulaActions) {
+ const value = variable.valuesByMode[modeId]
+ return typeof value === 'object' ? formula.format(value) : tokenValueText(variable, value)
+}
+
+/**
+ * Read the field: a plain number is typed in the token's unit, as the number field took it;
+ * anything else is a formula, whose numbers are stored units.
+ */
+export function parseTokenEditorText(
+ variable: Variable,
+ modeId: string,
+ source: string,
+ formula: TokenFormulaActions
+): TokenValueEdit {
+ const text = source.trim()
+ 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' }
+}
diff --git a/src/components/ui/binding/VariablePicker.vue b/src/components/ui/binding/VariablePicker.vue
index da06eb560..502b9b0c9 100644
--- a/src/components/ui/binding/VariablePicker.vue
+++ b/src/components/ui/binding/VariablePicker.vue
@@ -34,7 +34,12 @@ const {
ui
} = defineProps<VariablePickerProps>()
const open = defineModel<boolean>('open', { default: false })
-const emit = defineEmits<{ select: [id: string]; detach: []; create: [name: string] }>()
+const emit = defineEmits<{
+ select: [id: string]
+ detach: []
+ create: [name: string]
+ closeAutoFocus: [event: Event]
+}>()
const { common } = useI18n()
const creating = ref(false)
@@ -90,6 +95,7 @@ defineOptions({ inheritAttrs: false })
:tooltip="triggerLabel"
:side="side"
@select="emit('select', $event)"
+ @close-auto-focus="emit('closeAutoFocus', $event)"
>
<template #trigger>
<BindingTrigger
@@ -115,7 +121,15 @@ defineOptions({ inheritAttrs: false })
/>
<icon-lucide-diamond v-else class="size-3.5 text-muted" />
</template>
- <template #footer>
+ <template #trailing="{ item }">
+ <span
+ v-if="items.find((entry) => entry.id === item.value)?.text"
+ class="shrink-0 text-muted tabular-nums"
+ >
+ {{ items.find((entry) => entry.id === item.value)?.text }}
+ </span>
+ </template>
+ <template v-if="state !== 'unbound' || creating || createLabel" #footer>
<AppButton
v-if="state !== 'unbound'"
size="xs"
diff --git a/src/components/ui/binding/picker.ts b/src/components/ui/binding/picker.ts
index ffbdd13df..1dda6cef9 100644
--- a/src/components/ui/binding/picker.ts
+++ b/src/components/ui/binding/picker.ts
@@ -10,6 +10,8 @@ export interface VariablePickerItem {
collection?: string
/** A color variable's value, shown as a swatch in place of the variable icon. */
color?: Color
+ /** Resolved numeric value, or mixed/unresolved state for the selected targets. */
+ text?: string
}
export interface VariablePickerProps {
diff --git a/src/components/ui/select/AppPicker.vue b/src/components/ui/select/AppPicker.vue
index 0e0257f3b..0d2915f27 100644
--- a/src/components/ui/select/AppPicker.vue
+++ b/src/components/ui/select/AppPicker.vue
@@ -52,6 +52,7 @@ export interface AppPickerSlots {
leading?(props: { item: AppPickerItem }): VNode[]
/** A control at the end of the search field that narrows the list, such as a category. */
'search-trailing'?(): VNode[]
+ trailing?(props: { item: AppPickerItem }): VNode[]
/** Actions or details below the list; `highlighted` is the item under the pointer or keys. */
footer?(props: { close: () => void; highlighted: AppPickerItem | null }): VNode[]
}
@@ -99,7 +100,11 @@ const {
align = 'start',
ui
} = defineProps<AppPickerProps>()
-const emit = defineEmits<{ select: [value: string]; loadMore: [] }>()
+const emit = defineEmits<{
+ select: [value: string]
+ loadMore: []
+ closeAutoFocus: [event: Event]
+}>()
const slots = defineSlots<AppPickerSlots>()
const open = defineModel<boolean>('open', { default: false })
const { portalActive } = useRetainedPopup(open, () => close())
@@ -193,6 +198,7 @@ function select(value: AcceptableValue) {
:aria-label="heading"
:class="styles.content({ class: ui?.content })"
@open-auto-focus.prevent
+ @close-auto-focus="emit('closeAutoFocus', $event)"
>
<div :class="styles.header({ class: ui?.header })">
<h3 :class="styles.title({ class: ui?.title })">{{ heading }}</h3>
@@ -270,6 +276,7 @@ function select(value: AcceptableValue) {
{{ item.description }}
</span>
</span>
+ <slot name="trailing" :item="item" />
<icon-lucide-check
v-if="item.value === selected"
:class="styles.check({ class: ui?.check })"
diff --git a/src/components/variables/CollectionInspector.vue b/src/components/variables/CollectionInspector.vue
index cf93aec8d..0f5faae47 100644
--- a/src/components/variables/CollectionInspector.vue
+++ b/src/components/variables/CollectionInspector.vue
@@ -33,9 +33,10 @@ import AppInput from '@/components/ui/input/AppInput.vue'
import { useMenuUI } from '@/components/ui/menu/menu'
import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import { useConditionLabels } from '@/components/variables/useConditionLabels'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import inspectorTheme from '@/theme/variables/inspector'
const { collection, layout = 'side' } = defineProps<{
collection: VariableCollection
@@ -57,7 +58,7 @@ const emit = defineEmits<{
const { variables } = useI18n()
const { kindOptions } = useConditionLabels()
-const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const ui = computed(() => tv(inspectorTheme)({ layout }))
const menu = useMenuUI({ content: 'w-44', item: 'justify-start gap-2' })
const dangerItem = useMenuUI({ item: 'justify-start gap-2 text-error' }).item
@@ -99,7 +100,8 @@ function commitName() {
else draft.name = collection.name
}
-const attributeErrorId = `${useId()}-attribute`
+const attributeId = `${useId()}-attribute`
+const attributeErrorId = `${attributeId}-error`
/** Blank restores the default; anything else must be an attribute a selector can name as is. */
const attributeInvalid = computed(() => {
const name = draft.attribute.trim()
@@ -188,7 +190,7 @@ function attributeDone(event: KeyboardEvent) {
</script>
<template>
- <aside :class="ui.inspector()" data-test-id="collection-inspector">
+ <aside :class="ui.root()" data-test-id="collection-inspector">
<section :class="ui.section()">
<span :class="ui.label()" class="flex items-center gap-1.5">
{{ variables.collection }}
@@ -231,9 +233,13 @@ function attributeDone(event: KeyboardEvent) {
</DropdownMenuPortal>
</DropdownMenuRoot>
</div>
- <label v-if="collection.modes.length > 1" :class="ui.field()">
- <span :class="ui.label()">{{ variables.modeAttribute }}</span>
+ <PanelFieldGroup
+ v-if="collection.modes.length > 1"
+ :label="variables.modeAttribute"
+ :for="attributeId"
+ >
<AppInput
+ :id="attributeId"
v-model="draft.attribute"
size="sm"
:placeholder="defaultModeAttributeName(collection)"
@@ -251,12 +257,12 @@ function attributeDone(event: KeyboardEvent) {
<span v-else-if="attributeExample" :class="ui.hint()">{{
variables.modeAttributeHint({ example: attributeExample })
}}</span>
- </label>
+ </PanelFieldGroup>
</section>
<section :class="ui.section()">
<div class="flex items-center justify-between">
- <h3 :class="ui.sectionTitle()">{{ variables.modes }}</h3>
+ <h3 :class="ui.title()">{{ variables.modes }}</h3>
<IconButton
:label="variables.addMode"
data-test-id="variables-add-mode"
diff --git a/src/components/variables/TokenBulkInspector.vue b/src/components/variables/TokenBulkInspector.vue
index 017cebeb9..3e9a21cdd 100644
--- a/src/components/variables/TokenBulkInspector.vue
+++ b/src/components/variables/TokenBulkInspector.vue
@@ -1,12 +1,13 @@
<script setup lang="ts">
import { tv } from 'tailwind-variants'
-import { computed, onMounted, ref, useTemplateRef, type ComponentPublicInstance } from 'vue'
+import { computed, onMounted, ref, useId, useTemplateRef, type ComponentPublicInstance } from 'vue'
import { useI18n } from '@open-pencil/vue'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
+import inspectorTheme from '@/theme/variables/inspector'
/** Actions for several selected tokens, and naming a new group for the selection. */
const {
@@ -23,8 +24,9 @@ const {
const emit = defineEmits<{ moveToGroup: [group: string]; duplicate: []; remove: [] }>()
const { variables } = useI18n()
-const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const ui = computed(() => tv(inspectorTheme)({ layout }))
const group = ref('')
+const groupId = `${useId()}-group`
const groupInput = useTemplateRef<ComponentPublicInstance>('groupInput')
onMounted(() => {
@@ -46,15 +48,15 @@ function move() {
</script>
<template>
- <aside :class="ui.inspector()" data-test-id="token-bulk-inspector">
+ <aside :class="ui.root()" data-test-id="token-bulk-inspector">
<section :class="ui.section()">
- <h3 :class="ui.sectionTitle()">{{ variables.selectedCount({ count }) }}</h3>
+ <h3 :class="ui.title()">{{ variables.selectedCount({ count }) }}</h3>
</section>
<section :class="ui.section()">
- <label :class="ui.field()">
- <span :class="ui.label()">{{ variables.moveToGroup }}</span>
+ <PanelFieldGroup :label="variables.moveToGroup" :for="groupId">
<div class="flex items-center gap-1">
<AppInput
+ :id="groupId"
ref="groupInput"
v-model="group"
size="sm"
@@ -67,7 +69,7 @@ function move() {
{{ variables.move }}
</AppButton>
</div>
- </label>
+ </PanelFieldGroup>
</section>
<section :class="ui.section()">
<AppButton variant="ghost" size="sm" class="self-start" @click="emit('duplicate')">
diff --git a/src/components/variables/TokenCSSExpression.vue b/src/components/variables/TokenCSSExpression.vue
new file mode 100644
index 000000000..4cef87766
--- /dev/null
+++ b/src/components/variables/TokenCSSExpression.vue
@@ -0,0 +1,191 @@
+<script setup lang="ts">
+import { computedAsync } from '@vueuse/core'
+import { tv } from 'tailwind-variants'
+import { computed, ref, useTemplateRef, watch } from 'vue'
+
+import {
+ cssExpressionProblem,
+ loadTokenValidator,
+ tokenNumberToCSS
+} from '@open-pencil/dom-css/export'
+import type { TokenUnit } from '@open-pencil/scene-graph'
+import { useI18n } from '@open-pencil/vue'
+
+import { cssExpressionPreview } from '@/app/editor/tokens/css-expression'
+import type { CSSReferenceCandidate } from '@/app/editor/tokens/model'
+import { VariablePicker } from '@/components/ui/binding'
+import cssExpressionTheme from '@/theme/variables/css-expression'
+
+import { cssValueDialect } from './formula-field/dialects/css'
+import type { FormulaSelection } from './formula-field/source'
+import type TokenFormulaField from './TokenFormulaField.vue'
+
+/** A value only CSS can draw, shown where the field is empty. */
+const EXAMPLE = 'clamp(1rem, 4vw, 1.5rem)'
+
+const css = defineModel<string>({ required: true })
+const { id, label, unit, candidates, describedBy } = defineProps<{
+ id: string
+ label: string
+ unit: TokenUnit
+ /** Number tokens the expression can name as `var(--name)`. */
+ candidates: CSSReferenceCandidate[]
+ describedBy: string
+}>()
+const emit = defineEmits<{ commit: [css: string]; cancel: [] }>()
+const { variables } = useI18n()
+const ui = tv(cssExpressionTheme)()
+const field = useTemplateRef<InstanceType<typeof TokenFormulaField>>('field')
+
+const reference = (candidate: CSSReferenceCandidate) => `var(--${candidate.cssName})`
+const completions = computed(() =>
+ candidates.map((candidate) => ({
+ label: `--${candidate.cssName}`,
+ section: candidate.collection,
+ detail: candidate.text,
+ insert: reference(candidate)
+ }))
+)
+const byProperty = computed(
+ () => new Map(candidates.map((candidate) => [`--${candidate.cssName}`, candidate]))
+)
+const pickerItems = computed(() =>
+ candidates.map(({ id: candidateId, name, collection, text }) => ({
+ id: candidateId,
+ name,
+ collection,
+ text
+ }))
+)
+
+/** The custom property in a `var()` shows as a pill of its name; the tooltip gives the token. */
+function resolveReference(property: string) {
+ const candidate = byProperty.value.get(property)
+ if (!candidate) return undefined
+ return {
+ label: property,
+ tooltip: `${candidate.collection} · ${candidate.name} · ${candidate.text}`
+ }
+}
+
+/**
+ * What the expression comes to, computed by the browser on a hidden probe with the tokens it
+ * names, shown as the value field shows its result.
+ */
+const probe = useTemplateRef<HTMLDivElement>('probe')
+function measure(property: string, value: string, variables: ReadonlyMap<string, string>) {
+ const element = probe.value
+ if (!element) return ''
+ element.style.cssText = ''
+ for (const [name, text] of variables) element.style.setProperty(name, text)
+ element.style.setProperty(property, value)
+ return getComputedStyle(element).getPropertyValue(property)
+}
+const preview = computed(() => {
+ const text = css.value.trim()
+ if (!text || error.value || !probe.value) return undefined
+ const tokens = new Map(candidates.map((candidate) => [`--${candidate.cssName}`, candidate.text]))
+ return cssExpressionPreview(text, unit, tokens, measure)
+})
+const previewText = computed(() =>
+ preview.value ? tokenNumberToCSS(preview.value.value, unit) : undefined
+)
+
+/** Errors show once the expression is committed, as the value field's do. */
+const error = ref('')
+watch(css, () => (error.value = ''))
+const validator = computedAsync(loadTokenValidator, null)
+function message(text: string) {
+ if (!validator.value) return ''
+ const problem = cssExpressionProblem(
+ text,
+ unit,
+ new Set(byProperty.value.keys()),
+ validator.value,
+ (property, value) => CSS.supports(property, value)
+ )
+ if (!problem) return ''
+ if (problem.kind === 'unclosed') return variables.value.cssExpressionUnclosed
+ if (problem.kind === 'syntax') return variables.value.cssExpressionSyntax
+ if (problem.kind === 'negated-reference')
+ return variables.value.cssExpressionNegated({ property: problem.property })
+ if (problem.kind === 'unknown-token')
+ return variables.value.cssExpressionUnknownToken({ name: problem.name })
+ return variables.value.cssExpressionInvalid({ property: problem.property })
+}
+function commit() {
+ const text = css.value.trim()
+ error.value = text ? message(text) : ''
+ if (error.value) return false
+ emit('commit', text)
+ return true
+}
+function enter() {
+ if (commit()) field.value?.blur()
+}
+
+/** The picker puts `var(--name)` at the caret and gives the focus back to the field. */
+const selection = ref<FormulaSelection | null>(null)
+const insertionCaret = ref<number | null>(null)
+function insert(candidateId: string) {
+ const candidate = candidates.find((item) => item.id === candidateId)
+ if (!candidate) return
+ const text = reference(candidate)
+ const range = selection.value ?? { start: css.value.length, end: css.value.length }
+ css.value = css.value.slice(0, range.start) + text + css.value.slice(range.end)
+ insertionCaret.value = range.start + text.length
+}
+function restoreFocus(event: Event) {
+ if (insertionCaret.value === null) return
+ event.preventDefault()
+ const caret = insertionCaret.value
+ insertionCaret.value = null
+ field.value?.focus()
+ field.value?.setSelectionRange(caret, caret)
+}
+
+defineExpose({ focus: () => field.value?.focus() })
+</script>
+
+<template>
+ <!-- The field and its error sit in the value grid's first column, under the value field. -->
+ <div class="contents">
+ <div :class="ui.field()">
+ <TokenFormulaField
+ :id="id"
+ ref="field"
+ v-model="css"
+ :dialect="cssValueDialect"
+ :label="label"
+ prefix="CSS"
+ :placeholder="EXAMPLE"
+ :completions="completions"
+ :resolve="resolveReference"
+ :invalid="Boolean(error)"
+ :suffix="previewText"
+ :approximate="preview?.approximate"
+ :described-by="describedBy"
+ @change="commit"
+ @enter="enter"
+ @cancel="emit('cancel')"
+ @selection="selection = $event"
+ >
+ <template #actions>
+ <VariablePicker
+ :items="pickerItems"
+ state="unbound"
+ :trigger-label="variables.useVariable"
+ :search-placeholder="variables.searchVariables"
+ :empty-label="variables.noMatchingVariables"
+ :detach-label="variables.detachVariable"
+ @select="insert"
+ @close-auto-focus="restoreFocus"
+ />
+ </template>
+ </TokenFormulaField>
+ </div>
+
+ <p v-if="error" :class="[ui.error(), ui.field()]" role="alert">{{ error }}</p>
+ <div ref="probe" :class="ui.probe()" aria-hidden="true" />
+ </div>
+</template>
diff --git a/src/components/variables/TokenCellInput.vue b/src/components/variables/TokenCellInput.vue
index 6f8008895..306fdd623 100644
--- a/src/components/variables/TokenCellInput.vue
+++ b/src/components/variables/TokenCellInput.vue
@@ -2,7 +2,7 @@
import { tv } from 'tailwind-variants'
import { onMounted, ref, useTemplateRef } from 'vue'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import cellInputTheme from '@/theme/variables/cell-input'
/**
* Edits one cell of the token list in place. Enter or leaving the field commits, Escape cancels,
@@ -11,7 +11,7 @@ import tokensPanelTheme from '@/theme/tokens-panel'
const { value, label } = defineProps<{ value: string; label: string }>()
const emit = defineEmits<{ commit: [text: string]; cancel: [] }>()
-const ui = tv(tokensPanelTheme)()
+const ui = tv(cellInputTheme)()
const draft = ref(value)
const input = useTemplateRef('input')
let done = false
@@ -40,7 +40,7 @@ function onKeydown(event: KeyboardEvent) {
ref="input"
v-model="draft"
:aria-label="label"
- :class="ui.cellInput()"
+ :class="ui.base()"
data-test-id="variables-cell-input"
@keydown="onKeydown"
@click.stop
diff --git a/src/components/variables/TokenFormulaField.vue b/src/components/variables/TokenFormulaField.vue
new file mode 100644
index 000000000..20a5d03b9
--- /dev/null
+++ b/src/components/variables/TokenFormulaField.vue
@@ -0,0 +1,96 @@
+<script setup lang="ts">
+import { tv } from 'tailwind-variants'
+import { useSlots, useTemplateRef } from 'vue'
+
+import inputTheme from '@/theme/input/input'
+import formulaFieldTheme from '@/theme/variables/formula-field'
+
+import type { ExpressionDialect, ReferenceCompletion } from './formula-field/dialects/types'
+import type { FormulaPill, FormulaSelection } from './formula-field/source'
+import { useFormulaField } from './formula-field/useFormulaField'
+
+const model = defineModel<string>({ required: true })
+const {
+ dialect,
+ id,
+ label,
+ placeholder = '',
+ invalid = false,
+ describedBy,
+ resolve,
+ completions,
+ prefix,
+ suffix,
+ approximate = false,
+ unit
+} = defineProps<{
+ /** The syntax the field edits; fixed for the field's lifetime. */
+ dialect: ExpressionDialect
+ completions: readonly ReferenceCompletion[]
+ id: string
+ label: string
+ placeholder?: string
+ invalid?: boolean
+ describedBy?: string
+ resolve: (source: string) => FormulaPill | undefined
+ /** What the field holds, such as CSS, shown at its start. */
+ prefix?: string
+ /** What the formula gives, shown after its text. */
+ suffix?: string
+ /** Whether the result holds only where it was computed, such as for this window. */
+ approximate?: boolean
+ /** The unit a plain number is in, shown after it in place of a result. */
+ unit?: string
+}>()
+const emit = defineEmits<{
+ change: []
+ enter: []
+ cancel: []
+ selection: [range: FormulaSelection]
+}>()
+const field = useTemplateRef<HTMLDivElement>('field')
+const slots = useSlots()
+const ui = tv(formulaFieldTheme)()
+const inputUI = tv(inputTheme)
+
+const editing = useFormulaField(field, model, {
+ dialect,
+ label: () => label,
+ placeholder: () => placeholder,
+ completions: () => completions,
+ attributes: () => ({
+ id,
+ 'aria-invalid': String(invalid),
+ ...(describedBy ? { 'aria-describedby': describedBy } : {}),
+ 'aria-multiline': 'true'
+ }),
+ resolve: (source) => resolve(source),
+ result: () => (suffix ? `${approximate ? '≈' : '='} ${suffix}` : unit),
+ buttons: () => Boolean(slots.actions),
+ onChange: () => emit('change'),
+ onEnter: () => emit('enter'),
+ onCancel: () => emit('cancel'),
+ onSelection: (range) => emit('selection', range)
+})
+
+defineExpose({
+ focus: editing.focus,
+ blur: editing.blur,
+ setSelectionRange: editing.setSelectionRange
+})
+defineOptions({ inheritAttrs: false })
+</script>
+
+<template>
+ <div
+ :class="[inputUI({ size: 'sm' }), ui.root()]"
+ :data-invalid="invalid ? '' : undefined"
+ @pointerdown.self.prevent="editing.focus()"
+ >
+ <span v-if="prefix" :class="ui.prefix()" aria-hidden="true">{{ prefix }}</span>
+ <div ref="field" :class="ui.editor()" />
+ <span v-if="$slots.actions" :class="ui.actions()">
+ <slot name="actions" />
+ </span>
+ </div>
+</template>
diff --git a/src/components/variables/TokenInspector.vue b/src/components/variables/TokenInspector.vue
index 05f886bc2..80e7e9672 100644
--- a/src/components/variables/TokenInspector.vue
+++ b/src/components/variables/TokenInspector.vue
@@ -2,7 +2,7 @@
import { computedAsync } from '@vueuse/core'
import { isEmptyObject, omit } from 'es-toolkit'
import { tv } from 'tailwind-variants'
-import { computed, reactive, useId, watch } from 'vue'
+import { computed, nextTick, reactive, ref, useId, watch } from 'vue'
import type { VariableTokenFields } from '@open-pencil/core/editor'
import {
@@ -26,28 +26,44 @@ import {
import { randomHex } from '@open-pencil/scene-graph/random'
import { useI18n } from '@open-pencil/vue'
-import type { AliasCandidate, TokenRow } from '@/app/editor/tokens/model'
+import type {
+ AliasCandidate,
+ CSSReferenceCandidate,
+ TokenFormulaActions,
+ TokenRow
+} from '@/app/editor/tokens/model'
import { SCOPES_BY_TYPE } from '@/app/editor/tokens/scopes'
import ColorInput from '@/components/ColorPicker/ColorInput.vue'
import { BindingPill, VariablePicker } from '@/components/ui/binding'
import AppButton from '@/components/ui/button/AppButton.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import AppTextarea from '@/components/ui/input/AppTextarea.vue'
+import Tip from '@/components/ui/overlay/Tip.vue'
import FillSwatch from '@/components/ui/paint/FillSwatch.vue'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import inspectorTheme from '@/theme/variables/inspector'
+
+import TokenCSSExpression from './TokenCSSExpression.vue'
+import TokenValueEditor from './TokenValueEditor.vue'
const {
row,
collection,
aliasCandidates,
+ cssCandidates = [],
+ formula,
layout = 'side'
} = defineProps<{
row: TokenRow
collection: VariableCollection
/** Variables of the same type a mode's value can point at. */
aliasCandidates: AliasCandidate[]
+ /** Number tokens a CSS expression can name as `var(--name)`. */
+ cssCandidates?: CSSReferenceCandidate[]
+ /** Reads and writes number and true/false values, which may be formulas. */
+ formula?: TokenFormulaActions
/** `full` fills the panel behind a back button on narrow screens. */
layout?: 'side' | 'full'
}>()
@@ -62,7 +78,7 @@ const emit = defineEmits<{
}>()
const { variables } = useI18n()
-const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const ui = computed(() => tv(inspectorTheme)({ layout }))
/**
* A copy per list refresh: the graph edits a variable in place, so the same object coming back
* would not tell the fields an inline rename or an undo changed it.
@@ -160,7 +176,12 @@ function commitName() {
/** The browser's CSS parser decides what a custom property name may be. */
const validator = computedAsync(loadTokenValidator, null)
-const cssNameErrorId = `${useId()}-css-name`
+const fieldId = useId()
+const nameId = `${fieldId}-name`
+const unitId = `${fieldId}-unit`
+const cssNameId = `${fieldId}-css-name`
+const cssNameErrorId = `${cssNameId}-error`
+const cssNameHintId = `${cssNameErrorId}-hint`
/** The name typed, without the `--` the field shows, also when `--name` or `var(--name)` is pasted. */
const typedCSSName = computed(() => {
const text = draft.cssName.trim()
@@ -197,18 +218,49 @@ function commitValue(modeId: string) {
emit('updateValue', modeId, text)
}
-/** An expression replaces a number in CSS; the stored number stays what the canvas draws. */
-function commitExpression(modeId: string) {
- const css = (draft.expressions[modeId] ?? '').trim()
- const resolved = variable.value.valuesByMode[modeId]
+/**
+ * An expression replaces a mode's value in CSS alone; the canvas keeps drawing the value. It
+ * records a plain number, so a number edited elsewhere later shows it no longer applies.
+ */
+function commitExpression(modeId: string, css: string) {
+ addingExpression.value = null
+ if (css === (variable.value.expressions?.[modeId]?.css ?? '')) return
+ const value = variable.value.valuesByMode[modeId]
const others = omit(variable.value.expressions ?? {}, [modeId])
- const expressions: Record<string, TokenExpression> =
- css && typeof resolved === 'number' ? { ...others, [modeId]: { css, resolved } } : others
- emit('updateToken', {
- expressions: isEmptyObject(expressions) ? undefined : expressions
- })
+ const expression: TokenExpression = typeof value === 'number' ? { css, resolved: value } : { css }
+ const expressions = css ? { ...others, [modeId]: expression } : others
+ emit('updateToken', { expressions: isEmptyObject(expressions) ? undefined : expressions })
+}
+
+/** The mode whose expression field was asked for, which shows until it is committed. */
+const addingExpression = ref<string | null>(null)
+const expressionId = `${useId()}-expression`
+watch(
+ () => variable.value.id,
+ () => (addingExpression.value = null)
+)
+function showsExpression(modeId: string) {
+ return addingExpression.value === modeId || Boolean(variable.value.expressions?.[modeId])
+}
+function addExpression(modeId: string) {
+ addingExpression.value = modeId
+ void nextTick(() => document.getElementById(`${expressionId}-${modeId}`)?.focus())
+}
+/** Escape restores the saved expression; a field asked for and left empty closes again. */
+function cancelExpression(modeId: string) {
+ draft.expressions[modeId] = variable.value.expressions?.[modeId]?.css ?? ''
+ addingExpression.value = null
+}
+function clearExpression(modeId: string) {
+ draft.expressions[modeId] = ''
+ 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')
+)
+
function hasScope(scope: VariableScope) {
return variable.value.scopes?.includes(scope) ?? false
}
@@ -270,44 +322,75 @@ function cssNameDone(event: KeyboardEvent) {
</script>
<template>
- <aside :class="ui.inspector()" data-test-id="token-inspector">
+ <aside :class="ui.root()" data-test-id="token-inspector">
<section :class="ui.section()">
- <label :class="ui.field()">
- <span :class="ui.label()">{{ variables.name }}</span>
- <AppInput v-model="draft.name" size="sm" @change="commitName" @enter="done" />
- </label>
- <label :class="ui.field()">
- <span :class="ui.label()">{{ variables.cssName }}</span>
- <AppInput
- v-model="draft.cssName"
- size="sm"
- :placeholder="row.cssName"
- :state="cssNameInvalid ? 'invalid' : 'idle'"
- :aria-invalid="cssNameInvalid"
- :aria-describedby="cssNameInvalid ? cssNameErrorId : undefined"
- :ui="{ input: 'font-mono pl-7' }"
- data-test-id="variables-css-name"
- @change="commitCSSName"
- @enter="cssNameDone"
- >
- <template #leading><span :class="ui.prefix()">--</span></template>
- </AppInput>
+ <PanelFieldGroup :label="variables.name" :for="nameId">
+ <AppInput :id="nameId" v-model="draft.name" size="sm" @change="commitName" @enter="done" />
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="variables.cssName" :for="cssNameId">
+ <Tip :label="variables.cssNameHint">
+ <AppInput
+ :id="cssNameId"
+ v-model="draft.cssName"
+ size="sm"
+ :placeholder="row.cssName"
+ :state="cssNameInvalid ? 'invalid' : 'idle'"
+ :aria-invalid="cssNameInvalid"
+ :aria-describedby="cssNameInvalid ? cssNameErrorId : cssNameHintId"
+ :ui="{ input: 'font-mono pl-7' }"
+ data-test-id="variables-css-name"
+ @change="commitCSSName"
+ @enter="cssNameDone"
+ >
+ <template #leading><span :class="ui.prefix()">--</span></template>
+ </AppInput>
+ </Tip>
<p v-if="cssNameInvalid" :id="cssNameErrorId" :class="ui.error()" role="alert">
{{ variables.cssNameInvalid }}
</p>
- <span :class="ui.hint()">{{ variables.cssNameHint }}</span>
- </label>
- <label v-if="variable.type === 'FLOAT'" :class="ui.field()">
- <span :class="ui.label()">{{ variables.unit }}</span>
- <AppSelect v-model="unit" :options="unitOptions" />
- </label>
+ <span :id="cssNameHintId" class="sr-only">{{ variables.cssNameHint }}</span>
+ </PanelFieldGroup>
+ <PanelFieldGroup v-if="variable.type === 'FLOAT'" :label="variables.unit" :for="unitId">
+ <AppSelect :id="unitId" v-model="unit" :options="unitOptions" />
+ </PanelFieldGroup>
</section>
<section :class="ui.section()">
- <h3 :class="ui.sectionTitle()">{{ singleMode ? variables.value : variables.values }}</h3>
- <div v-for="mode in collection.modes" :key="mode.modeId" :class="ui.field()">
- <span v-if="!singleMode" :class="ui.label()">{{ mode.name }}</span>
- <div :class="ui.valueRow()">
+ <!-- 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()">
+ {{ singleMode ? variables.value : variables.values }}
+ </h3>
+ <div v-for="mode in collection.modes" :key="mode.modeId" :class="ui.value()">
+ <span v-if="!editsValues && !singleMode" :class="ui.label()">{{ mode.name }}</span>
+ <TokenValueEditor
+ v-if="editsValues && formula"
+ :variable="variable"
+ :mode-id="mode.modeId"
+ :label="singleMode ? variables.value : mode.name"
+ :heading="singleMode ? 'section' : 'mode'"
+ :candidates="aliasCandidates"
+ :formula="formula"
+ :expression="variable.type === 'FLOAT' ? showsExpression(mode.modeId) : undefined"
+ @apply="emit('updateValue', mode.modeId, $event)"
+ @done="emit('done')"
+ @add-expression="addExpression(mode.modeId)"
+ @remove-expression="clearExpression(mode.modeId)"
+ >
+ <template #below>
+ <TokenCSSExpression
+ v-if="showsExpression(mode.modeId)"
+ :id="`${expressionId}-${mode.modeId}`"
+ v-model="draft.expressions[mode.modeId]"
+ :label="singleMode ? variables.expression : `${mode.name}: ${variables.expression}`"
+ :unit="numberUnit"
+ :candidates="cssCandidates"
+ :described-by="`${expressionId}-hint`"
+ @commit="commitExpression(mode.modeId, $event)"
+ @cancel="cancelExpression(mode.modeId)"
+ />
+ </template>
+ </TokenValueEditor>
+ <div v-else :class="ui.valueRow()">
<div v-if="alias(mode.modeId)" :class="ui.valueControl()">
<FillSwatch
v-if="aliasColor(mode.modeId)"
@@ -362,28 +445,13 @@ function cssNameDone(event: KeyboardEvent) {
@detach="emit('detach', mode.modeId)"
/>
</div>
- <AppInput
- v-if="variable.type === 'FLOAT' && !alias(mode.modeId)"
- v-model="draft.expressions[mode.modeId]"
- size="sm"
- :placeholder="variables.expression"
- :ui="{ input: 'font-mono' }"
- @change="commitExpression(mode.modeId)"
- @enter="done"
- />
</div>
- <span v-if="variable.type === 'FLOAT'" :class="ui.hint()">{{
- variables.expressionHint
- }}</span>
+ <span :id="`${expressionId}-hint`" class="sr-only">{{ variables.expressionHint }}</span>
</section>
<section v-if="scopes.length > 0" :class="ui.section()">
- <h3 :class="ui.sectionTitle()">{{ variables.scopes }}</h3>
- <label
- v-for="scope in scopes"
- :key="scope"
- class="flex items-center gap-2 text-xs text-surface"
- >
+ <h3 :class="ui.title()">{{ variables.scopes }}</h3>
+ <label v-for="scope in scopes" :key="scope" :class="ui.scope()">
<AppCheckbox
:model-value="hasScope(scope)"
:ariaLabel="SCOPE_MESSAGES[scope]?.() ?? scope"
@@ -394,7 +462,7 @@ function cssNameDone(event: KeyboardEvent) {
</section>
<section :class="ui.section()">
- <h3 :class="ui.sectionTitle()">{{ variables.description }}</h3>
+ <h3 :class="ui.title()">{{ variables.description }}</h3>
<AppTextarea v-model="draft.description" :rows="2" @change="commitDescription" />
</section>
diff --git a/src/components/variables/TokenOutput.vue b/src/components/variables/TokenOutput.vue
index 775c4a242..054f83bc6 100644
--- a/src/components/variables/TokenOutput.vue
+++ b/src/components/variables/TokenOutput.vue
@@ -18,7 +18,7 @@ import CodeViewer from '@/components/code-editor/CodeViewer.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import { useMenuUI } from '@/components/ui/menu/menu'
import MenuScrollArea from '@/components/ui/menu/MenuScrollArea.vue'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import outputTheme from '@/theme/variables/output'
const { collectionId, layout = 'side' } = defineProps<{
collectionId: string
@@ -28,7 +28,7 @@ const { collectionId, layout = 'side' } = defineProps<{
const emit = defineEmits<{ copy: [format: TokenStylesheetFormat]; export: [] }>()
const { variables } = useI18n()
-const ui = computed(() => tv(tokensPanelTheme)({ layout }))
+const ui = computed(() => tv(outputTheme)({ layout }))
const menu = useMenuUI({ content: 'w-60', item: 'justify-start gap-2' })
const editor = useEditor()
@@ -53,9 +53,9 @@ const stylesheet = computedAsync(async () => {
</script>
<template>
- <section :class="ui.output()" data-test-id="token-output">
+ <section :class="ui.root()" data-test-id="token-output">
<div class="flex items-center gap-2 px-4 py-1.5">
- <span v-if="layout === 'side'" :class="ui.sectionTitle()">{{ variables.stylesheet }}</span>
+ <span v-if="layout === 'side'" :class="ui.title()">{{ variables.stylesheet }}</span>
<span class="flex-1" />
<DropdownMenuRoot>
<DropdownMenuTrigger as-child>
diff --git a/src/components/variables/TokenSidebar.vue b/src/components/variables/TokenSidebar.vue
index af3916cbc..5d3e29894 100644
--- a/src/components/variables/TokenSidebar.vue
+++ b/src/components/variables/TokenSidebar.vue
@@ -7,7 +7,7 @@ import type { GroupEntry } from '@/app/editor/tokens/model'
import IconButton from '@/components/ui/button/IconButton.vue'
import AppBadge from '@/components/ui/feedback/AppBadge.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import sidebarTheme from '@/theme/variables/sidebar'
/**
* Collections and the groups inside the active one, each with how many tokens it holds. Picking
@@ -26,14 +26,14 @@ const activeGroup = defineModel<string | null>('group', { default: null })
const emit = defineEmits<{ addCollection: [] }>()
const { variables } = useI18n()
-const ui = tv(tokensPanelTheme)()
+const ui = tv(sidebarTheme)()
</script>
<template>
- <nav :class="ui.sidebar()" :aria-label="variables.collections" data-test-id="tokens-sidebar">
- <section :class="ui.sidebarSection()">
- <div :class="ui.sidebarHeading()">
- <h3 :class="ui.sectionTitle()">{{ variables.collections }}</h3>
+ <nav :class="ui.root()" :aria-label="variables.collections" data-test-id="tokens-sidebar">
+ <section :class="ui.section()">
+ <div :class="ui.heading()">
+ <h3 :class="ui.title()">{{ variables.collections }}</h3>
<IconButton
:label="variables.createCollection"
data-test-id="variables-add-collection"
@@ -46,7 +46,7 @@ const ui = tv(tokensPanelTheme)()
v-for="item in collections"
:key="item.id"
type="button"
- :class="ui.sidebarItem()"
+ :class="ui.item()"
:data-active="item.id === activeCollectionId || undefined"
:aria-current="item.id === activeCollectionId ? 'true' : undefined"
data-test-id="variables-collection-tab"
@@ -56,35 +56,35 @@ const ui = tv(tokensPanelTheme)()
<Tip v-if="item.library" :label="variables.libraryCollectionHint">
<AppBadge>{{ variables.libraryCollection }}</AppBadge>
</Tip>
- <span :class="ui.sidebarCount()">{{ item.count }}</span>
+ <span :class="ui.count()">{{ item.count }}</span>
</button>
</section>
- <section v-if="groups.length > 0" :class="ui.sidebarSection()">
- <h3 :class="[ui.sectionTitle(), ui.sidebarHeading()]">{{ variables.groups }}</h3>
+ <section v-if="groups.length > 0" :class="ui.section()">
+ <h3 :class="[ui.title(), ui.heading()]">{{ variables.groups }}</h3>
<button
type="button"
- :class="ui.sidebarItem()"
+ :class="ui.item()"
:data-active="activeGroup === null || undefined"
:aria-current="activeGroup === null ? 'true' : undefined"
@click="activeGroup = null"
>
<span class="truncate">{{ variables.allVariables }}</span>
- <span :class="ui.sidebarCount()">{{ total }}</span>
+ <span :class="ui.count()">{{ total }}</span>
</button>
<button
v-for="group in groups"
:key="group.path"
type="button"
- :class="ui.sidebarItem()"
+ :class="ui.item()"
:style="{ '--depth': group.depth }"
:data-active="activeGroup === group.path || undefined"
:aria-current="activeGroup === group.path ? 'true' : undefined"
data-test-id="variables-group"
@click="activeGroup = group.path"
>
- <span :class="ui.sidebarGroupLabel()">{{ group.label }}</span>
- <span :class="ui.sidebarCount()">{{ group.count }}</span>
+ <span :class="ui.groupLabel()">{{ group.label }}</span>
+ <span :class="ui.count()">{{ group.count }}</span>
</button>
</section>
</nav>
diff --git a/src/components/variables/TokenTable.vue b/src/components/variables/TokenTable.vue
index bbca30f70..4db0ce4a8 100644
--- a/src/components/variables/TokenTable.vue
+++ b/src/components/variables/TokenTable.vue
@@ -23,7 +23,7 @@ import TokenCellInput from '@/components/variables/TokenCellInput.vue'
import TokenRowMenu from '@/components/variables/TokenRowMenu.vue'
import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'
import { useConditionLabels } from '@/components/variables/useConditionLabels'
-import tokensPanelTheme from '@/theme/tokens-panel'
+import tableTheme from '@/theme/variables/table'
const { collection, groups, labels, modeIds, groupOptions } = defineProps<{
collection: VariableCollection
@@ -47,7 +47,7 @@ const emit = defineEmits<{
}>()
const { variables } = useI18n()
-const ui = tv(tokensPanelTheme)()
+const ui = tv(tableTheme)()
/** Figma does not show a variable the file adds to a library's collection; such a row says so. */
const libraryCollection = computed(() => isLibraryCollection(collection))
@@ -136,7 +136,7 @@ function commitName(row: TokenRow, text: string) {
/** Numbers and text edit in place; colors, booleans and aliases open the inspector instead. */
function editableValue(row: TokenRow, modeId: string) {
const value = row.variable.valuesByMode[modeId]
- const aliased = typeof value === 'object' && 'aliasId' in value
+ const aliased = typeof value === 'object' && ('aliasId' in value || 'expression' in value)
return !aliased && (row.variable.type === 'FLOAT' || row.variable.type === 'STRING')
}
@@ -186,7 +186,7 @@ function dropEdge(id: string) {
v-model="selectedIds"
multiple
selection-behavior="replace"
- :class="ui.list()"
+ :class="ui.root()"
highlight-on-hover
data-test-id="token-list"
@keydown="onKeydown"
@@ -238,7 +238,7 @@ function dropEdge(id: string) {
>
<span :class="ui.name()" @dblclick.stop="startRename(row.variable.id)">
<span :class="ui.nameLine()">
- <component :is="VARIABLE_TYPE_ICONS[row.variable.type]" :class="ui.typeIcon()" />
+ <component :is="VARIABLE_TYPE_ICONS[row.variable.type]" :class="ui.icon()" />
<TokenCellInput
v-if="isEditing(row.variable.id)"
:value="row.label"
@@ -288,9 +288,24 @@ function dropEdge(id: string) {
}"
:ui="{ root: 'size-3.5 shrink-0 rounded-sm' }"
/>
- <span v-if="value.expression" :class="ui.expression()">{{ value.expression }}</span>
- <BindingPill v-else-if="value.alias" :label="value.alias" />
+ <template v-if="value.formula">
+ <Tip :label="value.formula">
+ <icon-lucide-square-function
+ :class="ui.icon()"
+ :aria-label="variables.formula"
+ />
+ </Tip>
+ <span class="truncate">{{ value.css || '—' }}</span>
+ </template>
+ <template v-else-if="value.alias">
+ <BindingPill :class="ui.aliasPill()" :label="value.alias" />
+ <span v-if="value.result" :class="ui.aliasResult()">{{ value.result }}</span>
+ </template>
<span v-else class="truncate">{{ value.css }}</span>
+ <!-- CSS writes the expression instead; the canvas, and this list, show the value. -->
+ <Tip v-if="value.expression" :label="value.expression">
+ <span :class="ui.expressionBadge()" :aria-label="variables.expression">CSS</span>
+ </Tip>
</template>
</span>
</ListboxItem>
diff --git a/src/components/variables/TokenValueEditor.vue b/src/components/variables/TokenValueEditor.vue
new file mode 100644
index 000000000..98e81b621
--- /dev/null
+++ b/src/components/variables/TokenValueEditor.vue
@@ -0,0 +1,300 @@
+<script setup lang="ts">
+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 { useI18n } from '@open-pencil/vue'
+
+import {
+ referencePillName,
+ type AliasCandidate,
+ type TokenFormulaActions
+} from '@/app/editor/tokens/model'
+import { parseTokenEditorText, tokenEditorText } from '@/app/editor/tokens/value-editor'
+import { VariablePicker } from '@/components/ui/binding'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
+import valueEditorTheme from '@/theme/variables/value-editor'
+
+import { formulaDialect } from './formula-field/dialects/formula'
+import type { FormulaSelection } from './formula-field/source'
+import type TokenFormulaField from './TokenFormulaField.vue'
+
+const {
+ variable,
+ modeId,
+ label,
+ heading = 'mode',
+ candidates,
+ formula,
+ expression
+} = defineProps<{
+ variable: Variable
+ modeId: string
+ label: string
+ /** A lone value's label reads as the section's title; one of several, as its mode's name. */
+ heading?: 'section' | 'mode'
+ candidates: AliasCandidate[]
+ formula: TokenFormulaActions
+ /** Whether the mode has a CSS expression; left out where the value takes none. */
+ expression?: boolean
+}>()
+const emit = defineEmits<{
+ apply: [value: VariableValue]
+ done: []
+ addExpression: []
+ removeExpression: []
+}>()
+const { variables } = useI18n()
+const ui = computed(() => tv(valueEditorTheme)({ heading }))
+const fieldId = useId()
+const field = useTemplateRef<InstanceType<typeof TokenFormulaField>>('field')
+
+const draft = ref('')
+const selection = ref<FormulaSelection | null>(null)
+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. */
+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
+)
+const alias = computed(() =>
+ typeof value.value === 'object' && 'aliasId' in value.value ? value.value.aliasId : undefined
+)
+
+function reset() {
+ draft.value = saved.value
+ selection.value = null
+ insertionCaret.value = null
+ committed.value = false
+ commitError.value = ''
+}
+watch([() => variable.id, () => modeId], () => {
+ writingFormula.value = false
+ reset()
+})
+watch(saved, reset, { immediate: true })
+watch(draft, () => {
+ committed.value = false
+ commitError.value = ''
+})
+
+/** A resolved value as the list shows it: a number with its unit, or true and false. */
+function resultText(resolved: VariableValue | undefined) {
+ if (typeof resolved === 'number') return tokenNumberToCSS(resolved, variableUnit(variable))
+ if (typeof resolved === 'boolean') return String(resolved)
+ return '—'
+}
+
+/** A candidate's value in this mode; one of another type, compared in a formula, shows its own. */
+function withValue(candidate: AliasCandidate) {
+ try {
+ const { resolved } = formula.parse(modeId, formula.reference(candidate.id))
+ return { ...candidate, text: resultText(resolved) }
+ } catch {
+ return { ...candidate, text: candidate.text ?? '—' }
+ }
+}
+const pickerItems = computed(() => candidates.map(withValue))
+const referenceItems = computed(() => formula.candidates.map(withValue))
+const completions = computed(() =>
+ referenceItems.value.map((item) => ({
+ label: item.name,
+ section: item.collection,
+ detail: item.text,
+ insert: formula.reference(item.id)
+ }))
+)
+const candidatesBySource = computed(
+ () => new Map(referenceItems.value.map((item) => [formula.reference(item.id), item]))
+)
+const candidatesById = computed(() => new Map(referenceItems.value.map((item) => [item.id, item])))
+
+/** A reference's pill: found by its spelling, or by resolving another spelling of the name. */
+function resolveReference(source: string) {
+ const candidate = candidatesBySource.value.get(source) ?? candidateNamed(source)
+ // The pill names the variable as its group row does; the tooltip gives the full path.
+ if (candidate)
+ return {
+ label: referencePillName(candidate.name),
+ tooltip: `${candidate.collection} · ${candidate.name} · ${candidate.text}`
+ }
+}
+function candidateNamed(source: string) {
+ try {
+ const parsed = formula.parse(modeId, source).value
+ if (typeof parsed === 'object' && 'aliasId' in parsed)
+ return candidatesById.value.get(parsed.aliasId)
+ } catch {
+ // Incomplete or invalid references stay editable source text.
+ return undefined
+ }
+}
+
+const preview = computed(() => {
+ try {
+ return { edit: parseTokenEditorText(variable, modeId, draft.value, formula), error: '' }
+ } catch (error) {
+ return { edit: undefined, error: error instanceof Error ? error.message : String(error) }
+ }
+})
+const error = computed(() => commitError.value || (committed.value ? preview.value.error : ''))
+const suffix = computed(() => {
+ const edit = preview.value.edit
+ return edit && edit.kind !== 'literal' ? resultText(edit.resolved) : undefined
+})
+/** A plain number reads in its unit, as the number field showed it. */
+const unit = computed(() => {
+ const literal = !draft.value.trim() || preview.value.edit?.kind === 'literal'
+ const name = variableUnit(variable)
+ return variable.type === 'FLOAT' && literal && name !== 'none' ? name : undefined
+})
+
+function apply() {
+ committed.value = true
+ if (draft.value === saved.value) {
+ if (typeof value.value === 'boolean') writingFormula.value = false
+ return true
+ }
+ const edit = preview.value.edit
+ if (!edit) return false
+ emit('apply', edit.value)
+ if (typeof edit.value === 'boolean') writingFormula.value = false
+ return true
+}
+function done() {
+ if (!apply()) return
+ field.value?.blur()
+ emit('done')
+}
+function cancel() {
+ reset()
+ writingFormula.value = false
+ field.value?.blur()
+}
+
+const offersFormula = computed(() => showsSwitch.value)
+async function writeFormula() {
+ writingFormula.value = true
+ await nextTick()
+ field.value?.focus()
+ field.value?.setSelectionRange(0, draft.value.length)
+}
+/** One button adds a CSS expression, focusing its field, and removes the one there is. */
+function toggleExpression() {
+ if (expression) emit('removeExpression')
+ else emit('addExpression')
+}
+
+/** 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) {
+ const parsed = formula.parse(modeId, reference)
+ emit('apply', parsed.value)
+ return
+ }
+ const range = selection.value
+ draft.value = draft.value.slice(0, range.start) + reference + draft.value.slice(range.end)
+ insertionCaret.value = range.start + reference.length
+}
+function restoreInputFocus(event: Event) {
+ if (insertionCaret.value === null) return
+ event.preventDefault()
+ const caret = insertionCaret.value
+ insertionCaret.value = null
+ field.value?.focus()
+ 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. */
+const picker = computed(() => ({
+ items: pickerItems.value,
+ selected: alias.value,
+ state: alias.value ? ('bound' as const) : ('unbound' as const),
+ triggerLabel: variables.value.useVariable,
+ searchPlaceholder: variables.value.searchVariables,
+ emptyLabel: variables.value.noMatchingVariables,
+ detachLabel: variables.value.detachVariable,
+ onSelect: insert,
+ onDetach: detach,
+ onCloseAutoFocus: restoreInputFocus
+}))
+function detach() {
+ try {
+ const { resolved } = formula.parse(modeId, formula.format(value.value))
+ emit('apply', resolved)
+ } catch (error) {
+ commitError.value = error instanceof Error ? error.message : String(error)
+ }
+}
+</script>
+
+<template>
+ <div :class="ui.root()">
+ <div :class="ui.header()">
+ <span :class="ui.label()">{{ label }}</span>
+ <span :class="ui.tools()">
+ <IconButton
+ v-if="offersFormula"
+ :label="variables.useFormula"
+ data-test-id="variables-use-formula"
+ @click="writeFormula"
+ >
+ <icon-lucide-square-function class="size-3.5" />
+ </IconButton>
+ <IconButton
+ v-if="expression !== undefined"
+ :label="expression ? variables.removeExpression : variables.addExpression"
+ :active="expression"
+ toggle
+ data-test-id="variables-css-expression"
+ @click="toggleExpression"
+ >
+ <icon-lucide-code class="size-3.5" />
+ </IconButton>
+ </span>
+ </div>
+ <div v-if="showsSwitch" :class="ui.control()">
+ <AppSwitch
+ :model-value="value === true"
+ :label="label"
+ @update:model-value="emit('apply', $event)"
+ />
+ <VariablePicker v-bind="picker" />
+ </div>
+ <TokenFormulaField
+ v-else
+ ref="field"
+ :id="fieldId"
+ v-model="draft"
+ :dialect="formulaDialect"
+ :label="label"
+ :placeholder="variables.formulaPlaceholder"
+ :resolve="resolveReference"
+ :completions="completions"
+ :invalid="Boolean(error)"
+ :described-by="`${fieldId}-result`"
+ :suffix="suffix"
+ :unit="unit"
+ @change="apply"
+ @enter="done"
+ @cancel="cancel"
+ @selection="selection = $event"
+ >
+ <template #actions><VariablePicker v-bind="picker" /></template>
+ </TokenFormulaField>
+ <p :id="`${fieldId}-result`" :class="error ? ui.error() : 'sr-only'" aria-live="polite">
+ {{ error || suffix }}
+ </p>
+ <!-- Fields that belong to this value, such as its CSS expression, follow it. -->
+ <slot name="below" />
+ </div>
+</template>
diff --git a/src/components/variables/TokensPanel.vue b/src/components/variables/TokensPanel.vue
index 55a1431c2..38b75743a 100644
--- a/src/components/variables/TokensPanel.vue
+++ b/src/components/variables/TokensPanel.vue
@@ -6,6 +6,9 @@ import { computed, ref, useTemplateRef, watch } from 'vue'
import type { VariableTokenFields } from '@open-pencil/core/editor'
import type { TokenStylesheetFormat } from '@open-pencil/dom-css/export'
import {
+ formatVariableFormula,
+ parseVariableFormula,
+ variableFormulaReference,
isLibraryCollection,
type VariableType,
type VariableValue
@@ -14,6 +17,9 @@ import { useI18n, useSceneComputed, useVariables } from '@open-pencil/vue'
import {
aliasCandidates,
+ cssReferenceCandidates,
+ referencePillName,
+ formulaCandidates,
groupTree,
inGroup,
searchTokenIds,
@@ -39,15 +45,15 @@ import TokenTable from '@/components/variables/TokenTable.vue'
import TokenTypeFilter from '@/components/variables/TokenTypeFilter.vue'
import { useTokenActions } from '@/components/variables/useTokenActions'
import { swapTransition } from '@/theme/motion/styles'
-import tokensPanelTheme, {
+import panelTheme, {
TOKENS_PANEL_COMPACT_WIDTH,
TOKENS_PANEL_SIDEBAR_WIDTH
-} from '@/theme/tokens-panel'
+} from '@/theme/variables/panel'
const emit = defineEmits<{ copy: [format: TokenStylesheetFormat]; export: [] }>()
const { variables: messages, common } = useI18n()
-const ui = tv(tokensPanelTheme)()
+const ui = tv(panelTheme)()
/**
* The panel lays out by its own width, not the window: inside a dialog, a split view, or a phone.
@@ -137,6 +143,15 @@ const bulkIds = computed(
const candidates = computed(() =>
editedRow.value ? aliasCandidates(editor.graph, editedRow.value.variable) : []
)
+/** Characters, counting each pill by its name, a formula fits on one line before it breaks. */
+const FORMULA_LINE_WIDTH = 36
+
+const referenceCandidates = computed(() =>
+ editedRow.value ? formulaCandidates(editor.graph, editedRow.value.variable) : []
+)
+const cssCandidates = computed(() =>
+ editedRow.value ? cssReferenceCandidates(editor.graph, editedRow.value.variable) : []
+)
const collectionOptions = computed(() =>
ctx.collections.value.map((candidate) => ({ value: candidate.id, label: candidate.name }))
@@ -273,6 +288,22 @@ const tokenInspector = computed(() => {
const id = editedId.value
return {
aliasCandidates: candidates.value,
+ cssCandidates: cssCandidates.value,
+ formula: id
+ ? {
+ candidates: referenceCandidates.value,
+ parse: (modeId: string, source: string) =>
+ parseVariableFormula(editor.graph, id, modeId, source),
+ // A long formula reads on several lines in its field.
+ format: (value: VariableValue) =>
+ formatVariableFormula(editor.graph, value, {
+ width: FORMULA_LINE_WIDTH,
+ display: (variableId) =>
+ referencePillName(editor.graph.variables.get(variableId)?.name ?? variableId)
+ }),
+ reference: (id: string) => variableFormulaReference(editor.graph, id)
+ }
+ : undefined,
onRename: (name: string) => id && editor.renameVariable(id, name),
onUpdateToken: (patch: Partial<VariableTokenFields>) =>
id && editor.updateVariableToken(id, patch),
@@ -502,9 +533,10 @@ const groupOptions = computed(() => groupEntries.value.map((entry) => entry.path
/>
<Transition v-bind="swapTransition" mode="out-in">
<TokenBulkInspector v-if="bulkIds" key="bulk" v-bind="bulkInspector" />
+ <!-- One key for every token: switching rows updates the inspector in place, unanimated. -->
<TokenInspector
v-else-if="editedRow"
- :key="editedRow.variable.id"
+ key="token"
v-bind="tokenInspector"
:row="editedRow"
:collection="collection"
diff --git a/src/components/variables/formula-field/dialects/css.ts b/src/components/variables/formula-field/dialects/css.ts
new file mode 100644
index 000000000..7df2d9ef5
--- /dev/null
+++ b/src/components/variables/formula-field/dialects/css.ts
@@ -0,0 +1,130 @@
+import {
+ insertCompletionText,
+ type Completion,
+ type CompletionContext
+} from '@codemirror/autocomplete'
+import { StreamLanguage } from '@codemirror/language'
+import type { EditorState } from '@codemirror/state'
+import { tags } from '@lezer/highlight'
+
+import {
+ cssTokenProperty,
+ cssValueTokens,
+ type CSSValueTokenKind
+} from '@open-pencil/dom-css/export'
+
+import { nodeText, tokenBefore, type SyntaxNode } from './syntax'
+import type { ExpressionDialect, ReferenceCompletion } from './types'
+
+/** The CSS math functions a token value is usually written with. */
+const FUNCTIONS = [
+ { label: 'calc', detail: 'expression' },
+ { label: 'clamp', detail: 'min, preferred, max' },
+ { label: 'min', detail: 'a, b, …' },
+ { label: 'max', detail: 'a, b, …' }
+]
+
+/** A CSS value as a CodeMirror language, read by Scene Graph's CSS value tokenizer. */
+const cssValueLanguage = StreamLanguage.define<null>({
+ name: 'css-value',
+ startState: () => null,
+ token(stream) {
+ // A token value is one short line, so reading it again for each token costs little.
+ const token = cssValueTokens(stream.string).find(({ to }) => to > stream.pos)
+ if (!token || token.from > stream.pos) {
+ stream.pos = token?.from ?? stream.string.length
+ return null
+ }
+ stream.pos = token.to
+ return token.kind
+ },
+ tokenTable: {
+ reference: tags.special(tags.variableName),
+ property: tags.variableName,
+ function: tags.function(tags.variableName),
+ separator: tags.separator
+ } satisfies Partial<Record<CSSValueTokenKind, unknown>>,
+ mergeTokens: false
+})
+
+/** The start of an unfinished `var(` the caret is inside, right after its `(` or its name. */
+function openVarStart(state: EditorState, token: SyntaxNode, pos: number) {
+ const paren = token.name === 'property' && token.to === pos ? token.prevSibling : token
+ if (paren?.name !== 'paren' || nodeText(state, paren) !== '(' || paren.to > pos) return undefined
+ const name = paren.prevSibling
+ return name?.name === 'function' && name.to === paren.from && nodeText(state, name) === 'var'
+ ? name.from
+ : undefined
+}
+
+interface CompletionRange {
+ /** Where the typed text starts, which filters the list. */
+ from: number
+ /** Where a chosen option replaces from, which includes an unfinished `var(`. */
+ replace: number
+ variablesOnly: boolean
+}
+
+function completionRange(context: CompletionContext): CompletionRange | undefined {
+ const { state, pos } = context
+ const token = tokenBefore(state, pos)
+ // A `-` at the caret may be the start of a custom property, so the list reads from it.
+ const minus = token?.to === pos && token.name === 'operator' && nodeText(state, token) === '-'
+ const typed = token?.to === pos && (minus || ['property', 'keyword'].includes(token.name))
+ const variable = token ? openVarStart(state, token, pos) : undefined
+ if (token && variable !== undefined)
+ return { from: typed ? token.from : pos, replace: variable, variablesOnly: true }
+ if (token && typed) return { from: token.from, replace: token.from, variablesOnly: false }
+ const operand =
+ !token ||
+ ['separator', 'operator'].includes(token.name) ||
+ (token.name === 'paren' && nodeText(state, token) === '(')
+ return operand || context.explicit ? { from: pos, replace: pos, variablesOnly: false } : undefined
+}
+
+/**
+ * Token names complete as `var(--name)` while a name or `var(` is typed and wherever a value
+ * goes, alongside the math functions; the syntax tree says which.
+ */
+function completeCSSValue(references: () => readonly ReferenceCompletion[]) {
+ return (context: CompletionContext) => {
+ const range = completionRange(context)
+ if (!range) return null
+ const insert = (text: string, closes: boolean) =>
+ ((view, _completion, _from, to) => {
+ const end = closes && view.state.sliceDoc(to, to + 1) === ')' ? to + 1 : to
+ view.dispatch(insertCompletionText(view.state, text, range.replace, end))
+ }) satisfies Completion['apply']
+ const variables = references().map(({ label, section, detail, insert: text }): Completion => ({
+ label,
+ section,
+ detail,
+ type: 'variable',
+ apply: insert(text, range.variablesOnly)
+ }))
+ const functions = FUNCTIONS.map(({ label, detail }): Completion => ({
+ label,
+ detail,
+ type: 'function',
+ apply: insert(`${label}(`, false)
+ }))
+ return {
+ from: range.from,
+ validFor: /^[\w-]*$/,
+ options: range.variablesOnly ? variables : [...functions, ...variables]
+ }
+ }
+}
+
+export const cssValueDialect: ExpressionDialect = {
+ language: cssValueLanguage,
+ complete: completeCSSValue,
+ // The pill covers the custom property inside `var()`, which stays visible as CSS.
+ references: (source) =>
+ cssValueTokens(source).flatMap((token) => {
+ const property = token.kind === 'reference' ? cssTokenProperty(token) : undefined
+ if (!property) return []
+ const from = token.from + token.text.indexOf(property)
+ return [{ source: property, from, to: from + property.length }]
+ })
+}
diff --git a/src/components/variables/formula-field/dialects/formula.ts b/src/components/variables/formula-field/dialects/formula.ts
new file mode 100644
index 000000000..76c2c4a91
--- /dev/null
+++ b/src/components/variables/formula-field/dialects/formula.ts
@@ -0,0 +1,107 @@
+import {
+ insertCompletionText,
+ type Completion,
+ type CompletionContext
+} from '@codemirror/autocomplete'
+import { StreamLanguage } from '@codemirror/language'
+import type { EditorState } from '@codemirror/state'
+import { tags } from '@lezer/highlight'
+
+import { formulaTokens, readFormulaToken, type FormulaTokenKind } from '@open-pencil/scene-graph'
+
+import { nodeText, tokenBefore, type SyntaxNode } from './syntax'
+import type { ExpressionDialect, ReferenceCompletion } from './types'
+
+/**
+ * The formula syntax as a CodeMirror language, read by Scene Graph's tokenizer, so completion
+ * and pills see the tokens the parser does. Each token is its own syntax node named by kind.
+ */
+const formulaLanguage = StreamLanguage.define<null>({
+ name: 'formula',
+ startState: () => null,
+ token(stream) {
+ if (stream.eatSpace()) return null
+ const token = readFormulaToken(stream.string, stream.pos)
+ stream.pos = token.to
+ return token.kind
+ },
+ tokenTable: {
+ reference: tags.special(tags.variableName),
+ name: tags.variableName
+ } satisfies Partial<Record<FormulaTokenKind, unknown>>,
+ // Adjacent operators or parentheses stay separate nodes, as the parser reads them.
+ mergeTokens: false
+})
+
+/**
+ * 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.
+ */
+function pathStart(state: EditorState, last: SyntaxNode): number | undefined {
+ const isSlash = (node: SyntaxNode) => node.name === 'operator' && nodeText(state, node) === '/'
+ if (last.name !== 'name' && !isSlash(last)) return undefined
+ let first = last
+ for (let node = last.prevSibling; node && node.to === first.from; node = node.prevSibling) {
+ if (node.name !== 'name' && !isSlash(node)) break
+ first = node
+ }
+ return first.name === 'name' ? first.from : undefined
+}
+
+/** Where the completion replaces from, and whether it sits inside braces, or none if it should not open. */
+function completionRange(context: CompletionContext) {
+ const { state, pos } = context
+ const token = tokenBefore(state, pos)
+ // An open reference runs to the line's end while it is typed, so check the text before the caret.
+ if (token?.name === 'reference' && !state.sliceDoc(token.from, pos).includes('}'))
+ return { from: token.from + 1, braced: true }
+ const path = token?.to === pos ? pathStart(state, token) : undefined
+ if (path !== undefined) return { from: path, braced: false }
+ // A logic word must be finished, with a space after it, before it can take an operand.
+ const operand =
+ !token ||
+ token.name === 'operator' ||
+ (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
+ * with the parser about what each piece of text is.
+ */
+function completeFormula(references: () => readonly ReferenceCompletion[]) {
+ return (context: CompletionContext) => {
+ const range = completionRange(context)
+ if (!range) return null
+ const { from, braced } = range
+ 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
+ )
+ }
+ }
+}
+
+export const formulaDialect: ExpressionDialect = {
+ language: formulaLanguage,
+ complete: completeFormula,
+ references: (source) =>
+ formulaTokens(source).flatMap(({ kind, text, from, to }) =>
+ kind === 'reference' && text.endsWith('}') ? [{ source: text, from, to }] : []
+ )
+}
diff --git a/src/components/variables/formula-field/dialects/syntax.ts b/src/components/variables/formula-field/dialects/syntax.ts
new file mode 100644
index 000000000..d083ad7f7
--- /dev/null
+++ b/src/components/variables/formula-field/dialects/syntax.ts
@@ -0,0 +1,14 @@
+import { syntaxTree } from '@codemirror/language'
+import type { EditorState } from '@codemirror/state'
+
+export type SyntaxNode = ReturnType<ReturnType<typeof syntaxTree>['resolveInner']>
+
+/** The token that ends at or before `pos`, skipping the whitespace between. */
+export function tokenBefore(state: EditorState, pos: number): SyntaxNode | null {
+ const node = syntaxTree(state).resolveInner(pos, -1)
+ return node.type.isTop ? node.childBefore(pos) : node
+}
+
+export function nodeText(state: EditorState, node: SyntaxNode) {
+ return state.sliceDoc(node.from, node.to)
+}
diff --git a/src/components/variables/formula-field/dialects/types.ts b/src/components/variables/formula-field/dialects/types.ts
new file mode 100644
index 000000000..8118367c3
--- /dev/null
+++ b/src/components/variables/formula-field/dialects/types.ts
@@ -0,0 +1,30 @@
+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. */
+export interface ReferenceCompletion {
+ label: string
+ /** The collection, which groups the list as the variable picker does. */
+ section: string
+ /** The variable's current value, 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)`. */
+ insert: string
+}
+
+/** A finished reference in the text, which the field shows as a pill. */
+export interface ReferenceRange {
+ source: string
+ from: number
+ to: number
+}
+
+/**
+ * One syntax a value field edits: a formula over variables, or a CSS value. Each has its own
+ * language, so completion reads the syntax tree, and its own reference spelling for pills.
+ */
+export interface ExpressionDialect {
+ language: Extension
+ complete: (references: () => readonly ReferenceCompletion[]) => CompletionSource
+ references: (source: string) => ReferenceRange[]
+}
diff --git a/src/components/variables/formula-field/references.ts b/src/components/variables/formula-field/references.ts
new file mode 100644
index 000000000..a6c02eac4
--- /dev/null
+++ b/src/components/variables/formula-field/references.ts
@@ -0,0 +1,98 @@
+import { Facet, StateField, type EditorState } from '@codemirror/state'
+import { Decoration, EditorView, WidgetType } from '@codemirror/view'
+import { h, nextTick, render, type AppContext } from 'vue'
+
+import BindingPill from '@/components/ui/binding/BindingPill.vue'
+
+import type { ReferenceRange } from './dialects/types'
+import { formulaSegments, type FormulaPill } from './source'
+
+interface FormulaReferences {
+ pills: ReadonlyMap<string, FormulaPill>
+ /** Where the field's syntax spells finished references. */
+ ranges: (source: string) => ReferenceRange[]
+ /** The host app's context, so a pill rendered outside the component tree keeps its globals. */
+ appContext: AppContext | null
+}
+
+export const formulaReferences = Facet.define<FormulaReferences>()
+
+/**
+ * A pill inside the line, sitting on the text like a word. It leaves room on its line for an
+ * operator before it, so a long name truncates instead of parting from its operator.
+ */
+const PILL_UI = { pill: 'mx-px inline-flex max-w-[calc(100%-2.5rem)] flex-none align-middle' }
+
+class ReferenceWidget extends WidgetType {
+ constructor(
+ readonly source: string,
+ readonly pill: FormulaPill,
+ readonly appContext: AppContext | null
+ ) {
+ super()
+ }
+
+ eq(other: ReferenceWidget) {
+ return (
+ this.source === other.source &&
+ this.pill.label === other.pill.label &&
+ this.pill.tooltip === other.pill.tooltip
+ )
+ }
+
+ toDOM(view: EditorView) {
+ const host = view.dom.ownerDocument.createElement('span')
+ host.contentEditable = 'false'
+ // A zero-width space lets a line break before the pill, even right after `(`.
+ const pill = view.dom.ownerDocument.createElement('span')
+ pill.dataset.reference = this.source
+ host.append('\u200B', pill)
+ // Vue rendering flushes watchers; defer it until CodeMirror finishes its transaction.
+ void nextTick(() => {
+ if (!host.isConnected) return
+ const vnode = h(BindingPill, {
+ label: this.pill.label,
+ tooltip: this.pill.tooltip,
+ ui: PILL_UI
+ })
+ vnode.appContext = this.appContext
+ render(vnode, pill)
+ view.requestMeasure()
+ })
+ return host
+ }
+
+ destroy(host: HTMLElement) {
+ const pill = host.lastElementChild
+ if (pill instanceof HTMLElement) void nextTick(() => render(null, pill))
+ }
+}
+
+function pillDecorations(state: EditorState) {
+ const references = state.facet(formulaReferences).at(0)
+ const decorations = []
+ const doc = state.doc.toString()
+ const ranges = references?.ranges(doc) ?? []
+ for (const { source, start, end, pill } of formulaSegments(doc, ranges, (reference) =>
+ references?.pills.get(reference)
+ )) {
+ if (pill)
+ decorations.push(
+ Decoration.replace({
+ widget: new ReferenceWidget(source, pill, references?.appContext ?? null)
+ }).range(start, end)
+ )
+ }
+ return Decoration.set(decorations)
+}
+
+/** References show as variable pills that the caret, Backspace and Delete treat as one unit. */
+export const referencePills = StateField.define({
+ create: pillDecorations,
+ update: (value, transaction) =>
+ transaction.docChanged || transaction.reconfigured ? pillDecorations(transaction.state) : value,
+ provide: (field) => [
+ EditorView.decorations.from(field),
+ EditorView.atomicRanges.of((view) => view.state.field(field))
+ ]
+})
diff --git a/src/components/variables/formula-field/result.ts b/src/components/variables/formula-field/result.ts
new file mode 100644
index 000000000..22064d529
--- /dev/null
+++ b/src/components/variables/formula-field/result.ts
@@ -0,0 +1,71 @@
+import { Facet } from '@codemirror/state'
+import { Decoration, EditorView, WidgetType } from '@codemirror/view'
+
+/** What the value gives, such as `= 16px`, or a plain number's unit. */
+export const formulaResult = Facet.define<string, string | undefined>({
+ combine: (values) => values.at(-1) || undefined
+})
+
+/** Whether the field's buttons sit over the top right corner of the text. */
+export const formulaButtonSpace = Facet.define<boolean, boolean>({
+ combine: (values) => values.some(Boolean)
+})
+
+/** Keeps the first line clear of the buttons over it; later lines take the field's width. */
+class ButtonSpaceWidget extends WidgetType {
+ eq() {
+ return true
+ }
+
+ toDOM(view: EditorView) {
+ const element = view.dom.ownerDocument.createElement('span')
+ element.className = 'cm-formula-button-space'
+ element.ariaHidden = 'true'
+ // Floating is how the space stays on the first line only.
+ element.style.float = 'right'
+ return element
+ }
+}
+
+class ResultWidget extends WidgetType {
+ constructor(readonly text: string) {
+ super()
+ }
+
+ eq(other: ResultWidget) {
+ return this.text === other.text
+ }
+
+ toDOM(view: EditorView) {
+ const element = view.dom.ownerDocument.createElement('span')
+ element.className = 'cm-formula-result'
+ // Floating is how the result keeps to the last line; its look is the editor theme's.
+ element.style.float = 'right'
+ element.ariaHidden = 'true'
+ element.textContent = this.text
+ return element
+ }
+
+ ignoreEvent() {
+ return false
+ }
+}
+
+/**
+ * The result floats right after the text's end, so it takes room only on the last line and drops
+ * to a line of its own when that line is full, rather than narrowing every line of the field.
+ */
+export const resultDecoration = EditorView.decorations.compute(
+ ['doc', formulaResult, formulaButtonSpace],
+ (state) => {
+ const ranges = []
+ if (state.facet(formulaButtonSpace))
+ ranges.push(Decoration.widget({ widget: new ButtonSpaceWidget(), side: -1 }).range(0))
+ const text = state.facet(formulaResult)
+ if (text)
+ ranges.push(
+ Decoration.widget({ widget: new ResultWidget(text), side: 1 }).range(state.doc.length)
+ )
+ return Decoration.set(ranges, true)
+ }
+)
diff --git a/src/components/variables/formula-field/source.ts b/src/components/variables/formula-field/source.ts
new file mode 100644
index 000000000..f16bd1c02
--- /dev/null
+++ b/src/components/variables/formula-field/source.ts
@@ -0,0 +1,38 @@
+import type { ReferenceRange } from './dialects/types'
+
+/** The source spelling stays intact when a reference is displayed as an atomic pill. */
+export interface FormulaPill {
+ label: string
+ /** The variable's collection and current value, shown on hover. */
+ tooltip: string
+}
+
+export interface FormulaSelection {
+ start: number
+ end: number
+}
+
+export interface FormulaSegment extends FormulaSelection {
+ source: string
+ pill?: FormulaPill
+}
+
+/** Keep offsets in source coordinates, even when a reference is displayed as a pill. */
+export function formulaSegments(
+ source: string,
+ references: readonly ReferenceRange[],
+ resolve: (reference: string) => FormulaPill | undefined
+) {
+ const segments: FormulaSegment[] = []
+ let start = 0
+ for (const token of references) {
+ const pill = resolve(token.source)
+ if (!pill) continue
+ if (start < token.from)
+ segments.push({ source: source.slice(start, token.from), start, end: token.from })
+ segments.push({ source: token.source, start: token.from, end: token.to, pill })
+ start = token.to
+ }
+ segments.push({ source: source.slice(start), start, end: source.length })
+ return segments
+}
diff --git a/src/components/variables/formula-field/useFormulaField.ts b/src/components/variables/formula-field/useFormulaField.ts
new file mode 100644
index 000000000..f664eaefe
--- /dev/null
+++ b/src/components/variables/formula-field/useFormulaField.ts
@@ -0,0 +1,180 @@
+import {
+ autocompletion,
+ completionKeymap,
+ completionStatus,
+ acceptCompletion,
+ closeCompletion
+} from '@codemirror/autocomplete'
+import {
+ defaultKeymap,
+ history,
+ insertNewline,
+ isolateHistory,
+ redo,
+ undo
+} from '@codemirror/commands'
+import { Annotation, EditorSelection, Prec } from '@codemirror/state'
+import { EditorView, keymap, placeholder, tooltips } from '@codemirror/view'
+import { getCurrentInstance, watch, type Ref, type ShallowRef } from 'vue'
+
+import { useCodeMirror } from '@/components/code-editor/useCodeMirror'
+import { formulaEditorTheme } from '@/theme/code/formula'
+
+import type { ExpressionDialect, ReferenceCompletion } from './dialects/types'
+import { formulaReferences, referencePills } from './references'
+import { formulaButtonSpace, formulaResult, resultDecoration } from './result'
+import { formulaSegments, type FormulaPill, type FormulaSelection } from './source'
+
+interface FormulaFieldOptions {
+ dialect: ExpressionDialect
+ completions: () => readonly ReferenceCompletion[]
+ label: () => string
+ placeholder: () => string
+ attributes: () => Record<string, string>
+ resolve: (source: string) => FormulaPill | undefined
+ /** What the value gives, or a plain number's unit, shown after its text. */
+ result: () => string | undefined
+ /** Whether buttons sit over the field's top right corner, which the first line keeps clear. */
+ buttons: () => boolean
+ onChange: () => void
+ onEnter: () => void
+ onCancel: () => void
+ onSelection: (range: FormulaSelection) => void
+}
+
+const externalUpdate = Annotation.define<boolean>()
+
+/**
+ * The completion list lives in the surrounding dialog and keeps within it: the inspector scrolls
+ * and would clip it, and a modal dialog takes no pointer events outside itself.
+ */
+function completionPlacement(host: HTMLElement | null) {
+ const container = host?.closest<HTMLElement>('[role="dialog"]')
+ if (!container) return tooltips({ position: 'fixed' })
+ return tooltips({
+ position: 'absolute',
+ parent: container,
+ tooltipSpace: () => container.getBoundingClientRect()
+ })
+}
+
+/** CodeMirror owns document edits, atomic references, selection, composition and history. */
+export function useFormulaField(
+ host: Readonly<ShallowRef<HTMLDivElement | null>>,
+ model: Ref<string>,
+ options: FormulaFieldOptions
+) {
+ const appContext = getCurrentInstance()?.appContext ?? null
+ const view = useCodeMirror(host, {
+ doc: () => model.value,
+ label: options.label,
+ theme: formulaEditorTheme,
+ extensions: [
+ history(),
+ options.dialect.language,
+ autocompletion({ override: [options.dialect.complete(options.completions)], icons: false }),
+ keymap.of([...completionKeymap, { key: 'Tab', run: acceptCompletion }]),
+ referencePills,
+ resultDecoration,
+ EditorView.lineWrapping,
+ keymap.of(defaultKeymap),
+ Prec.highest(
+ EditorView.domEventHandlers({
+ keydown(event, editor) {
+ if (event.isComposing) return false
+ if (
+ (event.metaKey || event.ctrlKey) &&
+ (event.code === 'KeyZ' || event.code === 'KeyY')
+ ) {
+ event.preventDefault()
+ event.stopPropagation()
+ if (event.shiftKey || event.code === 'KeyY') redo(editor)
+ else undo(editor)
+ return true
+ }
+ // Line breaks are whitespace in both syntaxes, so long values can span lines.
+ if (event.code === 'Enter' && event.shiftKey) {
+ event.preventDefault()
+ return insertNewline(editor)
+ }
+ if (event.code === 'Enter' || event.code === 'Escape') {
+ event.preventDefault()
+ event.stopPropagation()
+ if (completionStatus(editor.state) === 'active') {
+ if (event.code === 'Escape') closeCompletion(editor)
+ else acceptCompletion(editor)
+ return true
+ }
+ if (event.code === 'Enter') options.onEnter()
+ else options.onCancel()
+ return true
+ }
+ return false
+ },
+ blur(event, editor) {
+ if (event.relatedTarget instanceof Node && editor.dom.contains(event.relatedTarget))
+ return false
+ options.onChange()
+ return false
+ }
+ })
+ ),
+ EditorView.updateListener.of((update) => {
+ if (
+ update.docChanged &&
+ !update.transactions.some((transaction) => transaction.annotation(externalUpdate))
+ )
+ model.value = update.state.doc.toString()
+ if (update.docChanged || update.selectionSet || update.focusChanged) {
+ const { from, to } = update.state.selection.main
+ options.onSelection({ start: from, end: to })
+ }
+ })
+ ],
+ reactive: [
+ () => completionPlacement(host.value),
+ () => EditorView.contentAttributes.of(options.attributes()),
+ () => placeholder(options.placeholder()),
+ () => formulaResult.of(options.result() ?? ''),
+ () => formulaButtonSpace.of(options.buttons()),
+ () =>
+ formulaReferences.of({
+ appContext,
+ ranges: options.dialect.references,
+ pills: new Map(
+ formulaSegments(
+ model.value,
+ options.dialect.references(model.value),
+ options.resolve
+ ).flatMap(({ source, pill }) => (pill ? [[source, pill]] : []))
+ )
+ })
+ ]
+ })
+
+ watch(model, (value) => {
+ const editor = view.value
+ if (!editor || editor.state.doc.toString() === value) return
+ const { anchor, head } = editor.state.selection.main
+ editor.dispatch({
+ changes: { from: 0, to: editor.state.doc.length, insert: value },
+ selection: EditorSelection.single(
+ Math.min(anchor, value.length),
+ Math.min(head, value.length)
+ ),
+ annotations: [externalUpdate.of(true), isolateHistory.of('full')]
+ })
+ // Keep the explicit post-replacement range in CodeMirror's selection history for redo.
+ editor.dispatch({ selection: editor.state.selection })
+ })
+
+ return {
+ focus: () => view.value?.focus(),
+ blur: () => view.value?.contentDOM.blur(),
+ setSelectionRange: (start: number, end: number) => {
+ const editor = view.value
+ if (!editor) return
+ editor.dispatch({ selection: EditorSelection.single(start, end) })
+ }
+ }
+}
diff --git a/src/components/variables/useTokenActions.ts b/src/components/variables/useTokenActions.ts
index 6c28088b0..10c59e4d0 100644
--- a/src/components/variables/useTokenActions.ts
+++ b/src/components/variables/useTokenActions.ts
@@ -60,9 +60,9 @@ export function useTokenActions(editor: Editor, copyName: (name: string) => stri
/** Detaching keeps what the alias resolved to, so nothing on the canvas changes. */
function detach(id: string, modeId: string) {
const value = variable(id)?.valuesByMode[modeId]
- if (typeof value !== 'object' || !('aliasId' in value)) return
+ if (typeof value !== 'object' || !('aliasId' in value || 'expression' in value)) return
// In the edited mode, as the row shows it, not the mode the canvas happens to be in.
- const resolved = editor.graph.resolveVariable(value.aliasId, modeId)
+ const resolved = editor.graph.resolveVariable(id, modeId)
if (resolved !== undefined) editor.updateVariableValue(id, modeId, structuredClone(resolved))
}
diff --git a/src/theme/code/formula.ts b/src/theme/code/formula.ts
new file mode 100644
index 000000000..0e4909c3e
--- /dev/null
+++ b/src/theme/code/formula.ts
@@ -0,0 +1,110 @@
+import { HighlightStyle, syntaxHighlighting } from '@codemirror/language'
+import { EditorView } from '@codemirror/view'
+import { tags } from '@lezer/highlight'
+
+/**
+ * A one-line value field in the UI font, without the gutters or panels of the code editor. Its
+ * completion list matches the variable picker: a floating surface with compact rows grouped by
+ * collection, each value at the row's end.
+ */
+export function formulaEditorTheme(dark: boolean) {
+ return [formulaTheme(dark), formulaHighlighting]
+}
+
+/** The code editor's token colours, quieter for a field: operators and brackets recede. */
+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.string, color: 'var(--color-code-string)' },
+ { tag: tags.function(tags.variableName), color: 'var(--color-code-tag)' },
+ {
+ tag: [tags.operator, tags.punctuation, tags.paren, tags.separator],
+ color: 'var(--color-muted)'
+ },
+ { tag: tags.invalid, color: 'var(--color-error)', textDecoration: 'underline wavy' }
+ ])
+)
+
+function formulaTheme(dark: boolean) {
+ return EditorView.theme(
+ {
+ '&': { fontSize: '12px' },
+ '&.cm-focused': { outline: 'none' },
+ // About twelve lines, then the value scrolls inside the field.
+ '.cm-scroller': {
+ fontFamily: 'inherit',
+ lineHeight: '20px',
+ maxHeight: '240px',
+ overflowX: 'hidden',
+ overflowY: 'auto'
+ },
+ // The content may be narrower than its longest pill, which then truncates, so the field
+ // never grows past the inspector.
+ '.cm-content': { padding: '0', minWidth: '0', caretColor: 'var(--color-surface)' },
+ '.cm-line': { padding: '0' },
+ '.cm-placeholder': { color: 'var(--color-muted)' },
+ '.cm-formula-button-space': { width: '26px', height: '20px' },
+ '.cm-formula-result': {
+ paddingLeft: '8px',
+ color: 'var(--color-muted)',
+ fontVariantNumeric: 'tabular-nums',
+ pointerEvents: 'none',
+ userSelect: 'none'
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete': {
+ backgroundColor: 'var(--color-panel)',
+ color: 'var(--color-surface)',
+ border: 'none',
+ borderRadius: '12px',
+ boxShadow: '0 0 0 1px var(--color-border), 0 8px 30px rgb(0 0 0 / 0.4)',
+ padding: '4px',
+ marginTop: '6px'
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul': {
+ fontFamily: 'inherit',
+ maxHeight: '15rem',
+ minWidth: '14rem',
+ maxWidth: '18rem'
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > li': {
+ display: 'flex',
+ alignItems: 'center',
+ gap: '8px',
+ minHeight: '28px',
+ padding: '0 4px',
+ borderRadius: '4px',
+ fontSize: '12px'
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > li[aria-selected]': {
+ backgroundColor: 'var(--color-hover)',
+ color: 'var(--color-surface)'
+ },
+ '.cm-tooltip.cm-tooltip-autocomplete > ul > completion-section': {
+ display: 'block',
+ padding: '6px 4px 4px',
+ border: 'none',
+ fontSize: '10px',
+ fontWeight: '500',
+ letterSpacing: '0.025em',
+ textTransform: 'uppercase',
+ color: 'var(--color-muted)',
+ opacity: '1'
+ },
+ '.cm-completionLabel': {
+ flex: '1',
+ minWidth: '0',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis'
+ },
+ '.cm-completionMatchedText': { textDecoration: 'none', fontWeight: '600' },
+ '.cm-completionDetail': {
+ marginLeft: 'auto',
+ fontStyle: 'normal',
+ fontVariantNumeric: 'tabular-nums',
+ color: 'var(--color-muted)'
+ }
+ },
+ { dark }
+ )
+}
diff --git a/src/theme/tokens-panel.ts b/src/theme/tokens-panel.ts
deleted file mode 100644
index 92e0a869e..000000000
--- a/src/theme/tokens-panel.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-/** Below this panel width (40rem) the inspector opens over the list instead of beside it. */
-export const TOKENS_PANEL_COMPACT_WIDTH = 640
-
-/** From this panel width (56rem) collections and groups move into a sidebar beside the list. */
-export const TOKENS_PANEL_SIDEBAR_WIDTH = 896
-
-/**
- * The list is its own `tokens-list` container, so its columns follow the space left beside the
- * inspector. Below 42rem (`@2xl`) the CSS name moves under the token name; the value columns
- * repeat `--token-modes` times. The name keeps a width of its own, so a collection with more
- * modes than fit scrolls sideways instead of hiding its names.
- */
-const COLUMNS =
- 'grid-cols-[minmax(8rem,1.4fr)_repeat(var(--token-modes),minmax(6rem,1fr))] @2xl/tokens-list:grid-cols-[minmax(8rem,1.1fr)_minmax(8rem,1fr)_repeat(var(--token-modes),minmax(7rem,1fr))]'
-
-export default {
- slots: {
- root: '@container/tokens flex min-h-0 flex-1 flex-col',
- toolbar: 'flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5',
- body: 'flex min-h-0 flex-1 overflow-hidden',
- sidebar: 'flex w-52 shrink-0 flex-col gap-4 overflow-y-auto border-r border-border p-2',
- sidebarSection: 'flex flex-col gap-0.5',
- sidebarHeading: 'mb-1 flex items-center justify-between px-2',
- sidebarItem:
- 'flex cursor-pointer items-center gap-2 rounded py-1 pr-2 pl-[calc(0.5rem+var(--depth,0)*0.75rem)] text-left text-xs text-surface hover:bg-hover data-[active]:bg-hover data-[active]:font-medium',
- sidebarGroupLabel: 'truncate',
- sidebarCount: 'ml-auto text-[11px] text-muted tabular-nums',
- list: '@container/tokens-list flex min-w-0 flex-1 flex-col overflow-auto',
- inspector: 'flex shrink-0 flex-col gap-4 overflow-y-auto p-4',
- output: 'flex shrink-0 flex-col border-t border-border',
- header: `sticky top-0 z-10 grid min-w-min items-center gap-3 border-b border-border bg-panel px-4 py-2 text-[11px] font-medium text-muted ${COLUMNS}`,
- group: 'px-4 pt-3 pb-1 text-[11px] font-semibold text-muted',
- row: `${COLUMNS} grid min-w-min cursor-pointer items-center gap-3 px-4 py-1.5 text-xs text-surface outline-none transition-colors duration-100 hover:bg-hover data-[highlighted]:bg-hover data-[state=checked]:bg-hover data-[state=checked]:ring-1 data-[state=checked]:ring-accent/40 data-[state=checked]:ring-inset data-[dragging]:opacity-50 data-[drop=after]:shadow-[inset_0_-2px_0_var(--color-accent)] data-[drop=before]:shadow-[inset_0_2px_0_var(--color-accent)] motion-reduce:transition-none`,
- name: 'flex min-w-0 flex-col truncate',
- nameLine: 'flex min-w-0 items-center gap-1.5',
- typeIcon: 'size-3 shrink-0 text-muted',
- cssName: 'truncate font-mono text-[11px] text-muted',
- /** The CSS name as its own column, from 42rem of list width. */
- cssColumn: 'hidden truncate font-mono text-[11px] text-muted @2xl/tokens-list:block',
- /** The CSS name column's title, in the header's own font like the others. */
- headerCssColumn: 'hidden @2xl/tokens-list:block',
- /** The CSS name under the token name, below 42rem of list width. */
- cssStacked: 'truncate font-mono text-[11px] text-muted @2xl/tokens-list:hidden',
- value:
- 'flex min-w-0 animate-in items-center gap-1.5 truncate font-mono text-[11px] fade-in duration-150 motion-reduce:animate-none',
- expression: 'truncate font-mono text-[11px] text-primary',
- modeHeader: 'flex min-w-0 flex-col gap-0.5',
- /** When a mode applies: words in the UI font, a selector or query in the code font. */
- modeCondition:
- 'truncate text-[11px] font-normal text-muted data-[code]:font-mono data-[code]:text-[10px]',
- section: 'flex flex-col gap-2',
- sectionTitle: 'text-[11px] font-semibold text-muted',
- field: 'flex flex-col gap-1',
- /** One mode in the collection inspector: its name, when it applies, and the CSS it writes. */
- /** The CSS a mode is written under, wrapped rather than cut so it reads in full. */
- modeCSS: 'font-mono text-[11px] break-all text-muted',
- mode: 'flex flex-col gap-1.5 border-b border-border pb-3 last:border-b-0 last:pb-0',
- label: 'text-[11px] text-muted',
- hint: 'text-[10px] text-muted',
- error: 'text-[10px] text-error',
- /** The fixed `--` in front of a CSS name the user types. */
- prefix: 'font-mono text-xs text-muted',
- /** A list cell being edited in place. */
- cellInput:
- 'w-full min-w-0 rounded border border-accent bg-input px-1.5 py-0.5 text-xs text-surface outline-none',
- /** A mode's value control beside the button that points it at a variable. */
- valueRow: 'flex items-center gap-1 [&>*:first-child]:min-w-0 [&>*:first-child]:flex-1',
- valueControl: 'flex min-w-0 items-center gap-1.5',
- empty: 'px-4 py-8 text-center text-xs text-muted'
- },
- variants: {
- /** Beside the token list on desktop; the whole panel, behind a back button, on mobile. */
- layout: {
- side: { inspector: 'w-64 border-l border-border @6xl/tokens:w-72', output: 'h-56' },
- full: { inspector: 'min-h-0 w-full flex-1', output: 'min-h-0 flex-1 border-t-0' }
- }
- },
- defaultVariants: { layout: 'side' }
-} as const
diff --git a/src/theme/variables/cell-input.ts b/src/theme/variables/cell-input.ts
new file mode 100644
index 000000000..f84ea7963
--- /dev/null
+++ b/src/theme/variables/cell-input.ts
@@ -0,0 +1,6 @@
+/** A list cell being edited in place. */
+export default {
+ slots: {
+ base: 'w-full min-w-0 rounded border border-accent bg-input px-1.5 py-0.5 text-xs text-surface outline-none'
+ }
+} as const
diff --git a/src/theme/variables/css-expression.ts b/src/theme/variables/css-expression.ts
new file mode 100644
index 000000000..c389b9bf3
--- /dev/null
+++ b/src/theme/variables/css-expression.ts
@@ -0,0 +1,9 @@
+export default {
+ slots: {
+ /** The field and buttons, in the value grid's columns under the value's. */
+ field: 'min-w-0',
+ error: 'text-[10px] text-error',
+ /** Where the browser computes the preview, out of sight. */
+ probe: 'pointer-events-none invisible absolute size-0 overflow-hidden'
+ }
+} as const
diff --git a/src/theme/variables/formula-field.ts b/src/theme/variables/formula-field.ts
new file mode 100644
index 000000000..fcf33cdfc
--- /dev/null
+++ b/src/theme/variables/formula-field.ts
@@ -0,0 +1,11 @@
+/** The value field: an input holding pills and operators, with the result at its end. */
+export default {
+ slots: {
+ root: 'relative flex h-auto min-h-7 cursor-text items-end gap-1.5 py-[3px] focus-within:border-panel-focus focus-within:ring-1 focus-within:ring-accent/25 data-[invalid]:border-error data-[invalid]:focus-within:border-error',
+ /** What the field holds, such as CSS, muted at its start. */
+ prefix: 'shrink-0 self-start leading-5 text-muted',
+ editor: 'flex min-w-0 flex-1 *:min-w-0 *:flex-1',
+ /** Buttons over the field's top right corner, which the text's first line keeps clear. */
+ actions: 'absolute top-[3px] right-2 flex h-5 items-center'
+ }
+} as const
diff --git a/src/theme/variables/inspector.ts b/src/theme/variables/inspector.ts
new file mode 100644
index 000000000..c119e2b36
--- /dev/null
+++ b/src/theme/variables/inspector.ts
@@ -0,0 +1,32 @@
+/** The collection, token, and selection inspectors beside or over the token list. */
+export default {
+ slots: {
+ root: 'flex shrink-0 flex-col gap-4 overflow-y-auto p-4',
+ section: 'flex flex-col gap-2',
+ title: 'text-[11px] font-semibold text-muted',
+ label: 'text-[11px] text-muted',
+ hint: 'text-[10px] text-muted',
+ error: 'text-[10px] text-error',
+ /** One mode's value, under the mode's name when there are several. */
+ value: 'flex flex-col gap-1',
+ /** The fixed `--` in front of a CSS name the user types. */
+ prefix: 'font-mono text-xs text-muted',
+ /** A scope's checkbox and name, only as wide as they are, so a click beside them toggles nothing. */
+ scope: 'flex w-fit items-center gap-2 text-xs text-surface',
+ /** A mode's value control beside the button that points it at a variable. */
+ valueRow: 'flex items-center gap-1 [&>*:first-child]:min-w-0 [&>*:first-child]:flex-1',
+ valueControl: 'flex min-h-7 min-w-0 items-center gap-1.5',
+ /** One mode in the collection inspector: its name, when it applies, and the CSS it writes. */
+ mode: 'flex flex-col gap-1.5 border-b border-border pb-3 last:border-b-0 last:pb-0',
+ /** The CSS a mode is written under, wrapped rather than cut so it reads in full. */
+ modeCSS: 'font-mono text-[11px] break-all text-muted'
+ },
+ variants: {
+ /** Beside the token list on desktop; the whole panel, behind a back button, on mobile. */
+ layout: {
+ side: { root: 'w-72 border-l border-border @6xl/tokens:w-80' },
+ full: { root: 'min-h-0 w-full flex-1' }
+ }
+ },
+ defaultVariants: { layout: 'side' }
+} as const
diff --git a/src/theme/variables/output.ts b/src/theme/variables/output.ts
new file mode 100644
index 000000000..7b582f9b2
--- /dev/null
+++ b/src/theme/variables/output.ts
@@ -0,0 +1,14 @@
+export default {
+ slots: {
+ root: 'flex shrink-0 flex-col border-t border-border',
+ title: 'text-[11px] font-semibold text-muted'
+ },
+ variants: {
+ /** Under the token list on desktop; the whole panel, behind a back button, on mobile. */
+ layout: {
+ side: { root: 'h-56' },
+ full: { root: 'min-h-0 flex-1 border-t-0' }
+ }
+ },
+ defaultVariants: { layout: 'side' }
+} as const
diff --git a/src/theme/variables/panel.ts b/src/theme/variables/panel.ts
new file mode 100644
index 000000000..dc86c7dea
--- /dev/null
+++ b/src/theme/variables/panel.ts
@@ -0,0 +1,13 @@
+/** Below this panel width (40rem) the inspector opens over the list instead of beside it. */
+export const TOKENS_PANEL_COMPACT_WIDTH = 640
+
+/** From this panel width (56rem) collections and groups move into a sidebar beside the list. */
+export const TOKENS_PANEL_SIDEBAR_WIDTH = 896
+
+export default {
+ slots: {
+ root: '@container/tokens flex min-h-0 flex-1 flex-col',
+ toolbar: 'flex shrink-0 items-center gap-1 border-b border-border px-3 py-1.5',
+ body: 'flex min-h-0 flex-1 overflow-hidden'
+ }
+} as const
diff --git a/src/theme/variables/sidebar.ts b/src/theme/variables/sidebar.ts
new file mode 100644
index 000000000..eb4f8181f
--- /dev/null
+++ b/src/theme/variables/sidebar.ts
@@ -0,0 +1,11 @@
+export default {
+ slots: {
+ root: 'flex w-52 shrink-0 flex-col gap-4 overflow-y-auto border-r border-border p-2',
+ section: 'flex flex-col gap-0.5',
+ heading: 'mb-1 flex items-center justify-between px-2',
+ title: 'text-[11px] font-semibold text-muted',
+ item: 'flex cursor-pointer items-center gap-2 rounded py-1 pr-2 pl-[calc(0.5rem+var(--depth,0)*0.75rem)] text-left text-xs text-surface hover:bg-hover data-[active]:bg-hover data-[active]:font-medium',
+ groupLabel: 'truncate',
+ count: 'ml-auto text-[11px] text-muted tabular-nums'
+ }
+} as const
diff --git a/src/theme/variables/table.ts b/src/theme/variables/table.ts
new file mode 100644
index 000000000..63f7e7006
--- /dev/null
+++ b/src/theme/variables/table.ts
@@ -0,0 +1,40 @@
+/**
+ * The list is its own `tokens-list` container, so its columns follow the space left beside the
+ * inspector. Below 42rem (`@2xl`) the CSS name moves under the token name; the value columns
+ * repeat `--token-modes` times. The name keeps a width of its own, so a collection with more
+ * modes than fit scrolls sideways instead of hiding its names.
+ */
+const COLUMNS =
+ 'grid-cols-[minmax(8rem,1.4fr)_repeat(var(--token-modes),minmax(6rem,1fr))] @2xl/tokens-list:grid-cols-[minmax(8rem,1.1fr)_minmax(8rem,1fr)_repeat(var(--token-modes),minmax(7rem,1fr))]'
+
+export default {
+ slots: {
+ root: '@container/tokens-list flex min-w-0 flex-1 flex-col overflow-auto',
+ header: `sticky top-0 z-10 grid min-w-min items-center gap-3 border-b border-border bg-panel px-4 py-2 text-[11px] font-medium text-muted ${COLUMNS}`,
+ group: 'px-4 pt-3 pb-1 text-[11px] font-semibold text-muted',
+ row: `${COLUMNS} grid min-w-min cursor-pointer items-center gap-3 px-4 py-1.5 text-xs text-surface outline-none transition-colors duration-100 hover:bg-hover data-[highlighted]:bg-hover data-[state=checked]:bg-hover data-[state=checked]:ring-1 data-[state=checked]:ring-accent/40 data-[state=checked]:ring-inset data-[dragging]:opacity-50 data-[drop=after]:shadow-[inset_0_-2px_0_var(--color-accent)] data-[drop=before]:shadow-[inset_0_2px_0_var(--color-accent)] motion-reduce:transition-none`,
+ name: 'flex min-w-0 flex-col truncate',
+ nameLine: 'flex min-w-0 items-center gap-1.5',
+ /** A token's type, or that a formula gives its value. */
+ icon: 'size-3 shrink-0 text-muted',
+ /** The CSS name as its own column, from 42rem of list width. */
+ cssColumn: 'hidden truncate font-mono text-[11px] text-muted @2xl/tokens-list:block',
+ /** The CSS name column's title, in the header's own font like the others. */
+ headerCssColumn: 'hidden @2xl/tokens-list:block',
+ /** The CSS name under the token name, below 42rem of list width. */
+ cssStacked: 'truncate font-mono text-[11px] text-muted @2xl/tokens-list:hidden',
+ value:
+ 'flex min-w-0 animate-in items-center gap-1.5 truncate font-mono text-[11px] fade-in duration-150 motion-reduce:animate-none',
+ /** An alias: its target's name, as wide as the name, and what it gives. */
+ aliasPill: 'max-w-[65%] flex-none',
+ aliasResult: 'truncate text-muted',
+ /** Marks a value whose CSS is an expression, which its tooltip shows. */
+ expressionBadge:
+ 'shrink-0 rounded-sm border border-border px-1 font-sans text-[9px] leading-3.5 font-medium text-muted',
+ modeHeader: 'flex min-w-0 flex-col gap-0.5',
+ /** When a mode applies: words in the UI font, a selector or query in the code font. */
+ modeCondition:
+ 'truncate text-[11px] font-normal text-muted data-[code]:font-mono data-[code]:text-[10px]',
+ empty: 'px-4 py-8 text-center text-xs text-muted'
+ }
+} as const
diff --git a/src/theme/variables/value-editor.ts b/src/theme/variables/value-editor.ts
new file mode 100644
index 000000000..4e76b92ff
--- /dev/null
+++ b/src/theme/variables/value-editor.ts
@@ -0,0 +1,19 @@
+/** A value editor: its label with its tools, then its field and what belongs to it. */
+export default {
+ slots: {
+ root: 'flex flex-col gap-1',
+ header: 'flex min-h-6 items-center justify-between gap-2',
+ label: 'text-[11px] text-muted',
+ tools: 'flex shrink-0 items-center',
+ control: 'flex min-h-7 min-w-0 items-center gap-1.5',
+ error: 'text-[10px] text-error'
+ },
+ variants: {
+ /** A single value heads its section; one of several modes is labelled with the mode. */
+ heading: {
+ section: { label: 'font-semibold' },
+ mode: {}
+ }
+ },
+ defaultVariants: { heading: 'mode' }
+} as const
diff --git a/tests/app/collab/variables.test.ts b/tests/app/collab/variables.test.ts
index 2de5e23c7..04296246e 100644
--- a/tests/app/collab/variables.test.ts
+++ b/tests/app/collab/variables.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph, type Color, type Variable } from '@open-pencil/scene-graph'
+import {
+ SceneGraph,
+ parseVariableFormula,
+ type Color,
+ type Variable
+} from '@open-pencil/scene-graph'
import { openRoomSession, type RoomSession } from '@/app/collab/session'
import { createEditorStore, type EditorStore } from '@/app/editor/session'
@@ -76,6 +81,35 @@ function brandOf(store: EditorStore, id: string): Variable {
}
describe('variables in a room', () => {
+ test('formula definitions and edits to their dependencies reach both peers', async () => {
+ await withRoom(async ({ host, guest, settle, ids }) => {
+ const base = host.graph.createVariable('space/base', 'FLOAT', ids.collection, 4)
+ const gap = host.graph.createVariable('space/gap', 'FLOAT', ids.collection, 8)
+ const enabled = host.graph.createVariable('enabled', 'BOOLEAN', ids.collection, true)
+ const visible = host.graph.createVariable('visible', 'BOOLEAN', ids.collection, false)
+ host.updateVariableValue(
+ gap.id,
+ ids.light,
+ parseVariableFormula(host.graph, gap.id, ids.light, '{space/base} * 2').value
+ )
+ host.updateVariableValue(
+ visible.id,
+ ids.light,
+ parseVariableFormula(host.graph, visible.id, ids.light, 'NOT {enabled}').value
+ )
+ await settle()
+ expect(guest.graph.resolveVariable(gap.id)).toBe(8)
+ expect(guest.graph.resolveVariable(visible.id)).toBe(false)
+ guest.updateVariableValue(base.id, ids.light, 6)
+ guest.updateVariableValue(enabled.id, ids.light, false)
+ await settle()
+ for (const store of [host, guest]) {
+ expect(store.graph.resolveVariable(gap.id)).toBe(12)
+ expect(store.graph.resolveVariable(visible.id)).toBe(true)
+ }
+ })
+ })
+
test('a joined tab receives the collections, modes, and values of the shared document', async () => {
await withRoom(async ({ guest, ids }) => {
const collection = expectDefined(guest.graph.variableCollections.get(ids.collection), 'Theme')
diff --git a/tests/app/editor/tokens/css-expression.test.ts b/tests/app/editor/tokens/css-expression.test.ts
new file mode 100644
index 000000000..38a51cc88
--- /dev/null
+++ b/tests/app/editor/tokens/css-expression.test.ts
@@ -0,0 +1,27 @@
+import { expect, test } from 'bun:test'
+
+import { cssExpressionPreview } from '@/app/editor/tokens/css-expression'
+
+test('a CSS expression previews what the browser computes, in stored units', () => {
+ const calls: Array<[string, string, string[]]> = []
+ /** A stand-in for the browser: every value computes to 20 of the property's unit. */
+ const measure = (property: string, value: string, variables: ReadonlyMap<string, string>) => {
+ calls.push([property, value, [...variables.keys()]])
+ return property === 'transition-duration' ? '0.15s' : '20px'
+ }
+ const tokens = new Map([['--space-md', '8px']])
+ expect(cssExpressionPreview('calc(12px + var(--space-md))', 'px', tokens, measure)).toEqual({
+ value: 20,
+ approximate: false
+ })
+ expect(calls.at(-1)).toEqual(['width', 'calc(12px + var(--space-md))', ['--space-md']])
+ expect(cssExpressionPreview('clamp(1rem, 4vw, 2rem)', 'rem', tokens, measure)).toEqual({
+ value: 20,
+ approximate: true
+ })
+ expect(cssExpressionPreview('calc(100ms + 50ms)', 'ms', tokens, measure)?.value).toBe(150)
+ // A percentage resolves against a container, and an unknown token has no value to use.
+ expect(cssExpressionPreview('50%', 'px', tokens, measure)).toBeUndefined()
+ expect(cssExpressionPreview('var(--missing)', 'px', tokens, measure)).toBeUndefined()
+ expect(cssExpressionPreview('4px', '%', tokens, measure)).toBeUndefined()
+})
diff --git a/tests/app/editor/tokens/value-editor.test.ts b/tests/app/editor/tokens/value-editor.test.ts
new file mode 100644
index 000000000..b890d89ca
--- /dev/null
+++ b/tests/app/editor/tokens/value-editor.test.ts
@@ -0,0 +1,61 @@
+import { expect, test } from 'bun:test'
+
+import {
+ formatVariableFormula,
+ parseVariableFormula,
+ SceneGraph,
+ variableFormulaReference,
+ type Variable
+} from '@open-pencil/scene-graph'
+
+import { parseTokenEditorText, tokenEditorText } from '@/app/editor/tokens/value-editor'
+
+function actions(graph: SceneGraph, target: Variable) {
+ return {
+ candidates: [],
+ parse: (modeId: string, text: string) => parseVariableFormula(graph, target.id, modeId, text),
+ format: (value: Parameters<typeof formatVariableFormula>[1]) =>
+ formatVariableFormula(graph, value),
+ reference: (id: string) => variableFormulaReference(graph, id)
+ }
+}
+
+test('one value field reads literals in the token unit, references and formulas', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Spacing')
+ const mode = collection.defaultModeId
+ const base = graph.createVariable('space/base', 'FLOAT', collection.id, 4)
+ const target = graph.createVariable('target', 'FLOAT', collection.id, 8)
+ const formula = actions(graph, target)
+ const read = (text: string) => parseTokenEditorText(target, mode, text, formula)
+
+ expect(read('20')).toEqual({ value: 20, resolved: 20, kind: 'literal' })
+ expect(read('{space/base}')).toMatchObject({ value: { aliasId: base.id }, kind: 'reference' })
+ expect(read('({space/base} * 3)')).toMatchObject({ resolved: 12, kind: 'formula' })
+ expect(() => read('{target} * 2')).toThrow('Circular')
+ expect(() => read('1 / 0')).toThrow('Cannot divide by zero')
+ expect(() => read('12nonsense')).toThrow()
+
+ target.valuesByMode[mode] = read('({space/base} * 3)').value
+ expect(tokenEditorText(target, mode, formula)).toBe('{space/base} * 3')
+ target.unit = 'rem'
+ expect(read('2')).toMatchObject({ value: 32, kind: 'literal' })
+ target.valuesByMode[mode] = 32
+ expect(tokenEditorText(target, mode, formula)).toBe('2')
+})
+
+test('true/false values read words, references, logic and number comparisons', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Flags')
+ const mode = collection.defaultModeId
+ graph.createVariable('enabled', 'BOOLEAN', collection.id, true)
+ graph.createVariable('width', 'FLOAT', collection.id, 640)
+ const target = graph.createVariable('visible', 'BOOLEAN', collection.id, true)
+ const read = (text: string) => parseTokenEditorText(target, mode, text, actions(graph, target))
+
+ expect(read('true')).toMatchObject({ value: true, kind: 'literal' })
+ expect(read('not {enabled}')).toMatchObject({ resolved: false, kind: 'formula' })
+ expect(read('{width} >= 600 and enabled')).toMatchObject({ resolved: true, kind: 'formula' })
+ expect(() => read('{width}')).toThrow('This gives a number, but visible holds true or false')
+ expect(() => read('var(--enabled)')).toThrow()
+})
diff --git a/tests/e2e/variables/formula.webkit.spec.ts b/tests/e2e/variables/formula.webkit.spec.ts
new file mode 100644
index 000000000..28d942ae1
--- /dev/null
+++ b/tests/e2e/variables/formula.webkit.spec.ts
@@ -0,0 +1,306 @@
+import type { Page } from '@playwright/test'
+
+import { expect, test } from '#tests/e2e/fixtures'
+import { CanvasHelper } from '#tests/helpers/canvas'
+import { cloudDiscoveryFixture } from '#tests/helpers/cloud/discovery'
+import {
+ formulaSceneState,
+ pasteFormulaText,
+ seedFormulaScene,
+ updateFormulaNumber
+} from '#tests/helpers/variables/formula'
+
+test.beforeEach(async ({ page }) => {
+ await page.route('https://cloud.openpencil.dev/.well-known/openpencil', (route) =>
+ route.fulfill({ json: cloudDiscoveryFixture('https://cloud.openpencil.dev') })
+ )
+})
+
+async function openToken(page: Page, id: string) {
+ await page
+ .getByRole('region', { name: 'Variables' })
+ .getByRole('button', { name: 'Open variables' })
+ .click()
+ const dialog = page.getByTestId('variables-dialog')
+ const row = dialog.locator(`[data-variable-id="${id}"]`)
+ await row.click()
+ const inspector = dialog.getByTestId('token-inspector')
+ return { dialog, row, inspector }
+}
+
+test('a number field takes literals, references and formulas, and reports errors on commit', async ({
+ page
+}) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { inspector, row } = await openToken(page, ids.width)
+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })
+ await expect(value).toHaveText('8')
+ await value.fill('{base} * 3')
+ await expect(inspector.getByText('= 12px', { exact: true })).toBeVisible()
+ expect((await formulaSceneState(page, ids)).width).toBe(8)
+ await value.press('Enter')
+ await expect.poll(async () => (await formulaSceneState(page, ids)).width).toBe(12)
+ await expect(row).toContainText('12px')
+
+ await value.fill('1 / 0')
+ await expect(value).toHaveAttribute('aria-invalid', 'false')
+ await value.press('Enter')
+ await expect(value).toHaveAttribute('aria-invalid', 'true')
+ await expect(inspector.getByText('Cannot divide by zero')).toBeVisible()
+ expect((await formulaSceneState(page, ids)).width).toBe(12)
+ await value.press('Escape')
+ await expect(value).toContainText('* 3')
+
+ await value.fill('base')
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).numberDefinition).toEqual({ aliasId: ids.base })
+ await expect(value.locator('[data-reference]')).toHaveCount(1)
+ await value.fill('16')
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).numberDefinition).toBe(16)
+
+ await value.fill('{base} * 2')
+ await value.press('End')
+ await value.press('Shift+ArrowLeft')
+ await inspector.getByRole('button', { name: 'Use a variable', exact: true }).click()
+ await page.getByRole('option', { name: 'base 4px', exact: true }).click()
+ await expect(value.locator('[data-reference]')).toHaveCount(2)
+ await expect(value).toBeFocused()
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).width).toBe(16)
+
+ const css = inspector.getByRole('textbox', { name: 'CSS expression', exact: true })
+ const cssToggle = inspector.getByTestId('variables-css-expression')
+ await expect(css).toHaveCount(0)
+ await expect(cssToggle).toHaveAttribute('aria-pressed', 'false')
+ await cssToggle.click()
+ await expect(css).toBeFocused()
+ await page.keyboard.insertText('clamp(1rem, 4vw, 2rem)')
+ await css.press('Enter')
+ await expect(page.getByTestId('token-output')).toContainText('clamp(1rem, 4vw, 2rem)')
+ expect((await formulaSceneState(page, ids)).width).toBe(16)
+ await value.fill('24')
+ await value.press('Enter')
+ await expect(css).toHaveText('clamp(1rem, 4vw, 2rem)')
+ await expect(cssToggle).toHaveAttribute('aria-pressed', 'true')
+ await cssToggle.click()
+ await expect(css).toHaveCount(0)
+ await expect(page.getByTestId('token-output')).not.toContainText('clamp(')
+ canvas.assertNoErrors()
+})
+
+test('a true/false value keeps its switch until a formula is asked for', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { inspector } = await openToken(page, ids.visible)
+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })
+ await expect(inspector.getByRole('switch', { name: 'Value' })).toBeChecked()
+ await expect(value).toHaveCount(0)
+ await inspector.getByRole('button', { name: 'Use a formula' }).click()
+ await expect(value).toBeFocused()
+ await page.keyboard.insertText('not {enabled}')
+ await expect(inspector.getByText('= false', { exact: true })).toBeVisible()
+ await value.press('Enter')
+ await expect.poll(async () => (await formulaSceneState(page, ids)).visible).toBe(false)
+
+ await value.fill('{size} > 4')
+ await expect(value.locator('[data-reference]')).toHaveCount(1)
+ await expect(inspector.getByText('= true', { exact: true })).toBeVisible()
+ await value.press('Enter')
+ await expect.poll(async () => (await formulaSceneState(page, ids)).visible).toBe(true)
+
+ await value.fill('false')
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).booleanDefinition).toBe(false)
+ await expect(inspector.getByRole('switch', { name: 'Value' })).not.toBeChecked()
+ canvas.assertNoErrors()
+})
+
+test('references are atomic pills with editable operators and plain source on copy', async ({
+ page
+}) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { inspector } = await openToken(page, ids.width)
+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })
+ await value.fill('{base} * 2')
+ const pill = value.locator('[data-reference]')
+ await expect(pill).toHaveText('base')
+ await expect(pill).toHaveAttribute('contenteditable', 'false')
+ await expect(value).not.toContainText('{')
+ await value.press('Meta+a')
+ const copied = await value.evaluate((element) => {
+ const clipboard = new DataTransfer()
+ element.dispatchEvent(
+ new ClipboardEvent('copy', { clipboardData: clipboard, bubbles: true, cancelable: true })
+ )
+ return clipboard.getData('text/plain')
+ })
+ expect(copied).toBe('{base} * 2')
+
+ await value.fill('{base}')
+ await value.press('End')
+ await value.press('Backspace')
+ await expect(pill).toHaveCount(0)
+ await expect(value.locator('.cm-placeholder')).toHaveText('Value or formula')
+ await pasteFormulaText(value, '{base} + 1')
+ await value.press('End')
+ await page.keyboard.insertText('0')
+ await expect(inspector.getByText('= 14px', { exact: true })).toBeVisible()
+ await value.press('Meta+z')
+ await expect(inspector.getByText('= 5px', { exact: true })).toBeVisible()
+ await value.press('Meta+Shift+z')
+ await expect(inspector.getByText('= 14px', { exact: true })).toBeVisible()
+ await value.press('Home')
+ await page.keyboard.type('2 * ')
+ await expect(inspector.getByText('= 18px', { exact: true })).toBeVisible()
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).width).toBe(18)
+ canvas.assertNoErrors()
+})
+
+test('the variable picker shows the numeric value of the edited mode', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ await page.evaluate(({ base, width }) => {
+ const editor = window.openPencil?.getStore?.()
+ const variable = editor?.graph.variables.get(base)
+ if (!editor || !variable) throw new Error('Missing variable')
+ const mode = editor.graph.createMode(variable.collectionId, 'Dense')
+ if (!mode) throw new Error('Missing mode')
+ editor.updateVariableValue(base, mode, 2)
+ editor.updateVariableValue(width, mode, 8)
+ }, ids)
+ const { inspector } = await openToken(page, ids.width)
+ const dense = inspector.getByRole('textbox', { name: 'Dense', exact: true })
+ await dense.fill('{base} * 2')
+ await expect(dense.locator('[data-reference]')).toHaveText('base')
+ await expect(inspector.getByText('= 4px', { exact: true })).toBeVisible()
+ await inspector.getByRole('button', { name: 'Use a variable', exact: true }).last().click()
+ await expect(page.getByRole('option', { name: 'base 2px', exact: true })).toBeVisible()
+ canvas.assertNoErrors()
+})
+
+test('redo preserves the selection restored after an external value update', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ await updateFormulaNumber(page, ids, 1234)
+ const { inspector } = await openToken(page, ids.width)
+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })
+ await value.press('Home')
+ await value.press('ArrowRight')
+ await value.press('Shift+ArrowRight')
+ await updateFormulaNumber(page, ids, 5678)
+ await expect(value).toHaveText('5678')
+ await expect(value).toBeFocused()
+ await value.press('Meta+z')
+ await expect(value).toHaveText('1234')
+ await value.press('Meta+Shift+z')
+ await expect(value).toHaveText('5678')
+ await page.keyboard.insertText('9')
+ await expect(value).toHaveText('5978')
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).width).toBe(5978)
+ canvas.assertNoErrors()
+})
+
+test('completion inserts a reference and the table shows the result', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { dialog, inspector, row } = 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('ba')
+ await expect(completion.getByRole('option', { name: /base/ })).toBeVisible()
+ await value.press('Enter')
+ await expect(value.locator('[data-reference]')).toHaveCount(1)
+ await expect(value).toBeFocused()
+ await value.press('Enter')
+ await expect.poll(async () => (await formulaSceneState(page, ids)).width).toBe(8)
+ await expect(row).toContainText('8px')
+ await expect(row).not.toContainText('{')
+ await value.fill('{ba')
+ await expect(completion.getByRole('option', { name: /base/ })).toBeVisible()
+ await value.press('Escape')
+ await expect(value).toHaveText('{ba')
+ await value.press('Escape')
+ await expect(value.locator('[data-reference]')).toHaveCount(1)
+ 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')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { dialog, inspector } = await openToken(page, ids.width)
+ await inspector.getByRole('button', { name: 'Add CSS expression' }).click()
+ const css = inspector.getByRole('textbox', { name: 'CSS expression', exact: true })
+ const completion = dialog.locator('.cm-tooltip-autocomplete')
+ await expect(css).toBeFocused()
+ await page.keyboard.type('cla')
+ await expect(completion.getByRole('option', { name: /^clamp/ })).toBeVisible()
+ await page.keyboard.press('Enter')
+ await page.keyboard.type('1rem, var(')
+ await expect(completion.getByRole('option', { name: /^--base/ })).toBeVisible()
+ await expect(completion.getByRole('option', { name: /^clamp/ })).toHaveCount(0)
+ await page.keyboard.press('Enter')
+ await page.keyboard.type(', 2rem)')
+ await expect(css.locator('[data-reference]')).toHaveText('--base')
+ await page.keyboard.press('Enter')
+ await expect(page.getByTestId('token-output')).toContainText('clamp(1rem, var(--base), 2rem)')
+
+ const error = inspector.getByRole('alert')
+ await css.press('Meta+a')
+ await page.keyboard.insertText('var(--missing)')
+ await expect(css).toHaveAttribute('aria-invalid', 'false')
+ await css.press('Enter')
+ await expect(error).toHaveText('No token is named --missing')
+ await page.keyboard.insertText(' ')
+ await expect(error).toHaveCount(0)
+ await css.press('Meta+a')
+ await page.keyboard.insertText('4 apples')
+ await css.press('Enter')
+ await expect(error).toHaveText('Not a valid value for width')
+ await css.press('Meta+a')
+ await page.keyboard.insertText('calc(2 * ')
+ await inspector.getByRole('button', { name: 'Use a variable' }).last().click()
+ await page.getByRole('option', { name: 'base 4px', exact: true }).click()
+ await expect(css).toBeFocused()
+ await page.keyboard.insertText(')')
+ await css.press('Enter')
+ await expect(page.getByTestId('token-output')).toContainText('calc(2 * var(--base))')
+ canvas.assertNoErrors()
+})
+
+test('long values span lines', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const ids = await seedFormulaScene(page)
+ const { inspector } = await openToken(page, ids.width)
+ const value = inspector.getByRole('textbox', { name: 'Value', exact: true })
+ await value.fill('{base} * 2')
+ await value.press('End')
+ await value.press('Shift+Enter')
+ await page.keyboard.insertText('+ {base}')
+ await expect(value.locator('.cm-line')).toHaveCount(2)
+ await value.press('Enter')
+ expect((await formulaSceneState(page, ids)).width).toBe(12)
+ canvas.assertNoErrors()
+})
diff --git a/tests/helpers/variables/formula.ts b/tests/helpers/variables/formula.ts
new file mode 100644
index 000000000..03f8c699b
--- /dev/null
+++ b/tests/helpers/variables/formula.ts
@@ -0,0 +1,76 @@
+import type { Locator, Page } from '@playwright/test'
+
+/** A number and Boolean token bound to ordinary frame geometry and visibility. */
+export async function seedFormulaScene(page: Page) {
+ return page.evaluate(() => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const graph = editor.graph
+ const collection = graph.createCollection('Formula tokens')
+ const base = graph.createVariable('base', 'FLOAT', collection.id, 4)
+ const width = graph.createVariable('size', 'FLOAT', collection.id, 8)
+ const enabled = graph.createVariable('enabled', 'BOOLEAN', collection.id, true)
+ const visible = graph.createVariable('visible', 'BOOLEAN', collection.id, true)
+ const node = graph.createNode('FRAME', editor.state.currentPageId, {
+ name: 'Formula consumer',
+ x: 100,
+ y: 100,
+ width: 8,
+ height: 20,
+ boundVariables: { width: width.id, visible: visible.id }
+ })
+ editor.requestRender()
+ return {
+ base: base.id,
+ width: width.id,
+ enabled: enabled.id,
+ visible: visible.id,
+ node: node.id,
+ mode: collection.defaultModeId
+ }
+ })
+}
+
+export async function formulaSceneState(
+ page: Page,
+ ids: Awaited<ReturnType<typeof seedFormulaScene>>
+) {
+ return page.evaluate(({ node, width, visible, mode }) => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ return {
+ width: editor.graph.getNode(node)?.width,
+ visible: editor.graph.getNode(node)?.visible,
+ numberDefinition: editor.graph.variables.get(width)?.valuesByMode[mode],
+ booleanDefinition: editor.graph.variables.get(visible)?.valuesByMode[mode]
+ }
+ }, ids)
+}
+
+/** Apply a document update without moving focus out of the value editor. */
+export async function updateFormulaNumber(
+ page: Page,
+ ids: Awaited<ReturnType<typeof seedFormulaScene>>,
+ value: number
+) {
+ await page.evaluate(
+ ({ width, mode, value }) => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ editor.updateVariableValue(width, mode, value)
+ },
+ { ...ids, value }
+ )
+}
+
+/** Paste through the editor's clipboard handler, preserving a distinct undoable edit. */
+export async function pasteFormulaText(field: Locator, text: string) {
+ await field.press('Meta+a')
+ await field.evaluate((element, text) => {
+ const clipboardData = new DataTransfer()
+ clipboardData.setData('text/plain', text)
+ element.dispatchEvent(
+ new ClipboardEvent('paste', { clipboardData, bubbles: true, cancelable: true })
+ )
+ }, text)
+}
diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txt
index 46090bc54..2e92732c5 100644
--- a/tools/checks/i18n/mixed-script-baseline.txt
+++ b/tools/checks/i18n/mixed-script-baseline.txt
@@ -416,6 +416,10 @@ zh-cn:variables.copyAsCSS
zh-cn:variables.copyAsTailwindTheme
ja:variables.cssName
ja:variables.expression
+ja:variables.addExpression
+ja:variables.removeExpression
+ja:variables.cssExpressionNegated
+ja:variables.cssExpressionSyntax
ja:variables.expressionHint
ja:variables.conditionHint
ja:variables.conditionCustom
@@ -423,6 +427,10 @@ ja:variables.libraryCollectionHint
ja:variables.addedToLibraryCollection
zh-cn:variables.cssName
zh-cn:variables.expression
+zh-cn:variables.addExpression
+zh-cn:variables.removeExpression
+zh-cn:variables.cssExpressionNegated
+zh-cn:variables.cssExpressionSyntax
zh-cn:variables.expressionHint
zh-cn:variables.conditionHint
zh-cn:variables.conditionCustom
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 83def7027..6965359dd 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -352,6 +352,7 @@ fr:variables.description
fr:variables.collection
fr:variables.condition
fr:variables.mode
+it:variables.formula
it:variables.unitAuto
pl:variables.unitAuto
es:menu.variables