Skip to content

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

feat!: define variables, modes, and component properties in design JSX (#1518)

Danila Poyarkov998e369c287e
diff --git a/changes/1518/added.md b/changes/1518/added.md
new file mode 100644
index 000000000..e759313c9
--- /dev/null
+++ b/changes/1518/added.md
@@ -0,0 +1,3 @@
+- Design JSX defines variables: `defineVars` adds a collection to the file's variables table, `defineMode` adds a mode to it, and a variable used as a value makes an alias. Running the same JSX again updates them instead of adding copies, and `designVar(collection, name)` names a variable that several collections share.
+- Design JSX pins a layer's variable modes with `mode`, as the Appearance panel does, and exports them; `<Icon color>` takes a variable.
+- Design JSX exposes a nested instance's properties with `exposed`, and an outer instance sets that instance's variant and properties by its layer name, as in `Action={{ Label: 'Save' }}`.
diff --git a/changes/1518/breaking.md b/changes/1518/breaking.md
new file mode 100644
index 000000000..e3e58258b
--- /dev/null
+++ b/changes/1518/breaking.md
@@ -0,0 +1,2 @@
+- Design JSX binds component properties with `property(name, default)` in a layer's `text`, `visible`, or an instance's `of`, creating them on the component; `propertyRefs` and `properties` on `<Component>` and `<ComponentSet>` are removed.
+- Design JSX's `defineVars(collection, values, options)` defines a collection instead of grouping references, and the `VarDef` type is removed. `designVar` takes a variable's name or ID, or its collection and name as `designVar('Theme', 'Line')`, without a fallback value; a missing, unresolvable, or ambiguous variable is an error.
diff --git a/changes/1518/fixed.md b/changes/1518/fixed.md
new file mode 100644
index 000000000..4f851fd66
--- /dev/null
+++ b/changes/1518/fixed.md
@@ -0,0 +1 @@
+- The code panel runs `shader()` paints, which failed there with "Unknown Design JSX helper".
diff --git a/oxlint.json b/oxlint.json
index 455e3f24c..1b9a992ec 100644
--- a/oxlint.json
+++ b/oxlint.json
@@ -619,11 +619,22 @@
"files": [
"packages/core/src/io/formats/fig/export/index.ts",
"packages/core/src/io/formats/fig/export/worker.ts",
- "packages/core/src/kiwi/fig/parse/worker.ts"
+ "packages/core/src/kiwi/fig/parse/worker.ts",
+ "src/app/code/sandbox/frame.ts",
+ "src/app/code/sandbox/worker/index.ts"
],
"rules": {
"unicorn/require-post-message-target-origin": "off"
}
+ },
+ {
+ "files": [
+ "src/app/code/sandbox/evaluate.ts",
+ "src/app/code/sandbox/frame.ts"
+ ],
+ "rules": {
+ "import/default": "off"
+ }
}
],
"ignorePatterns": [
diff --git a/packages/core/src/editor/history/document-change.ts b/packages/core/src/editor/history/document-change.ts
index 924456c06..5f8926667 100644
--- a/packages/core/src/editor/history/document-change.ts
+++ b/packages/core/src/editor/history/document-change.ts
@@ -216,25 +216,31 @@ function diffRecords<T>(previous: Map<string, T>, current: Map<string, T>): Reco
}
/** Restores records in place where they exist, as views may hold them, as atomic tools do. */
+/** Make `target` hold `value` under `id`, or nothing; an existing record is kept and rewritten. */
+export function writeRecord<T extends object>(
+ target: Map<string, T>,
+ id: string,
+ value: T | null
+): void {
+ const existing = target.get(id)
+ if (!value) {
+ target.delete(id)
+ } else if (existing) {
+ for (const key of Object.keys(existing)) {
+ if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)
+ }
+ Object.assign(existing, structuredClone(value))
+ } else {
+ target.set(id, structuredClone(value))
+ }
+}
+
function restoreRecords<T extends object>(
target: Map<string, T>,
changes: RecordChange<T>[],
side: Side
): void {
- for (const change of changes) {
- const value = change[side]
- const existing = target.get(change.id)
- if (!value) {
- target.delete(change.id)
- } else if (existing) {
- for (const key of Object.keys(existing)) {
- if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)
- }
- Object.assign(existing, structuredClone(value))
- } else {
- target.set(change.id, structuredClone(value))
- }
- }
+ for (const change of changes) writeRecord(target, change.id, change[side])
}
/**
diff --git a/packages/core/src/editor/history/snapshot/graph.ts b/packages/core/src/editor/history/snapshot/graph.ts
index fd57dab97..01749fb9a 100644
--- a/packages/core/src/editor/history/snapshot/graph.ts
+++ b/packages/core/src/editor/history/snapshot/graph.ts
@@ -24,10 +24,12 @@ export function graphFromPageSnapshot(
snapshot: PageSnapshot
): SceneGraph | null {
// `snapshotPage` records the page first.
- const page = snapshot.values().next().value
+ const page = snapshot.nodes.values().next().value
if (!page || !source.getNode(page.id)) return null
const graph = pageContext(source, page.id, [])
- for (const node of snapshot.values()) graph.nodes.set(node.id, structuredClone(node))
+ graph.variables = structuredClone(snapshot.variables)
+ graph.variableCollections = structuredClone(snapshot.collections)
+ for (const node of snapshot.nodes.values()) graph.nodes.set(node.id, structuredClone(node))
graph.clearAbsPosCache()
return graph
}
diff --git a/packages/core/src/editor/history/snapshot/page.ts b/packages/core/src/editor/history/snapshot/page.ts
index 40048fddf..0c065433d 100644
--- a/packages/core/src/editor/history/snapshot/page.ts
+++ b/packages/core/src/editor/history/snapshot/page.ts
@@ -1,35 +1,80 @@
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { isEqual, uniq } from 'es-toolkit'
+import type { SceneGraph, SceneNode, Variable, VariableCollection } from '@open-pencil/scene-graph'
+
+import { writeRecord } from '#core/editor/history/document-change'
import type { EditorContext } from '#core/editor/types'
import { computeAllLayouts } from '#core/layout'
+import { reconcileVariableLayouts } from '#core/layout/variables'
-export type PageSnapshot = Map<string, SceneNode>
+/**
+ * A page's layers, page first, and the document's variables, which the layers bind. Restoring
+ * puts both back as they were: the layers of that page, and every variable and collection, as
+ * undo of an edit that defined variables needs. Snapshots stay whole so coalesced undo entries,
+ * which keep the first inverse and the last forward, still restore a consistent state.
+ */
+export interface PageSnapshot {
+ nodes: Map<string, SceneNode>
+ variables: Map<string, Variable>
+ collections: Map<string, VariableCollection>
+}
export function snapshotPage(graph: SceneGraph, pageId: string): PageSnapshot {
- const snapshot: PageSnapshot = new Map()
+ const nodes = new Map<string, SceneNode>()
const walk = (id: string) => {
const node = graph.getNode(id)
if (!node) return
- snapshot.set(id, structuredClone(node))
+ nodes.set(id, structuredClone(node))
for (const childId of node.childIds) walk(childId)
}
walk(pageId)
- return snapshot
+ return {
+ nodes,
+ variables: structuredClone(graph.variables),
+ collections: structuredClone(graph.variableCollections)
+ }
+}
+
+/**
+ * The variables restoring `snapshot` changes: those whose record differs from the saved one,
+ * and those of a collection that does, whose modes they resolve in.
+ */
+function changedVariables(graph: SceneGraph, snapshot: PageSnapshot): string[] {
+ const differs = <T>(current: Map<string, T>, saved: Map<string, T>) =>
+ uniq([...current.keys(), ...saved.keys()]).filter(
+ (id) => !isEqual(current.get(id), saved.get(id))
+ )
+ const collections = new Set(differs(graph.variableCollections, snapshot.collections))
+ const inChangedCollection = [...graph.variables.values(), ...snapshot.variables.values()]
+ .filter((variable) => collections.has(variable.collectionId))
+ .map((variable) => variable.id)
+ return [...differs(graph.variables, snapshot.variables), ...inChangedCollection]
+}
+
+/** Make `target` hold exactly the records of `saved`. */
+function restoreRecords<T extends object>(target: Map<string, T>, saved: Map<string, T>): void {
+ for (const id of target.keys()) if (!saved.has(id)) writeRecord(target, id, null)
+ for (const [id, value] of saved) writeRecord(target, id, value)
}
-/** Restore the page the snapshot was taken of, whichever page is on screen. */
+/** Restore the page the snapshot was taken of, whichever page is on screen, and its variables. */
export function restorePageFromSnapshot(ctx: EditorContext, snapshot: PageSnapshot): void {
// `snapshotPage` records the page first.
- const pageSnap = snapshot.values().next().value
+ const pageSnap = snapshot.nodes.values().next().value
if (!pageSnap) return
const page = ctx.graph.getNode(pageSnap.id)
if (!page) return
+ const variables = changedVariables(ctx.graph, snapshot)
+ restoreRecords(ctx.graph.variableCollections, snapshot.collections)
+ restoreRecords(ctx.graph.variables, snapshot.variables)
for (const childId of page.childIds.slice()) ctx.graph.deleteNode(childId)
- restoreChildren(ctx.graph, snapshot, page.id, pageSnap.childIds)
+ restoreChildren(ctx.graph, snapshot.nodes, page.id, pageSnap.childIds)
ctx.graph.clearAbsPosCache()
computeAllLayouts(ctx.graph, page.id)
+ // Layers on other pages that bind a restored variable take its restored value.
+ if (variables.length > 0) reconcileVariableLayouts(ctx.graph, { variables })
if (page.id === ctx.state.currentPageId) {
ctx.setSelectedIds(new Set())
ctx.state.hoveredNodeId = null
@@ -39,7 +84,7 @@ export function restorePageFromSnapshot(ctx: EditorContext, snapshot: PageSnapsh
function restoreChildren(
graph: SceneGraph,
- snapshot: PageSnapshot,
+ snapshot: PageSnapshot['nodes'],
parentId: string,
childIds: string[]
): void {
diff --git a/packages/core/tests/design-jsx/connectors.test.ts b/packages/core/tests/design-jsx/connectors.test.ts
index 5cf890c6b..a0be7c2a7 100644
--- a/packages/core/tests/design-jsx/connectors.test.ts
+++ b/packages/core/tests/design-jsx/connectors.test.ts
@@ -301,7 +301,7 @@ return <Frame name="Flow" w={800} h={400}>
`<Frame name="Flow" w={800} h={400}>
<Frame name="A" x={0} y={0} w={100} h={100} />
<Frame name="B" x={400} y={0} w={100} h={100} />
- <Connector from="A" to="B" stroke={designVar('var-line', '#FF0000')} />
+ <Connector from="A" to="B" stroke={designVar('var-line')} />
</Frame>`
)
const connector = getNodeOrThrow(graph, graph.getChildren(result.id)[2].id)
diff --git a/packages/core/tests/design-jsx/instance-properties.test.ts b/packages/core/tests/design-jsx/instance-properties.test.ts
index 37ff76004..b1560706d 100644
--- a/packages/core/tests/design-jsx/instance-properties.test.ts
+++ b/packages/core/tests/design-jsx/instance-properties.test.ts
@@ -2,22 +2,21 @@ import { expect, test } from 'bun:test'
import { renderJSX, renderTree } from '@open-pencil/core/design-jsx'
import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
-import { Component, Instance, Text } from '@open-pencil/design-jsx'
+import { Component, Instance, Text, property } from '@open-pencil/design-jsx'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, type ComponentPropertyDefinition } from '@open-pencil/scene-graph'
const CARD = `
-<ComponentSet name="Card" properties={[
- { id: "title", name: "Title", type: "TEXT", defaultValue: "Default title" },
- { id: "badge", name: "Badge", type: "BOOLEAN", defaultValue: "true" }
-]}>
+const title = property("Title", "Default title")
+const badge = property("Badge", true)
+return <ComponentSet name="Card">
<Component name="state=default">
- <Text propertyRefs={[{ propertyId: "title", field: "TEXT" }]}>Default title</Text>
- <Text propertyRefs={[{ propertyId: "badge", field: "VISIBLE" }]}>New</Text>
+ <Text text={title} />
+ <Text visible={badge}>New</Text>
</Component>
<Component name="state=selected">
- <Text propertyRefs={[{ propertyId: "title", field: "TEXT" }]}>Default title</Text>
- <Text propertyRefs={[{ propertyId: "badge", field: "VISIBLE" }]}>New</Text>
+ <Text text={title} />
+ <Text visible={badge}>New</Text>
</Component>
</ComponentSet>`
@@ -51,7 +50,6 @@ test('assigns properties by ID or by name', async () => {
const set = [...graph.getAllNodes()].find((node) => node.type === 'COMPONENT_SET')
const title = set?.componentPropertyDefinitions.find((item) => item.name === 'Title')
if (!title) throw new Error('Missing Title property')
- expect(title.id).not.toBe('title')
for (const key of [title.id, 'Title']) {
const [instance] = await renderJSX(
@@ -65,22 +63,26 @@ test('assigns properties by ID or by name', async () => {
).rejects.toThrow('Unknown component property: title')
})
-test('properties prefers an ID; a prop always names the property', async () => {
- const graph = new SceneGraph()
+/** A component with property definitions as a file can hold them, IDs and names chosen. */
+async function noteWith(graph: SceneGraph, definitions: ComponentPropertyDefinition[]) {
const component = await renderTree(
graph,
- Component({
- name: 'Note',
- properties: [
- { id: 'label', name: 'Title', type: 'TEXT', defaultValue: 'Label' },
- { id: 'Title', name: 'Heading', type: 'TEXT', defaultValue: 'Heading' }
- ],
- children: Text({
- children: 'Label',
- propertyRefs: [{ propertyId: 'label', field: 'TEXT' }]
- })
- })
+ Component({ name: 'Note', children: Text({ text: property('Label', 'Label') }) })
)
+ const [text] = graph.getChildren(component.id)
+ graph.updateNode(component.id, { componentPropertyDefinitions: definitions })
+ graph.updateNode(text.id, {
+ componentPropertyReferences: [{ propertyId: definitions[0].id, field: 'TEXT' }]
+ })
+ return component
+}
+
+test('properties prefers an ID; a prop always names the property', async () => {
+ const graph = new SceneGraph()
+ const component = await noteWith(graph, [
+ { id: 'label', name: 'Title', type: 'TEXT', defaultValue: 'Label' },
+ { id: 'Title', name: 'Heading', type: 'TEXT', defaultValue: 'Heading' }
+ ])
const instance = await renderTree(
graph,
Instance({ of: component.id, properties: { Title: 'Changed' } })
@@ -95,16 +97,10 @@ test('properties prefers an ID; a prop always names the property', async () => {
test('rejects a property name that more than one property has', async () => {
const graph = new SceneGraph()
- const component = await renderTree(
- graph,
- Component({
- name: 'Note',
- properties: [
- { id: 'a', name: 'Title', type: 'TEXT', defaultValue: 'A' },
- { id: 'b', name: 'Title', type: 'TEXT', defaultValue: 'B' }
- ]
- })
- )
+ const component = await noteWith(graph, [
+ { id: 'a', name: 'Title', type: 'TEXT', defaultValue: 'A' },
+ { id: 'b', name: 'Title', type: 'TEXT', defaultValue: 'B' }
+ ])
await expect(renderTree(graph, Instance({ of: component.id, Title: 'Changed' }))).rejects.toThrow(
'Component property name Title is ambiguous; use one of the IDs: a, b'
)
diff --git a/packages/core/tests/design-jsx/stickies.test.ts b/packages/core/tests/design-jsx/stickies.test.ts
index dadfb8b3c..2d9d49efa 100644
--- a/packages/core/tests/design-jsx/stickies.test.ts
+++ b/packages/core/tests/design-jsx/stickies.test.ts
@@ -98,7 +98,7 @@ describe('sticky notes in design JSX', () => {
const [result] = await renderJSX(
graph,
`<Frame name="Board" flex="col" w={600} h={600}>
- <Sticky opacity={designVar('var-faded', 0.5)}>Faded</Sticky>
+ <Sticky opacity={designVar('var-faded')}>Faded</Sticky>
<Sticky x={300} y={40}>Placed</Sticky>
</Frame>`
)
diff --git a/packages/core/tests/design-jsx/variables.test.ts b/packages/core/tests/design-jsx/variables.test.ts
new file mode 100644
index 000000000..c29ed2b85
--- /dev/null
+++ b/packages/core/tests/design-jsx/variables.test.ts
@@ -0,0 +1,222 @@
+import { describe, expect, test } from 'bun:test'
+
+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 { SceneGraph, type VariableCollection } from '@open-pencil/scene-graph'
+
+const THEME = `
+const palette = defineVars('Palette', { 'Gray/900': '#111111', 'Gray/50': '#FAFAFA' })
+const theme = defineVars('Theme', { Page: palette['Gray/50'], Text: palette['Gray/900'], Radius: 12 }, { mode: 'Light' })
+const dark = defineMode(theme, 'Dark', { Page: palette['Gray/900'], Text: palette['Gray/50'] })
+return <Frame name="Card" mode={dark} bg={theme.Page} rounded={theme.Radius} w={100} h={100} />`
+
+function collectionNamed(graph: SceneGraph, name: string): VariableCollection {
+ const collection = [...graph.variableCollections.values()].find((item) => item.name === name)
+ if (!collection) throw new Error(`Missing collection ${name}`)
+ return collection
+}
+
+function table(graph: SceneGraph, name: string) {
+ const collection = collectionNamed(graph, name)
+ return Object.fromEntries(
+ collection.variableIds.map((id) => {
+ const variable = graph.variables.get(id)
+ if (!variable) throw new Error(`Missing variable ${id}`)
+ const values = collection.modes.map(({ modeId, name: mode }) => {
+ const value = variable.valuesByMode[modeId]
+ const shown =
+ typeof value === 'object' && 'aliasId' in value
+ ? `→ ${graph.variables.get(value.aliasId)?.name}`
+ : value
+ return [mode, shown]
+ })
+ return [variable.name, { type: variable.type, ...Object.fromEntries(values) }]
+ })
+ )
+}
+
+describe('Design JSX variable definitions', () => {
+ test('create collections, modes, and aliases in the variables table', async () => {
+ const graph = new SceneGraph()
+ await renderJSX(graph, THEME)
+ const theme = collectionNamed(graph, 'Theme')
+ expect(theme.modes.map((mode) => mode.name)).toEqual(['Light', 'Dark'])
+ expect(theme.defaultModeId).toBe(theme.modes[0].modeId)
+ expect(collectionNamed(graph, 'Palette').modes.map((mode) => mode.name)).toEqual(['Mode 1'])
+ expect(table(graph, 'Theme')).toEqual({
+ Page: { type: 'COLOR', Light: '→ Gray/50', Dark: '→ Gray/900' },
+ Text: { type: 'COLOR', Light: '→ Gray/900', Dark: '→ Gray/50' },
+ Radius: { type: 'FLOAT', Light: 12, Dark: 12 }
+ })
+ })
+
+ test('pin the mode on the layer and bind its fields with the values of that mode', async () => {
+ const graph = new SceneGraph()
+ const [card] = await renderJSX(graph, THEME)
+ const node = graph.getNode(card.id)
+ const theme = collectionNamed(graph, 'Theme')
+ expect(node?.variableModes).toEqual({ [theme.id]: theme.modes[1].modeId })
+ expect(node?.fills[0]?.color).toMatchObject({ r: 0x11 / 255, g: 0x11 / 255, b: 0x11 / 255 })
+ expect(node?.cornerRadius).toBe(12)
+ const page = theme.variableIds
+ .map((id) => graph.variables.get(id))
+ .find((item) => item?.name === 'Page')
+ expect(node?.boundVariables['fills/0/color']).toBe(page?.id)
+ })
+
+ test('running the JSX again updates the collections it defined instead of adding new ones', async () => {
+ const graph = new SceneGraph()
+ await renderJSX(graph, THEME)
+ await renderJSX(graph, THEME.replace('Radius: 12', 'Radius: 16'))
+ expect([...graph.variableCollections.values()].map((item) => item.name)).toEqual([
+ 'Palette',
+ 'Theme'
+ ])
+ expect(graph.variables.size).toBe(5)
+ expect(table(graph, 'Theme').Radius).toEqual({ type: 'FLOAT', Light: 16, Dark: 16 })
+ })
+
+ test('binding one variable brings its whole collection, unbound modes included', async () => {
+ const graph = new SceneGraph()
+ const space = defineVars('Spacing', { Small: 4, Large: 16 }, { mode: 'Comfortable' })
+ defineMode(space, 'Compact', { Large: 8 })
+ await renderTree(graph, Frame({ p: space.Large, children: Rectangle({ w: 10, h: 10 }) }))
+ expect(table(graph, 'Spacing')).toEqual({
+ Small: { type: 'FLOAT', Comfortable: 4, Compact: 4 },
+ Large: { type: 'FLOAT', Comfortable: 16, Compact: 8 }
+ })
+ })
+
+ test('reject values the variables cannot hold, and modes and names that do not exist', async () => {
+ const graph = new SceneGraph()
+ const invalid = defineVars('Broken', { Ink: 'not a color' })
+ await expect(renderTree(graph, Frame({ bg: invalid.Ink }))).rejects.toThrow(
+ 'Variable Ink has "not a color", which is not a color'
+ )
+ const mixed = defineVars('Mixed', { Size: 4 })
+ defineMode(mixed, 'Loud', { Size: '#FF0000' })
+ await expect(renderTree(graph, Frame({ p: mixed.Size }))).rejects.toThrow(
+ 'Variable Size mixes FLOAT with COLOR values'
+ )
+ const theme = defineVars('Shades', { Page: '#FFFFFF' })
+ expect(() => defineMode(theme, 'Dark', { Missing: '#000000' })).toThrow(
+ 'Collection Shades has no variable named Missing'
+ )
+ defineMode(theme, 'Dark', {})
+ expect(() => defineMode(theme, 'Dark', {})).toThrow('already has a mode named Dark')
+ await expect(renderJSX(graph, `<Frame mode={designMode('Nope', 'Dark')} />`)).rejects.toThrow(
+ 'Unknown variable collection: Nope'
+ )
+ })
+})
+
+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)
+})
+
+test('artwork drawn in a variable binds its paths and resolves in its own mode', async () => {
+ const graph = new SceneGraph()
+ const [svg] = await renderJSX(
+ graph,
+ `const ink = defineVars('Ink', { Line: '#000000' }, { mode: 'Light' })
+const dark = defineMode(ink, 'Dark', { Line: '#FFFFFF' })
+return <svg mode={dark} color={ink.Line} w={10} h={10} body="<path d='M0 0h10v10H0z' fill='currentColor'/>" />`
+ )
+ const ink = collectionNamed(graph, 'Ink')
+ const line = ink.variableIds[0]
+ const node = graph.getNode(svg.id)
+ expect(node?.variableModes).toEqual({ [ink.id]: ink.modes[1].modeId })
+ const paths = graph.getChildren(svg.id).flatMap((child) => [child, ...graph.getChildren(child.id)])
+ const painted = paths.find((child) => child.fills[0]?.type === 'SOLID')
+ expect(painted?.boundVariables['fills/0/color']).toBe(line)
+ expect(painted?.fills[0]?.color).toMatchObject({ r: 1, g: 1, b: 1 })
+})
+
+test('a variable whose value cannot be resolved is an error, not a dropped paint', async () => {
+ const graph = new SceneGraph()
+ const collection = graph.createCollection('Loop')
+ const a = graph.createVariable('A', 'COLOR', collection.id)
+ const b = graph.createVariable('B', 'COLOR', collection.id)
+ a.valuesByMode[collection.defaultModeId] = { aliasId: b.id }
+ b.valuesByMode[collection.defaultModeId] = { aliasId: a.id }
+ await expect(renderJSX(graph, `<Frame bg={designVar('A')} />`)).rejects.toThrow(
+ 'Cannot resolve variable A for bg'
+ )
+ const size = graph.createCollection('Size')
+ graph.createVariable('Gap', 'FLOAT', size.id, 4)
+ for (const name of ['A', 'Gap']) {
+ await expect(
+ renderJSX(graph, `<svg color={designVar('${name}')} body="<path d='M0 0h1v1H0z'/>" />`)
+ ).rejects.toThrow(`Cannot resolve color variable ${name} for color`)
+ }
+})
+
+test('designVar names a variable by collection when several collections share its name', async () => {
+ const graph = new SceneGraph()
+ await renderJSX(graph, THEME)
+ await renderJSX(graph, `const d = defineVars('Density', { Page: 8 }); return <Frame p={d.Page} />`)
+ await expect(renderJSX(graph, `<Frame bg={designVar('Page')} />`)).rejects.toThrow(
+ "Variable name Page is in more than one collection; name one, as in designVar('Theme', 'Page')"
+ )
+ await expect(renderJSX(graph, `<Frame bg={designVar('Theme', 'Missing')} />`)).rejects.toThrow(
+ 'Unknown variable Missing in Theme'
+ )
+ const [frame] = await renderJSX(
+ graph,
+ `<Frame bg={designVar('Theme', 'Page')} p={designVar('Density', 'Page')} />`
+ )
+ const node = graph.getNode(frame.id)
+ const id = (collection: string) => {
+ const owner = collectionNamed(graph, collection)
+ return owner.variableIds.find((item) => graph.variables.get(item)?.name === 'Page')
+ }
+ 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 [copy] = await renderJSX(graph, exported)
+ expect(graph.getNode(copy.id)?.boundVariables).toEqual(node?.boundVariables)
+})
+
+test('a collection name several collections share is an error, not the first of them', async () => {
+ const graph = new SceneGraph()
+ for (const _ of [0, 1]) graph.createVariable('Ink', 'COLOR', graph.createCollection('Twin').id)
+ for (const jsx of [
+ `<Frame bg={designVar('Twin', 'Ink')} />`,
+ `<Frame mode={designMode('Twin', 'Mode 1')} />`
+ ]) {
+ await expect(renderJSX(graph, jsx)).rejects.toThrow(
+ 'More than one variable collection is named Twin; rename one to use it'
+ )
+ }
+ // Export names such a collection by its ID, which renders back into the same mode.
+ const twin = expectDefined([...graph.variableCollections.values()].at(-1))
+ const [frame] = await renderJSX(graph, '<Frame w={10} h={10} />')
+ graph.updateNode(frame.id, { variableModes: { [twin.id]: twin.defaultModeId } })
+ const exported = sceneNodeToJSX(frame.id, graph)
+ expect(exported).toContain(`mode={designMode("${twin.id}", "Mode 1")}`)
+ const [copy] = await renderJSX(graph, exported)
+ expect(graph.getNode(copy.id)?.variableModes).toEqual({ [twin.id]: twin.defaultModeId })
+})
+
+test('a sticky note pins its mode and reads its values in it, as any layer does', async () => {
+ const graph = new SceneGraph()
+ const [board] = await renderJSX(
+ graph,
+ `const fade = defineVars('Fade', { Note: 1 }, { mode: 'Light' })
+const dark = defineMode(fade, 'Dark', { Note: 0.5 })
+return <Frame name="Board" w={400} h={400}><Sticky mode={dark} opacity={fade.Note}>Hi</Sticky></Frame>`
+ )
+ const [sticky] = graph.getChildren(board.id)
+ const fade = collectionNamed(graph, 'Fade')
+ expect(sticky.variableModes).toEqual({ [fade.id]: fade.modes[1].modeId })
+ expect(sticky.opacity).toBe(0.5)
+})
diff --git a/packages/core/tests/editor/history/snapshot-graph.test.ts b/packages/core/tests/editor/history/snapshot-graph.test.ts
index 6f2142d69..acd2987c5 100644
--- a/packages/core/tests/editor/history/snapshot-graph.test.ts
+++ b/packages/core/tests/editor/history/snapshot-graph.test.ts
@@ -30,6 +30,42 @@ describe('page snapshot graphs', () => {
expect(editor.graph.getNode(label.id)?.text).toBe('Changed')
})
+ test('restores and rebuilds the variables the page had, keeping live records in place', () => {
+ const { editor, pageId } = setup()
+ const kept = editor.graph.createCollection('Kept')
+ const before = editor.snapshotPage(pageId)
+ const keptRecord = editor.graph.variableCollections.get(kept.id)
+ editor.graph.renameMode(kept.id, kept.defaultModeId, 'Renamed')
+ const added = editor.graph.createCollection('Added')
+ editor.graph.createVariable('Ink', 'COLOR', added.id)
+
+ const past = expectDefined(graphFromPageSnapshot(editor.graph, before), 'past graph')
+ expect([...past.variableCollections.values()].map((item) => item.name)).toEqual(['Kept'])
+
+ editor.restorePageFromSnapshot(before)
+ expect([...editor.graph.variableCollections.values()].map((item) => item.name)).toEqual([
+ 'Kept'
+ ])
+ expect(editor.graph.variables.size).toBe(0)
+ expect(editor.graph.variableCollections.get(kept.id)).toBe(keptRecord)
+ expect(keptRecord?.modes[0].name).toBe('Mode 1')
+ })
+
+ test('gives layers on other pages the values of the variables it restores', () => {
+ const { editor, pageId } = setup()
+ const collection = editor.graph.createCollection('Shape')
+ const radius = editor.graph.createVariable('Radius', 'FLOAT', collection.id, 12)
+ const other = editor.graph.addPage('Other')
+ const tile = editor.graph.createNode('FRAME', other.id, { name: 'Tile', cornerRadius: 12 })
+ editor.graph.bindVariable(tile.id, 'cornerRadius', radius.id)
+ const before = editor.snapshotPage(pageId)
+ editor.updateVariableValue(radius.id, collection.defaultModeId, 16)
+ expect(editor.graph.getNode(tile.id)?.cornerRadius).toBe(16)
+
+ editor.restorePageFromSnapshot(before)
+ expect(editor.graph.getNode(tile.id)?.cornerRadius).toBe(12)
+ })
+
test('renders both states of a region at one size and finds the changed pixels', async () => {
const { editor, pageId, card } = setup()
editor.graph.updateNode(card.id, {
diff --git a/packages/design-jsx/src/component-properties.ts b/packages/design-jsx/src/component-properties.ts
index 1885629d2..ca97a19f0 100644
--- a/packages/design-jsx/src/component-properties.ts
+++ b/packages/design-jsx/src/component-properties.ts
@@ -1,4 +1,5 @@
import { compact } from 'es-toolkit/array'
+import { isPlainObject } from 'es-toolkit/predicate'
import * as v from 'valibot'
import type {
@@ -10,72 +11,146 @@ import type {
import {
applyComponentPropertyValue,
componentPropertyDefinitions,
- createComponentPropertyId
+ createComponentPropertyId,
+ exposableInstances,
+ exposedInstances,
+ instanceExposureIssue
} from '@open-pencil/scene-graph/components'
+import { instanceMainComponent } from '@open-pencil/scene-graph/instances'
import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './definitions'
import { parseScriptInput } from './schema'
-const definitionSchema = v.object({
- id: v.string(),
- name: v.string(),
- type: v.picklist(['VARIANT', 'TEXT', 'BOOLEAN', 'INSTANCE_SWAP']),
- defaultValue: v.string(),
- variantOptions: v.optional(v.array(v.string())),
- preferredValues: v.optional(v.array(v.string()))
-}) satisfies v.GenericSchema<ComponentPropertyDefinition>
-const referenceSchema = v.object({
- propertyId: v.string(),
- field: v.picklist(['VISIBLE', 'TEXT', 'INSTANCE_SWAP'])
-}) satisfies v.GenericSchema<ComponentPropertyReference>
-
-/** Accept the native graph contracts, without introducing a second property model. */
-export function componentMetadata(
- props: Record<string, unknown>,
- type: SceneNode['type'],
- definitions?: readonly ComponentPropertyDefinition[]
-): Partial<SceneNode> {
- const result: Partial<SceneNode> = {}
- if (props.properties !== undefined && type !== 'INSTANCE') {
- if (type !== 'COMPONENT' && type !== 'COMPONENT_SET')
- throw new Error('Only components, component sets, and instances accept properties')
- const definitions = parseScriptInput(
- 'Invalid properties',
- v.array(definitionSchema),
- props.properties
- )
- if (new Set(definitions.map((definition) => definition.id)).size !== definitions.length)
- throw new Error('Duplicate component property IDs')
- const variantNames = definitions
- .filter((item) => item.type === 'VARIANT')
- .map((item) => item.name)
- if (new Set(variantNames).size !== variantNames.length)
- throw new Error('Duplicate variant property names')
- result.componentPropertyDefinitions = definitions
+const PROPERTY_SYMBOL = Symbol.for('open-pencil.component-property')
+
+/**
+ * A component property, by its name in the component that holds it. Where it is placed picks
+ * its type: `text` on a text layer makes a TEXT property, `visible` a BOOLEAN one, and `of` on an
+ * instance an INSTANCE_SWAP one, whose default is the component that `of` names.
+ */
+export interface ComponentProperty<T extends string | boolean = string | boolean> {
+ readonly [PROPERTY_SYMBOL]: true
+ readonly name: string
+ readonly defaultValue: T
+}
+
+export function isComponentProperty(value: unknown): value is ComponentProperty {
+ return typeof value === 'object' && value !== null && PROPERTY_SYMBOL in value
+}
+
+/**
+ * Bind a field to a property of the component it is drawn in, created on first use: on the
+ * component set, for a variant, as Figma keeps them, or else on the component.
+ */
+export function property<T extends string | boolean>(
+ name: string,
+ defaultValue: T
+): ComponentProperty<T> {
+ return Object.freeze({ [PROPERTY_SYMBOL]: true as const, name, defaultValue })
+}
+
+/** The prop each property type binds, and the field it binds there. */
+const BOUND_PROPS = {
+ text: { type: 'TEXT', field: 'TEXT', node: 'TEXT' },
+ visible: { type: 'BOOLEAN', field: 'VISIBLE', node: undefined },
+ of: { type: 'INSTANCE_SWAP', field: 'INSTANCE_SWAP', node: 'INSTANCE' }
+} as const satisfies Record<
+ string,
+ {
+ type: ComponentPropertyDefinition['type']
+ field: ComponentPropertyReference['field']
+ node: SceneNode['type'] | undefined
}
- if (props.propertyRefs !== undefined) {
- const references = parseScriptInput(
- 'Invalid propertyRefs',
- v.array(referenceSchema),
- props.propertyRefs
- )
- for (const reference of references) {
- if (reference.field === 'TEXT' && type !== 'TEXT')
- throw new Error('TEXT properties require a text node')
- if (reference.field === 'INSTANCE_SWAP' && type !== 'INSTANCE')
- throw new Error('INSTANCE_SWAP properties require an instance')
- if (definitions) {
- const definition = definitions.find((item) => item.id === reference.propertyId)
- if (!definition)
- throw new Error(`Unknown component property reference: ${reference.propertyId}`)
- const expectedField = definition.type === 'BOOLEAN' ? 'VISIBLE' : definition.type
- if (reference.field !== expectedField)
- throw new Error(`Component property ${definition.id} cannot bind ${reference.field}`)
- }
+>
+
+/** The component, or the set it is a variant of, that holds properties for layers under `parentId`. */
+function propertyOwner(graph: SceneGraph, parentId: string): SceneNode {
+ let node = graph.getNode(parentId)
+ while (node) {
+ if (node.type === 'INSTANCE') throw new Error('property() cannot be used inside an instance')
+ if (node.type === 'COMPONENT_SET') return node
+ if (node.type === 'COMPONENT') {
+ const set = node.parentId ? graph.getNode(node.parentId) : undefined
+ return set?.type === 'COMPONENT_SET' ? set : node
}
- result.componentPropertyReferences = references
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
}
- return result
+ throw new Error('property() must be inside a <Component> or <ComponentSet>')
+}
+
+/** The ID of the property with this name on `owner`, added if it has none. */
+function ensureDefinition(
+ graph: SceneGraph,
+ owner: SceneNode,
+ name: string,
+ type: ComponentPropertyDefinition['type'],
+ defaultValue: string
+): string {
+ const existing = owner.componentPropertyDefinitions.find((item) => item.name === name)
+ if (existing) {
+ if (existing.type !== type)
+ throw new Error(`Component property ${name} is ${existing.type}, not ${type}`)
+ if (existing.defaultValue !== defaultValue)
+ throw new Error(
+ `Component property ${name} has two defaults: ${existing.defaultValue} and ${defaultValue}`
+ )
+ return existing.id
+ }
+ const id = createComponentPropertyId()
+ graph.updateNode(owner.id, {
+ componentPropertyDefinitions: [
+ ...owner.componentPropertyDefinitions,
+ { id, name, type, defaultValue }
+ ]
+ })
+ return id
+}
+
+export interface BoundProperties {
+ /** The props, with each property in place of its default. */
+ props: Record<string, unknown>
+ references: ComponentPropertyReference[]
+}
+
+/**
+ * Bind the fields a layer's props place a `property()` in, creating the properties on its
+ * component; `componentId` gives the ID a swap's default component has.
+ */
+export function bindProperties(
+ graph: SceneGraph,
+ source: Record<string, unknown>,
+ type: SceneNode['type'],
+ parentId: string,
+ componentId: ComponentLookup
+): BoundProperties {
+ if (source.properties !== undefined && type !== 'INSTANCE')
+ throw new Error('Only instances accept properties; bind a field to property() instead')
+ const props = { ...source }
+ const references: ComponentPropertyReference[] = []
+ for (const [key, value] of Object.entries(source)) {
+ if (!isComponentProperty(value)) continue
+ if (!Object.hasOwn(BOUND_PROPS, key))
+ throw new Error(`property() binds text, visible, or of, not ${key}`)
+ const bound = BOUND_PROPS[key as keyof typeof BOUND_PROPS]
+ if (bound.node && bound.node !== type)
+ throw new Error(
+ `property() in ${key} needs ${bound.node === 'TEXT' ? '<Text>' : '<Instance>'}`
+ )
+ const expected = bound.type === 'BOOLEAN' ? 'boolean' : 'string'
+ if (typeof value.defaultValue !== expected)
+ throw new Error(`Component property ${value.name} in ${key} takes a ${expected} default`)
+ let defaultValue = String(value.defaultValue)
+ if (bound.type === 'INSTANCE_SWAP') {
+ const id = componentId(defaultValue)
+ if (!id) throw new Error(`<Instance> component not found: ${defaultValue}`)
+ defaultValue = id
+ }
+ const owner = propertyOwner(graph, parentId)
+ const propertyId = ensureDefinition(graph, owner, value.name, bound.type, defaultValue)
+ references.push({ propertyId, field: bound.field })
+ props[key] = value.defaultValue
+ }
+ return { props, references }
}
/** Match the nearest component scope, including definitions inherited from its set. */
@@ -111,67 +186,186 @@ function namedDefinition(
return matches[0]
}
+/** The ID of the component a name or ID names, as `<Instance of>` finds it. */
+export type ComponentLookup = (nameOrId: string) => string | undefined
+
function assignValue(
graph: SceneGraph,
instance: SceneNode,
definition: ComponentPropertyDefinition,
key: string,
- value: string
+ value: string,
+ componentId: ComponentLookup
): void {
if (definition.type === 'VARIANT')
throw new Error('Select a component-set variant when creating the instance')
if (definition.type === 'BOOLEAN' && value !== 'true' && value !== 'false')
throw new Error(`Expected true or false for component property: ${key}`)
- if (!applyComponentPropertyValue(graph, instance.id, definition, value))
+ // A swap names its component as `of` does: by ID or by name.
+ const assigned = definition.type === 'INSTANCE_SWAP' ? (componentId(value) ?? value) : value
+ if (!applyComponentPropertyValue(graph, instance.id, definition, assigned))
throw new Error(`Cannot assign component property: ${key}`)
}
+/** A value an instance gives a property, or an exposed nested instance's values by name. */
+const assignedValueSchema = v.union([v.string(), v.boolean(), v.number()])
+const exposedValuesSchema = v.record(v.string(), assignedValueSchema)
+
+/** The one exposed nested instance with this name; a name several share is an error. */
+function exposedInstanceNamed(
+ graph: SceneGraph,
+ instance: SceneNode,
+ name: string
+): SceneNode | undefined {
+ const matches = exposedInstances(graph, instance).filter((node) => node.name === name)
+ if (matches.length > 1)
+ throw new Error(`Exposed instance name ${name} is shared by ${matches.length} layers`)
+ return matches[0]
+}
+
+/**
+ * Pick the variant of an exposed instance's set that has the values it names, keeping its own
+ * for the rest, as its panel group does.
+ */
+function selectNestedVariant(
+ graph: SceneGraph,
+ nested: SceneNode,
+ name: string,
+ values: Record<string, string>
+): void {
+ if (Object.keys(values).length === 0) return
+ const component = instanceMainComponent(graph, nested)
+ const set = component?.parentId ? graph.getNode(component.parentId) : undefined
+ if (!component || set?.type !== 'COMPONENT_SET') return
+ const wanted = { ...component.componentPropertyValues, ...values }
+ const variant = graph
+ .getChildren(set.id)
+ .find(
+ (node) =>
+ node.type === 'COMPONENT' &&
+ Object.entries(wanted).every(([key, value]) => node.componentPropertyValues[key] === value)
+ )
+ if (!variant)
+ throw new Error(
+ `${name} has no variant ${Object.entries(values)
+ .map(([key, value]) => `${key}=${value}`)
+ .join(', ')}`
+ )
+ if (variant.id !== component.id) graph.swapInstanceComponent(nested.id, variant.id)
+}
+
/**
- * Set text, boolean, and swap properties an instance names as props, as in
- * `Title="Hello"`, the way it picks a variant; design JSX props keep their meaning.
+ * Give the exposed nested instance named `name` its values: variants and properties by name,
+ * the way the instance itself takes them.
+ */
+function assignExposedInstance(
+ graph: SceneGraph,
+ instance: SceneNode,
+ name: string,
+ input: unknown,
+ componentId: ComponentLookup
+): void {
+ const nested = exposedInstanceNamed(graph, instance, name)
+ if (!nested) throw new Error(`Unknown component property or exposed instance: ${name}`)
+ const values = parseScriptInput(`Invalid values for ${name}`, exposedValuesSchema, input)
+ const variantNames = new Set(
+ componentPropertyDefinitions(graph, nested)
+ .filter((definition) => definition.type === 'VARIANT')
+ .map((definition) => definition.name)
+ )
+ const variants = Object.fromEntries(
+ Object.entries(values)
+ .filter(([key]) => variantNames.has(key))
+ .map(([key, value]) => [key, String(value)])
+ )
+ selectNestedVariant(graph, nested, name, variants)
+ const definitions = componentPropertyDefinitions(graph, nested)
+ for (const [key, value] of Object.entries(values)) {
+ if (variantNames.has(key)) continue
+ const definition = namedDefinition(definitions, key)
+ if (!definition) throw new Error(`Unknown component property on ${name}: ${key}`)
+ assignValue(graph, nested, definition, key, String(value), componentId)
+ }
+}
+
+/**
+ * Set text, boolean, and swap properties an instance names as props, as in `Title="Hello"`, the
+ * way it picks a variant, and an exposed nested instance's values, as in `Action={{ Label: 'Save' }}`;
+ * design JSX props keep their meaning.
*/
export function assignNamedProperties(
graph: SceneGraph,
instance: SceneNode,
- props: Record<string, unknown>
+ props: Record<string, unknown>,
+ componentId: ComponentLookup
): void {
const definitions = componentPropertyDefinitions(graph, instance).filter(
(definition) => definition.type !== 'VARIANT'
)
for (const [key, value] of Object.entries(props)) {
if (DESIGN_JSX_SUPPORTED_PROPERTIES.has(key)) continue
+ if (isPlainObject(value) && exposedInstanceNamed(graph, instance, key)) {
+ assignExposedInstance(graph, instance, key, value, componentId)
+ continue
+ }
const definition = namedDefinition(definitions, key)
if (!definition) continue
if (typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number')
throw new Error(`Expected a string or boolean for component property: ${key}`)
- assignValue(graph, instance, definition, key, String(value))
+ assignValue(graph, instance, definition, key, String(value), componentId)
}
}
/**
* Keys are property IDs or, because saving to `.fig` replaces authored IDs
- * with GUIDs, names, which survive a reload.
+ * with GUIDs, names, which survive a reload; an object gives an exposed nested instance its values.
*/
export function assignComponentProperties(
graph: SceneGraph,
instance: SceneNode,
- input: unknown
+ input: unknown,
+ componentId: ComponentLookup
): void {
if (input === undefined) return
const assignments = parseScriptInput(
'Invalid properties on <Instance>',
- v.record(v.string(), v.string()),
+ v.record(v.string(), v.union([assignedValueSchema, exposedValuesSchema])),
input
)
const definitions = componentPropertyDefinitions(graph, instance)
for (const [key, value] of Object.entries(assignments)) {
+ if (isPlainObject(value)) {
+ assignExposedInstance(graph, instance, key, value, componentId)
+ continue
+ }
const definition =
definitions.find((item) => item.id === key) ?? namedDefinition(definitions, key)
if (!definition) throw new Error(`Unknown component property: ${key}`)
- assignValue(graph, instance, definition, key, value)
+ assignValue(graph, instance, definition, key, String(value), componentId)
}
}
+/** Mark an instance in a component's layers as exposed, under Figma's rules for exposing one. */
+export function exposeInstance(graph: SceneGraph, instance: SceneNode): void {
+ const issue = instanceExposureIssue(graph, instance)
+ if (issue === 'not-in-component') throw new Error('exposed needs an <Instance> in a component')
+ if (issue === 'not-primary')
+ throw new Error('exposed needs an <Instance> in a component, not inside another instance')
+ if (issue === 'nothing-to-expose')
+ throw new Error(`${instance.name} has no properties or exposed instances to expose`)
+ graph.updateNode(instance.id, { isExposedInstance: true })
+}
+
+/** The names an instance of `component` takes: its properties' and its exposed instances'. */
+export function componentPropNames(graph: SceneGraph, component: SceneNode): string[] {
+ return [
+ ...(componentPropertyScope(graph, component.id) ?? []).map((definition) => definition.name),
+ ...exposableInstances(graph, component.id)
+ .filter((node) => node.isExposedInstance)
+ .map((node) => node.name)
+ ]
+}
+
function parseVariantValues(name: string): Record<string, string> {
const entries = compact(name.split(',').map((part) => part.trim()))
const values: Record<string, string> = {}
diff --git a/packages/design-jsx/src/definitions.ts b/packages/design-jsx/src/definitions.ts
index 71ecb57e3..252356e59 100644
--- a/packages/design-jsx/src/definitions.ts
+++ b/packages/design-jsx/src/definitions.ts
@@ -183,8 +183,9 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = [
'component',
'componentId',
'properties',
- 'propertyRefs',
'of',
+ 'exposed',
+ 'mode',
// A Reka UI root's behaviour, by its own property names
'modelValue',
'open',
@@ -264,21 +265,3 @@ export const DESIGN_JSX_PROPERTIES: DesignJSXPropertyDefinition[] =
name,
description: `OpenPencil ${name} property.`
}))
-
-export const DESIGN_JSX_HELPERS: DesignJSXHelperDefinition[] = [
- 'solid',
- 'gradient',
- 'linearGradient',
- 'radialGradient',
- 'angularGradient',
- 'diamondGradient',
- 'shader',
- 'dropShadow',
- 'innerShadow',
- 'layerBlur',
- 'backgroundBlur',
- 'foregroundBlur',
- 'designVar',
- 'defineVars',
- 'ref'
-].map((name) => ({ name, description: `OpenPencil ${name} helper.` }))
diff --git a/packages/design-jsx/src/export/state.ts b/packages/design-jsx/src/export/state.ts
index f346085fa..e4a89a345 100644
--- a/packages/design-jsx/src/export/state.ts
+++ b/packages/design-jsx/src/export/state.ts
@@ -35,14 +35,22 @@ function collectSizeLimitProps(node: SceneNode, props: JSXProp[]): void {
}
/**
- * Variables are named when the name is unique in the document, which is how `designVar`
- * resolves them, and referenced by ID otherwise.
+ * 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)
- return sameName.length === 1 ? helperCall('designVar', variable.name) : variableId
+ 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 {
@@ -54,6 +62,22 @@ function collectBindingProps(node: SceneNode, graph: SceneGraph, props: JSXProp[
])
}
+/**
+ * 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>,
@@ -65,5 +89,6 @@ export function collectStateProps(
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)
}
diff --git a/packages/design-jsx/src/helpers.ts b/packages/design-jsx/src/helpers.ts
index 361628f19..bacb7c07c 100644
--- a/packages/design-jsx/src/helpers.ts
+++ b/packages/design-jsx/src/helpers.ts
@@ -1,6 +1,8 @@
import { difference } from 'es-toolkit/array'
import { isPlainObject } from 'es-toolkit/predicate'
+import { property } from './component-properties'
+import type { DesignJSXHelperDefinition } from './definitions'
import {
backgroundBlur,
dropShadow,
@@ -22,6 +24,7 @@ import {
type SolidPaintOptions
} from './paints'
import { ref } from './refs'
+import { defineMode, defineVars, designMode, designVar } from './variables'
/** Every option a helper reads; `satisfies` keeps the list equal to the options type. */
type OptionKeys<Options> = Record<keyof Options, true>
@@ -89,21 +92,36 @@ function checked<Args extends unknown[], Result>(
}
}
-/** The paint and effect helpers evaluated Design JSX can call, reporting ignored options. */
+/**
+ * Every helper Design JSX code can call, reporting ignored options to `warnings`. This is the
+ * one list of them: the string renderer's scope, the code panel's sandbox, the editor's
+ * completions, and the authoring reference all read it.
+ */
export function designJSXHelpers(warnings: string[]) {
return {
- dropShadow: checked(warnings, 'dropShadow', dropShadow, SHADOW_OPTIONS, 0),
- innerShadow: checked(warnings, 'innerShadow', innerShadow, SHADOW_OPTIONS, 0),
- layerBlur: checked(warnings, 'layerBlur', layerBlur, BLUR_OPTIONS, 0),
- backgroundBlur: checked(warnings, 'backgroundBlur', backgroundBlur, BLUR_OPTIONS, 0),
- foregroundBlur: checked(warnings, 'foregroundBlur', foregroundBlur, BLUR_OPTIONS, 0),
solid: checked(warnings, 'solid', solid, SOLID_OPTIONS, 1),
- shader: checked(warnings, 'shader', shader, SOLID_OPTIONS, 1),
gradient: checked(warnings, 'gradient', gradient, GRADIENT_OPTIONS, 2),
linearGradient: checked(warnings, 'linearGradient', linearGradient, GRADIENT_OPTIONS, 1),
radialGradient: checked(warnings, 'radialGradient', radialGradient, GRADIENT_OPTIONS, 1),
angularGradient: checked(warnings, 'angularGradient', angularGradient, GRADIENT_OPTIONS, 1),
diamondGradient: checked(warnings, 'diamondGradient', diamondGradient, GRADIENT_OPTIONS, 1),
+ shader: checked(warnings, 'shader', shader, SOLID_OPTIONS, 1),
+ dropShadow: checked(warnings, 'dropShadow', dropShadow, SHADOW_OPTIONS, 0),
+ innerShadow: checked(warnings, 'innerShadow', innerShadow, SHADOW_OPTIONS, 0),
+ layerBlur: checked(warnings, 'layerBlur', layerBlur, BLUR_OPTIONS, 0),
+ backgroundBlur: checked(warnings, 'backgroundBlur', backgroundBlur, BLUR_OPTIONS, 0),
+ foregroundBlur: checked(warnings, 'foregroundBlur', foregroundBlur, BLUR_OPTIONS, 0),
+ defineVars,
+ defineMode,
+ designVar,
+ designMode,
+ property,
ref
}
}
+
+export type DesignJSXHelperName = keyof ReturnType<typeof designJSXHelpers>
+
+export const DESIGN_JSX_HELPERS: DesignJSXHelperDefinition[] = Object.keys(
+ designJSXHelpers([])
+).map((name) => ({ name, description: `OpenPencil ${name} helper.` }))
diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.ts
index d104a93b3..7af4a3604 100644
--- a/packages/design-jsx/src/index.ts
+++ b/packages/design-jsx/src/index.ts
@@ -82,7 +82,19 @@ export {
type SolidPaintOptions
} from './paints'
-export { defineVars, designVar, isVariable, type DesignVariable, type VarDef } from './vars'
+export {
+ defineMode,
+ defineVars,
+ designMode,
+ designVar,
+ isMode,
+ isVariable,
+ isVariableInput,
+ type DesignMode,
+ type DesignVariable,
+ type VariableInput
+} from './variables'
+export { isComponentProperty, property, type ComponentProperty } from './component-properties'
export { isLayerRef, ref, type LayerRef } from './refs'
export { createElement } from './mini-react'
@@ -95,8 +107,8 @@ export {
elementPropsByName,
type DesignJSXElementDefinition
} from './elements'
+export { DESIGN_JSX_HELPERS, designJSXHelpers, type DesignJSXHelperName } from './helpers'
export {
- DESIGN_JSX_HELPERS,
DESIGN_JSX_PROPERTIES,
DESIGN_JSX_SUPPORTED_PROPERTIES,
DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,
diff --git a/packages/design-jsx/src/reference.ts b/packages/design-jsx/src/reference.ts
index e83caa404..a7ce93b7a 100644
--- a/packages/design-jsx/src/reference.ts
+++ b/packages/design-jsx/src/reference.ts
@@ -1,5 +1,6 @@
-import { DESIGN_JSX_HELPERS, DESIGN_JSX_SUPPORTED_PROPERTY_NAMES } from './definitions'
+import { DESIGN_JSX_SUPPORTED_PROPERTY_NAMES } from './definitions'
import { DESIGN_JSX_ELEMENTS } from './elements'
+import { DESIGN_JSX_HELPERS } from './helpers'
import authoring from './reference/authoring.md?raw'
import { AUTHORING_EXAMPLES } from './reference/examples'
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 3d1b579b6..c04c0c349 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -33,16 +33,19 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
-- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
+- `defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' })` defines a collection in the file's variables table and returns its variables by name, such as `theme.Page`. Each value is the variable's value in the first mode, named by `mode` (`Mode 1` without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as `palette['Gray/900']`. `defineMode(theme, 'Dark', { Page: '#111111' })` adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.
+- `designVar('name-or-id')` refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as `designMode` does: `designVar('Theme', 'Line')`.
- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
-- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
+- `mode={dark}` shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and `designMode('Theme', 'Dark')` names a mode of a collection the document already has, by the collection's ID when several share its name. Without `mode`, a layer inherits its parent's.
+- Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.
- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.
-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.
-- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.
-- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
+- `property(name, defaultValue)` binds a field of a component's layer to a component property, created on first use: `text={property('Message', 'Hi')}` on a `Text` makes a TEXT property, `visible={property('Pinned', true)}` a BOOLEAN one, and `of={property('Icon', 'Star')}` on an `Instance` an INSTANCE_SWAP one whose default is the component `of` names. The property belongs to the nearest `Component`, or to its `ComponentSet` for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.
+- An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Only instances accept `properties`.
+- `exposed` on an `Instance` in a component shows that instance's own properties on the component's instances, as Figma's "Expose properties from nested instances" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: `<Instance of="Card" Title="Welcome" Action={{ Variant: 'Secondary', Label: 'Save' }} />`, or `properties={{ Action: { … } }}`.
+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name or ID for swaps, as `of` does, whether set as a prop or in `properties`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.
- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.
diff --git a/packages/design-jsx/src/reference/examples.ts b/packages/design-jsx/src/reference/examples.ts
index e00b8ab91..f17ab54ca 100644
--- a/packages/design-jsx/src/reference/examples.ts
+++ b/packages/design-jsx/src/reference/examples.ts
@@ -19,6 +19,21 @@ export const AUTHORING_EXAMPLES: readonly AuthoringExample[] = [
jsx: dedent`<Frame name="Bound note" w={280} h="hug" flex="col" gap={designVar('Space/small')} p={designVar('Space/medium')} bg="#FFFFFF">
<Text name="Message" w="fill" size={designVar('Type/body')} lineHeight={designVar('Type/body-leading')} letterSpacing={designVar('Type/body-tracking')} color="#252A31">A note that grows with its content.</Text>
</Frame>`
+ },
+ {
+ title: 'A theme with two modes',
+ jsx: dedent`const theme = defineVars('Theme', { Surface: '#FFFFFF', Ink: '#252A31', Radius: 12 }, { mode: 'Light' })
+const dark = defineMode(theme, 'Dark', { Surface: '#1A1A20', Ink: '#F5F5F7' })
+return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p={16} bg={theme.Surface} rounded={theme.Radius}>
+ <Text name="Message" w="fill" size={12} color={theme.Ink}>Shown in the Dark mode of the Theme collection.</Text>
+</Frame>`
+ },
+ {
+ title: 'Component with text and visibility properties',
+ jsx: dedent`<Component name="Comment" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
+ <Text name="Author" size={12} weight="medium" color="#252A31" text={property('Author', 'June Lee')} />
+ <Text name="Message" w="fill" size={12} color="#6B7079" text={property('Message', 'Give the date more room.')} visible={property('Show message', true)} />
+</Component>`
},
{
title: 'Rich text with spans and lists',
diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.ts
index ffeddb372..028e47d9d 100644
--- a/packages/design-jsx/src/render.ts
+++ b/packages/design-jsx/src/render.ts
@@ -5,7 +5,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { REKA_ELEMENTS } from './behaviours'
import { elementBindings, elementProps, elementSchema } from './elements'
import { ENUM_PROPS } from './enums'
-import { designJSXHelpers } from './helpers'
+import { DESIGN_JSX_HELPERS, designJSXHelpers } from './helpers'
import * as React from './mini-react'
import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'
import { elementPropWarnings } from './schema'
@@ -25,6 +25,11 @@ const REKA_ALIASES = Object.entries(REKA_ELEMENTS)
)
.join('\n')
+/** `const solid = __helpers.solid`, …: every helper in the scope of the code. */
+const HELPER_BINDINGS = DESIGN_JSX_HELPERS.map(
+ ({ name }) => `const ${name} = __helpers.${name}`
+).join('\n')
+
function stripHTMLComments(jsxString: string): string {
return jsxString.replace(/<!--[\s\S]*?-->/g, '')
}
@@ -81,26 +86,7 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reac
${elementBindings()}
const svg = 'svg'
${REKA_ALIASES}
- const dropShadow = __helpers.dropShadow
- const innerShadow = __helpers.innerShadow
- const layerBlur = __helpers.layerBlur
- const backgroundBlur = __helpers.backgroundBlur
- const foregroundBlur = __helpers.foregroundBlur
- const solid = __helpers.solid
- const shader = __helpers.shader
- const gradient = __helpers.gradient
- const linearGradient = __helpers.linearGradient
- const radialGradient = __helpers.radialGradient
- const angularGradient = __helpers.angularGradient
- const diamondGradient = __helpers.diamondGradient
- const ref = __helpers.ref
- const __varSymbol = Symbol.for('open-pencil.variable')
- const designVar = (def, value) => typeof def === 'string'
- ? ({ [__varSymbol]: true, id: def, name: def, value })
- : ({ [__varSymbol]: true, id: def.id, name: def.name ?? def.id ?? '', value: def.value })
- const defineVars = (vars) => Object.fromEntries(
- Object.entries(vars).map(([key, def]) => [key, designVar(def)])
- )
+ ${HELPER_BINDINGS}
`
const body = transformDesignJSXExpression(trimmed)
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index e4303c46f..dcedbd47b 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -1,17 +1,17 @@
import { omitBy } from 'es-toolkit/object'
-import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { NodeType, SceneGraph, SceneNode, VariableModeMap } from '@open-pencil/scene-graph'
import { parseColor } from '@open-pencil/scene-graph/color'
import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'
-import type { Color } from '@open-pencil/scene-graph/primitives'
import type { RekaScope } from './behaviours'
import { renderRekaNode } from './behaviours/render'
import {
assignComponentProperties,
- componentMetadata,
assignNamedProperties,
- componentPropertyScope,
+ bindProperties,
+ componentPropNames as namesOnInstance,
+ exposeInstance,
inferComponentSetProperties
} from './component-properties'
import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'
@@ -25,7 +25,15 @@ import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-con
import { FRAGMENT, isTreeNode } from './tree'
import type { TreeNode } from './tree'
import type { RenderOptions } from './types'
-import { isVariable, resolveVariableId, type DesignVariable } from './vars'
+import { isVariable } from './variables'
+import {
+ applyVariableDefinitions,
+ bindVariableProp,
+ requireVariableId,
+ resolveForLayer,
+ variableModes,
+ type LayerContext
+} from './variables/graph'
export interface RenderResult {
id: string
@@ -35,8 +43,6 @@ export interface RenderResult {
warnings?: string[]
}
-/** Component property ids only need to be unique within a document. */
-
/** The nodes a tree renders as: a fragment's children, or the tree itself. */
function treeRoots(tree: TreeNode): TreeNode[] {
return tree.type === FRAGMENT ? tree.children.filter(isTreeNode) : [tree]
@@ -52,6 +58,7 @@ export async function renderRoots<Artwork>(
const roots = treeRoots(tree)
if (roots.length === 0) throw new Error('JSX must return a Figma element (Frame, Text, etc)')
const parentId = options.parentId ?? graph.getPages()[0].id
+ applyVariableDefinitions(graph, tree)
const nodes: SceneNode[] = []
const connectors: Array<{ node: SceneNode; tree: TreeNode }> = []
@@ -101,85 +108,49 @@ function isObjectRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
-function variableFallback(graph: SceneGraph, variable: DesignVariable): string | Color | undefined {
- if (variable.value !== undefined && typeof variable.value !== 'number') return variable.value
- const variableId = resolveVariableId(graph, variable)
- return variableId ? graph.resolveColorVariable(variableId) : undefined
-}
-
-function bindVariableProp(
- graph: SceneGraph,
- props: Record<string, unknown>,
- bindings: Record<string, string>,
- key: string,
- field: string
-): void {
- const value = props[key]
- if (!isVariable(value)) return
- const variableId = resolveVariableId(graph, value)
- if (variableId) bindings[field] = variableId
- const fallback = variableFallback(graph, value)
- if (fallback !== undefined) props[key] = fallback
-}
-
-function bindStyleVariableProp(
- graph: SceneGraph,
- style: Record<string, unknown>,
- bindings: Record<string, string>,
- key: string,
- field: string
-): void {
- const value = style[key]
- if (!isVariable(value)) return
- const variableId = resolveVariableId(graph, value)
- if (variableId) bindings[field] = variableId
- const fallback = variableFallback(graph, value)
- if (fallback !== undefined) style[key] = fallback
-}
-
function preparePropsForRender(
graph: SceneGraph,
source: Record<string, unknown>,
isText: boolean,
- parentId: string
+ layer: LayerContext
): PreparedProps {
const props = { ...source }
const bindings: Record<string, string> = {}
if (Array.isArray(props.fills)) {
- props.fills = props.fills.map((value, index) => {
- if (!isVariable(value)) return value
- const variableId = resolveVariableId(graph, value)
- if (variableId) bindings[`fills/${index}/color`] = variableId
- return variableFallback(graph, value) ?? value
+ props.fills = props.fills.map((value: unknown, index) => {
+ const fill = { value }
+ bindVariableProp(graph, fill, bindings, 'value', `fills/${index}/color`, layer)
+ return fill.value
})
}
for (const key of ['bg', 'fill', 'background', 'backgroundColor']) {
- bindVariableProp(graph, props, bindings, key, 'fills/0/color')
+ bindVariableProp(graph, props, bindings, key, 'fills/0/color', layer)
}
- if (isText) bindVariableProp(graph, props, bindings, 'color', 'fills/0/color')
+ 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')
+ bindVariableProp(graph, props, bindings, key, 'strokes/0/color', layer)
}
if (isObjectRecord(props.style)) {
const style = { ...props.style }
for (const key of ['background', 'backgroundColor']) {
- bindStyleVariableProp(graph, style, bindings, key, 'fills/0/color')
+ bindVariableProp(graph, style, bindings, key, 'fills/0/color', layer)
}
- if (isText) bindStyleVariableProp(graph, style, bindings, 'color', 'fills/0/color')
- bindStyleVariableProp(graph, style, bindings, 'borderColor', 'strokes/0/color')
+ if (isText) bindVariableProp(graph, style, bindings, 'color', 'fills/0/color', layer)
+ bindVariableProp(graph, style, bindings, 'borderColor', 'strokes/0/color', layer)
props.style = style
}
- prepareScalarBindings(graph, props, bindings, isText, parentId)
+ prepareScalarBindings(graph, props, bindings, isText, (variableId) =>
+ resolveForLayer(graph, variableId, layer.parentId, layer.modes)
+ )
if (isObjectRecord(props.bind)) {
for (const [field, value] of Object.entries(props.bind)) {
if (isVariable(value)) {
- const variableId = resolveVariableId(graph, value)
- if (variableId) bindings[field] = variableId
+ bindings[field] = requireVariableId(graph, value)
} else if (typeof value === 'string') {
bindings[field] = value
}
@@ -200,10 +171,14 @@ function renderOwnLayerElement(
parentId: string,
element: OwnLayerRenderer
): SceneNode {
- const { props, bindings } = preparePropsForRender(graph, tree.props, false, parentId)
+ const modes = variableModes(graph, tree.props.mode)
+ const { props, bindings } = preparePropsForRender(graph, tree.props, false, { parentId, modes })
const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
const layer = omitBy(
- propsToOverrides(readElementProps(element.layer, props), false, parentLayout),
+ {
+ ...propsToOverrides(readElementProps(element.layer, props), false, parentLayout),
+ ...(modes && { variableModes: modes })
+ },
(value) => value === undefined
)
const node = element.render(graph, { ...tree, props }, parentId, layer)
@@ -258,8 +233,29 @@ function placeArtwork<Artwork>(
const overrides: Partial<SceneNode> = {}
if (props.label) overrides.name = props.label as string
applyIconSize(props, overrides, parentLayout, size)
- const color = parseColor((props.color as string | undefined) ?? '#000000')
- return services.createArtwork(graph, artwork, { parentId, size, color, overrides })
+ const modes = variableModes(graph, props.mode)
+ if (modes) overrides.variableModes = modes
+ const variableId = isVariable(props.color) ? requireVariableId(graph, props.color) : undefined
+ const resolved = variableId && resolveForLayer(graph, variableId, parentId, modes)
+ if (isVariable(props.color) && typeof resolved !== 'object')
+ throw new Error(`Cannot resolve color variable ${props.color.name} for color`)
+ const color =
+ typeof resolved === 'object'
+ ? resolved
+ : parseColor(typeof props.color === 'string' ? props.color : '#000000')
+ const node = services.createArtwork(graph, artwork, { parentId, size, color, overrides })
+ if (variableId) bindSolidPaints(graph, node, variableId)
+ return node
+}
+
+/** Bind every solid paint of an artwork's paths, so it follows the variable it was drawn in. */
+function bindSolidPaints(graph: SceneGraph, node: SceneNode, variableId: string): void {
+ for (const field of ['fills', 'strokes'] as const) {
+ node[field].forEach((paint, index) => {
+ if (paint.type === 'SOLID') graph.bindVariable(node.id, `${field}/${index}/color`, variableId)
+ })
+ }
+ for (const child of graph.getChildren(node.id)) bindSolidPaints(graph, child, variableId)
}
/**
@@ -345,11 +341,13 @@ function resolveComponent(
return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named
}
-/** The component properties an element sets by name, such as `State` or `Title`. */
+/**
+ * The names an element sets on its component by prop: properties such as `State` or `Title`, and
+ * exposed instances.
+ */
export function componentPropNames(graph: SceneGraph, props: Record<string, unknown>): string[] {
const component = resolveComponent(graph, props)
- if (!component) return []
- return (componentPropertyScope(graph, component.id) ?? []).map((definition) => definition.name)
+ return component ? namesOnInstance(graph, component) : []
}
async function renderInstanceNode(
@@ -359,7 +357,9 @@ async function renderInstanceNode(
): Promise<SceneNode> {
const parent = graph.getNode(parentId)
const parentLayout = parent?.layoutMode ?? 'NONE'
- const { props, bindings } = preparePropsForRender(graph, tree.props, false, parentId)
+ const modes = variableModes(graph, tree.props.mode)
+ const bound = bindProperties(graph, tree.props, 'INSTANCE', parentId, componentIdNamed(graph))
+ const { props, bindings } = preparePropsForRender(graph, bound.props, false, { parentId, modes })
const component = resolveComponent(graph, props)
if (!component) {
const ref = props.component ?? props.componentId ?? props.of
@@ -368,7 +368,7 @@ async function renderInstanceNode(
}
const overrides: Partial<SceneNode> = {
...propsToOverrides(props, false, parentLayout),
- ...componentMetadata(props, 'INSTANCE', componentPropertyScope(graph, parentId))
+ ...layerMetadata(modes, bound.references)
}
// Instances inherit their container layout, but explicitly authored dimensions
// must also replace the inherited sizing mode on that axis.
@@ -396,8 +396,9 @@ async function renderInstanceNode(
graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
applyBindings(graph, instance.id, bindings)
applyInstanceOverrides(graph, instance, tree.props.overrides)
- assignNamedProperties(graph, instance, props)
- assignComponentProperties(graph, instance, props.properties)
+ assignNamedProperties(graph, instance, props, componentIdNamed(graph))
+ assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph))
+ if (props.exposed === true) exposeInstance(graph, instance)
return instance
} catch (error) {
graph.deleteNode(instance.id)
@@ -453,15 +454,34 @@ async function renderArtworkNode<Artwork>(
tree: TreeNode,
parentId: string
): Promise<SceneNode> {
- const metadata = componentMetadata(tree.props, 'VECTOR', componentPropertyScope(graph, parentId))
+ const bound = bindProperties(graph, tree.props, 'VECTOR', parentId, componentIdNamed(graph))
+ const artwork = { ...tree, props: bound.props }
const node =
tree.type === 'icon'
- ? await renderIconNode(services, graph, tree, parentId)
- : renderSVGNode(services, graph, tree, parentId)
+ ? await renderIconNode(services, graph, artwork, parentId)
+ : renderSVGNode(services, graph, artwork, parentId)
+ const metadata: Partial<SceneNode> = layerMetadata(undefined, bound.references)
+ if (typeof bound.props.visible === 'boolean') metadata.visible = bound.props.visible
if (Object.keys(metadata).length > 0) graph.updateNode(node.id, metadata)
return node
}
+/** The modes a layer pins and the component properties its fields are bound to. */
+function layerMetadata(
+ modes: VariableModeMap | undefined,
+ references: SceneNode['componentPropertyReferences']
+): Partial<SceneNode> {
+ return {
+ ...(modes && { variableModes: modes }),
+ ...(references.length > 0 && { componentPropertyReferences: references })
+ }
+}
+
+/** The component a swap property's default names, by ID or name, as `<Instance of>` finds it. */
+function componentIdNamed(graph: SceneGraph) {
+ return (name: string) => resolveComponent(graph, { of: name })?.id
+}
+
export interface ElementOverrides {
overrides: Partial<SceneNode>
/** Variable IDs by bound field, such as `fills/0/color`. */
@@ -477,17 +497,20 @@ export function elementOverrides(
): ElementOverrides {
const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
const isText = nodeType === 'TEXT'
- const { props, bindings } = preparePropsForRender(graph, tree.props, isText, parentId)
+ const modes = variableModes(graph, tree.props.mode)
+ const bound = bindProperties(graph, tree.props, nodeType, parentId, componentIdNamed(graph))
+ const layer = { parentId, modes }
+ const { props, bindings } = preparePropsForRender(graph, bound.props, isText, layer)
const overrides = {
...propsToOverrides(props, isText, parentLayout),
...shapeOverrides(nodeType, props),
- ...componentMetadata(props, nodeType, componentPropertyScope(graph, parentId))
+ ...layerMetadata(modes, bound.references)
}
if (isText) {
// A span's variables give their values; characters keep no bindings of their own.
const spanOverrides = (spanProps: Record<string, unknown>) =>
- propsToOverrides(preparePropsForRender(graph, spanProps, true, parentId).props, true, 'NONE')
+ propsToOverrides(preparePropsForRender(graph, spanProps, true, layer).props, true, 'NONE')
Object.assign(overrides, textContentFields(tree, props, overrides, spanOverrides))
}
return { overrides, bindings }
diff --git a/packages/design-jsx/src/scalar-bindings.ts b/packages/design-jsx/src/scalar-bindings.ts
index 4434f29f9..9b1550de4 100644
--- a/packages/design-jsx/src/scalar-bindings.ts
+++ b/packages/design-jsx/src/scalar-bindings.ts
@@ -1,6 +1,7 @@
-import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { SceneGraph, VariableLiteral } from '@open-pencil/scene-graph'
-import { isVariable, resolveVariableId } from './vars'
+import { isVariable } from './variables'
+import { requireVariableId } from './variables/graph'
// Shorthands precede their longhands, matching propsToOverrides precedence.
const PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']
@@ -29,7 +30,7 @@ export function prepareScalarBindings(
props: Record<string, unknown>,
bindings: Record<string, string>,
isText: boolean,
- parentId: string
+ resolve: (variableId: string) => VariableLiteral | undefined
): void {
const entries = [...SCALAR_PROPS]
const scalarBindings = new Map<string, string>()
@@ -59,16 +60,13 @@ export function prepareScalarBindings(
for (const field of fields) scalarBindings.delete(field)
if (!isVariable(value)) continue
- const variableId = resolveVariableId(graph, value)
- const variable = variableId ? graph.variables.get(variableId) : undefined
+ const variable = graph.variables.get(requireVariableId(graph, value))
if (variable?.type !== 'FLOAT') {
throw new Error(`Expected a FLOAT variable for ${key}: ${value.name}`)
}
- const resolved =
- graph.resolveNumberVariableForNode(parentId, variable.id) ??
- (typeof value.value === 'number' ? value.value : undefined)
- if (resolved === undefined || !Number.isFinite(resolved)) {
- throw new Error(`Cannot resolve numeric variable for ${key}: ${value.name}`)
+ const resolved = resolve(variable.id)
+ if (typeof resolved !== 'number' || !Number.isFinite(resolved)) {
+ throw new TypeError(`Cannot resolve numeric variable for ${key}: ${value.name}`)
}
props[key] = resolved
for (const field of fields) scalarBindings.set(field, variable.id)
diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.ts
index d05352bb6..b5dfdf33f 100644
--- a/packages/design-jsx/src/schema.ts
+++ b/packages/design-jsx/src/schema.ts
@@ -19,7 +19,7 @@ import {
import { isColor, isFillValue } from './overrides/fills'
import { isStrokeValue } from './overrides/strokes'
import { isLayerRef, type LayerRef } from './refs'
-import { isVariable } from './vars'
+import { isVariable } from './variables'
/**
* Parse a value a design JSX script passed, or throw `heading` followed by every problem and
diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.ts
index 0fc7fae98..53b7da12d 100644
--- a/packages/design-jsx/src/tree.ts
+++ b/packages/design-jsx/src/tree.ts
@@ -1,7 +1,8 @@
-import type { Effect, Fill, SceneNode } from '@open-pencil/scene-graph'
+import type { Effect, Fill } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import type { DesignVariable } from './vars'
+import type { ComponentProperty } from './component-properties'
+import type { DesignMode, DesignVariable } from './variables'
export interface TreeNode {
type: string
@@ -179,7 +180,7 @@ export type StyleProps = {
weight?: number | 'bold' | 'medium' | 'normal'
fontWeight?: number | 'bold' | 'medium' | 'normal'
color?: PaintProp
- text?: string
+ text?: string | ComponentProperty<string>
characters?: string
textAlign?: 'left' | 'center' | 'right' | 'justified'
textAlignHorizontal?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'
@@ -194,7 +195,9 @@ type NodeProps = StyleProps & {
key?: string | number
children?: unknown
bind?: Record<string, unknown>
- propertyRefs?: SceneNode['componentPropertyReferences']
+ visible?: boolean | ComponentProperty<boolean>
+ /** The modes the layer shows collections in, as the Appearance panel sets them. */
+ mode?: DesignMode | DesignMode[]
[key: string]: unknown
}
@@ -247,13 +250,14 @@ export type ParagraphProps = {
children?: unknown
}
-export type ComponentProps = NodeProps & {
- properties?: SceneNode['componentPropertyDefinitions']
-}
+export type ComponentProps = BaseProps
export type InstanceProps = NodeProps & {
component?: string
componentId?: string
- of?: string
- properties?: SceneNode['componentPropertyAssignments']
+ of?: string | ComponentProperty<string>
+ /** Show the instance's own properties on instances of the component it is in, as Figma does. */
+ exposed?: boolean
+ /** Values by property ID or name, or an exposed nested instance's values by its name. */
+ properties?: Record<string, string | boolean | number | Record<string, string | boolean | number>>
}
diff --git a/packages/design-jsx/src/variables/graph.ts b/packages/design-jsx/src/variables/graph.ts
new file mode 100644
index 000000000..8f73bace6
--- /dev/null
+++ b/packages/design-jsx/src/variables/graph.ts
@@ -0,0 +1,265 @@
+import { isEqual } from 'es-toolkit'
+import { isPlainObject } from 'es-toolkit/predicate'
+
+import type {
+ SceneGraph,
+ Variable,
+ VariableCollection,
+ VariableLiteral,
+ VariableModeMap,
+ VariableType,
+ VariableValue
+} from '@open-pencil/scene-graph'
+import { tryParseColor } from '@open-pencil/scene-graph/color'
+import { getNodeVariableModeId, resolveVariableInModes } from '@open-pencil/scene-graph/variables'
+
+import { isTreeNode, type TreeNode } from '../tree'
+import {
+ isMode,
+ isVariable,
+ type CollectionDefinition,
+ type DesignVariable,
+ type VariableInput
+} from './index'
+
+/**
+ * Every collection a value declares, through the variables and modes in it and their aliases;
+ * a collection comes after the ones it aliases, as it would be written.
+ */
+function collectDefinitions(
+ value: unknown,
+ found: Map<string, CollectionDefinition>,
+ visiting = new Set<CollectionDefinition>()
+): void {
+ const definition = isVariable(value) || isMode(value) ? value.collection : undefined
+ if (definition && typeof definition !== 'string') {
+ const known = found.get(definition.name)
+ if (known === definition || visiting.has(definition)) return
+ if (known && !isEqual(known, definition))
+ throw new Error(`Collection ${definition.name} is defined twice with different variables`)
+ visiting.add(definition)
+ for (const mode of definition.modes) collectDefinitions(mode.values, found, visiting)
+ found.set(definition.name, definition)
+ return
+ }
+ if (isTreeNode(value)) {
+ collectDefinitions(value.props, found, visiting)
+ for (const child of value.children) collectDefinitions(child, found, visiting)
+ } else if (Array.isArray(value)) {
+ for (const item of value) collectDefinitions(item, found, visiting)
+ } else if (isPlainObject(value)) {
+ for (const item of Object.values(value)) collectDefinitions(item, found, visiting)
+ }
+}
+
+/** The one collection with this name; a name several collections share is an error. */
+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`)
+ return matches[0]
+}
+
+function variableNamed(
+ graph: SceneGraph,
+ collection: VariableCollection,
+ name: string
+): Variable | undefined {
+ for (const id of collection.variableIds) {
+ const variable = graph.variables.get(id)
+ if (variable?.name === name) return variable
+ }
+ return undefined
+}
+
+/** The collection, with its modes in place, by the definition's names. */
+function ensureCollection(graph: SceneGraph, definition: CollectionDefinition): VariableCollection {
+ let collection = collectionNamed(graph, definition.name)
+ if (!collection) {
+ collection = graph.createCollection(definition.name)
+ graph.renameMode(collection.id, collection.defaultModeId, definition.modes[0].name)
+ }
+ for (const mode of definition.modes) {
+ if (!collection.modes.some((existing) => existing.name === mode.name))
+ graph.createMode(collection.id, mode.name)
+ }
+ const first = collection.modes.find((mode) => mode.name === definition.modes[0].name)
+ if (first && collection.defaultModeId !== first.modeId)
+ graph.setDefaultMode(collection.id, first.modeId)
+ return collection
+}
+
+function literalType(value: Exclude<VariableInput, DesignVariable>): VariableType {
+ if (typeof value === 'number') return 'FLOAT'
+ if (typeof value === 'boolean') return 'BOOLEAN'
+ return 'COLOR'
+}
+
+/** The type a defined variable holds: its first value's, or for an alias, its target's. */
+function definedType(
+ graph: SceneGraph,
+ definition: CollectionDefinition,
+ name: string,
+ visiting = new Set<string>()
+): VariableType {
+ const key = `${definition.name}\u0000${name}`
+ if (visiting.has(key)) throw new Error(`Variable ${name} aliases itself`)
+ visiting.add(key)
+ const value = definition.modes[0].values[name]
+ if (!isVariable(value)) return literalType(value)
+ if (typeof value.collection === 'object')
+ return definedType(graph, value.collection, value.name, visiting)
+ const target = graph.variables.get(requireVariableId(graph, value))
+ if (!target) throw new Error(`Unknown variable: ${value.name}`)
+ return target.type
+}
+
+function storedValue(
+ graph: SceneGraph,
+ type: VariableType,
+ name: string,
+ value: VariableInput
+): VariableValue {
+ if (isVariable(value)) return { aliasId: requireVariableId(graph, value) }
+ if (literalType(value) !== type)
+ throw new Error(`Variable ${name} mixes ${type} with ${literalType(value)} values`)
+ if (typeof value !== 'string') return value
+ const color = tryParseColor(value)
+ if (!color) throw new Error(`Variable ${name} has "${value}", which is not a color`)
+ return color
+}
+
+/**
+ * Create or update the collections a tree defines, by name: their modes, their variables, and
+ * each variable's value in each mode, a mode's missing values taken from the first mode.
+ */
+export function applyVariableDefinitions(graph: SceneGraph, tree: TreeNode): void {
+ const found = new Map<string, CollectionDefinition>()
+ collectDefinitions(tree, found)
+ const definitions = [...found.values()]
+ const collections = definitions.map((definition) => ensureCollection(graph, definition))
+
+ const variables = definitions.map((definition, index) => {
+ const collection = collections[index]
+ return Object.keys(definition.modes[0].values).map((name) => {
+ const type = definedType(graph, definition, name)
+ const existing = variableNamed(graph, collection, name)
+ if (existing && existing.type !== type)
+ throw new Error(`Variable ${name} in ${definition.name} is ${existing.type}, not ${type}`)
+ return existing ?? graph.createVariable(name, type, collection.id)
+ })
+ })
+
+ definitions.forEach((definition, index) => {
+ const collection = collections[index]
+ const [first] = definition.modes
+ for (const variable of variables[index]) {
+ for (const mode of definition.modes) {
+ const modeId = collection.modes.find((existing) => existing.name === mode.name)?.modeId
+ if (!modeId) continue
+ const value = mode.values[variable.name] ?? first.values[variable.name]
+ variable.valuesByMode[modeId] = storedValue(graph, variable.type, variable.name, value)
+ }
+ }
+ })
+}
+
+/** The ID of the variable a handle refers to: by collection and name, or by ID or name. */
+export function resolveVariableId(graph: SceneGraph, variable: DesignVariable): string | undefined {
+ if (variable.collection) {
+ const name =
+ typeof variable.collection === 'string' ? variable.collection : variable.collection.name
+ const collection = collectionNamed(graph, name)
+ return collection && variableNamed(graph, collection, variable.name)?.id
+ }
+ if (graph.variables.has(variable.name)) return variable.name
+ const matches = [...graph.variables.values()].filter((item) => item.name === variable.name)
+ if (matches.length > 1) {
+ const [first] = matches
+ const collection = graph.variableCollections.get(first.collectionId)?.name ?? ''
+ throw new Error(
+ `Variable name ${variable.name} is in more than one collection; name one, as in designVar('${collection}', '${variable.name}')`
+ )
+ }
+ return matches[0]?.id
+}
+
+export function requireVariableId(graph: SceneGraph, variable: DesignVariable): string {
+ const id = resolveVariableId(graph, variable)
+ if (id) return id
+ const collection =
+ typeof variable.collection === 'object' ? variable.collection.name : variable.collection
+ throw new Error(
+ collection
+ ? `Unknown variable ${variable.name} in ${collection}`
+ : `Unknown variable: ${variable.name}`
+ )
+}
+
+/** The collection and mode IDs a layer's `mode` prop pins, by their names. */
+export function variableModes(graph: SceneGraph, value: unknown): VariableModeMap | undefined {
+ if (value === undefined) return undefined
+ const modes: unknown[] = Array.isArray(value) ? value : [value]
+ const result: VariableModeMap = {}
+ for (const mode of modes) {
+ if (!isMode(mode)) throw new Error('mode takes defineMode() or designMode() modes')
+ const name = typeof mode.collection === 'string' ? mode.collection : mode.collection.name
+ const collection =
+ (typeof mode.collection === 'string' && graph.variableCollections.get(name)) ||
+ collectionNamed(graph, name)
+ if (!collection)
+ throw new Error(
+ `Unknown variable collection: ${name}. A defineVars() collection is added once a layer binds one of its variables`
+ )
+ const modeId = collection.modes.find((item) => item.name === mode.name)?.modeId
+ if (!modeId) throw new Error(`Collection ${name} has no mode named ${mode.name}`)
+ result[collection.id] = modeId
+ }
+ return result
+}
+
+/**
+ * A variable's value for a layer created under `parentId`, in the modes the layer pins or else
+ * the ones it inherits.
+ */
+export function resolveForLayer(
+ graph: SceneGraph,
+ variableId: string,
+ parentId: string,
+ modes: VariableModeMap | undefined
+): VariableLiteral | undefined {
+ try {
+ return resolveVariableInModes(
+ graph,
+ variableId,
+ (collectionId) =>
+ modes?.[collectionId] ?? getNodeVariableModeId(graph, parentId, collectionId)
+ )
+ } catch {
+ return undefined
+ }
+}
+
+/** Where a layer is created, and the modes it pins, which give a variable its value there. */
+export interface LayerContext {
+ parentId: string
+ modes: VariableModeMap | undefined
+}
+
+/** Bind the variable in `target[key]`, if it holds one, and put its value for the layer there. */
+export function bindVariableProp(
+ graph: SceneGraph,
+ target: Record<string, unknown>,
+ bindings: Record<string, string>,
+ key: string,
+ field: string,
+ layer: LayerContext
+): void {
+ const value = target[key]
+ if (!isVariable(value)) return
+ const variableId = requireVariableId(graph, value)
+ bindings[field] = variableId
+ const resolved = resolveForLayer(graph, variableId, layer.parentId, layer.modes)
+ if (resolved === undefined) throw new Error(`Cannot resolve variable ${value.name} for ${key}`)
+ target[key] = resolved
+}
diff --git a/packages/design-jsx/src/variables/index.ts b/packages/design-jsx/src/variables/index.ts
new file mode 100644
index 000000000..16ce47f19
--- /dev/null
+++ b/packages/design-jsx/src/variables/index.ts
@@ -0,0 +1,124 @@
+import { isPlainObject } from 'es-toolkit/predicate'
+
+import type { Color } from '@open-pencil/scene-graph/primitives'
+
+const VAR_SYMBOL = Symbol.for('open-pencil.variable')
+const MODE_SYMBOL = Symbol.for('open-pencil.variable-mode')
+
+/** The name a collection's first mode has when `defineVars` names none, as Figma names it. */
+export const DEFAULT_MODE_NAME = 'Mode 1'
+
+/**
+ * A value a variable holds in one mode: a color as a string or a `Color`, a number, a boolean,
+ * or another variable, which makes it an alias.
+ */
+export type VariableInput = string | Color | number | boolean | DesignVariable
+
+/** A collection as `defineVars` and `defineMode` declare it; the first mode is the default. */
+export interface CollectionDefinition {
+ name: string
+ modes: Array<{ name: string; values: Record<string, VariableInput> }>
+}
+
+/**
+ * A variable a field binds to. `defineVars` gives one its collection, which a render creates or
+ * updates; `designVar` names a variable the document already has, and may name its collection.
+ */
+export interface DesignVariable {
+ readonly [VAR_SYMBOL]: true
+ /** The variable's name, or for `designVar` without a collection, its name or ID. */
+ readonly name: string
+ readonly collection?: CollectionDefinition | string
+}
+
+/**
+ * A mode a layer shows a collection in. `defineMode` gives it the collection it declares;
+ * `designMode` names a collection the document already has.
+ */
+export interface DesignMode {
+ readonly [MODE_SYMBOL]: true
+ readonly name: string
+ readonly collection: CollectionDefinition | string
+}
+
+export function isVariable(value: unknown): value is DesignVariable {
+ return typeof value === 'object' && value !== null && VAR_SYMBOL in value
+}
+
+export function isMode(value: unknown): value is DesignMode {
+ return typeof value === 'object' && value !== null && MODE_SYMBOL in value
+}
+
+/** Whether a value can be a variable's value: a color, a number, a boolean, or a variable. */
+export function isVariableInput(value: unknown): value is VariableInput {
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
+ return true
+ if (isVariable(value)) return true
+ return isPlainObject(value) && ['r', 'g', 'b', 'a'].every((key) => typeof value[key] === 'number')
+}
+
+/**
+ * A variable the document already has: by its name or ID, or by the names of its collection and
+ * itself, as `designMode` names a mode, for a name more than one collection has.
+ */
+export function designVar(idOrName: string): DesignVariable
+export function designVar(collection: string, name: string): DesignVariable
+export function designVar(first: string, second?: string): DesignVariable {
+ return Object.freeze(
+ second === undefined
+ ? { [VAR_SYMBOL]: true as const, name: first }
+ : { [VAR_SYMBOL]: true as const, name: second, collection: first }
+ )
+}
+
+/**
+ * Define a variable collection: its variables, by name, with their values in its first mode,
+ * named `mode` (Figma's `Mode 1` by default). A render that binds any of them creates the
+ * collection, or updates the one with that name, so running the JSX again changes nothing twice.
+ */
+export function defineVars<T extends Record<string, VariableInput>>(
+ collection: string,
+ values: T,
+ options: { mode?: string } = {}
+): { [K in keyof T]: DesignVariable } {
+ const definition: CollectionDefinition = {
+ name: collection,
+ modes: [{ name: options.mode ?? DEFAULT_MODE_NAME, values }]
+ }
+ const handles = {} as { [K in keyof T]: DesignVariable }
+ for (const name of Object.keys(values) as Array<keyof T & string>) {
+ handles[name] = Object.freeze({ [VAR_SYMBOL]: true as const, name, collection: definition })
+ }
+ return handles
+}
+
+/**
+ * Add a mode to a collection `defineVars` defined, with the values that differ from its first
+ * mode; the rest keep the first mode's values, as a mode Figma adds copies them.
+ */
+export function defineMode(
+ vars: Record<string, DesignVariable>,
+ name: string,
+ values: Record<string, VariableInput>
+): DesignMode {
+ const definition = Object.values(vars)[0]?.collection
+ if (!definition || typeof definition === 'string')
+ throw new Error('defineMode() takes the variables defineVars() returned')
+ if (definition.modes.some((mode) => mode.name === name))
+ throw new Error(`Collection ${definition.name} already has a mode named ${name}`)
+ const known = definition.modes[0].values
+ for (const key of Object.keys(values)) {
+ if (!Object.hasOwn(known, key))
+ throw new Error(`Collection ${definition.name} has no variable named ${key}`)
+ }
+ definition.modes.push({ name, values })
+ return Object.freeze({ [MODE_SYMBOL]: true as const, name, collection: definition })
+}
+
+/**
+ * A mode of a collection the document already has, by their names, or by the collection's ID
+ * when several collections share its name.
+ */
+export function designMode(collection: string, mode: string): DesignMode {
+ return Object.freeze({ [MODE_SYMBOL]: true as const, name: mode, collection })
+}
diff --git a/packages/design-jsx/src/vars.ts b/packages/design-jsx/src/vars.ts
deleted file mode 100644
index 511112cc0..000000000
--- a/packages/design-jsx/src/vars.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import type { SceneGraph } from '@open-pencil/scene-graph'
-import type { Color } from '@open-pencil/scene-graph/primitives'
-
-const VAR_SYMBOL = Symbol.for('open-pencil.variable')
-
-export type VarDef =
- | string
- | {
- id?: string
- name?: string
- value?: string | Color | number
- }
-
-export interface DesignVariable {
- [VAR_SYMBOL]: true
- id?: string
- name: string
- value?: string | Color | number
-}
-
-export function resolveVariableId(graph: SceneGraph, variable: DesignVariable): string | undefined {
- if (variable.id && graph.variables.has(variable.id)) return variable.id
- if (variable.id && !variable.name) return variable.id
- for (const candidate of graph.variables.values()) {
- if (candidate.name === variable.name || candidate.id === variable.name) return candidate.id
- }
- return variable.id
-}
-
-export function isVariable(value: unknown): value is DesignVariable {
- return typeof value === 'object' && value !== null && VAR_SYMBOL in value
-}
-
-export function defineVars<T extends Record<string, VarDef>>(
- vars: T
-): { [K in keyof T]: DesignVariable } {
- const result = {} as { [K in keyof T]: DesignVariable }
-
- for (const [key, def] of Object.entries(vars)) {
- result[key as keyof T] = designVar(def)
- }
-
- return result
-}
-
-export function designVar(def: VarDef): DesignVariable
-export function designVar(idOrName: string, value?: DesignVariable['value']): DesignVariable
-export function designVar(def: VarDef, value?: DesignVariable['value']): DesignVariable {
- if (typeof def === 'string') {
- return {
- [VAR_SYMBOL]: true,
- id: def,
- name: def,
- value
- }
- }
-
- return {
- [VAR_SYMBOL]: true,
- id: def.id,
- name: def.name ?? def.id ?? '',
- value: def.value
- }
-}
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index f5a585ad4..2d63d6d75 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -35,16 +35,19 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
-- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
+- `defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' })` defines a collection in the file's variables table and returns its variables by name, such as `theme.Page`. Each value is the variable's value in the first mode, named by `mode` (`Mode 1` without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as `palette['Gray/900']`. `defineMode(theme, 'Dark', { Page: '#111111' })` adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.
+- `designVar('name-or-id')` refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as `designMode` does: `designVar('Theme', 'Line')`.
- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
-- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
+- `mode={dark}` shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and `designMode('Theme', 'Dark')` names a mode of a collection the document already has, by the collection's ID when several share its name. Without `mode`, a layer inherits its parent's.
+- Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.
- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.
-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.
-- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.
-- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
+- `property(name, defaultValue)` binds a field of a component's layer to a component property, created on first use: `text={property('Message', 'Hi')}` on a `Text` makes a TEXT property, `visible={property('Pinned', true)}` a BOOLEAN one, and `of={property('Icon', 'Star')}` on an `Instance` an INSTANCE_SWAP one whose default is the component `of` names. The property belongs to the nearest `Component`, or to its `ComponentSet` for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.
+- An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Only instances accept `properties`.
+- `exposed` on an `Instance` in a component shows that instance's own properties on the component's instances, as Figma's "Expose properties from nested instances" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: `<Instance of="Card" Title="Welcome" Action={{ Variant: 'Secondary', Label: 'Save' }} />`, or `properties={{ Action: { … } }}`.
+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name or ID for swaps, as `of` does, whether set as a prop or in `properties`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.
- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.
@@ -89,6 +92,25 @@ The examples below are executed by the authoring-reference tests. Create the nam
</Frame>
```
+## A theme with two modes
+
+```jsx
+const theme = defineVars('Theme', { Surface: '#FFFFFF', Ink: '#252A31', Radius: 12 }, { mode: 'Light' })
+const dark = defineMode(theme, 'Dark', { Surface: '#1A1A20', Ink: '#F5F5F7' })
+return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p={16} bg={theme.Surface} rounded={theme.Radius}>
+<Text name="Message" w="fill" size={12} color={theme.Ink}>Shown in the Dark mode of the Theme collection.</Text>
+</Frame>
+```
+
+## Component with text and visibility properties
+
+```jsx
+<Component name="Comment" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
+<Text name="Author" size={12} weight="medium" color="#252A31" text={property('Author', 'June Lee')} />
+<Text name="Message" w="fill" size={12} color="#6B7079" text={property('Message', 'Give the date more room.')} visible={property('Show message', true)} />
+</Component>
+```
+
## Rich text with spans and lists
```jsx
@@ -108,6 +130,6 @@ Generated from the renderer metadata. This inventory lists accepted names, not a
**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
-**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.
+**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index f5a585ad4..2d63d6d75 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -35,16 +35,19 @@ This reference describes scene creation, not React DOM output. Use the `render`
## Variables and components
-- Create document variables before referencing them with `designVar('id-or-name')`. `defineVars` groups references; it does not create variable collections.
+- `defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' })` defines a collection in the file's variables table and returns its variables by name, such as `theme.Page`. Each value is the variable's value in the first mode, named by `mode` (`Mode 1` without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as `palette['Gray/900']`. `defineMode(theme, 'Dark', { Page: '#111111' })` adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.
+- `designVar('name-or-id')` refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as `designMode` does: `designVar('Theme', 'Line')`.
- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is `lineHeight` and `letterSpacing`, which also take a percent of the font size such as `"150%"` that follows the size when it changes.
-- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
+- `mode={dark}` shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and `designMode('Theme', 'Dark')` names a mode of a collection the document already has, by the collection's ID when several share its name. Without `mode`, a layer inherits its parent's.
+- Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.
- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.
- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.
-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.
-- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.
-- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
+- `property(name, defaultValue)` binds a field of a component's layer to a component property, created on first use: `text={property('Message', 'Hi')}` on a `Text` makes a TEXT property, `visible={property('Pinned', true)}` a BOOLEAN one, and `of={property('Icon', 'Star')}` on an `Instance` an INSTANCE_SWAP one whose default is the component `of` names. The property belongs to the nearest `Component`, or to its `ComponentSet` for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.
+- An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Only instances accept `properties`.
+- `exposed` on an `Instance` in a component shows that instance's own properties on the component's instances, as Figma's "Expose properties from nested instances" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: `<Instance of="Card" Title="Welcome" Action={{ Variant: 'Secondary', Label: 'Save' }} />`, or `properties={{ Action: { … } }}`.
+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name or ID for swaps, as `of` does, whether set as a prop or in `properties`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.
- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.
@@ -89,6 +92,25 @@ The examples below are executed by the authoring-reference tests. Create the nam
</Frame>
```
+## A theme with two modes
+
+```jsx
+const theme = defineVars('Theme', { Surface: '#FFFFFF', Ink: '#252A31', Radius: 12 }, { mode: 'Light' })
+const dark = defineMode(theme, 'Dark', { Surface: '#1A1A20', Ink: '#F5F5F7' })
+return <Frame name="Dark note" mode={dark} w={280} h="hug" flex="col" gap={8} p={16} bg={theme.Surface} rounded={theme.Radius}>
+<Text name="Message" w="fill" size={12} color={theme.Ink}>Shown in the Dark mode of the Theme collection.</Text>
+</Frame>
+```
+
+## Component with text and visibility properties
+
+```jsx
+<Component name="Comment" w={280} h="hug" flex="col" gap={8} p={16} bg="#FFFFFF">
+<Text name="Author" size={12} weight="medium" color="#252A31" text={property('Author', 'June Lee')} />
+<Text name="Message" w="fill" size={12} color="#6B7079" text={property('Message', 'Give the date more room.')} visible={property('Show message', true)} />
+</Component>
+```
+
## Rich text with spans and lists
```jsx
@@ -108,6 +130,6 @@ Generated from the renderer metadata. This inventory lists accepted names, not a
**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Sticky`, `Shape`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.
-**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.
+**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `defineVars`, `defineMode`, `designVar`, `designMode`, `property`, `ref`.
-**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `flipX`, `flipY`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `startAngle`, `endAngle`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.
\ No newline at end of file
diff --git a/src/AGENTS.md b/src/AGENTS.md
index c22337a23..da1509a5d 100644
--- a/src/AGENTS.md
+++ b/src/AGENTS.md
@@ -53,6 +53,7 @@ The supported browser baseline lives in `src/app/shell/support/baseline.ts` and
- Browser and native menus share `src/app/shell/menu/schema.ts`; handle IDs in `use.ts` or editor commands, and regenerate `desktop/generated/menu.json` with `bun run generate:tauri-menu`.
- Motion policy lives in `src/app/shell/motion/`: resolve the persisted System/Off preference and OS reduction once. The root `data-motion` attribute and the Tailwind `motion-safe`/`motion-reduce` variants represent the effective policy, including portalled content. Use the policy-aware Motion adapters rather than repeating preference conditionals in components.
- Canvas shortcuts stop while a dialog, menu, or listbox is open. A dialog that edits the document listens for undo and redo on its own content with `useDocumentShortcuts`, so keys in menus it portals never reach it; there is one history, the editor's (`src/app/shell/keyboard/document.ts`, `src/components/variables/VariablesDialog.vue`).
+- Code that can only run inline, such as the code panel's opaque-origin sandbox frame and the `blob:` worker it starts, is an ordinary module imported as `?script`, which bundles it into a string (`vite/inline-script.ts`); never write it as a source string or serialize functions (`src/app/code/sandbox/frame.ts`).
- Keep the app manifest in `vite/pwa.ts`; use `BrandMark` for in-app branding; never symlink web assets to desktop icons (`tools/AGENTS.md`, Brand assets).
## UI
diff --git a/src/app/ai/reply/run.ts b/src/app/ai/reply/run.ts
index 1613cf1ad..f880f655d 100644
--- a/src/app/ai/reply/run.ts
+++ b/src/app/ai/reply/run.ts
@@ -244,7 +244,7 @@ export function runAgentId(store: EditorStore): string | undefined {
/** Keep `snapshot` as the run's starting state of its page unless the run already edited it. */
export function recordRunBaseline(run: Run, snapshot: PageSnapshot): void {
- const pageId = snapshot.values().next().value?.id
+ const pageId = snapshot.nodes.values().next().value?.id
if (pageId && !run.baselines.has(pageId)) run.baselines.set(pageId, snapshot)
}
diff --git a/src/app/code/live-preview.ts b/src/app/code/live-preview.ts
index df385c4af..da762db2f 100644
--- a/src/app/code/live-preview.ts
+++ b/src/app/code/live-preview.ts
@@ -91,7 +91,7 @@ export async function previewDesignJSX(
let roots: TreeNode[]
try {
- roots = convertDesignJSXRoots(evaluated.roots, evaluated.lineOffset)
+ roots = convertDesignJSXRoots(evaluated.roots, evaluated.lineOffset, evaluated.collections)
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
diff --git a/src/app/code/sandbox/convert.ts b/src/app/code/sandbox/convert.ts
index 49ea868d8..203de890e 100644
--- a/src/app/code/sandbox/convert.ts
+++ b/src/app/code/sandbox/convert.ts
@@ -1,43 +1,23 @@
import { mapValues } from 'es-toolkit'
+import * as v from 'valibot'
import {
- angularGradient,
- backgroundBlur,
- designVar,
+ defineMode,
defineVars,
- diamondGradient,
- dropShadow,
- foregroundBlur,
- gradient,
- innerShadow,
- layerBlur,
- linearGradient,
- radialGradient,
+ designJSXHelpers,
+ isVariableInput,
ref as layerRef,
- solid,
+ type DesignMode,
+ type DesignVariable,
type LayerRef,
- type TreeNode
+ type TreeNode,
+ type VariableInput
} from '@open-pencil/design-jsx'
import type { DesignJSXHelperDescriptor } from '@/app/code/sandbox/types'
-const HELPERS = {
- solid,
- gradient,
- linearGradient,
- radialGradient,
- angularGradient,
- diamondGradient,
- dropShadow,
- innerShadow,
- layerBlur,
- backgroundBlur,
- foregroundBlur,
- designVar,
- defineVars
-}
-
-type HelperName = keyof typeof HELPERS
+/** The helpers a run's descriptors call, as the string renderer gives them to JSX. */
+const HELPERS: Record<string, (...args: never[]) => unknown> = designJSXHelpers([])
type PlainRecord = { [key: string]: unknown }
@@ -73,43 +53,102 @@ function isHelper(value: unknown): value is DesignJSXHelperDescriptor {
)
}
-/** The handle each numbered `ref()` of one evaluation stands for. */
-type RefHandles = Map<unknown, LayerRef>
+/** A collection as the sandbox's `defineVars` writes it, with the modes `defineMode` added. */
+const collectionRecordSchema = v.object({
+ collection: v.string(),
+ values: v.record(v.string(), v.unknown()),
+ options: v.object({ mode: v.optional(v.string()) }),
+ modes: v.array(v.object({ mode: v.string(), values: v.record(v.string(), v.unknown()) }))
+})
+
+/** One evaluation's handles: each numbered `ref()`, and each collection's variables and modes. */
+type Collection = {
+ variables: Record<string, DesignVariable>
+ modes: Map<string, DesignMode>
+}
+type Handles = {
+ refs: Map<unknown, LayerRef>
+ records: unknown[]
+ collections: Map<number, Collection>
+}
+
+function variableValues(values: Record<string, unknown>, handles: Handles) {
+ return mapValues(values, (value, name): VariableInput => {
+ const converted = convertValue(value, handles)
+ if (!isVariableInput(converted)) throw new Error(`Variable ${name} has an unsupported value.`)
+ return converted
+ })
+}
-function convertValue(value: unknown, refs: RefHandles): unknown {
+/**
+ * The collection numbered `index`, defined once per evaluation. Its modes are defined after its
+ * variables, so a mode can alias the collection's own variables.
+ */
+function collection(index: unknown, handles: Handles): Collection {
+ if (typeof index !== 'number') throw new Error('Unknown variable collection.')
+ const known = handles.collections.get(index)
+ if (known) return known
+ const parsed = v.safeParse(collectionRecordSchema, handles.records[index])
+ if (!parsed.success) throw new Error('Unknown variable collection.')
+ const record = parsed.output
+ const variables = defineVars(
+ record.collection,
+ variableValues(record.values, handles),
+ record.options
+ )
+ const defined: Collection = { variables, modes: new Map() }
+ handles.collections.set(index, defined)
+ for (const mode of record.modes) {
+ const values = variableValues(mode.values, handles)
+ defined.modes.set(mode.mode, defineMode(variables, mode.mode, values))
+ }
+ return defined
+}
+
+function convertValue(value: unknown, handles: Handles): unknown {
if (isHelper(value)) {
const helperName = value.__openPencilHelper
+ const [first, second] = value.args
if (helperName === 'ref') {
- const [number] = value.args
- const handle = refs.get(number) ?? layerRef()
- refs.set(number, handle)
+ const handle = handles.refs.get(first) ?? layerRef()
+ handles.refs.set(first, handle)
return handle
}
- const helper = Object.hasOwn(HELPERS, helperName)
- ? (HELPERS[helperName as HelperName] as (...args: unknown[]) => unknown)
- : undefined
- if (typeof helper !== 'function') {
- throw new TypeError(`Unknown Design JSX helper "${helperName}".`)
+ if (helperName === 'variable') {
+ const variable =
+ typeof second === 'string' && Object.hasOwn(collection(first, handles).variables, second)
+ ? collection(first, handles).variables[second]
+ : undefined
+ if (!variable) throw new Error('Unknown variable.')
+ return variable
+ }
+ if (helperName === 'mode') {
+ const mode = typeof second === 'string' && collection(first, handles).modes.get(second)
+ if (!mode) throw new Error('Unknown variable mode.')
+ return mode
}
- return helper(...value.args.map((arg) => convertValue(arg, refs)))
+ if (!Object.hasOwn(HELPERS, helperName))
+ throw new TypeError(`Unknown Design JSX helper "${helperName}".`)
+ const helper = HELPERS[helperName] as (...args: unknown[]) => unknown
+ return helper(...value.args.map((arg) => convertValue(arg, handles)))
}
- if (Array.isArray(value)) return value.map((item) => convertValue(item, refs))
- if (isRecord(value)) return mapValues(value, (entry) => convertValue(entry, refs))
+ if (Array.isArray(value)) return value.map((item) => convertValue(item, handles))
+ if (isRecord(value)) return mapValues(value, (entry) => convertValue(entry, handles))
return value
}
-function convertTree(value: unknown, refs: RefHandles, lineOffset?: number): TreeNode {
+function convertTree(value: unknown, handles: Handles, lineOffset?: number): TreeNode {
if (!isSerializedElement(value)) {
throw new Error('Design JSX must return an OpenPencil element.')
}
const children = value.children.map((child): TreeNode | string => {
if (typeof child === 'string') return child
if (typeof child === 'number') return String(child)
- return convertTree(child, refs, lineOffset)
+ return convertTree(child, handles, lineOffset)
})
const tree: TreeNode = {
type: value.type,
- props: convertValue(value.props, refs) as PlainRecord,
+ props: convertValue(value.props, handles) as PlainRecord,
children
}
const line = sourceLine(value.source, lineOffset)
@@ -117,8 +156,12 @@ function convertTree(value: unknown, refs: RefHandles, lineOffset?: number): Tre
return tree
}
-export function convertDesignJSXRoots(values: unknown[], lineOffset?: number): TreeNode[] {
+export function convertDesignJSXRoots(
+ values: unknown[],
+ lineOffset?: number,
+ collections: unknown[] = []
+): TreeNode[] {
// Call validateDesignJSXOutput first; it enforces the depth bound used by this recursion.
- const refs: RefHandles = new Map()
- return values.map((value) => convertTree(value, refs, lineOffset))
+ const handles: Handles = { refs: new Map(), records: collections, collections: new Map() }
+ return values.map((value) => convertTree(value, handles, lineOffset))
}
diff --git a/src/app/code/sandbox/document.ts b/src/app/code/sandbox/document.ts
index 11d5a214c..9f9f9d1c8 100644
--- a/src/app/code/sandbox/document.ts
+++ b/src/app/code/sandbox/document.ts
@@ -1,132 +1,21 @@
-import type { DesignJSXValidationLimits } from '@/app/code/sandbox/types'
+const CONTENT_SECURITY_POLICY = [
+ "default-src 'none'",
+ "script-src 'unsafe-inline' 'unsafe-eval'",
+ "connect-src 'none'",
+ "img-src 'none'",
+ "media-src 'none'",
+ "font-src 'none'",
+ "style-src 'none'",
+ "object-src 'none'",
+ "frame-src 'none'",
+ 'worker-src blob:',
+ "base-uri 'none'",
+ "form-action 'none'"
+].join('; ')
-const workerSource = String.raw`
-self.onmessage = ({ data }) => {
- const { id, code, elements, helpers: helperNames, limits } = data
- const blocked = () => { throw new Error('Network access is unavailable in Design JSX.') }
- self.fetch = blocked
- self.XMLHttpRequest = undefined
- self.WebSocket = undefined
- self.EventSource = undefined
- self.importScripts = blocked
-
- const normalizeChildren = (children) => children.flat(Infinity).filter((child) => child != null && child !== false)
- const __fragment = ''
- const __h = (type, props, ...children) => {
- const { __source, __self, ...normalizedProps } = props == null ? {} : props
- const normalizedChildren = normalizeChildren(children)
- if (typeof type === 'function') return type({ ...normalizedProps, children: normalizedChildren })
- if (type === __fragment) return normalizedChildren
- const element = { type, props: normalizedProps, children: normalizedChildren }
- if (__source && typeof __source.lineNumber === 'number') element.source = __source.lineNumber
- return element
- }
- const helper = (name) => (...args) => ({ __openPencilHelper: name, args })
- // Each ref() is numbered, so the layer it marks and the ends that refer to it share one handle.
- let refs = 0
- const helperRuntime = (name) => {
- if (name === 'ref') return () => ({ __openPencilHelper: 'ref', args: [++refs] })
- if (name === 'defineVars') return (vars) => Object.fromEntries(Object.entries(vars).map(([key, value]) => [key, { __openPencilHelper: 'designVar', args: [value] }]))
- return helper(name)
- }
- // A dotted element such as Button.Root is a member of its namespace, as JSX reads the tag.
- const tags = {}
- for (const [name, type] of Object.entries(elements)) {
- const [space, member] = name.split('.')
- if (member === undefined) tags[name] = type
- else (tags[space] ??= {})[member] = type
- }
- const names = Object.keys(tags)
- const helpers = Object.fromEntries(helperNames.map((name) => [name, helperRuntime(name)]))
- const validate = (value, depth = 0, state = { elements: 0, bytes: 0 }) => {
- if (depth > limits.depth) throw new Error('Design JSX output is too deeply nested.')
- if (value === null) {
- state.bytes += 4
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- return state
- }
- if (typeof value === 'boolean') {
- state.bytes += value ? 4 : 5
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- return state
- }
- if (typeof value === 'number') {
- if (!Number.isFinite(value)) throw new Error('Design JSX output contains an invalid number.')
- state.bytes += 8
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- return state
- }
- if (typeof value === 'string') {
- if (value.length > limits.stringLength) throw new Error('Design JSX output contains a string that is too long.')
- state.bytes += new TextEncoder().encode(value).byteLength
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- return state
- }
- if (Array.isArray(value)) {
- state.bytes += 2 + Math.max(0, value.length - 1)
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- if (value.length > limits.arrayLength) throw new Error('Design JSX output contains an array that is too long.')
- for (const item of value) validate(item, depth + 1, state)
- return state
- }
- if (typeof value !== 'object') throw new Error('Design JSX output contains an unsupported value.')
- const keys = Object.keys(value)
- state.bytes += 2 + Math.max(0, keys.length - 1)
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- if (keys.length > limits.objectKeys) throw new Error('Design JSX output contains too many object properties.')
- if ('type' in value && 'props' in value && 'children' in value && ++state.elements > limits.elements) throw new Error('Design JSX output has too many elements.')
- for (const key of keys) {
- if (key === '__proto__' || key === 'prototype' || key === 'constructor') throw new Error('Design JSX output contains a blocked property.')
- state.bytes += key.length
- if (state.bytes > limits.outputBytes) throw new Error('Design JSX output is too large.')
- validate(value[key], depth + 1, state)
- }
- return state
- }
- try {
- const argumentNames = ['__h', '__fragment', ...names, ...helperNames]
- const argumentValues = [__h, __fragment, ...names.map((name) => tags[name]), ...helperNames.map((name) => helpers[name])]
- const run = new Function(...argumentNames, code)
- const value = run(...argumentValues)
- validate(value)
- self.postMessage({ id, ok: true, value })
- } catch (error) {
- self.postMessage({ id, ok: false, error: error instanceof Error ? error.message : String(error) })
- }
-}
-`
-
-export type SandboxDocumentOptions = {
- elements: Record<string, string>
- helpers: string[]
- limits: DesignJSXValidationLimits
-}
-
-export function sandboxDocument({ elements, helpers, limits }: SandboxDocumentOptions): string {
- const escapedWorkerSource = JSON.stringify(workerSource)
- const escapedElements = JSON.stringify(elements)
- const escapedHelpers = JSON.stringify(helpers)
- const escapedLimits = JSON.stringify(limits)
- return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; connect-src 'none'; img-src 'none'; media-src 'none'; font-src 'none'; style-src 'none'; object-src 'none'; frame-src 'none'; worker-src blob:; base-uri 'none'; form-action 'none'"></head><body><script>
- const workerURL = URL.createObjectURL(new Blob([${escapedWorkerSource}], { type: 'text/javascript' }))
- const workers = new Map()
- addEventListener('message', (event) => {
- const message = event.data
- if (!message || message.type !== 'open-pencil-design-jsx-run') return
- const worker = new Worker(workerURL)
- workers.set(message.id, worker)
- worker.onmessage = ({ data }) => {
- parent.postMessage({ type: 'open-pencil-design-jsx-result', ...data }, '*')
- worker.terminate()
- workers.delete(message.id)
- }
- worker.onerror = () => {
- parent.postMessage({ type: 'open-pencil-design-jsx-result', id: message.id, ok: false, error: 'Design JSX execution failed.' }, '*')
- worker.terminate()
- workers.delete(message.id)
- }
- worker.postMessage({ id: message.id, code: message.code, elements: ${escapedElements}, helpers: ${escapedHelpers}, limits: ${escapedLimits} })
- })
- parent.postMessage({ type: 'open-pencil-design-jsx-ready' }, '*')
- </script></body></html>`
+/** The sandbox frame's document: the bundled frame script (`frame.ts?script`) under a strict CSP. */
+export function sandboxDocument(frameScript: string): string {
+ // HTML ends a script at `</script` in any case.
+ if (/<\/script/i.test(frameScript)) throw new Error('The sandbox frame script cannot be inlined.')
+ return `<!doctype html><html><head><meta http-equiv="Content-Security-Policy" content="${CONTENT_SECURITY_POLICY}"></head><body><script>${frameScript}</script></body></html>`
}
diff --git a/src/app/code/sandbox/evaluate.ts b/src/app/code/sandbox/evaluate.ts
index 2ee67aa35..3e5798026 100644
--- a/src/app/code/sandbox/evaluate.ts
+++ b/src/app/code/sandbox/evaluate.ts
@@ -1,3 +1,5 @@
+import * as v from 'valibot'
+
import { IS_BROWSER } from '@open-pencil/core/constants'
import {
DESIGN_JSX_ELEMENTS,
@@ -7,6 +9,13 @@ import {
} from '@open-pencil/design-jsx'
import { sandboxDocument } from '@/app/code/sandbox/document'
+import frameScript from '@/app/code/sandbox/frame.ts?script'
+import {
+ SANDBOX_READY,
+ SANDBOX_RUN,
+ sandboxFrameMessageSchema,
+ type SandboxRunRequest
+} from '@/app/code/sandbox/schema'
import {
DESIGN_JSX_DEFAULT_READY_TIMEOUT_MS,
DESIGN_JSX_DEFAULT_TIMEOUT_MS,
@@ -44,13 +53,7 @@ export async function evaluateDesignJSX(
const iframe = document.createElement('iframe')
iframe.hidden = true
iframe.setAttribute('sandbox', 'allow-scripts')
- iframe.srcdoc = sandboxDocument({
- elements: Object.fromEntries(
- DESIGN_JSX_ELEMENTS.map(({ name, runtimeType }) => [name, runtimeType])
- ),
- helpers: DESIGN_JSX_HELPERS.map(({ name }) => name),
- limits: validationLimits
- })
+ iframe.srcdoc = sandboxDocument(frameScript)
document.body.append(iframe)
return new Promise((resolve) => {
@@ -69,36 +72,39 @@ export async function evaluateDesignJSX(
// eslint-disable-next-line promise/no-multiple-resolved -- settled guard makes completion single-shot
resolve(result)
}
- const onMessage = (event: MessageEvent) => {
+ const onMessage = (event: MessageEvent<unknown>) => {
if (event.source !== iframe.contentWindow || event.origin !== 'null') return
- const message = event.data as {
- type?: string
- id?: string
- ok?: boolean
- value?: unknown
- error?: string
- }
- if (message.type === 'open-pencil-design-jsx-ready') {
+ const parsed = v.safeParse(sandboxFrameMessageSchema, event.data)
+ if (!parsed.success) return
+ const message = parsed.output
+ if (message.type === SANDBOX_READY) {
clearTimeout(timer)
// eslint-disable-next-line promise/no-multiple-resolved -- finish has a settled guard
timer = setTimeout(
() => finish({ ok: false, error: 'Design JSX execution timed out.' }),
timeoutMs
)
- iframe.contentWindow?.postMessage(
- { type: 'open-pencil-design-jsx-run', id, code: program.code },
- '*'
- )
+ const request: SandboxRunRequest = {
+ id,
+ code: program.code,
+ elements: Object.fromEntries(
+ DESIGN_JSX_ELEMENTS.map(({ name, runtimeType }) => [name, runtimeType])
+ ),
+ helpers: DESIGN_JSX_HELPERS.map(({ name }) => name),
+ limits: validationLimits
+ }
+ iframe.contentWindow?.postMessage({ type: SANDBOX_RUN, ...request }, '*')
return
}
- if (message.type !== 'open-pencil-design-jsx-result' || message.id !== id) return
+ if (message.id !== id) return
if (!message.ok) {
- finish({ ok: false, error: message.error ?? 'Design JSX execution failed.' })
+ finish({ ok: false, error: message.error })
return
}
try {
- const roots = validateDesignJSXOutput(message.value, validationLimits)
- finish({ ok: true, roots, lineOffset: program.lineOffset })
+ const { collections } = message
+ const roots = validateDesignJSXOutput(message.value, validationLimits, collections)
+ finish({ ok: true, roots, collections, lineOffset: program.lineOffset })
} catch (error) {
finish({ ok: false, error: error instanceof Error ? error.message : String(error) })
}
diff --git a/src/app/code/sandbox/frame.ts b/src/app/code/sandbox/frame.ts
new file mode 100644
index 000000000..3ac9fd75b
--- /dev/null
+++ b/src/app/code/sandbox/frame.ts
@@ -0,0 +1,41 @@
+/**
+ * The sandbox frame's script (`document.ts`): runs each request from the host in a fresh worker
+ * and reports its result. The frame has an opaque origin, so it starts the worker from its
+ * bundled source rather than a URL of the app.
+ */
+import * as v from 'valibot'
+
+import {
+ SANDBOX_READY,
+ SANDBOX_RESULT,
+ sandboxHostMessageSchema,
+ sandboxRunResultSchema,
+ type SandboxRunResult
+} from '@/app/code/sandbox/schema'
+
+import workerSource from './worker/index.ts?script'
+
+const workerURL = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }))
+
+addEventListener('message', (event: MessageEvent<unknown>) => {
+ const message = v.safeParse(sandboxHostMessageSchema, event.data)
+ if (!message.success) return
+ const { type: _type, ...request } = message.output
+ const worker = new Worker(workerURL)
+ const report = (result: SandboxRunResult) => {
+ parent.postMessage({ type: SANDBOX_RESULT, ...result }, '*')
+ worker.terminate()
+ }
+ const failed = (): SandboxRunResult => ({
+ id: request.id,
+ ok: false,
+ error: 'Design JSX execution failed.'
+ })
+ worker.onmessage = ({ data }: MessageEvent<unknown>) => {
+ const result = v.safeParse(sandboxRunResultSchema, data)
+ report(result.success ? result.output : failed())
+ }
+ worker.onerror = () => report(failed())
+ worker.postMessage(request)
+})
+parent.postMessage({ type: SANDBOX_READY }, '*')
diff --git a/src/app/code/sandbox/schema.ts b/src/app/code/sandbox/schema.ts
new file mode 100644
index 000000000..94d2911ab
--- /dev/null
+++ b/src/app/code/sandbox/schema.ts
@@ -0,0 +1,65 @@
+/**
+ * The messages the host, the sandbox frame, and its worker exchange. Each side parses what it
+ * receives, as a message can come from any frame or script.
+ */
+import * as v from 'valibot'
+
+const designJSXValidationLimitsSchema = v.object({
+ outputBytes: v.number(),
+ elements: v.number(),
+ depth: v.number(),
+ arrayLength: v.number(),
+ objectKeys: v.number(),
+ stringLength: v.number()
+})
+
+export type DesignJSXValidationLimits = v.InferOutput<typeof designJSXValidationLimitsSchema>
+
+export const SANDBOX_READY = 'open-pencil-design-jsx-ready'
+export const SANDBOX_RUN = 'open-pencil-design-jsx-run'
+export const SANDBOX_RESULT = 'open-pencil-design-jsx-result'
+
+const runRequestEntries = {
+ id: v.string(),
+ code: v.string(),
+ /** Element names, such as `Frame` or `Button.Root`, by the runtime type they create. */
+ elements: v.record(v.string(), v.string()),
+ helpers: v.array(v.string()),
+ limits: designJSXValidationLimitsSchema
+}
+
+const resultEntries = {
+ succeeded: {
+ id: v.string(),
+ ok: v.literal(true),
+ value: v.unknown(),
+ collections: v.array(v.unknown())
+ },
+ failed: { id: v.string(), ok: v.literal(false), error: v.string() }
+}
+
+/** What the host asks the sandbox to run. */
+const sandboxRunRequestSchema = v.object(runRequestEntries)
+export type SandboxRunRequest = v.InferOutput<typeof sandboxRunRequestSchema>
+
+/** What the worker reports for a run. */
+export const sandboxRunResultSchema = v.variant('ok', [
+ v.object(resultEntries.succeeded),
+ v.object(resultEntries.failed)
+])
+export type SandboxRunResult = v.InferOutput<typeof sandboxRunResultSchema>
+
+/** A message the host sends the frame. */
+export const sandboxHostMessageSchema = v.object({
+ type: v.literal(SANDBOX_RUN),
+ ...runRequestEntries
+})
+
+/** A message the frame sends the host. */
+export const sandboxFrameMessageSchema = v.variant('type', [
+ v.object({ type: v.literal(SANDBOX_READY) }),
+ v.variant('ok', [
+ v.object({ type: v.literal(SANDBOX_RESULT), ...resultEntries.succeeded }),
+ v.object({ type: v.literal(SANDBOX_RESULT), ...resultEntries.failed })
+ ])
+])
diff --git a/src/app/code/sandbox/types.ts b/src/app/code/sandbox/types.ts
index 9ccacd207..f6b68ed11 100644
--- a/src/app/code/sandbox/types.ts
+++ b/src/app/code/sandbox/types.ts
@@ -1,5 +1,7 @@
import type { DesignJSXProgram } from '@open-pencil/design-jsx'
+import type { DesignJSXValidationLimits } from '@/app/code/sandbox/schema'
+
export const DESIGN_JSX_MAX_SOURCE_BYTES = 256_000
export const DESIGN_JSX_MAX_OUTPUT_BYTES = 2_000_000
export const DESIGN_JSX_MAX_ELEMENTS = 5_000
@@ -10,15 +12,6 @@ export const DESIGN_JSX_MAX_STRING_LENGTH = 100_000
export const DESIGN_JSX_DEFAULT_TIMEOUT_MS = 1_000
export const DESIGN_JSX_DEFAULT_READY_TIMEOUT_MS = 5_000
-export type DesignJSXValidationLimits = {
- outputBytes: number
- elements: number
- depth: number
- arrayLength: number
- objectKeys: number
- stringLength: number
-}
-
export type DesignJSXSandboxLimits = {
sourceBytes?: number
outputBytes?: number
@@ -50,5 +43,11 @@ export type DesignJSXHelperDescriptor = {
}
export type DesignJSXSandboxResult =
- | { ok: true; roots: unknown[]; lineOffset: DesignJSXProgram['lineOffset'] }
+ | {
+ ok: true
+ roots: unknown[]
+ /** The collections the run's `defineVars` calls wrote, which its variables name by index. */
+ collections: unknown[]
+ lineOffset: DesignJSXProgram['lineOffset']
+ }
| { ok: false; error: string }
diff --git a/src/app/code/sandbox/validate.ts b/src/app/code/sandbox/validate.ts
index 1d69e3bd6..15b1ed907 100644
--- a/src/app/code/sandbox/validate.ts
+++ b/src/app/code/sandbox/validate.ts
@@ -1,8 +1,8 @@
-import type { DesignJSXValidationLimits } from '@/app/code/sandbox/types'
+import type { DesignJSXValidationLimits } from '@/app/code/sandbox/schema'
const BLOCKED_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
-type ValidationState = {
+export type ValidationState = {
elements: number
bytes: number
}
@@ -95,14 +95,27 @@ function validateValue(
validateRecord(value, limits, state, depth)
}
+/** Check that `value` is plain structured data within `limits`, counting it toward `state`. */
+export function validateStructuredData(
+ value: unknown,
+ limits: DesignJSXValidationLimits,
+ state: ValidationState = { elements: 0, bytes: 0 }
+): ValidationState {
+ validateValue(value, limits, state, 0)
+ return state
+}
+
+/** The roots a run returned, checked with the collections its `defineVars` calls wrote. */
export function validateDesignJSXOutput(
value: unknown,
- limits: DesignJSXValidationLimits
+ limits: DesignJSXValidationLimits,
+ collections: unknown = []
): unknown[] {
if (value === undefined) throw new Error('Design JSX must return an OpenPencil element.')
const roots = Array.isArray(value) ? value : [value]
if (roots.length === 0) throw new Error('Design JSX must return an OpenPencil element.')
- const state: ValidationState = { elements: 0, bytes: 0 }
- validateValue(roots, limits, state, 0)
+ if (!Array.isArray(collections))
+ throw new Error('Design JSX output must contain plain structured data only.')
+ validateStructuredData(collections, limits, validateStructuredData(roots, limits))
return roots
}
diff --git a/src/app/code/sandbox/worker/index.ts b/src/app/code/sandbox/worker/index.ts
new file mode 100644
index 000000000..0bc5e3b48
--- /dev/null
+++ b/src/app/code/sandbox/worker/index.ts
@@ -0,0 +1,22 @@
+/**
+ * The sandbox worker's entry, which the frame starts from a `blob:` URL (`frame.ts`). Code it
+ * runs reaches no network: the worker's own globals for it are replaced before the first run.
+ */
+import type { SandboxRunRequest } from '@/app/code/sandbox/schema'
+
+import { runDesignJSX } from './run'
+
+const blocked = () => {
+ throw new Error('Network access is unavailable in Design JSX.')
+}
+Object.defineProperties(self, {
+ fetch: { value: blocked },
+ XMLHttpRequest: { value: undefined },
+ WebSocket: { value: undefined },
+ EventSource: { value: undefined },
+ importScripts: { value: blocked }
+})
+
+self.onmessage = (event: MessageEvent<SandboxRunRequest>) => {
+ self.postMessage(runDesignJSX(event.data))
+}
diff --git a/src/app/code/sandbox/worker/run.ts b/src/app/code/sandbox/worker/run.ts
new file mode 100644
index 000000000..6764610b5
--- /dev/null
+++ b/src/app/code/sandbox/worker/run.ts
@@ -0,0 +1,128 @@
+import type { SandboxRunRequest, SandboxRunResult } from '@/app/code/sandbox/schema'
+import type { DesignJSXHelperDescriptor } from '@/app/code/sandbox/types'
+import { validateStructuredData } from '@/app/code/sandbox/validate'
+
+type Element = {
+ type: unknown
+ props: Record<string, unknown>
+ children: unknown[]
+ source?: number
+}
+type CollectionRecord = {
+ collection: unknown
+ values: Record<string, unknown>
+ options: unknown
+ modes: Array<{ mode: unknown; values: unknown }>
+}
+
+const FRAGMENT = ''
+
+function normalizeChildren(children: unknown[]): unknown[] {
+ return children.flat(Infinity).filter((child) => child != null && child !== false)
+}
+
+function createElement(
+ type: unknown,
+ props: Record<string, unknown> | null,
+ ...children: unknown[]
+): unknown {
+ const { __source, __self: _self, ...normalizedProps } = props ?? {}
+ const normalizedChildren = normalizeChildren(children)
+ if (typeof type === 'function') return type({ ...normalizedProps, children: normalizedChildren })
+ if (type === FRAGMENT) return normalizedChildren
+ const element: Element = { type, props: normalizedProps, children: normalizedChildren }
+ const line = (__source as { lineNumber?: unknown } | undefined)?.lineNumber
+ if (typeof line === 'number') element.source = line
+ return element
+}
+
+function helper(name: string) {
+ return (...args: unknown[]): DesignJSXHelperDescriptor => ({
+ __openPencilHelper: name,
+ args
+ })
+}
+
+/**
+ * The helpers one run calls. They only describe their calls, which the host replays
+ * (`convert.ts`). Each `ref()` is numbered, so the layer it marks and the ends that refer to it
+ * share one handle. Each `defineVars()` collection is written once, with the modes `defineMode()`
+ * adds to it, and its variables and modes name it by number, so a mode can alias the
+ * collection's own variables.
+ */
+function helperRuntime() {
+ let refs = 0
+ const collections: CollectionRecord[] = []
+ const defineVars = (collection: unknown, values: Record<string, unknown>, options?: unknown) => {
+ const index = collections.push({ collection, values, options: options ?? {}, modes: [] }) - 1
+ return Object.fromEntries(
+ Object.keys(values).map((key): [string, DesignJSXHelperDescriptor] => [
+ key,
+ helper('variable')(index, key)
+ ])
+ )
+ }
+ const defineMode = (
+ vars: Record<string, DesignJSXHelperDescriptor>,
+ mode: unknown,
+ values: unknown
+ ) => {
+ const index = Object.values(vars)[0]?.args[0]
+ const record = typeof index === 'number' ? collections[index] : undefined
+ if (!record) throw new Error('defineMode() takes the variables defineVars() returned')
+ record.modes.push({ mode, values })
+ return helper('mode')(index, mode)
+ }
+ const byName = (name: string) => {
+ if (name === 'ref') return () => helper('ref')(++refs)
+ if (name === 'defineVars') return defineVars
+ if (name === 'defineMode') return defineMode
+ return helper(name)
+ }
+ return { byName, collections }
+}
+
+/** Element types by tag; a dotted element such as Button.Root is a member of its namespace. */
+function elementTags(elements: Record<string, string>) {
+ const tags: Record<string, string | Record<string, string>> = {}
+ for (const [name, type] of Object.entries(elements)) {
+ const dot = name.indexOf('.')
+ if (dot === -1) {
+ tags[name] = type
+ continue
+ }
+ const space = name.slice(0, dot)
+ const namespace = tags[space]
+ if (typeof namespace === 'object') namespace[name.slice(dot + 1)] = type
+ else tags[space] = { [name.slice(dot + 1)]: type }
+ }
+ return tags
+}
+
+/** Evaluate Design JSX into plain data the host can check and convert. */
+export function runDesignJSX({
+ id,
+ code,
+ elements,
+ helpers,
+ limits
+}: SandboxRunRequest): SandboxRunResult {
+ try {
+ const tags = elementTags(elements)
+ const names = Object.keys(tags)
+ const runtime = helperRuntime()
+ // eslint-disable-next-line typescript-eslint/no-implied-eval -- the sandbox exists to evaluate this code
+ const run = new Function('__h', '__fragment', ...names, ...helpers, code)
+ const value: unknown = run(
+ createElement,
+ FRAGMENT,
+ ...names.map((name) => tags[name]),
+ ...helpers.map(runtime.byName)
+ )
+ if (value === undefined) throw new Error('Design JSX must return an OpenPencil element.')
+ validateStructuredData(runtime.collections, limits, validateStructuredData(value, limits))
+ return { id, ok: true, value, collections: runtime.collections }
+ } catch (error) {
+ return { id, ok: false, error: error instanceof Error ? error.message : String(error) }
+ }
+}
diff --git a/src/env.d.ts b/src/env.d.ts
index 8befd4c2a..3c35e67aa 100644
--- a/src/env.d.ts
+++ b/src/env.d.ts
@@ -21,3 +21,9 @@ declare module '*.vue' {
const component: DefineComponent<object, object, unknown>
export default component
}
+
+/** A module bundled with its imports into one classic script, as a string (`vite/inline-script.ts`). */
+declare module '*?script' {
+ const source: string
+ export default source
+}
diff --git a/tests/e2e/code/sandbox.spec.ts b/tests/e2e/code/sandbox.spec.ts
index df1e4dfb9..e0aeecf92 100644
--- a/tests/e2e/code/sandbox.spec.ts
+++ b/tests/e2e/code/sandbox.spec.ts
@@ -42,6 +42,7 @@ test('evaluates JSX into plain inert data', async ({ page }) => {
source: 1
}
],
+ collections: [],
lineOffset: 0
})
})
@@ -76,22 +77,40 @@ return <Card title="Hello" visible />`
source: 3
}
],
+ collections: [],
lineOffset: 0
})
})
-test('converts variable helpers without executing host capabilities', async ({ page }) => {
+test('writes each defineVars() collection once, with the modes defineMode() adds', async ({
+ page
+}) => {
const result = await evaluate(
page,
- `const vars = defineVars({ primary: { name: 'Primary', value: '#ff0000' } })
-return <Frame fill={vars.primary}><Text color={designVar('text', '#000')}>Hello</Text></Frame>`
+ `const theme = defineVars('Theme', { Page: '#ffffff', Text: '#111111' }, { mode: 'Light' })
+const dark = defineMode(theme, 'Dark', { Page: '#111111', Text: theme.Page })
+return <Frame mode={dark} fill={theme.Page}><Text color={designVar('Ink')}>Hello</Text></Frame>`
)
expect(result.ok).toBe(true)
if (!result.ok) return
+ expect(result.collections).toEqual([
+ {
+ collection: 'Theme',
+ values: { Page: '#ffffff', Text: '#111111' },
+ options: { mode: 'Light' },
+ modes: [
+ {
+ mode: 'Dark',
+ values: { Page: '#111111', Text: { __openPencilHelper: 'variable', args: [0, 'Page'] } }
+ }
+ ]
+ }
+ ])
expect(result.roots[0]).toMatchObject({
type: 'frame',
props: {
- fill: { __openPencilHelper: 'designVar' }
+ mode: { __openPencilHelper: 'mode', args: [0, 'Dark'] },
+ fill: { __openPencilHelper: 'variable', args: [0, 'Page'] }
}
})
})
@@ -127,6 +146,7 @@ test('supports multiple roots through fragments', async ({ page }) => {
{ type: 'rectangle', props: { name: 'One' }, children: [], source: 1 },
{ type: 'ellipse', props: { name: 'Two' }, children: [], source: 1 }
],
+ collections: [],
lineOffset: 0
})
})
diff --git a/tests/engine/app/code/sandbox.test.ts b/tests/engine/app/code/sandbox.test.ts
index 048a747c1..b81cd8e4a 100644
--- a/tests/engine/app/code/sandbox.test.ts
+++ b/tests/engine/app/code/sandbox.test.ts
@@ -1,8 +1,9 @@
import { describe, expect, test } from 'bun:test'
-import { isLayerRef } from '@open-pencil/design-jsx'
+import { isLayerRef, isMode, isVariable } from '@open-pencil/design-jsx'
import { convertDesignJSXRoots } from '@/app/code/sandbox/convert'
+import { sandboxDocument } from '@/app/code/sandbox/document'
import {
DESIGN_JSX_MAX_ARRAY_LENGTH,
DESIGN_JSX_MAX_DEPTH,
@@ -13,6 +14,7 @@ import {
resolveDesignJSXValidationLimits
} from '@/app/code/sandbox/types'
import { validateDesignJSXOutput } from '@/app/code/sandbox/validate'
+import { runDesignJSX } from '@/app/code/sandbox/worker/run'
const limits = resolveDesignJSXValidationLimits({})
@@ -96,6 +98,21 @@ describe('Design JSX sandbox output', () => {
expect(() => validateDesignJSXOutput(frame(), tiny)).toThrow('too large')
})
+ test('converts every helper the renderer gives JSX, and nothing else', () => {
+ const [frameWithShader] = convertDesignJSXRoots(
+ validateDesignJSXOutput(
+ frame({ fill: { __openPencilHelper: 'shader', args: [[{ type: 'Aurora', props: {} }]] } }),
+ limits
+ )
+ )
+ expect(frameWithShader.props.fill).toMatchObject({
+ shader: { components: [{ type: 'Aurora' }] }
+ })
+ expect(() =>
+ convertDesignJSXRoots([frame({ fill: { __openPencilHelper: 'isVariableInput', args: [] } })])
+ ).toThrow('Unknown Design JSX helper "isVariableInput"')
+ })
+
test('rejects unknown helper descriptors during trusted conversion', () => {
for (const helperName of ['unknown', 'toString', 'constructor', 'valueOf']) {
const roots = validateDesignJSXOutput(
@@ -118,4 +135,90 @@ describe('Design JSX sandbox output', () => {
expect(connector.props.to).toBe(second.props.ref)
expect(first.props.ref).not.toBe(second.props.ref)
})
+
+ test('converts each written collection once, its modes able to alias its own variables', () => {
+ const variable = (name: string) => ({ __openPencilHelper: 'variable', args: [0, name] })
+ const collections = [
+ {
+ collection: 'Theme',
+ values: { Page: '#ffffff', Text: '#111111' },
+ options: { mode: 'Light' },
+ modes: [{ mode: 'Dark', values: { Page: '#111111', Text: variable('Page') } }]
+ }
+ ]
+ const roots = validateDesignJSXOutput(
+ [
+ frame({ fill: variable('Page'), mode: { __openPencilHelper: 'mode', args: [0, 'Dark'] } }),
+ frame({ fill: variable('Page') })
+ ],
+ limits,
+ collections
+ )
+ const [first, second] = convertDesignJSXRoots(roots, undefined, collections)
+ const page = first.props.fill
+ if (!isVariable(page) || typeof page.collection !== 'object')
+ throw new Error('Expected a defined variable')
+ expect(second.props.fill).toBe(page)
+ expect(isMode(first.props.mode) && first.props.mode.collection).toBe(page.collection)
+ expect(page.collection.modes).toEqual([
+ { name: 'Light', values: { Page: '#ffffff', Text: '#111111' } },
+ { name: 'Dark', values: { Page: '#111111', Text: page } }
+ ])
+ expect(() =>
+ convertDesignJSXRoots([frame({ fill: { __openPencilHelper: 'variable', args: [3, 'X'] } })])
+ ).toThrow('Unknown variable collection')
+ })
+
+ test('evaluates Design JSX into plain data in the worker', () => {
+ const run = (id: string, code: string) =>
+ runDesignJSX({
+ id,
+ code,
+ elements: { Frame: 'frame', 'Button.Root': 'Button.Root' },
+ helpers: ['solid', 'ref', 'defineVars', 'defineMode'],
+ limits
+ })
+ expect(
+ run(
+ 'theme',
+ `const t = defineVars('Theme', { Page: '#fff' }); const dark = defineMode(t, 'Dark', {})
+return __h(Frame, { fill: t.Page, mode: dark }, __h(Button.Root, null), 'Hi', false)`
+ )
+ ).toEqual({
+ id: 'theme',
+ ok: true,
+ value: {
+ type: 'frame',
+ props: {
+ fill: { __openPencilHelper: 'variable', args: [0, 'Page'] },
+ mode: { __openPencilHelper: 'mode', args: [0, 'Dark'] }
+ },
+ children: [{ type: 'Button.Root', props: {}, children: [] }, 'Hi']
+ },
+ collections: [
+ {
+ collection: 'Theme',
+ values: { Page: '#fff' },
+ options: {},
+ modes: [{ mode: 'Dark', values: {} }]
+ }
+ ]
+ })
+ expect(run('none', 'const frame = __h(Frame, null)')).toEqual({
+ id: 'none',
+ ok: false,
+ error: 'Design JSX must return an OpenPencil element.'
+ })
+ expect(run('date', 'return __h(Frame, { when: new Date(0) })')).toEqual({
+ id: 'date',
+ ok: false,
+ error: 'Design JSX output must contain plain structured data only.'
+ })
+ })
+
+ test('refuses a frame script that would close its own script element', () => {
+ expect(sandboxDocument('run()')).toContain('<script>run()</script>')
+ expect(() => sandboxDocument('"</script><script>alert(1)"')).toThrow('cannot be inlined')
+ expect(() => sandboxDocument('"</SCRIPT><script>alert(1)"')).toThrow('cannot be inlined')
+ })
})
diff --git a/tests/engine/render/jsx/component/properties.test.ts b/tests/engine/render/jsx/component/properties.test.ts
index 4fb6e84c7..519c77573 100644
--- a/tests/engine/render/jsx/component/properties.test.ts
+++ b/tests/engine/render/jsx/component/properties.test.ts
@@ -1,36 +1,36 @@
import { expect, expectTypeOf, test } from 'bun:test'
import { renderTree } from '@open-pencil/core/design-jsx'
-import { Component, ComponentSet, type Frame, Instance, Text, node } from '@open-pencil/design-jsx'
-import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'
+import {
+ Component,
+ ComponentSet,
+ type Frame,
+ Instance,
+ Text,
+ node,
+ property,
+ type ComponentProperty
+} from '@open-pencil/design-jsx'
import { getNodeOrThrow } from '#tests/helpers/assert'
import { makeSceneGraph } from '#tests/helpers/scene'
-test('property props are scoped to their authoring entities', () => {
+test('only instances take property values; layers bind fields to property()', () => {
expectTypeOf<Parameters<typeof Frame>[0]['properties']>().toEqualTypeOf<undefined>()
expectTypeOf<Parameters<typeof Text>[0]['properties']>().toEqualTypeOf<undefined>()
- expectTypeOf<Parameters<typeof Component>[0]['properties']>().toEqualTypeOf<
- SceneNode['componentPropertyDefinitions'] | undefined
- >()
+ expectTypeOf<Parameters<typeof Component>[0]['properties']>().toEqualTypeOf<undefined>()
expectTypeOf<Parameters<typeof Instance>[0]['properties']>().toEqualTypeOf<
- SceneNode['componentPropertyAssignments'] | undefined
+ | Record<string, string | boolean | number | Record<string, string | boolean | number>>
+ | undefined
+ >()
+ expectTypeOf<Parameters<typeof Text>[0]['text']>().toEqualTypeOf<
+ string | ComponentProperty<string> | undefined
+ >()
+ expectTypeOf<Parameters<typeof Text>[0]['visible']>().toEqualTypeOf<
+ boolean | ComponentProperty<boolean> | undefined
>()
})
-const MESSAGE: ComponentPropertyDefinition = {
- id: 'message',
- name: 'Message',
- type: 'TEXT',
- defaultValue: 'Default'
-}
-const VISIBLE: ComponentPropertyDefinition = {
- id: 'visible',
- name: 'Visible',
- type: 'BOOLEAN',
- defaultValue: 'true'
-}
-
async function setup() {
const graph = makeSceneGraph()
const component = await renderTree(
@@ -40,17 +40,13 @@ async function setup() {
flex: 'col',
w: 280,
h: 'hug',
- properties: [MESSAGE, VISIBLE],
children: [
Text({
name: 'Duplicate name',
- children: 'Default',
+ text: property('Message', 'Default'),
+ visible: property('Visible', true),
w: 'fill',
- color: '#111111',
- propertyRefs: [
- { propertyId: MESSAGE.id, field: 'TEXT' },
- { propertyId: VISIBLE.id, field: 'VISIBLE' }
- ]
+ color: '#111111'
}),
Text({ name: 'Duplicate name', children: 'Unrelated', color: '#111111' })
]
@@ -59,63 +55,107 @@ async function setup() {
return { graph, component }
}
+test('defines a property where a field binds it, typed by that field', async () => {
+ const { graph, component } = await setup()
+ const definitions = getNodeOrThrow(graph, component.id).componentPropertyDefinitions
+ expect(definitions.map(({ name, type, defaultValue }) => ({ name, type, defaultValue }))).toEqual(
+ [
+ { name: 'Message', type: 'TEXT', defaultValue: 'Default' },
+ { name: 'Visible', type: 'BOOLEAN', defaultValue: 'true' }
+ ]
+ )
+ const [text] = graph.getChildren(component.id)
+ expect(text.text).toBe('Default')
+ expect(text.componentPropertyReferences).toEqual([
+ { propertyId: definitions[0].id, field: 'TEXT' },
+ { propertyId: definitions[1].id, field: 'VISIBLE' }
+ ])
+})
+
test('assigns real text and visibility properties without resolving child names', async () => {
const { graph, component } = await setup()
const result = await renderTree(
graph,
- Instance({ of: component.id, properties: { message: 'June’s review', visible: 'false' } })
+ Instance({ of: component.id, properties: { Message: 'June’s review', Visible: false } })
)
const instance = getNodeOrThrow(graph, result.id)
const children = graph.getChildren(instance.id)
expect(children.map((child) => child.text)).toEqual(['June’s review', 'Unrelated'])
expect(children[0].visible).toBe(false)
- expect(instance.componentPropertyAssignments).toEqual({
- message: 'June’s review',
- visible: 'false'
- })
+ expect(Object.values(instance.componentPropertyAssignments)).toEqual(['June’s review', 'false'])
graph.syncInstances(component.id)
expect(graph.getChildren(instance.id)[0].text).toBe('June’s review')
expect(graph.getChildren(instance.id)[0].visible).toBe(false)
expect(graph.getChildren(component.id)[0].text).toBe('Default')
})
-test('variant selection ignores non-variant instance props', async () => {
+test('variants share the set’s property, and variant selection ignores other props', async () => {
const graph = makeSceneGraph()
const set = await renderTree(
graph,
ComponentSet({
name: 'Button',
- children: [
- Component({ name: 'variant=Primary', w: 100, h: 40 }),
+ children: ['Primary', 'Secondary'].map((variant) =>
Component({
- name: 'variant=Secondary',
+ name: `variant=${variant}`,
w: 100,
h: 40,
- properties: [MESSAGE],
- children: Text({
- children: 'Default',
- propertyRefs: [{ propertyId: MESSAGE.id, field: 'TEXT' }]
- })
+ children: Text({ text: property('Message', 'Default') })
})
- ]
+ )
})
)
+ const definitions = getNodeOrThrow(graph, set.id).componentPropertyDefinitions
+ expect(definitions.map(({ name, type }) => `${name}:${type}`)).toEqual([
+ 'Message:TEXT',
+ 'variant:VARIANT'
+ ])
+ for (const variant of graph.getChildren(set.id)) {
+ expect(variant.componentPropertyDefinitions).toEqual([])
+ expect(graph.getChildren(variant.id)[0].componentPropertyReferences).toEqual([
+ { propertyId: definitions[0].id, field: 'TEXT' }
+ ])
+ }
+
const result = await renderTree(
graph,
- Instance({ of: set.id, variant: 'Secondary', w: 120, properties: { message: 'Changed' } })
+ Instance({ of: set.id, variant: 'Secondary', w: 120, Message: 'Changed' })
)
const instance = getNodeOrThrow(graph, result.id)
expect(instance.componentId).toBe(graph.getChildren(set.id)[1].id)
expect(graph.getChildren(instance.id)[0].text).toBe('Changed')
})
+test('a property belongs to the nearest component, not an outer one', async () => {
+ const graph = makeSceneGraph()
+ const outer = await renderTree(
+ graph,
+ Component({ children: Component({ children: Text({ text: property('Caption', 'Hi') }) }) })
+ )
+ const [inner] = graph.getChildren(outer.id)
+ expect(getNodeOrThrow(graph, outer.id).componentPropertyDefinitions).toEqual([])
+ expect(inner.componentPropertyDefinitions.map((item) => item.name)).toEqual(['Caption'])
+})
+
+test('one property name with two types or two defaults is an error', async () => {
+ const graph = makeSceneGraph()
+ const label = (first: Parameters<typeof Text>[0], second: Parameters<typeof Text>[0]) =>
+ renderTree(graph, Component({ children: [Text(first), Text(second)] }))
+ await expect(
+ label({ text: property('Label', 'A') }, { visible: property('Label', true) })
+ ).rejects.toThrow('Component property Label is TEXT, not BOOLEAN')
+ await expect(
+ label({ text: property('Label', 'A') }, { text: property('Label', 'B') })
+ ).rejects.toThrow('Component property Label has two defaults: A and B')
+})
+
test('an assignment of the wrong type names the prop and the property', async () => {
const { graph, component } = await setup()
await expect(
// A script can pass any value; the types only describe valid calls.
- renderTree(graph, Instance({ of: component.id, properties: { message: 42 } as never }))
+ renderTree(graph, Instance({ of: component.id, properties: { Message: null } as never }))
).rejects.toThrow(
- 'Invalid properties on <Instance>:\n× Invalid type: Expected string but received 42\n → at message'
+ 'Invalid properties on <Instance>:\n× Invalid type: Expected ((string | boolean | number) | Object) but received null\n → at Message'
)
})
@@ -124,8 +164,8 @@ test('invalid assignments remove the new instance and do not edit its source', a
const count = graph.nodes.size
const invalidAssignments: Record<string, string>[] = [
{ missing: 'value' },
- { visible: 'yes' },
- { message: 'Changed', missing: 'value' }
+ { Visible: 'yes' },
+ { Message: 'Changed', missing: 'value' }
]
for (const assignments of invalidAssignments) {
await expect(
@@ -136,70 +176,118 @@ test('invalid assignments remove the new instance and do not edit its source', a
}
})
-test('assigns nested instance swaps through stable property references', async () => {
+test('binds an instance swap through of, its default the component of names', async () => {
const graph = makeSceneGraph()
const first = await renderTree(graph, Component({ name: 'First', w: 20, h: 20 }))
const second = await renderTree(graph, Component({ name: 'Second', w: 30, h: 30 }))
const component = await renderTree(
graph,
- Component({
- name: 'With slot',
- properties: [{ id: 'slot', name: 'Slot', type: 'INSTANCE_SWAP', defaultValue: first.id }],
- children: Instance({
- of: first.id,
- propertyRefs: [{ propertyId: 'slot', field: 'INSTANCE_SWAP' }]
- })
- })
- )
- const result = await renderTree(
- graph,
- Instance({ of: component.id, properties: { slot: second.id } })
+ Component({ name: 'With slot', children: Instance({ of: property('Slot', 'First') }) })
)
+ expect(getNodeOrThrow(graph, component.id).componentPropertyDefinitions).toMatchObject([
+ { name: 'Slot', type: 'INSTANCE_SWAP', defaultValue: first.id }
+ ])
+ const named = await renderTree(graph, Instance({ of: component.id, Slot: 'Second' }))
+ expect(graph.getChildren(named.id)[0].componentId).toBe(second.id)
+ const result = await renderTree(graph, Instance({ of: component.id, Slot: second.id }))
expect(graph.getChildren(result.id)[0].componentId).toBe(second.id)
graph.syncInstances(component.id)
expect(graph.getChildren(result.id)[0].componentId).toBe(second.id)
expect(graph.getChildren(component.id)[0].componentId).toBe(first.id)
})
-test('ordinary elements reject properties before rendering', async () => {
+test('property() binds text, visible, and of, on the layers that have them', async () => {
const graph = makeSceneGraph()
- for (const type of ['frame', 'text', 'rectangle', 'icon', 'svg']) {
- await expect(renderTree(graph, node(type, { properties: [MESSAGE] }))).rejects.toThrow(
- 'Only components'
+ const cases: Array<[ReturnType<typeof node>, string]> = [
+ [Component({ children: node('frame', { text: property('Label', 'A') }) }), 'needs <Text>'],
+ // A script can place a property anywhere; the types only describe valid calls.
+ [Component({ children: node('text', { opacity: property('Faded', true) }) }), 'not opacity'],
+ [Component({ children: node('text', { visible: property('Shown', 'yes') }) }), 'boolean'],
+ [Text({ text: property('Label', 'A') }), 'must be inside a <Component>']
+ ]
+ for (const [tree, message] of cases) {
+ await expect(renderTree(graph, tree)).rejects.toThrow(message)
+ }
+})
+
+test('elements other than instances reject properties before rendering', async () => {
+ const graph = makeSceneGraph()
+ for (const type of ['frame', 'text', 'rectangle', 'component', 'component-set']) {
+ await expect(renderTree(graph, node(type, { properties: [] }))).rejects.toThrow(
+ 'Only instances accept properties'
)
}
})
-test('validates metadata rather than accepting silent malformed property definitions', async () => {
+/** A Button set with a Label property, and a Card that exposes the Button it holds. */
+async function exposedSetup() {
const graph = makeSceneGraph()
- await expect(renderTree(graph, node('text', { properties: [MESSAGE] }))).rejects.toThrow(
- 'Only components'
- )
- await expect(renderTree(graph, Component({ properties: [MESSAGE, MESSAGE] }))).rejects.toThrow(
- 'Duplicate'
- )
- for (const element of [Component, ComponentSet]) {
- await expect(
- renderTree(
- graph,
- element({
- properties: [
- { id: 'kind-a', name: 'Kind', type: 'VARIANT', defaultValue: 'A' },
- { id: 'kind-b', name: 'Kind', type: 'VARIANT', defaultValue: 'B' }
- ]
+ const button = await renderTree(
+ graph,
+ ComponentSet({
+ name: 'Button',
+ children: ['Primary', 'Secondary'].map((variant) =>
+ Component({
+ name: `Variant=${variant}`,
+ children: Text({ text: property('Label', 'OK') })
})
)
- ).rejects.toThrow('Duplicate variant property names')
+ })
+ )
+ const card = await renderTree(
+ graph,
+ Component({
+ name: 'Card',
+ children: [
+ Text({ text: property('Title', 'Hello') }),
+ Instance({ name: 'Action', of: 'Button', exposed: true })
+ ]
+ })
+ )
+ return { graph, button, card }
+}
+
+test('an exposed instance takes its own properties and variant from the outer instance', async () => {
+ const { graph, button, card } = await exposedSetup()
+ expect(graph.getChildren(card.id)[1].isExposedInstance).toBe(true)
+ for (const tree of [
+ Instance({ of: 'Card', Title: 'Welcome', Action: { Label: 'Save', Variant: 'Secondary' } }),
+ Instance({
+ of: 'Card',
+ properties: { Title: 'Welcome', Action: { Label: 'Save', Variant: 'Secondary' } }
+ })
+ ]) {
+ const result = await renderTree(graph, tree)
+ const [title, action] = graph.getChildren(result.id)
+ expect(title.text).toBe('Welcome')
+ expect(action.componentId).toBe(graph.getChildren(button.id)[1].id)
+ expect(graph.getChildren(action.id)[0].text).toBe('Save')
+ graph.syncInstances(card.id)
+ const [, synced] = graph.getChildren(result.id)
+ expect(synced.componentId).toBe(graph.getChildren(button.id)[1].id)
+ expect(graph.getChildren(synced.id)[0].text).toBe('Save')
}
})
-test('preserves duplicate display names for non-variant properties with distinct IDs', async () => {
- const graph = makeSceneGraph()
- const result = await renderTree(
- graph,
- Component({ properties: [MESSAGE, { ...MESSAGE, id: 'other-message' }] })
+test('exposing follows Figma’s rules, and unknown exposed values are errors', async () => {
+ const { graph } = await exposedSetup()
+ await expect(renderTree(graph, Instance({ of: 'Button', exposed: true }))).rejects.toThrow(
+ 'exposed needs an <Instance> in a component'
+ )
+ const plain = await renderTree(graph, Component({ name: 'Plain', w: 10, h: 10 }))
+ await expect(
+ renderTree(graph, Component({ children: Instance({ of: plain.id, exposed: true }) }))
+ ).rejects.toThrow('Plain has no properties or exposed instances to expose')
+ await expect(
+ renderTree(graph, Instance({ of: 'Card', Action: { Missing: 'x' } }))
+ ).rejects.toThrow('Unknown component property on Action: Missing')
+ await expect(
+ renderTree(graph, Instance({ of: 'Card', Action: { Variant: 'Ghost' } }))
+ ).rejects.toThrow('Action has no variant Variant=Ghost')
+ await expect(
+ renderTree(graph, Instance({ of: 'Card', properties: { Other: { Label: 'x' } } }))
+ ).rejects.toThrow('Unknown component property or exposed instance: Other')
+ await expect(renderTree(graph, Instance({ of: 'Card', Title: { Label: 'x' } }))).rejects.toThrow(
+ 'Expected a string or boolean for component property: Title'
)
- expect(
- getNodeOrThrow(graph, result.id).componentPropertyDefinitions.map((item) => item.id)
- ).toEqual(['message', 'other-message'])
})
diff --git a/tests/engine/render/jsx/component/property-references.test.ts b/tests/engine/render/jsx/component/property-references.test.ts
deleted file mode 100644
index 00fac85ad..000000000
--- a/tests/engine/render/jsx/component/property-references.test.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { expect, test } from 'bun:test'
-
-import { renderTree } from '@open-pencil/core/design-jsx'
-import { Component, ComponentSet, Frame, Text } from '@open-pencil/design-jsx'
-import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'
-
-import { makeSceneGraph } from '#tests/helpers/scene'
-
-const definitions: ComponentPropertyDefinition[] = [
- { id: 'caption', name: 'Caption', type: 'TEXT', defaultValue: 'Hello' },
- { id: 'visible', name: 'Visible', type: 'BOOLEAN', defaultValue: 'true' }
-]
-
-for (const reference of [
- { propertyId: 'missing', field: 'TEXT' },
- { propertyId: 'visible', field: 'TEXT' },
- { propertyId: 'caption', field: 'VISIBLE' }
-] as const) {
- test(`rejects invalid scoped reference ${reference.propertyId}/${reference.field}`, async () => {
- await expect(
- renderTree(
- makeSceneGraph(),
- Component({
- properties: definitions,
- children: Frame({ children: Text({ children: 'Hello', propertyRefs: [reference] }) })
- })
- )
- ).rejects.toThrow(/component property/i)
- })
-}
-
-test('accepts references inherited from the owning component set', async () => {
- const result = await renderTree(
- makeSceneGraph(),
- ComponentSet({
- properties: definitions,
- children: Component({
- name: 'Kind=Default',
- children: Frame({
- children: Text({
- children: 'Hello',
- propertyRefs: [{ propertyId: 'caption', field: 'TEXT' }]
- })
- })
- })
- })
- )
- expect(result.type).toBe('COMPONENT_SET')
-})
-
-test('does not resolve a nested component reference against the outer component', async () => {
- await expect(
- renderTree(
- makeSceneGraph(),
- Component({
- properties: definitions,
- children: Component({
- children: Text({
- children: 'Hello',
- propertyRefs: [{ propertyId: 'caption', field: 'TEXT' }]
- })
- })
- })
- )
- ).rejects.toThrow('Unknown component property reference: caption')
-})
diff --git a/tests/engine/render/jsx/component/set-properties.test.ts b/tests/engine/render/jsx/component/set-properties.test.ts
deleted file mode 100644
index 61dc31fc4..000000000
--- a/tests/engine/render/jsx/component/set-properties.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { expect, test } from 'bun:test'
-
-import { renderTree } from '@open-pencil/core/design-jsx'
-import { Component, ComponentSet, Instance, Text } from '@open-pencil/design-jsx'
-import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'
-
-import { getNodeOrThrow } from '#tests/helpers/assert'
-import { makeSceneGraph } from '#tests/helpers/scene'
-
-const MESSAGE: ComponentPropertyDefinition = {
- id: 'message',
- name: 'Message',
- type: 'TEXT',
- defaultValue: 'Default'
-}
-const VARIANT: ComponentPropertyDefinition = {
- id: 'variant',
- name: 'variant',
- type: 'VARIANT',
- defaultValue: 'Primary',
- variantOptions: ['Primary', 'Secondary']
-}
-
-for (const explicitVariant of [false, true]) {
- test(`component-set properties preserve ${explicitVariant ? 'explicit' : 'inferred'} variant selection`, async () => {
- const graph = makeSceneGraph()
- const set = await renderTree(
- graph,
- ComponentSet({
- properties: explicitVariant ? [MESSAGE, VARIANT] : [MESSAGE],
- children: ['Primary', 'Secondary'].map((variant) =>
- Component({
- name: `variant=${variant}`,
- children: Text({
- children: 'Default',
- propertyRefs: [{ propertyId: MESSAGE.id, field: 'TEXT' }]
- })
- })
- )
- })
- )
- const result = await renderTree(
- graph,
- Instance({ of: set.id, variant: 'Secondary', properties: { message: 'Changed' } })
- )
- const instance = getNodeOrThrow(graph, result.id)
- expect(instance.componentId).toBe(graph.getChildren(set.id)[1].id)
- expect(graph.getChildren(instance.id)[0].text).toBe('Changed')
- const definitions = getNodeOrThrow(graph, set.id).componentPropertyDefinitions
- expect(definitions).toContainEqual(MESSAGE)
- expect(definitions.filter((definition) => definition.type === 'VARIANT')).toHaveLength(1)
- if (explicitVariant) expect(definitions).toContainEqual(VARIANT)
- })
-}
diff --git a/tests/engine/render/jsx/render-tree.test.ts b/tests/engine/render/jsx/render-tree.test.ts
index 2bdf011cc..6d253c99a 100644
--- a/tests/engine/render/jsx/render-tree.test.ts
+++ b/tests/engine/render/jsx/render-tree.test.ts
@@ -13,7 +13,6 @@ import {
Component,
ComponentSet,
Instance,
- defineVars,
designVar,
dropShadow,
innerShadow,
@@ -177,8 +176,10 @@ describe('renderTree', () => {
hiddenFromPublishing: false
})
- const vars = defineVars({ bg: { id: 'var-bg', name: 'Background' } })
- const result = await renderTree(g, Frame({ name: 'Bound', w: 100, h: 100, fill: vars.bg }))
+ const result = await renderTree(
+ g,
+ Frame({ name: 'Bound', w: 100, h: 100, fill: designVar('Background') })
+ )
const node = getNodeOrThrow(g, result.id)
expect(node.boundVariables['fills/0/color']).toBe('var-bg')
@@ -189,7 +190,7 @@ describe('renderTree', () => {
const g = makeSceneGraph()
addTestColorVariable(g, 'var-shadow', 'Shadow', { r: 0, g: 0, b: 0, a: 1 })
addTestColorVariable(g, 'var-bg', 'Background')
- const variable = designVar('var-shadow', '#000000')
+ const variable = designVar('var-shadow')
const result = await renderTree(
g,
Frame({
@@ -212,7 +213,7 @@ describe('renderTree', () => {
addTestColorVariable(g, 'var-bg', 'Background')
const [result] = await renderJSX(
g,
- `<Frame name="Bound JSX" w={100} h={100} fill={designVar('var-bg', '#ffffff')} />`
+ `<Frame name="Bound JSX" w={100} h={100} fill={designVar('var-bg')} />`
)
const node = getNodeOrThrow(g, result.id)
diff --git a/tests/engine/render/jsx/scalar-variables.test.ts b/tests/engine/render/jsx/scalar-variables.test.ts
index fcf5403ef..a54155adf 100644
--- a/tests/engine/render/jsx/scalar-variables.test.ts
+++ b/tests/engine/render/jsx/scalar-variables.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'bun:test'
import { renderJSX, renderTree } from '@open-pencil/core/design-jsx'
-import { Frame, Text, Rectangle, defineVars, designVar } from '@open-pencil/design-jsx'
+import { Frame, Text, Rectangle, designMode, designVar } from '@open-pencil/design-jsx'
import { getNodeOrThrow } from '#tests/helpers/assert'
import { addTestColorVariable, makeSceneGraph } from '#tests/helpers/scene'
@@ -80,16 +80,16 @@ describe('Design JSX scalar variables', () => {
expect(node.boundVariables).toEqual({ gridRowGap: 'space', gridColumnGap: 'space' })
})
- it('supports numeric fallback types, name lookup, typography, and fixed sizes', async () => {
+ it('binds typography and fixed sizes, finding a variable by name', async () => {
const { graph } = setup()
- const vars = defineVars({ space: { name: 'Space/medium', value: 16 } })
+ const space = designVar('Space/medium')
const result = await renderTree(
graph,
Text({
- w: vars.space,
- size: vars.space,
- lineHeight: vars.space,
- letterSpacing: vars.space,
+ w: space,
+ size: space,
+ lineHeight: space,
+ letterSpacing: space,
children: 'A'
})
)
@@ -107,7 +107,7 @@ describe('Design JSX scalar variables', () => {
const { graph } = setup()
const [result] = await renderJSX(
graph,
- '<Frame w={100} h="hug" flex="col" p={designVar("space", 16)} />'
+ '<Frame w={100} h="hug" flex="col" p={designVar("space")} />'
)
expect(result).toBeDefined()
expect(getNodeOrThrow(graph, result.id).boundVariables.paddingTop).toBe('space')
@@ -128,14 +128,33 @@ describe('Design JSX scalar variables', () => {
expect(node.height).toBe(36)
})
+ it('resolves a layer’s own values in the mode it pins', async () => {
+ const { graph, token } = setup()
+ const result = await renderTree(
+ graph,
+ Frame({
+ w: 100,
+ h: 'hug',
+ flex: 'col',
+ p: token,
+ mode: designMode('Spacing', 'Compact'),
+ children: Rectangle({ w: 20, h: 20 })
+ })
+ )
+ const node = getNodeOrThrow(graph, result.id)
+ expect(node.variableModes).toEqual({ spacing: 'compact' })
+ expect(node.paddingTop).toBe(8)
+ expect(node.height).toBe(36)
+ })
+
it('rejects missing and nonnumeric variables instead of storing objects in numeric fields', async () => {
const { graph } = setup()
addTestColorVariable(graph, 'color', 'Color')
await expect(renderTree(graph, Frame({ gap: designVar('color') }))).rejects.toThrow(
'Expected a FLOAT variable'
)
- await expect(renderTree(graph, Frame({ gap: designVar('missing', 16) }))).rejects.toThrow(
- 'Expected a FLOAT variable'
+ await expect(renderTree(graph, Frame({ gap: designVar('missing') }))).rejects.toThrow(
+ 'Unknown variable: missing'
)
})
})
diff --git a/tests/helpers/canvas/instance-sizing.ts b/tests/helpers/canvas/instance-sizing.ts
index cd6cc3fe7..ab00d166f 100644
--- a/tests/helpers/canvas/instance-sizing.ts
+++ b/tests/helpers/canvas/instance-sizing.ts
@@ -1,5 +1,5 @@
import { renderTree } from '@open-pencil/core/design-jsx'
-import { Component, Frame, Instance, Text } from '@open-pencil/design-jsx'
+import { Component, Frame, Instance, Text, property } from '@open-pencil/design-jsx'
import type { SceneGraph } from '@open-pencil/scene-graph'
export async function createInstanceSizingScene(graph: SceneGraph, parentId: string) {
@@ -14,7 +14,6 @@ export async function createInstanceSizingScene(graph: SceneGraph, parentId: str
p: 16,
bg: '#FFFFFF',
rounded: 10,
- properties: [{ id: 'message', name: 'Message', type: 'TEXT', defaultValue: 'A short note.' }],
children: Text({
name: 'Message',
w: 'fill',
@@ -22,8 +21,7 @@ export async function createInstanceSizingScene(graph: SceneGraph, parentId: str
size: 14,
lineHeight: 20,
color: '#252A31',
- propertyRefs: [{ propertyId: 'message', field: 'TEXT' }],
- children: 'A short note.'
+ text: property('Message', 'A short note.')
})
}),
{ parentId: library.id }
@@ -51,7 +49,7 @@ export async function createInstanceSizingScene(graph: SceneGraph, parentId: str
of: component.id,
w: 'fill',
properties: {
- message:
+ Message:
'The blue feels right. Give the date a little more room at the bottom, and keep the quieter version for the print edition.'
}
})
diff --git a/tests/helpers/chat/render-preview.ts b/tests/helpers/chat/render-preview.ts
index a9058b0d5..e863a62da 100644
--- a/tests/helpers/chat/render-preview.ts
+++ b/tests/helpers/chat/render-preview.ts
@@ -37,7 +37,13 @@ export function documentSnapshot(page: Page) {
return page.evaluate(() => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('Editor unavailable')
- return { nodes: [...store.snapshotPage()], undo: store.undo.canUndo }
+ const { nodes, variables, collections } = store.snapshotPage()
+ return {
+ nodes: [...nodes],
+ variables: [...variables],
+ collections: [...collections],
+ undo: store.undo.canUndo
+ }
})
}
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index e2aa4fd94..c4a561df2 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -354,8 +354,6 @@ tests/engine/render/canvas/tiles/scheduler.test.ts
tests/engine/render/canvas/variable-modes.test.ts
tests/engine/render/canvas/visual/boolean-matrix.test.ts
tests/engine/render/jsx/component/properties.test.ts
-tests/engine/render/jsx/component/property-references.test.ts
-tests/engine/render/jsx/component/set-properties.test.ts
tests/engine/render/jsx/gaps.test.ts
tests/engine/render/jsx/grid-layout.test.ts
tests/engine/render/jsx/instance-sizing.test.ts
diff --git a/tools/generate/demo/src/build.ts b/tools/generate/demo/src/build.ts
index 6076a55e3..39980d1ac 100644
--- a/tools/generate/demo/src/build.ts
+++ b/tools/generate/demo/src/build.ts
@@ -58,7 +58,7 @@ export async function withMeasuredText<T>(
export function buildDemoGraph(renderer: SkiaRenderer): Promise<SceneGraph> {
return withMeasuredText(renderer, async () => {
const graph = new SceneGraph()
- const theme = createTheme(graph)
+ const theme = createTheme()
const [page] = graph.getPages()
graph.updateNode(page.id, { name: PAGE_NAME })
setPageBackgrounds(graph, page, [
diff --git a/tools/generate/demo/src/document/callout.tsx b/tools/generate/demo/src/document/callout.tsx
index b54346dee..6eeb2ffe7 100644
--- a/tools/generate/demo/src/document/callout.tsx
+++ b/tools/generate/demo/src/document/callout.tsx
@@ -4,8 +4,8 @@
* It is a component with text properties, so its instances are the first thing a visitor who
* clicks one sees in the panel.
*/
-import { Component, Frame, Instance, Text, type TreeNode } from '@open-pencil/design-jsx'
-import type { ComponentPropertyDefinition, SceneGraph } from '@open-pencil/scene-graph'
+import { Component, Frame, Instance, Text, property, type TreeNode } from '@open-pencil/design-jsx'
+import type { SceneGraph } from '@open-pencil/scene-graph'
import { createComponentPropertyId } from '@open-pencil/scene-graph/components'
import { createSlotProperty, updateSlotProperty } from '@open-pencil/scene-graph/slots'
@@ -14,17 +14,12 @@ import { renderTree } from './icons'
import type { Theme } from './theme'
export const TIP_PROPERTIES = {
- step: { id: 'tip-step', name: 'Step', type: 'TEXT', defaultValue: '1' },
- title: { id: 'tip-title', name: 'Title', type: 'TEXT', defaultValue: 'Try this' },
- body: {
- id: 'tip-body',
- name: 'Body',
- type: 'TEXT',
- defaultValue: 'Select something on the canvas and look at the panel on the right.'
- },
- keys: { id: 'tip-keys', name: 'Shortcut', type: 'TEXT', defaultValue: '⌥ ⌘ ↩' },
- showKeys: { id: 'tip-show-keys', name: 'Show shortcut', type: 'BOOLEAN', defaultValue: 'true' }
-} satisfies Record<string, ComponentPropertyDefinition>
+ step: property('Step', '1'),
+ title: property('Title', 'Try this'),
+ body: property('Body', 'Select something on the canvas and look at the panel on the right.'),
+ keys: property('Shortcut', '⌥ ⌘ ↩'),
+ showKeys: property('Show shortcut', true)
+}
export const TIP_WIDTH = 320
/** The slot a tip shows where to click in: a piece of the app's chrome with the target ringed. */
@@ -54,7 +49,6 @@ function tipComponent(theme: Theme): TreeNode {
return (
<Component
name="Tip"
- properties={Object.values(TIP_PROPERTIES)}
flex="col"
w={TIP_WIDTH}
h="hug"
@@ -81,10 +75,8 @@ function tipComponent(theme: Theme): TreeNode {
size={13}
weight={700}
color={vars.onAccent}
- propertyRefs={[{ propertyId: TIP_PROPERTIES.step.id, field: 'TEXT' }]}
- >
- {TIP_PROPERTIES.step.defaultValue}
- </Text>
+ text={TIP_PROPERTIES.step}
+ />
</Frame>
<Text
name="Title"
@@ -92,10 +84,8 @@ function tipComponent(theme: Theme): TreeNode {
size={15}
weight={600}
color={vars.text}
- propertyRefs={[{ propertyId: TIP_PROPERTIES.title.id, field: 'TEXT' }]}
- >
- {TIP_PROPERTIES.title.defaultValue}
- </Text>
+ text={TIP_PROPERTIES.title}
+ />
</Frame>
<Text
name="Body"
@@ -104,10 +94,8 @@ function tipComponent(theme: Theme): TreeNode {
lineHeight={20}
w="fill"
color={vars.muted}
- propertyRefs={[{ propertyId: TIP_PROPERTIES.body.id, field: 'TEXT' }]}
- >
- {TIP_PROPERTIES.body.defaultValue}
- </Text>
+ text={TIP_PROPERTIES.body}
+ />
<Frame name={WHERE_SLOT_NAME} flex="col" w="fill" h="hug" items="start">
{previewButton(theme)}
</Frame>
@@ -120,7 +108,7 @@ function tipComponent(theme: Theme): TreeNode {
py={6}
rounded={8}
bg={vars.raised}
- propertyRefs={[{ propertyId: TIP_PROPERTIES.showKeys.id, field: 'VISIBLE' }]}
+ visible={TIP_PROPERTIES.showKeys}
>
<Text
name="Keys"
@@ -128,10 +116,8 @@ function tipComponent(theme: Theme): TreeNode {
size={12}
weight={600}
color={vars.text}
- propertyRefs={[{ propertyId: TIP_PROPERTIES.keys.id, field: 'TEXT' }]}
- >
- {TIP_PROPERTIES.keys.defaultValue}
- </Text>
+ text={TIP_PROPERTIES.keys}
+ />
</Frame>
</Component>
)
@@ -153,11 +139,11 @@ export function tipInstance(componentId: string, tip: Tip): TreeNode {
of={componentId}
name={`Tip ${tip.step}`}
properties={{
- [TIP_PROPERTIES.step.id]: String(tip.step),
- [TIP_PROPERTIES.title.id]: tip.title,
- [TIP_PROPERTIES.body.id]: tip.body,
- [TIP_PROPERTIES.keys.id]: tip.keys ?? '',
- [TIP_PROPERTIES.showKeys.id]: tip.keys ? 'true' : 'false'
+ [TIP_PROPERTIES.step.name]: String(tip.step),
+ [TIP_PROPERTIES.title.name]: tip.title,
+ [TIP_PROPERTIES.body.name]: tip.body,
+ [TIP_PROPERTIES.keys.name]: tip.keys ?? '',
+ [TIP_PROPERTIES.showKeys.name]: tip.keys ? 'true' : 'false'
}}
/>
)
diff --git a/tools/generate/demo/src/document/chapters/modes.ts b/tools/generate/demo/src/document/chapters/modes.ts
index ff77b14de..f557231dc 100644
--- a/tools/generate/demo/src/document/chapters/modes.ts
+++ b/tools/generate/demo/src/document/chapters/modes.ts
@@ -1,4 +1,4 @@
-import { Frame, Instance } from '@open-pencil/design-jsx'
+import { Frame, Instance, type DesignMode } from '@open-pencil/design-jsx'
import { variablesRow } from '../chrome'
import { layoutChapter, type Chapter, type ChapterContext } from './chapter'
@@ -11,9 +11,11 @@ export async function createModesChapter(
player: Player
): Promise<Chapter> {
const { graph, theme } = context
- const stage = (name: string) =>
+ // Both stages pin their mode, so they show dark and light whichever theme the app is in.
+ const stage = (name: string, mode: DesignMode) =>
Frame({
name,
+ mode,
flex: 'col',
w: 'hug',
h: 'hug',
@@ -34,7 +36,7 @@ export async function createModesChapter(
w: 'hug',
h: 'hug',
gap: 40,
- children: [stage('Dark'), stage('Light')]
+ children: [stage('Dark', theme.modes.dark), stage('Light', theme.modes.light)]
}),
tip: {
step: 4,
@@ -43,9 +45,5 @@ export async function createModesChapter(
where: variablesRow(theme, `${graph.variables.size} / ${graph.variableCollections.size}`)
}
})
- // Both stages pin their mode, so they show dark and light whichever theme the app is in.
- const [dark, light] = graph.getChildren(chapter.subject.id)
- graph.updateNode(dark.id, { variableModes: { [theme.collectionId]: theme.modeIds.dark } })
- graph.updateNode(light.id, { variableModes: { [theme.collectionId]: theme.modeIds.light } })
return chapter
}
diff --git a/tools/generate/demo/src/document/chapters/slots.ts b/tools/generate/demo/src/document/chapters/slots.ts
index 80387908b..5fa6bcfd5 100644
--- a/tools/generate/demo/src/document/chapters/slots.ts
+++ b/tools/generate/demo/src/document/chapters/slots.ts
@@ -116,8 +116,8 @@ export async function createSlotsChapter(
Instance({
of: component.id,
properties: {
- [PLAYER_PROPERTIES.title.id]: title,
- [PLAYER_PROPERTIES.artist.id]: artist
+ [PLAYER_PROPERTIES.title.name]: title,
+ [PLAYER_PROPERTIES.artist.name]: artist
}
}),
{ parentId: row.id }
diff --git a/tools/generate/demo/src/document/elements.ts b/tools/generate/demo/src/document/elements.ts
index ca5ce6e16..971ce1e7a 100644
--- a/tools/generate/demo/src/document/elements.ts
+++ b/tools/generate/demo/src/document/elements.ts
@@ -9,16 +9,7 @@ export interface IconProps {
label?: string
}
-/** The variable each icon element binds its paths to, read when the icon is rendered. */
-export const iconColors = new WeakMap<TreeNode, DesignVariable>()
-
-/**
- * An icon layer, as `<Icon>` in a design JSX string renders one, drawn in the variable's
- * value and bound to it once rendered (`renderTree` in `./icons`).
- */
-export function Icon({ color, ...props }: IconProps): TreeNode {
- const value = typeof color.value === 'string' ? color.value : '#000000'
- const tree = node('icon', { ...props, color: value })
- iconColors.set(tree, color)
- return tree
+/** An icon layer, as `<Icon>` in a design JSX string renders one, its paths bound to `color`. */
+export function Icon(props: IconProps): TreeNode {
+ return node('icon', { ...props })
}
diff --git a/tools/generate/demo/src/document/icons.ts b/tools/generate/demo/src/document/icons.ts
index 29f484197..1b3d3ed4b 100644
--- a/tools/generate/demo/src/document/icons.ts
+++ b/tools/generate/demo/src/document/icons.ts
@@ -2,10 +2,6 @@ import { icons as lucide } from '@iconify-json/lucide'
import { designJSXRenderer } from '@open-pencil/core/design-jsx'
import { createIconifyProvider } from '@open-pencil/core/icons'
-import type { RenderOptions, TreeNode } from '@open-pencil/design-jsx'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { iconColors } from './elements'
type IconifyClient = NonNullable<Parameters<typeof createIconifyProvider>[0]>
@@ -51,37 +47,5 @@ const client: IconifyClient = {
}
}
-const renderer = designJSXRenderer(createIconifyProvider(client))
-
-/** Bind every solid paint of an icon's paths to `variableId`. */
-function bindIcon(graph: SceneGraph, icon: SceneNode, variableId: string): void {
- const visit = (node: SceneNode): void => {
- for (const field of ['fills', 'strokes'] as const) {
- node[field].forEach((paint, index) => {
- if (paint.type === 'SOLID')
- graph.bindVariable(node.id, `${field}/${index}/color`, variableId)
- })
- }
- for (const child of graph.getChildren(node.id)) visit(child)
- }
- visit(icon)
-}
-
-/**
- * Design JSX rendering with the bundled icons. Icons from `Icon` in `./elements` are bound to
- * their color variable once drawn, so they follow the tour's modes like everything else.
- */
-export function renderTree(
- graph: SceneGraph,
- tree: TreeNode,
- options: RenderOptions = {}
-): ReturnType<typeof renderer.renderTree> {
- return renderer.renderTree(graph, tree, {
- ...options,
- onNode(element, node) {
- options.onNode?.(element, node)
- const variableId = iconColors.get(element)?.id
- if (variableId && graph.variables.has(variableId)) bindIcon(graph, node, variableId)
- }
- })
-}
+/** Design JSX rendering with the bundled icons. */
+export const { renderTree } = designJSXRenderer(createIconifyProvider(client))
diff --git a/tools/generate/demo/src/document/player/card.tsx b/tools/generate/demo/src/document/player/card.tsx
index 95cc9d7d9..70d825085 100644
--- a/tools/generate/demo/src/document/player/card.tsx
+++ b/tools/generate/demo/src/document/player/card.tsx
@@ -9,18 +9,18 @@ import {
Instance,
Rectangle,
Text,
+ property,
shader,
type TreeNode
} from '@open-pencil/design-jsx'
-import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'
import type { ShaderPreset } from '@open-pencil/scene-graph/shaders'
import type { Theme } from '../theme'
export const PLAYER_PROPERTIES = {
- title: { id: 'player-title', name: 'Title', type: 'TEXT', defaultValue: 'Night Drive' },
- artist: { id: 'player-artist', name: 'Artist', type: 'TEXT', defaultValue: 'Lumen' }
-} satisfies Record<string, ComponentPropertyDefinition>
+ title: property('Title', 'Night Drive'),
+ artist: property('Artist', 'Lumen')
+}
export const PLAYER_WIDTH = 360
export const ARTWORK_SIZE = 320
@@ -69,7 +69,6 @@ export function playerComponent({ vars }: Theme, parts: PlayerParts): TreeNode {
return (
<Component
name="Player"
- properties={Object.values(PLAYER_PROPERTIES)}
flex="col"
w={PLAYER_WIDTH}
h="hug"
@@ -96,19 +95,15 @@ export function playerComponent({ vars }: Theme, parts: PlayerParts): TreeNode {
size={20}
weight={600}
color={vars.text}
- propertyRefs={[{ propertyId: PLAYER_PROPERTIES.title.id, field: 'TEXT' }]}
- >
- {PLAYER_PROPERTIES.title.defaultValue}
- </Text>
+ text={PLAYER_PROPERTIES.title}
+ />
<Text
name="Artist"
font="Inter"
size={14}
color={vars.muted}
- propertyRefs={[{ propertyId: PLAYER_PROPERTIES.artist.id, field: 'TEXT' }]}
- >
- {PLAYER_PROPERTIES.artist.defaultValue}
- </Text>
+ text={PLAYER_PROPERTIES.artist}
+ />
</Frame>
<Frame name="Progress" flex="col" w="fill" h="hug" gap={8}>
<Instance of={parts.slider} />
diff --git a/tools/generate/demo/src/document/theme.ts b/tools/generate/demo/src/document/theme.ts
index 46cad1ce8..2b0dc0704 100644
--- a/tools/generate/demo/src/document/theme.ts
+++ b/tools/generate/demo/src/document/theme.ts
@@ -1,6 +1,10 @@
-import { defineVars, type DesignVariable } from '@open-pencil/design-jsx'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-import { parseColor } from '@open-pencil/scene-graph/color'
+import {
+ defineMode,
+ defineVars,
+ designMode,
+ type DesignMode,
+ type DesignVariable
+} from '@open-pencil/design-jsx'
/**
* The tour's colors live in two collections, each with a Dark and a Light mode: Theme, for the
@@ -56,65 +60,36 @@ const CHROME_COLORS = [
type Vars<T extends readonly Entry[]> = Record<T[number][0], DesignVariable>
-function addCollection(
- graph: SceneGraph,
- prefix: string,
- name: string,
- entries: readonly Entry[]
-): Record<string, DesignVariable> {
- const collectionId = `${prefix}-collection`
- const modeIds: Record<Mode, string> = { dark: `${prefix}-dark`, light: `${prefix}-light` }
- graph.addCollection({
- id: collectionId,
+/**
+ * A collection with a Dark and a Light mode, Dark the default, and its variables by their keys.
+ * A render that binds any of them adds the collection to the file.
+ */
+function defineCollection(name: string, entries: readonly Entry[]) {
+ const named = defineVars(
name,
- modes: [
- { modeId: modeIds.dark, name: MODE_NAMES.dark },
- { modeId: modeIds.light, name: MODE_NAMES.light }
- ],
- defaultModeId: modeIds.dark,
- variableIds: []
- })
- const value = (raw: string | number) => (typeof raw === 'number' ? raw : parseColor(raw))
- for (const [key, variableName, dark, light] of entries) {
- graph.addVariable({
- id: `${prefix}-${key}`,
- name: variableName,
- type: typeof dark === 'number' ? 'FLOAT' : 'COLOR',
- collectionId,
- valuesByMode: { [modeIds.dark]: value(dark), [modeIds.light]: value(light) },
- description: '',
- hiddenFromPublishing: false
- })
- }
- // Each reference carries its dark value, for layers drawn before they are bound, such as icons.
- return defineVars(
- Object.fromEntries(
- entries.map(([key, variableName, dark]) => [
- key,
- { id: `${prefix}-${key}`, name: variableName, value: dark }
- ])
- )
+ Object.fromEntries(entries.map(([, variableName, dark]) => [variableName, dark])),
+ { mode: MODE_NAMES.dark }
+ )
+ const light = defineMode(
+ named,
+ MODE_NAMES.light,
+ Object.fromEntries(entries.map(([, variableName, , value]) => [variableName, value]))
+ )
+ const vars: Record<string, DesignVariable> = Object.fromEntries(
+ entries.map(([key, variableName]) => [key, named[variableName]])
)
+ return { vars, modes: { dark: designMode(name, MODE_NAMES.dark), light } }
}
/** The tour's collections, with references to every variable in them. */
-export function createTheme(graph: SceneGraph) {
- const vars = addCollection(graph, 'demo-theme', COLLECTION_NAMES.theme, [
- ...THEME_COLORS,
- ...THEME_NUMBERS
- ]) as Vars<typeof THEME_COLORS> & Vars<typeof THEME_NUMBERS>
- const chrome = addCollection(
- graph,
- 'demo-chrome',
- COLLECTION_NAMES.chrome,
- CHROME_COLORS
- ) as Vars<typeof CHROME_COLORS>
+export function createTheme() {
+ const theme = defineCollection(COLLECTION_NAMES.theme, [...THEME_COLORS, ...THEME_NUMBERS])
+ const chrome = defineCollection(COLLECTION_NAMES.chrome, CHROME_COLORS)
return {
- vars,
- chrome,
- /** The Theme collection and its modes, for frames that pin one. */
- collectionId: 'demo-theme-collection',
- modeIds: { dark: 'demo-theme-dark', light: 'demo-theme-light' } satisfies Record<Mode, string>
+ vars: theme.vars as Vars<typeof THEME_COLORS> & Vars<typeof THEME_NUMBERS>,
+ chrome: chrome.vars as Vars<typeof CHROME_COLORS>,
+ /** The Theme collection's modes, for frames that pin one. */
+ modes: theme.modes satisfies Record<Mode, DesignMode>
}
}
diff --git a/vite.config.ts b/vite.config.ts
index e05cd4260..17e410ad8 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -22,6 +22,7 @@ import {
import { bootSplashPlugin } from './vite/boot-splash'
import { cloudSitePlugin } from './vite/cloud-site'
import { aiIconCollection } from './vite/icons'
+import { inlineScriptPlugin } from './vite/inline-script'
import { metricsBrandPlugin } from './vite/metrics'
import { openPencilPwaPlugin } from './vite/pwa'
import { rawMarkdownPlugin } from './vite/raw-markdown'
@@ -65,6 +66,7 @@ export default defineConfig(async ({ command, mode }) => {
optimizeDeps: { include: ['ai/test'] },
plugins: [
rawMarkdownPlugin(),
+ inlineScriptPlugin(),
bootSplashPlugin({
entry: resolve(__dirname, 'src/splash/theme.ts'),
pages: ['index.html', 'cloud.html', 'metrics.html']
diff --git a/vite/app-source.ts b/vite/app-source.ts
index ebc226de0..ceaec98ca 100644
--- a/vite/app-source.ts
+++ b/vite/app-source.ts
@@ -8,6 +8,7 @@ import type { Alias, Plugin, PluginOption } from 'vite'
import rootManifest from '../package.json' with { type: 'json' }
import { createOpenPencilAliases } from './aliases.ts'
+import { inlineScriptPlugin } from './inline-script.ts'
const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url))
const SOURCE_ROOT = fileURLToPath(new URL('../src/', import.meta.url))
@@ -50,7 +51,8 @@ export interface AppSourceConfig {
/**
* What another Vite host needs to compile the app's components from source: the app's
- * aliases, its icon plugins, its text imports, and the build-time constants it reads. The
+ * aliases, its icon plugins, its text and inline-script imports, and the build-time constants it
+ * reads. The
* host has no local automation server, so those constants are empty.
*/
export function appSourceConfig(): AppSourceConfig {
@@ -71,6 +73,7 @@ export function appSourceConfig(): AppSourceConfig {
},
plugins: [
appRawText(),
+ inlineScriptPlugin(),
Icons({ compiler: 'vue3' }),
Components({ dirs: [], dts: false, resolvers: [IconsResolver({ prefix: 'icon' })] })
]
diff --git a/vite/inline-script.ts b/vite/inline-script.ts
new file mode 100644
index 000000000..f6e2564ca
--- /dev/null
+++ b/vite/inline-script.ts
@@ -0,0 +1,57 @@
+import { fileURLToPath } from 'node:url'
+
+import { build, type Plugin } from 'vite'
+
+import { viteBuildTarget } from '../src/app/shell/support/baseline'
+import { createOpenPencilAliases } from './aliases.ts'
+
+const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url))
+/** `?script` among an id's query, which Vite extends, as with `?t=…&script` after a hot update. */
+const SCRIPT_QUERY = /[?&]script(?:&|$)/
+
+/** An id without its query, as Vite's own `cleanUrl`. */
+const withoutQuery = (id: string) => id.replace(/[?#].*$/s, '')
+
+/**
+ * `import source from './entry.ts?script'`: the module and everything it imports bundled into
+ * one classic script, as a string. It is for code that can run only inline, such as the code
+ * panel's sandbox, whose opaque-origin frame can start a worker only from a `blob:` URL. Vite's
+ * `?worker&inline` inlines only in a build, so the script is bundled the same way in dev and in
+ * a build, as Vite bundles an inline worker, and minified in a build.
+ */
+export function inlineScriptPlugin(): Plugin {
+ return {
+ name: 'open-pencil-inline-script',
+ load: {
+ filter: { id: SCRIPT_QUERY },
+ async handler(id) {
+ const entry = withoutQuery(id)
+ const result = await build({
+ configFile: false,
+ root: REPO_ROOT,
+ publicDir: false,
+ logLevel: 'warn',
+ resolve: { alias: createOpenPencilAliases(REPO_ROOT) },
+ // An entry may itself inline another, as the sandbox frame inlines its worker.
+ plugins: [inlineScriptPlugin()],
+ build: {
+ write: false,
+ minify: this.environment.config.command === 'build',
+ target: viteBuildTarget(),
+ emptyOutDir: false,
+ copyPublicDir: false,
+ lib: { entry, formats: ['iife'], name: 'openPencilInlineScript' }
+ }
+ })
+ // One IIFE entry builds one chunk, which comes first.
+ const [output] = [result].flat()
+ const chunk = 'output' in output ? output.output[0] : undefined
+ if (!chunk) throw new Error(`Could not bundle ${entry} as a script`)
+ for (const moduleId of chunk.moduleIds) {
+ if (!moduleId.startsWith('\0')) this.addWatchFile(withoutQuery(moduleId))
+ }
+ return { code: `export default ${JSON.stringify(chunk.code)}`, map: null }
+ }
+ }
+ }
+}