AI-native design editor. Open-source Figma alternative.
fix(design-jsx): preserve component properties in node reads and JSX export (#1601)
Danila Poyarkov598f835b921c
diff --git a/changes/1601/fixed.md b/changes/1601/fixed.mdnew file mode 100644index 000000000..ca62b52ef--- /dev/null+++ b/changes/1601/fixed.md@@ -0,0 +1,3 @@+- Node reads and `get_components` include component property definitions, and Design JSX export writes components, component sets, and instances with their `property()` bindings, property values, and layer overrides, so they render back as linked components; an instance whose changes JSX cannot write still exports as the frame it draws.+- Instance `overrides` find layers among the instance's children by the names they had before any rename, accept layer names with a colon, ignore tree fields, and reject a name several layers share instead of changing the first.+- Design JSX rejects an instance variant value the set does not have and an instance that would put a component inside itself instead of drawing the first variant or a plain frame, warns about skipped `overrides` keys, binds `visible={property()}` on stickies, connectors, and shapes with text, and leaves no property definitions behind when a render fails.diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex 75c2f15e3..ecec45d79 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -37,7 +37,7 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- Infer arguments from the schema; derive effects and default capabilities from execution metadata. Do not maintain parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.- `packages/core/src/tools/ai-adapter.ts` converts ToolDefs for Vercel AI; the app binds them to the active editor's `FigmaAPI` in `src/app/ai/tools/index.ts`. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the same input contract.- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions; Scene Graph owns checkpoint recovery. AI, MCP, and WebMCP share this execution path. Async and structural tools cannot declare atomic property execution.-- Shared scene-authoring guidance and tested examples live under `packages/design-jsx/src/reference/`; `reference.ts` combines them with renderer metadata. Prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that reference rather than copying it. Run `bun run generate:authoring-reference` after changes; `check:authoring-reference` (part of `check:docs`) verifies the committed skill/docs copies. Do not edit generated reference files.+- Shared scene-authoring guidance and tested examples live under `packages/design-jsx/src/reference/`; `reference/index.ts` combines them with renderer metadata. Prompts under `packages/core/src/tools/prompts/` and the app chat/ACP prompt compose that reference rather than copying it. Run `bun run generate:authoring-reference` after changes; `check:authoring-reference` (part of `check:docs`) verifies the committed skill/docs copies. Do not edit generated reference files.- The installable agent skill is maintained in `skills/open-pencil/`. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories.- MCP-only tools and transports: `packages/mcp/AGENTS.md`. WebMCP registration and app completion: `src/AGENTS.md`.diff --git a/packages/core/src/design-jsx/index.ts b/packages/core/src/design-jsx/index.tsindex f1f9b400a..78d836f7c 100644--- a/packages/core/src/design-jsx/index.ts+++ b/packages/core/src/design-jsx/index.ts@@ -1,4 +1,4 @@-export { designJSXRenderer, renderJSX, renderTree } from './renderer'+export { designJSXRenderer, renderJSX, renderRoots, renderTree } from './renderer'export {finishRenderPlacement,resolveRenderPlacement,diff --git a/packages/core/src/design-jsx/preview/stage.ts b/packages/core/src/design-jsx/preview/stage.tsindex 6933636f7..d0986fd08 100644--- a/packages/core/src/design-jsx/preview/stage.ts+++ b/packages/core/src/design-jsx/preview/stage.ts@@ -1,4 +1,4 @@-import type { RenderResult, TreeNode } from '@open-pencil/design-jsx'+import type { TreeNode } from '@open-pencil/design-jsx'import type { SceneGraph } from '@open-pencil/scene-graph'import {@@ -6,7 +6,7 @@ import {resolveRenderPlacement,type RenderPlacementInput} from '#core/design-jsx/placement'-import { renderTree } from '#core/design-jsx/renderer'+import { renderRoots } from '#core/design-jsx/renderer'import { extractPageContext, findPageChildId } from '#core/io/subgraph'const MAX_PREVIEW_CONTEXT_NODES = 1000@@ -56,14 +56,10 @@ export async function stageJSXPreview(graph.images = new Map(source.images)graph.variables = structuredClone(source.variables)graph.variableCollections = structuredClone(source.variableCollections)- const results: RenderResult[] = []- for (const root of tree.type === '' ? tree.children : [tree]) {- if (typeof root === 'string') continue- signal?.throwIfAborted()- results.push(await renderTree(graph, root, placement))- }+ // One call, so components render before the roots that use them.+ if (tree.type === '' && !tree.children.some((child) => typeof child !== 'string')) return null+ const results = await renderRoots(graph, tree, placement)signal?.throwIfAborted()- if (results.length === 0) return nullfinishRenderPlacement(graph, results, placement)return {graph,diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.tsindex 90cdac93d..0beacc54c 100644--- a/packages/core/src/design-jsx/renderer.ts+++ b/packages/core/src/design-jsx/renderer.ts@@ -74,4 +74,4 @@ export function designJSXRenderer(icons: IconProvider = defaultIcons) {}/** Design JSX rendering with Iconify's icons. */-export const { renderJSX, renderTree } = designJSXRenderer()+export const { renderJSX, renderTree, renderRoots } = designJSXRenderer()diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.tsindex b4d7d5a33..3f8349677 100644--- a/packages/core/src/figma-api/serialization.ts+++ b/packages/core/src/figma-api/serialization.ts@@ -35,6 +35,19 @@ function appendTextProps(obj: Record<string, unknown>, n: SceneNode): void {if (n.maxLines != null) obj.maxLines = n.maxLines}+function appendComponentProperties(obj: Record<string, unknown>, n: SceneNode): void {+ if (+ (n.type === 'COMPONENT' || n.type === 'COMPONENT_SET') &&+ n.componentPropertyDefinitions.length > 0+ ) {+ obj.componentPropertyDefinitions = n.componentPropertyDefinitions+ }+ if (n.componentPropertyReferences.length > 0)+ obj.componentPropertyReferences = n.componentPropertyReferences+ if (n.type === 'INSTANCE' && Object.keys(n.componentPropertyAssignments).length > 0)+ obj.componentPropertyAssignments = n.componentPropertyAssignments+}+export function nodeProxyToJSON(graph: SceneGraph,api: NodeProxyHost,@@ -61,6 +74,7 @@ export function nodeProxyToJSON(if (n.cornerRadius > 0) obj.cornerRadius = n.cornerRadiusif (!n.visible) obj.visible = falseif (n.text) obj.characters = n.text+ appendComponentProperties(obj, n)if (n.type === 'TEXT') {appendTextProps(obj, n)}diff --git a/packages/core/src/tools/read/components.ts b/packages/core/src/tools/read/components.tsindex e6b3f2d7f..b918a9014 100644--- a/packages/core/src/tools/read/components.ts+++ b/packages/core/src/tools/read/components.ts@@ -1,5 +1,7 @@import * as v from 'valibot'+import type { ComponentPropertyDefinition } from '@open-pencil/scene-graph'+import { getComponentCatalog } from '#core/tools/component-catalog'import { toolNumber, defineTool } from '#core/tools/schema'@@ -9,6 +11,7 @@ interface DocumentComponentResult {type: stringpage: stringsource: 'document'+ componentPropertyDefinitions?: ComponentPropertyDefinition[]}interface LibraryComponentResult {@@ -59,12 +62,18 @@ export const getComponents = defineTool({if (documentComponents.length >= limit) return falseif (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return falseif (nameFilter && !node.name.toLowerCase().includes(nameFilter)) return false+ const componentPropertyDefinitions = figma.graph.getNode(+ node.id+ )?.componentPropertyDefinitionsdocumentComponents.push({id: node.id,name: node.name,type: node.type,page: page.name,- source: 'document'+ source: 'document',+ ...(componentPropertyDefinitions && componentPropertyDefinitions.length > 0+ ? { componentPropertyDefinitions }+ : {})})return false})diff --git a/packages/core/tests/design-jsx/export-round-trip.test.ts b/packages/core/tests/design-jsx/attributes.test.tssimilarity index 100%rename from packages/core/tests/design-jsx/export-round-trip.test.tsrename to packages/core/tests/design-jsx/attributes.test.tsdiff --git a/packages/core/tests/design-jsx/behaviours.test.ts b/packages/core/tests/design-jsx/behaviours.test.tsindex 7bb2f4878..14537a0ba 100644--- a/packages/core/tests/design-jsx/behaviours.test.ts+++ b/packages/core/tests/design-jsx/behaviours.test.ts@@ -196,9 +196,17 @@ describe('Reka UI elements in JSX export', () => {)const [group] = await renderJSX(graph,- `<RadioGroup.Root name="Plan"><RadioGroup.Item of="${radio.id}" /></RadioGroup.Root>`+ `<RadioGroup.Root name="Plan">+ <RadioGroup.Item of="${radio.id}" />+ <RadioGroup.Item of="${radio.id}" Checked="On" />+ </RadioGroup.Root>`)- expect(sceneNodeToJSX(group.id, graph)).toContain(`<RadioGroup.Item of="${radio.id}" />`)+ // Each item keeps its variant, so a checked item renders back checked.+ const exported = sceneNodeToJSX(group.id, graph)+ expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" />')+ expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="On" />')+ const [copy] = await renderJSX(graph, exported)+ expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)const [tabs] = await renderJSX(graph,@@ -213,4 +221,61 @@ describe('Reka UI elements in JSX export', () => {expect(code).toContain('<Tabs.Content')expect(code).not.toContain('name="Panels"')})++ test('a group item whose changes JSX cannot write is written as the layer it draws', async () => {+ const graph = new SceneGraph()+ await renderJSX(+ graph,+ `<><Component name="Mark" w={4} h={4} />+ <RadioGroup.Item name="Radio" modelValue="Checked">+ <Component name="Checked=Off" w={20} h={20}><Instance name="Dot" of="Mark" /></Component>+ <Component name="Checked=On" w={20} h={20}><Instance name="Dot" of="Mark" /></Component>+ </RadioGroup.Item></>`+ )+ const [group] = await renderJSX(+ graph,+ `<RadioGroup.Root name="Plan">+ <RadioGroup.Item of="Radio" overrides={{ 'Dot:opacity': 0.5 }} />+ </RadioGroup.Root>`+ )+ const exported = sceneNodeToJSX(group.id, graph)+ expect(exported).not.toContain('<RadioGroup.Item')+ // The item renders back as the layers it drew, its dot still half transparent.+ const [copy] = await renderJSX(graph, exported)+ const [item] = graph.getChildren(copy.id)+ const [dot] = graph.getChildren(item?.id ?? '')+ expect([item?.type, item?.name]).toEqual(['FRAME', 'Checked=Off'])+ expect([dot?.type, dot?.name, dot?.opacity]).toEqual(['INSTANCE', 'Dot', 0.5])+ })++ test('a group item exports the property values and layer overrides it gives its component', async () => {+ const graph = new SceneGraph()+ await renderJSX(+ graph,+ `<RadioGroup.Item name="Radio" modelValue="Checked">+ <Component name="Checked=Off" w={20} h={20}>+ <Frame name="Dot" w={4} h={4} /><Text name="Label" text={property('Label', 'Plan')} />+ </Component>+ <Component name="Checked=On" w={20} h={20}>+ <Frame name="Dot" w={4} h={4} /><Text name="Label" text={property('Label', 'Plan')} />+ </Component>+ </RadioGroup.Item>`+ )+ const [group] = await renderJSX(+ graph,+ `<RadioGroup.Root name="Plan">+ <RadioGroup.Item of="Radio" Checked="On" Label="Pro" overrides={{ 'Dot:opacity': 0.5 }} />+ <RadioGroup.Item of="Radio" visible={false} />+ <RadioGroup.Item of="Radio" opacity={0.4} />+ </RadioGroup.Root>`+ )+ const exported = sceneNodeToJSX(group.id, graph)+ expect(exported).toContain(+ '<RadioGroup.Item of="Radio" Checked="On" Label="Pro" overrides={{ "Dot:opacity": 0.5 }} />'+ )+ expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" visible={false} />')+ expect(exported).toContain('<RadioGroup.Item of="Radio" Checked="Off" opacity={0.4} />')+ const [copy] = await renderJSX(graph, exported)+ expect(sceneNodeToJSX(copy.id, graph)).toBe(exported)+ })})diff --git a/packages/core/tests/design-jsx/components/export.test.ts b/packages/core/tests/design-jsx/components/export.test.tsnew file mode 100644index 000000000..cb2ff4650--- /dev/null+++ b/packages/core/tests/design-jsx/components/export.test.ts@@ -0,0 +1,385 @@+import { describe, expect, test } from 'bun:test'++import { getNodeOrThrow } from '#core-tests/helpers/assert'++import { renderJSX } from '@open-pencil/core/design-jsx'+import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'+import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'++const BUTTON = `<Frame name="Library">+ <Component name="Star" w={4} h={4} />+ <Component name="Heart" w={6} h={6} />+ <ComponentSet name="Button">+ <Component name="State=On" flex="row" bg="#3B6CF6">+ <Text name="Label" text={property('Label', 'Hi')} />+ <Frame name="Dot" w={4} h={4} bg="#FFFFFF" visible={property('Has dot', true)} />+ <Instance name="Icon" of={property('Icon', 'Star')} />+ </Component>+ <Component name="State=Off" flex="row" bg="#D0D4DA">+ <Text name="Label" text={property('Label', 'Hi')} />+ <Frame name="Dot" w={4} h={4} bg="#FFFFFF" visible={property('Has dot', true)} />+ <Instance name="Icon" of={property('Icon', 'Star')} />+ </Component>+ </ComponentSet>+</Frame>`++async function library() {+ const graph = new SceneGraph()+ const [frame] = await renderJSX(graph, BUTTON)+ return { graph, library: frame.id }+}++function named(graph: SceneGraph, name: string): SceneNode {+ const node = [...graph.getAllNodes()].find((item) => item.name === name)+ if (!node) throw new Error(`No layer named ${name}`)+ return node+}++function definitions(node: SceneNode) {+ return node.componentPropertyDefinitions.map(({ name, type, defaultValue }) => ({+ name,+ type,+ defaultValue+ }))+}++describe('component export', () => {+ test('writes bound fields as the property() calls that bind them', async () => {+ const { graph } = await library()+ const set = named(graph, 'Button')+ const jsx = sceneNodeToJSX(set.id, graph)+ expect(jsx).toContain('text={property("Label", "Hi")}')+ expect(jsx).toContain('visible={property("Has dot", true)}')+ expect(jsx).toContain('of={property("Icon", "Star")}')+ expect(jsx).not.toContain('propertyRefs')++ const page = graph.addPage('Copy')+ const [copy] = await renderJSX(graph, jsx, { parentId: page.id })+ const copied = getNodeOrThrow(graph, copy.id)+ expect(definitions(copied)).toEqual(definitions(set))+ expect(sceneNodeToJSX(copied.id, graph)).toBe(jsx)+ })++ test('writes an instance as its component, variant, and property values, not its layers', async () => {+ const { graph } = await library()+ const [instance] = await renderJSX(+ graph,+ '<Instance of="Button" State="Off" Label="Save" properties={{ "Has dot": false }} Icon="Heart" />'+ )+ const jsx = sceneNodeToJSX(instance.id, graph)+ expect(jsx).toBe(+ '<Instance name="State=Off" of="Button" State="Off" Label="Save" Icon="Heart" properties={{ "Has dot": false }} />'+ )++ const [copy] = await renderJSX(graph, jsx)+ const copied = getNodeOrThrow(graph, copy.id)+ expect(copied.componentId).toBe(getNodeOrThrow(graph, instance.id).componentId)+ expect(copied.componentPropertyAssignments).toEqual(+ getNodeOrThrow(graph, instance.id).componentPropertyAssignments+ )+ expect(sceneNodeToJSX(copied.id, graph)).toBe(jsx)+ })++ test('writes only the props an instance changes from its component', async () => {+ const { graph } = await library()+ const [instance] = await renderJSX(graph, '<Instance of="Button" x={40} bg="#000000" />')+ const jsx = sceneNodeToJSX(instance.id, graph)+ expect(jsx).toContain('x={40}')+ expect(jsx).toContain('bg="#000000"')+ expect(jsx).not.toContain('flex=')+ })++ test('writes what an instance changes in its layers as overrides', async () => {+ const { graph } = await library()+ const [created] = await renderJSX(graph, '<Instance of="Button" />')+ const instance = getNodeOrThrow(graph, created.id)+ const dot = graph.getChildren(instance.id).find((child) => child.name === 'Dot')+ if (!dot) throw new Error('No dot')+ const red = [{ ...dot.fills[0], color: { r: 1, g: 0, b: 0, a: 1 } }]+ graph.updateNode(dot.id, { fills: red, name: 'Red dot' })+ for (const field of ['fills', 'name'])+ setInstanceOverride(instance.instanceOverrides, instance.id, dot.id, field)++ const jsx = sceneNodeToJSX(instance.id, graph)+ expect(jsx).toContain('overrides={{')+ expect(jsx.indexOf('"Dot:fills"')).toBeLessThan(jsx.indexOf('"Dot:name"'))++ const [copy] = await renderJSX(graph, jsx)+ const copiedDot = graph.getChildren(copy.id).find((child) => child.name === 'Red dot')+ expect(copiedDot?.fills).toEqual(red)+ expect(sceneNodeToJSX(copy.id, graph)).toBe(jsx)+ })++ test('writes an override equal to the component value, so the layer keeps it', async () => {+ const { graph } = await library()+ const [created] = await renderJSX(graph, '<Instance of="Button" />')+ const instance = getNodeOrThrow(graph, created.id)+ const dot = graph.getChildren(instance.id).find((child) => child.name === 'Dot')+ if (!dot) throw new Error('No dot')+ setInstanceOverride(instance.instanceOverrides, instance.id, dot.id, 'opacity')++ const jsx = sceneNodeToJSX(instance.id, graph)+ expect(jsx).toContain('overrides={{ "Dot:opacity": 1 }}')+ const [copy] = await renderJSX(graph, jsx)+ const copiedDot = graph.getChildren(copy.id).find((child) => child.name === 'Dot')+ const claimed = getNodeOrThrow(graph, copy.id).instanceOverrides.descendants.get(copiedDot?.id ?? '')+ expect(claimed?.has('opacity')).toBe(true)+ })++ test('keeps the styling of text bound to a property', async () => {+ const graph = new SceneGraph()+ const [tag] = await renderJSX(+ graph,+ `<Component name="Tag"><Text name="Label" text={property('Label', 'Bold rest')}><Span weight={700}>Bold</Span> rest</Text></Component>`+ )+ const jsx = sceneNodeToJSX(tag.id, graph)+ expect(jsx).toContain('text={property("Label", "Bold rest")}')+ expect(jsx).toContain('<Span weight="bold">Bold</Span>')+ const [copy] = await renderJSX(graph, jsx)+ const label = (id: string) => graph.getChildren(id)[0]+ expect(label(copy.id)?.styleRuns).toEqual(label(tag.id)?.styleRuns)+ expect(sceneNodeToJSX(copy.id, graph)).toBe(jsx)+ })++ test('writes an instance as the frame it draws when it sets a property whose name is shared', async () => {+ const { graph } = await library()+ const set = named(graph, 'Button')+ const [created] = await renderJSX(graph, '<Instance of="Button" Label="Save" />')+ graph.updateNode(set.id, {+ componentPropertyDefinitions: set.componentPropertyDefinitions.map((definition) =>+ definition.type === 'BOOLEAN' ? { ...definition, name: 'Label' } : definition+ )+ })+ expect(sceneNodeToJSX(created.id, graph).startsWith('<Frame')).toBe(true)+ })++ test('writes an instance as the frame it draws when its changes cannot be written', async () => {+ const { graph } = await library()+ const [created] = await renderJSX(graph, '<Instance of="Button" />')+ const instance = getNodeOrThrow(graph, created.id)+ graph.updateNode(instance.id, { fills: [] })+ const jsx = sceneNodeToJSX(instance.id, graph)+ expect(jsx.startsWith('<Frame')).toBe(true)+ expect(jsx).not.toContain('property(')+ expect(jsx).toContain('<Instance name="Icon" of="Star" />')+ })++ test('names a component another graph can find, whatever is selected', async () => {+ const { graph, library: libraryId } = await library()+ const [instance] = await renderJSX(graph, '<Instance of="Button" Label="Go" />')+ expect(sceneNodeToJSX(instance.id, graph)).toContain('of="Button"')+ // With its component, by a ref: the target may have a Button of its own.+ const jsx = selectionToJSX([libraryId, instance.id], graph)+ expect(jsx).toContain('of={button1}')+ expect(jsx).toContain('of={property("Icon", star1)}')+ expect(jsx).not.toContain('ref={heart1}')++ // The target has a Button of its own, which the copy must not link to.+ const target = new SceneGraph()+ await renderJSX(target, '<ComponentSet name="Button"><Component name="State=On" w={1} h={1} /></ComponentSet>')+ const [copiedLibrary, copiedInstance] = await renderJSX(target, jsx)+ const copiedSet = target.getChildren(copiedLibrary.id).find((child) => child.name === 'Button')+ const variant = target.getChildren(copiedSet?.id ?? '').find((child) => child.name === 'State=On')+ expect(getNodeOrThrow(target, copiedInstance.id).componentId).toBe(variant?.id ?? "missing")+ expect(target.getChildren(copiedLibrary.id).length).toBe(3)+ const label = target.getChildren(copiedInstance.id).find((child) => child.name === 'Label')+ expect(label?.text).toBe('Go')+ })++ test('names a component by ID where its name is shared', async () => {+ const graph = new SceneGraph()+ const [first] = await renderJSX(graph, '<Component name="Card" w={10} h={10} />')+ await renderJSX(graph, '<Component name="Card" w={20} h={20} />')+ const [instance] = await renderJSX(graph, `<Instance of="${first.id}" />`)+ expect(sceneNodeToJSX(instance.id, graph)).toContain(`of="${first.id}"`)+ })++ test('names a component in the export by a ref where its name is shared', async () => {+ const graph = new SceneGraph()+ const [library] = await renderJSX(+ graph,+ `<Frame name="Library">+ <Component name="Card" w={10} h={10} />+ <Component name="Card" w={20} h={20} />+ </Frame>`+ )+ const [first] = graph.getChildren(library.id)+ const [instance] = await renderJSX(graph, `<Instance of="${first?.id}" />`)+ const jsx = selectionToJSX([instance.id, library.id], graph)+ expect(jsx).toContain('const card1 = ref()')+ expect(jsx).toContain('<Instance name="Card" of={card1} />')+ expect(jsx).toContain('<Component name="Card" w={10} h={10} ref={card1} />')++ const target = new SceneGraph()+ const [copiedInstance, copiedLibrary] = await renderJSX(target, jsx)+ expect(copiedInstance.warnings).toBeUndefined()+ const [copiedFirst] = target.getChildren(copiedLibrary.id)+ expect(getNodeOrThrow(target, copiedInstance.id).componentId).toBe(copiedFirst?.id)+ expect(selectionToJSX([copiedInstance.id, copiedLibrary.id], target)).toBe(jsx)+ })++ test('names swap defaults and values by refs, so they find the exported copies', async () => {+ const { graph, library: libraryId } = await library()+ const [instance] = await renderJSX(graph, '<Instance of="Button" Icon="Heart" />')+ const jsx = selectionToJSX([libraryId, instance.id], graph)+ expect(jsx).toContain('of={property("Icon", star1)}')+ expect(jsx).toContain('Icon={heart1}')++ const target = new SceneGraph()+ await renderJSX(target, '<><Component name="Star" w={1} h={1} /><Component name="Heart" w={1} h={1} /></>')+ const [copiedLibrary, copiedInstance] = await renderJSX(target, jsx)+ const copied = (name: string) =>+ [...target.getAllNodes()].find(+ (node) => node.name === name && node.parentId === copiedLibrary.id+ )+ const set = copied('Button')+ const swap = set?.componentPropertyDefinitions.find((item) => item.type === 'INSTANCE_SWAP')+ expect(swap?.defaultValue).toBe(copied('Star')?.id)+ const icon = target.getChildren(copiedInstance.id).find((child) => child.type === 'INSTANCE')+ expect(icon?.componentId).toBe(copied('Heart')?.id)+ expect(selectionToJSX([copiedLibrary.id, copiedInstance.id], target)).toBe(jsx)+ })++ test('names a component ref apart from the variables the export declares', async () => {+ const graph = new SceneGraph()+ const [library] = await renderJSX(+ graph,+ `const tokens = defineVars('Card 1', { Accent: '#FF0000' })+ return <Frame name="Library" bg={tokens.Accent}>+ <Component name="Card" w={10} h={10} />+ <Component name="Card" w={20} h={20} />+ </Frame>`+ )+ const [first] = graph.getChildren(library.id)+ const [instance] = await renderJSX(graph, `<Instance of="${first?.id}" />`)+ const jsx = selectionToJSX([library.id, instance.id], graph)+ expect(jsx).toContain('const card1 = defineVars("Card 1"')+ expect(jsx).toContain('const card2 = ref()')++ const target = new SceneGraph()+ const [copiedLibrary, copiedInstance] = await renderJSX(target, jsx)+ const [copiedFirst] = target.getChildren(copiedLibrary.id)+ expect(getNodeOrThrow(target, copiedInstance.id).componentId).toBe(copiedFirst?.id)+ })++ test('renders an instance written before its component', async () => {+ const { graph, library: libraryId } = await library()+ const [instance] = await renderJSX(graph, '<Instance of="Button" />')+ const target = new SceneGraph()+ const [copiedInstance, copiedLibrary] = await renderJSX(+ target,+ selectionToJSX([instance.id, libraryId], graph)+ )+ expect(copiedInstance.type).toBe('INSTANCE')+ expect(copiedLibrary.type).toBe('FRAME')+ const page = target.getPages()[0]+ expect(target.getChildren(page.id).map((node) => node.type)).toEqual(['INSTANCE', 'FRAME'])+ })++ test('renders components before the roots that use them, however they name them', async () => {+ const graph = new SceneGraph()+ const [radio, swap, star] = await renderJSX(+ graph,+ `<>+ <Instance of="Radio" />+ <Component name="Swap"><Instance name="Icon" of={property('Icon', 'Star')} /></Component>+ <Component name="Star" w={4} h={4} />+ <RadioGroup.Item name="Radio" modelValue="Checked">+ <Component name="Checked=Off" w={20} h={20} />+ <Component name="Checked=On" w={20} h={20} />+ </RadioGroup.Item>+ </>`+ )+ expect(radio.type).toBe('INSTANCE')+ expect(graph.getChildren(swap.id)[0]?.componentId).toBe(star.id)+ })++ test('renders a component before the instances that name it, wherever they are written', async () => {+ const graph = new SceneGraph()+ const [instance, frame] = await renderJSX(+ graph,+ `<>+ <Instance name="Root copy" of="Tile" />+ <Frame name="Board">+ <Instance name="Copy" of="Tile" />+ <ComponentSet name="Tile"><Component name="Size=S" w={4} h={4} /></ComponentSet>+ <Component name="Tile" w={8} h={8} />+ </Frame>+ </>`+ )+ expect(instance.type).toBe('INSTANCE')+ expect(graph.getChildren(frame.id).map((child) => child.name)).toEqual(['Copy', 'Tile', 'Tile'])+ })++ test('renders a component a swap names before the instance that assigns it', async () => {+ const graph = new SceneGraph()+ const [, instance, , heart] = await renderJSX(+ graph,+ `<>+ <Component name="Star" w={4} h={4} />+ <Instance of="Card" Icon="Heart" />+ <Component name="Card"><Instance name="Icon" of={property('Icon', 'Star')} /></Component>+ <Component name="Heart" w={4} h={4} />+ </>`+ )+ const icon = graph.getChildren(instance.id).find((child) => child.type === 'INSTANCE')+ expect(icon?.componentId).toBe(heart.id)+ })++ test('renders a component a swap names in properties before the instance', async () => {+ const graph = new SceneGraph()+ const [, instance, , heart] = await renderJSX(+ graph,+ `<>+ <Component name="Star" w={4} h={4} />+ <Instance of="Card" properties={{ Icon: 'Heart' }} />+ <Component name="Card"><Instance name="Icon" of={property('Icon', 'Star')} /></Component>+ <Component name="Heart" w={4} h={4} />+ </>`+ )+ const icon = graph.getChildren(instance.id).find((child) => child.type === 'INSTANCE')+ expect(icon?.componentId).toBe(heart.id)+ })++ test('lets a text that matches a component name give way to the components it needs', async () => {+ const graph = new SceneGraph()+ const [, board] = await renderJSX(+ graph,+ `<>+ <Component name="Badge"><Instance of="Tag" /></Component>+ <Frame name="Board"><Component name="Tag" w={4} h={4} /><Instance of="Card" Title="Badge" /></Frame>+ <Component name="Card"><Text name="Title" text={property('Title', 'Hi')} /></Component>+ </>`+ )+ const card = graph.getChildren(board.id).find((child) => child.type === 'INSTANCE')+ expect(graph.getChildren(card?.id ?? '')[0]?.text).toBe('Badge')+ })++ test('leaves nothing behind when a root fails to render', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ await expect(+ renderJSX(+ graph,+ '<><Instance of="Tile" properties={{ Missing: "x" }} /><Component name="Tile" w={4} h={4} /></>'+ )+ ).rejects.toThrow()+ expect(graph.getChildren(page.id)).toEqual([])+ })++ test('keeps a Reka text field binding its own text property', async () => {+ const graph = new SceneGraph()+ const [source] = await renderJSX(+ graph,+ '<TextField.Root name="Search"><TextField.Input name="Query" /></TextField.Root>'+ )+ const jsx = sceneNodeToJSX(source.id, graph)+ expect(jsx).not.toContain('property(')+ const [copy] = await renderJSX(graph, jsx)+ expect(definitions(getNodeOrThrow(graph, copy.id))).toEqual(+ definitions(getNodeOrThrow(graph, source.id))+ )+ expect(sceneNodeToJSX(copy.id, graph)).toBe(jsx)+ })+})diff --git a/packages/core/tests/design-jsx/components/overrides.test.ts b/packages/core/tests/design-jsx/components/overrides.test.tsnew file mode 100644index 000000000..f7278f7d9--- /dev/null+++ b/packages/core/tests/design-jsx/components/overrides.test.ts@@ -0,0 +1,64 @@+import { expect, test } from 'bun:test'++import { renderJSX } from '@open-pencil/core/design-jsx'+import { SceneGraph } from '@open-pencil/scene-graph'++test('finds an override layer among the instance children, by its name before renames', async () => {+ const graph = new SceneGraph()+ const [, created] = await renderJSX(+ graph,+ `<Component name="Card" w={60} h={24}>+ <Frame name="Card" w={4} h={4} />+ <Frame name="Icon:Small" w={4} h={4} />+ <Frame name="A" w={4} h={4} />+ <Frame name="B" w={4} h={4} />+ </Component>+ <Instance of="Card" overrides={{ 'Card:visible': false, 'Icon:Small:opacity': 0.5, 'A:name': 'B', 'B:name': 'C' }} />`+ )+ expect(graph.getNode(created.id)?.visible).toBe(true)+ const children = graph.getChildren(created.id)+ expect(children.map((child) => child.name)).toEqual(['Card', 'Icon:Small', 'B', 'C'])+ expect(children[0]?.visible).toBe(false)+ expect(children[1]?.opacity).toBe(0.5)+})++test('writes only fields an instance can override, and rejects a layer name several layers share', async () => {+ const graph = new SceneGraph()+ const [, created] = await renderJSX(+ graph,+ `<Component name="Pair" w={60} h={24}><Frame name="Dot" w={4} h={4} /><Frame name="Dot" w={4} h={4} /><Frame name="Box" w={4} h={4} /></Component>+ <Instance of="Pair" overrides={{ 'Box:childIds': ['missing'], 'Box:parentId': 'missing', 'Box:type': 'TEXT', 'Box:x': 30 }} />`+ )+ const box = graph.getChildren(created.id)[2]+ expect(box?.childIds).toEqual([])+ expect(box?.parentId).toBe(created.id)+ expect(box?.type).toBe('FRAME')+ expect(box?.x).toBe(0)+ const stored = graph.getNode(created.id)?.instanceOverrides.descendants.get(box?.id ?? '')+ for (const field of ['childIds', 'parentId', 'type', 'x']) expect(stored?.has(field)).not.toBe(true)+ await expect(+ renderJSX(graph, `<Instance of="Pair" overrides={{ 'Dot:opacity': 0.5 }} />`)+ ).rejects.toThrow('ambiguous')+})++test('warns about override keys it skips', async () => {+ const graph = new SceneGraph()+ const [, created] = await renderJSX(+ graph,+ `<Component name="Card" w={60} h={24}><Frame name="Dot" w={4} h={4} /></Component>+ <Instance of="Card" overrides={{ 'Dot:visible': 'false', 'Dot:fills': [null], 'Ghost:opacity': 0.5, 'Dot:x': 3, plain: 1 }} />`+ )+ const dot = graph.getChildren(created.id)[0]+ expect(dot?.visible).toBe(true)+ const stored = graph.getNode(created.id)?.instanceOverrides.descendants.get(dot?.id ?? '')+ for (const field of ['visible', 'fills', 'x']) expect(stored?.has(field)).not.toBe(true)+ expect(created.warnings).toEqual(+ expect.arrayContaining([+ 'overrides key "Dot:visible" takes a boolean, not a string; it is ignored.',+ 'overrides key "Dot:fills" holds an empty entry or one of another kind; it is ignored.',+ 'overrides key "Ghost:opacity" names no layer "Ghost" in the instance; it is ignored.',+ 'overrides key "Dot:x" names x, which an instance cannot override; it is ignored.',+ 'overrides key "plain" is not layer:field; it is ignored.'+ ])+ )+})diff --git a/packages/core/tests/design-jsx/instance-properties.test.ts b/packages/core/tests/design-jsx/components/properties.test.tssimilarity index 100%rename from packages/core/tests/design-jsx/instance-properties.test.tsrename to packages/core/tests/design-jsx/components/properties.test.tsdiff --git a/packages/core/tests/design-jsx/components/render.test.ts b/packages/core/tests/design-jsx/components/render.test.tsnew file mode 100644index 000000000..461842f3d--- /dev/null+++ b/packages/core/tests/design-jsx/components/render.test.ts@@ -0,0 +1,279 @@+import { describe, expect, test } from 'bun:test'++import { getNodeOrThrow } from '#core-tests/helpers/assert'++import { renderJSX } from '@open-pencil/core/design-jsx'+import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import { SceneGraph } from '@open-pencil/scene-graph'++describe('component rendering', () => {+ test('rejects a variant value the set does not have', async () => {+ const graph = new SceneGraph()+ await renderJSX(+ graph,+ '<ComponentSet name="Button"><Component name="State=On" /><Component name="State=Off" /></ComponentSet>'+ )+ await expect(renderJSX(graph, '<Instance of="Button" State="Nope" />')).rejects.toThrow(+ 'Button has no variant State=Nope'+ )+ })++ test('takes a variant prop set to undefined as no choice', async () => {+ const graph = new SceneGraph()+ const [set] = await renderJSX(+ graph,+ '<ComponentSet name="Button"><Component name="State=On" /><Component name="State=Off" /></ComponentSet>'+ )+ const [instance] = await renderJSX(graph, '<Instance of="Button" State={undefined} />')+ expect(getNodeOrThrow(graph, instance.id).componentId).toBe(graph.getChildren(set.id)[0]?.id)+ })++ test('runs renders into one graph one after another, so a failure undoes only its own', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const [failed, rendered] = await Promise.allSettled([+ renderJSX(graph, '<><Frame name="A" /><Instance of="Missing" /></>'),+ renderJSX(graph, '<Frame name="B" />')+ ])+ expect(failed?.status).toBe('rejected')+ expect(rendered?.status).toBe('fulfilled')+ expect(graph.getChildren(page.id).map((node) => node.name)).toEqual(['B'])+ })++ test('keeps a layer added to the parent while a failed render was in flight', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ // An editor adds a layer once the render has drawn its first one.+ const unsubscribe = graph.onNodeEvents({+ created: (node) => {+ if (node.name === 'A') graph.createNode('FRAME', page.id, { name: 'Editor' })+ }+ })+ await expect(+ renderJSX(graph, '<><Frame name="A" /><Instance of="Missing" /></>')+ ).rejects.toThrow('component not found')+ unsubscribe()+ expect(graph.getChildren(page.id).map((node) => node.name)).toEqual(['Editor'])+ })++ test('undoes a render whose steps after drawing fail', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ await expect(+ renderJSX(graph, '<Frame name="X" />', {+ onNode: () => {+ throw new Error('boom')+ }+ })+ ).rejects.toThrow('boom')+ expect(graph.getChildren(page.id)).toEqual([])+ })++ test('keeps the variables a failed render defined, which rendering again reuses', async () => {+ const graph = new SceneGraph()+ const jsx = (end: string) => `const theme = defineVars('Theme', { Accent: '#FF0000' })+ return <><Frame bg={theme.Accent} />${end}</>`+ await expect(renderJSX(graph, jsx('<Instance of="Missing" />'))).rejects.toThrow(+ 'component not found'+ )+ const kept = [...graph.variables.keys()]+ await renderJSX(graph, jsx(''))+ expect([...graph.variableCollections.values()].map((item) => item.name)).toEqual(['Theme'])+ expect([...graph.variables.values()].map((item) => item.name)).toEqual(['Accent'])+ expect([...graph.variables.keys()]).toEqual(kept)+ })++ test('removes an instance a Reka root draws when a later root fails', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ await renderJSX(+ graph,+ `<Switch.Root name="Toggle" modelValue="State">+ <Component name="State=Off" w={44} h={24} /><Component name="State=On" w={44} h={24} />+ </Switch.Root>`+ )+ await expect(+ renderJSX(graph, '<><Switch.Root of="Toggle" /><Instance of="Missing" /></>')+ ).rejects.toThrow('component not found')+ expect(graph.getChildren(page.id).map((node) => node.name)).toEqual(['Toggle'])+ })++ test('unbinds the layers another hand binds to a property a failed render added', async () => {+ const graph = new SceneGraph()+ const [card] = await renderJSX(+ graph,+ '<Component name="Card"><Text name="Title" /></Component>'+ )+ const title = graph.getChildren(card.id)[0]+ const unsubscribe = graph.onNodeEvents({+ created: (node) => {+ if (node.name !== 'Copy' || !title) return+ const [label] = getNodeOrThrow(graph, card.id).componentPropertyDefinitions+ graph.updateNode(title.id, {+ componentPropertyReferences: [{ propertyId: label?.id ?? '', field: 'TEXT' }]+ })+ }+ })+ await expect(+ renderJSX(+ graph,+ `<><Text name="Copy" text={property('Label', 'Hi')} /><Instance of="Missing" /></>`,+ { parentId: card.id }+ )+ ).rejects.toThrow('component not found')+ unsubscribe()+ expect(getNodeOrThrow(graph, card.id).componentPropertyDefinitions).toEqual([])+ expect(getNodeOrThrow(graph, title?.id ?? '').componentPropertyReferences).toEqual([])+ })++ test('removes a layer that draws itself when binding its variable fails', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ await expect(+ renderJSX(+ graph,+ `const theme = defineVars('Theme', { Size: 4 })+ return <Sticky bg={theme.Size}>Hi</Sticky>`+ )+ ).rejects.toThrow('Cannot bind FLOAT variable')+ expect(graph.getChildren(page.id)).toEqual([])+ })++ test('keeps a property another hand adds to the component a failed render renders into', async () => {+ const graph = new SceneGraph()+ const [, card] = await renderJSX(+ graph,+ '<><Component name="Tile" w={4} h={4} /><Component name="Card" /></>'+ )+ const unsubscribe = graph.onNodeEvents({+ created: (node) => {+ if (node.name !== 'Copy') return+ const owner = getNodeOrThrow(graph, card.id)+ graph.updateNode(card.id, {+ componentPropertyDefinitions: [+ ...owner.componentPropertyDefinitions,+ { id: 'editor', name: 'Editor', type: 'TEXT', defaultValue: '' }+ ]+ })+ }+ })+ await expect(+ renderJSX(+ graph,+ `<><Text name="Copy" text={property('Label', 'Hi')} /><Instance of="Missing" /></>`,+ { parentId: card.id }+ )+ ).rejects.toThrow('component not found')+ unsubscribe()+ expect(+ getNodeOrThrow(graph, card.id).componentPropertyDefinitions.map((item) => item.name)+ ).toEqual(['Editor'])+ })++ test('rejects an instance that would put its component inside itself', async () => {+ const graph = new SceneGraph()+ await expect(+ renderJSX(graph, '<Component name="Loop"><Instance of="Loop" /></Component>')+ ).rejects.toThrow('would put the component inside itself')+ expect(graph.getChildren(graph.getPages()[0].id)).toEqual([])+ })++ test('undoes the properties a failed render added to the component it renders into', async () => {+ const graph = new SceneGraph()+ const [card] = await renderJSX(+ graph,+ '<><Component name="Tile" w={4} h={4} /><Component name="Card" /></>'+ ).then((results) => results.slice(1))+ await expect(+ renderJSX(+ graph,+ `<Instance of="Tile" visible={property('Shown', true)} properties={{ Missing: 'x' }} />`,+ { parentId: card.id }+ )+ ).rejects.toThrow('Unknown component property: Missing')+ expect(getNodeOrThrow(graph, card.id).componentPropertyDefinitions).toEqual([])+ await renderJSX(graph, `<Frame visible={property('Shown', false)} />`, { parentId: card.id })+ expect(getNodeOrThrow(graph, card.id).componentPropertyDefinitions).toHaveLength(1)+ })++ test('rejects a variant property named like another property of the set', async () => {+ const graph = new SceneGraph()+ await expect(+ renderJSX(+ graph,+ `<ComponentSet name="Badge"><Component name="State=On"><Text text={property('State', 'x')} /></Component></ComponentSet>`+ )+ ).rejects.toThrow('Variant property State of Badge has the name of its TEXT property')+ })++ test('keeps a layer prop its meaning when a variant property shares its name', async () => {+ const graph = new SceneGraph()+ await renderJSX(+ graph,+ '<ComponentSet name="Eye"><Component name="visible=true" w={4} h={4} /><Component name="visible=false" w={8} h={8} /></ComponentSet>'+ )+ // `visible` hides the instance; it does not pick the visible=false variant.+ const [hidden] = await renderJSX(graph, '<Instance of="Eye" visible={false} />')+ expect(getNodeOrThrow(graph, hidden.id).visible).toBe(false)+ expect(getNodeOrThrow(graph, hidden.id).width).toBe(4)+ const [chosen] = await renderJSX(graph, '<Instance of="visible=false" />')+ expect(getNodeOrThrow(graph, chosen.id).width).toBe(8)+ })++ test('orders components inside Reka parts before the elements that name them', async () => {+ const graph = new SceneGraph()+ const [root] = await renderJSX(+ graph,+ `<Tabs.Root name="Tabs">+ <Tabs.Content name="First"><Instance name="Copy" of="Tile" /><Component name="Tile" w={4} h={4} /></Tabs.Content>+ <Tabs.Content name="Second" />+ </Tabs.Root>`+ )+ const panels = [...graph.getAllNodes()].filter(+ (node) => node.name === 'First' || node.name === 'Second'+ )+ expect(panels.map((panel) => panel.visible)).toEqual([true, false])+ const first = panels[0]+ expect(graph.getChildren(first?.id ?? '').map((child) => child.type)).toEqual([+ 'INSTANCE',+ 'COMPONENT'+ ])+ expect(root.type).toBe('COMPONENT')+ })++ test('orders a component an exposed instance value names before the instance', async () => {+ const graph = new SceneGraph()+ const results = await renderJSX(+ graph,+ `<>+ <Component name="Star" w={4} h={4} />+ <Instance of="Card" Action={{ Icon: 'Arrow' }} />+ <Component name="Button"><Instance name="Icon" of={property('Icon', 'Star')} /></Component>+ <Component name="Card"><Instance name="Action" of="Button" exposed /></Component>+ <Component name="Arrow" w={4} h={4} />+ </>`+ )+ const arrow = results[4]+ const action = graph.getChildren(results[1].id)[0]+ const icon = graph.getChildren(action?.id ?? '')[0]+ expect(icon?.componentId).toBe(arrow.id)+ })++ test('binds and writes back the visibility of an element that draws its own layer', async () => {+ const graph = new SceneGraph()+ const [note] = await renderJSX(+ graph,+ `<Component name="Note"><Sticky visible={property('Shown', true)}>Hi</Sticky></Component>`+ )+ const [definition] = getNodeOrThrow(graph, note.id).componentPropertyDefinitions+ expect(definition).toMatchObject({ name: 'Shown', type: 'BOOLEAN' })+ const sticky = graph.getChildren(note.id)[0]+ expect(sticky?.componentPropertyReferences).toEqual([+ { propertyId: definition?.id, field: 'VISIBLE' }+ ])+ const jsx = sceneNodeToJSX(note.id, graph)+ expect(jsx).toContain('visible={property("Shown", true)}')+ const [copy] = await renderJSX(graph, jsx)+ expect(sceneNodeToJSX(copy.id, graph)).toBe(jsx)+ })+})diff --git a/packages/core/tests/design-jsx/connectors.test.ts b/packages/core/tests/design-jsx/figjam/connectors.test.tssimilarity index 100%rename from packages/core/tests/design-jsx/connectors.test.tsrename to packages/core/tests/design-jsx/figjam/connectors.test.tsdiff --git a/packages/core/tests/design-jsx/shapes-with-text.test.ts b/packages/core/tests/design-jsx/figjam/shapes-with-text.test.tssimilarity index 100%rename from packages/core/tests/design-jsx/shapes-with-text.test.tsrename to packages/core/tests/design-jsx/figjam/shapes-with-text.test.tsdiff --git a/packages/core/tests/design-jsx/stickies.test.ts b/packages/core/tests/design-jsx/figjam/stickies.test.tssimilarity index 100%rename from packages/core/tests/design-jsx/stickies.test.tsrename to packages/core/tests/design-jsx/figjam/stickies.test.tsdiff --git a/packages/core/tests/design-jsx/placement.test.ts b/packages/core/tests/design-jsx/placement.test.tsindex 794798d16..d4f97e090 100644--- a/packages/core/tests/design-jsx/placement.test.ts+++ b/packages/core/tests/design-jsx/placement.test.ts@@ -170,6 +170,18 @@ describe('shared render/preview placement', () => {expect(page.childIds.map((id) => setup.graph.getNode(id)?.name)).toEqual(['A', 'B', 'Board'])})+ it('stages an instance written before its component', async () => {+ const setup = await fixture()+ const staged = await compareToFinal(+ setup,+ '<><Instance name="Copy" of="Tile"/><Component name="Tile" w={40} h={40}/></>',+ { insert_index: 0 }+ )+ const [copy, tile] = staged.renderedIds.map((id) => getNodeOrThrow(staged.graph, id))+ expect(copy?.type).toBe('INSTANCE')+ expect(copy?.componentId).toBe(tile?.id)+ })+it('rejects nonexistent targets before mutating the document', async () => {const setup = await fixture()const before = structuredClone([...setup.graph.nodes])diff --git a/packages/core/tests/figma-api/serialization.test.ts b/packages/core/tests/figma-api/serialization.test.tsindex a72e3a5ad..9128b389c 100644--- a/packages/core/tests/figma-api/serialization.test.ts+++ b/packages/core/tests/figma-api/serialization.test.ts@@ -29,6 +29,42 @@ describe('serialization', () => {expect(json.children?.length).toBe(1)})+ test('toJSON includes component properties and their layer references', () => {+ const api = createAPI()+ const component = api.createComponent()+ const definition = {+ id: 'label',+ name: 'Label',+ type: 'TEXT' as const,+ defaultValue: 'Hi'+ }+ api.graph.updateNode(component.id, { componentPropertyDefinitions: [definition] })+ const text = api.createText()+ component.appendChild(text)+ api.graph.updateNode(text.id, {+ text: 'Hi',+ componentPropertyReferences: [{ propertyId: definition.id, field: 'TEXT' }]+ })++ const json = component.toJSON() as {+ componentPropertyDefinitions?: unknown+ children?: Array<{ componentPropertyReferences?: unknown }>+ }+ expect(json.componentPropertyDefinitions).toEqual([definition])+ expect(json.children?.[0]?.componentPropertyReferences).toEqual([+ { propertyId: definition.id, field: 'TEXT' }+ ])++ const instance = api.graph.createInstance(component.id, api.currentPageId)+ if (!instance) throw new Error('Could not create a component instance')+ api.graph.updateNode(instance.id, {+ componentPropertyAssignments: { [definition.id]: 'Changed' }+ })+ expect(api.wrapNode(instance.id).toJSON()).toMatchObject({+ componentPropertyAssignments: { [definition.id]: 'Changed' }+ })+ })+test('toString returns readable string', () => {const api = createAPI()const frame = api.createFrame()diff --git a/packages/core/tests/tools/read/components.test.ts b/packages/core/tests/tools/read/components.test.tsnew file mode 100644index 000000000..15d2bd52e--- /dev/null+++ b/packages/core/tests/tools/read/components.test.ts@@ -0,0 +1,31 @@+import { expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++function getComponentsTool() {+ const tool = ALL_TOOLS.find((item) => item.name === 'get_components')+ if (!tool) throw new Error('Missing get_components tool')+ return tool+}++test('get_components includes component property definitions', async () => {+ const figma = new FigmaAPI(new SceneGraph())+ const component = figma.createComponent()+ component.name = 'Note'+ component.addComponentProperty('Label', 'TEXT', 'Hi')++ const result = await getComponentsTool().execute(figma, { source: 'document' })+ expect(result).toMatchObject({+ components: [+ {+ id: component.id,+ name: 'Note',+ componentPropertyDefinitions: [+ expect.objectContaining({ name: 'Label', type: 'TEXT', defaultValue: 'Hi' })+ ]+ }+ ]+ })+})diff --git a/packages/core/tests/tools/read/nodes.test.ts b/packages/core/tests/tools/read/nodes.test.tsnew file mode 100644index 000000000..fd075cf01--- /dev/null+++ b/packages/core/tests/tools/read/nodes.test.ts@@ -0,0 +1,41 @@+import { expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++function getNodeTool() {+ const tool = ALL_TOOLS.find((item) => item.name === 'get_node')+ if (!tool) throw new Error('Missing get_node tool')+ return tool+}++test('get_node includes component properties and layer references', () => {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const definition = {+ id: 'label',+ name: 'Label',+ type: 'TEXT' as const,+ defaultValue: 'Hi'+ }+ const component = graph.createNode('COMPONENT', figma.currentPageId, {+ name: 'Note',+ componentPropertyDefinitions: [definition]+ })+ graph.createNode('TEXT', component.id, {+ name: 'Label',+ text: 'Hi',+ componentPropertyReferences: [{ propertyId: definition.id, field: 'TEXT' }]+ })++ const result = getNodeTool().execute(figma, { id: component.id })+ expect(result).toMatchObject({+ componentPropertyDefinitions: [definition],+ children: [+ {+ componentPropertyReferences: [{ propertyId: definition.id, field: 'TEXT' }]+ }+ ]+ })+})diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.mdindex f210eb2c2..4fe182e0f 100644--- a/packages/design-jsx/AGENTS.md+++ b/packages/design-jsx/AGENTS.md@@ -7,8 +7,8 @@ Rules:- Depend only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX` and `renderTree` from `@open-pencil/core/design-jsx`.- The `layout` service receives the rendered roots. A caller that moves them into place afterwards passes `deferLayout` and lays them out once (`packages/core/src/design-jsx/placement.ts`).- `src/streaming/` parses JSX as it streams in and projects the static subset into trees without evaluating expressions; Core's `packages/core/src/design-jsx/preview/` stages and records those trees on the canvas.-- Each element is one entry in `DESIGN_JSX_ELEMENTS` (`src/elements.ts`): its name, the layer type it builds and the types it writes, and its props. The runtime bindings, renderer, export tag, unsupported-prop warnings, schema, and reference read it; do not add a parallel tag or type map (`tests/elements.test.ts`).-- An element that draws its own layer, such as `<Sticky>` or `<Connector>`, declares its props as a Valibot `schema` and its renderer as `ownLayer` on its entry; a value that does not fit warns and is left out. Its layer props (`OwnLayerProps`) go through `propsToOverrides` like any layer's, so variables bind; the element reads only its own props (`packages/core/tests/design-jsx/stickies.test.ts`).+- Each element is one entry in `DESIGN_JSX_ELEMENTS` (`src/elements/index.ts`): its name, the layer type it builds and the types it writes, and its props. The runtime bindings, renderer, export tag, unsupported-prop warnings, schema, and reference read it; do not add a parallel tag or type map (`tests/elements/index.test.ts`).+- An element that draws its own layer, such as `<Sticky>` or `<Connector>`, declares its props as a Valibot `schema` and its renderer as `ownLayer` on its entry; a value that does not fit warns and is left out. Its layer props (`OwnLayerProps`) go through `propsToOverrides` like any layer's, so variables bind; the element reads only its own props (`packages/core/tests/design-jsx/figjam/stickies.test.ts`).- Export writes each generated frame through `OWN_ELEMENTS`, keyed by `GeneratedFrameType`, so a new generated frame does not compile until it has an exporter (`src/export/index.ts`).- An enum prop is one `jsxEnum` table in `src/enums.ts` that both reads and writes it, and an unknown value warns instead of falling back silently (`tests/enums.test.ts`).- JSX export (`src/export/`) collects typed props in `props.ts` and prints them with `@open-pencil/emit`'s JSX builders; never build JSX from string fragments.diff --git a/packages/design-jsx/src/export/behaviours.ts b/packages/design-jsx/src/behaviours/export.tssimilarity index 85%rename from packages/design-jsx/src/export/behaviours.tsrename to packages/design-jsx/src/behaviours/export.tsindex 6870f0dd4..795f9fb74 100644--- a/packages/design-jsx/src/export/behaviours.ts+++ b/packages/design-jsx/src/behaviours/export.ts@@ -1,3 +1,5 @@+import { findKey } from 'es-toolkit'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import {behaviourToSpec,@@ -8,8 +10,10 @@ import {import { instanceMainComponent } from '@open-pencil/scene-graph/instances'import { slotPropertyId } from '@open-pencil/scene-graph/slots'-import { REKA_ELEMENTS, rekaRole } from '../behaviours'-import type { JSXProp, JSXValue } from './value'+import { REKA_ELEMENTS, rekaRole } from '.'+import { itemProps } from '../export/components/instances'+import type { ComponentReference } from '../export/components/references'+import type { JSXProp, JSXValue } from '../export/value'/** The Reka namespace and element a kind's component is written as. */const ROOTS: Record<BehaviourKind, [namespace: string, element: string]> = {@@ -78,7 +82,8 @@ function exportPart(namespace: string,layer: SceneNode,partId: string,- result: RekaExport+ result: RekaExport,+ componentRef: ComponentReference): void {const tag = elementFor(namespace, (role) => role?.role === 'part' && role.part === partId)const repeated = elementFor(@@ -91,10 +96,12 @@ function exportPart(if (repeated) result.tags.set(child.id, repeated)const item = child.type === 'INSTANCE' ? instanceMainComponent(graph, child) : undefinedif (partId !== 'items' || !item) continue- // A group's items are written as the group's Item, naming their component.- const set = item.parentId ? graph.getNode(item.parentId) : undefined+ // A group's items are written as the group's Item, naming their component and variant, and+ // what the item changes in it; an item whose changes cannot be written is written as a layer.+ const props = itemProps(graph, child, item, componentRef)+ if (!props) continueresult.tags.set(child.id, `${namespace}.Item`)- result.props.set(child.id, [['of', (set?.type === 'COMPONENT_SET' ? set : item).id]])+ result.props.set(child.id, props)}}@@ -108,7 +115,11 @@ function descendants(graph: SceneGraph, node: SceneNode): SceneNode[] {* `Switch.Thumb`, `TextField.Input`, tab triggers and panels, and a group's items as* `RadioGroup.Item of="…"`. Null for other layers.*/-export function rekaExport(graph: SceneGraph, owner: SceneNode): RekaExport | null {+export function rekaExport(+ graph: SceneGraph,+ owner: SceneNode,+ componentRef: ComponentReference+): RekaExport | null {const behaviour = readBehaviour(owner)if (!behaviour || (owner.type !== 'COMPONENT' && owner.type !== 'COMPONENT_SET')) return nullconst [namespace, element] = ROOTS[behaviour.kind]@@ -122,11 +133,9 @@ export function rekaExport(graph: SceneGraph, owner: SceneNode): RekaExport | nu)for (const layer of descendants(graph, owner)) {if (layer.type === 'INSTANCE') continue- const partId = Object.entries(behaviour.parts).find(- ([, id]) => id === slotPropertyId(layer)- )?.[0]+ const partId = findKey(behaviour.parts, (id) => id === slotPropertyId(layer))if (partId) {- exportPart(graph, namespace, layer, partId, result)+ exportPart(graph, namespace, layer, partId, result, componentRef)continue}const reference = layer.componentPropertyReferences.find((item) => item.field === 'TEXT')diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.tsindex fd512fc65..39cf65dc7 100644--- a/packages/design-jsx/src/behaviours/index.ts+++ b/packages/design-jsx/src/behaviours/index.ts@@ -1,3 +1,5 @@+import { isNumber } from 'es-toolkit'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import {behaviourFromSpec,@@ -222,11 +224,11 @@ function rootSpec(kind: BehaviourKind, props: Record<string, unknown>): Behaviouif (isBinding(main)) values[kind === 'collapsible' ? 'open' : 'value'] = mainif (isBinding(props.disabled)) values.disabled = props.disabledif (isBinding(props.filled)) values.filled = props.filled- const range = Object.fromEntries(- (['min', 'max', 'step'] as const).flatMap((key) =>- typeof props[key] === 'number' ? [[key, props[key]]] : []- )- )+ const range: Record<string, number> = {}+ for (const key of ['min', 'max', 'step'] as const) {+ const value = props[key]+ if (isNumber(value)) range[key] = value+ }if (typeof props.defaultValue === 'number') range.default = props.defaultValueconst spec: BehaviourSpec = { kind }if (Object.keys(values).length) spec.values = valuesdiff --git a/packages/design-jsx/src/behaviours/render.ts b/packages/design-jsx/src/behaviours/render.tsindex c546a9763..cf28142b4 100644--- a/packages/design-jsx/src/behaviours/render.ts+++ b/packages/design-jsx/src/behaviours/render.ts@@ -1,7 +1,9 @@+import { omit } from 'es-toolkit'+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { designJSXProp } from '../definitions'-import type { TreeNode } from '../tree'+import { isTreeNode, type TreeNode } from '../tree'import {BEHAVIOUR_PROPS,bindInput,@@ -15,30 +17,37 @@ import {type RekaScope} from './index'-export type RenderChild = (- tree: TreeNode,+/** Render children in the renderer's order, returning their layers in written order. */+export type RenderChildren = (+ children: TreeNode[],parentId: string,scope?: RekaScope-) => Promise<SceneNode>+) => Promise<SceneNode[]>export type CreateElement = (nodeType: NodeType, tree: TreeNode, parentId: string) => SceneNodeexport type RenderInstance = (tree: TreeNode, parentId: string) => Promise<SceneNode>function withoutBehaviourProps(tree: TreeNode): TreeNode {- const props = Object.fromEntries(- Object.entries(tree.props).filter(- ([key]) => !(BEHAVIOUR_PROPS as readonly string[]).includes(key)- )- )- return { ...tree, props }+ return { ...tree, props: omit(tree.props, BEHAVIOUR_PROPS) }}async function renderChildren(- render: RenderChild,+ graph: SceneGraph,+ render: RenderChildren,children: TreeNode['children'],parentId: string,scope: RekaScope | undefined): Promise<void> {- for (const child of children) if (typeof child !== 'string') await render(child, parentId, scope)+ const trees = children.filter(isTreeNode)+ const layers = await render(trees, parentId, scope)+ // Only the first tab's panel shows as designed; preview shows the others as chosen.+ const panels = trees.flatMap((tree, index) => {+ const role = rekaRole(tree.type)+ return role?.role === 'repeat' && role.container === 'panels'+ ? [{ tree, layer: layers[index] }]+ : []+ })+ for (const { tree, layer } of panels.slice(1))+ if (tree.props.visible === undefined) graph.updateNode(layer.id, { visible: false })}/** A name for a part that JSX leaves unnamed: the Reka part it is, such as Thumb. */@@ -73,7 +82,7 @@ export async function renderRekaNode(parentId: string,scope: RekaScope | undefined,hooks: {- render: RenderChild+ renderChildren: RenderChildrencreate: CreateElementinstance: RenderInstance/** Derive a component set's variant properties from its variants' names. */@@ -97,7 +106,13 @@ export async function renderRekaNode(parentId)const own = createScope(role.kind, root.id)- await renderChildren(hooks.render, wrapRepeatedParts(tree, role.kind), root.id, own)+ await renderChildren(+ graph,+ hooks.renderChildren,+ wrapRepeatedParts(tree, role.kind),+ root.id,+ own+ )if (variants) hooks.finishSet(root.id)finishRoot(graph, own, tree.props)return root@@ -105,21 +120,13 @@ export async function renderRekaNode(case 'part': {if (!scope) throw new Error(`<${tree.type}> must be inside its Root`)const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)- await renderChildren(hooks.render, tree.children, frame.id, scope)+ await renderChildren(graph, hooks.renderChildren, tree.children, frame.id, scope)bindPart(graph, scope, frame, role.part)return frame}case 'repeat': {const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)- await renderChildren(hooks.render, tree.children, frame.id, scope)- // Only the first tab's panel shows as designed; preview shows the others as chosen.- const siblings = graph.getChildren(parentId)- if (- role.container === 'panels' &&- siblings[0]?.id !== frame.id &&- tree.props.visible === undefined- )- graph.updateNode(frame.id, { visible: false })+ await renderChildren(graph, hooks.renderChildren, tree.children, frame.id, scope)return frame}case 'input': {@@ -136,7 +143,7 @@ export async function renderRekaNode(}case 'frame': {const frame = hooks.create('FRAME', laidOut(named(tree, partName)), parentId)- await renderChildren(hooks.render, tree.children, frame.id, scope)+ await renderChildren(graph, hooks.renderChildren, tree.children, frame.id, scope)return frame}}diff --git a/packages/design-jsx/src/component-properties.ts b/packages/design-jsx/src/component-properties.tsdeleted file mode 100644index ca97a19f0..000000000--- a/packages/design-jsx/src/component-properties.ts+++ /dev/null@@ -1,428 +0,0 @@-import { compact } from 'es-toolkit/array'-import { isPlainObject } from 'es-toolkit/predicate'-import * as v from 'valibot'--import type {- ComponentPropertyDefinition,- ComponentPropertyReference,- SceneGraph,- SceneNode-} from '@open-pencil/scene-graph'-import {- applyComponentPropertyValue,- componentPropertyDefinitions,- 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 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- }->--/** 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- }- node = node.parentId ? graph.getNode(node.parentId) : undefined- }- 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. */-export function componentPropertyScope(- graph: SceneGraph,- parentId: string-): readonly ComponentPropertyDefinition[] | undefined {- let parent = graph.getNode(parentId)- while (parent) {- if (parent.type === 'INSTANCE') return componentPropertyDefinitions(graph, parent)- if (parent.type === 'COMPONENT_SET') return parent.componentPropertyDefinitions- if (parent.type === 'COMPONENT') {- const set = parent.parentId ? graph.getNode(parent.parentId) : undefined- return set?.type === 'COMPONENT_SET'- ? [...set.componentPropertyDefinitions, ...parent.componentPropertyDefinitions]- : parent.componentPropertyDefinitions- }- parent = parent.parentId ? graph.getNode(parent.parentId) : undefined- }- return undefined-}--/** The one property with this name; a name several properties share is an error. */-function namedDefinition(- definitions: readonly ComponentPropertyDefinition[],- name: string-): ComponentPropertyDefinition | undefined {- const matches = definitions.filter((item) => item.name === name)- if (matches.length > 1)- throw new Error(- `Component property name ${name} is ambiguous; use one of the IDs: ${matches.map((item) => item.id).join(', ')}`- )- 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,- 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}`)- // 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)-}--/**- * 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>,- 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), componentId)- }-}--/**- * Keys are property IDs or, because saving to `.fig` replaces authored IDs- * 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,- componentId: ComponentLookup-): void {- if (input === undefined) return- const assignments = parseScriptInput(- 'Invalid properties on <Instance>',- 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, 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> = {}- for (const entry of entries) {- const [key = '', ...rest] = entry.split('=')- const property = key.trim()- const value = rest.join('=').trim()- if (property && value) values[property] = value- }- return values-}--/** Variant properties a component set takes from its variants' names, such as `State=On`. */-export function inferComponentSetProperties(graph: SceneGraph, componentSetId: string): void {- const componentSet = graph.getNode(componentSetId)- if (componentSet?.type !== 'COMPONENT_SET') return- const existingDefinitions = componentSet.componentPropertyDefinitions-- const variants = graph.getChildren(componentSetId).filter((node) => node.type === 'COMPONENT')- const options = new Map<string, Set<string>>()- const valuesById = new Map<string, Record<string, string>>()-- for (const variant of variants) {- const values = parseVariantValues(variant.name)- valuesById.set(variant.id, values)- for (const [property, value] of Object.entries(values)) {- let set = options.get(property)- if (!set) {- set = new Set()- options.set(property, set)- }- set.add(value)- }- }-- const definitions: ComponentPropertyDefinition[] = [...options.entries()]- .filter(- ([name]) =>- !existingDefinitions.some(- (definition) => definition.type === 'VARIANT' && definition.name === name- )- )- .map(([name, values]) => {- const variantOptions = [...values]- return {- id: createComponentPropertyId(),- name,- type: 'VARIANT',- defaultValue: variantOptions[0] ?? '',- variantOptions- }- })-- for (const [id, values] of valuesById) {- graph.updateNode(id, { componentPropertyValues: values })- }- graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...existingDefinitions, ...definitions]- })-}diff --git a/packages/design-jsx/src/components/assignments.ts b/packages/design-jsx/src/components/assignments.tsnew file mode 100644index 000000000..500c66924--- /dev/null+++ b/packages/design-jsx/src/components/assignments.ts@@ -0,0 +1,196 @@+import { isPlainObject, mapValues, omit, omitBy, pick, pickBy } from 'es-toolkit'+import * as v from 'valibot'++import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ applyComponentPropertyValue,+ componentPropertyDefinitions,+ exposedInstances+} from '@open-pencil/scene-graph/components'+import { instanceMainComponent } from '@open-pencil/scene-graph/instances'++import { DESIGN_JSX_SUPPORTED_PROPERTIES } from '../definitions'+import { isLayerRef, type LayerRef } from '../refs'+import { parseScriptInput } from '../schema'+import { hasVariantValues, type ComponentLookup } from './properties'++/** The one property with this name; a name several properties share is an error. */+function namedDefinition(+ definitions: readonly ComponentPropertyDefinition[],+ name: string+): ComponentPropertyDefinition | undefined {+ const matches = definitions.filter((item) => item.name === name)+ if (matches.length > 1)+ throw new Error(+ `Component property name ${name} is ambiguous; use one of the IDs: ${matches.map((item) => item.id).join(', ')}`+ )+ return matches[0]+}++/** A value as an assignment takes it: a swap's `ref()` as it is, anything else as text. */+function assignable(value: unknown): string | LayerRef {+ return isLayerRef(value) ? value : String(value)+}++function assignValue(+ graph: SceneGraph,+ instance: SceneNode,+ definition: ComponentPropertyDefinition,+ key: string,+ value: string | LayerRef,+ componentId: ComponentLookup+): void {+ if (isLayerRef(value)) {+ if (definition.type !== 'INSTANCE_SWAP')+ throw new Error(`A ref() names a component, for a swap property, not ${key}`)+ const id = componentId(value)+ if (!id) throw new Error(`${key} names a ref() that marks no component rendered before it`)+ if (!applyComponentPropertyValue(graph, instance.id, definition, id))+ throw new Error(`Cannot assign component property: ${key}`)+ return+ }+ 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}`)+ // 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' && hasVariantValues(node, wanted))+ 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)+}++/**+ * 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 = componentPropertyDefinitions(graph, nested)+ .filter((definition) => definition.type === 'VARIANT')+ .map((definition) => definition.name)+ selectNestedVariant(graph, nested, name, mapValues(pick(values, variantNames), String))+ const definitions = componentPropertyDefinitions(graph, nested)+ for (const [key, value] of Object.entries(omit(values, variantNames))) {+ const definition = namedDefinition(definitions, key)+ if (!definition) throw new Error(`Unknown component property on ${name}: ${key}`)+ assignValue(graph, nested, definition, key, assignable(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>,+ 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' &&+ !isLayerRef(value)+ )+ throw new Error(`Expected a string, boolean, or ref() for component property: ${key}`)+ assignValue(graph, instance, definition, key, assignable(value), componentId)+ }+}++/**+ * Keys are property IDs or, because saving to `.fig` replaces authored IDs+ * 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,+ componentId: ComponentLookup+): void {+ if (input === undefined) return+ // A swap's ref() is not data to validate; it is kept as it is.+ const refs = isPlainObject(input) ? pickBy(input, (value) => isLayerRef(value)) : {}+ const assignments = {+ ...parseScriptInput(+ 'Invalid properties on <Instance>',+ v.record(v.string(), v.union([assignedValueSchema, exposedValuesSchema])),+ isPlainObject(input) ? omitBy(input, (value) => isLayerRef(value)) : input+ ),+ ...refs+ }+ 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, assignable(value), componentId)+ }+}diff --git a/packages/design-jsx/src/components/instances.ts b/packages/design-jsx/src/components/instances.tsnew file mode 100644index 000000000..0fb17a562--- /dev/null+++ b/packages/design-jsx/src/components/instances.ts@@ -0,0 +1,267 @@+import { isEmptyObject, isUndefined, mapValues, omitBy, pick } from 'es-toolkit'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { INSTANCE_OVERRIDE_FIELDS } from '@open-pencil/scene-graph/instances'+import { setInstanceOverride } from '@open-pencil/scene-graph/instances/overrides'++import { DESIGN_JSX_SUPPORTED_PROPERTIES } from '../definitions'+import { propsToOverrides } from '../overrides'+import { isLayerRef, type LayerRefs } from '../refs'+import type { RenderContext } from '../render/node'+import { applyBindings, layerMetadata, preparePropsForRender } from '../render/props'+import type { TreeNode } from '../tree'+import { variableModes } from '../variables/graph'+import { assignComponentProperties, assignNamedProperties } from './assignments'+import {+ bindProperties,+ componentPropNames as namesOnInstance,+ exposeInstance,+ hasVariantValues,+ type ComponentLookup+} from './properties'++function findComponentByName(graph: SceneGraph, name: string): SceneNode | undefined {+ for (const node of graph.getAllNodes()) {+ if (node.type === 'COMPONENT' && node.name === name) return node+ }+ return undefined+}++function findVariantInSet(+ graph: SceneGraph,+ componentSet: SceneNode,+ props: Record<string, unknown>+) {+ // A variant property named like a layer prop, such as `visible`, keeps the prop's meaning;+ // `of` names such a variant itself, as export writes it.+ const variantNames = componentSet.componentPropertyDefinitions+ .filter(+ (definition) =>+ definition.type === 'VARIANT' && !DESIGN_JSX_SUPPORTED_PROPERTIES.has(definition.name)+ )+ .map((definition) => definition.name)+ // A prop set to undefined, as a conditional value can be, picks no variant.+ const requested = mapValues(omitBy(pick(props, variantNames), isUndefined), String)+ const variants = graph.getChildren(componentSet.id).filter((node) => node.type === 'COMPONENT')+ if (isEmptyObject(requested)) return variants.at(0)+ const variant = variants.find((item) => hasVariantValues(item, requested))+ if (!variant)+ throw new Error(+ `${componentSet.name} has no variant ${Object.entries(requested)+ .map(([key, value]) => `${key}=${value}`)+ .join(', ')}`+ )+ return variant+}++/** The component or component set an element names by id or name. */+function namedComponent(+ graph: SceneGraph,+ props: Record<string, unknown>,+ refs?: LayerRefs+): SceneNode | undefined {+ const ref = props.component ?? props.componentId ?? props.of+ if (isLayerRef(ref)) {+ const marked = graph.getNode(refs?.layerOf(ref) ?? '')+ return marked?.type === 'COMPONENT' || marked?.type === 'COMPONENT_SET' ? marked : undefined+ }+ if (typeof ref !== 'string') return undefined++ const byId = graph.getNode(ref)+ if (byId?.type === 'COMPONENT' || byId?.type === 'COMPONENT_SET') return byId++ const byName = findComponentByName(graph, ref)+ if (byName) return byName++ for (const node of graph.getAllNodes()) {+ if (node.type === 'COMPONENT_SET' && node.name === ref) return node+ }+ return undefined+}++function resolveComponent(+ graph: SceneGraph,+ props: Record<string, unknown>,+ refs?: LayerRefs+): SceneNode | undefined {+ const named = namedComponent(graph, props, refs)+ return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named+}++/**+ * The names an element sets on its component by prop: properties such as `State` or `Title`, and+ * exposed instances. The instance it rendered as, if given, names its component.+ */+export function componentPropNames(+ graph: SceneGraph,+ props: Record<string, unknown>,+ rendered?: SceneNode+): string[] {+ const component =+ rendered?.type === 'INSTANCE'+ ? graph.getNode(rendered.componentId ?? '')+ : resolveComponent(graph, props)+ return component ? namesOnInstance(graph, component) : []+}++/** The error for an `<Instance>` whose component no name, ID, or ref finds. */+function componentNotFound(props: Record<string, unknown>): Error {+ const ref = props.component ?? props.componentId ?? props.of+ if (isLayerRef(ref)) return new Error('<Instance> ref() marks no component rendered before it')+ const label = typeof ref === 'string' || typeof ref === 'number' ? String(ref) : ''+ return new Error(`<Instance> component not found: ${label}`)+}++export async function renderInstanceNode(+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ context?: RenderContext+): Promise<SceneNode> {+ const parent = graph.getNode(parentId)+ const parentLayout = parent?.layoutMode ?? 'NONE'+ const modes = variableModes(graph, tree.props.mode)+ const lookup = componentIdNamed(graph, context?.refs)+ const bound = bindProperties(graph, tree.props, 'INSTANCE', parentId, lookup, context?.properties)+ const { props, bindings } = preparePropsForRender(graph, bound.props, false, { parentId, modes })+ const component = resolveComponent(graph, props, context?.refs)+ if (!component) throw componentNotFound(props)+ const overrides: Partial<SceneNode> = {+ ...propsToOverrides(props, false, parentLayout),+ ...layerMetadata(modes, bound.references)+ }+ // Instances inherit their container layout, but explicitly authored dimensions+ // must also replace the inherited sizing mode on that axis.+ const layout = overrides.layoutMode ?? component.layoutMode+ if (layout !== 'NONE') {+ const axes =+ layout === 'HORIZONTAL'+ ? (['primaryAxisSizing', 'counterAxisSizing'] as const)+ : (['counterAxisSizing', 'primaryAxisSizing'] as const)+ for (const [dimension, field] of [+ ['w', axes[0]],+ ['h', axes[1]]+ ] as const) {+ const value = props[dimension]+ if (typeof value === 'number') overrides[field] = 'FIXED'+ else if (value === 'hug' || value === 'fill') overrides[field] = 'HUG'+ }+ }+ const instance = graph.createInstance(component.id, parentId, overrides)+ if (!instance)+ throw new Error(`<Instance> of ${component.name} would put the component inside itself`)+ try {+ for (const [field, value] of Object.entries(overrides)) {+ setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field, value)+ }+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })+ applyBindings(graph, instance.id, bindings)+ applyInstanceOverrides(graph, instance, tree.props.overrides, context?.warnings ?? [])+ assignNamedProperties(graph, instance, props, lookup)+ assignComponentProperties(graph, instance, props.properties, lookup)+ if (props.exposed === true) exposeInstance(graph, instance)+ return instance+ } catch (error) {+ graph.deleteNode(instance.id)+ throw error+ }+}++/**+ * The fields an instance may override in its layers, as Figma allows; where a layer sits, its+ * shape, its place in the tree, and its component follow the component.+ */+const OVERRIDE_FIELDS = new Set<string>(INSTANCE_OVERRIDE_FIELDS)++/** What kind of value a field holds, as an override's value must match it. */+function kind(value: unknown): string {+ if (Array.isArray(value)) return 'a list'+ if (value === null) return 'null'+ return typeof value === 'object' ? 'an object' : `a ${typeof value}`+}++/**+ * Whether `value` can take the place of `current`: the same kind, or either is empty. A list's+ * entries can't be empty, and are of the kind the field's own entries are.+ */+function sameKind(current: unknown, value: unknown): boolean {+ if (current === undefined || current === null || value === null) return true+ if (kind(current) !== kind(value)) return false+ if (!Array.isArray(value) || !Array.isArray(current)) return true+ const entry: unknown = current[0]+ return value.every(+ (item: unknown) =>+ item !== null && item !== undefined && (entry === undefined || kind(entry) === kind(item))+ )+}++/**+ * Apply child overrides to a freshly created instance. Keys are+ * `childName:prop` (e.g. 'label:text', 'icon:fills'); the child is resolved by+ * name among the instance's descendants, before any override renames one, and the+ * value is applied to both the child node and the instance's overrides record so+ * component sync keeps it. A name several descendants share is an error; a key that names no+ * layer, a field an instance cannot override, or a value of another kind is skipped with a warning.+ */+function applyInstanceOverrides(+ graph: SceneGraph,+ instance: SceneNode,+ overridesProp: unknown,+ warnings: string[]+): void {+ if (!overridesProp || typeof overridesProp !== 'object') return+ if (Array.isArray(overridesProp)) return+ const entries = Object.entries(overridesProp)+ if (entries.length === 0) return++ const descendants: SceneNode[] = []+ const walk = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return+ descendants.push(node)+ for (const cid of node.childIds) walk(cid)+ }+ for (const cid of instance.childIds) walk(cid)++ const skip = (key: string, reason: string) => {+ warnings.push(`overrides key "${key}" ${reason}; it is ignored.`)+ return []+ }+ // A layer's name may hold a colon; a field's never does.+ const targets = entries.flatMap(([key, value]) => {+ const sep = key.lastIndexOf(':')+ if (sep === -1) return skip(key, 'is not layer:field')+ const childName = key.slice(0, sep)+ const prop = key.slice(sep + 1)+ if (!OVERRIDE_FIELDS.has(prop))+ return skip(key, `names ${prop}, which an instance cannot override`)+ const matches = descendants.filter((n) => n.name === childName)+ if (matches.length > 1)+ throw new Error(+ `overrides key ${key} is ambiguous: ${matches.length} layers are named ${childName}`+ )+ const child = matches.at(0)+ if (!child) return skip(key, `names no layer "${childName}" in the instance`)+ const current: unknown = child[prop as keyof SceneNode]+ if (!sameKind(current, value))+ return skip(+ key,+ kind(current) === kind(value)+ ? 'holds an empty entry or one of another kind'+ : `takes ${kind(current)}, not ${kind(value)}`+ )+ return [{ child, prop, value }]+ })+ for (const { child, prop, value } of targets) {+ graph.updateNode(child.id, { [prop]: value })+ setInstanceOverride(instance.instanceOverrides, instance.id, child.id, prop, value)+ }+ if (targets.length > 0) {+ graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })+ }+}++/** The component a swap property's default names, by ID or name, as `<Instance of>` finds it. */+export function componentIdNamed(graph: SceneGraph, refs?: LayerRefs): ComponentLookup {+ return (reference) => resolveComponent(graph, { of: reference }, refs)?.id+}diff --git a/packages/design-jsx/src/components/properties.ts b/packages/design-jsx/src/components/properties.tsnew file mode 100644index 000000000..69145356d--- /dev/null+++ b/packages/design-jsx/src/components/properties.ts@@ -0,0 +1,265 @@+import { compact, groupBy, isEqual, pick, uniq } from 'es-toolkit'++import type {+ ComponentPropertyDefinition,+ ComponentPropertyReference,+ SceneGraph,+ SceneNode+} from '@open-pencil/scene-graph'+import {+ componentPropertyDefinitions,+ createComponentPropertyId,+ exposableInstances,+ instanceExposureIssue+} from '@open-pencil/scene-graph/components'++import { isLayerRef, type LayerRef } from '../refs'++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: by name, ID,+ * or the `ref()` that marks it.+ */+export interface ComponentProperty<+ T extends string | boolean | LayerRef = string | boolean | LayerRef+> {+ 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 | LayerRef>(+ 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+ }+>++/** 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+ }+ node = node.parentId ? graph.getNode(node.parentId) : undefined+ }+ 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,+ added: string[] | undefined+): 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()+ added?.push(id)+ 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, and `added` takes the+ * IDs of the properties it creates.+ */+export function bindProperties(+ graph: SceneGraph,+ source: Record<string, unknown>,+ type: SceneNode['type'],+ parentId: string,+ componentId: ComponentLookup,+ added?: string[]+): 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'+ const swapRef = bound.type === 'INSTANCE_SWAP' && isLayerRef(value.defaultValue)+ if (!swapRef && typeof value.defaultValue !== expected)+ throw new Error(`Component property ${value.name} in ${key} takes a ${expected} default`)+ let defaultValue = isLayerRef(value.defaultValue) ? '' : String(value.defaultValue)+ if (bound.type === 'INSTANCE_SWAP') {+ const id = componentId(isLayerRef(value.defaultValue) ? value.defaultValue : defaultValue)+ if (!id) throw new Error(`<Instance> component not found: ${defaultValue || 'ref()'}`)+ defaultValue = id+ }+ const owner = propertyOwner(graph, parentId)+ const propertyId = ensureDefinition(graph, owner, value.name, bound.type, defaultValue, added)+ references.push({ propertyId, field: bound.field })+ props[key] = value.defaultValue+ }+ return { props, references }+}++/** Match the nearest component scope, including definitions inherited from its set. */+export function componentPropertyScope(+ graph: SceneGraph,+ parentId: string+): readonly ComponentPropertyDefinition[] | undefined {+ let parent = graph.getNode(parentId)+ while (parent) {+ if (parent.type === 'INSTANCE') return componentPropertyDefinitions(graph, parent)+ if (parent.type === 'COMPONENT_SET') return parent.componentPropertyDefinitions+ if (parent.type === 'COMPONENT') {+ const set = parent.parentId ? graph.getNode(parent.parentId) : undefined+ return set?.type === 'COMPONENT_SET'+ ? [...set.componentPropertyDefinitions, ...parent.componentPropertyDefinitions]+ : parent.componentPropertyDefinitions+ }+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined+ }+ return undefined+}++/** Whether a variant has every value `wanted` names, by variant property. */+export function hasVariantValues(variant: SceneNode, wanted: Record<string, string>): boolean {+ return isEqual(pick(variant.componentPropertyValues, Object.keys(wanted)), wanted)+}++/** The ID of the component a name, ID, or `ref()` names, as `<Instance of>` finds it. */+export type ComponentLookup = (reference: string | LayerRef) => string | undefined++/** 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> = {}+ for (const entry of entries) {+ const [key = '', ...rest] = entry.split('=')+ const property = key.trim()+ const value = rest.join('=').trim()+ if (property && value) values[property] = value+ }+ return values+}++/** Variant properties a component set takes from its variants' names, such as `State=On`. */+export function inferComponentSetProperties(graph: SceneGraph, componentSetId: string): void {+ const componentSet = graph.getNode(componentSetId)+ if (componentSet?.type !== 'COMPONENT_SET') return+ const existingDefinitions = componentSet.componentPropertyDefinitions++ const variants = graph+ .getChildren(componentSetId)+ .filter((node) => node.type === 'COMPONENT')+ .map((variant) => ({ id: variant.id, values: parseVariantValues(variant.name) }))+ const defined = new Set(+ existingDefinitions+ .filter((definition) => definition.type === 'VARIANT')+ .map((definition) => definition.name)+ )+ // Each property's values in the order the variants first use them.+ const options = groupBy(+ variants.flatMap(({ values }) => Object.entries(values)),+ ([name]) => name+ )+ for (const name of Object.keys(options)) {+ const other = existingDefinitions.find(+ (definition) => definition.name === name && definition.type !== 'VARIANT'+ )+ if (other)+ throw new Error(+ `Variant property ${name} of ${componentSet.name} has the name of its ${other.type} property`+ )+ }+ const definitions: ComponentPropertyDefinition[] = Object.entries(options)+ .filter(([name]) => !defined.has(name))+ .map(([name, entries]) => {+ const variantOptions = uniq(entries.map(([, value]) => value))+ return {+ id: createComponentPropertyId(),+ name,+ type: 'VARIANT',+ defaultValue: variantOptions[0] ?? '',+ variantOptions+ }+ })++ for (const { id, values } of variants) graph.updateNode(id, { componentPropertyValues: values })+ graph.updateNode(componentSetId, {+ componentPropertyDefinitions: [...existingDefinitions, ...definitions]+ })+}diff --git a/packages/design-jsx/src/definitions.ts b/packages/design-jsx/src/definitions.tsindex a52a6e36b..f0a752ba4 100644--- a/packages/design-jsx/src/definitions.ts+++ b/packages/design-jsx/src/definitions.ts@@ -195,6 +195,7 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['properties','of','exposed',+ 'overrides','mode',// A Reka UI root's behaviour, by its own property names'modelValue',diff --git a/packages/design-jsx/src/components.ts b/packages/design-jsx/src/elements/functions.tssimilarity index 99%rename from packages/design-jsx/src/components.tsrename to packages/design-jsx/src/elements/functions.tsindex e2c364cbd..c81e69f83 100644--- a/packages/design-jsx/src/components.ts+++ b/packages/design-jsx/src/elements/functions.ts@@ -9,7 +9,7 @@ import {type SpanProps,type TextProps,type TreeNode-} from './tree'+} from '../tree'type Child = TreeNode | stringdiff --git a/packages/design-jsx/src/elements.ts b/packages/design-jsx/src/elements/index.tssimilarity index 94%rename from packages/design-jsx/src/elements.tsrename to packages/design-jsx/src/elements/index.tsindex 2b5586c51..23e3a080c 100644--- a/packages/design-jsx/src/elements.ts+++ b/packages/design-jsx/src/elements/index.ts@@ -1,15 +1,17 @@-import { difference } from 'es-toolkit/array'+import { difference } from 'es-toolkit'import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { REKA_ELEMENTS, rekaRole } from './behaviours'-import { connectorBindingTarget, renderConnectorNode } from './connectors'+import { REKA_ELEMENTS, rekaRole } from '../behaviours'import {DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,DESIGN_JSX_SPAN_PROPERTY_NAMES,DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES-} from './definitions'+} from '../definitions'+import { connectorBindingTarget, renderConnectorNode } from '../figjam/connectors'+import { renderShapeNode } from '../figjam/shapes-with-text'+import { renderStickyNode } from '../figjam/stickies'import {connectorPropsSchema,ownLayerPropsSchema,@@ -18,10 +20,8 @@ import {shapePropsSchema,stickyPropsSchema,type ElementPropsSchema-} from './schema'-import { renderShapeNode } from './shapes-with-text'-import { renderStickyNode } from './stickies'-import type { TreeNode } from './tree'+} from '../schema'+import type { TreeNode } from '../tree'/** How an element that draws a layer of its own, such as a sticky note, renders it. */export interface OwnLayerRenderer {@@ -78,8 +78,7 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [runtimeType: 'frame',description: 'A frame or auto-layout container.',nodeType: 'FRAME',- // A set and an instance read back as frames: JSX cannot name what they come from.- writes: ['FRAME', 'COMPONENT_SET', 'INSTANCE']+ writes: ['FRAME']},{name: 'Text',@@ -167,9 +166,15 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [name: 'ComponentSet',runtimeType: 'component-set',description: 'A component variant set.',- nodeType: 'COMPONENT_SET'+ nodeType: 'COMPONENT_SET',+ writes: ['COMPONENT_SET']+ },+ {+ name: 'Instance',+ runtimeType: 'instance',+ description: 'An instance of a component.',+ writes: ['INSTANCE']},- { name: 'Instance', runtimeType: 'instance', description: 'An instance of a component.' },{ name: 'View', runtimeType: 'frame', description: 'An alias for Frame.', nodeType: 'FRAME' },{name: 'Rect',diff --git a/packages/design-jsx/src/enums.ts b/packages/design-jsx/src/enums.tsindex f5fce1ad7..0aedf48cf 100644--- a/packages/design-jsx/src/enums.ts+++ b/packages/design-jsx/src/enums.ts@@ -1,3 +1,4 @@+import { invert } from 'es-toolkit'import * as v from 'valibot'import type {@@ -44,16 +45,17 @@ export function jsxEnum<T extends string>(spellings: Readonly<Record<T, string>>,aliases: Readonly<Record<string, T>> = {}): JSXEnum<T> {- const entries = Object.entries(spellings) as [T, string][]- const byName = new Map<string, T>(- [...entries.map(([value, name]): [string, T] => [name, value]), ...Object.entries(aliases)].map(- ([name, value]): [string, T] => [name.toLowerCase(), value]- )+ // Every spelling, the written ones and the aliases, read in any case.+ const byName = new Map(+ Object.entries({ ...invert(spellings), ...aliases }).map(([name, value]) => [+ name.toLowerCase(),+ value+ ]))return {parse: (value) => (typeof value === 'string' ? byName.get(value.toLowerCase()) : undefined),print: (value) => spellings[value],- names: [...entries.map(([, name]) => name), ...Object.keys(aliases)]+ names: [...Object.values<string>(spellings), ...Object.keys(aliases)]}}diff --git a/packages/design-jsx/src/export/components/instances.ts b/packages/design-jsx/src/export/components/instances.tsnew file mode 100644index 000000000..c4ca71e7e--- /dev/null+++ b/packages/design-jsx/src/export/components/instances.ts@@ -0,0 +1,197 @@+import { DESIGN_JSX_SUPPORTED_PROPERTIES } from '#design-jsx/definitions'+import { countBy, isEmptyObject, isEqual } from 'es-toolkit'++import { es } from '@open-pencil/emit'+import type {+ ComponentPropertyDefinition,+ ComponentPropertyReference,+ SceneGraph,+ SceneNode+} from '@open-pencil/scene-graph'+import { componentPropertyDefinitions } from '@open-pencil/scene-graph/components'+import { INSTANCE_OVERRIDE_FIELDS, instanceMainComponent } from '@open-pencil/scene-graph/instances'++import { collectProps, positionProps } from '../props'+import { plainValue, type JSXProp, type JSXValue } from '../value'+import type { VariableExport } from '../variables'+import type { ComponentReference } from './references'++/**+ * The fields `overrides` writes for a layer inside an instance, as it sets them. Bindings and+ * pinned modes name variables by ID, which another graph does not have.+ */+const WRITTEN_OVERRIDE_FIELDS = new Set<string>(+ INSTANCE_OVERRIDE_FIELDS.filter(+ (field) => field !== 'boundVariables' && field !== 'variableModes'+ )+)++/** The fields an assignment to the property a layer binds changes, which the assignment writes. */+const ASSIGNED_FIELDS: Record<ComponentPropertyReference['field'], readonly string[]> = {+ TEXT: ['text', 'styleRuns', 'textParagraphs'],+ VISIBLE: ['visible'],+ INSTANCE_SWAP: ['componentId', 'sourceComponentId', 'name'],+ SLOT_CONTENT: []+}++/** A name an instance can take as a prop: a JSX name design JSX gives no meaning of its own. */+function isPropName(name: string): boolean {+ return es.isIdentifierName(name) && !DESIGN_JSX_SUPPORTED_PROPERTIES.has(name)+}++function descendants(graph: SceneGraph, node: SceneNode): SceneNode[] {+ return graph.getChildren(node.id).flatMap((child) => [child, ...descendants(graph, child)])+}++/**+ * What the instance's layers override, as `overrides` sets it: `{ 'Label:fills': [...] }`,+ * keyed by the name each layer has in a new instance. An override equal to the component's value+ * is written too, so the layer keeps it when the component changes. A renamed layer is renamed+ * last, so the keys before it still find it. Null when an override cannot be written that way: one on a+ * nested instance, a binding, or a layer whose name another layer of the instance shares.+ */+function layerOverrides(graph: SceneGraph, instance: SceneNode): Record<string, JSXValue> | null {+ const layers = descendants(graph, instance)+ const sources = new Map(layers.map((layer) => [layer.id, graph.getNode(layer.componentId ?? '')]))+ const names = countBy(layers, (layer) => sources.get(layer.id)?.name ?? '')+ const fields: Array<[string, JSXValue]> = []+ const renames: Array<[string, JSXValue]> = []+ for (const [layerId, overridden] of instance.instanceOverrides.descendants) {+ const layer = graph.getNode(layerId)+ const source = sources.get(layerId)+ if (!layer || !sources.has(layerId)) continue+ const assigned = new Set(+ layer.componentPropertyReferences.flatMap((reference) => ASSIGNED_FIELDS[reference.field])+ )+ for (const field of overridden.keys()) {+ if (assigned.has(field)) continue+ if (layer.type === 'INSTANCE' || !source || !WRITTEN_OVERRIDE_FIELDS.has(field)) return null+ if (names[source.name] !== 1) return null+ const value: unknown = layer[field as keyof SceneNode]+ const entry: [string, JSXValue] = [`${source.name}:${field}`, plainValue(value)]+ if (field === 'name') renames.push(entry)+ else fields.push(entry)+ }+ }+ return Object.fromEntries([...fields, ...renames])+}++function assignedValue(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition,+ value: string,+ reference: ComponentReference+): JSXValue {+ if (definition.type === 'BOOLEAN') return value === 'true'+ if (definition.type !== 'INSTANCE_SWAP') return value+ const component = graph.getNode(value)+ return component ? reference.of(component) : value+}++/**+ * The values an instance gives its component's properties, by name, as `<Instance>` takes them:+ * as props where the name can be one, else in `properties`. Defaults are left out. Null when one+ * is a slot's content, which JSX cannot write, or names a property whose name another shares:+ * a render gives properties new IDs, so only the name finds one.+ */+function assignmentProps(+ graph: SceneGraph,+ instance: SceneNode,+ reference: ComponentReference+): JSXProp[] | null {+ const definitions = componentPropertyDefinitions(graph, instance)+ const names = countBy(definitions, (definition) => definition.name)+ const props: JSXProp[] = []+ const properties: Record<string, JSXValue> = {}+ for (const [id, value] of Object.entries(instance.componentPropertyAssignments)) {+ const definition = definitions.find((item) => item.id === id)+ if (!definition || definition.type === 'VARIANT' || value === definition.defaultValue) continue+ if (definition.type === 'SLOT' || names[definition.name] !== 1) return null+ const written = assignedValue(graph, definition, value, reference)+ if (isPropName(definition.name)) props.push([definition.name, written])+ else properties[definition.name] = written+ }+ return Object.keys(properties).length > 0 ? [...props, ['properties', properties]] : props+}++/**+ * The component an instance names: its set and variant values, `of="Button" State="On"`, or+ * the variant itself where a value's name cannot be a prop.+ */+export function componentProps(+ graph: SceneGraph,+ component: SceneNode,+ reference: ComponentReference+): JSXProp[] {+ const set = component.parentId ? graph.getNode(component.parentId) : undefined+ const values = Object.entries(component.componentPropertyValues)+ if (set?.type !== 'COMPONENT_SET' || !values.every(([name]) => isPropName(name)))+ return [['of', reference.of(component)]]+ return [['of', reference.of(set)], ...values]+}++/**+ * A group's item as its `Item` props: the component it is of, whether it is hidden, its opacity,+ * the values it gives the component's properties, and what its layers override. The group places+ * the item, so its other layer props are not written. Null when some of that cannot be written,+ * as for `instanceProps`.+ */+export function itemProps(+ graph: SceneGraph,+ item: SceneNode,+ component: SceneNode,+ reference: ComponentReference+): JSXProp[] | null {+ const assignments = assignmentProps(graph, item, reference)+ const overrides = layerOverrides(graph, item)+ if (!assignments || !overrides) return null+ return [+ ...componentProps(graph, component, reference),+ ...(item.visible ? [] : [['visible', false] as JSXProp]),+ ...(item.opacity < 1 ? [['opacity', item.opacity] as JSXProp] : []),+ ...assignments,+ ...(isEmptyObject(overrides) ? [] : [['overrides', overrides] as JSXProp])+ ]+}++/**+ * An instance as `<Instance>` props: the component it is of, its own layer's props where they+ * differ from the component's, the values it gives the component's properties, and what its+ * layers override. Its layers are the component's to draw, so they are not written. Null when+ * some of that cannot be written, so the instance is written as the frame it draws.+ */+export function instanceProps(+ node: SceneNode,+ graph: SceneGraph,+ variables: VariableExport,+ reference: ComponentReference+): JSXProp[] | null {+ const component = instanceMainComponent(graph, node)+ if (!component) return null+ const assignments = assignmentProps(graph, node, reference)+ const overrides = layerOverrides(graph, node)+ if (!assignments || !overrides) return null++ const own = collectProps(node, graph, variables, reference)+ const inherited = collectProps(component, graph, variables, reference)+ const placement = new Set(+ [...positionProps(node, graph), ...positionProps(component, graph)].map(([name]) => name)+ )+ placement.add('name')+ // A prop the component sets and the instance leaves at its default cannot be written.+ if (inherited.some(([name]) => !placement.has(name) && !own.some(([key]) => key === name)))+ return null+ const differs = own.filter(+ ([name, value]) =>+ placement.has(name) ||+ !inherited.some(([key, inheritedValue]) => key === name && isEqual(value, inheritedValue))+ )+ const bound = differs.find(([name]) => name === 'of')+ return [+ ...differs.filter(([name]) => name === 'name'),+ ...(bound ? [bound] : componentProps(graph, component, reference)),+ ...differs.filter(([name]) => name !== 'name' && name !== 'of'),+ ...assignments,+ ...(Object.keys(overrides).length > 0 ? [['overrides', overrides] as JSXProp] : [])+ ]+}diff --git a/packages/design-jsx/src/export/components/properties.ts b/packages/design-jsx/src/export/components/properties.tsnew file mode 100644index 000000000..685d5910a--- /dev/null+++ b/packages/design-jsx/src/export/components/properties.ts@@ -0,0 +1,87 @@+import type {+ ComponentPropertyDefinition,+ ComponentPropertyReference,+ SceneGraph,+ SceneNode+} from '@open-pencil/scene-graph'+import { readBehaviour } from '@open-pencil/scene-graph/behaviours'++import { helperCall, type JSXProp, type JSXValue } from '../value'+import type { ComponentReference } from './references'++/**+ * The component whose properties a layer's fields bind, as `property()` finds it: the set, for+ * a variant. None for a layer outside a main component or inside an instance, whose bindings+ * are its component's.+ */+function propertyOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {+ let parent = node.parentId ? graph.getNode(node.parentId) : undefined+ while (parent) {+ if (parent.type === 'INSTANCE') return undefined+ if (parent.type === 'COMPONENT_SET') return parent+ if (parent.type === 'COMPONENT') {+ const set = parent.parentId ? graph.getNode(parent.parentId) : undefined+ return set?.type === 'COMPONENT_SET' ? set : parent+ }+ parent = parent.parentId ? graph.getNode(parent.parentId) : undefined+ }+ return undefined+}++/** The prop a reference binds, as `property()` is written in it. */+const BOUND_PROPS: Partial<Record<ComponentPropertyReference['field'], string>> = {+ TEXT: 'text',+ VISIBLE: 'visible',+ INSTANCE_SWAP: 'of'+}++function defaultValue(+ graph: SceneGraph,+ definition: ComponentPropertyDefinition,+ reference: ComponentReference+): JSXValue {+ if (definition.type === 'BOOLEAN') return definition.defaultValue === 'true'+ if (definition.type !== 'INSTANCE_SWAP') return definition.defaultValue+ const component = graph.getNode(definition.defaultValue)+ return component ? reference.of(component) : definition.defaultValue+}++/** `props` with each field bound to a component property written as the binding instead. */+export function withPropertyBindings(+ props: JSXProp[],+ node: SceneNode,+ graph: SceneGraph,+ reference: ComponentReference+): JSXProp[] {+ const bound = propertyBindingProps(node, graph, reference)+ return [...props.filter(([name]) => !bound.some(([key]) => key === name)), ...bound]+}++/**+ * The fields of a main component's layer bound to its properties, as `property()` calls:+ * `text={property('Label', 'Hi')}`. A Reka text field's text and a part's slot are left to+ * the Reka elements, which bind them.+ */+export function propertyBindingProps(+ node: SceneNode,+ graph: SceneGraph,+ reference: ComponentReference+): JSXProp[] {+ if (node.componentPropertyReferences.length === 0) return []+ const owner = propertyOwner(graph, node)+ if (!owner) return []+ const rekaTexts = new Set(+ Object.values(readBehaviour(owner)?.texts ?? {}).map((binding) => binding.propertyId)+ )+ const props: JSXProp[] = []+ for (const { propertyId, field } of node.componentPropertyReferences) {+ const prop = BOUND_PROPS[field]+ const definition = owner.componentPropertyDefinitions.find((item) => item.id === propertyId)+ if (!prop || !definition || rekaTexts.has(propertyId)) continue+ props.push([+ prop,+ helperCall('property', definition.name, defaultValue(graph, definition, reference))+ ])+ }+ return props+}diff --git a/packages/design-jsx/src/export/components/references.ts b/packages/design-jsx/src/export/components/references.tsnew file mode 100644index 000000000..e571d4db9--- /dev/null+++ b/packages/design-jsx/src/export/components/references.ts@@ -0,0 +1,64 @@+import { refName } from '#design-jsx/refs'+import { countBy } from 'es-toolkit'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { Reference, type JSXValue } from '../value'++/**+ * How an export names a component, as `of` and swap properties take it: by the `ref()` the+ * export declares for it, by its name where no other component has it, else by its ID.+ */+export interface ComponentReference {+ of: (component: SceneNode) => JSXValue+}++function isComponent(node: SceneNode): boolean {+ return node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'+}++/**+ * Names `of` and swap properties resolve in this graph and in another that has the same+ * components.+ * A component the export writes is named by the ref `refs` gives it, so its instances find the+ * copy rendered with them, not a component the target already has by that name; `onOf` hears+ * of each component named. Otherwise a name two components share is written as the+ * component's ID, which only this graph has. The graph is read once, on the first reference.+ */+export function componentReferences(+ graph: SceneGraph,+ refs: ReadonlyMap<string, string | null> = new Map(),+ onOf?: (component: SceneNode) => void+): ComponentReference {+ let names: Record<string, number> | undefined+ const name = (component: SceneNode) => {+ names ??= countBy([...graph.getAllNodes()].filter(isComponent), (node) => node.name)+ return component.name && names[component.name] === 1 ? component.name : component.id+ }+ return {+ of: (component) => {+ onOf?.(component)+ const ref = refs.get(component.id)+ return ref ? new Reference(ref) : name(component)+ }+ }+}++/**+ * The refs an export declares: `connectorRefs`, and one for each component in `named` that it+ * writes, named apart from the names in `taken`. A layer both need takes one ref.+ */+export function componentRefs(+ graph: SceneGraph,+ named: Iterable<string>,+ connectorRefs: ReadonlyMap<string, string | null>,+ taken: Set<string>+): ReadonlyMap<string, string | null> {+ const refs = new Map(connectorRefs)+ for (const id of named) {+ const component = graph.getNode(id)+ if (component && !refs.get(id) && isComponent(component))+ refs.set(id, refName(component.name, taken))+ }+ return refs+}diff --git a/packages/design-jsx/src/export/decoration.ts b/packages/design-jsx/src/export/decoration.tsindex 28de3a021..f76acc781 100644--- a/packages/design-jsx/src/export/decoration.ts+++ b/packages/design-jsx/src/export/decoration.ts@@ -2,7 +2,7 @@ import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graphimport { TEXT_DECORATION_STYLE } from '../enums'import { AUTO, CURRENT_COLOR } from '../overrides/text'-import { paintPropValue } from './paint'+import { paintPropValue } from './paints'import type { JSXProp } from './value'type DecorationStyle = Pick<diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex e56b0aae3..9d658d98d 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -1,25 +1,32 @@-import { compact } from 'es-toolkit/array'+import { compact } from 'es-toolkit'import { jsx, type SyntaxNode } from '@open-pencil/emit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { isGeneratedFrame, type GeneratedFrameType } from '@open-pencil/scene-graph/generated'+import { rekaExport, type RekaExport } from '../behaviours/export'+import { elementTag } from '../elements'import {connectorExportScope,connectorLabel,connectorProps,- connectorRefDeclarations,type ConnectorExportScope-} from '../connectors'-import { elementTag } from '../elements'-import { shapeWithTextLabelText, shapeWithTextProps } from '../shapes-with-text'-import { stickyBody, stickyProps } from '../stickies'-import { rekaExport, type RekaExport } from './behaviours'+} from '../figjam/connectors'+import { shapeWithTextLabelText, shapeWithTextProps } from '../figjam/shapes-with-text'+import { stickyBody, stickyProps } from '../figjam/stickies'+import { refDeclarations } from '../refs'+import { instanceProps } from './components/instances'+import { propertyBindingProps, withPropertyBindings } from './components/properties'+import {+ componentReferences,+ componentRefs,+ type ComponentReference+} from './components/references'import { iconProps } from './icons'import { collectProps, positionProps, presenceProps } from './props'import { textChildren } from './text'import { plainValue, propAttribute, Reference, type JSXProp } from './value'-import { variableExport, type VariableExport } from './variables'+import { variableExport, variableReferences, type VariableExport } from './variables'/** Design JSX with the layer behind each element, in the order elements open. */export interface DesignJSXWithLayers {@@ -112,7 +119,48 @@ function ownElement(node: SceneNode,scope?: ConnectorExportScope): OwnElement | undefined {- return isGeneratedFrame(node) ? OWN_ELEMENTS[node.type](graph, node, scope) : undefined+ if (!isGeneratedFrame(node)) return undefined+ const own = OWN_ELEMENTS[node.type](graph, node, scope)+ // Its visibility can be a component property, as any layer's can.+ return { ...own, props: withPropertyBindings(own.props, node, graph, componentReferences(graph)) }+}++/**+ * The element a layer is written as. An instance whose props cannot be written is written as+ * the frame it draws.+ */+function layerTag(node: SceneNode, instance: JSXProp[] | null): string | undefined {+ return node.type === 'INSTANCE' && !instance ? 'Frame' : elementTag(node.type)+}++/** Whether a text layer's text is a component property, written as a prop rather than as children. */+function hasTextProp(props: JSXProp[]): boolean {+ return props.some(([name]) => name === 'text')+}++/**+ * A layer's props. An instance written as a frame leaves out the swap property it is bound to,+ * which only an instance takes.+ */+function frameProps(+ node: SceneNode,+ graph: SceneGraph,+ variables: VariableExport,+ reference: ComponentReference+): JSXProp[] {+ const props = collectProps(node, graph, variables, reference)+ return node.type === 'INSTANCE' ? props.filter(([name]) => name !== 'of') : props+}++/**+ * What an export writes layers with: connector ends, the refs it declares, variables, and how+ * it names components.+ */+interface ExportScope {+ connectors: ConnectorExportScope+ refs: ReadonlyMap<string, string | null>+ variables: VariableExport+ reference: ComponentReference}/** The layers an export writes, by the roots it starts from. */@@ -120,21 +168,21 @@ function nodeToJSX(node: SceneNode,graph: SceneGraph,depth: number,- scope: ConnectorExportScope,- variables: VariableExport,+ scope: ExportScope,layerIds?: Array<string | null>,outer: RekaExport = NO_REKA): SyntaxNode[] {- const reka = mergeReka(outer, rekaExport(graph, node))+ const { variables, reference } = scope+ const reka = mergeReka(outer, rekaExport(graph, node, reference))const ref = scope.refs.get(node.id)- // A layer a connector joins by a ref is marked with it, after its own props.+ // A layer a connector or `of` names by a ref is marked with it, after its own props.const withRef = (props: JSXProp[]): JSXProp[] =>ref ? [...props, ['ref', new Reference(ref)]] : props// Hidden children export with `visible={false}` rather than disappearing.const children = (childDepth: number) =>graph.getChildren(node.id)- .flatMap((child) => nodeToJSX(child, graph, childDepth, scope, variables, layerIds, reka))+ .flatMap((child) => nodeToJSX(child, graph, childDepth, scope, layerIds, reka))if (reka.flatten.has(node.id)) return children(depth)// An icon is written by name; its paths are the icon set's to draw again.const icon = iconProps(node, graph)@@ -142,10 +190,14 @@ function nodeToJSX(layerIds?.push(node.id)return [jsx.element('Icon', withRef(icon).map(propAttribute), [], depth)]}- const tag = reka.tags.get(node.id) ?? elementTag(node.type)+ const instance =+ node.type === 'INSTANCE' && !reka.tags.has(node.id)+ ? instanceProps(node, graph, variables, reference)+ : null+ const tag = reka.tags.get(node.id) ?? layerTag(node, instance)if (!tag) return []layerIds?.push(node.id)- const own = ownElement(graph, node, scope)+ const own = ownElement(graph, node, scope.connectors)if (own) {const children = own.text ? [jsx.text(own.text)] : []return [jsx.element(tag, own.props.map(propAttribute), children, depth, true)]@@ -154,15 +206,32 @@ function nodeToJSX(// An item names its component; the instance's own layers are the component's to write.if (ownProps?.some(([name]) => name === 'of'))return [jsx.element(tag, withRef(ownProps).map(propAttribute), [], depth)]- const attributes = withRef([...collectProps(node, graph, variables), ...(ownProps ?? [])]).map(- propAttribute- )- if (node.type === 'TEXT') {- const { children: content, inline } = textChildren(node, depth)- for (let count = elementCount(content); count > 0; count--) layerIds?.push(null)- return [jsx.element(tag, attributes, content, depth, inline)]- }- return [jsx.element(tag, attributes, children(depth + 1), depth)]+ // An instance's layers are its component's to draw; what it changes in them is in its props.+ if (instance) return [jsx.element(tag, withRef(instance).map(propAttribute), [], depth)]+ const props = [...frameProps(node, graph, variables, reference), ...(ownProps ?? [])]+ const attributes = withRef(props).map(propAttribute)+ const text =+ node.type === 'TEXT' ? textElement(node, tag, props, attributes, depth, layerIds) : null+ return [text ?? jsx.element(tag, attributes, children(depth + 1), depth)]+}++/**+ * A text layer with its content between its tags. A bound text's characters are the binding's,+ * so it keeps its content only for the styling: null for one with none.+ */+function textElement(+ node: SceneNode,+ tag: string,+ props: JSXProp[],+ attributes: SyntaxNode[],+ depth: number,+ layerIds?: Array<string | null>+): SyntaxNode | null {+ const { children: content, inline } = textChildren(node, depth)+ const count = elementCount(content)+ if (hasTextProp(props) && count === 0) return null+ for (let index = 0; index < count; index++) layerIds?.push(null)+ return jsx.element(tag, attributes, content, depth, inline)}/** A JSX attribute as the export prints it: its name and its source, such as `w={320}`. */@@ -186,10 +255,15 @@ export function sceneNodeAttributes(graph: SceneGraph): JSXAttributeSource[] | null {const node = graph.getNode(nodeId)- if (!node || !elementTag(node.type)) return null+ if (!node) return null+ const reference = componentReferences(graph)+ const variables = variableReferences(graph)+ const instance =+ node.type === 'INSTANCE' ? instanceProps(node, graph, variables, reference) : null+ if (!layerTag(node, instance)) return nullconst own = ownElement(graph, node)- const props = own ? own.props : collectProps(node, graph)- if (node.type === 'TEXT') props.push(['text', node.text])+ const props = instance ?? (own ? own.props : frameProps(node, graph, variables, reference))+ if (node.type === 'TEXT' && !hasTextProp(props)) props.push(['text', node.text])if (own?.text) props.push(['text', own.text])return props.map((prop) => ({name: prop[0],@@ -223,22 +297,37 @@ function contentBetween(tag: string, children: SyntaxNode[], inline: boolean): sexport function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElement | null {const node = graph.getNode(nodeId)- const tag = node && elementTag(node.type)const printed = sceneNodeAttributes(nodeId, graph)- if (!node || !tag || !printed) return null+ if (!node || !printed) return null+ const reference = componentReferences(graph)+ const isInstance =+ node.type === 'INSTANCE' &&+ instanceProps(node, graph, variableReferences(graph), reference) !== null+ const tag = node.type === 'INSTANCE' && !isInstance ? 'Frame' : elementTag(node.type)+ if (!tag) return null// A text layer's content, a connector's label, or a sticky note's body is written as its// children, not as the `text` attribute; the layers they generate are not written at all.+ // A text layer bound to a component property keeps it as the `text` attribute, and its+ // content only for the styling.const own = ownElement(graph, node)- const hasContent = node.type === 'TEXT' || own !== undefined+ const boundText =+ node.type === 'TEXT' && hasTextProp(propertyBindingProps(node, graph, reference))+ const content = node.type === 'TEXT' ? textChildren(node, 0) : undefined+ const writesContent = content !== undefined && (!boundText || elementCount(content.children) > 0)const attributes = Object.fromEntries(printed- .filter(({ name }) => !hasContent || name !== 'text')+ .filter(({ name }) => boundText || !(writesContent || own) || name !== 'text').map(({ name, source }) => [name, source]))- if (node.type === 'TEXT') {- const { children, inline } = textChildren(node, 0)- return { tag, attributes, text: contentBetween(tag, children, inline), childIds: [] }+ if (content && writesContent) {+ return {+ tag,+ attributes,+ text: contentBetween(tag, content.children, content.inline),+ childIds: []+ }}+ if (node.type === 'TEXT' || isInstance) return { tag, attributes, text: null, childIds: [] }if (own) {const children = own.text ? [jsx.text(own.text)] : []return { tag, attributes, text: contentBetween(tag, children, true), childIds: [] }@@ -274,22 +363,43 @@ export function selectionToJSXWithLayers(graph: SceneGraph,options: JSXExportOptions = {}): DesignJSXWithLayers {- const layerIds: Array<string | null> = []const declare = options.declarations ?? true- const scope = connectorExportScope(graph, nodeIds, declare)const variables = variableExport(graph, nodeIds, declare)- const roots = compact(- nodeIds.map((id) => {- const node = graph.getNode(id)- const syntax = node ? nodeToJSX(node, graph, 0, scope, variables, layerIds).at(0) : undefined- return syntax ? jsx.printJSX(syntax) : ''- })- )+ // Refs are named apart from the variables declared before them.+ const taken = new Set(variables.names)+ const connectors = connectorExportScope(graph, nodeIds, declare, taken)+ const write = (+ refs: ReadonlyMap<string, string | null>,+ onOf?: (component: SceneNode) => void+ ) => {+ const layerIds: Array<string | null> = []+ const reference = componentReferences(graph, refs, onOf)+ const scope = { connectors, refs, variables, reference }+ const roots = compact(+ nodeIds.map((id) => {+ const node = graph.getNode(id)+ const syntax = node ? nodeToJSX(node, graph, 0, scope, layerIds).at(0) : undefined+ return syntax ? jsx.printJSX(syntax) : ''+ })+ )+ return { roots, layerIds, written: new Set(layerIds) }+ }+ // A component written here that an instance names takes a ref, which needs a second pass:+ // the first finds which components those are.+ const named = new Set<string>()+ const first = write(connectors.refs, (component) => named.add(component.id))+ const refs = declare+ ? componentRefs(+ graph,+ [...named].filter((id) => first.written.has(id)),+ connectors.refs,+ taken+ )+ : connectors.refs+ const { roots, layerIds } = refs.size > connectors.refs.size ? write(refs) : firstconst elements = roots.join('\n\n')// Variables first: a ref names a layer, and nothing in a variable's definition refers to one.- const declarations = compact([variables.declarations(), connectorRefDeclarations(scope)]).join(- '\n\n'- )+ const declarations = compact([variables.declarations(), refDeclarations(refs)]).join('\n\n')if (!declarations || !elements) return { code: elements, layerIds }// Statements end with `return` and the JSX; several roots return as siblings in a fragment.const returned = roots.length > 1 ? `<>\n${elements}\n</>` : elementsdiff --git a/packages/design-jsx/src/export/paint.ts b/packages/design-jsx/src/export/paints.tssimilarity index 100%rename from packages/design-jsx/src/export/paint.tsrename to packages/design-jsx/src/export/paints.tsdiff --git a/packages/design-jsx/src/export/props.ts b/packages/design-jsx/src/export/props.tsindex 3ac86bd7a..374d0fc97 100644--- a/packages/design-jsx/src/export/props.ts+++ b/packages/design-jsx/src/export/props.ts@@ -9,6 +9,8 @@ import { vectorNetworkPaths } from '@open-pencil/scene-graph/vector-network'import { BLEND_MODE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_CASE, TEXT_DECORATION } from '../enums'import { textLengthJSX } from '../overrides/text'+import { withPropertyBindings } from './components/properties'+import { componentReferences, type ComponentReference } from './components/references'import { collectDecorationProps } from './decoration'import { collectFontSettingProps, FONT_SETTING_FIELDS } from './font'import {@@ -18,7 +20,7 @@ import {formatTracks,getNodeContext} from './helpers'-import { collectEffectProps, collectFillProps, collectStrokeProps } from './paint'+import { collectEffectProps, collectFillProps, collectStrokeProps } from './paints'import { collectStateProps } from './state'import type { JSXProp } from './value'import { variableReferences, type VariableExport } from './variables'@@ -339,12 +341,14 @@ function collectShapeNodeProps(node: SceneNode, props: JSXProp[]): void {/*** The props of `node`, in the order they are printed, with the variables it binds written as- * `variables` writes them: by default, by reference to the document's.+ * `variables` writes them: by default, by reference to the document's. Components are named as+ * `reference` names them.*/export function collectProps(node: SceneNode,graph: SceneGraph,- variables: VariableExport = variableReferences(graph)+ variables: VariableExport = variableReferences(graph),+ reference: ComponentReference = componentReferences(graph)): JSXProp[] {const props: JSXProp[] = []const ctx = getNodeContext(node, graph)@@ -364,5 +368,5 @@ export function collectProps(collectShapeNodeProps(node, props)collectStateProps(node, ctx, props, variables)- return props+ return withPropertyBindings(props, node, graph, reference)}diff --git a/packages/design-jsx/src/export/text.ts b/packages/design-jsx/src/export/text.tsindex 717abe180..4cebb6cf8 100644--- a/packages/design-jsx/src/export/text.ts+++ b/packages/design-jsx/src/export/text.ts@@ -19,7 +19,7 @@ import { AUTO, textLengthJSX } from '../overrides/text'import { SPAN_STYLE_FIELDS, type SpanStyle } from '../text-content'import { collectDecorationProps } from './decoration'import { collectFontSettingProps } from './font'-import { collectFillProps } from './paint'+import { collectFillProps } from './paints'import { fontWeightValue } from './props'import { propAttribute, type JSXProp } from './value'diff --git a/packages/design-jsx/src/export/value.ts b/packages/design-jsx/src/export/value.tsindex 120b2d566..afb43f8f3 100644--- a/packages/design-jsx/src/export/value.ts+++ b/packages/design-jsx/src/export/value.ts@@ -1,3 +1,5 @@+import { isUndefined, mapValues, omitBy } from 'es-toolkit'+import { es, jsx, type SyntaxNode } from '@open-pencil/emit'/** A paint, effect, or variable helper call inside a prop value, such as `solid("#FF0000")`. */@@ -56,11 +58,7 @@ export function plainValue(value: unknown): JSXValue {if (typeof value === 'number' && Number.isFinite(value)) return valueif (Array.isArray(value)) return value.map(plainValue)if (isRecord(value)) {- return Object.fromEntries(- Object.entries(value).flatMap(([key, item]) =>- item === undefined ? [] : [[key, plainValue(item)]]- )- )+ return mapValues(omitBy(value, isUndefined), (item) => plainValue(item))}throw new TypeError(`Cannot write a ${typeof value} value as JSX`)}diff --git a/packages/design-jsx/src/export/variables.ts b/packages/design-jsx/src/export/variables.tsindex a8f00bb8f..2227eafa7 100644--- a/packages/design-jsx/src/export/variables.ts+++ b/packages/design-jsx/src/export/variables.ts@@ -1,5 +1,4 @@-import { isEqual } from 'es-toolkit'-import { camelCase } from 'es-toolkit/string'+import { camelCase, compact, groupBy, isEqual, mapValues, sortBy } from 'es-toolkit'import { jsx } from '@open-pencil/emit'import type {@@ -10,8 +9,8 @@ import type {} from '@open-pencil/scene-graph'import { modesDefaultFirst } from '@open-pencil/scene-graph/variables'-import { layersUnder } from '../connectors'import { DESIGN_JSX_ELEMENTS } from '../elements'+import { layersUnder } from '../figjam/connectors'import { DESIGN_JSX_HELPERS } from '../helpers'import { DEFAULT_MODE_NAME, designMode, designVar, type DesignVariable } from '../variables'import { collectionNamed, resolveVariableId, variableModes } from '../variables/graph'@@ -24,6 +23,8 @@ export interface VariableExport {mode(collectionId: string, modeId: string): JSXValue/** The `defineVars` and `defineMode` statements the JSX refers to, if it declares any. */declarations(): string+ /** The names those statements declare, which other declarations must not take. */+ names: ReadonlySet<string>}/**@@ -48,6 +49,7 @@ export function variableReferences(graph: SceneGraph): VariableExport {}}return {+ names: new Set(),variable(variableId) {const variable = graph.variables.get(variableId)if (!variable) return variableId@@ -210,20 +212,15 @@ function definableVariables(graph: SceneGraph, rootIds: readonly string[]): Set</** The variables by collection, each in its collection's order, as the variables panel lists them. */function byCollectionOf(graph: SceneGraph, included: Set<string>): Map<string, Variable[]> {- const byCollection = new Map<string, Variable[]>()- for (const id of included) {- const variable = graph.variables.get(id)- if (variable)- byCollection.set(variable.collectionId, [- ...(byCollection.get(variable.collectionId) ?? []),- variable- ])- }- for (const [collectionId, variables] of byCollection) {- const listed = graph.variableCollections.get(collectionId)?.variableIds ?? []- variables.sort((a, b) => listed.indexOf(a.id) - listed.indexOf(b.id))- }- return byCollection+ const variables = compact([...included].map((id) => graph.variables.get(id)))+ const grouped = mapValues(+ groupBy(variables, (variable) => variable.collectionId),+ (members, collectionId) => {+ const listed = graph.variableCollections.get(collectionId)?.variableIds ?? []+ return sortBy(members, [(variable) => listed.indexOf(variable.id)])+ }+ )+ return new Map(Object.entries(grouped))}/** The collections in the order they are declared: after the ones their first mode aliases. */@@ -346,6 +343,7 @@ function definitionExport(graph: SceneGraph, rootIds: readonly string[]): Variab)return {+ names: new Set([...defined.values()].flatMap((entry) => [entry.name, ...entry.modes.values()])),variable,mode(collectionId, modeId) {const name = defined.get(collectionId)?.modes.get(modeId)diff --git a/packages/design-jsx/src/fields.ts b/packages/design-jsx/src/fields.tsindex 8277aa348..28b3320ad 100644--- a/packages/design-jsx/src/fields.ts+++ b/packages/design-jsx/src/fields.ts@@ -6,7 +6,7 @@ import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import type { JSXAttributeSource } from './export'import * as React from './mini-react'import { buildComponent } from './render'-import { elementOverrides } from './renderer'+import { elementOverrides } from './render/node'import { resolveToTree } from './tree'export interface JSXNodeFields {diff --git a/packages/design-jsx/src/connectors.ts b/packages/design-jsx/src/figjam/connectors.tssimilarity index 90%rename from packages/design-jsx/src/connectors.tsrename to packages/design-jsx/src/figjam/connectors.tsindex 34070cd49..44be55d66 100644--- a/packages/design-jsx/src/connectors.ts+++ b/packages/design-jsx/src/figjam/connectors.ts@@ -1,8 +1,6 @@-import { compact, countBy } from 'es-toolkit/array'-import { camelCase } from 'es-toolkit/string'+import { countBy } from 'es-toolkit'import type * as v from 'valibot'-import { es } from '@open-pencil/emit'import type { ConnectorEndpoint, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { colorToHex } from '@open-pencil/scene-graph/color'import {@@ -19,11 +17,11 @@ import {import { isGeneratedFrame } from '@open-pencil/scene-graph/generated'import type { Vector } from '@open-pencil/scene-graph/primitives'-import { CONNECTOR_LINE, CONNECTOR_SIDE, STROKE_CAP } from './enums'-import { Reference } from './export/value'-import { isLayerRef, type LayerRefs } from './refs'-import { connectorPropsSchema, readElementProps } from './schema'-import { plainTextOf, type TreeNode } from './tree'+import { CONNECTOR_LINE, CONNECTOR_SIDE, STROKE_CAP } from '../enums'+import { Reference } from '../export/value'+import { isLayerRef, refName, type LayerRefs } from '../refs'+import { connectorPropsSchema, readElementProps } from '../schema'+import { plainTextOf, type TreeNode } from '../tree'/*** `<Connector from="A" to="B">`: a FigJam connector whose ends name other layers of the same@@ -170,17 +168,6 @@ export function resolveConnectorEnds(return warnings}-/** `card1` for a layer named "Card": a name a declaration can take, numbered to stay unique. */-function refName(layerName: string, taken: Set<string>): string {- const camel = camelCase(layerName)- const base = es.isIdentifierName(camel) ? camel : 'layer'- let count = 1- while (taken.has(`${base}${count}`)) count++- const name = `${base}${count}`- taken.add(name)- return name-}-/** What an export of connectors writes: the layers under its roots, and how ends name them. */export interface ConnectorExportScope {roots: ReadonlySet<string>@@ -194,12 +181,14 @@ export interface ConnectorExportScope {/*** Plans how the connectors under `rootIds` write their ends. With `declare`, a joined layer- * whose name is not unique gets a `ref()` the export declares before its JSX.+ * whose name is not unique gets a `ref()` the export declares before its JSX, named apart from+ * the names in `taken`, which it adds to.*/export function connectorExportScope(graph: SceneGraph,rootIds: readonly string[],- declare: boolean+ declare: boolean,+ taken = new Set<string>()): ConnectorExportScope {const layers = layersUnder(graph, rootIds)const connectors = layers.filter((layer) => layer.type === 'CONNECTOR')@@ -215,7 +204,6 @@ export function connectorExportScope(layers.filter((layer) => layer.type !== 'CONNECTOR'),(layer) => layer.name)- const taken = new Set<string>()for (const layer of layers) {if (!joined.has(layer.id) || (named[layer.name] ?? 0) < 2) continuerefs.set(layer.id, declare ? refName(layer.name, taken) : null)@@ -223,13 +211,6 @@ export function connectorExportScope(return { roots: new Set(rootIds), refs }}-/** `const card1 = ref()` for each ref the scope declares, one per line. */-export function connectorRefDeclarations(scope: ConnectorExportScope): string {- return compact([...scope.refs.values()])- .map((name) => `const ${name} = ref()`)- .join('\n')-}-/** How a connector end is written: by its layer's name or ref, or as the point it is drawn at. */type EndTarget = { layer: SceneNode; ref?: string } | { point: Vector }diff --git a/packages/design-jsx/src/shapes-with-text.ts b/packages/design-jsx/src/figjam/shapes-with-text.tssimilarity index 88%rename from packages/design-jsx/src/shapes-with-text.tsrename to packages/design-jsx/src/figjam/shapes-with-text.tsindex 3bd752a2f..4864b4069 100644--- a/packages/design-jsx/src/shapes-with-text.ts+++ b/packages/design-jsx/src/figjam/shapes-with-text.ts@@ -6,12 +6,12 @@ import {shapeWithTextLabel} from '@open-pencil/scene-graph/generated'-import { SHAPE_KIND } from './enums'-import { collectFillProps, collectStrokeProps } from './export/paint'-import type { JSXProp } from './export/value'-import { figJamTextFields, figJamTextProps } from './figjam-text'-import { readElementProps, shapePropsSchema } from './schema'-import { plainTextOf, type TreeNode } from './tree'+import { SHAPE_KIND } from '../enums'+import { collectFillProps, collectStrokeProps } from '../export/paints'+import type { JSXProp } from '../export/value'+import { readElementProps, shapePropsSchema } from '../schema'+import { plainTextOf, type TreeNode } from '../tree'+import { figJamTextFields, figJamTextProps } from './text'/*** `<Shape kind="diamond" bg="#FFC943">Decide</Shape>`: a FigJam shape with text, made from thediff --git a/packages/design-jsx/src/stickies.ts b/packages/design-jsx/src/figjam/stickies.tssimilarity index 93%rename from packages/design-jsx/src/stickies.tsrename to packages/design-jsx/src/figjam/stickies.tsindex 8b5d1cccd..b5a3238c4 100644--- a/packages/design-jsx/src/stickies.ts+++ b/packages/design-jsx/src/figjam/stickies.ts@@ -9,9 +9,9 @@ import {} from '@open-pencil/scene-graph/generated'import type { Color } from '@open-pencil/scene-graph/primitives'-import { figJamTextFields, figJamTextProps } from './figjam-text'-import { readElementProps, stickyPropsSchema } from './schema'-import { plainTextOf, type TreeNode } from './tree'+import { readElementProps, stickyPropsSchema } from '../schema'+import { plainTextOf, type TreeNode } from '../tree'+import { figJamTextFields, figJamTextProps } from './text'/*** `<Sticky color="yellow" author="Ada">Body</Sticky>`: a FigJam sticky note, made from the samediff --git a/packages/design-jsx/src/figjam-text.ts b/packages/design-jsx/src/figjam/text.tssimilarity index 95%rename from packages/design-jsx/src/figjam-text.tsrename to packages/design-jsx/src/figjam/text.tsindex 8738bc7a6..98a872c2e 100644--- a/packages/design-jsx/src/figjam-text.ts+++ b/packages/design-jsx/src/figjam/text.ts@@ -8,7 +8,7 @@ import {type FigJamTypeface} from '@open-pencil/scene-graph/figjam'-import { FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE } from './enums'+import { FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE } from '../enums'/*** The fields a sticky note's body or a shape's label takes from `textSize` and `typeface`, asdiff --git a/packages/design-jsx/src/effects.ts b/packages/design-jsx/src/helpers/effects.tssimilarity index 100%rename from packages/design-jsx/src/effects.tsrename to packages/design-jsx/src/helpers/effects.tsdiff --git a/packages/design-jsx/src/helpers.ts b/packages/design-jsx/src/helpers/index.tssimilarity index 94%rename from packages/design-jsx/src/helpers.tsrename to packages/design-jsx/src/helpers/index.tsindex bacb7c07c..95f284d4e 100644--- a/packages/design-jsx/src/helpers.ts+++ b/packages/design-jsx/src/helpers/index.ts@@ -1,8 +1,9 @@-import { difference } from 'es-toolkit/array'-import { isPlainObject } from 'es-toolkit/predicate'+import { difference, isPlainObject } from 'es-toolkit'-import { property } from './component-properties'-import type { DesignJSXHelperDefinition } from './definitions'+import { property } from '../components/properties'+import type { DesignJSXHelperDefinition } from '../definitions'+import { ref } from '../refs'+import { defineMode, defineVars, designMode, designVar } from '../variables'import {backgroundBlur,dropShadow,@@ -23,8 +24,6 @@ import {type GradientPaintOptions,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>diff --git a/packages/design-jsx/src/paints.ts b/packages/design-jsx/src/helpers/paints.tssimilarity index 99%rename from packages/design-jsx/src/paints.tsrename to packages/design-jsx/src/helpers/paints.tsindex 7d34a522e..9ddddaa6c 100644--- a/packages/design-jsx/src/paints.ts+++ b/packages/design-jsx/src/helpers/paints.ts@@ -22,7 +22,7 @@ import {type ShaderPreset} from '@open-pencil/scene-graph/shaders'-import { parseScriptInput } from './schema'+import { parseScriptInput } from '../schema'export type PaintColor = string | Colorexport type PaintStop = readonly [PaintColor, number] | { color: PaintColor; position: number }diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex ff0a03bce..3522a61ea 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -18,7 +18,7 @@ export {Rect,Page,INTRINSIC_ELEMENTS-} from './components'+} from './elements/functions'export {Accordion,Button,@@ -55,7 +55,7 @@ export {resolveToTree} from './tree'-export type { RenderResult } from './renderer'+export type { RenderResult } from './render/roots'export {backgroundBlur,@@ -66,7 +66,7 @@ export {type BlurEffectOptions,type EffectColor,type ShadowEffectOptions-} from './effects'+} from './helpers/effects'export {angularGradient,@@ -81,7 +81,7 @@ export {type PaintStop,type ShaderFill,type SolidPaintOptions-} from './paints'+} from './helpers/paints'export {defineMode,@@ -95,14 +95,14 @@ export {type DesignVariable,type VariableInput} from './variables'-export { isComponentProperty, property, type ComponentProperty } from './component-properties'+export { isComponentProperty, property, type ComponentProperty } from './components/properties'export { isLayerRef, ref, type LayerRef } from './refs'export { createElement } from './mini-react'export { buildComponent, createDesignJSXRenderer, type DesignJSXRenderer } from './render'export type { ArtworkPlacement, DesignJSXServices, SVGSource } from './services'-export type { RenderOptions } from './types'+export type { RenderOptions } from './render/types'export {DESIGN_JSX_ELEMENTS,elementPropsByName,@@ -143,7 +143,7 @@ export {} from './export'export { parseJSXAttributes } from './attributes'export { jsxNodeFields, type JSXNodeFields } from './fields'-export { reconcileRenderedLayers } from './reconcile'+export { reconcileRenderedLayers } from './render/reconcile'export { JSX_REFERENCE, AUTHORING_EXAMPLES, type AuthoringExample } from './reference'export {createStreamingJSXParser,diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/overrides/index.tssimilarity index 97%rename from packages/design-jsx/src/props-overrides.tsrename to packages/design-jsx/src/overrides/index.tsindex cd3a1c2d0..f3055692d 100644--- a/packages/design-jsx/src/props-overrides.ts+++ b/packages/design-jsx/src/overrides/index.ts@@ -11,7 +11,7 @@ import {import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'import { withShaderPaints, type ShaderPaint } from '@open-pencil/scene-graph/shaders'-import { DESIGN_JSX_STYLE_KEYS, designJSXProp } from './definitions'+import { DESIGN_JSX_STYLE_KEYS, designJSXProp } from '../definitions'import {BLEND_MODE,TEXT_ALIGN,@@ -20,13 +20,13 @@ import {TEXT_CASE,TEXT_DECORATION,TEXT_DIRECTION-} from './enums'-import { applyEffectOverrides } from './overrides/effects'-import { fillFromValue, isColor, isFillValue } from './overrides/fills'-import { applyStateOverrides } from './overrides/state'-import { applyStrokeOverrides } from './overrides/strokes'-import { applyTextDetailOverrides, AUTO, textLengthProp } from './overrides/text'-import { isShaderFill } from './paints'+} from '../enums'+import { isShaderFill } from '../helpers/paints'+import { applyEffectOverrides } from './effects'+import { fillFromValue, isColor, isFillValue } from './fills'+import { applyStateOverrides } from './state'+import { applyStrokeOverrides } from './strokes'+import { applyTextDetailOverrides, AUTO, textLengthProp } from './text'const WEIGHT_MAP: Record<string, number> = {normal: 400,diff --git a/packages/design-jsx/src/scalar-bindings.ts b/packages/design-jsx/src/overrides/scalar-bindings.tssimilarity index 90%rename from packages/design-jsx/src/scalar-bindings.tsrename to packages/design-jsx/src/overrides/scalar-bindings.tsindex f1273e16d..cb941fad2 100644--- a/packages/design-jsx/src/scalar-bindings.ts+++ b/packages/design-jsx/src/overrides/scalar-bindings.ts@@ -1,8 +1,8 @@import type { SceneGraph, VariableLiteral } from '@open-pencil/scene-graph'-import { isVariable } from './variables'-import { requireVariableId } from './variables/graph'-import { scalarProps } from './variables/props'+import { isVariable } from '../variables'+import { requireVariableId } from '../variables/graph'+import { scalarProps } from '../variables/props'/** Resolve numeric props before sizing inference; retain real graph bindings afterward. */export function prepareScalarBindings(diff --git a/packages/design-jsx/src/overrides/vector.ts b/packages/design-jsx/src/overrides/vector.tsindex 91f8f8132..1a7e66800 100644--- a/packages/design-jsx/src/overrides/vector.ts+++ b/packages/design-jsx/src/overrides/vector.ts@@ -8,8 +8,8 @@ import {transformVectorNetwork} from '@open-pencil/scene-graph/vector-network'+import { normalizeStyleProps } from '.'import { designJSXProp } from '../definitions'-import { normalizeStyleProps } from '../props-overrides'import { parseScriptInput } from '../schema'const FILL_RULES = { nonzero: 'NONZERO', evenodd: 'EVENODD' } as constdiff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 27c914aeb..9b1e5ec93 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -42,11 +42,12 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.+- `Instance` resolves an existing component through `of`, `component`, or `componentId`, by name or ID. When components share a name, mark the one you mean with a `ref()` and pass it: `const card = ref()`, then `<Component name="Card" ref={card}>` and `<Instance of={card} />`. A swap property's default and values take a `ref()` the same way: `of={property('Icon', card)}`, `Icon={card}`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set; a value the set does not have is an error. A variant property named like a layer prop, such as `visible`, keeps the prop's meaning, so select such a variant by naming it: `<Instance of="visible=false" />`.- `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.+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name, ID, or `ref()` 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.+- An exported `Instance` has no children: its layers are its component's. What it changes in them is in `overrides`, keyed by the layer's name in the component and the scene field, with the field's value: `overrides={{ 'Dot:fills': [...] }}`. A name several of its layers share is an error; a key that names no layer, a field an instance cannot override, or a value of another kind is skipped with a warning. Change per-instance content through properties rather than `overrides`. An instance whose changes cannot be written that way exports as the `Frame` it draws.- 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.ts b/packages/design-jsx/src/reference/index.tssimilarity index 68%rename from packages/design-jsx/src/reference.tsrename to packages/design-jsx/src/reference/index.tsindex a7ce93b7a..608bd7ff7 100644--- a/packages/design-jsx/src/reference.ts+++ b/packages/design-jsx/src/reference/index.ts@@ -1,10 +1,10 @@-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'+import { DESIGN_JSX_SUPPORTED_PROPERTY_NAMES } from '../definitions'+import { DESIGN_JSX_ELEMENTS } from '../elements'+import { DESIGN_JSX_HELPERS } from '../helpers'+import authoring from './authoring.md?raw'+import { AUTHORING_EXAMPLES } from './examples'-export { AUTHORING_EXAMPLES, type AuthoringExample } from './reference/examples'+export { AUTHORING_EXAMPLES, type AuthoringExample } from './examples'/** Canonical scene-authoring guidance shared by runtime prompts and generated skill references. */export const JSX_REFERENCE = [diff --git a/packages/design-jsx/src/refs.ts b/packages/design-jsx/src/refs.tsindex 5ca9d429f..323882a8f 100644--- a/packages/design-jsx/src/refs.ts+++ b/packages/design-jsx/src/refs.ts@@ -1,3 +1,6 @@+import { camelCase, compact } from 'es-toolkit'++import { es } from '@open-pencil/emit'import type { SceneNode } from '@open-pencil/scene-graph'const REF_SYMBOL = Symbol.for('open-pencil.layer-ref')@@ -46,3 +49,21 @@ export class LayerRefs {return this.layers.get(ref)?.id}}++/** `card1` for a layer named "Card": a name a declaration can take, numbered to stay unique. */+export function refName(layerName: string, taken: Set<string>): string {+ const camel = camelCase(layerName)+ const base = es.isIdentifierName(camel) ? camel : 'layer'+ let count = 1+ while (taken.has(`${base}${count}`)) count+++ const name = `${base}${count}`+ taken.add(name)+ return name+}++/** `const card1 = ref()` for each ref an export declares, one per line. */+export function refDeclarations(refs: ReadonlyMap<string, string | null>): string {+ return compact([...refs.values()])+ .map((name) => `const ${name} = ref()`)+ .join('\n')+}diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render/index.tssimilarity index 73%rename from packages/design-jsx/src/render.tsrename to packages/design-jsx/src/render/index.tsindex 028e47d9d..1e0a89798 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render/index.ts@@ -1,18 +1,19 @@-import { uniq } from 'es-toolkit/array'--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 { DESIGN_JSX_HELPERS, designJSXHelpers } from './helpers'-import * as React from './mini-react'-import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'-import { elementPropWarnings } from './schema'-import type { DesignJSXServices } from './services'-import { TEXT_CONTENT_NAMES } from './text-content'-import { transformDesignJSXExpression } from './transform'-import { isTreeNode, resolveToTree, type TreeNode } from './tree'+import { uniq } from 'es-toolkit'++import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { REKA_ELEMENTS } from '../behaviours'+import { componentPropNames } from '../components/instances'+import { elementBindings, elementProps, elementSchema } from '../elements'+import { ENUM_PROPS } from '../enums'+import { DESIGN_JSX_HELPERS, designJSXHelpers } from '../helpers'+import * as React from '../mini-react'+import { elementPropWarnings } from '../schema'+import type { DesignJSXServices } from '../services'+import { TEXT_CONTENT_NAMES } from '../text-content'+import { transformDesignJSXExpression } from '../transform'+import { isTreeNode, resolveToTree, type TreeNode } from '../tree'+import { renderRoots, renderTree, type RenderResult } from './roots'import type { RenderOptions as RenderJSXOptions } from './types'/** `const Switch = { Root: 'Switch.Root', … }`: each Reka namespace as element types. */@@ -34,20 +35,25 @@ function stripHTMLComments(jsxString: string): string {return jsxString.replace(/<!--[\s\S]*?-->/g, '')}-function unsupportedPropWarnings(graph: SceneGraph, tree: TreeNode): string[] {+function unsupportedPropWarnings(+ graph: SceneGraph,+ tree: TreeNode,+ rendered: ReadonlyMap<TreeNode, SceneNode>+): string[] {const warnings: string[] = []- collectUnsupportedPropWarnings(graph, tree, warnings)+ collectUnsupportedPropWarnings(graph, tree, rendered, warnings)return warnings}function collectUnsupportedPropWarnings(graph: SceneGraph,tree: TreeNode,+ rendered: ReadonlyMap<TreeNode, SceneNode>,warnings: string[]): void {const supported = elementProps(tree.type)// An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.- const properties = componentPropNames(graph, tree.props)+ const properties = componentPropNames(graph, tree.props, rendered.get(tree))const element = TEXT_CONTENT_NAMES[tree.type] ?? tree.typeconst schema = elementSchema(tree.type)if (schema) warnings.push(...elementPropWarnings(schema, tree.props, element))@@ -68,7 +74,7 @@ function collectUnsupportedPropWarnings(if (tree.type === 'svg') returnfor (const child of tree.children) {- if (isTreeNode(child)) collectUnsupportedPropWarnings(graph, child, warnings)+ if (isTreeNode(child)) collectUnsupportedPropWarnings(graph, child, rendered, warnings)}}@@ -116,12 +122,19 @@ async function renderJSX<Artwork>(throw new Error('JSX must return a Figma element (Frame, Text, etc)')}- const results = await renderRoots(services, graph, tree, options)+ const rendered = new Map<TreeNode, SceneNode>()+ const results = await renderRoots(services, graph, tree, {+ ...options,+ onNode: (element, node) => {+ rendered.set(element, node)+ options?.onNode?.(element, node)+ }+ })// After rendering, so an instance's component set drawn in the same JSX names its variants.// A helper called in a loop reports each ignored option once.// Prop warnings come first, then the render's own, such as a connector end naming no layer.const warnings = uniq([- ...unsupportedPropWarnings(graph, tree),+ ...unsupportedPropWarnings(graph, tree, rendered),...helperWarnings,...(results[0].warnings ?? [])])@@ -140,7 +153,10 @@ export function createDesignJSXRenderer<Artwork>(services: DesignJSXServices<ArtrenderJSX(services, graph, jsxString, options),/** Render a tree built with the element functions into the graph. */renderTree: (graph: SceneGraph, tree: TreeNode, options?: RenderJSXOptions) =>- renderTree(services, graph, tree, options)+ renderTree(services, graph, tree, options),+ /** Render every root of a tree, components before the roots that use them. */+ renderRoots: (graph: SceneGraph, tree: TreeNode, options?: RenderJSXOptions) =>+ renderRoots(services, graph, tree, options)}}diff --git a/packages/design-jsx/src/render/node.ts b/packages/design-jsx/src/render/node.tsnew file mode 100644index 000000000..8f7a05c26--- /dev/null+++ b/packages/design-jsx/src/render/node.ts@@ -0,0 +1,364 @@+import { omitBy, range } from 'es-toolkit'++import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { parseColor } from '@open-pencil/scene-graph/color'++import type { RekaScope } from '../behaviours'+import { renderRekaNode } from '../behaviours/render'+import { componentIdNamed, renderInstanceNode } from '../components/instances'+import { bindProperties, inferComponentSetProperties } from '../components/properties'+import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from '../elements'+import { applySizeOverrides, propsToOverrides, shapeOverrides } from '../overrides'+import { placeVectorPaths } from '../overrides/vector'+import type { LayerRefs } from '../refs'+import { readElementProps } from '../schema'+import type { DesignJSXServices } from '../services'+import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from '../text-content'+import { isTreeNode } from '../tree'+import type { TreeNode } from '../tree'+import { isVariable } from '../variables'+import { requireVariableId, resolveForLayer, variableModes } from '../variables/graph'+import type { RenderOrder } from './order'+import { applyBindings, layerMetadata, preparePropsForRender } from './props'+import type { RenderOptions } from './types'++/**+ * An element that draws its own layer. Its props are resolved as any layer's are, so a+ * `designVar()` binds, and its layer props become fields as any layer's do; the element reads the+ * rest itself.+ */+function renderOwnLayerElement(+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ element: OwnLayerRenderer,+ context: RenderContext | undefined+): SceneNode {+ const modes = variableModes(graph, tree.props.mode)+ const nodeType = elementNodeType(tree.type) ?? 'FRAME'+ const bound = bindProperties(+ graph,+ tree.props,+ nodeType,+ parentId,+ componentIdNamed(graph),+ context?.properties+ )+ const { props, bindings } = preparePropsForRender(graph, bound.props, false, { parentId, modes })+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'+ const layer = omitBy(+ {+ ...propsToOverrides(readElementProps(element.layer, props), false, parentLayout),+ ...layerMetadata(modes, bound.references)+ },+ (value) => value === undefined+ )+ const node = element.render(graph, { ...tree, props }, parentId, layer)+ try {+ for (const [field, variableId] of Object.entries(bindings)) {+ graph.bindVariable(element.bindingTarget?.(graph, node, field) ?? node.id, field, variableId)+ }+ } catch (error) {+ graph.deleteNode(node.id)+ throw error+ }+ return node+}++function applyIconSize(+ props: Record<string, unknown>,+ overrides: Partial<SceneNode>,+ parentLayout: SceneNode['layoutMode'],+ size: number+): void {+ const { w, h } = applySizeOverrides(props, overrides, parentLayout)+ if (typeof w !== 'number') overrides.width = size+ if (typeof h !== 'number') overrides.height = size+}++async function renderIconNode<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string+): Promise<SceneNode> {+ const props = tree.props+ const iconName = props.name as string | undefined+ if (!iconName) throw new Error('<Icon> requires a name prop (e.g. name="lucide:heart")')++ const size = (props.size as number | undefined) ?? 24+ const artwork = await services.icon(iconName, size)+ if (!artwork) throw new Error(`Icon "${iconName}" not found`)+ return placeArtwork(services, graph, artwork, props, size, parentId)+}++function placeArtwork<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ artwork: Artwork,+ props: Record<string, unknown>,+ size: number,+ parentId: string+): SceneNode {+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'+ const overrides: Partial<SceneNode> = {}+ if (props.label) overrides.name = props.label as string+ applyIconSize(props, overrides, parentLayout, size)+ 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)+}++/**+ * Render an inline <svg> element into vector nodes through the same artwork path as+ * icons. The body may be string children or a `body` prop; parsed shape children work too.+ */+function renderSVGNode<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string+): SceneNode {+ const props = tree.props+ const explicitW = typeof props.w === 'number' ? props.w : 0+ const explicitH = typeof props.h === 'number' ? props.h : 0+ const size =+ explicitW > 0 || explicitH > 0+ ? Math.max(explicitW, explicitH)+ : ((props.size as number | undefined) ?? 24)+ const body =+ (typeof props.body === 'string' && props.body) ||+ tree.children.filter((c): c is string => typeof c === 'string').join('')+ const artwork = services.svg({ body, elements: tree.children.filter(isTreeNode), props }, size)+ if (!artwork) {+ throw new Error('<svg> requires SVG markup, a body prop, or supported SVG shape children')+ }+ return placeArtwork(services, graph, artwork, props, size, parentId)+}++async function renderArtworkNode<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ context: RenderContext | undefined+): Promise<SceneNode> {+ const bound = bindProperties(+ graph,+ tree.props,+ 'VECTOR',+ parentId,+ componentIdNamed(graph),+ context?.properties+ )+ const artwork = { ...tree, props: bound.props }+ const node =+ tree.type === 'icon'+ ? 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+}++export interface ElementOverrides {+ overrides: Partial<SceneNode>+ /** Variable IDs by bound field, such as `fills/0/color`. */+ bindings: Record<string, string>+}++/** The fields and variable bindings an element's props set on a `nodeType` node under `parentId`. */+export function elementOverrides(+ graph: SceneGraph,+ nodeType: NodeType,+ tree: TreeNode,+ parentId: string,+ context?: RenderContext+): ElementOverrides {+ const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'+ const isText = nodeType === 'TEXT'+ const modes = variableModes(graph, tree.props.mode)+ const bound = bindProperties(+ graph,+ tree.props,+ nodeType,+ parentId,+ componentIdNamed(graph),+ context?.properties+ )+ const layer = { parentId, modes }+ const { props, bindings } = preparePropsForRender(graph, bound.props, isText, layer)+ const overrides = {+ ...propsToOverrides(props, isText, parentLayout),+ ...shapeOverrides(nodeType, props),+ ...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, layer).props, true, 'NONE')+ Object.assign(overrides, textContentFields(tree, props, overrides, spanOverrides))+ }+ return { overrides, bindings }+}++/** What one render call shares across its elements: the layers refs marked, and their order. */+export interface RenderContext {+ refs: LayerRefs+ order: RenderOrder+ /** What the render skipped, for the author: reported with the results. */+ warnings: string[]+ /** The layers the render created, which a failed render removes. */+ created: string[]+ /** The component properties the render created, which a failed render removes. */+ properties: string[]+}++/**+ * Render `children` under `parentId`: components before the siblings that name them, then in+ * written order. Returns the rendered layers in written order.+ */+async function renderChildren(+ graph: SceneGraph,+ children: TreeNode[],+ parentId: string,+ context: RenderContext | undefined,+ render: (child: TreeNode) => Promise<SceneNode>+): Promise<SceneNode[]> {+ const start = graph.getChildren(parentId).length+ const order = context?.order.of(children) ?? range(children.length)+ const rendered: SceneNode[] = []+ for (const index of order) rendered[index] = await render(children[index])+ if (order.some((index, position) => index !== position))+ rendered.forEach((child, index) => graph.insertChildAt(child.id, parentId, start + index))+ return rendered+}++export async function renderNode<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ onNode?: RenderOptions['onNode'],+ scope?: RekaScope,+ context?: RenderContext+): Promise<SceneNode> {+ const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope, context)+ onNode?.(tree, node)+ return node+}++/**+ * The elements rendered their own way rather than as the layer their definition names, or null+ * for any other element.+ */+function renderOwnElement<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ context?: RenderContext+): Promise<SceneNode> | null {+ switch (tree.type) {+ case 'icon':+ case 'svg':+ return renderArtworkNode(services, graph, tree, parentId, context)+ case 'instance':+ return renderInstanceNode(graph, tree, parentId, context)+ default: {+ const element = elementOwnLayer(tree.type)+ return element+ ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element, context))+ : null+ }+ }+}++async function renderNodeContent<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ onNode?: RenderOptions['onNode'],+ scope?: RekaScope,+ context?: RenderContext+): Promise<SceneNode> {+ const own = renderOwnElement(services, graph, tree, parentId, context)+ if (own) {+ const node = await own+ context?.created.push(node.id)+ return node+ }+ const reka = await renderRekaNode(graph, tree, parentId, scope, {+ renderChildren: (children, childParentId, childScope) =>+ renderChildren(graph, children, childParentId, context, (child) =>+ renderNode(services, graph, child, childParentId, onNode, childScope, context)+ ),+ create: (nodeType, element, elementParentId) => {+ const { overrides, bindings } = elementOverrides(+ graph,+ nodeType,+ element,+ elementParentId,+ context+ )+ const created = graph.createNode(nodeType, elementParentId, overrides)+ context?.created.push(created.id)+ applyBindings(graph, created.id, bindings)+ placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network))+ return created+ },+ instance: async (element, elementParentId) => {+ const instance = await renderInstanceNode(graph, element, elementParentId, context)+ context?.created.push(instance.id)+ return instance+ },+ finishSet: (setId) => inferComponentSetProperties(graph, setId)+ })+ if (reka) return reka++ if (isTextContent(tree))+ throw new Error(`<${TEXT_CONTENT_NAMES[tree.type]}> must be inside <Text>`)+ const nodeType = elementNodeType(tree.type)+ if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)++ const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId, context)+ const node = graph.createNode(nodeType, parentId, overrides)+ context?.created.push(node.id)+ applyBindings(graph, node.id, bindings)+ placeVectorPaths(graph, node, tree.props, (network) => services.vectorBounds(network))++ const children = tree.children.filter(+ (child): child is TreeNode =>+ isTreeNode(child) && !(node.type === 'TEXT' && isTextContent(child))+ )+ await renderChildren(graph, children, node.id, context, (child) =>+ renderNode(services, graph, child, node.id, onNode, scope, context)+ )++ if (node.type === 'COMPONENT_SET') inferComponentSetProperties(graph, node.id)++ return node+}diff --git a/packages/design-jsx/src/render/order.ts b/packages/design-jsx/src/render/order.tsnew file mode 100644index 000000000..eba186276--- /dev/null+++ b/packages/design-jsx/src/render/order.ts@@ -0,0 +1,110 @@+import { compact, isPlainObject, isString, pull, range, uniq } from 'es-toolkit'++import { namesComponent, rekaRole } from '../behaviours'+import { isComponentProperty } from '../components/properties'+import { DESIGN_JSX_SUPPORTED_PROPERTIES } from '../definitions'+import { elementNodeType } from '../elements'+import { isLayerRef, type LayerRef } from '../refs'+import { isTreeNode, type TreeNode } from '../tree'++/** A component as an element names it: by name, or by the `ref()` that marks it. */+type ComponentKey = string | LayerRef++/**+ * The components an element and its descendants define and name. `mayName` holds the text values+ * property props give, an exposed nested instance's included: a swap takes one as a component's name, other properties as plain text,+ * and which is which is known only once the component renders.+ */+interface ComponentUse {+ defines: ComponentKey[]+ names: ComponentKey[]+ mayName: string[]+}++/** Whether an element defines a component: a component, a set, or a Reka root naming none. */+function definesComponent(node: TreeNode): boolean {+ const nodeType = elementNodeType(node.type)+ if (nodeType === 'COMPONENT' || nodeType === 'COMPONENT_SET') return true+ return rekaRole(node.type)?.role === 'root' && !namesComponent(node.props)+}++/** What the element itself defines or names, without its descendants. */+function ownUse(node: TreeNode): ComponentUse {+ const { props } = node+ if (definesComponent(node)) {+ const name = isString(props.name) ? props.name : ''+ return { defines: compact([name, isLayerRef(props.ref) && props.ref]), names: [], mayName: [] }+ }+ const of = props.component ?? props.componentId ?? props.of+ const component = isComponentProperty(of) ? of.defaultValue : of+ const assigned = [+ ...Object.entries(props)+ .filter(([key]) => !DESIGN_JSX_SUPPORTED_PROPERTIES.has(key))+ .map(([, value]) => value),+ ...(isPlainObject(props.properties) ? Object.values(props.properties) : [])+ ]+ // An exposed nested instance's values, as in `Action={{ Icon: 'Arrow' }}`.+ const nested = assigned.filter(isPlainObject).flatMap((values) => Object.values(values))+ return {+ defines: [],+ names: [+ ...(isString(component) || isLayerRef(component) ? [component] : []),+ ...assigned.filter(isLayerRef)+ ],+ mayName: [...assigned, ...nested].filter(isString)+ }+}++/** Reads each element's components once, for every level an order is asked at. */+export class RenderOrder {+ private readonly uses = new WeakMap<TreeNode, ComponentUse>()++ private use(node: TreeNode): ComponentUse {+ const known = this.uses.get(node)+ if (known) return known+ const parts = [+ ownUse(node),+ ...node.children.filter(isTreeNode).map((child) => this.use(child))+ ]+ const use = {+ defines: uniq(parts.flatMap((part) => part.defines)),+ names: uniq(parts.flatMap((part) => part.names)),+ mayName: uniq(parts.flatMap((part) => part.mayName))+ }+ this.uses.set(node, use)+ return use+ }++ /**+ * The indices of `siblings` in render order: those that define a component before those that+ * name it, otherwise as written. When none is ready, what text values may name gives way+ * first, so a text that matches a component's name never holds back a real reference; only+ * components that do name each other keep the written order.+ */+ of(siblings: readonly TreeNode[]): number[] {+ const uses = siblings.map((sibling) => this.use(sibling))+ if (uses.every((use) => use.defines.length === 0)) return range(siblings.length)++ const owners = new Map<ComponentKey, number[]>()+ uses.forEach((use, index) => {+ for (const key of use.defines) owners.set(key, [...(owners.get(key) ?? []), index])+ })+ const siblingsDefining = (keys: ComponentKey[], index: number) =>+ uniq(keys.flatMap((key) => owners.get(key) ?? [])).filter((owner) => owner !== index)+ const needs = uses.map((use, index) => siblingsDefining(use.names, index))+ const mayNeed = uses.map((use, index) => siblingsDefining(use.mayName, index))++ const order: number[] = []+ const pending = range(siblings.length)+ const rendered = (indices: number[]) => indices.every((index) => order.includes(index))+ while (pending.length > 0) {+ const next =+ pending.find((index) => rendered(needs[index]) && rendered(mayNeed[index])) ??+ pending.find((index) => rendered(needs[index])) ??+ pending[0]+ order.push(next)+ pull(pending, [next])+ }+ return order+ }+}diff --git a/packages/design-jsx/src/render/props.ts b/packages/design-jsx/src/render/props.tsnew file mode 100644index 000000000..907be5ab3--- /dev/null+++ b/packages/design-jsx/src/render/props.ts@@ -0,0 +1,89 @@+import type { SceneGraph, SceneNode, VariableModeMap } from '@open-pencil/scene-graph'++import { prepareScalarBindings } from '../overrides/scalar-bindings'+import { isVariable } from '../variables'+import {+ bindVariableProp,+ requireVariableId,+ resolveForLayer,+ type LayerContext+} from '../variables/graph'+import { paintProps } from '../variables/props'++export interface PreparedProps {+ props: Record<string, unknown>+ bindings: Record<string, string>+}++function isObjectRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+}++export function preparePropsForRender(+ graph: SceneGraph,+ source: Record<string, unknown>,+ isText: boolean,+ layer: LayerContext+): PreparedProps {+ const props = { ...source }+ const bindings: Record<string, string> = {}++ if (Array.isArray(props.fills)) {+ 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 { prop, fields } of paintProps({ text: isText })) {+ bindVariableProp(graph, props, bindings, prop, fields[0], layer)+ }++ if (isObjectRecord(props.style)) {+ const style = { ...props.style }+ for (const key of ['background', 'backgroundColor']) {+ bindVariableProp(graph, style, bindings, key, 'fills/0/color', layer)+ }+ 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, (variableId) =>+ resolveForLayer(graph, variableId, layer.parentId, layer.modes)+ )++ if (isObjectRecord(props.bind)) {+ for (const [field, value] of Object.entries(props.bind)) {+ if (isVariable(value)) {+ bindings[field] = requireVariableId(graph, value)+ } else if (typeof value === 'string') {+ bindings[field] = value+ }+ }+ }++ return { props, bindings }+}++export function applyBindings(+ graph: SceneGraph,+ nodeId: string,+ bindings: Record<string, string>+): void {+ for (const [field, variableId] of Object.entries(bindings)) {+ graph.bindVariable(nodeId, field, variableId)+ }+}++/** The modes a layer pins and the component properties its fields are bound to. */+export function layerMetadata(+ modes: VariableModeMap | undefined,+ references: SceneNode['componentPropertyReferences']+): Partial<SceneNode> {+ return {+ ...(modes && { variableModes: modes }),+ ...(references.length > 0 && { componentPropertyReferences: references })+ }+}diff --git a/packages/design-jsx/src/reconcile.ts b/packages/design-jsx/src/render/reconcile.tssimilarity index 100%rename from packages/design-jsx/src/reconcile.tsrename to packages/design-jsx/src/render/reconcile.tsdiff --git a/packages/design-jsx/src/render/roots.ts b/packages/design-jsx/src/render/roots.tsnew file mode 100644index 000000000..3ea396fdd--- /dev/null+++ b/packages/design-jsx/src/render/roots.ts@@ -0,0 +1,171 @@+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { removeComponentProperty } from '@open-pencil/scene-graph/components'++import { CONNECTOR_ELEMENT, resolveConnectorEnds } from '../figjam/connectors'+import { LayerRefs } from '../refs'+import type { DesignJSXServices } from '../services'+import { FRAGMENT, isTreeNode, type TreeNode } from '../tree'+import { applyVariableDefinitions } from '../variables/graph'+import { renderNode, type RenderContext } from './node'+import { RenderOrder } from './order'+import type { RenderOptions } from './types'++export interface RenderResult {+ id: string+ name: string+ type: NodeType+ childIds: string[]+ warnings?: string[]+}++/** `nodeId` and the layers it is in, nearest first. */+function ancestors(graph: SceneGraph, nodeId: string): SceneNode[] {+ const node = graph.getNode(nodeId)+ return node ? [node, ...ancestors(graph, node.parentId ?? '')] : []+}++/** 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]+}++/**+ * What puts back the layers a render into `parentId` creates and the property definitions+ * `property()` adds to the components around the parent. Only the render's own: another hand may+ * add to the parent or its components while it renders.+ */+function undoRender(graph: SceneGraph, parentId: string, context: RenderContext): () => void {+ const owners = ancestors(graph, parentId).filter(+ (node) => node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'+ )+ return () => {+ for (const id of context.created) graph.deleteNode(id)+ const added = new Set(context.properties)+ // As removing a property in the editor does: layers bound to it meanwhile are unbound.+ for (const { id } of owners) {+ for (const definition of graph.getNode(id)?.componentPropertyDefinitions ?? []) {+ if (added.has(definition.id)) removeComponentProperty(graph, id, definition.id)+ }+ }+ }+}++/** The render in flight on each graph, which the next waits for. */+const rendering = new WeakMap<SceneGraph, Promise<unknown>>()++/**+ * Render every root of `tree` into the parent and lay out once. Renders into one graph run one+ * after another, so a failed render puts back only what it changed.+ */+export function renderRoots<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ options: RenderOptions = {}+): Promise<RenderResult[]> {+ const previous = rendering.get(graph) ?? Promise.resolve()+ const render = previous+ .catch(() => undefined)+ .then(() => renderRootsNow(services, graph, tree, options))+ rendering.set(graph, render)+ return render+}++async function renderRootsNow<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ options: RenderOptions+): Promise<RenderResult[]> {+ 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+ const context: RenderContext = {+ refs: new LayerRefs(),+ order: new RenderOrder(),+ warnings: [],+ created: [],+ properties: []+ }+ // Variables apply by name, so a failed render's stay and the next render reuses them.+ applyVariableDefinitions(graph, tree)+ const undo = undoRender(graph, parentId, context)+ try {+ return await renderInto(services, graph, roots, parentId, options, context)+ } catch (error) {+ // A failed render leaves no layers behind, roots rendered before the failing one included.+ undo()+ throw error+ }+}++async function renderInto<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ roots: TreeNode[],+ parentId: string,+ options: RenderOptions,+ context: RenderContext+): Promise<RenderResult[]> {+ const originalChildCount = graph.getChildren(parentId).length+ // By each root's position in `roots`: a fragment may list one element twice.+ const nodes: SceneNode[] = []+ const eventsByRoot: Array<Array<[TreeNode, SceneNode]>> = []+ const connectorsByRoot: Array<Array<{ node: SceneNode; tree: TreeNode }>> = []+ const { refs } = context+ for (const index of context.order.of(roots)) {+ const events: Array<[TreeNode, SceneNode]> = []+ const connectors: Array<{ node: SceneNode; tree: TreeNode }> = []+ eventsByRoot[index] = events+ connectorsByRoot[index] = connectors+ const onNode = (element: TreeNode, node: SceneNode) => {+ if (element.type === CONNECTOR_ELEMENT) connectors.push({ node, tree: element })+ else refs.mark(element.props.ref, node)+ events.push([element, node])+ }+ const node = await renderNode(+ services,+ graph,+ roots[index],+ parentId,+ onNode,+ undefined,+ context+ )+ if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })+ if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })+ nodes[index] = node+ }++ nodes.forEach((node, index) => graph.insertChildAt(node.id, parentId, originalChildCount + index))+ for (const events of eventsByRoot) {+ for (const [element, node] of events) options.onNode?.(element, node)+ }+ const connectors = connectorsByRoot.flat()+ const rootIds = nodes.map((node) => node.id)+ const warnings = [+ ...refs.warnings,+ ...context.warnings,+ ...resolveConnectorEnds(graph, rootIds, connectors, refs)+ ]+ if (!options.deferLayout) services.layout(graph, rootIds)++ return nodes.map((node) => ({+ id: node.id,+ name: node.name,+ type: node.type,+ childIds: node.childIds,+ ...(warnings.length > 0 && { warnings })+ }))+}++/** Render `tree` and return its first root; a fragment's other roots are rendered too. */+export async function renderTree<Artwork>(+ services: DesignJSXServices<Artwork>,+ graph: SceneGraph,+ tree: TreeNode,+ options: RenderOptions = {}+): Promise<RenderResult> {+ const [first] = await renderRoots(services, graph, tree, options)+ return first+}diff --git a/packages/design-jsx/src/types.ts b/packages/design-jsx/src/render/types.tssimilarity index 90%rename from packages/design-jsx/src/types.tsrename to packages/design-jsx/src/render/types.tsindex a283b4877..22d09b1dc 100644--- a/packages/design-jsx/src/types.ts+++ b/packages/design-jsx/src/render/types.ts@@ -1,6 +1,6 @@import type { SceneNode } from '@open-pencil/scene-graph'-import type { TreeNode } from './tree'+import type { TreeNode } from '../tree'export interface RenderOptions {x?: numberdiff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsdeleted file mode 100644index 38cf3a3bb..000000000--- a/packages/design-jsx/src/renderer.ts+++ /dev/null@@ -1,598 +0,0 @@-import { omitBy } from 'es-toolkit/object'--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 { RekaScope } from './behaviours'-import { renderRekaNode } from './behaviours/render'-import {- assignComponentProperties,- assignNamedProperties,- bindProperties,- componentPropNames as namesOnInstance,- exposeInstance,- inferComponentSetProperties-} from './component-properties'-import { CONNECTOR_ELEMENT, resolveConnectorEnds } from './connectors'-import { elementNodeType, elementOwnLayer, type OwnLayerRenderer } from './elements'-import { placeVectorPaths } from './overrides/vector'-import { applySizeOverrides, propsToOverrides, shapeOverrides } from './props-overrides'-import { LayerRefs } from './refs'-import { prepareScalarBindings } from './scalar-bindings'-import { readElementProps } from './schema'-import type { DesignJSXServices } from './services'-import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-content'-import { FRAGMENT, isTreeNode } from './tree'-import type { TreeNode } from './tree'-import type { RenderOptions } from './types'-import { isVariable } from './variables'-import {- applyVariableDefinitions,- bindVariableProp,- requireVariableId,- resolveForLayer,- variableModes,- type LayerContext-} from './variables/graph'-import { paintProps } from './variables/props'--export interface RenderResult {- id: string- name: string- type: NodeType- childIds: string[]- warnings?: string[]-}--/** 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]-}--/** Render every root of `tree` into the parent and lay out once. */-export async function renderRoots<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- options: RenderOptions = {}-): Promise<RenderResult[]> {- 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 }> = []- const refs = new LayerRefs()- const onNode = (element: TreeNode, node: SceneNode) => {- if (element.type === CONNECTOR_ELEMENT) connectors.push({ node, tree: element })- else refs.mark(element.props.ref, node)- options.onNode?.(element, node)- }- for (const root of roots) {- const node = await renderNode(services, graph, root, parentId, onNode)- if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })- if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })- nodes.push(node)- }-- const rootIds = nodes.map((node) => node.id)- const warnings = [...refs.warnings, ...resolveConnectorEnds(graph, rootIds, connectors, refs)]- if (!options.deferLayout) services.layout(graph, rootIds)-- return nodes.map((node) => ({- id: node.id,- name: node.name,- type: node.type,- childIds: node.childIds,- ...(warnings.length > 0 && { warnings })- }))-}--/** Render `tree` and return its first root; a fragment's other roots are rendered too. */-export async function renderTree<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- options: RenderOptions = {}-): Promise<RenderResult> {- const [first] = await renderRoots(services, graph, tree, options)- return first-}--interface PreparedProps {- props: Record<string, unknown>- bindings: Record<string, string>-}--function isObjectRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value)-}--function preparePropsForRender(- graph: SceneGraph,- source: Record<string, unknown>,- isText: boolean,- layer: LayerContext-): PreparedProps {- const props = { ...source }- const bindings: Record<string, string> = {}-- if (Array.isArray(props.fills)) {- 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 { prop, fields } of paintProps({ text: isText })) {- bindVariableProp(graph, props, bindings, prop, fields[0], layer)- }-- if (isObjectRecord(props.style)) {- const style = { ...props.style }- for (const key of ['background', 'backgroundColor']) {- bindVariableProp(graph, style, bindings, key, 'fills/0/color', layer)- }- 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, (variableId) =>- resolveForLayer(graph, variableId, layer.parentId, layer.modes)- )-- if (isObjectRecord(props.bind)) {- for (const [field, value] of Object.entries(props.bind)) {- if (isVariable(value)) {- bindings[field] = requireVariableId(graph, value)- } else if (typeof value === 'string') {- bindings[field] = value- }- }- }-- return { props, bindings }-}--/**- * An element that draws its own layer. Its props are resolved as any layer's are, so a- * `designVar()` binds, and its layer props become fields as any layer's do; the element reads the- * rest itself.- */-function renderOwnLayerElement(- graph: SceneGraph,- tree: TreeNode,- parentId: string,- element: OwnLayerRenderer-): SceneNode {- 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),- ...(modes && { variableModes: modes })- },- (value) => value === undefined- )- const node = element.render(graph, { ...tree, props }, parentId, layer)- for (const [field, variableId] of Object.entries(bindings)) {- graph.bindVariable(element.bindingTarget?.(graph, node, field) ?? node.id, field, variableId)- }- return node-}--function applyBindings(graph: SceneGraph, nodeId: string, bindings: Record<string, string>): void {- for (const [field, variableId] of Object.entries(bindings)) {- graph.bindVariable(nodeId, field, variableId)- }-}--function applyIconSize(- props: Record<string, unknown>,- overrides: Partial<SceneNode>,- parentLayout: SceneNode['layoutMode'],- size: number-): void {- const { w, h } = applySizeOverrides(props, overrides, parentLayout)- if (typeof w !== 'number') overrides.width = size- if (typeof h !== 'number') overrides.height = size-}--async function renderIconNode<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string-): Promise<SceneNode> {- const props = tree.props- const iconName = props.name as string | undefined- if (!iconName) throw new Error('<Icon> requires a name prop (e.g. name="lucide:heart")')-- const size = (props.size as number | undefined) ?? 24- const artwork = await services.icon(iconName, size)- if (!artwork) throw new Error(`Icon "${iconName}" not found`)- return placeArtwork(services, graph, artwork, props, size, parentId)-}--function placeArtwork<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- artwork: Artwork,- props: Record<string, unknown>,- size: number,- parentId: string-): SceneNode {- const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'- const overrides: Partial<SceneNode> = {}- if (props.label) overrides.name = props.label as string- applyIconSize(props, overrides, parentLayout, size)- 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)-}--/**- * Render an inline <svg> element into vector nodes through the same artwork path as- * icons. The body may be string children or a `body` prop; parsed shape children work too.- */-function renderSVGNode<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string-): SceneNode {- const props = tree.props- const explicitW = typeof props.w === 'number' ? props.w : 0- const explicitH = typeof props.h === 'number' ? props.h : 0- const size =- explicitW > 0 || explicitH > 0- ? Math.max(explicitW, explicitH)- : ((props.size as number | undefined) ?? 24)- const body =- (typeof props.body === 'string' && props.body) ||- tree.children.filter((c): c is string => typeof c === 'string').join('')- const artwork = services.svg({ body, elements: tree.children.filter(isTreeNode), props }, size)- if (!artwork) {- throw new Error('<svg> requires SVG markup, a body prop, or supported SVG shape children')- }- return placeArtwork(services, graph, artwork, props, size, parentId)-}--function findComponentByName(graph: SceneGraph, name: string): SceneNode | undefined {- for (const node of graph.getAllNodes()) {- if (node.type === 'COMPONENT' && node.name === name) return node- }- return undefined-}--function findVariantInSet(- graph: SceneGraph,- componentSet: SceneNode,- props: Record<string, unknown>-) {- const requested = Object.fromEntries(- Object.entries(props)- .filter(([key]) =>- componentSet.componentPropertyDefinitions.some(- (definition) => definition.type === 'VARIANT' && definition.name === key- )- )- .map(([key, value]) => [key, String(value)])- )- const variants = graph.getChildren(componentSet.id).filter((node) => node.type === 'COMPONENT')- return (- variants.find((variant) =>- Object.entries(requested).every(- ([key, value]) => variant.componentPropertyValues[key] === value- )- ) ?? variants[0]- )-}--/** The component or component set an element names by id or name. */-function namedComponent(graph: SceneGraph, props: Record<string, unknown>): SceneNode | undefined {- const ref = props.component ?? props.componentId ?? props.of- if (typeof ref !== 'string') return undefined-- const byId = graph.getNode(ref)- if (byId?.type === 'COMPONENT' || byId?.type === 'COMPONENT_SET') return byId-- const byName = findComponentByName(graph, ref)- if (byName) return byName-- for (const node of graph.getAllNodes()) {- if (node.type === 'COMPONENT_SET' && node.name === ref) return node- }- return undefined-}--function resolveComponent(- graph: SceneGraph,- props: Record<string, unknown>-): SceneNode | undefined {- const named = namedComponent(graph, props)- return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named-}--/**- * 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)- return component ? namesOnInstance(graph, component) : []-}--async function renderInstanceNode(- graph: SceneGraph,- tree: TreeNode,- parentId: string-): Promise<SceneNode> {- const parent = graph.getNode(parentId)- const parentLayout = parent?.layoutMode ?? 'NONE'- 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- const label = typeof ref === 'string' || typeof ref === 'number' ? String(ref) : ''- throw new Error(`<Instance> component not found: ${label}`)- }- const overrides: Partial<SceneNode> = {- ...propsToOverrides(props, false, parentLayout),- ...layerMetadata(modes, bound.references)- }- // Instances inherit their container layout, but explicitly authored dimensions- // must also replace the inherited sizing mode on that axis.- const layout = overrides.layoutMode ?? component.layoutMode- if (layout !== 'NONE') {- const axes =- layout === 'HORIZONTAL'- ? (['primaryAxisSizing', 'counterAxisSizing'] as const)- : (['counterAxisSizing', 'primaryAxisSizing'] as const)- for (const [dimension, field] of [- ['w', axes[0]],- ['h', axes[1]]- ] as const) {- const value = props[dimension]- if (typeof value === 'number') overrides[field] = 'FIXED'- else if (value === 'hug' || value === 'fill') overrides[field] = 'HUG'- }- }- const instance =- graph.createInstance(component.id, parentId, overrides) ?? graph.createNode('FRAME', parentId)- try {- for (const [field, value] of Object.entries(overrides)) {- setInstanceOverride(instance.instanceOverrides, instance.id, instance.id, field, value)- }- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })- applyBindings(graph, instance.id, bindings)- applyInstanceOverrides(graph, instance, tree.props.overrides)- 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)- throw error- }-}--/**- * Apply child overrides to a freshly created instance. Keys are- * `childName:prop` (e.g. 'label:text', 'icon:fills'); the child is resolved by- * name among the instance's descendants, and the value is applied to both the- * child node and the instance's overrides record so component sync keeps it.- */-function applyInstanceOverrides(- graph: SceneGraph,- instance: SceneNode,- overridesProp: unknown-): void {- if (!overridesProp || typeof overridesProp !== 'object') return- if (Array.isArray(overridesProp)) return- const entries = Object.entries(overridesProp)- if (entries.length === 0) return-- const descendants: SceneNode[] = []- const walk = (id: string) => {- const node = graph.getNode(id)- if (!node) return- descendants.push(node)- for (const cid of node.childIds) walk(cid)- }- walk(instance.id)-- let mutated = false- for (const [key, value] of entries) {- const sep = key.indexOf(':')- if (sep === -1) continue- const childName = key.slice(0, sep)- const prop = key.slice(sep + 1)- const child = descendants.find((n) => n.name === childName)- if (!child || !(prop in child)) continue- graph.updateNode(child.id, { [prop]: value })- setInstanceOverride(instance.instanceOverrides, instance.id, child.id, prop, value)- mutated = true- }- if (mutated) {- graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })- }-}--async function renderArtworkNode<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string-): Promise<SceneNode> {- 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, 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`. */- bindings: Record<string, string>-}--/** The fields and variable bindings an element's props set on a `nodeType` node under `parentId`. */-export function elementOverrides(- graph: SceneGraph,- nodeType: NodeType,- tree: TreeNode,- parentId: string-): ElementOverrides {- const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'- const isText = nodeType === 'TEXT'- 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),- ...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, layer).props, true, 'NONE')- Object.assign(overrides, textContentFields(tree, props, overrides, spanOverrides))- }- return { overrides, bindings }-}--async function renderNode<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string,- onNode?: RenderOptions['onNode'],- scope?: RekaScope-): Promise<SceneNode> {- const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope)- onNode?.(tree, node)- return node-}--/**- * The elements rendered their own way rather than as the layer their definition names, or null- * for any other element.- */-function renderOwnElement<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string-): Promise<SceneNode> | null {- switch (tree.type) {- case 'icon':- case 'svg':- return renderArtworkNode(services, graph, tree, parentId)- case 'instance':- return renderInstanceNode(graph, tree, parentId)- default: {- const element = elementOwnLayer(tree.type)- return element ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element)) : null- }- }-}--async function renderNodeContent<Artwork>(- services: DesignJSXServices<Artwork>,- graph: SceneGraph,- tree: TreeNode,- parentId: string,- onNode?: RenderOptions['onNode'],- scope?: RekaScope-): Promise<SceneNode> {- const own = renderOwnElement(services, graph, tree, parentId)- if (own) return own- const reka = await renderRekaNode(graph, tree, parentId, scope, {- render: (child, childParentId, childScope) =>- renderNode(services, graph, child, childParentId, onNode, childScope),- create: (nodeType, element, elementParentId) => {- const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId)- const created = graph.createNode(nodeType, elementParentId, overrides)- applyBindings(graph, created.id, bindings)- placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network))- return created- },- instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),- finishSet: (setId) => inferComponentSetProperties(graph, setId)- })- if (reka) return reka-- if (isTextContent(tree))- throw new Error(`<${TEXT_CONTENT_NAMES[tree.type]}> must be inside <Text>`)- const nodeType = elementNodeType(tree.type)- if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)-- const { overrides, bindings } = elementOverrides(graph, nodeType, tree, parentId)- const node = graph.createNode(nodeType, parentId, overrides)- applyBindings(graph, node.id, bindings)- placeVectorPaths(graph, node, tree.props, (network) => services.vectorBounds(network))-- for (const child of tree.children) {- if (typeof child === 'string' || (node.type === 'TEXT' && isTextContent(child))) continue- if (isTreeNode(child)) {- await renderNode(services, graph, child, node.id, onNode, scope)- }- }-- if (node.type === 'COMPONENT_SET') inferComponentSetProperties(graph, node.id)-- return node-}diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex b5dfdf33f..d63bebaae 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -1,4 +1,4 @@-import { mapValues } from 'es-toolkit/object'+import { mapValues } from 'es-toolkit'import * as v from 'valibot'import { tryParseColor } from '@open-pencil/scene-graph/color'diff --git a/packages/design-jsx/src/tree.ts b/packages/design-jsx/src/tree.tsindex cb1c168db..cd3b7135a 100644--- a/packages/design-jsx/src/tree.ts+++ b/packages/design-jsx/src/tree.ts@@ -1,7 +1,8 @@import type { Effect, Fill } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'-import type { ComponentProperty } from './component-properties'+import type { ComponentProperty } from './components/properties'+import type { LayerRef } from './refs'import type { DesignMode, DesignVariable } from './variables'export interface TreeNode {@@ -277,9 +278,12 @@ export type ComponentProps = BasePropsexport type InstanceProps = NodeProps & {component?: stringcomponentId?: string- of?: string | ComponentProperty<string>+ of?: string | LayerRef | ComponentProperty<string | LayerRef>/** 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>>+ properties?: Record<+ string,+ string | boolean | number | LayerRef | Record<string, string | boolean | number>+ >}diff --git a/packages/design-jsx/src/variables/graph.ts b/packages/design-jsx/src/variables/graph.tsindex 632b9f66f..b45a26488 100644--- a/packages/design-jsx/src/variables/graph.ts+++ b/packages/design-jsx/src/variables/graph.ts@@ -1,5 +1,4 @@-import { isEqual } from 'es-toolkit'-import { isPlainObject } from 'es-toolkit/predicate'+import { isEqual, isPlainObject } from 'es-toolkit'import type {SceneGraph,diff --git a/packages/design-jsx/src/variables/index.ts b/packages/design-jsx/src/variables/index.tsindex 16ce47f19..337aa0799 100644--- a/packages/design-jsx/src/variables/index.ts+++ b/packages/design-jsx/src/variables/index.ts@@ -1,4 +1,4 @@-import { isPlainObject } from 'es-toolkit/predicate'+import { isPlainObject } from 'es-toolkit'import type { Color } from '@open-pencil/scene-graph/primitives'diff --git a/packages/design-jsx/tests/builders.test.ts b/packages/design-jsx/tests/elements/functions.test.tssimilarity index 100%rename from packages/design-jsx/tests/builders.test.tsrename to packages/design-jsx/tests/elements/functions.test.tsdiff --git a/packages/design-jsx/tests/elements.test.ts b/packages/design-jsx/tests/elements/index.test.tssimilarity index 98%rename from packages/design-jsx/tests/elements.test.tsrename to packages/design-jsx/tests/elements/index.test.tsindex e11ba72e8..c321e30c4 100644--- a/packages/design-jsx/tests/elements.test.ts+++ b/packages/design-jsx/tests/elements/index.test.ts@@ -5,7 +5,7 @@ import {elementPropsByName,elementSchema,elementTag-} from '#design-jsx/elements'+} from '#design-jsx/elements/index'import { createDesignJSXRenderer } from '#design-jsx/index'import { elementPropWarnings } from '#design-jsx/schema'diff --git a/packages/design-jsx/tests/export.test.ts b/packages/design-jsx/tests/export/index.test.tssimilarity index 100%rename from packages/design-jsx/tests/export.test.tsrename to packages/design-jsx/tests/export/index.test.tsdiff --git a/packages/design-jsx/tests/layer-order.test.ts b/packages/design-jsx/tests/export/layer-order.test.tssimilarity index 100%rename from packages/design-jsx/tests/layer-order.test.tsrename to packages/design-jsx/tests/export/layer-order.test.tsdiff --git a/packages/design-jsx/tests/paints.test.ts b/packages/design-jsx/tests/helpers/paints.test.tssimilarity index 100%rename from packages/design-jsx/tests/paints.test.tsrename to packages/design-jsx/tests/helpers/paints.test.tsdiff --git a/packages/design-jsx/tests/props-overrides.test.ts b/packages/design-jsx/tests/overrides/index.test.tssimilarity index 98%rename from packages/design-jsx/tests/props-overrides.test.tsrename to packages/design-jsx/tests/overrides/index.test.tsindex c8ff36a63..6794b20ff 100644--- a/packages/design-jsx/tests/props-overrides.test.ts+++ b/packages/design-jsx/tests/overrides/index.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from 'bun:test'import { designJSXProp } from '#design-jsx/index'-import { propsToOverrides } from '#design-jsx/props-overrides'+import { propsToOverrides } from '#design-jsx/overrides/index'import { DEFAULT_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'diff --git a/packages/design-jsx/tests/reconcile.test.ts b/packages/design-jsx/tests/render/reconcile.test.tssimilarity index 100%rename from packages/design-jsx/tests/reconcile.test.tsrename to packages/design-jsx/tests/render/reconcile.test.tsdiff --git a/packages/design-jsx/tsdown.config.ts b/packages/design-jsx/tsdown.config.tsindex 7e4e3e0ba..bf923c20e 100644--- a/packages/design-jsx/tsdown.config.ts+++ b/packages/design-jsx/tsdown.config.ts@@ -7,7 +7,7 @@ export default defineConfig({'jsx-runtime': './src/jsx-runtime.ts','jsx-dev-runtime': './src/jsx-dev-runtime.ts'},- // `reference.ts` imports the authoring guide as text.+ // `reference/index.ts` imports the authoring guide as text.plugins: [raw()],platform: 'neutral',format: ['esm'],diff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.mdindex 581130f3e..06df7d5fd 100644--- a/packages/docs/development/behaviours-and-preview.md+++ b/packages/docs/development/behaviours-and-preview.md@@ -26,7 +26,7 @@ All of them write the same model.| Behaviour section | `src/components/properties/component-properties/behaviour/`, `useBehaviour` in `packages/vue` | Binds by id; Core's editor actions (`setBehaviour`, `addBehaviourText`, `addBehaviourVariant`, `addBehaviourPart`) create what is missing in one undo step. || `openpencil` scripting API | `packages/core/src/openpencil-api/` | The `openpencil` global next to `figma` in every script runner, through `compileScript`. || Tools | `packages/core/src/tools/create/behaviours.ts` | `set_behaviour`, `get_behaviour`, `create_slot`, built on the `openpencil` API. |-| Design JSX | `packages/design-jsx/src/behaviours/`, `export/behaviours.ts` | Reka-named elements (`Switch.Root`, `Switch.Thumb`) render and export components with behaviours. |+| Design JSX | `packages/design-jsx/src/behaviours/` | Reka-named elements (`Switch.Root`, `Switch.Thumb`) render and export components with behaviours. |## Preview islands@@ -56,6 +56,6 @@ Export reads the same model as preview. `behaviourArgs` gives a component set it1. Add the kind to `BEHAVIOUR_KINDS` and its contract to `BEHAVIOUR_CONTRACTS` in scene-graph; part ids follow Reka's part names.2. Map it in preview: its root and parts in `packages/vue/src/canvas/islands/controls/`, with the Reka primitives it uses.-3. Name its elements in design JSX: `REKA_ELEMENTS` in `packages/design-jsx/src/behaviours/index.ts` and the export's root table in `export/behaviours.ts`.+3. Name its elements in design JSX: `REKA_ELEMENTS` in `packages/design-jsx/src/behaviours/index.ts` and the export's root table in `behaviours/export.ts`.4. Label it in the Behaviour section (`labels.ts`) and translate the strings.5. Cover the model and spec in scene-graph tests, preview in `tests/e2e/components/behaviours.spec.ts`, and JSX in `packages/core/tests/design-jsx/behaviours.test.ts`.diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 268b615f2..4639ce707 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -44,11 +44,12 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.+- `Instance` resolves an existing component through `of`, `component`, or `componentId`, by name or ID. When components share a name, mark the one you mean with a `ref()` and pass it: `const card = ref()`, then `<Component name="Card" ref={card}>` and `<Instance of={card} />`. A swap property's default and values take a `ref()` the same way: `of={property('Icon', card)}`, `Icon={card}`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set; a value the set does not have is an error. A variant property named like a layer prop, such as `visible`, keeps the prop's meaning, so select such a variant by naming it: `<Instance of="visible=false" />`.- `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.+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name, ID, or `ref()` 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.+- An exported `Instance` has no children: its layers are its component's. What it changes in them is in `overrides`, keyed by the layer's name in the component and the scene field, with the field's value: `overrides={{ 'Dot:fills': [...] }}`. A name several of its layers share is an error; a key that names no layer, a field an instance cannot override, or a value of another kind is skipped with a warning. Change per-instance content through properties rather than `overrides`. An instance whose changes cannot be written that way exports as the `Frame` it draws.- 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.@@ -133,4 +134,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**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`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `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`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `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`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `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`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 268b615f2..4639ce707 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -44,11 +44,12 @@ This reference describes scene creation, not React DOM output. Use the `render`- `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.+- `Instance` resolves an existing component through `of`, `component`, or `componentId`, by name or ID. When components share a name, mark the one you mean with a `ref()` and pass it: `const card = ref()`, then `<Component name="Card" ref={card}>` and `<Instance of={card} />`. A swap property's default and values take a `ref()` the same way: `of={property('Icon', card)}`, `Icon={card}`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set; a value the set does not have is an error. A variant property named like a layer prop, such as `visible`, keeps the prop's meaning, so select such a variant by naming it: `<Instance of="visible=false" />`.- `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.+- Instance assignments take `true` / `false` or the native `'true'` / `'false'` for BOOLEAN properties, and a component's name, ID, or `ref()` 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.+- An exported `Instance` has no children: its layers are its component's. What it changes in them is in `overrides`, keyed by the layer's name in the component and the scene field, with the field's value: `overrides={{ 'Dot:fills': [...] }}`. A name several of its layers share is an error; a key that names no layer, a field an instance cannot override, or a value of another kind is skipped with a warning. Change per-instance content through properties rather than `overrides`. An instance whose changes cannot be written that way exports as the `Frame` it draws.- 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.@@ -133,4 +134,4 @@ Generated from the renderer metadata. This inventory lists accepted names, not a**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`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `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`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `mode`, `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`, `fontFeatures`, `fontVariations`, `lang`, `fontOpticalSizing`, `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`, `d`, `fillRule`, `paths`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `of`, `exposed`, `overrides`, `mode`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/tests/engine/render/jsx/component/properties.test.ts b/tests/engine/render/jsx/component/properties.test.tsindex 519c77573..50e118e4f 100644--- a/tests/engine/render/jsx/component/properties.test.ts+++ b/tests/engine/render/jsx/component/properties.test.ts@@ -9,7 +9,8 @@ import {Text,node,property,- type ComponentProperty+ type ComponentProperty,+ type LayerRef} from '@open-pencil/design-jsx'import { getNodeOrThrow } from '#tests/helpers/assert'@@ -20,7 +21,10 @@ test('only instances take property values; layers bind fields to property()', ()expectTypeOf<Parameters<typeof Text>[0]['properties']>().toEqualTypeOf<undefined>()expectTypeOf<Parameters<typeof Component>[0]['properties']>().toEqualTypeOf<undefined>()expectTypeOf<Parameters<typeof Instance>[0]['properties']>().toEqualTypeOf<- | Record<string, string | boolean | number | Record<string, string | boolean | number>>+ | Record<+ string,+ string | boolean | number | LayerRef | Record<string, string | boolean | number>+ >| undefined>()expectTypeOf<Parameters<typeof Text>[0]['text']>().toEqualTypeOf<@@ -288,6 +292,6 @@ test('exposing follows Figma’s rules, and unknown exposed values are errors',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'+ 'Expected a string, boolean, or ref() for component property: Title')})