AI-native design editor. Open-source Figma alternative.
feat(core)!: keep figma to Figma's Plugin API (#1354)
Danila Poyarkov620c4f88f67f
diff --git a/changes/1344/breaking.md b/changes/1344/breaking.mdindex 8df7ba9b4..7c5c9e9a6 100644--- a/changes/1344/breaking.md+++ b/changes/1344/breaking.md@@ -1 +1 @@-- Scripts bind variables with `openpencil.bindVariable(node, field, variable)` and `openpencil.unbindVariable(node, field)`, taking a variable from `figma.getLocalVariables()`; `figma.bindVariable` and `figma.unbindVariable` are removed, so `figma` keeps to Figma's Plugin API.+- Scripts bind variables with `openpencil.bindVariable(node, field, variable)` and `openpencil.unbindVariable(node, field)`, taking a variable from `figma.variables`; `figma.bindVariable` and `figma.unbindVariable` are removed, so `figma` keeps to Figma's Plugin API.diff --git a/changes/1354/breaking.md b/changes/1354/breaking.mdnew file mode 100644index 000000000..37aac2701--- /dev/null+++ b/changes/1354/breaking.md@@ -0,0 +1,2 @@+- Scripts use variables as in Figma's Plugin API: `figma.variables` creates and looks up variables and collections, variables set values with `setValueForMode`, and layers bind with `node.setBoundVariable` and paint `boundVariables`; the top-level `figma.getVariableById`, `createVariable`, `setVariableValue`, `deleteVariable` and collection methods are removed.+- Scripts reach OpenPencil-only features through `openpencil`: `exposeInstanceSwap`, `getFontStatus`, `getFillOkHCL`/`setFillOkHCL` and the stroke pair, and `get`/`setLayoutDirection` and `get`/`setTextDirection` take a node; `figma.booleanOperation` and `figma.flattenNode` are removed in favour of Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `flatten`.diff --git a/changes/1354/fixed.md b/changes/1354/fixed.mdnew file mode 100644index 000000000..1b72ee50a--- /dev/null+++ b/changes/1354/fixed.md@@ -0,0 +1 @@+- Scripts edit variant properties as Figma's Plugin API does: renaming or adding a variant property on a component set renames every variant and instances follow, renaming a variant updates the set's values, deleting a variant property fails as in Figma, and `variantProperties` reads a variant's or an instance's values.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex f1cf77958..0a2e341c8 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -54,7 +54,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do`OpenPencilAPI` (`packages/core/src/openpencil-api/`) is what OpenPencil adds to the Plugin API, exposed to scripts as the `openpencil` global next to `figma`.-- Keep `figma` Figma-shaped and put OpenPencil-only features on `openpencil`, in the same style: methods and node-like handles with getters and setters, not parallel helper functions. Never add non-Figma members to `FigmaAPI` (`compatibility.ts`).+- Put OpenPencil-only features on `openpencil`, in the same style as `figma`: methods and node-like handles with getters and setters, not parallel helper functions. `figma` stays Figma's (Figma API, Shape follows Figma).- Script runners get both globals only through `compileScript` (`packages/core/src/tools/analyze/eval/wrap.ts`); the `eval` tool, `openpencil eval`, and app automation must not build their own `AsyncFunction`.- Members take names, not internal ids, and write through the same scene-graph functions the editor's actions use, such as `behaviourFromSpec`; errors name what exists. Tools for the same feature wrap the `openpencil` API rather than reimplementing it (`packages/core/src/tools/create/behaviours.ts`).- A new member updates `packages/docs/programmable/cli/scripting.md` and the agent skill in the same change; tests drive it as scripts do, through `compileScript` (`packages/core/tests/openpencil-api/`).@@ -108,7 +108,7 @@ Pixel-affecting features need committed visual coverage, not only mock or geomet`FigmaAPI` mimics Figma's Plugin API over the SceneGraph. `openpencil eval`, the AI and MCP tools, and the app bind to it. Tests live under `tests/engine/figma/api/` and mirror the API surface.-- **Shape follows Figma.** Match `@figma/plugin-typings` at the version pinned in the root `package.json`. `packages/core/src/figma-api/compatibility.ts` type-checks the supported surface against `PluginAPI`; add every new member to `SupportedPluginAPI` there. Model unsupported members explicitly rather than approximating them.+- **Shape follows Figma.** Match `@figma/plugin-typings` at the version pinned in the root `package.json`, and add every new member to `SupportedPluginAPI`. `compatibility.ts` fails the typecheck on a member Figma's types lack or type differently, and `packages/core/tests/figma-api/surface.test.ts` on one a script can reach; the lists in `packages/core/src/figma-api/surface.ts` only shrink.- **Behavior follows Figma.** Read the Plugin API documentation for the member, and for anything observable (geometry, ordering, defaults, errors) run the same script in live Figma and record the observed result in the test. `figma-use` and `tests/figma/` are the live oracle; `tests/fixtures/figma-oracles/` holds recorded values.- **User actions are shared code.** When an editor command does the same thing (group, ungroup, boolean, flatten, instance creation, component sync), call the implementation under `packages/core/src/editor/` or its shared helper. Do not reimplement geometry, placement, or propagation here; new geometry helpers belong in Scene Graph.- Geometry getters lay out what the graph's edits touched since the last read, as Figma does, through `flushPendingLayout` in `packages/core/src/figma-api/pending-layout.ts`; a new geometry getter calls it first (`packages/core/tests/figma-api/pending-layout.test.ts`).diff --git a/packages/core/src/editor/components/variants/definitions.ts b/packages/core/src/editor/components/variants/definitions.tsindex 2895f9f28..003429cfa 100644--- a/packages/core/src/editor/components/variants/definitions.ts+++ b/packages/core/src/editor/components/variants/definitions.ts@@ -1,6 +1,10 @@import { omit } from 'es-toolkit/object'-import type { ComponentPropertyDefinition, ComponentPropertyType } from '@open-pencil/scene-graph'+import type {+ ComponentPropertyDefinition,+ ComponentPropertyType,+ SceneGraph+} from '@open-pencil/scene-graph'import { createComponentPropertyId } from '@open-pencil/scene-graph'import { assertNodeEditable } from '#core/editor/capabilities'@@ -53,7 +57,7 @@ export function reorderPropertyDefinitions(})})for (const variant of getComponentSetVariants(ctx.graph, componentSetId))- updateVariantName(ctx, componentSetId, variant)+ updateVariantName(ctx.graph, componentSetId, variant)const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, 'Reorder properties', before, after)return true@@ -98,6 +102,42 @@ export function reorderVariantValues(return true}+/**+ * Appends a property to a component set; a variant axis gives every variant its value and renames+ * them to match. The caller checks the name. Shared by the panel and the Plugin API.+ */+export function appendPropertyDefinition(+ graph: SceneGraph,+ componentSetId: string,+ name: string,+ type: ComponentPropertyType,+ defaultValue: string+): string {+ const node = getComponentSet(graph, componentSetId)+ if (!node) throw new Error(`No component set ${componentSetId}`)+ const id = createComponentPropertyId()+ const definition: ComponentPropertyDefinition = {+ id,+ name,+ type,+ defaultValue,+ variantOptions: type === 'VARIANT' ? [defaultValue] : undefined+ }+ graph.updateNode(componentSetId, {+ componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]+ })+ if (type === 'VARIANT') {+ for (const variant of getComponentSetVariants(graph, componentSetId)) {+ setVariantValues(graph, componentSetId, variant.id, {+ ...variant.componentPropertyValues,+ [name]: defaultValue+ })+ }+ refreshVariantOptions(graph, componentSetId)+ }+ return id+}+export function addPropertyDefinition(ctx: EditorContext,componentSetId: string,@@ -115,26 +155,7 @@ export function addPropertyDefinition(const before = captureVariantSnapshot(ctx, componentSetId)if (!before) return undefined- const id = createComponentPropertyId()- const definition: ComponentPropertyDefinition = {- id,- name: normalizedName,- type,- defaultValue,- variantOptions: type === 'VARIANT' ? [defaultValue] : undefined- }- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]- })- if (type === 'VARIANT') {- for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {- setVariantValues(ctx, componentSetId, variant.id, {- ...variant.componentPropertyValues,- [normalizedName]: defaultValue- })- }- refreshVariantOptions(ctx, componentSetId)- }+ const id = appendPropertyDefinition(ctx.graph, componentSetId, normalizedName, type, defaultValue)const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, 'Add property', before, after)return id@@ -159,19 +180,47 @@ export function removePropertyDefinition(if (definition.type === 'VARIANT') {for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {setVariantValues(- ctx,+ ctx.graph,componentSetId,variant.id,omit(variant.componentPropertyValues, [definition.name]))}- refreshVariantOptions(ctx, componentSetId)+ refreshVariantOptions(ctx.graph, componentSetId)}const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, 'Remove property', before, after)return true}+/**+ * Renames a component set's property; a variant axis is renamed in every variant's name, which+ * instances follow. The caller checks the name. Shared by the panel and the Plugin API.+ */+export function renameProperty(+ graph: SceneGraph,+ componentSetId: string,+ propertyId: string,+ name: string+): void {+ const node = getComponentSet(graph, componentSetId)+ const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ if (!node || !definition) throw new Error(`No property ${propertyId}`)+ graph.updateNode(componentSetId, {+ componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>+ item.id === propertyId ? { ...item, name } : item+ )+ })+ if (definition.type !== 'VARIANT') return+ for (const variant of getComponentSetVariants(graph, componentSetId)) {+ const value = variant.componentPropertyValues[definition.name] ?? ''+ setVariantValues(graph, componentSetId, variant.id, {+ ...omit(variant.componentPropertyValues, [definition.name]),+ [name]: value+ })+ }+}+export function renamePropertyDefinition(ctx: EditorContext,componentSetId: string,@@ -193,20 +242,7 @@ export function renamePropertyDefinition(}if (definition.name === normalizedName) return true- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>- item.id === propertyId ? { ...item, name: normalizedName } : item- )- })- if (definition.type === 'VARIANT') {- for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {- const value = variant.componentPropertyValues[definition.name] ?? ''- setVariantValues(ctx, componentSetId, variant.id, {- ...omit(variant.componentPropertyValues, [definition.name]),- [normalizedName]: value- })- }- }+ renameProperty(ctx.graph, componentSetId, propertyId, normalizedName)const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, 'Rename property', before, after)return true@@ -252,12 +288,12 @@ export function renameVariantValue(})for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {if (variant.componentPropertyValues[definition.name] !== previousValue) continue- setVariantValues(ctx, componentSetId, variant.id, {+ setVariantValues(ctx.graph, componentSetId, variant.id, {...variant.componentPropertyValues,[definition.name]: normalizedValue})}- refreshVariantOptions(ctx, componentSetId)+ refreshVariantOptions(ctx.graph, componentSetId)const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, 'Rename variant value', before, after)return true@@ -292,11 +328,11 @@ export function setVariantPropertyValue(return { kind: 'conflict', componentIds: [variantId, conflicting.id] }}- setVariantValues(ctx, componentSetId, variantId, {+ setVariantValues(ctx.graph, componentSetId, variantId, {...variant.componentPropertyValues,[definition.name]: normalizedValue})- refreshVariantOptions(ctx, componentSetId)+ refreshVariantOptions(ctx.graph, componentSetId)const after = captureVariantSnapshot(ctx, componentSetId)if (after) recordSnapshotChange(ctx, componentSetId, `Change ${definition.name}`, before, after)return { kind: 'changed' }diff --git a/packages/core/src/editor/components/variants/history.ts b/packages/core/src/editor/components/variants/history.tsindex db1e8dbb2..cd3a68ae8 100644--- a/packages/core/src/editor/components/variants/history.ts+++ b/packages/core/src/editor/components/variants/history.ts@@ -1,4 +1,4 @@-import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { buildVariantName } from '@open-pencil/scene-graph/variant-name'import { assertNodeEditable } from '#core/editor/capabilities'@@ -8,6 +8,7 @@ import {collectVariantOptions,getComponentSet,getComponentSetVariants,+ getDefaultVariantForComponentSet,getVariantDefinitions} from './model'@@ -80,52 +81,59 @@ export function recordSnapshotChange(}export function updateVariantName(- ctx: EditorContext,+ graph: SceneGraph,componentSetId: string,variant: SceneNode): void {const values = Object.fromEntries(- getVariantDefinitions(ctx.graph, componentSetId).map((definition) => [+ getVariantDefinitions(graph, componentSetId).map((definition) => [definition.name,variant.componentPropertyValues[definition.name] ?? '']))- if (Object.keys(values).length)- ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })+ if (Object.keys(values).length) graph.updateNode(variant.id, { name: buildVariantName(values) })}-export function refreshVariantOptions(ctx: EditorContext, componentSetId: string): void {- const componentSet = getComponentSet(ctx.graph, componentSetId)+/**+ * Adds the values variants use to each axis's list. The panel keeps values no variant uses yet;+ * `dropUnused` drops them and falls back to the default variant's value, as Figma does when a+ * script renames a variant.+ */+export function refreshVariantOptions(+ graph: SceneGraph,+ componentSetId: string,+ { dropUnused = false }: { dropUnused?: boolean } = {}+): void {+ const componentSet = getComponentSet(graph, componentSetId)if (!componentSet) return- const collected = collectVariantOptions(ctx.graph, componentSetId)+ const collected = collectVariantOptions(graph, componentSetId)+ const fallback = getDefaultVariantForComponentSet(graph, componentSetId)const definitions = componentSet.componentPropertyDefinitions.map((definition) => {if (definition.type !== 'VARIANT') return definitionconst present = collected.get(definition.name) ?? new Set<string>()- const options = [- ...(definition.variantOptions ?? []),- ...[...present].filter((value) => !definition.variantOptions?.includes(value))- ]- return {- ...definition,- defaultValue: options.includes(definition.defaultValue)- ? definition.defaultValue- : (options[0] ?? ''),- variantOptions: options- }+ const kept = (definition.variantOptions ?? []).filter(+ (value) => !dropUnused || present.has(value)+ )+ const options = [...kept, ...[...present].filter((value) => !kept.includes(value))]+ const replacement = dropUnused ? fallback?.componentPropertyValues[definition.name] : undefined+ const defaultValue = options.includes(definition.defaultValue)+ ? definition.defaultValue+ : (replacement ?? options.at(0) ?? '')+ return { ...definition, defaultValue, variantOptions: options }})- ctx.graph.updateNode(componentSetId, {+ graph.updateNode(componentSetId, {componentPropertyDefinitions: definitions})}/** Set a variant's property values and rename it to match. */export function setVariantValues(- ctx: EditorContext,+ graph: SceneGraph,componentSetId: string,variantId: string,componentPropertyValues: Record<string, string>): void {- ctx.graph.updateNode(variantId, { componentPropertyValues })- const updated = ctx.graph.getNode(variantId)- if (updated) updateVariantName(ctx, componentSetId, updated)+ graph.updateNode(variantId, { componentPropertyValues })+ const updated = graph.getNode(variantId)+ if (updated) updateVariantName(graph, componentSetId, updated)}diff --git a/packages/core/src/editor/components/variants/options.ts b/packages/core/src/editor/components/variants/options.tsindex 18bd3b8c3..36327c84e 100644--- a/packages/core/src/editor/components/variants/options.ts+++ b/packages/core/src/editor/components/variants/options.ts@@ -93,7 +93,7 @@ export function removeVariantValue(})if (replacement)for (const node of affected)- setVariantValues(ctx, setId, node.id, {+ setVariantValues(ctx.graph, setId, node.id, {...node.componentPropertyValues,[definition.name]: replacement})diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsindex 0d670d579..9dec265cd 100644--- a/packages/core/src/figma-api/accessors/basic.ts+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -43,6 +43,7 @@ import {withOrigin} from '#core/figma-api/transform'import type { FigmaTransform } from '#core/figma-api/types'+import { syncVariantName } from '#core/figma-api/variants'import { figmaRotation } from '#core/geometry/figma'const TRANSFORM_FIELDS: ReadonlySet<string> = new Set(NODE_TRANSFORM_FIELDS)@@ -116,6 +117,8 @@ export function installBasicNodeProxyAccessors(},set(this: ProxyThis, value: string) {updateNode(this, internals, { name: value })+ // A variant's name holds its values, which the set's value lists follow.+ syncVariantName(graph(this, internals), raw(this, internals))}},removed: {diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.tsindex 6ba555e39..34aa82711 100644--- a/packages/core/src/figma-api/accessors/layout.ts+++ b/packages/core/src/figma-api/accessors/layout.ts@@ -80,15 +80,6 @@ export function installLayoutNodeProxyAccessors(updateNode(this, internals, { layoutGrids: grids })}},- layoutDirection: {- get(this: ProxyThis): string {- const node = raw(this, internals)- return Object.hasOwn(node, 'layoutDirection') ? node.layoutDirection : 'AUTO'- },- set(this: ProxyThis, value: string) {- updateNode(this, internals, { layoutDirection: value as SceneNode['layoutDirection'] })- }- },primaryAxisAlignItems: mappedAccessor(internals, 'primaryAxisAlign'),counterAxisAlignItems: mappedAccessor(internals, 'counterAxisAlign'),itemSpacing: simpleAccessor(internals, 'itemSpacing'),diff --git a/packages/core/src/figma-api/accessors/text/index.ts b/packages/core/src/figma-api/accessors/text/index.tsindex 592516ad5..61ce03ab9 100644--- a/packages/core/src/figma-api/accessors/text/index.ts+++ b/packages/core/src/figma-api/accessors/text/index.ts@@ -118,7 +118,6 @@ export function installTextNodeProxyAccessors(})),textAlignHorizontal: field(internals, 'textAlignHorizontal'),textAlignVertical: field(internals, 'textAlignVertical'),- textDirection: field(internals, 'textDirection'),textAutoResize: field(internals, 'textAutoResize'),// Figma's plugin API reads and writes these as { unit, value }; a bare object stored on the// node instead of pixels would leave the text unmeasurable.diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.tsindex fb0a6041a..78700ff31 100644--- a/packages/core/src/figma-api/accessors/text/ranges.ts+++ b/packages/core/src/figma-api/accessors/text/ranges.ts@@ -9,8 +9,7 @@ import type {TextBindableField,TextCase,TextDecoration,- TextDecorationStyle,- Variable+ TextDecorationStyle} from '@open-pencil/scene-graph'import {@@ -39,10 +38,10 @@ import {rangeHasUnderline,type FigmaDecorationColor,type FigmaTextLength,- type FigmaVariableAlias,type StyledTextSegment,type TextSegmentField} from '#core/figma-api/text/style'+import type { FigmaVariableAlias } from '#core/figma-api/variables/values'import { styleRunsWithPatch, type TextStylePatch } from '#core/text/character-style'import { hyperlinkTarget } from './hyperlink'@@ -404,7 +403,7 @@ export interface TextRangeMethods {start: number,end: number,field: TextBindableField,- variable: Variable | null+ variable: { readonly id: string } | null) => voidgetRangeListOptions: RangeGetter<TextListOptions>setRangeListOptions: RangeSetterMethod<TextListOptions>diff --git a/packages/core/src/figma-api/accessors/variables.ts b/packages/core/src/figma-api/accessors/variables.tsindex d05c5225b..b56fce165 100644--- a/packages/core/src/figma-api/accessors/variables.ts+++ b/packages/core/src/figma-api/accessors/variables.ts@@ -1,11 +1,61 @@-import type { SceneGraph } from '@open-pencil/scene-graph'+import { omit } from 'es-toolkit/object'-import { raw, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'+import type { SceneGraph, Variable } from '@open-pencil/scene-graph'-function graph(target: ProxyThis, internals: NodeProxyInternals): SceneGraph {- return target[internals.graph] as SceneGraph+import {+ assertProxyEditable,+ graph,+ raw,+ updateNode,+ type NodeProxyInternals,+ type ProxyThis+} from '#core/figma-api/accessor-utils'+import {+ type FigmaBindableField,+ assertBindableField,+ bindingVariable,+ figmaBoundVariables,+ hasBindableField,+ isTextBindableField,+ setEmptyTextBinding,+ setLayerBinding+} from '#core/figma-api/variables/bindings'+import type { FigmaVariableAlias } from '#core/figma-api/variables/values'+import { reconcileVariableLayouts } from '#core/layout/variables'++type CollectionRef = { readonly id: string } | string++/** The variable members every node proxy has, as Figma's `SceneNodeMixin` names them. */+export interface VariableNodeMembers {+ readonly explicitVariableModes: Readonly<Record<string, string>>+ readonly resolvedVariableModes: Readonly<Record<string, string>>+ setExplicitVariableModeForCollection(collection: CollectionRef, modeId: string): void+ clearExplicitVariableModeForCollection(collection: CollectionRef): void+ readonly boundVariables: Readonly<+ Record<string, FigmaVariableAlias | readonly FigmaVariableAlias[]>+ >+ setBoundVariable(+ field: FigmaBindableField,+ variable: { readonly id: string } | string | null+ ): void+}++function collectionId(collection: CollectionRef): string {+ return typeof collection === 'string' ? collection : collection.id}+function setVariableModes(+ target: ProxyThis,+ internals: NodeProxyInternals,+ variableModes: Record<string, string>+): void {+ const node = raw(target, internals)+ updateNode(target, internals, { variableModes })+ reconcileVariableLayouts(graph(target, internals), { subtrees: [node.id] })+}++type RangeBinder = (start: number, end: number, field: string, variable: Variable | null) => void+export function installVariableModeNodeProxyAccessors(prototype: object,internals: NodeProxyInternals@@ -18,7 +68,7 @@ export function installVariableModeNodeProxyAccessors(},resolvedVariableModes: {get(this: ProxyThis): Readonly<Record<string, string>> {- const sceneGraph = graph(this, internals)+ const sceneGraph: SceneGraph = graph(this, internals)const node = raw(this, internals)const modes: Record<string, string> = {}for (const collectionId of sceneGraph.variableCollections.keys()) {@@ -27,6 +77,59 @@ export function installVariableModeNodeProxyAccessors(}return Object.freeze(modes)}+ },+ setExplicitVariableModeForCollection: {+ value(this: ProxyThis, collection: CollectionRef, modeId: string): void {+ const id = collectionId(collection)+ const found = graph(this, internals).variableCollections.get(id)+ // Figma's message names the two ids the other way round.+ if (!found?.modes.some((mode) => mode.modeId === modeId)) {+ throw new Error(+ `in setExplicitVariableModeForCollection: Could not find modeId ${id} in variable ` ++ `set with variableCollectionId: '${modeId}'`+ )+ }+ setVariableModes(this, internals, { ...raw(this, internals).variableModes, [id]: modeId })+ }+ },+ clearExplicitVariableModeForCollection: {+ value(this: ProxyThis, collection: CollectionRef): void {+ const modes = raw(this, internals).variableModes+ const id = collectionId(collection)+ if (id in modes) setVariableModes(this, internals, omit(modes, [id]))+ }+ },+ boundVariables: {+ get(this: ProxyThis) {+ return Object.freeze(figmaBoundVariables(raw(this, internals)))+ }+ },+ setBoundVariable: {+ /**+ * Binds a field to a variable, by object or id, or unbinds it for `null`, with Figma's field+ * names and type rules; a field the layer lacks is ignored.+ */+ value(+ this: ProxyThis & { setRangeBoundVariable: RangeBinder },+ field: string,+ variable: { readonly id: string } | string | null+ ): void {+ const name = assertBindableField(field)+ const sceneGraph = graph(this, internals)+ const bound =+ variable === null ? null : bindingVariable(sceneGraph, 'setBoundVariable', name, variable)+ const node = raw(this, internals)+ if (!hasBindableField(node, name)) return+ assertProxyEditable(this, internals)+ if (isTextBindableField(name)) {+ // A text style field binds every character, as setting it on the whole text does;+ // text with none yet keeps it on the layer, which its characters then take.+ if (node.text === '') setEmptyTextBinding(sceneGraph, node, name, bound)+ else this.setRangeBoundVariable(0, node.text.length, name, bound)+ return+ }+ setLayerBinding(sceneGraph, node, name, bound)+ }}})}diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.tsindex 58d4ad2ea..8170d05dd 100644--- a/packages/core/src/figma-api/accessors/visual.ts+++ b/packages/core/src/figma-api/accessors/visual.ts@@ -1,5 +1,6 @@import {newStrokeGeometry,+ resolvedPaintBindings,type Color,type Fill,type GradientStop,@@ -10,6 +11,7 @@ import { normalizeColor } from '@open-pencil/scene-graph/color'import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'import {+ graph,raw,strokeOwner,updateNode,@@ -18,6 +20,12 @@ import {} from '#core/figma-api/accessor-utils'import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'import { getTextStyle } from '#core/figma-api/text/style'+import {+ paintBindings,+ setPaintBindings,+ withPaintBinding+} from '#core/figma-api/variables/bindings'+import type { FigmaVariableAlias } from '#core/figma-api/variables/values'import { textStyleChanges } from '#core/text/character-style'function styleReference(@@ -54,14 +62,18 @@ function paintDefaults(paint: Partial<Pick<Fill, 'opacity' | 'visible'>>) {/** A colour as Figma's plugin API takes it, RGB with an optional alpha. */type FigmaColor = Omit<Color, 'a'> & Partial<Pick<Color, 'a'>>-/** A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility. */+/**+ * A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility, and the+ * variable its colour is bound to.+ */export type FigmaPaint = Omit<Fill, 'color' | 'opacity' | 'visible' | 'gradientStops'> &Partial<Pick<Fill, 'opacity' | 'visible'>> & {color?: FigmaColorgradientStops?: Array<Omit<GradientStop, 'color'> & { color: FigmaColor }>+ boundVariables?: { color?: FigmaVariableAlias }}-export function figmaPaintToFill(fill: FigmaPaint): Fill {+export function figmaPaintToFill({ boundVariables: _bound, ...fill }: FigmaPaint): Fill {return {...fill,...paintDefaults(fill),@@ -83,11 +95,19 @@ export function installVisualNodeProxyAccessors(// Text reads mixed while its characters are filled differently, and setting it fills them all.get(this: ProxyThis): readonly Fill[] | symbol {const node = raw(this, internals)- if (node.type !== 'TEXT') return Object.freeze(copyFills(node.fills))+ if (node.type !== 'TEXT') {+ const bound = paintBindings(node, 'fills')+ const fills = bound.size+ ? (resolvedPaintBindings(graph(this, internals), node).fills ?? node.fills)+ : node.fills+ return Object.freeze(+ copyFills(fills).map((fill, index) => withPaintBinding(fill, bound.get(index)))+ )+ }const fills = getTextStyle(node, 'fills', mixed)return typeof fills === 'symbol' ? fills : Object.freeze(fills as Fill[])},- set(this: ProxyThis, value: readonly Fill[]) {+ set(this: ProxyThis, value: readonly FigmaPaint[]) {const node = raw(this, internals)const fills = value.map(figmaPaintToFill)updateNode(@@ -95,24 +115,34 @@ export function installVisualNodeProxyAccessors(internals,node.type === 'TEXT' ? textStyleChanges(node, { fills }) : { fills })+ setPaintBindings(graph(this, internals), raw(this, internals), 'fills', value)}},strokes: {get(this: ProxyThis): readonly Stroke[] {- return Object.freeze(copyStrokes(raw(strokeOwner(this, internals), internals).strokes))+ const owner = raw(strokeOwner(this, internals), internals)+ const bound = paintBindings(owner, 'strokes')+ const strokes = bound.size+ ? (resolvedPaintBindings(graph(this, internals), owner).strokes ?? owner.strokes)+ : owner.strokes+ return Object.freeze(+ copyStrokes(strokes).map((stroke, index) => withPaintBinding(stroke, bound.get(index)))+ )},// Figma paints carry no geometry; a stroke takes the node's weight and alignment, which// outlast its strokes.set(this: ProxyThis,value: readonly (Omit<Stroke, 'weight' | 'align'> &- Partial<Pick<Stroke, 'weight' | 'align'>>)[]+ Partial<Pick<Stroke, 'weight' | 'align'>> & {+ boundVariables?: { color?: FigmaVariableAlias }+ })[]) {const owner = strokeOwner(this, internals)const geometry = newStrokeGeometry(raw(owner, internals))// The script keeps its paint objects; the node gets its own copies of every nested value.const strokes = copyStrokes(- value.map((stroke) => ({+ value.map(({ boundVariables: _bound, ...stroke }) => ({...stroke,...paintDefaults(stroke),weight: stroke.weight ?? geometry.weight,@@ -130,6 +160,7 @@ export function installVisualNodeProxyAccessors(strokeWeight: kept.weight,strokeAlign: kept.align})+ setPaintBindings(graph(this, internals), raw(owner, internals), 'strokes', value)}},effects: {diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex efb307028..c12624487 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -8,6 +8,12 @@ import type {FigmaSlotNode} from './node-types'import type { FigmaNodeProxy } from './proxy'+import type {+ FIGMA_API_HOST_MEMBERS,+ FIGMA_API_INCOMPLETE_MEMBERS,+ SERIALIZATION_MEMBERS+} from './surface'+import type { FigmaVariable, FigmaVariableCollection, FigmaVariablesAPI } from './variables'type Expect<T extends true> = T@@ -186,3 +192,106 @@ type TextMixedMatch = Expect<>>const _textMixedMatch: TextMixedMatch = true++type SupportedVariableKeys =+ | 'id'+ | 'name'+ | 'description'+ | 'hiddenFromPublishing'+ | 'remote'+ | 'variableCollectionId'+ | 'key'+ | 'resolvedType'+ | 'valuesByMode'+ | 'scopes'+ | 'codeSyntax'+ | 'setVariableCodeSyntax'+ | 'removeVariableCodeSyntax'+ | 'setValueForMode'+ | 'remove'+type VariableMatch = Expect<+ Extends<Pick<FigmaVariable, SupportedVariableKeys>, Pick<Variable, SupportedVariableKeys>>+>+const _variableMatch: VariableMatch = true++type SupportedCollectionKeys =+ | 'id'+ | 'name'+ | 'hiddenFromPublishing'+ | 'remote'+ | 'isExtension'+ | 'modes'+ | 'variableIds'+ | 'defaultModeId'+ | 'key'+ | 'remove'+ | 'removeMode'+ | 'addMode'+ | 'renameMode'+type CollectionMatch = Expect<+ Extends<+ Pick<FigmaVariableCollection, SupportedCollectionKeys>,+ Pick<VariableCollection, SupportedCollectionKeys>+ >+>+const _collectionMatch: CollectionMatch = true++/** Every `figma.variables` member is Figma's, and takes what Figma's takes. */+type VariablesAPIArguments = {+ [K in keyof FigmaVariablesAPI]: K extends keyof VariablesAPI+ ? Parameters<VariablesAPI[K]> extends Parameters<FigmaVariablesAPI[K]>+ ? true+ : K+ : K+}[keyof FigmaVariablesAPI]+type VariablesAPIMatch = Expect<VariablesAPIArguments extends true ? true : false>+const _variablesAPIMatch: VariablesAPIMatch = true++type NodeBindingMatch = Expect<+ Extends<+ Parameters<SceneNodeMixin['setBoundVariable']>,+ Parameters<FigmaNodeProxy['setBoundVariable']>+ >+>+const _nodeBindingMatch: NodeBindingMatch = true++// --- Surface: nothing beyond Figma's Plugin API except what `surface.ts` lists ---+// Each check is a `Record` of the offending names, so a failure names them: "Property 'x' is+// missing". Add a Figma member as Figma types it; put an OpenPencil feature on `openpencil`.++type HostMembers = (typeof FIGMA_API_HOST_MEMBERS)[number]+type IncompleteMembers = (typeof FIGMA_API_INCOMPLETE_MEMBERS)[number]+type SerializationMembers = (typeof SERIALIZATION_MEMBERS)[number]+type KeysOfUnion<T> = T extends unknown ? keyof T : never+type None<Names extends PropertyKey> = Record<Names, never>++/** `figma` members Figma's Plugin API does not have. */+const _figmaExtras: None<Exclude<keyof FigmaAPI, keyof PluginAPI | HostMembers>> = {}+/** Listed host members that no longer exist. */+const _figmaGoneListings: None<Exclude<HostMembers, keyof FigmaAPI>> = {}+/** Listed host members that are Figma's after all. */+const _figmaFigmaListings: None<Extract<HostMembers, keyof PluginAPI>> = {}++type SharedKeys = keyof FigmaAPI & keyof PluginAPI+type DriftedKeys = {+ [K in SharedKeys]: FigmaAPI[K] extends PluginAPI[K] ? never : K+}[SharedKeys]+/** Members named as in Figma whose types differ from Figma's. */+const _figmaDrifted: None<Exclude<DriftedKeys, IncompleteMembers>> = {}+/** Members listed as incomplete that now match Figma's types. */+const _figmaNowComplete: None<Exclude<IncompleteMembers, DriftedKeys>> = {}++type FigmaNodeKeys = KeysOfUnion<SceneNode | PageNode | DocumentNode>+/** Node proxy members no Figma node type has. */+const _nodeExtras: None<+ Exclude<Extract<keyof FigmaNodeProxy, string>, FigmaNodeKeys | SerializationMembers>+> = {}+/** Variable members Figma's do not have. */+const _variableExtras: None<Exclude<keyof FigmaVariable, keyof Variable | SerializationMembers>> =+ {}+/** Collection members Figma's do not have. */+const _collectionExtras: None<+ Exclude<keyof FigmaVariableCollection, keyof VariableCollection | SerializationMembers>+> = {}+/** `figma.variables` members Figma's do not have. */+const _variablesAPIExtras: None<Exclude<keyof FigmaVariablesAPI, keyof VariablesAPI>> = {}diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.tsindex ca66a5888..7c27c7f93 100644--- a/packages/core/src/figma-api/components.ts+++ b/packages/core/src/figma-api/components.ts@@ -19,20 +19,11 @@ import {import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { becomesComponent, componentWrapProps } from '#core/editor/components/create'-import {- measurePropertyText,- reapplyInstanceComponentProperties-} from '#core/editor/components/properties'-import { applyVariantProperties, variantSetProps } from '#core/editor/components/variant-set'-import {- findExactVariant,- getComponentSet,- variantValues-} from '#core/editor/components/variants/model'+import { measurePropertyText } from '#core/editor/components/properties'import { wrapNodes } from '#core/editor/structure/container-wrap'import type { NodeProxyInternals, ProxyThis } from './accessor-utils'-import { graph, raw, updateNode } from './accessor-utils'+import { assertProxyEditable, graph, raw, updateNode } from './accessor-utils'import type { FigmaNodeProxy } from './proxy'import {assertSlotSettings,@@ -40,6 +31,9 @@ import {mergeSlotSettings,type FigmaSlotSettings} from './slots'+import { addVariantAxis, editVariantAxis, switchVariant, variantPropertiesOf } from './variants'++export { combineComponentsAsVariants } from './variants'type InstanceSwapPreferredValue = { type: 'COMPONENT' | 'COMPONENT_SET'; key: string }@@ -131,19 +125,6 @@ function findPropertyHost(graph: SceneGraph, nodeId: string | null): SceneNode |return fallback}-function requireDistinctComponents(graph: SceneGraph, nodeIds: ReadonlyArray<string>): SceneNode[] {- if (nodeIds.length === 0) throw new Error('Need at least 1 component to combine as variants')- if (new Set(nodeIds).size !== nodeIds.length) {- throw new Error('combineAsVariants requires distinct COMPONENT nodes')- }-- const nodes = nodeIds.map((id) => graph.getNode(id))- if (!nodes.every((node): node is SceneNode => node?.type === 'COMPONENT')) {- throw new Error('combineAsVariants requires COMPONENT nodes')- }- return nodes-}-function propertyName(definition: ComponentPropertyDefinition): string {return definition.type === 'VARIANT' ? definition.name : `${definition.name}#${definition.id}`}@@ -257,7 +238,13 @@ function editPropertyDefinitions(if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')throw new Error('editComponentProperty() can only be called on components')const definition = findDefinition(target, internals, propertyNameValue)+ if (!definition && node.type === 'COMPONENT_SET')+ throw new Error('in editComponentProperty: Invalid variant property name')if (!definition) throw new Error(`Unknown component property: ${propertyNameValue}`)+ if (definition.type === 'VARIANT') {+ assertProxyEditable(target, internals)+ return editVariantAxis(graph(target, internals), node, definition, changes)+ }if (changes.defaultValue !== undefined &&!['BOOLEAN', 'TEXT', 'INSTANCE_SWAP'].includes(definition.type)@@ -320,34 +307,6 @@ function propertyReferenceName(field: ComponentPropertyReferenceField): string {if (field === 'SLOT_CONTENT') return 'slotContentId'return field === 'TEXT' ? 'characters' : 'visible'}-interface PropertyValue {- definition: ComponentPropertyDefinition- value: string | boolean-}--/**- * Switches an instance to the variant with the given values, the rest kept, as Figma's- * `setProperties` does; a combination no variant has fails without changing anything.- */-function switchVariant(scene: SceneGraph, instance: SceneNode, values: PropertyValue[]): void {- const component = instance.componentId ? scene.getNode(instance.componentId) : undefined- const setId = component?.parentId- const target =- component && setId && getComponentSet(scene, setId)- ? findExactVariant(scene, setId, {- ...variantValues(scene, setId, component),- ...Object.fromEntries(- values.map(({ definition, value }) => [definition.name, String(value)])- )- })- : undefined- if (!target)- throw new Error('in setProperties: Unable to find a variant with those property values')- if (target.id === instance.componentId) return- scene.swapInstanceComponent(instance.id, target.id)- reapplyInstanceComponentProperties({ graph: scene }, instance.id)-}-function applyProperty(target: ProxyThis,internals: NodeProxyInternals,@@ -412,6 +371,11 @@ export function installComponentPropertyAccessors(return componentProperties(this, internals)}},+ variantProperties: {+ get(this: ProxyThis) {+ return variantPropertiesOf(graph(this, internals), raw(this, internals))+ }+ },isExposedInstance: {get(this: ProxyThis) {const node = raw(this, internals)@@ -491,6 +455,11 @@ export function installComponentPropertyAccessors(}) {const node = raw(this, internals)+ if (type === 'VARIANT') {+ assertProxyEditable(this, internals)+ return addVariantAxis(graph(this, internals), node, name.trim(), String(defaultValue))+ .name+ }if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')throw new Error('addComponentProperty() can only be called on components')const definition: ComponentPropertyDefinition = {@@ -538,36 +507,14 @@ export function installComponentPropertyAccessors(if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')throw new Error('deleteComponentProperty() can only be called on components')const definition = findDefinition(this, internals, name)- if (!definition) throw new Error(`Unknown component property: ${name}`)+ // Figma keeps a variant axis: deleting one reads as a name it does not know.+ if (!definition || definition.type === 'VARIANT')+ throw new Error('in deleteComponentProperty: Invalid component property name')removeComponentProperty(graph(this, internals), node.id, definition.id)}}})}-export function combineComponentsAsVariants(- graph: SceneGraph,- nodeIds: ReadonlyArray<string>,- parentId: string,- index?: number-): SceneNode {- const components = requireDistinctComponents(graph, nodeIds)- const parent = graph.getNode(parentId)- if (!parent) throw new Error('Parent node not found')-- // The plugin API wraps the variants exactly; see `variantSetProps`.- const componentSet = wrapNodes(- graph,- 'COMPONENT_SET',- components,- parentId,- index,- variantSetProps(graph, components, parentId, 'script')- )- applyVariantProperties(graph, components, componentSet.id)-- return componentSet-}-/*** Makes a component from a layer as Figma's `createComponentFromNode` does: a frame or group* becomes a new component with its look and children in its place in the stack, and any otherdiff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 389b6ca95..ca798eea1 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -3,15 +3,10 @@ import { fromUint8Array, isValid, toUint8Array } from 'js-base64'import {createConnector,freeEndpoint,- updateTokenExpression,type GroupFitOptions,type SceneGraph,type SceneNode as CoreSceneNode,- type NodeType,- type Variable,- type VariableCollection,- type VariableType,- type VariableValue+ type NodeType} from '@open-pencil/scene-graph'import { computeBounds } from '@open-pencil/scene-graph/geometry'import { computeImageHash } from '@open-pencil/scene-graph/images'@@ -29,11 +24,9 @@ import { iconify, type IconProvider } from '#core/icons'import type { RasterCodec } from '#core/io/formats/raster'import { createSVGNodes } from '#core/io/formats/svg'import { textAutoResizeChanges } from '#core/layout/text-auto-resize'-import { reconcileVariableLayouts } from '#core/layout/variables'-import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'import { fontManager } from '#core/text/fonts'-import { combineComponentsAsVariants, componentFromNode, exposeInstanceSwap } from './components'+import { componentFromNode } from './components'import { flattenSceneNodes } from './flatten'import type {FigmaBooleanOperationNode,@@ -63,6 +56,8 @@ import {} from './proxy'import { newShapeWithText } from './shape-with-text'import type { ExportImageOptions } from './types'+import { FigmaVariablesAPI } from './variables'+import { combineComponentsAsVariants } from './variants'const noop = () => undefined@@ -71,6 +66,14 @@ export { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'export { flushPendingLayout } from './pending-layout'export type { FigmaEffect } from './effects'export type { ExportImageOptions } from './types'+export {+ FigmaVariable,+ FigmaVariableCollection,+ FigmaVariablesAPI,+ type FigmaComposedColor,+ type FigmaVariableAlias,+ type FigmaVariableValue+} from './variables'export type {FigmaBooleanOperationNode,FigmaComponentNode,@@ -107,9 +110,12 @@ export class FigmaAPI implements NodeProxyHost {theme: InterfaceTheme = 'light'readonly mixed = MIXED+ /** The document's variables and collections, as Figma's `figma.variables`. */+ readonly variables: FigmaVariablesAPIconstructor(graph: SceneGraph) {this.graph = graph+ this.variables = new FigmaVariablesAPI(graph)startPendingLayout(graph)const pages = graph.getPages()this._currentPageId = pages[0]?.id ?? graph.rootId@@ -333,64 +339,6 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(componentSet.id) as FigmaComponentSetNode}- exposeInstanceSwap(- slots: ReadonlyArray<FigmaNodeProxy>,- candidates: ReadonlyArray<FigmaNodeProxy>,- propertyName = 'Instance'- ): FigmaNodeProxy {- const host = exposeInstanceSwap(this.graph, slots, candidates, propertyName)- return this.wrapNode(host.id)- }-- getVariableById(id: string): Variable | null {- return this.graph.variables.get(id) ?? null- }-- getLocalVariables(type?: string): Variable[] {- const vars = [...this.graph.variables.values()]- if (type) return vars.filter((v) => v.type === type)- return vars- }-- getLocalVariableCollections(): VariableCollection[] {- return [...this.graph.variableCollections.values()]- }-- getVariableCollectionById(id: string): VariableCollection | null {- return this.graph.variableCollections.get(id) ?? null- }-- // --- Variable/Collection CRUD ----- createVariable(- name: string,- type: VariableType,- collectionId: string,- value?: VariableValue- ): Variable {- return this.graph.createVariable(name, type, collectionId, value)- }-- setVariableValue(variableId: string, modeId: string, value: VariableValue): void {- 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] })- }-- deleteVariable(id: string): void {- this.graph.removeVariable(id)- }-- createVariableCollection(name: string): VariableCollection {- return this.graph.createCollection(name)- }-- deleteVariableCollection(id: string): void {- this.graph.removeCollection(id)- }-// --- Boolean Operations ---private _booleanOperation(@@ -414,52 +362,75 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(group.id) as FigmaBooleanOperationNode}- private _nodesById(nodeIds: string[]) {- return nodeIds.map((id) => {- const node = this.getNodeById(id)- if (!node) throw new Error(`Node ${id} not found`)- return node- })- }-- booleanOperation(- operation: 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE',- nodeIds: string[]- ): FigmaBooleanOperationNode {- const first = this.graph.getNode(nodeIds[0])- const parent = this.wrapNode(first?.parentId ?? this._currentPageId)- return this._booleanOperation(operation, this._nodesById(nodeIds), parent)- }-+ union(+ nodes: ReadonlyArray<FigmaNodeProxy>,+ parent: FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNodeunion(nodes: ReadonlyArray<BaseNode>,parent: BaseNode & ChildrenMixin,index?: number- ): BooleanOperationNode {+ ): BooleanOperationNode+ union(+ nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,+ parent: (BaseNode & ChildrenMixin) | FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNode {return this._booleanOperation('UNION', nodes, parent, index)}+ subtract(+ nodes: ReadonlyArray<FigmaNodeProxy>,+ parent: FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNodesubtract(nodes: ReadonlyArray<BaseNode>,parent: BaseNode & ChildrenMixin,index?: number- ): BooleanOperationNode {+ ): BooleanOperationNode+ subtract(+ nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,+ parent: (BaseNode & ChildrenMixin) | FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNode {return this._booleanOperation('SUBTRACT', nodes, parent, index)}+ intersect(+ nodes: ReadonlyArray<FigmaNodeProxy>,+ parent: FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNodeintersect(nodes: ReadonlyArray<BaseNode>,parent: BaseNode & ChildrenMixin,index?: number- ): BooleanOperationNode {+ ): BooleanOperationNode+ intersect(+ nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,+ parent: (BaseNode & ChildrenMixin) | FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNode {return this._booleanOperation('INTERSECT', nodes, parent, index)}+ exclude(+ nodes: ReadonlyArray<FigmaNodeProxy>,+ parent: FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNodeexclude(nodes: ReadonlyArray<BaseNode>,parent: BaseNode & ChildrenMixin,index?: number- ): BooleanOperationNode {+ ): BooleanOperationNode+ exclude(+ nodes: ReadonlyArray<BaseNode | FigmaNodeProxy>,+ parent: (BaseNode & ChildrenMixin) | FigmaNodeProxy,+ index?: number+ ): FigmaBooleanOperationNode {return this._booleanOperation('EXCLUDE', nodes, parent, index)}@@ -496,12 +467,6 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(vector.id) as FigmaVectorNode}- flattenNode(nodeIds: string[]): FigmaVectorNode {- const first = this.graph.getNode(nodeIds[0])- const parent = this.wrapNode(first?.parentId ?? this._currentPageId)- return this.flatten(this._nodesById(nodeIds), parent)- }-// --- Viewport ---private _viewport = { x: 0, y: 0, zoom: 1 }@@ -555,10 +520,6 @@ export class FigmaAPI implements NodeProxyHost {return []}- getFontStatus(): DocumentFontStatus {- return documentFontStatus(this.graph, this.currentPageId)- }-base64Encode(data: Uint8Array): string {return fromUint8Array(data)}diff --git a/packages/core/src/figma-api/plugin-data.ts b/packages/core/src/figma-api/plugin-data.tsindex 9e0699323..1411ce6ae 100644--- a/packages/core/src/figma-api/plugin-data.ts+++ b/packages/core/src/figma-api/plugin-data.ts@@ -1,5 +1,13 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ assertProxyEditable,+ graph,+ raw,+ type NodeProxyInternals,+ type ProxyThis+} from './accessor-utils'+export const OPEN_PENCIL_PLUGIN_DATA_NAMESPACE = 'open-pencil'type PluginDataEntry = SceneNode['pluginData'][number]@@ -87,3 +95,48 @@ export function getSharedPluginDataKeys(node: SceneNode, namespace: string): strreturn key === null ? [] : [key]})}++/** Figma's plugin data methods, which every node proxy has. */+export interface PluginDataMethods {+ getPluginData(key: string): string+ setPluginData(key: string, value: string): void+ getPluginDataKeys(): string[]+ getSharedPluginData(namespace: string, key: string): string+ setSharedPluginData(namespace: string, key: string, value: string): void+ getSharedPluginDataKeys(namespace: string): string[]+}++export function installPluginDataMethods(prototype: object, internals: NodeProxyInternals): void {+ const methods: {+ [K in keyof PluginDataMethods]: (+ this: ProxyThis,+ ...args: Parameters<PluginDataMethods[K]>+ ) => ReturnType<PluginDataMethods[K]>+ } = {+ getPluginData(key) {+ return getPluginData(raw(this, internals), key)+ },+ setPluginData(key, value) {+ assertProxyEditable(this, internals)+ setPluginData(graph(this, internals), raw(this, internals), key, value)+ },+ getPluginDataKeys() {+ return getPluginDataKeys(raw(this, internals))+ },+ getSharedPluginData(namespace, key) {+ return getSharedPluginData(raw(this, internals), namespace, key)+ },+ setSharedPluginData(namespace, key, value) {+ assertProxyEditable(this, internals)+ setSharedPluginData(graph(this, internals), raw(this, internals), namespace, key, value)+ },+ getSharedPluginDataKeys(namespace) {+ return getSharedPluginDataKeys(raw(this, internals), namespace)+ }+ }+ // Non-enumerable, as class methods are.+ Object.defineProperties(+ prototype,+ Object.fromEntries(Object.entries(methods).map(([name, value]) => [name, { value }]))+ )+}diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex dc56bf8d4..ac9529134 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -15,13 +15,6 @@ import type {LayoutGrid,LayoutMode} from '@open-pencil/scene-graph'-import {- getFillOkHCL,- getStrokeOkHCL,- setNodeFillOkHCL,- setNodeStrokeOkHCL-} from '@open-pencil/scene-graph/color'-import type { OkHCLColor, OkHCLPayload } from '@open-pencil/scene-graph/color'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { ShapeWithTextType } from '@open-pencil/scene-graph/shape-with-text'@@ -36,7 +29,10 @@ import { installStickyNodeProxyAccessors, pluginChildren } from './accessors/stiimport { installStrokeNodeProxyAccessors } from './accessors/strokes'import { installTextNodeProxyAccessors } from './accessors/text'import { installTextRangeMethods, type TextRangeMethods } from './accessors/text/ranges'-import { installVariableModeNodeProxyAccessors } from './accessors/variables'+import {+ installVariableModeNodeProxyAccessors,+ type VariableNodeMembers+} from './accessors/variables'import {installVectorNodeProxyAccessors,type FigmaVectorNetwork,@@ -53,7 +49,7 @@ import type { FigmaFontName } from './fonts'import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'-import * as PluginData from './plugin-data'+import { installPluginDataMethods, type PluginDataMethods } from './plugin-data'import { nodeProxyToJSON } from './serialization'import { installShapeWithTextAccessors } from './shape-with-text'import { installSlotAccessors, prepareSlotMove, prepareSlotRemoval } from './slots'@@ -132,7 +128,6 @@ export class FigmaNodeProxy {declare layoutMode: LayoutModedeclare layoutGrids: readonly LayoutGrid[]- declare layoutDirection: stringdeclare primaryAxisAlignItems: stringdeclare counterAxisAlignItems: stringdeclare itemSpacing: number@@ -166,8 +161,18 @@ export class FigmaNodeProxy {declare vectorNetwork: FigmaVectorNetworkdeclare setVectorNetworkAsync: (vectorNetwork: FigmaVectorNetwork) => Promise<void>declare handleMirroring: SceneNode['handleMirroring'] | typeof MIXED- declare readonly explicitVariableModes: Readonly<Record<string, string>>- declare readonly resolvedVariableModes: Readonly<Record<string, string>>+ declare getPluginData: PluginDataMethods['getPluginData']+ declare setPluginData: PluginDataMethods['setPluginData']+ declare getPluginDataKeys: PluginDataMethods['getPluginDataKeys']+ declare getSharedPluginData: PluginDataMethods['getSharedPluginData']+ declare setSharedPluginData: PluginDataMethods['setSharedPluginData']+ declare getSharedPluginDataKeys: PluginDataMethods['getSharedPluginDataKeys']+ declare readonly explicitVariableModes: VariableNodeMembers['explicitVariableModes']+ declare readonly resolvedVariableModes: VariableNodeMembers['resolvedVariableModes']+ declare setExplicitVariableModeForCollection: VariableNodeMembers['setExplicitVariableModeForCollection']+ declare clearExplicitVariableModeForCollection: VariableNodeMembers['clearExplicitVariableModeForCollection']+ declare readonly boundVariables: VariableNodeMembers['boundVariables']+ declare setBoundVariable: VariableNodeMembers['setBoundVariable']declare readonly overrides: FigmaInstanceOverride[] | undefined/** A sticky note's body or a shape's label, a sticky's author line, and whether it is wide. */declare readonly text: FigmaNodeProxy | undefined@@ -194,7 +199,6 @@ export class FigmaNodeProxy {declare fontWeight: number | symboldeclare textAlignHorizontal: stringdeclare textAlignVertical: string- declare textDirection: stringdeclare textAutoResize: stringdeclare letterSpacing: FigmaLetterSpacing | symboldeclare lineHeight: FigmaLineHeight | symbol@@ -497,54 +501,6 @@ export class FigmaNodeProxy {)}- // --- Plugin data ----- getPluginData(key: string): string {- return PluginData.getPluginData(this._raw(), key)- }-- setPluginData(key: string, value: string): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- PluginData.setPluginData(this[INTERNAL_GRAPH], this._raw(), key, value)- }-- getPluginDataKeys(): string[] {- return PluginData.getPluginDataKeys(this._raw())- }-- getSharedPluginData(namespace: string, key: string): string {- return PluginData.getSharedPluginData(this._raw(), namespace, key)- }-- setSharedPluginData(namespace: string, key: string, value: string): void {- assertNodeEditable(this[INTERNAL_GRAPH], this[INTERNAL_ID])- PluginData.setSharedPluginData(this[INTERNAL_GRAPH], this._raw(), namespace, key, value)- }-- getSharedPluginDataKeys(namespace: string): string[] {- return PluginData.getSharedPluginDataKeys(this._raw(), namespace)- }-- getFillOkHCL(index = 0): OkHCLPayload | null {- return getFillOkHCL(this._raw(), index)- }-- setFillOkHCL(color: OkHCLColor, index = 0): void {- this._update(- setNodeFillOkHCL(this._raw(), index, color, this[INTERNAL_GRAPH].documentColorSpace)- )- }-- getStrokeOkHCL(index = 0): OkHCLPayload | null {- return getStrokeOkHCL(this._raw(), index)- }-- setStrokeOkHCL(color: OkHCLColor, index = 0): void {- this._update(- setNodeStrokeOkHCL(this._raw(), index, color, this[INTERNAL_GRAPH].documentColorSpace)- )- }-// --- Serialization ---toJSON(maxDepth?: number, currentDepth = 0): Record<string, unknown> {@@ -592,6 +548,7 @@ installTextNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals, MIXED)installTextRangeMethods(FigmaNodeProxy.prototype, proxyInternals, MIXED)installLayoutNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)installVariableModeNodeProxyAccessors(FigmaNodeProxy.prototype, proxyInternals)+installPluginDataMethods(FigmaNodeProxy.prototype, proxyInternals)installComponentPropertyAccessors(FigmaNodeProxy.prototype, proxyInternals)installInstanceOverrideAccessors(FigmaNodeProxy.prototype, proxyInternals)installSlotAccessors(FigmaNodeProxy.prototype, proxyInternals)diff --git a/packages/core/src/figma-api/surface.ts b/packages/core/src/figma-api/surface.tsnew file mode 100644index 000000000..85519a972--- /dev/null+++ b/packages/core/src/figma-api/surface.ts@@ -0,0 +1,39 @@+/**+ * What `figma` and its objects have beyond Figma's Plugin API. `compatibility.ts` checks the+ * types against these lists and `tests/figma-api/surface.test.ts` checks what scripts can reach.+ * A feature Figma has no API for goes on `openpencil`, never on these lists; entries only leave.+ */++/** Members a host or tool wires up on `figma`, which scripts do not write against. */+export const FIGMA_API_HOST_MEMBERS = [+ 'graph',+ 'wrapNode',+ 'currentPageId',+ 'groupFitOptions',+ 'setRenderer',+ 'theme',+ 'exportImage',+ 'icons',+ 'rasterCodec',+ 'changeBaseline'+] as const++/**+ * Members named as in Figma whose types do not match Figma's yet, mostly because node proxies do+ * not implement every Figma node type; remove one when it matches.+ */+export const FIGMA_API_INCOMPLETE_MEMBERS = [+ 'createComponentFromNode',+ 'createImage',+ 'createPage',+ 'currentPage',+ 'getNodeById',+ 'getNodeByIdAsync',+ 'mixed',+ 'root',+ 'variables',+ 'viewport'+] as const++/** The `JSON.stringify` hook hosts use to report what a script returns. */+export const SERIALIZATION_MEMBERS = ['toJSON'] as constdiff --git a/packages/core/src/figma-api/text/bindings.ts b/packages/core/src/figma-api/text/bindings.tsindex 76812d554..e1736a57e 100644--- a/packages/core/src/figma-api/text/bindings.ts+++ b/packages/core/src/figma-api/text/bindings.ts@@ -14,9 +14,10 @@ import {import { copyFills } from '@open-pencil/scene-graph/copy'import { styleNameToWeight } from '#core/figma-api/fonts'+import { variableAlias, type FigmaVariableAlias } from '#core/figma-api/variables/values'import { styleRunsWithPatch } from '#core/text/character-style'-import { getStyledTextSegments, variableAlias, type FigmaVariableAlias } from './style'+import { getStyledTextSegments } from './style'/** Fields a string variable binds; the rest take numbers. */const STRING_FIELDS: ReadonlySet<TextBindableField> = new Set(['fontFamily', 'fontStyle'])diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.tsindex f79d59c4a..3ae04d1b2 100644--- a/packages/core/src/figma-api/text/style.ts+++ b/packages/core/src/figma-api/text/style.ts@@ -11,6 +11,7 @@ import {import { copyFills } from '@open-pencil/scene-graph/copy'import { weightToStyleName } from '#core/figma-api/fonts'+import { variableAlias } from '#core/figma-api/variables/values'import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'/** The fields `getStyledTextSegments` takes, in the order Figma lists them. */@@ -77,16 +78,6 @@ function spacing(field: 'paragraphSpacing' | 'listSpacing' | 'paragraphIndent')return ({ node, paragraph }: FieldContext) => paragraphSpacingAt(node, paragraph, field)}-/** Figma's reference to a variable, as bound fields read it. */-export function variableAlias(id: string): FigmaVariableAlias {- return { type: 'VARIABLE_ALIAS', id }-}--export interface FigmaVariableAlias {- type: 'VARIABLE_ALIAS'- id: string-}-/*** Figma's value of each field for one character. Fields the model keeps for the whole text read* the text's value; fields it has no place for read Figma's defaults.diff --git a/packages/core/src/figma-api/variables/bindings.ts b/packages/core/src/figma-api/variables/bindings.tsnew file mode 100644index 000000000..ab89df015--- /dev/null+++ b/packages/core/src/figma-api/variables/bindings.ts@@ -0,0 +1,263 @@+import { uniq } from 'es-toolkit/array'++import {+ TEXT_BINDABLE_FIELDS,+ type SceneGraph,+ type SceneNode,+ type TextBindableField,+ type Variable,+ type VariableType+} from '@open-pencil/scene-graph'++import { reconcileVariableLayouts } from '#core/layout/variables'++import { variableAlias, type FigmaVariableAlias } from './values'++/**+ * The fields Figma's `setBoundVariable` takes, in the order its message lists them, with the+ * document field each one binds. Text style fields bind every character's style instead.+ */+const NODE_FIELDS = {+ height: 'height',+ width: 'width',+ characters: 'text',+ itemSpacing: 'itemSpacing',+ paddingLeft: 'paddingLeft',+ paddingRight: 'paddingRight',+ paddingTop: 'paddingTop',+ paddingBottom: 'paddingBottom',+ visible: 'visible',+ cornerRadius: 'cornerRadius',+ topLeftRadius: 'topLeftRadius',+ topRightRadius: 'topRightRadius',+ bottomLeftRadius: 'bottomLeftRadius',+ bottomRightRadius: 'bottomRightRadius',+ strokeWeight: 'strokeWeight',+ strokeTopWeight: 'borderTopWeight',+ strokeBottomWeight: 'borderBottomWeight',+ strokeLeftWeight: 'borderLeftWeight',+ strokeRightWeight: 'borderRightWeight',+ minWidth: 'minWidth',+ maxWidth: 'maxWidth',+ minHeight: 'minHeight',+ maxHeight: 'maxHeight',+ counterAxisSpacing: 'counterAxisSpacing',+ opacity: 'opacity',+ gridRowGap: 'gridRowGap',+ gridColumnGap: 'gridColumnGap'+} as const++export type FigmaBindableNodeField = keyof typeof NODE_FIELDS+export type FigmaBindableField = FigmaBindableNodeField | TextBindableField++const FIELD_NAMES = [...Object.keys(NODE_FIELDS), ...TEXT_BINDABLE_FIELDS]++const CORNER_FIELDS = [+ 'topLeftRadius',+ 'topRightRadius',+ 'bottomLeftRadius',+ 'bottomRightRadius'+] as const++/** Fields only an auto layout or grid container has; elsewhere Figma ignores the binding. */+const CONTAINER_FIELDS: ReadonlySet<string> = new Set([+ 'itemSpacing',+ 'paddingLeft',+ 'paddingRight',+ 'paddingTop',+ 'paddingBottom',+ 'counterAxisSpacing',+ 'gridRowGap',+ 'gridColumnGap'+])++const CONTAINER_TYPES: ReadonlySet<string> = new Set([+ 'FRAME',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])++/** The variable type each field takes from `setBoundVariable`, which is stricter than the panel. */+function fieldType(field: FigmaBindableField): VariableType {+ if (field === 'characters' || field === 'fontFamily' || field === 'fontStyle') return 'STRING'+ if (field === 'visible') return 'BOOLEAN'+ return 'FLOAT'+}++export function isTextBindableField(field: string): field is TextBindableField {+ return (TEXT_BINDABLE_FIELDS as readonly string[]).includes(field)+}++/** Figma's checks on a field name, in the order it makes them. */+export function assertBindableField(field: unknown): FigmaBindableField {+ if (field === 'fills' || field === 'strokes') {+ throw new Error(+ 'in setBoundVariable: fills and strokes variable bindings must be set on paints directly'+ )+ }+ if (typeof field !== 'string' || !FIELD_NAMES.includes(field)) {+ throw new Error(+ 'in setBoundVariable: Property "field" failed validation: Invalid option: expected one of ' ++ FIELD_NAMES.map((name) => `"${name}"`).join('|')+ )+ }+ return field as FigmaBindableField+}++/** The variable a `setBoundVariable` call names, by object or by id, checked against the field. */+export function bindingVariable(+ graph: SceneGraph,+ method: string,+ field: FigmaBindableField,+ variable: { readonly id: string } | string+): Variable {+ const id = typeof variable === 'string' ? variable : variable.id+ const found = graph.variables.get(id)+ if (!found) throw new Error(`in ${method}: Variable not found`)+ if (found.type !== fieldType(field)) {+ throw new Error(+ `in ${method}: variable of resolved type '${found.type}' cannot be bound to '${field}'`+ )+ }+ return found+}++/** Whether the layer has the field at all; Figma ignores a binding to one it lacks. */+export function hasBindableField(node: SceneNode, field: FigmaBindableField): boolean {+ if (field === 'characters' || isTextBindableField(field)) return node.type === 'TEXT'+ if (CONTAINER_FIELDS.has(field)) return CONTAINER_TYPES.has(node.type)+ return true+}++/** The document fields a Figma field binds: a uniform corner radius binds every corner. */+function documentFields(field: FigmaBindableNodeField): readonly string[] {+ return field === 'cornerRadius' ? CORNER_FIELDS : [NODE_FIELDS[field]]+}++/**+ * Binds or unbinds the document fields behind a Figma node field, then shows the variable's value+ * on the layer and lays out what it moves.+ */+export function setLayerBinding(+ graph: SceneGraph,+ node: SceneNode,+ field: FigmaBindableNodeField,+ variable: Variable | null+): void {+ for (const name of documentFields(field)) {+ if (variable) graph.bindVariable(node.id, name, variable.id)+ else graph.unbindVariable(node.id, name)+ }+ reconcileVariableLayouts(graph, { subtrees: [node.id] })+}++/** Text style fields a text layer itself can hold a binding for. */+const LAYER_TEXT_FIELDS: ReadonlySet<TextBindableField> = new Set([+ 'fontFamily',+ 'fontSize',+ 'letterSpacing',+ 'lineHeight'+])++/**+ * Binds a text style field of text with no characters on the layer, as Figma keeps it for the+ * characters typed later. OpenPencil keeps only some of those fields on a layer.+ */+export function setEmptyTextBinding(+ graph: SceneGraph,+ node: SceneNode,+ field: TextBindableField,+ variable: Variable | null+): void {+ if (!LAYER_TEXT_FIELDS.has(field)) {+ throw new Error(+ `in setBoundVariable: OpenPencil binds ${field} only on text that has characters`+ )+ }+ if (variable) graph.bindVariable(node.id, field, variable.id)+ else graph.unbindVariable(node.id, field)+ reconcileVariableLayouts(graph, { subtrees: [node.id] })+}++const FIGMA_FIELD_BY_DOCUMENT_FIELD = new Map<string, string>(+ Object.entries(NODE_FIELDS)+ .filter(([figma]) => figma !== 'cornerRadius')+ .map(([figma, field]) => [field, figma])+)++const PAINT_FIELD = /^(fills|strokes)\/(\d+)\/color$/++/** The variable bound to each paint's colour, by paint index, for `fills` or `strokes`. */+export function paintBindings(node: SceneNode, key: 'fills' | 'strokes'): Map<number, string> {+ const bindings = new Map<number, string>()+ for (const [field, id] of Object.entries(node.boundVariables)) {+ const match = PAINT_FIELD.exec(field)+ if (match?.[1] === key) bindings.set(Number(match[2]), id)+ }+ return bindings+}++/**+ * Binds each paint's colour to the variable its `boundVariables.color` names, as Figma does when+ * paints are set, and drops bindings of paints that no longer carry one.+ */+export function setPaintBindings(+ graph: SceneGraph,+ node: SceneNode,+ key: 'fills' | 'strokes',+ paints: readonly { boundVariables?: { color?: FigmaVariableAlias } }[]+): void {+ const current = paintBindings(node, key)+ const wanted = new Map<number, string>()+ paints.forEach((paint, index) => {+ const id = paint.boundVariables?.color?.id+ if (id && graph.variables.get(id)?.type === 'COLOR') wanted.set(index, id)+ })+ for (const index of current.keys()) {+ if (!wanted.has(index)) graph.unbindVariable(node.id, `${key}/${index}/color`)+ }+ for (const [index, id] of wanted) {+ if (current.get(index) !== id) graph.bindVariable(node.id, `${key}/${index}/color`, id)+ }+ if (current.size > 0 || wanted.size > 0) reconcileVariableLayouts(graph, { subtrees: [node.id] })+}++/** A paint as Figma reads it, carrying the reference its colour is bound to. */+export function withPaintBinding<T extends object>(paint: T, variableId: string | undefined): T {+ return variableId ? { ...paint, boundVariables: { color: variableAlias(variableId) } } : paint+}++type FigmaBoundVariables = Record<string, FigmaVariableAlias | FigmaVariableAlias[]>++/**+ * A layer's bindings as Figma's `boundVariables` reads them: a reference per node field, a list+ * per text style field and per bound paint.+ */+export function figmaBoundVariables(node: SceneNode): FigmaBoundVariables {+ const result: FigmaBoundVariables = {}+ for (const [field, id] of Object.entries(node.boundVariables)) {+ const name = FIGMA_FIELD_BY_DOCUMENT_FIELD.get(field)+ if (name) result[name] = variableAlias(id)+ }+ if (node.type === 'TEXT') {+ for (const field of TEXT_BINDABLE_FIELDS) {+ const ids = uniq([+ ...(node.boundVariables[field] ? [node.boundVariables[field]] : []),+ ...node.styleRuns.flatMap((run) => {+ const id = run.style.boundVariables?.[field]+ return id ? [id] : []+ })+ ])+ if (ids.length > 0) result[field] = ids.map(variableAlias)+ }+ }+ for (const key of ['fills', 'strokes'] as const) {+ const bindings = paintBindings(node, key)+ if (bindings.size === 0) continue+ result[key] = [...bindings.entries()]+ .sort(([a], [b]) => a - b)+ .map(([, id]) => variableAlias(id))+ }+ return result+}diff --git a/packages/core/src/figma-api/variables/index.ts b/packages/core/src/figma-api/variables/index.tsnew file mode 100644index 000000000..4efb087f9--- /dev/null+++ b/packages/core/src/figma-api/variables/index.ts@@ -0,0 +1,145 @@+import type { SceneGraph, VariableType } from '@open-pencil/scene-graph'++import { FIGMA_DEFAULT_VALUES, variableAlias, type FigmaVariableAlias } from './values'+import { FigmaVariable, FigmaVariableCollection, assertVariableName } from './variable'++export { FigmaVariable, FigmaVariableCollection, writeVariableValue } from './variable'+export type { FigmaComposedColor, FigmaVariableAlias, FigmaVariableValue } from './values'+export {+ figmaBoundVariables,+ paintBindings,+ setLayerBinding,+ setPaintBindings,+ withPaintBinding,+ type FigmaBindableField+} from './bindings'++/** Figma's variable types, including the motion types OpenPencil does not model. */+const FIGMA_TYPES = ['BOOLEAN', 'COLOR', 'FLOAT', 'STRING', 'EASING', 'TIMING'] as const+export type FigmaVariableResolvedType = (typeof FIGMA_TYPES)[number]++function assertType(method: string, type: unknown): FigmaVariableResolvedType {+ if (!(FIGMA_TYPES as readonly unknown[]).includes(type)) {+ throw new Error(+ `in ${method}: Property "resolvedType" failed validation: Invalid option: expected one of ` ++ FIGMA_TYPES.map((name) => `"${name}"`).join('|')+ )+ }+ return type as FigmaVariableResolvedType+}++function isModelledType(type: FigmaVariableResolvedType): type is VariableType {+ return Object.hasOwn(FIGMA_DEFAULT_VALUES, type)+}++/** A solid paint as `setBoundVariableForPaint` takes and returns it. */+type FigmaSolidPaint = {+ readonly type: string+ readonly boundVariables?: { color?: FigmaVariableAlias }+}++/** `figma.variables`: the document's variables and collections, as Figma's plugin API has them. */+export class FigmaVariablesAPI {+ readonly #graph: SceneGraph++ constructor(graph: SceneGraph) {+ this.#graph = graph+ }++ getVariableById(id: string): FigmaVariable | null {+ return this.#graph.variables.has(id) ? new FigmaVariable(this.#graph, id) : null+ }++ async getVariableByIdAsync(id: string): Promise<FigmaVariable | null> {+ return this.getVariableById(id)+ }++ getVariableCollectionById(id: string): FigmaVariableCollection | null {+ return this.#graph.variableCollections.has(id)+ ? new FigmaVariableCollection(this.#graph, id)+ : null+ }++ async getVariableCollectionByIdAsync(id: string): Promise<FigmaVariableCollection | null> {+ return this.getVariableCollectionById(id)+ }++ getLocalVariables(type?: FigmaVariableResolvedType): FigmaVariable[] {+ const wanted = type === undefined ? undefined : assertType('getLocalVariables', type)+ return [...this.#graph.variables.values()]+ .filter((variable) => wanted === undefined || variable.type === wanted)+ .map((variable) => new FigmaVariable(this.#graph, variable.id))+ }++ async getLocalVariablesAsync(type?: FigmaVariableResolvedType): Promise<FigmaVariable[]> {+ return this.getLocalVariables(type)+ }++ getLocalVariableCollections(): FigmaVariableCollection[] {+ return [...this.#graph.variableCollections.keys()].map(+ (id) => new FigmaVariableCollection(this.#graph, id)+ )+ }++ async getLocalVariableCollectionsAsync(): Promise<FigmaVariableCollection[]> {+ return this.getLocalVariableCollections()+ }++ /** A variable in `collection` whose every mode starts at Figma's default for its type. */+ createVariable(+ name: string,+ collection: { readonly id: string } | string,+ resolvedType: FigmaVariableResolvedType+ ): FigmaVariable {+ const type = assertType('createVariable', resolvedType)+ if (!isModelledType(type))+ throw new Error(`in createVariable: OpenPencil does not support ${type} variables`)+ const collectionId = typeof collection === 'string' ? collection : collection.id+ if (!this.#graph.variableCollections.has(collectionId)) {+ throw new Error('in createVariable: Could not find variable collection')+ }+ assertVariableName(this.#graph, 'createVariable', name, collectionId)+ const variable = this.#graph.createVariable(+ name,+ type,+ collectionId,+ structuredClone(FIGMA_DEFAULT_VALUES[type])+ )+ return new FigmaVariable(this.#graph, variable.id)+ }++ createVariableCollection(name: string): FigmaVariableCollection {+ return new FigmaVariableCollection(this.#graph, this.#graph.createCollection(name).id)+ }++ createVariableAlias(variable: { readonly id: string }): FigmaVariableAlias {+ return variableAlias(variable.id)+ }++ async createVariableAliasByIdAsync(variableId: string): Promise<FigmaVariableAlias> {+ if (!this.#graph.variables.has(variableId)) {+ throw new Error('in createVariableAliasByIdAsync: Variable not found')+ }+ return variableAlias(variableId)+ }++ /**+ * A copy of `paint` whose colour is bound to `variable`, or unbound for `null`; it binds when the+ * paint is set on a layer. Colour is the one paint field Figma binds.+ */+ setBoundVariableForPaint<T extends FigmaSolidPaint>(+ paint: T,+ _field: 'color',+ variable: { readonly id: string } | null+ ): T & { boundVariables: { color?: FigmaVariableAlias } } {+ const { color: _previous, ...others } = paint.boundVariables ?? {}+ if (variable === null) return { ...structuredClone(paint), boundVariables: others }+ if (this.#graph.variables.get(variable.id)?.type !== 'COLOR') {+ throw new Error('in setBoundVariableForPaint: can only bind color variables to color')+ }+ return {+ ...structuredClone(paint),+ boundVariables: { ...others, color: variableAlias(variable.id) }+ }+ }+}diff --git a/packages/core/src/figma-api/variables/values.ts b/packages/core/src/figma-api/variables/values.tsnew file mode 100644index 000000000..44b233a7d--- /dev/null+++ b/packages/core/src/figma-api/variables/values.ts@@ -0,0 +1,165 @@+import {+ variableValueReferences,+ type Color,+ type SceneGraph,+ type Variable,+ type VariableLiteral,+ type VariableType,+ type VariableValue+} from '@open-pencil/scene-graph'++/** A reference to a variable, as Figma's plugin API writes one. */+export interface FigmaVariableAlias {+ type: 'VARIABLE_ALIAS'+ id: string+}++/** A colour from a colour variable and an opacity percentage, either of them a reference. */+export type FigmaComposedColor =+ | { color: Color | Omit<Color, 'a'>; opacity: FigmaVariableAlias }+ | { color: FigmaVariableAlias; opacity: number | FigmaVariableAlias }++/** A mode's value as Figma's plugin API reads and writes it. */+export type FigmaVariableValue =+ | boolean+ | string+ | number+ | Color+ | Omit<Color, 'a'>+ | FigmaVariableAlias+ | FigmaComposedColor++export function variableAlias(id: string): FigmaVariableAlias {+ return { type: 'VARIABLE_ALIAS', id }+}++/** The values `figma.variables.createVariable` starts every mode with, as Figma does. */+export const FIGMA_DEFAULT_VALUES: Record<VariableType, VariableLiteral> = {+ FLOAT: 0,+ STRING: 'String value',+ BOOLEAN: false,+ COLOR: { r: 1, g: 1, b: 1, a: 1 }+}++function isAlias(value: unknown): value is FigmaVariableAlias {+ if (typeof value !== 'object' || value === null) return false+ return (+ Reflect.get(value, 'type') === 'VARIABLE_ALIAS' && typeof Reflect.get(value, 'id') === 'string'+ )+}++/** A colour as Figma's plugin API takes it, RGB with an optional alpha. */+type FigmaColorInput = Omit<Color, 'a'> & Partial<Pick<Color, 'a'>>++function isColor(value: unknown): value is FigmaColorInput {+ if (typeof value !== 'object' || value === null) return false+ const channels = ['r', 'g', 'b'].map((key) => Reflect.get(value, key))+ const alpha: unknown = Reflect.get(value, 'a')+ return (+ channels.every((channel) => typeof channel === 'number') &&+ (alpha === undefined || typeof alpha === 'number')+ )+}++function storedColor(color: FigmaColorInput): Color {+ return { r: color.r, g: color.g, b: color.b, a: color.a ?? 1 }+}++function literal(value: VariableLiteral): FigmaVariableValue {+ return typeof value === 'object' ? { ...value } : value+}++/**+ * A mode's value as Figma's plugin API reads it. A colour expression reads as Figma's composed+ * colour; a formula reads as what it resolves to in that mode.+ */+export function figmaVariableValue(+ graph: SceneGraph,+ variable: Variable,+ modeId: string+): FigmaVariableValue {+ const value = variable.valuesByMode[modeId]+ if (typeof value !== 'object') return value+ if ('aliasId' in value) return variableAlias(value.aliasId)+ if ('expression' in value) {+ if (value.expression === 'COMPOSE_COLOR') {+ const ref = (part: Color | number | { aliasId: string }) =>+ typeof part === 'object' && 'aliasId' in part ? variableAlias(part.aliasId) : literal(part)+ return { color: ref(value.color), opacity: ref(value.opacity) } as FigmaComposedColor+ }+ const resolved = graph.resolveVariable(variable.id, modeId)+ return resolved === undefined ? FIGMA_DEFAULT_VALUES[variable.type] : literal(resolved)+ }+ return literal(value)+}++/** Whether a variable reads `id`, directly or through the variables it reads. */+function readsVariable(graph: SceneGraph, from: string, id: string): boolean {+ const seen = new Set<string>()+ const pending = [from]+ for (let next = pending.pop(); next !== undefined; next = pending.pop()) {+ if (next === id) return true+ if (seen.has(next)) continue+ seen.add(next)+ const variable = graph.variables.get(next)+ if (!variable) continue+ for (const value of Object.values(variable.valuesByMode)) {+ pending.push(...variableValueReferences(value))+ }+ }+ return false+}++/** A composed colour's part as the document stores it: a reference, a colour, or a number. */+function storedPart(input: unknown): Color | number | { aliasId: string } | undefined {+ if (isAlias(input)) return { aliasId: input.id }+ if (isColor(input)) return storedColor(input)+ return typeof input === 'number' ? input : undefined+}++/** A colour variable's value: a colour, or Figma's composed colour from its two parts. */+function storedColorValue(value: unknown): VariableValue | undefined {+ if (isColor(value)) return storedColor(value)+ if (typeof value !== 'object' || value === null) return undefined+ if (!('color' in value) || !('opacity' in value)) return undefined+ const color = storedPart(value.color)+ const opacity = storedPart(value.opacity)+ if (color === undefined || typeof color === 'number') return undefined+ if (opacity === undefined || (typeof opacity === 'object' && !('aliasId' in opacity)))+ return undefined+ return { expression: 'COMPOSE_COLOR', color, opacity }+}++/**+ * The value `setValueForMode` stores, or `null` for a reference Figma ignores: one that would make+ * the variable read itself. Throws Figma's messages for a value of the wrong type.+ */+export function storedVariableValue(+ graph: SceneGraph,+ variable: Variable,+ modeId: string,+ value: unknown+): VariableValue | null {+ const mismatch = () =>+ new TypeError(`in setValueForMode: Mismatched variable resolved type for mode ${modeId}`)+ if (!(modeId in variable.valuesByMode)) {+ throw new Error(`in setValueForMode: mode with id ${modeId} not defined for variable`)+ }+ if (isAlias(value)) {+ const target = graph.variables.get(value.id)+ if (!target) throw new Error('in setValueForMode: Variable not found')+ if (target.type !== variable.type) throw mismatch()+ return readsVariable(graph, target.id, variable.id) ? null : { aliasId: target.id }+ }+ if (typeof value === 'number' && !Number.isFinite(value)) {+ throw new TypeError('in setValueForMode: Property "newValue" failed validation')+ }+ if (variable.type === 'COLOR') {+ const color = storedColorValue(value)+ if (color === undefined) throw mismatch()+ return color+ }+ const expected = { FLOAT: 'number', STRING: 'string', BOOLEAN: 'boolean' }[variable.type]+ if (typeof value !== expected) throw mismatch()+ return value as VariableLiteral+}diff --git a/packages/core/src/figma-api/variables/variable.ts b/packages/core/src/figma-api/variables/variable.tsnew file mode 100644index 000000000..9be1c187a--- /dev/null+++ b/packages/core/src/figma-api/variables/variable.ts@@ -0,0 +1,286 @@+import { uniq } from 'es-toolkit/array'++import {+ updateTokenExpression,+ VARIABLE_SCOPES,+ type CodeSyntaxPlatform,+ type SceneGraph,+ type Variable,+ type VariableCollection,+ type VariableScope,+ type VariableType,+ type VariableValue+} from '@open-pencil/scene-graph'++import { reconcileVariableLayouts } from '#core/layout/variables'++import { figmaVariableValue, storedVariableValue, type FigmaVariableValue } from './values'++/** Scopes as Figma's plugin API names them; the file calls a stroke colour scope `STROKE`. */+export type FigmaVariableScope =+ | Exclude<VariableScope, 'STROKE' | 'FONT_VARIATIONS' | 'TRANSFORM'>+ | 'STROKE_COLOR'++/** The plugin API lists no font variation or transform scope, so those stay unread. */+function figmaScope(scope: VariableScope): FigmaVariableScope[] {+ if (scope === 'STROKE') return ['STROKE_COLOR']+ if (scope === 'FONT_VARIATIONS' || scope === 'TRANSFORM') return []+ return [scope]+}++function documentScope(scope: FigmaVariableScope): VariableScope {+ if (scope === 'STROKE_COLOR') return 'STROKE'+ if (!(VARIABLE_SCOPES as readonly string[]).includes(scope)) {+ throw new Error(`in set_scopes: OpenPencil does not support the ${scope as string} scope`)+ }+ return scope+}++/** Figma refuses empty names and names with `.`, `{` or `}`, which its references reserve. */+const RESERVED_NAME_CHARACTERS = /[.{}]/++/** Figma's checks for a variable name: not empty, not reserved, not taken in the collection. */+export function assertVariableName(+ graph: SceneGraph,+ method: string,+ name: string,+ collectionId: string,+ self?: string+): void {+ if (name === '') throw new Error(`in ${method}: name cannot be empty`)+ if (RESERVED_NAME_CHARACTERS.test(name)) throw new Error(`in ${method}: invalid variable name`)+ const taken = graph.variableCollections+ .get(collectionId)+ ?.variableIds.some((id) => id !== self && graph.variables.get(id)?.name === name)+ if (taken) throw new Error(`in ${method}: duplicate variable name`)+}++/** Stores one mode's value and shows it on the layers that use the variable. */+export function writeVariableValue(+ graph: SceneGraph,+ variable: Variable,+ modeId: string,+ value: VariableValue+): void {+ variable.valuesByMode[modeId] = structuredClone(value)+ updateTokenExpression(variable, modeId, value)+ reconcileVariableLayouts(graph, { variables: [variable.id] })+}++/** A variable as Figma's plugin API hands it out, reading and writing the document's. */+export class FigmaVariable {+ readonly id: string+ readonly remote = false+ readonly #graph: SceneGraph++ constructor(graph: SceneGraph, id: string) {+ this.#graph = graph+ this.id = id+ }++ get #variable(): Variable {+ const variable = this.#graph.variables.get(this.id)+ if (!variable) throw new Error(`Variable ${this.id} has been removed`)+ return variable+ }++ get name(): string {+ return this.#variable.name+ }++ set name(name: string) {+ const variable = this.#variable+ assertVariableName(this.#graph, 'set_name', name, variable.collectionId, variable.id)+ variable.name = name+ }++ get description(): string {+ return this.#variable.description+ }++ set description(description: string) {+ this.#variable.description = description+ }++ get hiddenFromPublishing(): boolean {+ return this.#variable.hiddenFromPublishing+ }++ set hiddenFromPublishing(hidden: boolean) {+ this.#variable.hiddenFromPublishing = hidden+ }++ get variableCollectionId(): string {+ return this.#variable.collectionId+ }++ get key(): string {+ return this.#variable.key ?? ''+ }++ get resolvedType(): VariableType {+ return this.#variable.type+ }++ get valuesByMode(): Record<string, FigmaVariableValue> {+ const variable = this.#variable+ return Object.fromEntries(+ Object.keys(variable.valuesByMode).map((modeId) => [+ modeId,+ figmaVariableValue(this.#graph, variable, modeId)+ ])+ )+ }++ get scopes(): FigmaVariableScope[] {+ return (this.#variable.scopes ?? ['ALL_SCOPES']).flatMap(figmaScope)+ }++ /** Scopes the plugin API cannot name stay, as the script never saw them. */+ set scopes(scopes: FigmaVariableScope[]) {+ const variable = this.#variable+ if (scopes.includes('ALL_SCOPES')) {+ delete variable.scopes+ return+ }+ const unnamed = (variable.scopes ?? []).filter((scope) => figmaScope(scope).length === 0)+ variable.scopes = uniq([...scopes.map(documentScope), ...unnamed])+ }++ get codeSyntax(): Partial<Record<CodeSyntaxPlatform, string>> {+ return { ...this.#variable.codeSyntax }+ }++ setVariableCodeSyntax(platform: CodeSyntaxPlatform, value: string): void {+ const variable = this.#variable+ variable.codeSyntax = { ...variable.codeSyntax, [platform]: value }+ }++ removeVariableCodeSyntax(platform: CodeSyntaxPlatform): void {+ const variable = this.#variable+ const { [platform]: _removed, ...rest } = variable.codeSyntax ?? {}+ variable.codeSyntax = rest+ }++ /** Sets one mode's value; a reference that would make the variable read itself is ignored. */+ setValueForMode(modeId: string, newValue: FigmaVariableValue): void {+ const variable = this.#variable+ const value = storedVariableValue(this.#graph, variable, modeId, newValue)+ if (value !== null) writeVariableValue(this.#graph, variable, modeId, value)+ }++ /** The value the variable gives `consumer`, in the modes that layer resolves. */+ resolveForConsumer(consumer: { readonly id: string }): {+ value: FigmaVariableValue+ resolvedType: VariableType+ } {+ const variable = this.#variable+ const value = this.#graph.resolveVariableForNode(consumer.id, variable.id)+ if (value !== undefined) {+ return {+ value: typeof value === 'object' ? { ...value } : value,+ resolvedType: variable.type+ }+ }+ const modeId = this.#graph.getNodeVariableModeId(consumer.id, variable.collectionId)+ return { value: figmaVariableValue(this.#graph, variable, modeId), resolvedType: variable.type }+ }++ remove(): void {+ this.#graph.removeVariable(this.#variable.id)+ }++ toJSON() {+ return {+ id: this.id,+ name: this.name,+ resolvedType: this.resolvedType,+ variableCollectionId: this.variableCollectionId,+ valuesByMode: this.valuesByMode+ }+ }+}++/** A variable collection as Figma's plugin API hands it out. */+export class FigmaVariableCollection {+ readonly id: string+ readonly remote = false+ readonly isExtension = false+ readonly #graph: SceneGraph++ constructor(graph: SceneGraph, id: string) {+ this.#graph = graph+ this.id = id+ }++ get #collection(): VariableCollection {+ const collection = this.#graph.variableCollections.get(this.id)+ if (!collection) throw new Error(`Variable collection ${this.id} has been removed`)+ return collection+ }++ get name(): string {+ return this.#collection.name+ }++ set name(name: string) {+ this.#collection.name = name+ }++ get hiddenFromPublishing(): boolean {+ return false+ }++ get modes(): Array<{ modeId: string; name: string }> {+ return this.#collection.modes.map(({ modeId, name }) => ({ modeId, name }))+ }++ get defaultModeId(): string {+ return this.#collection.defaultModeId+ }++ get variableIds(): string[] {+ return [...this.#collection.variableIds]+ }++ get key(): string {+ return this.#collection.key ?? ''+ }++ /** Adds a mode that starts with every variable's default-mode value, as Figma does. */+ addMode(name: string): string {+ const modeId = this.#graph.createMode(this.#collection.id, name)+ if (modeId === undefined) throw new Error('in addMode: Could not find variable collection')+ return modeId+ }++ renameMode(modeId: string, newName: string): void {+ const collection = this.#collection+ if (!collection.modes.some((mode) => mode.modeId === modeId))+ throw new Error('in renameMode: Could not find mode')+ this.#graph.renameMode(collection.id, modeId, newName)+ }++ /** Removes a mode; removing the default makes the next mode the default, as in Figma. */+ removeMode(modeId: string): void {+ const collection = this.#collection+ if (!collection.modes.some((mode) => mode.modeId === modeId))+ throw new Error('in removeMode: Could not find mode')+ this.#graph.removeMode(collection.id, modeId)+ reconcileVariableLayouts(this.#graph, { variables: collection.variableIds })+ }++ remove(): void {+ this.#graph.removeCollection(this.#collection.id)+ }++ toJSON() {+ return {+ id: this.id,+ name: this.name,+ modes: this.modes,+ defaultModeId: this.defaultModeId,+ variableIds: this.variableIds+ }+ }+}diff --git a/packages/core/src/figma-api/variants.ts b/packages/core/src/figma-api/variants.tsnew file mode 100644index 000000000..67d1608f1--- /dev/null+++ b/packages/core/src/figma-api/variants.ts@@ -0,0 +1,170 @@+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { parseVariantName } from '@open-pencil/scene-graph/variant-name'++import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'+import { applyVariantProperties, variantSetProps } from '#core/editor/components/variant-set'+import {+ appendPropertyDefinition,+ renameProperty+} from '#core/editor/components/variants/definitions'+import { refreshVariantOptions, setVariantValues } from '#core/editor/components/variants/history'+import {+ findExactVariant,+ getComponentSet,+ getVariantDefinitions,+ variantValues+} from '#core/editor/components/variants/model'+import { wrapNodes } from '#core/editor/structure/container-wrap'++// Variant edits through the Plugin API run the panel's own edits, with Figma's messages. Figma+// accepts renames that break a set (an axis named as another or left empty); those are refused.++interface VariantValue {+ definition: ComponentPropertyDefinition+ value: string | boolean+}++function requireDistinctComponents(graph: SceneGraph, nodeIds: ReadonlyArray<string>): SceneNode[] {+ if (nodeIds.length === 0) throw new Error('Need at least 1 component to combine as variants')+ if (new Set(nodeIds).size !== nodeIds.length) {+ throw new Error('combineAsVariants requires distinct COMPONENT nodes')+ }++ const nodes = nodeIds.map((id) => graph.getNode(id))+ if (!nodes.every((node): node is SceneNode => node?.type === 'COMPONENT')) {+ throw new Error('combineAsVariants requires COMPONENT nodes')+ }+ return nodes+}++export function combineComponentsAsVariants(+ graph: SceneGraph,+ nodeIds: ReadonlyArray<string>,+ parentId: string,+ index?: number+): SceneNode {+ const components = requireDistinctComponents(graph, nodeIds)+ const parent = graph.getNode(parentId)+ if (!parent) throw new Error('Parent node not found')++ // The plugin API wraps the variants exactly; see `variantSetProps`.+ const componentSet = wrapNodes(+ graph,+ 'COMPONENT_SET',+ components,+ parentId,+ index,+ variantSetProps(graph, components, parentId, 'script')+ )+ applyVariantProperties(graph, components, componentSet.id)++ return componentSet+}++/**+ * Switches an instance to the variant with the given values, the rest kept, as Figma's+ * `setProperties` does; a combination no variant has fails without changing anything.+ */+export function switchVariant(+ scene: SceneGraph,+ instance: SceneNode,+ values: VariantValue[]+): void {+ const component = instance.componentId ? scene.getNode(instance.componentId) : undefined+ const setId = component?.parentId+ const target =+ component && setId && getComponentSet(scene, setId)+ ? findExactVariant(scene, setId, {+ ...variantValues(scene, setId, component),+ ...Object.fromEntries(+ values.map(({ definition, value }) => [definition.name, String(value)])+ )+ })+ : undefined+ if (!target)+ throw new Error('in setProperties: Unable to find a variant with those property values')+ if (target.id === instance.componentId) return+ scene.swapInstanceComponent(instance.id, target.id)+ reapplyInstanceComponentProperties({ graph: scene }, instance.id)+}++function assertAxisNameFree(set: SceneNode, method: string, name: string, self?: string): void {+ const taken = set.componentPropertyDefinitions.some(+ (definition) =>+ definition.id !== self && definition.type === 'VARIANT' && definition.name === name+ )+ if (taken) throw new Error(`in ${method}: Node already has a variant property with name ${name}`)+}++/** Adds a variant axis to a set, appending its value to every variant's name, as Figma does. */+export function addVariantAxis(+ scene: SceneGraph,+ node: SceneNode,+ name: string,+ defaultValue: string+): ComponentPropertyDefinition {+ if (node.type !== 'COMPONENT_SET')+ throw new Error('in addComponentProperty: Can only add variant property to a component set')+ if (defaultValue.trim() === '')+ throw new Error('in addComponentProperty: Component property default value cannot be empty')+ assertAxisNameFree(node, 'addComponentProperty', name)+ const id = appendPropertyDefinition(scene, node.id, name, 'VARIANT', defaultValue.trim())+ const definition = getVariantDefinitions(scene, node.id).find((item) => item.id === id)+ if (!definition) throw new Error(`in addComponentProperty: Could not add ${name}`)+ return definition+}++/**+ * Edits a variant axis: a new name renames it in every variant's name, which instances follow,+ * as Figma does. Its default comes from the default variant, so it cannot be set.+ */+export function editVariantAxis(+ scene: SceneGraph,+ node: SceneNode,+ definition: ComponentPropertyDefinition,+ changes: { name?: string; defaultValue?: string | boolean }+): string {+ if (changes.defaultValue !== undefined)+ throw new Error('in editComponentProperty: Cannot change defaultValue of a variant property')+ const name = changes.name?.trim()+ if (name === undefined) return definition.name+ if (name === '') throw new Error('Property name must not be empty')+ assertAxisNameFree(node, 'editComponentProperty', name, definition.id)+ if (name !== definition.name) renameProperty(scene, node.id, definition.id, name)+ return name+}++/**+ * A variant's values, or an instance's of one, by axis in the set's order; null for anything+ * that is not a variant.+ */+export function variantPropertiesOf(+ scene: SceneGraph,+ node: SceneNode+): Record<string, string> | null {+ const variant =+ node.type === 'INSTANCE' && node.componentId ? scene.getNode(node.componentId) : node+ const setId = variant?.type === 'COMPONENT' ? variant.parentId : undefined+ if (!variant || !setId || !getComponentSet(scene, setId)) return null+ return variantValues(scene, setId, variant)+}++/**+ * Takes a renamed variant's values from its name, as Figma does, and lets the set's value lists+ * follow: values no variant uses drop out. A name that does not name exactly the set's axes,+ * or names another variant's values, changes no values, as Figma leaves such a set in error.+ */+export function syncVariantName(scene: SceneGraph, node: SceneNode): void {+ const setId = node.type === 'COMPONENT' ? node.parentId : undefined+ if (!setId || !getComponentSet(scene, setId)) return+ const axes = getVariantDefinitions(scene, setId).map((definition) => definition.name)+ const parsed = parseVariantName(node.name)+ const names = Object.keys(parsed)+ if (names.length !== axes.length || !axes.every((axis) => parsed[axis]?.trim())) return+ const values = { ...node.componentPropertyValues, ...parsed }+ // Values another variant has already leave the set in error in Figma; these stay too.+ const twin = findExactVariant(scene, setId, values)+ if (twin && twin.id !== node.id) return+ setVariantValues(scene, setId, node.id, values)+ refreshVariantOptions(scene, setId, { dropUnused: true })+}diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.tsindex 80f31d5e8..5cd1c3571 100644--- a/packages/core/src/openpencil-api/index.ts+++ b/packages/core/src/openpencil-api/index.ts@@ -6,12 +6,17 @@ import {type BehaviourSpec,type VariableLiteral} from '@open-pencil/scene-graph'+import type { OkHCLColor, OkHCLPayload } from '@open-pencil/scene-graph/color'-import type { FigmaAPI } from '#core/figma-api/index'+import { exposeInstanceSwap } from '#core/figma-api/components'+import type { FigmaAPI, FigmaNodeProxy } from '#core/figma-api/index'+import { writeVariableValue } from '#core/figma-api/variables'+import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'import {getBehaviour,makeSlot,+ nodeOf,setBehaviour,type BehaviourHandle,type NodeRef@@ -24,6 +29,16 @@ import {type CommentHandle,type NewComment} from './comments'+import {+ readFillOkHCL,+ readLayoutDirection,+ readStrokeOkHCL,+ readTextDirection,+ writeFillOkHCL,+ writeLayoutDirection,+ writeStrokeOkHCL,+ writeTextDirection+} from './nodes'import { getStatus, listStatuses, setStatus, type StatusInfo } from './statuses'import { bindVariable, unbindVariable, type VariableRef } from './variables'@@ -77,12 +92,12 @@ export class OpenPencilAPI {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)+ writeVariableValue(graph, variable, mode.modeId, value)return resolved}/**- * Bind a layer field to a variable from `figma.getLocalVariables()`, as the layer panel does:+ * Bind a layer field to a variable from `figma.variables`, as the layer panel does:* fields by OpenPencil's names, such as `'text'`, `'visible'`, `'opacity'` or `'fills/0/color'`.* Text content takes a text or number variable, a number shown as text; visibility takes a* boolean, or text that shows the layer unless it is empty or reads false, no or off.@@ -160,4 +175,68 @@ export class OpenPencilAPI {setStatus(node: NodeRef, status: string | null): void {setStatus(this.figma.graph, node, status)}++ /**+ * Expose a swap on instances as one INSTANCE_SWAP property, offering the candidate components;+ * returns the layer that holds the property.+ */+ exposeInstanceSwap(+ instances: readonly NodeRef[],+ candidates: readonly NodeRef[],+ propertyName = 'Instance'+ ): FigmaNodeProxy {+ const proxies = (refs: readonly NodeRef[]) =>+ refs.map((ref) => this.figma.wrapNode(nodeOf(this.figma.graph, ref).id))+ const host = exposeInstanceSwap(+ this.figma.graph,+ proxies(instances),+ proxies(candidates),+ propertyName+ )+ return this.figma.wrapNode(host.id)+ }++ /**+ * Whether the current page's fonts are faithfully available: requested faces, where each+ * loaded from, substitutions, why an installed face could not load, and the layers affected.+ */+ getFontStatus(): DocumentFontStatus {+ return documentFontStatus(this.figma.graph, this.figma.currentPageId)+ }++ /** A fill's OkHCL color, which the color picker keeps beside its RGB, or null. */+ getFillOkHCL(node: NodeRef, index = 0): OkHCLPayload | null {+ return readFillOkHCL(this.figma.graph, node, index)+ }++ /** Set a fill's color in OkHCL; its RGB follows in the document's color space. */+ setFillOkHCL(node: NodeRef, color: OkHCLColor, index = 0): void {+ writeFillOkHCL(this.figma.graph, node, color, index)+ }++ getStrokeOkHCL(node: NodeRef, index = 0): OkHCLPayload | null {+ return readStrokeOkHCL(this.figma.graph, node, index)+ }++ setStrokeOkHCL(node: NodeRef, color: OkHCLColor, index = 0): void {+ writeStrokeOkHCL(this.figma.graph, node, color, index)+ }++ /** Which way a frame's auto layout runs: `AUTO`, `LTR` or `RTL`. */+ getLayoutDirection(node: NodeRef): string {+ return readLayoutDirection(this.figma.graph, node)+ }++ setLayoutDirection(node: NodeRef, direction: string): void {+ writeLayoutDirection(this.figma.graph, node, direction)+ }++ /** Which way a text runs: `AUTO`, `LTR` or `RTL`. */+ getTextDirection(node: NodeRef): string {+ return readTextDirection(this.figma.graph, node)+ }++ setTextDirection(node: NodeRef, direction: string): void {+ writeTextDirection(this.figma.graph, node, direction)+ }}diff --git a/packages/core/src/openpencil-api/nodes.ts b/packages/core/src/openpencil-api/nodes.tsnew file mode 100644index 000000000..45f4e2f2c--- /dev/null+++ b/packages/core/src/openpencil-api/nodes.ts@@ -0,0 +1,89 @@+import { isEqual } from 'es-toolkit/predicate'++import {+ recordInstanceOverride,+ type LayoutDirection,+ type SceneGraph,+ type SceneNode,+ type TextDirection+} from '@open-pencil/scene-graph'+import {+ getFillOkHCL,+ getStrokeOkHCL,+ setNodeFillOkHCL,+ setNodeStrokeOkHCL,+ type OkHCLColor,+ type OkHCLPayload+} from '@open-pencil/scene-graph/color'++import { assertNodeEditable } from '#core/editor/capabilities'++import { nodeOf, type NodeRef } from './behaviours'++const DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const++/** Writes a layer's fields as a script edit does: an instance's layer claims what changed. */+function editNode(graph: SceneGraph, node: SceneNode, changes: Partial<SceneNode>): void {+ assertNodeEditable(graph, node.id)+ const changed = Object.keys(changes).filter(+ (key) => !isEqual(Reflect.get(changes, key), Reflect.get(node, key))+ )+ graph.updateNode(node.id, changes)+ recordInstanceOverride(graph, node.id, changed)+}++function direction(value: string): LayoutDirection & TextDirection {+ if (!(DIRECTIONS as readonly string[]).includes(value))+ throw new Error(`Unknown direction ${value}; use ${DIRECTIONS.join(', ')}`)+ return value as LayoutDirection & TextDirection+}++export function readFillOkHCL(graph: SceneGraph, ref: NodeRef, index: number): OkHCLPayload | null {+ return getFillOkHCL(nodeOf(graph, ref), index)+}++export function writeFillOkHCL(+ graph: SceneGraph,+ ref: NodeRef,+ color: OkHCLColor,+ index: number+): void {+ const node = nodeOf(graph, ref)+ editNode(graph, node, setNodeFillOkHCL(node, index, color, graph.documentColorSpace))+}++export function readStrokeOkHCL(+ graph: SceneGraph,+ ref: NodeRef,+ index: number+): OkHCLPayload | null {+ return getStrokeOkHCL(nodeOf(graph, ref), index)+}++export function writeStrokeOkHCL(+ graph: SceneGraph,+ ref: NodeRef,+ color: OkHCLColor,+ index: number+): void {+ const node = nodeOf(graph, ref)+ editNode(graph, node, setNodeStrokeOkHCL(node, index, color, graph.documentColorSpace))+}++/** A frame's auto layout direction; a layer saved without one reads `AUTO`. */+export function readLayoutDirection(graph: SceneGraph, ref: NodeRef): LayoutDirection {+ const node = nodeOf(graph, ref)+ return Object.hasOwn(node, 'layoutDirection') ? node.layoutDirection : 'AUTO'+}++export function writeLayoutDirection(graph: SceneGraph, ref: NodeRef, value: string): void {+ editNode(graph, nodeOf(graph, ref), { layoutDirection: direction(value) })+}++export function readTextDirection(graph: SceneGraph, ref: NodeRef): TextDirection {+ return nodeOf(graph, ref).textDirection+}++export function writeTextDirection(graph: SceneGraph, ref: NodeRef, value: string): void {+ editNode(graph, nodeOf(graph, ref), { textDirection: direction(value) })+}diff --git a/packages/core/src/openpencil-api/variables.ts b/packages/core/src/openpencil-api/variables.tsindex cc597a481..d7b402a76 100644--- a/packages/core/src/openpencil-api/variables.ts+++ b/packages/core/src/openpencil-api/variables.ts@@ -1,10 +1,12 @@-import type { SceneGraph } from '@open-pencil/scene-graph'+import { resolvedPaintBindings, type SceneGraph } from '@open-pencil/scene-graph'import { reconcileVariableLayouts } from '#core/layout/variables'import { nodeOf, type NodeRef } from './behaviours'-/** A variable as `figma` hands it out, such as from `figma.getLocalVariables()`. */+const PAINT_FIELD = /^(fills|strokes)\/\d+\/color$/++/** A variable as `figma` hands it out, such as from `figma.variables.getLocalVariables()`. */export type VariableRef = { readonly id: string }function variableOf(graph: SceneGraph, ref: VariableRef) {@@ -33,6 +35,8 @@ export function unbindVariable(graph: SceneGraph, node: NodeRef, field: string):const target = nodeOf(graph, node)if (!(field in target.boundVariables))throw new Error(`${target.name} has no variable bound to ${field}`)+ // A paint keeps the color its variable last gave it, as values do and as Figma's detach does.+ if (PAINT_FIELD.test(field)) graph.updateNode(target.id, resolvedPaintBindings(graph, target))graph.unbindVariable(target.id, field)reconcileVariableLayouts(graph, { subtrees: [target.id] })}diff --git a/packages/core/src/tools/analyze/eval/index.ts b/packages/core/src/tools/analyze/eval/index.tsindex 32a94c117..fd7ec841a 100644--- a/packages/core/src/tools/analyze/eval/index.ts+++ b/packages/core/src/tools/analyze/eval/index.ts@@ -7,7 +7,7 @@ import { compileScript } from './wrap'export const evalCode = defineTool({name: 'eval',description:- 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`), slots (`openpencil.createSlot`), comments (`openpencil.getComments`, `openpencil.getComment`, `openpencil.addComment`, and each comment’s `reply` and `resolve`), statuses (`openpencil.statuses`, `openpencil.getStatus`, `openpencil.setStatus`), and variable bindings (`openpencil.bindVariable(node, field, variable)`, `openpencil.unbindVariable(node, field)`).',+ 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`), slots (`openpencil.createSlot`), comments (`openpencil.getComments`, `openpencil.getComment`, `openpencil.addComment`, and each comment’s `reply` and `resolve`), statuses (`openpencil.statuses`, `openpencil.getStatus`, `openpencil.setStatus`), variable bindings as the layer panel makes them (`openpencil.bindVariable(node, field, variable)`, `openpencil.unbindVariable(node, field)`), layout and text direction (`openpencil.getLayoutDirection`, `setLayoutDirection`, `getTextDirection`, `setTextDirection`), OkHCL paint colors (`openpencil.getFillOkHCL`, `setFillOkHCL`, `getStrokeOkHCL`, `setStrokeOkHCL`), `openpencil.exposeInstanceSwap(instances, candidates, name)`, and `openpencil.getFontStatus()`.',execution: { kind: 'async', mutation: 'document' },capabilities: ['document:read', 'document:write', 'code:execute'],availability: 'eval',diff --git a/packages/core/src/tools/create/components.ts b/packages/core/src/tools/create/components.tsindex 7fe2a4734..24e0f6072 100644--- a/packages/core/src/tools/create/components.ts+++ b/packages/core/src/tools/create/components.ts@@ -1,6 +1,7 @@import * as v from 'valibot'import type { FigmaComponentNode, FigmaNodeProxy } from '#core/figma-api'+import { OpenPencilAPI } from '#core/openpencil-api'import { toolNumber } from '#core/tools/input'import { defineTool, nodeSummary, requireNodes } from '#core/tools/schema'@@ -97,7 +98,9 @@ export const exposeInstanceSwap = defineTool({if (candidates.length !== candidate_ids.length)return { error: 'One or more candidate IDs were not found' }try {- return nodeSummary(figma.exposeInstanceSwap(slots, candidates, property_name))+ return nodeSummary(+ new OpenPencilAPI(figma).exposeInstanceSwap(slots, candidates, property_name)+ )} catch (error) {return { error: error instanceof Error ? error.message : String(error) }}diff --git a/packages/core/src/tools/modify/layout.ts b/packages/core/src/tools/modify/layout.tsindex f8e8fe72f..50a67a693 100644--- a/packages/core/src/tools/modify/layout.ts+++ b/packages/core/src/tools/modify/layout.ts@@ -1,7 +1,6 @@import * as v from 'valibot'-import type { SceneNode } from '@open-pencil/scene-graph'-+import { OpenPencilAPI } from '#core/openpencil-api'import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound } from '#core/tools/schema'@@ -82,7 +81,7 @@ export const setLayout = defineTool({if (args.align !== undefined) node.primaryAxisAlignItems = args.alignif (args.counter_align !== undefined) node.counterAxisAlignItems = args.counter_alignif (args.flow_direction !== undefined)- node.layoutDirection = args.flow_direction as SceneNode['layoutDirection']+ new OpenPencilAPI(figma).setLayoutDirection(node, args.flow_direction)if (args.padding !== undefined) {node.paddingTop = args.paddingdiff --git a/packages/core/src/tools/modify/text.ts b/packages/core/src/tools/modify/text.tsindex f8a001914..dc04a6472 100644--- a/packages/core/src/tools/modify/text.ts+++ b/packages/core/src/tools/modify/text.ts@@ -1,8 +1,8 @@import * as v from 'valibot'-import type { SceneNode } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'+import { OpenPencilAPI } from '#core/openpencil-api'import { toolNumber, nodeIdInput } from '#core/tools/input'import { defineTool, nodeNotFound, toolFailure } from '#core/tools/schema'@@ -169,7 +169,7 @@ export const setTextProperties = defineTool({updated.push('textAutoResize')}if (args.direction !== undefined) {- node.textDirection = args.direction as SceneNode['textDirection']+ new OpenPencilAPI(figma).setTextDirection(node, args.direction)updated.push('textDirection')}if (args.text_decoration !== undefined) {diff --git a/packages/core/src/tools/read/fonts.ts b/packages/core/src/tools/read/fonts.tsindex af8c1ceba..c68d565a1 100644--- a/packages/core/src/tools/read/fonts.ts+++ b/packages/core/src/tools/read/fonts.ts@@ -1,6 +1,7 @@import { uniq } from 'es-toolkit/array'import * as v from 'valibot'+import { OpenPencilAPI } from '#core/openpencil-api'import { defineTool } from '#core/tools/schema'export const getFontStatus = defineTool({@@ -12,7 +13,7 @@ export const getFontStatus = defineTool({execution: { kind: 'sync', mutation: 'none' },exposure: { webmcp: false },input: v.strictObject({}),- execute: (figma) => figma.getFontStatus()+ execute: (figma) => new OpenPencilAPI(figma).getFontStatus()})export const listFonts = defineTool({diff --git a/packages/core/src/tools/structure/hierarchy.ts b/packages/core/src/tools/structure/hierarchy.tsindex a20be7b27..54e2afae8 100644--- a/packages/core/src/tools/structure/hierarchy.ts+++ b/packages/core/src/tools/structure/hierarchy.ts@@ -63,8 +63,9 @@ export const flattenNodes = defineTool({ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Node IDs to flatten'))}),execute: (figma, { ids }) => {- const result = figma.flattenNode(ids)- return nodeSummary(result)+ const nodes = requireNodes(figma, ids)+ if (!nodes) return { error: 'One or more node IDs were not found' }+ return nodeSummary(figma.flatten(nodes, nodes[0].parent ?? figma.currentPage))}})diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.tsindex 47b25d0e0..73e2f0f22 100644--- a/packages/core/src/tools/variables/bindings.ts+++ b/packages/core/src/tools/variables/bindings.ts@@ -31,7 +31,7 @@ export const bindVariable = defineTool({execute: (figma, args) => {const node = figma.getNodeById(args.node_id)if (!node) return { error: `Node "${args.node_id}" not found` }- const variable = figma.getVariableById(args.variable_id)+ const variable = figma.variables.getVariableById(args.variable_id)if (!variable) return { error: `Variable "${args.variable_id}" not found` }try {new OpenPencilAPI(figma).bindVariable(args.node_id, args.field, variable)diff --git a/packages/core/src/tools/variables/collections.ts b/packages/core/src/tools/variables/collections.tsindex 18bb45138..1dd18029d 100644--- a/packages/core/src/tools/variables/collections.ts+++ b/packages/core/src/tools/variables/collections.ts@@ -8,7 +8,7 @@ export const listCollections = defineTool({execution: { kind: 'sync', mutation: 'none' },input: v.strictObject({}),execute: (figma) => {- const collections = figma.getLocalVariableCollections()+ const collections = [...figma.graph.variableCollections.values()]return { count: collections.length, collections }}})@@ -22,7 +22,7 @@ export const getCollection = defineTool({id: v.pipe(v.string(), v.description('Collection ID'))}),execute: (figma, { id }) => {- const collection = figma.getVariableCollectionById(id)+ const collection = figma.graph.variableCollections.get(id)if (!collection) return { error: `Collection "${id}" not found` }return {...collection,@@ -40,7 +40,7 @@ export const createCollection = defineTool({name: v.pipe(v.string(), v.description('Collection name'))}),execute: (figma, { name }) => {- return figma.createVariableCollection(name)+ return figma.graph.variableCollections.get(figma.variables.createVariableCollection(name).id)}})@@ -53,7 +53,9 @@ export const deleteCollection = defineTool({id: v.pipe(v.string(), v.description('Collection ID'))}),execute: (figma, { id }) => {- figma.deleteVariableCollection(id)+ const collection = figma.variables.getVariableCollectionById(id)+ if (!collection) return { error: `Collection "${id}" not found` }+ collection.remove()return { deleted: id }}})diff --git a/packages/core/src/tools/variables/read.ts b/packages/core/src/tools/variables/read.tsindex a73084bd7..34572ec0a 100644--- a/packages/core/src/tools/variables/read.ts+++ b/packages/core/src/tools/variables/read.ts@@ -1,7 +1,18 @@import * as v from 'valibot'+import type { VariableType } from '@open-pencil/scene-graph'++import type { FigmaAPI } from '#core/figma-api'import { defineTool } from '#core/tools/schema'+/** The document's variables as tools report them, of one type or all. */+function documentVariables(figma: FigmaAPI, type?: VariableType) {+ return figma.variables.getLocalVariables(type).flatMap((variable) => {+ const record = figma.graph.variables.get(variable.id)+ return record ? [record] : []+ })+}+export const listVariables = defineTool({name: 'list_variables',description: 'List all design variables (colors, numbers, strings, booleans).',@@ -15,7 +26,7 @@ export const listVariables = defineTool({)}),execute: (figma, args) => {- const variables = figma.getLocalVariables(args.type)+ const variables = documentVariables(figma, args.type)return { count: variables.length, variables }}})@@ -28,7 +39,7 @@ export const getVariable = defineTool({id: v.pipe(v.string(), v.description('Variable ID'))}),execute: (figma, { id }) => {- const variable = figma.getVariableById(id)+ const variable = figma.graph.variables.get(id)if (!variable) return { error: `Variable "${id}" not found` }return variable}@@ -45,8 +56,7 @@ export const findVariables = defineTool({)}),execute: (figma, args) => {- let variables = figma.getLocalVariables(args.type)- variables = variables.filter((variable) =>+ const variables = documentVariables(figma, args.type).filter((variable) =>variable.name.toLowerCase().includes(args.query.toLowerCase()))return { count: variables.length, variables }diff --git a/packages/core/src/tools/variables/values.ts b/packages/core/src/tools/variables/values.tsindex fc39affbf..863968483 100644--- a/packages/core/src/tools/variables/values.ts+++ b/packages/core/src/tools/variables/values.ts@@ -1,11 +1,19 @@import * as v from 'valibot'-import type { VariableType, VariableValue } from '@open-pencil/scene-graph'+import type { Color, VariableType } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'+import type { FigmaVariableValue } from '#core/figma-api'import { defineTool } from '#core/tools/schema'-function parseVariableValue(type: VariableType, value: string): VariableValue {+/** A parsed value as `setValueForMode` takes it; a colour gets a copy of its own. */+function figmaValue(value: ToolValue): FigmaVariableValue {+ return typeof value === 'object' ? { ...value } : value+}++type ToolValue = Color | number | string | boolean++function parseVariableValue(type: VariableType, value: string): ToolValue {if (type === 'COLOR') return parseColor(value)if (type === 'FLOAT') return Number(value)if (type === 'BOOLEAN') return value === 'true'@@ -30,8 +38,16 @@ export const createVariable = defineTool({}),execute: (figma, args) => {const type = args.type as VariableType- const parsedValue = args.value === undefined ? undefined : parseVariableValue(type, args.value)- return figma.createVariable(args.name, type, args.collection_id, parsedValue)+ // The value is checked first, so a value the variable cannot hold creates nothing.+ const value = args.value === undefined ? undefined : parseVariableValue(type, args.value)+ if (typeof value === 'number' && !Number.isFinite(value))+ return { error: `"${args.value}" is not a number` }+ const variable = figma.variables.createVariable(args.name, args.collection_id, type)+ if (value !== undefined) {+ for (const modeId of Object.keys(variable.valuesByMode))+ variable.setValueForMode(modeId, figmaValue(value))+ }+ return figma.graph.variables.get(variable.id)}})@@ -46,10 +62,10 @@ export const setVariable = defineTool({value: v.pipe(v.string(), v.description('Value (hex for COLOR, number for FLOAT, etc.)'))}),execute: (figma, args) => {- const variable = figma.getVariableById(args.id)+ const variable = figma.variables.getVariableById(args.id)if (!variable) return { error: `Variable "${args.id}" not found` }- const parsedValue = parseVariableValue(variable.type, args.value)- figma.setVariableValue(args.id, args.mode, parsedValue)+ const parsedValue = parseVariableValue(variable.resolvedType, args.value)+ variable.setValueForMode(args.mode, figmaValue(parsedValue))return { id: args.id, mode: args.mode, value: parsedValue }}})@@ -63,7 +79,9 @@ export const deleteVariable = defineTool({id: v.pipe(v.string(), v.description('Variable ID'))}),execute: (figma, { id }) => {- figma.deleteVariable(id)+ const variable = figma.variables.getVariableById(id)+ if (!variable) return { error: `Variable "${id}" not found` }+ variable.remove()return { deleted: id }}})diff --git a/packages/core/src/tools/vector/boolean.ts b/packages/core/src/tools/vector/boolean.tsindex 43aff4368..1adaf8ce7 100644--- a/packages/core/src/tools/vector/boolean.ts+++ b/packages/core/src/tools/vector/boolean.ts@@ -1,6 +1,22 @@import * as v from 'valibot'-import { defineTool, nodeSummary } from '#core/tools/schema'+import type { FigmaAPI } from '#core/figma-api'+import { defineTool, nodeSummary, requireNodes, toolFailure } from '#core/tools/schema'++/** Combines the layers in the first one's parent, as Figma's boolean methods do. */+function booleanOf(+ figma: FigmaAPI,+ ids: readonly string[],+ operation: 'union' | 'subtract' | 'intersect' | 'exclude'+) {+ const nodes = requireNodes(figma, ids)+ if (!nodes) return { error: 'One or more node IDs were not found' }+ try {+ return nodeSummary(figma[operation](nodes, nodes[0].parent ?? figma.currentPage))+ } catch (error) {+ return toolFailure(error)+ }+}export const booleanUnion = defineTool({name: 'boolean_union',@@ -11,8 +27,7 @@ export const booleanUnion = defineTool({ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to union'))}),execute: (figma, { ids }) => {- const result = figma.booleanOperation('UNION', ids)- return nodeSummary(result)+ return booleanOf(figma, ids, 'union')}})@@ -25,8 +40,7 @@ export const booleanSubtract = defineTool({ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs (first minus rest)'))}),execute: (figma, { ids }) => {- const result = figma.booleanOperation('SUBTRACT', ids)- return nodeSummary(result)+ return booleanOf(figma, ids, 'subtract')}})@@ -39,8 +53,7 @@ export const booleanIntersect = defineTool({ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to intersect'))}),execute: (figma, { ids }) => {- const result = figma.booleanOperation('INTERSECT', ids)- return nodeSummary(result)+ return booleanOf(figma, ids, 'intersect')}})@@ -53,7 +66,6 @@ export const booleanExclude = defineTool({ids: v.pipe(v.array(v.string()), v.minLength(2), v.description('Node IDs to exclude'))}),execute: (figma, { ids }) => {- const result = figma.booleanOperation('EXCLUDE', ids)- return nodeSummary(result)+ return booleanOf(figma, ids, 'exclude')}})diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.tsindex 970bba53d..af2eea5d5 100644--- a/packages/core/tests/editor/history/atomic-tools.test.ts+++ b/packages/core/tests/editor/history/atomic-tools.test.ts@@ -66,13 +66,9 @@ describe('atomic agent tools', () => {test('variable values and bound nodes are undoable across pages', () => {const { figma, editor, undo, rectangle, tool } = setup()- const collection = figma.createVariableCollection('Colors')- const variable = figma.createVariable('Brand', 'COLOR', collection.id, {- r: 1,- g: 0,- b: 0,- a: 1- })+ const collection = figma.variables.createVariableCollection('Colors')+ const variable = figma.variables.createVariable('Brand', collection, 'COLOR')+ variable.setValueForMode(collection.defaultModeId, { r: 1, g: 0, b: 0, a: 1 })tool('set_fill').execute(figma, { id: rectangle.id, color: '#ff0000' })new OpenPencilAPI(figma).bindVariable(rectangle.id, 'fills/0/color', variable)const page = figma.createPage()@@ -83,15 +79,15 @@ describe('atomic agent tools', () => {value: '#00ff00'})expect(- figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ figma.variables.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]).toMatchObject({ g: 1 })undo.undo()expect(- figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ figma.variables.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]).toMatchObject({ r: 1, g: 0 })undo.redo()expect(- figma.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]+ figma.variables.getVariableById(variable.id)?.valuesByMode[collection.defaultModeId]).toMatchObject({ r: 0, g: 1 })})diff --git a/packages/core/tests/figma-api/boolean-bounds.test.ts b/packages/core/tests/figma-api/boolean-bounds.test.tsindex 39f27894a..7824d2a7a 100644--- a/packages/core/tests/figma-api/boolean-bounds.test.ts+++ b/packages/core/tests/figma-api/boolean-bounds.test.ts@@ -12,7 +12,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'// Recorded with the same script in Figma desktop 126: a boolean operation takes the box of its// result, and an empty result keeps its operands' box. Measuring needs a renderer.-type Operation = 'UNION' | 'SUBTRACT' | 'INTERSECT' | 'EXCLUDE'+type Operation = 'union' | 'subtract' | 'intersect' | 'exclude'let renderer: SkiaRendererlet surface: Surface@@ -47,27 +47,24 @@ describe('boolean operation bounds', () => {test('from scripts, a boolean takes the box of its result', () => {const { figma, square } = api()const combine = (operation: Operation, ...nodes: FigmaNodeProxy[]) =>- figma.booleanOperation(- operation,- nodes.map((node) => node.id)- )- expect(box(combine('UNION', square(0, 0), square(20, 20)))).toEqual([0, 0, 70, 70])- expect(box(combine('SUBTRACT', square(0, 0), square(20, 20)))).toEqual([0, 0, 50, 50])- const intersect = combine('INTERSECT', square(0, 0), square(20, 20))+ figma[operation](nodes, figma.currentPage)+ expect(box(combine('union', square(0, 0), square(20, 20)))).toEqual([0, 0, 70, 70])+ expect(box(combine('subtract', square(0, 0), square(20, 20)))).toEqual([0, 0, 50, 50])+ const intersect = combine('intersect', square(0, 0), square(20, 20))expect(box(intersect)).toEqual([20, 20, 30, 30])// The operands keep their places in the container's space.expect(intersect.children.map((child) => [child.x, child.y])).toEqual([[0, 0],[20, 20]])- expect(box(combine('SUBTRACT', square(0, 0), square(25, -10, 50, 70)))).toEqual([0, 0, 25, 50])- expect(box(combine('INTERSECT', square(0, 0), square(100, 0)))).toEqual([0, 0, 150, 50])+ expect(box(combine('subtract', square(0, 0), square(25, -10, 50, 70)))).toEqual([0, 0, 25, 50])+ expect(box(combine('intersect', square(0, 0), square(100, 0)))).toEqual([0, 0, 150, 50])})test('moving an operand refits the boolean to its new result', () => {const { figma, square } = api()const moving = square(20, 20)- const intersect = figma.booleanOperation('INTERSECT', [square(0, 0).id, moving.id])+ const intersect = figma.intersect([square(0, 0), moving], figma.currentPage)moving.x = 40expect(box(intersect)).toEqual([40, 20, 10, 30])})diff --git a/packages/core/tests/figma-api/surface.test.ts b/packages/core/tests/figma-api/surface.test.tsnew file mode 100644index 000000000..7368293dd--- /dev/null+++ b/packages/core/tests/figma-api/surface.test.ts@@ -0,0 +1,75 @@+import { describe, expect, test } from 'bun:test'+import { fileURLToPath } from 'node:url'++import ts from 'typescript'++import { FigmaAPI } from '#core/figma-api/index'+import { FIGMA_API_HOST_MEMBERS, SERIALIZATION_MEMBERS } from '#core/figma-api/surface'++import { SceneGraph } from '@open-pencil/scene-graph'++// `compatibility.ts` checks the declared types; this checks what a script can actually reach,+// including members installed on prototypes, against the names Figma's typings declare.++const TYPINGS = fileURLToPath(import.meta.resolve('@figma/plugin-typings/plugin-api.d.ts'))++/** Member names of Figma's declared types, read with the TypeScript checker. */+function figmaMembers(...typeNames: string[]): Set<string> {+ const program = ts.createProgram([TYPINGS], { noEmit: true, types: [] })+ const checker = program.getTypeChecker()+ const source = program.getSourceFile(TYPINGS)+ if (!source) throw new Error('Figma plugin typings are missing')+ const names = new Set<string>()+ const add = (type: ts.Type) => {+ for (const member of type.isUnion() ? type.types : [type]) {+ for (const property of checker.getPropertiesOfType(member)) names.add(property.name)+ }+ }+ for (const statement of source.statements) {+ if (!ts.isInterfaceDeclaration(statement) && !ts.isTypeAliasDeclaration(statement)) continue+ if (!typeNames.includes(statement.name.text)) continue+ add(checker.getTypeAtLocation(statement.name))+ }+ return names+}++/**+ * What a script reaches on an object, up its prototype chain. TypeScript-private members, named+ * with a leading underscore, are left out: scripts are not meant to touch them.+ */+function reachable(target: object): string[] {+ const names = new Set<string>()+ for (let proto = target; proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {+ for (const name of Object.getOwnPropertyNames(proto)) names.add(name)+ }+ return [...names].filter((name) => name !== 'constructor' && !name.startsWith('_'))+}++function beyondFigma(target: object, figma: Set<string>, listed: readonly string[]): string[] {+ return reachable(target).filter((name) => !figma.has(name) && !listed.includes(name))+}++describe('the scripting surface is Figma’s Plugin API', () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)++ test('figma has no members beyond the listed host members', () => {+ expect(beyondFigma(figma, figmaMembers('PluginAPI'), FIGMA_API_HOST_MEMBERS)).toEqual([])+ })++ test('nodes have only the members of Figma’s node types', () => {+ const nodeMembers = figmaMembers('SceneNode', 'PageNode', 'DocumentNode')+ for (const node of [figma.createFrame(), figma.createText(), figma.currentPage, figma.root])+ expect(beyondFigma(node, nodeMembers, SERIALIZATION_MEMBERS)).toEqual([])+ })++ test('variables, collections and figma.variables have only Figma’s members', () => {+ const collection = figma.variables.createVariableCollection('Tokens')+ const variable = figma.variables.createVariable('size', collection, 'FLOAT')+ expect(beyondFigma(figma.variables, figmaMembers('VariablesAPI'), [])).toEqual([])+ expect(beyondFigma(variable, figmaMembers('Variable'), SERIALIZATION_MEMBERS)).toEqual([])+ expect(+ beyondFigma(collection, figmaMembers('VariableCollection'), SERIALIZATION_MEMBERS)+ ).toEqual([])+ })+})diff --git a/packages/core/tests/figma-api/text/references.test.ts b/packages/core/tests/figma-api/text/references.test.tsindex 98a5ee030..28f2ae1f7 100644--- a/packages/core/tests/figma-api/text/references.test.ts+++ b/packages/core/tests/figma-api/text/references.test.ts@@ -194,14 +194,16 @@ describe('style ranges', () => {describe('bound variable ranges', () => {function sized() {const { api, text } = styledText()- const collection = api.createVariableCollection('Type')- const size = api.createVariable('size/lg', 'FLOAT', collection.id, 28)- const family = api.createVariable('font/body', 'STRING', collection.id, 'Roboto')+ const collection = api.variables.createVariableCollection('Type')+ const size = api.variables.createVariable('size/lg', collection, 'FLOAT')+ size.setValueForMode(collection.defaultModeId, 28)+ const family = api.variables.createVariable('font/body', collection, 'STRING')+ family.setValueForMode(collection.defaultModeId, 'Roboto')return { api, text, collection, size, family }}test('bind a range, show the variable value there, and follow it when it changes', () => {- const { api, text, collection, size } = sized()+ const { text, collection, size } = sized()text.setRangeBoundVariable(0, 5, 'fontSize', size)expect(text.getRangeBoundVariable(0, 5, 'fontSize')).toEqual({@@ -220,7 +222,7 @@ describe('bound variable ranges', () => {}])- api.setVariableValue(size.id, collection.defaultModeId, 40)+ size.setValueForMode(collection.defaultModeId, 40)expect(text.getRangeFontSize(0, 5)).toBe(40)text.setRangeBoundVariable(0, 5, 'fontSize', null)@@ -246,8 +248,9 @@ describe('bound variable ranges', () => {test('bind paragraph spacing for the paragraphs of the range', () => {const { api, text } = styledText('One\nTwo')- const collection = api.createVariableCollection('Space')- const gap = api.createVariable('gap', 'FLOAT', collection.id, 12)+ const collection = api.variables.createVariableCollection('Space')+ const gap = api.variables.createVariable('gap', collection, 'FLOAT')+ gap.setValueForMode(collection.defaultModeId, 12)text.setRangeBoundVariable(0, 2, 'paragraphSpacing', gap)expect(text.getRangeParagraphSpacing(0, 2)).toBe(12)expect(text.getRangeParagraphSpacing(5, 6)).toBe(0)diff --git a/packages/core/tests/figma-api/variables/scaled-bindings.test.ts b/packages/core/tests/figma-api/variables/scaled-bindings.test.tsindex ee2be34af..4e86e7245 100644--- a/packages/core/tests/figma-api/variables/scaled-bindings.test.ts+++ b/packages/core/tests/figma-api/variables/scaled-bindings.test.ts@@ -7,8 +7,9 @@ import { SceneGraph } from '@open-pencil/scene-graph'test('Figma API edits reconcile existing scaled bindings without an editor', () => {const graph = new SceneGraph()const api = new FigmaAPI(graph)- const collection = api.createVariableCollection('Spacing')- const first = api.createVariable('First', 'FLOAT', collection.id, 10)+ const collection = api.variables.createVariableCollection('Spacing')+ const first = api.variables.createVariable('First', collection, 'FLOAT')+ first.setValueForMode(collection.defaultModeId, 10)const frame = graph.createNode('INSTANCE', graph.getPages()[0].id, {layoutMode: 'HORIZONTAL',primaryAxisSizing: 'HUG',@@ -19,22 +20,22 @@ test('Figma API edits reconcile existing scaled bindings without an editor', ()})frame.source.format = 'fig'const child = graph.createNode('RECTANGLE', frame.id, { width: 5, height: 5 })- api.setVariableValue(first.id, collection.defaultModeId, 20)+ first.setValueForMode(collection.defaultModeId, 20)expect(frame.paddingLeft).toBe(5)expect(frame.width).toBe(10)expect(child.x).toBe(5)new OpenPencilAPI(api).unbindVariable(frame.id, 'paddingLeft')- api.setVariableValue(first.id, collection.defaultModeId, 80)+ first.setValueForMode(collection.defaultModeId, 80)expect(frame.paddingLeft).toBe(5)})test('Figma API copies assigned variable values rather than retaining caller aliases', () => {const graph = new SceneGraph()const api = new FigmaAPI(graph)- const collection = api.createVariableCollection('Colors')- const variable = api.createVariable('Color', 'COLOR', collection.id)+ const collection = api.variables.createVariableCollection('Colors')+ const variable = api.variables.createVariable('Color', collection, 'COLOR')const value = { r: 1, g: 0, b: 0, a: 1 }- api.setVariableValue(variable.id, collection.defaultModeId, value)+ variable.setValueForMode(collection.defaultModeId, value)value.r = 0expect(variable.valuesByMode[collection.defaultModeId]).toEqual({ r: 1, g: 0, b: 0, a: 1 })})diff --git a/packages/core/tests/figma-api/variants.test.ts b/packages/core/tests/figma-api/variants.test.tsnew file mode 100644index 000000000..57f2b6005--- /dev/null+++ b/packages/core/tests/figma-api/variants.test.ts@@ -0,0 +1,116 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI, type FigmaComponentSetNode, type FigmaNodeProxy } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++// Recorded by running the same script in Figma desktop: variant edits through the Plugin API+// rename the variants, instances follow, and the value lists follow the variants' names.++function variants() {+ const figma = new FigmaAPI(new SceneGraph())+ const base = figma.createComponent()+ base.name = 'State=Default'+ const hover = figma.createComponent()+ hover.name = 'State=Hover'+ const set = figma.combineAsVariants([base, hover], figma.currentPage)+ const instance = base.createInstance()+ return { figma, set, base, hover, instance }+}++const names = (set: FigmaComponentSetNode) => set.children.map((child) => child.name)+const variantProperties = (node: FigmaNodeProxy) =>+ (node as FigmaNodeProxy & { variantProperties: Record<string, string> | null }).variantProperties++describe('variant properties through the Plugin API', () => {+ test('variants and their instances read their values; other components read null', () => {+ const { figma, base, instance } = variants()+ expect(variantProperties(base)).toEqual({ State: 'Default' })+ expect(variantProperties(instance)).toEqual({ State: 'Default' })+ const lone = figma.createComponent()+ expect(variantProperties(lone)).toBeNull()+ expect(variantProperties(lone.createInstance())).toBeNull()+ })++ test('renaming an axis renames every variant, and instances switch by the new name', () => {+ const { set, instance } = variants()+ expect(set.editComponentProperty('State', { name: 'Mode' })).toBe('Mode')+ expect(names(set)).toEqual(['Mode=Default', 'Mode=Hover'])+ expect(set.componentPropertyDefinitions).toEqual({+ Mode: { type: 'VARIANT', defaultValue: 'Default', variantOptions: ['Default', 'Hover'] }+ })+ expect(variantProperties(instance)).toEqual({ Mode: 'Default' })+ instance.setProperties({ Mode: 'Hover' })+ expect(instance.mainComponent?.name).toBe('Mode=Hover')+ })++ test('adding an axis appends its value to every variant', () => {+ const { set, instance } = variants()+ expect(set.addComponentProperty('Size', 'VARIANT', 'sm')).toBe('Size')+ expect(names(set)).toEqual(['State=Default, Size=sm', 'State=Hover, Size=sm'])+ expect(set.componentPropertyDefinitions.Size).toEqual({+ type: 'VARIANT',+ defaultValue: 'sm',+ variantOptions: ['sm']+ })+ expect(variantProperties(instance)).toEqual({ State: 'Default', Size: 'sm' })+ })++ test('value lists follow the variants’ names', () => {+ const { set, base, hover } = variants()+ hover.name = 'State=Pressed'+ base.name = 'State=Base'+ expect(set.componentPropertyDefinitions.State).toEqual({+ type: 'VARIANT',+ defaultValue: 'Base',+ variantOptions: ['Pressed', 'Base']+ })+ expect(variantProperties(hover)).toEqual({ State: 'Pressed' })+ })++ test('a variant renamed to another’s values keeps its own, where Figma leaves the set in error', () => {+ const { set, hover, instance } = variants()+ hover.name = 'State=Default'+ expect(variantProperties(hover)).toEqual({ State: 'Hover' })+ expect(set.componentPropertyDefinitions.State).toMatchObject({+ variantOptions: ['Default', 'Hover']+ })+ instance.setProperties({ State: 'Hover' })+ expect(instance.mainComponent?.id).toBe(hover.id)+ })++ test('variant edits fail as Figma’s do', () => {+ const { set, base } = variants()+ set.addComponentProperty('Size', 'VARIANT', 'sm')+ expect(() => set.addComponentProperty('Size', 'VARIANT', 'md')).toThrow(+ 'in addComponentProperty: Node already has a variant property with name Size'+ )+ expect(() => set.addComponentProperty('Empty', 'VARIANT', '')).toThrow(+ 'in addComponentProperty: Component property default value cannot be empty'+ )+ expect(() => base.addComponentProperty('X', 'VARIANT', 'a')).toThrow(+ 'in addComponentProperty: Can only add variant property to a component set'+ )+ expect(() => set.editComponentProperty('Size', { defaultValue: 'lg' })).toThrow(+ 'in editComponentProperty: Cannot change defaultValue of a variant property'+ )+ expect(() => set.editComponentProperty('Nope', { name: 'x' })).toThrow(+ 'in editComponentProperty: Invalid variant property name'+ )+ expect(() => set.deleteComponentProperty('Size')).toThrow(+ 'in deleteComponentProperty: Invalid component property name'+ )+ expect(names(set)).toEqual(['State=Default, Size=sm', 'State=Hover, Size=sm'])+ })++ test('renames that would break the set are refused, where Figma leaves the set in error', () => {+ const { set } = variants()+ set.addComponentProperty('Size', 'VARIANT', 'sm')+ expect(() => set.editComponentProperty('Size', { name: 'State' })).toThrow(+ 'in editComponentProperty: Node already has a variant property with name State'+ )+ expect(() => set.editComponentProperty('Size', { name: '' })).toThrow(+ 'Property name must not be empty'+ )+ expect(names(set)).toEqual(['State=Default, Size=sm', 'State=Hover, Size=sm'])+ })+})diff --git a/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts b/packages/core/tests/io/formats/fig/export/definition-rescale.test.tsindex ddb5d8ffd..eea2131ee 100644--- a/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts+++ b/packages/core/tests/io/formats/fig/export/definition-rescale.test.ts@@ -70,9 +70,9 @@ test('definition rescale preserves an explicit placed binding in its declaring uexpect(nested.variableBindingScales.paddingLeft).toBe(0.25)const variable = expectDefined(graph.variables.get('293742:7'))const mode = graph.getNodeVariableModeId(nested.id, variable.collectionId)- api.setVariableValue(variable.id, mode, 16)+ expectDefined(api.variables.getVariableById(variable.id)).setValueForMode(mode, 16)expect([root.width, nested.width, nested.paddingLeft]).toEqual([29, 19, 4])- api.setVariableValue(variable.id, mode, 12)+ expectDefined(api.variables.getVariableById(variable.id)).setValueForMode(mode, 12)graph.updateNode(root.id, { name: 'Protected rescale acceptance' })await initCodec()const bytes = await exportFigFile(graph)@@ -119,23 +119,15 @@ test('definition rescale propagates occurrence units through editor sync and expnested.paddingRight]).toEqual([22.5, 7, 12.5, 7, 5, 2.5])expect(nested.variableBindingScales.paddingLeft).toBe(0.25)- api.setVariableValue(- '293733:7',- graph.getNodeVariableModeId(+ expectDefined(api.variables.getVariableById('293733:7')).setValueForMode(graph.getNodeVariableModeId(nested.id,expectDefined(graph.variables.get('293733:7')).collectionId- ),- 40- )+ ), 40)expect([root.width, nested.width, nested.paddingLeft]).toEqual([27.5, 17.5, 10])- api.setVariableValue(- '293733:7',- graph.getNodeVariableModeId(+ expectDefined(api.variables.getVariableById('293733:7')).setValueForMode(graph.getNodeVariableModeId(nested.id,expectDefined(graph.variables.get('293733:7')).collectionId- ),- 20- )+ ), 20)graph.updateNode(root.id, { name: 'Definition rescale acceptance' })await initCodec()const bytes = await exportFigFile(graph)diff --git a/packages/core/tests/io/formats/fig/export/formula.test.ts b/packages/core/tests/io/formats/fig/export/formula.test.tsindex 7cee987f0..ddcbbc69d 100644--- a/packages/core/tests/io/formats/fig/export/formula.test.ts+++ b/packages/core/tests/io/formats/fig/export/formula.test.ts@@ -1,5 +1,7 @@import { expect, test } from 'bun:test'+import { expectDefined } from '#core-tests/helpers/assert'+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'import { parseFigBuffer } from '@open-pencil/fig'import { FigmaAPI } from '@open-pencil/core/figma-api'@@ -49,8 +51,8 @@ test('numeric, Boolean and comparison formulas survive fresh and patched .fig saconst 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)+ if (variable.name === base.name) expectDefined(api.variables.getVariableById(variable.id)).setValueForMode(active, 10)+ if (variable.name === enabled.name) expectDefined(api.variables.getVariableById(variable.id)).setValueForMode(active, false)}}})diff --git a/packages/core/tests/io/formats/fig/export/rescale-export.test.ts b/packages/core/tests/io/formats/fig/export/rescale-export.test.tsindex 15cc8606e..d9634051d 100644--- a/packages/core/tests/io/formats/fig/export/rescale-export.test.ts+++ b/packages/core/tests/io/formats/fig/export/rescale-export.test.ts@@ -86,11 +86,7 @@ for (const scale of [0.5, 2]) {expect(restored.componentScale).toBe(scale * 0.5)expect(child.variableBindingScales.paddingLeft).toBe(scale * 0.5)const variable = expectDefined(reopened.variables.get(child.boundVariables.paddingLeft))- new FigmaAPI(reopened).setVariableValue(- variable.id,- reopened.getNodeVariableModeId(child.id, variable.collectionId),- 16- )+ expectDefined(new FigmaAPI(reopened).variables.getVariableById(variable.id)).setValueForMode(reopened.getNodeVariableModeId(child.id, variable.collectionId), 16)expect(child.paddingLeft).toBe(8 * scale)expect(restored.width).toBe((literalClaim ? 41 : 39) * scale)})diff --git a/tests/engine/figma/api/create/expose-instance-swap.test.ts b/packages/core/tests/openpencil-api/expose-instance-swap.test.tssimilarity index 80%rename from tests/engine/figma/api/create/expose-instance-swap.test.tsrename to packages/core/tests/openpencil-api/expose-instance-swap.test.tsindex 89905647e..183ea5ff8 100644--- a/tests/engine/figma/api/create/expose-instance-swap.test.ts+++ b/packages/core/tests/openpencil-api/expose-instance-swap.test.ts@@ -1,6 +1,12 @@import { describe, expect, test } from 'bun:test'-import { createAPI } from '../helpers'+import { OpenPencilAPI } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++function createAPI() {+ return new FigmaAPI(new SceneGraph())+}describe('exposeInstanceSwap', () => {test('adds an INSTANCE_SWAP property to the host component and tags the slot', () => {@@ -19,7 +25,7 @@ describe('exposeInstanceSwap', () => {const slot = iconA.createInstance()host.appendChild(slot)- const result = api.exposeInstanceSwap([slot], [iconA, iconB], 'Icon')+ const result = new OpenPencilAPI(api).exposeInstanceSwap([slot], [iconA, iconB], 'Icon')const raw = api.graph.getNode(result.id)expect(result.id).toBe(host.id)@@ -55,7 +61,7 @@ describe('exposeInstanceSwap', () => {const set = api.graph.createNode('COMPONENT_SET', api.currentPageId, { name: 'Button' })api.graph.reparentNode(a.id, set.id)api.graph.reparentNode(b.id, set.id)- const result = api.exposeInstanceSwap([slotA, slotB], [icon], 'Icon')+ const result = new OpenPencilAPI(api).exposeInstanceSwap([slotA, slotB], [icon], 'Icon')expect(result.id).toBe(set.id)const raw = api.graph.getNode(set.id)@@ -68,7 +74,7 @@ describe('exposeInstanceSwap', () => {const icon = api.createComponent()const frame = api.createFrame()host.appendChild(frame)- expect(() => api.exposeInstanceSwap([frame], [icon])).toThrow()+ expect(() => new OpenPencilAPI(api).exposeInstanceSwap([frame], [icon])).toThrow()})test('rejects non-component candidates', () => {@@ -78,7 +84,7 @@ describe('exposeInstanceSwap', () => {const slot = icon.createInstance()host.appendChild(slot)const notAComponent = api.createFrame()- expect(() => api.exposeInstanceSwap([slot], [notAComponent])).toThrow()+ expect(() => new OpenPencilAPI(api).exposeInstanceSwap([slot], [notAComponent])).toThrow()})test('rejects slots from unrelated hosts', () => {@@ -93,6 +99,6 @@ describe('exposeInstanceSwap', () => {hostA.appendChild(slotA)const slotB = icon.createInstance()hostB.appendChild(slotB)- expect(() => api.exposeInstanceSwap([slotA, slotB], [icon])).toThrow()+ expect(() => new OpenPencilAPI(api).exposeInstanceSwap([slotA, slotB], [icon])).toThrow()})})diff --git a/packages/core/tests/openpencil-api/formula.test.ts b/packages/core/tests/openpencil-api/formula.test.tsindex 36ea44369..e4a346654 100644--- a/packages/core/tests/openpencil-api/formula.test.ts+++ b/packages/core/tests/openpencil-api/formula.test.ts@@ -1,5 +1,7 @@import { expect, test } from 'bun:test'+import { expectDefined } from '#core-tests/helpers/assert'+import { FigmaAPI } from '@open-pencil/core/figma-api'import { compileScript } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'@@ -43,6 +45,6 @@ test('a mode’s CSS expression outlives a script formula and records a script nconst 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)+ expectDefined(figma.variables.getVariableById(gap.id)).setValueForMode('large', 40)expect(gap.expressions).toEqual({ [mode]: { css: '1rem' }, large: { css: '2rem', resolved: 40 } })})diff --git a/packages/core/tests/openpencil-api/nodes.test.ts b/packages/core/tests/openpencil-api/nodes.test.tsnew file mode 100644index 000000000..d9e74ed56--- /dev/null+++ b/packages/core/tests/openpencil-api/nodes.test.ts@@ -0,0 +1,36 @@+import { expect, test } from 'bun:test'++import { OpenPencilAPI } from '@open-pencil/core'+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compileScript } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++test('scripts set layout and text direction through openpencil, which figma lacks', async () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const result = (await compileScript(`+ const frame = figma.createFrame()+ const text = figma.createText()+ const before = openpencil.getLayoutDirection(frame)+ openpencil.setLayoutDirection(frame, 'RTL')+ openpencil.setTextDirection(text, 'RTL')+ return {+ before,+ layout: openpencil.getLayoutDirection(frame),+ text: openpencil.getTextDirection(text),+ onFigma: 'layoutDirection' in frame || 'textDirection' in text+ }+ `)(figma)) as { before: string; layout: string; text: string; onFigma: boolean }+ expect(result).toEqual({ before: 'AUTO', layout: 'RTL', text: 'RTL', onFigma: false })+ await expect(+ compileScript(`openpencil.setTextDirection(figma.createText(), 'UP')`)(figma)+ ).rejects.toThrow('Unknown direction UP; use AUTO, LTR, RTL')+})++test('a layer saved without a layout direction reads AUTO', () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const frame = figma.createFrame()+ Reflect.deleteProperty(graph.getNode(frame.id) as object, 'layoutDirection')+ expect(new OpenPencilAPI(figma).getLayoutDirection(frame)).toBe('AUTO')+})diff --git a/packages/core/tests/openpencil-api/variables.test.ts b/packages/core/tests/openpencil-api/variables.test.tsindex c48e1ccd7..a5d22b45b 100644--- a/packages/core/tests/openpencil-api/variables.test.ts+++ b/packages/core/tests/openpencil-api/variables.test.ts@@ -1,5 +1,6 @@import { expect, test } from 'bun:test'+import { OpenPencilAPI } from '@open-pencil/core'import { FigmaAPI } from '@open-pencil/core/figma-api'import { compileScript } from '@open-pencil/core/tools'import { SceneGraph } from '@open-pencil/scene-graph'@@ -15,7 +16,7 @@ function document() {test('scripts bind what the layer panel binds, beyond Figma’s setBoundVariable', async () => {const { graph, figma } = document()const result = await compileScript(`- const [price, state] = figma.getLocalVariables()+ const [price, state] = figma.variables.getLocalVariables()const label = figma.createText()openpencil.bindVariable(label, 'text', price)openpencil.bindVariable(label, 'visible', state)@@ -31,7 +32,7 @@ test('unbinding keeps the value the variable last gave, and errors name the layeconst id = (await compileScript(`const label = figma.createText()label.name = 'Label'- openpencil.bindVariable(label, 'text', figma.getLocalVariables()[0])+ openpencil.bindVariable(label, 'text', figma.variables.getLocalVariables()[0])openpencil.unbindVariable(label, 'text')return label.id`)(figma)) as string@@ -41,7 +42,21 @@ test('unbinding keeps the value the variable last gave, and errors name the laye).rejects.toThrow('Label has no variable bound to text')await expect(compileScript(- `openpencil.bindVariable(${JSON.stringify(id)}, 'text', figma.getLocalVariables()[1]); openpencil.bindVariable(${JSON.stringify(id)}, 'fontFamily', figma.getLocalVariables()[0])`+ `openpencil.bindVariable(${JSON.stringify(id)}, 'text', figma.variables.getLocalVariables()[1]); openpencil.bindVariable(${JSON.stringify(id)}, 'fontFamily', figma.variables.getLocalVariables()[0])`)(figma)).rejects.toThrow('Cannot bind FLOAT variable to string field "fontFamily"')})++test('unbinding a paint keeps the color its variable last gave it', () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Colors')+ const brand = graph.createVariable('brand', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })+ const figma = new FigmaAPI(graph)+ const rect = figma.createRectangle()+ const black = { type: 'SOLID' as const, color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }+ rect.fills = [black]+ const openpencil = new OpenPencilAPI(figma)+ openpencil.bindVariable(rect, 'fills/0/color', brand)+ openpencil.unbindVariable(rect, 'fills/0/color')+ expect(graph.getNode(rect.id)?.fills[0]?.color).toEqual({ r: 1, g: 0, b: 0, a: 1 })+})diff --git a/packages/core/tests/tools/variables/values.test.ts b/packages/core/tests/tools/variables/values.test.tsnew file mode 100644index 000000000..c9bbdcd1e--- /dev/null+++ b/packages/core/tests/tools/variables/values.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++import { createVariable, deleteVariable } from '#core/tools/variables/values'++describe('variable value tools', () => {+ test('a value the variable cannot hold creates no variable', async () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Tokens')+ const figma = new FigmaAPI(graph)+ const args = { name: 'gap', type: 'FLOAT' as const, collection_id: collection.id }+ expect(await createVariable.execute(figma, { ...args, value: 'wide' })).toEqual({+ error: '"wide" is not a number'+ })+ expect(graph.variables.size).toBe(0)+ expect(await createVariable.execute(figma, { ...args, value: '8' })).toMatchObject({+ name: 'gap',+ valuesByMode: { [collection.defaultModeId]: 8 }+ })+ })++ test('deleting a variable the document lacks reports it', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ expect(await deleteVariable.execute(figma, { id: 'VariableID:9:9' })).toEqual({+ error: 'Variable "VariableID:9:9" not found'+ })+ })+})diff --git a/packages/docs/.vitepress/theme/landing/stage/panels/terminal-commands.ts b/packages/docs/.vitepress/theme/landing/stage/panels/terminal-commands.tsindex 757e1ddd4..a40333e5f 100644--- a/packages/docs/.vitepress/theme/landing/stage/panels/terminal-commands.ts+++ b/packages/docs/.vitepress/theme/landing/stage/panels/terminal-commands.ts@@ -102,11 +102,11 @@ async function printTailwind(store: EditorStore): Promise<string> {}// The players' colors are Theme variables, so one value changes every player in both modes.-const RECOLOR = `const theme = figma.getLocalVariableCollections().find(c => c.name === 'Theme')-const accent = figma.getLocalVariables('COLOR')- .find(v => v.name === 'Accent' && v.collectionId === theme.id)+const RECOLOR = `const theme = figma.variables.getLocalVariableCollections().find(c => c.name === 'Theme')+const accent = figma.variables.getLocalVariables('COLOR')+ .find(v => v.name === 'Accent' && v.variableCollectionId === theme.id)const coral = { r: 0.96, g: 0.33, b: 0.24, a: 1 }-for (const mode of theme.modes) figma.setVariableValue(accent.id, mode.modeId, coral)+for (const mode of theme.modes) accent.setValueForMode(mode.modeId, coral)return 'Accent is coral in ' + theme.modes.map(m => m.name).join(' and ')`const ADD_PLAYER = `const player = figma.currentPage.findOne(n => n.type === 'COMPONENT' && n.name === 'Player')diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.mdindex 247310e7f..196a2a8f5 100644--- a/packages/docs/es/programmable/cli/scripting.md+++ b/packages/docs/es/programmable/cli/scripting.md@@ -94,7 +94,7 @@ La API sigue el modelo de Figma Plugin API, pero actúa sobre SceneGraph y los f### Componentes y variables-Se admiten creación de componentes e instancias, consulta del componente principal, colecciones, modos, creación y eliminación de variables y enlaces mediante `openpencil.bindVariable` y `openpencil.unbindVariable`.+Se admiten creación de componentes e instancias, consulta del componente principal y `figma.variables` como en la API de plugins de Figma: colecciones, modos, creación y eliminación de variables, `node.setBoundVariable` y `node.boundVariables`. Los enlaces tal como los hace el panel de capas usan `openpencil.bindVariable` y `openpencil.unbindVariable`. La dirección del diseño automático y del texto (`AUTO`, `LTR`, `RTL`) se fija con `openpencil.setLayoutDirection` y `openpencil.setTextDirection`, el color OkHCL con `openpencil.setFillOkHCL` y `setStrokeOkHCL`, y `openpencil.exposeInstanceSwap` y `openpencil.getFontStatus()` exponen el intercambio de instancias y el estado de las fuentes.### Propiedades@@ -111,6 +111,6 @@ Las propiedades habituales se leen y modifican mediante el objeto correspondient## Limitaciones-Aún no hay equivalentes completos para `node.exportAsync()`, `node.setBoundVariable()`, `figma.combineAsVariants()`, estilos de pintura/texto y todas las operaciones booleanas vectoriales.+Aún no hay equivalentes completos para `node.exportAsync()`, las variables de bibliotecas, estilos de pintura/texto y todas las operaciones booleanas vectoriales.Según la tarea, pueden usarse el comando de exportación, las herramientas del núcleo o las operaciones directas de SceneGraph.diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.mdindex 17d0ca7ae..5f61182bf 100644--- a/packages/docs/pl/programmable/cli/scripting.md+++ b/packages/docs/pl/programmable/cli/scripting.md@@ -84,7 +84,7 @@ API jest celowo zbliżone do Figma Plugin API, ale pracuje z SceneGraph i format### Komponenty i zmienne-Nazwy metod, takie jak `component.createInstance()` i `figma.getLocalVariables()`, pozostają zgodne z Figma Plugin API. Zmienne wiąże się z polami warstw przez `openpencil.bindVariable(node, field, variable)` i `openpencil.unbindVariable(node, field)`.+Nazwy metod, takie jak `component.createInstance()`, `figma.variables.getLocalVariables()` i `node.setBoundVariable()`, pozostają zgodne z Figma Plugin API. Tak jak panel warstwy zmienne wiąże się z polami przez `openpencil.bindVariable(node, field, variable)` i `openpencil.unbindVariable(node, field)`. Kierunek automatycznego układu i tekstu (`AUTO`, `LTR`, `RTL`) ustawiają `openpencil.setLayoutDirection(node, direction)` i `openpencil.setTextDirection(node, direction)`, kolor w OkHCL `openpencil.setFillOkHCL(node, color)` i `setStrokeOkHCL`, a `openpencil.exposeInstanceSwap` i `openpencil.getFontStatus()` udostępniają zamianę instancji i stan czcionek.### Właściwości@@ -108,6 +108,6 @@ Najczęściej używane właściwości można odczytywać i zapisywać przez poś## Brak pełnej zgodności z Figmą-Nie są jeszcze dostępne między innymi `node.exportAsync()`, `node.setBoundVariable()`, `figma.combineAsVariants()` i API stylów Figmy.+Nie są jeszcze dostępne między innymi `node.exportAsync()`, zmienne z bibliotek i API stylów Figmy.Zamiast nich używaj poleceń eksportu CLI, narzędzi głównego pakietu albo bezpośrednich funkcji pomocniczych SceneGraph.diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex 1b9987a70..47be30bd5 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -40,10 +40,10 @@ References use variable names or `{Collection::variable}` and are stored as stab## Variable bindings-Use `openpencil.bindVariable(node, field, variable)` to bind a layer field to a variable from `figma.getLocalVariables()`, and `openpencil.unbindVariable(node, field)` to let it go; the field keeps the value the variable last gave it. Fields use OpenPencil's names, such as `text`, `visible`, `opacity`, `paddingLeft` or `fills/0/color`. Bindings follow the layer panel, which takes more than Figma's `setBoundVariable`: text content takes a text or number variable, a number shown as text, and visibility a boolean or a text variable that shows the layer unless it is empty or reads `false`, `no` or `off`.+Figma's `node.setBoundVariable(field, variable)` binds with Figma's field names and type rules. Use `openpencil.bindVariable(node, field, variable)` to bind a layer field to a variable from `figma.variables` the way the layer panel does, and `openpencil.unbindVariable(node, field)` to let it go; the field keeps the value the variable last gave it. Fields use OpenPencil's names, such as `text`, `visible`, `opacity`, `paddingLeft` or `fills/0/color`. Bindings follow the layer panel, which takes more than Figma's `setBoundVariable`: text content takes a text or number variable, a number shown as text, and visibility a boolean or a text variable that shows the layer unless it is empty or reads `false`, `no` or `off`.```js-const [price] = figma.getLocalVariables('FLOAT')+const [price] = figma.variables.getLocalVariables('FLOAT')const label = figma.currentPage.findOne((node) => node.name === 'Price')openpencil.bindVariable(label, 'text', price)```@@ -161,6 +161,13 @@ openpencil eval design.fig -w -c '- `openpencil.getStatus(node)` reads the name of the status a layer shows, or `null`, also while a section around it shows its own.- `openpencil.setStatus(node, name)` sets one by name, and `null` clears it. Only sections, frames, components, component sets, and instances directly on a page or in a section take one; anything else fails with an error that says why, and an unknown name lists the statuses there are.+Layer features Figma's API has no member for:++- `openpencil.getLayoutDirection(node)` / `setLayoutDirection(node, direction)` and `getTextDirection(node)` / `setTextDirection(node, direction)` read and set which way an auto layout or a text runs: `AUTO`, `LTR`, or `RTL`.+- `openpencil.getFillOkHCL(node, index?)` / `setFillOkHCL(node, color, index?)` and the `Stroke` pair read and set a paint's color in OkHCL, `{ h, c, l, a? }`; its RGB follows in the document's color space.+- `openpencil.exposeInstanceSwap(instances, candidates, name?)` exposes swapping those instances as one instance swap property offering the candidate components, and returns the layer that holds it.+- `openpencil.getFontStatus()` reports whether the current page's fonts are available: the faces asked for, where each loaded from, substitutions, and the layers affected.+## Supported API surfaceThe API is intentionally close to Figma's Plugin API, but it maps to OpenPencil's scene graph and file format.@@ -206,20 +213,18 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'- `figma.createComponentFromNode(node)`- `figma.combineAsVariants(components, parent)` — properties come from names such as `State=On, Size=Large`+- On a component set, `addComponentProperty(name, 'VARIANT', value)` appends the value to every variant's name and `editComponentProperty(name, { name })` renames the property in them, which instances follow; renaming a variant updates the set's values, and `variantProperties` reads a variant's or an instance's values- `component.createInstance()`- `instance.mainComponent`### Variables-- `figma.getLocalVariables(type?)`-- `figma.getVariableById(id)`-- `figma.getLocalVariableCollections()`-- `figma.getVariableCollectionById(id)`-- `figma.createVariable(name, type, collectionId, value?)`-- `figma.setVariableValue(variableId, modeId, value)`-- `figma.deleteVariable(id)`-- `figma.createVariableCollection(name)`-- `figma.deleteVariableCollection(id)`+- `figma.variables.getLocalVariables(type?)`, `getVariableById(id)`, `getLocalVariableCollections()`, `getVariableCollectionById(id)`, and their `…Async` forms+- `figma.variables.createVariableCollection(name)` and `createVariable(name, collection, resolvedType)`, which starts every mode at Figma's default+- `figma.variables.createVariableAlias(variable)` and `setBoundVariableForPaint(paint, 'color', variable)`+- `variable.setValueForMode(modeId, value)`, `valuesByMode`, `resolveForConsumer(node)`, `name`, `description`, `scopes`, `codeSyntax`, and `remove()`+- `collection.addMode(name)`, `renameMode(modeId, name)`, `removeMode(modeId)`, `modes`, `defaultModeId`, `variableIds`, and `remove()`+- `node.boundVariables`, `node.setBoundVariable(field, variable)`, `node.setExplicitVariableModeForCollection(collection, modeId)`, and `node.clearExplicitVariableModeForCollection(collection)`### Properties@@ -253,8 +258,7 @@ Common node properties are readable/writable through the proxy, including:These Figma APIs are not exposed as compatible helpers yet:- `node.exportAsync()`-- `node.setBoundVariable(field, variable)`-- `figma.combineAsVariants(components, parent)`+- Library variables, extended collections, and variable bindings on effects and layout grids- Figma style APIs such as `figma.createPaintStyle()` / `figma.createTextStyle()`- Full vector boolean operation paritydiff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.mdindex 9bc10bd98..1cc85dbbc 100644--- a/packages/docs/ru/programmable/cli/scripting.md+++ b/packages/docs/ru/programmable/cli/scripting.md@@ -112,17 +112,17 @@ API намеренно близок к Figma Plugin API, но работает### Переменные-- `figma.getLocalVariables(type?)`-- `figma.getVariableById(id)`-- `figma.getLocalVariableCollections()`-- `figma.getVariableCollectionById(id)`-- `figma.createVariable(name, type, collectionId, value?)`-- `figma.setVariableValue(variableId, modeId, value)`-- `figma.deleteVariable(id)`-- `figma.createVariableCollection(name)`-- `figma.deleteVariableCollection(id)`+- `figma.variables.getLocalVariables(type?)`, `getVariableById(id)`, `getLocalVariableCollections()`, `getVariableCollectionById(id)` и их варианты `…Async`+- `figma.variables.createVariableCollection(name)` и `createVariable(name, collection, resolvedType)` — каждый режим получает значение Figma по умолчанию+- `figma.variables.createVariableAlias(variable)` и `setBoundVariableForPaint(paint, 'color', variable)`+- `variable.setValueForMode(modeId, value)`, `valuesByMode`, `resolveForConsumer(node)`, `name`, `description`, `scopes`, `codeSyntax` и `remove()`+- `collection.addMode(name)`, `renameMode(modeId, name)`, `removeMode(modeId)`, `modes`, `defaultModeId`, `variableIds` и `remove()`+- `node.boundVariables`, `node.setBoundVariable(field, variable)` — поля и типы как в Figma, `node.setExplicitVariableModeForCollection(collection, modeId)` и `node.clearExplicitVariableModeForCollection(collection)`- `openpencil.bindVariable(node, field, variable)` — привязки как в панели слоя: текст принимает текстовую или числовую переменную, видимость — логическую или текстовую- `openpencil.unbindVariable(node, field)`+- `openpencil.getLayoutDirection(node)` / `setLayoutDirection(node, direction)` и `getTextDirection(node)` / `setTextDirection(node, direction)` — направление автолейаута и текста: `AUTO`, `LTR` или `RTL`+- `openpencil.getFillOkHCL(node, index?)` / `setFillOkHCL(node, color, index?)` и пара для обводки — цвет заливки или обводки в OkHCL+- `openpencil.exposeInstanceSwap(instances, candidates, name?)` и `openpencil.getFontStatus()`### Свойства@@ -150,8 +150,7 @@ API намеренно близок к Figma Plugin API, но работаетСледующие API пока не предоставляются в совместимом виде:- `node.exportAsync()`-- `node.setBoundVariable(field, variable)`-- `figma.combineAsVariants(components, parent)`+- переменные из библиотек, расширенные коллекции и привязки переменных к эффектам и сеткам- API стилей Figma, например `figma.createPaintStyle()` и `figma.createTextStyle()`- полная совместимость логических операций над векторамиdiff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 820460658..d4408913e 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -26,7 +26,7 @@ Use `openpencil --help`, per-command help, and the connected MCP server’s toolInside `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`.-Bind layer fields to variables with `openpencil.bindVariable(node, field, variable)`, a variable from `figma.getLocalVariables()`, and `openpencil.unbindVariable(node, field)`; `figma` has no binding method. Fields use OpenPencil names (`text`, `visible`, `opacity`, `fills/0/color`). Text content takes a text or number variable, shown as text; visibility a boolean or text one.+Variables follow Figma's plugin API: `figma.variables.getLocalVariables()`, `createVariable(name, collection, type)`, `variable.setValueForMode(modeId, value)`, and `node.setBoundVariable(field, variable)` with Figma's field names (`characters`, `width`, `paddingLeft`) and types; paint colours bind through `figma.variables.setBoundVariableForPaint`. To bind as the layer panel does, use `openpencil.bindVariable(node, field, variable)` and `openpencil.unbindVariable(node, field)` with OpenPencil names (`text`, `visible`, `opacity`, `fills/0/color`): text content takes a text or number variable, shown as text; visibility a boolean or text one. `openpencil` also sets layout and text direction (`setLayoutDirection`, `setTextDirection`), OkHCL paint colors (`setFillOkHCL`, `setStrokeOkHCL`), exposes instance swaps (`exposeInstanceSwap`), and reports font availability (`getFontStatus()`); booleans and flattening are Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `figma.flatten`.## Requirementsdiff --git a/tests/app/automation/bridge/handlers.test.ts b/tests/app/automation/bridge/handlers.test.tsindex cb601c24a..bb756d737 100644--- a/tests/app/automation/bridge/handlers.test.ts+++ b/tests/app/automation/bridge/handlers.test.ts@@ -238,8 +238,8 @@ describe('undo and redo', () => {other.findOne((node) => node.name === 'Card').name = 'Renamed'other.name = 'Renamed page'figma.createPage().name = 'Added'- const colors = figma.createVariableCollection('Colors')- figma.createVariable('Brand', 'COLOR', colors.id)+ const colors = figma.variables.createVariableCollection('Colors')+ figma.variables.createVariable('Brand', colors, 'COLOR')`})expect(graph.getNode(card.id)?.name).toBe('Renamed')diff --git a/tests/engine/cli/eval.test.ts b/tests/engine/cli/eval.test.tsindex e100be5c5..e42c41a84 100644--- a/tests/engine/cli/eval.test.ts+++ b/tests/engine/cli/eval.test.ts@@ -49,8 +49,9 @@ heavy('eval CLI', () => {'--json','--code',`- const collection = figma.createVariableCollection('Eval spacing');- const variable = figma.createVariable('Padding', 'FLOAT', collection.id, 10);+ const collection = figma.variables.createVariableCollection('Eval spacing');+ const variable = figma.variables.createVariable('Padding', collection, 'FLOAT');+ variable.setValueForMode(collection.defaultModeId, 10);const frame = figma.createFrame();frame.layoutMode = 'HORIZONTAL';frame.primaryAxisSizingMode = 'AUTO';@@ -59,7 +60,7 @@ heavy('eval CLI', () => {child.resize(5, 5);frame.appendChild(child);openpencil.bindVariable(frame, 'paddingLeft', variable);- figma.setVariableValue(variable.id, collection.defaultModeId, 20);+ variable.setValueForMode(collection.defaultModeId, 20);return { padding: frame.paddingLeft, width: frame.width, childX: child.x };`])diff --git a/tests/engine/color/okhcl/basic.test.ts b/tests/engine/color/okhcl/basic.test.tsindex e5efd89f4..a30990193 100644--- a/tests/engine/color/okhcl/basic.test.ts+++ b/tests/engine/color/okhcl/basic.test.ts@@ -7,6 +7,7 @@ import {getFillOkHCL,getStrokeOkHCL,initCodec,+ OpenPencilAPI,okhclToRGBA,parseFigFile,rgbaToOkHCL,@@ -21,13 +22,14 @@ describe('OkHCL metadata', () => {test('applies rgba rendering color while preserving fill metadata', () => {const graph = new SceneGraph()const api = new FigmaAPI(graph)+ const openpencil = new OpenPencilAPI(api)const frame = api.createFrame()frame.fills = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]- frame.setFillOkHCL({ h: 240, c: 0.12, l: 0.7, a: 0.8 })+ openpencil.setFillOkHCL(frame, { h: 240, c: 0.12, l: 0.7, a: 0.8 })expect(frame.fills[0]?.color).toEqual(okhclToRGBA({ h: 240, c: 0.12, l: 0.7, a: 0.8 }))- expect(frame.getFillOkHCL()).toMatchObject({+ expect(openpencil.getFillOkHCL(frame)).toMatchObject({version: 1,kind: 'fill',index: 0,@@ -38,13 +40,14 @@ describe('OkHCL metadata', () => {test('applies rgba rendering color while preserving stroke metadata', () => {const graph = new SceneGraph()const api = new FigmaAPI(graph)+ const openpencil = new OpenPencilAPI(api)const frame = api.createFrame()frame.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 1, align: 'INSIDE' })]- frame.setStrokeOkHCL({ h: 20, c: 0.08, l: 0.6 })+ openpencil.setStrokeOkHCL(frame, { h: 20, c: 0.08, l: 0.6 })expect(frame.strokes[0]?.color).toEqual(okhclToRGBA({ h: 20, c: 0.08, l: 0.6 }))- expect(frame.getStrokeOkHCL()).toMatchObject({+ expect(openpencil.getStrokeOkHCL(frame)).toMatchObject({version: 1,kind: 'stroke',index: 0,@@ -66,12 +69,13 @@ describe('OkHCL metadata', () => {const graph = new SceneGraph()const api = new FigmaAPI(graph)+ const openpencil = new OpenPencilAPI(api)const frame = api.createFrame()frame.name = 'OKHCL frame'frame.fills = [solidFill({ r: 0, g: 0, b: 0, a: 1 })]frame.strokes = [solidStroke({ r: 0, g: 0, b: 0, a: 1 }, { weight: 1, align: 'INSIDE' })]- frame.setFillOkHCL({ h: 210, c: 0.1, l: 0.65 })- frame.setStrokeOkHCL({ h: 320, c: 0.09, l: 0.55, a: 0.9 })+ openpencil.setFillOkHCL(frame, { h: 210, c: 0.1, l: 0.65 })+ openpencil.setStrokeOkHCL(frame, { h: 320, c: 0.09, l: 0.55, a: 0.9 })const bytes = await exportFigFile(graph)const parsed = await parseFigFile(uint8ArrayToArrayBuffer(bytes))diff --git a/tests/engine/figma/api/auto-layout/basic.test.ts b/tests/engine/figma/api/auto-layout/basic.test.tsindex 92d4bf700..30afb12a0 100644--- a/tests/engine/figma/api/auto-layout/basic.test.ts+++ b/tests/engine/figma/api/auto-layout/basic.test.ts@@ -10,24 +10,6 @@ describe('auto-layout', () => {expect(frame.layoutMode).toBe('VERTICAL')})- test('layoutDirection', () => {- const api = createAPI()- const frame = api.createFrame()- expect(frame.layoutDirection).toBe('AUTO')- frame.layoutDirection = 'RTL'- expect(frame.layoutDirection).toBe('RTL')- })-- test('layoutDirection falls back to AUTO for legacy nodes with no stored value', () => {- const api = createAPI()- const frame = api.createFrame()- const raw = api.graph.getNode(frame.id)- expect(raw).toBeDefined()- if (!raw) return- Reflect.deleteProperty(raw as object, 'layoutDirection')- expect(frame.layoutDirection).toBe('AUTO')- })-test('itemSpacing', () => {const api = createAPI()const frame = api.createFrame()diff --git a/tests/engine/figma/api/create/component-from-node.test.ts b/tests/engine/figma/api/create/component-from-node.test.tsindex 66a05d255..e00a9f18f 100644--- a/tests/engine/figma/api/create/component-from-node.test.ts+++ b/tests/engine/figma/api/create/component-from-node.test.ts@@ -27,8 +27,9 @@ describe('createComponentFromNode', () => {test('preserves root variable bindings and explicit modes', () => {const api = createAPI()- const collection = api.createVariableCollection('Radii')- const variable = api.createVariable('radius/md', 'FLOAT', collection.id, 8)+ const collection = api.variables.createVariableCollection('Radii')+ const variable = api.variables.createVariable('radius/md', collection, 'FLOAT')+ variable.setValueForMode(collection.defaultModeId, 8)const frame = api.createFrame()frame.name = 'Card'diff --git a/tests/engine/figma/api/text/basic.test.ts b/tests/engine/figma/api/text/basic.test.tsindex f318b914e..431b98172 100644--- a/tests/engine/figma/api/text/basic.test.ts+++ b/tests/engine/figma/api/text/basic.test.ts@@ -41,13 +41,6 @@ describe('text', () => {expect(text.textAlignHorizontal).toBe('CENTER')})- test('textDirection', () => {- const api = createAPI()- const text = api.createText()- text.textDirection = 'RTL'- expect(text.textDirection).toBe('RTL')- })-test('textAutoResize', () => {const api = createAPI()const text = api.createText()diff --git a/tests/engine/figma/api/variables.test.ts b/tests/engine/figma/api/variables.test.tsindex 412e96792..a75c44dd0 100644--- a/tests/engine/figma/api/variables.test.ts+++ b/tests/engine/figma/api/variables.test.ts@@ -4,70 +4,318 @@ import { expectDefined } from '#tests/helpers/assert'import { createAPI } from './helpers'-describe('variables', () => {- test('getLocalVariables returns empty by default', () => {- const api = createAPI()- expect(api.getLocalVariables()).toEqual([])- })+// Expected values and messages were recorded by running the same calls in Figma desktop.- test('getLocalVariables returns added variables', () => {- const api = createAPI()- api.graph.addCollection({- id: 'col1',- name: 'Colors',- modes: [{ modeId: 'mode1', name: 'Default' }],- defaultModeId: 'mode1',- variableIds: []- })- api.graph.addVariable({- id: 'var1',- name: 'primary',- type: 'COLOR',- collectionId: 'col1',- valuesByMode: { mode1: { r: 1, g: 0, b: 0, a: 1 } },+function tokens() {+ const api = createAPI()+ const collection = api.variables.createVariableCollection('Tokens')+ const mode = collection.defaultModeId+ const size = api.variables.createVariable('size', collection, 'FLOAT')+ size.setValueForMode(mode, 4.5)+ const label = api.variables.createVariable('label', collection, 'STRING')+ const flag = api.variables.createVariable('flag', collection, 'BOOLEAN')+ const color = api.variables.createVariable('color', collection, 'COLOR')+ return { api, collection, mode, size, label, flag, color }+}++describe('figma.variables', () => {+ test('creates collections and variables with Figma’s shapes and defaults', () => {+ const { api, collection, mode, size, label, flag, color } = tokens()+ expect(collection.modes).toEqual([{ modeId: mode, name: 'Mode 1' }])+ expect(collection.variableIds).toEqual([size.id, label.id, flag.id, color.id])+ expect(collection).toMatchObject({ name: 'Tokens', remote: false, isExtension: false })+ expect(size).toMatchObject({+ name: 'size',+ resolvedType: 'FLOAT',+ variableCollectionId: collection.id,description: '',- hiddenFromPublishing: false+ remote: false,+ hiddenFromPublishing: false,+ scopes: ['ALL_SCOPES'],+ codeSyntax: {}})- expect(api.getLocalVariables().length).toBe(1)- expect(api.getLocalVariables('COLOR').length).toBe(1)- expect(api.getLocalVariables('FLOAT').length).toBe(0)+ expect([label, flag, color].map((variable) => variable.valuesByMode[mode])).toEqual([+ 'String value',+ false,+ { r: 1, g: 1, b: 1, a: 1 }+ ])+ expect(api.variables.getLocalVariables('FLOAT').map((variable) => variable.name)).toEqual([+ 'size'+ ])+ expect(api.variables.getVariableById(size.id)?.name).toBe('size')+ expect(api.variables.getVariableById('VariableID:9:9')).toBeNull()+ expect(api.variables.getVariableCollectionById('nope')).toBeNull()+ expect(api.variables.createVariable('by-id', collection.id, 'STRING').resolvedType).toBe(+ 'STRING'+ )})- test('getVariableById', () => {- const api = createAPI()- api.graph.addCollection({- id: 'col1',- name: 'Spacing',- modes: [{ modeId: 'mode1', name: 'Default' }],- defaultModeId: 'mode1',- variableIds: []+ test('async lookups return what the sync ones do', async () => {+ const { api, collection, size } = tokens()+ expect((await api.variables.getVariableByIdAsync(size.id))?.id).toBe(size.id)+ expect((await api.variables.getVariableCollectionByIdAsync(collection.id))?.id).toBe(+ collection.id+ )+ expect(await api.variables.getLocalVariablesAsync('BOOLEAN')).toHaveLength(1)+ expect(await api.variables.getLocalVariableCollectionsAsync()).toHaveLength(1)+ expect(await api.variables.createVariableAliasByIdAsync(size.id)).toEqual({+ type: 'VARIABLE_ALIAS',+ id: size.id})- api.graph.addVariable({- id: 'var1',- name: 'spacing-sm',- type: 'FLOAT',- collectionId: 'col1',- valuesByMode: { mode1: 8 },- description: '',- hiddenFromPublishing: false+ })++ test('refuses names and types as Figma does', () => {+ const { api, collection, size } = tokens()+ const types = '"BOOLEAN"|"COLOR"|"FLOAT"|"STRING"|"EASING"|"TIMING"'+ expect(() => api.variables.createVariable('x', collection, 'NUMBER' as 'FLOAT')).toThrow(+ `in createVariable: Property "resolvedType" failed validation: Invalid option: expected one of ${types}`+ )+ expect(() => api.variables.getLocalVariables('NUMBER' as 'FLOAT')).toThrow(+ `in getLocalVariables: Property "resolvedType" failed validation`+ )+ expect(() => api.variables.createVariable('size', collection, 'FLOAT')).toThrow(+ 'in createVariable: duplicate variable name'+ )+ expect(() => api.variables.createVariable('', collection, 'FLOAT')).toThrow(+ 'in createVariable: name cannot be empty'+ )+ expect(() => api.variables.createVariable('a.b', collection, 'FLOAT')).toThrow(+ 'in createVariable: invalid variable name'+ )+ const other = api.variables.createVariable('other', collection, 'FLOAT')+ other.name = 'renamed'+ expect(other.name).toBe('renamed')+ expect(() => {+ other.name = size.name+ }).toThrow('in set_name: duplicate variable name')+ })++ test('setValueForMode checks the type and mode, and takes RGB and references', () => {+ const { api, mode, size, label, color } = tokens()+ expect(() => size.setValueForMode(mode, 'x')).toThrow(+ `in setValueForMode: Mismatched variable resolved type for mode ${mode}`+ )+ expect(() => size.setValueForMode('1:999', 3)).toThrow(+ 'in setValueForMode: mode with id 1:999 not defined for variable'+ )+ expect(() => color.setValueForMode(mode, 3)).toThrow('Mismatched variable resolved type')+ color.setValueForMode(mode, { r: 1, g: 0, b: 0 })+ expect(color.valuesByMode[mode]).toEqual({ r: 1, g: 0, b: 0, a: 1 })++ const alias = api.variables.createVariableAlias(size)+ expect(alias).toEqual({ type: 'VARIABLE_ALIAS', id: size.id })+ expect(() => label.setValueForMode(mode, alias)).toThrow('Mismatched variable resolved type')+ const copy = api.variables.createVariable('copy', size.variableCollectionId, 'FLOAT')+ copy.setValueForMode(mode, alias)+ expect(copy.valuesByMode[mode]).toEqual(alias)+ })++ test('a reference that would make a variable read itself is ignored', () => {+ const { api, mode, size } = tokens()+ const copy = api.variables.createVariable('copy', size.variableCollectionId, 'FLOAT')+ copy.setValueForMode(mode, api.variables.createVariableAlias(size))+ size.setValueForMode(mode, api.variables.createVariableAlias(size))+ size.setValueForMode(mode, api.variables.createVariableAlias(copy))+ expect(size.valuesByMode[mode]).toBe(4.5)+ })++ test('resolveForConsumer reads the value a layer sees', () => {+ const { api, mode, size } = tokens()+ const copy = api.variables.createVariable('copy', size.variableCollectionId, 'FLOAT')+ copy.setValueForMode(mode, api.variables.createVariableAlias(size))+ expect(copy.resolveForConsumer(api.createRectangle())).toEqual({+ value: 4.5,+ resolvedType: 'FLOAT'})- const v = api.getVariableById('var1')- expect(expectDefined(v, 'spacing variable').name).toBe('spacing-sm')- expect(api.getVariableById('nonexistent')).toBeNull()})- test('getLocalVariableCollections', () => {- const api = createAPI()- api.graph.addCollection({- id: 'col1',- name: 'Colors',- modes: [{ modeId: 'mode1', name: 'Default' }],- defaultModeId: 'mode1',- variableIds: []+ test('modes copy the default values, rename, and the default mode can go', () => {+ const { collection, mode, size } = tokens()+ const dark = collection.addMode('Dark')+ expect(collection.modes.map((item) => item.name)).toEqual(['Mode 1', 'Dark'])+ expect(size.valuesByMode).toEqual({ [mode]: 4.5, [dark]: 4.5 })+ expect(() => collection.renameMode('1:999', 'x')).toThrow('in renameMode: Could not find mode')+ collection.removeMode(mode)+ expect(collection.modes).toEqual([{ name: 'Dark', modeId: dark }])+ expect(collection.defaultModeId).toBe(dark)+ })++ test('scopes the plugin API cannot name stay when a script sets scopes', () => {+ const { api, size } = tokens()+ expectDefined(api.graph.variables.get(size.id), 'size').scopes = ['GAP', 'TRANSFORM', 'STROKE']+ expect(size.scopes).toEqual(['GAP', 'STROKE_COLOR'])+ size.scopes = size.scopes.filter((scope) => scope !== 'GAP')+ expect(api.graph.variables.get(size.id)?.scopes).toEqual(['STROKE', 'TRANSFORM'])+ size.scopes = ['ALL_SCOPES']+ expect(api.graph.variables.get(size.id)?.scopes).toBeUndefined()+ })++ test('removing a variable or collection takes it out of the document', () => {+ const { api, collection, size } = tokens()+ size.remove()+ expect(api.variables.getLocalVariables().map((variable) => variable.name)).toEqual([+ 'label',+ 'flag',+ 'color'+ ])+ expect(collection.variableIds).not.toContain(size.id)+ collection.remove()+ expect(api.variables.getLocalVariables()).toEqual([])+ expect(api.variables.getLocalVariableCollections()).toEqual([])+ })+})++describe('node variable bindings', () => {+ test('setBoundVariable binds by Figma field names and shows the value', () => {+ const { api, size } = tokens()+ const rect = api.createRectangle()+ expect(rect.boundVariables).toEqual({})+ rect.setBoundVariable('width', size)+ expect(rect.width).toBe(4.5)+ expect(rect.boundVariables).toEqual({ width: { type: 'VARIABLE_ALIAS', id: size.id } })+ rect.setBoundVariable('cornerRadius', size)+ expect(Object.keys(rect.boundVariables)).toEqual([+ 'width',+ 'topLeftRadius',+ 'topRightRadius',+ 'bottomLeftRadius',+ 'bottomRightRadius'+ ])+ rect.setBoundVariable('height', size.id)+ expect(rect.height).toBe(4.5)+ rect.setBoundVariable('width', null)+ expect(rect.width).toBe(4.5)+ expect(rect.boundVariables.width).toBeUndefined()+ rect.setBoundVariable('minWidth', null)+ })++ test('setBoundVariable takes only the type Figma’s API allows for each field', () => {+ const { api, size, label, flag, color } = tokens()+ const rect = api.createRectangle()+ expect(() => rect.setBoundVariable('height', label)).toThrow(+ "in setBoundVariable: variable of resolved type 'STRING' cannot be bound to 'height'"+ )+ expect(() => rect.setBoundVariable('height', color)).toThrow(+ "variable of resolved type 'COLOR' cannot be bound to 'height'"+ )+ expect(() => rect.setBoundVariable('visible', label)).toThrow(+ "variable of resolved type 'STRING' cannot be bound to 'visible'"+ )+ expect(() => rect.setBoundVariable('visible', size)).toThrow(+ "variable of resolved type 'FLOAT' cannot be bound to 'visible'"+ )+ rect.setBoundVariable('visible', flag)+ expect(rect.visible).toBe(false)++ const text = api.createText()+ text.characters = 'Hi'+ expect(() => text.setBoundVariable('characters', size)).toThrow(+ "variable of resolved type 'FLOAT' cannot be bound to 'characters'"+ )+ text.setBoundVariable('characters', label)+ expect(text.characters).toBe('String value')+ expect(text.boundVariables).toEqual({ characters: { type: 'VARIABLE_ALIAS', id: label.id } })+ })++ test('text with no characters yet keeps a style binding for the characters typed later', () => {+ const { api, size } = tokens()+ const text = api.createText()+ text.setBoundVariable('fontSize', size)+ expect(text.boundVariables).toEqual({ fontSize: [{ type: 'VARIABLE_ALIAS', id: size.id }] })+ expect(text.fontSize).toBe(4.5)+ text.characters = 'Hello'+ expect(text.boundVariables).toEqual({ fontSize: [{ type: 'VARIABLE_ALIAS', id: size.id }] })+ expect(text.fontSize).toBe(4.5)+ expect(() => api.createText().setBoundVariable('fontWeight', size)).toThrow(+ 'in setBoundVariable: OpenPencil binds fontWeight only on text that has characters'+ )+ })++ test('setBoundVariable refuses a layer of a library definition, as other setters do', () => {+ const { api, size } = tokens()+ const component = api.graph.createNode('COMPONENT', api.currentPage.id, {+ name: 'Remote button',+ librarySource: {+ identity: { libraryId: 'design-system', assetKey: 'button', revisionId: 'r1' },+ sourceNodeId: 'source',+ readOnly: true+ }})- const cols = api.getLocalVariableCollections()- expect(cols.length).toBe(1)- expect(cols[0].name).toBe('Colors')+ const proxy = expectDefined(api.getNodeById(component.id), 'component')+ expect(() => proxy.setBoundVariable('width', size)).toThrow('belongs to library design-system')+ expect(component.boundVariables).toEqual({})+ })++ test('setBoundVariable refuses unknown fields and paints, and ignores fields a layer lacks', () => {+ const { api, size, color } = tokens()+ const rect = api.createRectangle()+ expect(() => rect.setBoundVariable('foo' as 'width', size)).toThrow(+ 'in setBoundVariable: Property "field" failed validation: Invalid option: expected one of "height"|"width"|"characters"|'+ )+ expect(() => rect.setBoundVariable('text' as 'width', size)).toThrow(+ 'Property "field" failed validation'+ )+ expect(() => rect.setBoundVariable('fills' as 'width', color)).toThrow(+ 'in setBoundVariable: fills and strokes variable bindings must be set on paints directly'+ )+ rect.setBoundVariable('paddingLeft', size)+ expect(rect.boundVariables).toEqual({})++ const frame = api.createFrame()+ frame.layoutMode = 'HORIZONTAL'+ frame.setBoundVariable('paddingLeft', size)+ frame.setBoundVariable('itemSpacing', size)+ expect(frame.itemSpacing).toBe(4.5)+ expect(Object.keys(frame.boundVariables)).toEqual(['paddingLeft', 'itemSpacing'])+ })++ test('paints bind their colour through setBoundVariableForPaint', () => {+ const { api, mode, size, color } = tokens()+ color.setValueForMode(mode, { r: 0, g: 0, b: 1 })+ const solid = {+ type: 'SOLID' as const,+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true+ }+ const paint = api.variables.setBoundVariableForPaint(solid, 'color', color)+ expect(paint.boundVariables).toEqual({ color: { type: 'VARIABLE_ALIAS', id: color.id } })+ expect(solid).not.toHaveProperty('boundVariables')+ expect(() => api.variables.setBoundVariableForPaint(solid, 'color', size)).toThrow(+ 'in setBoundVariableForPaint: can only bind color variables to color'+ )+ expect(api.variables.setBoundVariableForPaint(paint, 'color', null).boundVariables).toEqual({})++ const rect = api.createRectangle()+ rect.fills = [paint]+ expect(rect.boundVariables).toEqual({ fills: [{ type: 'VARIABLE_ALIAS', id: color.id }] })+ const [fill] = rect.fills as readonly { color: unknown; boundVariables?: unknown }[]+ expect(fill.color).toEqual({ r: 0, g: 0, b: 1, a: 1 })+ expect(fill.boundVariables).toEqual({ color: { type: 'VARIABLE_ALIAS', id: color.id } })+ rect.fills = [solid]+ expect(rect.boundVariables).toEqual({})+ })++ test('explicit modes are set and cleared per collection', () => {+ const { api, collection, mode, size } = tokens()+ const dark = collection.addMode('Dark')+ size.setValueForMode(dark, 10)+ const frame = api.createFrame()+ const child = api.createRectangle()+ frame.appendChild(child)+ child.setBoundVariable('width', size)+ frame.setExplicitVariableModeForCollection(collection, dark)+ expect(frame.explicitVariableModes).toEqual({ [collection.id]: dark })+ expect(child.resolvedVariableModes).toEqual({ [collection.id]: dark })+ expect(child.width).toBe(10)+ expect(() => frame.setExplicitVariableModeForCollection(collection, '1:999')).toThrow(+ `in setExplicitVariableModeForCollection: Could not find modeId ${collection.id} in variable set with variableCollectionId: '1:999'`+ )+ frame.clearExplicitVariableModeForCollection(collection)+ expect(frame.explicitVariableModes).toEqual({})+ expect(child.width).toBe(4.5)+ frame.setExplicitVariableModeForCollection(collection.id, mode)+ expect(frame.explicitVariableModes).toEqual({ [collection.id]: mode })})test('exposes explicit and inherited variable modes on nodes', () => {@@ -95,16 +343,10 @@ describe('variables', () => {expect(Object.isFrozen(child.resolvedVariableModes)).toBe(true)})- test('getVariableCollectionById', () => {+ test('figma has no variable members of its own besides figma.variables', () => {const api = createAPI()- api.graph.addCollection({- id: 'col1',- name: 'Colors',- modes: [{ modeId: 'mode1', name: 'Default' }],- defaultModeId: 'mode1',- variableIds: []- })- expect(api.getVariableCollectionById('col1')?.name).toBe('Colors')- expect(api.getVariableCollectionById('nonexistent')).toBeNull()+ for (const name of ['getVariableById', 'createVariable', 'setVariableValue', 'bindVariable'])+ expect(name in api).toBe(false)+ expectDefined(api.variables, 'figma.variables')})})diff --git a/tests/engine/tools/cli.test.ts b/tests/engine/tools/cli.test.tsindex 7c038d23a..3b2ec2271 100644--- a/tests/engine/tools/cli.test.ts+++ b/tests/engine/tools/cli.test.ts@@ -206,8 +206,8 @@ heavy('CLI tool operations via eval', () => {test('list variables from fixture', async () => {const { stdout, exitCode } = await evalCode(`- const vars = figma.getLocalVariables()- const cols = figma.getLocalVariableCollections()+ const vars = figma.variables.getLocalVariables()+ const cols = figma.variables.getLocalVariableCollections()return { variables: vars.length, collections: cols.length }`)expect(exitCode).toBe(0)diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txtindex 61b45f998..41c7ede56 100644--- a/tools/checks/test-homes/engine-baseline.txt+++ b/tools/checks/test-homes/engine-baseline.txt@@ -144,7 +144,6 @@ tests/engine/figma/api/components.test.tstests/engine/figma/api/corner/radius.test.tstests/engine/figma/api/create/combine-as-variants.test.tstests/engine/figma/api/create/component-from-node.test.ts-tests/engine/figma/api/create/expose-instance-swap.test.tstests/engine/figma/api/create/instance-fill-override.test.tstests/engine/figma/api/document/pages.test.tstests/engine/figma/api/expanded.test.ts