AI-native design editor. Open-source Figma alternative.
refactor!: register HTML and Tailwind JSX as IO formats (#774)
Danila Poyarkov7a37f1432781
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b2e38908..95f7aa9a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,11 +5,12 @@### 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`.+- `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 the browser-safe `@open-pencil/dom-css/export`.- Color conversion and management and text/layout direction helpers moved from `@open-pencil/core/color` and `@open-pencil/core/text` to `@open-pencil/scene-graph/color` and `@open-pencil/scene-graph/text-direction`, and `@open-pencil/core/bytes` is removed in favor of `js-base64`; the `@open-pencil/core` root exports are unchanged. `@open-pencil/dom-css` no longer requires `@open-pencil/core`, and `exportHTMLBundle` takes a font resolver in `fonts` instead of `'assets'`; pass one built on `exportWebFontFaceAssets` from `@open-pencil/core/text/web-font/assets` to keep font files in standalone exports.### Added+- 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.- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.### Changeddiff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export.tsindex 487c4985b..12ecabdc2 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export.ts@@ -4,14 +4,7 @@ import { basename, dirname, extname, join, resolve } from 'node:path'import { defineCommand } from 'citty'import { toUint8Array } from 'js-base64'-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'-import { exportWebFontFaceAssets } from '@open-pencil/core/text/web-font/assets'-import {- exportHTMLBundle,- sceneNodesToTailwindJSX,- sceneGraphToDesignDocument,- type ExportHTMLBundleOptions-} from '@open-pencil/dom-css'+import { BUILTIN_IO_FORMATS, IORegistry, type ExportResult } from '@open-pencil/core/io'import { isAppMode, requireFile, rpc } from '#cli/app-client'import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'@@ -20,8 +13,7 @@ import { ok, printError } from '#cli/format'import { loadDocument, populateDocumentPage, populateWholeDocument } from '#cli/headless'const io = new IORegistry(BUILTIN_IO_FORMATS)-// HTML goes through the DOM/CSS bundle exporter; every other format is a Core IO adapter.-const FORMAT_IDS = [...io.listExportFormats('node').map((format) => format.id), 'html']+const FORMAT_IDS = io.listExportFormats('node').map((format) => format.id)const ALL_FORMATS = new Set(FORMAT_IDS.map((id) => id.toUpperCase()))const FORMAT_LIST = `${FORMAT_IDS.slice(0, -1).join(', ')}, or ${FORMAT_IDS.at(-1)}`@@ -120,68 +112,16 @@ function targetLabel(pageName?: string, nodeId?: string, wholeDocument = false):type FileExportTarget = { scope: 'node'; nodeId: string } | { scope: 'page'; pageId: string }-async function writeHTMLFiles(- output: string,- bundle: Awaited<ReturnType<typeof exportHTMLBundle>>-) {- const entrypoint = bundle.files.find((file) => file.path === bundle.entrypoint)- if (!entrypoint) {- printError(`HTML export did not include ${bundle.entrypoint}.`)- process.exit(1)- }-- await writeAndLog(output, entrypoint.content)- const outputDir = dirname(output)- const assetFiles = bundle.files.filter((file) => file.path !== bundle.entrypoint)- for (const file of assetFiles) {- const assetPath = join(outputDir, file.path)+/** Writes the export and the files it refers to, which sit next to it. */+async function writeExport(output: string, result: ExportResult) {+ await writeAndLog(output, result.data as string | Uint8Array)+ const assets = result.assets ?? []+ for (const asset of assets) {+ const assetPath = join(dirname(output), asset.path)await mkdir(dirname(assetPath), { recursive: true })- await writeFile(assetPath, file.content)- }- 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 writeFile(assetPath, asset.content as string | Uint8Array)}- 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>>,- target: FileExportTarget,- defaultName: string-) {- const document = sceneGraphToDesignDocument(graph, {- rootId: target.scope === 'page' ? target.pageId : target.nodeId- })- const output = resolve(args.output ?? exportFileName(defaultName, 'html'))- const assetBasePath = `${basename(output, extname(output))}.assets`- const bundle = await exportHTMLBundle(document, {- html: args.html as ExportHTMLBundleOptions['html'],- style: args.css as ExportHTMLBundleOptions['style'],- assets: args.assets as ExportHTMLBundleOptions['assets'],- fonts:- args.fonts === 'assets'- ? async (fonts, assetBasePath) =>- (await exportWebFontFaceAssets({ fonts, assetBasePath })).assets- : 'none',- assetBasePath- })- await writeHTMLFiles(output, bundle)- console.log(ok(`Target: ${targetLabel(args.page, args.node)}`))+ if (assets.length > 0) console.log(ok(`Assets: ${assets.length} files`))}function prepareGraphForExport(@@ -200,16 +140,28 @@ async function executeFileExport(formatId: string,graph: Awaited<ReturnType<typeof loadDocument>>,target: FileExportTarget,- options:- | { format?: string; scale?: number; quality?: number; renderThumbnail?: boolean }- | undefined,- wholeDocument: boolean+ options: unknown,+ wholeDocument: boolean,+ fileName: string) {if (wholeDocument) {if (formatId === 'fig') return io.writeDocument(formatId, graph, options)- return io.exportContent(formatId, { graph, target: { scope: 'document' } }, options)+ return io.exportContent(formatId, { graph, target: { scope: 'document' }, fileName }, options)}- return io.exportContent(formatId, { graph, target }, options)+ return io.exportContent(formatId, { graph, target, fileName }, options)+}++function exportOptions(format: string, args: ExportArgs): unknown {+ if (format === 'FIG') return { renderThumbnail: true }+ if (format === 'HTML')+ return { html: args.html, style: args.css, assets: args.assets, fonts: args.fonts }+ if (formatSupportsScale(format))+ return {+ format,+ scale: Number(args.scale),+ quality: args.quality ? Number(args.quality) : undefined+ }+ return undefined}async function exportFromFile(format: string, args: ExportArgs) {@@ -257,41 +209,21 @@ async function exportFromFile(format: string, args: ExportArgs) {process.exit(1)}- const formatId = format.toLowerCase()- let options:- | { format?: string; scale?: number; quality?: number; renderThumbnail?: boolean }- | undefined- if (format === 'HTML') {- await exportHTMLFromFile(args, graph, target, defaultName)- return- }-- // 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 = {- format,- scale: Number(args.scale),- quality: args.quality ? Number(args.quality) : undefined- }- }-- const result = await executeFileExport(formatId, graph, target, options, wholeDocument)- const output = resolve(- args.output ??- exportFileName(- defaultName,- result.extension,- formatSupportsScale(format) ? Number(args.scale) : undefined- )+ // `--style tailwind` keeps the JSX spelling of the Tailwind JSX format.+ const formatId =+ format === 'JSX' && args.style === 'tailwind' ? 'tailwind-jsx' : format.toLowerCase()+ const scale = formatSupportsScale(format) ? Number(args.scale) : undefined+ const extension = io.getFormat(formatId)?.extensions[0] ?? formatId+ const output = resolve(args.output ?? exportFileName(defaultName, extension, scale))+ const result = await executeFileExport(+ formatId,+ graph,+ target,+ exportOptions(format, args),+ wholeDocument,+ basename(output))- await writeAndLog(output, result.data as string | Uint8Array)+ await writeExport(output, result)console.log(ok(`Target: ${targetLabel(args.page, args.node, wholeDocument)}`))}diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.tsindex 90a386e11..c919971fc 100644--- a/packages/core/src/io/formats.ts+++ b/packages/core/src/io/formats.ts@@ -11,12 +11,26 @@ import type {ExportRequest,ExportResult,FigWriteOptions,+ HTMLExportOptions,IOContext,IOFormatAdapter,+ IOFormatExportOptions,+ IOFormatSupport,RasterExportOptions,SVGExportOptions} from './types'+/** Formats that export a document, page, selection, or single node alike. */+const EXPORT_EVERY_TARGET: IOFormatSupport = {+ exportDocument: true,+ exportPage: true,+ exportSelection: true,+ exportNode: true+}++/** Formats with a size of their own, so no export scale or quality. */+const FIXED_SIZE_EXPORT: IOFormatExportOptions = { scale: false, quality: false }+function lowerExt(name: string): string {const match = /\.([^.]+)$/.exec(name.toLowerCase())return match?.[1] ?? ''@@ -152,10 +166,7 @@ export const figFormat: IOFormatAdapter<'fig'> = {exportSelection: true,exportNode: true},- exportOptions: {- scale: false,- quality: false- },+ exportOptions: FIXED_SIZE_EXPORT,matchesFile(fileName) {return lowerExt(fileName) === 'fig'},@@ -228,17 +239,8 @@ export const svgFormat: IOFormatAdapter<'svg'> = {category: 'vector',extensions: ['svg'],mimeTypes: ['image/svg+xml'],- support: {- exportDocument: true,- exportPage: true,- exportSelection: true,- exportNode: true- },- exportOptions: {- scale: false,- quality: false,- colorSpace: true- },+ support: EXPORT_EVERY_TARGET,+ exportOptions: { ...FIXED_SIZE_EXPORT, colorSpace: true },async exportContent(request, options?: SVGExportOptions) {const target = resolveExportNodes(request)if (!target) throw new Error('Nothing to export')@@ -261,16 +263,8 @@ export const pdfFormat: IOFormatAdapter<'pdf'> = {category: 'vector',extensions: ['pdf'],mimeTypes: ['application/pdf'],- support: {- exportDocument: true,- exportPage: true,- exportSelection: true,- exportNode: true- },- exportOptions: {- scale: false,- quality: false- },+ support: EXPORT_EVERY_TARGET,+ exportOptions: FIXED_SIZE_EXPORT,async exportContent(request) {const target = resolveExportNodes(request)if (!target) throw new Error('Nothing to export')@@ -306,16 +300,8 @@ export const pptxFormat: IOFormatAdapter<'pptx'> = {category: 'print',extensions: ['pptx'],mimeTypes: ['application/vnd.openxmlformats-officedocument.presentationml.presentation'],- support: {- exportDocument: true,- exportPage: true,- exportSelection: true,- exportNode: true- },- exportOptions: {- scale: false,- quality: false- },+ support: EXPORT_EVERY_TARGET,+ exportOptions: FIXED_SIZE_EXPORT,async exportContent(request, options?: PPTXExportOptions, context?: IOContext) {const target = resolvePPTXExportNodes(request)if (!target) throw new Error('Nothing to export')@@ -345,10 +331,7 @@ export const jsxFormat: IOFormatAdapter<'jsx'> = {exportSelection: true,exportNode: true},- exportOptions: {- scale: false,- quality: false- },+ exportOptions: FIXED_SIZE_EXPORT,async exportContent(request): Promise<ExportResult> {const nodeId = ensureSingleNode(request.target)let data = ''@@ -368,6 +351,61 @@ export const jsxFormat: IOFormatAdapter<'jsx'> = {}}+export const htmlFormat: IOFormatAdapter<'html'> = {+ id: 'html',+ label: 'HTML',+ role: 'derived-export',+ category: 'code',+ extensions: ['html'],+ mimeTypes: ['text/html'],+ support: EXPORT_EVERY_TARGET,+ exportOptions: FIXED_SIZE_EXPORT,+ async exportContent(request, options?: HTMLExportOptions) {+ const target = resolveExportNodes(request)+ if (!target) throw new Error('Nothing to export')+ const { renderNodesToHTML } = await import('./formats/html')+ const { html, assets } = await renderNodesToHTML(+ request.graph,+ target.nodeIds,+ options,+ request.fileName+ )+ return {+ format: 'html',+ mimeType: 'text/html',+ extension: 'html',+ data: html,+ encoding: 'utf8',+ assets+ }+ }+}++export const tailwindJSXFormat: IOFormatAdapter<'tailwind-jsx'> = {+ id: 'tailwind-jsx',+ label: 'Tailwind JSX',+ role: 'derived-export',+ category: 'code',+ extensions: ['jsx'],+ mimeTypes: ['text/plain', 'text/jsx'],+ support: EXPORT_EVERY_TARGET,+ exportOptions: FIXED_SIZE_EXPORT,+ async exportContent(request) {+ 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)+ if (!data) throw new Error('Nothing to export')+ return {+ format: 'tailwind-jsx',+ mimeType: 'text/plain',+ extension: 'jsx',+ data,+ encoding: 'utf8'+ }+ }+}+export const BUILTIN_IO_FORMATS = [figFormat,penFormat,@@ -377,7 +415,9 @@ export const BUILTIN_IO_FORMATS = [svgFormat,pdfFormat,pptxFormat,- jsxFormat+ jsxFormat,+ tailwindJSXFormat,+ htmlFormat] as const satisfies readonly IOFormatAdapter[]export type BuiltinIOFormatId = (typeof BUILTIN_IO_FORMATS)[number]['id']diff --git a/packages/core/src/io/formats/html/index.ts b/packages/core/src/io/formats/html/index.tsnew file mode 100644index 000000000..53c1aeb60--- /dev/null+++ b/packages/core/src/io/formats/html/index.ts@@ -0,0 +1,48 @@+import {+ exportHTMLBundle,+ sceneNodeToDesignDocument,+ type DesignDocument+} from '@open-pencil/dom-css/export'+import type { SceneGraph } from '@open-pencil/scene-graph'++import type { ExportAsset, HTMLExportOptions } from '#core/io/types'+import { exportWebFontFaceAssets } from '#core/text/web-font/assets'++function designDocument(graph: SceneGraph, nodeIds: string[]): DesignDocument {+ return {+ type: 'document',+ sourceGraph: graph,+ children: nodeIds.flatMap((id) => sceneNodeToDesignDocument(graph, id).children)+ }+}++/** `card.html` keeps its external files in `card.assets/` next to it, whatever the path style. */+function assetBasePath(fileName: string | undefined): string {+ const name = fileName+ ?.split(/[\\/]/)+ .pop()+ ?.replace(/\.[^.]*$/, '')+ return `${name || 'export'}.assets`+}++export async function renderNodesToHTML(+ graph: SceneGraph,+ nodeIds: string[],+ options: HTMLExportOptions = {},+ fileName?: string+): Promise<{ html: string; assets: ExportAsset[] }> {+ const bundle = await exportHTMLBundle(designDocument(graph, nodeIds), {+ html: options.html,+ style: options.style,+ assets: options.assets,+ fonts:+ options.fonts === 'assets'+ ? async (fonts, basePath) =>+ (await exportWebFontFaceAssets({ fonts, assetBasePath: basePath })).assets+ : 'none',+ assetBasePath: assetBasePath(fileName)+ })+ const page = bundle.files.find((file) => file.path === bundle.entrypoint)+ if (typeof page?.content !== 'string') throw new Error('HTML export produced no page')+ return { html: page.content, assets: bundle.files.filter((file) => file !== page) }+}diff --git a/packages/core/src/io/index.ts b/packages/core/src/io/index.tsindex a1fbe3976..7e5a8db57 100644--- a/packages/core/src/io/index.ts+++ b/packages/core/src/io/index.ts@@ -9,7 +9,9 @@ export {jpgFormat,webpFormat,svgFormat,- jsxFormat+ jsxFormat,+ htmlFormat,+ tailwindJSXFormat} from './formats'export { exportFigFile, parseFigFile, readFigFile, type ParseFigFileOptions } from './formats/fig'export { parsePenFile, readPenFile } from '@open-pencil/pen'@@ -51,7 +53,9 @@ export type {ReadDocumentResult,ExportTarget,ExportRequest,+ ExportAsset,ExportResult,+ HTMLExportOptions,IOContext,FigWriteOptions,RasterExportOptions,diff --git a/packages/core/src/io/types.ts b/packages/core/src/io/types.tsindex dbe6ecf20..9b7c4a680 100644--- a/packages/core/src/io/types.ts+++ b/packages/core/src/io/types.ts@@ -81,12 +81,28 @@ export interface SVGExportOptions {colorSpace?: RenderColorSpace}+/** A file written next to an export's main file, at a path relative to it. */+export interface ExportAsset {+ path: string+ content: IOData+}+export interface ExportResult {format: stringmimeType: stringextension: stringdata: IODataencoding?: IOTextEncoding+ /** Extra files the main file refers to, such as external images and fonts. */+ assets?: ExportAsset[]+}++export interface HTMLExportOptions {+ html?: 'fragment' | 'standalone'+ style?: 'inline' | 'tailwind'+ assets?: 'inline' | 'external'+ /** `assets` ships web fonts with external assets. */+ fonts?: 'assets' | 'none'}export interface IOFormatSupport {diff --git a/packages/core/src/text/web-font/assets.ts b/packages/core/src/text/web-font/assets.tsindex 05849bba8..60e94e7fe 100644--- a/packages/core/src/text/web-font/assets.ts+++ b/packages/core/src/text/web-font/assets.ts@@ -1,6 +1,6 @@import type { RemoteFontSource, ResolveFontResult } from 'unifont'-import type { WebFontFaceAsset, WebFontFaceRequest } from '@open-pencil/dom-css'+import type { WebFontFaceAsset, WebFontFaceRequest } from '@open-pencil/dom-css/export'import {createProviderUnifont,diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex 5d20f429e..50830d789 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -53,7 +53,7 @@ This policy does not apply to exports from the running app, or to SVG, PowerPoinExport as JSX with Tailwind utility classes:```sh-openpencil export design.fig -f jsx --style tailwind+openpencil export design.fig -f tailwind-jsx # or: -f jsx --style tailwind```Output:diff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.mdindex a9dde4318..80c5f5abe 100644--- a/packages/docs/reference/cli.md+++ b/packages/docs/reference/cli.md@@ -98,13 +98,13 @@ openpencil export [file] [options]| Option | Alias | Description ||--------|-------|-------------|-| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `jsx`, `html`, `fig` |+| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `pdf`, `pptx`, `jsx`, `tailwind-jsx`, `html`, `fig` || `--output` | `-o` | Output file path (default: `<name>.<format>`) || `--scale` | `-s` | Export scale (default: 1) || `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) || `--page` | | Page name (default: first page) || `--node` | | Node ID to export (default: all top-level nodes) |-| `--style` | | JSX style: `openpencil` (default), `tailwind` |+| `--style` | | JSX style: `openpencil` (default), `tailwind` (same as `-f tailwind-jsx`) || `--html` | | HTML mode: `fragment` (default), `standalone` || `--css` | | HTML CSS output: `inline` (default), `tailwind` || `--assets` | | Standalone HTML assets: `inline` (default), `external` |diff --git a/packages/dom-css/package.json b/packages/dom-css/package.jsonindex e09f91e4e..c25fab703 100644--- a/packages/dom-css/package.json+++ b/packages/dom-css/package.json@@ -23,6 +23,12 @@"import": "./dist/browser.js","default": "./dist/browser.js"},+ "./export": {+ "types": "./dist/export.d.ts",+ "bun": "./src/export.ts",+ "import": "./dist/export.js",+ "default": "./dist/export.js"+ },"./jsx-runtime": {"types": "./dist/jsx-runtime.d.ts","bun": "./src/jsx/runtime.ts",diff --git a/packages/dom-css/src/browser.ts b/packages/dom-css/src/browser.tsindex 1e0834ab5..f35f73441 100644--- a/packages/dom-css/src/browser.ts+++ b/packages/dom-css/src/browser.ts@@ -8,7 +8,6 @@ import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './to-sceneimport 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/export.ts b/packages/dom-css/src/export.tsnew file mode 100644index 000000000..a49e11f74--- /dev/null+++ b/packages/dom-css/src/export.ts@@ -0,0 +1,14 @@+// SceneGraph → HTML and JSX without the CSS runtimes, so browsers can bundle it.+export { sceneGraphToDesignDocument, sceneNodeToDesignDocument } from './from-scene-graph'+export { exportHTMLBundle } from './html-export'+export { designDocumentToTailwindJSX, sceneNodesToTailwindJSX } from './jsx/print'+export { serializeHTML } from './serialize'+export type {+ ExportHTMLBundle,+ ExportHTMLBundleOptions,+ ExportHTMLFile,+ WebFontFaceAsset,+ WebFontFaceRequest,+ WebFontFaceResolver+} from './html-export'+export type { DesignDocument, DesignElement, DesignNode } from './types'diff --git a/packages/dom-css/src/html-export.ts b/packages/dom-css/src/html-export.tsindex 3590e6563..ff66a188e 100644--- a/packages/dom-css/src/html-export.ts+++ b/packages/dom-css/src/html-export.ts@@ -1,4 +1,4 @@-import { CSSFontFaceRule } from '@acemir/cssom'+import type { CSSFontFaceRule } from '@acemir/cssom'import { isValid, toUint8Array } from 'js-base64'import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'@@ -192,7 +192,7 @@ async function compileTailwindClasses(classNames: string[]): Promise<string> {if (classNames.length === 0) return ''const [{ compile }, { readFile }] = await Promise.all([import('tailwindcss'),- import('node:fs/promises')+ import(/* @vite-ignore */ 'node:fs/promises')])const [themeCSS, utilitiesCSS] = await Promise.all([readFile(new URL(import.meta.resolve('tailwindcss/theme.css')), 'utf8'),@@ -240,8 +240,8 @@ function fontSourceValue(asset: WebFontFaceAsset): string {)}-function fontFaceCSS(asset: WebFontFaceAsset): string {- const rule = new CSSFontFaceRule()+function fontFaceCSS(FontFaceRule: typeof CSSFontFaceRule, asset: WebFontFaceAsset): string {+ const rule = new FontFaceRule()rule.style.setProperty('font-family', JSON.stringify(asset.family))rule.style.setProperty('src', fontSourceValue(asset))rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))@@ -261,8 +261,15 @@ async function fontFaceAssets(if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }const requests = new Map<string, WebFontFaceRequest>()for (const child of document.children) collectFontRequests(child, requests)- const assets = await options.fonts([...requests.values()], `${options.assetBasePath}/fonts`)- return { css: assets.map(fontFaceCSS).join(''), files: assets }+ // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.+ const [assets, cssom] = await Promise.all([+ options.fonts([...requests.values()], `${options.assetBasePath}/fonts`),+ import('@acemir/cssom')+ ])+ return {+ css: assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset)).join(''),+ files: assets+ }}function dataImageParts(value: string): { mime: string; base64: string } | undefined {diff --git a/packages/dom-css/tsconfig.json b/packages/dom-css/tsconfig.jsonindex 126d11199..e7f911fe5 100644--- a/packages/dom-css/tsconfig.json+++ b/packages/dom-css/tsconfig.json@@ -19,6 +19,7 @@"#dom-css/*": ["./src/*"],"@open-pencil/dom-css": ["./src/index.ts"],"@open-pencil/dom-css/browser": ["./src/browser.ts"],+ "@open-pencil/dom-css/export": ["./src/export.ts"],"@open-pencil/dom-css/jsx-runtime": ["./src/jsx/runtime.ts"],"@open-pencil/dom-css/jsx-dev-runtime": ["./src/jsx/dev-runtime.ts"]}diff --git a/packages/dom-css/tsdown.config.ts b/packages/dom-css/tsdown.config.tsindex a82f8740c..b2d737ed8 100644--- a/packages/dom-css/tsdown.config.ts+++ b/packages/dom-css/tsdown.config.ts@@ -4,6 +4,7 @@ export default defineConfig({entry: {index: './src/index.ts',browser: './src/browser.ts',+ export: './src/export.ts','jsx-runtime': './src/jsx/runtime.ts','jsx-dev-runtime': './src/jsx/dev-runtime.ts'},diff --git a/src/app/automation/bridge/export-handlers.ts b/src/app/automation/bridge/export-handlers.tsindex 7cc8f4107..7df9f1683 100644--- a/src/app/automation/bridge/export-handlers.ts+++ b/src/app/automation/bridge/export-handlers.ts@@ -1,7 +1,7 @@import { fromUint8Array } from 'js-base64'import { selectionToJSX, type RasterExportFormat } from '@open-pencil/core/io'-import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/browser'+import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/export'import type { AutomationTarget } from '@/app/automation/bridge/target'diff --git a/src/app/code/generated.ts b/src/app/code/generated.tsindex 5c039892f..fd44747aa 100644--- a/src/app/code/generated.ts+++ b/src/app/code/generated.ts@@ -1,5 +1,5 @@import { selectionToJSX } from '@open-pencil/core/design-jsx'-import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/browser'+import { sceneNodesToTailwindJSX } from '@open-pencil/dom-css/export'import type { SceneGraph } from '@open-pencil/scene-graph'import { starterSourceFor, type CodeSource } from '@/app/code/templates'diff --git a/tests/engine/io/dom-css-formats.test.ts b/tests/engine/io/dom-css-formats.test.tsnew file mode 100644index 000000000..e523f8605--- /dev/null+++ b/tests/engine/io/dom-css-formats.test.ts@@ -0,0 +1,91 @@+import { describe, expect, test } from 'bun:test'++import { toUint8Array } from 'js-base64'++import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'+import { SceneGraph } from '@open-pencil/scene-graph'++const io = new IORegistry(BUILTIN_IO_FORMATS)++function cardGraph() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const card = graph.createNode('FRAME', page.id, {+ name: 'Card',+ width: 120,+ height: 80,+ layoutMode: 'VERTICAL'+ })+ graph.createNode('TEXT', card.id, { name: 'Title', text: 'Hello', width: 100, height: 20 })+ // A 1×1 PNG, exported as an external image file.+ const png = toUint8Array(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='+ )+ graph.images.set('pixel', png)+ graph.createNode('RECTANGLE', card.id, {+ name: 'Photo',+ width: 40,+ height: 40,+ fills: [+ { type: 'IMAGE', imageHash: 'pixel', imageScaleMode: 'FILL', opacity: 1, visible: true }+ ]+ })+ return { graph, page, card }+}++describe('HTML export format', () => {+ test('exports a node with its own box', async () => {+ const { graph, card } = cardGraph()+ const result = await io.exportContent('html', {+ graph,+ target: { scope: 'node', nodeId: card.id }+ })++ expect(result).toMatchObject({ format: 'html', extension: 'html', mimeType: 'text/html' })+ expect(String(result.data)).toContain('width: 120px')+ expect(String(result.data)).toContain('Hello')+ })++ test('writes external assets next to the file it was named after', async () => {+ const { graph, page } = cardGraph()+ const result = await io.exportContent(+ 'html',+ { graph, target: { scope: 'page', pageId: page.id }, fileName: 'out/card.html' },+ { html: 'standalone', assets: 'external' }+ )++ const paths = (result.assets ?? []).map((asset) => asset.path)+ expect(paths.length).toBeGreaterThan(0)+ for (const path of paths) expect(path).toStartWith('card.assets/')+ for (const path of paths) expect(String(result.data)).toContain(path)+ })+})++describe('HTML export asset paths', () => {+ test('are relative for Windows paths too', async () => {+ const { graph, page } = cardGraph()+ const result = await io.exportContent(+ 'html',+ { graph, target: { scope: 'page', pageId: page.id }, fileName: 'C:\\out\\card.html' },+ { html: 'standalone', assets: 'external' }+ )++ const paths = (result.assets ?? []).map((asset) => asset.path)+ expect(paths.length).toBeGreaterThan(0)+ for (const path of paths) expect(path).toStartWith('card.assets/')+ })+})++describe('Tailwind JSX export format', () => {+ test('is a registered export next to OpenPencil JSX', async () => {+ const { graph, card } = cardGraph()+ const result = await io.exportContent('tailwind-jsx', {+ graph,+ target: { scope: 'selection', nodeIds: [card.id] }+ })++ expect(result).toMatchObject({ format: 'tailwind-jsx', extension: 'jsx' })+ expect(String(result.data)).toStartWith('<div data-name="Card" className="flex flex-col')+ expect(io.listExportFormats('page').map((format) => format.id)).toContain('tailwind-jsx')+ })+})diff --git a/tsconfig.json b/tsconfig.jsonindex 5f3b76dba..433ea1073 100644--- a/tsconfig.json+++ b/tsconfig.json@@ -94,7 +94,9 @@"src/**/*.ts","src/**/*.vue","packages/core/src/global.d.ts",- "packages/vue/src/global.d.ts"+ "packages/vue/src/global.d.ts",+ "packages/dom-css/src/cssom.d.ts",+ "packages/dom-css/src/postcss-value-parser.d.ts"],"references": [{diff --git a/vite/aliases.ts b/vite/aliases.tsindex 283d4f89f..41164a64b 100644--- a/vite/aliases.ts+++ b/vite/aliases.ts@@ -14,6 +14,10 @@ export function createOpenPencilAliases(rootDir: string) {find: /^@open-pencil\/dom-css\/browser$/,replacement: resolve(rootDir, 'packages/dom-css/src/browser.ts')},+ {+ find: /^@open-pencil\/dom-css\/export$/,+ replacement: resolve(rootDir, 'packages/dom-css/src/export.ts')+ },{find: /^@open-pencil\/dom-css\/jsx-runtime$/,replacement: resolve(rootDir, 'packages/dom-css/src/jsx/runtime.ts')