Skip to content

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

fix(design-jsx): teach repeated content with JavaScript, and explain statement errors (#1079)

Danila Poyarkovfe1152ab8e6c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 930a96b00..2a9c247d3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -170,6 +170,7 @@
- Keep the Share button labeled Share while you are in a room, instead of turning it into a Connected status; a green dot on your avatar shows the room is live.
- Show Flatten, Outline text, and Outline stroke in the canvas context menu without icons, like every other item there.
- The AI chat starts with more tools turned on: comments (`get_comments`, `add_comment`, `reply_to_comment`, `resolve_comment`), variables (`list_variables`, `create_collection`, `create_variable`, `set_variable`, `bind_variable`), `lint` and `lint_fix`, `export_image` to look at its result, and `list_pages` and `create_page`. Before, it could reach these only through `eval` or after turning them on under Settings → Tool access, so when asked for a comment, it drew a note layer instead. Tools you turned off stay off.
+- The design JSX reference, which the AI chat, MCP clients, and the agent skill read, says to build repeated content such as a calendar's days with JavaScript inside `{}`, `{days.map(…)}` or `Array.from(…)`, instead of writing each item out. When JSX with several top-level elements uses an undefined name, the error now adds that a statement such as `const` before the JSX does not run, and how to compute the value inside it, instead of only `days is not defined`.
- Keep an AI chat working on the page where it started when you switch to another page, instead of sending its next edits to whichever page is on screen. When the AI switches pages itself, your view follows.
- `openpencil://` and web `?node=` links select the layer on another page when the current page has none, switching to that page.
- Generate Tailwind JSX with the same class mapping as Tailwind HTML export, so both describe a design the same way, and write opaque colors as hex in HTML, CSS, and Tailwind output. `openpencil export -f jsx --style tailwind` now exports a whole page when no `--node` is given.
diff --git a/packages/core/tests/design-jsx/expressions.test.ts b/packages/core/tests/design-jsx/expressions.test.ts
new file mode 100644
index 000000000..8598579c0
--- /dev/null
+++ b/packages/core/tests/design-jsx/expressions.test.ts
@@ -0,0 +1,44 @@
+import { expect, test } from 'bun:test'
+
+import { getNodeOrThrow } from '#core-tests/helpers/assert'
+
+import { renderJSX } from '@open-pencil/core/design-jsx'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+async function render(jsx: string) {
+ const graph = new SceneGraph()
+ const [root] = await renderJSX(graph, jsx)
+ if (!root) throw new Error('Nothing rendered')
+ return { graph, root: getNodeOrThrow(graph, root.id) }
+}
+
+test('JavaScript inside braces builds repeated and conditional content', async () => {
+ const { graph, root } = await render(
+ `<Frame flex="row" wrap w={300}>{Array.from({ length: 35 }, (_, i) => (
+ <Frame w={36} h={36} name={i % 7 === 0 ? 'Sunday' : 'Day'} />
+ ))}</Frame>`
+ )
+ expect(root.childIds).toHaveLength(35)
+ expect(graph.getNode(root.childIds[7] ?? '')?.name).toBe('Sunday')
+})
+
+test('an arrow function called in place can hold statements', async () => {
+ const { graph, root } = await render(
+ `<Frame>{(() => {
+ const days = ['Mo', 'Tu', 'We']
+ return days.map((day) => <Text name={day}>{day}</Text>)
+ })()}</Frame>`
+ )
+ 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)
+})
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 9e5564850..30e122c9e 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -33,6 +33,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.
- 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/render.ts b/packages/design-jsx/src/render.ts
index 27ff54b34..af4b4bff9 100644
--- a/packages/design-jsx/src/render.ts
+++ b/packages/design-jsx/src/render.ts
@@ -121,17 +121,37 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reac
}
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
}
// eslint-disable-next-line typescript-eslint/no-implied-eval -- sucrase output must be evaluated at runtime
- return new Function('React', '__helpers', code)(
+ const component = new Function('React', '__helpers', code)(
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/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index f19e58542..fbc916d4b 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -35,6 +35,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.
- 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/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index f19e58542..fbc916d4b 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -35,6 +35,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.
- 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`.