AI-native design editor. Open-source Figma alternative.
feat: author connectors in design JSX (#1236)
Danila Poyarkov7b717fdf7042
diff --git a/changes/1236/added.md b/changes/1236/added.mdnew file mode 100644index 000000000..3ec3a4199--- /dev/null+++ b/changes/1236/added.md@@ -0,0 +1,2 @@+- Design JSX draws connectors with `<Connector from="A" to="B">`, joining layers of the same JSX by name or, where layers share a name, by a `ref()` the layer is marked with, and JSX export writes them back (#616).+- Design JSX may begin with statements, such as `const` declarations, that end with `return` and the JSX, as a component's body does.diff --git a/changes/1236/breaking.md b/changes/1236/breaking.mdnew file mode 100644index 000000000..21b9b4c0d--- /dev/null+++ b/changes/1236/breaking.md@@ -0,0 +1 @@+- Code in the Code tab that puts statements before its JSX ends them with `return` and the JSX, as a component's body does; the JSX alone on the last line no longer renders.diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsindex 5708d7bb2..fe63e5b6b 100644--- a/packages/core/src/layout.ts+++ b/packages/core/src/layout.ts@@ -134,6 +134,12 @@ export function layoutAuthoredNodes(graph: SceneGraph, rootIds: Iterable<string>layout()// Layout gives wrapping text its width, which its height follows.if (roots.map((id) => sizeAutoResizingText(graph, id, true)).some(Boolean)) layout()+ // Connectors authored with the layers they join route once those layers are in place.+ for (const id of roots) {+ for (const { node } of graph.flattenTree(id)) {+ if (node.type === 'CONNECTOR') layoutConnector(graph, node)+ }+ }}function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<string>): void {diff --git a/packages/core/tests/design-jsx/connectors.test.ts b/packages/core/tests/design-jsx/connectors.test.tsnew file mode 100644index 000000000..a02352c38--- /dev/null+++ b/packages/core/tests/design-jsx/connectors.test.ts@@ -0,0 +1,291 @@+import { describe, expect, test } from 'bun:test'++import { getNodeOrThrow } from '#core-tests/helpers/assert'++import { renderJSX } from '@open-pencil/core/design-jsx'+import {+ designJSXElement,+ sceneNodeToJSX,+ selectionToJSX,+ selectionToJSXWithLayers+} from '@open-pencil/design-jsx'+import { connectorRouteEnds, connectorSublayers, SceneGraph } from '@open-pencil/scene-graph'++const FLOW = `+ <Frame name="Flow" w={800} h={400}>+ <Frame name="Start" x={0} y={100} w={200} h={100} bg="#DDE3F5" />+ <Frame name="Done" x={500} y={200} w={200} h={100} bg="#DDE3F5" />+ <Connector from="Start" to="Done" endCap="circle_filled">Next</Connector>+ <Connector from="Done" to={{ x: 750, y: 40 }} line="curved" />+ </Frame>`++describe('connectors in design JSX', () => {+ test('join the layers they name and route once laid out', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, FLOW)+ const flow = getNodeOrThrow(graph, result.id)+ const [start, done, next, free] = graph.getChildren(flow.id)+ expect(next.connectorStart).toMatchObject({+ nodeId: start.id,+ magnet: 'AUTO'+ })+ expect(next.connectorEnd).toMatchObject({+ nodeId: done.id,+ magnet: 'AUTO'+ })+ expect(next.connectorEndCap).toBe('CIRCLE_FILLED')+ expect(free.connectorEnd).toMatchObject({+ nodeId: null,+ position: { x: 750, y: 40 }+ })+ expect(connectorRouteEnds(graph, next)).toEqual({+ start: { x: 206, y: 150 },+ end: { x: 500, y: 250 }+ })+ })++ test('write back as Connector elements that name their layers', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, FLOW)+ const jsx = sceneNodeToJSX(result.id, graph)+ expect(jsx).toContain(+ '<Connector from="Start" to="Done" endCap="circle_filled">Next</Connector>'+ )+ expect(jsx).toContain('<Connector from="Done" to={{ x: 750, y: 40 }} line="curved" />')++ const again = new SceneGraph()+ const [reread] = await renderJSX(again, jsx)+ expect(sceneNodeToJSX(reread.id, again)).toBe(jsx)+ })++ test('exported alone, write ends on layers outside the export as the points they are drawn at', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, FLOW)+ const [, , next] = graph.getChildren(result.id)+ const jsx = sceneNodeToJSX(next.id, graph)+ expect(jsx).toBe(+ '<Connector from={{ x: 206, y: 150 }} to={{ x: 500, y: 250 }} endCap="circle_filled">Next</Connector>'+ )++ const again = new SceneGraph()+ const [reread] = await renderJSX(again, jsx)+ expect(reread.warnings ?? []).toEqual([])+ expect(sceneNodeToJSX(reread.id, again)).toBe(jsx)+ })++ test('describe themselves to an editor as their export writes them', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, FLOW)+ const [, , next] = graph.getChildren(result.id)+ expect(designJSXElement(next.id, graph)).toEqual({+ tag: 'Connector',+ attributes: { from: 'from="Start"', to: 'to="Done"', endCap: 'endCap="circle_filled"' },+ text: 'Next',+ childIds: []+ })+ })++ test("never join a connector's own line or label, though they have names", async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(+ graph,+ `<Frame name="Flow" w={800} h={400}>+ <Connector from={{ x: 0, y: 0 }} to={{ x: 100, y: 0 }}>Note</Connector>+ <Frame name="Line" x={0} y={100} w={100} h={100} />+ <Frame name="Label" x={500} y={100} w={100} h={100} />+ <Connector from="Line" to="Label" />+ </Frame>`+ )+ const [, line, label, joined] = graph.getChildren(result.id)+ expect(result.warnings ?? []).toEqual([])+ expect(joined.connectorStart?.nodeId).toBe(line.id)+ expect(joined.connectorEnd?.nodeId).toBe(label.id)+ expect(sceneNodeToJSX(result.id, graph)).toContain('<Connector from="Line" to="Label" />')+ })++ const TWIN_CARDS = `const left = ref()+const right = ref()+return <Frame name="Flow" w={800} h={400}>+ <Frame name="Card" x={0} y={100} w={200} h={100} ref={left} />+ <Frame name="Card" x={500} y={100} w={200} h={100} ref={right} />+ <Connector from={left} to={right} />+</Frame>`++ test('join the layers marked with the refs they take, whatever the layers are named', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, TWIN_CARDS)+ const [left, right, connector] = graph.getChildren(result.id)+ expect(result.warnings ?? []).toEqual([])+ expect(connector.connectorStart?.nodeId).toBe(left.id)+ expect(connector.connectorEnd?.nodeId).toBe(right.id)+ })++ test('write layers that share a name as refs, and read them back the same', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, TWIN_CARDS)+ const jsx = sceneNodeToJSX(result.id, graph)+ expect(jsx).toStartWith('const card1 = ref()\nconst card2 = ref()\n\nreturn <Frame name="Flow"')+ expect(jsx).toContain('ref={card1} />')+ expect(jsx).toContain('<Connector from={card1} to={card2} />')++ const again = new SceneGraph()+ const [reread] = await renderJSX(again, jsx)+ expect(reread.warnings ?? []).toEqual([])+ const [left, right, connector] = again.getChildren(reread.id)+ expect(connector.connectorStart?.nodeId).toBe(left.id)+ expect(connector.connectorEnd?.nodeId).toBe(right.id)+ expect(sceneNodeToJSX(reread.id, again)).toBe(jsx)+ })++ test('write several layers that need refs as one returned fragment, and read it back', async () => {+ const graph = new SceneGraph()+ const results = await renderJSX(+ graph,+ `const left = ref()+const right = ref()+return <>+ <Frame name="Card" x={0} y={100} w={200} h={100} ref={left} />+ <Frame name="Card" x={500} y={100} w={200} h={100} ref={right} />+ <Connector from={left} to={right} />+</>`+ )+ const jsx = selectionToJSX(+ results.map(({ id }) => id),+ graph+ )+ expect(jsx).toStartWith(+ 'const card1 = ref()\nconst card2 = ref()\n\nreturn <>\n<Frame name="Card"'+ )+ expect(jsx).toEndWith('\n</>')+ const again = new SceneGraph()+ const reread = await renderJSX(again, jsx)+ const [left, right, connector] = reread.map(({ id }) => again.getNode(id))+ expect(connector?.connectorStart?.nodeId).toBe(left?.id)+ expect(connector?.connectorEnd?.nodeId).toBe(right?.id)+ })++ test('without declarations, write ends whose layers share a name as their points', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, TWIN_CARDS)+ const { code } = selectionToJSXWithLayers([result.id], graph, { declarations: false })+ expect(code).toStartWith('<Frame name="Flow"')+ expect(code).not.toContain('ref')+ expect(code).toContain('<Connector from={{ x: 206, y: 150 }} to={{ x: 493.5, y: 150 }} />')+ })++ test('warn for a name more than one layer has, and for refs that mark no layer or two', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(+ graph,+ `const twice = ref()+const unused = ref()+return <Frame name="Flow" w={800} h={400}>+ <Frame name="Card" w={100} h={100} ref={twice} />+ <Frame name="Card" x={300} w={100} h={100} ref={twice} />+ <Connector from="Card" to={unused} />+</Frame>`+ )+ expect(result.warnings).toEqual([+ 'One ref() marks both "Card" and "Card"; it refers to "Card".',+ '<Connector> from="Card" names 2 layers and joins the first; mark the one to join with ref().',+ '<Connector> to={ref} refers to no layer.'+ ])+ })++ test('restyle the line by each stroke prop alone, and write the style back', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(+ graph,+ `<Frame name="Flow" w={800} h={400}>+ <Frame name="A" x={0} y={0} w={100} h={100} />+ <Frame name="B" x={400} y={0} w={100} h={100} />+ <Connector from="A" to="B" strokeWidth={8} />+ <Connector from="A" to="B" stroke="#FF0000" dashPattern={[6, 4]} />+ </Frame>`+ )+ const [, , heavy, dashed] = graph.getChildren(result.id)+ const heavyLine = connectorSublayers(graph, heavy)?.line+ expect(heavyLine?.strokes[0]).toMatchObject({+ weight: 8,+ color: { r: 117 / 255 },+ cap: 'ROUND'+ })+ const dashedLine = connectorSublayers(graph, dashed)?.line+ expect(dashedLine?.strokes[0]).toMatchObject({+ weight: 4,+ color: { r: 1, g: 0, b: 0 }+ })+ expect(dashedLine?.dashPattern).toEqual([6, 4])+ const jsx = sceneNodeToJSX(result.id, graph)+ expect(jsx).toContain('<Connector from="A" to="B" strokeWidth={8} />')+ expect(jsx).toContain('<Connector from="A" to="B" stroke="#FF0000" dashPattern={[6, 4]} />')+ })++ test('an end naming no layer is left free, with a warning', async () => {+ const graph = new SceneGraph()+ const [result] = await renderJSX(+ graph,+ '<Frame name="Flow" w={400} h={200}><Frame name="A" w={50} h={50} /><Connector from="A" to="Nowhere" /></Frame>'+ )+ expect(result.warnings).toContain('<Connector> to="Nowhere" names no layer.')+ })++ test('name the rendered roots too, not only the layers inside them', async () => {+ const graph = new SceneGraph()+ const [flow] = await renderJSX(+ graph,+ `<Frame name="Flow" w={800} h={400}>+ <Frame name="Step" x={300} y={100} w={100} h={100} />+ <Connector from="Flow" to="Step" />+ </Frame>`+ )+ expect(flow.warnings ?? []).toEqual([])+ const connector = getNodeOrThrow(graph, graph.getChildren(flow.id)[1].id)+ expect(connector.connectorStart?.nodeId).toBe(flow.id)+ })++ test('write back their name, visibility, and opacity', async () => {+ const graph = new SceneGraph()+ const jsx = `<Frame name="Flow" w={800} h={400}>+ <Frame name="A" x={0} y={0} w={100} h={100} />+ <Frame name="B" x={400} y={0} w={100} h={100} />+ <Connector name="Hidden" from="A" to="B" opacity={0.5} visible={false} />+ </Frame>`+ const [result] = await renderJSX(graph, jsx)+ expect(sceneNodeToJSX(result.id, graph)).toContain(+ '<Connector name="Hidden" from="A" to="B" opacity={0.5} visible={false} />'+ )+ })++ test('style and bind their line by the variables their stroke props name', async () => {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'colors',+ name: 'Colors',+ modes: [{ modeId: 'light', name: 'Light' }],+ defaultModeId: 'light',+ variableIds: []+ })+ graph.addVariable({+ id: 'var-line',+ name: 'Line',+ type: 'COLOR',+ collectionId: 'colors',+ valuesByMode: { light: { r: 1, g: 0, b: 0, a: 1 } },+ description: '',+ hiddenFromPublishing: false+ })+ const [result] = await renderJSX(+ graph,+ `<Frame name="Flow" w={800} h={400}>+ <Frame name="A" x={0} y={0} w={100} h={100} />+ <Frame name="B" x={400} y={0} w={100} h={100} />+ <Connector from="A" to="B" stroke={designVar('var-line', '#FF0000')} />+ </Frame>`+ )+ const connector = getNodeOrThrow(graph, graph.getChildren(result.id)[2].id)+ const line = connectorSublayers(graph, connector)?.line+ expect(line?.strokes[0]?.color).toMatchObject({ r: 1, g: 0, b: 0 })+ expect(line?.boundVariables['strokes/0/color']).toBe('var-line')+ })+})diff --git a/packages/core/tests/design-jsx/expressions.test.ts b/packages/core/tests/design-jsx/expressions.test.tsindex 8598579c0..d9aa044f1 100644--- a/packages/core/tests/design-jsx/expressions.test.ts+++ b/packages/core/tests/design-jsx/expressions.test.ts@@ -32,13 +32,58 @@ test('an arrow function called in place can hold statements', async () => {expect(root.childIds.map((id) => graph.getNode(id)?.name)).toEqual(['Mo', 'Tu', 'We'])})-test('a statement before the JSX fails with guidance added to the undefined name', async () => {- const error = await render(`const days = ['Mo']-<Frame>{days.map((day) => <Text>{day}</Text>)}</Frame>`).catch((thrown: unknown) => thrown)-- if (!(error instanceof Error) || !(error.cause instanceof ReferenceError)) {- throw new Error('Expected guidance wrapping the ReferenceError')- }- expect(error.message).toStartWith(error.cause.message)- expect(error.message.length).toBeGreaterThan(error.cause.message.length)+test('statements run before the JSX they return, with or without semicolons', async () => {+ const { graph, root } = await render(`const days = ['Mo', 'Tu']+const label = (day: string) => day.toUpperCase()+return <Frame name="Week">{days.map((day) => <Text name={label(day)}>{day}</Text>)}</Frame>`)+ expect(root.name).toBe('Week')+ expect(root.childIds.map((id) => graph.getNode(id)?.name)).toEqual(['MO', 'TU'])+})++test('the returned JSX may open with a parenthesis on the line of the return', async () => {+ const { root } = await render(`const name = 'Wrapped'+return (+ <Frame name={name} />+)`)+ expect(root.name).toBe('Wrapped')+})++test('statements may return sibling elements in a fragment, which all render', async () => {+ const graph = new SceneGraph()+ const results = await renderJSX(+ graph,+ `const size = 40+return <>+ <Frame name="A" w={size} />+ <Frame name="B" w={size} />+</>`+ )+ expect(results.map(({ name }) => name)).toEqual(['A', 'B'])+ expect(results.map(({ id }) => graph.getNode(id)?.width)).toEqual([40, 40])+})++test('sibling elements on their own lines stay siblings', async () => {+ const graph = new SceneGraph()+ const results = await renderJSX(graph, '<Frame name="A" />\n<Frame name="B" />')+ expect(results.map(({ name }) => name)).toEqual(['A', 'B'])+})++test('a statement may shadow a helper or element name', async () => {+ const { root } = await render(`const solid = 'Shadowed'+return <Frame name={solid} />`)+ expect(root.name).toBe('Shadowed')+})++test('statements that do not return the JSX are reported as such', async () => {+ const graph = new SceneGraph()+ const rule = 'Design JSX is one JSX expression, or statements that end with `return` and the JSX'+ await expect(renderJSX(graph, `const size = 40\n<Frame w={size} />`)).rejects.toThrow(rule)+ await expect(renderJSX(graph, `const name = 'Wrapped'\n(<Frame name={name} />)`)).rejects.toThrow(+ `${rule}; these statements return nothing.`+ )+})++test('a comment before the JSX does not end the return', async () => {+ const { root } = await render('// The header\n<Frame name="Header" />')+ expect(root.name).toBe('Header')})diff --git a/packages/design-jsx/src/connectors.ts b/packages/design-jsx/src/connectors.tsnew file mode 100644index 000000000..0b272b602--- /dev/null+++ b/packages/design-jsx/src/connectors.ts@@ -0,0 +1,316 @@+import { compact, countBy } from 'es-toolkit/array'+import { camelCase } from 'es-toolkit/string'++import {+ boundEndpoint,+ CONNECTOR_COLOR,+ CONNECTOR_NAME,+ CONNECTOR_STROKE_WEIGHT,+ connectorRouteEnds,+ connectorStroke,+ connectorSublayers,+ createConnector,+ freeEndpoint,+ type ConnectorEndpoint,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'+import { colorToHex, tryParseColor } from '@open-pencil/scene-graph/color'+import type { Color, Vector } from '@open-pencil/scene-graph/primitives'++import { CONNECTOR_LINE, CONNECTOR_SIDE, STROKE_CAP } from './enums'+import { Reference } from './export/value'+import { isColor } from './overrides/fills'+import { isLayerRef, type LayerRefs } from './refs'+import type { TreeNode } from './tree'++/**+ * `<Connector from="A" to="B">`: a FigJam connector whose ends name other layers of the same+ * JSX, or give `{ x, y }` points in its parent. Ends resolve once the whole tree is rendered, and+ * the connector routes once it is laid out.+ */+export const CONNECTOR_ELEMENT = 'connector'++function isPoint(value: unknown): value is Vector {+ if (typeof value !== 'object' || value === null || !('x' in value) || !('y' in value)) {+ return false+ }+ return typeof value.x === 'number' && typeof value.y === 'number'+}++function labelOf(tree: TreeNode): string {+ return tree.children.filter((child): child is string => typeof child === 'string').join('')+}++/** Makes the connector an element describes, its ends free until `resolveConnectorEnds`. */+export function renderConnectorNode(graph: SceneGraph, tree: TreeNode, parentId: string) {+ const { props } = tree+ const line = CONNECTOR_LINE.parse(props.line)+ const parent = graph.getNode(parentId)+ const connector = createConnector(+ graph,+ parentId,+ {+ start: freeEndpoint(0, 0),+ end: freeEndpoint(0, 0),+ lineType: line,+ startCap: STROKE_CAP.parse(props.startCap) ?? 'NONE',+ endCap: STROKE_CAP.parse(props.endCap) ?? 'ARROW_LINES',+ text: labelOf(tree)+ },+ {+ ...(typeof props.name === 'string' && { name: props.name }),+ ...(props.visible === false && { visible: false }),+ ...(typeof props.opacity === 'number' && { opacity: props.opacity }),+ // A connector is drawn between layers, not placed by its parent's auto layout.+ ...(parent && parent.layoutMode !== 'NONE' && { layoutPositioning: 'ABSOLUTE' as const })+ }+ )+ const lineLayer = connectorSublayers(graph, connector)?.line+ if (lineLayer) styleLine(graph, lineLayer, props)+ return connector+}++function colorOf(value: unknown): Color | undefined {+ if (isColor(value)) return value+ return typeof value === 'string' ? (tryParseColor(value) ?? undefined) : undefined+}++/** Restyles the line by `stroke`, `strokeWidth`, and `dashPattern`; each left out keeps FigJam's. */+function styleLine(graph: SceneGraph, line: SceneNode, props: TreeNode['props']) {+ const [stroke = connectorStroke()] = line.strokes+ const color = colorOf(props.stroke) ?? stroke.color+ const weight =+ typeof props.strokeWidth === 'number' && props.strokeWidth > 0+ ? props.strokeWidth+ : stroke.weight+ const dashPattern = Array.isArray(props.dashPattern)+ ? props.dashPattern.filter((length): length is number => typeof length === 'number')+ : line.dashPattern+ graph.updateNode(line.id, {+ strokes: [{ ...stroke, color, weight }],+ strokeWeight: weight,+ dashPattern+ })+}++/**+ * The layers JSX writes under `rootIds`, in order, each before its descendants: a connector's+ * generated line and label are not, so an end never names them.+ */+function layersUnder(graph: SceneGraph, rootIds: readonly string[]): SceneNode[] {+ const layers: SceneNode[] = []+ const visit = (id: string) => {+ const node = graph.getNode(id)+ if (!node) return+ layers.push(node)+ if (node.type !== 'CONNECTOR') for (const childId of node.childIds) visit(childId)+ }+ for (const id of rootIds) visit(id)+ return layers+}++/** A connector end's prop as a warning quotes it. */+function endSource(prop: string, value: unknown): string {+ if (isLayerRef(value)) return `${prop}={ref}`+ return `${prop}="${String(value)}"`+}++/**+ * Binds the ends of connectors rendered from `trees` to the layers they refer to: a `ref()` a+ * layer was marked with, or a name among `rootIds`' layers, the first of a name winning. Returns+ * warnings for ends that refer to no layer, and for names that more than one layer has.+ */+export function resolveConnectorEnds(+ graph: SceneGraph,+ rootIds: readonly string[],+ connectors: ReadonlyArray<{ node: SceneNode; tree: TreeNode }>,+ refs: LayerRefs+): string[] {+ if (connectors.length === 0) return []+ const named = new Map<string, string[]>()+ for (const layer of layersUnder(graph, rootIds)) {+ if (layer.type === 'CONNECTOR') continue+ const ids = named.get(layer.name)+ if (ids) ids.push(layer.id)+ else named.set(layer.name, [layer.id])+ }+ const warnings: string[] = []+ const endpoint = (prop: 'from' | 'to', props: TreeNode['props'], straight: boolean) => {+ const value = props[prop]+ if (isPoint(value)) return freeEndpoint(value.x, value.y)+ let id: string | undefined+ if (isLayerRef(value)) id = refs.layerOf(value)+ else if (typeof value === 'string') {+ const ids = named.get(value) ?? []+ if (ids.length > 1) {+ warnings.push(+ `<Connector> ${endSource(prop, value)} names ${ids.length} layers and joins the first; mark the one to join with ref().`+ )+ }+ id = ids.at(0)+ }+ if (!id) {+ const missing = isLayerRef(value) ? 'refers to no layer' : 'names no layer'+ warnings.push(`<Connector> ${endSource(prop, value)} ${missing}.`)+ return null+ }+ const side = props[prop === 'from' ? 'fromSide' : 'toSide']+ return boundEndpoint(id, straight ? 'CENTER' : (CONNECTOR_SIDE.parse(side) ?? 'AUTO'))+ }+ for (const { node, tree } of connectors) {+ const straight = node.connectorLineType === 'STRAIGHT'+ const start = endpoint('from', tree.props, straight)+ const end = endpoint('to', tree.props, straight)+ graph.updateNode(node.id, {+ ...(start && { connectorStart: start }),+ ...(end && { connectorEnd: end })+ })+ }+ 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 = /^[A-Za-z_$][\w$]*$/.test(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>+ /**+ * The layers connector ends join whose name another layer of the export has too, so the name+ * would not say which: each with the `ref()` the export declares for it, or `null` when the+ * export declares nothing and such an end is written as the point it is drawn at.+ */+ refs: ReadonlyMap<string, string | null>+}++/**+ * 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.+ */+export function connectorExportScope(+ graph: SceneGraph,+ rootIds: readonly string[],+ declare: boolean+): ConnectorExportScope {+ const layers = layersUnder(graph, rootIds)+ const connectors = layers.filter((layer) => layer.type === 'CONNECTOR')+ const refs = new Map<string, string | null>()+ if (connectors.length === 0) return { roots: new Set(rootIds), refs }+ const joined = new Set(+ connectors.flatMap((connector) => [+ connector.connectorStart?.nodeId,+ connector.connectorEnd?.nodeId+ ])+ )+ const named = countBy(+ 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) continue+ refs.set(layer.id, declare ? refName(layer.name, taken) : null)+ }+ 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 }++function endTarget(+ graph: SceneGraph,+ endpoint: ConnectorEndpoint,+ drawn: Vector | undefined,+ scope: ConnectorExportScope | undefined+): EndTarget {+ const layer = endpoint.nodeId ? graph.getNode(endpoint.nodeId) : undefined+ if (!layer) return { point: endpoint.position }+ const exported =+ !scope || graph.closest(layer.id, (ancestor) => scope.roots.has(ancestor.id)) !== undefined+ const ref = scope?.refs.get(layer.id)+ if (exported && ref !== null) return { layer, ref }+ return { point: drawn ?? endpoint.position }+}++/**+ * A connector's props as `<Connector>` writes them, its ends by the names of their layers, or by+ * the refs `scope` declares for layers whose names are not unique. An end on a layer outside the+ * export, or one the scope gives no ref, is written as the point it is drawn at.+ */+export function connectorProps(+ graph: SceneGraph,+ node: SceneNode,+ scope?: ConnectorExportScope+): Array<[string, unknown]> {+ const drawn = connectorRouteEnds(graph, node)+ const target = (endpoint: ConnectorEndpoint | null, at: Vector | undefined) =>+ endpoint ? endTarget(graph, endpoint, at, scope) : null+ const start = target(node.connectorStart, drawn?.start)+ const end = target(node.connectorEnd, drawn?.end)+ const value = (written: EndTarget | null) => {+ if (!written) return null+ if ('point' in written) return { x: written.point.x, y: written.point.y }+ return written.ref ? new Reference(written.ref) : written.layer.name+ }+ const side = (endpoint: ConnectorEndpoint | null, written: EndTarget | null) => {+ if (!endpoint || !written || 'point' in written) return undefined+ const magnet = endpoint.magnet+ if (magnet !== 'TOP' && magnet !== 'RIGHT' && magnet !== 'BOTTOM' && magnet !== 'LEFT') {+ return undefined+ }+ return CONNECTOR_SIDE.print(magnet)+ }+ const props: Array<[string, unknown]> = [+ ['name', node.name === CONNECTOR_NAME ? undefined : node.name],+ ['from', value(start)],+ ['to', value(end)],+ ['fromSide', side(node.connectorStart, start)],+ ['toSide', side(node.connectorEnd, end)],+ [+ 'line',+ node.connectorLineType === 'ELBOWED'+ ? undefined+ : CONNECTOR_LINE.print(node.connectorLineType)+ ],+ [+ 'startCap',+ node.connectorStartCap === 'NONE' ? undefined : STROKE_CAP.print(node.connectorStartCap)+ ],+ [+ 'endCap',+ node.connectorEndCap === 'ARROW_LINES' ? undefined : STROKE_CAP.print(node.connectorEndCap)+ ]+ ]+ const line = connectorSublayers(graph, node)?.line+ const stroke = line?.strokes[0]+ if (stroke && colorToHex(stroke.color) !== colorToHex(CONNECTOR_COLOR)) {+ props.push(['stroke', colorToHex(stroke.color)])+ }+ if (stroke && stroke.weight !== CONNECTOR_STROKE_WEIGHT)+ props.push(['strokeWidth', stroke.weight])+ if (line && line.dashPattern.length > 0) props.push(['dashPattern', [...line.dashPattern]])+ if (node.opacity < 1) props.push(['opacity', Math.round(node.opacity * 100) / 100])+ if (!node.visible) props.push(['visible', false])+ return props.filter(([, value]) => value !== undefined && value !== null)+}++/** The label a connector writes as its children. */+export function connectorLabel(graph: SceneGraph, node: SceneNode): string {+ return connectorSublayers(graph, node)?.label.text ?? ''+}diff --git a/packages/design-jsx/src/elements.ts b/packages/design-jsx/src/elements.tsindex ace8762d3..a904c4924 100644--- a/packages/design-jsx/src/elements.ts+++ b/packages/design-jsx/src/elements.ts@@ -4,6 +4,8 @@ import type { NodeType } from '@open-pencil/scene-graph'import { REKA_ELEMENTS, rekaRole } from './behaviours'import {+ DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES,+ DESIGN_JSX_CONNECTOR_PROPERTY_NAMES,DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,DESIGN_JSX_SPAN_PROPERTY_NAMES,DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,@@ -152,6 +154,14 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [nodeType: 'RECTANGLE'},{ name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' },+ {+ name: 'Connector',+ runtimeType: 'connector',+ description:+ 'A FigJam connector between two layers of the same JSX, named by `from` and `to`, or points.',+ props: [...DESIGN_JSX_CONNECTOR_PROPERTY_NAMES, ...DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES],+ writes: ['CONNECTOR']+ },...rekaElementDefinitions()]diff --git a/packages/design-jsx/src/enums.ts b/packages/design-jsx/src/enums.tsindex 41a88bd2d..b42f7210d 100644--- a/packages/design-jsx/src/enums.ts+++ b/packages/design-jsx/src/enums.ts@@ -1,5 +1,7 @@import type {BlendMode,+ ConnectorLineType,+ ConnectorMagnet,ConstraintType,MaskType,SceneNode,@@ -115,6 +117,12 @@ export const TEXT_DECORATION = lowercaseEnum<TextDecoration>(['NONE', 'UNDERLINEexport const TEXT_DECORATION_STYLE = lowercaseEnum<TextDecorationStyle>(['SOLID', 'DOTTED', 'WAVY'])export const TEXT_CASE = lowercaseEnum<TextCase>(['ORIGINAL', 'UPPER', 'LOWER', 'TITLE'])+export const CONNECTOR_LINE = lowercaseEnum<ConnectorLineType>(['ELBOWED', 'STRAIGHT', 'CURVED'])+/** The sides a `<Connector>` end attaches by; the other magnets come only from files. */+export const CONNECTOR_SIDE = lowercaseEnum<+ Extract<ConnectorMagnet, 'AUTO' | 'TOP' | 'RIGHT' | 'BOTTOM' | 'LEFT' | 'CENTER'>+>(['AUTO', 'TOP', 'RIGHT', 'BOTTOM', 'LEFT', 'CENTER'])+/** The props whose values are one of an enum's spellings, for checking what JSX passes. */export const ENUM_PROPS: Readonly<Partial<Record<string, JSXEnum<string>>>> = {strokeCap: STROKE_CAP,@@ -128,5 +136,10 @@ export const ENUM_PROPS: Readonly<Partial<Record<string, JSXEnum<string>>>> = {dir: TEXT_DIRECTION,textDecoration: TEXT_DECORATION,textDecorationStyle: TEXT_DECORATION_STYLE,- textCase: TEXT_CASE+ textCase: TEXT_CASE,+ line: CONNECTOR_LINE,+ fromSide: CONNECTOR_SIDE,+ toSide: CONNECTOR_SIDE,+ startCap: STROKE_CAP,+ endCap: STROKE_CAP}diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex 9326bd106..bdea9b20e 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -1,14 +1,21 @@import { compact } from 'es-toolkit/array'import { jsx, type SyntaxNode } from '@open-pencil/emit'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import {+ connectorExportScope,+ connectorLabel,+ connectorProps,+ connectorRefDeclarations,+ type ConnectorExportScope+} from '../connectors'import { elementTag } from '../elements'import { rekaExport, type RekaExport } from './behaviours'import { iconProps } from './icons'import { collectProps } from './props'import { textChildren } from './text'-import { propAttribute } from './value'+import { plainValue, propAttribute, Reference, type JSXProp } from './value'/** Design JSX with the layer behind each element, in the order elements open. */export interface DesignJSXWithLayers {@@ -46,34 +53,64 @@ function elementCount(nodes: readonly SyntaxNode[]): number {* A layer and the layers below it as JSX elements. A component with a behaviour is written as* Reka UI elements; a container JSX leaves implicit is written as its children alone.*/+/** What an element written its own way holds: its props, and the text it writes as children. */+interface OwnElement {+ props: JSXProp[]+ text: string+}++/** The layers whose elements take props of their own rather than the layer props. */+const OWN_ELEMENTS: Partial<+ Record<NodeType, (graph: SceneGraph, node: SceneNode, scope?: ConnectorExportScope) => OwnElement>+> = {+ CONNECTOR: (graph, node, scope) => ({+ props: connectorProps(graph, node, scope).map(([key, value]): JSXProp => [+ key,+ plainValue(value)+ ]),+ text: connectorLabel(graph, node)+ })+}++/** The layers an export writes, by the roots it starts from. */function nodeToJSX(node: SceneNode,graph: SceneGraph,depth: number,+ scope: ConnectorExportScope,layerIds?: Array<string | null>,outer: RekaExport = NO_REKA): SyntaxNode[] {const reka = mergeReka(outer, rekaExport(graph, node))+ const ref = scope.refs.get(node.id)+ // A layer a connector joins 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, 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)if (icon) {layerIds?.push(node.id)- return [jsx.element('Icon', icon.map(propAttribute), [], depth)]+ return [jsx.element('Icon', withRef(icon).map(propAttribute), [], depth)]}const tag = reka.tags.get(node.id) ?? elementTag(node.type)if (!tag) return []layerIds?.push(node.id)+ const own = OWN_ELEMENTS[node.type]?.(graph, node, scope)+ if (own) {+ const children = own.text ? [jsx.text(own.text)] : []+ return [jsx.element(tag, own.props.map(propAttribute), children, depth, true)]+ }const ownProps = reka.props.get(node.id)// 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, ownProps.map(propAttribute), [], depth)]- const attributes = [...collectProps(node, graph), ...(ownProps ?? [])].map(propAttribute)+ return [jsx.element(tag, withRef(ownProps).map(propAttribute), [], depth)]+ const attributes = withRef([...collectProps(node, graph), ...(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)@@ -95,7 +132,8 @@ function oneLine(source: string): string {/*** The attributes `sceneNodeToJSX` prints for a node, each on one line, with a text node's- * content as a `text` attribute. `null` for a node the export does not write.+ * content, or a connector's label, as a `text` attribute. `null` for a node the export does not+ * write. A connector's ends are written by their layers' names.*/export function sceneNodeAttributes(nodeId: string,@@ -103,8 +141,10 @@ export function sceneNodeAttributes(): JSXAttributeSource[] | null {const node = graph.getNode(nodeId)if (!node || !elementTag(node.type)) return null- const props = collectProps(node, graph)+ const own = OWN_ELEMENTS[node.type]?.(graph, node)+ const props = own ? own.props : collectProps(node, graph)if (node.type === 'TEXT') props.push(['text', node.text])+ if (own?.text) props.push(['text', own.text])return props.map((prop) => ({name: prop[0],source: oneLine(jsx.printJSX(propAttribute(prop)))@@ -128,9 +168,8 @@ export interface DesignJSXElement {childIds: string[]}-/** What a text's element holds between its tags, printed as `sceneNodeToJSX` prints it. */-function textContent(node: SceneNode, tag: string): string | null {- const { children, inline } = textChildren(node, 0)+/** What an element holds between its tags, printed as `sceneNodeToJSX` prints it. */+function contentBetween(tag: string, children: SyntaxNode[], inline: boolean): string | null {if (children.length === 0) return nullconst printed = jsx.printJSX(jsx.element(tag, [], children, 0, inline))return printed.slice(tag.length + 2, printed.lastIndexOf(`</${tag}>`))@@ -141,14 +180,24 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElconst tag = node && elementTag(node.type)const printed = sceneNodeAttributes(nodeId, graph)if (!node || !tag || !printed) return null- // A text layer's content is written as its children, not as the `text` attribute.- const isText = node.type === 'TEXT'+ // A text layer's content, or a connector's label, is written as its children, not as the+ // `text` attribute; a connector's generated layers are not written at all.+ const own = OWN_ELEMENTS[node.type]+ const hasContent = node.type === 'TEXT' || own !== undefinedconst attributes = Object.fromEntries(printed- .filter(({ name }) => !isText || name !== 'text')+ .filter(({ name }) => !hasContent || name !== 'text').map(({ name, source }) => [name, source]))- if (isText) return { tag, attributes, text: textContent(node, tag), childIds: [] }+ if (node.type === 'TEXT') {+ const { children, inline } = textChildren(node, 0)+ return { tag, attributes, text: contentBetween(tag, children, inline), childIds: [] }+ }+ if (own) {+ const { text } = own(graph, node)+ const children = text ? [jsx.text(text)] : []+ return { tag, attributes, text: contentBetween(tag, children, true), childIds: [] }+ }const childIds = graph.getChildren(node.id).filter((child) => elementTag(child.type))@@ -156,10 +205,17 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElreturn { tag, attributes, text: null, childIds }}+/** How an export is written: by default, with the declarations its JSX uses before it. */+export interface JSXExportOptions {+ /**+ * `false` writes only JSX, for code that places it inside other JSX: a connector end whose+ * layer would need a declared `ref()` is then written as the point it is drawn at.+ */+ declarations?: boolean+}+export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {- const node = graph.getNode(nodeId)- const syntax = node ? nodeToJSX(node, graph, 0).at(0) : undefined- return syntax ? jsx.printJSX(syntax) : ''+ return selectionToJSX([nodeId], graph)}export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {@@ -168,15 +224,22 @@ export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {export function selectionToJSXWithLayers(nodeIds: string[],- graph: SceneGraph+ graph: SceneGraph,+ options: JSXExportOptions = {}): DesignJSXWithLayers {const layerIds: Array<string | null> = []- const code = compact(+ const scope = connectorExportScope(graph, nodeIds, options.declarations ?? true)+ const roots = compact(nodeIds.map((id) => {const node = graph.getNode(id)- const syntax = node ? nodeToJSX(node, graph, 0, layerIds).at(0) : undefined+ const syntax = node ? nodeToJSX(node, graph, 0, scope, layerIds).at(0) : undefinedreturn syntax ? jsx.printJSX(syntax) : ''})- ).join('\n\n')- return { code, layerIds }+ )+ const elements = roots.join('\n\n')+ const declarations = connectorRefDeclarations(scope)+ if (!declarations || !elements) return { code: elements, layerIds }+ // Statements end with `return` and the JSX; several roots return as siblings in a fragment.+ const returned = roots.length > 1 ? `<>\n${elements}\n</>` : elements+ return { code: `${declarations}\n\nreturn ${returned}`, layerIds }}diff --git a/packages/design-jsx/src/export/value.ts b/packages/design-jsx/src/export/value.tsindex ed9b18aba..f24c23bf5 100644--- a/packages/design-jsx/src/export/value.ts+++ b/packages/design-jsx/src/export/value.ts@@ -8,6 +8,11 @@ export class HelperCall {) {}}+/** A name the export declares before the JSX, such as the `card1` of `ref={card1}`. */+export class Reference {+ constructor(readonly name: string) {}+}+/** A prop value: plain data, possibly holding helper calls. Undefined object fields are left out. */export type JSXValue =| string@@ -15,6 +20,7 @@ export type JSXValue =| boolean| null| HelperCall+ | Reference| JSXValue[]| { [key: string]: JSXValue | undefined }@@ -39,6 +45,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {* cannot write back, such as binary data.*/export function plainValue(value: unknown): JSXValue {+ if (value instanceof Reference) return valueif (value === null || typeof value === 'string' || typeof value === 'boolean') return valueif (typeof value === 'number' && Number.isFinite(value)) return valueif (Array.isArray(value)) return value.map(plainValue)@@ -56,6 +63,7 @@ export function plainValue(value: unknown): JSXValue {export function valueSyntax(value: JSXValue): SyntaxNode {if (value === null) return { type: 'Literal', value: null }if (value instanceof HelperCall) return es.call(value.helper, value.args.map(valueSyntax))+ if (value instanceof Reference) return es.identifier(value.name)if (Array.isArray(value)) return es.array(value.map(valueSyntax))if (typeof value === 'object') {return es.object(diff --git a/packages/design-jsx/src/helpers.ts b/packages/design-jsx/src/helpers.tsindex cca80ebdb..361628f19 100644--- a/packages/design-jsx/src/helpers.ts+++ b/packages/design-jsx/src/helpers.ts@@ -21,6 +21,7 @@ import {type GradientPaintOptions,type SolidPaintOptions} from './paints'+import { ref } from './refs'/** Every option a helper reads; `satisfies` keeps the list equal to the options type. */type OptionKeys<Options> = Record<keyof Options, true>@@ -102,6 +103,7 @@ export function designJSXHelpers(warnings: string[]) {linearGradient: checked(warnings, 'linearGradient', linearGradient, GRADIENT_OPTIONS, 1),radialGradient: checked(warnings, 'radialGradient', radialGradient, GRADIENT_OPTIONS, 1),angularGradient: checked(warnings, 'angularGradient', angularGradient, GRADIENT_OPTIONS, 1),- diamondGradient: checked(warnings, 'diamondGradient', diamondGradient, GRADIENT_OPTIONS, 1)+ diamondGradient: checked(warnings, 'diamondGradient', diamondGradient, GRADIENT_OPTIONS, 1),+ ref}}diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.tsindex 8d4200e65..3ca9a6740 100644--- a/packages/design-jsx/src/index.ts+++ b/packages/design-jsx/src/index.ts@@ -82,6 +82,7 @@ export {} from './paints'export { defineVars, designVar, isVariable, type DesignVariable, type VarDef } from './vars'+export { isLayerRef, ref, type LayerRef } from './refs'export { createElement } from './mini-react'@@ -108,7 +109,6 @@ export {export {transformDesignJSXExpression,transformDesignJSXProgram,- type DesignJSXChunk,type DesignJSXProgram} from './transform'@@ -120,7 +120,8 @@ export {selectionToJSXWithLayers,type DesignJSXElement,type DesignJSXWithLayers,- type JSXAttributeSource+ type JSXAttributeSource,+ type JSXExportOptions} from './export'export { parseJSXAttributes } from './attributes'export { jsxNodeFields, type JSXNodeFields } from './fields'diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex f3e9bbe5b..ca34b1cfa 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -25,6 +25,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.## Variables and components@@ -33,7 +34,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.-- A JSX string is one expression. 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. For longer logic, call an arrow function in place: `{(() => { const weeks = …; return weeks.map(…) })()}`; statements outside an expression do not run.+- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.diff --git a/packages/design-jsx/src/refs.ts b/packages/design-jsx/src/refs.tsnew file mode 100644index 000000000..5ca9d429f--- /dev/null+++ b/packages/design-jsx/src/refs.ts@@ -0,0 +1,48 @@+import type { SceneNode } from '@open-pencil/scene-graph'++const REF_SYMBOL = Symbol.for('open-pencil.layer-ref')++/**+ * A handle on one layer of the JSX: `ref={card}` marks the layer, and an element that refers to+ * a layer, such as `<Connector from={card}>`, takes the handle where a name could be ambiguous.+ */+export interface LayerRef {+ readonly [REF_SYMBOL]: true+}++/** A new handle for `ref={…}` to mark a layer with. */+export function ref(): LayerRef {+ return Object.freeze({ [REF_SYMBOL]: true as const })+}++export function isLayerRef(value: unknown): value is LayerRef {+ return typeof value === 'object' && value !== null && REF_SYMBOL in value+}++/** The layers a render marked with `ref={…}`, for the elements that refer to them. */+export class LayerRefs {+ readonly warnings: string[] = []+ private readonly layers = new Map<LayerRef, SceneNode>()++ /** Marks `node` with the `ref` prop its element passed, if any. */+ mark(value: unknown, node: SceneNode) {+ if (value === undefined) return+ if (!isLayerRef(value)) {+ this.warnings.push(`ref on "${node.name}" is not a ref() and is ignored.`)+ return+ }+ const first = this.layers.get(value)+ if (first) {+ this.warnings.push(+ `One ref() marks both "${first.name}" and "${node.name}"; it refers to "${first.name}".`+ )+ return+ }+ this.layers.set(value, node)+ }++ /** The id of the layer `ref` marks, if one does. */+ layerOf(ref: LayerRef): string | undefined {+ return this.layers.get(ref)?.id+ }+}diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.tsindex 120d7d542..ee651ab5c 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render.ts@@ -1,5 +1,4 @@import { uniq } from 'es-toolkit/array'-import { transform } from 'sucrase'import type { SceneGraph } from '@open-pencil/scene-graph'@@ -11,6 +10,7 @@ import * as React from './mini-react'import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'import type { DesignJSXServices } from './services'import { TEXT_CONTENT_NAMES } from './text-content'+import { transformDesignJSXExpression } from './transform'import { isTreeNode, resolveToTree, type TreeNode } from './tree'import type { RenderOptions as RenderJSXOptions } from './types'@@ -65,15 +65,16 @@ function collectUnsupportedPropWarnings(}/**- * Build a component function from a JSX string using sucrase.- * Works in both Node/Bun and the browser (no native bindings).+ * Build a component function from a JSX string: one JSX expression, sibling elements, or+ * statements that end with `return` and the JSX. The statements run inside the component, so+ * they may shadow an element or helper name. Works in both Node/Bun and the browser.*/export function buildComponent(jsxString: string, warnings: string[] = []): React.ComponentType {const trimmed = stripHTMLComments(jsxString).trim()const aliases = `const __h = React.createElement- const __frag = ''+ const __fragment = ''${elementBindings()}const svg = 'svg'${REKA_ALIASES}@@ -89,6 +90,7 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reacconst radialGradient = __helpers.radialGradientconst angularGradient = __helpers.angularGradientconst diamondGradient = __helpers.diamondGradient+ const ref = __helpers.refconst __varSymbol = Symbol.for('open-pencil.variable')const designVar = (def, value) => typeof def === 'string'? ({ [__varSymbol]: true, id: def, name: def, value })@@ -97,45 +99,13 @@ export function buildComponent(jsxString: string, warnings: string[] = []): ReacObject.entries(vars).map(([key, def]) => [key, designVar(def)]))`- const opts = {- transforms: ['typescript', 'jsx'] as Array<'typescript' | 'jsx'>,- jsxPragma: '__h',- jsxFragmentPragma: '__frag',- production: true- }-- let code: string- let siblings = false- try {- code = transform(`${aliases}\nreturn function __render() { return ${trimmed} }`, opts).code- } catch {- siblings = true- code = transform(`${aliases}\nreturn function __render() { return <>${trimmed}</> }`, opts).code- }+ const body = transformDesignJSXExpression(trimmed)// eslint-disable-next-line typescript-eslint/no-implied-eval -- sucrase output must be evaluated at runtime- const component = new Function('React', '__helpers', code)(+ return new Function('React', '__helpers', `${aliases}\nreturn function __render() {\n${body}\n}`)(React,designJSXHelpers(warnings)) as React.ComponentType- if (!siblings) return component- // Siblings are wrapped in a fragment, where a statement such as `const` is only text, so a- // name it meant to declare is undefined where the JSX uses it. An undefined name can also- // be a plain mistake, so the hint says when it applies.- return (props) => {- try {- return component(props)- } catch (error) {- if (!(error instanceof ReferenceError)) throw error- throw new Error(- `${error.message}. If a statement before the JSX, such as \`const\`, declares it, ` +- 'that statement does not run: a JSX string is one expression. Compute values inside ' +- 'it instead, for example ' +- '`{(() => { const days = […]; return days.map((day) => <Text>{day}</Text>) })()}`.',- { cause: error }- )- }- }}/**diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 6495a37f4..a0b013966 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -1,4 +1,5 @@import {+ connectorSublayers,setInstanceOverride,type Color,type NodeType,@@ -16,8 +17,10 @@ import {componentPropertyScope,inferComponentSetProperties} from './component-properties'+import { CONNECTOR_ELEMENT, renderConnectorNode, resolveConnectorEnds } from './connectors'import { elementNodeType } from './elements'import { applySizeOverrides, propsToOverrides } from './props-overrides'+import { LayerRefs } from './refs'import { prepareScalarBindings } from './scalar-bindings'import type { DesignJSXServices } from './services'import { isTextContent, TEXT_CONTENT_NAMES, textContentFields } from './text-content'@@ -53,21 +56,30 @@ export async function renderRoots<Artwork>(const parentId = options.parentId ?? graph.getPages()[0].idconst 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, options.onNode)+ 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+ childIds: node.childIds,+ ...(warnings.length > 0 && { warnings })}))}@@ -179,6 +191,21 @@ function preparePropsForRender(return { props, bindings }}+/**+ * A connector, its props resolved as any layer's are: a `designVar()` stroke colour or width+ * styles and binds the line it draws, and the rest bind the connector itself.+ */+function renderConnectorElement(graph: SceneGraph, tree: TreeNode, parentId: string): SceneNode {+ const { props, bindings } = preparePropsForRender(graph, tree.props, false, parentId)+ const connector = renderConnectorNode(graph, { ...tree, props }, parentId)+ const line = connectorSublayers(graph, connector)?.line+ for (const [field, variableId] of Object.entries(bindings)) {+ const onLine = field.startsWith('strokes/') || field === 'strokeWeight'+ graph.bindVariable(onLine && line ? line.id : connector.id, field, variableId)+ }+ return connector+}+function applyBindings(graph: SceneGraph, nodeId: string, bindings: Record<string, string>): void {for (const [field, variableId] of Object.entries(bindings)) {graph.bindVariable(nodeId, field, variableId)@@ -487,6 +514,8 @@ function renderOwnElement<Artwork>(return renderArtworkNode(services, graph, tree, parentId)case 'instance':return renderInstanceNode(graph, tree, parentId)+ case CONNECTOR_ELEMENT:+ return Promise.resolve(renderConnectorElement(graph, tree, parentId))default:return null}diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex 2af1270cf..be688d1aa 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -15,6 +15,28 @@ export const DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES = ['indent'] as const+/** Props only `<Connector>` takes. */+export const DESIGN_JSX_CONNECTOR_PROPERTY_NAMES = [+ 'from',+ 'to',+ 'fromSide',+ 'toSide',+ 'line',+ 'startCap',+ 'endCap'+] as const++/** Layer props a connector takes too: its name and the stroke of its line. */+export const DESIGN_JSX_CONNECTOR_LAYER_PROPERTY_NAMES = [+ 'name',+ 'key',+ 'visible',+ 'opacity',+ 'stroke',+ 'strokeWidth',+ 'dashPattern'+] as const+/** Props `<Span>` takes: `<Text>`'s character styles, under the same names, and a link. */export const DESIGN_JSX_SPAN_PROPERTY_NAMES = ['style',@@ -51,6 +73,7 @@ export const DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES = [export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['name','key',+ 'ref','flex','flow','dir',@@ -274,5 +297,6 @@ export const DESIGN_JSX_HELPERS: DesignJSXHelperDefinition[] = ['backgroundBlur','foregroundBlur','designVar',- 'defineVars'+ 'defineVars',+ 'ref'].map((name) => ({ name, description: `OpenPencil ${name} helper.` }))diff --git a/packages/design-jsx/src/transform.ts b/packages/design-jsx/src/transform.tsindex 6926b25ec..f817952b2 100644--- a/packages/design-jsx/src/transform.ts+++ b/packages/design-jsx/src/transform.ts@@ -1,3 +1,4 @@+import { parse } from 'acorn'import { transform } from 'sucrase'const options = {@@ -7,80 +8,66 @@ const options = {production: true}-/** The part of an authored program a JSX element was written in. */-export type DesignJSXChunk = 'statements' | 'expression'-/**- * Transformed Design JSX whose elements carry `__source: { fileName, lineNumber }` props.- * `fileName` names the chunk; adding its offset to `lineNumber` gives the 1-based line in the- * source that was passed in.+ * Transformed Design JSX: a function body that returns what the source renders. Its elements+ * carry `__source: { lineNumber }` props; adding `lineOffset` to `lineNumber` gives the 1-based+ * line in the source that was passed in.*/export interface DesignJSXProgram {code: string- lineOffsets: Readonly<Record<DesignJSXChunk, number>>+ lineOffset: number}+const RULE = 'Design JSX is one JSX expression, or statements that end with `return` and the JSX'+function lineCount(text: string): number {let lines = 0for (const char of text) if (char === '\n') lines++return lines}-function transformChunk(source: string, chunk: DesignJSXChunk | null): string {- if (!chunk) return transform(source, options).code- const { code } = transform(source, { ...options, production: false, filePath: chunk })- // Both chunks share one function body, and Sucrase declares `_jsxFileName` in each.- return chunk === 'statements' ? code.replaceAll('_jsxFileName', '_jsxStatementsFileName') : code+function transformBody(body: string, withLines: boolean): string {+ return withLines+ ? transform(body, { ...options, production: false, filePath: 'design.jsx' }).code+ : transform(body, options).code}-function transformExpression(source: string, chunk: DesignJSXChunk | null): string {- return transformChunk(`return (${source.trim()})`, chunk)-}--function statementBoundaries(source: string): number[] {- const boundaries = new Set<number>()- for (let index = 0; index < source.length; index++) {- if (source[index] === '\n') boundaries.add(index + 1)- }- return [...boundaries].sort((left, right) => right - left)+/** Whether a function body returns from its top level, as statements must end. */+function returns(code: string): boolean {+ const program = parse(code, { ecmaVersion: 'latest', allowReturnOutsideFunction: true })+ return program.body.some((statement) => statement.type === 'ReturnStatement')}+/**+ * The function body a Design JSX string stands for, tried in order: one JSX expression, sibling+ * elements, or statements that end with `return` and the JSX, as a component's body does. Each+ * keeps the source's lines where they are.+ */function transformProgram(source: string, withLines: boolean): DesignJSXProgram {- const leadingLines = lineCount(source.slice(0, source.length - source.trimStart().length))const trimmed = source.trim()- try {- return {- code: transformExpression(trimmed, withLines ? 'expression' : null),- lineOffsets: { statements: leadingLines, expression: leadingLines }- }- } catch (expressionError) {- for (const boundary of statementBoundaries(trimmed)) {- const statements = trimmed.slice(0, boundary).trim()- const rawExpression = trimmed.slice(boundary)- const expression = rawExpression.trim()- if (!statements || !expression) continue- try {- const transformedStatements = transformChunk(statements, withLines ? 'statements' : null)- const expressionStart = boundary + rawExpression.length - rawExpression.trimStart().length- return {- code: `${transformedStatements}\n${transformExpression(expression, withLines ? 'expression' : null)}`,- lineOffsets: {- statements: leadingLines,- expression: leadingLines + lineCount(trimmed.slice(0, expressionStart))- }- }- } catch {- continue- }+ const lineOffset = lineCount(source.slice(0, source.length - source.trimStart().length))+ const expressions = [`return (${trimmed})`]+ if (trimmed.startsWith('<')) expressions.push(`return (<>${trimmed}</>)`)+ for (const body of expressions) {+ try {+ return { code: transformBody(body, withLines), lineOffset }+ } catch {+ continue}- throw expressionError}+ let code: string+ try {+ code = transformBody(trimmed, withLines)+ } catch (error) {+ throw new Error(`${RULE}: ${error instanceof Error ? error.message : String(error)}`, {+ cause: error+ })+ }+ if (!returns(code)) throw new Error(`${RULE}; these statements return nothing.`)+ return { code, lineOffset }}-/**- * Transform Design JSX into a function body. A plain JSX expression is accepted directly.- * For authored programs, top-level declarations must precede a final expression on a new line.- */+/** Transform Design JSX into the body of a function that returns what it renders. */export function transformDesignJSXExpression(source: string): string {return transformProgram(source, false).code}diff --git a/packages/design-jsx/tests/enums.test.ts b/packages/design-jsx/tests/enums.test.tsindex 21a548677..90069aa31 100644--- a/packages/design-jsx/tests/enums.test.ts+++ b/packages/design-jsx/tests/enums.test.ts@@ -111,4 +111,14 @@ describe('design JSX enums', () => {expect(node.textDecorationStyle).toBe('WAVY')expect(warnings).toEqual([])})++ test('a connector cap is spelled as strokeCap spells it, and an unknown one warns', async () => {+ const { graph, warnings } = await render(+ '<Frame><Rectangle name="A" /><Rectangle name="B" /><Connector from="A" to="B" startCap="circle_filled" endCap="arrow" /></Frame>'+ )+ const connector = [...graph.getAllNodes()].find((node) => node.type === 'CONNECTOR')+ expect(connector?.connectorStartCap).toBe('CIRCLE_FILLED')+ expect(connector?.connectorEndCap).toBe('ARROW_LINES')+ expect(warnings[0]).toStartWith('Unknown endCap "arrow" on <connector> is ignored')+ })})diff --git a/packages/design-jsx/tests/schema.test.ts b/packages/design-jsx/tests/schema.test.tsindex 42bc01af4..c243db4db 100644--- a/packages/design-jsx/tests/schema.test.ts+++ b/packages/design-jsx/tests/schema.test.ts@@ -40,16 +40,16 @@ describe('Design JSX transform', () => {expect(code).toContain('__h(Text')})- test('transforms declarations followed by a final expression', () => {+ test('transforms statements that return the JSX', () => {const code = transformDesignJSXExpression(`const Card = ({ title }) => <Text>{title}</Text>-<Card title="Hello" />`+return <Card title="Hello" />`)expect(code).toContain('const Card')- expect(code).toContain('return (__h(Card')+ expect(code).toContain('return __h(Card')})- test('rejects declarations without a final expression', () => {+ test('rejects statements that return nothing', () => {expect(() => transformDesignJSXExpression('const value = 1')).toThrow()})})diff --git a/packages/design-jsx/tests/transform.test.ts b/packages/design-jsx/tests/transform.test.tsindex 062df6871..53141533d 100644--- a/packages/design-jsx/tests/transform.test.ts+++ b/packages/design-jsx/tests/transform.test.ts@@ -14,11 +14,8 @@ function locate(source: string): Located[] {const h = (type: unknown, props: Record<string, unknown> | null, ...children: unknown[]) => {if (typeof type === 'function')return (type as (props: unknown) => unknown)({ ...props, children })- const origin = props?.__source as { fileName: 'statements' | 'expression'; lineNumber: number }- located.push({- type: String(type),- line: program.lineOffsets[origin.fileName] + origin.lineNumber- })+ const origin = props?.__source as { lineNumber: number }+ located.push({ type: String(type), line: program.lineOffset + origin.lineNumber })return null}// eslint-disable-next-line typescript-eslint/no-implied-eval -- evaluates the transformed test fixture@@ -32,7 +29,7 @@ describe('transformDesignJSXProgram', () => {expect(locate(source).map(({ type, line }) => `${type}@${line}`)).toEqual(['text@4', 'frame@3'])})- test('reports lines in both declarations and the final expression of a program', () => {+ test('reports lines in both the statements and the JSX a program returns', () => {const source = ['','const Card = () => (',@@ -41,7 +38,7 @@ describe('transformDesignJSXProgram', () => {' </Frame>',')','',- '<Frame name="Root">',+ 'return <Frame name="Root">',' <Card />','</Frame>'].join('\n')diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 096ba6daf..360d4f1d7 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -27,6 +27,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.## Variables and components@@ -35,7 +36,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.-- A JSX string is one expression. 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. For longer logic, call an arrow function in place: `{(() => { const weeks = …; return weeks.map(…) })()}`; statements outside an expression do not run.+- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.@@ -102,8 +103,8 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.-**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.+**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.-**Properties:** `name`, `key`, `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`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/packages/scene-graph/src/connectors/create.ts b/packages/scene-graph/src/connectors/create.tsindex ef098c991..1d27ed027 100644--- a/packages/scene-graph/src/connectors/create.ts+++ b/packages/scene-graph/src/connectors/create.ts@@ -18,6 +18,9 @@ export interface ConnectorContent {* Makes a connector in `parentId` with its line and label, routed between its ends. Figma names* a new connector "Connector line".*/+/** The name FigJam gives a connector it draws. */+export const CONNECTOR_NAME = 'Connector line'+export function createConnector(graph: SceneGraph,parentId: string,@@ -25,7 +28,7 @@ export function createConnector(props: Partial<SceneNode> = {}): SceneNode {const connector = graph.createNode('CONNECTOR', parentId, {- name: 'Connector line',+ name: CONNECTOR_NAME,fills: [],strokes: [],connectorStart: structuredClone(content.start),diff --git a/packages/scene-graph/src/connectors/index.ts b/packages/scene-graph/src/connectors/index.tsindex 0f2ca31c1..dd2d71a5b 100644--- a/packages/scene-graph/src/connectors/index.ts+++ b/packages/scene-graph/src/connectors/index.ts@@ -1,4 +1,4 @@-export { createConnector, type ConnectorContent } from './create'+export { CONNECTOR_NAME, createConnector, type ConnectorContent } from './create'export { hitsConnectorLine } from './hit'export { CONNECTOR_LABEL_PADDING, placeConnectorLabel, type ConnectorLabelLayout } from './label'export { attachedConnectors, connectorsAffectedBy, layoutConnector } from './layout'diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 096ba6daf..360d4f1d7 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -27,6 +27,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Decorations take CSS's names and values: `textDecorationStyle` (`solid`, `dotted`, `wavy`), `textDecorationColor` (`currentColor` follows the text), `textDecorationThickness` and `textUnderlineOffset` (pixels or `auto`), and `textDecorationSkipInk`. `lineHeight="auto"` follows the font, and `fills={[]}` paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.- `Span` styles some characters of a `Text` with `Text`'s own prop names: `size`, `font`, `weight`, `italic`, `color`, `fills`, `lineHeight`, `letterSpacing`, `textDecoration`, the decoration details, and `textCase`. `href` links its characters to a URL without changing how they look. Spans nest; the inner one wins. `Paragraph` writes one paragraph: `list="ordered"` or `list="unordered"` makes it a list item nested at `level` 1–5, and `spacing`, `listSpacing`, and `indent` override the `Text`'s `paragraphSpacing`, `listSpacing`, and `paragraphIndent` for it; `hangingList` on the `Text` hangs list markers outside the text box. A `Text` holds only `Paragraph`s or none; without them, a line break in its text still starts a paragraph.- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.+- `Connector` draws a FigJam connector that follows the layers it joins: `<Connector from="Start" to="Done">Next</Connector>`. `from` and `to` name layers of the same JSX, take a `ref()` a layer is marked with (`const card = ref()`, then `<Frame ref={card}>` and `from={card}`), or give `{ x, y }` points in the connector's parent; `fromSide`/`toSide` (`top`, `right`, `bottom`, `left`) fix the side it attaches by, `line` is `elbowed` (default), `straight`, or `curved`, and `startCap`/`endCap` take the same caps as `strokeCap`: `none`, `round`, `square`, `arrow_lines`, `arrow_equilateral`, `triangle_filled`, `diamond_filled`, or `circle_filled` (it starts with none and ends with `arrow_lines`). Its text is the label; `stroke`, `strokeWidth`, and `dashPattern` style the line. When layers share a name, join them by `ref()`; a name more than one layer has joins the first, with a warning.- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.## Variables and components@@ -35,7 +36,7 @@ This reference describes scene creation, not React DOM output. Use the `render`- COLOR references work in paint props. FLOAT references work in `w`, `h`, `gap`, padding, corner radii, `strokeWidth`, `opacity`, text `size`/`fontSize`, `lineHeight`, and `letterSpacing`. Grid `columnGap`/`rowGap` and wrapped flex `rowGap` also support FLOAT references; grid `gap` overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings.- References preserve real graph bindings, not just copied values. Set the intended collection mode on the parent before creating scalar-bound content: initial scalar layout resolves that inherited mode. This does not guarantee automatic scalar layout recomputation after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.-- A JSX string is one expression. 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. For longer logic, call an arrow function in place: `{(() => { const weeks = …; return weeks.map(…) })()}`; statements outside an expression do not run.+- Build repeated or computed content with JavaScript inside `{}` rather than writing each item out: `{days.map((day) => <Text>{day}</Text>)}`, `{Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}`, and conditionals. Statements such as `const weeks = …` may come first and then end with `return` and the JSX, as a component's body does: `const weeks = 5` on one line, `return <Frame>…</Frame>` on the next.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.@@ -102,8 +103,8 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.+**Elements:** `Frame`, `Text`, `Span`, `Paragraph`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Connector`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Track`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.-**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.+**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `shader`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`, `ref`.-**Properties:** `name`, `key`, `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`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of file+**Properties:** `name`, `key`, `ref`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textDecorationStyle`, `textDecorationColor`, `textDecorationThickness`, `textUnderlineOffset`, `textDecorationSkipInk`, `textCase`, `paragraphSpacing`, `paragraphIndent`, `hangingList`, `list`, `level`, `spacing`, `listSpacing`, `indent`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/src/app/code/layers/use.ts b/src/app/code/layers/use.tsindex 0638e22de..f9f27ef23 100644--- a/src/app/code/layers/use.ts+++ b/src/app/code/layers/use.ts@@ -54,7 +54,10 @@ export function useCodeLayers(source: Readonly<Ref<CodeSource>>) {function snippet(nodeId: string): { code: string; layerIds: ReadonlyArray<string | null> } | null {- const { code, layerIds } = selectionToJSXWithLayers([nodeId], store.graph)+ // The snippet goes inside the panel's JSX, where a declaration cannot.+ const { code, layerIds } = selectionToJSXWithLayers([nodeId], store.graph, {+ declarations: false+ })return code ? { code, layerIds } : null}diff --git a/src/app/code/live-preview.ts b/src/app/code/live-preview.tsindex 04cf735ed..7f2c7373e 100644--- a/src/app/code/live-preview.ts+++ b/src/app/code/live-preview.ts@@ -90,7 +90,7 @@ export async function previewDesignJSX(let roots: TreeNode[]try {- roots = convertDesignJSXRoots(evaluated.roots, evaluated.lineOffsets)+ roots = convertDesignJSXRoots(evaluated.roots, evaluated.lineOffset)} catch (error) {return { ok: false, error: error instanceof Error ? error.message : String(error) }}diff --git a/src/app/code/sandbox/convert.ts b/src/app/code/sandbox/convert.tsindex 492ac0284..49ea868d8 100644--- a/src/app/code/sandbox/convert.ts+++ b/src/app/code/sandbox/convert.ts@@ -13,8 +13,9 @@ import {layerBlur,linearGradient,radialGradient,+ ref as layerRef,solid,- type DesignJSXProgram,+ type LayerRef,type TreeNode} from '@open-pencil/design-jsx'@@ -44,18 +45,13 @@ type SerializedDesignJSXElement = {type: stringprops: PlainRecordchildren: unknown[]- /** `[chunk, line]` from the transform, when the element's source line is known. */+ /** The line the transform reports, when the element's source line is known. */source?: unknown}-type LineOffsets = DesignJSXProgram['lineOffsets']--function sourceLine(value: unknown, lineOffsets: LineOffsets | undefined): number | undefined {- if (!lineOffsets || !Array.isArray(value) || value.length !== 2) return undefined- const [chunk, line] = value as unknown[]- if ((chunk !== 'statements' && chunk !== 'expression') || typeof line !== 'number')- return undefined- return lineOffsets[chunk] + line+function sourceLine(value: unknown, lineOffset: number | undefined): number | undefined {+ if (lineOffset === undefined || typeof value !== 'number') return undefined+ return lineOffset + value}function isRecord(value: unknown): value is PlainRecord {@@ -77,42 +73,52 @@ function isHelper(value: unknown): value is DesignJSXHelperDescriptor {)}-function convertValue(value: unknown): unknown {+/** The handle each numbered `ref()` of one evaluation stands for. */+type RefHandles = Map<unknown, LayerRef>++function convertValue(value: unknown, refs: RefHandles): unknown {if (isHelper(value)) {const helperName = value.__openPencilHelper+ if (helperName === 'ref') {+ const [number] = value.args+ const handle = refs.get(number) ?? layerRef()+ refs.set(number, handle)+ return handle+ }const helper = Object.hasOwn(HELPERS, helperName)? (HELPERS[helperName as HelperName] as (...args: unknown[]) => unknown): undefinedif (typeof helper !== 'function') {throw new TypeError(`Unknown Design JSX helper "${helperName}".`)}- return helper(...value.args.map(convertValue))+ return helper(...value.args.map((arg) => convertValue(arg, refs)))}- if (Array.isArray(value)) return value.map(convertValue)- if (isRecord(value)) return mapValues(value, (entry) => convertValue(entry))+ if (Array.isArray(value)) return value.map((item) => convertValue(item, refs))+ if (isRecord(value)) return mapValues(value, (entry) => convertValue(entry, refs))return value}-function convertTree(value: unknown, lineOffsets?: LineOffsets): TreeNode {+function convertTree(value: unknown, refs: RefHandles, lineOffset?: number): TreeNode {if (!isSerializedElement(value)) {throw new Error('Design JSX must return an OpenPencil element.')}const children = value.children.map((child): TreeNode | string => {if (typeof child === 'string') return childif (typeof child === 'number') return String(child)- return convertTree(child, lineOffsets)+ return convertTree(child, refs, lineOffset)})const tree: TreeNode = {type: value.type,- props: convertValue(value.props) as PlainRecord,+ props: convertValue(value.props, refs) as PlainRecord,children}- const line = sourceLine(value.source, lineOffsets)+ const line = sourceLine(value.source, lineOffset)if (line !== undefined) tree.source = { line }return tree}-export function convertDesignJSXRoots(values: unknown[], lineOffsets?: LineOffsets): TreeNode[] {+export function convertDesignJSXRoots(values: unknown[], lineOffset?: number): TreeNode[] {// Call validateDesignJSXOutput first; it enforces the depth bound used by this recursion.- return values.map((value) => convertTree(value, lineOffsets))+ const refs: RefHandles = new Map()+ return values.map((value) => convertTree(value, refs, lineOffset))}diff --git a/src/app/code/sandbox/document.ts b/src/app/code/sandbox/document.tsindex f4712750a..11d5a214c 100644--- a/src/app/code/sandbox/document.ts+++ b/src/app/code/sandbox/document.ts@@ -18,11 +18,14 @@ self.onmessage = ({ data }) => {if (typeof type === 'function') return type({ ...normalizedProps, children: normalizedChildren })if (type === __fragment) return normalizedChildrenconst element = { type, props: normalizedProps, children: normalizedChildren }- if (__source && typeof __source.lineNumber === 'number') element.source = [String(__source.fileName), __source.lineNumber]+ if (__source && typeof __source.lineNumber === 'number') element.source = __source.lineNumberreturn element}const helper = (name) => (...args) => ({ __openPencilHelper: name, args })+ // Each ref() is numbered, so the layer it marks and the ends that refer to it share one handle.+ let refs = 0const helperRuntime = (name) => {+ if (name === 'ref') return () => ({ __openPencilHelper: 'ref', args: [++refs] })if (name === 'defineVars') return (vars) => Object.fromEntries(Object.entries(vars).map(([key, value]) => [key, { __openPencilHelper: 'designVar', args: [value] }]))return helper(name)}diff --git a/src/app/code/sandbox/evaluate.ts b/src/app/code/sandbox/evaluate.tsindex 4a6a62292..2ee67aa35 100644--- a/src/app/code/sandbox/evaluate.ts+++ b/src/app/code/sandbox/evaluate.ts@@ -98,7 +98,7 @@ export async function evaluateDesignJSX(}try {const roots = validateDesignJSXOutput(message.value, validationLimits)- finish({ ok: true, roots, lineOffsets: program.lineOffsets })+ finish({ ok: true, roots, lineOffset: program.lineOffset })} catch (error) {finish({ ok: false, error: error instanceof Error ? error.message : String(error) })}diff --git a/src/app/code/sandbox/types.ts b/src/app/code/sandbox/types.tsindex c361e407a..9ccacd207 100644--- a/src/app/code/sandbox/types.ts+++ b/src/app/code/sandbox/types.ts@@ -50,5 +50,5 @@ export type DesignJSXHelperDescriptor = {}export type DesignJSXSandboxResult =- | { ok: true; roots: unknown[]; lineOffsets: DesignJSXProgram['lineOffsets'] }+ | { ok: true; roots: unknown[]; lineOffset: DesignJSXProgram['lineOffset'] }| { ok: false; error: string }diff --git a/tests/e2e/code/sandbox.spec.ts b/tests/e2e/code/sandbox.spec.tsindex 01f485846..df1e4dfb9 100644--- a/tests/e2e/code/sandbox.spec.ts+++ b/tests/e2e/code/sandbox.spec.ts@@ -38,11 +38,11 @@ test('evaluates JSX into plain inert data', async ({ page }) => {w: 320,fill: { __openPencilHelper: 'solid', args: ['#fff'] }},- children: [{ type: 'text', props: {}, children: ['Hello'], source: ['expression', 1] }],- source: ['expression', 1]+ children: [{ type: 'text', props: {}, children: ['Hello'], source: 1 }],+ source: 1}],- lineOffsets: { statements: 0, expression: 0 }+ lineOffset: 0})})@@ -58,10 +58,10 @@ const Card = ({ title, visible }) => ({[1, 2].map((item) => <Text>{item}</Text>)}</Frame>)-<Card title="Hello" visible />`+return <Card title="Hello" visible />`)- // Elements carry the chunk and line they were written on; the offsets map them to the source.+ // Elements carry the line they were written on; the offset maps it to the source.expect(result).toEqual({ok: true,roots: [@@ -69,14 +69,14 @@ const Card = ({ title, visible }) => (type: 'frame',props: { fill: '#fff' },children: [- { type: 'text', props: {}, children: ['Hello'], source: ['statements', 4] },- { type: 'text', props: {}, children: [1], source: ['statements', 5] },- { type: 'text', props: {}, children: [2], source: ['statements', 5] }+ { type: 'text', props: {}, children: ['Hello'], source: 4 },+ { type: 'text', props: {}, children: [1], source: 5 },+ { type: 'text', props: {}, children: [2], source: 5 }],- source: ['statements', 3]+ source: 3}],- lineOffsets: { statements: 0, expression: 7 }+ lineOffset: 0})})@@ -84,7 +84,7 @@ test('converts variable helpers without executing host capabilities', async ({ pconst result = await evaluate(page,`const vars = defineVars({ primary: { name: 'Primary', value: '#ff0000' } })-<Frame fill={vars.primary}><Text color={designVar('text', '#000')}>Hello</Text></Frame>`+return <Frame fill={vars.primary}><Text color={designVar('text', '#000')}>Hello</Text></Frame>`)expect(result.ok).toBe(true)if (!result.ok) return@@ -96,15 +96,38 @@ test('converts variable helpers without executing host capabilities', async ({ p})})+test('numbers each ref() so a layer and the ends that refer to it share it', async ({ page }) => {+ const result = await evaluate(+ page,+ `const left = ref()+const right = ref()+return <Frame>+ <Frame name="Card" ref={left} />+ <Frame name="Card" ref={right} />+ <Connector from={left} to={right} />+</Frame>`+ )+ expect(result.ok).toBe(true)+ if (!result.ok) return+ const ref = (number: number) => ({ __openPencilHelper: 'ref', args: [number] })+ expect(result.roots[0]).toMatchObject({+ children: [+ { props: { ref: ref(1) } },+ { props: { ref: ref(2) } },+ { type: 'connector', props: { from: ref(1), to: ref(2) } }+ ]+ })+})+test('supports multiple roots through fragments', async ({ page }) => {const result = await evaluate(page, '<><Rectangle name="One" /><Ellipse name="Two" /></>')expect(result).toEqual({ok: true,roots: [- { type: 'rectangle', props: { name: 'One' }, children: [], source: ['expression', 1] },- { type: 'ellipse', props: { name: 'Two' }, children: [], source: ['expression', 1] }+ { type: 'rectangle', props: { name: 'One' }, children: [], source: 1 },+ { type: 'ellipse', props: { name: 'Two' }, children: [], source: 1 }],- lineOffsets: { statements: 0, expression: 0 }+ lineOffset: 0})})diff --git a/tests/engine/app/code/sandbox.test.ts b/tests/engine/app/code/sandbox.test.tsindex efb5f1d6c..048a747c1 100644--- a/tests/engine/app/code/sandbox.test.ts+++ b/tests/engine/app/code/sandbox.test.ts@@ -1,5 +1,7 @@import { describe, expect, test } from 'bun:test'+import { isLayerRef } from '@open-pencil/design-jsx'+import { convertDesignJSXRoots } from '@/app/code/sandbox/convert'import {DESIGN_JSX_MAX_ARRAY_LENGTH,@@ -103,4 +105,17 @@ describe('Design JSX sandbox output', () => {expect(() => convertDesignJSXRoots(roots)).toThrow('Unknown Design JSX helper')}})++ test('converts each numbered ref() to one handle across the elements of an evaluation', () => {+ const marked = (number: number) => ({ __openPencilHelper: 'ref', args: [number] })+ const [first, second, connector] = convertDesignJSXRoots([+ frame({ ref: marked(1) }),+ frame({ ref: marked(2) }),+ { type: 'connector', props: { from: marked(1), to: marked(2) }, children: [] }+ ])+ expect(isLayerRef(first.props.ref)).toBe(true)+ expect(connector.props.from).toBe(first.props.ref)+ expect(connector.props.to).toBe(second.props.ref)+ expect(first.props.ref).not.toBe(second.props.ref)+ })})