AI-native design editor. Open-source Figma alternative.
fix(fig): open unsupported variable expressions with a warning (#1284)
Victor Wadsd2eb697b2377
diff --git a/changes/1284/fixed.md b/changes/1284/fixed.mdnew file mode 100644index 000000000..6f859436d--- /dev/null+++ b/changes/1284/fixed.md@@ -0,0 +1 @@+- `.fig` files whose variables use expressions OpenPencil cannot evaluate yet, such as `TERNARY` or `VAR_MODE_LOOKUP`, open with the values saved in the file and keep those expressions when saved, instead of failing to open.diff --git a/packages/core/src/editor/clipboard/variables.ts b/packages/core/src/editor/clipboard/variables.tsindex 4c20435c2..a7b1c6dd2 100644--- a/packages/core/src/editor/clipboard/variables.ts+++ b/packages/core/src/editor/clipboard/variables.ts@@ -1,4 +1,5 @@import {+ isUnsupportedVariableValue,remapStyleRunReferences,mapVariableValueReferences,variableValueReferences,@@ -21,15 +22,26 @@ export function captureClipboardVariables(): ClipboardVariables {const variables = new Map<string, Variable>()const collections = new Map<string, VariableCollection>()+ function capture(collection: VariableCollection | undefined) {+ if (collection && !collections.has(collection.id))+ collections.set(collection.id, structuredClone(collection))+ }function visit(id: string) {if (variables.has(id)) returnconst variable = graph.variables.get(id)if (!variable) returnvariables.set(id, structuredClone(variable))- const collection = graph.variableCollections.get(variable.collectionId)- if (collection) collections.set(collection.id, structuredClone(collection))+ capture(graph.variableCollections.get(variable.collectionId))for (const value of Object.values(variable.valuesByMode)) {for (const reference of variableValueReferences(value)) visit(reference)+ // A kept expression can name a mode of a collection none of its aliases reach.+ if (isUnsupportedVariableValue(value))+ for (const modeId of value.modes)+ capture(+ [...graph.variableCollections.values()].find((collection) =>+ collection.modes.some((mode) => mode.modeId === modeId)+ )+ )}}for (const node of nodes) {@@ -76,7 +88,11 @@ export function importClipboardVariables(graph: SceneGraph, dependencies: ClipbovaluesByMode: Object.fromEntries(Object.entries(variable.valuesByMode).map(([mode, value]) => [modeIds.get(mode) ?? mode,- mapVariableValueReferences(value, (id) => variableIds.get(id) ?? id)+ mapVariableValueReferences(+ value,+ (id) => variableIds.get(id) ?? id,+ (id) => modeIds.get(id) ?? id+ )]))}))diff --git a/packages/core/src/io/formats/fig/export/variables.ts b/packages/core/src/io/formats/fig/export/variables.tsindex 7e1591855..df7c34995 100644--- a/packages/core/src/io/formats/fig/export/variables.ts+++ b/packages/core/src/io/formats/fig/export/variables.ts@@ -3,6 +3,8 @@ import * as v from 'valibot'import {collectionPluginDataNodeChange,parseGuidOrNull,+ mapUnsupportedExpressionReferences,+ unsupportedExpressionData,variableAlias,variableMetadataNodeChange} from '@open-pencil/fig/node-change'@@ -10,6 +12,7 @@ import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'import {modesDefaultFirst,+ isUnsupportedVariableValue,MAX_FORMULA_DEPTH,formulaResultType,variableFormulaSchema,@@ -144,8 +147,21 @@ function variableValueToKiwi(graph: SceneGraph,value: VariableValue,type: string,- ids: Map<string, GUID>+ ids: Map<string, GUID>,+ modes?: ReadonlyMap<string, GUID>): VariableDataEntry {+ if (isUnsupportedVariableValue(value)) {+ const data = unsupportedExpressionData(value.value)+ mapUnsupportedExpressionReferences(+ data,+ (_, index) => {+ const id = value.references[index]+ return id && graph.variables.has(id) ? variableAlias(graph, id, ids) : undefined+ },+ (guid, index) => modes?.get(value.modes[index] ?? '') ?? guid+ )+ return data+ }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')@@ -275,7 +291,7 @@ export function appendVariableNodeChanges(variableDataValues: {entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({modeID: modes.get(mode) ?? stringToGuid(mode),- variableData: variableValueToKiwi(graph, value, variable.type, ids)+ variableData: variableValueToKiwi(graph, value, variable.type, ids, modes)}))},...variableMetadataNodeChange(variable, modeKey),diff --git a/packages/core/src/kiwi/fig/session/options.ts b/packages/core/src/kiwi/fig/session/options.tsindex 2355c42fe..ecc25bd06 100644--- a/packages/core/src/kiwi/fig/session/options.ts+++ b/packages/core/src/kiwi/fig/session/options.ts@@ -7,6 +7,10 @@ export type FigReaderDiagnostic =| { kind: 'property'; diagnostic: Parameters<Handler<'onUnresolvedProperty'>>[0] }| { kind: 'assignment'; diagnostic: Parameters<Handler<'onUnresolvedAssignment'>>[0] }| { kind: 'binding'; diagnostic: Parameters<Handler<'onUnresolvedBinding'>>[0] }+ | {+ kind: 'variable-expression'+ diagnostic: Parameters<Handler<'onUnsupportedVariableExpression'>>[0]+ }| { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }| { kind: 'slot-content'; diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0] }@@ -43,6 +47,8 @@ export function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemonUnresolvedProperty: (diagnostic) => report(sink, { kind: 'property', diagnostic }),onUnresolvedAssignment: (diagnostic) => report(sink, { kind: 'assignment', diagnostic }),onUnresolvedBinding: (diagnostic) => report(sink, { kind: 'binding', diagnostic }),+ onUnsupportedVariableExpression: (diagnostic) =>+ report(sink, { kind: 'variable-expression', diagnostic }),onMissingComponent: (diagnostic) => report(sink, { kind: 'component', diagnostic }),onMissingSlotContent: (diagnostic) => report(sink, { kind: 'slot-content', diagnostic })}diff --git a/packages/core/tests/io/formats/fig/import/unsupported-expressions.test.ts b/packages/core/tests/io/formats/fig/import/unsupported-expressions.test.tsnew file mode 100644index 000000000..50446d0cf--- /dev/null+++ b/packages/core/tests/io/formats/fig/import/unsupported-expressions.test.ts@@ -0,0 +1,206 @@+import { expect, test } from 'bun:test'++import { deflateSync } from 'fflate'++import { compressFigDataSync, parseFigBuffer } from '@open-pencil/fig'+import { getCompiledSchema, getSchemaBytes, type NodeChange } from '@open-pencil/kiwi/fig/codec'+import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'+import { isUnsupportedVariableValue, SceneGraph, type VariableValue } from '@open-pencil/scene-graph'++import { createEditor } from '#core/editor/create'+import {+ captureClipboardVariables,+ importClipboardVariables+} from '#core/editor/clipboard/variables'+import { exportFigFile } from '#core/io/formats/fig/export'+import { appendVariableNodeChanges } from '#core/io/formats/fig/export/variables'+import { parseFigFile, parseFigFileViaWorker } from '#core/io/formats/fig/read'+import { releaseFigPopulationWorker } from '#core/kiwi/fig/population/client'+import { deserializeSceneGraph, serializeSceneGraph } from '#core/kiwi/fig/parse/transfer'+import { populateFigPage } from '#core/kiwi/fig/session/document-state'++/**+ * A file whose `Gap` variable is `VAR_MODE_LOOKUP` over a mode of `Lookup` and that collection's+ * `Compact` variable, with a 91px rectangle bound to it on each of two pages.+ */+async function figWithLookup() {+ const source = new SceneGraph()+ const collection = source.createCollection('Theme')+ const lookup = source.createCollection('Lookup')+ const compact = source.createVariable('Compact', 'FLOAT', lookup.id, 8)+ const gap = source.createVariable('Gap', 'FLOAT', collection.id, 24)+ for (const page of [source.getPages()[0], source.createNode('CANVAS', source.rootId)])+ source.createNode('RECTANGLE', page.id, { width: 91, height: 70, boundVariables: { width: gap.id } })+ const decoded = parseFigBuffer((await exportFigFile(source)).slice().buffer)+ const record = (id: string) =>+ decoded.nodeChanges.find((node) => node.guid && guidToString(node.guid) === id)+ const entry = record(gap.id)?.variableDataValues?.entries?.[0]+ const target = record(compact.id)?.guid+ if (!entry || !target) throw new Error('Missing synthetic variables')+ entry.variableData = {+ dataType: 'EXPRESSION',+ resolvedDataType: 'FLOAT',+ value: {+ expressionValue: {+ expressionFunction: 'VAR_MODE_LOOKUP',+ expressionArguments: [+ {+ dataType: 'MAP',+ value: {+ mapValue: {+ values: [+ {+ guidKey: stringToGuid(lookup.defaultModeId),+ value: { dataType: 'ALIAS', value: { alias: { guid: target } } }+ }+ ]+ }+ }+ }+ ]+ }+ }+ }+ // Figma saves the size a binding gave; drawing keeps it while the expression has no value.+ for (const node of decoded.nodeChanges)+ if (node.type === 'RECTANGLE') node.size = { x: 91, y: 70 }+ const bytes = compressFigDataSync(+ deflateSync(getSchemaBytes()),+ getCompiledSchema().encodeMessage(decoded),+ new Uint8Array(),+ '{}',+ []+ )+ return {+ bytes,+ data: entry.variableData,+ mode: collection.defaultModeId,+ lookupMode: lookup.defaultModeId,+ compact: compact.id,+ gap: gap.id+ }+}++function lookupOperand(record: NodeChange | undefined) {+ return record?.variableDataValues?.entries?.[0].variableData.value?.expressionValue+ ?.expressionArguments?.[0].value?.mapValue?.values?.[0]+}++test('layers bound to a kept expression open at the size the file saved', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFileViaWorker(file.bytes.slice().buffer, { populate: 'first-page' })+ try {+ populateFigPage(graph, graph.getPages()[1].id)+ expect(graph.getPages().map((page) => graph.getChildren(page.id)[0].width)).toEqual([91, 91])+ } finally {+ releaseFigPopulationWorker(graph)+ }+})++test('saving and reopening writes a kept expression back unchanged', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer)+ expect(reopened.variables.get(file.gap)?.valuesByMode[file.mode]).toEqual({+ expression: 'UNSUPPORTED',+ function: 'VAR_MODE_LOOKUP',+ value: { ...file.data },+ references: [file.compact],+ modes: [file.lookupMode]+ })+ expect(reopened.getChildren(reopened.getPages()[0].id)[0].width).toBe(91)+})++test('saving points a kept expression’s aliases and mode keys at the saved GUIDs', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const records: NodeChange[] = []+ appendVariableNodeChanges(+ graph,+ records,+ { sessionID: 0, localID: 1 },+ new Map([[file.compact, { sessionID: 99, localID: 1 }]]),+ new Map([[file.lookupMode, { sessionID: 99, localID: 2 }]])+ )+ expect(lookupOperand(records.find((node) => node.name === 'Gap'))).toMatchObject({+ guidKey: { sessionID: 99, localID: 2 },+ value: { value: { alias: { guid: { sessionID: 99, localID: 1 } } } }+ })+})++test('an alias to a variable the document no longer has is written as the file had it', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ graph.removeVariable(file.compact)+ const records: NodeChange[] = []+ appendVariableNodeChanges(graph, records, { sessionID: 0, localID: 1 }, new Map(), new Map())+ expect(lookupOperand(records.find((node) => node.name === 'Gap'))?.value?.value?.alias).toEqual({+ guid: stringToGuid(file.compact)+ })+})++test('pasting a layer bound to a kept expression into another file follows the copied alias and mode', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const rectangle = graph.getChildren(graph.getPages()[0].id)[0]+ const destination = new SceneGraph()+ const transfer = importClipboardVariables(+ destination,+ captureClipboardVariables(graph, [rectangle])+ )+ transfer.apply()+ const gap = transfer.variableIds.get(file.gap) ?? ''+ const compact = transfer.variableIds.get(file.compact) ?? ''+ expect(destination.variables.get(gap)?.valuesByMode[transfer.modeIds.get(file.mode) ?? '']).toMatchObject(+ { expression: 'UNSUPPORTED', references: [compact], modes: [transfer.modeIds.get(file.lookupMode)] }+ )+ const saved = parseFigBuffer((await exportFigFile(destination)).slice().buffer).nodeChanges+ const savedCompact = saved.find((node) => node.name === 'Compact')?.guid+ const savedLookupMode = saved.find((node) => node.name === 'Lookup')?.variableSetModes?.[0]?.id+ expect(savedLookupMode).toBeDefined()+ expect(lookupOperand(saved.find((node) => node.name === 'Gap'))).toMatchObject({+ guidKey: savedLookupMode,+ value: { value: { alias: { guid: savedCompact } } }+ })+})++test('pasting copies a collection that a kept expression reaches only through a mode key', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const size = graph.createCollection('Size')+ const kept = graph.variables.get(file.gap)?.valuesByMode[file.mode]+ if (!isUnsupportedVariableValue(kept)) throw new Error('Missing kept expression')+ kept.modes = [size.defaultModeId]+ const destination = new SceneGraph()+ const transfer = importClipboardVariables(+ destination,+ captureClipboardVariables(graph, [graph.getChildren(graph.getPages()[0].id)[0]])+ )+ transfer.apply()+ const sizeMode = transfer.modeIds.get(size.defaultModeId)+ expect(sizeMode).toBeDefined()+ const gap = destination.variables.get(transfer.variableIds.get(file.gap) ?? '')+ expect(gap?.valuesByMode[transfer.modeIds.get(file.mode) ?? '']).toMatchObject({+ modes: [sizeMode]+ })+})++test('a kept expression can be replaced with a value, and the replacement undone', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const kept = structuredClone(graph.variables.get(file.gap)?.valuesByMode[file.mode])+ const editor = createEditor({ graph })+ editor.updateVariableValue(file.gap, file.mode, 12 satisfies VariableValue)+ expect(graph.resolveVariable(file.gap, file.mode)).toBe(12)+ editor.undoAction()+ expect(graph.variables.get(file.gap)?.valuesByMode[file.mode]).toEqual(kept)+})++test('recovery keeps a kept expression', async () => {+ const file = await figWithLookup()+ const graph = await parseFigFile(file.bytes.slice().buffer)+ const recovered = deserializeSceneGraph(structuredClone(serializeSceneGraph(graph)))+ expect(recovered.variables.get(file.gap)?.valuesByMode[file.mode]).toEqual(+ graph.variables.get(file.gap)?.valuesByMode[file.mode]+ )+})diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex 93c8fe311..3c8858a4f 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -38,7 +38,10 @@ import type { ComponentConstruction } from './components'import { loadPageTransaction } from './load-transaction'import { applyDocumentMetadata } from './metadata'import { createArchiveDocumentReader, createDocumentReader } from './read'-import { materializeVariableResources } from './variables'+import {+ materializeVariableResources,+ type UnsupportedVariableExpressionDiagnostic+} from './variables'export interface DocumentAssemblyOptions extends InterpretInstanceOptions {/** Restrict scene population to these source pages plus required component ownership. */@@ -46,6 +49,8 @@ export interface DocumentAssemblyOptions extends InterpretInstanceOptions {images?: ReadonlyMap<string, Uint8Array>/** A resource record the materializer does not convert; acknowledged rather than dropped. */onUnsupportedResource?: (resource: NodeChange) => void+ /** Explicitly preserve expression-valued variables without evaluating them. */+ onUnsupportedVariableExpression?: (diagnostic: UnsupportedVariableExpressionDiagnostic) => voidonUnresolvedBinding?: (diagnostic: BindingReferenceDiagnostic) => void}@@ -256,7 +261,13 @@ function createAssemblyState(applyDocumentMetadata(graph, reader.documentRecord)for (const [hash, bytes] of options.images ?? []) graph.images.set(hash, bytes.slice())graph.applyImportedStateDuring(- () => materializeVariableResources(graph, reader.resources, options.onUnsupportedResource),+ () =>+ materializeVariableResources(+ graph,+ reader.resources,+ options.onUnsupportedResource,+ options.onUnsupportedVariableExpression+ ),() => `0:${nextImportedId++}`)for (const page of graph.getPages()) graph.deleteNode(page.id)diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.tsindex e0e59b770..5bac3ba68 100644--- a/packages/fig/src/document/variables.ts+++ b/packages/fig/src/document/variables.ts@@ -21,8 +21,20 @@ import {readVariableToken,withoutTokenPluginData} from '../node-change/variable/token'+import { mapUnsupportedExpressionReferences } from '../node-change/variable/unsupported'import { createResourceResolver } from './resource-reference'+export interface UnsupportedVariableExpressionDiagnostic {+ sourceId: string+ modeId: string+ reason: 'unsupported-variable-expression'+}+type ExpressionReporter = (diagnostic: UnsupportedVariableExpressionDiagnostic) => void++class UnsupportedExpressionError extends Error {+ override name = 'UnsupportedExpressionError'+}+function valueOf(entry: VariableDataEntry,resolve: ReturnType<typeof createResourceResolver>,@@ -55,7 +67,14 @@ function expressionValue(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 parsed = v.safeParse(v.picklist(VARIABLE_FORMULA_OPERATORS), expression?.expressionFunction)+ if (!parsed.success) {+ if (!expression?.expressionFunction) throw new Error('Missing variable expression function')+ throw new UnsupportedExpressionError(+ `Unsupported variable expression ${expression.expressionFunction}`+ )+ }+ const operator = parsed.outputconst type = formulaResultType(operator)if (entry.resolvedDataType && entry.resolvedDataType !== type)throw new Error(`Expression result type does not match ${entry.resolvedDataType}`)@@ -81,10 +100,12 @@ function colorExpression(const expression = entry.value?.expressionValueconst args = expression?.expressionArgumentsif (expression?.expressionFunction !== 'COMPOSE_COLOR' || args?.length !== 2)- throw new Error(`Unsupported variable expression ${expression?.expressionFunction}`)+ throw new UnsupportedExpressionError(+ `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')+ throw new UnsupportedExpressionError('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 })@@ -93,7 +114,8 @@ function colorExpression(function modeValues(resource: NodeChange,modes: readonly string[],- resolve: ReturnType<typeof createResourceResolver>+ resolve: ReturnType<typeof createResourceResolver>,+ onUnsupportedExpression?: ExpressionReporter): Record<string, VariableValue> {const entries = resource.variableDataValues?.entries ?? []if (!entries.length) throw new Error('Missing mode values')@@ -101,7 +123,38 @@ function modeValues(for (const entry of entries) {const modeId = guidToString(entry.modeID)if (!modes.includes(modeId)) throw new Error('Unknown mode')- const value = valueOf(entry.variableData, resolve)+ let value: VariableValue+ try {+ value = valueOf(entry.variableData, resolve)+ } catch (error) {+ if (!(error instanceof UnsupportedExpressionError) || !onUnsupportedExpression) throw error+ const data = structuredClone(entry.variableData)+ const references: (string | null)[] = []+ const modeKeys: string[] = []+ mapUnsupportedExpressionReferences(+ data,+ (reference) => {+ references.push(resolve(reference) ?? null)+ return undefined+ },+ (guid) => {+ modeKeys.push(guidToString(guid))+ return guid+ }+ )+ value = {+ expression: 'UNSUPPORTED',+ function: data.value?.expressionValue?.expressionFunction ?? '',+ value: { ...data },+ references,+ modes: modeKeys+ }+ onUnsupportedExpression({+ sourceId: resource.guid ? guidToString(resource.guid) : '',+ modeId,+ reason: 'unsupported-variable-expression'+ })+ }if (typeof value === 'object' &&'expression' in value &&@@ -118,7 +171,8 @@ function modeValues(export function materializeVariableResources(graph: SceneGraph,resources: readonly NodeChange[],- onUnsupported?: (resource: NodeChange) => void+ onUnsupported?: (resource: NodeChange) => void,+ onUnsupportedExpression?: ExpressionReporter): void {const report = (resource: NodeChange, reason: string): void => {if (!onUnsupported) throw new Error(`Unsupported document resource ${resource.type}: ${reason}`)@@ -153,13 +207,14 @@ export function materializeVariableResources(version: typeof resource.version === 'string' ? resource.version : undefined})}- addVariables(graph, resources, report)+ addVariables(graph, resources, report, onUnsupportedExpression)}function addVariables(graph: SceneGraph,resources: readonly NodeChange[],- report: (resource: NodeChange, reason: string) => void+ report: (resource: NodeChange, reason: string) => void,+ onUnsupportedExpression?: ExpressionReporter): void {const resolve = createResourceResolver(resources)for (const resource of resources) {@@ -185,7 +240,8 @@ function addVariables(modeValues(resource,collection.modes.map((mode) => mode.modeId),- resolve+ resolve,+ onUnsupportedExpression))} catch (error) {diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.tsindex d8e8ef8e4..5a8a3f6ba 100644--- a/packages/fig/src/node-change/index.ts+++ b/packages/fig/src/node-change/index.ts@@ -24,5 +24,6 @@ export * from './text/values'export * from './variable/bindings'export * from './variable/metadata'export * from './variable/token'+export * from './variable/unsupported'export * from './vector/geometry'export * from './vector/network'diff --git a/packages/fig/src/node-change/variable/unsupported.ts b/packages/fig/src/node-change/variable/unsupported.tsnew file mode 100644index 000000000..3c360cd19--- /dev/null+++ b/packages/fig/src/node-change/variable/unsupported.ts@@ -0,0 +1,97 @@+import * as v from 'valibot'++import type { GUID, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'++const guid = v.looseObject({+ sessionID: v.pipe(v.number(), v.integer(), v.minValue(0)),+ localID: v.pipe(v.number(), v.integer(), v.minValue(0))+})+const reference = v.looseObject({+ guid: v.optional(guid),+ assetRef: v.optional(v.looseObject({ key: v.string(), version: v.optional(v.string()) }))+})+const data: v.GenericSchema<VariableDataEntry> = v.lazy(() =>+ v.looseObject({+ dataType: v.optional(v.string()),+ resolvedDataType: v.optional(v.string()),+ value: v.optional(+ v.looseObject({+ alias: v.optional(reference),+ mapValue: v.optional(+ v.looseObject({+ values: v.optional(+ v.array(+ v.looseObject({+ key: v.optional(v.string()),+ guidKey: v.optional(guid),+ value: v.optional(data)+ })+ )+ )+ })+ ),+ colorArrayValue: v.optional(v.looseObject({ colors: v.optional(v.array(data)) })),+ fontStyleValue: v.optional(+ v.looseObject({+ asString: v.optional(data),+ asFloat: v.optional(data),+ asVariations: v.optional(data)+ })+ ),+ boolValue: v.optional(v.boolean()),+ floatValue: v.optional(v.number()),+ textValue: v.optional(v.string()),+ colorValue: v.optional(+ v.looseObject({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })+ ),+ expressionValue: v.optional(+ v.looseObject({+ expressionFunction: v.string(),+ expressionArguments: v.optional(v.array(data))+ })+ )+ })+ )+ })+)+type Alias = NonNullable<NonNullable<VariableDataEntry['value']>['alias']>++/**+ * Walk the aliases and mode keys of an expression OpenPencil does not evaluate, always in the same+ * order, without reading the function. `alias` gets each alias with its position and may return a+ * replacement; `mode` does the same for each mode key. Changes `entry` in place.+ */+export function mapUnsupportedExpressionReferences(+ entry: VariableDataEntry,+ alias: (reference: Alias, index: number) => Alias | undefined,+ mode: (guid: GUID, index: number) => GUID = (guid) => guid+): void {+ let index = 0+ let modeIndex = 0+ const visit = (data: VariableDataEntry): void => {+ const value = data.value+ if (!value) return+ if (value.alias) value.alias = alias(value.alias, index++) ?? value.alias+ const nested = [+ ...(value.expressionValue?.expressionArguments ?? []),+ ...(value.colorArrayValue?.colors ?? []),+ value.fontStyleValue?.asString,+ value.fontStyleValue?.asFloat,+ value.fontStyleValue?.asVariations+ ]+ for (const item of value.mapValue?.values ?? []) {+ if (item.guidKey) item.guidKey = mode(item.guidKey, modeIndex++)+ nested.push(item.value)+ }+ for (const child of nested) if (child) visit(child)+ }+ visit(entry)+}++/** Check a kept expression, which may have come back through the clipboard, before writing it. */+export function unsupportedExpressionData(raw: unknown): VariableDataEntry {+ const parsed = v.parse(data, structuredClone(raw))+ if (parsed.dataType !== 'EXPRESSION' || !parsed.value?.expressionValue)+ throw new Error('Invalid unsupported variable expression')+ return parsed+}diff --git a/packages/fig/tests/document/unsupported-expressions.test.ts b/packages/fig/tests/document/unsupported-expressions.test.tsnew file mode 100644index 000000000..98effe6a3--- /dev/null+++ b/packages/fig/tests/document/unsupported-expressions.test.ts@@ -0,0 +1,154 @@+import { expect, test } from 'bun:test'++import { guid } from '#fig-tests/helpers/guid'+import { materializeDocument, type DocumentAssemblyOptions } from '#fig/document/materialize'+import { unsupportedExpressionData } from '#fig/node-change/variable/unsupported'+import { noop } from 'es-toolkit/function'++import type { NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'++const COLLECTION = '1:1'+const DEFAULT_MODE = '1:2'+const OTHER_MODE = '1:3'+const TARGET = '1:4'+const VARIABLE = '1:5'++/** A collection with two modes, a literal at `1:4` and `variableData` in `1:5`'s first mode. */+function resources(variableData: VariableDataEntry): NodeChange[] {+ return [+ {+ guid: guid(1),+ type: 'VARIABLE_SET',+ variableSetModes: [+ { id: guid(2), name: 'Default' },+ { id: guid(3), name: 'Other' }+ ]+ },+ {+ guid: guid(4),+ type: 'VARIABLE',+ variableResolvedType: 'BOOLEAN',+ variableSetID: { guid: guid(1) },+ variableDataValues: {+ entries: [guid(2), guid(3)].map((modeID) => ({+ modeID,+ variableData: { dataType: 'BOOLEAN', value: { boolValue: true } }+ }))+ }+ },+ {+ guid: guid(5),+ type: 'VARIABLE',+ variableResolvedType: 'FLOAT',+ variableSetID: { guid: guid(1) },+ variableDataValues: {+ entries: [+ { modeID: guid(2), variableData },+ { modeID: guid(3), variableData: { dataType: 'FLOAT', value: { floatValue: 42 } } }+ ]+ }+ }+ ]+}++function expression(+ expressionFunction: string,+ expressionArguments: VariableDataEntry[] = []+): VariableDataEntry {+ return {+ dataType: 'EXPRESSION',+ resolvedDataType: 'FLOAT',+ value: { expressionValue: { expressionFunction, expressionArguments } }+ }+}++const ternary = expression('TERNARY', [+ { dataType: 'ALIAS', value: { alias: { guid: guid(4) } } },+ { dataType: 'FLOAT', value: { floatValue: 8 } },+ { dataType: 'ALIAS', value: { alias: { assetRef: { key: 'missing-library-variable' } } } }+])++function open(source: NodeChange[], options: DocumentAssemblyOptions = {}) {+ return materializeDocument(source, [], { onUnsupportedVariableExpression: noop, ...options })+ .graph+}++test('a strict read still rejects an expression it cannot evaluate', () => {+ expect(() => materializeDocument(resources(ternary))).toThrow(+ 'Unsupported variable expression TERNARY'+ )+})++test('a tolerant read keeps the expression with one reference slot per alias', () => {+ const graph = open(resources(ternary))+ expect(graph.variables.get(VARIABLE)?.valuesByMode[DEFAULT_MODE]).toEqual({+ expression: 'UNSUPPORTED',+ function: 'TERNARY',+ value: { ...ternary },+ references: [TARGET, null],+ modes: []+ })+})++test('a kept expression has no value, while the variable’s other modes still resolve', () => {+ const graph = open(resources(ternary))+ expect(graph.resolveVariable(VARIABLE, DEFAULT_MODE)).toBeUndefined()+ expect(graph.resolveVariable(VARIABLE, OTHER_MODE)).toBe(42)+ expect(graph.variableCollections.get(COLLECTION)?.modes).toHaveLength(2)+})++test('each kept expression is reported with its variable and mode', () => {+ const diagnostics: unknown[] = []+ open(resources(ternary), {+ onUnsupportedVariableExpression: (diagnostic) => diagnostics.push(diagnostic)+ })+ expect(diagnostics).toEqual([+ { sourceId: VARIABLE, modeId: DEFAULT_MODE, reason: 'unsupported-variable-expression' }+ ])+})++test.each(['STRINGIFY', 'VAR_MODE_LOOKUP', 'IS_TRUTHY', 'RESOLVE_VARIANT', 'KEYFRAME', 'UNKNOWN'])(+ '%s is kept rather than evaluated',+ (name) => {+ const value = open(resources(expression(name))).variables.get(VARIABLE)?.valuesByMode[+ DEFAULT_MODE+ ]+ expect(value).toMatchObject({ expression: 'UNSUPPORTED', function: name })+ }+)++test('a color composed from another expression is kept whole', () => {+ const nested = {+ ...expression('COMPOSE_COLOR', [expression('TERNARY'), { dataType: 'FLOAT', value: {} }]),+ resolvedDataType: 'COLOR'+ }+ const value = open(resources(nested)).variables.get(VARIABLE)?.valuesByMode[DEFAULT_MODE]+ expect(value).toMatchObject({ expression: 'UNSUPPORTED', function: 'COMPOSE_COLOR' })+})++test('formulas OpenPencil evaluates are not kept opaque', () => {+ const sum = expression('ADDITION', [+ { dataType: 'FLOAT', value: { floatValue: 2 } },+ { dataType: 'FLOAT', value: { floatValue: 3 } }+ ])+ expect(open(resources(sum)).resolveVariable(VARIABLE, DEFAULT_MODE)).toBe(5)+})++test('a kept expression is written back with fields the codec does not know', () => {+ const data = {+ dataType: 'EXPRESSION',+ value: {+ expressionValue: {+ expressionFunction: 'TERNARY',+ expressionArguments: [+ { value: { colorValue: { r: 1, g: 0, b: 0, a: 1, colorSpace: 'DISPLAY_P3' } } },+ { value: { alias: { assetRef: { key: 'remote', version: 'v1', futureField: true } } } }+ ]+ }+ }+ }+ expect(unsupportedExpressionData(data)).toEqual(data)+ expect(() => unsupportedExpressionData({ dataType: 'FLOAT' })).toThrow(+ 'Invalid unsupported variable expression'+ )+})diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex f1c546b00..a0a711958 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -180,6 +180,13 @@ export interface VariableAnyValue {symbolIdValue?: { guid?: GUID }// fig.kiwi PropRefValue: the component property a parameter entry points at.propRefValue?: { defId?: GUID }+ mapValue?: { values?: { key?: string; guidKey?: GUID; value?: VariableDataEntry }[] }+ colorArrayValue?: { colors?: VariableDataEntry[] }+ fontStyleValue?: {+ asString?: VariableDataEntry+ asFloat?: VariableDataEntry+ asVariations?: VariableDataEntry+ }expressionValue?: {expressionFunction?: stringexpressionArguments?: VariableDataEntry[]diff --git a/packages/scene-graph/src/transfer/variables.ts b/packages/scene-graph/src/transfer/variables.tsindex 7be7d0032..a1e74f509 100644--- a/packages/scene-graph/src/transfer/variables.ts+++ b/packages/scene-graph/src/transfer/variables.ts@@ -52,7 +52,11 @@ export function prepareVariableTransfer(assertUniqueMappings(references.collections, 'collection')assertUniqueMappings(references.modes, 'mode')const value = (input: VariableValue): VariableValue =>- mapVariableValueReferences(input, (id) => mapped(references.variables, id, 'variable alias'))+ mapVariableValueReferences(+ input,+ (id) => mapped(references.variables, id, 'variable alias'),+ (id) => references.modes.get(id) ?? id+ )return {collections: collections.map((collection) => ({...structuredClone(collection),diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex e8a30035a..559dbee16 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -869,11 +869,26 @@ export interface VariableFormula {type: 'FLOAT' | 'BOOLEAN'value: VariableFormulaNode}+/**+ * An imported expression OpenPencil cannot evaluate, kept as the file wrote it so saving writes it+ * back. `references` holds one entry per alias in `value`, in the order the format walks them, and+ * `null` where the alias names a variable this document does not have. `modes` holds the mode id of+ * each mode key in `value`, in the same walk order.+ */+export interface VariableUnsupportedExpression {+ expression: 'UNSUPPORTED'+ /** The function name the file gives, such as `TERNARY`. */+ function: string+ value: Record<string, unknown>+ references: (string | null)[]+ modes: string[]+}export type VariableValue =| VariableLiteral| VariableAlias| VariableColorExpression| VariableFormula+ | VariableUnsupportedExpressionexport type VariableModeMap = Record<string, string>/** Property pickers a variable is offered in, as Figma names them. */diff --git a/packages/scene-graph/src/variables/value.ts b/packages/scene-graph/src/variables/value.tsindex c66228d3d..ecce12bf8 100644--- a/packages/scene-graph/src/variables/value.ts+++ b/packages/scene-graph/src/variables/value.ts@@ -1,6 +1,7 @@+import { compact } from 'es-toolkit/array'import * as v from 'valibot'-import type { VariableLiteral, VariableValue } from '../types'+import type { VariableLiteral, VariableValue, VariableUnsupportedExpression } from '../types'import {evaluateVariableFormula,mapFormulaReferences,@@ -8,8 +9,15 @@ import {} from './formula/evaluate'import { variableColorExpressionSchema } from './schema'+export function isUnsupportedVariableValue(+ value: VariableValue | undefined+): value is VariableUnsupportedExpression {+ return typeof value === 'object' && 'expression' in value && value.expression === 'UNSUPPORTED'+}+/** All references in one definition, including color and opacity operands. */export function variableValueReferences(value: VariableValue): string[] {+ if (isUnsupportedVariableValue(value)) return compact(value.references)if (typeof value !== 'object') return []if ('aliasId' in value) return [value.aliasId]if ('expression' in value && value.expression === 'FORMULA') {@@ -28,8 +36,15 @@ export function variableValueReferences(value: VariableValue): string[] {/** Clone a value while remapping its references for transfer to another document. */export function mapVariableValueReferences(value: VariableValue,- map: (id: string) => string+ map: (id: string) => string,+ mapMode: (id: string) => string = (id) => id): VariableValue {+ if (isUnsupportedVariableValue(value))+ return {+ ...structuredClone(value),+ references: value.references.map((id) => (id === null ? null : map(id))),+ modes: value.modes.map(mapMode)+ }if (typeof value !== 'object') return valueif ('aliasId' in value) return { aliasId: map(value.aliasId) }if ('expression' in value && value.expression === 'FORMULA')@@ -49,6 +64,7 @@ export function resolveVariableValue(value: VariableValue,resolve: (id: string) => VariableLiteral | undefined): VariableLiteral | undefined {+ if (isUnsupportedVariableValue(value)) return undefinedif (typeof value !== 'object') return valueif ('aliasId' in value) return resolve(value.aliasId)if (!('expression' in value)) return valuediff --git a/packages/vue/src/i18n/locales/de/variables/panel.json b/packages/vue/src/i18n/locales/de/variables/panel.jsonindex ece518aa0..32acdb157 100644--- a/packages/vue/src/i18n/locales/de/variables/panel.json+++ b/packages/vue/src/i18n/locales/de/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Importieren","formula": "Formel","useFormula": "Formel verwenden",- "formulaPlaceholder": "Wert oder Formel"+ "formulaPlaceholder": "Wert oder Formel",+ "unsupportedExpression": "OpenPencil kann {name} noch nicht auswerten. Beim Speichern bleibt es unverändert."}diff --git a/packages/vue/src/i18n/locales/es/variables/panel.json b/packages/vue/src/i18n/locales/es/variables/panel.jsonindex 40558c69c..cbe91a45d 100644--- a/packages/vue/src/i18n/locales/es/variables/panel.json+++ b/packages/vue/src/i18n/locales/es/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Importar","formula": "Fórmula","useFormula": "Usar una fórmula",- "formulaPlaceholder": "Valor o fórmula"+ "formulaPlaceholder": "Valor o fórmula",+ "unsupportedExpression": "OpenPencil aún no puede evaluar {name}. Al guardar se conserva tal cual."}diff --git a/packages/vue/src/i18n/locales/fr/variables/panel.json b/packages/vue/src/i18n/locales/fr/variables/panel.jsonindex 6662fc8ce..cdfdb7349 100644--- a/packages/vue/src/i18n/locales/fr/variables/panel.json+++ b/packages/vue/src/i18n/locales/fr/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Importer","formula": "Formule","useFormula": "Utiliser une formule",- "formulaPlaceholder": "Valeur ou formule"+ "formulaPlaceholder": "Valeur ou formule",+ "unsupportedExpression": "OpenPencil ne sait pas encore évaluer {name}. L’enregistrement le conserve tel quel."}diff --git a/packages/vue/src/i18n/locales/it/variables/panel.json b/packages/vue/src/i18n/locales/it/variables/panel.jsonindex dec54048f..8651a1aae 100644--- a/packages/vue/src/i18n/locales/it/variables/panel.json+++ b/packages/vue/src/i18n/locales/it/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Importa","formula": "Formula","useFormula": "Usa una formula",- "formulaPlaceholder": "Valore o formula"+ "formulaPlaceholder": "Valore o formula",+ "unsupportedExpression": "OpenPencil non sa ancora valutare {name}. Il salvataggio lo mantiene invariato."}diff --git a/packages/vue/src/i18n/locales/ja/variables/panel.json b/packages/vue/src/i18n/locales/ja/variables/panel.jsonindex 3c66cf279..84397c655 100644--- a/packages/vue/src/i18n/locales/ja/variables/panel.json+++ b/packages/vue/src/i18n/locales/ja/variables/panel.json@@ -128,5 +128,6 @@"importAction": "読み込む","formula": "数式","useFormula": "数式を使用",- "formulaPlaceholder": "値または数式"+ "formulaPlaceholder": "値または数式",+ "unsupportedExpression": "OpenPencil はまだ {name} を評価できません。保存してもそのまま残ります。"}diff --git a/packages/vue/src/i18n/locales/pl/variables/panel.json b/packages/vue/src/i18n/locales/pl/variables/panel.jsonindex 765bfbd9e..aaaa5b11b 100644--- a/packages/vue/src/i18n/locales/pl/variables/panel.json+++ b/packages/vue/src/i18n/locales/pl/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Importuj","formula": "Formuła","useFormula": "Użyj formuły",- "formulaPlaceholder": "Wartość lub formuła"+ "formulaPlaceholder": "Wartość lub formuła",+ "unsupportedExpression": "OpenPencil nie potrafi jeszcze obliczyć {name}. Zapis zachowuje je bez zmian."}diff --git a/packages/vue/src/i18n/locales/ru/variables/panel.json b/packages/vue/src/i18n/locales/ru/variables/panel.jsonindex 1a2775059..86ef29476 100644--- a/packages/vue/src/i18n/locales/ru/variables/panel.json+++ b/packages/vue/src/i18n/locales/ru/variables/panel.json@@ -128,5 +128,6 @@"importAction": "Импортировать","formula": "Формула","useFormula": "Использовать формулу",- "formulaPlaceholder": "Значение или формула"+ "formulaPlaceholder": "Значение или формула",+ "unsupportedExpression": "OpenPencil пока не умеет вычислять {name}. При сохранении оно остаётся как есть."}diff --git a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json b/packages/vue/src/i18n/locales/zh-cn/variables/panel.jsonindex 0255a4871..a3483fba2 100644--- a/packages/vue/src/i18n/locales/zh-cn/variables/panel.json+++ b/packages/vue/src/i18n/locales/zh-cn/variables/panel.json@@ -128,5 +128,6 @@"importAction": "导入","formula": "公式","useFormula": "使用公式",- "formulaPlaceholder": "值或公式"+ "formulaPlaceholder": "值或公式",+ "unsupportedExpression": "OpenPencil 暂不能计算 {name}。保存时会原样保留。"}diff --git a/packages/vue/src/i18n/messages/variables/panel.ts b/packages/vue/src/i18n/messages/variables/panel.tsindex 198c34308..94427008b 100644--- a/packages/vue/src/i18n/messages/variables/panel.ts+++ b/packages/vue/src/i18n/messages/variables/panel.ts@@ -137,7 +137,8 @@ export const variablesMessageDefaults = {importAction: 'Import',formula: 'Formula',useFormula: 'Use a formula',- formulaPlaceholder: 'Value or formula'+ formulaPlaceholder: 'Value or formula',+ unsupportedExpression: params('OpenPencil can’t evaluate {name} yet. Saving keeps it as it is.')} as constexport const variablesMessages = i18n('variables', variablesMessageDefaults)diff --git a/src/app/document/io/fig.ts b/src/app/document/io/fig.tsindex 88ff5c5a0..c4fe73b55 100644--- a/src/app/document/io/fig.ts+++ b/src/app/document/io/fig.ts@@ -1,8 +1,25 @@import { readFigFile } from '@open-pencil/core/io/formats/fig'+import { isUnsupportedVariableValue, type SceneGraph } from '@open-pencil/scene-graph'-export function readFigDocument(file: File, signal?: AbortSignal) {- return readFigFile(file, {+import { notificationMessages } from '@/app/i18n/notifications'+import { toast } from '@/app/shell/ui'++export async function readFigDocument(file: File, signal?: AbortSignal) {+ const graph = await readFigFile(file, {populate: 'first-page',signal})+ warnUnsupportedVariableExpressions(graph)+ return graph+}++/** Names the variables whose expressions OpenPencil cannot evaluate, which draw as saved. */+function warnUnsupportedVariableExpressions(graph: SceneGraph) {+ const names = [...graph.variables.values()]+ .filter((variable) => Object.values(variable.valuesByMode).some(isUnsupportedVariableValue))+ .map((variable) => variable.name)+ if (names.length === 0) return+ toast.warning(+ notificationMessages.get().unsupportedVariableExpressions({ names: names.join(', ') })+ )}diff --git a/src/app/editor/tokens/model.ts b/src/app/editor/tokens/model.tsindex 4654bbfc5..36601102b 100644--- a/src/app/editor/tokens/model.ts+++ b/src/app/editor/tokens/model.ts@@ -36,6 +36,8 @@ export interface TokenModeValue {result?: string/** A CSS expression written instead of the stored number, such as `clamp(…)`. */expression?: string+ /** A function from the file OpenPencil cannot evaluate, such as `TERNARY`. */+ unsupported?: string}export interface TokenRow {@@ -94,6 +96,7 @@ function modeValue(): TokenModeValue {const expression = variable.expressions?.[modeId]?.cssif (typeof value === 'object' && 'expression' in value) {+ if (value.expression === 'UNSUPPORTED') return { modeId, css: '', unsupported: value.function }if (value.expression === 'COMPOSE_COLOR')return colorExpressionMode(graph, variable, modeId, value)const resolved = graph.resolveVariable(variable.id, modeId)diff --git a/src/app/i18n/notifications/index.ts b/src/app/i18n/notifications/index.tsindex dd5ab7992..e0f2cd24f 100644--- a/src/app/i18n/notifications/index.ts+++ b/src/app/i18n/notifications/index.ts@@ -14,6 +14,9 @@ export const notificationMessageDefaults = {tokensLeftOut: params('Left out of the stylesheet: {names}.'),designTokensLeftOut: params('Left out of the design tokens: {names}.'),designTokensImported: params('Imported {count} design tokens.'),+ unsupportedVariableExpressions: params(+ 'OpenPencil can’t evaluate these variables yet, so layers keep the values saved in the file: {names}.'+ ),nodeID: 'node ID',nodeIDs: 'node IDs',xPath: 'XPath',diff --git a/src/app/i18n/notifications/locales/de.json b/src/app/i18n/notifications/locales/de.jsonindex 00eac411d..e57610415 100644--- a/src/app/i18n/notifications/locales/de.json+++ b/src/app/i18n/notifications/locales/de.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "Die an OpenPencil übergebenen Dateien konnten nicht geöffnet werden: {error}","tokensLeftOut": "Nicht im Stylesheet enthalten: {names}.","designTokensLeftOut": "Nicht in den Design-Tokens enthalten: {names}.",- "designTokensImported": "{count} Design-Tokens importiert."+ "designTokensImported": "{count} Design-Tokens importiert.",+ "unsupportedVariableExpressions": "OpenPencil kann diese Variablen noch nicht auswerten, daher behalten Ebenen die in der Datei gespeicherten Werte: {names}."}diff --git a/src/app/i18n/notifications/locales/es.json b/src/app/i18n/notifications/locales/es.jsonindex 2aa360ae6..cf45f5d39 100644--- a/src/app/i18n/notifications/locales/es.json+++ b/src/app/i18n/notifications/locales/es.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "No se pudieron abrir los archivos entregados a OpenPencil: {error}","tokensLeftOut": "No incluido en la hoja de estilos: {names}.","designTokensLeftOut": "No incluidos en los design tokens: {names}.",- "designTokensImported": "Se importaron {count} design tokens."+ "designTokensImported": "Se importaron {count} design tokens.",+ "unsupportedVariableExpressions": "OpenPencil aún no puede evaluar estas variables, así que las capas conservan los valores guardados en el archivo: {names}."}diff --git a/src/app/i18n/notifications/locales/fr.json b/src/app/i18n/notifications/locales/fr.jsonindex 304e9786a..de6fa2613 100644--- a/src/app/i18n/notifications/locales/fr.json+++ b/src/app/i18n/notifications/locales/fr.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "Impossible d’ouvrir les fichiers transmis à OpenPencil : {error}","tokensLeftOut": "Non inclus dans la feuille de style : {names}.","designTokensLeftOut": "Exclus des design tokens : {names}.",- "designTokensImported": "{count} design tokens importés."+ "designTokensImported": "{count} design tokens importés.",+ "unsupportedVariableExpressions": "OpenPencil ne sait pas encore évaluer ces variables ; les calques gardent les valeurs enregistrées dans le fichier : {names}."}diff --git a/src/app/i18n/notifications/locales/it.json b/src/app/i18n/notifications/locales/it.jsonindex 59b4246f1..406fb2f03 100644--- a/src/app/i18n/notifications/locales/it.json+++ b/src/app/i18n/notifications/locales/it.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "Impossibile aprire i file passati a OpenPencil: {error}","tokensLeftOut": "Esclusi dal foglio di stile: {names}.","designTokensLeftOut": "Esclusi dai design token: {names}.",- "designTokensImported": "Importati {count} design token."+ "designTokensImported": "Importati {count} design token.",+ "unsupportedVariableExpressions": "OpenPencil non sa ancora valutare queste variabili, quindi i livelli mantengono i valori salvati nel file: {names}."}diff --git a/src/app/i18n/notifications/locales/ja.json b/src/app/i18n/notifications/locales/ja.jsonindex 30705b0ee..9418bd673 100644--- a/src/app/i18n/notifications/locales/ja.json+++ b/src/app/i18n/notifications/locales/ja.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "OpenPencil に渡されたファイルを開けませんでした: {error}","tokensLeftOut": "スタイルシートに含まれていません: {names}","designTokensLeftOut": "デザイントークンに含まれていません: {names}",- "designTokensImported": "{count} 個のデザイントークンを読み込みました。"+ "designTokensImported": "{count} 個のデザイントークンを読み込みました。",+ "unsupportedVariableExpressions": "OpenPencil はまだこれらの変数を評価できないため、レイヤーはファイルに保存された値を保ちます: {names}"}diff --git a/src/app/i18n/notifications/locales/pl.json b/src/app/i18n/notifications/locales/pl.jsonindex e29ae32d4..de4786f9a 100644--- a/src/app/i18n/notifications/locales/pl.json+++ b/src/app/i18n/notifications/locales/pl.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "Nie udało się otworzyć plików przekazanych do OpenPencil: {error}","tokensLeftOut": "Pominięte w arkuszu stylów: {names}.","designTokensLeftOut": "Pominięte w tokenach projektowych: {names}.",- "designTokensImported": "Zaimportowano tokeny projektowe: {count}."+ "designTokensImported": "Zaimportowano tokeny projektowe: {count}.",+ "unsupportedVariableExpressions": "OpenPencil nie potrafi jeszcze obliczyć tych zmiennych, więc warstwy zachowują wartości zapisane w pliku: {names}."}diff --git a/src/app/i18n/notifications/locales/ru.json b/src/app/i18n/notifications/locales/ru.jsonindex 45a05a06f..f2074e18e 100644--- a/src/app/i18n/notifications/locales/ru.json+++ b/src/app/i18n/notifications/locales/ru.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "Не удалось открыть файлы, переданные OpenPencil: {error}","tokensLeftOut": "Не вошли в таблицу стилей: {names}.","designTokensLeftOut": "Не вошли в дизайн-токены: {names}.",- "designTokensImported": "Импортировано дизайн-токенов: {count}."+ "designTokensImported": "Импортировано дизайн-токенов: {count}.",+ "unsupportedVariableExpressions": "OpenPencil пока не умеет вычислять эти переменные, поэтому слои сохраняют значения из файла: {names}."}diff --git a/src/app/i18n/notifications/locales/zh-cn.json b/src/app/i18n/notifications/locales/zh-cn.jsonindex 4fffd1f4a..3584cd5c4 100644--- a/src/app/i18n/notifications/locales/zh-cn.json+++ b/src/app/i18n/notifications/locales/zh-cn.json@@ -30,5 +30,6 @@"openQueuedFilesFailed": "无法打开传递给 OpenPencil 的文件:{error}","tokensLeftOut": "未写入样式表:{names}","designTokensLeftOut": "未写入设计令牌:{names}",- "designTokensImported": "已导入 {count} 个设计令牌。"+ "designTokensImported": "已导入 {count} 个设计令牌。",+ "unsupportedVariableExpressions": "OpenPencil 暂不能计算这些变量,图层保留文件中保存的值:{names}"}diff --git a/src/components/variables/TokenInspector.vue b/src/components/variables/TokenInspector.vueindex 80e7e9672..dd0bb8687 100644--- a/src/components/variables/TokenInspector.vue+++ b/src/components/variables/TokenInspector.vue@@ -275,6 +275,11 @@ function alias(modeId: string) {return row.values.find((value) => value.modeId === modeId)?.alias}+/** A function from the file OpenPencil cannot evaluate; that mode's value is read-only. */+function unsupported(modeId: string) {+ return row.values.find((value) => value.modeId === modeId)?.unsupported+}+/** The color an aliased value resolves to, shown beside the variable as the panel does. */function aliasColor(modeId: string): Color | undefined {return row.values.find((value) => value.modeId === modeId)?.color@@ -361,9 +366,19 @@ function cssNameDone(event: KeyboardEvent) {{{ 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>+ <span+ v-if="!singleMode && (!editsValues || unsupported(mode.modeId))"+ :class="ui.label()"+ >{{ mode.name }}</span+ >+ <Tip+ v-if="unsupported(mode.modeId)"+ :label="variables.unsupportedExpression({ name: unsupported(mode.modeId) ?? '' })"+ >+ <span :class="ui.hint()">{{ unsupported(mode.modeId) }}(…)</span>+ </Tip><TokenValueEditor- v-if="editsValues && formula"+ v-else-if="editsValues && formula":variable="variable":mode-id="mode.modeId":label="singleMode ? variables.value : mode.name"diff --git a/src/components/variables/TokenTable.vue b/src/components/variables/TokenTable.vueindex 4db0ce4a8..aaa11535b 100644--- a/src/components/variables/TokenTable.vue+++ b/src/components/variables/TokenTable.vue@@ -297,6 +297,12 @@ function dropEdge(id: string) {</Tip><span class="truncate">{{ value.css || '—' }}</span></template>+ <Tip+ v-else-if="value.unsupported"+ :label="variables.unsupportedExpression({ name: value.unsupported })"+ >+ <span :class="ui.aliasResult()">{{ value.unsupported }}(…)</span>+ </Tip><template v-else-if="value.alias"><BindingPill :class="ui.aliasPill()" :label="value.alias" /><span v-if="value.result" :class="ui.aliasResult()">{{ value.result }}</span>diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex 2e92732c5..56deb48f3 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -425,6 +425,7 @@ ja:variables.conditionHintja:variables.conditionCustomja:variables.libraryCollectionHintja:variables.addedToLibraryCollection+ja:variables.unsupportedExpressionzh-cn:variables.cssNamezh-cn:variables.expressionzh-cn:variables.addExpression@@ -436,6 +437,7 @@ zh-cn:variables.conditionHintzh-cn:variables.conditionCustomzh-cn:variables.libraryCollectionHintzh-cn:variables.addedToLibraryCollection+zh-cn:variables.unsupportedExpressionzh-cn:panels.shaderPresetzh-cn:panels.invalidShaderPresetzh-cn:panels.shaderNeedsWebGPU