Skip to content

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

feat!: bind text content to text and number variables (#1344)

Danila Poyarkovc791215e65d6
diff --git a/changes/1344/added.md b/changes/1344/added.md
new file mode 100644
index 000000000..a1a515d97
--- /dev/null
+++ b/changes/1344/added.md
@@ -0,0 +1 @@
+- A text layer's content binds to a text or number variable from the layer header, as in Figma; a number shows as text, and typing over bound text detaches the variable.
diff --git a/changes/1344/breaking.md b/changes/1344/breaking.md
new file mode 100644
index 000000000..8df7ba9b4
--- /dev/null
+++ b/changes/1344/breaking.md
@@ -0,0 +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.
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index 2cfe89c50..312de123b 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -22,6 +22,7 @@ import {
type TextEditSession
} from './text/session'
import type { EditorContext } from './types'
+import { createVariableBindingActions } from './variable-bindings'
/**
* Path text is edited by re-flowing glyph OUTLINES along its path. When the font
@@ -106,6 +107,7 @@ function applyTextInstanceOverride(
export function createTextActions(ctx: EditorContext) {
let activeSession: TextEditSession | null = null
+ const variableBindings = createVariableBindingActions(ctx)
/**
* Typing resizes auto-sized text and lays out its auto-layout ancestors as it goes, so a Hug
@@ -178,7 +180,8 @@ export function createTextActions(ctx: EditorContext) {
}
const instanceOverridesAfter = snapshotInstanceOverrides(ctx, containingInstances)
- // Text a property drives becomes the property's value too, in the same undo step.
+ // Text a property drives becomes the property's value too, and typing over text a variable
+ // decides lets go of the variable, as in Figma, both in the same undo step.
ctx.undo.runBatch('Edit text', () => {
ctx.undo.push({
label: 'Edit text',
@@ -206,6 +209,8 @@ export function createTextActions(ctx: EditorContext) {
}
})
if (before.text !== after.text) {
+ if (node && 'text' in node.boundVariables)
+ variableBindings.unbindVariable(result.nodeId, 'text')
applyBoundTextEdit(ctx, result.nodeId, after.text)
applyGeneratedTextNameEdit(ctx, result.nodeId, after.text)
}
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 6eedcf6ab..389b6ca95 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -391,16 +391,6 @@ export class FigmaAPI implements NodeProxyHost {
this.graph.removeCollection(id)
}
- bindVariable(nodeId: string, field: string, variableId: string): void {
- this.graph.bindVariable(nodeId, field, variableId)
- reconcileVariableLayouts(this.graph, { subtrees: [nodeId] })
- }
-
- unbindVariable(nodeId: string, field: string): void {
- this.graph.unbindVariable(nodeId, field)
- reconcileVariableLayouts(this.graph, { subtrees: [nodeId] })
- }
-
// --- Boolean Operations ---
private _booleanOperation(
diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.ts
index cdbb988de..80f31d5e8 100644
--- a/packages/core/src/openpencil-api/index.ts
+++ b/packages/core/src/openpencil-api/index.ts
@@ -25,9 +25,11 @@ import {
type NewComment
} from './comments'
import { getStatus, listStatuses, setStatus, type StatusInfo } from './statuses'
+import { bindVariable, unbindVariable, type VariableRef } from './variables'
export { BehaviourHandle, type NodeRef } from './behaviours'
export type { StatusInfo } from './statuses'
+export type { VariableRef } from './variables'
export {
CommentHandle,
DEFAULT_COMMENT_AUTHOR,
@@ -79,6 +81,21 @@ export class OpenPencilAPI {
return resolved
}
+ /**
+ * Bind a layer field to a variable from `figma.getLocalVariables()`, 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.
+ */
+ bindVariable(node: NodeRef, field: string, variable: VariableRef): void {
+ bindVariable(this.figma.graph, node, field, variable)
+ }
+
+ /** Let a layer field go of its variable, keeping the value the variable last gave it. */
+ unbindVariable(node: NodeRef, field: string): void {
+ unbindVariable(this.figma.graph, node, field)
+ }
+
/** The behaviour kinds, after Reka UI's primitives, with the values and parts each binds. */
get behaviourKinds() {
return BEHAVIOUR_KINDS.map((kind) => ({ kind, ...structuredClone(BEHAVIOUR_CONTRACTS[kind]) }))
diff --git a/packages/core/src/openpencil-api/variables.ts b/packages/core/src/openpencil-api/variables.ts
new file mode 100644
index 000000000..cc597a481
--- /dev/null
+++ b/packages/core/src/openpencil-api/variables.ts
@@ -0,0 +1,38 @@
+import 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()`. */
+export type VariableRef = { readonly id: string }
+
+function variableOf(graph: SceneGraph, ref: VariableRef) {
+ const variable = graph.variables.get(ref.id)
+ if (!variable) throw new Error(`No variable ${ref.id}`)
+ return variable
+}
+
+/**
+ * Binds a layer field to a variable as the layer panel does, which takes more than Figma's
+ * `setBoundVariable`: text content a text or number variable, visibility a boolean or text one.
+ */
+export function bindVariable(
+ graph: SceneGraph,
+ node: NodeRef,
+ field: string,
+ variable: VariableRef
+): void {
+ const target = nodeOf(graph, node)
+ graph.bindVariable(target.id, field, variableOf(graph, variable).id)
+ reconcileVariableLayouts(graph, { subtrees: [target.id] })
+}
+
+/** Lets a layer field go of its variable; the field keeps the value the variable last gave it. */
+export function unbindVariable(graph: SceneGraph, node: NodeRef, field: string): void {
+ const target = nodeOf(graph, node)
+ if (!(field in target.boundVariables))
+ throw new Error(`${target.name} has no variable bound to ${field}`)
+ 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.ts
index e2c496b1d..32a94c117 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`), and statuses (`openpencil.statuses`, `openpencil.getStatus`, `openpencil.setStatus`).',
+ '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)`).',
execution: { kind: 'async', mutation: 'document' },
capabilities: ['document:read', 'document:write', 'code:execute'],
availability: 'eval',
diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.ts
index 286c3c8e6..47b25d0e0 100644
--- a/packages/core/src/tools/variables/bindings.ts
+++ b/packages/core/src/tools/variables/bindings.ts
@@ -1,5 +1,6 @@
import * as v from 'valibot'
+import { OpenPencilAPI } from '#core/openpencil-api'
import { nodeIdInput } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -21,7 +22,8 @@ export const bindVariable = defineTool({
'"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' +
'"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' +
'"gridRowGap", "gridColumnGap". ' +
- 'For STRING: "fontFamily". For BOOLEAN: "visible".'
+ 'For STRING: "fontFamily". For STRING or FLOAT: "text", a number shown as text. ' +
+ 'For BOOLEAN or STRING: "visible", text showing the layer unless empty or "false", "no", "off".'
)
),
variable_id: v.pipe(v.string(), v.description('Variable ID'))
@@ -32,7 +34,7 @@ export const bindVariable = defineTool({
const variable = figma.getVariableById(args.variable_id)
if (!variable) return { error: `Variable "${args.variable_id}" not found` }
try {
- figma.bindVariable(args.node_id, args.field, args.variable_id)
+ new OpenPencilAPI(figma).bindVariable(args.node_id, args.field, variable)
} catch (err) {
return { error: err instanceof Error ? err.message : String(err) }
}
diff --git a/packages/core/src/tools/variables/unbind.ts b/packages/core/src/tools/variables/unbind.ts
index 19c4ab5b3..c6caeaad0 100644
--- a/packages/core/src/tools/variables/unbind.ts
+++ b/packages/core/src/tools/variables/unbind.ts
@@ -1,5 +1,6 @@
import * as v from 'valibot'
+import { OpenPencilAPI } from '#core/openpencil-api'
import { nodeIdInput } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -20,7 +21,7 @@ export const unbindVariable = defineTool({
'"topLeftRadius", "topRightRadius", "bottomLeftRadius", "bottomRightRadius", ' +
'"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' +
'"gridRowGap", "gridColumnGap". ' +
- 'For STRING: "fontFamily". For BOOLEAN: "visible".'
+ 'Text: "text", "fontFamily". Visibility: "visible".'
)
)
}),
@@ -32,7 +33,7 @@ export const unbindVariable = defineTool({
if (!boundValue) {
return { error: `No binding found for field "${args.field}" on node "${args.node_id}"` }
}
- figma.unbindVariable(args.node_id, args.field)
+ new OpenPencilAPI(figma).unbindVariable(args.node_id, args.field)
return { unbound: true, node_id: args.node_id, field: args.field }
}
})
diff --git a/packages/core/tests/editor/history/atomic-tools.test.ts b/packages/core/tests/editor/history/atomic-tools.test.ts
index d5e763155..970bba53d 100644
--- a/packages/core/tests/editor/history/atomic-tools.test.ts
+++ b/packages/core/tests/editor/history/atomic-tools.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test'
+import { OpenPencilAPI } from '@open-pencil/core'
import { createEditor, executeAtomicTool } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { ALL_TOOLS, type ToolDef } from '@open-pencil/core/tools'
@@ -73,7 +74,7 @@ describe('atomic agent tools', () => {
a: 1
})
tool('set_fill').execute(figma, { id: rectangle.id, color: '#ff0000' })
- figma.bindVariable(rectangle.id, 'fills/0/color', variable.id)
+ new OpenPencilAPI(figma).bindVariable(rectangle.id, 'fills/0/color', variable)
const page = figma.createPage()
figma.currentPage = page
executeAtomicTool(editor, figma, tool('set_variable'), {
diff --git a/packages/core/tests/figma-api/variables/scaled-bindings.test.ts b/packages/core/tests/figma-api/variables/scaled-bindings.test.ts
index 6cbd9cb62..ee2be34af 100644
--- a/packages/core/tests/figma-api/variables/scaled-bindings.test.ts
+++ b/packages/core/tests/figma-api/variables/scaled-bindings.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 { SceneGraph } from '@open-pencil/scene-graph'
@@ -22,7 +23,7 @@ test('Figma API edits reconcile existing scaled bindings without an editor', ()
expect(frame.paddingLeft).toBe(5)
expect(frame.width).toBe(10)
expect(child.x).toBe(5)
- api.unbindVariable(frame.id, 'paddingLeft')
+ new OpenPencilAPI(api).unbindVariable(frame.id, 'paddingLeft')
api.setVariableValue(first.id, collection.defaultModeId, 80)
expect(frame.paddingLeft).toBe(5)
})
diff --git a/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
index 95ee9af7b..96bccd8f8 100644
--- a/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
+++ b/packages/core/tests/io/formats/fig/export/binding/authoring.test.ts
@@ -5,6 +5,7 @@ import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixture
import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
import * as v from 'valibot'
+import { OpenPencilAPI } from '@open-pencil/core'
import { createEditor } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
@@ -43,9 +44,14 @@ function document(inherited = false) {
for (const caller of ['editor', 'api'] as const) {
test(`${caller} authors new root and nested aliases in occurrence-owner units`, async () => {
const { graph, root, nested } = document()
- const writer = caller === 'editor' ? createEditor({ graph }) : new FigmaAPI(graph)
- writer.bindVariable(nested.id, 'paddingRight', '293742:7')
- writer.bindVariable(root.id, 'paddingRight', '293742:7')
+ const editor = caller === 'editor' ? createEditor({ graph }) : undefined
+ const openpencil = new OpenPencilAPI(new FigmaAPI(graph))
+ const bind = (id: string) =>
+ editor
+ ? editor.bindVariable(id, 'paddingRight', '293742:7')
+ : openpencil.bindVariable(id, 'paddingRight', { id: '293742:7' })
+ bind(nested.id)
+ bind(root.id)
expect(nested.paddingRight).toBe(6)
expect(root.paddingRight).toBe(6)
expect(nested.width).toBe(17)
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.ts
index 6108ca511..ddb5d8ffd 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
@@ -4,6 +4,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
import { inheritedNestedBindingRecords } from '#core-tests/helpers/fig/nested-binding'
+import { OpenPencilAPI } from '@open-pencil/core'
import { createEditor } from '@open-pencil/core/editor'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
@@ -22,16 +23,17 @@ test('a placed binding does not freeze an unrelated inherited binding', async ()
const template = graph.getChildren(expectDefined(sources.get('1:4')))[0]
const nested = graph.getChildren(root)[0]
const api = new FigmaAPI(graph)
+ const openpencil = new OpenPencilAPI(api)
createEditor({ graph })
- api.bindVariable(nested.id, 'paddingLeft', '293742:7')
- api.bindVariable(template.id, 'paddingRight', '293733:7')
+ openpencil.bindVariable(nested.id, 'paddingLeft', { id: '293742:7' })
+ openpencil.bindVariable(template.id, 'paddingRight', { id: '293733:7' })
await Promise.resolve()
expect(nested.boundVariables.paddingLeft).toBe('293742:7')
expect(nested.boundVariables.paddingRight).toBe('293733:7')
expect(nested.variableBindingScales.paddingRight).toBe(0.25)
expect(nested.paddingRight).toBe(5)
- api.unbindVariable(nested.id, 'paddingRight')
- api.bindVariable(template.id, 'paddingTop', '293733:7')
+ openpencil.unbindVariable(nested.id, 'paddingRight')
+ openpencil.bindVariable(template.id, 'paddingTop', { id: '293733:7' })
await Promise.resolve()
expect(nested.boundVariables.paddingRight).toBeUndefined()
expect(nested.boundVariables.paddingTop).toBe('293733:7')
@@ -48,11 +50,12 @@ test('definition rescale preserves an explicit placed binding in its declaring u
const template = graph.getChildren(expectDefined(sources.get('1:4')))[0]
const nested = graph.getChildren(root.id)[0]
const api = new FigmaAPI(graph)
+ const openpencil = new OpenPencilAPI(api)
createEditor({ graph })
expectDefined(api.getNodeById(root.id)).rescale(0.5)
expectDefined(api.getNodeById(template.id)).rescale(2)
await Promise.resolve()
- api.bindVariable(nested.id, 'paddingLeft', '293742:7')
+ openpencil.bindVariable(nested.id, 'paddingLeft', { id: '293742:7' })
expect([root.width, nested.width, nested.paddingLeft]).toEqual([20.5, 10.5, 3])
expectDefined(api.getNodeById(template.id)).rescale(2)
await Promise.resolve()
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.ts
index 74608ea33..15cc8606e 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
@@ -4,6 +4,7 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { CapturedFigRecords, readFixture } from '#core-tests/helpers/fig/fixtures'
import { createEditor } from '@open-pencil/core/editor'
+import { OpenPencilAPI } from '@open-pencil/core'
import { FigmaAPI } from '@open-pencil/core/figma-api'
import { exportFigFile } from '@open-pencil/core/io'
import { initCodec } from '@open-pencil/core/kiwi'
@@ -24,8 +25,9 @@ for (const scale of [0.5, 2]) {
const root = expectDefined(graph.getNode(expectDefined(sources.get('293733:8'))))
const nested = expectDefined(graph.getChildren(root.id)[0])
const api = new FigmaAPI(graph)
- api.bindVariable(root.id, 'paddingRight', '293742:7')
- api.bindVariable(nested.id, 'paddingRight', '293742:7')
+ const openpencil = new OpenPencilAPI(api)
+ openpencil.bindVariable(root.id, 'paddingRight', { id: '293742:7' })
+ openpencil.bindVariable(nested.id, 'paddingRight', { id: '293742:7' })
if (literalClaim) {
createEditor({ graph }).updateNodeWithUndo(root.id, { paddingLeft: 12 })
setInstanceOverride(root.instanceOverrides, root.id, root.id, 'paddingLeft', 12)
diff --git a/packages/core/tests/openpencil-api/variables.test.ts b/packages/core/tests/openpencil-api/variables.test.ts
new file mode 100644
index 000000000..c48e1ccd7
--- /dev/null
+++ b/packages/core/tests/openpencil-api/variables.test.ts
@@ -0,0 +1,47 @@
+import { expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { compileScript } from '@open-pencil/core/tools'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function document() {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Copy')
+ graph.createVariable('price', 'FLOAT', collection.id, 42.5)
+ graph.createVariable('state', 'STRING', collection.id, 'off')
+ return { graph, figma: new FigmaAPI(graph) }
+}
+
+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 label = figma.createText()
+ openpencil.bindVariable(label, 'text', price)
+ openpencil.bindVariable(label, 'visible', state)
+ return { id: label.id, figmaBinds: 'bindVariable' in figma }
+ `)(figma)
+ const { id, figmaBinds } = result as { id: string; figmaBinds: boolean }
+ expect(figmaBinds).toBe(false)
+ expect(graph.getNode(id)).toMatchObject({ text: '42.50', visible: false })
+})
+
+test('unbinding keeps the value the variable last gave, and errors name the layer', async () => {
+ const { graph, figma } = document()
+ const id = (await compileScript(`
+ const label = figma.createText()
+ label.name = 'Label'
+ openpencil.bindVariable(label, 'text', figma.getLocalVariables()[0])
+ openpencil.unbindVariable(label, 'text')
+ return label.id
+ `)(figma)) as string
+ expect(graph.getNode(id)).toMatchObject({ text: '42.50', boundVariables: {} })
+ await expect(
+ compileScript(`openpencil.unbindVariable(${JSON.stringify(id)}, 'text')`)(figma)
+ ).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])`
+ )(figma)
+ ).rejects.toThrow('Cannot bind FLOAT variable to string field "fontFamily"')
+})
diff --git a/packages/docs/es/programmable/cli/scripting.md b/packages/docs/es/programmable/cli/scripting.md
index 53c797c11..247310e7f 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 `bindVariable` y `unbindVariable`.
+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`.
### Propiedades
diff --git a/packages/docs/pl/programmable/cli/scripting.md b/packages/docs/pl/programmable/cli/scripting.md
index 0f1de5104..17d0ca7ae 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()`, `figma.getLocalVariables()` i `figma.bindVariable()`, pozostają zgodne z Figma Plugin API.
+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)`.
### Właściwości
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 4daa28dd8..1b9987a70 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -38,6 +38,16 @@ openpencil.setVariableFormula('Copy', 'greeting', 'if({compact}, "Hi", "Hello, "
References use variable names or `{Collection::variable}` and are stored as stable IDs. Formulas use stored units, so lengths are in pixels. See [Variables](/user-guide/variables) for operators and export limitations.
+## 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`.
+
+```js
+const [price] = figma.getLocalVariables('FLOAT')
+const label = figma.currentPage.findOne((node) => node.name === 'Price')
+openpencil.bindVariable(label, 'text', price)
+```
+
## Query nodes
```sh
@@ -210,8 +220,6 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `figma.deleteVariable(id)`
- `figma.createVariableCollection(name)`
- `figma.deleteVariableCollection(id)`
-- `figma.bindVariable(nodeId, field, variableId)`
-- `figma.unbindVariable(nodeId, field)`
### Properties
diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md
index 3a1a0f4dc..9bc10bd98 100644
--- a/packages/docs/ru/programmable/cli/scripting.md
+++ b/packages/docs/ru/programmable/cli/scripting.md
@@ -121,8 +121,8 @@ API намеренно близок к Figma Plugin API, но работает
- `figma.deleteVariable(id)`
- `figma.createVariableCollection(name)`
- `figma.deleteVariableCollection(id)`
-- `figma.bindVariable(nodeId, field, variableId)`
-- `figma.unbindVariable(nodeId, field)`
+- `openpencil.bindVariable(node, field, variable)` — привязки как в панели слоя: текст принимает текстовую или числовую переменную, видимость — логическую или текстовую
+- `openpencil.unbindVariable(node, field)`
### Свойства
diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts
index f95ff6d74..ef3b43375 100644
--- a/packages/scene-graph/src/variables.ts
+++ b/packages/scene-graph/src/variables.ts
@@ -20,6 +20,7 @@ import {
import {
BOOLEAN_BINDING_FIELDS,
STRING_BINDING_FIELDS,
+ TEXT_CONTENT_VARIABLE_TYPES,
VISIBILITY_VARIABLE_TYPES
} from './variables/fields'
@@ -265,7 +266,9 @@ export function bindVariable(
throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`)
}
- if (STRING_BINDING_FIELDS.has(field) && variable.type !== 'STRING') {
+ const textTypes: readonly VariableType[] =
+ field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']
+ if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(variable.type)) {
throw new Error(`Cannot bind ${variable.type} variable to string field "${field}"`)
}
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index 7eedea714..6ccff016d 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -7,7 +7,11 @@ import type { VariableModeFallback } from '../variables'
import { NUMERIC_FIELDS, isNumericVariableBindingField } from './fields'
import { variableText, variableTruthy } from './text'
import { variableValueReferences } from './value'
-export { isNumericVariableBindingField, VISIBILITY_VARIABLE_TYPES } from './fields'
+export {
+ isNumericVariableBindingField,
+ TEXT_CONTENT_VARIABLE_TYPES,
+ VISIBILITY_VARIABLE_TYPES
+} from './fields'
/** New declarations belong to the outermost occurrence, bounded by a component definition. */
export function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {
diff --git a/packages/scene-graph/src/variables/fields.ts b/packages/scene-graph/src/variables/fields.ts
index b2d37d089..d502e9c0b 100644
--- a/packages/scene-graph/src/variables/fields.ts
+++ b/packages/scene-graph/src/variables/fields.ts
@@ -41,6 +41,15 @@ export function isNumericVariableBindingField(field: string): boolean {
/** Text content and font family are the string-valued bindings a node accepts. */
export const STRING_BINDING_FIELDS: ReadonlySet<string> = new Set(['text', 'fontFamily'])
+/**
+ * The variable types text content binds to: text, or a number shown as text, as Figma's layer
+ * panel offers. Figma's plugin API takes text alone; font family stays text-only.
+ */
+export const TEXT_CONTENT_VARIABLE_TYPES = [
+ 'STRING',
+ 'FLOAT'
+] as const satisfies readonly VariableType[]
+
/** Visibility is the only boolean-valued binding a node accepts. */
export const BOOLEAN_BINDING_FIELDS: ReadonlySet<string> = new Set(['visible'])
diff --git a/packages/scene-graph/tests/basic/variables.test.ts b/packages/scene-graph/tests/basic/variables.test.ts
index e5d0cc88c..b73c9717b 100644
--- a/packages/scene-graph/tests/basic/variables.test.ts
+++ b/packages/scene-graph/tests/basic/variables.test.ts
@@ -276,6 +276,29 @@ describe('Variables', () => {
)
})
+ test('text content binds a text or number variable and shows a number as text', () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Copy')
+ const mode = collection.defaultModeId
+ const label = graph.createVariable('label', 'STRING', collection.id, 'Buy')
+ const count = graph.createVariable('count', 'FLOAT', collection.id, 42.5)
+ const flag = graph.createVariable('flag', 'BOOLEAN', collection.id, true)
+ const node = graph.createNode('TEXT', graph.getPages()[0].id, { text: 'Hello' })
+
+ graph.bindVariable(node.id, 'text', count.id)
+ expect(resolvedValueBindings(graph, node)).toMatchObject({ text: '42.50' })
+ count.valuesByMode[mode] = 3
+ expect(resolvedValueBindings(graph, node)).toMatchObject({ text: '3' })
+ graph.bindVariable(node.id, 'text', label.id)
+ expect(resolvedValueBindings(graph, node)).toMatchObject({ text: 'Buy' })
+ expect(() => graph.bindVariable(node.id, 'text', flag.id)).toThrow(
+ 'Cannot bind BOOLEAN variable to string field "text"'
+ )
+ expect(() => graph.bindVariable(node.id, 'fontFamily', count.id)).toThrow(
+ 'Cannot bind FLOAT variable to string field "fontFamily"'
+ )
+ })
+
test('removing variable cleans up bindings', () => {
const graph = new SceneGraph()
graph.addCollection({
diff --git a/packages/vue/src/controls/binding-provider/index.ts b/packages/vue/src/controls/binding-provider/index.ts
index 0bd0a39af..90978b6fa 100644
--- a/packages/vue/src/controls/binding-provider/index.ts
+++ b/packages/vue/src/controls/binding-provider/index.ts
@@ -22,4 +22,5 @@ export type {
BindingTarget,
BoundEditPolicy
} from '#vue/controls/binding-provider/types'
+export { useTextContentBindingProvider } from '#vue/controls/binding-provider/text'
export { useVisibilityBindingProvider } from '#vue/controls/binding-provider/visibility'
diff --git a/packages/vue/src/controls/binding-provider/text.ts b/packages/vue/src/controls/binding-provider/text.ts
new file mode 100644
index 000000000..fa05f5898
--- /dev/null
+++ b/packages/vue/src/controls/binding-provider/text.ts
@@ -0,0 +1,22 @@
+import type { Editor } from '@open-pencil/core/editor'
+import { TEXT_CONTENT_VARIABLE_TYPES, variableText } from '@open-pencil/scene-graph'
+
+import { useOpenPencilBindingProvider } from '#vue/controls/binding-provider/open-pencil'
+import type { BindingTarget } from '#vue/controls/binding-provider/types'
+
+/** What a variable shows as a text layer's content: text as it is, a number formatted as text. */
+function resolveTextContent(editor: Editor, id: string, target?: BindingTarget) {
+ return variableText(
+ target
+ ? editor.graph.resolveVariableForNode(target.nodeId, id)
+ : editor.graph.resolveVariable(id)
+ )
+}
+
+/** Binds a text layer's content to a text or number variable, as Figma's layer panel does. */
+export function useTextContentBindingProvider() {
+ return useOpenPencilBindingProvider<string>({
+ types: TEXT_CONTENT_VARIABLE_TYPES,
+ resolve: resolveTextContent
+ })
+}
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index d4160c30c..8e03b6d77 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -402,6 +402,7 @@
"createComponentProperty": "Eigenschaft erstellen…",
"applyComponentProperty": "Komponenteneigenschaft auf {field} anwenden",
"applyVariableOrProperty": "Variable/Eigenschaft anwenden",
+ "applyVariableToTextContent": "Variable auf Textinhalt anwenden",
"propertiesInComponent": "Eigenschaften in {name}",
"goToComponentProperty": "Zur Eigenschaft",
"detachComponentProperty": "Eigenschaft trennen",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index f90adf18a..7f00137ad 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -420,6 +420,7 @@
"createComponentProperty": "Crear propiedad…",
"applyComponentProperty": "Aplicar propiedad de componente a {field}",
"applyVariableOrProperty": "Aplicar variable/propiedad",
+ "applyVariableToTextContent": "Aplicar variable al contenido de texto",
"propertiesInComponent": "Propiedades de {name}",
"goToComponentProperty": "Ir a la propiedad",
"detachComponentProperty": "Separar propiedad",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 91a418bef..608adbfec 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -402,6 +402,7 @@
"createComponentProperty": "Créer une propriété…",
"applyComponentProperty": "Appliquer une propriété de composant à {field}",
"applyVariableOrProperty": "Appliquer une variable/propriété",
+ "applyVariableToTextContent": "Appliquer une variable au contenu du texte",
"propertiesInComponent": "Propriétés de {name}",
"goToComponentProperty": "Aller à la propriété",
"detachComponentProperty": "Dissocier la propriété",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 1f8790f8b..2d52fd638 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -402,6 +402,7 @@
"createComponentProperty": "Crea proprietà…",
"applyComponentProperty": "Applica proprietà del componente a {field}",
"applyVariableOrProperty": "Applica variabile/proprietà",
+ "applyVariableToTextContent": "Applica variabile al contenuto del testo",
"propertiesInComponent": "Proprietà di {name}",
"goToComponentProperty": "Vai alla proprietà",
"detachComponentProperty": "Scollega proprietà",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index d7545b018..06e622239 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -414,6 +414,7 @@
"createComponentProperty": "プロパティを作成…",
"applyComponentProperty": "{field}にコンポーネントプロパティを適用",
"applyVariableOrProperty": "変数/プロパティを適用",
+ "applyVariableToTextContent": "テキストの内容に変数を適用",
"propertiesInComponent": "{name}のプロパティ",
"goToComponentProperty": "プロパティに移動",
"detachComponentProperty": "プロパティを解除",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index d32e9c96b..36754b7ed 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -408,6 +408,7 @@
"createComponentProperty": "Utwórz właściwość…",
"applyComponentProperty": "Zastosuj właściwość komponentu do: {field}",
"applyVariableOrProperty": "Zastosuj zmienną/właściwość",
+ "applyVariableToTextContent": "Zastosuj zmienną do treści tekstu",
"propertiesInComponent": "Właściwości w: {name}",
"goToComponentProperty": "Przejdź do właściwości",
"detachComponentProperty": "Odłącz właściwość",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 28f5db991..1492e87df 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -408,6 +408,7 @@
"createComponentProperty": "Создать свойство…",
"applyComponentProperty": "Применить свойство компонента к полю «{field}»",
"applyVariableOrProperty": "Применить переменную или свойство",
+ "applyVariableToTextContent": "Применить переменную к тексту",
"propertiesInComponent": "Свойства компонента «{name}»",
"goToComponentProperty": "Перейти к свойству",
"detachComponentProperty": "Отвязать свойство",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 07e06378f..5b4884b84 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -396,6 +396,7 @@
"createComponentProperty": "创建属性…",
"applyComponentProperty": "将组件属性应用到{field}",
"applyVariableOrProperty": "应用变量/属性",
+ "applyVariableToTextContent": "将变量应用到文本内容",
"propertiesInComponent": "{name}中的属性",
"goToComponentProperty": "转到属性",
"detachComponentProperty": "分离属性",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 604cbf1a5..757d4b1d8 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -102,6 +102,7 @@ export const panelMessageDefaults = {
createComponentProperty: 'Create property…',
applyComponentProperty: params('Apply component property to {field}'),
applyVariableOrProperty: 'Apply variable/property',
+ applyVariableToTextContent: 'Apply variable to text content',
propertiesInComponent: params('Properties in {name}'),
goToComponentProperty: 'Go to property',
detachComponentProperty: 'Detach property',
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index d5f927154..8d951e74c 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -408,6 +408,7 @@ export {
useOpenPencilBindingProvider,
useNumberBindingProvider,
useColorBindingProvider,
+ useTextContentBindingProvider,
useVisibilityBindingProvider
} from '#vue/controls/binding-provider'
export type {
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 56bf88aa2..820460658 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -26,6 +26,8 @@ Use `openpencil --help`, per-command help, and the connected MCP server’s tool
Inside `eval`, use `openpencil.setVariableFormula('Spacing', 'large', '{base} * 2')` for numeric formulas or `openpencil.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}')` for Boolean formulas, which use `and`, `or`, `not` and number comparisons. Collections and variables must already exist. An optional fourth argument selects a mode by name; otherwise the default mode is edited. The call validates before mutation and returns the resolved value. Length formulas use stored pixels. The CSS stylesheet writes number formulas as `calc()`; design-token files hold the result with the formula in `$extensions`.
+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.
+
## Requirements
```bash
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 917438606..18cd4695a 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -47,6 +47,8 @@ import StatusesSection from './properties/status/StatusesSection.vue'
import StatusSection from './properties/status/StatusSection.vue'
import StickySection from './properties/sticky/StickySection.vue'
import StrokeSection from './properties/stroke/StrokeSection.vue'
+import TextContentControl from './properties/text-content/TextContentControl.vue'
+import TextContentSection from './properties/text-content/TextContentSection.vue'
import TypographySection from './properties/TypographySection.vue'
import VariablesSection from './properties/VariablesSection.vue'
@@ -174,6 +176,7 @@ const { panels } = useI18n()
<icon-lucide-diamond-plus class="size-3.5" />
</IconButton>
<PropertyBindButton v-if="node.type === 'INSTANCE'" field="INSTANCE_SWAP" />
+ <TextContentControl v-if="node.type === 'TEXT'" :node-id="node.id" :text="node.text" />
<InstanceUpdateAction
v-if="node.type === 'INSTANCE'"
:node="node"
@@ -201,6 +204,7 @@ const { panels } = useI18n()
</template>
</PanelHeader>
+ <TextContentSection v-if="node.type === 'TEXT'" :node-id="node.id" />
<StatusSection />
<ComponentPropertiesSection v-if="node.type === 'INSTANCE'" />
<VariantAuthoringSection
diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vue
index 5b7d68c9a..68db59965 100644
--- a/src/components/properties/AppearanceSection.vue
+++ b/src/components/properties/AppearanceSection.vue
@@ -12,10 +12,10 @@ import PanelGrid from '@/components/ui/panel/PanelGrid.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
+import VariableBoundRow from './binding/VariableBoundRow.vue'
import PropertyBoundField from './component-properties/PropertyBoundField.vue'
import VariableModeMenu from './variable-modes/VariableModeMenu.vue'
import VariableModeRows from './variable-modes/VariableModeRows.vue'
-import VisibilityBindingRow from './visibility/VisibilityBindingRow.vue'
import VisibilityControl from './visibility/VisibilityControl.vue'
const { panels } = useI18n()
@@ -67,7 +67,12 @@ function blendModeGroups(value: BlendMode | typeof MIXED) {
/>
</template>
<PropertyBoundField field="VISIBLE" />
- <VisibilityBindingRow v-if="node && !isMulti" :node-id="node.id" />
+ <VariableBoundRow
+ v-if="node && !isMulti"
+ :node-id="node.id"
+ field="VISIBLE"
+ :label="panels.layerVisibility"
+ />
<PanelGrid :columns="2" distribution="wide-first">
<PanelFieldGroup :label="panels.blendMode">
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index b49a41f65..51164caaf 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -20,9 +20,6 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
-import PropertyBindButton from './component-properties/PropertyBindButton.vue'
-import PropertyBoundField from './component-properties/PropertyBoundField.vue'
-
const { panels, menu } = useI18n()
const fontLoader = { load: loadFont }
const alignmentOptions = computed(() => [
@@ -78,14 +75,6 @@ function picked<T>(value: MixedValue<T>): T | '' {
<template>
<TypographyControlsRoot v-slot="ctx" :font-loader="fontLoader">
<PanelSection v-if="ctx.node.value" :label="panels.typography" data-test-id="typography">
- <template v-if="ctx.nodes.value.length === 1" #actions>
- <PropertyBindButton field="TEXT" />
- </template>
- <PropertyBoundField
- v-if="ctx.nodes.value.length === 1"
- field="TEXT"
- :label="panels.content"
- />
<SharedStyleField kind="text" :label="panels.textStyle" />
<div class="mb-1.5 flex min-w-0 items-center gap-1.5">
diff --git a/src/components/properties/visibility/VisibilityPicker.vue b/src/components/properties/binding/FieldBindingPicker.vue
similarity index 72%
rename from src/components/properties/visibility/VisibilityPicker.vue
rename to src/components/properties/binding/FieldBindingPicker.vue
index e783de155..9a808c433 100644
--- a/src/components/properties/visibility/VisibilityPicker.vue
+++ b/src/components/properties/binding/FieldBindingPicker.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed } from 'vue'
+import { computed, useSlots } from 'vue'
import { variableText } from '@open-pencil/scene-graph'
import { useBindableValue, useEditor, useI18n } from '@open-pencil/vue'
@@ -11,19 +11,23 @@ import IconButton from '@/components/ui/button/IconButton.vue'
import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'
import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'
+import { BOUND_LAYER_FIELDS, type BoundLayerField } from './fields'
+
/**
- * The list a layer's visibility binds from, as Figma's: a component layer's boolean properties,
- * then boolean and text variables. A component layer opens it from its own button; any layer
- * opens it by right-clicking the eye, which the `eye` slot renders.
+ * The list a layer field binds from, as Figma's: a component layer's properties of the field's
+ * type, then the variables the field takes. It opens from its own button, or, for a layer outside
+ * a component, from the control the `anchor` slot renders when there is one, such as the eye.
*/
-const { nodeId } = defineProps<{ nodeId: string }>()
-defineSlots<{ eye(props: { open: () => void }): unknown }>()
+const { nodeId, field } = defineProps<{ nodeId: string; field: BoundLayerField }>()
+defineSlots<{ anchor?(props: { open: () => void }): unknown }>()
const PROPERTY = 'property:'
const editor = useEditor()
-const binding = useBindableValue<boolean>()
-const property = usePropertyBinding('VISIBLE')
+const slots = useSlots()
+const config = BOUND_LAYER_FIELDS[field]
+const binding = useBindableValue()
+const property = usePropertyBinding(field)
const { panels, common } = useI18n()
const open = computed({
@@ -33,6 +37,17 @@ const open = computed({
const properties = computed(() => (property.available.value ? property.compatible.value : []))
+const heading = computed(() =>
+ property.available.value ? panels.value.applyVariableOrProperty : panels.value.applyVariable
+)
+/** The section's other fields have buttons of their own, so the field's button names its field. */
+const buttonLabel = computed(() =>
+ property.available.value ? heading.value : panels.value[config.buttonLabel]
+)
+
+/** A layer outside a component with an anchor opens the list from it, not from a button. */
+const ownButton = computed(() => property.available.value || !slots.anchor)
+
/** A property the layer follows can only be let go of where properties are editable. */
const lockedToProperty = computed(() => !!property.definition.value && !property.editable.value)
@@ -74,7 +89,7 @@ function variableType(value: string) {
/** A layer follows one source at a time, so choosing one lets go of the other in the same step. */
function select(value: string) {
if (value.startsWith(PROPERTY) ? !property.editable.value : lockedToProperty.value) return
- editor.undo.runBatch('Bind visibility', () => {
+ editor.undo.runBatch(config.undoLabel, () => {
if (value.startsWith(PROPERTY)) {
if (binding.state.value !== 'unbound') binding.actions.unbind()
property.bind(value.slice(PROPERTY.length))
@@ -87,7 +102,7 @@ function select(value: string) {
function createProperty() {
open.value = false
- editor.undo.runBatch('Bind visibility', () => {
+ editor.undo.runBatch(config.undoLabel, () => {
if (binding.state.value !== 'unbound') binding.actions.unbind()
property.create()
})
@@ -104,10 +119,10 @@ function openPicker() {
</script>
<template>
- <slot v-if="property.available.value" name="eye" :open="openPicker" />
+ <slot v-if="ownButton" name="anchor" :open="openPicker" />
<AppPicker
v-model:open="open"
- :heading="property.available.value ? panels.applyVariableOrProperty : panels.applyVariable"
+ :heading="heading"
:items="items"
:selected="selected"
density="compact"
@@ -116,25 +131,25 @@ function openPicker() {
:search-placeholder="common.search"
:empty-label="panels.noVariablesFound"
:close-label="common.close"
- :tooltip="panels.applyVariableOrProperty"
+ :tooltip="buttonLabel"
@select="select"
>
- <template v-if="property.available.value" #trigger>
+ <template v-if="ownButton" #trigger>
<IconButton
- :label="panels.applyVariableOrProperty"
- :disabled="!property.editable.value"
+ :label="buttonLabel"
+ :disabled="property.available.value && !property.editable.value"
:active="open"
>
<icon-lucide-diamond-plus class="size-3.5" />
</IconButton>
</template>
<template v-else #anchor>
- <slot name="eye" :open="openPicker" />
+ <slot name="anchor" :open="openPicker" />
</template>
<template #leading="{ item }">
- <PropertyTypeIcon v-if="item.value.startsWith(PROPERTY)" kind="BOOLEAN" />
+ <PropertyTypeIcon v-if="item.value.startsWith(PROPERTY)" :kind="config.propertyType" />
<component
- :is="VARIABLE_TYPE_ICONS[variableType(item.value) ?? 'BOOLEAN']"
+ :is="VARIABLE_TYPE_ICONS[variableType(item.value) ?? 'STRING']"
v-else
class="size-3.5 shrink-0 text-muted"
aria-hidden="true"
diff --git a/src/components/properties/visibility/VisibilityBindingRow.vue b/src/components/properties/binding/VariableBoundRow.vue
similarity index 60%
rename from src/components/properties/visibility/VisibilityBindingRow.vue
rename to src/components/properties/binding/VariableBoundRow.vue
index 9885665b2..d31d1cc33 100644
--- a/src/components/properties/visibility/VisibilityBindingRow.vue
+++ b/src/components/properties/binding/VariableBoundRow.vue
@@ -2,26 +2,29 @@
import { computed } from 'vue'
import { variableText } from '@open-pencil/scene-graph'
-import {
- BindableValueRoot,
- useEditor,
- useI18n,
- useVisibilityBindingProvider
-} from '@open-pencil/vue'
+import { BindableValueRoot, useEditor, useI18n, type BindingProvider } from '@open-pencil/vue'
-import BoundFieldRow from '@/components/properties/binding/BoundFieldRow.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import { VARIABLE_TYPE_ICONS } from '@/components/variables/type-icons'
+import BoundFieldRow from './BoundFieldRow.vue'
+import { BOUND_LAYER_FIELDS, type BoundLayerField } from './fields'
+
/**
- * The variable a layer's visibility follows, with its value here and a way to let go of it.
+ * The variable a layer field follows, with its value here and a way to let go of it.
*/
-const { nodeId } = defineProps<{ nodeId: string }>()
+const { nodeId, field, label } = defineProps<{
+ nodeId: string
+ field: BoundLayerField
+ label: string
+}>()
const editor = useEditor()
const { panels } = useI18n()
-const provider = useVisibilityBindingProvider()
-const targets = computed(() => [{ nodeId, path: 'visible' }])
+const config = BOUND_LAYER_FIELDS[field]
+// The row reads the binding alone, never the field's value, so any field's provider fits.
+const provider: BindingProvider<unknown> = config.useProvider()
+const targets = computed(() => [{ nodeId, path: config.path }])
function valueText(variableId: string) {
return variableText(editor.graph.resolveVariableForNode(nodeId, variableId))
@@ -29,17 +32,17 @@ function valueText(variableId: string) {
</script>
<template>
- <BindableValueRoot v-slot="binding" :provider="provider" :targets="targets" :value="true">
+ <BindableValueRoot v-slot="binding" :provider="provider" :targets="targets" :value="undefined">
<BoundFieldRow
v-if="binding.state !== 'unbound'"
- :label="panels.layerVisibility"
+ :label="label"
:name="binding.variable?.name ?? binding.bindingId ?? panels.unresolvedVariable"
:value="binding.variable ? valueText(binding.variable.id) : undefined"
:tone="binding.state === 'unresolved' ? 'unresolved' : 'variable'"
>
<template #icon>
<component
- :is="VARIABLE_TYPE_ICONS[binding.variable?.type ?? 'BOOLEAN']"
+ :is="VARIABLE_TYPE_ICONS[binding.variable?.type ?? 'STRING']"
class="size-3.5 shrink-0 text-muted"
aria-hidden="true"
/>
diff --git a/src/components/properties/binding/fields.ts b/src/components/properties/binding/fields.ts
new file mode 100644
index 000000000..56ef3e701
--- /dev/null
+++ b/src/components/properties/binding/fields.ts
@@ -0,0 +1,22 @@
+import { useTextContentBindingProvider, useVisibilityBindingProvider } from '@open-pencil/vue'
+
+/** The layer fields a component property or a variable can decide, as Figma's layer panel offers. */
+export type BoundLayerField = 'VISIBLE' | 'TEXT'
+
+export const BOUND_LAYER_FIELDS = {
+ VISIBLE: {
+ path: 'visible',
+ propertyType: 'BOOLEAN',
+ undoLabel: 'Bind visibility',
+ /** Outside a component the eye opens the list; there is no button to name. */
+ buttonLabel: 'applyVariable',
+ useProvider: useVisibilityBindingProvider
+ },
+ TEXT: {
+ path: 'text',
+ propertyType: 'TEXT',
+ undoLabel: 'Bind text content',
+ buttonLabel: 'applyVariableToTextContent',
+ useProvider: useTextContentBindingProvider
+ }
+} as const
diff --git a/src/components/properties/text-content/TextContentControl.vue b/src/components/properties/text-content/TextContentControl.vue
new file mode 100644
index 000000000..1a5c4e25e
--- /dev/null
+++ b/src/components/properties/text-content/TextContentControl.vue
@@ -0,0 +1,19 @@
+<script setup lang="ts">
+import { computed } from 'vue'
+
+import { BindableValueRoot, useTextContentBindingProvider } from '@open-pencil/vue'
+
+import FieldBindingPicker from '@/components/properties/binding/FieldBindingPicker.vue'
+
+/** What binds a text layer's content: its component's text properties, or a text or number variable. */
+const { nodeId, text } = defineProps<{ nodeId: string; text: string }>()
+
+const provider = useTextContentBindingProvider()
+const targets = computed(() => [{ nodeId, path: 'text' }])
+</script>
+
+<template>
+ <BindableValueRoot :provider="provider" :targets="targets" :value="text">
+ <FieldBindingPicker :node-id="nodeId" field="TEXT" />
+ </BindableValueRoot>
+</template>
diff --git a/src/components/properties/text-content/TextContentSection.vue b/src/components/properties/text-content/TextContentSection.vue
new file mode 100644
index 000000000..3ddce85ee
--- /dev/null
+++ b/src/components/properties/text-content/TextContentSection.vue
@@ -0,0 +1,23 @@
+<script setup lang="ts">
+import { useI18n } from '@open-pencil/vue'
+
+import VariableBoundRow from '@/components/properties/binding/VariableBoundRow.vue'
+import PropertyBoundField from '@/components/properties/component-properties/PropertyBoundField.vue'
+
+/**
+ * What a text layer's content follows, under the layer's header as Figma's Content row: a
+ * component property or a variable. Content is what the layer says, so it sits apart from
+ * Typography, which is how it looks.
+ */
+const { nodeId } = defineProps<{ nodeId: string }>()
+
+const { panels } = useI18n()
+</script>
+
+<template>
+ <!-- Both rows render nothing while unbound; `empty:hidden` then drops the band too. -->
+ <div class="border-b border-border px-3 pt-2 pb-1.5 empty:hidden">
+ <PropertyBoundField field="TEXT" :label="panels.content" />
+ <VariableBoundRow :node-id="nodeId" field="TEXT" :label="panels.content" />
+ </div>
+</template>
diff --git a/src/components/properties/visibility/VisibilityControl.vue b/src/components/properties/visibility/VisibilityControl.vue
index 8495aad65..4a81b6356 100644
--- a/src/components/properties/visibility/VisibilityControl.vue
+++ b/src/components/properties/visibility/VisibilityControl.vue
@@ -3,10 +3,9 @@ import { computed } from 'vue'
import { BindableValueRoot, useI18n, useVisibilityBindingProvider } from '@open-pencil/vue'
+import FieldBindingPicker from '@/components/properties/binding/FieldBindingPicker.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
-import VisibilityPicker from './VisibilityPicker.vue'
-
/**
* The Appearance eye with what binds visibility. While a variable decides it, the eye is
* disabled, as in Figma: detaching the variable is what hands visibility back to the eye.
@@ -31,8 +30,8 @@ const targets = computed(() => (nodeId ? [{ nodeId, path: 'visible' }] : []))
:targets="targets"
:value="visibility === 'visible'"
>
- <VisibilityPicker :node-id="nodeId">
- <template #eye="{ open }">
+ <FieldBindingPicker :node-id="nodeId" field="VISIBLE">
+ <template #anchor="{ open }">
<!-- A disabled button gets no events, so the right-click that opens the list lands here. -->
<span class="inline-flex" @contextmenu.prevent="open">
<IconButton
@@ -47,7 +46,7 @@ const targets = computed(() => (nodeId ? [{ nodeId, path: 'visible' }] : []))
</IconButton>
</span>
</template>
- </VisibilityPicker>
+ </FieldBindingPicker>
</BindableValueRoot>
<IconButton
v-else
diff --git a/tests/e2e/components/property-authoring.spec.ts b/tests/e2e/components/property-authoring.spec.ts
index e53e59225..8093adc1b 100644
--- a/tests/e2e/components/property-authoring.spec.ts
+++ b/tests/e2e/components/property-authoring.spec.ts
@@ -8,7 +8,7 @@ import {
selectNode,
type PropertyAuthoringScene
} from '#tests/helpers/components/properties'
-import { propertySection } from '#tests/helpers/properties'
+import { layerHeader, propertySection } from '#tests/helpers/properties'
let page: Page
let canvas: CanvasHelper
@@ -34,13 +34,17 @@ test.afterAll(async () => {
await page.close()
})
-test('links a layer field to a new property from the section that owns the field', async () => {
+test('links a layer field to a new property from the layer header', async () => {
await select(ids.labelId)
- const typography = propertySection(page, 'Typography')
- await typography.getByRole('button', { name: /Apply component property/ }).click()
- await page.getByRole('menuitem', { name: /Create property/ }).click()
+ await layerHeader(page, 'Label').getByRole('button', { name: 'Apply variable/property' }).click()
+ await page
+ .getByRole('dialog', { name: 'Apply variable/property' })
+ .getByRole('button', { name: 'Create property…' })
+ .click()
- await expect(typography.getByRole('button', { name: 'Detach property' })).toBeVisible()
+ await expect(
+ page.getByRole('group', { name: 'Content' }).getByRole('button', { name: 'Detach property' })
+ ).toBeVisible()
await expect
.poll(() => componentPropertyDefinitions(page, ids.buttonId))
.toEqual([{ name: 'Label', type: 'TEXT', defaultValue: 'Button' }])
diff --git a/tests/e2e/properties/bound-text-content.spec.ts b/tests/e2e/properties/bound-text-content.spec.ts
new file mode 100644
index 000000000..a09ef0d60
--- /dev/null
+++ b/tests/e2e/properties/bound-text-content.spec.ts
@@ -0,0 +1,72 @@
+import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
+import { layerHeader } from '#tests/helpers/properties'
+import { boundFieldDriver } from '#tests/helpers/properties/bound-field-driver'
+
+// Figma desktop 126: a text layer's content binds to a text or number variable, a number shown as
+// text; a component's text layer also lists the component's text properties. Detaching keeps the
+// text the variable last gave.
+
+const editor = useEditorSetupWithClear('/?test')
+const fields = boundFieldDriver(() => editor.page)
+
+function header(name: string) {
+ return layerHeader(editor.page, name)
+}
+
+function content() {
+ return editor.page.getByRole('group', { name: 'Content' })
+}
+
+test('a plain text layer shows a number variable as its text', async () => {
+ const scene = await fields.build()
+ await fields.select('plainText')
+ await header('Note').getByRole('button', { name: 'Apply variable to text content' }).click()
+ const picker = editor.page.getByRole('dialog', { name: 'Apply variable' })
+ await expect(picker.getByRole('option')).toHaveText([/state\s*yes/, /size\s*4/])
+ await picker.getByRole('option', { name: /size/ }).click()
+
+ const bound = content()
+ await expect(bound).toContainText(/size\s*4/)
+ await expect
+ .poll(() => fields.layer(scene.plainText, 'TEXT'))
+ .toMatchObject({
+ text: '4',
+ variable: scene.size
+ })
+ await fields.setSize(42.5)
+ await expect.poll(async () => (await fields.layer(scene.plainText, 'TEXT')).text).toBe('42.50')
+
+ await bound.getByRole('button', { name: 'Detach variable' }).click()
+ expect(await fields.layer(scene.plainText, 'TEXT')).toMatchObject({
+ text: '42.50',
+ variable: undefined
+ })
+})
+
+test('a component text layer picks a text property or a variable, one at a time', async () => {
+ const scene = await fields.build()
+ await fields.select('componentText')
+ const apply = header('Caption').getByRole('button', { name: 'Apply variable/property' })
+ const picker = editor.page.getByRole('dialog', { name: 'Apply variable/property' })
+
+ await apply.click()
+ await picker.getByRole('button', { name: 'Create property…' }).click()
+ const property = (await fields.layer(scene.componentText, 'TEXT')).property
+ expect(property).toBeDefined()
+
+ await apply.click()
+ await expect(picker.getByRole('group', { name: 'Properties in Button' })).toBeVisible()
+ await picker.getByRole('option', { name: /state/ }).click()
+ await expect
+ .poll(() => fields.layer(scene.componentText, 'TEXT'))
+ .toMatchObject({
+ text: 'yes',
+ variable: scene.state,
+ property: undefined
+ })
+
+ await editor.page.keyboard.press('ControlOrMeta+z')
+ await expect
+ .poll(() => fields.layer(scene.componentText, 'TEXT'))
+ .toMatchObject({ variable: undefined, property })
+})
diff --git a/tests/e2e/properties/bound-visibility.spec.ts b/tests/e2e/properties/bound-visibility.spec.ts
index d2e7db9c3..7cc9f0a88 100644
--- a/tests/e2e/properties/bound-visibility.spec.ts
+++ b/tests/e2e/properties/bound-visibility.spec.ts
@@ -1,12 +1,12 @@
import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'
-import { visibilityDriver } from '#tests/helpers/properties/visibility-driver'
+import { boundFieldDriver } from '#tests/helpers/properties/bound-field-driver'
// Figma desktop 126: right-clicking the Appearance eye binds visibility to a boolean or text
// variable; a component layer's own button also lists its boolean properties. While a variable
// decides visibility the eye is disabled, and detaching keeps the visibility it last gave.
const editor = useEditorSetupWithClear('/?test')
-const visibility = visibilityDriver(() => editor.page)
+const visibility = boundFieldDriver(() => editor.page)
function appearance() {
return editor.page.getByRole('region', { name: 'Appearance', exact: true })
@@ -35,7 +35,7 @@ test('right-clicking the eye binds visibility to a text variable that decides it
}
await bound.getByRole('button', { name: 'Detach variable' }).click()
- expect(await visibility.layer(scene.plain)).toEqual({
+ expect(await visibility.layer(scene.plain)).toMatchObject({
visible: false,
variable: undefined,
property: undefined
@@ -45,7 +45,7 @@ test('right-clicking the eye binds visibility to a text variable that decides it
test('a component layer picks a property or a variable, one at a time', async () => {
const scene = await visibility.build()
- await visibility.selectComponentLayer()
+ await visibility.select('componentLayer')
const apply = appearance().getByRole('button', { name: 'Apply variable/property' })
const picker = editor.page.getByRole('dialog', { name: 'Apply variable/property' })
diff --git a/tests/engine/cli/eval.test.ts b/tests/engine/cli/eval.test.ts
index 4573c2a2d..e100be5c5 100644
--- a/tests/engine/cli/eval.test.ts
+++ b/tests/engine/cli/eval.test.ts
@@ -58,7 +58,7 @@ heavy('eval CLI', () => {
const child = figma.createRectangle();
child.resize(5, 5);
frame.appendChild(child);
- figma.bindVariable(frame.id, 'paddingLeft', variable.id);
+ openpencil.bindVariable(frame, 'paddingLeft', variable);
figma.setVariableValue(variable.id, collection.defaultModeId, 20);
return { padding: frame.paddingLeft, width: frame.width, childX: child.x };
`
diff --git a/tests/engine/figma/api/create/component-from-node.test.ts b/tests/engine/figma/api/create/component-from-node.test.ts
index 31125cb57..66a05d255 100644
--- a/tests/engine/figma/api/create/component-from-node.test.ts
+++ b/tests/engine/figma/api/create/component-from-node.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { computeAllLayouts } from '@open-pencil/core'
+import { OpenPencilAPI, computeAllLayouts } from '@open-pencil/core'
import { createAPI } from '../helpers'
@@ -34,7 +34,7 @@ describe('createComponentFromNode', () => {
frame.name = 'Card'
frame.resize(200, 50)
frame.cornerRadius = 8
- api.bindVariable(frame.id, 'cornerRadius', variable.id)
+ new OpenPencilAPI(api).bindVariable(frame, 'cornerRadius', variable)
api.graph.updateNode(frame.id, {
variableModes: { [collection.id]: collection.defaultModeId }
})
diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.ts
index 200e225e7..e76a3c337 100644
--- a/tests/engine/text/edit-undo.test.ts
+++ b/tests/engine/text/edit-undo.test.ts
@@ -554,4 +554,27 @@ describe('editing text a component property drives', () => {
expect(getNodeOrThrow(graph, label.id).text).toBe('Buy')
expect(getNodeOrThrow(graph, caption.id).text).toBe('Buy')
})
+
+ test('typing over text a variable decides lets go of the variable in the same step', () => {
+ const { graph, undo, textEditor, textNode, actions } = setup()
+ const collection = graph.createCollection('Copy')
+ const count = graph.createVariable('count', 'FLOAT', collection.id, 3)
+ graph.bindVariable(textNode.id, 'text', count.id)
+ graph.updateNode(textNode.id, { text: '3' })
+
+ actions.startTextEditing(textNode.id)
+ textEditor.insert(' items', getNodeOrThrow(graph, textNode.id))
+ actions.commitTextEdit()
+
+ expect(getNodeOrThrow(graph, textNode.id)).toMatchObject({
+ text: '3 items',
+ boundVariables: {}
+ })
+ undo.undo()
+ expect(getNodeOrThrow(graph, textNode.id)).toMatchObject({
+ text: '3',
+ boundVariables: { text: count.id }
+ })
+ expect(undo.canUndo).toBe(false)
+ })
})
diff --git a/tests/helpers/properties.ts b/tests/helpers/properties.ts
index 8a751c466..1afe55364 100644
--- a/tests/helpers/properties.ts
+++ b/tests/helpers/properties.ts
@@ -4,6 +4,11 @@ export function propertySection(page: Page, name: string): Locator {
return page.getByRole('region', { name, exact: true })
}
+/** The Design panel's header for the selected layer, found by the layer's name. */
+export function layerHeader(page: Page, name: string): Locator {
+ return page.locator('header').filter({ has: page.getByRole('heading', { name, exact: true }) })
+}
+
export function propertyField(page: Page, property: string): Locator {
return page.locator(`[data-property=${JSON.stringify(property)}]`)
}
diff --git a/tests/helpers/properties/bound-field-driver.ts b/tests/helpers/properties/bound-field-driver.ts
new file mode 100644
index 000000000..363efe8d3
--- /dev/null
+++ b/tests/helpers/properties/bound-field-driver.ts
@@ -0,0 +1,127 @@
+import type { Page } from '@playwright/test'
+
+interface BoundFieldScene {
+ componentLayer: string
+ componentText: string
+ plain: string
+ plainText: string
+ flag: string
+ state: string
+ size: string
+ mode: string
+}
+
+type LayerField = 'VISIBLE' | 'TEXT'
+const PATHS = { VISIBLE: 'visible', TEXT: 'text' } as const
+
+/**
+ * Builds variables of each type, a component with a layer and a text layer, a plain layer and a
+ * plain text layer, and reads back what decides a layer's visibility or text. Selection, variable
+ * values and typing are fixture setup; binding goes through the panel.
+ */
+export function boundFieldDriver(page: () => Page) {
+ let scene: BoundFieldScene | undefined
+
+ function built() {
+ if (!scene) throw new Error('Build the scene first')
+ return scene
+ }
+
+ return {
+ async build() {
+ scene = await page().evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const graph = store.graph
+ const pageId = store.state.currentPageId
+ // The page is cleared between tests; the variables an earlier test made are not.
+ for (const id of graph.variableCollections.keys()) graph.removeCollection(id)
+ const collection = graph.createCollection('Flags')
+ const flag = graph.createVariable('show-icon', 'BOOLEAN', collection.id, true)
+ const state = graph.createVariable('state', 'STRING', collection.id, 'yes')
+ const size = graph.createVariable('size', 'FLOAT', collection.id, 4)
+ const button = graph.createNode('COMPONENT', pageId, {
+ name: 'Button',
+ width: 160,
+ height: 48
+ })
+ const badge = graph.createNode('RECTANGLE', button.id, {
+ name: 'Badge',
+ width: 24,
+ height: 24
+ })
+ const caption = graph.createNode('TEXT', button.id, {
+ name: 'Caption',
+ text: 'Buy',
+ y: 24,
+ width: 80,
+ height: 20
+ })
+ const note = graph.createNode('TEXT', pageId, {
+ name: 'Note',
+ text: 'Note',
+ x: 400,
+ width: 80,
+ height: 20
+ })
+ const plain = graph.createNode('RECTANGLE', pageId, {
+ name: 'Plain',
+ x: 300,
+ width: 48,
+ height: 48
+ })
+ store.select([plain.id])
+ return {
+ componentLayer: badge.id,
+ componentText: caption.id,
+ plain: plain.id,
+ plainText: note.id,
+ flag: flag.id,
+ state: state.id,
+ size: size.id,
+ mode: collection.defaultModeId
+ }
+ })
+ return scene
+ },
+
+ select(layer: 'componentLayer' | 'componentText' | 'plain' | 'plainText') {
+ return page().evaluate((id) => window.openPencil?.getStore?.().select([id]), built()[layer])
+ },
+
+ setText(text: string) {
+ const { state, mode } = built()
+ return page().evaluate(
+ (args) =>
+ window.openPencil?.getStore?.().updateVariableValue(args.state, args.mode, args.text),
+ { state, mode, text }
+ )
+ },
+
+ setSize(size: number) {
+ const { size: id, mode } = built()
+ return page().evaluate(
+ (args) =>
+ window.openPencil?.getStore?.().updateVariableValue(args.id, args.mode, args.size),
+ { id, mode, size }
+ )
+ },
+
+ /** What decides a layer field: the layer's value, its variable, and its component property. */
+ layer(id: string, field: LayerField = 'VISIBLE') {
+ return page().evaluate(
+ ({ nodeId, field, path }) => {
+ const node = window.openPencil?.getStore?.().graph.getNode(nodeId)
+ return {
+ visible: node?.visible,
+ text: node?.text,
+ variable: node?.boundVariables[path],
+ property: node?.componentPropertyReferences.find((item) => item.field === field)
+ ?.propertyId
+ }
+ },
+ { nodeId: id, field, path: PATHS[field] }
+ )
+ }
+ }
+}
diff --git a/tests/helpers/properties/visibility-driver.ts b/tests/helpers/properties/visibility-driver.ts
deleted file mode 100644
index 4b3273231..000000000
--- a/tests/helpers/properties/visibility-driver.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import type { Page } from '@playwright/test'
-
-interface VisibilityScene {
- componentLayer: string
- plain: string
- flag: string
- state: string
- mode: string
-}
-
-/**
- * Builds variables of each type, a component with a layer and a plain layer, and reads back
- * what decides a layer's visibility. Selection and variable values are fixture setup; binding
- * goes through the panel.
- */
-export function visibilityDriver(page: () => Page) {
- let scene: VisibilityScene | undefined
-
- function built() {
- if (!scene) throw new Error('Build the scene first')
- return scene
- }
-
- return {
- async build() {
- scene = await page().evaluate(() => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const graph = store.graph
- const pageId = store.state.currentPageId
- // The page is cleared between tests; the variables an earlier test made are not.
- for (const id of graph.variableCollections.keys()) graph.removeCollection(id)
- const collection = graph.createCollection('Flags')
- const flag = graph.createVariable('show-icon', 'BOOLEAN', collection.id, true)
- const state = graph.createVariable('state', 'STRING', collection.id, 'yes')
- graph.createVariable('size', 'FLOAT', collection.id, 4)
- const button = graph.createNode('COMPONENT', pageId, {
- name: 'Button',
- width: 160,
- height: 48
- })
- const badge = graph.createNode('RECTANGLE', button.id, {
- name: 'Badge',
- width: 24,
- height: 24
- })
- const plain = graph.createNode('RECTANGLE', pageId, {
- name: 'Plain',
- x: 300,
- width: 48,
- height: 48
- })
- store.select([plain.id])
- return {
- componentLayer: badge.id,
- plain: plain.id,
- flag: flag.id,
- state: state.id,
- mode: collection.defaultModeId
- }
- })
- return scene
- },
-
- selectComponentLayer() {
- return page().evaluate(
- (id) => window.openPencil?.getStore?.().select([id]),
- built().componentLayer
- )
- },
-
- setText(text: string) {
- const { state, mode } = built()
- return page().evaluate(
- (args) =>
- window.openPencil?.getStore?.().updateVariableValue(args.state, args.mode, args.text),
- { state, mode, text }
- )
- },
-
- /** What decides a layer's visibility: its value, its variable, and its component property. */
- layer(id: string) {
- return page().evaluate((nodeId) => {
- const node = window.openPencil?.getStore?.().graph.getNode(nodeId)
- return {
- visible: node?.visible,
- variable: node?.boundVariables.visible,
- property: node?.componentPropertyReferences.find((item) => item.field === 'VISIBLE')
- ?.propertyId
- }
- }, id)
- }
- }
-}