Skip to content

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

refactor!: generate Tailwind JSX through dom-css (#763)

Danila Poyarkov9bc353587f47
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c30e3b142..acfc09005 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
### Breaking changes
- The desktop app now requires macOS 13 or later; the web app supports Chrome 111, Edge 111, Firefox 128, and Safari 16.4 or later.
+- `sceneNodeToJSX` and `selectionToJSX` in `@open-pencil/core` produce only OpenPencil JSX, and `JSXFormat` and `JSXExportOptions` are removed. For Tailwind JSX, use `sceneNodesToTailwindJSX(graph, nodeIds)` from `@open-pencil/dom-css` or `@open-pencil/dom-css/browser`.
### Added
@@ -12,10 +13,12 @@
### Changed
+- 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.
- Show download progress with a percentage and transferred size while installing a desktop update, instead of an indeterminate message that lasted until the restart.
### Fixed
+- Keep grid layouts, rotation, inner shadows, every shadow of a layer, layer and background blur, flex grow, right-to-left direction, and sections in HTML export, which previously turned grids into columns and dropped the rest.
- Show what to update instead of a blank window when the browser or system WebView is too old, naming the detected macOS, Safari, Chrome, Edge, Firefox, WebKitGTK, or WebView2 version and linking a prefilled bug report, and explain a failed start the same way (#744).
- Start on macOS 13 with WebKit older than Safari 17.4, which previously failed with `Promise.withResolvers is not a function` (#744).
- Evaluate the `**` operator in the AI and MCP `calc` tool, which its own description advertised but which the tool rejected. `calc` now accepts exactly the arithmetic it documents — `+ - * / % **`, parentheses and `min max floor ceil round abs sqrt pow` — and no longer evaluates undocumented expressions such as `random()`, factorials, trigonometry, strings, arrays, or property access.
diff --git a/bun.lock b/bun.lock
index 46e1b67d7..b67ed4311 100644
--- a/bun.lock
+++ b/bun.lock
@@ -247,6 +247,7 @@
"version": "0.15.1",
"dependencies": {
"@acemir/cssom": "^0.9.31",
+ "esrap": "^2.3.11",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
"tailwindcss": "^4.3.3",
@@ -2671,6 +2672,8 @@
"esquery": ["[email protected]", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="],
+ "esrap": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" }, "peerDependencies": { "@typescript-eslint/types": "^8.2.0" }, "optionalPeers": ["@typescript-eslint/types"] }, "sha512-Dc8aMY0tqJNIN3ahtccEm/UWma05Mt/N7NBGdTMtJ1bR5SyctNEFVaOUfmkzVXe6Psk8MPfiiqUafXIoMbWCsQ=="],
+
"esrecurse": ["[email protected]", "", { "dependencies": { "estraverse": "^5.2.0" } }, "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag=="],
"estraverse": ["[email protected]", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="],
diff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.ts
index 41d494ad0..780d638f4 100644
--- a/packages/cli/src/commands/export.ts
+++ b/packages/cli/src/commands/export.ts
@@ -7,6 +7,7 @@ import { decodeBase64 } from '@open-pencil/core/bytes'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
import {
exportHTMLBundle,
+ sceneNodesToTailwindJSX,
sceneGraphToDesignDocument,
type ExportHTMLBundleOptions
} from '@open-pencil/dom-css'
@@ -139,6 +140,23 @@ async function writeHTMLFiles(
if (assetFiles.length > 0) console.log(ok(`Assets: ${assetFiles.length} files`))
}
+async function exportTailwindJSXFromFile(
+ args: ExportArgs,
+ graph: Awaited<ReturnType<typeof loadDocument>>,
+ target: FileExportTarget,
+ defaultName: string
+) {
+ const nodeIds =
+ target.scope === 'node' ? [target.nodeId] : (graph.getNode(target.pageId)?.childIds ?? [])
+ const jsx = sceneNodesToTailwindJSX(graph, nodeIds)
+ if (!jsx) {
+ printError('Nothing to export.')
+ process.exit(1)
+ }
+ await writeAndLog(resolve(args.output ?? exportFileName(defaultName, 'jsx')), jsx)
+ console.log(ok(`Target: ${targetLabel(args.page, args.node)}`))
+}
+
async function exportHTMLFromFile(
args: ExportArgs,
graph: Awaited<ReturnType<typeof loadDocument>>,
@@ -243,9 +261,13 @@ async function exportFromFile(format: string, args: ExportArgs) {
return
}
- if (format === 'JSX') {
- options = { format: args.style }
- } else if (format === 'FIG') {
+ // Tailwind JSX is projected through DOM/CSS, like HTML; OpenPencil JSX is a Core adapter.
+ if (format === 'JSX' && args.style === 'tailwind') {
+ await exportTailwindJSXFromFile(args, graph, target, defaultName)
+ return
+ }
+
+ if (format === 'FIG') {
options = { renderThumbnail: true }
} else if (formatSupportsScale(format)) {
options = {
diff --git a/packages/core/src/design-jsx/index.ts b/packages/core/src/design-jsx/index.ts
index 70cdebdf9..8160262a1 100644
--- a/packages/core/src/design-jsx/index.ts
+++ b/packages/core/src/design-jsx/index.ts
@@ -74,5 +74,5 @@ export {
} from './schema'
export { transformDesignJSXExpression } from './transform'
-export { sceneNodeToJSX, selectionToJSX, type JSXFormat } from '#core/io/formats/jsx'
+export { sceneNodeToJSX, selectionToJSX } from '#core/io/formats/jsx'
export { JSX_REFERENCE, AUTHORING_EXAMPLES, type AuthoringExample } from './reference'
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e6b058571..3d94ade45 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -367,8 +367,7 @@ export {
type VarDef,
type RenderResult,
sceneNodeToJSX,
- selectionToJSX,
- type JSXFormat
+ selectionToJSX
} from './design-jsx'
export {
parseFigmaClipboard,
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 223adfa6e..90a386e11 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -13,7 +13,6 @@ import type {
FigWriteOptions,
IOContext,
IOFormatAdapter,
- JSXExportOptions,
RasterExportOptions,
SVGExportOptions
} from './types'
@@ -350,14 +349,13 @@ export const jsxFormat: IOFormatAdapter<'jsx'> = {
scale: false,
quality: false
},
- async exportContent(request, options?: JSXExportOptions): Promise<ExportResult> {
- const format = options?.format ?? 'openpencil'
+ async exportContent(request): Promise<ExportResult> {
const nodeId = ensureSingleNode(request.target)
let data = ''
if (nodeId) {
- data = sceneNodeToJSX(nodeId, request.graph, format)
+ data = sceneNodeToJSX(nodeId, request.graph)
} else if (request.target.scope === 'selection') {
- data = selectionToJSX(request.target.nodeIds, request.graph, format)
+ data = selectionToJSX(request.target.nodeIds, request.graph)
}
if (!data) throw new Error('Nothing to export')
return {
diff --git a/packages/core/src/io/formats/jsx/export.ts b/packages/core/src/io/formats/jsx/export.ts
index f61d57999..13a3c840d 100644
--- a/packages/core/src/io/formats/jsx/export.ts
+++ b/packages/core/src/io/formats/jsx/export.ts
@@ -15,9 +15,6 @@ import {
solidFillColor,
solidStroke
} from './helpers'
-import { collectTailwindClasses } from './tailwind-classes'
-
-export type JSXFormat = 'openpencil' | 'tailwind'
const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
FRAME: 'Frame',
@@ -36,23 +33,6 @@ const NODE_TYPE_TO_TAG: Partial<Record<NodeType, string>> = {
INSTANCE: 'Frame'
}
-const NODE_TYPE_TO_TW_TAG: Partial<Record<NodeType, string>> = {
- FRAME: 'div',
- RECTANGLE: 'div',
- ROUNDED_RECTANGLE: 'div',
- ELLIPSE: 'div',
- TEXT: 'p',
- LINE: 'div',
- STAR: 'div',
- POLYGON: 'div',
- VECTOR: 'div',
- GROUP: 'div',
- SECTION: 'section',
- COMPONENT: 'div',
- COMPONENT_SET: 'div',
- INSTANCE: 'div'
-}
-
// --- OpenPencil format helpers ---
function collectGridSizingProps(node: SceneNode, props: [string, unknown][]): void {
@@ -298,24 +278,14 @@ function collectProps(node: SceneNode, graph: SceneGraph): [string, unknown][] {
// --- JSX rendering ---
-function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number, format: JSXFormat): string {
- const tagMap = format === 'tailwind' ? NODE_TYPE_TO_TW_TAG : NODE_TYPE_TO_TAG
- const tag = tagMap[node.type]
+function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number): string {
+ const tag = NODE_TYPE_TO_TAG[node.type]
if (!tag) return ''
const prefix = ' '.repeat(indent)
- let attrsStr: string
-
- if (format === 'tailwind') {
- const classes = collectTailwindClasses(node, graph)
- const attrs: [string, string][] = []
- if (node.name && node.name !== node.type) attrs.push(['data-name', node.name])
- if (classes.length > 0) attrs.push(['className', classes.join(' ')])
- attrsStr = attrs.map(([k, v]) => formatProp(k, v)).join(' ')
- } else {
- const props = collectProps(node, graph)
- attrsStr = props.map(([k, v]) => formatProp(k, v)).join(' ')
- }
+ const attrsStr = collectProps(node, graph)
+ .map(([k, v]) => formatProp(k, v))
+ .join(' ')
const opening = attrsStr ? `<${tag} ${attrsStr}` : `<${tag}`
const children = graph.getChildren(node.id)
@@ -338,7 +308,7 @@ function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number, format: J
const childJSX = children
.filter((c) => c.visible)
- .map((c) => nodeToJSX(c, graph, indent + 1, format))
+ .map((c) => nodeToJSX(c, graph, indent + 1))
.filter(Boolean)
if (childJSX.length === 0) return `${prefix}${opening} />`
@@ -346,23 +316,15 @@ function nodeToJSX(node: SceneNode, graph: SceneGraph, indent: number, format: J
return [`${prefix}${opening}>`, ...childJSX, `${prefix}</${tag}>`].join('\n')
}
-export function sceneNodeToJSX(
- nodeId: string,
- graph: SceneGraph,
- format: JSXFormat = 'openpencil'
-): string {
+export function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {
const node = graph.getNode(nodeId)
if (!node) return ''
- return nodeToJSX(node, graph, 0, format)
+ return nodeToJSX(node, graph, 0)
}
-export function selectionToJSX(
- nodeIds: string[],
- graph: SceneGraph,
- format: JSXFormat = 'openpencil'
-): string {
+export function selectionToJSX(nodeIds: string[], graph: SceneGraph): string {
return nodeIds
- .map((id) => sceneNodeToJSX(id, graph, format))
+ .map((id) => sceneNodeToJSX(id, graph))
.filter(Boolean)
.join('\n\n')
}
diff --git a/packages/core/src/io/formats/jsx/index.ts b/packages/core/src/io/formats/jsx/index.ts
index 50e005f10..5a4ff2dd3 100644
--- a/packages/core/src/io/formats/jsx/index.ts
+++ b/packages/core/src/io/formats/jsx/index.ts
@@ -1 +1 @@
-export { sceneNodeToJSX, selectionToJSX, type JSXFormat } from './export'
+export { sceneNodeToJSX, selectionToJSX } from './export'
diff --git a/packages/core/src/io/formats/jsx/tailwind-classes.ts b/packages/core/src/io/formats/jsx/tailwind-classes.ts
deleted file mode 100644
index 4efcebad0..000000000
--- a/packages/core/src/io/formats/jsx/tailwind-classes.ts
+++ /dev/null
@@ -1,179 +0,0 @@
-import { twirl } from 'twirlwind'
-
-import type { GridTrack, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-
-import { colorToCSSCompact } from '#core/color'
-import { DEFAULT_FONT_FAMILY } from '#core/constants'
-import { resolveNodeTextDirection } from '#core/text/direction'
-
-import { formatTrack, getNodeContext, solidFillColor, solidStroke } from './helpers'
-
-function px(v: number): string {
- return `${v}px`
-}
-
-function gridTemplateTw(tracks: GridTrack[]): string {
- const allEqual1Fr = tracks.every((t) => t.sizing === 'FR' && t.value === 1)
- if (allEqual1Fr) return String(tracks.length)
- return `[${tracks.map(formatTrack).join('_')}]`
-}
-
-function collectGridClasses(node: SceneNode): string[] {
- const classes = ['grid']
- if (node.gridTemplateColumns.length > 0)
- classes.push(`grid-cols-${gridTemplateTw(node.gridTemplateColumns)}`)
- if (node.gridTemplateRows.length > 0)
- classes.push(`grid-rows-${gridTemplateTw(node.gridTemplateRows)}`)
- return classes
-}
-
-function collectGridPositionClasses(node: SceneNode): string[] {
- if (!node.gridPosition) return []
- const classes: string[] = []
- const pos = node.gridPosition
- if (pos.column > 0) classes.push(`col-start-${pos.column}`)
- if (pos.row > 0) classes.push(`row-start-${pos.row}`)
- if (pos.columnSpan > 1) classes.push(`col-span-${pos.columnSpan}`)
- if (pos.rowSpan > 1) classes.push(`row-span-${pos.rowSpan}`)
- return classes
-}
-
-const JUSTIFY_MAP: Record<string, string> = {
- CENTER: 'center',
- MAX: 'flex-end',
- SPACE_BETWEEN: 'space-between'
-}
-
-const ALIGN_MAP: Record<string, string> = {
- CENTER: 'center',
- MAX: 'flex-end',
- STRETCH: 'stretch'
-}
-
-function applyFlexStyle(style: Record<string, string>, node: SceneNode): void {
- style.display = 'flex'
- if (node.layoutMode === 'VERTICAL') style.flexDirection = 'column'
- if (node.layoutWrap === 'WRAP') style.flexWrap = 'wrap'
- if (node.itemSpacing > 0) style.gap = px(node.itemSpacing)
- if (node.layoutWrap === 'WRAP' && node.counterAxisSpacing > 0)
- style.rowGap = px(node.counterAxisSpacing)
- if (JUSTIFY_MAP[node.primaryAxisAlign]) style.justifyContent = JUSTIFY_MAP[node.primaryAxisAlign]
- if (ALIGN_MAP[node.counterAxisAlign]) style.alignItems = ALIGN_MAP[node.counterAxisAlign]
-}
-
-function applyFlexSizing(style: Record<string, string>, node: SceneNode): void {
- const primaryAxis = node.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
- const crossAxis = node.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
- if (node.primaryAxisSizing === 'FILL') style[primaryAxis] = '100%'
- else if (node.primaryAxisSizing !== 'HUG') style[primaryAxis] = px(node[primaryAxis])
- if (node.counterAxisSizing === 'FILL') style[crossAxis] = '100%'
- else if (node.counterAxisSizing !== 'HUG') style[crossAxis] = px(node[crossAxis])
-}
-
-function applyPadding(style: Record<string, string>, node: SceneNode): void {
- const { paddingTop: pt, paddingRight: pr, paddingBottom: pb, paddingLeft: pl } = node
- if (pt === 0 && pr === 0 && pb === 0 && pl === 0) return
- if (pt === pr && pr === pb && pb === pl) style.padding = px(pt)
- else if (pt === pb && pl === pr) style.padding = `${px(pt)} ${px(pl)}`
- else style.padding = `${px(pt)} ${px(pr)} ${px(pb)} ${px(pl)}`
-}
-
-function applyLayoutStyle(style: Record<string, string>, node: SceneNode, graph: SceneGraph): void {
- const ctx = getNodeContext(node, graph)
-
- if (ctx.isGrid) {
- style.display = 'grid'
- if (node.gridColumnGap > 0) style.columnGap = px(node.gridColumnGap)
- if (node.gridRowGap > 0) style.rowGap = px(node.gridRowGap)
- if (node.width > 0) style.width = px(node.width)
- if (node.gridTemplateRows.length > 0 && node.height > 0) style.height = px(node.height)
- } else if (ctx.isFlex) {
- applyFlexStyle(style, node)
- applyFlexSizing(style, node)
- } else {
- if (node.width > 0) style.width = px(node.width)
- if (node.height > 0) style.height = px(node.height)
- }
-
- if (ctx.parentIsAutoLayout && node.layoutGrow > 0) style.flexGrow = '1'
- if (ctx.isAutoLayout) applyPadding(style, node)
-}
-
-function applyAppearanceStyle(style: Record<string, string>, node: SceneNode): void {
- const bg = solidFillColor(node.fills)
- if (bg && node.type !== 'TEXT') style.backgroundColor = bg
-
- const stroke = solidStroke(node.strokes)
- if (stroke) {
- style.borderWidth = px(stroke.weight)
- style.borderColor = stroke.color
- style.borderStyle = 'solid'
- }
-
- if (node.cornerRadius > 0) {
- if (node.independentCorners) {
- style.borderRadius = `${px(node.topLeftRadius)} ${px(node.topRightRadius)} ${px(node.bottomRightRadius)} ${px(node.bottomLeftRadius)}`
- } else {
- style.borderRadius = node.cornerRadius >= 9999 ? '9999px' : px(node.cornerRadius)
- }
- }
-
- if (node.opacity < 1) style.opacity = String(node.opacity)
- if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`
- if (node.clipsContent) style.overflow = 'hidden'
-
- for (const effect of node.effects) {
- if (!effect.visible) continue
- if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {
- const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''
- const spread = effect.spread !== 0 ? ` ${px(effect.spread)}` : ''
- const color = colorToCSSCompact(effect.color)
- style.boxShadow = `${inset}${px(effect.offset.x)} ${px(effect.offset.y)} ${px(effect.radius)}${spread} ${color}`
- } else if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR') {
- style.filter = `blur(${px(effect.radius)})`
- } else {
- style.backdropFilter = `blur(${px(effect.radius)})`
- }
- }
-}
-
-function applyTextStyle(style: Record<string, string>, node: SceneNode): void {
- if (node.type !== 'TEXT') return
- style.fontSize = px(node.fontSize)
- if (node.fontFamily && node.fontFamily !== DEFAULT_FONT_FAMILY) style.fontFamily = node.fontFamily
- if (node.fontWeight !== 400) style.fontWeight = String(node.fontWeight)
- if (node.textAlignHorizontal !== 'LEFT') style.textAlign = node.textAlignHorizontal.toLowerCase()
- const textColor = solidFillColor(node.fills)
- if (textColor) style.color = textColor
-}
-
-function nodeToStyle(node: SceneNode, graph: SceneGraph): Record<string, string> {
- const style: Record<string, string> = {}
- applyLayoutStyle(style, node, graph)
- applyAppearanceStyle(style, node)
- applyTextStyle(style, node)
- return style
-}
-
-export function collectTailwindClasses(node: SceneNode, graph: SceneGraph): string[] {
- const style = nodeToStyle(node, graph)
- const ctx = getNodeContext(node, graph)
-
- const extraClasses: string[] = []
-
- if (ctx.isGrid) extraClasses.push(...collectGridClasses(node))
- if (ctx.parentIsGrid) extraClasses.push(...collectGridPositionClasses(node))
- if (node.layoutDirection === 'RTL') extraClasses.push('[direction:rtl]')
- if (node.type === 'TEXT' && resolveNodeTextDirection(node) === 'RTL')
- extraClasses.push('[direction:rtl]')
-
- const twirlClasses = twirl(style)
- const combined = twirlClasses ? twirlClasses.split(' ') : []
-
- if (style.display === 'grid') {
- const filtered = combined.filter((c) => c !== 'grid')
- return [...extraClasses, ...filtered]
- }
-
- return [...extraClasses, ...combined]
-}
diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.ts
index c43df14d2..a1fbe3976 100644
--- a/packages/core/src/io/index.ts
+++ b/packages/core/src/io/index.ts
@@ -13,7 +13,7 @@ export {
} from './formats'
export { exportFigFile, parseFigFile, readFigFile, type ParseFigFileOptions } from './formats/fig'
export { parsePenFile, readPenFile } from '@open-pencil/pen'
-export { sceneNodeToJSX, selectionToJSX, type JSXFormat } from './formats/jsx'
+export { sceneNodeToJSX, selectionToJSX } from './formats/jsx'
export {
computeContentBounds,
renderNodesToImage,
@@ -56,7 +56,6 @@ export type {
FigWriteOptions,
RasterExportOptions,
SVGExportOptions,
- JSXExportOptions,
IOFormatSupport,
IOFormatExportOptions,
IOFormatAdapter
diff --git a/packages/core/src/io/types.ts b/packages/core/src/io/types.ts
index 8192c8dcd..455f236c6 100644
--- a/packages/core/src/io/types.ts
+++ b/packages/core/src/io/types.ts
@@ -4,7 +4,6 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import type { SkiaRenderer } from '#core/canvas'
import type { RenderColorSpace } from '#core/color/management'
-import type { JSXFormat } from '#core/design-jsx'
import type { RasterExportFormat } from './formats/raster'
@@ -82,10 +81,6 @@ export interface SVGExportOptions {
colorSpace?: RenderColorSpace
}
-export interface JSXExportOptions {
- format?: JSXFormat
-}
-
export interface ExportResult {
format: string
mimeType: string
diff --git a/packages/docs/reference/dom-css-mapping.md b/packages/docs/reference/dom-css-mapping.md
index 88c7e09dc..b979bf673 100644
--- a/packages/docs/reference/dom-css-mapping.md
+++ b/packages/docs/reference/dom-css-mapping.md
@@ -50,6 +50,23 @@ OpenPencil maps browser-computed DOM/CSS styles into SceneGraph fields through `
| `white-space: nowrap` | `maxLines = 1` | Other white-space values are not mapped yet. |
| `text-shadow` | drop shadow effect | Simple shadows only. |
+## Export
+
+HTML export, Tailwind HTML, and Tailwind JSX (`sceneNodesToTailwindJSX`) share one SceneGraph → CSS projection; Tailwind classes are derived from that CSS.
+
+| SceneGraph | CSS | Notes |
+|---|---|---|
+| auto layout | `display: flex`, `flex-direction`, gaps, padding | Row direction is the default and is not written. |
+| grid layout | `display: grid`, `grid-template-*`, gaps | Equal `1fr` tracks use `repeat(N, minmax(0, 1fr))`. |
+| grid child position | `grid-column`, `grid-row`, `*-start` | Spans are written before starts. |
+| `layoutGrow` in auto layout | `flex-grow: 1` | |
+| rotation | `transform: rotate()` | Rotates around the element center. |
+| drop and inner shadows | `box-shadow` | Every visible shadow, in order; inner shadows use `inset`. |
+| layer / background blur | `filter` / `backdrop-filter: blur()` | |
+| right-to-left layout or text | `direction: rtl` | |
+| section | `<section>` | |
+| colors | hex, or `rgba()` when translucent | Hex lets Tailwind match its palette. |
+
## Browser-oracle but not mapped yet
These values are collected or covered by browser oracle tests but do not yet have a stable SceneGraph mapping:
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index 1fb867818..a33a48ff9 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -72,6 +72,7 @@
},
"dependencies": {
"@acemir/cssom": "^0.9.31",
+ "esrap": "^2.3.11",
"parse5": "^8.0.1",
"postcss-value-parser": "^4.2.0",
"tailwindcss": "^4.3.3",
diff --git a/packages/dom-css/src/browser.ts b/packages/dom-css/src/browser.ts
index f35f73441..1e0834ab5 100644
--- a/packages/dom-css/src/browser.ts
+++ b/packages/dom-css/src/browser.ts
@@ -8,6 +8,7 @@ import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './to-scene
import type { CSSComputeOptions, DesignDocument } from './types'
export { Fragment, jsx, jsxs } from './jsx/core'
+export { designDocumentToTailwindJSX, sceneNodesToTailwindJSX } from './jsx/print'
export type { JSXChild, JSXElementProps, JSXStyleInput, JSXTag } from './jsx/core'
export interface BrowserToDesignDocumentOptions extends BrowserCSSRuntimeOptions {
diff --git a/packages/dom-css/src/css-values.ts b/packages/dom-css/src/css-values.ts
index facec3efe..cba10e0b6 100644
--- a/packages/dom-css/src/css-values.ts
+++ b/packages/dom-css/src/css-values.ts
@@ -1,6 +1,6 @@
import valueParser, { type ParsedNode } from 'postcss-value-parser'
-import { colorToCSS, parseColor } from '@open-pencil/core/color'
+import { colorToCSS, colorToHex, parseColor } from '@open-pencil/core/color'
import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/scene-graph'
import type { Color } from '@open-pencil/scene-graph/primitives'
@@ -24,9 +24,14 @@ export function parseCSSColor(value: string | undefined): Color | null {
return parseColor(trimmed)
}
+/** Opaque colors as hex, which Tailwind matches to its palette; translucent ones as `rgba()`. */
+export function cssColor(color: Color): string {
+ return color.a >= 1 ? colorToHex(color) : colorToCSS(color)
+}
+
export function fillToCSS(fill: Fill | undefined): string | undefined {
if (fill?.type !== 'SOLID' || !fill.visible) return undefined
- return colorToCSS({ ...fill.color, a: fill.opacity })
+ return cssColor({ ...fill.color, a: fill.opacity })
}
export function colorToFillFromCSS(value: string | undefined): Fill[] {
@@ -37,7 +42,7 @@ export function colorToFillFromCSS(value: string | undefined): Fill[] {
export function strokeColorToCSS(stroke: Stroke | undefined): string | undefined {
if (!stroke?.visible) return undefined
- return colorToCSS({ ...stroke.color, a: stroke.opacity })
+ return cssColor({ ...stroke.color, a: stroke.opacity })
}
export function strokeToCSS(stroke: Stroke | undefined): string | undefined {
@@ -56,9 +61,30 @@ export function colorToStrokeFromCSS(
return [{ color, weight, opacity: color.a, visible: true, align: 'INSIDE' }]
}
+function shadowToCSS(effect: Effect): string {
+ const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''
+ return `${inset}${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${cssColor(effect.color)}`
+}
+
export function dropShadowToCSS(effect: Effect | undefined): string | undefined {
if (effect?.type !== 'DROP_SHADOW' || !effect.visible) return undefined
- return `${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${colorToCSS({ ...effect.color, a: effect.color.a })}`
+ return shadowToCSS(effect)
+}
+
+/** Every visible shadow, in order, plus layer and background blur. */
+export function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {
+ const style: DesignStyleDeclaration = {}
+ const visible = effects.filter((effect) => effect.visible)
+ const shadows = visible.filter(
+ (effect) => effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
+ )
+ if (shadows.length > 0) style['box-shadow'] = shadows.map(shadowToCSS).join(', ')
+ for (const effect of visible) {
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR')
+ style.filter = `blur(${effect.radius}px)`
+ if (effect.type === 'BACKGROUND_BLUR') style['backdrop-filter'] = `blur(${effect.radius}px)`
+ }
+ return style
}
function firstShadowLayerNodes(value: string): ParsedNode[] {
diff --git a/packages/dom-css/src/from-scene-graph.ts b/packages/dom-css/src/from-scene-graph.ts
index 098ab5afc..4b4781c21 100644
--- a/packages/dom-css/src/from-scene-graph.ts
+++ b/packages/dom-css/src/from-scene-graph.ts
@@ -1,15 +1,18 @@
import { encodeBase64 } from '@open-pencil/core/bytes'
-import { colorToCSS } from '@open-pencil/core/color'
+import { resolveNodeTextDirection } from '@open-pencil/core/text'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { BLACK } from '@open-pencil/scene-graph/constants'
import {
+ cssColor,
dropShadowToCSS,
+ effectsToCSS,
fillToCSS,
sceneNodeSizeStyle,
strokeColorToCSS,
strokeToCSS
} from './css-values'
+import { addGridContainer, addGridPlacement } from './grid'
import type { DesignDocument, DesignNode, DesignStyleDeclaration } from './types'
const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'
@@ -154,7 +157,21 @@ function addImageStyle(style: DesignStyleDeclaration, node: SceneNode): void {
if (fill.imageScaleMode === 'FILL') style['object-fit'] = 'cover'
}
-function styleFromSceneNode(node: SceneNode): DesignStyleDeclaration {
+/** Styles a node takes from its parent's layout, and its own rotation. */
+function addLayoutChild(
+ style: DesignStyleDeclaration,
+ node: SceneNode,
+ parent: SceneNode | undefined
+): void {
+ if (parent?.layoutMode === 'GRID') addGridPlacement(style, node)
+ else if (parent && parent.layoutMode !== 'NONE' && node.layoutGrow > 0) style['flex-grow'] = '1'
+ if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`
+}
+
+function styleFromSceneNode(
+ node: SceneNode,
+ parent: SceneNode | undefined
+): DesignStyleDeclaration {
const style = sceneNodeSizeStyle(node)
addPositioning(style, node)
addSizeConstraints(style, node)
@@ -162,17 +179,23 @@ function styleFromSceneNode(node: SceneNode): DesignStyleDeclaration {
if (fill) style['background-color'] = fill
addImageStyle(style, node)
addStroke(style, node)
- const shadow = dropShadowToCSS(node.effects[0])
- if (shadow) style['box-shadow'] = shadow
+ Object.assign(style, effectsToCSS(node.effects))
if (node.opacity < 1) style.opacity = String(node.opacity)
addCornerRadii(style, node)
if (node.clipsContent) style.overflow = 'hidden'
const alignSelf = alignSelfToCSS(node.layoutAlignSelf)
if (alignSelf) style['align-self'] = alignSelf
- if (node.layoutMode !== 'NONE') {
+ addLayoutChild(style, node, parent)
+ if (node.layoutDirection === 'RTL') style.direction = 'rtl'
+
+ if (node.layoutMode === 'GRID') {
+ addGridContainer(style, node)
+ addPadding(style, node)
+ } else if (node.layoutMode !== 'NONE') {
style.display = 'flex'
- style['flex-direction'] = node.layoutMode === 'HORIZONTAL' ? 'row' : 'column'
+ // Row is the flexbox default.
+ if (node.layoutMode === 'VERTICAL') style['flex-direction'] = 'column'
const justifyContent = justifyContentToCSS(node.primaryAxisAlign)
const alignItems = alignItemsToCSS(node.counterAxisAlign)
if (justifyContent) style['justify-content'] = justifyContent
@@ -185,10 +208,12 @@ function styleFromSceneNode(node: SceneNode): DesignStyleDeclaration {
return style
}
-function styleFromTextNode(node: SceneNode): DesignStyleDeclaration {
+function styleFromTextNode(node: SceneNode, parent: SceneNode | undefined): DesignStyleDeclaration {
const style = sceneNodeSizeStyle(node)
addPositioning(style, node)
- style.color = fillToCSS(node.fills.at(0)) ?? colorToCSS(BLACK)
+ addLayoutChild(style, node, parent)
+ if (resolveNodeTextDirection(node) === 'RTL') style.direction = 'rtl'
+ style.color = fillToCSS(node.fills.at(0)) ?? cssColor(BLACK)
style['font-family'] = node.fontFamily
style['font-size'] = `${node.fontSize}px`
style['font-weight'] = String(node.fontWeight)
@@ -234,6 +259,7 @@ function attrsForNode(
}
function tagNameForNode(node: SceneNode): string {
+ if (node.type === 'SECTION') return 'section'
const fill = node.fills.at(0)
if ((fill?.type === 'IMAGE' || imageSourceURL(node)) && node.childIds.length === 0) return 'img'
return 'div'
@@ -245,13 +271,14 @@ function sceneNodeToDesignNode(
options: Required<SceneGraphToDesignOptions>
): DesignNode | null {
if (!node.visible || node.internalOnly) return null
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
if (node.type === 'TEXT') {
return {
type: 'element',
tagName: 'span',
attrs: attrsForNode(graph, node, options.includeSourceIds),
- inlineStyle: styleFromTextNode(node),
+ inlineStyle: styleFromTextNode(node, parent),
sourceSceneNodeId: node.id,
sourceSceneNode: node,
children: [{ type: 'text', text: node.text }]
@@ -277,7 +304,7 @@ function sceneNodeToDesignNode(
type: 'element',
tagName: tagNameForNode(node),
attrs: attrsForNode(graph, node, options.includeSourceIds),
- inlineStyle: styleFromSceneNode(node),
+ inlineStyle: styleFromSceneNode(node, parent),
sourceSceneNodeId: node.id,
sourceSceneNode: node,
children
@@ -307,4 +334,17 @@ export function sceneGraphToDesignDocument(
}
}
+/** Project one node, including its own box, instead of the children of a root. */
+export function sceneNodeToDesignDocument(
+ graph: SceneGraph,
+ nodeId: string,
+ includeSourceIds = true
+): DesignDocument {
+ const node = graph.getNode(nodeId)
+ const projected = node
+ ? sceneNodeToDesignNode(graph, node, { rootId: nodeId, includeSourceIds })
+ : null
+ return { type: 'document', sourceGraph: graph, children: projected ? [projected] : [] }
+}
+
export type { SceneGraphToDesignOptions as ToDesignDocumentOptions }
diff --git a/packages/dom-css/src/grid.ts b/packages/dom-css/src/grid.ts
new file mode 100644
index 000000000..b18ff7651
--- /dev/null
+++ b/packages/dom-css/src/grid.ts
@@ -0,0 +1,38 @@
+import type { GridTrack, SceneNode } from '@open-pencil/scene-graph'
+
+import type { DesignStyleDeclaration } from './types'
+
+function trackToCSS(track: GridTrack): string {
+ if (track.sizing === 'FR') return `${track.value}fr`
+ if (track.sizing === 'FIXED') return `${track.value}px`
+ return 'auto'
+}
+
+/** Equal `1fr` tracks use Tailwind's `grid-cols-N` form, which keeps them from overflowing. */
+function tracksToCSS(tracks: GridTrack[]): string {
+ if (tracks.every((track) => track.sizing === 'FR' && track.value === 1))
+ return `repeat(${tracks.length}, minmax(0, 1fr))`
+ return tracks.map(trackToCSS).join(' ')
+}
+
+export function addGridContainer(style: DesignStyleDeclaration, node: SceneNode): void {
+ style.display = 'grid'
+ if (node.gridTemplateColumns.length > 0)
+ style['grid-template-columns'] = tracksToCSS(node.gridTemplateColumns)
+ if (node.gridTemplateRows.length > 0)
+ style['grid-template-rows'] = tracksToCSS(node.gridTemplateRows)
+ if (node.gridColumnGap > 0) style['column-gap'] = `${node.gridColumnGap}px`
+ if (node.gridRowGap > 0) style['row-gap'] = `${node.gridRowGap}px`
+}
+
+/** A span sets the whole placement, so the start follows it. */
+export function addGridPlacement(style: DesignStyleDeclaration, node: SceneNode): void {
+ const position = node.gridPosition
+ if (!position) return
+ if (position.columnSpan > 1)
+ style['grid-column'] = `span ${position.columnSpan} / span ${position.columnSpan}`
+ if (position.column > 0) style['grid-column-start'] = String(position.column)
+ if (position.rowSpan > 1)
+ style['grid-row'] = `span ${position.rowSpan} / span ${position.rowSpan}`
+ if (position.row > 0) style['grid-row-start'] = String(position.row)
+}
diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.ts
index 296ee823d..99801b026 100644
--- a/packages/dom-css/src/index.ts
+++ b/packages/dom-css/src/index.ts
@@ -10,7 +10,8 @@ export {
tailwindHTMLToSceneGraph
} from './convert'
export { designDocumentToSceneGraph } from './to-scene-graph'
-export { sceneGraphToDesignDocument } from './from-scene-graph'
+export { sceneGraphToDesignDocument, sceneNodeToDesignDocument } from './from-scene-graph'
+export { designDocumentToTailwindJSX, sceneNodesToTailwindJSX } from './jsx/print'
export { compileTailwindCSS } from './tailwind'
export {
browserHTMLToDesignDocument,
diff --git a/packages/dom-css/src/jsx/print.ts b/packages/dom-css/src/jsx/print.ts
new file mode 100644
index 000000000..2d83f02dd
--- /dev/null
+++ b/packages/dom-css/src/jsx/print.ts
@@ -0,0 +1,115 @@
+import { print } from 'esrap'
+import tsx from 'esrap/languages/tsx'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { sceneNodeToDesignDocument } from '../from-scene-graph'
+import { mergeClassNames, serializeTailwindClasses } from '../serialize'
+import type { DesignDocument, DesignElement, DesignNode } from '../types'
+
+/** A JSX node as esrap prints it. */
+interface JSXNode {
+ type: string
+ [key: string]: unknown
+}
+
+/** HTML attribute names that JSX spells differently. */
+const JSX_ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor' }
+
+/**
+ * JSX attribute strings end at `"`, decode `&` entities, and keep backslashes literally,
+ * so the printer's escapes for backslashes and line breaks would change the value. JSX
+ * text also treats braces and angle brackets as syntax and trims whitespace at line
+ * edges. Anything else is written as a string literal, which the printer escapes.
+ */
+const LITERAL_ATTRIBUTE = /^[^"&\\\r\n]*$/
+const LITERAL_TEXT = /^[^{}<>&\n]*$/
+
+const identifier = (name: string): JSXNode => ({ type: 'JSXIdentifier', name })
+const literal = (value: string): JSXNode => ({ type: 'Literal', value })
+const expression = (value: string): JSXNode => ({
+ type: 'JSXExpressionContainer',
+ expression: literal(value)
+})
+const whitespace = (value: string): JSXNode => ({ type: 'JSXText', value, raw: value })
+
+function attribute(name: string, value: string): JSXNode {
+ return {
+ type: 'JSXAttribute',
+ name: identifier(JSX_ATTRIBUTE_NAMES[name] ?? name),
+ value: LITERAL_ATTRIBUTE.test(value) ? literal(value) : expression(value)
+ }
+}
+
+function text(value: string): JSXNode {
+ const plain = LITERAL_TEXT.test(value) && value.trim() === value && value.length > 0
+ return plain ? whitespace(value) : expression(value)
+}
+
+/** Scene text layers become paragraphs; Tailwind's preflight removes their margins. */
+function tagName(node: DesignElement): string {
+ return node.sourceSceneNode?.type === 'TEXT' ? 'p' : node.tagName
+}
+
+function attributes(node: DesignElement): JSXNode[] {
+ const { class: className, ...attrs } = node.attrs
+ const name = node.sourceSceneNode?.name
+ const entries: [string, string | undefined][] = [
+ ['data-name', name && name !== node.sourceSceneNode?.type ? name : undefined],
+ ...Object.entries(attrs),
+ ['className', mergeClassNames(className, serializeTailwindClasses(node))]
+ ]
+ return entries.flatMap(([key, value]) => (value === undefined ? [] : [attribute(key, value)]))
+}
+
+/** Children on their own lines; JSX drops whitespace-only lines between elements. */
+function indented(children: JSXNode[], depth: number): JSXNode[] {
+ const inner = `\n${' '.repeat(depth + 1)}`
+ return [
+ ...children.flatMap((child) => [whitespace(inner), child]),
+ whitespace(`\n${' '.repeat(depth)}`)
+ ]
+}
+
+function childNodes(node: DesignElement, depth: number): JSXNode[] {
+ const children = node.children.map((child) => jsxNode(child, depth + 1))
+ if (children.length === 0) return []
+ // A lone text child stays on the element's line.
+ if (children.length === 1 && node.children[0]?.type === 'text') return children
+ return indented(children, depth)
+}
+
+function element(node: DesignElement, depth: number): JSXNode {
+ const name = identifier(tagName(node))
+ const children = childNodes(node, depth)
+ return {
+ type: 'JSXElement',
+ openingElement: {
+ type: 'JSXOpeningElement',
+ name,
+ attributes: attributes(node),
+ selfClosing: children.length === 0
+ },
+ closingElement: children.length > 0 ? { type: 'JSXClosingElement', name } : null,
+ children
+ }
+}
+
+function jsxNode(node: DesignNode, depth: number): JSXNode {
+ return node.type === 'text' ? text(node.text) : element(node, depth)
+}
+
+/** Print a design document as Tailwind JSX, one top-level element per block. */
+export function designDocumentToTailwindJSX(document: DesignDocument): string {
+ return document.children
+ .map((node) => print(jsxNode(node, 0), tsx({ quotes: 'double' }), { indent: ' ' }).code)
+ .join('\n\n')
+}
+
+/** Tailwind JSX for scene nodes, separated by blank lines. */
+export function sceneNodesToTailwindJSX(graph: SceneGraph, nodeIds: string[]): string {
+ return nodeIds
+ .map((id) => designDocumentToTailwindJSX(sceneNodeToDesignDocument(graph, id, false)))
+ .filter(Boolean)
+ .join('\n\n')
+}
diff --git a/packages/dom-css/src/serialize.ts b/packages/dom-css/src/serialize.ts
index 84ac27c12..c8e7df63b 100644
--- a/packages/dom-css/src/serialize.ts
+++ b/packages/dom-css/src/serialize.ts
@@ -58,7 +58,7 @@ function serializeStyle(node: DesignElement): string | undefined {
.join('; ')
}
-function serializeTailwindClasses(node: DesignElement): string | undefined {
+export function serializeTailwindClasses(node: DesignElement): string | undefined {
const style = serializeStyle(node)
if (!style) return undefined
const className = twirl(style)
diff --git a/packages/dom-css/tests/jsx/print/appearance.test.ts b/packages/dom-css/tests/jsx/print/appearance.test.ts
new file mode 100644
index 000000000..7d6f78bbb
--- /dev/null
+++ b/packages/dom-css/tests/jsx/print/appearance.test.ts
@@ -0,0 +1,237 @@
+import { describe, expect, test } from 'bun:test'
+
+import { makeGraph, pageId, tw } from './helpers'
+
+describe('Tailwind JSX appearance classes', () => {
+ test('fill and stroke', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }],
+ strokes: [
+ {
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ weight: 2,
+ opacity: 1,
+ visible: true,
+ align: 'INSIDE' as const
+ }
+ ]
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('bg-white')
+ // twirlwind maps 2px border correctly
+ expect(jsx).toContain('border-[#FF0000]')
+ })
+
+ test('border radius — named values', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ cornerRadius: 8
+ })
+ expect(tw(graph, node.id)).toContain('rounded-lg')
+ })
+
+ test('border radius — default (4px) omits suffix', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ cornerRadius: 4
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toMatch(/rounded/)
+ })
+
+ test('border radius — full', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ cornerRadius: 9999
+ })
+ expect(tw(graph, node.id)).toContain('rounded-full')
+ })
+
+ test('border radius — arbitrary', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ cornerRadius: 5
+ })
+ expect(tw(graph, node.id)).toContain('rounded-[5px]')
+ })
+
+ test('independent corners', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 40,
+ cornerRadius: 20,
+ independentCorners: true,
+ topLeftRadius: 8,
+ topRightRadius: 0,
+ bottomRightRadius: 0,
+ bottomLeftRadius: 8
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toMatch(/rounded/)
+ expect(jsx).toMatch(/rounded/)
+ })
+
+ test('opacity and rotation', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 50,
+ height: 50,
+ opacity: 0.5,
+ rotation: 45
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('opacity-50')
+ expect(jsx).toContain('rotate-45')
+ })
+
+ test('non-standard opacity and rotation use arbitrary values', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 50,
+ height: 50,
+ opacity: 0.37,
+ rotation: 13
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('opacity-37')
+ expect(jsx).toContain('rotate-13')
+ })
+
+ test('overflow hidden', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 100,
+ height: 100,
+ clipsContent: true
+ })
+ expect(tw(graph, frame.id)).toContain('overflow-hidden')
+ })
+
+ test('shadow emits arbitrary shadow class', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ effects: [
+ {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 0.25 },
+ offset: { x: 0, y: 4 },
+ radius: 8,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ expect(tw(graph, node.id)).toMatch(/shadow-\[0px_4px_8px/)
+ })
+
+ test('inner shadow includes inset and spread', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ effects: [
+ {
+ type: 'INNER_SHADOW',
+ color: { r: 1, g: 0, b: 0, a: 0.5 },
+ offset: { x: 1, y: 2 },
+ radius: 3,
+ spread: 4,
+ visible: true
+ }
+ ]
+ })
+ expect(tw(graph, node.id)).toMatch(/shadow-\[inset_1px_2px_3px_4px/)
+ })
+
+ test('blur emits blur class', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ effects: [
+ {
+ type: 'LAYER_BLUR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ offset: { x: 0, y: 0 },
+ radius: 4,
+ spread: 0,
+ visible: true
+ }
+ ]
+ })
+ expect(tw(graph, node.id)).toContain('blur-[4px]')
+ })
+
+ test('font size — named values', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ width: 200,
+ height: 24,
+ text: 'Hello',
+ fontSize: 24,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ expect(tw(graph, node.id)).toContain('text-2xl')
+ })
+
+ test('font size — arbitrary', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ width: 200,
+ height: 24,
+ text: 'Hello',
+ fontSize: 22,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ expect(tw(graph, node.id)).toContain('text-[22px]')
+ })
+
+ test('font weight — named values', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ width: 100,
+ height: 20,
+ text: 'X',
+ fontWeight: 600
+ })
+ expect(tw(graph, node.id)).toContain('font-semibold')
+ })
+
+ test('font family keeps original spaces via arbitrary value', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ width: 100,
+ height: 20,
+ text: 'X',
+ fontFamily: 'IBM Plex Sans'
+ })
+ expect(tw(graph, node.id)).toContain('font-[IBM_Plex_Sans]')
+ })
+
+ test('white color uses named class', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ width: 100,
+ height: 20,
+ text: 'X',
+ fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('text-white')
+ expect(jsx).not.toContain('#')
+ })
+})
diff --git a/packages/dom-css/tests/jsx/print/helpers.ts b/packages/dom-css/tests/jsx/print/helpers.ts
new file mode 100644
index 000000000..e9582e5ed
--- /dev/null
+++ b/packages/dom-css/tests/jsx/print/helpers.ts
@@ -0,0 +1,17 @@
+import { sceneNodesToTailwindJSX } from '#dom-css/index'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+export function makeGraph() {
+ const graph = new SceneGraph()
+ graph.createNode('CANVAS', graph.rootId, { name: 'Page 1' })
+ return graph
+}
+
+export function pageId(graph: SceneGraph) {
+ return graph.getPages()[0].id
+}
+
+export function tw(graph: SceneGraph, nodeId: string) {
+ return sceneNodesToTailwindJSX(graph, [nodeId])
+}
diff --git a/packages/dom-css/tests/jsx/print/layout.test.ts b/packages/dom-css/tests/jsx/print/layout.test.ts
new file mode 100644
index 000000000..4d205d06e
--- /dev/null
+++ b/packages/dom-css/tests/jsx/print/layout.test.ts
@@ -0,0 +1,232 @@
+import { describe, expect, test } from 'bun:test'
+
+import { makeGraph, pageId, tw } from './helpers'
+
+describe('Tailwind JSX layout classes', () => {
+ test('spacing uses v4 multiplier (px / 4)', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 16,
+ height: 2
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('w-4')
+ expect(jsx).toContain('h-[2px]')
+ })
+
+ test('non-standard spacing falls back to arbitrary value', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 37,
+ height: 100
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('w-[37px]')
+ expect(jsx).toContain('h-25')
+ })
+
+ test('1px uses w-px', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 1,
+ height: 1
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('w-px')
+ expect(jsx).toContain('h-px')
+ })
+
+ test('auto-layout frame → flex classes', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ name: 'Row',
+ width: 400,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 16,
+ paddingTop: 12,
+ paddingRight: 12,
+ paddingBottom: 12,
+ paddingLeft: 12,
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'HUG'
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('<div')
+ expect(jsx).toContain('flex ')
+ expect(jsx).not.toContain('flex-col')
+ expect(jsx).toContain('gap-4')
+ expect(jsx).toContain('p-3')
+ expect(jsx).toContain('w-100')
+ })
+
+ test('vertical auto-layout', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 320,
+ height: 200,
+ layoutMode: 'VERTICAL',
+ itemSpacing: 8,
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'FIXED'
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('flex ')
+ expect(jsx).toContain('flex-col')
+ expect(jsx).toContain('gap-2')
+ expect(jsx).toContain('w-80')
+ })
+
+ test('asymmetric padding', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 100,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ paddingTop: 8,
+ paddingRight: 16,
+ paddingBottom: 8,
+ paddingLeft: 16,
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('py-2')
+ expect(jsx).toContain('px-4')
+ expect(jsx).not.toContain('pt-')
+ expect(jsx).not.toContain('pb-')
+ })
+
+ test('justify and items alignment', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 100,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisAlign: 'CENTER',
+ counterAxisAlign: 'CENTER',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('justify-center')
+ expect(jsx).toContain('items-center')
+ })
+
+ test('grow emits grow class', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 400,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const child = graph.createNode('RECTANGLE', frame.id, {
+ width: 100,
+ height: 50,
+ layoutGrow: 1
+ })
+ const jsx = tw(graph, child.id)
+ expect(jsx).toContain('grow')
+ })
+
+ test('wrap emits flex-wrap', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 400,
+ height: 400,
+ layoutMode: 'HORIZONTAL',
+ layoutWrap: 'WRAP',
+ counterAxisSpacing: 12,
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('flex-wrap')
+ expect(jsx).toContain('gap-y-3')
+ })
+
+ test('grid layout → grid + grid-cols + grid-rows', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ name: 'Grid',
+ width: 400,
+ height: 300,
+ layoutMode: 'GRID',
+ gridTemplateColumns: [
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 }
+ ],
+ gridTemplateRows: [
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 }
+ ],
+ gridColumnGap: 16,
+ gridRowGap: 8,
+ paddingTop: 12,
+ paddingRight: 12,
+ paddingBottom: 12,
+ paddingLeft: 12
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('grid ')
+ expect(jsx).toContain('grid-cols-3')
+ expect(jsx).toContain('grid-rows-2')
+ expect(jsx).toContain('gap-x-4')
+ expect(jsx).toContain('gap-y-2')
+ expect(jsx).toContain('p-3')
+ expect(jsx).not.toContain('flex')
+ })
+
+ test('grid with mixed tracks uses arbitrary value', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 600,
+ height: 400,
+ layoutMode: 'GRID',
+ gridTemplateColumns: [
+ { sizing: 'FIXED', value: 200 },
+ { sizing: 'FR', value: 1 },
+ { sizing: 'AUTO', value: 0 }
+ ],
+ gridTemplateRows: [],
+ gridColumnGap: 0,
+ gridRowGap: 0
+ })
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('grid-cols-[200px_1fr_auto]')
+ expect(jsx).not.toContain('grid-rows')
+ })
+
+ test('grid child placement → col-start/row-start/col-span', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ width: 400,
+ height: 300,
+ layoutMode: 'GRID',
+ gridTemplateColumns: [
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 }
+ ],
+ gridTemplateRows: [
+ { sizing: 'FR', value: 1 },
+ { sizing: 'FR', value: 1 }
+ ],
+ gridColumnGap: 0,
+ gridRowGap: 0
+ })
+ const child = graph.createNode('RECTANGLE', frame.id, {
+ name: 'Span',
+ width: 100,
+ height: 50,
+ gridPosition: { column: 1, row: 2, columnSpan: 2, rowSpan: 1 }
+ })
+ const jsx = tw(graph, child.id)
+ expect(jsx).toContain('col-start-1')
+ expect(jsx).toContain('row-start-2')
+ expect(jsx).toContain('col-span-2')
+ expect(jsx).not.toContain('row-span')
+ })
+})
diff --git a/packages/dom-css/tests/jsx/print/structure.test.ts b/packages/dom-css/tests/jsx/print/structure.test.ts
new file mode 100644
index 000000000..2c69fd80d
--- /dev/null
+++ b/packages/dom-css/tests/jsx/print/structure.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from 'bun:test'
+
+import { sceneNodesToTailwindJSX } from '#dom-css/index'
+
+import { makeGraph, pageId, tw } from './helpers'
+
+describe('Tailwind JSX structure', () => {
+ test('layer names cannot add attributes', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ name: 'a" onClick={alert(1)} x="',
+ width: 100,
+ height: 48
+ })
+ expect(tw(graph, node.id)).toStartWith(
+ '<div data-name={"a\\" onClick={alert(1)} x=\\""} className='
+ )
+ })
+
+ test('backslashes and line breaks in names use string literals', () => {
+ const graph = makeGraph()
+ const backslash = graph.createNode('RECTANGLE', pageId(graph), {
+ name: 'a\\b',
+ width: 8,
+ height: 8
+ })
+ const lines = graph.createNode('RECTANGLE', pageId(graph), {
+ name: 'two\nlines',
+ width: 8,
+ height: 8
+ })
+ expect(tw(graph, backslash.id)).toStartWith('<div data-name={"a\\\\b"} className=')
+ expect(tw(graph, lines.id)).toStartWith('<div data-name={"two\\nlines"} className=')
+ })
+
+ test('basic rectangle — div with w/h', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ name: 'Box',
+ width: 100,
+ height: 48
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('<div')
+ expect(jsx).toContain('data-name="Box"')
+ expect(jsx).toContain('w-25')
+ expect(jsx).toContain('h-12')
+ expect(jsx).not.toContain('<Rectangle')
+ })
+
+ test('text node uses <p> with text classes', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('TEXT', pageId(graph), {
+ name: 'Title',
+ width: 200,
+ height: 24,
+ text: 'Hello World',
+ fontSize: 18,
+ fontWeight: 700,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('<p')
+ expect(jsx).toContain('text-lg')
+ expect(jsx).toContain('font-bold')
+ expect(jsx).toContain('text-black')
+ expect(jsx).toContain('>Hello World</p>')
+ expect(jsx).not.toContain('<Text')
+ })
+
+ test('section uses <section> tag', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('SECTION', pageId(graph), {
+ width: 800,
+ height: 600
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).toContain('<section')
+ })
+
+ test('frame with children renders nested', () => {
+ const graph = makeGraph()
+ const frame = graph.createNode('FRAME', pageId(graph), {
+ name: 'Card',
+ width: 320,
+ height: 200,
+ layoutMode: 'VERTICAL',
+ itemSpacing: 8,
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'FIXED',
+ fills: [
+ { type: 'SOLID', color: { r: 0.95, g: 0.95, b: 0.95, a: 1 }, opacity: 1, visible: true }
+ ],
+ cornerRadius: 12
+ })
+ graph.createNode('TEXT', frame.id, {
+ name: 'Title',
+ width: 200,
+ height: 20,
+ text: 'Card Title',
+ fontSize: 16,
+ fontWeight: 700,
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+
+ const jsx = tw(graph, frame.id)
+ expect(jsx).toContain('<div')
+ expect(jsx).toContain('flex flex-col')
+ expect(jsx).toContain('gap-2')
+ expect(jsx).toMatch(/rounded/)
+ expect(jsx).toContain(' <p')
+ expect(jsx).toContain('text-base')
+ expect(jsx).toContain('font-bold')
+ expect(jsx).toContain('>Card Title</p>')
+ expect(jsx).toContain('</div>')
+ })
+
+ test('selections are separated by blank lines', () => {
+ const graph = makeGraph()
+ const a = graph.createNode('RECTANGLE', pageId(graph), {
+ name: 'A',
+ width: 40,
+ height: 40
+ })
+ const b = graph.createNode('ELLIPSE', pageId(graph), {
+ name: 'B',
+ width: 80,
+ height: 80
+ })
+ const jsx = sceneNodesToTailwindJSX(graph, [a.id, b.id])
+ expect(jsx).toContain('<div')
+ expect(jsx).not.toContain('<Rectangle')
+ expect(jsx).not.toContain('<Ellipse')
+ expect(jsx).toContain('\n\n')
+ })
+
+ test('default values are omitted', () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ width: 100,
+ height: 100,
+ opacity: 1,
+ rotation: 0,
+ cornerRadius: 0
+ })
+ const jsx = tw(graph, node.id)
+ expect(jsx).not.toContain('opacity')
+ expect(jsx).not.toContain('rotate')
+ expect(jsx).not.toContain('rounded')
+ })
+})
diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.ts
index 27dc386bd..33a31e1fd 100644
--- a/src/app/automation/bridge/export-handlers.ts
+++ b/src/app/automation/bridge/export-handlers.ts
@@ -1,5 +1,6 @@
import { encodeBase64 } from '@open-pencil/core/bytes'
-import { selectionToJSX, sceneNodeToJSX, type RasterExportFormat } from '@open-pencil/core/io'
+import { selectionToJSX, type RasterExportFormat } from '@open-pencil/core/io'
+import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/browser'
import type { AutomationTarget } from '@/app/automation/bridge/target'
@@ -24,12 +25,11 @@ export async function handleExport(target: AutomationTarget, args: unknown): Pro
export async function handleExportJSX(target: AutomationTarget, args: unknown): Promise<unknown> {
const store = target.store
const jsxArgs = args as { nodeIds?: string[]; style?: string } | undefined
- const style = (jsxArgs?.style ?? 'openpencil') as 'openpencil' | 'tailwind'
const currentPage = store.graph.getNode(target.pageId)
const nodeIds = jsxArgs?.nodeIds ?? currentPage?.childIds ?? []
const jsx =
- nodeIds.length === 1
- ? sceneNodeToJSX(nodeIds[0], store.graph, style)
- : selectionToJSX(nodeIds, store.graph, style)
+ jsxArgs?.style === 'tailwind'
+ ? sceneNodesToTailwindJSX(store.graph, nodeIds)
+ : selectionToJSX(nodeIds, store.graph)
return { ok: true, result: { jsx } }
}
diff --git a/src/app/code/generated.ts b/src/app/code/generated.ts
new file mode 100644
index 000000000..5c039892f
--- /dev/null
+++ b/src/app/code/generated.ts
@@ -0,0 +1,17 @@
+import { selectionToJSX } from '@open-pencil/core/design-jsx'
+import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/browser'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { starterSourceFor, type CodeSource } from '@/app/code/templates'
+
+/** Code shown for the selection: editable Design JSX, or read-only Tailwind JSX. */
+export function generatedSourceFor(
+ source: Exclude<CodeSource, 'html-css'>,
+ graph: SceneGraph,
+ nodeIds: string[]
+): string {
+ if (nodeIds.length === 0) return starterSourceFor(source)
+ return source === 'tailwind-jsx'
+ ? sceneNodesToTailwindJSX(graph, nodeIds)
+ : selectionToJSX(nodeIds, graph)
+}
diff --git a/src/app/document/export/files.ts b/src/app/document/export/files.ts
index 4272cd806..f6899add6 100644
--- a/src/app/document/export/files.ts
+++ b/src/app/document/export/files.ts
@@ -78,7 +78,6 @@ export function getExportOptions(format: IOFormatAdapter, options?: ExportOption
if (format.exportOptions?.scale) {
return { scale: options?.scale ?? 1, quality: options?.quality }
}
- if (format.id === 'jsx') return { format: options?.jsxFormat ?? 'openpencil' }
return undefined
}
diff --git a/src/app/document/export/types.ts b/src/app/document/export/types.ts
index 4d5c2d70b..6077c917b 100644
--- a/src/app/document/export/types.ts
+++ b/src/app/document/export/types.ts
@@ -1,5 +1,4 @@
export type ExportOptions = {
scale?: number
quality?: number
- jsxFormat?: 'openpencil' | 'tailwind'
}
diff --git a/src/components/CodePanel.vue b/src/components/CodePanel.vue
index 43f6878b2..7f930032d 100644
--- a/src/components/CodePanel.vue
+++ b/src/components/CodePanel.vue
@@ -3,7 +3,7 @@ import { useClipboard, useDebounceFn } from '@vueuse/core'
import { tv } from 'tailwind-variants'
import { computed, defineAsyncComponent, onBeforeUnmount, ref, shallowRef, watch } from 'vue'
-import { JSX_REFERENCE, selectionToJSX } from '@open-pencil/core/design-jsx'
+import { JSX_REFERENCE } from '@open-pencil/core/design-jsx'
import { useI18n, useSceneComputed } from '@open-pencil/vue'
import {
@@ -13,6 +13,7 @@ import {
resetDOMCodePreview,
type DOMCodeSession
} from '@/app/code/dom-preview'
+import { generatedSourceFor } from '@/app/code/generated'
import {
commitDesignJSXSession,
createDesignJSXEditSession,
@@ -51,13 +52,7 @@ let disposing = false
const generatedJSX = useSceneComputed(() => {
if (!editorActive.value || source.value === 'html-css' || designSession.value) return ''
void store.state.sceneVersion
- const ids = [...store.state.selectedIds]
- if (ids.length === 0) return starterSourceFor(source.value)
- return selectionToJSX(
- ids,
- store.graph,
- source.value === 'tailwind-jsx' ? 'tailwind' : 'openpencil'
- )
+ return generatedSourceFor(source.value, store.graph, [...store.state.selectedIds])
})
const sourceOptions = computed(() => [
@@ -189,9 +184,7 @@ async function changeSource(next: CodeSource): Promise<void> {
}
function generatedFor(next: Exclude<CodeSource, 'html-css'>): string {
- const ids = [...store.state.selectedIds]
- if (ids.length === 0) return starterSourceFor(next)
- return selectionToJSX(ids, store.graph, next === 'tailwind-jsx' ? 'tailwind' : 'openpencil')
+ return generatedSourceFor(next, store.graph, [...store.state.selectedIds])
}
watch(
diff --git a/tests/engine/cli/export.test.ts b/tests/engine/cli/export.test.ts
index 0a2c8bdcc..989ab5fd3 100644
--- a/tests/engine/cli/export.test.ts
+++ b/tests/engine/cli/export.test.ts
@@ -177,6 +177,29 @@ test('export CLI can write HTML styles as Tailwind classes', async () => {
expect(html).not.toContain('style=')
})
+test('export CLI writes Tailwind JSX for a page', async () => {
+ const { dir, figPath } = await createFigFixture()
+ const output = join(dir, 'card.jsx')
+
+ const { stderr, exitCode } = await runOpenPencilCLI([
+ 'export',
+ figPath,
+ '--format',
+ 'jsx',
+ '--style',
+ 'tailwind',
+ '--output',
+ output
+ ])
+
+ expect(stderr).toBe('')
+ expect(exitCode).toBe(0)
+ const jsx = await Bun.file(output).text()
+ expect(jsx).toStartWith('<div data-name="First slide" className="')
+ expect(jsx).toContain('<div data-name="Export Card" className="flex p-4 gap-2')
+ expect(jsx).not.toContain('Second Card')
+})
+
test('export CLI can write standalone HTML', async () => {
const { dir, figPath } = await createFigFixture()
const output = join(dir, 'card-standalone.html')
diff --git a/tests/engine/render/jsx/tailwind.test.ts b/tests/engine/render/jsx/tailwind.test.ts
deleted file mode 100644
index b460b38e8..000000000
--- a/tests/engine/render/jsx/tailwind.test.ts
+++ /dev/null
@@ -1,606 +0,0 @@
-import { describe, expect, test } from 'bun:test'
-
-import { SceneGraph, sceneNodeToJSX, selectionToJSX } from '@open-pencil/core'
-
-function makeGraph() {
- const graph = new SceneGraph()
- graph.createNode('CANVAS', graph.rootId, { name: 'Page 1' })
- return graph
-}
-
-function pageId(graph: SceneGraph) {
- return graph.getPages()[0].id
-}
-
-function tw(graph: SceneGraph, nodeId: string) {
- return sceneNodeToJSX(nodeId, graph, 'tailwind')
-}
-
-describe('Tailwind JSX export', () => {
- test('layer names cannot add attributes', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- name: 'a" onClick={alert(1)} x="',
- width: 100,
- height: 48
- })
- expect(tw(graph, node.id)).toStartWith(
- '<div data-name={"a\\" onClick={alert(1)} x=\\""} className='
- )
- })
-
- test('basic rectangle — div with w/h', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- name: 'Box',
- width: 100,
- height: 48
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('<div')
- expect(jsx).toContain('data-name="Box"')
- expect(jsx).toContain('w-25')
- expect(jsx).toContain('h-12')
- expect(jsx).not.toContain('<Rectangle')
- })
-
- test('spacing uses v4 multiplier (px / 4)', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 16,
- height: 2
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('w-4')
- expect(jsx).toContain('h-[2px]')
- })
-
- test('non-standard spacing falls back to arbitrary value', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 37,
- height: 100
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('w-[37px]')
- expect(jsx).toContain('h-25')
- })
-
- test('1px uses w-px', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 1,
- height: 1
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('w-px')
- expect(jsx).toContain('h-px')
- })
-
- test('fill and stroke', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }],
- strokes: [
- {
- color: { r: 1, g: 0, b: 0, a: 1 },
- weight: 2,
- opacity: 1,
- visible: true,
- align: 'INSIDE' as const
- }
- ]
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('bg-white')
- // twirlwind maps 2px border correctly
- expect(jsx).toContain('border-[#FF0000]')
- })
-
- test('text node uses <p> with text classes', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- name: 'Title',
- width: 200,
- height: 24,
- text: 'Hello World',
- fontSize: 18,
- fontWeight: 700,
- fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('<p')
- expect(jsx).toContain('text-lg')
- expect(jsx).toContain('font-bold')
- expect(jsx).toContain('text-black')
- expect(jsx).toContain('>Hello World</p>')
- expect(jsx).not.toContain('<Text')
- })
-
- test('auto-layout frame → flex classes', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- name: 'Row',
- width: 400,
- height: 100,
- layoutMode: 'HORIZONTAL',
- itemSpacing: 16,
- paddingTop: 12,
- paddingRight: 12,
- paddingBottom: 12,
- paddingLeft: 12,
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'HUG'
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('<div')
- expect(jsx).toContain('flex ')
- expect(jsx).not.toContain('flex-col')
- expect(jsx).toContain('gap-4')
- expect(jsx).toContain('p-3')
- expect(jsx).toContain('w-100')
- })
-
- test('vertical auto-layout', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 320,
- height: 200,
- layoutMode: 'VERTICAL',
- itemSpacing: 8,
- primaryAxisSizing: 'HUG',
- counterAxisSizing: 'FIXED'
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('flex ')
- expect(jsx).toContain('flex-col')
- expect(jsx).toContain('gap-2')
- expect(jsx).toContain('w-80')
- })
-
- test('asymmetric padding', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 100,
- height: 100,
- layoutMode: 'HORIZONTAL',
- paddingTop: 8,
- paddingRight: 16,
- paddingBottom: 8,
- paddingLeft: 16,
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'FIXED'
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('py-2')
- expect(jsx).toContain('px-4')
- expect(jsx).not.toContain('pt-')
- expect(jsx).not.toContain('pb-')
- })
-
- test('justify and items alignment', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 100,
- height: 100,
- layoutMode: 'HORIZONTAL',
- primaryAxisAlign: 'CENTER',
- counterAxisAlign: 'CENTER',
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'FIXED'
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('justify-center')
- expect(jsx).toContain('items-center')
- })
-
- test('border radius — named values', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- cornerRadius: 8
- })
- expect(tw(graph, node.id)).toContain('rounded-lg')
- })
-
- test('border radius — default (4px) omits suffix', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- cornerRadius: 4
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toMatch(/rounded/)
- })
-
- test('border radius — full', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- cornerRadius: 9999
- })
- expect(tw(graph, node.id)).toContain('rounded-full')
- })
-
- test('border radius — arbitrary', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- cornerRadius: 5
- })
- expect(tw(graph, node.id)).toContain('rounded-[5px]')
- })
-
- test('independent corners', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 40,
- cornerRadius: 20,
- independentCorners: true,
- topLeftRadius: 8,
- topRightRadius: 0,
- bottomRightRadius: 0,
- bottomLeftRadius: 8
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toMatch(/rounded/)
- expect(jsx).toMatch(/rounded/)
- })
-
- test('opacity and rotation', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 50,
- height: 50,
- opacity: 0.5,
- rotation: 45
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('opacity-50')
- expect(jsx).toContain('rotate-45')
- })
-
- test('non-standard opacity and rotation use arbitrary values', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 50,
- height: 50,
- opacity: 0.37,
- rotation: 13
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('opacity-37')
- expect(jsx).toContain('rotate-13')
- })
-
- test('overflow hidden', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 100,
- height: 100,
- clipsContent: true
- })
- expect(tw(graph, frame.id)).toContain('overflow-hidden')
- })
-
- test('shadow emits arbitrary shadow class', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- effects: [
- {
- type: 'DROP_SHADOW',
- color: { r: 0, g: 0, b: 0, a: 0.25 },
- offset: { x: 0, y: 4 },
- radius: 8,
- spread: 0,
- visible: true
- }
- ]
- })
- expect(tw(graph, node.id)).toMatch(/shadow-\[0px_4px_8px/)
- })
-
- test('inner shadow includes inset and spread', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- effects: [
- {
- type: 'INNER_SHADOW',
- color: { r: 1, g: 0, b: 0, a: 0.5 },
- offset: { x: 1, y: 2 },
- radius: 3,
- spread: 4,
- visible: true
- }
- ]
- })
- expect(tw(graph, node.id)).toMatch(/shadow-\[inset_1px_2px_3px_4px/)
- })
-
- test('blur emits blur class', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- effects: [
- {
- type: 'LAYER_BLUR',
- color: { r: 0, g: 0, b: 0, a: 0 },
- offset: { x: 0, y: 0 },
- radius: 4,
- spread: 0,
- visible: true
- }
- ]
- })
- expect(tw(graph, node.id)).toContain('blur-[4px]')
- })
-
- test('font size — named values', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- width: 200,
- height: 24,
- text: 'Hello',
- fontSize: 24,
- fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- })
- expect(tw(graph, node.id)).toContain('text-2xl')
- })
-
- test('font size — arbitrary', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- width: 200,
- height: 24,
- text: 'Hello',
- fontSize: 22,
- fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- })
- expect(tw(graph, node.id)).toContain('text-[22px]')
- })
-
- test('font weight — named values', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- width: 100,
- height: 20,
- text: 'X',
- fontWeight: 600
- })
- expect(tw(graph, node.id)).toContain('font-semibold')
- })
-
- test('font family keeps original spaces via arbitrary value', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- width: 100,
- height: 20,
- text: 'X',
- fontFamily: 'IBM Plex Sans'
- })
- expect(tw(graph, node.id)).toContain('font-[IBM_Plex_Sans]')
- })
-
- test('section uses <section> tag', () => {
- const graph = makeGraph()
- const node = graph.createNode('SECTION', pageId(graph), {
- width: 800,
- height: 600
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('<section')
- })
-
- test('frame with children renders nested', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- name: 'Card',
- width: 320,
- height: 200,
- layoutMode: 'VERTICAL',
- itemSpacing: 8,
- primaryAxisSizing: 'HUG',
- counterAxisSizing: 'FIXED',
- fills: [
- { type: 'SOLID', color: { r: 0.95, g: 0.95, b: 0.95, a: 1 }, opacity: 1, visible: true }
- ],
- cornerRadius: 12
- })
- graph.createNode('TEXT', frame.id, {
- name: 'Title',
- width: 200,
- height: 20,
- text: 'Card Title',
- fontSize: 16,
- fontWeight: 700,
- fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
- })
-
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('<div')
- expect(jsx).toContain('flex flex-col')
- expect(jsx).toContain('gap-2')
- expect(jsx).toMatch(/rounded/)
- expect(jsx).toContain(' <p')
- expect(jsx).toContain('text-base')
- expect(jsx).toContain('font-bold')
- expect(jsx).toContain('>Card Title</p>')
- expect(jsx).toContain('</div>')
- })
-
- test('selectionToJSX with tailwind format', () => {
- const graph = makeGraph()
- const a = graph.createNode('RECTANGLE', pageId(graph), {
- name: 'A',
- width: 40,
- height: 40
- })
- const b = graph.createNode('ELLIPSE', pageId(graph), {
- name: 'B',
- width: 80,
- height: 80
- })
- const jsx = selectionToJSX([a.id, b.id], graph, 'tailwind')
- expect(jsx).toContain('<div')
- expect(jsx).not.toContain('<Rectangle')
- expect(jsx).not.toContain('<Ellipse')
- expect(jsx).toContain('\n\n')
- })
-
- test('grow emits grow class', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 400,
- height: 100,
- layoutMode: 'HORIZONTAL',
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'FIXED'
- })
- const child = graph.createNode('RECTANGLE', frame.id, {
- width: 100,
- height: 50,
- layoutGrow: 1
- })
- const jsx = tw(graph, child.id)
- expect(jsx).toContain('grow')
- })
-
- test('wrap emits flex-wrap', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 400,
- height: 400,
- layoutMode: 'HORIZONTAL',
- layoutWrap: 'WRAP',
- counterAxisSpacing: 12,
- primaryAxisSizing: 'FIXED',
- counterAxisSizing: 'FIXED'
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('flex-wrap')
- expect(jsx).toContain('gap-y-3')
- })
-
- test('default values are omitted', () => {
- const graph = makeGraph()
- const node = graph.createNode('RECTANGLE', pageId(graph), {
- width: 100,
- height: 100,
- opacity: 1,
- rotation: 0,
- cornerRadius: 0
- })
- const jsx = tw(graph, node.id)
- expect(jsx).not.toContain('opacity')
- expect(jsx).not.toContain('rotate')
- expect(jsx).not.toContain('rounded')
- })
-
- test('white color uses named class', () => {
- const graph = makeGraph()
- const node = graph.createNode('TEXT', pageId(graph), {
- width: 100,
- height: 20,
- text: 'X',
- fills: [{ type: 'SOLID', color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }]
- })
- const jsx = tw(graph, node.id)
- expect(jsx).toContain('text-white')
- expect(jsx).not.toContain('#')
- })
-
- test('grid layout → grid + grid-cols + grid-rows', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- name: 'Grid',
- width: 400,
- height: 300,
- layoutMode: 'GRID',
- gridTemplateColumns: [
- { sizing: 'FR', value: 1 },
- { sizing: 'FR', value: 1 },
- { sizing: 'FR', value: 1 }
- ],
- gridTemplateRows: [
- { sizing: 'FR', value: 1 },
- { sizing: 'FR', value: 1 }
- ],
- gridColumnGap: 16,
- gridRowGap: 8,
- paddingTop: 12,
- paddingRight: 12,
- paddingBottom: 12,
- paddingLeft: 12
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('grid ')
- expect(jsx).toContain('grid-cols-3')
- expect(jsx).toContain('grid-rows-2')
- expect(jsx).toContain('gap-x-4')
- expect(jsx).toContain('gap-y-2')
- expect(jsx).toContain('p-3')
- expect(jsx).not.toContain('flex')
- })
-
- test('grid with mixed tracks uses arbitrary value', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 600,
- height: 400,
- layoutMode: 'GRID',
- gridTemplateColumns: [
- { sizing: 'FIXED', value: 200 },
- { sizing: 'FR', value: 1 },
- { sizing: 'AUTO', value: 0 }
- ],
- gridTemplateRows: [],
- gridColumnGap: 0,
- gridRowGap: 0
- })
- const jsx = tw(graph, frame.id)
- expect(jsx).toContain('grid-cols-[200px_1fr_auto]')
- expect(jsx).not.toContain('grid-rows')
- })
-
- test('grid child placement → col-start/row-start/col-span', () => {
- const graph = makeGraph()
- const frame = graph.createNode('FRAME', pageId(graph), {
- width: 400,
- height: 300,
- layoutMode: 'GRID',
- gridTemplateColumns: [
- { sizing: 'FR', value: 1 },
- { sizing: 'FR', value: 1 }
- ],
- gridTemplateRows: [
- { sizing: 'FR', value: 1 },
- { sizing: 'FR', value: 1 }
- ],
- gridColumnGap: 0,
- gridRowGap: 0
- })
- const child = graph.createNode('RECTANGLE', frame.id, {
- name: 'Span',
- width: 100,
- height: 50,
- gridPosition: { column: 1, row: 2, columnSpan: 2, rowSpan: 1 }
- })
- const jsx = tw(graph, child.id)
- expect(jsx).toContain('col-start-1')
- expect(jsx).toContain('row-start-2')
- expect(jsx).toContain('col-span-2')
- expect(jsx).not.toContain('row-span')
- })
-})