Skip to content

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

feat: bind effect fields to variables from the effect settings (#1739)

Danila Poyarkove73223e70283
diff --git a/changes/1715/added.md b/changes/1715/added.md
index 7bf9508ab..100fec92d 100644
--- a/changes/1715/added.md
+++ b/changes/1715/added.md
@@ -1 +1 @@
-- Shadow colour, blur, spread and offsets, and blur radius, bind to variables, so effects follow a variable mode; `figma.variables.setBoundVariableForEffect`, `bind_variable`, effect styles, `.fig` files and the Figma clipboard carry the bindings (#1712).
+- Shadow colour, blur, spread and offsets, and blur radius, bind to variables, so effects follow a variable mode: apply or create a variable from each field in the effect settings, where typing a value detaches it, and `figma.variables.setBoundVariableForEffect`, `bind_variable`, effect styles, `.fig` files and the Figma clipboard carry the bindings (#1712).
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 4f0883c27..a2b7ba235 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -40,7 +40,7 @@ References use variable names or `{Collection::variable}` and are stored as stab
## Variable bindings
-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`.
+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`, `fills/0/color` or `effects/0/radius`. 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.variables.getLocalVariables('FLOAT')
diff --git a/packages/vue/src/controls/number-variable-binding/use.ts b/packages/vue/src/controls/number-variable-binding/use.ts
index 25b6a6dc1..9c0c32926 100644
--- a/packages/vue/src/controls/number-variable-binding/use.ts
+++ b/packages/vue/src/controls/number-variable-binding/use.ts
@@ -26,6 +26,7 @@ export type NumberBindingPath =
| 'letterSpacing'
| 'paragraphSpacing'
| 'paragraphIndent'
+ | `effects/${number}/${'radius' | 'spread' | 'offsetX' | 'offsetY'}`
export function useNumberVariableBinding(path: NumberBindingPath) {
const binding = useVariableBinding({
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index db328720d..81e0fbc8d 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -443,6 +443,7 @@
"pointCount": "Anzahl",
"starRatio": "Verhältnis",
"spread": "Ausbreitung",
+ "effectColor": "Farbe",
"foregroundBlur": "Vordergrund-Weichzeichnung",
"strokeType": "Linientyp",
"strokeWeight": "Linienstärke",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 22afb52be..49fd0af40 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -38,6 +38,7 @@
"pointCount": "Cantidad",
"starRatio": "Proporción",
"spread": "Esparcimiento",
+ "effectColor": "Color",
"fill": "Relleno",
"stroke": "Trazo",
"effects": "Efectos",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index cba642941..8026e6393 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -443,6 +443,7 @@
"pointCount": "Nombre",
"starRatio": "Rapport",
"spread": "Diffusion",
+ "effectColor": "Couleur",
"foregroundBlur": "Flou de premier plan",
"strokeType": "Type de contour",
"strokeWeight": "Épaisseur du contour",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index cf99e064e..28cc106d3 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -443,6 +443,7 @@
"pointCount": "Numero",
"starRatio": "Rapporto",
"spread": "Diffusione",
+ "effectColor": "Colore",
"foregroundBlur": "Sfocatura primo piano",
"strokeType": "Tipo tratto",
"strokeWeight": "Spessore tratto",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 0f2e4fb55..2dfd48d79 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -38,6 +38,7 @@
"pointCount": "数",
"starRatio": "比率",
"spread": "スプレッド",
+ "effectColor": "色",
"fill": "塗り",
"stroke": "線",
"effects": "エフェクト",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 9633577e9..5fe5920e2 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -449,6 +449,7 @@
"pointCount": "Liczba",
"starRatio": "Proporcja",
"spread": "Rozproszenie",
+ "effectColor": "Kolor",
"foregroundBlur": "Rozmycie pierwszego planu",
"strokeType": "Typ obrysu",
"strokeWeight": "Grubość obrysu",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index be3069604..78af8ffbe 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -449,6 +449,7 @@
"pointCount": "Количество",
"starRatio": "Соотношение",
"spread": "Размах",
+ "effectColor": "Цвет",
"foregroundBlur": "Размытие переднего плана",
"strokeType": "Тип обводки",
"strokeWeight": "Толщина обводки",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 52ea09d9d..c91b25afe 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -437,6 +437,7 @@
"pointCount": "数量",
"starRatio": "比例",
"spread": "扩展",
+ "effectColor": "颜色",
"foregroundBlur": "前景模糊",
"strokeType": "描边类型",
"strokeWeight": "描边粗细",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 270ef78fa..9cbef4298 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -143,6 +143,7 @@ export const panelMessageDefaults = {
/** A star's inner radius as a share of its outer one. */
starRatio: 'Ratio',
spread: 'Spread',
+ effectColor: 'Color',
page: 'Page',
selectionColors: 'Selection colors',
diff --git a/src/components/properties/EffectsSection.vue b/src/components/properties/EffectsSection.vue
index d759d0026..c8d3bf8f3 100644
--- a/src/components/properties/EffectsSection.vue
+++ b/src/components/properties/EffectsSection.vue
@@ -1,17 +1,32 @@
<script setup lang="ts">
import type { Effect, Fill } from '@open-pencil/scene-graph'
+import { colorToHexRaw } from '@open-pencil/scene-graph/color'
+import type { Color } from '@open-pencil/scene-graph/primitives'
+import type { EffectBindingProperty } from '@open-pencil/scene-graph/variables'
+import {
+ useColorBindingProvider,
+ type BindingTarget
+} from '@open-pencil/vue/controls/binding-provider'
import { useEffectsControls } from '@open-pencil/vue/controls/effects'
import { useI18n } from '@open-pencil/vue/i18n'
+import {
+ BindableValueRoot,
+ type BindableValueActions
+} from '@open-pencil/vue/primitives/BindableValue'
-import ColorInput from '@/components/ColorPicker/ColorInput.vue'
+import ColorPicker from '@/components/ColorPicker/ColorPicker.vue'
import NumberField from '@/components/inputs/NumberField.vue'
+import VariableBindingPicker from '@/components/properties/binding/VariableBindingPicker.vue'
import {
commitDiscretePropertyListChange,
useBlendModeGroups
} from '@/components/properties/blend-mode/use'
import PropertyItemRow from '@/components/properties/item-list/PropertyItemRow.vue'
+import { applyPaintMutation, commitPaintMutation } from '@/components/properties/paint/binding'
+import PaintValue from '@/components/properties/paint/PaintValue.vue'
import PropertyListRoot from '@/components/properties/PropertyListRoot.vue'
import { useSharedStylePicker } from '@/components/properties/shared-style/useSharedStylePicker'
+import VariableNumberField from '@/components/properties/VariableNumberField.vue'
import IconButton from '@/components/ui/button/IconButton.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
import FillSwatch from '@/components/ui/paint/FillSwatch.vue'
@@ -20,7 +35,8 @@ import PanelSection from '@/components/ui/panel/PanelSection.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
const effectsCtx = useEffectsControls()
-const { panels } = useI18n()
+const { panels, common } = useI18n()
+const colorProvider = useColorBindingProvider()
const blendModeGroups = useBlendModeGroups()
const {
visible: stylesVisible,
@@ -30,6 +46,24 @@ const {
update: updateStyle
} = useSharedStylePicker('effect')
+/** The binding field of one effect property on every selected layer, such as `effects/0/radius`. */
+function effectTargets(
+ nodeIds: readonly string[],
+ index: number,
+ property: EffectBindingProperty
+): BindingTarget[] {
+ return nodeIds.map((nodeId) => ({ nodeId, path: `effects/${index}/${property}` }))
+}
+
+/** A bound colour edits its variable in the layer's mode; an unbound one edits the effect. */
+function updateEffectColor(
+ binding: BindableValueActions<Color>,
+ flush: () => void,
+ update: () => void
+) {
+ if (applyPaintMutation(binding, flush, update)) commitPaintMutation(binding)
+}
+
function effectPreview(effect: Effect): Fill {
return {
type: 'SOLID',
@@ -42,7 +76,7 @@ function effectPreview(effect: Effect): Fill {
<template>
<PropertyListRoot
- v-slot="{ items, isMixed, activeNode, flush, actions }"
+ v-slot="{ items, isMixed, activeNode, selectedNodeIds, flush, actions }"
prop-key="effects"
:label="panels.effects"
>
@@ -158,10 +192,13 @@ function effectPreview(effect: Effect): Fill {
<template v-if="effectsCtx.isShadow(effect.type)">
<div class="flex items-center gap-1.5">
<Tip :label="panels.xAxis">
- <NumberField
+ <VariableNumberField
icon="X"
+ :aria-label="panels.xAxis"
:model-value="effect.offset.x"
- data-property="effect-offset-x"
+ :node-id="selectedNodeIds[0] ?? ''"
+ :node-ids="selectedNodeIds"
+ :binding-path="`effects/${index}/offsetX`"
@update:model-value="
effectsCtx.scrubEffect(index, {
offset: { ...effect.offset, x: $event }
@@ -175,10 +212,13 @@ function effectPreview(effect: Effect): Fill {
/>
</Tip>
<Tip :label="panels.yAxis">
- <NumberField
+ <VariableNumberField
icon="Y"
+ :aria-label="panels.yAxis"
:model-value="effect.offset.y"
- data-property="effect-offset-y"
+ :node-id="selectedNodeIds[0] ?? ''"
+ :node-ids="selectedNodeIds"
+ :binding-path="`effects/${index}/offsetY`"
@update:model-value="
effectsCtx.scrubEffect(index, {
offset: { ...effect.offset, y: $event }
@@ -195,63 +235,113 @@ function effectPreview(effect: Effect): Fill {
<div class="flex items-center gap-1.5">
<Tip :label="panels.radius">
- <NumberField
+ <VariableNumberField
icon="B"
+ :aria-label="panels.radius"
:model-value="effect.radius"
:min="0"
- data-property="effect-radius"
+ :node-id="selectedNodeIds[0] ?? ''"
+ :node-ids="selectedNodeIds"
+ :binding-path="`effects/${index}/radius`"
@update:model-value="effectsCtx.scrubEffect(index, { radius: $event })"
@commit="effectsCtx.commitEffect(index, { radius: $event })"
/>
</Tip>
<Tip :label="panels.spread">
- <NumberField
+ <VariableNumberField
icon="S"
+ :aria-label="panels.spread"
:model-value="effect.spread"
- data-property="effect-spread"
+ :node-id="selectedNodeIds[0] ?? ''"
+ :node-ids="selectedNodeIds"
+ :binding-path="`effects/${index}/spread`"
@update:model-value="effectsCtx.scrubEffect(index, { spread: $event })"
@commit="effectsCtx.commitEffect(index, { spread: $event })"
/>
</Tip>
</div>
- <div class="flex items-center gap-1.5">
- <ColorInput
- class="min-w-0 flex-1"
- :color="effect.color"
- editable
- @update="effectsCtx.updateColor(actions.patch, index, $event)"
- />
- <Tip :label="panels.opacity">
- <NumberField
- class="w-14"
- suffix="%"
- :model-value="Math.round(effect.color.a * 100)"
- :min="0"
- :max="100"
- data-property="effect-opacity"
- @update:model-value="
- effectsCtx.scrubEffect(index, {
- color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
- })
+ <BindableValueRoot
+ v-slot="binding"
+ :provider="colorProvider"
+ :targets="effectTargets(selectedNodeIds, index, 'color')"
+ :value="effect.color"
+ batch-label="Change effect color"
+ >
+ <div class="flex items-center gap-1.5" data-property="effect-color">
+ <ColorPicker
+ :color="binding.resolvedValue ?? effect.color"
+ @update="
+ updateEffectColor(binding.actions, flush, () =>
+ effectsCtx.updateColor(actions.patch, index, $event)
+ )
"
- @commit="
- effectsCtx.commitEffect(index, {
- color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
- })
+ />
+ <PaintValue
+ :color="effect.color"
+ :resolved-color="binding.resolvedValue"
+ :variable-name="binding.variable?.name ?? binding.bindingId"
+ :unavailable-label="
+ binding.state === 'unresolved' ? panels.unresolvedVariable : undefined
+ "
+ :label="panels.effectColor"
+ @update="
+ updateEffectColor(binding.actions, flush, () =>
+ effectsCtx.updateColor(actions.patch, index, $event)
+ )
"
/>
- </Tip>
- </div>
+ <!-- A bound colour takes its opacity from the variable, as in Figma. -->
+ <Tip
+ v-if="!binding.variable && binding.state !== 'unresolved'"
+ :label="panels.opacity"
+ >
+ <NumberField
+ class="w-14"
+ suffix="%"
+ :inherit-binding="false"
+ :aria-label="panels.opacity"
+ :model-value="Math.round(effect.color.a * 100)"
+ :min="0"
+ :max="100"
+ data-property="effect-opacity"
+ @update:model-value="
+ effectsCtx.scrubEffect(index, {
+ color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
+ })
+ "
+ @commit="
+ effectsCtx.commitEffect(index, {
+ color: { ...effect.color, a: Math.max(0, Math.min(1, $event / 100)) }
+ })
+ "
+ />
+ </Tip>
+ <VariableBindingPicker
+ :trigger-label="panels.applyVariable"
+ :search-placeholder="common.search"
+ :empty-label="panels.noVariablesFound"
+ :detach-label="panels.detachVariable"
+ :create-label="
+ panels.createColorVariable({ value: `#${colorToHexRaw(effect.color)}` })
+ "
+ :create-name-placeholder="panels.variableName"
+ :create-submit-label="panels.create"
+ />
+ </div>
+ </BindableValueRoot>
</template>
- <NumberField
+ <VariableNumberField
v-else
class="w-24 flex-none"
icon="B"
+ :aria-label="panels.radius"
:model-value="effect.radius"
:min="0"
- data-property="effect-radius"
+ :node-id="selectedNodeIds[0] ?? ''"
+ :node-ids="selectedNodeIds"
+ :binding-path="`effects/${index}/radius`"
@update:model-value="effectsCtx.scrubEffect(index, { radius: $event })"
@commit="effectsCtx.commitEffect(index, { radius: $event })"
/>
diff --git a/tests/e2e/properties/effect-panel.spec.ts b/tests/e2e/properties/effect-panel.spec.ts
index 7bd608735..2198cae25 100644
--- a/tests/e2e/properties/effect-panel.spec.ts
+++ b/tests/e2e/properties/effect-panel.spec.ts
@@ -31,7 +31,7 @@ for (const theme of ['light', 'dark']) {
const section = page.getByRole('region', { name: 'Effects', exact: true })
await section.getByRole('button', { name: 'Expand effect settings' }).click()
if (theme === 'light') await expect(section).toHaveScreenshot('inline-shadow-light.png')
- const radius = section.getByRole('spinbutton', { name: 'B', exact: true })
+ const radius = section.getByRole('spinbutton', { name: 'Radius', exact: true })
await radius.focus()
await radius.fill('20')
await radius.press('Enter')
@@ -55,7 +55,7 @@ for (const theme of ['light', 'dark']) {
.toBe(12)
await section.getByRole('combobox', { name: 'Effects', exact: true }).click()
await page.getByRole('option', { name: 'Layer blur', exact: true }).click()
- await expect(section.getByRole('spinbutton', { name: 'B', exact: true })).toBeVisible()
+ await expect(section.getByRole('spinbutton', { name: 'Radius', exact: true })).toBeVisible()
await section.getByRole('button', { name: 'Remove effect' }).click()
await expect
.poll(() =>
@@ -65,3 +65,69 @@ for (const theme of ['light', 'dark']) {
await expect(section.locator('[data-slot="effect-settings"]')).toHaveCount(0)
})
}
+
+test('bind a shadow’s blur and colour to variables, and detach by typing', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const id = await page.evaluate(() => {
+ const editor = window.openPencil?.getStore?.()
+ if (!editor) throw new Error('Editor unavailable')
+ const id = editor.createShape('RECTANGLE', 100, 100, 180, 120)
+ editor.updateNode(id, {
+ effects: [
+ {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius: 12,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ editor.select([id])
+ return id
+ })
+ const node = () =>
+ page.evaluate((id) => {
+ const layer = window.openPencil?.getStore?.().graph.getNode(id)
+ return { bindings: layer?.boundVariables, radius: layer?.effects[0].radius }
+ }, id)
+ const section = page.getByRole('region', { name: 'Effects', exact: true })
+ await section.getByRole('button', { name: 'Expand effect settings' }).click()
+
+ const blur = section.locator('[data-property="effects/0/radius"]')
+ await blur.getByRole('button', { name: 'Apply variable' }).click()
+ await page.getByRole('button', { name: 'Create number variable from 12', exact: true }).click()
+ await page.getByPlaceholder('Variable name').fill('Shadow/Blur')
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(blur).toHaveAttribute('data-bound')
+ await expect
+ .poll(async () => (await node()).bindings)
+ .toEqual({ 'effects/0/radius': expect.any(String) })
+
+ const colour = section.locator('[data-property="effect-color"]')
+ await expect(colour.getByRole('spinbutton', { name: 'Opacity' })).toBeVisible()
+ await colour.getByRole('button', { name: 'Apply variable' }).click()
+ await page
+ .getByRole('button', { name: 'Create color variable from #000000', exact: true })
+ .click()
+ await page.getByPlaceholder('Variable name').fill('Shadow/Color')
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ await expect(colour).toContainText('Shadow/Color')
+ // A bound colour takes its opacity from the variable.
+ await expect(colour.getByRole('spinbutton', { name: 'Opacity' })).toHaveCount(0)
+ await expect
+ .poll(async () => Object.keys((await node()).bindings ?? {}).sort())
+ .toEqual(['effects/0/color', 'effects/0/radius'])
+
+ const radius = section.getByRole('spinbutton', { name: 'Radius', exact: true })
+ await radius.focus()
+ const input = blur.locator('input')
+ await input.fill('24')
+ await input.press('Enter')
+ await expect
+ .poll(node)
+ .toEqual({ bindings: { 'effects/0/color': expect.any(String) }, radius: 24 })
+ await expect(blur).not.toHaveAttribute('data-bound')
+})
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index 3a36cb588..d6fdf92fe 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -382,6 +382,7 @@ de:panels.gridAuto
de:storage.cloudTitle
de:statuses.name
de:statuses.status
+es:panels.effectColor
es:panels.gridColor
es:panels.gridAuto
es:storage.cloudTitle