Skip to content

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

JSX renderer in @open-pencil/core

Danila Poyarkov13f562adc6c1
diff --git a/bun.lock b/bun.lock
index 690dfc40a..44406136d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -31,6 +31,7 @@
"@types/node": "^25.3.2",
"@typescript/native-preview": "^7.0.0-dev.20260228.1",
"@vitejs/plugin-vue": "^6.0.4",
+ "esbuild": "^0.27.3",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"typescript": "~5.8.3",
diff --git a/package.json b/package.json
index 49b618058..b2db10056 100644
--- a/package.json
+++ b/package.json
@@ -48,6 +48,7 @@
"@types/node": "^25.3.2",
"@typescript/native-preview": "^7.0.0-dev.20260228.1",
"@vitejs/plugin-vue": "^6.0.4",
+ "esbuild": "^0.27.3",
"oxfmt": "^0.35.0",
"oxlint": "^1.50.0",
"typescript": "~5.8.3",
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5f69cd8e4..5eb008991 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -66,6 +66,36 @@ export {
} from './style-runs'
export { renderNodesToImage, renderThumbnail, type ExportFormat } from './render-image'
export { exportFigFile } from './fig-export'
+
+export {
+ renderTree,
+ renderJsx,
+ renderTreeNode,
+ buildComponent,
+ Frame,
+ Text,
+ Rectangle,
+ Ellipse,
+ Line,
+ Star,
+ Polygon,
+ Vector as VectorNode,
+ Group,
+ Section,
+ View,
+ Rect as RectNode,
+ Component as ComponentNode,
+ Instance as InstanceNode,
+ Page as PageNode,
+ INTRINSIC_ELEMENTS,
+ isTreeNode,
+ node,
+ type TreeNode,
+ type BaseProps,
+ type TextProps,
+ type StyleProps,
+ type RenderResult
+} from './render'
export {
parseFigmaClipboard,
importClipboardNodes,
diff --git a/packages/core/src/render/components.ts b/packages/core/src/render/components.ts
new file mode 100644
index 000000000..14eadbc94
--- /dev/null
+++ b/packages/core/src/render/components.ts
@@ -0,0 +1,60 @@
+import { node, type BaseProps, type TextProps, type TreeNode } from './tree'
+
+export function Frame(props: BaseProps): TreeNode {
+ return node('frame', props as Record<string, unknown>)
+}
+
+export function Text(props: TextProps): TreeNode {
+ return node('text', props as Record<string, unknown>)
+}
+
+export function Rectangle(props: BaseProps): TreeNode {
+ return node('rectangle', props as Record<string, unknown>)
+}
+
+export function Ellipse(props: BaseProps): TreeNode {
+ return node('ellipse', props as Record<string, unknown>)
+}
+
+export function Line(props: BaseProps): TreeNode {
+ return node('line', props as Record<string, unknown>)
+}
+
+export function Star(props: BaseProps & { points?: number; innerRadius?: number }): TreeNode {
+ return node('star', props as Record<string, unknown>)
+}
+
+export function Polygon(props: BaseProps & { pointCount?: number }): TreeNode {
+ return node('polygon', props as Record<string, unknown>)
+}
+
+export function Vector(props: BaseProps): TreeNode {
+ return node('vector', props as Record<string, unknown>)
+}
+
+export function Group(props: BaseProps): TreeNode {
+ return node('group', props as Record<string, unknown>)
+}
+
+export function Section(props: BaseProps): TreeNode {
+ return node('section', props as Record<string, unknown>)
+}
+
+export const View = Frame
+export const Rect = Rectangle
+export const Component = Frame
+export const Instance = Frame
+export const Page = Frame
+
+export const INTRINSIC_ELEMENTS = [
+ 'frame',
+ 'text',
+ 'rectangle',
+ 'ellipse',
+ 'line',
+ 'star',
+ 'polygon',
+ 'vector',
+ 'group',
+ 'section'
+] as const
diff --git a/packages/core/src/render/index.ts b/packages/core/src/render/index.ts
new file mode 100644
index 000000000..62d379e4f
--- /dev/null
+++ b/packages/core/src/render/index.ts
@@ -0,0 +1,24 @@
+export {
+ Frame,
+ Text,
+ Rectangle,
+ Ellipse,
+ Line,
+ Star,
+ Polygon,
+ Vector,
+ Group,
+ Section,
+ View,
+ Rect,
+ Component,
+ Instance,
+ Page,
+ INTRINSIC_ELEMENTS
+} from './components'
+
+export { type TreeNode, type BaseProps, type TextProps, type StyleProps, isTreeNode, node } from './tree'
+
+export { renderTree, type RenderResult } from './renderer'
+
+export { renderJsx, renderTreeNode, buildComponent } from './render-jsx'
diff --git a/packages/core/src/render/jsx-runtime.ts b/packages/core/src/render/jsx-runtime.ts
new file mode 100644
index 000000000..8681fc0df
--- /dev/null
+++ b/packages/core/src/render/jsx-runtime.ts
@@ -0,0 +1,36 @@
+import { node, type BaseProps, type TreeNode, type TextProps } from './tree'
+
+export function jsx(type: string | ((props: BaseProps) => TreeNode), props: BaseProps): TreeNode {
+ if (typeof type === 'function') {
+ return type(props)
+ }
+ return node(type, props as Record<string, unknown>)
+}
+
+export const jsxs = jsx
+export const jsxDEV = jsx
+
+export function Fragment({ children }: { children?: unknown }): TreeNode {
+ return node('fragment', { children } as Record<string, unknown>)
+}
+
+export namespace JSX {
+ export type Element = TreeNode
+
+ export interface IntrinsicElements {
+ frame: BaseProps
+ text: TextProps
+ rectangle: BaseProps
+ ellipse: BaseProps
+ line: BaseProps
+ star: BaseProps & { points?: number; innerRadius?: number }
+ polygon: BaseProps & { pointCount?: number }
+ vector: BaseProps
+ group: BaseProps
+ section: BaseProps
+ }
+
+ export interface ElementChildrenAttribute {
+ children: {}
+ }
+}
diff --git a/packages/core/src/render/mini-react.ts b/packages/core/src/render/mini-react.ts
new file mode 100644
index 000000000..931faa0bc
--- /dev/null
+++ b/packages/core/src/render/mini-react.ts
@@ -0,0 +1,30 @@
+export type ReactElement = {
+ type: string | Function
+ props: Record<string, unknown> & { children?: ReactNode[] }
+}
+
+export type ReactNode = ReactElement | string | number | null | undefined | ReactNode[]
+
+export type FC<P = Record<string, unknown>> = (props: P) => ReactElement
+
+export function createElement(
+ type: string | Function,
+ props: Record<string, unknown> | null,
+ ...children: ReactNode[]
+): ReactElement {
+ const flatChildren = children.flat()
+ return {
+ type,
+ props: {
+ ...props,
+ children:
+ flatChildren.length === 1
+ ? (flatChildren as ReactNode[])
+ : flatChildren.length > 0
+ ? flatChildren
+ : undefined
+ }
+ }
+}
+
+export default { createElement }
diff --git a/packages/core/src/render/render-jsx.ts b/packages/core/src/render/render-jsx.ts
new file mode 100644
index 000000000..3d567f33b
--- /dev/null
+++ b/packages/core/src/render/render-jsx.ts
@@ -0,0 +1,116 @@
+import * as React from './mini-react'
+import { isTreeNode, type TreeNode } from './tree'
+import { renderTree, type RenderResult } from './renderer'
+
+import type { SceneGraph } from '../scene-graph'
+
+interface ReactElement {
+ type: unknown
+ props: Record<string, unknown>
+}
+
+function isReactElement(x: unknown): x is ReactElement {
+ return x !== null && typeof x === 'object' && 'type' in x && 'props' in x
+}
+
+function resolveToTree(element: unknown, depth = 0): TreeNode | null {
+ if (depth > 100) throw new Error('Component resolution depth exceeded')
+ if (isTreeNode(element)) return element
+
+ if (isReactElement(element)) {
+ if (typeof element.type === 'function') {
+ return resolveToTree(
+ (element.type as (p: Record<string, unknown>) => unknown)(element.props),
+ depth + 1
+ )
+ }
+ if (typeof element.type === 'string') {
+ const children: (TreeNode | string)[] = []
+ const elChildren = element.props.children
+ if (elChildren != null) {
+ const childArray = Array.isArray(elChildren) ? elChildren : [elChildren]
+ for (const child of childArray.flat()) {
+ if (child == null) continue
+ if (typeof child === 'string' || typeof child === 'number') {
+ children.push(String(child))
+ } else {
+ const resolved = resolveToTree(child, depth + 1)
+ if (resolved) children.push(resolved)
+ }
+ }
+ }
+ const { children: _, ...props } = element.props
+ return { type: element.type, props, children }
+ }
+ }
+
+ return null
+}
+
+/**
+ * Build a component function from a JSX string using esbuild.
+ * Uses mini-react createElement — no React dependency.
+ * Only works in Node/Bun — not available in the browser.
+ */
+export async function buildComponent(jsxString: string): Promise<() => unknown> {
+ let esbuild: typeof import('esbuild')
+ try {
+ esbuild = await import('esbuild')
+ } catch {
+ throw new Error('esbuild is required for JSX string rendering. Install it or use renderTreeNode() instead.')
+ }
+
+ const code = `
+ const h = React.createElement
+ const Frame = 'frame', Text = 'text', Rectangle = 'rectangle', Ellipse = 'ellipse'
+ const Line = 'line', Star = 'star', Polygon = 'polygon', Vector = 'vector'
+ const Group = 'group', Section = 'section', View = 'frame', Rect = 'rectangle'
+ return function Component() { return ${jsxString.trim()} }
+ `
+
+ const result = esbuild.transformSync(code, {
+ loader: 'tsx',
+ jsx: 'transform',
+ jsxFactory: 'h'
+ })
+
+ return new Function('React', result.code)(React) as () => unknown
+}
+
+interface RenderJsxOptions {
+ x?: number
+ y?: number
+ parentId?: string
+}
+
+/**
+ * Render a JSX string into the scene graph.
+ * For headless/CLI use — requires esbuild.
+ */
+export async function renderJsx(
+ graph: SceneGraph,
+ jsxString: string,
+ options?: RenderJsxOptions
+): Promise<RenderResult> {
+ const Component = await buildComponent(jsxString)
+ const element = React.createElement(Component, null)
+ const tree = resolveToTree(element)
+
+ if (!tree) {
+ throw new Error('JSX must return a Figma element (Frame, Text, etc)')
+ }
+
+ return renderTree(graph, tree, options)
+}
+
+/**
+ * Render a pre-built TreeNode into the scene graph.
+ * For in-browser use — no esbuild needed, tree is built by the AI SDK tool call.
+ */
+export function renderTreeNode(
+ graph: SceneGraph,
+ tree: TreeNode,
+ options?: RenderJsxOptions
+): RenderResult {
+ return renderTree(graph, tree, options)
+}
diff --git a/packages/core/src/render/renderer.ts b/packages/core/src/render/renderer.ts
new file mode 100644
index 000000000..f9c15ebf5
--- /dev/null
+++ b/packages/core/src/render/renderer.ts
@@ -0,0 +1,334 @@
+import { parseColor, colorToFill } from '../color'
+
+import type { SceneGraph, SceneNode, NodeType, Fill, LayoutMode, Stroke } from '../scene-graph'
+import type { TreeNode } from './tree'
+import { isTreeNode } from './tree'
+
+const TYPE_MAP: Record<string, NodeType> = {
+ frame: 'FRAME',
+ view: 'FRAME',
+ rectangle: 'RECTANGLE',
+ rect: 'RECTANGLE',
+ ellipse: 'ELLIPSE',
+ text: 'TEXT',
+ line: 'LINE',
+ star: 'STAR',
+ polygon: 'POLYGON',
+ vector: 'VECTOR',
+ group: 'GROUP',
+ section: 'SECTION',
+ component: 'COMPONENT'
+}
+
+const WEIGHT_MAP: Record<string, number> = {
+ normal: 400,
+ medium: 500,
+ bold: 700
+}
+
+const ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER' | 'SPACE_BETWEEN'> = {
+ start: 'MIN',
+ end: 'MAX',
+ center: 'CENTER',
+ between: 'SPACE_BETWEEN'
+}
+
+const COUNTER_ALIGN_MAP: Record<string, 'MIN' | 'MAX' | 'CENTER'> = {
+ start: 'MIN',
+ end: 'MAX',
+ center: 'CENTER',
+ stretch: 'MIN'
+}
+
+const TEXT_ALIGN_MAP: Record<string, SceneNode['textAlignHorizontal']> = {
+ left: 'LEFT',
+ center: 'CENTER',
+ right: 'RIGHT',
+ justified: 'JUSTIFIED'
+}
+
+const TEXT_AUTO_RESIZE_MAP: Record<string, SceneNode['textAutoResize']> = {
+ none: 'NONE',
+ width: 'WIDTH_AND_HEIGHT',
+ height: 'HEIGHT'
+}
+
+function parseFill(value: string): Fill {
+ return colorToFill(value)
+}
+
+function parseStroke(value: string, width: number): Stroke {
+ const color = parseColor(value)
+ return {
+ color,
+ opacity: color.a,
+ visible: true,
+ weight: width,
+ align: 'INSIDE'
+ }
+}
+
+interface RenderOptions {
+ x?: number
+ y?: number
+ parentId?: string
+}
+
+export interface RenderResult {
+ id: string
+ name: string
+ type: NodeType
+ childIds: string[]
+}
+
+export function renderTree(
+ graph: SceneGraph,
+ tree: TreeNode,
+ options: RenderOptions = {}
+): RenderResult {
+ const parentId = options.parentId ?? graph.getPages()[0]?.id ?? graph.rootId
+
+ const result = renderNode(graph, tree, parentId)
+
+ if (options.x !== undefined) graph.updateNode(result.id, { x: options.x })
+ if (options.y !== undefined) graph.updateNode(result.id, { y: options.y })
+
+ return {
+ id: result.id,
+ name: result.name,
+ type: result.type,
+ childIds: result.childIds
+ }
+}
+
+function renderNode(graph: SceneGraph, tree: TreeNode, parentId: string): SceneNode {
+ const nodeType = TYPE_MAP[tree.type]
+ if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)
+
+ const isText = nodeType === 'TEXT'
+ const overrides = propsToOverrides(tree.props, isText)
+
+ // Text content from children
+ if (isText) {
+ const textContent = tree.children
+ .filter((c): c is string => typeof c === 'string')
+ .join('')
+ if (textContent) overrides.text = textContent
+ }
+
+ const node = graph.createNode(nodeType, parentId, overrides)
+
+ // Render child nodes (skip string children — already handled for text)
+ for (const child of tree.children) {
+ if (typeof child === 'string') continue
+ if (isTreeNode(child)) {
+ renderNode(graph, child, node.id)
+ }
+ }
+
+ return node
+}
+
+function propsToOverrides(props: Record<string, unknown>, isText: boolean): Partial<SceneNode> {
+ const o: Partial<SceneNode> = {}
+
+ // Name
+ if (props.name) o.name = props.name as string
+
+ // Size
+ const w = props.w ?? props.width
+ const h = props.h ?? props.height
+ if (typeof w === 'number') o.width = w
+ if (typeof h === 'number') o.height = h
+
+ // "fill" and "hug" sizing handled via layout sizing
+ const hasFlex = props.flex !== undefined
+ if (w === 'fill') {
+ o.layoutGrow = 1
+ o.layoutAlignSelf = 'STRETCH'
+ }
+ if (h === 'fill') {
+ o.layoutAlignSelf = 'STRETCH'
+ }
+
+ // Position
+ if (props.x !== undefined) o.x = props.x as number
+ if (props.y !== undefined) o.y = props.y as number
+
+ // Fill / background
+ const bg = props.bg ?? props.fill
+ if (typeof bg === 'string') {
+ o.fills = [parseFill(bg)]
+ }
+
+ // Stroke
+ if (typeof props.stroke === 'string') {
+ const strokeWidth = (props.strokeWidth as number) ?? 1
+ o.strokes = [parseStroke(props.stroke, strokeWidth)]
+ }
+
+ // Corner radius
+ const rounded = props.rounded ?? props.cornerRadius
+ if (typeof rounded === 'number') {
+ o.cornerRadius = rounded
+ }
+ if (props.roundedTL !== undefined || props.roundedTR !== undefined ||
+ props.roundedBL !== undefined || props.roundedBR !== undefined) {
+ o.independentCorners = true
+ if (props.roundedTL !== undefined) o.topLeftRadius = props.roundedTL as number
+ if (props.roundedTR !== undefined) o.topRightRadius = props.roundedTR as number
+ if (props.roundedBL !== undefined) o.bottomLeftRadius = props.roundedBL as number
+ if (props.roundedBR !== undefined) o.bottomRightRadius = props.roundedBR as number
+ }
+ if (props.cornerSmoothing !== undefined) o.cornerSmoothing = props.cornerSmoothing as number
+
+ // Opacity
+ if (props.opacity !== undefined) o.opacity = props.opacity as number
+
+ // Rotation
+ if (props.rotate !== undefined) o.rotation = props.rotate as number
+
+ // Blend mode
+ if (props.blendMode !== undefined) {
+ o.blendMode = (props.blendMode as string).toUpperCase() as SceneNode['blendMode']
+ }
+
+ // Overflow / clip
+ if (props.overflow === 'hidden') o.clipsContent = true
+
+ // Layout (auto-layout / flexbox)
+ if (hasFlex) {
+ const dir = props.flex as string
+ o.layoutMode = (dir === 'col' || dir === 'column' ? 'VERTICAL' : 'HORIZONTAL') as LayoutMode
+
+ // Default sizing: hug content
+ o.primaryAxisSizing = 'HUG'
+ o.counterAxisSizing = 'HUG'
+
+ // Override with explicit w/h
+ if (typeof w === 'number') o.primaryAxisSizing = 'FIXED'
+ if (typeof h === 'number') o.counterAxisSizing = 'FIXED'
+ if (w === 'hug') o.primaryAxisSizing = 'HUG'
+ if (h === 'hug') o.counterAxisSizing = 'HUG'
+ }
+
+ // Gap / spacing
+ if (props.gap !== undefined) o.itemSpacing = props.gap as number
+
+ // Wrap
+ if (props.wrap) {
+ o.layoutWrap = 'WRAP'
+ if (props.rowGap !== undefined) o.counterAxisSpacing = props.rowGap as number
+ }
+
+ // Alignment
+ if (props.justify) {
+ o.primaryAxisAlign = ALIGN_MAP[props.justify as string] ?? 'MIN'
+ }
+ if (props.items) {
+ o.counterAxisAlign = COUNTER_ALIGN_MAP[props.items as string] ?? 'MIN'
+ if (props.items === 'stretch') {
+ // Children should stretch — handled at child level
+ }
+ }
+
+ // Padding
+ const p = props.p ?? props.padding
+ if (typeof p === 'number') {
+ o.paddingTop = p
+ o.paddingRight = p
+ o.paddingBottom = p
+ o.paddingLeft = p
+ }
+ const px = props.px as number | undefined
+ const py = props.py as number | undefined
+ if (px !== undefined) { o.paddingLeft = px; o.paddingRight = px }
+ if (py !== undefined) { o.paddingTop = py; o.paddingBottom = py }
+ if (props.pt !== undefined) o.paddingTop = props.pt as number
+ if (props.pr !== undefined) o.paddingRight = props.pr as number
+ if (props.pb !== undefined) o.paddingBottom = props.pb as number
+ if (props.pl !== undefined) o.paddingLeft = props.pl as number
+
+ // Grow
+ if (props.grow !== undefined) o.layoutGrow = props.grow as number
+
+ // Min/max size — stored as-is, layout engine uses them
+ if (props.minW !== undefined) o.width = Math.max(o.width ?? 0, props.minW as number)
+ if (props.maxW !== undefined) o.width = Math.min(o.width ?? Infinity, props.maxW as number)
+
+ // Text properties
+ if (isText) {
+ const fontSize = props.size ?? props.fontSize
+ if (typeof fontSize === 'number') o.fontSize = fontSize
+
+ const fontFamily = props.font ?? props.fontFamily
+ if (typeof fontFamily === 'string') o.fontFamily = fontFamily
+
+ const weight = props.weight ?? props.fontWeight
+ if (typeof weight === 'number') {
+ o.fontWeight = weight
+ } else if (typeof weight === 'string') {
+ o.fontWeight = WEIGHT_MAP[weight] ?? 400
+ }
+
+ if (typeof props.color === 'string') {
+ o.fills = [parseFill(props.color)]
+ }
+
+ if (props.textAlign) {
+ o.textAlignHorizontal = TEXT_ALIGN_MAP[props.textAlign as string] ?? 'LEFT'
+ }
+
+ if (props.textAutoResize) {
+ o.textAutoResize = TEXT_AUTO_RESIZE_MAP[props.textAutoResize as string] ?? 'NONE'
+ } else {
+ // Default: auto-resize height for text nodes
+ o.textAutoResize = 'HEIGHT'
+ }
+ }
+
+ // Star-specific
+ if (props.points !== undefined) o.pointCount = props.points as number
+ if (props.innerRadius !== undefined) o.starInnerRadius = props.innerRadius as number
+
+ // Polygon-specific
+ if (props.pointCount !== undefined) o.pointCount = props.pointCount as number
+
+ // Stroke align
+ if (props.strokeAlign) {
+ // Stored on the stroke itself, applied during rendering
+ }
+
+ // Effects: shadow and blur
+ if (typeof props.shadow === 'string') {
+ const parts = (props.shadow as string).split(/\s+/)
+ if (parts.length >= 4) {
+ const [x, y, blur, color] = [
+ parseFloat(parts[0]!),
+ parseFloat(parts[1]!),
+ parseFloat(parts[2]!),
+ parts.slice(3).join(' ')
+ ]
+ const c = parseColor(color)
+ o.effects = [
+ ...(o.effects ?? []),
+ { type: 'DROP_SHADOW', color: c, offset: { x, y }, radius: blur, spread: 0, visible: true }
+ ]
+ }
+ }
+ if (typeof props.blur === 'number') {
+ o.effects = [
+ ...(o.effects ?? []),
+ {
+ type: 'LAYER_BLUR',
+ radius: props.blur as number,
+ visible: true,
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ offset: { x: 0, y: 0 },
+ spread: 0
+ }
+ ]
+ }
+
+ return o
+}
diff --git a/packages/core/src/render/tree.ts b/packages/core/src/render/tree.ts
new file mode 100644
index 000000000..1e5cffada
--- /dev/null
+++ b/packages/core/src/render/tree.ts
@@ -0,0 +1,139 @@
+export interface TreeNode {
+ type: string
+ props: Record<string, unknown>
+ children: (TreeNode | string)[]
+}
+
+export function isTreeNode(x: unknown): x is TreeNode {
+ if (x === null || typeof x !== 'object') return false
+ const obj = x as Record<string, unknown>
+ return typeof obj.type === 'string' && 'props' in obj && Array.isArray(obj.children)
+}
+
+interface ReactElement {
+ type: unknown
+ props: Record<string, unknown>
+}
+
+function isReactElement(x: unknown): x is ReactElement {
+ return x !== null && typeof x === 'object' && 'type' in x && 'props' in x
+}
+
+function resolveElement(el: ReactElement, depth = 0): TreeNode | null {
+ if (depth > 100) throw new Error('Component resolution depth exceeded')
+ if (isTreeNode(el)) return el
+
+ if (typeof el.type === 'function') {
+ const result = (el.type as (p: Record<string, unknown>) => unknown)(el.props)
+ if (isTreeNode(result)) return result
+ if (isReactElement(result)) return resolveElement(result, depth + 1)
+ }
+
+ if (typeof el.type === 'string') {
+ return convertToTree(el)
+ }
+
+ return null
+}
+
+function convertToTree(el: ReactElement): TreeNode {
+ const children: (TreeNode | string)[] = []
+ const elChildren = el.props.children
+
+ if (elChildren != null) {
+ const childArray = Array.isArray(elChildren) ? elChildren : [elChildren]
+ for (const child of childArray.flat()) {
+ if (child == null) continue
+ if (typeof child === 'string' || typeof child === 'number') {
+ children.push(String(child))
+ } else if (isReactElement(child)) {
+ const resolved = resolveElement(child)
+ if (resolved) children.push(resolved)
+ }
+ }
+ }
+
+ const { children: _, ...props } = el.props
+ return { type: el.type as string, props, children }
+}
+
+function processChild(child: unknown): TreeNode | string | null {
+ if (child == null) return null
+ if (typeof child === 'string' || typeof child === 'number') return String(child)
+ if (isTreeNode(child)) return child
+ if (isReactElement(child)) return resolveElement(child)
+ return null
+}
+
+export function node(type: string, props: Record<string, unknown>): TreeNode {
+ const { children, ...rest } = props
+ const processed = [children]
+ .flat(Infinity)
+ .map(processChild)
+ .filter((c): c is TreeNode | string => c !== null)
+ return { type, props: rest, children: processed }
+}
+
+export type StyleProps = {
+ flex?: 'row' | 'col' | 'column'
+ gap?: number
+ wrap?: boolean
+ rowGap?: number
+ justify?: 'start' | 'end' | 'center' | 'between'
+ items?: 'start' | 'end' | 'center' | 'stretch'
+ grow?: number
+
+ w?: number | 'fill' | 'hug'
+ h?: number | 'fill' | 'hug'
+ minW?: number
+ maxW?: number
+ minH?: number
+ maxH?: number
+
+ x?: number
+ y?: number
+
+ p?: number
+ px?: number
+ py?: number
+ pt?: number
+ pr?: number
+ pb?: number
+ pl?: number
+
+ bg?: string
+ fill?: string
+ stroke?: string
+ strokeWidth?: number
+ strokeAlign?: 'inside' | 'outside' | 'center'
+ rounded?: number
+ roundedTL?: number
+ roundedTR?: number
+ roundedBL?: number
+ roundedBR?: number
+ cornerSmoothing?: number
+ opacity?: number
+ blendMode?: string
+ rotate?: number
+ overflow?: 'hidden' | 'visible'
+ shadow?: string
+ blur?: number
+
+ size?: number
+ fontSize?: number
+ font?: string
+ fontFamily?: string
+ weight?: number | 'bold' | 'medium' | 'normal'
+ fontWeight?: number | 'bold' | 'medium' | 'normal'
+ color?: string
+ textAlign?: 'left' | 'center' | 'right' | 'justified'
+ textAutoResize?: 'none' | 'width' | 'height'
+}
+
+export type BaseProps = StyleProps & {
+ name?: string
+ key?: string | number
+ children?: unknown
+}
+
+export type TextProps = BaseProps
diff --git a/tests/engine/render.test.ts b/tests/engine/render.test.ts
new file mode 100644
index 000000000..f35125919
--- /dev/null
+++ b/tests/engine/render.test.ts
@@ -0,0 +1,357 @@
+import { describe, expect, it } from 'bun:test'
+
+import {
+ SceneGraph,
+ renderTree,
+ renderJsx,
+ renderTreeNode,
+ Frame,
+ Text,
+ Rectangle,
+ Ellipse,
+ Line,
+ Star,
+ Group,
+ Section,
+ isTreeNode,
+ node
+} from '@open-pencil/core'
+
+function createGraph(): SceneGraph {
+ const g = new SceneGraph()
+ g.addPage('Test')
+ return g
+}
+
+describe('TreeNode builders', () => {
+ it('creates Frame tree node', () => {
+ const tree = Frame({ name: 'Card', w: 320, h: 200, bg: '#FFF' })
+ expect(isTreeNode(tree)).toBe(true)
+ expect(tree.type).toBe('frame')
+ expect(tree.props.name).toBe('Card')
+ expect(tree.props.w).toBe(320)
+ expect(tree.children).toEqual([])
+ })
+
+ it('creates Text tree node with string child', () => {
+ const tree = Text({ name: 'Title', size: 18, children: 'Hello World' })
+ expect(tree.type).toBe('text')
+ expect(tree.children).toEqual(['Hello World'])
+ })
+
+ it('creates nested tree', () => {
+ const tree = Frame({
+ name: 'Card',
+ children: [
+ Rectangle({ name: 'Bg', w: 100, h: 100, bg: '#E5E7EB' }),
+ Text({ name: 'Label', size: 14, children: 'Click me' })
+ ]
+ })
+ expect(tree.children.length).toBe(2)
+ expect(isTreeNode(tree.children[0]!)).toBe(true)
+ const bg = tree.children[0] as ReturnType<typeof Rectangle>
+ expect(bg.type).toBe('rectangle')
+ expect(bg.props.name).toBe('Bg')
+ })
+
+ it('node() flattens nested arrays', () => {
+ const tree = node('frame', {
+ children: [[Text({ children: 'A' }), Text({ children: 'B' })], Text({ children: 'C' })]
+ })
+ expect(tree.children.length).toBe(3)
+ })
+
+ it('node() filters null/undefined children', () => {
+ const tree = node('frame', {
+ children: [null, Text({ children: 'A' }), undefined]
+ })
+ expect(tree.children.length).toBe(1)
+ })
+})
+
+describe('renderTree', () => {
+ it('renders a simple frame', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'MyFrame', w: 200, h: 100, bg: '#FF0000' })
+ const result = renderTree(g, tree)
+
+ expect(result.name).toBe('MyFrame')
+ expect(result.type).toBe('FRAME')
+
+ const node = g.nodes.get(result.id)!
+ expect(node.width).toBe(200)
+ expect(node.height).toBe(100)
+ expect(node.fills.length).toBe(1)
+ expect(node.fills[0]!.type).toBe('SOLID')
+ })
+
+ it('renders text node with content', () => {
+ const g = createGraph()
+ const tree = Text({ name: 'Heading', size: 24, weight: 'bold', color: '#111', children: 'Hello' })
+ const result = renderTree(g, tree)
+
+ const node = g.nodes.get(result.id)!
+ expect(node.type).toBe('TEXT')
+ expect(node.text).toBe('Hello')
+ expect(node.fontSize).toBe(24)
+ expect(node.fontWeight).toBe(700)
+ expect(node.fills.length).toBe(1)
+ })
+
+ it('renders nested structure', () => {
+ const g = createGraph()
+ const tree = Frame({
+ name: 'Card',
+ w: 320,
+ flex: 'col',
+ gap: 16,
+ p: 24,
+ bg: '#FFF',
+ children: [
+ Rectangle({ name: 'Image', w: 272, h: 200, bg: '#E5E7EB' }),
+ Text({ name: 'Title', size: 18, weight: 'bold', color: '#111', children: 'Card Title' }),
+ Text({ name: 'Description', size: 14, color: '#6B7280', children: 'Lorem ipsum' })
+ ]
+ })
+ const result = renderTree(g, tree)
+
+ const card = g.nodes.get(result.id)!
+ expect(card.layoutMode).toBe('VERTICAL')
+ expect(card.itemSpacing).toBe(16)
+ expect(card.paddingTop).toBe(24)
+ expect(card.paddingRight).toBe(24)
+ expect(card.childIds.length).toBe(3)
+
+ const title = g.nodes.get(card.childIds[1]!)!
+ expect(title.text).toBe('Card Title')
+ expect(title.fontWeight).toBe(700)
+ })
+
+ it('renders with position override', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Positioned', w: 100, h: 100 })
+ const result = renderTree(g, tree, { x: 50, y: 75 })
+
+ const node = g.nodes.get(result.id)!
+ expect(node.x).toBe(50)
+ expect(node.y).toBe(75)
+ })
+
+ it('renders into a specific parent', () => {
+ const g = createGraph()
+ const page = g.getPages()[0]!
+ const container = g.createNode('FRAME', page.id, { name: 'Container' })
+
+ const tree = Frame({ name: 'Child', w: 50, h: 50 })
+ renderTree(g, tree, { parentId: container.id })
+
+ expect(container.childIds.length).toBe(1)
+ })
+
+ it('handles auto-layout properties', () => {
+ const g = createGraph()
+ const tree = Frame({
+ name: 'Flex',
+ flex: 'row',
+ gap: 8,
+ justify: 'between',
+ items: 'center',
+ wrap: true
+ })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.layoutMode).toBe('HORIZONTAL')
+ expect(node.itemSpacing).toBe(8)
+ expect(node.primaryAxisAlign).toBe('SPACE_BETWEEN')
+ expect(node.counterAxisAlign).toBe('CENTER')
+ expect(node.layoutWrap).toBe('WRAP')
+ })
+
+ it('handles padding shorthands', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Padded', px: 16, py: 8, pt: 4 })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.paddingLeft).toBe(16)
+ expect(node.paddingRight).toBe(16)
+ expect(node.paddingBottom).toBe(8)
+ expect(node.paddingTop).toBe(4) // pt overrides py
+ })
+
+ it('handles corner radius', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Rounded', rounded: 12 })
+ const result = renderTree(g, tree)
+ expect(g.nodes.get(result.id)!.cornerRadius).toBe(12)
+ })
+
+ it('handles independent corners', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Corners', roundedTL: 8, roundedBR: 16 })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.independentCorners).toBe(true)
+ expect(node.topLeftRadius).toBe(8)
+ expect(node.bottomRightRadius).toBe(16)
+ })
+
+ it('handles stroke', () => {
+ const g = createGraph()
+ const tree = Rectangle({ name: 'Bordered', stroke: '#000', strokeWidth: 2 })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.strokes.length).toBe(1)
+ expect(node.strokes[0]!.weight).toBe(2)
+ })
+
+ it('handles opacity and rotation', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Transformed', opacity: 0.5, rotate: 45 })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.opacity).toBe(0.5)
+ expect(node.rotation).toBe(45)
+ })
+
+ it('handles overflow hidden (clip)', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Clipped', overflow: 'hidden' })
+ const result = renderTree(g, tree)
+ expect(g.nodes.get(result.id)!.clipsContent).toBe(true)
+ })
+
+ it('handles hug sizing', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Hug', w: 'hug', h: 'hug', flex: 'col' })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.primaryAxisSizing).toBe('HUG')
+ expect(node.counterAxisSizing).toBe('HUG')
+ })
+
+ it('handles fill sizing', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Fill', w: 'fill' })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.layoutGrow).toBe(1)
+ })
+
+ it('handles shadow effect', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Shadow', shadow: '0 4 12 rgba(0,0,0,0.1)' })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.effects.length).toBe(1)
+ expect(node.effects[0]!.type).toBe('DROP_SHADOW')
+ expect(node.effects[0]!.radius).toBe(12)
+ })
+
+ it('handles blur effect', () => {
+ const g = createGraph()
+ const tree = Frame({ name: 'Blurred', blur: 8 })
+ const result = renderTree(g, tree)
+ const node = g.nodes.get(result.id)!
+
+ expect(node.effects.length).toBe(1)
+ expect(node.effects[0]!.type).toBe('LAYER_BLUR')
+ expect(node.effects[0]!.radius).toBe(8)
+ })
+
+ it('renders all primitive types', () => {
+ const g = createGraph()
+ const types = [
+ { fn: Rectangle, expected: 'RECTANGLE' },
+ { fn: Ellipse, expected: 'ELLIPSE' },
+ { fn: Line, expected: 'LINE' },
+ { fn: Star, expected: 'STAR' },
+ { fn: Group, expected: 'GROUP' },
+ { fn: Section, expected: 'SECTION' }
+ ] as const
+
+ for (const { fn, expected } of types) {
+ const tree = fn({ name: expected })
+ const result = renderTree(g, tree)
+ expect(g.nodes.get(result.id)!.type).toBe(expected)
+ }
+ })
+
+ it('throws on unknown element type', () => {
+ const g = createGraph()
+ const tree = { type: 'foobar', props: {}, children: [] }
+ expect(() => renderTree(g, tree)).toThrow('Unknown element: <foobar>')
+ })
+})
+
+describe('renderTreeNode', () => {
+ it('renders pre-built tree (browser path)', () => {
+ const g = createGraph()
+ const tree = Frame({
+ name: 'FromAI',
+ w: 200,
+ h: 100,
+ bg: '#3B82F6',
+ children: [Text({ name: 'Label', size: 16, color: '#FFF', children: 'Button' })]
+ })
+ const result = renderTreeNode(g, tree)
+
+ expect(result.name).toBe('FromAI')
+ const node = g.nodes.get(result.id)!
+ expect(node.childIds.length).toBe(1)
+ const label = g.nodes.get(node.childIds[0]!)!
+ expect(label.text).toBe('Button')
+ })
+})
+
+describe('renderJsx (string → scene graph)', () => {
+ it('renders JSX string', async () => {
+ const g = createGraph()
+ const jsx = `
+ <Frame name="Test" w={200} h={100} bg="#FF0000">
+ <Text name="Hello" size={16} color="#000">World</Text>
+ </Frame>
+ `
+ const result = await renderJsx(g, jsx)
+
+ expect(result.name).toBe('Test')
+ const node = g.nodes.get(result.id)!
+ expect(node.type).toBe('FRAME')
+ expect(node.childIds.length).toBe(1)
+
+ const text = g.nodes.get(node.childIds[0]!)!
+ expect(text.text).toBe('World')
+ })
+
+ it('renders nested JSX', async () => {
+ const g = createGraph()
+ const jsx = `
+ <Frame name="Card" w={320} flex="col" gap={16} p={24} bg="#FFF" rounded={16}>
+ <Rectangle name="Image" w={272} h={200} bg="#E5E7EB" rounded={12} />
+ <Text name="Title" size={18} weight="bold" color="#111">Card Title</Text>
+ <Text name="Description" size={14} color="#6B7280">Lorem ipsum</Text>
+ </Frame>
+ `
+ const result = await renderJsx(g, jsx)
+ const card = g.nodes.get(result.id)!
+
+ expect(card.layoutMode).toBe('VERTICAL')
+ expect(card.childIds.length).toBe(3)
+ })
+
+ it('renders with position', async () => {
+ const g = createGraph()
+ const result = await renderJsx(g, '<Frame name="At" w={50} h={50} />', { x: 100, y: 200 })
+ const node = g.nodes.get(result.id)!
+
+ expect(node.x).toBe(100)
+ expect(node.y).toBe(200)
+ })
+})