import type { CSSFontFaceRule } from '@acemir/cssom' import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5' import { normalizeFontFamily } from '@open-pencil/scene-graph/font-style' import { parseDataURL } from '@open-pencil/scene-graph/images' import { maxOf, minOf } from '@open-pencil/std/arrays' import { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet' import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types' import { mergeClassNames, serializeHTML, splitWhitespace } from './html' /** A font face the exported text uses. */ export interface WebFontFaceRequest { family: string weight: number style?: 'normal' | 'italic' } /** A font file to ship next to the page, described as an `@font-face` rule. */ export interface WebFontFaceAsset { family: string weight: string | number | [number, number] style: string display?: string stretch?: string unicodeRange?: string[] format: 'woff2' | 'woff' | 'opentype' | 'truetype' path: string content: Uint8Array } /** Finds font files for the requested faces; paths start with `assetBasePath`. */ export type WebFontFaceResolver = ( fonts: WebFontFaceRequest[], assetBasePath: string ) => Promise export interface ExportHTMLBundleOptions { html?: 'fragment' | 'standalone' style?: 'inline' | 'tailwind' assets?: 'inline' | 'external' /** Resolves font files to include with external assets; `none` includes no fonts. */ fonts?: 'none' | WebFontFaceResolver assetBasePath?: string } export interface ExportHTMLFile { path: string content: string | Uint8Array } export interface ExportHTMLBundle { entrypoint: string files: ExportHTMLFile[] } interface StandaloneBounds { minX: number minY: number width: number height: number } type ParseNode = DefaultTreeAdapterTypes.Node type ParseParent = DefaultTreeAdapterTypes.ParentNode type ParseElement = DefaultTreeAdapterTypes.Element const RESET_CSS = '*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}' function styleToCSS(style: DesignStyleDeclaration): string { return Object.entries(style) .filter(([, value]) => value !== '') .map(([property, value]) => `${property}: ${value}`) .join('; ') } function cloneNode(node: DesignNode): DesignNode { if (node.type === 'text') return { ...node } return { ...node, attrs: { ...node.attrs }, inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined, children: node.children.map(cloneNode) } } function standaloneStyleForNode( node: DesignElement, parent: DesignElement | undefined, origin: StandaloneBounds ): DesignStyleDeclaration { const style = { ...node.inlineStyle } const source = node.sourceSceneNode if (!source) return style style.position = 'absolute' style.left = `${source.x - (parent ? 0 : origin.minX)}px` style.top = `${source.y - (parent ? 0 : origin.minY)}px` return style } function standaloneNode( node: DesignNode, origin: StandaloneBounds, parent?: DesignElement ): DesignNode { if (node.type === 'text') return cloneNode(node) const standalone: DesignElement = { ...node, attrs: { ...node.attrs }, inlineStyle: standaloneStyleForNode(node, parent, origin), children: [] } standalone.children = node.children.map((child) => standaloneNode(child, origin, node)) return standalone } function nodeBounds(node: DesignNode): StandaloneBounds | undefined { if (node.type === 'text' || !node.sourceSceneNode) return undefined return { minX: node.sourceSceneNode.x, minY: node.sourceSceneNode.y, width: node.sourceSceneNode.width, height: node.sourceSceneNode.height } } function standaloneSize(document: DesignDocument): StandaloneBounds { const bounds = document.children .map(nodeBounds) .filter((value): value is NonNullable => value !== undefined) const minX = bounds.length > 0 ? minOf(bounds.map((bound) => bound.minX)) : 0 const minY = bounds.length > 0 ? minOf(bounds.map((bound) => bound.minY)) : 0 const maxX = bounds.length > 0 ? maxOf(bounds.map((bound) => bound.minX + bound.width)) : 1 const maxY = bounds.length > 0 ? maxOf(bounds.map((bound) => bound.minY + bound.height)) : 1 return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) } } function standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument { return { ...document, children: document.children.map((node) => standaloneNode(node, size)) } } function cssClassName(index: number): string { return `op-${index.toString(36)}` } function extractInlineStyles( node: DesignNode, rules: string[], nextIndex: { value: number } ): DesignNode { if (node.type === 'text') return node const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex)) if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children } const className = cssClassName(nextIndex.value) nextIndex.value += 1 rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`) return { ...node, attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className }, inlineStyle: undefined, children } } function isElement(node: ParseNode): node is ParseElement { return 'attrs' in node && 'tagName' in node } function walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void { if (isElement(node)) visit(node) if ('childNodes' in node) { for (const child of node.childNodes) walkParseTree(child, visit) } } function classNamesFromHTML(html: string): string[] { const fragment = parseFragment(html) const classes = new Set() walkParseTree(fragment, (element) => { const classAttr = element.attrs.find((attr) => attr.name === 'class') if (!classAttr) return for (const className of splitWhitespace(classAttr.value)) classes.add(className) }) return [...classes] } /** * The stylesheet for the tokens the document references, in the format the page needs: plain * custom properties for inline styles, `@theme` for Tailwind, so token utilities compile. */ async function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise { const { tokens, sourceGraph } = document if (!tokens || !sourceGraph || tokens.used.size === 0) return '' const variables = tokens.stylesheetVariables() const { css } = await tokenStylesheet(sourceGraph, { format, include: (variable) => variables.has(variable.id) }) return css } async function compileTailwindClasses(classNames: string[], tokens: string): Promise { if (classNames.length === 0) return '' const [{ compile }, { readFile }] = await Promise.all([ import('tailwindcss'), import(/* @vite-ignore */ 'node:fs/promises') ]) const [themeCSS, utilitiesCSS] = await Promise.all([ readFile(new URL(import.meta.resolve('tailwindcss/theme.css')), 'utf8'), readFile(new URL(import.meta.resolve('tailwindcss/utilities.css')), 'utf8') ]) const compiler = await compile(`${themeCSS}\n${tokens}\n${utilitiesCSS}`) return compiler.build(classNames) } function collectFontRequests(node: DesignNode, fonts: Map): void { if (node.type === 'text') return const source = node.sourceSceneNode if (source?.type === 'TEXT') { const family = normalizeFontFamily(source.fontFamily) const style = source.italic ? 'italic' : 'normal' const key = `${family}|${source.fontWeight}|${style}` fonts.set(key, { family, weight: source.fontWeight, style }) } for (const child of node.children) collectFontRequests(child, fonts) } function serializeFontWeight(weight: string | number | [number, number]): string { return Array.isArray(weight) ? weight.join(' ') : String(weight) } function fontSourceValue(asset: WebFontFaceAsset, from: string): string { // Relative to the stylesheet's folder, which the asset's path may start with. const path = from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path const url = new URL(path, 'file:///') const escapedPath = url.pathname.slice(1) return ['url(', JSON.stringify(escapedPath), ') format(', JSON.stringify(asset.format), ')'].join( '' ) } interface FontFaceCSSOptions { /** The folder the stylesheet is in, which font paths are written relative to. */ from: string /** `font-display` for every face, rather than each face's own. */ display?: string } function fontFaceCSS( FontFaceRule: typeof CSSFontFaceRule, asset: WebFontFaceAsset, options: FontFaceCSSOptions ): string { const rule = new FontFaceRule() rule.style.setProperty('font-family', JSON.stringify(asset.family)) rule.style.setProperty('src', fontSourceValue(asset, options.from)) rule.style.setProperty('font-weight', serializeFontWeight(asset.weight)) rule.style.setProperty('font-style', asset.style) rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap') if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch) if (asset.unicodeRange && asset.unicodeRange.length > 0) { rule.style.setProperty('unicode-range', asset.unicodeRange.join(',')) } return rule.cssText } /** Every font face a document's text uses, once each. */ export function designFontRequests(document: DesignDocument): WebFontFaceRequest[] { const requests = new Map() for (const child of document.children) collectFontRequests(child, requests) return [...requests.values()] } /** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */ export async function fontFaceStylesheet( assets: readonly WebFontFaceAsset[], options: FontFaceCSSOptions ): Promise { if (assets.length === 0) return '' // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers. const cssom = await import('@acemir/cssom') return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('') } async function fontFaceAssets( document: DesignDocument, options: Required ): Promise<{ css: string; files: ExportHTMLFile[] }> { if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] } const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`) // The page's stylesheet sits at the top, so font paths stay as they are. return { css: await fontFaceStylesheet(assets, { from: '' }), files: assets } } /** The file extension of each raster type a bundle moves out of the page. */ const IMAGE_EXTENSIONS: Partial> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp', 'image/avif': 'avif' } /** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */ export function extractImageAssets( html: string, assetBasePath: string ): { html: string; files: ExportHTMLFile[] } { const fragment = parseFragment(html) const files: ExportHTMLFile[] = [] const sources = new Map() walkParseTree(fragment, (element) => { const src = element.attrs.find((attr) => attr.name === 'src') if (!src) return const cachedPath = sources.get(src.value) if (cachedPath) { src.value = cachedPath return } // Documents can come from parsed HTML. Only a raster type a file extension names moves to a // file: an SVG could run script when its file is opened on the site's origin, and the rest, // such as a data URL that does not decode, stays inline. const image = parseDataURL(src.value) const extension = image && IMAGE_EXTENSIONS[image.mimeType] if (!image || !extension) return const path = `${assetBasePath}/images/image-${sources.size + 1}.${extension}` sources.set(src.value, path) files.push({ path, content: image.bytes }) src.value = path }) return { html: serialize(fragment), files } } function stylesheetLink(path: string): string { return `` } function styleTag(css: string): string { return css ? `` : '' } async function exportStandaloneHTML( document: DesignDocument, options: Required ): Promise { const size = standaloneSize(document) const doc = standaloneDocument(document, size) const stageCSS = `.op-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}` let body: string let css = `${RESET_CSS}${stageCSS}` if (options.style === 'tailwind') { body = serializeHTML(doc, { style: 'tailwind' }) css += await compileTailwindClasses( classNamesFromHTML(body), await tokenCSS(document, 'tailwind') ) } else { css += await tokenCSS(document, 'css') const rules: string[] = [] const index = { value: 0 } const styledDocument: DesignDocument = { ...doc, children: doc.children.map((node) => extractInlineStyles(node, rules, index)) } body = serializeHTML(styledDocument) css += rules.join('') } if (options.assets === 'external') { const [extracted, fonts] = await Promise.all([ Promise.resolve(extractImageAssets(body, options.assetBasePath)), fontFaceAssets(document, options) ]) body = extracted.html const cssPath = `${options.assetBasePath}/openpencil.css` const html = `${stylesheetLink(cssPath)}
${body}
` return { entrypoint: 'index.html', files: [ { path: 'index.html', content: html }, { path: cssPath, content: `${fonts.css}${css}` }, ...fonts.files, ...extracted.files ] } } const html = `${styleTag(css)}
${body}
` return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] } } export async function exportHTMLBundle( document: DesignDocument, options: ExportHTMLBundleOptions = {} ): Promise { const resolvedOptions: Required = { html: options.html ?? 'fragment', style: options.style ?? 'inline', assets: options.assets ?? 'inline', fonts: options.fonts ?? 'none', assetBasePath: options.assetBasePath ?? 'assets' } if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions) return { entrypoint: 'index.html', files: [ { path: 'index.html', content: serializeHTML(document, { style: resolvedOptions.style }) } ] } }