@pairdraw/dom-css 0.16.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.js","names":[],"sources":["../../../src/export/bundle.ts"],"sourcesContent":["import type { CSSFontFaceRule } from '@acemir/cssom'\nimport { isValid, toUint8Array } from 'js-base64'\nimport { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { normalizeFontFamily } from '@pairdraw/scene-graph/font-style'\n\nimport { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { mergeClassNames, serializeHTML, splitWhitespace } from './html'\n\n/** A font face the exported text uses. */\nexport interface WebFontFaceRequest {\n family: string\n weight: number\n style?: 'normal' | 'italic'\n}\n\n/** A font file to ship next to the page, described as an `@font-face` rule. */\nexport interface WebFontFaceAsset {\n family: string\n weight: string | number | [number, number]\n style: string\n display?: string\n stretch?: string\n unicodeRange?: string[]\n format: 'woff2' | 'woff' | 'opentype' | 'truetype'\n path: string\n content: Uint8Array\n}\n\n/** Finds font files for the requested faces; paths start with `assetBasePath`. */\nexport type WebFontFaceResolver = (\n fonts: WebFontFaceRequest[],\n assetBasePath: string\n) => Promise<WebFontFaceAsset[]>\n\nexport interface ExportHTMLBundleOptions {\n html?: 'fragment' | 'standalone'\n style?: 'inline' | 'tailwind'\n assets?: 'inline' | 'external'\n /** Resolves font files to include with external assets; `none` includes no fonts. */\n fonts?: 'none' | WebFontFaceResolver\n assetBasePath?: string\n /**\n * Reads one of Tailwind's stylesheets, `tailwindcss/theme.css` or `tailwindcss/utilities.css`,\n * for a standalone Tailwind page. Browsers pass one; Node and Bun read the installed package.\n */\n loadTailwindStylesheet?: TailwindStylesheetLoader\n}\n\nexport type TailwindStylesheetLoader = (id: TailwindStylesheetId) => Promise<string>\nexport type TailwindStylesheetId = 'tailwindcss/theme.css' | 'tailwindcss/utilities.css'\n\nexport interface ExportHTMLFile {\n path: string\n content: string | Uint8Array\n}\n\nexport interface ExportHTMLBundle {\n entrypoint: string\n files: ExportHTMLFile[]\n}\n\ninterface StandaloneBounds {\n minX: number\n minY: number\n width: number\n height: number\n}\n\ntype ParseNode = DefaultTreeAdapterTypes.Node\ntype ParseParent = DefaultTreeAdapterTypes.ParentNode\ntype ParseElement = DefaultTreeAdapterTypes.Element\n\nconst RESET_CSS =\n '*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}'\n\nfunction styleToCSS(style: DesignStyleDeclaration): string {\n return Object.entries(style)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction cloneNode(node: DesignNode): DesignNode {\n if (node.type === 'text') return { ...node }\n return {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined,\n children: node.children.map(cloneNode)\n }\n}\n\nfunction standaloneStyleForNode(\n node: DesignElement,\n parent: DesignElement | undefined,\n origin: StandaloneBounds\n): DesignStyleDeclaration {\n const style = { ...node.inlineStyle }\n const source = node.sourceSceneNode\n if (!source) return style\n\n style.position = 'absolute'\n style.left = `${source.x - (parent ? 0 : origin.minX)}px`\n style.top = `${source.y - (parent ? 0 : origin.minY)}px`\n return style\n}\n\nfunction standaloneNode(\n node: DesignNode,\n origin: StandaloneBounds,\n parent?: DesignElement\n): DesignNode {\n if (node.type === 'text') return cloneNode(node)\n const standalone: DesignElement = {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: standaloneStyleForNode(node, parent, origin),\n children: []\n }\n standalone.children = node.children.map((child) => standaloneNode(child, origin, node))\n return standalone\n}\n\nfunction nodeBounds(node: DesignNode): StandaloneBounds | undefined {\n if (node.type === 'text' || !node.sourceSceneNode) return undefined\n return {\n minX: node.sourceSceneNode.x,\n minY: node.sourceSceneNode.y,\n width: node.sourceSceneNode.width,\n height: node.sourceSceneNode.height\n }\n}\n\nfunction standaloneSize(document: DesignDocument): StandaloneBounds {\n const bounds = document.children\n .map(nodeBounds)\n .filter((value): value is NonNullable<typeof value> => value !== undefined)\n const minX = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minX)) : 0\n const minY = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minY)) : 0\n const maxX = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minX + bound.width)) : 1\n const maxY = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minY + bound.height)) : 1\n return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) }\n}\n\nfunction standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument {\n return {\n ...document,\n children: document.children.map((node) => standaloneNode(node, size))\n }\n}\n\nfunction cssClassName(index: number): string {\n return `op-${index.toString(36)}`\n}\n\nfunction extractInlineStyles(\n node: DesignNode,\n rules: string[],\n nextIndex: { value: number }\n): DesignNode {\n if (node.type === 'text') return node\n const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex))\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children }\n\n const className = cssClassName(nextIndex.value)\n nextIndex.value += 1\n rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`)\n return {\n ...node,\n attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className },\n inlineStyle: undefined,\n children\n }\n}\n\nfunction isElement(node: ParseNode): node is ParseElement {\n return 'attrs' in node && 'tagName' in node\n}\n\nfunction walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void {\n if (isElement(node)) visit(node)\n if ('childNodes' in node) {\n for (const child of node.childNodes) walkParseTree(child, visit)\n }\n}\n\nfunction classNamesFromHTML(html: string): string[] {\n const fragment = parseFragment(html)\n const classes = new Set<string>()\n walkParseTree(fragment, (element) => {\n const classAttr = element.attrs.find((attr) => attr.name === 'class')\n if (!classAttr) return\n for (const className of splitWhitespace(classAttr.value)) classes.add(className)\n })\n return [...classes]\n}\n\n/**\n * The stylesheet for the tokens the document references, in the format the page needs: plain\n * custom properties for inline styles, `@theme` for Tailwind, so token utilities compile.\n */\nasync function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise<string> {\n const { tokens, sourceGraph } = document\n if (!tokens || !sourceGraph || tokens.used.size === 0) return ''\n const variables = tokens.stylesheetVariables()\n const { css } = await tokenStylesheet(sourceGraph, {\n format,\n include: (variable) => variables.has(variable.id)\n })\n return css\n}\n\nasync function readInstalledTailwindStylesheet(id: TailwindStylesheetId): Promise<string> {\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(new URL(import.meta.resolve(id)), 'utf8')\n}\n\nasync function compileTailwindClasses(\n classNames: string[],\n tokens: string,\n load: TailwindStylesheetLoader = readInstalledTailwindStylesheet\n): Promise<string> {\n if (classNames.length === 0) return ''\n const [{ compile }, themeCSS, utilitiesCSS] = await Promise.all([\n import('tailwindcss'),\n load('tailwindcss/theme.css'),\n load('tailwindcss/utilities.css')\n ])\n const compiler = await compile(`${themeCSS}\\n${tokens}\\n${utilitiesCSS}`)\n return compiler.build(classNames)\n}\n\nfunction collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {\n if (node.type === 'text') return\n const source = node.sourceSceneNode\n if (source?.type === 'TEXT') {\n const family = normalizeFontFamily(source.fontFamily)\n const style = source.italic ? 'italic' : 'normal'\n const key = `${family}|${source.fontWeight}|${style}`\n fonts.set(key, { family, weight: source.fontWeight, style })\n }\n for (const child of node.children) collectFontRequests(child, fonts)\n}\n\nfunction serializeFontWeight(weight: string | number | [number, number]): string {\n return Array.isArray(weight) ? weight.join(' ') : String(weight)\n}\n\n/**\n * A relative file path as a URL that points at it: each folder and file name percent-encoded,\n * so a page named `Card #1` finds `Card #1.assets/` rather than reading `#1` as a fragment.\n */\nfunction assetURL(path: string): string {\n return path.split('/').map(encodeURIComponent).join('/')\n}\n\nfunction fontSourceValue(asset: WebFontFaceAsset, from: string): string {\n // Relative to the stylesheet's folder, which the asset's path may start with.\n const path =\n from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path\n return [\n 'url(',\n JSON.stringify(assetURL(path)),\n ') format(',\n JSON.stringify(asset.format),\n ')'\n ].join('')\n}\n\ninterface FontFaceCSSOptions {\n /** The folder the stylesheet is in, which font paths are written relative to. */\n from: string\n /** `font-display` for every face, rather than each face's own. */\n display?: string\n}\n\nfunction fontFaceCSS(\n FontFaceRule: typeof CSSFontFaceRule,\n asset: WebFontFaceAsset,\n options: FontFaceCSSOptions\n): string {\n const rule = new FontFaceRule()\n rule.style.setProperty('font-family', JSON.stringify(asset.family))\n rule.style.setProperty('src', fontSourceValue(asset, options.from))\n rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))\n rule.style.setProperty('font-style', asset.style)\n rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')\n if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)\n if (asset.unicodeRange && asset.unicodeRange.length > 0) {\n rule.style.setProperty('unicode-range', asset.unicodeRange.join(','))\n }\n return rule.cssText\n}\n\n/** Every font face a document's text uses, once each. */\nexport function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {\n const requests = new Map<string, WebFontFaceRequest>()\n for (const child of document.children) collectFontRequests(child, requests)\n return [...requests.values()]\n}\n\n/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */\nexport async function fontFaceStylesheet(\n assets: readonly WebFontFaceAsset[],\n options: FontFaceCSSOptions\n): Promise<string> {\n if (assets.length === 0) return ''\n // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.\n const cssom = await import('@acemir/cssom')\n return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')\n}\n\nasync function fontFaceAssets(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<{ css: string; files: ExportHTMLFile[] }> {\n if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }\n const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)\n // The page's stylesheet sits in the asset folder, beside the fonts' own folder.\n return {\n css: await fontFaceStylesheet(assets, { from: options.assetBasePath }),\n files: assets\n }\n}\n\nfunction dataImageParts(value: string): { mime: string; base64: string } | undefined {\n if (!value.startsWith('data:image/')) return undefined\n const marker = ';base64,'\n const markerIndex = value.indexOf(marker)\n if (markerIndex === -1) return undefined\n const base64 = value.slice(markerIndex + marker.length)\n // Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.\n if (!isValid(base64)) return undefined\n return { mime: value.slice('data:'.length, markerIndex), base64 }\n}\n\nfunction extensionForMime(mime: string): string {\n if (mime === 'image/jpeg') return 'jpg'\n if (mime === 'image/webp') return 'webp'\n if (mime === 'image/gif') return 'gif'\n if (mime === 'image/svg+xml') return 'svg'\n return 'png'\n}\n\n/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */\nexport function extractImageAssets(\n html: string,\n assetBasePath: string\n): { html: string; files: ExportHTMLFile[] } {\n const fragment = parseFragment(html)\n const files: ExportHTMLFile[] = []\n const sources = new Map<string, string>()\n walkParseTree(fragment, (element) => {\n const src = element.attrs.find((attr) => attr.name === 'src')\n if (!src) return\n const parts = dataImageParts(src.value)\n if (!parts) return\n const cachedPath = sources.get(src.value)\n if (cachedPath) {\n src.value = assetURL(cachedPath)\n return\n }\n const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`\n sources.set(src.value, path)\n files.push({ path, content: toUint8Array(parts.base64) })\n src.value = assetURL(path)\n })\n return { html: serialize(fragment), files }\n}\n\nfunction stylesheetLink(path: string): string {\n return `<link rel=\"stylesheet\" href=\"${assetURL(path)}\">`\n}\n\nfunction styleTag(css: string): string {\n return css ? `<style>${css}</style>` : ''\n}\n\ntype ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &\n Pick<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>\n\nasync function exportStandaloneHTML(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<ExportHTMLBundle> {\n const size = standaloneSize(document)\n const doc = standaloneDocument(document, size)\n const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`\n let body: string\n let css = `${RESET_CSS}${stageCSS}`\n\n if (options.style === 'tailwind') {\n body = serializeHTML(doc, { style: 'tailwind' })\n css += await compileTailwindClasses(\n classNamesFromHTML(body),\n await tokenCSS(document, 'tailwind'),\n options.loadTailwindStylesheet\n )\n } else {\n css += await tokenCSS(document, 'css')\n const rules: string[] = []\n const index = { value: 0 }\n const styledDocument: DesignDocument = {\n ...doc,\n children: doc.children.map((node) => extractInlineStyles(node, rules, index))\n }\n body = serializeHTML(styledDocument)\n css += rules.join('')\n }\n\n if (options.assets === 'external') {\n const [extracted, fonts] = await Promise.all([\n Promise.resolve(extractImageAssets(body, options.assetBasePath)),\n fontFaceAssets(document, options)\n ])\n body = extracted.html\n const cssPath = `${options.assetBasePath}/pairdraw.css`\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${stylesheetLink(cssPath)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return {\n entrypoint: 'index.html',\n files: [\n { path: 'index.html', content: html },\n { path: cssPath, content: `${fonts.css}${css}` },\n ...fonts.files,\n ...extracted.files\n ]\n }\n }\n\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${styleTag(css)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] }\n}\n\nexport async function exportHTMLBundle(\n document: DesignDocument,\n options: ExportHTMLBundleOptions = {}\n): Promise<ExportHTMLBundle> {\n const resolvedOptions: ResolvedBundleOptions = {\n html: options.html ?? 'fragment',\n style: options.style ?? 'inline',\n assets: options.assets ?? 'inline',\n fonts: options.fonts ?? 'none',\n assetBasePath: options.assetBasePath ?? 'assets',\n loadTailwindStylesheet: options.loadTailwindStylesheet\n }\n\n if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions)\n\n const fragment = serializeHTML(document, { style: resolvedOptions.style })\n if (resolvedOptions.assets !== 'external') {\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: fragment }] }\n }\n // A fragment has no stylesheet to declare fonts in, so only its images become files.\n const extracted = extractImageAssets(fragment, resolvedOptions.assetBasePath)\n return {\n entrypoint: 'index.html',\n files: [{ path: 'index.html', content: extracted.html }, ...extracted.files]\n }\n}\n"],"mappings":";;;;;;AA0EA,MAAM,YACJ;AAEF,SAAS,WAAW,OAAuC;CACzD,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,QAAQ,GAAG,WAAW,UAAU,EAAE,CAAC,CACnC,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAS,UAAU,MAA8B;CAC/C,IAAI,KAAK,SAAS,QAAQ,OAAO,EAAE,GAAG,KAAK;CAC3C,OAAO;EACL,GAAG;EACH,OAAO,EAAE,GAAG,KAAK,MAAM;EACvB,aAAa,KAAK,cAAc,EAAE,GAAG,KAAK,YAAY,IAAI,KAAA;EAC1D,UAAU,KAAK,SAAS,IAAI,SAAS;CACvC;AACF;AAEA,SAAS,uBACP,MACA,QACA,QACwB;CACxB,MAAM,QAAQ,EAAE,GAAG,KAAK,YAAY;CACpC,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,WAAW;CACjB,MAAM,OAAO,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACtD,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACrD,OAAO;AACT;AAEA,SAAS,eACP,MAC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AU;EACjB,MAAM,UAAU,GAAG,QAAQ,cAAc;EAEzC,OAAO;GACL,YAAY;GACZ,OAAO;IACL;KAAE,MAAM;KAAc,SAAS,wHAJkG,eAAe,OAAO,EAAE,4EAA4E,KAAK;IAItM;IACpC;KAAE,MAAM;KAAS,SAAS,GAAG,MAAM,MAAM;IAAM;IAC/C,GAAG,MAAM;IACT,GAAG,UAAU;GACf;EACF;CACF;CAGA,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,wHAD2D,SAAS,GAAG,EAAE,4EAA4E,KAAK;EACrJ,CAAC;CAAE;AACpF;AAEA,eAAsB,iBACpB,UACA,UAAmC,CAAC,GACT;CAC3B,MAAM,kBAAyC;EAC7C,MAAM,QAAQ,QAAQ;EACtB,OAAO,QAAQ,SAAS;EACxB,QAAQ,QAAQ,UAAU;EAC1B,OAAO,QAAQ,SAAS;EACxB,eAAe,QAAQ,iBAAiB;EACxC,wBAAwB,QAAQ;CAClC;CAEA,IAAI,gBAAgB,SAAS,cAAc,OAAO,qBAAqB,UAAU,eAAe;CAEhG,MAAM,WAAW,cAAc,UAAU,EAAE,OAAO,gBAAgB,MAAM,CAAC;CACzE,IAAI,gBAAgB,WAAW,YAC7B,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS;EAAS,CAAC;CAAE;CAGxF,MAAM,YAAY,mBAAmB,UAAU,gBAAgB,aAAa;CAC5E,OAAO;EACL,YAAY;EACZ,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,UAAU;EAAK,GAAG,GAAG,UAAU,KAAK;CAC7E;AACF"}
1
+ {"version":3,"file":"bundle.js","names":[],"sources":["../../../src/export/bundle.ts"],"sourcesContent":["import type { CSSFontFaceRule } from '@acemir/cssom'\nimport { isValid, toUint8Array } from 'js-base64'\nimport { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { normalizeFontFamily } from '@pairdraw/scene-graph/font-style'\n\nimport { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { mergeClassNames, serializeHTML, splitWhitespace } from './html'\n\n/** A font face the exported text uses. */\nexport interface WebFontFaceRequest {\n family: string\n weight: number\n style?: 'normal' | 'italic'\n}\n\n/** A font file to ship next to the page, described as an `@font-face` rule. */\nexport interface WebFontFaceAsset {\n family: string\n weight: string | number | [number, number]\n style: string\n display?: string\n stretch?: string\n unicodeRange?: string[]\n format: 'woff2' | 'woff' | 'opentype' | 'truetype'\n path: string\n content: Uint8Array\n}\n\n/** Finds font files for the requested faces; paths start with `assetBasePath`. */\nexport type WebFontFaceResolver = (\n fonts: WebFontFaceRequest[],\n assetBasePath: string\n) => Promise<WebFontFaceAsset[]>\n\nexport interface ExportHTMLBundleOptions {\n html?: 'fragment' | 'standalone'\n style?: 'inline' | 'tailwind'\n assets?: 'inline' | 'external'\n /** Resolves font files to include with external assets; `none` includes no fonts. */\n fonts?: 'none' | WebFontFaceResolver\n assetBasePath?: string\n /**\n * Reads one of Tailwind's stylesheets, `tailwindcss/theme.css` or `tailwindcss/utilities.css`,\n * for a standalone Tailwind page. Browsers pass one; Node and Bun read the installed package.\n */\n loadTailwindStylesheet?: TailwindStylesheetLoader\n}\n\nexport type TailwindStylesheetLoader = (id: TailwindStylesheetId) => Promise<string>\nexport type TailwindStylesheetId = 'tailwindcss/theme.css' | 'tailwindcss/utilities.css'\n\nexport interface ExportHTMLFile {\n path: string\n content: string | Uint8Array\n}\n\nexport interface ExportHTMLBundle {\n entrypoint: string\n files: ExportHTMLFile[]\n}\n\ninterface StandaloneBounds {\n minX: number\n minY: number\n width: number\n height: number\n}\n\ntype ParseNode = DefaultTreeAdapterTypes.Node\ntype ParseParent = DefaultTreeAdapterTypes.ParentNode\ntype ParseElement = DefaultTreeAdapterTypes.Element\n\nconst RESET_CSS =\n '*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}'\n\nfunction styleToCSS(style: DesignStyleDeclaration): string {\n return Object.entries(style)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction cloneNode(node: DesignNode): DesignNode {\n if (node.type === 'text') return { ...node }\n return {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined,\n children: node.children.map(cloneNode)\n }\n}\n\nfunction standaloneStyleForNode(\n node: DesignElement,\n parent: DesignElement | undefined,\n origin: StandaloneBounds\n): DesignStyleDeclaration {\n const style = { ...node.inlineStyle }\n const source = node.sourceSceneNode\n if (!source) return style\n\n style.position = 'absolute'\n style.left = `${source.x - (parent ? 0 : origin.minX)}px`\n style.top = `${source.y - (parent ? 0 : origin.minY)}px`\n return style\n}\n\nfunction standaloneNode(\n node: DesignNode,\n origin: StandaloneBounds,\n parent?: DesignElement\n): DesignNode {\n if (node.type === 'text') return cloneNode(node)\n const standalone: DesignElement = {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: standaloneStyleForNode(node, parent, origin),\n children: []\n }\n standalone.children = node.children.map((child) => standaloneNode(child, origin, node))\n return standalone\n}\n\nfunction nodeBounds(node: DesignNode): StandaloneBounds | undefined {\n if (node.type === 'text' || !node.sourceSceneNode) return undefined\n return {\n minX: node.sourceSceneNode.x,\n minY: node.sourceSceneNode.y,\n width: node.sourceSceneNode.width,\n height: node.sourceSceneNode.height\n }\n}\n\nfunction standaloneSize(document: DesignDocument): StandaloneBounds {\n const bounds = document.children\n .map(nodeBounds)\n .filter((value): value is NonNullable<typeof value> => value !== undefined)\n const minX = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minX)) : 0\n const minY = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minY)) : 0\n const maxX = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minX + bound.width)) : 1\n const maxY = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minY + bound.height)) : 1\n return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) }\n}\n\nfunction standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument {\n return {\n ...document,\n children: document.children.map((node) => standaloneNode(node, size))\n }\n}\n\nfunction cssClassName(index: number): string {\n return `op-${index.toString(36)}`\n}\n\nfunction extractInlineStyles(\n node: DesignNode,\n rules: string[],\n nextIndex: { value: number }\n): DesignNode {\n if (node.type === 'text') return node\n const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex))\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children }\n\n const className = cssClassName(nextIndex.value)\n nextIndex.value += 1\n rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`)\n return {\n ...node,\n attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className },\n inlineStyle: undefined,\n children\n }\n}\n\nfunction isElement(node: ParseNode): node is ParseElement {\n return 'attrs' in node && 'tagName' in node\n}\n\nfunction walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void {\n if (isElement(node)) visit(node)\n if ('childNodes' in node) {\n for (const child of node.childNodes) walkParseTree(child, visit)\n }\n}\n\nfunction classNamesFromHTML(html: string): string[] {\n const fragment = parseFragment(html)\n const classes = new Set<string>()\n walkParseTree(fragment, (element) => {\n const classAttr = element.attrs.find((attr) => attr.name === 'class')\n if (!classAttr) return\n for (const className of splitWhitespace(classAttr.value)) classes.add(className)\n })\n return [...classes]\n}\n\n/**\n * The stylesheet for the tokens the document references, in the format the page needs: plain\n * custom properties for inline styles, `@theme` for Tailwind, so token utilities compile.\n */\nasync function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise<string> {\n const { tokens, sourceGraph } = document\n if (!tokens || !sourceGraph || tokens.used.size === 0) return ''\n const variables = tokens.stylesheetVariables()\n const { css } = await tokenStylesheet(sourceGraph, {\n format,\n include: (variable) => variables.has(variable.id)\n })\n return css\n}\n\nasync function readInstalledTailwindStylesheet(id: TailwindStylesheetId): Promise<string> {\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(new URL(import.meta.resolve(id)), 'utf8')\n}\n\nasync function compileTailwindClasses(\n classNames: string[],\n tokens: string,\n load: TailwindStylesheetLoader = readInstalledTailwindStylesheet\n): Promise<string> {\n if (classNames.length === 0) return ''\n const [{ compile }, themeCSS, utilitiesCSS] = await Promise.all([\n import('tailwindcss'),\n load('tailwindcss/theme.css'),\n load('tailwindcss/utilities.css')\n ])\n const compiler = await compile(`${themeCSS}\\n${tokens}\\n${utilitiesCSS}`)\n return compiler.build(classNames)\n}\n\nfunction collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {\n if (node.type === 'text') return\n const source = node.sourceSceneNode\n if (source?.type === 'TEXT') {\n const family = normalizeFontFamily(source.fontFamily)\n const style = source.italic ? 'italic' : 'normal'\n const key = `${family}|${source.fontWeight}|${style}`\n fonts.set(key, { family, weight: source.fontWeight, style })\n }\n for (const child of node.children) collectFontRequests(child, fonts)\n}\n\nfunction serializeFontWeight(weight: string | number | [number, number]): string {\n return Array.isArray(weight) ? weight.join(' ') : String(weight)\n}\n\n/**\n * A relative file path as a URL that points at it: each folder and file name percent-encoded,\n * so a page named `Card #1` finds `Card #1.assets/` rather than reading `#1` as a fragment.\n */\nfunction assetURL(path: string): string {\n return path.split('/').map(encodeURIComponent).join('/')\n}\n\nfunction fontSourceValue(asset: WebFontFaceAsset, from: string): string {\n // Relative to the stylesheet's folder, which the asset's path may start with.\n const path =\n from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path\n return [\n 'url(',\n JSON.stringify(assetURL(path)),\n ') format(',\n JSON.stringify(asset.format),\n ')'\n ].join('')\n}\n\ninterface FontFaceCSSOptions {\n /** The folder the stylesheet is in, which font paths are written relative to. */\n from: string\n /** `font-display` for every face, rather than each face's own. */\n display?: string\n}\n\nfunction fontFaceCSS(\n FontFaceRule: typeof CSSFontFaceRule,\n asset: WebFontFaceAsset,\n options: FontFaceCSSOptions\n): string {\n const rule = new FontFaceRule()\n rule.style.setProperty('font-family', JSON.stringify(asset.family))\n rule.style.setProperty('src', fontSourceValue(asset, options.from))\n rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))\n rule.style.setProperty('font-style', asset.style)\n rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')\n if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)\n if (asset.unicodeRange && asset.unicodeRange.length > 0) {\n rule.style.setProperty('unicode-range', asset.unicodeRange.join(','))\n }\n return rule.cssText\n}\n\n/** Every font face a document's text uses, once each. */\nexport function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {\n const requests = new Map<string, WebFontFaceRequest>()\n for (const child of document.children) collectFontRequests(child, requests)\n return [...requests.values()]\n}\n\n/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */\nexport async function fontFaceStylesheet(\n assets: readonly WebFontFaceAsset[],\n options: FontFaceCSSOptions\n): Promise<string> {\n if (assets.length === 0) return ''\n // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.\n const cssom = await import('@acemir/cssom')\n return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')\n}\n\nasync function fontFaceAssets(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<{ css: string; files: ExportHTMLFile[] }> {\n if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }\n const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)\n // The page's stylesheet sits in the asset folder, beside the fonts' own folder.\n return {\n css: await fontFaceStylesheet(assets, { from: options.assetBasePath }),\n files: assets\n }\n}\n\nfunction dataImageParts(value: string): { mime: string; base64: string } | undefined {\n if (!value.startsWith('data:image/')) return undefined\n const marker = ';base64,'\n const markerIndex = value.indexOf(marker)\n if (markerIndex === -1) return undefined\n const base64 = value.slice(markerIndex + marker.length)\n // Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.\n if (!isValid(base64)) return undefined\n return { mime: value.slice('data:'.length, markerIndex), base64 }\n}\n\nfunction extensionForMime(mime: string): string {\n if (mime === 'image/jpeg') return 'jpg'\n if (mime === 'image/webp') return 'webp'\n if (mime === 'image/gif') return 'gif'\n if (mime === 'image/svg+xml') return 'svg'\n return 'png'\n}\n\n/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */\nexport function extractImageAssets(\n html: string,\n assetBasePath: string\n): { html: string; files: ExportHTMLFile[] } {\n const fragment = parseFragment(html)\n const files: ExportHTMLFile[] = []\n const sources = new Map<string, string>()\n walkParseTree(fragment, (element) => {\n const src = element.attrs.find((attr) => attr.name === 'src')\n if (!src) return\n const parts = dataImageParts(src.value)\n if (!parts) return\n const cachedPath = sources.get(src.value)\n if (cachedPath) {\n src.value = assetURL(cachedPath)\n return\n }\n const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`\n sources.set(src.value, path)\n files.push({ path, content: toUint8Array(parts.base64) })\n src.value = assetURL(path)\n })\n return { html: serialize(fragment), files }\n}\n\nfunction stylesheetLink(path: string): string {\n return `<link rel=\"stylesheet\" href=\"${assetURL(path)}\">`\n}\n\n/**\n * A `<style>` element holding `css`. The HTML parser ends the element at the first `</style`\n * in any letter case, whatever the CSS around it means, and style values can come from an\n * imported document, so each one is written `<\\/style`, which CSS strings and URLs read back\n * as `</style`.\n */\nfunction styleTag(css: string): string {\n return css ? `<style>${css.replace(/<\\/(?=style)/gi, '<\\\\/')}</style>` : ''\n}\n\ntype ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &\n Pick<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>\n\nasync function exportStandaloneHTML(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<ExportHTMLBundle> {\n const size = standaloneSize(document)\n const doc = standaloneDocument(document, size)\n const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`\n let body: string\n let css = `${RESET_CSS}${stageCSS}`\n\n if (options.style === 'tailwind') {\n body = serializeHTML(doc, { style: 'tailwind' })\n css += await compileTailwindClasses(\n classNamesFromHTML(body),\n await tokenCSS(document, 'tailwind'),\n options.loadTailwindStylesheet\n )\n } else {\n css += await tokenCSS(document, 'css')\n const rules: string[] = []\n const index = { value: 0 }\n const styledDocument: DesignDocument = {\n ...doc,\n children: doc.children.map((node) => extractInlineStyles(node, rules, index))\n }\n body = serializeHTML(styledDocument)\n css += rules.join('')\n }\n\n if (options.assets === 'external') {\n const [extracted, fonts] = await Promise.all([\n Promise.resolve(extractImageAssets(body, options.assetBasePath)),\n fontFaceAssets(document, options)\n ])\n body = extracted.html\n const cssPath = `${options.assetBasePath}/pairdraw.css`\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${stylesheetLink(cssPath)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return {\n entrypoint: 'index.html',\n files: [\n { path: 'index.html', content: html },\n { path: cssPath, content: `${fonts.css}${css}` },\n ...fonts.files,\n ...extracted.files\n ]\n }\n }\n\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${styleTag(css)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] }\n}\n\nexport async function exportHTMLBundle(\n document: DesignDocument,\n options: ExportHTMLBundleOptions = {}\n): Promise<ExportHTMLBundle> {\n const resolvedOptions: ResolvedBundleOptions = {\n html: options.html ?? 'fragment',\n style: options.style ?? 'inline',\n assets: options.assets ?? 'inline',\n fonts: options.fonts ?? 'none',\n assetBasePath: options.assetBasePath ?? 'assets',\n loadTailwindStylesheet: options.loadTailwindStylesheet\n }\n\n if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions)\n\n const fragment = serializeHTML(document, { style: resolvedOptions.style })\n if (resolvedOptions.assets !== 'external') {\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: fragment }] }\n }\n // A fragment has no stylesheet to declare fonts in, so only its images become files.\n const extracted = extractImageAssets(fragment, resolvedOptions.assetBasePath)\n return {\n entrypoint: 'index.html',\n files: [{ path: 'index.html', content: extracted.html }, ...extracted.files]\n }\n}\n"],"mappings":";;;;;;AA0EA,MAAM,YACJ;AAEF,SAAS,WAAW,OAAuC;CACzD,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,QAAQ,GAAG,WAAW,UAAU,EAAE,CAAC,CACnC,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAS,UAAU,MAA8B;CAC/C,IAAI,KAAK,SAAS,QAAQ,OAAO,EAAE,GAAG,KAAK;CAC3C,OAAO;EACL,GAAG;EACH,OAAO,EAAE,GAAG,KAAK,MAAM;EACvB,aAAa,KAAK,cAAc,EAAE,GAAG,KAAK,YAAY,IAAI,KAAA;EAC1D,UAAU,KAAK,SAAS,IAAI,SAAS;CACvC;AACF;AAEA,SAAS,uBACP,MACA,QACA,QACwB;CACxB,MAAM,QAAQ,EAAE,GAAG,KAAK,YAAY;CACpC,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,WAAW;CACjB,MAAM,OAAO,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACtD,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACrD,OAAO;AACT;AAEA,SAAS,eACP,MACA,QACA,QACY;CACZ,IAAI,KAAK,SAAS,QAAQ,OAAO,UAAU,IAAI;CAC/C,MAAM,aAA4B;EAChC,GAAG;EACH,OAAO,EAAE,GAAG,KAAK,MAAM;EACvB,aAAa,uBAAuB,MAAM,QAAQ,MAAM;EACxD,UAAU,CA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IAItM;IACpC;KAAE,MAAM;KAAS,SAAS,GAAG,MAAM,MAAM;IAAM;IAC/C,GAAG,MAAM;IACT,GAAG,UAAU;GACf;EACF;CACF;CAGA,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,wHAD2D,SAAS,GAAG,EAAE,4EAA4E,KAAK;EACrJ,CAAC;CAAE;AACpF;AAEA,eAAsB,iBACpB,UACA,UAAmC,CAAC,GACT;CAC3B,MAAM,kBAAyC;EAC7C,MAAM,QAAQ,QAAQ;EACtB,OAAO,QAAQ,SAAS;EACxB,QAAQ,QAAQ,UAAU;EAC1B,OAAO,QAAQ,SAAS;EACxB,eAAe,QAAQ,iBAAiB;EACxC,wBAAwB,QAAQ;CAClC;CAEA,IAAI,gBAAgB,SAAS,cAAc,OAAO,qBAAqB,UAAU,eAAe;CAEhG,MAAM,WAAW,cAAc,UAAU,EAAE,OAAO,gBAAgB,MAAM,CAAC;CACzE,IAAI,gBAAgB,WAAW,YAC7B,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS;EAAS,CAAC;CAAE;CAGxF,MAAM,YAAY,mBAAmB,UAAU,gBAAgB,aAAa;CAC5E,OAAO;EACL,YAAY;EACZ,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,UAAU;EAAK,GAAG,GAAG,UAAU,KAAK;CAC7E;AACF"}
@@ -32,13 +32,30 @@ const INHERITED_PROPERTIES = /* @__PURE__ */ new Set([
32
32
  "font-weight",
33
33
  "line-height"
34
34
  ]);
35
- function styleToRecord(style, customProperties = {}) {
35
+ /** Declared values as written, before custom properties and shorthands are resolved. */
36
+ function declarationsOf(style) {
36
37
  const result = {};
37
38
  for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {
38
- const value = resolveCSSValue(style.getPropertyValue(property), customProperties);
39
+ const value = style.getPropertyValue(property).trim();
39
40
  if (property && value) result[property] = value;
40
41
  }
41
- return expandStyleShorthands(result);
42
+ return result;
43
+ }
44
+ function resolveDeclarations(declarations, customProperties) {
45
+ const resolved = {};
46
+ for (const [property, value] of Object.entries(declarations)) {
47
+ const resolvedValue = resolveCSSValue(value, customProperties);
48
+ if (resolvedValue) resolved[property] = resolvedValue;
49
+ }
50
+ return expandStyleShorthands(resolved);
51
+ }
52
+ /** Adds the custom properties a declaration block sets, resolved against those already in scope. */
53
+ function declareCustomProperties(scope, declarations) {
54
+ for (const [name, value] of Object.entries(declarations)) {
55
+ if (!name.startsWith("--")) continue;
56
+ const resolved = resolveCSSValue(value, scope);
57
+ if (resolved) scope[name] = resolved;
58
+ }
42
59
  }
43
60
  function isStyleRule(rule) {
44
61
  return typeof rule === "object" && rule !== null && "selectorText" in rule && "style" in rule && typeof rule.selectorText === "string";
@@ -59,12 +76,12 @@ function parseRules(cssText) {
59
76
  const customProperties = collectCustomProperties(styleRules);
60
77
  return {
61
78
  rules: styleRules.flatMap((rule) => {
62
- const style = styleToRecord(rule.style, customProperties);
79
+ const declarations = declarationsOf(rule.style);
63
80
  return rule.selectorText.split(",").map((selector) => selector.trim()).filter((selector) => selector.length > 0).map((selector) => ({
64
81
  selector,
65
82
  specificity: selectorSpecificity(selector),
66
83
  order: order++,
67
- style
84
+ declarations
68
85
  }));
69
86
  }),
70
87
  customProperties
@@ -74,23 +91,48 @@ function collectCustomProperties(rules) {
74
91
  const customProperties = {};
75
92
  for (const rule of rules) {
76
93
  if (!rule.selectorText.split(",").some((selector) => selector.trim() === ":root")) continue;
77
- Object.assign(customProperties, styleToRecord(rule.style));
94
+ declareCustomProperties(customProperties, declarationsOf(rule.style));
78
95
  }
79
96
  return customProperties;
80
97
  }
81
98
  function resolveCSSValue(value, customProperties) {
82
- return resolveSimpleCalc(value.replaceAll(/var\((--[\w-]+)(?:,[^)]+)?\)/g, (_, name) => {
83
- return customProperties[name] ?? "";
84
- }));
99
+ return resolveSimpleCalc(resolveVariables(value, customProperties));
100
+ }
101
+ const CUSTOM_PROPERTY_NAME = /^--[\w-]+$/;
102
+ /** `var()` references as their values; a fallback can hold parentheses and other `var()`s. */
103
+ function resolveVariables(value, customProperties) {
104
+ let result = "";
105
+ let index = 0;
106
+ for (;;) {
107
+ const start = value.indexOf("var(", index);
108
+ const end = start === -1 ? -1 : closingParenthesis(value, start + 3);
109
+ if (end === -1) return result + value.slice(index);
110
+ const inner = value.slice(start + 4, end);
111
+ const comma = inner.indexOf(",");
112
+ const name = (comma === -1 ? inner : inner.slice(0, comma)).trim();
113
+ const declared = Object.hasOwn(customProperties, name) ? customProperties[name] : void 0;
114
+ const fallback = comma === -1 ? "" : inner.slice(comma + 1).trim();
115
+ result += value.slice(index, start);
116
+ result += CUSTOM_PROPERTY_NAME.test(name) ? declared ?? resolveVariables(fallback, customProperties) : value.slice(start, end + 1);
117
+ index = end + 1;
118
+ }
119
+ }
120
+ /** The index of the `)` closing the `(` at `open`, or -1 when it is never closed. */
121
+ function closingParenthesis(value, open) {
122
+ let depth = 0;
123
+ for (let index = open; index < value.length; index++) if (value[index] === "(") depth++;
124
+ else if (value[index] === ")" && --depth === 0) return index;
125
+ return -1;
85
126
  }
127
+ /** `calc()` of a product, with the length on either side, as pixels. */
86
128
  function resolveSimpleCalc(value) {
87
- const calc = value.match(/^calc\(([-\d.]+)(rem|px)?\s*\*\s*([-\d.]+)\)$/);
88
- if (!calc?.[1] || !calc[3]) return value;
89
- const base = Number.parseFloat(calc[1]);
90
- const multiplier = Number.parseFloat(calc[3]);
91
- const unit = calc.at(2) ?? "px";
92
- if (!Number.isFinite(base) || !Number.isFinite(multiplier)) return value;
93
- return `${unit === "rem" ? base * multiplier * 16 : base * multiplier}px`;
129
+ const calc = /^calc\(\s*([-\d.]+)(rem|px)?\s*\*\s*([-\d.]+)(rem|px)?\s*\)$/.exec(value);
130
+ if (!calc?.[1] || !calc[3] || calc[2] && calc[4]) return value;
131
+ const left = Number.parseFloat(calc[1]);
132
+ const right = Number.parseFloat(calc[3]);
133
+ const unit = calc[2] || calc[4] || "px";
134
+ if (!Number.isFinite(left) || !Number.isFinite(right)) return value;
135
+ return `${unit === "rem" ? left * right * 16 : left * right}px`;
94
136
  }
95
137
  const BORDER_STYLES = /* @__PURE__ */ new Set([
96
138
  "none",
@@ -186,36 +228,51 @@ function matchesSimpleSelector(element, selector) {
186
228
  const tag = selector.replace(/#[\w-]+/g, "").replace(/\.[\w-]+/g, "");
187
229
  return tag.length === 0 || tag === "*" || element.tagName.toLowerCase() === tag.toLowerCase();
188
230
  }
189
- function matchesSelector(element, selector, parent) {
190
- const childParts = selector.split(">").map((part) => part.trim());
191
- if (childParts.length > 1) return matchesChildSelector(element, childParts, parent);
192
- const descendantParts = selector.split(/\s+/).filter((part) => part.length > 0);
193
- if (descendantParts.length > 1) return matchesDescendantSelector(element, descendantParts, parent);
194
- return matchesSimpleSelector(element, selector);
195
- }
196
- function matchesSelectorParts(element, parts, parent, directParentOnly) {
197
- const current = parts.at(-1);
198
- if (!current || !matchesSimpleSelector(element, current)) return false;
199
- let ancestor = parent;
200
- for (const selector of parts.slice(0, -1).reverse()) {
201
- if (!directParentOnly) while (ancestor && !matchesSimpleSelector(ancestor.element, selector)) ancestor = ancestor.parent;
202
- if (!ancestor || !matchesSimpleSelector(ancestor.element, selector)) return false;
203
- ancestor = ancestor.parent;
231
+ /** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */
232
+ function selectorSteps(selector) {
233
+ const tokens = selector.replaceAll(">", " > ").split(/\s+/).filter((token) => token.length > 0);
234
+ const steps = [];
235
+ let pending = null;
236
+ for (const token of tokens) {
237
+ if (token === ">") {
238
+ if (pending || steps.length === 0) return null;
239
+ pending = ">";
240
+ continue;
241
+ }
242
+ const previous = steps.at(-1);
243
+ if (previous) previous.combinator = pending ?? " ";
244
+ steps.push({
245
+ compound: token,
246
+ combinator: " "
247
+ });
248
+ pending = null;
204
249
  }
205
- return true;
206
- }
207
- function matchesChildSelector(element, parts, parent) {
208
- return matchesSelectorParts(element, parts, parent, true);
250
+ return pending ? null : steps;
209
251
  }
210
- function matchesDescendantSelector(element, parts, parent) {
211
- return matchesSelectorParts(element, parts, parent, false);
212
- }
213
- function applyComputedStyles(node, rules, parent, inheritedStyle) {
252
+ function matchesSelector(element, selector, parent) {
253
+ const steps = selectorSteps(selector);
254
+ return steps !== null && matchesSteps(element, steps, steps.length - 1, parent);
255
+ }
256
+ /** Whether the element matches the compound at `index` and some ancestors match those before. */
257
+ function matchesSteps(element, steps, index, parent) {
258
+ const step = steps.at(index);
259
+ if (!step || !matchesSimpleSelector(element, step.compound)) return false;
260
+ if (index === 0) return true;
261
+ const previous = steps.at(index - 1);
262
+ if (!previous) return false;
263
+ if (previous.combinator === ">") return parent !== null && matchesSteps(parent.element, steps, index - 1, parent.parent);
264
+ for (let ancestor = parent; ancestor; ancestor = ancestor.parent) if (matchesSteps(ancestor.element, steps, index - 1, ancestor.parent)) return true;
265
+ return false;
266
+ }
267
+ function applyComputedStyles(node, rules, parent, inheritedStyle, inheritedCustomProperties) {
214
268
  if (node.type === "text") return node;
215
269
  const computedStyle = pickInheritedStyle(inheritedStyle);
216
270
  const matchingRules = rules.filter((rule) => matchesSelector(node, rule.selector, parent)).sort((left, right) => left.specificity - right.specificity || left.order - right.order);
217
- for (const rule of matchingRules) Object.assign(computedStyle, rule.style);
218
- Object.assign(computedStyle, expandStyleShorthands(node.inlineStyle ?? {}));
271
+ const customProperties = { ...inheritedCustomProperties };
272
+ for (const rule of matchingRules) declareCustomProperties(customProperties, rule.declarations);
273
+ declareCustomProperties(customProperties, node.inlineStyle ?? {});
274
+ for (const rule of matchingRules) Object.assign(computedStyle, resolveDeclarations(rule.declarations, customProperties));
275
+ Object.assign(computedStyle, resolveDeclarations(node.inlineStyle ?? {}, customProperties));
219
276
  const context = {
220
277
  element: node,
221
278
  parent
@@ -223,7 +280,7 @@ function applyComputedStyles(node, rules, parent, inheritedStyle) {
223
280
  return {
224
281
  ...node,
225
282
  computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : void 0,
226
- children: node.children.map((child) => applyComputedStyles(child, rules, context, computedStyle))
283
+ children: node.children.map((child) => applyComputedStyles(child, rules, context, computedStyle, customProperties))
227
284
  };
228
285
  }
229
286
  function pickInheritedStyle(style) {
@@ -235,10 +292,12 @@ function pickInheritedStyle(style) {
235
292
  return inherited;
236
293
  }
237
294
  function computeHeadlessStyles(document, cssText = "") {
238
- const { rules } = parseRules([document.stylesheets?.map((sheet) => sheet.cssText).join("\n"), cssText].filter((text) => !!text).join("\n"));
295
+ const { rules, customProperties } = parseRules([document.stylesheets?.map((sheet) => sheet.cssText).join("\n"), cssText].filter((text) => !!text).join("\n"));
296
+ const rootStyle = {};
297
+ for (const rule of rules.filter(({ selector }) => selector === ":root")) Object.assign(rootStyle, resolveDeclarations(rule.declarations, customProperties));
239
298
  return {
240
299
  ...document,
241
- children: document.children.map((child) => applyComputedStyles(child, rules, null, {}))
300
+ children: document.children.map((child) => applyComputedStyles(child, rules, null, rootStyle, customProperties))
242
301
  };
243
302
  }
244
303
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"html.js","names":["parse","parse"],"sources":["../../../src/import/style-attribute.ts","../../../src/runtime/headless/styles.ts","../../../src/runtime/headless/runtime.ts","../../../src/runtime/index.ts","../../../src/import/tailwind.ts","../../../src/import/html.ts"],"sourcesContent":["import { parse } from '@acemir/cssom'\nimport type { CSSStyleRuleLike } from '@acemir/cssom'\n\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction firstStyleRule(cssText: string): CSSStyleRuleLike | null {\n const [rule] = parse(cssText).cssRules\n if (!rule || typeof rule !== 'object' || !('style' in rule)) return null\n return rule as CSSStyleRuleLike\n}\n\nexport function parseStyleAttribute(value: string | undefined): DesignStyleDeclaration | undefined {\n if (!value) return undefined\n\n const rule = firstStyleRule(`*{${value}}`)\n if (!rule) return undefined\n\n const style: DesignStyleDeclaration = {}\n for (const property of Array.from(rule.style)) {\n const propertyValue = rule.style.getPropertyValue(property)\n if (propertyValue) style[property] = propertyValue\n }\n\n return Object.keys(style).length > 0 ? style : undefined\n}\n","import type {\n DesignDocument,\n DesignElement,\n DesignNode,\n DesignStyleDeclaration\n} from '#dom-css/types'\nimport {\n parse,\n type CSSGroupingRuleLike,\n type CSSStyleDeclarationLike,\n type CSSStyleRuleLike\n} from '@acemir/cssom'\n\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber, splitCSSValue } from '@pairdraw/scene-graph/css'\n\ninterface HeadlessCSSRule {\n selector: string\n specificity: number\n order: number\n style: DesignStyleDeclaration\n}\n\ninterface ParsedHeadlessCSS {\n rules: HeadlessCSSRule[]\n customProperties: DesignStyleDeclaration\n}\n\ninterface AncestorContext {\n element: DesignElement\n parent: AncestorContext | null\n}\n\nconst INHERITED_PROPERTIES = new Set([\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'line-height'\n])\n\nfunction styleToRecord(\n style: CSSStyleDeclarationLike,\n customProperties: DesignStyleDeclaration = {}\n): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {\n const value = resolveCSSValue(style.getPropertyValue(property), customProperties)\n if (property && value) result[property] = value\n }\n return expandStyleShorthands(result)\n}\n\nfunction isStyleRule(rule: unknown): rule is CSSStyleRuleLike {\n return (\n typeof rule === 'object' &&\n rule !== null &&\n 'selectorText' in rule &&\n 'style' in rule &&\n typeof rule.selectorText === 'string'\n )\n}\n\nfunction isGroupingRule(rule: unknown): rule is CSSGroupingRuleLike {\n return (\n typeof rule === 'object' && rule !== null && 'cssRules' in rule && Array.isArray(rule.cssRules)\n )\n}\n\nfunction collectStyleRules(rules: unknown[]): CSSStyleRuleLike[] {\n return rules.flatMap((rule) => {\n if (isStyleRule(rule)) return [rule]\n if (isGroupingRule(rule)) return collectStyleRules(rule.cssRules)\n return []\n })\n}\n\nfunction parseRules(cssText: string): ParsedHeadlessCSS {\n let order = 0\n const sheet = parse(cssText)\n const styleRules = collectStyleRules(sheet.cssRules)\n const customProperties = collectCustomProperties(styleRules)\n const rules = styleRules.flatMap((rule) => {\n const style = styleToRecord(rule.style, customProperties)\n return rule.selectorText\n .split(',')\n .map((selector) => selector.trim())\n .filter((selector) => selector.length > 0)\n .map((selector) => ({\n selector,\n specificity: selectorSpecificity(selector),\n order: order++,\n style\n }))\n })\n return { rules, customProperties }\n}\n\nfunction collectCustomProperties(rules: CSSStyleRuleLike[]): DesignStyleDeclaration {\n const customProperties: DesignStyleDeclaration = {}\n for (const rule of rules) {\n if (!rule.selectorText.split(',').some((selector) => selector.trim() === ':root')) continue\n Object.assign(customProperties, styleToRecord(rule.style))\n }\n return customProperties\n}\n\nfunction resolveCSSValue(value: string, customProperties: DesignStyleDeclaration): string {\n const withVariables = value.replaceAll(/var\\((--[\\w-]+)(?:,[^)]+)?\\)/g, (_, name: string) => {\n return customProperties[name] ?? ''\n })\n return resolveSimpleCalc(withVariables)\n}\n\nfunction resolveSimpleCalc(value: string): string {\n const calc = value.match(/^calc\\(([-\\d.]+)(rem|px)?\\s*\\*\\s*([-\\d.]+)\\)$/)\n if (!calc?.[1] || !calc[3]) return value\n\n const base = Number.parseFloat(calc[1])\n const multiplier = Number.parseFloat(calc[3])\n const unit = calc.at(2) ?? 'px'\n if (!Number.isFinite(base) || !Number.isFinite(multiplier)) return value\n return `${unit === 'rem' ? base * multiplier * 16 : base * multiplier}px`\n}\n\nconst BORDER_STYLES = new Set([\n 'none',\n 'hidden',\n 'dotted',\n 'dashed',\n 'solid',\n 'double',\n 'groove',\n 'ridge',\n 'inset',\n 'outset'\n])\n\n/**\n * Shorthands as the longhands they set, in declaration order, so a later declaration wins over\n * an earlier one whether it is a shorthand, a logical side, or a single side, as in CSS.\n */\nfunction expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(style)) {\n result[property] = value\n Object.assign(result, longhandsOf(property, value))\n }\n return result\n}\n\nfunction longhandsOf(property: string, value: string): DesignStyleDeclaration {\n if (property === 'margin' || property === 'padding') return boxSides(property, value)\n const logical = /^(margin|padding)-(inline|block)$/u.exec(property)\n if (logical) return logicalSides(property, value, logical[2] === 'inline')\n if (property === 'border') return borderLonghands(value)\n if (property === 'background') {\n const color = splitCSSValue(value).find(isColor)\n return color ? { 'background-color': color } : {}\n }\n return {}\n}\n\nfunction boxSides(property: string, value: string): DesignStyleDeclaration {\n const [top, right = top, bottom = top, left = right] = splitCSSValue(value)\n if (!top || !right || !bottom || !left) return {}\n return {\n [`${property}-top`]: top,\n [`${property}-right`]: right,\n [`${property}-bottom`]: bottom,\n [`${property}-left`]: left\n }\n}\n\n/** `padding-inline` and `padding-block` as the sides they set in left-to-right, horizontal text. */\nfunction logicalSides(property: string, value: string, inline: boolean): DesignStyleDeclaration {\n const box = property.slice(0, property.lastIndexOf('-'))\n const [first, second = first] = splitCSSValue(value)\n if (!first || !second) return {}\n const [start, end] = inline ? ['left', 'right'] : ['top', 'bottom']\n return { [`${box}-${start}`]: first, [`${box}-${end}`]: second }\n}\n\nfunction borderLonghands(value: string): DesignStyleDeclaration {\n const parts = splitCSSValue(value)\n const longhands: DesignStyleDeclaration = {}\n const color = parts.find(isColor)\n const width = parts.find((part) => parseCSSNumber(part) !== null)\n const style = parts.find((part) => BORDER_STYLES.has(part.toLowerCase()))\n if (color) longhands['border-color'] = color\n if (width) longhands['border-width'] = width\n if (style) longhands['border-style'] = style.toLowerCase()\n return longhands\n}\n\n/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */\nfunction isColor(value: string): boolean {\n return tryParseColor(value) !== null\n}\n\nfunction classList(element: DesignElement): Set<string> {\n const className = 'class' in element.attrs ? element.attrs.class : ''\n return new Set(className.split(/\\s+/).filter((name) => name.length > 0))\n}\n\nfunction elementId(element: DesignElement): string | undefined {\n return 'id' in element.attrs ? element.attrs.id : undefined\n}\n\nfunction selectorSpecificity(selector: string): number {\n const idCount = selector.match(/#[\\w-]+/g)?.length ?? 0\n const classCount = selector.match(/\\.[\\w-]+/g)?.length ?? 0\n // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.\n const tagCount = selector.split(/[\\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length\n return idCount * 100 + classCount * 10 + tagCount\n}\n\nfunction matchesSimpleSelector(element: DesignElement, selector: string): boolean {\n if (selector.includes(':') || selector.includes('[')) return false\n\n const idMatch = selector.match(/#([\\w-]+)/)\n if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false\n\n const classes = selector.match(/\\.[\\w-]+/g) ?? []\n const elementClasses = classList(element)\n if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false\n\n const tag = selector.replace(/#[\\w-]+/g, '').replace(/\\.[\\w-]+/g, '')\n // The universal selector, as Tailwind's preflight uses for `box-sizing`, matches any element.\n return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()\n}\n\nfunction matchesSelector(\n element: DesignElement,\n selector: string,\n parent: AncestorContext | null\n): boolean {\n const childParts = selector.split('>').map((part) => part.trim())\n if (childParts.length > 1) return matchesChildSelector(element, childParts, parent)\n\n const descendantParts = selector.split(/\\s+/).filter((part) => part.length > 0)\n if (descendantParts.length > 1) return matchesDescendantSelector(element, descendantParts, parent)\n\n return matchesSimpleSelector(element, selector)\n}\n\nfunction matchesSelectorParts(\n element: DesignElement,\n parts: string[],\n parent: AncestorContext | null,\n directParentOnly: boolean\n): boolean {\n const current = parts.at(-1)\n if (!current || !matchesSimpleSelector(element, current)) return false\n\n let ancestor = parent\n for (const selector of parts.slice(0, -1).reverse()) {\n if (!directParentOnly) {\n while (ancestor && !matchesSimpleSelector(ancestor.element, selector)) {\n ancestor = ancestor.parent\n }\n }\n if (!ancestor || !matchesSimpleSelector(ancestor.element, selector)) return false\n ancestor = ancestor.parent\n }\n return true\n}\n\nfunction matchesChildSelector(\n element: DesignElement,\n parts: string[],\n parent: AncestorContext | null\n): boolean {\n return matchesSelectorParts(element, parts, parent, true)\n}\n\nfunction matchesDescendantSelector(\n element: DesignElement,\n parts: string[],\n parent: AncestorContext | null\n): boolean {\n return matchesSelectorParts(element, parts, parent, false)\n}\n\nfunction applyComputedStyles(\n node: DesignNode,\n rules: HeadlessCSSRule[],\n parent: AncestorContext | null,\n inheritedStyle: DesignStyleDeclaration\n): DesignNode {\n if (node.type === 'text') return node\n\n const computedStyle: DesignStyleDeclaration = pickInheritedStyle(inheritedStyle)\n const matchingRules = rules\n .filter((rule) => matchesSelector(node, rule.selector, parent))\n .sort((left, right) => left.specificity - right.specificity || left.order - right.order)\n\n for (const rule of matchingRules) Object.assign(computedStyle, rule.style)\n Object.assign(computedStyle, expandStyleShorthands(node.inlineStyle ?? {}))\n\n const context = { element: node, parent }\n return {\n ...node,\n computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,\n children: node.children.map((child) =>\n applyComputedStyles(child, rules, context, computedStyle)\n )\n }\n}\n\nfunction pickInheritedStyle(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const inherited: DesignStyleDeclaration = {}\n for (const property of INHERITED_PROPERTIES) {\n const value = style[property]\n if (value) inherited[property] = value\n }\n return inherited\n}\n\nexport function computeHeadlessStyles(document: DesignDocument, cssText = ''): DesignDocument {\n const stylesheetText = [document.stylesheets?.map((sheet) => sheet.cssText).join('\\n'), cssText]\n .filter((text): text is string => !!text)\n .join('\\n')\n const { rules } = parseRules(stylesheetText)\n\n return {\n ...document,\n children: document.children.map((child) => applyComputedStyles(child, rules, null, {}))\n }\n}\n","import { serializeHTML } from '#dom-css/export/html'\nimport { INLINE_TAGS } from '#dom-css/import/flow'\nimport { parseStyleAttribute } from '#dom-css/import/style-attribute'\nimport type { CSSRuntime, DesignDocument, DesignElement, DesignNode } from '#dom-css/types'\nimport { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { computeHeadlessStyles } from './styles'\n\nfunction attrsToRecord(attrs: DefaultTreeAdapterTypes.Element['attrs']): Record<string, string> {\n const result: Record<string, string> = {}\n for (const attr of attrs) result[attr.name] = attr.value\n return result\n}\n\nfunction isTextNode(\n node: DefaultTreeAdapterTypes.ChildNode\n): node is DefaultTreeAdapterTypes.TextNode {\n return node.nodeName === '#text'\n}\n\nconst NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])\n\nfunction isInlineElement(node: DefaultTreeAdapterTypes.ChildNode | undefined): boolean {\n return node !== undefined && 'tagName' in node && INLINE_TAGS.has(node.tagName.toLowerCase())\n}\n\n/**\n * Text, and the spaces in or beside inline elements, which CSS draws among their words; spaces\n * between blocks lay nothing out, so they are left out.\n */\nfunction keepsText(\n node: DefaultTreeAdapterTypes.TextNode,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n index: number,\n inInline: boolean\n): boolean {\n if (node.value.trim().length > 0) return true\n return (\n node.value.length > 0 &&\n (inInline || isInlineElement(siblings[index - 1]) || isInlineElement(siblings[index + 1]))\n )\n}\n\nfunction childrenToDesignNodes(\n nodes: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode[] {\n return nodes\n .map((node, index) => childToDesignNode(node, index, nodes, inInline))\n .filter((child): child is DesignNode => child !== null)\n}\n\nfunction childToDesignNode(\n node: DefaultTreeAdapterTypes.ChildNode,\n index: number,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode | null {\n if (isTextNode(node)) {\n return keepsText(node, siblings, index, inInline) ? { type: 'text', text: node.value } : null\n }\n\n if (!('tagName' in node)) return null\n if (NON_RENDERED_TAGS.has(node.tagName.toLowerCase())) return null\n\n const attrs = attrsToRecord(node.attrs)\n const element: DesignElement = {\n type: 'element',\n tagName: node.tagName.toLowerCase(),\n attrs,\n children: childrenToDesignNodes(node.childNodes, isInlineElement(node))\n }\n\n const inlineStyle = parseStyleAttribute(attrs.style)\n if (inlineStyle) element.inlineStyle = inlineStyle\n\n return element\n}\n\nfunction parseHTML(html: string): DesignDocument {\n const fragment = parseFragment(html)\n return {\n type: 'document',\n children: childrenToDesignNodes(fragment.childNodes, false)\n }\n}\n\nexport function createHeadlessCSSRuntime(): CSSRuntime {\n return {\n kind: 'headless',\n parseHTML,\n serializeHTML(document: DesignDocument) {\n return serializeHTML(document)\n },\n async computeStyles(document: DesignDocument, cssText = '') {\n return computeHeadlessStyles(document, cssText)\n }\n }\n}\n","import type { CSSRuntime } from '../types'\nimport { createBrowserCSSRuntime } from './browser/runtime'\nimport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport { createBrowserCSSRuntime } from './browser/runtime'\nexport type { BrowserCSSRuntimeOptions } from './browser/runtime'\nexport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport function createCSSRuntime(): CSSRuntime {\n return typeof document !== 'undefined' ? createBrowserCSSRuntime() : createHeadlessCSSRuntime()\n}\n","import { compile } from 'tailwindcss'\n\nexport interface CompileTailwindCSSOptions {\n css?: string\n base?: string\n loadStylesheet?: (id: string, base: string) => Promise<string>\n}\n\nconst DEFAULT_TAILWIND_CSS = '@import \"tailwindcss\";'\n\nexport async function compileTailwindCSS(\n classes: string | Iterable<string>,\n options: CompileTailwindCSSOptions = {}\n): Promise<string> {\n const compiler = await compile(tailwindCompilerCSS(options.css), {\n base: options.base,\n loadStylesheet: async (id, base) => {\n const content = options.loadStylesheet\n ? await options.loadStylesheet(id, base)\n : await loadTailwindStylesheet(id)\n return { path: id, base, content }\n }\n })\n return compiler.build(normalizeClasses(classes))\n}\n\nfunction tailwindCompilerCSS(css: string | undefined): string {\n const trimmed = css?.trim()\n if (!trimmed) return DEFAULT_TAILWIND_CSS\n if (containsTailwindImport(trimmed)) return trimmed\n return `${DEFAULT_TAILWIND_CSS}\\n${trimmed}`\n}\n\nfunction containsTailwindImport(css: string): boolean {\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n return /^\\s*@import\\s+(?:\"tailwindcss(?:\\/[^\"]*)?\"|'tailwindcss(?:\\/[^']*)?')/m.test(\n withoutComments\n )\n}\n\nfunction normalizeClasses(classes: string | Iterable<string>): string[] {\n const classNames = typeof classes === 'string' ? [classes] : Array.from(classes)\n return classNames\n .flatMap((className) => className.split(/\\s+/))\n .map((className) => className.trim())\n .filter((className) => className.length > 0)\n}\n\nasync function loadTailwindStylesheet(id: string): Promise<string> {\n const stylesheet = id === 'tailwindcss' ? 'tailwindcss/index.css' : id\n const url = new URL(import.meta.resolve(stylesheet))\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(url, 'utf8')\n}\n","import { parse, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { createCSSRuntime } from '../runtime'\nimport type { CSSComputeOptions, CSSRuntime, DesignDocument } from '../types'\nimport { mergeCSSText } from './css-text'\nimport { designDocumentToSceneGraph, type ToSceneGraphOptions } from './scene-graph'\nimport { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'\n\nexport interface HTMLToDesignDocumentOptions {\n cssText?: string\n runtime?: CSSRuntime\n compute?: CSSComputeOptions\n}\n\nexport interface HTMLToSceneGraphOptions extends HTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nexport interface TailwindHTMLToDesignDocumentOptions\n extends Omit<HTMLToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}\n\nexport interface TailwindHTMLToSceneGraphOptions\n extends TailwindHTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nfunction runtimeForOptions(runtime: CSSRuntime | undefined) {\n return runtime ?? createCSSRuntime()\n}\n\nfunction getChildNodes(node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.ChildNode[] {\n return 'childNodes' in node ? node.childNodes : []\n}\n\nfunction textContent(node: DefaultTreeAdapterTypes.Node): string {\n if (node.nodeName === '#text' && 'value' in node) return node.value\n return getChildNodes(node).map(textContent).join('')\n}\n\nfunction collectStyleText(node: DefaultTreeAdapterTypes.Node, styles: string[]): void {\n if ('tagName' in node && node.tagName.toLowerCase() === 'style') {\n const css = textContent(node).trim()\n if (css) styles.push(css)\n return\n }\n\n for (const child of getChildNodes(node)) collectStyleText(child, styles)\n}\n\nfunction extractEmbeddedCSSText(html: string): string | undefined {\n const styles: string[] = []\n collectStyleText(parse(html), styles)\n return styles.length > 0 ? styles.join('\\n') : undefined\n}\n\nexport async function htmlToDesignDocument(\n html: string,\n options: HTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const runtime = runtimeForOptions(options.runtime)\n const document = runtime.parseHTML(html)\n const cssText = mergeCSSText(extractEmbeddedCSSText(html), options.cssText)\n return runtime.computeStyles(document, cssText, options.compute)\n}\n\nexport async function htmlToSceneGraph(\n html: string,\n options: HTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await htmlToDesignDocument(html, options)\n return designDocumentToSceneGraph(document, options)\n}\n\nexport async function tailwindHTMLToDesignDocument(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const cssText = await compileTailwindCSS(candidates, options)\n return htmlToDesignDocument(html, { ...options, cssText })\n}\n\nexport async function tailwindHTMLToSceneGraph(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await tailwindHTMLToDesignDocument(html, candidates, options)\n return designDocumentToSceneGraph(document, options)\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,eAAe,SAA0C;CAChE,MAAM,CAAC,QAAQA,QAAM,OAAO,CAAC,CAAC;CAC9B,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,EAAE,WAAW,OAAO,OAAO;CACpE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAA+D;CACjG,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAAO,eAAe,KAAK,MAAM,EAAE;CACzC,IAAI,CAAC,MAAM,OAAO,KAAA;CAElB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,YAAY,MAAM,KAAK,KAAK,KAAK,GAAG;EAC7C,M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Y,OAAO;CAC5D,OAAO,qBAAqB,MAAM;EAAE,GAAG;EAAS;CAAQ,CAAC;AAC3D;AAEA,eAAsB,yBACpB,MACA,YACA,UAA2C,CAAC,GACvB;CACrB,MAAM,WAAW,MAAM,6BAA6B,MAAM,YAAY,OAAO;CAC7E,OAAO,2BAA2B,UAAU,OAAO;AACrD"}
1
+ {"version":3,"file":"html.js","names":["parse","parse"],"sources":["../../../src/import/style-attribute.ts","../../../src/runtime/headless/styles.ts","../../../src/runtime/headless/runtime.ts","../../../src/runtime/index.ts","../../../src/import/tailwind.ts","../../../src/import/html.ts"],"sourcesContent":["import { parse } from '@acemir/cssom'\nimport type { CSSStyleRuleLike } from '@acemir/cssom'\n\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction firstStyleRule(cssText: string): CSSStyleRuleLike | null {\n const [rule] = parse(cssText).cssRules\n if (!rule || typeof rule !== 'object' || !('style' in rule)) return null\n return rule as CSSStyleRuleLike\n}\n\nexport function parseStyleAttribute(value: string | undefined): DesignStyleDeclaration | undefined {\n if (!value) return undefined\n\n const rule = firstStyleRule(`*{${value}}`)\n if (!rule) return undefined\n\n const style: DesignStyleDeclaration = {}\n for (const property of Array.from(rule.style)) {\n const propertyValue = rule.style.getPropertyValue(property)\n if (propertyValue) style[property] = propertyValue\n }\n\n return Object.keys(style).length > 0 ? style : undefined\n}\n","import type {\n DesignDocument,\n DesignElement,\n DesignNode,\n DesignStyleDeclaration\n} from '#dom-css/types'\nimport {\n parse,\n type CSSGroupingRuleLike,\n type CSSStyleDeclarationLike,\n type CSSStyleRuleLike\n} from '@acemir/cssom'\n\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber, splitCSSValue } from '@pairdraw/scene-graph/css'\n\ninterface HeadlessCSSRule {\n selector: string\n specificity: number\n order: number\n /** Declared values with `var()` unresolved, so each element resolves them in its own scope. */\n declarations: DesignStyleDeclaration\n}\n\ninterface ParsedHeadlessCSS {\n rules: HeadlessCSSRule[]\n customProperties: DesignStyleDeclaration\n}\n\ninterface AncestorContext {\n element: DesignElement\n parent: AncestorContext | null\n}\n\nconst INHERITED_PROPERTIES = new Set([\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'line-height'\n])\n\n/** Declared values as written, before custom properties and shorthands are resolved. */\nfunction declarationsOf(style: CSSStyleDeclarationLike): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {\n const value = style.getPropertyValue(property).trim()\n if (property && value) result[property] = value\n }\n return result\n}\n\nfunction resolveDeclarations(\n declarations: DesignStyleDeclaration,\n customProperties: DesignStyleDeclaration\n): DesignStyleDeclaration {\n const resolved: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(declarations)) {\n const resolvedValue = resolveCSSValue(value, customProperties)\n if (resolvedValue) resolved[property] = resolvedValue\n }\n return expandStyleShorthands(resolved)\n}\n\n/** Adds the custom properties a declaration block sets, resolved against those already in scope. */\nfunction declareCustomProperties(\n scope: DesignStyleDeclaration,\n declarations: DesignStyleDeclaration\n): void {\n for (const [name, value] of Object.entries(declarations)) {\n if (!name.startsWith('--')) continue\n const resolved = resolveCSSValue(value, scope)\n if (resolved) scope[name] = resolved\n }\n}\n\nfunction isStyleRule(rule: unknown): rule is CSSStyleRuleLike {\n return (\n typeof rule === 'object' &&\n rule !== null &&\n 'selectorText' in rule &&\n 'style' in rule &&\n typeof rule.selectorText === 'string'\n )\n}\n\nfunction isGroupingRule(rule: unknown): rule is CSSGroupingRuleLike {\n return (\n typeof rule === 'object' && rule !== null && 'cssRules' in rule && Array.isArray(rule.cssRules)\n )\n}\n\nfunction collectStyleRules(rules: unknown[]): CSSStyleRuleLike[] {\n return rules.flatMap((rule) => {\n if (isStyleRule(rule)) return [rule]\n if (isGroupingRule(rule)) return collectStyleRules(rule.cssRules)\n return []\n })\n}\n\nfunction parseRules(cssText: string): ParsedHeadlessCSS {\n let order = 0\n const sheet = parse(cssText)\n const styleRules = collectStyleRules(sheet.cssRules)\n const customProperties = collectCustomProperties(styleRules)\n const rules = styleRules.flatMap((rule) => {\n const declarations = declarationsOf(rule.style)\n return rule.selectorText\n .split(',')\n .map((selector) => selector.trim())\n .filter((selector) => selector.length > 0)\n .map((selector) => ({\n selector,\n specificity: selectorSpecificity(selector),\n order: order++,\n declarations\n }))\n })\n return { rules, customProperties }\n}\n\nfunction collectCustomProperties(rules: CSSStyleRuleLike[]): DesignStyleDeclaration {\n const customProperties: DesignStyleDeclaration = {}\n for (const rule of rules) {\n if (!rule.selectorText.split(',').some((selector) => selector.trim() === ':root')) continue\n declareCustomProperties(customProperties, declarationsOf(rule.style))\n }\n return customProperties\n}\n\nfunction resolveCSSValue(value: string, customProperties: DesignStyleDeclaration): string {\n return resolveSimpleCalc(resolveVariables(value, customProperties))\n}\n\nconst CUSTOM_PROPERTY_NAME = /^--[\\w-]+$/\n\n/** `var()` references as their values; a fallback can hold parentheses and other `var()`s. */\nfunction resolveVariables(value: string, customProperties: DesignStyleDeclaration): string {\n let result = ''\n let index = 0\n for (;;) {\n const start = value.indexOf('var(', index)\n const end = start === -1 ? -1 : closingParenthesis(value, start + 3)\n if (end === -1) return result + value.slice(index)\n const inner = value.slice(start + 4, end)\n const comma = inner.indexOf(',')\n const name = (comma === -1 ? inner : inner.slice(0, comma)).trim()\n const declared: string | undefined = Object.hasOwn(customProperties, name)\n ? customProperties[name]\n : undefined\n const fallback = comma === -1 ? '' : inner.slice(comma + 1).trim()\n result += value.slice(index, start)\n result += CUSTOM_PROPERTY_NAME.test(name)\n ? (declared ?? resolveVariables(fallback, customProperties))\n : value.slice(start, end + 1)\n index = end + 1\n }\n}\n\n/** The index of the `)` closing the `(` at `open`, or -1 when it is never closed. */\nfunction closingParenthesis(value: string, open: number): number {\n let depth = 0\n for (let index = open; index < value.length; index++) {\n if (value[index] === '(') depth++\n else if (value[index] === ')' && --depth === 0) return index\n }\n return -1\n}\n\n/** `calc()` of a product, with the length on either side, as pixels. */\nfunction resolveSimpleCalc(value: string): string {\n const calc = /^calc\\(\\s*([-\\d.]+)(rem|px)?\\s*\\*\\s*([-\\d.]+)(rem|px)?\\s*\\)$/.exec(value)\n if (!calc?.[1] || !calc[3] || (calc[2] && calc[4])) return value\n\n const left = Number.parseFloat(calc[1])\n const right = Number.parseFloat(calc[3])\n // An unmatched group is undefined at run time, though the match array types it as a string.\n const unit = calc[2] || calc[4] || 'px'\n if (!Number.isFinite(left) || !Number.isFinite(right)) return value\n return `${unit === 'rem' ? left * right * 16 : left * right}px`\n}\n\nconst BORDER_STYLES = new Set([\n 'none',\n 'hidden',\n 'dotted',\n 'dashed',\n 'solid',\n 'double',\n 'groove',\n 'ridge',\n 'inset',\n 'outset'\n])\n\n/**\n * Shorthands as the longhands they set, in declaration order, so a later declaration wins over\n * an earlier one whether it is a shorthand, a logical side, or a single side, as in CSS.\n */\nfunction expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(style)) {\n result[property] = value\n Object.assign(result, longhandsOf(property, value))\n }\n return result\n}\n\nfunction longhandsOf(property: string, value: string): DesignStyleDeclaration {\n if (property === 'margin' || property === 'padding') return boxSides(property, value)\n const logical = /^(margin|padding)-(inline|block)$/u.exec(property)\n if (logical) return logicalSides(property, value, logical[2] === 'inline')\n if (property === 'border') return borderLonghands(value)\n if (property === 'background') {\n const color = splitCSSValue(value).find(isColor)\n return color ? { 'background-color': color } : {}\n }\n return {}\n}\n\nfunction boxSides(property: string, value: string): DesignStyleDeclaration {\n const [top, right = top, bottom = top, left = right] = splitCSSValue(value)\n if (!top || !right || !bottom || !left) return {}\n return {\n [`${property}-top`]: top,\n [`${property}-right`]: right,\n [`${property}-bottom`]: bottom,\n [`${property}-left`]: left\n }\n}\n\n/** `padding-inline` and `padding-block` as the sides they set in left-to-right, horizontal text. */\nfunction logicalSides(property: string, value: string, inline: boolean): DesignStyleDeclaration {\n const box = property.slice(0, property.lastIndexOf('-'))\n const [first, second = first] = splitCSSValue(value)\n if (!first || !second) return {}\n const [start, end] = inline ? ['left', 'right'] : ['top', 'bottom']\n return { [`${box}-${start}`]: first, [`${box}-${end}`]: second }\n}\n\nfunction borderLonghands(value: string): DesignStyleDeclaration {\n const parts = splitCSSValue(value)\n const longhands: DesignStyleDeclaration = {}\n const color = parts.find(isColor)\n const width = parts.find((part) => parseCSSNumber(part) !== null)\n const style = parts.find((part) => BORDER_STYLES.has(part.toLowerCase()))\n if (color) longhands['border-color'] = color\n if (width) longhands['border-width'] = width\n if (style) longhands['border-style'] = style.toLowerCase()\n return longhands\n}\n\n/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */\nfunction isColor(value: string): boolean {\n return tryParseColor(value) !== null\n}\n\nfunction classList(element: DesignElement): Set<string> {\n const className = 'class' in element.attrs ? element.attrs.class : ''\n return new Set(className.split(/\\s+/).filter((name) => name.length > 0))\n}\n\nfunction elementId(element: DesignElement): string | undefined {\n return 'id' in element.attrs ? element.attrs.id : undefined\n}\n\nfunction selectorSpecificity(selector: string): number {\n const idCount = selector.match(/#[\\w-]+/g)?.length ?? 0\n const classCount = selector.match(/\\.[\\w-]+/g)?.length ?? 0\n // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.\n const tagCount = selector.split(/[\\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length\n return idCount * 100 + classCount * 10 + tagCount\n}\n\nfunction matchesSimpleSelector(element: DesignElement, selector: string): boolean {\n if (selector.includes(':') || selector.includes('[')) return false\n\n const idMatch = selector.match(/#([\\w-]+)/)\n if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false\n\n const classes = selector.match(/\\.[\\w-]+/g) ?? []\n const elementClasses = classList(element)\n if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false\n\n const tag = selector.replace(/#[\\w-]+/g, '').replace(/\\.[\\w-]+/g, '')\n // The universal selector, as Tailwind's preflight uses for `box-sizing`, matches any element.\n return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()\n}\n\ninterface SelectorStep {\n compound: string\n /** How this compound relates to the one after it: `>` for a parent, ` ` for any ancestor. */\n combinator: '>' | ' '\n}\n\n/** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */\nfunction selectorSteps(selector: string): SelectorStep[] | null {\n const tokens = selector\n .replaceAll('>', ' > ')\n .split(/\\s+/)\n .filter((token) => token.length > 0)\n const steps: SelectorStep[] = []\n let pending: '>' | null = null\n for (const token of tokens) {\n if (token === '>') {\n if (pending || steps.length === 0) return null\n pending = '>'\n continue\n }\n const previous = steps.at(-1)\n if (previous) previous.combinator = pending ?? ' '\n steps.push({ compound: token, combinator: ' ' })\n pending = null\n }\n return pending ? null : steps\n}\n\nfunction matchesSelector(\n element: DesignElement,\n selector: string,\n parent: AncestorContext | null\n): boolean {\n const steps = selectorSteps(selector)\n return steps !== null && matchesSteps(element, steps, steps.length - 1, parent)\n}\n\n/** Whether the element matches the compound at `index` and some ancestors match those before. */\nfunction matchesSteps(\n element: DesignElement,\n steps: SelectorStep[],\n index: number,\n parent: AncestorContext | null\n): boolean {\n const step = steps.at(index)\n if (!step || !matchesSimpleSelector(element, step.compound)) return false\n if (index === 0) return true\n const previous = steps.at(index - 1)\n if (!previous) return false\n if (previous.combinator === '>') {\n return parent !== null && matchesSteps(parent.element, steps, index - 1, parent.parent)\n }\n for (let ancestor = parent; ancestor; ancestor = ancestor.parent) {\n if (matchesSteps(ancestor.element, steps, index - 1, ancestor.parent)) return true\n }\n return false\n}\n\nfunction applyComputedStyles(\n node: DesignNode,\n rules: HeadlessCSSRule[],\n parent: AncestorContext | null,\n inheritedStyle: DesignStyleDeclaration,\n inheritedCustomProperties: DesignStyleDeclaration\n): DesignNode {\n if (node.type === 'text') return node\n\n const computedStyle: DesignStyleDeclaration = pickInheritedStyle(inheritedStyle)\n const matchingRules = rules\n .filter((rule) => matchesSelector(node, rule.selector, parent))\n .sort((left, right) => left.specificity - right.specificity || left.order - right.order)\n\n // Custom properties cascade and inherit like any property, so `var()` resolves per element.\n const customProperties = { ...inheritedCustomProperties }\n for (const rule of matchingRules) declareCustomProperties(customProperties, rule.declarations)\n declareCustomProperties(customProperties, node.inlineStyle ?? {})\n\n for (const rule of matchingRules) {\n Object.assign(computedStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n Object.assign(computedStyle, resolveDeclarations(node.inlineStyle ?? {}, customProperties))\n\n const context = { element: node, parent }\n return {\n ...node,\n computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,\n children: node.children.map((child) =>\n applyComputedStyles(child, rules, context, computedStyle, customProperties)\n )\n }\n}\n\nfunction pickInheritedStyle(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const inherited: DesignStyleDeclaration = {}\n for (const property of INHERITED_PROPERTIES) {\n const value = style[property]\n if (value) inherited[property] = value\n }\n return inherited\n}\n\nexport function computeHeadlessStyles(document: DesignDocument, cssText = ''): DesignDocument {\n const stylesheetText = [document.stylesheets?.map((sheet) => sheet.cssText).join('\\n'), cssText]\n .filter((text): text is string => !!text)\n .join('\\n')\n const { rules, customProperties } = parseRules(stylesheetText)\n // A fragment has no document element, so `:root` reaches its elements through inheritance only.\n const rootStyle: DesignStyleDeclaration = {}\n for (const rule of rules.filter(({ selector }) => selector === ':root')) {\n Object.assign(rootStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n\n return {\n ...document,\n children: document.children.map((child) =>\n applyComputedStyles(child, rules, null, rootStyle, customProperties)\n )\n }\n}\n","import { serializeHTML } from '#dom-css/export/html'\nimport { INLINE_TAGS } from '#dom-css/import/flow'\nimport { parseStyleAttribute } from '#dom-css/import/style-attribute'\nimport type { CSSRuntime, DesignDocument, DesignElement, DesignNode } from '#dom-css/types'\nimport { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { computeHeadlessStyles } from './styles'\n\nfunction attrsToRecord(attrs: DefaultTreeAdapterTypes.Element['attrs']): Record<string, string> {\n const result: Record<string, string> = {}\n for (const attr of attrs) result[attr.name] = attr.value\n return result\n}\n\nfunction isTextNode(\n node: DefaultTreeAdapterTypes.ChildNode\n): node is DefaultTreeAdapterTypes.TextNode {\n return node.nodeName === '#text'\n}\n\nconst NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])\n\nfunction isInlineElement(node: DefaultTreeAdapterTypes.ChildNode | undefined): boolean {\n return node !== undefined && 'tagName' in node && INLINE_TAGS.has(node.tagName.toLowerCase())\n}\n\n/**\n * Text, and the spaces in or beside inline elements, which CSS draws among their words; spaces\n * between blocks lay nothing out, so they are left out.\n */\nfunction keepsText(\n node: DefaultTreeAdapterTypes.TextNode,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n index: number,\n inInline: boolean\n): boolean {\n if (node.value.trim().length > 0) return true\n return (\n node.value.length > 0 &&\n (inInline || isInlineElement(siblings[index - 1]) || isInlineElement(siblings[index + 1]))\n )\n}\n\nfunction childrenToDesignNodes(\n nodes: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode[] {\n return nodes\n .map((node, index) => childToDesignNode(node, index, nodes, inInline))\n .filter((child): child is DesignNode => child !== null)\n}\n\nfunction childToDesignNode(\n node: DefaultTreeAdapterTypes.ChildNode,\n index: number,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode | null {\n if (isTextNode(node)) {\n return keepsText(node, siblings, index, inInline) ? { type: 'text', text: node.value } : null\n }\n\n if (!('tagName' in node)) return null\n if (NON_RENDERED_TAGS.has(node.tagName.toLowerCase())) return null\n\n const attrs = attrsToRecord(node.attrs)\n const element: DesignElement = {\n type: 'element',\n tagName: node.tagName.toLowerCase(),\n attrs,\n children: childrenToDesignNodes(node.childNodes, isInlineElement(node))\n }\n\n const inlineStyle = parseStyleAttribute(attrs.style)\n if (inlineStyle) element.inlineStyle = inlineStyle\n\n return element\n}\n\nfunction parseHTML(html: string): DesignDocument {\n const fragment = parseFragment(html)\n return {\n type: 'document',\n children: childrenToDesignNodes(fragment.childNodes, false)\n }\n}\n\nexport function createHeadlessCSSRuntime(): CSSRuntime {\n return {\n kind: 'headless',\n parseHTML,\n serializeHTML(document: DesignDocument) {\n return serializeHTML(document)\n },\n async computeStyles(document: DesignDocument, cssText = '') {\n return computeHeadlessStyles(document, cssText)\n }\n }\n}\n","import type { CSSRuntime } from '../types'\nimport { createBrowserCSSRuntime } from './browser/runtime'\nimport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport { createBrowserCSSRuntime } from './browser/runtime'\nexport type { BrowserCSSRuntimeOptions } from './browser/runtime'\nexport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport function createCSSRuntime(): CSSRuntime {\n return typeof document !== 'undefined' ? createBrowserCSSRuntime() : createHeadlessCSSRuntime()\n}\n","import { compile } from 'tailwindcss'\n\nexport interface CompileTailwindCSSOptions {\n css?: string\n base?: string\n loadStylesheet?: (id: string, base: string) => Promise<string>\n}\n\nconst DEFAULT_TAILWIND_CSS = '@import \"tailwindcss\";'\n\nexport async function compileTailwindCSS(\n classes: string | Iterable<string>,\n options: CompileTailwindCSSOptions = {}\n): Promise<string> {\n const compiler = await compile(tailwindCompilerCSS(options.css), {\n base: options.base,\n loadStylesheet: async (id, base) => {\n const content = options.loadStylesheet\n ? await options.loadStylesheet(id, base)\n : await loadTailwindStylesheet(id)\n return { path: id, base, content }\n }\n })\n return compiler.build(normalizeClasses(classes))\n}\n\nfunction tailwindCompilerCSS(css: string | undefined): string {\n const trimmed = css?.trim()\n if (!trimmed) return DEFAULT_TAILWIND_CSS\n if (containsTailwindImport(trimmed)) return trimmed\n return `${DEFAULT_TAILWIND_CSS}\\n${trimmed}`\n}\n\nfunction containsTailwindImport(css: string): boolean {\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n return /^\\s*@import\\s+(?:\"tailwindcss(?:\\/[^\"]*)?\"|'tailwindcss(?:\\/[^']*)?')/m.test(\n withoutComments\n )\n}\n\nfunction normalizeClasses(classes: string | Iterable<string>): string[] {\n const classNames = typeof classes === 'string' ? [classes] : Array.from(classes)\n return classNames\n .flatMap((className) => className.split(/\\s+/))\n .map((className) => className.trim())\n .filter((className) => className.length > 0)\n}\n\nasync function loadTailwindStylesheet(id: string): Promise<string> {\n const stylesheet = id === 'tailwindcss' ? 'tailwindcss/index.css' : id\n const url = new URL(import.meta.resolve(stylesheet))\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(url, 'utf8')\n}\n","import { parse, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { createCSSRuntime } from '../runtime'\nimport type { CSSComputeOptions, CSSRuntime, DesignDocument } from '../types'\nimport { mergeCSSText } from './css-text'\nimport { designDocumentToSceneGraph, type ToSceneGraphOptions } from './scene-graph'\nimport { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'\n\nexport interface HTMLToDesignDocumentOptions {\n cssText?: string\n runtime?: CSSRuntime\n compute?: CSSComputeOptions\n}\n\nexport interface HTMLToSceneGraphOptions extends HTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nexport interface TailwindHTMLToDesignDocumentOptions\n extends Omit<HTMLToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}\n\nexport interface TailwindHTMLToSceneGraphOptions\n extends TailwindHTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nfunction runtimeForOptions(runtime: CSSRuntime | undefined) {\n return runtime ?? createCSSRuntime()\n}\n\nfunction getChildNodes(node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.ChildNode[] {\n return 'childNodes' in node ? node.childNodes : []\n}\n\nfunction textContent(node: DefaultTreeAdapterTypes.Node): string {\n if (node.nodeName === '#text' && 'value' in node) return node.value\n return getChildNodes(node).map(textContent).join('')\n}\n\nfunction collectStyleText(node: DefaultTreeAdapterTypes.Node, styles: string[]): void {\n if ('tagName' in node && node.tagName.toLowerCase() === 'style') {\n const css = textContent(node).trim()\n if (css) styles.push(css)\n return\n }\n\n for (const child of getChildNodes(node)) collectStyleText(child, styles)\n}\n\nfunction extractEmbeddedCSSText(html: string): string | undefined {\n const styles: string[] = []\n collectStyleText(parse(html), styles)\n return styles.length > 0 ? styles.join('\\n') : undefined\n}\n\nexport async function htmlToDesignDocument(\n html: string,\n options: HTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const runtime = runtimeForOptions(options.runtime)\n const document = runtime.parseHTML(html)\n const cssText = mergeCSSText(extractEmbeddedCSSText(html), options.cssText)\n return runtime.computeStyles(document, cssText, options.compute)\n}\n\nexport async function htmlToSceneGraph(\n html: string,\n options: HTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await htmlToDesignDocument(html, options)\n return designDocumentToSceneGraph(document, options)\n}\n\nexport async function tailwindHTMLToDesignDocument(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const cssText = await compileTailwindCSS(candidates, options)\n return htmlToDesignDocument(html, { ...options, cssText })\n}\n\nexport async function tailwindHTMLToSceneGraph(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await tailwindHTMLToDesignDocument(html, candidates, options)\n return designDocumentToSceneGraph(document, options)\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,eAAe,SAA0C;CAChE,MAAM,CAAC,QAAQA,QAAM,OAAO,CAAC,CAAC;CAC9B,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,EAAE,WAAW,OAAO,OAAO;CACpE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAA+D;CACjG,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAAO,eAAe,KAAK,MAAM,EAAE;CACzC,IAAI,CAAC,MAAM,OAAO,KAAA;CAElB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,YAAY,MAAM,KAAK,KAAK,KAA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AI,GAAG,iBAAiB,OAAO,MAAM;AACzE;AAEA,SAAS,uBAAuB,MAAkC;CAChE,MAAM,SAAmB,CAAC;CAC1B,iBAAiB,MAAM,IAAI,GAAG,MAAM;CACpC,OAAO,OAAO,SAAS,IAAI,OAAO,KAAK,IAAI,IAAI,KAAA;AACjD;AAEA,eAAsB,qBACpB,MACA,UAAuC,CAAC,GACf;CACzB,MAAM,UAAU,kBAAkB,QAAQ,OAAO;CACjD,MAAM,WAAW,QAAQ,UAAU,IAAI;CACvC,MAAM,UAAU,aAAa,uBAAuB,IAAI,GAAG,QAAQ,OAAO;CAC1E,OAAO,QAAQ,cAAc,UAAU,SAAS,QAAQ,OAAO;AACjE;AAEA,eAAsB,iBACpB,MACA,UAAmC,CAAC,GACf;CACrB,MAAM,WAAW,MAAM,qBAAqB,MAAM,OAAO;CACzD,OAAO,2BAA2B,UAAU,OAAO;AACrD;AAEA,eAAsB,6BACpB,MACA,YACA,UAA+C,CAAC,GACvB;CACzB,MAAM,UAAU,MAAM,mBAAmB,YAAY,OAAO;CAC5D,OAAO,qBAAqB,MAAM;EAAE,GAAG;EAAS;CAAQ,CAAC;AAC3D;AAEA,eAAsB,yBACpB,MACA,YACA,UAA2C,CAAC,GACvB;CACrB,MAAM,WAAW,MAAM,6BAA6B,MAAM,YAAY,OAAO;CAC7E,OAAO,2BAA2B,UAAU,OAAO;AACrD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/dom-css",
3
- "version": "0.16.2",
3
+ "version": "0.17.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,7 +11,7 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "dependencies": {
13
13
  "@acemir/cssom": "^0.9.31",
14
- "@pairdraw/emit": "^0.16.2",
14
+ "@pairdraw/emit": "^0.17.0",
15
15
  "css-tree": "^3.2.1",
16
16
  "cssesc": "^3.0.0",
17
17
  "dedent": "^1.7.2",
@@ -24,7 +24,7 @@
24
24
  "twirlwind": "^0.4.1"
25
25
  },
26
26
  "peerDependencies": {
27
- "@pairdraw/scene-graph": "^0.16.2"
27
+ "@pairdraw/scene-graph": "^0.17.0"
28
28
  },
29
29
  "exports": {
30
30
  ".": {
@@ -374,8 +374,14 @@ function stylesheetLink(path: string): string {
374
374
  return `<link rel="stylesheet" href="${assetURL(path)}">`
375
375
  }
376
376
 
377
+ /**
378
+ * A `<style>` element holding `css`. The HTML parser ends the element at the first `</style`
379
+ * in any letter case, whatever the CSS around it means, and style values can come from an
380
+ * imported document, so each one is written `<\/style`, which CSS strings and URLs read back
381
+ * as `</style`.
382
+ */
377
383
  function styleTag(css: string): string {
378
- return css ? `<style>${css}</style>` : ''
384
+ return css ? `<style>${css.replace(/<\/(?=style)/gi, '<\\/')}</style>` : ''
379
385
  }
380
386
 
381
387
  type ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &
@@ -78,6 +78,22 @@ export function mergeClassNames(...values: Array<string | undefined>): string |
78
78
  return className.length > 0 ? className : undefined
79
79
  }
80
80
 
81
+ /**
82
+ * Characters that end an attribute name or quote one. Imported JSX props can have any name, and
83
+ * one holding these would write other attributes, so such a name is left out.
84
+ */
85
+ const UNSAFE_ATTRIBUTE_NAME = /[\s"'/=>]/
86
+
87
+ /**
88
+ * HTML, SVG, and custom element names. Imported JSX can name any tag, and one holding spaces or
89
+ * quotes would write attributes, so another name is written as a `div` with the same content.
90
+ */
91
+ const SAFE_TAG_NAME = /^[a-z][\w.:-]*$/i
92
+
93
+ function safeTagName(tagName: string): string {
94
+ return SAFE_TAG_NAME.test(tagName) ? tagName : 'div'
95
+ }
96
+
81
97
  function serializeAttrs(node: DesignElement, options: SerializeHTMLOptions): string {
82
98
  const style = serializeStyle(node)
83
99
  const tailwindClass =
@@ -92,6 +108,7 @@ function serializeAttrs(node: DesignElement, options: SerializeHTMLOptions): str
92
108
  if (style && options.style !== 'tailwind') attrs.style = style
93
109
  const serialized = Object.entries(attrs)
94
110
  .filter((entry): entry is [string, string] => typeof entry[1] === 'string' && entry[1] !== '')
111
+ .filter(([name]) => name !== '' && !UNSAFE_ATTRIBUTE_NAME.test(name))
95
112
  .map(([name, value]) => `${name}="${escapeAttribute(value)}"`)
96
113
 
97
114
  if (serialized.length === 0) return ''
@@ -113,7 +130,7 @@ function serializeElement(
113
130
  depth: number
114
131
  ): string {
115
132
  // SVG names such as `linearGradient` keep their case, as an SVG parser needs them.
116
- const tagName = node.tagName
133
+ const tagName = safeTagName(node.tagName)
117
134
  const attrs = serializeAttrs(node, options)
118
135
  if (VOID_ELEMENTS.has(tagName.toLowerCase())) return `<${tagName}${attrs}>`
119
136
  const children = [
@@ -143,7 +160,7 @@ export function serializeNode(
143
160
  export function serializedElements(document: DesignDocument): (DesignElement | null)[] {
144
161
  const visit = (node: DesignNode): (DesignElement | null)[] => {
145
162
  if (node.type === 'text') return []
146
- if (VOID_ELEMENTS.has(node.tagName.toLowerCase())) return [node]
163
+ if (VOID_ELEMENTS.has(safeTagName(node.tagName).toLowerCase())) return [node]
147
164
  return [node, ...(node.shader?.frame ? [null] : []), ...node.children.flatMap(visit)]
148
165
  }
149
166
  return document.children.flatMap(visit)