Skip to content

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

feat: export variable-bound effect fields as CSS variables and token references (#1741)

Danila Poyarkove2d36c2b2243
diff --git a/changes/1741/added.md b/changes/1741/added.md
new file mode 100644
index 000000000..27edb8293
--- /dev/null
+++ b/changes/1741/added.md
@@ -0,0 +1 @@
+- CSS, HTML and Tailwind export write a shadow or blur field bound to a variable as that variable's `var()` where the layer draws the variable's value, and design token export writes it as a reference to the variable's token, which import binds back.
diff --git a/packages/core/src/editor/design-tokens.ts b/packages/core/src/editor/design-tokens.ts
index 780217f78..e9392c0bb 100644
--- a/packages/core/src/editor/design-tokens.ts
+++ b/packages/core/src/editor/design-tokens.ts
@@ -70,7 +70,8 @@ export function createDesignTokenActions(
setTokenFields: (variableId, fields) => variables.updateVariableToken(variableId, fields),
addStyle,
updateNode: (nodeId, changes) => nodes.updateNodeWithUndo(nodeId, changes, 'Update style'),
- bindVariable: (nodeId, field, variableId) => nodes.bindVariable(nodeId, field, variableId)
+ bindVariable: (nodeId, field, variableId) => nodes.bindVariable(nodeId, field, variableId),
+ unbindVariable: (nodeId, field) => nodes.unbindVariable(nodeId, field)
}
/** Applies an import plan as one undo step; nothing is deleted. */
diff --git a/packages/core/src/io/formats/design-tokens/apply.ts b/packages/core/src/io/formats/design-tokens/apply.ts
index a5d3185e3..3b5d76f95 100644
--- a/packages/core/src/io/formats/design-tokens/apply.ts
+++ b/packages/core/src/io/formats/design-tokens/apply.ts
@@ -16,6 +16,7 @@ import type {
import { copyEffects } from '@open-pencil/scene-graph/copy'
import { findInstanceAncestor } from '@open-pencil/scene-graph/instances'
import { randomHex } from '@open-pencil/scene-graph/random'
+import { effectBindingTarget } from '@open-pencil/scene-graph/variables'
import { reconcileVariableLayouts } from '#core/layout/variables'
@@ -50,6 +51,7 @@ export interface TokenImportTarget {
addStyle(style: PlannedStyle, fields: Partial<SceneNode>): SceneNode
updateNode(nodeId: string, changes: Partial<SceneNode>): void
bindVariable(nodeId: string, field: string, variableId: string): void
+ unbindVariable(nodeId: string, field: string): void
}
export interface TokenImportResult {
@@ -207,6 +209,12 @@ function applyStyles(
const node = existing ?? target.addStyle(style, { ...style.fields, name: style.name })
const own = existing && changedFields(existing, style.fields)
if (own) target.updateNode(node.id, own)
+ // An effect field the token now writes as a literal lets its variable go.
+ if (existing && style.kind === 'EFFECT') {
+ for (const field of Object.keys(node.boundVariables))
+ if (effectBindingTarget(field) && !Object.hasOwn(style.bindings, field))
+ target.unbindVariable(node.id, field)
+ }
for (const [field, alias] of Object.entries(style.bindings)) {
const variableId = aliasId(alias, created)
if (variableId && node.boundVariables[field] !== variableId)
@@ -297,7 +305,8 @@ function graphTokenImportTarget(
return node
},
updateNode: (nodeId, changes) => graph.updateNode(nodeId, changes),
- bindVariable: (nodeId, field, variableId) => graph.bindVariable(nodeId, field, variableId)
+ bindVariable: (nodeId, field, variableId) => graph.bindVariable(nodeId, field, variableId),
+ unbindVariable: (nodeId, field) => graph.unbindVariable(nodeId, field)
}
}
diff --git a/packages/core/src/io/formats/design-tokens/plan/styles.ts b/packages/core/src/io/formats/design-tokens/plan/styles.ts
index 04c69515b..d75074b00 100644
--- a/packages/core/src/io/formats/design-tokens/plan/styles.ts
+++ b/packages/core/src/io/formats/design-tokens/plan/styles.ts
@@ -5,6 +5,7 @@ import type { Effect, SceneGraph, SceneNode, TextLength } from '@open-pencil/sce
import type { Color } from '@open-pencil/scene-graph/primitives'
import { getSharedStyles } from '@open-pencil/scene-graph/shared-styles'
import { percentLength, pixelLength, textLengthSchema } from '@open-pencil/scene-graph/text'
+import { effectBindingField, effectBindingTarget } from '@open-pencil/scene-graph/variables'
import { tryParseFigmaEffects } from '#core/figma-api/effects'
import {
@@ -14,8 +15,14 @@ import {
decodeFontWeight,
referencePath
} from '#core/io/formats/design-tokens/decode'
+import { tokenReference } from '#core/io/formats/design-tokens/paths'
import type { DesignTokenBundle, ReadToken } from '#core/io/formats/design-tokens/read'
-import { isShadow, shadowTokenValue, typographyValue } from '#core/io/formats/design-tokens/styles'
+import {
+ isShadow,
+ SHADOW_TOKEN_FIELDS,
+ shadowTokenValue,
+ typographyValue
+} from '#core/io/formats/design-tokens/styles'
import { OPENPENCIL_EXTENSION } from '#core/io/formats/design-tokens/types'
import type { AliasTarget, ImportSkip, ResolvedReference } from './'
@@ -27,8 +34,8 @@ export interface PlannedStyle {
/** The style updated, or null for one the import makes. */
existingNodeId: string | null
fields: Partial<SceneNode>
- /** Text style fields bound to variables. */
- bindings: Partial<Record<TextBindingField, AliasTarget>>
+ /** Fields bound to variables, such as `fontSize` or `effects/0/radius`. */
+ bindings: Record<string, AliasTarget>
}
type TextBindingField = 'fontFamily' | 'fontSize' | 'letterSpacing' | 'lineHeight'
@@ -52,7 +59,10 @@ const ownTextSchema = v.object({
}),
bindings: v.optional(v.record(v.string(), v.string()))
})
-const ownEffectsSchema = v.object({ effects: v.array(v.unknown()) })
+const ownEffectsSchema = v.object({
+ effects: v.optional(v.array(v.unknown())),
+ bindings: v.optional(v.record(v.string(), v.string()))
+})
/** The composite types that become styles. */
const STYLE_KINDS: Partial<Record<string, PlannedStyle['kind']>> = {
@@ -126,6 +136,16 @@ function decodedTextFields(token: ReadToken, resolve: Resolve): Partial<SceneNod
}
}
+/** A typography token as text style fields and the fields its references bind. */
+function textStyle(
+ token: ReadToken,
+ resolve: Resolve,
+ alias: Alias
+): Pick<PlannedStyle, 'fields' | 'bindings'> | null {
+ const fields = textFields(token, resolve)
+ return fields && { fields, bindings: textBindings(token, alias) }
+}
+
/** Text style fields bound to variables: OpenPencil's recorded bindings, or the token's references. */
function textBindings(token: ReadToken, alias: Alias): PlannedStyle['bindings'] {
const own = ownText(token)
@@ -141,66 +161,145 @@ function textBindings(token: ReadToken, alias: Alias): PlannedStyle['bindings']
return bindings
}
-/** One shadow of a shadow token, or the shadows a referenced shadow token holds. */
-function shadowEffects(raw: unknown, resolve: Resolve, depth = 0): Effect[] | null {
+/** Shadows read from a token, each with the token paths its fields reference. */
+type ReadShadows = { effects: Effect[]; references: Array<Record<string, string[]>> }
+
+/** The token paths one shadow's fields reference, by the effect property they set. */
+function shadowReferences(raw: Record<string, unknown>): Record<string, string[]> {
+ return Object.fromEntries(
+ Object.entries(SHADOW_TOKEN_FIELDS).flatMap(([property, key]) => {
+ const path = referencePath(raw[key])
+ return path ? [[property, path]] : []
+ })
+ )
+}
+
+/**
+ * One shadow of a shadow token, or the shadows a referenced shadow token holds; those reference a
+ * whole shadow, not a variable, so they bind nothing.
+ */
+function shadowEffects(raw: unknown, resolve: Resolve, depth = 0): ReadShadows | null {
const path = referencePath(raw)
if (path) {
const resolved = depth < 16 ? resolve(path) : undefined
- return resolved?.kind === 'token' ? shadowList(resolved.token.value, resolve, depth + 1) : null
+ const shadows =
+ resolved?.kind === 'token' ? shadowList(resolved.token.value, resolve, depth + 1) : null
+ return shadows && { effects: shadows.effects, references: shadows.effects.map(() => ({})) }
}
if (!isPlainObject(raw)) return null
const color = fieldValue<Color>(raw.color, resolve, (value) =>
isPlainObject(value) && typeof value.r === 'number' ? (value as Color) : decodeColor(value)
)
- const length = (key: string) => fieldValue(raw[key], resolve, pixels) ?? 0
- if (!color) return null
- return [
- {
- type: raw.inset === true ? 'INNER_SHADOW' : 'DROP_SHADOW',
- color,
- offset: { x: length('offsetX'), y: length('offsetY') },
- radius: length('blur'),
- spread: length('spread'),
- visible: true,
- blendMode: 'NORMAL'
- }
- ]
+ // A missing length is 0; one that names a token which does not resolve makes the shadow invalid.
+ const length = (key: string) =>
+ raw[key] === undefined ? 0 : fieldValue(raw[key], resolve, pixels)
+ const [offsetX, offsetY, radius, spread] = ['offsetX', 'offsetY', 'blur', 'spread'].map(length)
+ if (!color || offsetX === null || offsetY === null || radius === null || spread === null)
+ return null
+ const effect: Effect = {
+ type: raw.inset === true ? 'INNER_SHADOW' : 'DROP_SHADOW',
+ color,
+ offset: { x: offsetX, y: offsetY },
+ radius,
+ spread,
+ visible: true,
+ blendMode: 'NORMAL'
+ }
+ return { effects: [effect], references: [shadowReferences(raw)] }
}
-function shadowList(value: unknown, resolve: Resolve, depth = 0): Effect[] | null {
+function shadowList(value: unknown, resolve: Resolve, depth = 0): ReadShadows | null {
const entries = Array.isArray(value) ? value : [value]
- const effects: Effect[] = []
+ const list: ReadShadows = { effects: [], references: [] }
for (const entry of entries) {
const shadows = shadowEffects(entry, resolve, depth)
if (!shadows) return null
- effects.push(...shadows)
+ list.effects.push(...shadows.effects)
+ list.references.push(...shadows.references)
}
- return effects.length > 0 ? effects : null
+ return list.effects.length > 0 ? list : null
}
/**
* Shadows edited in another tool, in place of the visible shadows OpenPencil wrote. Effects
* `$value` cannot hold, such as blurs and hidden shadows, keep their places; extra shadows go last.
+ * Also gives the position each new shadow lands at, and each kept effect's new position.
*/
-function replaceShadows(exact: readonly Effect[], shadows: readonly Effect[]): Effect[] {
+function replaceShadows(
+ exact: readonly Effect[],
+ shadows: readonly Effect[]
+): { effects: Effect[]; positions: number[]; kept: Map<number, number> } {
const queue = [...shadows]
- const effects = exact.flatMap((effect) => {
- if (!isShadow(effect) || !effect.visible) return [effect]
- const next = queue.shift()
- return next ? [next] : []
- })
- return [...effects, ...queue]
+ const effects: Effect[] = []
+ const positions: number[] = []
+ const kept = new Map<number, number>()
+ for (const [index, effect] of exact.entries()) {
+ if (isShadow(effect) && effect.visible) {
+ const next = queue.shift()
+ if (!next) continue
+ positions.push(effects.length)
+ effects.push(next)
+ } else {
+ kept.set(index, effects.length)
+ effects.push(effect)
+ }
+ }
+ for (const next of queue) {
+ positions.push(effects.length)
+ effects.push(next)
+ }
+ return { effects, positions, kept }
}
-/** A shadow token as effects, preferring the exact effects OpenPencil wrote. */
-function effectFields(token: ReadToken, resolve: Resolve): Partial<SceneNode> | null {
+/** A shadow token as effect style fields and the fields its references bind. */
+function effectStyle(
+ token: ReadToken,
+ resolve: Resolve,
+ alias: Alias
+): Pick<PlannedStyle, 'fields' | 'bindings'> | null {
const own = v.safeParse(ownEffectsSchema, token.extensions[OPENPENCIL_EXTENSION])
+ const ownBindings = own.success ? (own.output.bindings ?? {}) : {}
// Extension effects that do not read fall back to the token's own shadows.
- const exact = own.success ? tryParseFigmaEffects(own.output.effects) : null
- if (exact && isEqual(token.value, shadowTokenValue(exact))) return { effects: exact }
+ const exact = own.success && own.output.effects ? tryParseFigmaEffects(own.output.effects) : null
+ if (exact && isEqual(token.value, shadowTokenValue(exact, ownBindings))) {
+ return { fields: { effects: exact }, bindings: aliasedBindings(ownBindings, alias) }
+ }
const shadows = shadowList(token.value, resolve)
if (!shadows) return null
- return { effects: exact ? replaceShadows(exact, shadows) : shadows }
+ const placed = exact
+ ? replaceShadows(exact, shadows.effects)
+ : { effects: shadows.effects, positions: shadows.effects.map((_, index) => index), kept: null }
+ const references: Record<string, string> = {}
+ // Effects `$value` cannot hold, such as a bound blur, keep the bindings OpenPencil recorded.
+ for (const [field, reference] of Object.entries(ownBindings)) {
+ const target = effectBindingTarget(field)
+ const index = target && placed.kept?.get(target.index)
+ if (target && index !== undefined && index !== null)
+ references[effectBindingField(index, target.property)] = reference
+ }
+ shadows.references.forEach((paths, shadow) => {
+ const index = placed.positions.at(shadow)
+ if (index === undefined) return
+ for (const [property, path] of Object.entries(paths)) {
+ const field = `effects/${index}/${property}`
+ if (effectBindingTarget(field)) references[field] = tokenReference(path)
+ }
+ })
+ return { fields: { effects: placed.effects }, bindings: aliasedBindings(references, alias) }
+}
+
+/** Bound fields whose references name a variable, as alias targets. */
+function aliasedBindings(
+ references: Readonly<Record<string, string>>,
+ alias: Alias
+): PlannedStyle['bindings'] {
+ const bindings: PlannedStyle['bindings'] = {}
+ for (const [field, reference] of Object.entries(references)) {
+ const path = referencePath(reference)
+ const target = path && effectBindingTarget(field) && alias(path)
+ if (target) bindings[field] = target
+ }
+ return bindings
}
/** Typography tokens as text styles and shadow tokens as effect styles, matched by name. */
@@ -220,8 +319,9 @@ export function planStyles(
skipped.push({ name: token.name, collection: undefined, reason: 'unsupported-type' })
continue
}
- const fields = kind === 'TEXT' ? textFields(token, resolve) : effectFields(token, resolve)
- if (!fields) {
+ const style =
+ kind === 'TEXT' ? textStyle(token, resolve, alias) : effectStyle(token, resolve, alias)
+ if (!style) {
skipped.push({ name: token.name, collection: undefined, reason: 'invalid-value' })
continue
}
@@ -232,8 +332,7 @@ export function planStyles(
kind,
name: token.name,
existingNodeId: existing?.nodeId ?? null,
- fields,
- bindings: kind === 'TEXT' ? textBindings(token, alias) : {}
+ ...style
})
}
return { styles, skipped }
diff --git a/packages/core/src/io/formats/design-tokens/styles.ts b/packages/core/src/io/formats/design-tokens/styles.ts
index 979f52cd8..6e13be2a6 100644
--- a/packages/core/src/io/formats/design-tokens/styles.ts
+++ b/packages/core/src/io/formats/design-tokens/styles.ts
@@ -2,6 +2,11 @@ import { isEmptyObject, isPlainObject } from 'es-toolkit/predicate'
import type { Effect, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { lineHeightPixels, textLengthPixels } from '@open-pencil/scene-graph/text'
+import {
+ effectBindingField,
+ effectBindingTarget,
+ type EffectBindingProperty
+} from '@open-pencil/scene-graph/variables'
import { toFigmaEffect } from '#core/figma-api/effects'
@@ -84,31 +89,60 @@ export function isShadow(effect: Effect): boolean {
return effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
}
-function shadowValue(effect: Effect) {
+/** A shadow token's field for each effect property a variable binds. */
+export const SHADOW_TOKEN_FIELDS = {
+ color: 'color',
+ offsetX: 'offsetX',
+ offsetY: 'offsetY',
+ radius: 'blur',
+ spread: 'spread'
+} as const satisfies Record<EffectBindingProperty, string>
+
+/** A bound effect field's token reference, such as `{shadow.blur}` for `effects/0/radius`. */
+export type ShadowReferences = Readonly<Partial<Record<string, string>>>
+
+function shadowValue(effect: Effect, index: number, references: ShadowReferences) {
+ const field = (property: EffectBindingProperty) => references[effectBindingField(index, property)]
return {
- color: colorTokenValue(effect.color),
- offsetX: dimensionTokenValue(effect.offset.x),
- offsetY: dimensionTokenValue(effect.offset.y),
- blur: dimensionTokenValue(effect.radius),
- spread: dimensionTokenValue(effect.spread),
+ color: field('color') ?? colorTokenValue(effect.color),
+ offsetX: field('offsetX') ?? dimensionTokenValue(effect.offset.x),
+ offsetY: field('offsetY') ?? dimensionTokenValue(effect.offset.y),
+ blur: field('radius') ?? dimensionTokenValue(effect.radius),
+ spread: field('spread') ?? dimensionTokenValue(effect.spread),
...(effect.type === 'INNER_SHADOW' ? { inset: true } : {})
}
}
-/** A shadow token's `$value`: the visible shadows of `effects`, or undefined when there are none. */
-export function shadowTokenValue(effects: readonly Effect[]) {
- const values = effects.filter((effect) => isShadow(effect) && effect.visible).map(shadowValue)
+/**
+ * A shadow token's `$value`: the visible shadows of `effects`, bound fields as references to their
+ * variables' tokens, or undefined when there are none.
+ */
+export function shadowTokenValue(effects: readonly Effect[], references: ShadowReferences = {}) {
+ const values = [...effects.entries()]
+ .filter(([, effect]) => isShadow(effect) && effect.visible)
+ .map(([index, effect]) => shadowValue(effect, index, references))
if (values.length === 0) return undefined
return values.length === 1 ? values[0] : values
}
+/** The token references of a layer's bound effect fields, by binding field. */
+function effectReferences(node: SceneNode, references: TokenReferences): ShadowReferences {
+ return Object.fromEntries(
+ Object.entries(node.boundVariables).flatMap(([field, variableId]) => {
+ const path = effectBindingTarget(field) ? references.get(variableId) : undefined
+ return path ? [[field, tokenReference(path)]] : []
+ })
+ )
+}
+
/**
* An effect style's shadows as a shadow token. Effects a shadow token cannot express, such as
* blurs or hidden shadows, ride along whole in OpenPencil's extension, in the plugin API's shape;
* a style with no visible shadow has no token.
*/
-function shadowToken(node: SceneNode): DesignToken | undefined {
- const $value = shadowTokenValue(node.effects)
+function shadowToken(node: SceneNode, references: TokenReferences): DesignToken | undefined {
+ const bindings = effectReferences(node, references)
+ const $value = shadowTokenValue(node.effects, bindings)
if ($value === undefined) return undefined
const exact = node.effects.every(
(effect) =>
@@ -117,17 +151,12 @@ function shadowToken(node: SceneNode): DesignToken | undefined {
(effect.blendMode ?? 'NORMAL') === 'NORMAL' &&
effect.showShadowBehindNode !== true
)
- return {
- $type: 'shadow',
- $value,
- ...(exact
- ? {}
- : {
- $extensions: {
- [OPENPENCIL_EXTENSION]: { effects: node.effects.map((effect) => toFigmaEffect(effect)) }
- }
- })
- }
+ // Bindings ride along so a file read back binds them where `$value` has no place for them.
+ const own: Record<string, unknown> = {}
+ if (!exact) own.effects = node.effects.map((effect) => toFigmaEffect(effect))
+ if (!isEmptyObject(bindings)) own.bindings = bindings
+ if (isEmptyObject(own)) return { $type: 'shadow', $value }
+ return { $type: 'shadow', $value, $extensions: { [OPENPENCIL_EXTENSION]: own } }
}
/** Text and effect styles as typography and shadow tokens, nested by their names. */
@@ -143,7 +172,9 @@ export function styleTokens(
)
const candidates = styles.flatMap((node) => {
const token =
- node.sharedStyleType === 'TEXT' ? typographyToken(node, references) : shadowToken(node)
+ node.sharedStyleType === 'TEXT'
+ ? typographyToken(node, references)
+ : shadowToken(node, references)
if (!token) {
issues.push({ kind: 'unsupported-effect', style: node.name })
return []
diff --git a/packages/core/tests/design-jsx/variables.test.ts b/packages/core/tests/design-jsx/variables.test.ts
index b95e7e731..f77cc8194 100644
--- a/packages/core/tests/design-jsx/variables.test.ts
+++ b/packages/core/tests/design-jsx/variables.test.ts
@@ -388,3 +388,21 @@ test('a reference export writes is one rendering resolves back to the same varia
const [copy] = await renderJSX(graph, references)
expect(graph.getNode(copy.id)?.boundVariables['fills/0/color']).toBe(named.id)
})
+
+test('a shadow bound to variables exports its bindings and renders them back', async () => {
+ const graph = new SceneGraph()
+ const elevation = graph.createCollection('Elevation')
+ const blur = graph.createVariable('Blur', 'FLOAT', elevation.id, 12)
+ const tint = graph.createVariable('Tint', 'COLOR', elevation.id, { r: 0, g: 0, b: 0, a: 0.5 })
+ const [card] = await renderJSX(graph, '<Frame name="Card" w={40} h={40} shadow="0 4 12 #00000080" />')
+ graph.bindVariable(card.id, 'effects/0/radius', blur.id)
+ graph.bindVariable(card.id, 'effects/0/color', tint.id)
+
+ const exported = sceneNodeToJSX(card.id, graph)
+ expect(exported).toContain('"effects/0/radius": elevation.Blur')
+ const [copy] = await renderJSX(graph, exported)
+ expect(graph.getNode(copy.id)?.boundVariables).toEqual({
+ 'effects/0/color': tint.id,
+ 'effects/0/radius': blur.id
+ })
+})
diff --git a/packages/core/tests/editor/design-tokens.test.ts b/packages/core/tests/editor/design-tokens.test.ts
index 597ecc55a..0cd6bba41 100644
--- a/packages/core/tests/editor/design-tokens.test.ts
+++ b/packages/core/tests/editor/design-tokens.test.ts
@@ -258,6 +258,125 @@ describe('design token import', () => {
{ type: 'DROP_SHADOW', radius: 2 }
])
})
+
+ describe('a shadow bound to variables', () => {
+ /** An effect style with a layer blur, then a shadow whose blur and colour are bound. */
+ function boundShadow() {
+ const source = designSystem()
+ const card = source.createNode('RECTANGLE', source.getPages()[0].id, {
+ name: 'Elevation/Card',
+ sharedStyleType: 'EFFECT',
+ internalOnly: true,
+ effects: [
+ {
+ type: 'LAYER_BLUR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ offset: { x: 0, y: 0 },
+ radius: 6,
+ spread: 0,
+ visible: true
+ },
+ {
+ type: 'DROP_SHADOW',
+ color: blue,
+ offset: { x: 0, y: 4 },
+ radius: 24,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ card.source.id = 'style:card'
+ source.bindVariable(card.id, 'effects/1/radius', variableNamed(source, 'Space/Gutter').id)
+ source.bindVariable(card.id, 'effects/1/color', variableNamed(source, 'Accent').id)
+ return source
+ }
+
+ /** The exported files with the styles file's text edited, as another tool would. */
+ function editedStyles(source: SceneGraph, edit: (text: string) => string) {
+ return exported(source).map((file) =>
+ file.path === 'styles.tokens.json' ? { ...file, text: edit(file.text) } : file
+ )
+ }
+
+ function importedStyle(files: DesignTokenSourceFile[]) {
+ const graph = new SceneGraph()
+ importInto(graph, files)
+ const [style] = getSharedStyles(graph, 'effect')
+ return { graph, node: graph.getNode(style.nodeId) }
+ }
+
+ test('writes the bound fields as references to their variables’ tokens', () => {
+ const styles = exportDesignTokens(boundShadow()).files.find(
+ (file) => file.path === 'styles.tokens.json'
+ )
+ expect(styles?.content).toMatchObject({
+ Elevation: { Card: { $value: { blur: '{Space.Gutter}', color: '{Accent}' } } }
+ })
+ })
+
+ test('reads the references back as bindings on the same effect', () => {
+ const { graph, node } = importedStyle(exported(boundShadow()))
+
+ expect(node?.boundVariables).toEqual({
+ 'effects/1/radius': variableNamed(graph, 'Space/Gutter').id,
+ 'effects/1/color': variableNamed(graph, 'Accent').id
+ })
+ expect(node?.effects).toMatchObject([
+ { type: 'LAYER_BLUR', radius: 6 },
+ { type: 'DROP_SHADOW', radius: 24 }
+ ])
+ })
+
+ test('binds the references a shadow edited in another tool keeps, and the blur’s own', () => {
+ const source = boundShadow()
+ const soft = source.createVariable('Blur/Soft', 'FLOAT', variableNamed(source, 'Accent').collectionId, 6)
+ const [style] = getSharedStyles(source, 'effect')
+ source.bindVariable(style.nodeId, 'effects/0/radius', soft.id)
+ const files = editedStyles(source, (text) =>
+ text.replace('"offsetY":{"value":4', '"offsetY":{"value":8')
+ )
+ const { graph, node } = importedStyle(files)
+
+ expect(node?.effects[1]).toMatchObject({ offset: { x: 0, y: 8 }, radius: 24 })
+ expect(node?.boundVariables).toEqual({
+ 'effects/0/radius': variableNamed(graph, 'Blur/Soft').id,
+ 'effects/1/radius': variableNamed(graph, 'Space/Gutter').id,
+ 'effects/1/color': variableNamed(graph, 'Accent').id
+ })
+ })
+
+ test('lets a variable go when the token writes its field as a value again', () => {
+ const source = boundShadow()
+ const { graph } = importedStyle(exported(source))
+ importInto(
+ graph,
+ editedStyles(source, (text) =>
+ text.replace('"blur":"{Space.Gutter}"', '"blur":{"value":30,"unit":"px"}')
+ )
+ )
+
+ const [style] = getSharedStyles(graph, 'effect')
+ const node = graph.getNode(style.nodeId)
+ expect(node?.effects[1].radius).toBe(30)
+ expect(node?.boundVariables).toEqual({
+ 'effects/1/color': variableNamed(graph, 'Accent').id
+ })
+ })
+
+ test('skips a shadow whose field names a token that does not exist', () => {
+ const graph = new SceneGraph()
+ const { plan } = importInto(
+ graph,
+ editedStyles(boundShadow(), (text) => text.replace('{Space.Gutter}', '{Space.Missing}'))
+ )
+
+ expect(plan.skipped).toContainEqual(
+ expect.objectContaining({ name: 'Elevation/Card', reason: 'invalid-value' })
+ )
+ expect(getSharedStyles(graph, 'effect')).toEqual([])
+ })
+ })
})
test('a formula token holds its result and keeps the formula with token references', () => {
diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.md
index 2fd06bb97..18c80cd51 100644
--- a/packages/docs/programmable/cli/exporting.md
+++ b/packages/docs/programmable/cli/exporting.md
@@ -133,7 +133,7 @@ Tokens that cannot be written, such as boolean variables or a condition that is
openpencil tokens design.fig --format dtcg --out tokens
```
-Each collection mode is one file, `Theme/Light.tokens.json` and `Theme/Dark.tokens.json`, in the shape Figma imports as a mode: lengths in `px`, times in `s`, booleans as numbers marked `com.figma.type`, and aliases to another collection naming it in `com.figma.aliasData`. Text and effect styles become typography and shadow tokens in `styles.tokens.json`, kept apart because Figma's import refuses composite tokens. `tokens.resolver.json` is a DTCG resolver that switches each collection's modes and layers the rest, for tools such as Style Dictionary. OpenPencil's own fields, such as a token's `rem` unit, CSS name, scopes, or `clamp()` expression, and each mode's condition, ride in `$extensions["dev.openpencil"]`, so the export reads back exactly.
+Each collection mode is one file, `Theme/Light.tokens.json` and `Theme/Dark.tokens.json`, in the shape Figma imports as a mode: lengths in `px`, times in `s`, booleans as numbers marked `com.figma.type`, and aliases to another collection naming it in `com.figma.aliasData`. Text and effect styles become typography and shadow tokens in `styles.tokens.json`, kept apart because Figma's import refuses composite tokens; a style field bound to a variable, such as a shadow's blur, is written as a reference to that variable's token and read back as a binding. An effect style with no visible shadow has no token, so its bound blur is not written. `tokens.resolver.json` is a DTCG resolver that switches each collection's modes and layers the rest, for tools such as Style Dictionary. OpenPencil's own fields, such as a token's `rem` unit, CSS name, scopes, or `clamp()` expression, and each mode's condition, ride in `$extensions["dev.openpencil"]`, so the export reads back exactly.
Import token files into a document with the `import_design_tokens` tool, passing each file's path and text:
diff --git a/packages/docs/reference/dom-css-mapping.md b/packages/docs/reference/dom-css-mapping.md
index 28a2e939b..e8e580d41 100644
--- a/packages/docs/reference/dom-css-mapping.md
+++ b/packages/docs/reference/dom-css-mapping.md
@@ -61,8 +61,8 @@ HTML export, Tailwind HTML, and Tailwind JSX (`sceneNodesToTailwindJSX`) share o
| grid child position | `grid-column`, `grid-row`, `*-start` | Spans are written before starts. |
| `layoutGrow` in auto layout | `flex-grow: 1` | |
| rotation | `transform: rotate()` | Rotates around the element center. |
-| drop and inner shadows | `box-shadow` | Every visible shadow, in order; inner shadows use `inset`. |
-| layer / background blur | `filter` / `backdrop-filter: blur()` | |
+| drop and inner shadows | `box-shadow` | Every visible shadow, in order; inner shadows use `inset`. A field bound to a variable is written as its `var()` where it draws the variable's value. |
+| layer / background blur | `filter` / `backdrop-filter: blur()` | A radius bound to a variable is written as its `var()` where it draws the variable's value; a negative radius keeps the literal, since CSS has no negative blur. |
| right-to-left layout or text | `direction: rtl` | |
| section | `<section>` | |
| colors | hex, or `rgba()` when translucent | Hex lets Tailwind match its palette. |
diff --git a/packages/dom-css/src/export/css.ts b/packages/dom-css/src/export/css.ts
index 24830ebf3..f9063f527 100644
--- a/packages/dom-css/src/export/css.ts
+++ b/packages/dom-css/src/export/css.ts
@@ -20,28 +20,48 @@ export function strokeColorToCSS(stroke: Stroke | undefined): string | undefined
return cssColor({ ...stroke.color, a: stroke.opacity })
}
-function shadowToCSS(effect: Effect): string {
+/** A bound field's CSS: `var()` where its variable draws the value, else the literal. */
+export type EffectFieldCSS = (field: string, literal: string) => string
+
+const LITERAL: EffectFieldCSS = (_field, literal) => literal
+
+function shadowToCSS(effect: Effect, index: number, css: EffectFieldCSS): string {
const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''
- return `${inset}${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${cssColor(effect.color)}`
+ const length = (property: string, value: number) =>
+ css(`effects/${index}/${property}`, `${value}px`)
+ return [
+ `${inset}${length('offsetX', effect.offset.x)}`,
+ length('offsetY', effect.offset.y),
+ length('radius', effect.radius),
+ length('spread', effect.spread),
+ css(`effects/${index}/color`, cssColor(effect.color))
+ ].join(' ')
}
-export function dropShadowToCSS(effect: Effect | undefined): string | undefined {
+/** The first effect as a drop shadow, as a text's `text-shadow` writes it. */
+export function dropShadowToCSS(effect: Effect | undefined, css = LITERAL): string | undefined {
if (effect?.type !== 'DROP_SHADOW' || !effect.visible) return undefined
- return shadowToCSS(effect)
+ return shadowToCSS(effect, 0, css)
}
-/** Every visible shadow, in order, plus layer and background blur. */
-export function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {
+const isShadow = (effect: Effect) => effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
+
+/**
+ * Every visible shadow, in order, plus layer and background blur. `css` names the variable a
+ * bound field, such as `effects/0/radius`, draws from.
+ */
+export function effectsToCSS(effects: Effect[], css = LITERAL): DesignStyleDeclaration {
const style: DesignStyleDeclaration = {}
- const visible = effects.filter((effect) => effect.visible)
- const shadows = visible.filter(
- (effect) => effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
- )
- if (shadows.length > 0) style['box-shadow'] = shadows.map(shadowToCSS).join(', ')
- for (const effect of visible) {
- if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR')
- style.filter = `blur(${effect.radius}px)`
- if (effect.type === 'BACKGROUND_BLUR') style['backdrop-filter'] = `blur(${effect.radius}px)`
+ const visible = [...effects.entries()].filter(([, effect]) => effect.visible)
+ const shadows = visible.filter(([, effect]) => isShadow(effect))
+ if (shadows.length > 0)
+ style['box-shadow'] = shadows
+ .map(([index, effect]) => shadowToCSS(effect, index, css))
+ .join(', ')
+ for (const [index, effect] of visible) {
+ const blur = () => `blur(${css(`effects/${index}/radius`, `${effect.radius}px`)})`
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR') style.filter = blur()
+ if (effect.type === 'BACKGROUND_BLUR') style['backdrop-filter'] = blur()
}
return style
}
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index b11005d86..a100bcb4a 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -362,7 +362,7 @@ function styleFromSceneNode(
addBackground(style, node, css)
addImageStyle(style, node)
addStroke(style, node, css)
- Object.assign(style, effectsToCSS(node.effects))
+ Object.assign(style, effectsToCSS(node.effects, css))
if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
addCornerRadii(style, node, css)
if (node.clipsContent) style.overflow = 'hidden'
@@ -417,7 +417,7 @@ function styleFromTextNode(
if (node.textAlignHorizontal !== 'LEFT')
style['text-align'] = node.textAlignHorizontal.toLowerCase()
if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
- const shadow = dropShadowToCSS(node.effects[0])
+ const shadow = dropShadowToCSS(node.effects[0], css)
if (shadow) style['text-shadow'] = shadow
if (node.textDecoration !== 'NONE') {
style['text-decoration-line'] =
diff --git a/packages/dom-css/src/tokens/references.ts b/packages/dom-css/src/tokens/references.ts
index 17a111ac0..9ee9ba29b 100644
--- a/packages/dom-css/src/tokens/references.ts
+++ b/packages/dom-css/src/tokens/references.ts
@@ -1,5 +1,6 @@
-import type { SceneGraph, SceneNode, Variable } from '@open-pencil/scene-graph'
+import type { Effect, SceneGraph, SceneNode, Variable } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import { effectBindingTarget, type EffectBindingProperty } from '@open-pencil/scene-graph/variables'
import { collectionVariables, variableCSSNames, variableNamespace } from './names'
import { modeAttribute } from './stylesheet'
@@ -54,6 +55,13 @@ function isColor(value: unknown): value is Color {
return typeof value === 'object' && value !== null && 'r' in value && 'a' in value
}
+/** The length an effect draws for one of its bindable length properties. */
+function effectLength(effect: Effect, property: Exclude<EffectBindingProperty, 'color'>): number {
+ if (property === 'offsetX') return effect.offset.x
+ if (property === 'offsetY') return effect.offset.y
+ return property === 'radius' ? effect.radius : effect.spread
+}
+
/** Where an alias chain ends in the modes the canvas draws: a value, or a CSS expression. */
type TokenChain = {
ids: string[]
@@ -161,7 +169,21 @@ export class DesignTokens {
return undefined
}
- #drawsResolved(node: SceneNode, field: string, { value, end, expression }: TokenChain): boolean {
+ /** Whether a bound effect field draws the value its token chain ends at, in a length CSS reads. */
+ #drawsEffect(node: SceneNode, field: string, { value, end, expression }: TokenChain): boolean {
+ const bound = effectBindingTarget(field)
+ const effect = bound && node.effects.at(bound.index)
+ if (!bound || !effect?.visible) return false
+ if (bound.property === 'color') return isColor(value) && sameColor(effect.color, value)
+ // CSS has no negative blur, so a variable that gives one keeps the literal.
+ if (typeof value !== 'number' || (bound.property === 'radius' && value < 0)) return false
+ if (Math.fround(effectLength(effect, bound.property)) !== Math.fround(value)) return false
+ return expression || LENGTH_UNITS.has(variableUnit(end))
+ }
+
+ #drawsResolved(node: SceneNode, field: string, chain: TokenChain): boolean {
+ if (effectBindingTarget(field)) return this.#drawsEffect(node, field, chain)
+ const { value, end, expression } = chain
if (field.endsWith('/color')) {
const paint = boundPaint(node, field)
if (!paint?.visible || paint.type !== 'SOLID' || !isColor(value)) return false
diff --git a/packages/dom-css/tests/export/projection/tokens.test.ts b/packages/dom-css/tests/export/projection/tokens.test.ts
index caf45f9f3..845dd2441 100644
--- a/packages/dom-css/tests/export/projection/tokens.test.ts
+++ b/packages/dom-css/tests/export/projection/tokens.test.ts
@@ -114,3 +114,43 @@ describe('token references in design-to-code', () => {
})
})
})
+
+describe('token references in effects', () => {
+ const shadow = (offsetY: number) => ({
+ type: 'DROP_SHADOW' as const,
+ color: BLUE_500,
+ offset: { x: 0, y: offsetY },
+ radius: 8,
+ spread: 0,
+ visible: true
+ })
+
+ test('write a bound shadow’s colour and length as tokens', () => {
+ const graph = designSystem()
+ const frame = card(graph, graph.getPages()[0].id, BLUE_500, { effects: [shadow(24)] })
+ graph.bindVariable(frame.id, 'effects/0/offsetY', 'gutter')
+ graph.bindVariable(frame.id, 'effects/0/color', 'primary')
+
+ expect(element(graph, frame.id).inlineStyle?.['box-shadow']).toBe(
+ '0px var(--spacing-gutter) 8px 0px var(--color-primary)'
+ )
+ })
+
+ test('write a bound blur radius as a token', () => {
+ const graph = designSystem()
+ const frame = card(graph, graph.getPages()[0].id, BLUE_500, {
+ effects: [{ ...shadow(0), type: 'LAYER_BLUR' as const, radius: 24 }]
+ })
+ graph.bindVariable(frame.id, 'effects/0/radius', 'gutter')
+
+ expect(element(graph, frame.id).inlineStyle?.filter).toBe('blur(var(--spacing-gutter))')
+ })
+
+ test('keep the literal where the shadow draws another value, as a scaled instance does', () => {
+ const graph = designSystem()
+ const frame = card(graph, graph.getPages()[0].id, BLUE_500, { effects: [shadow(48)] })
+ graph.updateNode(frame.id, { boundVariables: { 'effects/0/offsetY': 'gutter' } })
+
+ expect(element(graph, frame.id).inlineStyle?.['box-shadow']).toBe('0px 48px 8px 0px #3B82F5')
+ })
+})