Skip to content

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

feat(design-jsx): export the variables JSX binds as definitions and props (#1535)

Danila Poyarkov11353fae7ba5
diff --git a/changes/1535/changed.md b/changes/1535/changed.md
new file mode 100644
index 000000000..b0305fd6f
--- /dev/null
+++ b/changes/1535/changed.md
@@ -0,0 +1,2 @@
+- JSX export, in the Code panel, `get_jsx`, and the CLI, starts with the `defineVars` and `defineMode` for the variables its layers use, so the code makes the same tokens in another file.
+- JSX export writes each bound value through its prop, as in `bg={theme.Surface}` and `p={density.Pad}`, instead of a literal beside a `bind` entry.
diff --git a/packages/core/tests/design-jsx/variables.test.ts b/packages/core/tests/design-jsx/variables.test.ts
index c29ed2b85..b95e7e731 100644
--- a/packages/core/tests/design-jsx/variables.test.ts
+++ b/packages/core/tests/design-jsx/variables.test.ts
@@ -1,9 +1,18 @@
import { describe, expect, test } from 'bun:test'
+import { pick } from 'es-toolkit'
+
import { expectDefined } from '#core-tests/helpers/assert'
import { renderJSX, renderTree } from '@open-pencil/core/design-jsx'
-import { defineMode, defineVars, Frame, Rectangle, sceneNodeToJSX } from '@open-pencil/design-jsx'
+import {
+ defineMode,
+ defineVars,
+ Frame,
+ Rectangle,
+ sceneNodeToJSX,
+ selectionToJSXWithLayers
+} from '@open-pencil/design-jsx'
import { SceneGraph, type VariableCollection } from '@open-pencil/scene-graph'
const THEME = `
@@ -112,13 +121,148 @@ describe('Design JSX variable definitions', () => {
})
})
-test('export writes the modes a layer pins, and renders back into the same ones', async () => {
- const graph = new SceneGraph()
- const [card] = await renderJSX(graph, THEME)
- const exported = sceneNodeToJSX(card.id, graph)
- expect(exported).toContain('mode={designMode("Theme", "Dark")}')
- const [copy] = await renderJSX(graph, exported)
- expect(graph.getNode(copy.id)?.variableModes).toEqual(graph.getNode(card.id)?.variableModes)
+describe('Design JSX export of variables', () => {
+ test('writes the definitions its layers use, which render the same tokens in another file', async () => {
+ const graph = new SceneGraph()
+ await renderJSX(graph, `const unused = defineVars('Unused', { Other: 1 }); return <Frame w={unused.Other} />`)
+ const [card] = await renderJSX(graph, THEME)
+ const exported = sceneNodeToJSX(card.id, graph)
+ expect(exported).toBe(`const palette = defineVars("Palette", { "Gray/900": "#111111", "Gray/50": "#FAFAFA" })
+const theme = defineVars("Theme", { Page: palette["Gray/50"], Radius: 12 }, { mode: "Light" })
+const dark = defineMode(theme, "Dark", { Page: palette["Gray/900"] })
+
+return <Frame name="Card" w={100} h={100} bg={theme.Page} rounded={theme.Radius} mode={dark} />`)
+
+ const copy = new SceneGraph()
+ const [rendered] = await renderJSX(copy, exported)
+ // Only what the card uses: Theme's Text is left out.
+ expect(table(copy, 'Theme')).toEqual(pick(table(graph, 'Theme'), ['Page', 'Radius']))
+ expect(table(copy, 'Palette')).toEqual(table(graph, 'Palette'))
+ expect([...copy.variableCollections.values()].map((item) => item.name)).toEqual([
+ 'Palette',
+ 'Theme'
+ ])
+ const node = copy.getNode(rendered.id)
+ const theme = collectionNamed(copy, 'Theme')
+ expect(node?.variableModes).toEqual({ [theme.id]: theme.modes[1].modeId })
+ expect(Object.keys(node?.boundVariables ?? {})).toEqual(['fills/0/color', 'cornerRadius'])
+ })
+
+ test('writes references instead when it declares nothing, or JSX cannot define a variable', async () => {
+ const graph = new SceneGraph()
+ const [card] = await renderJSX(graph, THEME)
+ const references = selectionToJSXWithLayers([card.id], graph, { declarations: false }).code
+ expect(references).toBe(
+ '<Frame name="Card" w={100} h={100} bg={designVar("Page")} rounded={designVar("Radius")} mode={designMode("Theme", "Dark")} />'
+ )
+
+ const strings = graph.createCollection('Copy')
+ const label = graph.createVariable('Label', 'STRING', strings.id, 'Hi')
+ const [text] = await renderJSX(graph, '<Text>Hi</Text>')
+ graph.bindVariable(text.id, 'text', label.id)
+ expect(sceneNodeToJSX(text.id, graph)).toContain('bind={{ text: designVar("Label") }}')
+ })
+
+ test('writes an alias to its own collection by reference, and names no handle a reserved word', async () => {
+ const graph = new SceneGraph()
+ const [card] = await renderJSX(
+ graph,
+ `const space = defineVars('Space', { Base: 4 }, { mode: 'Default' })
+const roomy = defineMode(space, 'Roomy', { Base: 8 })
+return <Frame name="Card" flex="col" mode={roomy} p={space.Base} />`
+ )
+ const collection = collectionNamed(graph, 'Space')
+ const base = expectDefined(graph.variables.get(collection.variableIds[0]))
+ const gap = graph.createVariable('Gap', 'FLOAT', collection.id, { aliasId: base.id })
+ graph.bindVariable(card.id, 'itemSpacing', gap.id)
+ graph.updateNode(card.id, {
+ variableModes: { [collection.id]: collection.modes[0].modeId }
+ })
+ graph.renameMode(collection.id, collection.modes[1].modeId, 'Default')
+ graph.renameMode(collection.id, collection.modes[0].modeId, 'Roomy')
+ const exported = sceneNodeToJSX(card.id, graph)
+ expect(exported).toContain('gap={designVar("Gap")}')
+ expect(exported).not.toMatch(/const default\b/)
+ // The code runs: no handle is read before it is declared.
+ const [copy] = await renderJSX(graph, exported)
+ expect(graph.getNode(copy.id)?.boundVariables.itemSpacing).toBe(gap.id)
+ })
+
+ test('declares no variable whose name its collection shares, nor one that aliases it', async () => {
+ const graph = new SceneGraph()
+ const space = graph.createCollection('Space')
+ const first = graph.createVariable('Pad', 'FLOAT', space.id, 4)
+ const second = graph.createVariable('Pad', 'FLOAT', space.id, 8)
+ const palette = graph.createCollection('Palette')
+ const base = graph.createVariable('Base', 'FLOAT', palette.id, 2)
+ const derived = graph.createVariable('Derived', 'FLOAT', palette.id, { aliasId: base.id })
+ const theme = graph.createCollection('Theme')
+ const spacing = graph.createVariable('Spacing', 'FLOAT', theme.id, { aliasId: derived.id })
+ const [card] = await renderJSX(graph, '<Frame name="Card" flex="col" w={10} h={10} />')
+ graph.bindVariable(card.id, 'itemSpacing', second.id)
+ graph.bindVariable(card.id, 'cornerRadius', spacing.id)
+
+ const exported = sceneNodeToJSX(card.id, graph)
+ // Derived aliases its own collection, so it and Spacing, which aliases it, stay references.
+ expect(exported).not.toContain('defineVars(')
+ expect(exported).toContain('rounded={designVar("Spacing")}')
+ const [copy] = await renderJSX(graph, exported)
+ expect(graph.getNode(copy.id)?.boundVariables).toEqual({
+ itemSpacing: second.id,
+ cornerRadius: spacing.id
+ })
+ expect(first.valuesByMode[space.defaultModeId]).toBe(4)
+ })
+
+ test('writes a padding bound on every side as p, and a partly bound one in bind', async () => {
+ const graph = new SceneGraph()
+ const space = 'const s = defineVars("Space", { M: 8, L: 16 })'
+ const [even] = await renderJSX(graph, `${space}; return <Frame flex="col" p={s.M} />`)
+ expect(sceneNodeToJSX(even.id, graph)).toContain('p={space.M}')
+ const [uneven] = await renderJSX(graph, `${space}; return <Frame flex="col" px={s.M} py={s.L} pt={4} />`)
+ const exported = sceneNodeToJSX(uneven.id, graph)
+ expect(exported).toContain('pt={4} pr={space.M} pb={space.L} pl={space.M}')
+ expect(exported).not.toContain('bind=')
+ })
+
+ test('writes a binding in bind where its prop would change the layer it renders', async () => {
+ const graph = new SceneGraph()
+ const [row] = await renderJSX(
+ graph,
+ `const s = defineVars("Space", { M: 8 })
+return <Frame name="Row" flex="row" w={200} h={50} p={s.M}>
+ <Frame name="Bar" w={20} h="fill" />
+ <Frame name="Card" rounded={8} w={40} h={40} />
+</Frame>`
+ )
+ const m = expectDefined(collectionNamed(graph, 'Space').variableIds[0])
+ const child = (name: string) =>
+ expectDefined(graph.getChildren(row.id).find((node) => node.name === name))
+ graph.bindVariable(child('Bar').id, 'height', m)
+ graph.bindVariable(child('Card').id, 'topLeftRadius', m)
+ const [loose] = await renderJSX(graph, '<Frame name="Loose" w={40} h={40} />')
+ graph.updateNode(loose.id, { paddingLeft: 8 })
+ graph.bindVariable(loose.id, 'paddingLeft', m)
+
+ const exported = sceneNodeToJSX(row.id, graph)
+ // The bar keeps filling the row, and the card's other corners keep their radius.
+ expect(exported).toContain('w={20} h="fill" bind={{ height: space.M }}')
+ expect(exported).toContain('roundedTL={space.M} roundedTR={8} roundedBR={8} roundedBL={8}')
+ // A padding prop would give the frame auto layout.
+ expect(sceneNodeToJSX(loose.id, graph)).toContain('bind={{ paddingLeft: space.M }}')
+
+ const [copy] = await renderJSX(graph, exported)
+ const bar = expectDefined(graph.getChildren(copy.id).find((node) => node.name === 'Bar'))
+ expect(bar.height).toBe(child('Bar').height)
+ const card = expectDefined(graph.getChildren(copy.id).find((node) => node.name === 'Card'))
+ expect(pick(card, ['topLeftRadius', 'topRightRadius', 'bottomRightRadius'])).toEqual({
+ topLeftRadius: 8,
+ topRightRadius: 8,
+ bottomRightRadius: 8
+ })
+ const [looseCopy] = await renderJSX(graph, sceneNodeToJSX(loose.id, graph))
+ expect(graph.getNode(looseCopy.id)?.layoutMode).toBe('NONE')
+ })
})
test('artwork drawn in a variable binds its paths and resolves in its own mode', async () => {
@@ -180,8 +324,10 @@ test('designVar names a variable by collection when several collections share it
expect(node?.boundVariables['fills/0/color']).toBe(id('Theme'))
expect(node?.boundVariables.paddingTop).toBe(id('Density'))
const exported = sceneNodeToJSX(frame.id, graph)
- expect(exported).toContain('designVar("Theme", "Page")')
- expect(exported).toContain('designVar("Density", "Page")')
+ const references = selectionToJSXWithLayers([frame.id], graph, { declarations: false }).code
+ expect(references).toContain('designVar("Theme", "Page")')
+ expect(references).toContain('designVar("Density", "Page")')
+ expect(exported).toContain('bg={theme.Page} p={density.Page}')
const [copy] = await renderJSX(graph, exported)
expect(graph.getNode(copy.id)?.boundVariables).toEqual(node?.boundVariables)
})
@@ -220,3 +366,25 @@ return <Frame name="Board" w={400} h={400}><Sticky mode={dark} opacity={fade.Not
expect(sticky.variableModes).toEqual({ [fade.id]: fade.modes[1].modeId })
expect(sticky.opacity).toBe(0.5)
})
+
+test('a reference export writes is one rendering resolves back to the same variable', async () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Ink')
+ graph.addVariable({
+ id: 'x',
+ name: 'Other',
+ type: 'COLOR',
+ collectionId: collection.id,
+ valuesByMode: { [collection.defaultModeId]: { r: 0, g: 0, b: 0, a: 1 } },
+ description: '',
+ hiddenFromPublishing: false
+ })
+ // Named as the other variable's ID, which `designVar('x')` finds first.
+ const named = graph.createVariable('x', 'COLOR', collection.id, { r: 1, g: 0, b: 0, a: 1 })
+ const [frame] = await renderJSX(graph, '<Frame bg="#FFFFFF" />')
+ graph.bindVariable(frame.id, 'fills/0/color', named.id)
+ const references = selectionToJSXWithLayers([frame.id], graph, { declarations: false }).code
+ expect(references).toContain('bg={designVar("Ink", "x")}')
+ const [copy] = await renderJSX(graph, references)
+ expect(graph.getNode(copy.id)?.boundVariables['fills/0/color']).toBe(named.id)
+})
diff --git a/packages/design-jsx/src/connectors.ts b/packages/design-jsx/src/connectors.ts
index 24ace9133..34070cd49 100644
--- a/packages/design-jsx/src/connectors.ts
+++ b/packages/design-jsx/src/connectors.ts
@@ -92,7 +92,7 @@ function styleLine(graph: SceneGraph, line: SceneNode, props: ConnectorPropValue
* The layers JSX writes under `rootIds`, in order, each before its descendants: the layers a
* connector or sticky note generates are not, so an end never names them.
*/
-function layersUnder(graph: SceneGraph, rootIds: readonly string[]): SceneNode[] {
+export function layersUnder(graph: SceneGraph, rootIds: readonly string[]): SceneNode[] {
const layers: SceneNode[] = []
const visit = (id: string) => {
const node = graph.getNode(id)
diff --git a/packages/design-jsx/src/export/bindings.ts b/packages/design-jsx/src/export/bindings.ts
new file mode 100644
index 000000000..786704c67
--- /dev/null
+++ b/packages/design-jsx/src/export/bindings.ts
@@ -0,0 +1,155 @@
+import { isEqual } from 'es-toolkit'
+
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ PADDING_FIELDS,
+ paintProps,
+ scalarProps,
+ type BindingContext,
+ type BoundProp
+} from '../variables/props'
+import type { JSXProp, JSXValue } from './value'
+import type { VariableExport } from './variables'
+
+/** Sizes are not added when the export left them out, as a fixed size would replace Hug or Fill. */
+const NOT_ADDED = new Set(['width', 'height'])
+/** The corner props, which make the corners independent wherever one of them is written. */
+const CORNER_PROPS = ['roundedTL', 'roundedTR', 'roundedBR', 'roundedBL']
+
+function bindingContext(node: SceneNode): BindingContext {
+ return {
+ text: node.type === 'TEXT',
+ grid: node.layoutMode === 'GRID',
+ wrap: node.layoutWrap === 'WRAP'
+ }
+}
+
+/**
+ * The prop `field` is written through on `node`: one the export printed that sets that field
+ * alone, or else the last number prop that does, as rendering reads it, or none, when only
+ * `bind` can set it. A paint prop is printed only for a single solid paint, which a colour
+ * variable can stand for; a number prop printed as a word, such as `w="fill"`, keeps it.
+ */
+function fieldProp(node: SceneNode, field: string, props: JSXProp[]) {
+ const context = bindingContext(node)
+ const sets = ({ fields }: BoundProp) => fields.length === 1 && fields[0] === field
+ const scalar = scalarProps(context).filter(sets)
+ const printedAs = (prop: string, numeric: boolean) =>
+ props.some(([name, value]) => name === prop && (!numeric || typeof value === 'number'))
+ const printed =
+ scalar.find(({ prop }) => printedAs(prop, true)) ??
+ paintProps(context)
+ .filter(sets)
+ .find(({ prop }) => printedAs(prop, false))
+ if (printed) return { prop: printed.prop, add: false }
+ const last = scalar.at(-1)
+ return last && !NOT_ADDED.has(field) ? { prop: last.prop, add: true } : undefined
+}
+
+function setProp(props: JSXProp[], name: string, value: JSXValue, add: boolean): boolean {
+ const index = props.findIndex(([prop]) => prop === name)
+ if (index !== -1) props[index] = [name, value]
+ else if (add) props.push([name, value])
+ return index !== -1 || add
+}
+
+/**
+ * Write the padding again when a side is bound, each bound side as its variable, grouped as
+ * `p`, `py` and `px`, or one prop per side, as the export groups literal padding.
+ */
+function writePadding(
+ node: SceneNode,
+ props: JSXProp[],
+ remaining: Map<string, string>,
+ variables: VariableExport,
+ named: (variableId: string) => boolean
+): void {
+ const sides = PADDING_FIELDS.map((field): JSXValue => {
+ const variableId = remaining.get(field)
+ return variableId && named(variableId)
+ ? variables.variable(variableId)
+ : node[field as 'paddingTop']
+ })
+ if (sides.every((side) => typeof side === 'number')) return
+ const paddingProps = new Set(
+ scalarProps(bindingContext(node))
+ .filter(({ fields }) => fields.every((field) => PADDING_FIELDS.includes(field)))
+ .map(({ prop }) => prop)
+ )
+ for (let index = props.length - 1; index >= 0; index--) {
+ if (paddingProps.has(props[index][0])) props.splice(index, 1)
+ }
+ const [top, right, bottom, left] = sides
+ if ([right, bottom, left].every((side) => isEqual(side, top))) props.push(['p', top])
+ else if (isEqual(top, bottom) && isEqual(left, right)) props.push(['py', top], ['px', left])
+ else {
+ ;(['pt', 'pr', 'pb', 'pl'] as const).forEach((prop, index) => {
+ if (sides[index] !== 0) props.push([prop, sides[index]])
+ })
+ }
+ for (const field of PADDING_FIELDS) {
+ const variableId = remaining.get(field)
+ if (variableId && named(variableId)) remaining.delete(field)
+ }
+}
+
+/**
+ * Write corners printed together as `rounded` one by one when a corner is bound, since the
+ * bound corner's own prop makes the corners independent and the others would then be 0.
+ */
+function expandCorners(
+ node: SceneNode,
+ props: JSXProp[],
+ remaining: Map<string, string>,
+ named: (variableId: string) => boolean
+): void {
+ const corners = new Set(
+ scalarProps(bindingContext(node))
+ .filter(({ prop }) => CORNER_PROPS.includes(prop))
+ .flatMap(({ fields }) => fields)
+ )
+ const bound = [...remaining].some(([field, id]) => corners.has(field) && named(id))
+ const index = props.findIndex(([prop]) => prop === 'rounded')
+ if (!bound || index === -1) return
+ const [, radius] = props[index]
+ props.splice(index, 1, ...CORNER_PROPS.map((prop): JSXProp => [prop, radius]))
+}
+
+/**
+ * Write the variables `node` binds through the props that set those fields, such as
+ * `bg={theme.Surface}` and `p={density.Pad}`, and the rest in `bind`. Padding stays in `bind`
+ * on a layer without auto layout, where a padding prop would turn it on.
+ */
+export function collectBindingProps(
+ node: SceneNode,
+ props: JSXProp[],
+ variables: VariableExport
+): void {
+ const remaining = new Map(Object.entries(node.boundVariables))
+ // A variable only `bind` can name, by its ID, is not written in a prop, which reads a string.
+ const named = (variableId: string) => typeof variables.variable(variableId) !== 'string'
+ const laidOut = node.layoutMode !== 'NONE'
+ if (laidOut) writePadding(node, props, remaining, variables, named)
+ expandCorners(node, props, remaining, named)
+ for (const [field, variableId] of remaining) {
+ if (!named(variableId) || (!laidOut && PADDING_FIELDS.includes(field))) continue
+ const target = fieldProp(node, field, props)
+ if (target && setProp(props, target.prop, variables.variable(variableId), target.add))
+ remaining.delete(field)
+ }
+ if (remaining.size === 0) return
+ const bindings = [...remaining].toSorted(([a], [b]) => a.localeCompare(b))
+ props.push([
+ 'bind',
+ Object.fromEntries(bindings.map(([field, id]) => [field, variables.variable(id)]))
+ ])
+}
+
+/** The modes a layer pins; one is written without a list. */
+export function collectModeProps(node: SceneNode, props: JSXProp[], variables: VariableExport) {
+ const modes = Object.entries(node.variableModes).map(([collectionId, modeId]) =>
+ variables.mode(collectionId, modeId)
+ )
+ if (modes.length > 0) props.push(['mode', modes.length === 1 ? modes[0] : modes])
+}
diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.ts
index e9b1762e9..e56b0aae3 100644
--- a/packages/design-jsx/src/export/index.ts
+++ b/packages/design-jsx/src/export/index.ts
@@ -19,6 +19,7 @@ import { iconProps } from './icons'
import { collectProps, positionProps, presenceProps } from './props'
import { textChildren } from './text'
import { plainValue, propAttribute, Reference, type JSXProp } from './value'
+import { variableExport, type VariableExport } from './variables'
/** Design JSX with the layer behind each element, in the order elements open. */
export interface DesignJSXWithLayers {
@@ -120,6 +121,7 @@ function nodeToJSX(
graph: SceneGraph,
depth: number,
scope: ConnectorExportScope,
+ variables: VariableExport,
layerIds?: Array<string | null>,
outer: RekaExport = NO_REKA
): SyntaxNode[] {
@@ -132,7 +134,7 @@ function nodeToJSX(
const children = (childDepth: number) =>
graph
.getChildren(node.id)
- .flatMap((child) => nodeToJSX(child, graph, childDepth, scope, layerIds, reka))
+ .flatMap((child) => nodeToJSX(child, graph, childDepth, scope, variables, layerIds, reka))
if (reka.flatten.has(node.id)) return children(depth)
// An icon is written by name; its paths are the icon set's to draw again.
const icon = iconProps(node, graph)
@@ -152,7 +154,9 @@ function nodeToJSX(
// An item names its component; the instance's own layers are the component's to write.
if (ownProps?.some(([name]) => name === 'of'))
return [jsx.element(tag, withRef(ownProps).map(propAttribute), [], depth)]
- const attributes = withRef([...collectProps(node, graph), ...(ownProps ?? [])]).map(propAttribute)
+ const attributes = withRef([...collectProps(node, graph, variables), ...(ownProps ?? [])]).map(
+ propAttribute
+ )
if (node.type === 'TEXT') {
const { children: content, inline } = textChildren(node, depth)
for (let count = elementCount(content); count > 0; count--) layerIds?.push(null)
@@ -250,7 +254,9 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXEl
export interface JSXExportOptions {
/**
* `false` writes only JSX, for code that places it inside other JSX: a connector end whose
- * layer would need a declared `ref()` is then written as the point it is drawn at.
+ * layer would need a declared `ref()` is then written as the point it is drawn at, and the
+ * variables layers bind are written by reference (`designVar`) instead of with the
+ * `defineVars` and `defineMode` that define them.
*/
declarations?: boolean
}
@@ -269,16 +275,21 @@ export function selectionToJSXWithLayers(
options: JSXExportOptions = {}
): DesignJSXWithLayers {
const layerIds: Array<string | null> = []
- const scope = connectorExportScope(graph, nodeIds, options.declarations ?? true)
+ const declare = options.declarations ?? true
+ const scope = connectorExportScope(graph, nodeIds, declare)
+ const variables = variableExport(graph, nodeIds, declare)
const roots = compact(
nodeIds.map((id) => {
const node = graph.getNode(id)
- const syntax = node ? nodeToJSX(node, graph, 0, scope, layerIds).at(0) : undefined
+ const syntax = node ? nodeToJSX(node, graph, 0, scope, variables, layerIds).at(0) : undefined
return syntax ? jsx.printJSX(syntax) : ''
})
)
const elements = roots.join('\n\n')
- const declarations = connectorRefDeclarations(scope)
+ // Variables first: a ref names a layer, and nothing in a variable's definition refers to one.
+ const declarations = compact([variables.declarations(), connectorRefDeclarations(scope)]).join(
+ '\n\n'
+ )
if (!declarations || !elements) return { code: elements, layerIds }
// Statements end with `return` and the JSX; several roots return as siblings in a fragment.
const returned = roots.length > 1 ? `<>\n${elements}\n</>` : elements
diff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.ts
index 398e87d13..63d828590 100644
--- a/packages/design-jsx/src/export/props.ts
+++ b/packages/design-jsx/src/export/props.ts
@@ -19,6 +19,7 @@ import {
import { collectEffectProps, collectFillProps, collectStrokeProps } from './paint'
import { collectStateProps } from './state'
import type { JSXProp } from './value'
+import { variableReferences, type VariableExport } from './variables'
export type { JSXProp } from './value'
@@ -318,8 +319,15 @@ function collectShapeNodeProps(node: SceneNode, props: JSXProp[]): void {
}
}
-/** The props of `node`, in the order they are printed. */
-export function collectProps(node: SceneNode, graph: SceneGraph): JSXProp[] {
+/**
+ * The props of `node`, in the order they are printed, with the variables it binds written as
+ * `variables` writes them: by default, by reference to the document's.
+ */
+export function collectProps(
+ node: SceneNode,
+ graph: SceneGraph,
+ variables: VariableExport = variableReferences(graph)
+): JSXProp[] {
const props: JSXProp[] = []
const ctx = getNodeContext(node, graph)
@@ -336,7 +344,7 @@ export function collectProps(node: SceneNode, graph: SceneGraph): JSXProp[] {
collectTextAutoResizeProp(node, ctx, props)
}
collectShapeNodeProps(node, props)
- collectStateProps(node, ctx, graph, props)
+ collectStateProps(node, ctx, props, variables)
return props
}
diff --git a/packages/design-jsx/src/export/state.ts b/packages/design-jsx/src/export/state.ts
index e4a89a345..3f725bdcc 100644
--- a/packages/design-jsx/src/export/state.ts
+++ b/packages/design-jsx/src/export/state.ts
@@ -1,8 +1,10 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { SceneNode } from '@open-pencil/scene-graph'
import { CONSTRAINT, MASK_TYPE } from '../enums'
+import { collectBindingProps, collectModeProps } from './bindings'
import type { getNodeContext } from './helpers'
-import { helperCall, type JSXProp, type JSXValue } from './value'
+import type { JSXProp } from './value'
+import type { VariableExport } from './variables'
/** Constraints apply where a parent does not lay its children out. */
function hasConstraints(node: SceneNode, ctx: ReturnType<typeof getNodeContext>): boolean {
@@ -34,61 +36,17 @@ function collectSizeLimitProps(node: SceneNode, props: JSXProp[]): void {
if (node.maxHeight != null) props.push(['maxH', node.maxHeight])
}
-/**
- * Variables are named as `designVar` resolves them: by name when it is unique in the document, by
- * collection and name when that pair is, and by ID otherwise.
- */
-function variableRef(graph: SceneGraph, variableId: string): JSXValue {
- const variable = graph.variables.get(variableId)
- if (!variable) return variableId
- const sameName = [...graph.variables.values()].filter((v) => v.name === variable.name)
- if (sameName.length === 1) return helperCall('designVar', variable.name)
- const collection = graph.variableCollections.get(variable.collectionId)
- const sameCollectionName = [...graph.variableCollections.values()].filter(
- (item) => item.name === collection?.name
- )
- const inCollection = sameName.filter((v) => v.collectionId === variable.collectionId)
- return collection && sameCollectionName.length === 1 && inCollection.length === 1
- ? helperCall('designVar', collection.name, variable.name)
- : variableId
-}
-
-function collectBindingProps(node: SceneNode, graph: SceneGraph, props: JSXProp[]): void {
- const bindings = Object.entries(node.boundVariables).toSorted(([a], [b]) => a.localeCompare(b))
- if (bindings.length === 0) return
- props.push([
- 'bind',
- Object.fromEntries(bindings.map(([field, id]) => [field, variableRef(graph, id)]))
- ])
-}
-
-/**
- * The modes a layer pins, as `designMode` names them: by the collection's name when it is unique
- * in the document and by its ID otherwise. One is written without a list.
- */
-function collectModeProps(node: SceneNode, graph: SceneGraph, props: JSXProp[]): void {
- const collections = [...graph.variableCollections.values()]
- const modes = Object.entries(node.variableModes).flatMap(([collectionId, modeId]) => {
- const collection = graph.variableCollections.get(collectionId)
- const mode = collection?.modes.find((item) => item.modeId === modeId)
- if (!collection || !mode) return []
- const unique = collections.filter((item) => item.name === collection.name).length === 1
- return [helperCall('designMode', unique ? collection.name : collection.id, mode.name)]
- })
- if (modes.length > 0) props.push(['mode', modes.length === 1 ? modes[0] : modes])
-}
-
export function collectStateProps(
node: SceneNode,
ctx: ReturnType<typeof getNodeContext>,
- graph: SceneGraph,
- props: JSXProp[]
+ props: JSXProp[],
+ variables: VariableExport
): void {
collectConstraintProps(node, ctx, props)
collectSizeLimitProps(node, props)
if (node.isMask) props.push(['mask', MASK_TYPE.print(node.maskType)])
if (!node.visible) props.push(['visible', false])
if (node.locked) props.push(['locked', true])
- collectModeProps(node, graph, props)
- collectBindingProps(node, graph, props)
+ collectModeProps(node, props, variables)
+ collectBindingProps(node, props, variables)
}
diff --git a/packages/design-jsx/src/export/value.ts b/packages/design-jsx/src/export/value.ts
index f24c23bf5..120b2d566 100644
--- a/packages/design-jsx/src/export/value.ts
+++ b/packages/design-jsx/src/export/value.ts
@@ -8,9 +8,15 @@ export class HelperCall {
) {}
}
-/** A name the export declares before the JSX, such as the `card1` of `ref={card1}`. */
+/**
+ * A name the export declares before the JSX, such as the `card1` of `ref={card1}`, or one of its
+ * members, such as the `theme.Page` of a variable `defineVars` declared.
+ */
export class Reference {
- constructor(readonly name: string) {}
+ constructor(
+ readonly name: string,
+ readonly member?: string
+ ) {}
}
/** A prop value: plain data, possibly holding helper calls. Undefined object fields are left out. */
@@ -63,7 +69,10 @@ export function plainValue(value: unknown): JSXValue {
export function valueSyntax(value: JSXValue): SyntaxNode {
if (value === null) return { type: 'Literal', value: null }
if (value instanceof HelperCall) return es.call(value.helper, value.args.map(valueSyntax))
- if (value instanceof Reference) return es.identifier(value.name)
+ if (value instanceof Reference)
+ return value.member === undefined
+ ? es.identifier(value.name)
+ : es.member(es.identifier(value.name), value.member)
if (Array.isArray(value)) return es.array(value.map(valueSyntax))
if (typeof value === 'object') {
return es.object(
diff --git a/packages/design-jsx/src/export/variables.ts b/packages/design-jsx/src/export/variables.ts
new file mode 100644
index 000000000..a8f00bb8f
--- /dev/null
+++ b/packages/design-jsx/src/export/variables.ts
@@ -0,0 +1,398 @@
+import { isEqual } from 'es-toolkit'
+import { camelCase } from 'es-toolkit/string'
+
+import { jsx } from '@open-pencil/emit'
+import type {
+ SceneGraph,
+ Variable,
+ VariableCollection,
+ VariableValue
+} from '@open-pencil/scene-graph'
+import { modesDefaultFirst } from '@open-pencil/scene-graph/variables'
+
+import { layersUnder } from '../connectors'
+import { DESIGN_JSX_ELEMENTS } from '../elements'
+import { DESIGN_JSX_HELPERS } from '../helpers'
+import { DEFAULT_MODE_NAME, designMode, designVar, type DesignVariable } from '../variables'
+import { collectionNamed, resolveVariableId, variableModes } from '../variables/graph'
+import { formatColor } from './helpers'
+import { helperCall, Reference, valueSyntax, type JSXValue } from './value'
+
+/** How an export writes the variables its layers bind and the modes they pin. */
+export interface VariableExport {
+ variable(variableId: string): JSXValue
+ mode(collectionId: string, modeId: string): JSXValue
+ /** The `defineVars` and `defineMode` statements the JSX refers to, if it declares any. */
+ declarations(): string
+}
+
+/**
+ * Variables and modes by reference to the document's own, as `designVar` and `designMode` find
+ * them: by name when it is unique, then by collection and name, and by ID otherwise.
+ */
+export function variableReferences(graph: SceneGraph): VariableExport {
+ // A reference is written only when rendering would resolve it back to the same variable.
+ const finds = (handle: DesignVariable, variableId: string) => {
+ try {
+ return resolveVariableId(graph, handle) === variableId
+ } catch {
+ return false
+ }
+ }
+ // A collection name several collections share names none of them; its ID still does.
+ const findsMode = (collection: string, mode: string, collectionId: string, modeId: string) => {
+ try {
+ return variableModes(graph, designMode(collection, mode))?.[collectionId] === modeId
+ } catch {
+ return false
+ }
+ }
+ return {
+ variable(variableId) {
+ const variable = graph.variables.get(variableId)
+ if (!variable) return variableId
+ if (finds(designVar(variable.name), variableId)) return helperCall('designVar', variable.name)
+ const collection = graph.variableCollections.get(variable.collectionId)
+ return collection && finds(designVar(collection.name, variable.name), variableId)
+ ? helperCall('designVar', collection.name, variable.name)
+ : variableId
+ },
+ mode(collectionId, modeId) {
+ const collection = graph.variableCollections.get(collectionId)
+ const mode = collection?.modes.find((item) => item.modeId === modeId)
+ if (!collection || !mode) return modeId
+ const named = [collection.name, collectionId].find((name) =>
+ findsMode(name, mode.name, collectionId, modeId)
+ )
+ return named ? helperCall('designMode', named, mode.name) : modeId
+ },
+ declarations: () => ''
+ }
+}
+
+/** The variables the layers under `rootIds` bind. */
+function boundVariableIds(graph: SceneGraph, rootIds: readonly string[]): Set<string> {
+ return new Set(
+ layersUnder(graph, rootIds).flatMap((layer) => Object.values(layer.boundVariables))
+ )
+}
+
+/** A value `defineVars` can write: a color, a number, a boolean, or an alias. */
+function definable(variable: Variable): boolean {
+ if (variable.type === 'STRING') return false
+ return Object.values(variable.valuesByMode).every(
+ (value) =>
+ typeof value === 'number' ||
+ typeof value === 'boolean' ||
+ (typeof value === 'object' && ('aliasId' in value || 'r' in value))
+ )
+}
+
+/** Words JavaScript reserves, which no `const` may be named, as a mode named Default would be. */
+const RESERVED_WORDS = [
+ 'await',
+ 'break',
+ 'case',
+ 'catch',
+ 'class',
+ 'const',
+ 'continue',
+ 'debugger',
+ 'default',
+ 'delete',
+ 'do',
+ 'else',
+ 'enum',
+ 'export',
+ 'extends',
+ 'false',
+ 'finally',
+ 'for',
+ 'function',
+ 'if',
+ 'implements',
+ 'import',
+ 'in',
+ 'instanceof',
+ 'interface',
+ 'let',
+ 'new',
+ 'null',
+ 'package',
+ 'private',
+ 'protected',
+ 'public',
+ 'return',
+ 'static',
+ 'super',
+ 'switch',
+ 'this',
+ 'throw',
+ 'true',
+ 'try',
+ 'typeof',
+ 'var',
+ 'void',
+ 'while',
+ 'with',
+ 'yield',
+ 'arguments',
+ 'eval',
+ 'undefined',
+ 'NaN',
+ 'Infinity'
+]
+
+const TAKEN = new Set([
+ ...RESERVED_WORDS,
+ ...DESIGN_JSX_ELEMENTS.map((element) => element.name),
+ ...DESIGN_JSX_HELPERS.map((helper) => helper.name),
+ 'svg',
+ 'React'
+])
+
+function handleName(name: string, taken: Set<string>, fallback: string): string {
+ const camel = camelCase(name)
+ const base = /^[A-Za-z_$][\w$]*$/.test(camel) ? camel : fallback
+ let candidate = base
+ for (let count = 2; taken.has(candidate); count++) candidate = `${base}${count}`
+ taken.add(candidate)
+ return candidate
+}
+
+interface DefinedCollection {
+ collection: VariableCollection
+ name: string
+ variables: Variable[]
+ /** Handles for the modes after the first, by mode ID. */
+ modes: Map<string, string>
+}
+
+/** The variable a value aliases, if it is an alias. */
+function aliasOf(value: VariableValue | undefined): string | undefined {
+ return typeof value === 'object' && 'aliasId' in value ? value.aliasId : undefined
+}
+
+/**
+ * Whether rendering finds `variable` again by its collection's name and its own, as definitions
+ * are found: a name another collection or variable shares stays a reference rather than redefine
+ * whichever comes first.
+ */
+function findsByName(graph: SceneGraph, variable: Variable): boolean {
+ const collection = graph.variableCollections.get(variable.collectionId)
+ if (!collection) return false
+ try {
+ return (
+ collectionNamed(graph, collection.name) === collection &&
+ resolveVariableId(graph, designVar(collection.name, variable.name)) === variable.id
+ )
+ } catch {
+ return false
+ }
+}
+
+/** The variables the layers bind that JSX can define, with every variable they alias. */
+function definableVariables(graph: SceneGraph, rootIds: readonly string[]): Set<string> {
+ const included = new Set<string>()
+ const include = (variableId: string) => {
+ const variable = graph.variables.get(variableId)
+ if (!variable || included.has(variableId) || !definable(variable)) return
+ if (!findsByName(graph, variable)) return
+ included.add(variableId)
+ for (const value of Object.values(variable.valuesByMode)) {
+ const target = aliasOf(value)
+ if (target) include(target)
+ }
+ }
+ for (const id of boundVariableIds(graph, rootIds)) include(id)
+ return included
+}
+
+/** The variables by collection, each in its collection's order, as the variables panel lists them. */
+function byCollectionOf(graph: SceneGraph, included: Set<string>): Map<string, Variable[]> {
+ const byCollection = new Map<string, Variable[]>()
+ for (const id of included) {
+ const variable = graph.variables.get(id)
+ if (variable)
+ byCollection.set(variable.collectionId, [
+ ...(byCollection.get(variable.collectionId) ?? []),
+ variable
+ ])
+ }
+ for (const [collectionId, variables] of byCollection) {
+ const listed = graph.variableCollections.get(collectionId)?.variableIds ?? []
+ variables.sort((a, b) => listed.indexOf(a.id) - listed.indexOf(b.id))
+ }
+ return byCollection
+}
+
+/** The collections in the order they are declared: after the ones their first mode aliases. */
+function declarationOrder(graph: SceneGraph, byCollection: Map<string, Variable[]>): string[] {
+ const order: string[] = []
+ const visiting = new Set<string>()
+ const visit = (collectionId: string) => {
+ if (order.includes(collectionId) || visiting.has(collectionId)) return
+ visiting.add(collectionId)
+ const collection = graph.variableCollections.get(collectionId)
+ for (const variable of byCollection.get(collectionId) ?? []) {
+ const target = collection && aliasOf(variable.valuesByMode[collection.defaultModeId])
+ const aliased = target ? graph.variables.get(target) : undefined
+ if (aliased) visit(aliased.collectionId)
+ }
+ order.push(collectionId)
+ }
+ for (const id of byCollection.keys()) visit(id)
+ return order
+}
+
+/**
+ * What an export declares: the variables it can define and still have its code run. A first-mode
+ * value can only name a collection declared before its own, so one that aliases its own
+ * collection, or a later one in a cycle, is written by reference, which keeps the alias; and a
+ * declared value may alias only a declared variable, so one that aliases a reference, in any mode,
+ * is written by reference too.
+ */
+function declaredVariables(graph: SceneGraph, rootIds: readonly string[]) {
+ const included = definableVariables(graph, rootIds)
+ let byCollection = byCollectionOf(graph, included)
+ const order = declarationOrder(graph, byCollection)
+ const declaredEarlier = (variable: Variable) => {
+ const collection = graph.variableCollections.get(variable.collectionId)
+ const target = collection && aliasOf(variable.valuesByMode[collection.defaultModeId])
+ const aliased = target && included.has(target) ? graph.variables.get(target) : undefined
+ return !aliased || order.indexOf(aliased.collectionId) < order.indexOf(variable.collectionId)
+ }
+ const aliasesDeclared = (variable: Variable) =>
+ Object.values(variable.valuesByMode).every((value) => {
+ const target = aliasOf(value)
+ return !target || included.has(target)
+ })
+ for (const variable of [...byCollection.values()].flat()) {
+ if (!declaredEarlier(variable)) included.delete(variable.id)
+ }
+ for (let dropped = 1; dropped > 0;) {
+ const unresolved = [...included].flatMap((id) => {
+ const variable = graph.variables.get(id)
+ return variable && !aliasesDeclared(variable) ? [id] : []
+ })
+ for (const id of unresolved) included.delete(id)
+ dropped = unresolved.length
+ }
+ // What is left is declared only if a layer still uses it, itself or through an alias.
+ const used = new Set<string>()
+ const use = (variableId: string) => {
+ const variable = graph.variables.get(variableId)
+ if (!variable || used.has(variableId) || !included.has(variableId)) return
+ used.add(variableId)
+ for (const value of Object.values(variable.valuesByMode)) {
+ const target = aliasOf(value)
+ if (target) use(target)
+ }
+ }
+ for (const id of boundVariableIds(graph, rootIds)) use(id)
+ for (const id of included) if (!used.has(id)) included.delete(id)
+ byCollection = byCollectionOf(graph, included)
+ return { included, byCollection, order }
+}
+
+/**
+ * Writes the collections the layers use as `defineVars`, with a `defineMode` for each mode after
+ * the first, so the JSX carries its tokens: only the variables it binds and those they alias.
+ * Variables JSX cannot define, such as formulas, and collections whose name is not unique are
+ * written by reference.
+ */
+function definitionExport(graph: SceneGraph, rootIds: readonly string[]): VariableExport {
+ const references = variableReferences(graph)
+ const { included, byCollection, order } = declaredVariables(graph, rootIds)
+
+ const taken = new Set(TAKEN)
+ const defined = new Map<string, DefinedCollection>()
+ for (const collectionId of order) {
+ const collection = graph.variableCollections.get(collectionId)
+ if (!collection || !byCollection.get(collectionId)?.length) continue
+ defined.set(collectionId, {
+ collection,
+ name: handleName(collection.name, taken, 'vars'),
+ variables: byCollection.get(collectionId) ?? [],
+ modes: new Map()
+ })
+ }
+ for (const entry of defined.values()) {
+ for (const mode of modesDefaultFirst(entry.collection).slice(1)) {
+ entry.modes.set(mode.modeId, handleName(mode.name, taken, `${entry.name}Mode`))
+ }
+ }
+
+ const variable = (variableId: string): JSXValue => {
+ const found = graph.variables.get(variableId)
+ const entry = found && included.has(variableId) ? defined.get(found.collectionId) : undefined
+ return entry && found ? new Reference(entry.name, found.name) : references.variable(variableId)
+ }
+ const value = (raw: VariableValue | undefined): JSXValue | undefined => {
+ if (typeof raw === 'number' || typeof raw === 'boolean') return raw
+ if (typeof raw !== 'object') return undefined
+ if ('aliasId' in raw) return variable(raw.aliasId)
+ return 'r' in raw ? formatColor(raw, raw.a) : undefined
+ }
+ const values = (variables: Variable[], modeId: string, base?: string) =>
+ Object.fromEntries(
+ variables.flatMap((item) => {
+ const written = value(item.valuesByMode[modeId])
+ const first = base === undefined ? undefined : value(item.valuesByMode[base])
+ if (written === undefined) return []
+ if (base !== undefined && isEqual(written, first)) return []
+ return [[item.name, written]]
+ })
+ )
+
+ return {
+ variable,
+ mode(collectionId, modeId) {
+ const name = defined.get(collectionId)?.modes.get(modeId)
+ return name ? new Reference(name) : references.mode(collectionId, modeId)
+ },
+ declarations() {
+ // Written as `ref()` declarations are, so the statements read like the JSX after them.
+ const statements: string[] = []
+ const declare = (name: string, value: JSXValue) =>
+ statements.push(`const ${name} = ${jsx.printJSX(valueSyntax(value))}`)
+ for (const entry of defined.values()) {
+ const [first] = modesDefaultFirst(entry.collection)
+ const options = first.name === DEFAULT_MODE_NAME ? undefined : { mode: first.name }
+ const call = helperCall(
+ 'defineVars',
+ entry.collection.name,
+ values(entry.variables, first.modeId),
+ options
+ )
+ declare(entry.name, call)
+ }
+ for (const entry of defined.values()) {
+ const [first] = modesDefaultFirst(entry.collection)
+ for (const [modeId, name] of entry.modes) {
+ const mode = entry.collection.modes.find((item) => item.modeId === modeId)
+ const call = helperCall(
+ 'defineMode',
+ new Reference(entry.name),
+ mode?.name ?? '',
+ values(entry.variables, modeId, first.modeId)
+ )
+ declare(name, call)
+ }
+ }
+ return statements.join('\n')
+ }
+ }
+}
+
+/**
+ * How an export writes variables: with `declare`, as the definitions its JSX carries, otherwise
+ * by reference to the document's own.
+ */
+export function variableExport(
+ graph: SceneGraph,
+ rootIds: readonly string[],
+ declare: boolean
+): VariableExport {
+ return declare ? definitionExport(graph, rootIds) : variableReferences(graph)
+}
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index dcedbd47b..97b65fc72 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -34,6 +34,7 @@ import {
variableModes,
type LayerContext
} from './variables/graph'
+import { paintProps } from './variables/props'
export interface RenderResult {
id: string
@@ -125,12 +126,8 @@ function preparePropsForRender(
})
}
- for (const key of ['bg', 'fill', 'background', 'backgroundColor']) {
- bindVariableProp(graph, props, bindings, key, 'fills/0/color', layer)
- }
- if (isText) bindVariableProp(graph, props, bindings, 'color', 'fills/0/color', layer)
- for (const key of ['stroke', 'border', 'borderColor']) {
- bindVariableProp(graph, props, bindings, key, 'strokes/0/color', layer)
+ for (const { prop, fields } of paintProps({ text: isText })) {
+ bindVariableProp(graph, props, bindings, prop, fields[0], layer)
}
if (isObjectRecord(props.style)) {
diff --git a/packages/design-jsx/src/scalar-bindings.ts b/packages/design-jsx/src/scalar-bindings.ts
index 9b1550de4..f1273e16d 100644
--- a/packages/design-jsx/src/scalar-bindings.ts
+++ b/packages/design-jsx/src/scalar-bindings.ts
@@ -2,27 +2,7 @@ import type { SceneGraph, VariableLiteral } from '@open-pencil/scene-graph'
import { isVariable } from './variables'
import { requireVariableId } from './variables/graph'
-
-// Shorthands precede their longhands, matching propsToOverrides precedence.
-const PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']
-const SCALAR_PROPS: ReadonlyArray<readonly [string, readonly string[]]> = [
- ['w', ['width']],
- ['h', ['height']],
- ['p', PADDING_FIELDS],
- ['px', ['paddingLeft', 'paddingRight']],
- ['py', ['paddingTop', 'paddingBottom']],
- ['pt', ['paddingTop']],
- ['pr', ['paddingRight']],
- ['pb', ['paddingBottom']],
- ['pl', ['paddingLeft']],
- ['rounded', ['cornerRadius']],
- ['roundedTL', ['topLeftRadius']],
- ['roundedTR', ['topRightRadius']],
- ['roundedBL', ['bottomLeftRadius']],
- ['roundedBR', ['bottomRightRadius']],
- ['strokeWidth', ['strokeWeight']],
- ['opacity', ['opacity']]
-]
+import { scalarProps } from './variables/props'
/** Resolve numeric props before sizing inference; retain real graph bindings afterward. */
export function prepareScalarBindings(
@@ -32,28 +12,9 @@ export function prepareScalarBindings(
isText: boolean,
resolve: (variableId: string) => VariableLiteral | undefined
): void {
- const entries = [...SCALAR_PROPS]
+ const entries = scalarProps({ text: isText, grid: !!props.grid, wrap: !!props.wrap })
const scalarBindings = new Map<string, string>()
- if (props.grid) {
- // Existing grid authoring gives gap precedence over the axis-specific props.
- entries.push(
- ['columnGap', ['gridColumnGap']],
- ['rowGap', ['gridRowGap']],
- ['gap', ['gridColumnGap', 'gridRowGap']]
- )
- } else {
- entries.push(['gap', ['itemSpacing']])
- if (props.wrap) entries.push(['rowGap', ['counterAxisSpacing']])
- }
- if (isText) {
- entries.push(
- [props.size !== undefined ? 'size' : 'fontSize', ['fontSize']],
- ['lineHeight', ['lineHeight']],
- ['letterSpacing', ['letterSpacing']]
- )
- }
-
- for (const [key, fields] of entries) {
+ for (const { prop: key, fields } of entries) {
const value = props[key]
if (value === undefined) continue
// A literal longhand must also override a bound shorthand on that edge.
diff --git a/packages/design-jsx/src/variables/graph.ts b/packages/design-jsx/src/variables/graph.ts
index 8f73bace6..632b9f66f 100644
--- a/packages/design-jsx/src/variables/graph.ts
+++ b/packages/design-jsx/src/variables/graph.ts
@@ -53,7 +53,7 @@ function collectDefinitions(
}
/** The one collection with this name; a name several collections share is an error. */
-function collectionNamed(graph: SceneGraph, name: string): VariableCollection | undefined {
+export function collectionNamed(graph: SceneGraph, name: string): VariableCollection | undefined {
const matches = [...graph.variableCollections.values()].filter((item) => item.name === name)
if (matches.length > 1)
throw new Error(`More than one variable collection is named ${name}; rename one to use it`)
diff --git a/packages/design-jsx/src/variables/props.ts b/packages/design-jsx/src/variables/props.ts
new file mode 100644
index 000000000..19a51c963
--- /dev/null
+++ b/packages/design-jsx/src/variables/props.ts
@@ -0,0 +1,77 @@
+/** What decides which props bind a variable on a layer. */
+export interface BindingContext {
+ text: boolean
+ grid: boolean
+ wrap: boolean
+}
+
+/** A prop a variable binds through, and the fields it sets. */
+export interface BoundProp {
+ prop: string
+ fields: readonly string[]
+}
+
+export const PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']
+
+/**
+ * The number props a FLOAT variable binds, in the order rendering reads them: shorthands before
+ * their longhands, as `propsToOverrides` gives them precedence, so a literal longhand also
+ * overrides a bound shorthand on that edge.
+ */
+export function scalarProps({ text, grid, wrap }: BindingContext): BoundProp[] {
+ const props: BoundProp[] = [
+ { prop: 'w', fields: ['width'] },
+ { prop: 'h', fields: ['height'] },
+ { prop: 'p', fields: PADDING_FIELDS },
+ { prop: 'px', fields: ['paddingLeft', 'paddingRight'] },
+ { prop: 'py', fields: ['paddingTop', 'paddingBottom'] },
+ { prop: 'pt', fields: ['paddingTop'] },
+ { prop: 'pr', fields: ['paddingRight'] },
+ { prop: 'pb', fields: ['paddingBottom'] },
+ { prop: 'pl', fields: ['paddingLeft'] },
+ { prop: 'rounded', fields: ['cornerRadius'] },
+ { prop: 'roundedTL', fields: ['topLeftRadius'] },
+ { prop: 'roundedTR', fields: ['topRightRadius'] },
+ { prop: 'roundedBL', fields: ['bottomLeftRadius'] },
+ { prop: 'roundedBR', fields: ['bottomRightRadius'] },
+ { prop: 'strokeWidth', fields: ['strokeWeight'] },
+ { prop: 'opacity', fields: ['opacity'] }
+ ]
+ if (grid) {
+ // Grid authoring gives `gap` precedence over the axis-specific props.
+ props.push(
+ { prop: 'columnGap', fields: ['gridColumnGap'] },
+ { prop: 'rowGap', fields: ['gridRowGap'] },
+ { prop: 'gap', fields: ['gridColumnGap', 'gridRowGap'] }
+ )
+ } else {
+ props.push({ prop: 'gap', fields: ['itemSpacing'] })
+ if (wrap) props.push({ prop: 'rowGap', fields: ['counterAxisSpacing'] })
+ }
+ if (text) {
+ props.push(
+ { prop: 'fontSize', fields: ['fontSize'] },
+ // `size` is the short name, so it wins over `fontSize`, as it does for a literal.
+ { prop: 'size', fields: ['fontSize'] },
+ { prop: 'lineHeight', fields: ['lineHeight'] },
+ { prop: 'letterSpacing', fields: ['letterSpacing'] }
+ )
+ }
+ return props
+}
+
+/** The paint props a COLOR variable binds: the first fill's colour, or the first stroke's. */
+export function paintProps({ text }: Pick<BindingContext, 'text'>): BoundProp[] {
+ const fill = ['fills/0/color']
+ const stroke = ['strokes/0/color']
+ return [
+ { prop: 'bg', fields: fill },
+ { prop: 'fill', fields: fill },
+ { prop: 'background', fields: fill },
+ { prop: 'backgroundColor', fields: fill },
+ ...(text ? [{ prop: 'color', fields: fill }] : []),
+ { prop: 'stroke', fields: stroke },
+ { prop: 'border', fields: stroke },
+ { prop: 'borderColor', fields: stroke }
+ ]
+}
diff --git a/packages/emit/src/estree.ts b/packages/emit/src/estree.ts
index 6ec5e4213..eb49036ff 100644
--- a/packages/emit/src/estree.ts
+++ b/packages/emit/src/estree.ts
@@ -139,6 +139,18 @@ export function object(entries: (readonly [string, SyntaxNode])[]): SyntaxNode {
export const array = (elements: SyntaxNode[]): SyntaxNode => ({ type: 'ArrayExpression', elements })
+/** `object.key`, or `object['key']` for a key that is not an identifier. */
+export function member(object: SyntaxNode, key: string): SyntaxNode {
+ const computed = !/^[A-Za-z_$][\w$]*$/.test(key)
+ return {
+ type: 'MemberExpression',
+ object,
+ property: computed ? string(key) : identifier(key),
+ computed,
+ optional: false
+ }
+}
+
/**
* A value read from JSON written as source: strings, finite numbers, booleans, null, and lists
* and objects of them. Anything else, such as a function or an infinite number, is null.