Skip to content

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

fix(export): draw vector layers as inline SVG in HTML exports (#985)

Danila Poyarkove3645ebcdba2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8a8e9ad2..68880778c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -74,7 +74,7 @@
- Detach an instance from its component with `detachInstance()` in the plugin API, as in Figma, from scripts run through `eval`.
- Run scripts written for Figma's dynamic-page mode that call `figma.getNodeByIdAsync()` or `getMainComponentAsync()`; both resolve to the same nodes as their synchronous forms.
- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, or Collapsible becomes a Reka UI or Radix UI component whose variants are compiled into state styles, with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).
-- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do.
+- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do. Vector shapes, booleans, stars, and polygons export as inline SVG with their fills, gradients, strokes, and shadows, in HTML, Tailwind JSX, and Storybook stories.
- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.
- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.
- Compare designs from the terminal with `openpencil diff`: `create`, `jsx`, `show`, `apply`, and `visual` work on a file or the running app, and `diff files` compares two documents page by page and exits with status 1 when they differ.
diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.ts
index d960aea4c..fd0fc4bde 100644
--- a/packages/cli/src/commands/export/storybook/index.ts
+++ b/packages/cli/src/commands/export/storybook/index.ts
@@ -12,7 +12,7 @@ import {
sep
} from 'node:path'
-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+import { BUILTIN_IO_FORMATS, IORegistry, vectorElement } from '@open-pencil/core/io'
import {
exportStorybook,
STORYBOOK_FRAMEWORKS,
@@ -154,6 +154,7 @@ async function writeStories(
framework,
pageId,
linkPath: linkPath(file),
+ vectorElement,
renderDesignImage: args['design-images']
? async (nodeId) => {
const result = await io.exportContent(
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 021b992cf..16edbb192 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -393,7 +393,8 @@ export const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {
const target = resolveExportNodes(request)
if (!target) throw new Error('Nothing to export')
const { sceneNodesToTailwindJSX } = await import('@open-pencil/dom-css/export')
- const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds)
+ const { vectorElement } = await import('#core/io/formats/html/vectors')
+ const data = sceneNodesToTailwindJSX(request.graph, target.nodeIds, { vectorElement })
if (!data) throw new Error('Nothing to export')
return {
format: 'tailwind-jsx',
diff --git a/packages/core/src/io/formats/html/index.ts b/packages/core/src/io/formats/html/index.ts
index 53c1aeb60..afd7b7fea 100644
--- a/packages/core/src/io/formats/html/index.ts
+++ b/packages/core/src/io/formats/html/index.ts
@@ -8,11 +8,15 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import type { ExportAsset, HTMLExportOptions } from '#core/io/types'
import { exportWebFontFaceAssets } from '#core/text/web-font/assets'
+import { vectorElement } from './vectors'
+
function designDocument(graph: SceneGraph, nodeIds: string[]): DesignDocument {
return {
type: 'document',
sourceGraph: graph,
- children: nodeIds.flatMap((id) => sceneNodeToDesignDocument(graph, id).children)
+ children: nodeIds.flatMap(
+ (id) => sceneNodeToDesignDocument(graph, id, { vectorElement }).children
+ )
}
}
diff --git a/packages/core/src/io/formats/html/vectors.ts b/packages/core/src/io/formats/html/vectors.ts
new file mode 100644
index 000000000..de7c94186
--- /dev/null
+++ b/packages/core/src/io/formats/html/vectors.ts
@@ -0,0 +1,41 @@
+import type { DesignElement, DesignNode, VectorElementRenderer } from '@open-pencil/dom-css/export'
+
+import { renderNodeSVGElement } from '#core/io/formats/svg/export'
+import type { SVGNode } from '#core/io/formats/svg/node'
+
+function designNode(node: SVGNode | string): DesignNode {
+ if (typeof node === 'string') return { type: 'text', text: node }
+ return {
+ type: 'element',
+ tagName: node.tag,
+ attrs: Object.fromEntries(
+ Object.entries(node.attrs).map(([name, value]) => [name, String(value)])
+ ),
+ children: node.children.map(designNode)
+ }
+}
+
+/**
+ * A layer id as an id-safe string, one to one: letters, digits, and `-` stay, and anything
+ * else, `_` included, becomes `_<code point>_`, so `a:b` and `a-b` never meet.
+ */
+function idPart(id: string): string {
+ return id.replace(/[^A-Za-z0-9-]/gu, (char) => `_${char.codePointAt(0)?.toString(16) ?? ''}_`)
+}
+
+/**
+ * Vector layers in HTML exports as inline SVG from the SVG export, so paths, gradients, and
+ * shadows draw as they do there. Def ids start with the layer's id, so several SVGs on one page
+ * never pick up each other's gradients or filters.
+ */
+export const vectorElement: VectorElementRenderer = (graph, node) => {
+ const idPrefix = `${idPart(node.id)}-`
+ const drawn = renderNodeSVGElement(graph, node, {
+ idPrefix,
+ colorSpace: graph.documentColorSpace
+ })
+ const element = drawn && designNode(drawn)
+ if (element?.type !== 'element') return null
+ // Strokes and shadows can reach past the layer's box, which an inline SVG would clip.
+ return { ...element, inlineStyle: { overflow: 'visible' } } satisfies DesignElement
+}
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index a01a1812e..eeddbc025 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -17,10 +17,12 @@ export interface SVGExportContext {
defIdCounter: number
graph: SceneGraph
colorSpace: RenderColorSpace
+ /** Starts every def id, so SVGs inlined on one page cannot reference each other's defs. */
+ idPrefix?: string
}
export function nextDefId(ctx: SVGExportContext, prefix: string): string {
- return `${prefix}${ctx.defIdCounter++}`
+ return `${ctx.idPrefix ?? ''}${prefix}${ctx.defIdCounter++}`
}
export function formatColor(
diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.ts
index a62f60f58..f8e8577fe 100644
--- a/packages/core/src/io/formats/svg/export.ts
+++ b/packages/core/src/io/formats/svg/export.ts
@@ -1,3 +1,4 @@
+import type { RenderColorSpace } from '@open-pencil/scene-graph/color'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { computeContentBounds } from '#core/io/formats/raster'
@@ -510,3 +511,27 @@ export function renderNodesToSVG(
const xmlDecl = options.xmlDeclaration !== false ? '<?xml version="1.0" encoding="UTF-8"?>\n' : ''
return xmlDecl + svgStr
}
+
+/**
+ * One layer as an `<svg>` element sized to its box, for inlining in HTML where the box already
+ * places, rotates, and fades it: the drawing starts at the layer's origin without its rotation
+ * or opacity, and keeps its flips.
+ */
+export function renderNodeSVGElement(
+ graph: SceneGraph,
+ node: SceneNode,
+ { idPrefix, colorSpace = 'srgb' }: { idPrefix: string; colorSpace?: RenderColorSpace }
+): SVGNode | null {
+ const ctx: SVGExportContext = { defs: [], defIdCounter: 0, graph, colorSpace, idPrefix }
+ const drawn = renderNode({ ...node, x: 0, y: 0, rotation: 0, opacity: 1 }, ctx)
+ if (!drawn) return null
+ // A straight line has no height or width, but its stroke still needs a viewport to draw in.
+ const width = Math.max(1, round(node.width))
+ const height = Math.max(1, round(node.height))
+ return svg(
+ 'svg',
+ { width, height, viewBox: `0 0 ${width} ${height}` },
+ ctx.defs.length > 0 ? svg('defs', {}, ...ctx.defs) : null,
+ drawn
+ )
+}
diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.ts
index 7a6f07c0d..1911a4a6b 100644
--- a/packages/core/src/io/index.ts
+++ b/packages/core/src/io/index.ts
@@ -35,6 +35,7 @@ export {
type SVGImportData,
type SVGImportOptions
} from './formats/svg'
+export { vectorElement } from './formats/html/vectors'
export {
renderNodesToPPTX,
type PPTXExportOptions,
diff --git a/packages/core/tests/io/formats/html/vectors.test.ts b/packages/core/tests/io/formats/html/vectors.test.ts
new file mode 100644
index 000000000..5e9aa9d5b
--- /dev/null
+++ b/packages/core/tests/io/formats/html/vectors.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
+
+import { renderNodesToHTML } from '#core/io/formats/html'
+
+const gradient: Fill = {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 1, g: 0, b: 0, a: 1 },
+ visible: true,
+ opacity: 1,
+ gradientStops: [
+ { color: { r: 1, g: 0, b: 0, a: 1 }, position: 0 },
+ { color: { r: 0, g: 0, b: 1, a: 1 }, position: 1 }
+ ],
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }
+}
+
+describe('vector layers in HTML export', () => {
+ test('draw their paths as inline SVG with def ids of their own', async () => {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card', width: 200, height: 100 })
+ for (const x of [0, 100])
+ graph.createNode('STAR', frame.id, { name: 'Star', x, width: 80, height: 80, fills: [gradient] })
+
+ const { html } = await renderNodesToHTML(graph, [frame.id])
+ expect(html.match(/<svg/g)?.length).toBe(2)
+ expect(html.match(/<polygon points=/g)?.length).toBe(2)
+ expect(html).toContain('overflow: visible')
+ // Each SVG's gradient has its own id, and each SVG fills with its own.
+ const ids = [...html.matchAll(/<linearGradient[^>]* id="([^"]+)"/g)].map((match) => match[1])
+ expect(ids).toHaveLength(2)
+ expect(new Set(ids).size).toBe(2)
+ for (const id of ids) expect(html).toContain(`url(#${id})`)
+ })
+
+ test('keep def ids apart for layer ids that differ only in punctuation', async () => {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card', width: 200, height: 100 })
+ for (const [id, x] of [['a:b', 0], ['a-b', 100]] as const)
+ graph.createNodeWithId(id, 'STAR', frame.id, { name: 'Star', x, width: 80, height: 80, fills: [gradient] })
+
+ const { html } = await renderNodesToHTML(graph, [frame.id])
+ const ids = [...html.matchAll(/<linearGradient[^>]* id="([^"]+)"/g)].map((match) => match[1])
+ expect(new Set(ids).size).toBe(2)
+ })
+
+ test('give a straight line a viewport to draw its stroke in', async () => {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, { name: 'Card', width: 200, height: 100 })
+ graph.createNode('VECTOR', frame.id, {
+ name: 'Rule',
+ width: 120,
+ height: 0,
+ vectorNetwork: {
+ vertices: [{ x: 0, y: 0 }, { x: 120, y: 0 }],
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
+ regions: []
+ },
+ strokes: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true, weight: 2, align: 'CENTER' }]
+ })
+ const { html } = await renderNodesToHTML(graph, [frame.id])
+ expect(html).toMatch(/<svg width="120" height="1" viewBox="0 0 120 1"/)
+ })
+})
diff --git a/packages/dom-css/src/behaviours/states/layers.ts b/packages/dom-css/src/behaviours/states/layers.ts
index e5c11d0a0..a0aa36e48 100644
--- a/packages/dom-css/src/behaviours/states/layers.ts
+++ b/packages/dom-css/src/behaviours/states/layers.ts
@@ -1,4 +1,7 @@
-import { sceneNodeToDesignDocument } from '#dom-css/export/projection'
+import {
+ sceneNodeToDesignDocument,
+ type SceneGraphToDesignOptions
+} from '#dom-css/export/projection'
import type { DesignElement, DesignNode, DesignText } from '#dom-css/types'
import { omit } from 'es-toolkit/object'
@@ -46,8 +49,15 @@ function variantLayer(
}
/** A variant projected to DOM, without where the set places it. */
-export function projectVariant(graph: SceneGraph, variant: SceneNode): VariantLayer | null {
- const document = sceneNodeToDesignDocument(graph, variant.id, { includeSourceIds: false })
+export function projectVariant(
+ graph: SceneGraph,
+ variant: SceneNode,
+ { vectorElement }: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}
+): VariantLayer | null {
+ const document = sceneNodeToDesignDocument(graph, variant.id, {
+ includeSourceIds: false,
+ vectorElement
+ })
const root = document.children.at(0)
if (root?.type !== 'element') return null
const style = root.inlineStyle ?? {}
diff --git a/packages/dom-css/src/behaviours/states/model.ts b/packages/dom-css/src/behaviours/states/model.ts
index 3385e9835..577015e0f 100644
--- a/packages/dom-css/src/behaviours/states/model.ts
+++ b/packages/dom-css/src/behaviours/states/model.ts
@@ -1,3 +1,4 @@
+import type { SceneGraphToDesignOptions } from '#dom-css/export/projection'
import type { DesignStyleDeclaration } from '#dom-css/types'
import { isEmptyObject, isEqual } from 'es-toolkit/predicate'
@@ -72,14 +73,18 @@ function pruneCombined(rules: StateRule[]): StateRule[] {
*
* `null` when no variant shows the rest state, since every look then depends on a condition.
*/
-export function stateStyles(graph: SceneGraph, set: SceneNode): StateStyles | null {
+export function stateStyles(
+ graph: SceneGraph,
+ set: SceneNode,
+ options: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}
+): StateStyles | null {
const conditionsOf = variantConditions(graph, set)
const variants = graph
.getChildren(set.id)
.filter((child) => child.type === 'COMPONENT' && child.visible)
.flatMap((variant) => {
const conditions = conditionsOf(variant)
- const root = conditions && projectVariant(graph, variant)
+ const root = conditions && projectVariant(graph, variant, options)
return conditions && root ? [{ conditions, root }] : []
})
const rest = variants.find((variant) => variant.conditions.length === 0)
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index 97c8b1a0c..434ec244e 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -17,6 +17,7 @@ import {
type SceneNode
} from '@open-pencil/scene-graph'
+import type { SceneGraphToDesignOptions } from '../projection'
import { identifierName } from '../storybook/names'
/** Kinds generated as components so far; the rest keep static stories. */
@@ -139,10 +140,14 @@ function partPaths(graph: SceneGraph, set: SceneNode, behaviour: Behaviour): Map
* The component a set with a behaviour generates, or `null` when its kind is not generated
* yet or its variants have no rest state to start from.
*/
-export function componentModel(graph: SceneGraph, set: SceneNode): ComponentModel | null {
+export function componentModel(
+ graph: SceneGraph,
+ set: SceneNode,
+ options: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}
+): ComponentModel | null {
const behaviour = readBehaviour(set)
if (!behaviour || !isGenerated(behaviour.kind)) return null
- const styles = stateStyles(graph, set)
+ const styles = stateStyles(graph, set, options)
const args = behaviourArgs(graph, set)
if (!styles || !args) return null
diff --git a/packages/dom-css/src/export/html.ts b/packages/dom-css/src/export/html.ts
index ecb05cfe5..0025502be 100644
--- a/packages/dom-css/src/export/html.ts
+++ b/packages/dom-css/src/export/html.ts
@@ -100,9 +100,10 @@ function serializeAttrs(node: DesignElement, options: SerializeHTMLOptions): str
}
function serializeElement(node: DesignElement, options: SerializeHTMLOptions): string {
- const tagName = node.tagName.toLowerCase()
+ // SVG names such as `linearGradient` keep their case, as an SVG parser needs them.
+ const tagName = node.tagName
const attrs = serializeAttrs(node, options)
- if (VOID_ELEMENTS.has(tagName)) return `<${tagName}${attrs}>`
+ if (VOID_ELEMENTS.has(tagName.toLowerCase())) return `<${tagName}${attrs}>`
return `<${tagName}${attrs}>${node.children.map((child) => serializeNode(child, options)).join('')}</${tagName}>`
}
diff --git a/packages/dom-css/src/export/index.ts b/packages/dom-css/src/export/index.ts
index 0b6b101c3..c5b0ffc98 100644
--- a/packages/dom-css/src/export/index.ts
+++ b/packages/dom-css/src/export/index.ts
@@ -1,5 +1,10 @@
// SceneGraph → HTML and JSX without the CSS runtimes, so browsers can bundle it.
-export { sceneGraphToDesignDocument, sceneNodeToDesignDocument } from './projection'
+export {
+ sceneGraphToDesignDocument,
+ sceneNodeToDesignDocument,
+ type SceneGraphToDesignOptions,
+ type VectorElementRenderer
+} from './projection'
export { exportHTMLBundle } from './bundle'
export {
designDocumentToTailwindJSX,
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index f9a66ae59..9dbfd2688 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -5,20 +5,34 @@ import { BLACK } from '@open-pencil/scene-graph/constants'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text-direction'
import { DesignTokens, type CSSModes } from '../tokens/references'
-import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '../types'
+import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
import { cssColor, dropShadowToCSS, effectsToCSS, fillToCSS, strokeColorToCSS } from './css'
import { addGridContainer, addGridPlacement } from './grid'
const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'
const IMAGE_SOURCE_URL_KEY = 'image-source-url'
+/**
+ * Draws a vector-shaped layer as an inline `<svg>` element sized to the layer, from the
+ * engine's own SVG export. dom-css cannot depend on that engine, so it comes in as an option.
+ */
+export type VectorElementRenderer = (graph: SceneGraph, node: SceneNode) => DesignElement | null
+
export interface SceneGraphToDesignOptions {
rootId?: string
includeSourceIds?: boolean
/** Write variable-bound values as `var(--name)` where CSS resolves them as drawn. Default true. */
tokens?: boolean
+ /** Vector, boolean, star, and polygon layers as inline SVG; without it they project as boxes. */
+ vectorElement?: VectorElementRenderer
}
+/** Layers whose shape only paths describe, which CSS boxes cannot draw. */
+const VECTOR_SHAPES = new Set<SceneNode['type']>(['VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON'])
+
+/** What a box draws itself, which the SVG of a vector layer draws instead. */
+const BOX_PAINT = /^(background|border|box-shadow|outline|filter)/
+
/** A field's CSS: its token reference where one is faithful, otherwise the literal value. */
type FieldCSS = (field: string, literal: string) => string
@@ -347,6 +361,31 @@ interface ProjectionContext {
graph: SceneGraph
includeSourceIds: boolean
tokens: DesignTokens | undefined
+ vectorElement: VectorElementRenderer | undefined
+}
+
+/**
+ * A vector layer as the renderer's `<svg>`, placed where the layer's box would be: its
+ * position, size, opacity, and transform stay, and its paint is the SVG's, not the box's.
+ */
+function vectorDesignNode(
+ context: ProjectionContext,
+ node: SceneNode,
+ attrs: Record<string, string>,
+ style: DesignStyleDeclaration
+): DesignElement | null {
+ const drawn = context.vectorElement?.(context.graph, node)
+ if (!drawn) return null
+ const placement = Object.fromEntries(
+ Object.entries(style).filter(([property]) => !BOX_PAINT.test(property))
+ )
+ return {
+ ...drawn,
+ attrs: { ...drawn.attrs, ...attrs },
+ inlineStyle: { ...drawn.inlineStyle, ...placement },
+ sourceSceneNodeId: node.id,
+ sourceSceneNode: node
+ }
}
function sceneNodeToDesignNode(
@@ -375,6 +414,11 @@ function sceneNodeToDesignNode(
}
}
+ if (VECTOR_SHAPES.has(node.type)) {
+ const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css))
+ if (vector) return vector
+ }
+
const children = nodeChildren(graph, node)
.map((child) => sceneNodeToDesignNode(context, child, modes, false))
.filter((child): child is DesignNode => child !== null)
@@ -403,9 +447,14 @@ function sceneNodeToDesignNode(
function projectionContext(
graph: SceneGraph,
- { includeSourceIds = true, tokens = true }: SceneGraphToDesignOptions
+ { includeSourceIds = true, tokens = true, vectorElement }: SceneGraphToDesignOptions
): ProjectionContext {
- return { graph, includeSourceIds, tokens: tokens ? new DesignTokens(graph) : undefined }
+ return {
+ graph,
+ includeSourceIds,
+ tokens: tokens ? new DesignTokens(graph) : undefined,
+ vectorElement
+ }
}
export function sceneGraphToDesignDocument(
diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.ts
index 3fd7fece6..acdff203b 100644
--- a/packages/dom-css/src/export/storybook/export.ts
+++ b/packages/dom-css/src/export/storybook/export.ts
@@ -5,7 +5,7 @@ import { componentModel, type ComponentGenerator } from '../components/model'
import { reactComponent } from '../components/react'
import { vueComponent } from '../components/vue'
import { serializeHTML } from '../html'
-import { sceneNodeToDesignDocument } from '../projection'
+import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'
import { printComponentStories } from './component'
import { collectGroups, type StoryGroup } from './groups'
import {
@@ -32,6 +32,8 @@ export interface ExportStorybookOptions {
linkPath?: string
/** Renders a variant to PNG; each story then shows it next to the link as its design. */
renderDesignImage?: (nodeId: string) => Promise<Uint8Array>
+ /** Draws vector layers as inline SVG, from the engine's SVG export. */
+ vectorElement?: VectorElementRenderer
}
export interface StorybookFile extends ExportHTMLFile {
@@ -55,6 +57,7 @@ interface ModuleContext {
storyNames: string[]
/** Import path of each variant's design image, by variant index. */
images: string[]
+ vectorElement?: VectorElementRenderer
}
function designLink(
@@ -91,7 +94,10 @@ function storyModule(group: StoryGroup, context: ModuleContext): string {
variants: group.variants.map((variant) => ({
values: variant.values,
html: serializeHTML(
- sceneNodeToDesignDocument(context.graph, variant.node.id, { includeSourceIds: false })
+ sceneNodeToDesignDocument(context.graph, variant.node.id, {
+ includeSourceIds: false,
+ vectorElement: context.vectorElement
+ })
)
})),
metaDesign: designLink(context, group.linkNode),
@@ -136,7 +142,10 @@ export async function exportStorybook(
if (options.pageId && page.id !== options.pageId) continue
const generate = GENERATORS[framework]
- const component = generate && group.set ? componentModel(graph, group.set) : null
+ const component =
+ generate && group.set
+ ? componentModel(graph, group.set, { vectorElement: options.vectorElement })
+ : null
if (generate && component) {
// The component is imported by the file's name, so the two always match.
component.name = file
diff --git a/packages/dom-css/src/export/tailwind-jsx.ts b/packages/dom-css/src/export/tailwind-jsx.ts
index ffa2b8856..c6ccf5561 100644
--- a/packages/dom-css/src/export/tailwind-jsx.ts
+++ b/packages/dom-css/src/export/tailwind-jsx.ts
@@ -3,10 +3,25 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import type { DesignDocument, DesignElement, DesignNode } from '../types'
import { mergeClassNames, serializeTailwindClasses } from './html'
-import { sceneNodeToDesignDocument } from './projection'
+import { sceneNodeToDesignDocument, type SceneGraphToDesignOptions } from './projection'
+
+/** Engine services the projection takes, such as drawing vector layers as SVG. */
+type ProjectionServices = Pick<SceneGraphToDesignOptions, 'vectorElement'>
/** HTML attribute names that JSX spells differently. */
-const JSX_ATTRIBUTE_NAMES: Record<string, string> = { class: 'className', for: 'htmlFor' }
+const JSX_ATTRIBUTE_NAMES: Record<string, string> = {
+ class: 'className',
+ for: 'htmlFor',
+ 'xlink:href': 'xlinkHref'
+}
+
+/** React spells SVG's dashed attributes in camel case, such as `fillRule`; data and ARIA stay. */
+function jsxAttributeName(name: string): string {
+ const named = JSX_ATTRIBUTE_NAMES[name]
+ if (named) return named
+ if (name.startsWith('data-') || name.startsWith('aria-')) return name
+ return name.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
+}
/** Scene text layers become paragraphs; Tailwind's preflight removes their margins. */
function tagName(node: DesignElement): string {
@@ -22,9 +37,7 @@ function attributes(node: DesignElement, themeVariables: readonly string[]): Syn
['className', mergeClassNames(className, serializeTailwindClasses(node, themeVariables))]
]
return entries.flatMap(([key, value]) =>
- value === undefined
- ? []
- : [jsx.attribute(JSX_ATTRIBUTE_NAMES[key] ?? key, jsx.stringValue(value))]
+ value === undefined ? [] : [jsx.attribute(jsxAttributeName(key), jsx.stringValue(value))]
)
}
@@ -52,8 +65,12 @@ export function designDocumentToTailwindJSX(document: DesignDocument): string {
}
/** Tailwind JSX for scene nodes, separated by blank lines. */
-export function sceneNodesToTailwindJSX(graph: SceneGraph, nodeIds: string[]): string {
- return sceneNodesToTailwindJSXWithLayers(graph, nodeIds).code
+export function sceneNodesToTailwindJSX(
+ graph: SceneGraph,
+ nodeIds: string[],
+ options: ProjectionServices = {}
+): string {
+ return sceneNodesToTailwindJSXWithLayers(graph, nodeIds, options).code
}
/** Tailwind JSX with the layer behind each element, in the order elements open. */
@@ -71,12 +88,16 @@ function collectLayerIds(node: DesignNode, layerIds: Array<string | null>): void
export function sceneNodesToTailwindJSXWithLayers(
graph: SceneGraph,
- nodeIds: string[]
+ nodeIds: string[],
+ { vectorElement }: ProjectionServices = {}
): TailwindJSXWithLayers {
const layerIds: Array<string | null> = []
const blocks: string[] = []
for (const id of nodeIds) {
- const document = sceneNodeToDesignDocument(graph, id, { includeSourceIds: false })
+ const document = sceneNodeToDesignDocument(graph, id, {
+ includeSourceIds: false,
+ vectorElement
+ })
const code = designDocumentToTailwindJSX(document)
if (!code) continue
blocks.push(code)
diff --git a/packages/dom-css/tests/export/projection/vectors.test.ts b/packages/dom-css/tests/export/projection/vectors.test.ts
new file mode 100644
index 000000000..8d38f3fa7
--- /dev/null
+++ b/packages/dom-css/tests/export/projection/vectors.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, test } from 'bun:test'
+
+import { sceneNodeToDesignDocument, sceneNodesToTailwindJSX } from '#dom-css/export/index'
+import type { VectorElementRenderer } from '#dom-css/export/projection'
+import type { DesignElement } from '#dom-css/types'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** A star with a fill, a stroke, and a shadow, inside a frame. */
+function starInFrame() {
+ const graph = new SceneGraph()
+ const frame = graph.createNode('FRAME', graph.getPages()[0].id, {
+ name: 'Card',
+ width: 100,
+ height: 100
+ })
+ const star = graph.createNode('STAR', frame.id, {
+ name: 'Star',
+ x: 10,
+ y: 20,
+ width: 40,
+ height: 40,
+ rotation: 15,
+ opacity: 0.5,
+ fills: [{ type: 'SOLID', color: { r: 1, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }]
+ })
+ return { graph, frame, star }
+}
+
+/** Draws every vector layer as a one-path SVG, as the engine's SVG export would. */
+const renderer: VectorElementRenderer = (_graph, node) => ({
+ type: 'element',
+ tagName: 'svg',
+ attrs: { viewBox: `0 0 ${node.width} ${node.height}` },
+ inlineStyle: { overflow: 'visible' },
+ children: [
+ {
+ type: 'element',
+ tagName: 'path',
+ attrs: { d: 'M0 0L40 40', 'fill-rule': 'evenodd' },
+ children: []
+ }
+ ]
+})
+
+function first(element: DesignElement): DesignElement {
+ const child = element.children[0]
+ if (child?.type !== 'element') throw new Error('No child element')
+ return child
+}
+
+describe('vector layers', () => {
+ test("project as the renderer's SVG, placed where the layer's box is", () => {
+ const { graph, frame } = starInFrame()
+ const card = sceneNodeToDesignDocument(graph, frame.id, { vectorElement: renderer }).children[0]
+ if (card?.type !== 'element') throw new Error('No card')
+ const star = first(card)
+ expect(star.tagName).toBe('svg')
+ expect(first(star).attrs.d).toBe('M0 0L40 40')
+ expect(star.inlineStyle).toMatchObject({
+ position: 'absolute',
+ left: '10px',
+ top: '20px',
+ width: '40px',
+ height: '40px',
+ opacity: '0.5',
+ transform: 'rotate(15deg)',
+ overflow: 'visible'
+ })
+ // The SVG paints the star; the box would paint a rectangle.
+ expect(
+ Object.keys(star.inlineStyle ?? {}).filter((key) => key.startsWith('background'))
+ ).toEqual([])
+ })
+
+ test('stay boxes without a renderer, as before', () => {
+ const { graph, frame } = starInFrame()
+ const card = sceneNodeToDesignDocument(graph, frame.id).children[0]
+ if (card?.type !== 'element') throw new Error('No card')
+ expect(first(card).tagName).toBe('div')
+ })
+
+ test("write SVG attributes in React's camel case in Tailwind JSX", () => {
+ const { graph, frame } = starInFrame()
+ const code = sceneNodesToTailwindJSX(graph, [frame.id], { vectorElement: renderer })
+ expect(code).toContain('fillRule="evenodd"')
+ expect(code).not.toContain('fill-rule')
+ })
+})