Skip to content

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

feat: bind effects to variables so shadows and blurs follow a mode (#1715)

Danila Poyarkov48720536532c
diff --git a/changes/1715/added.md b/changes/1715/added.md
new file mode 100644
index 000000000..7bf9508ab
--- /dev/null
+++ b/changes/1715/added.md
@@ -0,0 +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).
diff --git a/packages/core/src/canvas/effects.ts b/packages/core/src/canvas/effects.ts
index 567bbdf7c..e1fa56af4 100644
--- a/packages/core/src/canvas/effects.ts
+++ b/packages/core/src/canvas/effects.ts
@@ -2,6 +2,7 @@ import type { Canvas, ImageFilter, MaskFilter, Path } from 'canvaskit-wasm'
import { readEffectiveFigmaRawField } from '@open-pencil/fig'
import type { SceneNode } from '@open-pencil/scene-graph'
+import { drawnBlurRadius } from '@open-pencil/scene-graph/geometry'
import type { Color, Vector } from '@open-pencil/scene-graph/primitives'
import { ResourceCache } from '#core/cache/resource'
@@ -33,7 +34,7 @@ export function createMaskFilterCache(): MaskFilterCache {
* SVG export writes radius / 2, which is wider (`packages/core/tests/canvas/blur.test.ts`).
*/
export function blurSigma(radius: number): number {
- return radius * 0.43
+ return drawnBlurRadius(radius) * 0.43
}
export function getCachedDropShadow(
diff --git a/packages/core/src/canvas/renderer.ts b/packages/core/src/canvas/renderer.ts
index 9cc031887..24cfc7982 100644
--- a/packages/core/src/canvas/renderer.ts
+++ b/packages/core/src/canvas/renderer.ts
@@ -2,6 +2,7 @@ import { isEqual, noop } from 'es-toolkit'
import type { SceneNode, SceneGraph, Fill, Stroke } from '@open-pencil/scene-graph'
import type { RenderColorSpace, ResolvedRenderColor } from '@open-pencil/scene-graph/color'
+import { drawnBlurRadius } from '@open-pencil/scene-graph/geometry'
import type { Mat3 } from '@open-pencil/scene-graph/matrix'
import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { slotPropertyId } from '@open-pencil/scene-graph/slots'
@@ -350,7 +351,7 @@ export class SkiaRenderer {
let expand = 0
for (const e of node.effects) {
if (!e.visible) continue
- const blur = e.radius
+ const blur = drawnBlurRadius(e.radius)
const spread = e.spread
const ox = Math.abs(e.offset.x)
const oy = Math.abs(e.offset.y)
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index c9ef2ac50..070a45156 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -2,6 +2,7 @@ import type { Canvas } from 'canvaskit-wasm'
import { type SceneNode, type SceneGraph, type Fill } from '@open-pencil/scene-graph'
import { getNodeLocalMatrix } from '@open-pencil/scene-graph/coordinate'
+import { drawnBlurRadius } from '@open-pencil/scene-graph/geometry'
import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'
import { isLayerContainer } from '@open-pencil/scene-graph/node-defaults'
import { textLinesOverflow } from '@open-pencil/scene-graph/text'
@@ -166,7 +167,7 @@ function renderMaskNodeContent(
)
const layered = node.opacity < 1 || blur !== undefined
if (layered) {
- const padding = (blur?.radius ?? 0) * 2
+ const padding = drawnBlurRadius(blur?.radius ?? 0) * 2
r.opacityPaint.setAlphaf(node.opacity)
r.opacityPaint.setBlendMode(r.ck.BlendMode.SrcOver)
r.opacityPaint.setImageFilter(blur ? r.getCachedBlur(blurSigma(blur.radius)) : null)
@@ -381,7 +382,7 @@ export function renderNode(
r.effectLayerPaint.setBlendMode(r.ck.BlendMode.SrcOver)
r.effectLayerPaint.setImageFilter(r.getCachedBlur(blurSigma(layerBlur.radius)))
- const blurPadding = layerBlur.radius * 2
+ const blurPadding = drawnBlurRadius(layerBlur.radius) * 2
canvas.saveLayer(
r.effectLayerPaint,
viewportLayerBounds(r, world(), blurPadding) ??
diff --git a/packages/core/src/canvas/shadows.ts b/packages/core/src/canvas/shadows.ts
index 03c8ac17e..d88b83909 100644
--- a/packages/core/src/canvas/shadows.ts
+++ b/packages/core/src/canvas/shadows.ts
@@ -1,6 +1,7 @@
import type { Canvas, ImageFilter } from 'canvaskit-wasm'
import type { BlendMode, Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { drawnBlurRadius } from '@open-pencil/scene-graph/geometry'
import Matrix from '@open-pencil/scene-graph/matrix'
import { isLayerContainer } from '@open-pencil/scene-graph/node-defaults'
import { regionFills } from '@open-pencil/scene-graph/vector-network'
@@ -79,7 +80,7 @@ function shadowLayerBounds(
height: node.height
}
const offset = effect.offset
- const padding = effect.radius * 2 + Math.abs(spread)
+ const padding = drawnBlurRadius(effect.radius) * 2 + Math.abs(spread)
return r.ck.LTRBRect(
box.x + Math.min(0, offset.x) - padding,
box.y + Math.min(0, offset.y) - padding,
diff --git a/packages/core/src/canvas/shadows/shape.ts b/packages/core/src/canvas/shadows/shape.ts
index 75a6761f7..fc536d1c7 100644
--- a/packages/core/src/canvas/shadows/shape.ts
+++ b/packages/core/src/canvas/shadows/shape.ts
@@ -1,6 +1,7 @@
import type { Canvas, Path } from 'canvaskit-wasm'
import type { BlendMode, Effect, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import { drawnBlurRadius } from '@open-pencil/scene-graph/geometry'
import { setPaintBlendMode } from '#core/canvas/blend'
import { blurSigma } from '#core/canvas/effects'
@@ -256,7 +257,7 @@ export function drawShapeInnerShadow(
canvas.save()
try {
- const expand = effect.radius * 2
+ const expand = drawnBlurRadius(effect.radius) * 2
const { x: offsetX, y: offsetY } = effect.offset
const spreadPadding = sp < 0 ? -sp : 0
const area = new r.ck.PathBuilder()
diff --git a/packages/core/src/figma-api/accessors/styles.ts b/packages/core/src/figma-api/accessors/styles.ts
index d06cfcabb..20bf8cc99 100644
--- a/packages/core/src/figma-api/accessors/styles.ts
+++ b/packages/core/src/figma-api/accessors/styles.ts
@@ -12,7 +12,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { bindStylePaints, STYLE_NOT_FOUND, styleChanges } from '#core/figma-api/styles/apply'
+import { bindStyleVariables, STYLE_NOT_FOUND, styleChanges } from '#core/figma-api/styles/apply'
import { getTextStyle } from '#core/figma-api/text/style'
import { parseFigma } from '#core/figma-api/validation'
@@ -36,7 +36,8 @@ function styleKinds(type: SceneNode['type'], isDocument: boolean): SharedStyleKi
/**
* Gives `target` the style, or refuses it with `refusal`. A stroke style goes to the layer that
- * draws the strokes, a connector's line, and the layer binds to the variables its paints follow.
+ * draws the strokes, a connector's line, and the layer binds to the variables its paints and
+ * effects follow.
*/
function applyStyle(
target: ProxyThis,
@@ -50,7 +51,7 @@ function applyStyle(
const changes = styleChanges(scene, raw(holder, internals), kind, styleId)
if (!changes) throw new Error(refusal)
updateNode(holder, internals, changes)
- bindStylePaints(scene, raw(holder, internals), kind, styleId)
+ bindStyleVariables(scene, raw(holder, internals), kind, styleId)
}
function styleMembers(internals: NodeProxyInternals, kind: SharedStyleKind, mixed: symbol) {
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index a944f993a..708c01579 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -14,7 +14,12 @@ import {
import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'
import { parseFigmaPaints, toFigmaPaint, type FigmaPaint } from '#core/figma-api/paints'
import { getTextStyle } from '#core/figma-api/text/style'
-import { paintBindings, setPaintBindings } from '#core/figma-api/variables/bindings'
+import {
+ effectBindings,
+ paintBindings,
+ setEffectBindings,
+ setPaintBindings
+} from '#core/figma-api/variables/bindings'
import { textStyleChanges } from '#core/text/character-style'
/**
@@ -38,6 +43,16 @@ export function figmaStrokes(sceneGraph: SceneGraph, node: SceneNode): FigmaPain
return strokes.map((stroke, index) => toFigmaPaint(stroke, bound.get(index)))
}
+/**
+ * `node`'s effects as Figma's plugin API reads them, carrying the variables they are bound to.
+ * Bound values are read as the layer holds them, as bound sizes are: resolving bindings keeps them
+ * current, and a layer scaled outside an instance keeps its scaled values until then, as in Figma.
+ */
+export function figmaEffects(node: SceneNode): FigmaEffect[] {
+ const bound = effectBindings(node)
+ return node.effects.map((effect, index) => toFigmaEffect(effect, bound.get(index)))
+}
+
function setFills(
target: ProxyThis,
internals: NodeProxyInternals,
@@ -128,10 +143,11 @@ export function installVisualNodeProxyAccessors(
},
effects: {
get(this: ProxyThis): readonly FigmaEffect[] {
- return Object.freeze(raw(this, internals).effects.map(toFigmaEffect))
+ return Object.freeze(figmaEffects(raw(this, internals)))
},
set(this: ProxyThis, value: readonly FigmaEffect[]) {
updateNode(this, internals, { effects: parseFigmaEffects(value) })
+ setEffectBindings(graph(this, internals), raw(this, internals), value)
}
},
// Applied shared styles, as Figma exposes them; an assignment inside an instance is an override.
diff --git a/packages/core/src/figma-api/effects.ts b/packages/core/src/figma-api/effects.ts
index 8cc5ab5a7..8041dcb59 100644
--- a/packages/core/src/figma-api/effects.ts
+++ b/packages/core/src/figma-api/effects.ts
@@ -1,9 +1,17 @@
+import type {
+ BlurEffectNormal,
+ DropShadowEffect,
+ Effect as PluginEffect,
+ InnerShadowEffect
+} from '@figma/plugin-typings/plugin-api-standalone'
import * as v from 'valibot'
import type { BlendMode, Effect } from '@open-pencil/scene-graph'
+import type { EffectBindingProperty } from '@open-pencil/scene-graph/variables'
import { TRANSPARENT } from '#core/constants'
import { invalid, parseFigma } from '#core/figma-api/validation'
+import type { FigmaVariableAlias } from '#core/figma-api/variables/values'
/** Blend modes in the order Figma lists them in its messages. */
const BLEND_MODE_KEYS = {
@@ -40,8 +48,17 @@ const nonNegativeSchema = v.pipe(finiteSchema, v.minValue(0))
const colorSchema = v.strictObject({ r: unitSchema, g: unitSchema, b: unitSchema, a: unitSchema })
const vectorSchema = v.strictObject({ x: finiteSchema, y: finiteSchema })
-// Variable bindings on effects are not supported; Figma reports an empty object.
-const boundVariablesSchema = v.optional(v.strictObject({}))
+const aliasSchema = v.strictObject({ type: v.literal('VARIABLE_ALIAS'), id: v.string() })
+const shadowBindingsSchema = v.optional(
+ v.strictObject({
+ color: v.optional(aliasSchema),
+ radius: v.optional(aliasSchema),
+ spread: v.optional(aliasSchema),
+ offsetX: v.optional(aliasSchema),
+ offsetY: v.optional(aliasSchema)
+ })
+)
+const blurBindingsSchema = v.optional(v.strictObject({ radius: v.optional(aliasSchema) }))
const shadowEntries = {
color: colorSchema,
@@ -50,7 +67,7 @@ const shadowEntries = {
spread: v.optional(finiteSchema),
visible: v.boolean(),
blendMode: v.picklist(BLEND_MODES),
- boundVariables: boundVariablesSchema
+ boundVariables: shadowBindingsSchema
}
const effectSchema = v.variant('type', [
@@ -65,7 +82,7 @@ const effectSchema = v.variant('type', [
radius: nonNegativeSchema,
visible: v.boolean(),
blurType: v.optional(v.literal('NORMAL'), 'NORMAL'),
- boundVariables: boundVariablesSchema
+ boundVariables: blurBindingsSchema
})
])
@@ -74,20 +91,76 @@ const effectsSchema = v.array(effectSchema)
/** An effect as Figma's plugin API reads and writes it (`Effect` in `@figma/plugin-typings`). */
export type FigmaEffect = v.InferOutput<typeof effectSchema>
+/** Why OpenPencil cannot keep `effect`, and the field that says so, or null when it can. */
+function unsupportedEffectReason(effect: unknown): { message: string; field: string } | null {
+ const type: unknown = v.is(v.object({ type: v.unknown() }), effect) ? effect.type : undefined
+ if (typeof type === 'string' && UNSUPPORTED_EFFECT_TYPES.has(type)) {
+ return { message: `${type} effects are not supported`, field: 'type' }
+ }
+ if (v.is(v.object({ blurType: v.literal('PROGRESSIVE') }), effect)) {
+ return { message: 'Progressive blur is not supported', field: 'blurType' }
+ }
+ return null
+}
+
function unsupportedEffect(value: unknown): string | null {
if (!Array.isArray(value)) return null
for (const [index, effect] of value.entries()) {
- const type: unknown = v.is(v.object({ type: v.unknown() }), effect) ? effect.type : undefined
- if (typeof type === 'string' && UNSUPPORTED_EFFECT_TYPES.has(type)) {
- return `${type} effects are not supported at [${index}].type`
- }
- if (v.is(v.object({ blurType: v.literal('PROGRESSIVE') }), effect)) {
- return `Progressive blur is not supported at [${index}].blurType`
- }
+ const reason = unsupportedEffectReason(effect)
+ if (reason) return `${reason.message} at [${index}].${reason.field}`
}
return null
}
+/** The shadows and plain blurs OpenPencil models, in the shapes Figma's plugin typings give them. */
+type ModelledPluginEffect = DropShadowEffect | InnerShadowEffect | BlurEffectNormal
+
+function isPluginShadow(
+ effect: ModelledPluginEffect
+): effect is DropShadowEffect | InnerShadowEffect {
+ return effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
+}
+
+function modelledPluginEffect(method: string, effect: PluginEffect): ModelledPluginEffect {
+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') return effect
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {
+ if (effect.blurType !== 'PROGRESSIVE') return effect
+ }
+ const reason = unsupportedEffectReason(effect)
+ throw new Error(`in ${method}: ${reason?.message ?? `${effect.type} effects are not supported`}`)
+}
+
+/**
+ * `effect` with `bindings` as `setBoundVariableForEffect` returns it: fields in Figma's order, a
+ * shadow's spread at 0. Effects OpenPencil does not model are refused, as `effects` refuses them.
+ */
+export function boundEffectCopy(
+ method: string,
+ effect: PluginEffect,
+ bindings: (effect: ModelledPluginEffect) => FigmaEffectBindings
+): FigmaEffect {
+ const modelled = modelledPluginEffect(method, effect)
+ // The copy owns its aliases, so changing them leaves the effect it was made from alone.
+ const boundVariables = structuredClone(bindings(modelled))
+ const { visible, radius } = modelled
+ if (!isPluginShadow(modelled)) {
+ return { type: modelled.type, visible, radius, boundVariables, blurType: 'NORMAL' }
+ }
+ const shadow = {
+ visible,
+ radius,
+ boundVariables,
+ color: { ...modelled.color },
+ offset: { ...modelled.offset },
+ spread: 0,
+ blendMode: modelled.blendMode
+ }
+ if (modelled.type === 'INNER_SHADOW') return { type: modelled.type, ...shadow }
+ return modelled.showShadowBehindNode === undefined
+ ? { type: modelled.type, ...shadow }
+ : { type: modelled.type, ...shadow, showShadowBehindNode: modelled.showShadowBehindNode }
+}
+
/** Check `value` against Figma's effect shapes and convert it to scene effects. */
export function parseFigmaEffects(value: unknown): Effect[] {
const method = 'set_effects'
@@ -129,8 +202,14 @@ function toSceneEffect(effect: FigmaEffect): Effect {
}
}
-/** A scene effect in the shape Figma's `effects` getter returns. */
-export function toFigmaEffect(effect: Effect): FigmaEffect {
+/** The variables an effect's properties are bound to, as its `boundVariables` names them. */
+export type FigmaEffectBindings = Partial<Record<EffectBindingProperty, FigmaVariableAlias>>
+
+/**
+ * A scene effect in the shape Figma's `effects` getter returns, with the variables its properties
+ * are bound to.
+ */
+export function toFigmaEffect(effect: Effect, bindings: FigmaEffectBindings = {}): FigmaEffect {
if (
effect.type === 'LAYER_BLUR' ||
effect.type === 'FOREGROUND_BLUR' ||
@@ -141,14 +220,14 @@ export function toFigmaEffect(effect: Effect): FigmaEffect {
type: effect.type === 'BACKGROUND_BLUR' ? 'BACKGROUND_BLUR' : 'LAYER_BLUR',
visible: effect.visible,
radius: effect.radius,
- boundVariables: {},
+ boundVariables: bindings.radius ? { radius: bindings.radius } : {},
blurType: 'NORMAL'
}
}
const shadow = {
visible: effect.visible,
radius: effect.radius,
- boundVariables: {},
+ boundVariables: bindings,
color: { ...effect.color },
offset: { ...effect.offset },
spread: effect.spread,
diff --git a/packages/core/src/figma-api/styles/apply.ts b/packages/core/src/figma-api/styles/apply.ts
index 1887e85a1..0fdcf3f01 100644
--- a/packages/core/src/figma-api/styles/apply.ts
+++ b/packages/core/src/figma-api/styles/apply.ts
@@ -16,9 +16,9 @@ import {
sharedStyleTypeForKind
} from '@open-pencil/scene-graph/shared-styles'
-import { figmaFills } from '#core/figma-api/accessors/visual'
+import { figmaEffects, figmaFills } from '#core/figma-api/accessors/visual'
import { rangeSharedStylePatch } from '#core/figma-api/text/bindings'
-import { setPaintBindings } from '#core/figma-api/variables/bindings'
+import { setEffectBindings, setPaintBindings } from '#core/figma-api/variables/bindings'
import {
layerTextStyleChanges,
styleRunsWithPatchOver,
@@ -85,6 +85,33 @@ export function bindStylePaints(
setPaintBindings(graph, node, kind === 'fill' ? 'fills' : 'strokes', figmaFills(graph, style))
}
+/**
+ * Binds `node`'s effects to the variables its effect style's effects are bound to, and drops
+ * bindings the style's effects do not carry, so the layer follows them in its own mode as in Figma.
+ */
+export function bindStyleEffects(
+ graph: SceneGraph,
+ node: SceneNode,
+ kind: SharedStyleKind,
+ styleId: string
+): void {
+ if (kind !== 'effect' || !styleId) return
+ const style = findSharedStyle(graph, styleId, 'EFFECT')
+ if (!style) return
+ setEffectBindings(graph, node, figmaEffects(style))
+}
+
+/** Binds `node` to the variables the style it now uses binds, for each kind that binds any. */
+export function bindStyleVariables(
+ graph: SceneGraph,
+ node: SceneNode,
+ kind: SharedStyleKind,
+ styleId: string
+): void {
+ bindStylePaints(graph, node, kind, styleId)
+ bindStyleEffects(graph, node, kind, styleId)
+}
+
/** A layer that uses a style itself, and the fields it uses it through, as Figma lists them. */
export interface StyleConsumer {
node: SceneNode
@@ -181,7 +208,7 @@ export function restyleUsers(graph: SceneGraph, style: SceneNode, update: LayerU
// A layer's own fields only: its ranges keep the values they set themselves.
(node, kind) => sharedStylePatch(kind, node, id, style),
(kind) => rangeSharedStylePatch(graph, kind, id) ?? {},
- (node, kind) => bindStylePaints(graph, node, kind, id)
+ (node, kind) => bindStyleVariables(graph, node, kind, id)
)
}
diff --git a/packages/core/src/figma-api/styles/handles.ts b/packages/core/src/figma-api/styles/handles.ts
index 62997af86..864b08419 100644
--- a/packages/core/src/figma-api/styles/handles.ts
+++ b/packages/core/src/figma-api/styles/handles.ts
@@ -11,7 +11,8 @@ import { figmaFills } from '#core/figma-api/accessors/visual'
import { parseFigmaPaints, type FigmaPaint } from '#core/figma-api/paints'
import type { FigmaNodeProxy } from '#core/figma-api/proxy'
import { parseFigma } from '#core/figma-api/validation'
-import { setPaintBindings } from '#core/figma-api/variables/bindings'
+import { figmaBoundVariables, setPaintBindings } from '#core/figma-api/variables/bindings'
+import type { FigmaVariableAlias } from '#core/figma-api/variables/values'
import { releaseUsers, restyleUsers, styleConsumers, type LayerUpdate } from './apply'
@@ -55,7 +56,6 @@ export abstract class FigmaBaseStyle {
abstract readonly type: FigmaStyleType
readonly remote = false
readonly documentationLinks: readonly never[] = Object.freeze([])
- readonly boundVariables: Readonly<Record<string, never>> = Object.freeze({})
readonly [HOST]: StyleHost
constructor(host: StyleHost, id: string) {
@@ -81,6 +81,11 @@ export abstract class FigmaBaseStyle {
restyleUsers(this[HOST].graph, this[NODE]('restyle'), this[HOST].updateLayer)
}
+ /** The variables the style's values use; only an effect style lists any. */
+ get boundVariables(): Readonly<Record<string, readonly FigmaVariableAlias[]>> {
+ return Object.freeze({})
+ }
+
get name(): string {
return this[NODE]('get_name').name
}
@@ -161,6 +166,14 @@ export class FigmaEffectStyle extends FigmaBaseStyle {
this[LAYER]('set_effects').effects = value
this[RESTYLE]()
}
+
+ /** Every variable the style's effects use, each once, as a layer lists its own. */
+ override get boundVariables(): Readonly<Record<string, readonly FigmaVariableAlias[]>> {
+ const { effects } = figmaBoundVariables(this[NODE]('get_boundVariables'))
+ const bound: Record<string, readonly FigmaVariableAlias[]> = {}
+ if (Array.isArray(effects)) bound.effects = effects
+ return Object.freeze(bound)
+ }
}
export class FigmaGridStyle extends FigmaBaseStyle {
diff --git a/packages/core/src/figma-api/variables/bindings.ts b/packages/core/src/figma-api/variables/bindings.ts
index 9dc5e79c3..19f1b28ae 100644
--- a/packages/core/src/figma-api/variables/bindings.ts
+++ b/packages/core/src/figma-api/variables/bindings.ts
@@ -10,8 +10,16 @@ import {
type VariableType
} from '@open-pencil/scene-graph'
import { recordInstanceOverride } from '@open-pencil/scene-graph/instances'
-import { independentCornerChanges, paintBindingTarget } from '@open-pencil/scene-graph/variables'
+import {
+ effectBindableProperties,
+ effectBindingField,
+ effectBindingTarget,
+ effectBindingVariableType,
+ independentCornerChanges,
+ paintBindingTarget
+} from '@open-pencil/scene-graph/variables'
+import type { FigmaEffect, FigmaEffectBindings } from '#core/figma-api/effects'
import type { FigmaPaint } from '#core/figma-api/paints'
import { reconcileVariableLayouts } from '#core/layout/variables'
@@ -239,11 +247,62 @@ export function setPaintBindings(
if (current.size > 0 || wanted.size > 0) reconcileVariableLayouts(graph, { subtrees: [node.id] })
}
+/** The variables each effect's properties are bound to, by effect index. */
+export function effectBindings(node: SceneNode): Map<number, FigmaEffectBindings> {
+ const bindings = new Map<number, FigmaEffectBindings>()
+ for (const [field, id] of Object.entries(node.boundVariables)) {
+ const target = effectBindingTarget(field)
+ if (!target) continue
+ const effect = bindings.get(target.index) ?? {}
+ effect[target.property] = variableAlias(id)
+ bindings.set(target.index, effect)
+ }
+ return bindings
+}
+
+/**
+ * Binds each effect's properties to the variables its `boundVariables` names, as Figma does when
+ * effects are set, and drops bindings the effects no longer carry. A reference to a missing
+ * variable, one of the wrong type, or a property the effect lacks binds nothing.
+ */
+export function setEffectBindings(
+ graph: SceneGraph,
+ node: SceneNode,
+ effects: readonly FigmaEffect[]
+): void {
+ const current = new Map(
+ Object.entries(node.boundVariables).filter(([field]) => effectBindingTarget(field))
+ )
+ const wanted = new Map<string, string>()
+ effects.forEach((effect, index) => {
+ const bound: FigmaEffectBindings = effect.boundVariables ?? {}
+ for (const property of effectBindableProperties(effect.type)) {
+ const id = bound[property]?.id
+ if (id && graph.variables.get(id)?.type === effectBindingVariableType(property))
+ wanted.set(effectBindingField(index, property), id)
+ }
+ })
+ for (const field of current.keys()) {
+ if (!wanted.has(field)) graph.unbindVariable(node.id, field)
+ }
+ for (const [field, id] of wanted) {
+ if (current.get(field) !== id) graph.bindVariable(node.id, field, id)
+ }
+ if (current.size > 0 || wanted.size > 0) reconcileVariableLayouts(graph, { subtrees: [node.id] })
+}
+
+/** Figma's order for a list of variables: by ID, each once. */
+function byVariableId(ids: readonly string[]): FigmaVariableAlias[] {
+ return uniq(ids)
+ .sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))
+ .map(variableAlias)
+}
+
type FigmaBoundVariables = Record<string, FigmaVariableAlias | FigmaVariableAlias[]>
/**
* A layer's bindings as Figma's `boundVariables` reads them: a reference per node field, a list
- * per text style field and per bound paint.
+ * per text style field and per bound paint, and one list of every variable its effects use.
*/
export function figmaBoundVariables(node: SceneNode): FigmaBoundVariables {
const result: FigmaBoundVariables = {}
@@ -273,5 +332,9 @@ export function figmaBoundVariables(node: SceneNode): FigmaBoundVariables {
.sort(([a], [b]) => a - b)
.map(([, id]) => variableAlias(id))
}
+ const effectIds = Object.entries(node.boundVariables)
+ .filter(([field]) => effectBindingTarget(field))
+ .map(([, id]) => id)
+ if (effectIds.length > 0) result.effects = byVariableId(effectIds)
return result
}
diff --git a/packages/core/src/figma-api/variables/index.ts b/packages/core/src/figma-api/variables/index.ts
index 7e49fba64..76c07db44 100644
--- a/packages/core/src/figma-api/variables/index.ts
+++ b/packages/core/src/figma-api/variables/index.ts
@@ -1,4 +1,17 @@
-import type { SceneGraph, VariableType } from '@open-pencil/scene-graph'
+import type {
+ Effect as PluginEffect,
+ VariableBindableEffectField
+} from '@figma/plugin-typings/plugin-api-standalone'
+
+import type { Effect, SceneGraph, VariableType } from '@open-pencil/scene-graph'
+import {
+ EFFECT_BINDING_PROPERTIES,
+ effectBindableProperties,
+ effectBindingVariableType,
+ type EffectBindingProperty
+} from '@open-pencil/scene-graph/variables'
+
+import { boundEffectCopy, type FigmaEffect } from '#core/figma-api/effects'
import { FIGMA_DEFAULT_VALUES, variableAlias, type FigmaVariableAlias } from './values'
import { FigmaVariable, FigmaVariableCollection, assertVariableName } from './variable'
@@ -9,6 +22,8 @@ export {
figmaBoundVariables,
paintBindings,
setLayerBinding,
+ effectBindings,
+ setEffectBindings,
setPaintBindings,
type FigmaBindableField
} from './bindings'
@@ -141,4 +156,42 @@ export class FigmaVariablesAPI {
boundVariables: { ...others, color: variableAlias(variable.id) }
}
}
+
+ /**
+ * A copy of `effect` with one property bound to `variable`; it binds when the effect is set on a
+ * layer. As in Figma, the copy's values are not resolved yet, a shadow's spread reads 0, and
+ * `null` unbinds every property of the effect, not only `field`.
+ */
+ setBoundVariableForEffect(
+ effect: PluginEffect,
+ field: VariableBindableEffectField,
+ variable: { readonly id: string } | null
+ ): FigmaEffect {
+ return boundEffectCopy('setBoundVariableForEffect', effect, (modelled) => {
+ const property = assertEffectField(modelled.type, field)
+ if (variable === null) return {}
+ if (typeof variable !== 'object') {
+ throw new TypeError(`in setBoundVariableForEffect: Expected node, got ${typeof variable}`)
+ }
+ const type = effectBindingVariableType(property)
+ if (this.#graph.variables.get(variable.id)?.type !== type) {
+ throw new Error(
+ `in setBoundVariableForEffect: can only bind ${type.toLowerCase()} variables to ${property}`
+ )
+ }
+ return { ...modelled.boundVariables, [property]: variableAlias(variable.id) }
+ })
+ }
+}
+
+/** Figma's check of the property `setBoundVariableForEffect` binds, which a blur limits to radius. */
+function assertEffectField(type: Effect['type'], field: unknown): EffectBindingProperty {
+ const properties = effectBindableProperties(type)
+ const found = properties.find((property) => property === field)
+ if (found) return found
+ const expected =
+ properties.length === 1
+ ? `Invalid input: expected "${properties[0]}"`
+ : `Invalid option: expected one of ${EFFECT_BINDING_PROPERTIES.map((name) => `"${name}"`).join('|')}`
+ throw new Error(`in setBoundVariableForEffect: Property "field" failed validation: ${expected}`)
}
diff --git a/packages/core/src/io/formats/design-tokens/styles.ts b/packages/core/src/io/formats/design-tokens/styles.ts
index 27ac8b15b..979f52cd8 100644
--- a/packages/core/src/io/formats/design-tokens/styles.ts
+++ b/packages/core/src/io/formats/design-tokens/styles.ts
@@ -122,7 +122,11 @@ function shadowToken(node: SceneNode): DesignToken | undefined {
$value,
...(exact
? {}
- : { $extensions: { [OPENPENCIL_EXTENSION]: { effects: node.effects.map(toFigmaEffect) } } })
+ : {
+ $extensions: {
+ [OPENPENCIL_EXTENSION]: { effects: node.effects.map((effect) => toFigmaEffect(effect)) }
+ }
+ })
}
}
diff --git a/packages/core/src/tools/variables/bindings.ts b/packages/core/src/tools/variables/bindings.ts
index 9bd0aace2..ed728f8fb 100644
--- a/packages/core/src/tools/variables/bindings.ts
+++ b/packages/core/src/tools/variables/bindings.ts
@@ -22,7 +22,9 @@ export const bindVariable = defineTool({
'"borderTopWeight", "borderBottomWeight", "borderLeftWeight", "borderRightWeight", ' +
'"gridRowGap", "gridColumnGap". ' +
'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".'
+ 'For BOOLEAN or STRING: "visible", text showing the layer unless empty or "false", "no", "off". ' +
+ 'For effects use indexed format: "effects/0/color" (COLOR), "effects/0/radius", ' +
+ '"effects/0/spread", "effects/0/offsetX", "effects/0/offsetY" (FLOAT); a blur binds only radius.'
)
),
variable_id: v.pipe(v.string(), v.description('Variable ID'))
diff --git a/packages/core/tests/canvas/blur.test.ts b/packages/core/tests/canvas/blur.test.ts
index fb63fbca1..7dfc8b302 100644
--- a/packages/core/tests/canvas/blur.test.ts
+++ b/packages/core/tests/canvas/blur.test.ts
@@ -117,6 +117,25 @@ function square(graph: SceneGraph, frameId: string, props: Partial<SceneNode>) {
graph.createNode('RECTANGLE', frameId, { x: 100, y: 100, width: 200, height: 200, ...props })
}
+/** Red across a black-to-white edge at x = 100 under a layer of background blur. */
+function backgroundBlurRow(radius: number): number[] {
+ return edgeRow((graph, frameId) => {
+ graph.createNode('RECTANGLE', frameId, { width: 100, height: 400, fills: [solid(0, 0, 0)] })
+ graph.createNode('RECTANGLE', frameId, {
+ x: 100,
+ width: 300,
+ height: 400,
+ fills: [solid(1, 1, 1)]
+ })
+ graph.createNode('RECTANGLE', frameId, {
+ width: 400,
+ height: 400,
+ fills: [solid(1, 1, 1, 0.01)],
+ effects: [effect('BACKGROUND_BLUR', radius)]
+ })
+ }, 0)
+}
+
function expectFigmaEdge(row: number[], figma: number[], from = 60) {
const differences = row.flatMap((value, index) =>
60 + index < from ? [] : [Math.abs(value - figma[index])]
@@ -161,22 +180,7 @@ describe('blur effects fall off as in Figma', () => {
})
test('background blur', () => {
- const row = edgeRow((graph, frameId) => {
- graph.createNode('RECTANGLE', frameId, { width: 100, height: 400, fills: [solid(0, 0, 0)] })
- graph.createNode('RECTANGLE', frameId, {
- x: 100,
- width: 300,
- height: 400,
- fills: [solid(1, 1, 1)]
- })
- graph.createNode('RECTANGLE', frameId, {
- width: 400,
- height: 400,
- fills: [solid(1, 1, 1, 0.01)],
- effects: [effect('BACKGROUND_BLUR', 16)]
- })
- }, 0)
- expectFigmaEdge(row, FIGMA['BACKGROUND_BLUR 16'])
+ expectFigmaEdge(backgroundBlurRow(16), FIGMA['BACKGROUND_BLUR 16'])
})
test('background blur on a boolean, inside its result alone', () => {
@@ -205,6 +209,51 @@ describe('blur effects fall off as in Figma', () => {
})
})
+describe('a negative blur, which only a bound variable gives', () => {
+ // Figma 126 exports each effect at radius -6 pixel for pixel as at radius 0.
+ for (const type of ['DROP_SHADOW', 'INNER_SHADOW', 'LAYER_BLUR'] as const) {
+ test(`draws a ${type.toLowerCase()} as no blur`, () => {
+ // An inner shadow moved right darkens the white fill at the left edge the row crosses.
+ const inner = type === 'INNER_SHADOW'
+ const row = (radius: number) =>
+ edgeRow(
+ (graph, frameId) =>
+ square(graph, frameId, {
+ fills: [solid(1, 1, 1)],
+ effects: [{ ...effect(type, radius), offset: { x: inner ? 10 : -10, y: 0 } }]
+ }),
+ inner ? 0 : 3
+ )
+ expect(row(-6)).toEqual(row(0))
+ })
+ }
+
+ for (const type of ['DROP_SHADOW', 'INNER_SHADOW'] as const) {
+ test(`draws a ${type.toLowerCase()} cast from a boolean's silhouette as no blur`, () => {
+ const inner = type === 'INNER_SHADOW'
+ const row = (radius: number) =>
+ edgeRow((graph, frameId) => {
+ const union = graph.createNode('BOOLEAN_OPERATION', frameId, {
+ x: 100,
+ y: 100,
+ width: 200,
+ height: 200,
+ booleanOperation: 'UNION',
+ fills: [solid(1, 1, 1)],
+ effects: [{ ...effect(type, radius), offset: { x: inner ? 10 : -10, y: 0 } }]
+ })
+ graph.createNode('RECTANGLE', union.id, { width: 200, height: 120 })
+ graph.createNode('RECTANGLE', union.id, { y: 80, width: 200, height: 120 })
+ }, inner ? 0 : 3)
+ expect(row(-6)).toEqual(row(0))
+ })
+ }
+
+ test('draws a background blur as no blur', () => {
+ expect(backgroundBlurRow(-6)).toEqual(backgroundBlurRow(0))
+ })
+})
+
describe('shadows of a transparent fill', () => {
const shadowRow = (opacity: number, showShadowBehindNode = false) =>
edgeRow(
diff --git a/packages/core/tests/figma-api/variables/effects.test.ts b/packages/core/tests/figma-api/variables/effects.test.ts
new file mode 100644
index 000000000..0b962865c
--- /dev/null
+++ b/packages/core/tests/figma-api/variables/effects.test.ts
@@ -0,0 +1,244 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { createAPI, registerTestFont } from '#core-tests/helpers/figma-api'
+
+beforeAll(() => registerTestFont())
+
+// Expected values and messages were recorded by running the same calls in Figma desktop.
+
+const DROP = {
+ type: 'DROP_SHADOW' as const,
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ offset: { x: 1, y: 2 },
+ radius: 3,
+ spread: 4,
+ visible: true,
+ blendMode: 'NORMAL' as const
+}
+
+/** Light and Dark shadow tokens, as the probe in Figma set them up. */
+function elevation() {
+ const api = createAPI()
+ const collection = api.variables.createVariableCollection('Elevation')
+ const light = collection.defaultModeId
+ const dark = collection.addMode('Dark')
+ const color = api.variables.createVariable('shadowColor', collection, 'COLOR')
+ color.setValueForMode(light, { r: 0, g: 0, b: 0.5, a: 0.25 })
+ color.setValueForMode(dark, { r: 0, g: 0, b: 0, a: 0.6 })
+ const radius = api.variables.createVariable('shadowRadius', collection, 'FLOAT')
+ radius.setValueForMode(light, 8)
+ radius.setValueForMode(dark, 24)
+ const label = api.variables.createVariable('label', collection, 'STRING')
+ return { api, collection, dark, color, radius, label }
+}
+
+const alias = (id: string) => ({ type: 'VARIABLE_ALIAS' as const, id })
+
+describe('setBoundVariableForEffect', () => {
+ test('returns a bound copy whose values are not resolved and whose spread reads 0', () => {
+ const { api, color } = elevation()
+ const bound = api.variables.setBoundVariableForEffect(DROP, 'color', color)
+
+ expect(bound).toEqual({ ...DROP, spread: 0, boundVariables: { color: alias(color.id) } })
+ expect(DROP).not.toHaveProperty('boundVariables')
+ expect(api.variables.setBoundVariableForEffect(bound, 'color', null).boundVariables).toEqual({})
+ })
+
+ test('binding keeps the effect’s other bindings and null clears them all', () => {
+ const { api, color, radius } = elevation()
+ const both = api.variables.setBoundVariableForEffect(
+ api.variables.setBoundVariableForEffect(DROP, 'color', color),
+ 'radius',
+ radius
+ )
+
+ expect(both.boundVariables).toEqual({ color: alias(color.id), radius: alias(radius.id) })
+ expect(api.variables.setBoundVariableForEffect(both, 'radius', null).boundVariables).toEqual({})
+ })
+
+ test('returns a copy that shares no aliases with the effect it was made from', () => {
+ const { api, color, radius } = elevation()
+ const bound = api.variables.setBoundVariableForEffect(DROP, 'color', color)
+ const copy = api.variables.setBoundVariableForEffect(bound, 'radius', radius)
+ const aliases = copy.boundVariables
+ if (aliases && 'color' in aliases && aliases.color) aliases.color.id = radius.id
+
+ expect(bound.boundVariables).toEqual({ color: alias(color.id) })
+ })
+
+ test('binds every shadow property and a blur’s radius only', () => {
+ const { api, radius } = elevation()
+ for (const field of ['radius', 'spread', 'offsetX', 'offsetY'] as const)
+ expect(api.variables.setBoundVariableForEffect(DROP, field, radius).boundVariables).toEqual({
+ [field]: alias(radius.id)
+ })
+
+ const blur = {
+ type: 'LAYER_BLUR' as const,
+ radius: 4,
+ visible: true,
+ blurType: 'NORMAL' as const
+ }
+ expect(api.variables.setBoundVariableForEffect(blur, 'radius', radius)).toEqual({
+ ...blur,
+ boundVariables: { radius: alias(radius.id) }
+ })
+ expect(() => api.variables.setBoundVariableForEffect(blur, 'color', radius)).toThrow(
+ 'in setBoundVariableForEffect: Property "field" failed validation: Invalid input: expected "radius"'
+ )
+ })
+
+ test('refuses other fields, the wrong variable type, and a variable ID', () => {
+ const { api, color, radius, label } = elevation()
+ const bind = (field: string, variable: unknown) => () =>
+ Reflect.apply(api.variables.setBoundVariableForEffect, api.variables, [DROP, field, variable])
+
+ expect(bind('offset', radius)).toThrow(
+ 'in setBoundVariableForEffect: Property "field" failed validation: Invalid option: expected one of "color"|"radius"|"spread"|"offsetX"|"offsetY"'
+ )
+ expect(bind('color', radius)).toThrow(
+ 'in setBoundVariableForEffect: can only bind color variables to color'
+ )
+ expect(bind('radius', color)).toThrow(
+ 'in setBoundVariableForEffect: can only bind float variables to radius'
+ )
+ expect(bind('offsetX', label)).toThrow(
+ 'in setBoundVariableForEffect: can only bind float variables to offsetX'
+ )
+ expect(bind('radius', radius.id)).toThrow(
+ 'in setBoundVariableForEffect: Expected node, got string'
+ )
+ })
+})
+
+describe('bound effects on a layer', () => {
+ test('read resolved in the layer’s mode and carry their variables', () => {
+ const { api, collection, dark, color, radius } = elevation()
+ let effect = api.variables.setBoundVariableForEffect(DROP, 'color', color)
+ effect = api.variables.setBoundVariableForEffect(effect, 'radius', radius)
+ effect = api.variables.setBoundVariableForEffect(effect, 'offsetY', radius)
+ const rect = api.createRectangle()
+ rect.effects = [effect]
+ const bindings = { color: alias(color.id), radius: alias(radius.id), offsetY: alias(radius.id) }
+
+ expect(rect.effects).toEqual([
+ {
+ ...DROP,
+ color: { r: 0, g: 0, b: 0.5, a: 0.25 },
+ radius: 8,
+ offset: { x: 1, y: 8 },
+ spread: 0,
+ boundVariables: bindings,
+ showShadowBehindNode: true
+ }
+ ])
+ expect(rect.boundVariables).toEqual({ effects: [alias(color.id), alias(radius.id)] })
+
+ rect.setExplicitVariableModeForCollection(collection, dark)
+ expect(rect.effects[0]).toMatchObject({
+ color: { r: 0, g: 0, b: 0, a: 0.6 },
+ radius: 24,
+ offset: { x: 1, y: 24 }
+ })
+ })
+
+ test('list each variable once, by ID, hidden effects included', () => {
+ const { api, color, radius } = elevation()
+ const rect = api.createRectangle()
+ rect.effects = [
+ { ...api.variables.setBoundVariableForEffect(DROP, 'radius', radius), visible: false },
+ api.variables.setBoundVariableForEffect(DROP, 'color', color),
+ api.variables.setBoundVariableForEffect(DROP, 'spread', radius)
+ ]
+
+ expect(rect.boundVariables).toEqual({ effects: [alias(color.id), alias(radius.id)] })
+ })
+
+ test('unbind when set without the reference, keeping the value', () => {
+ const { api, collection, dark, radius } = elevation()
+ const rect = api.createRectangle()
+ rect.setExplicitVariableModeForCollection(collection, dark)
+ rect.effects = [api.variables.setBoundVariableForEffect(DROP, 'radius', radius)]
+ rect.effects = [api.variables.setBoundVariableForEffect(rect.effects[0], 'radius', null)]
+
+ expect(rect.effects[0]).toMatchObject({ radius: 24, boundVariables: {} })
+ expect(rect.boundVariables).toEqual({})
+ })
+
+ test('follow an effect style’s variables in the layer’s own mode', async () => {
+ const { api, collection, dark, radius } = elevation()
+ const style = api.createEffectStyle()
+ style.effects = [api.variables.setBoundVariableForEffect(DROP, 'radius', radius)]
+ const rect = api.createRectangle()
+ await rect.setEffectStyleIdAsync(style.id)
+ rect.setExplicitVariableModeForCollection(collection, dark)
+
+ expect(rect.effects[0]).toMatchObject({
+ radius: 24,
+ boundVariables: { radius: alias(radius.id) }
+ })
+ expect(rect.boundVariables).toEqual({ effects: [alias(radius.id)] })
+
+ await rect.setEffectStyleIdAsync('')
+ expect(rect.boundVariables).toEqual({ effects: [alias(radius.id)] })
+ })
+
+ test('follow a style rebound to another variable of the same value', async () => {
+ const { api, collection, radius } = elevation()
+ const twin = api.variables.createVariable('twin', collection, 'FLOAT')
+ twin.setValueForMode(collection.defaultModeId, 8)
+ const style = api.createEffectStyle()
+ style.effects = [api.variables.setBoundVariableForEffect(DROP, 'radius', radius)]
+ const rect = api.createRectangle()
+ await rect.setEffectStyleIdAsync(style.id)
+
+ style.effects = [api.variables.setBoundVariableForEffect(DROP, 'radius', twin)]
+ expect(rect.effects[0]).toMatchObject({ radius: 8, boundVariables: { radius: alias(twin.id) } })
+ expect(rect.effectStyleId).toBe(style.id)
+
+ twin.setValueForMode(collection.defaultModeId, 20)
+ radius.setValueForMode(collection.defaultModeId, 50)
+ expect(rect.effects[0].radius).toBe(20)
+ expect(rect.boundVariables).toEqual({ effects: [alias(twin.id)] })
+ })
+
+ test('resolve in an instance’s mode', () => {
+ const { api, collection, dark, color } = elevation()
+ const component = api.createComponent()
+ component.effects = [api.variables.setBoundVariableForEffect(DROP, 'color', color)]
+ const instance = component.createInstance()
+ instance.setExplicitVariableModeForCollection(collection, dark)
+
+ expect(instance.effects[0].type === 'DROP_SHADOW' && instance.effects[0].color).toEqual({
+ r: 0,
+ g: 0,
+ b: 0,
+ a: 0.6
+ })
+ })
+
+ test('scale with an instance, whenever bound, and not with a plain layer', () => {
+ const { api, collection, dark, radius } = elevation()
+ const shadow = api.variables.setBoundVariableForEffect(DROP, 'radius', radius)
+ const rect = api.createRectangle()
+ rect.effects = [shadow]
+ rect.rescale(2)
+ rect.setExplicitVariableModeForCollection(collection, dark)
+ expect(rect.effects[0].radius).toBe(24)
+
+ const component = api.createComponent()
+ const child = api.createRectangle()
+ component.appendChild(child)
+ child.effects = [shadow]
+ const instance = component.createInstance()
+ instance.rescale(2)
+ expect(instance.children[0].effects[0].radius).toBe(16)
+ instance.setExplicitVariableModeForCollection(collection, dark)
+ expect(instance.children[0].effects[0].radius).toBe(48)
+
+ const scaled = component.createInstance()
+ scaled.rescale(3)
+ scaled.effects = [shadow]
+ expect(scaled.effects[0].radius).toBe(24)
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/export/effect-variable-binding.test.ts b/packages/core/tests/io/formats/fig/export/effect-variable-binding.test.ts
new file mode 100644
index 000000000..93ffc303c
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/effect-variable-binding.test.ts
@@ -0,0 +1,138 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
+import { parseFigBuffer, patchFigArchive } from '@open-pencil/fig'
+import { initCodec } from '@open-pencil/kiwi/fig/codec'
+import { SceneGraph, type Effect } from '@open-pencil/scene-graph'
+
+const SHADOW: Effect = {
+ type: 'DROP_SHADOW',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ offset: { x: 0, y: 2 },
+ radius: 3,
+ spread: 0,
+ visible: true,
+ blendMode: 'NORMAL'
+}
+
+/** A Light and Dark shadow, the Dark default, with one card in each mode. */
+function elevation() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const theme = graph.createCollection('Theme')
+ const light = theme.defaultModeId
+ graph.addMode(theme.id, 'dark', 'Dark')
+ const color = graph.createVariable('Shadow', 'COLOR', theme.id, { r: 0, g: 0, b: 0.5, a: 0.25 })
+ color.valuesByMode.dark = { r: 0, g: 0, b: 0, a: 0.6 }
+ const radius = graph.createVariable('Blur', 'FLOAT', theme.id, 8)
+ radius.valuesByMode.dark = 24
+ const card = (name: string, variableModes: Record<string, string> = {}) => {
+ const node = graph.createNode('RECTANGLE', page.id, {
+ name,
+ width: 40,
+ height: 40,
+ variableModes,
+ effects: [SHADOW]
+ })
+ graph.bindVariable(node.id, 'effects/0/color', color.id)
+ graph.bindVariable(node.id, 'effects/0/radius', radius.id)
+ graph.bindVariable(node.id, 'effects/0/offsetY', radius.id)
+ return node
+ }
+ card('Light card', { [theme.id]: light })
+ card('Dark card', { [theme.id]: 'dark' })
+ return { graph, theme }
+}
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+describe('Figma export of effect variable bindings', () => {
+ test('writes each bound property as an alias, with the value of the card’s mode', async () => {
+ const { graph } = elevation()
+ const records = parseFigBuffer(Uint8Array.from(await exportFigFile(graph)).buffer).nodeChanges
+ const guid = (name: string) =>
+ expectDefined(
+ records.find((record) => record.type === 'VARIABLE' && record.name === name)?.guid,
+ name
+ )
+ const effect = (name: string) =>
+ expectDefined(records.find((record) => record.name === name)?.effects?.[0], name)
+ const alias = (name: string, type: string) => ({
+ dataType: 'ALIAS',
+ resolvedDataType: type,
+ value: { alias: { guid: guid(name) } }
+ })
+
+ expect(effect('Light card')).toMatchObject({
+ radius: 8,
+ offset: { x: 0, y: 8 },
+ colorVar: alias('Shadow', 'COLOR'),
+ radiusVar: alias('Blur', 'FLOAT'),
+ yVar: alias('Blur', 'FLOAT')
+ })
+ expect(effect('Light card').color?.a).toBeCloseTo(0.25, 5)
+ expect(effect('Light card')).not.toHaveProperty('spreadVar')
+ expect(effect('Dark card')).toMatchObject({ radius: 24, offset: { x: 0, y: 24 } })
+ })
+
+ test('reads the aliases back and resolves the values a file saved for another mode', async () => {
+ const { graph } = elevation()
+ const exported = await exportFigFile(graph)
+ const record = expectDefined(
+ parseFigBuffer(Uint8Array.from(exported).buffer).nodeChanges.find(
+ (node) => node.name === 'Dark card'
+ ),
+ 'Dark card'
+ )
+ // Figma saves the default mode's values even on a layer set to another mode.
+ const saved = {
+ ...record,
+ effects: record.effects?.map((effect) => ({ ...effect, radius: 8, offset: { x: 0, y: 8 } }))
+ }
+ const patched = patchFigArchive(
+ Uint8Array.from(exported).buffer,
+ { records: [saved], blobs: [], removed: [], replaceVariables: false },
+ { thumbnailPNG: new Uint8Array(), metaJSON: '{}', images: [] }
+ )
+
+ const reopened = await parseFigFile(Uint8Array.from(patched).buffer)
+ const variable = (name: string) =>
+ expectDefined(
+ [...reopened.variables.values()].find((candidate) => candidate.name === name),
+ name
+ ).id
+ const dark = expectDefined(
+ [...reopened.getAllNodes()].find((node) => node.name === 'Dark card'),
+ 'reopened Dark card'
+ )
+
+ expect(dark.boundVariables).toMatchObject({
+ 'effects/0/color': variable('Shadow'),
+ 'effects/0/radius': variable('Blur'),
+ 'effects/0/offsetY': variable('Blur')
+ })
+ expect(dark.effects[0]).toMatchObject({ radius: 24, offset: { x: 0, y: 24 } })
+ expect(dark.effects[0].color.a).toBeCloseTo(0.6, 5)
+ })
+
+ test('drops an alias the document no longer binds', async () => {
+ const { graph } = elevation()
+ const reopened = await parseFigFile(Uint8Array.from(await exportFigFile(graph)).buffer)
+ const light = expectDefined(
+ [...reopened.getAllNodes()].find((node) => node.name === 'Light card'),
+ 'reopened Light card'
+ )
+ reopened.unbindVariable(light.id, 'effects/0/radius')
+
+ const records = parseFigBuffer(
+ Uint8Array.from(await exportFigFile(reopened)).buffer
+ ).nodeChanges
+ const effect = records.find((record) => record.name === 'Light card')?.effects?.[0]
+ expect(effect).not.toHaveProperty('radiusVar')
+ expect(effect).toHaveProperty('yVar')
+ })
+})
diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.md
index 3bbb380a0..30c65ab3b 100644
--- a/packages/docs/programmable/cli/scripting.md
+++ b/packages/docs/programmable/cli/scripting.md
@@ -235,7 +235,7 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'
- `figma.variables.getLocalVariables(type?)`, `getVariableById(id)`, `getLocalVariableCollections()`, `getVariableCollectionById(id)`, and their `…Async` forms
- `figma.variables.createVariableCollection(name)` and `createVariable(name, collection, resolvedType)`, which starts every mode at Figma's default
-- `figma.variables.createVariableAlias(variable)` and `setBoundVariableForPaint(paint, 'color', variable)`
+- `figma.variables.createVariableAlias(variable)`, `setBoundVariableForPaint(paint, 'color', variable)`, and `setBoundVariableForEffect(effect, field, variable)`, which binds a shadow's `color`, `radius`, `spread`, `offsetX`, or `offsetY`, or a blur's `radius`
- `variable.setValueForMode(modeId, value)`, `valuesByMode`, `resolveForConsumer(node)`, `name`, `description`, `scopes`, `codeSyntax`, and `remove()`
- `collection.addMode(name)`, `renameMode(modeId, name)`, `removeMode(modeId)`, `modes`, `defaultModeId`, `variableIds`, and `remove()`
- `node.boundVariables`, `node.setBoundVariable(field, variable)`, `node.setExplicitVariableModeForCollection(collection, modeId)`, and `node.clearExplicitVariableModeForCollection(collection)`
@@ -294,7 +294,7 @@ Common node properties are readable/writable through the proxy, including:
These Figma APIs are not exposed as compatible helpers yet:
- `figma.util.normalizeMarkdown()`, which fails because OpenPencil has no rich-text descriptions or annotations to normalize for
-- Library variables, extended collections, and variable bindings on effects and layout grids
+- Library variables, extended collections, and variable bindings on layout grids
- Full vector boolean operation parity
Use OpenPencil CLI export commands, core tools, or direct scene-graph helpers where available.
diff --git a/packages/docs/ru/programmable/cli/scripting.md b/packages/docs/ru/programmable/cli/scripting.md
index 3cd55d4c7..c4dcbe0f3 100644
--- a/packages/docs/ru/programmable/cli/scripting.md
+++ b/packages/docs/ru/programmable/cli/scripting.md
@@ -114,7 +114,7 @@ API намеренно близок к Figma Plugin API, но работает
- `figma.variables.getLocalVariables(type?)`, `getVariableById(id)`, `getLocalVariableCollections()`, `getVariableCollectionById(id)` и их варианты `…Async`
- `figma.variables.createVariableCollection(name)` и `createVariable(name, collection, resolvedType)` — каждый режим получает значение Figma по умолчанию
-- `figma.variables.createVariableAlias(variable)` и `setBoundVariableForPaint(paint, 'color', variable)`
+- `figma.variables.createVariableAlias(variable)`, `setBoundVariableForPaint(paint, 'color', variable)` и `setBoundVariableForEffect(effect, field, variable)` — привязывает `color`, `radius`, `spread`, `offsetX` или `offsetY` тени либо `radius` размытия
- `variable.setValueForMode(modeId, value)`, `valuesByMode`, `resolveForConsumer(node)`, `name`, `description`, `scopes`, `codeSyntax` и `remove()`
- `collection.addMode(name)`, `renameMode(modeId, name)`, `removeMode(modeId)`, `modes`, `defaultModeId`, `variableIds` и `remove()`
- `node.boundVariables`, `node.setBoundVariable(field, variable)` — поля и типы как в Figma, `node.setExplicitVariableModeForCollection(collection, modeId)` и `node.clearExplicitVariableModeForCollection(collection)`
@@ -149,7 +149,7 @@ API намеренно близок к Figma Plugin API, но работает
Следующие API пока не предоставляются в совместимом виде:
-- переменные из библиотек, расширенные коллекции и привязки переменных к эффектам и сеткам
+- переменные из библиотек, расширенные коллекции и привязки переменных к сеткам
- полная совместимость логических операций над векторами
Вместо них используйте команды экспорта OpenPencil CLI, инструменты основного пакета или прямые вспомогательные функции SceneGraph, когда они доступны.
diff --git a/packages/fig/src/document/bindings/effects.ts b/packages/fig/src/document/bindings/effects.ts
new file mode 100644
index 000000000..459eeb73f
--- /dev/null
+++ b/packages/fig/src/document/bindings/effects.ts
@@ -0,0 +1,16 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { resolvedEffectBindings } from '@open-pencil/scene-graph/variables'
+
+/**
+ * Resolve bound effect values once hierarchy and modes exist: a file saves the default mode's
+ * values even on a layer set to another mode, and Figma resolves them again on open.
+ */
+export function applyDocumentEffectBindings(
+ graph: SceneGraph,
+ materialized: readonly SceneNode[]
+): void {
+ for (const node of materialized) {
+ const changes = resolvedEffectBindings(graph, node)
+ if (changes.effects) graph.updateNode(node.id, changes)
+ }
+}
diff --git a/packages/fig/src/document/bindings/references.ts b/packages/fig/src/document/bindings/references.ts
index a614776f8..ce1ca79f3 100644
--- a/packages/fig/src/document/bindings/references.ts
+++ b/packages/fig/src/document/bindings/references.ts
@@ -1,5 +1,6 @@
import { symbolOverridesOf, type SymbolOverride } from '#fig/instance-overrides/types'
import { variableConsumptionEntries } from '#fig/node-change/variable/bindings'
+import { effectVariableAliases } from '#fig/node-change/variable/effects'
import { visitVariableReferences } from '#fig/node-change/variable/expression'
import type { GUID } from '@open-pencil/kiwi/fig'
@@ -61,6 +62,9 @@ function createRecordNormalizer(resolve: ReturnType<typeof createResourceResolve
] as const) {
for (const paint of paints ?? []) normalize(paint.colorVar?.value?.alias, field, path)
}
+ for (const effect of node.effects ?? []) {
+ for (const alias of effectVariableAliases(effect)) normalize(alias, 'effects', path)
+ }
const modeMap = node.variableModeBySetMap as
| {
entries?: Array<{ variableSetID?: NodeChange['variableSetID']; variableModeID?: GUID }>
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index 2656fde97..9eac15737 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -24,6 +24,7 @@ import { nodeChangeToProps } from '../node-change'
import { generatedFrameCodec } from '../node-change/generated/codecs'
import { readNodeChangePluginData } from '../node-change/plugin-data'
import { figArchiveRecordInfo, type FigArchiveRecordInfo } from '../record-patch'
+import { applyDocumentEffectBindings } from './bindings/effects'
import { applyDocumentLayoutBindings } from './bindings/layout'
import { applyDocumentPaintBindings } from './bindings/paint'
import type { BindingReferenceDiagnostic } from './bindings/references'
@@ -547,6 +548,7 @@ function materializeReaderInto(
resolveVariantPropertyValues(graph, materialized)
applyDocumentLayoutBindings(graph, savedSizeNodes, materialized, layoutScales)
applyDocumentPaintBindings(graph, materialized)
+ applyDocumentEffectBindings(graph, materialized)
applyDocumentValueBindings(graph, materialized)
})
return state
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index b93913cfd..14946732e 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -1,6 +1,6 @@
import { isEqual } from 'es-toolkit/predicate'
-import type { Paint } from '@open-pencil/kiwi/fig/codec'
+import type { Effect as KiwiEffect, Paint } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
import {
@@ -8,9 +8,11 @@ import {
setInstanceOverride
} from '@open-pencil/scene-graph/instances/overrides'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
+import { EFFECT_BINDING_PROPERTIES, effectBindingField } from '@open-pencil/scene-graph/variables'
import { nodeChangeToProps } from '../node-change'
import { numericVariableBindingScales } from '../node-change/variable/bindings'
+import { EFFECT_VARIABLE_FIELDS } from '../node-change/variable/effects'
import {
recordVariableBindingClaims,
occurrenceAssignmentScales,
@@ -289,6 +291,27 @@ function recordPaintBindingClaims(
if (declared) setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')
}
+/** A claimed effect carries its properties' aliases, so its bindings are part of the claim too. */
+function recordEffectBindingClaims(owner: SceneNode, target: SceneNode, effects: unknown): void {
+ if (!Array.isArray(effects)) return
+ let declared = false
+ for (const [index, effect] of (effects as KiwiEffect[]).entries()) {
+ for (const property of EFFECT_BINDING_PROPERTIES) {
+ if (!effect[EFFECT_VARIABLE_FIELDS[property]]?.value?.alias) continue
+ const path = effectBindingField(index, property)
+ setInstanceOverride(
+ owner.instanceOverrides,
+ owner.id,
+ target.id,
+ bindingOverrideField(path),
+ target.boundVariables[path] ?? null
+ )
+ declared = true
+ }
+ }
+ if (declared) setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')
+}
+
function recordPropertyClaims(nodes: ReadonlyMap<InstanceOccurrence, SceneNode>): void {
for (const [ownerOccurrence, owner] of nodes) {
if (owner.type !== 'INSTANCE') continue
@@ -312,6 +335,7 @@ function recordPropertyClaims(nodes: ReadonlyMap<InstanceOccurrence, SceneNode>)
}
if (field.kind === 'paint')
recordPaintBindingClaims(owner, target, field.scene[0], claim.properties[raw])
+ if (raw === 'effects') recordEffectBindingClaims(owner, target, claim.properties[raw])
}
recordVariableBindingClaims(owner, target, claim.properties)
}
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
index 227627e8d..dcb4b0477 100644
--- a/packages/fig/src/node-change/export/context.ts
+++ b/packages/fig/src/node-change/export/context.ts
@@ -1,6 +1,11 @@
import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'
-import type { NodeChange, Paint, StyleReference } from '@open-pencil/kiwi/fig/codec'
+import type {
+ Effect as KiwiEffect,
+ NodeChange,
+ Paint,
+ StyleReference
+} from '@open-pencil/kiwi/fig/codec'
import { isUnsetGuid, stringToGuid, UNSET_GUID } from '@open-pencil/kiwi/fig/guid'
import type {
ComponentPropertyDefinition,
@@ -9,8 +14,10 @@ import type {
SceneNode
} from '@open-pencil/scene-graph'
import type { Color, GUID, Matrix } from '@open-pencil/scene-graph/primitives'
+import { EFFECT_BINDING_PROPERTIES, effectBindingField } from '@open-pencil/scene-graph/variables'
import { variableAlias } from '../variable/bindings'
+import { EFFECT_VARIABLE_FIELDS, kiwiEffectWithBindings } from '../variable/effects'
export type KiwiNodeChange = NodeChange & Record<string, unknown>
@@ -88,8 +95,6 @@ export interface SceneNodeToKiwiContext {
glyphBlobMap?: Map<string, number>
varIdToGuid?: Map<string, GUID>
modeIdToGuid?: Map<string, GUID>
- /** Variable GUIDs used only where raw effect aliases cannot retain asset refs. */
- assetRefToVarGuid?: Map<string, GUID>
/** GUIDs minted for component property IDs (e.g. "prop:abc123") that aren't
* already Figma-GUID-shaped, keyed by the original ID so refs/assignments/
* variantPropSpecs pointing at the same property reuse the same GUID. */
@@ -290,6 +295,55 @@ export function createStrokePaints(context: SceneNodeToKiwiContext, node: SceneN
)
}
+/**
+ * `effects` as a record writes them for `node`. Each bound property names its variable as a
+ * paint's colour does and carries the value it resolves to; a property the node no longer binds
+ * loses its alias. With `keepUnresolved`, an imported alias to a library variable the document
+ * never resolved stays as it came, since nothing stands in for it.
+ */
+export function bindKiwiEffects(
+ context: SceneNodeToKiwiContext,
+ node: SceneNode,
+ effects: readonly KiwiEffect[],
+ keepUnresolved = false
+): KiwiEffect[] {
+ const alias = (variableId: string) =>
+ variableAlias(context.graph, variableId, context.varIdToGuid)
+ return effects.map((effect, index) => {
+ const bound = kiwiEffectWithBindings(effect, index, node.boundVariables, alias)
+ const current = node.effects.at(index)
+ for (const property of EFFECT_BINDING_PROPERTIES) {
+ const key = EFFECT_VARIABLE_FIELDS[property]
+ const kept = effect[key]?.value?.alias
+ if (keepUnresolved && !bound[key] && kept?.assetRef && !kept.guid) bound[key] = effect[key]
+ if (!current || !node.boundVariables[effectBindingField(index, property)]) continue
+ if (property === 'color') bound.color = context.safeColor(current.color)
+ else if (property === 'radius') bound.radius = current.radius
+ else if (property === 'spread') bound.spread = current.spread
+ else bound.offset = { ...current.offset }
+ }
+ return bound
+ })
+}
+
+/** A node's effects as its record writes them, `.fig` naming a layer blur a foreground blur. */
+export function createEffects(context: SceneNodeToKiwiContext, node: SceneNode): KiwiEffect[] {
+ return bindKiwiEffects(
+ context,
+ node,
+ node.effects.map((effect) => ({
+ type: effect.type === 'LAYER_BLUR' ? 'FOREGROUND_BLUR' : effect.type,
+ color: context.safeColor(effect.color),
+ offset: effect.offset,
+ radius: effect.radius,
+ spread: effect.spread,
+ visible: effect.visible,
+ blendMode: effect.blendMode ?? 'NORMAL',
+ showShadowBehindNode: effect.showShadowBehindNode
+ }))
+ )
+}
+
/** Instances address descendants by override key when one exists, else by node GUID. */
export function instanceGuidResolver(context: SceneNodeToKiwiContext, counter: { value: number }) {
return (id: string): GUID | undefined => {
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 492501fa7..97ad78c5f 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -3,7 +3,6 @@ import { effectiveFigmaRawNodeFields, effectiveFigmaSourcePayload } from '#fig/s
import { compact } from 'es-toolkit/array'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
-import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import type {
ComponentPropertyDefinition,
ComponentPropertyReferenceField,
@@ -42,6 +41,8 @@ import {
} from './assignments/values'
import {
applyColorVariableBinding,
+ bindKiwiEffects,
+ createEffects,
createFillPaints,
createStrokePaints,
getOrCreateNodeGuid,
@@ -107,21 +108,6 @@ function toKiwiBooleanOperation(operation: SceneNode['booleanOperation']): KiwiB
return operation === 'EXCLUDE' ? 'XOR' : (operation ?? 'UNION')
}
-/** Resolve effect variable asset refs when the Kiwi effect schema requires GUID aliases. */
-export function buildAssetRefToVarGuidMap(
- graph: SceneGraph,
- varIdToGuid: Map<string, GUID>
-): Map<string, GUID> {
- const map = new Map<string, GUID>()
- for (const [varId, variable] of graph.variables) {
- if (!variable.key) continue
- const guid = varIdToGuid.get(varId) ?? stringToGuid(varId)
- map.set(variable.key, guid)
- if (variable.version) map.set(`${variable.key}@${variable.version}`, guid)
- }
- return map
-}
-
function componentPropertyTypeForKiwi(type: string) {
if (type === 'BOOLEAN') return 'BOOL'
return type
@@ -175,17 +161,6 @@ interface FigmaPayloadVariableMapEntry {
variableData?: { dataType?: string; value?: { propRefValue?: unknown } }
}
-interface ColorVarCarrier {
- colorVar?: {
- value?: {
- alias?: {
- guid?: GUID
- assetRef?: { key: string; version?: string }
- }
- }
- }
-}
-
function isFigmaPayloadVariableMap(value: unknown): value is FigmaPayloadVariableMap {
return !!value && typeof value === 'object' && !Array.isArray(value) && 'entries' in value
}
@@ -409,13 +384,9 @@ function applyRawFigmaNodeFields(
})
continue
}
- if (
- key === 'effects' &&
- node.source.id &&
- context.assetRefToVarGuid &&
- context.assetRefToVarGuid.size > 0
- ) {
- nc[key] = convertColorVarAssetRefs(materialized[key], context.assetRefToVarGuid)
+ // Imported effects keep what OpenPencil does not model, and take the node's bindings.
+ if (key === 'effects' && node.source.id && materialized.effects) {
+ nc.effects = bindKiwiEffects(context, node, materialized.effects, true)
continue
}
if (key === 'derivedTextData' && node.source.id) {
@@ -432,28 +403,6 @@ function applyRawFigmaNodeFields(
}
}
-/** Convert asset refs only for payloads whose Kiwi schema rejects asset-ref aliases. */
-function convertColorVarAssetRefs<T>(values: T, assetRefToVarGuid: Map<string, GUID>): T {
- if (!Array.isArray(values)) return values
- const converted = values.map((value: ColorVarCarrier) => {
- const colorVar = value.colorVar
- const alias = colorVar?.value?.alias
- if (!colorVar || !alias || alias.guid || !alias.assetRef?.key) return value
- const assetRef = alias.assetRef
- const lookupKey = assetRef.version ? `${assetRef.key}@${assetRef.version}` : assetRef.key
- const guid = assetRefToVarGuid.get(lookupKey) ?? assetRefToVarGuid.get(assetRef.key)
- if (!guid) return value
- return {
- ...value,
- colorVar: {
- ...colorVar,
- value: { ...colorVar.value, alias: { guid } }
- }
- }
- })
- return converted.some((value, index) => value !== values[index]) ? (converted as T) : values
-}
-
function applyInstancePayload(
context: SceneNodeToKiwiContext,
node: SceneNode,
@@ -877,16 +826,7 @@ function applyNodeVisualProps(
if (node.type === 'STAR') nc.starInnerScale = node.starInnerRadius
if (node.effects.length > 0 && !hasRawUnsupportedEffects(node)) {
- nc.effects = node.effects.map((effect) => ({
- type: effect.type === 'LAYER_BLUR' ? 'FOREGROUND_BLUR' : effect.type,
- color: context.safeColor(effect.color),
- offset: effect.offset,
- radius: effect.radius,
- spread: effect.spread,
- visible: effect.visible,
- blendMode: effect.blendMode ?? 'NORMAL',
- showShadowBehindNode: effect.showShadowBehindNode
- }))
+ nc.effects = createEffects(context, node)
}
if (node.type === 'TEXT') serializeText(context, node, nc)
diff --git a/packages/fig/src/node-change/export/resolved-bindings.ts b/packages/fig/src/node-change/export/resolved-bindings.ts
index a6b5e2ff6..46ccede07 100644
--- a/packages/fig/src/node-change/export/resolved-bindings.ts
+++ b/packages/fig/src/node-change/export/resolved-bindings.ts
@@ -1,5 +1,6 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import {
+ resolvedEffectBindings,
resolvedNumericBindings,
resolvedPaintBindings,
resolvedRunBindings,
@@ -18,7 +19,8 @@ export function nodeWithResolvedBindings(graph: SceneGraph, node: SceneNode): Sc
...resolvedNumericBindings(graph, node, 'default'),
...resolvedPaintBindings(graph, node, 'default'),
...resolvedValueBindings(graph, node, 'default'),
- ...resolvedRunBindings(graph, node, 'default')
+ ...resolvedRunBindings(graph, node, 'default'),
+ ...resolvedEffectBindings(graph, node, 'default')
}
return Object.keys(changes).length > 0 ? { ...node, ...changes } : node
}
diff --git a/packages/fig/src/node-change/paint.ts b/packages/fig/src/node-change/paint.ts
index ad3a0aaa2..163b340bb 100644
--- a/packages/fig/src/node-change/paint.ts
+++ b/packages/fig/src/node-change/paint.ts
@@ -1,4 +1,4 @@
-import type { Paint, Effect as KiwiEffect } from '@open-pencil/kiwi/fig/codec'
+import type { Effect as KiwiEffect, Paint, VariableAliasValue } from '@open-pencil/kiwi/fig/codec'
import { guidToString, stringToGuid } from '@open-pencil/kiwi/fig/guid'
import type {
Fill,
@@ -70,12 +70,10 @@ function convertGradientTransform(t?: Matrix): GradientTransform | undefined {
return { m00: t.m00, m01: t.m01, m02: t.m02, m10: t.m10, m11: t.m11, m12: t.m12 }
}
-type VariableAliasRef = NonNullable<NonNullable<NonNullable<Paint['colorVar']>['value']>['alias']>
-
-let variableColorResolver: ((alias: VariableAliasRef) => Color | null) | null = null
+let variableColorResolver: ((alias: VariableAliasValue) => Color | null) | null = null
export function setVariableColorResolver(
- resolver: ((alias: VariableAliasRef) => Color | null) | null
+ resolver: ((alias: VariableAliasValue) => Color | null) | null
): void {
variableColorResolver = resolver
}
diff --git a/packages/fig/src/node-change/plugin-data.ts b/packages/fig/src/node-change/plugin-data.ts
index 2f776115a..4434c029a 100644
--- a/packages/fig/src/node-change/plugin-data.ts
+++ b/packages/fig/src/node-change/plugin-data.ts
@@ -19,7 +19,7 @@ import {
type PluginDataField
} from '@open-pencil/scene-graph/plugin-data'
import type { Rect } from '@open-pencil/scene-graph/primitives'
-import { paintBindingTarget } from '@open-pencil/scene-graph/variables'
+import { effectBindingTarget, paintBindingTarget } from '@open-pencil/scene-graph/variables'
import { readEffectiveFigmaRawField } from '../source-metadata'
import {
@@ -28,6 +28,7 @@ import {
VARIABLE_BINDING_FIELDS_INVERSE,
referencesVariable
} from './variable/bindings'
+import { effectBindingsFromKiwi } from './variable/effects'
const { boundVariables, exportSettings, librarySource, textPathBox } = OPEN_PENCIL_PLUGIN_DATA
@@ -93,9 +94,10 @@ export function extractTextPathBox(nc: NodeChange): Rect | null {
export function extractBoundVariables(nc: NodeChange): Record<string, string> {
let bindings = readNodeChangePluginData(nc, boundVariables) ?? {}
- // Each paint carries its colour's alias. An instance's copy pairs its component's plugin data
- // with paints an override set, so the plugin data can name a binding those paints dropped.
+ // Each paint and effect carries its own aliases. An instance's copy pairs its component's plugin
+ // data with paints or effects an override set, so the plugin data can name a binding they dropped.
const decidedByPaints = (field: string) => {
+ if (effectBindingTarget(field)) return nc.effects !== undefined
const list = paintBindingTarget(field)?.list
return list === 'fills'
? nc.fillPaints !== undefined
@@ -120,6 +122,7 @@ export function extractBoundVariables(nc: NodeChange): Record<string, string> {
const variableGuid = paint.colorVar?.value?.alias?.guid
if (variableGuid) bindings[`strokes/${i}/color`] = guidToString(variableGuid)
})
+ if (nc.effects) Object.assign(bindings, effectBindingsFromKiwi(nc.effects))
return bindings
}
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 53f06ee2b..688acf33e 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -17,7 +17,6 @@ import { computeExportTransform, mapToFigmaType } from './basics'
import { buildNodeDerivedTextData } from './derived-text/build'
import { fillsOwnSizingAxis } from './export/fill-sizing'
import {
- buildAssetRefToVarGuidMap,
buildComponentPropIndex,
sceneNodeToKiwiWithContext,
type KiwiNodeChange
@@ -497,9 +496,6 @@ export function sceneNodeToKiwi(
orderKeys,
writeChildren
} = options
- // Raw paints retain library asset refs; effects use this map because their
- // Kiwi schema accepts only GUID-backed aliases.
- const assetRefToVarGuid = varIdToGuid ? buildAssetRefToVarGuidMap(graph, varIdToGuid) : undefined
return sceneNodeToKiwiWithContext(node, parentGuid, childIndex, localIdCounter, {
graph,
blobs,
@@ -510,7 +506,6 @@ export function sceneNodeToKiwi(
glyphBlobMap,
varIdToGuid,
modeIdToGuid,
- assetRefToVarGuid,
componentPropertyDefinitionsById,
propertyIdToGuid,
slotContentRecords,
diff --git a/packages/fig/src/node-change/variable/effects.ts b/packages/fig/src/node-change/variable/effects.ts
new file mode 100644
index 000000000..f714a5b57
--- /dev/null
+++ b/packages/fig/src/node-change/variable/effects.ts
@@ -0,0 +1,66 @@
+import { omit } from 'es-toolkit/object'
+
+import type { Effect as KiwiEffect, VariableAliasValue } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import {
+ EFFECT_BINDING_PROPERTIES,
+ effectBindableProperties,
+ effectBindingField,
+ effectBindingVariableType,
+ type EffectBindingProperty
+} from '@open-pencil/scene-graph/variables'
+
+/** The field of a `.fig` effect that holds each property's variable alias. */
+export const EFFECT_VARIABLE_FIELDS = {
+ color: 'colorVar',
+ radius: 'radiusVar',
+ spread: 'spreadVar',
+ offsetX: 'xVar',
+ offsetY: 'yVar'
+} as const satisfies Record<EffectBindingProperty, keyof KiwiEffect>
+
+/** The aliases a `.fig` effect binds its properties to, library references included. */
+export function effectVariableAliases(effect: KiwiEffect): VariableAliasValue[] {
+ return EFFECT_BINDING_PROPERTIES.flatMap((property) => {
+ const alias = effect[EFFECT_VARIABLE_FIELDS[property]]?.value?.alias
+ return alias ? [alias] : []
+ })
+}
+
+/**
+ * The node binding fields the effects of a record bind, such as `effects/0/radius`, skipping an
+ * alias on a property the effect does not have, such as a blur's colour.
+ */
+export function effectBindingsFromKiwi(effects: readonly KiwiEffect[]): Record<string, string> {
+ const bindings: Record<string, string> = {}
+ effects.forEach((effect, index) => {
+ for (const property of effectBindableProperties(effect.type)) {
+ const guid = effect[EFFECT_VARIABLE_FIELDS[property]]?.value?.alias?.guid
+ if (guid) bindings[effectBindingField(index, property)] = guidToString(guid)
+ }
+ })
+ return bindings
+}
+
+/**
+ * `effect` with the aliases the node's bindings give the effect at `index`, and none for a
+ * property the node does not bind, so an imported alias the document dropped is not written back.
+ */
+export function kiwiEffectWithBindings(
+ effect: KiwiEffect,
+ index: number,
+ boundVariables: Readonly<Record<string, string>>,
+ alias: (variableId: string) => VariableAliasValue
+): KiwiEffect {
+ const next: KiwiEffect = omit(effect, Object.values(EFFECT_VARIABLE_FIELDS))
+ for (const property of EFFECT_BINDING_PROPERTIES) {
+ const variableId = boundVariables[effectBindingField(index, property)]
+ if (!variableId) continue
+ next[EFFECT_VARIABLE_FIELDS[property]] = {
+ dataType: 'ALIAS',
+ resolvedDataType: effectBindingVariableType(property),
+ value: { alias: alias(variableId) }
+ }
+ }
+ return next
+}
diff --git a/packages/fig/tests/node-change/plugin-data.test.ts b/packages/fig/tests/node-change/plugin-data.test.ts
index 85b04a491..7dce13616 100644
--- a/packages/fig/tests/node-change/plugin-data.test.ts
+++ b/packages/fig/tests/node-change/plugin-data.test.ts
@@ -55,6 +55,26 @@ describe('OpenPencil plugin data readers', () => {
}
})
+ test('effect aliases bind only the properties each effect has', () => {
+ const alias = (localID: number, resolvedDataType: 'COLOR' | 'FLOAT') => ({
+ dataType: 'ALIAS' as const,
+ resolvedDataType,
+ value: { alias: { guid: { sessionID: 1, localID } } }
+ })
+ expect(
+ extractBoundVariables({
+ effects: [
+ { type: 'DROP_SHADOW', colorVar: alias(2, 'COLOR'), yVar: alias(3, 'FLOAT') },
+ { type: 'FOREGROUND_BLUR', colorVar: alias(2, 'COLOR'), radiusVar: alias(3, 'FLOAT') }
+ ]
+ })
+ ).toEqual({
+ 'effects/0/color': '1:2',
+ 'effects/0/offsetY': '1:3',
+ 'effects/1/radius': '1:3'
+ })
+ })
+
test('export settings clamp scales and fall back to native settings when any entry is invalid', () => {
const native: NodeChange = {
exportSettings: [{ imageType: 'SVG', constraint: { type: 'CONTENT_SCALE', value: 1 } }]
diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.ts
index 95372e692..edfd819f2 100644
--- a/packages/kiwi/src/fig/codec.ts
+++ b/packages/kiwi/src/fig/codec.ts
@@ -146,16 +146,7 @@ export interface Paint {
density?: number
noiseSize?: Vector
customEffectId?: { guid?: GUID }
- colorVar?: {
- value?: {
- alias?: {
- guid?: GUID
- assetRef?: { key: string; version?: string }
- }
- }
- dataType?: string
- resolvedDataType?: string
- }
+ colorVar?: VariableDataEntry
}
export interface Effect {
@@ -167,6 +158,17 @@ export interface Effect {
spread?: number
blendMode?: string
showShadowBehindNode?: boolean
+ colorVar?: VariableDataEntry
+ radiusVar?: VariableDataEntry
+ spreadVar?: VariableDataEntry
+ xVar?: VariableDataEntry
+ yVar?: VariableDataEntry
+}
+
+/** A reference to a variable: by GUID in the file, or by key in a library. */
+export interface VariableAliasValue {
+ guid?: GUID
+ assetRef?: { key: string; version?: string }
}
export interface VariableAnyValue {
@@ -174,7 +176,7 @@ export interface VariableAnyValue {
textValue?: string
floatValue?: number
colorValue?: Color
- alias?: { guid?: GUID; assetRef?: { key: string; version?: string } }
+ alias?: VariableAliasValue
symbolIdValue?: { guid?: GUID }
// fig.kiwi PropRefValue: the component property a parameter entry points at.
propRefValue?: { defId?: GUID }
diff --git a/packages/scene-graph/src/bindings.ts b/packages/scene-graph/src/bindings.ts
index 2780dca8f..5157def39 100644
--- a/packages/scene-graph/src/bindings.ts
+++ b/packages/scene-graph/src/bindings.ts
@@ -1,10 +1,18 @@
import { omit } from 'es-toolkit/object'
import type { SceneNode } from './types'
+import { effectBindableProperties, effectBindingTarget } from './variables/fields'
+
+/** Whether an effect binding names a property its effect still has: a blur binds only radius. */
+function bindsEffectProperty(node: SceneNode, key: string): boolean {
+ const target = effectBindingTarget(key)
+ const effect = target && node.effects.at(target.index)
+ return !effect || effectBindableProperties(effect.type).includes(target.property)
+}
export function removeStaleBindings(
node: SceneNode,
- field: 'fills' | 'strokes',
+ field: 'fills' | 'strokes' | 'effects',
changes: Partial<SceneNode>
): void {
const length = node[field].length
@@ -12,7 +20,8 @@ export function removeStaleBindings(
if (key === field) return true
if (!key.startsWith(`${field}/`)) return false
const index = Number.parseInt(key.split('/')[1] ?? '', 10)
- return Number.isNaN(index) || index < 0 || index >= length
+ if (Number.isNaN(index) || index < 0 || index >= length) return true
+ return field === 'effects' && !bindsEffectProperty(node, key)
})
if (stale.length === 0) return
node.boundVariables = omit(node.boundVariables, stale)
diff --git a/packages/scene-graph/src/geometry.ts b/packages/scene-graph/src/geometry.ts
index cc7537bcf..a993aa25a 100644
--- a/packages/scene-graph/src/geometry.ts
+++ b/packages/scene-graph/src/geometry.ts
@@ -218,6 +218,14 @@ function miterRatio(network: VectorNetwork, join: StrokeJoin | undefined, limit
return ratio
}
+/**
+ * The blur radius Figma draws: a negative one, which only a bound variable can give, draws as no
+ * blur, though the layer keeps the value.
+ */
+export function drawnBlurRadius(radius: number): number {
+ return Math.max(0, radius)
+}
+
export function effectOverflow(effects?: Effect[]) {
let left = 0
let right = 0
@@ -233,7 +241,7 @@ export function effectOverflow(effects?: Effect[]) {
) {
continue
}
- const blurSpread = effect.radius + effect.spread
+ const blurSpread = drawnBlurRadius(effect.radius) + effect.spread
left = Math.max(left, blurSpread + Math.max(0, -effect.offset.x))
right = Math.max(right, blurSpread + Math.max(0, effect.offset.x))
top = Math.max(top, blurSpread + Math.max(0, -effect.offset.y))
diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.ts
index ccef62ebc..33c072f87 100644
--- a/packages/scene-graph/src/graph.ts
+++ b/packages/scene-graph/src/graph.ts
@@ -597,6 +597,7 @@ export class SceneGraph {
Object.assign(node, changes)
if (changes.fills) removeStaleBindings(node, 'fills', changes)
if (changes.strokes) removeStaleBindings(node, 'strokes', changes)
+ if (changes.effects) removeStaleBindings(node, 'effects', changes)
for (const key of absent) Reflect.deleteProperty(node, key)
this.publishNodeUpdate(id, changes)
}
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index 5186b8d30..6c32fd1c7 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -7,6 +7,7 @@ import type { SceneGraph } from '../graph'
import { scaleNodeChanges } from '../scaling/node'
import { ownsSlotContent, slotPropertyId } from '../slots/frames'
import type { SceneNode } from '../types'
+import { effectBindingTarget } from '../variables/fields'
import { scaleVariableBindingUnits } from '../variables/units'
import { applyEnclosingAssignments, assignedFieldValues, propertyDrivenFields } from './assignments'
import { keepOwnContentSize, remeasureChangedText, type SyncedPlacement } from './content-size'
@@ -76,7 +77,12 @@ export function bindingProtection(scopes: ReadonlySet<string>[]): (field: string
if (field !== 'boundVariables' || !perField) fields.add(field)
}
}
- return (field) => fields.has(field)
+ return (field) => {
+ if (fields.has(field)) return true
+ // Effects an instance set itself own their bindings too, bound or not, as its fills do.
+ const binding = overriddenBindingField(field)
+ return binding !== null && fields.has('effects') && effectBindingTarget(binding) !== null
+ }
}
export function syncBindingFields(
diff --git a/packages/scene-graph/src/variables/bindings.ts b/packages/scene-graph/src/variables/bindings.ts
index c443d9b93..811ee1cce 100644
--- a/packages/scene-graph/src/variables/bindings.ts
+++ b/packages/scene-graph/src/variables/bindings.ts
@@ -1,4 +1,4 @@
-import { isEqual } from 'es-toolkit/predicate'
+import { isEmptyObject, isEqual } from 'es-toolkit/predicate'
import type { VariableModeFallback } from '.'
import { copyFills, copyStrokes } from '../copy'
@@ -6,13 +6,26 @@ import type { SceneGraph } from '../graph'
import { hasInstanceOverride } from '../instances'
import type { Color } from '../primitives'
import { pixelLength } from '../text/lengths'
-import type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'
-import { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'
+import type { Effect, Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'
+import {
+ effectBindableProperties,
+ effectBindingTarget,
+ NUMERIC_FIELDS,
+ isNumericVariableBindingField,
+ paintBindingTarget,
+ type EffectBindingProperty
+} from './fields'
import { variableText, variableTruthy } from './text'
import { variableValueReferences } from './value'
export {
+ EFFECT_BINDING_PROPERTIES,
+ effectBindableProperties,
+ effectBindingField,
+ effectBindingTarget,
+ effectBindingVariableType,
isNumericVariableBindingField,
paintBindingTarget,
+ type EffectBindingProperty,
TEXT_CONTENT_VARIABLE_TYPES,
VISIBILITY_VARIABLE_TYPES,
type PaintBindingList
@@ -181,6 +194,56 @@ export function resolvedPaintBindings(
return changes
}
+/** `effect` with one bound property set to its variable's value; a colour keeps its alpha. */
+function withBoundEffectValue(
+ effect: Effect,
+ property: EffectBindingProperty,
+ value: number | Color
+): Effect {
+ if (typeof value !== 'number') return property === 'color' ? { ...effect, color: value } : effect
+ if (property === 'offsetX') return { ...effect, offset: { ...effect.offset, x: value } }
+ if (property === 'offsetY') return { ...effect, offset: { ...effect.offset, y: value } }
+ if (property === 'radius' || property === 'spread') return { ...effect, [property]: value }
+ return effect
+}
+
+/** A bound effect length in an occurrence's coordinates, which are 1:1 outside instances. */
+function scaledLength(length: number | undefined, node: SceneNode): number | undefined {
+ return length === undefined ? undefined : length * node.componentScale
+}
+
+/**
+ * The effects a node's effect bindings resolve to in its mode, when one differs from what the node
+ * holds. Lengths stay as the variables give them, negative ones included, as Figma keeps them;
+ * drawing treats a negative blur as none. In an instance they take its scale against its
+ * component, whenever they were bound, as Figma scales them; a layer scaled outside an instance
+ * goes back to the variable's own value.
+ */
+export function resolvedEffectBindings(
+ graph: SceneGraph,
+ node: SceneNode,
+ fallback: VariableModeFallback = 'active'
+): Pick<Partial<SceneNode>, 'effects'> {
+ // Most nodes bind nothing, so no copy is made until a value actually changes.
+ let effects: Effect[] | undefined
+ for (const [field, variableId] of Object.entries(node.boundVariables)) {
+ const target = effectBindingTarget(field)
+ if (!target) continue
+ const effect = (effects ?? node.effects).at(target.index)
+ if (!effect || !effectBindableProperties(effect.type).includes(target.property)) continue
+ const value =
+ target.property === 'color'
+ ? graph.resolveColorVariableForNode(node.id, variableId, fallback)
+ : scaledLength(graph.resolveNumberVariableForNode(node.id, variableId, fallback), node)
+ if (value == null || (typeof value === 'number' && !Number.isFinite(value))) continue
+ const next = withBoundEffectValue(effect, target.property, value)
+ if (isEqual(next, effect)) continue
+ effects ??= [...node.effects]
+ effects[target.index] = next
+ }
+ return effects ? { effects } : {}
+}
+
/**
* The layers a reconcile looks at: those bound to these variables, directly or through a variable
* aliasing them, or the layers in these subtrees. Without a scope, every layer.
@@ -257,21 +320,24 @@ function scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterab
}
/**
- * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
- * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved
- * values differ from their bindings elsewhere in the document are left as saved.
+ * Resolve live numeric, text, visibility, and effect bindings, numbers in scene units, without
+ * authoring instance overrides. A scope limits it to the layers a change can reach, so layers whose
+ * saved values differ from their bindings elsewhere in the document are left as saved. Returns the
+ * layers whose change needs a layout pass; effects are not a layout input, so an effect-only change
+ * is written but not returned.
*/
export function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {
- const changed: string[] = []
+ const relaid: string[] = []
for (const node of scopedNodes(graph, scope)) {
- const updates = {
+ const layoutUpdates = {
...resolvedNumericBindings(graph, node),
...resolvedValueBindings(graph, node),
...resolvedRunBindings(graph, node)
}
- if (Object.keys(updates).length === 0) continue
+ const updates = { ...layoutUpdates, ...resolvedEffectBindings(graph, node) }
+ if (isEmptyObject(updates)) continue
graph.updateNode(node.id, updates)
- changed.push(node.id)
+ if (!isEmptyObject(layoutUpdates)) relaid.push(node.id)
}
- return changed
+ return relaid
}
diff --git a/packages/scene-graph/src/variables/fields.ts b/packages/scene-graph/src/variables/fields.ts
index 6831fd284..01ead8cd9 100644
--- a/packages/scene-graph/src/variables/fields.ts
+++ b/packages/scene-graph/src/variables/fields.ts
@@ -1,4 +1,4 @@
-import type { VariableType } from '../types'
+import type { Effect, VariableType } from '../types'
export const NUMERIC_FIELDS = new Set([
'opacity',
@@ -79,3 +79,48 @@ export function paintBindingTarget(
if (!match) return null
return { list: match[1] === 'fills' ? 'fills' : 'strokes', index: Number(match[2]) }
}
+
+/** The effect fields that bind to variables, in the order Figma's messages list them. */
+export const EFFECT_BINDING_PROPERTIES = [
+ 'color',
+ 'radius',
+ 'spread',
+ 'offsetX',
+ 'offsetY'
+] as const
+
+export type EffectBindingProperty = (typeof EFFECT_BINDING_PROPERTIES)[number]
+
+const EFFECT_BINDING_FIELD = /^effects\/(\d+)\/(color|radius|spread|offsetX|offsetY)$/
+
+const BLUR_BINDING_PROPERTIES = ['radius'] as const satisfies readonly EffectBindingProperty[]
+
+/** The node binding field for one property of the effect at `index`, such as `effects/0/radius`. */
+export function effectBindingField(index: number, property: EffectBindingProperty): string {
+ return `effects/${index}/${property}`
+}
+
+/**
+ * The effect and property a binding field names, such as the second effect's blur for
+ * `effects/1/radius`, or null for a field that binds anything else.
+ */
+export function effectBindingTarget(
+ field: string
+): { index: number; property: EffectBindingProperty } | null {
+ if (!field.startsWith('effects/')) return null
+ const match = EFFECT_BINDING_FIELD.exec(field)
+ if (!match) return null
+ return { index: Number(match[1]), property: match[2] as EffectBindingProperty }
+}
+
+/** The properties of an effect that bind: every shadow property, and only a blur's radius. */
+export function effectBindableProperties(type: Effect['type']): readonly EffectBindingProperty[] {
+ return type === 'DROP_SHADOW' || type === 'INNER_SHADOW'
+ ? EFFECT_BINDING_PROPERTIES
+ : BLUR_BINDING_PROPERTIES
+}
+
+/** The variable type an effect property binds to: colour to COLOR, lengths to FLOAT. */
+export function effectBindingVariableType(property: EffectBindingProperty): 'COLOR' | 'FLOAT' {
+ return property === 'color' ? 'COLOR' : 'FLOAT'
+}
diff --git a/packages/scene-graph/src/variables/index.ts b/packages/scene-graph/src/variables/index.ts
index 4cf1a5d78..b817469cb 100644
--- a/packages/scene-graph/src/variables/index.ts
+++ b/packages/scene-graph/src/variables/index.ts
@@ -7,6 +7,7 @@ import { findInstanceAncestor } from '../instances'
import { bindingOverrideField, setInstanceOverride } from '../instances/overrides'
import { siblingOrderKeys } from '../order-keys'
import type {
+ Effect,
Variable,
VariableCollection,
VariableCollectionMode,
@@ -20,6 +21,10 @@ import {
} from './bindings'
import {
BOOLEAN_BINDING_FIELDS,
+ effectBindableProperties,
+ effectBindingTarget,
+ effectBindingVariableType,
+ type EffectBindingProperty,
paintBindingTarget,
STRING_BINDING_FIELDS,
TEXT_CONTENT_VARIABLE_TYPES,
@@ -237,6 +242,25 @@ export function getVariablesByType(graph: SceneGraph, type: VariableType): Varia
return [...graph.variables.values()].filter((v) => v.type === type)
}
+/** Checks that an effect binding names an effect the node has, a property it binds, and its type. */
+function assertEffectBinding(
+ effects: readonly Effect[],
+ target: { index: number; property: EffectBindingProperty },
+ type: VariableType,
+ field: string
+): void {
+ const effect = effects.at(target.index)
+ if (!effect) {
+ throw new Error(`Index ${target.index} out of range for effects (length ${effects.length})`)
+ }
+ if (!effectBindableProperties(effect.type).includes(target.property)) {
+ throw new Error(`A ${effect.type} effect has no bindable ${target.property} ("${field}")`)
+ }
+ if (type !== effectBindingVariableType(target.property)) {
+ throw new Error(`Cannot bind ${type} variable to effect field "${field}"`)
+ }
+}
+
export function bindVariable(
graph: SceneGraph,
nodeId: string,
@@ -272,6 +296,9 @@ export function bindVariable(
}
}
+ const effect = effectBindingTarget(field)
+ if (effect) assertEffectBinding(node.effects, effect, variable.type, field)
+
if (isNumericVariableBindingField(field) && variable.type !== 'FLOAT') {
throw new Error(`Cannot bind ${variable.type} variable to scalar field "${field}"`)
}
@@ -293,7 +320,8 @@ export function bindVariable(
isNumericVariableBindingField(field) ||
STRING_BINDING_FIELDS.has(field) ||
BOOLEAN_BINDING_FIELDS.has(field) ||
- paint !== null
+ paint !== null ||
+ effect !== null
if (!isKnownField) {
throw new Error(`Unknown binding field "${field}"`)
diff --git a/packages/scene-graph/tests/variable/binding/effects.test.ts b/packages/scene-graph/tests/variable/binding/effects.test.ts
new file mode 100644
index 000000000..cf55daa53
--- /dev/null
+++ b/packages/scene-graph/tests/variable/binding/effects.test.ts
@@ -0,0 +1,149 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type Effect } from '@open-pencil/scene-graph'
+import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
+import {
+ reconcileVariableBindings,
+ resolvedEffectBindings
+} from '@open-pencil/scene-graph/variables'
+
+const SHADOW: Effect = {
+ type: 'DROP_SHADOW',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ offset: { x: 1, y: 2 },
+ radius: 3,
+ spread: 4,
+ visible: true,
+ blendMode: 'NORMAL'
+}
+
+const BLUR: Effect = {
+ type: 'LAYER_BLUR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ offset: { x: 0, y: 0 },
+ radius: 4,
+ spread: 0,
+ visible: true
+}
+
+/** A Light and Dark elevation, as a design system binds a card's shadow. */
+function elevation() {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Theme')
+ const dark = graph.createMode(collection.id, 'Dark') ?? ''
+ const color = graph.createVariable('Shadow', 'COLOR', collection.id, {
+ r: 0,
+ g: 0,
+ b: 0.5,
+ a: 0.25
+ })
+ const blur = graph.createVariable('Blur', 'FLOAT', collection.id, 8)
+ const lift = graph.createVariable('Lift', 'FLOAT', collection.id, 4)
+ color.valuesByMode[dark] = { r: 0, g: 0, b: 0, a: 0.6 }
+ blur.valuesByMode[dark] = 24
+ lift.valuesByMode[dark] = -7
+ const card = graph.createNode('RECTANGLE', graph.getPages()[0].id, {
+ effects: [SHADOW, BLUR]
+ })
+ return { graph, collection, dark, color, blur, lift, card }
+}
+
+describe('effect bindings', () => {
+ test('resolve each property in the layer mode, colour alpha included', () => {
+ const { graph, collection, dark, color, blur, lift, card } = elevation()
+ graph.bindVariable(card.id, 'effects/0/color', color.id)
+ graph.bindVariable(card.id, 'effects/0/radius', blur.id)
+ graph.bindVariable(card.id, 'effects/0/offsetY', lift.id)
+ graph.bindVariable(card.id, 'effects/1/radius', blur.id)
+
+ reconcileVariableBindings(graph)
+ expect(graph.getNode(card.id)?.effects).toEqual([
+ { ...SHADOW, color: { r: 0, g: 0, b: 0.5, a: 0.25 }, radius: 8, offset: { x: 1, y: 4 } },
+ { ...BLUR, radius: 8 }
+ ])
+
+ graph.updateNode(card.id, { variableModes: { [collection.id]: dark } })
+ reconcileVariableBindings(graph)
+ expect(graph.getNode(card.id)?.effects).toEqual([
+ { ...SHADOW, color: { r: 0, g: 0, b: 0, a: 0.6 }, radius: 24, offset: { x: 1, y: -7 } },
+ { ...BLUR, radius: 24 }
+ ])
+ })
+
+ test('keep a negative length as the variable gives it', () => {
+ const { graph, collection, dark, lift, card } = elevation()
+ graph.bindVariable(card.id, 'effects/0/spread', lift.id)
+ graph.updateNode(card.id, { variableModes: { [collection.id]: dark } })
+
+ expect(resolvedEffectBindings(graph, card).effects?.[0].spread).toBe(-7)
+ })
+
+ test('write an effect-only change without asking for a layout pass', () => {
+ const { graph, blur, card } = elevation()
+ graph.bindVariable(card.id, 'effects/0/radius', blur.id)
+ const width = graph.createVariable('Width', 'FLOAT', blur.collectionId, 60)
+
+ expect(reconcileVariableBindings(graph)).toEqual([])
+ expect(graph.getNode(card.id)?.effects[0].radius).toBe(8)
+
+ graph.bindVariable(card.id, 'width', width.id)
+ expect(reconcileVariableBindings(graph)).toEqual([card.id])
+ })
+
+ test('change nothing when the effects already hold the values', () => {
+ const { graph, blur, card } = elevation()
+ graph.bindVariable(card.id, 'effects/0/radius', blur.id)
+ reconcileVariableBindings(graph)
+
+ expect(resolvedEffectBindings(graph, graph.getNode(card.id) ?? card)).toEqual({})
+ })
+
+ test('keep the effect style the layer uses', () => {
+ const { graph, blur, card } = elevation()
+ graph.updateNode(card.id, { effectStyleId: 'style:elevation' })
+ graph.bindVariable(card.id, 'effects/0/radius', blur.id)
+ reconcileVariableBindings(graph)
+
+ expect(graph.getNode(card.id)?.effectStyleId).toBe('style:elevation')
+ })
+
+ test('refuse a missing effect, a property a blur lacks, and the wrong variable type', () => {
+ const { graph, color, blur, card } = elevation()
+
+ expect(() => graph.bindVariable(card.id, 'effects/2/radius', blur.id)).toThrow(
+ 'Index 2 out of range for effects (length 2)'
+ )
+ expect(() => graph.bindVariable(card.id, 'effects/1/color', color.id)).toThrow(
+ 'A LAYER_BLUR effect has no bindable color ("effects/1/color")'
+ )
+ expect(() => graph.bindVariable(card.id, 'effects/0/radius', color.id)).toThrow(
+ 'Cannot bind COLOR variable to effect field "effects/0/radius"'
+ )
+ expect(() => graph.bindVariable(card.id, 'effects/0/color', blur.id)).toThrow(
+ 'Cannot bind FLOAT variable to effect field "effects/0/color"'
+ )
+ })
+})
+
+describe('effect bindings in instances', () => {
+ test('an instance that overrides its effects keeps them through a component sync', () => {
+ const { graph, blur } = elevation()
+ const page = graph.getPages()[0].id
+ const component = graph.createNode('COMPONENT', page, { width: 100, height: 100 })
+ const shape = graph.createNode('RECTANGLE', component.id, { effects: [SHADOW] })
+ graph.bindVariable(shape.id, 'effects/0/radius', blur.id)
+ const instance = graph.createInstance(component.id, page)
+ const copy = instance && graph.getNode(instance.childIds[0])
+ if (!copy) throw new Error('No instance copy')
+ // A .fig override replaces the effects without a radius alias, claiming effects alone.
+ graph.updateNode(copy.id, { effects: [{ ...SHADOW, radius: 2 }], boundVariables: {} })
+ setInstanceOverride(instance.instanceOverrides, instance.id, copy.id, 'effects', [])
+
+ graph.updateNode(shape.id, { name: 'Edited' })
+ graph.syncInstances(component.id)
+ reconcileVariableBindings(graph)
+
+ expect(graph.getNode(copy.id)?.boundVariables).toEqual({})
+ expect(graph.getNode(copy.id)?.effects[0].radius).toBe(2)
+ })
+})
diff --git a/packages/scene-graph/tests/variables/fields.test.ts b/packages/scene-graph/tests/variables/fields.test.ts
index 8ead03df6..dcb0b1a12 100644
--- a/packages/scene-graph/tests/variables/fields.test.ts
+++ b/packages/scene-graph/tests/variables/fields.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { paintBindingTarget } from '@open-pencil/scene-graph/variables'
+import { effectBindingTarget, paintBindingTarget } from '@open-pencil/scene-graph/variables'
describe('paint binding fields', () => {
test('name the fill or stroke whose colour they bind', () => {
@@ -19,3 +19,15 @@ describe('paint binding fields', () => {
expect(paintBindingTarget(field)).toBeNull()
})
})
+
+describe('effect binding fields', () => {
+ test('name the effect and the property they bind', () => {
+ expect(effectBindingTarget('effects/1/offsetY')).toEqual({ index: 1, property: 'offsetY' })
+ expect(effectBindingTarget('effects/0/color')).toEqual({ index: 0, property: 'color' })
+ })
+
+ test('are not any other binding field', () => {
+ for (const field of ['effects', 'effects/0/offset', 'effects/x/radius', 'fills/0/color'])
+ expect(effectBindingTarget(field)).toBeNull()
+ })
+})
diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.md
index 58a7e9c08..2dcf64195 100644
--- a/skills/open-pencil/SKILL.md
+++ b/skills/open-pencil/SKILL.md
@@ -26,7 +26,7 @@ Use `openpencil --help`, per-command help, and the connected MCP server’s 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`.
-Variables follow Figma's plugin API: `figma.variables.getLocalVariables()`, `createVariable(name, collection, type)`, `variable.setValueForMode(modeId, value)`, and `node.setBoundVariable(field, variable)` with Figma's field names (`characters`, `width`, `paddingLeft`) and types; paint colours bind through `figma.variables.setBoundVariableForPaint`. To bind as the layer panel does, use `openpencil.bindVariable(node, field, variable)` and `openpencil.unbindVariable(node, field)` with OpenPencil names (`text`, `visible`, `opacity`, `fills/0/color`): text content takes a text or number variable, shown as text; visibility a boolean or text one. `openpencil` also sets layout and text direction (`setLayoutDirection`, `setTextDirection`), OkHCL paint colors (`setFillOkHCL`, `setStrokeOkHCL`), writes styled text from Markdown (`setTextMarkdown(text, markdown)`, or `set_text` with `markdown: true`), exposes instance swaps (`exposeInstanceSwap`), and reports font availability (`getFontStatus()`); booleans and flattening are Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `figma.flatten`.
+Variables follow Figma's plugin API: `figma.variables.getLocalVariables()`, `createVariable(name, collection, type)`, `variable.setValueForMode(modeId, value)`, and `node.setBoundVariable(field, variable)` with Figma's field names (`characters`, `width`, `paddingLeft`) and types; paint colours bind through `figma.variables.setBoundVariableForPaint` and shadow or blur fields through `figma.variables.setBoundVariableForEffect`. To bind as the layer panel does, use `openpencil.bindVariable(node, field, variable)` and `openpencil.unbindVariable(node, field)` with OpenPencil names (`text`, `visible`, `opacity`, `fills/0/color`, `effects/0/radius`): text content takes a text or number variable, shown as text; visibility a boolean or text one. `openpencil` also sets layout and text direction (`setLayoutDirection`, `setTextDirection`), OkHCL paint colors (`setFillOkHCL`, `setStrokeOkHCL`), writes styled text from Markdown (`setTextMarkdown(text, markdown)`, or `set_text` with `markdown: true`), exposes instance swaps (`exposeInstanceSwap`), and reports font availability (`getFontStatus()`); booleans and flattening are Figma's `figma.union`, `subtract`, `intersect`, `exclude` and `figma.flatten`.
## Requirements
diff --git a/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png b/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png
index 237b26270..09b1e1329 100644
Binary files a/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png and b/tests/e2e/canvas/blur-effects-visual.spec.ts-snapshots/blur-effects-openpencil-darwin.png differ
diff --git a/tests/helpers/canvas/effects/scene.ts b/tests/helpers/canvas/effects/scene.ts
index b7af6b45d..762fb1f7d 100644
--- a/tests/helpers/canvas/effects/scene.ts
+++ b/tests/helpers/canvas/effects/scene.ts
@@ -23,8 +23,9 @@ function effect(type: Effect['type'], radius: number, y = 0): Effect {
/**
* Layer blur, drop and inner shadow, and background blur, each at a 16px radius, plus a drop
* shadow, shown behind the node, under a fill at 0% opacity, which casts nothing; a boolean's
- * background blur, inside its result alone; and sharp inner shadows over the rounded corners of
- * an opaque and a translucent fill, where no fill shows through the edge.
+ * background blur, inside its result alone; sharp inner shadows over the rounded corners of
+ * an opaque and a translucent fill, where no fill shows through the edge; and a layer blur and
+ * both shadows at a negative radius, as a variable can give one, which draws like a radius of 0.
*/
export function createBlurEffectsScene(graph: SceneGraph, pageId: string): void {
const card = { y: 100, width: 120, height: 120, cornerRadius: 20 }
@@ -131,6 +132,16 @@ export function createBlurEffectsScene(graph: SceneGraph, pageId: string): void
]
})
}
+ for (const [index, type] of (['LAYER_BLUR', 'DROP_SHADOW', 'INNER_SHADOW'] as const).entries()) {
+ graph.createNode('RECTANGLE', pageId, {
+ name: `Negative ${type.toLowerCase().replace('_', ' ')}`,
+ x: 80 + index * 180,
+ ...card,
+ y: 460,
+ fills: [solid(0.31, 0.27, 0.9)],
+ effects: [effect(type, -6, type === 'LAYER_BLUR' ? 0 : 8)]
+ })
+ }
}
function shadow(type: 'DROP_SHADOW' | 'INNER_SHADOW', showShadowBehindNode = false): Effect {