AI-native design editor. Open-source Figma alternative.
fix(dom-css): apply embedded HTML styles
Danila Poyarkov4811cac69bcf
diff --git a/packages/dom-css/src/browser.ts b/packages/dom-css/src/browser.tsindex 9433df91c..0e0376f85 100644--- a/packages/dom-css/src/browser.ts+++ b/packages/dom-css/src/browser.ts@@ -4,6 +4,7 @@ import { jsxToDesignDocument, type JSXChild } from './jsx/runtime'export { Fragment, jsx, jsxs } from './jsx/runtime'export type { JSXChild, JSXElementProps, JSXStyleInput, JSXTag } from './jsx/runtime'+import { mergeCSSText } from './css-text'import { createBrowserCSSRuntime, type BrowserCSSRuntimeOptions } from './runtime/browser'import { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './to-scene-graph'@@ -38,13 +39,33 @@ function createRuntime(options: BrowserCSSRuntimeOptions) {return createBrowserCSSRuntime({ sandbox: 'iframe', ...options })}+function resolveBrowserDocument(documentOverride: Document | undefined): Document {+ if (documentOverride) return documentOverride+ if (typeof document === 'undefined') {+ throw new TypeError('Browser DOM/CSS helpers require a DOM document')+ }+ return document+}++function extractEmbeddedCSSText(html: string, browserDocument: Document): string | undefined {+ const Parser = browserDocument.defaultView?.DOMParser+ if (!Parser) throw new TypeError('Browser DOM/CSS helpers require DOMParser')+ const parsed = new Parser().parseFromString(html, 'text/html')+ const styles = Array.from(parsed.querySelectorAll('style'))+ .map((style) => (style.textContent ? style.textContent.trim() : ''))+ .filter((css): css is string => !!css)+ return styles.length > 0 ? styles.join('\n') : undefined+}+export async function browserHTMLToDesignDocument(html: string,options: BrowserHTMLToDesignDocumentOptions = {}): Promise<DesignDocument> {- const runtime = createRuntime(options)+ const browserDocument = resolveBrowserDocument(options.document)+ const runtime = createRuntime({ ...options, document: browserDocument })const document = runtime.parseHTML(html)- return runtime.computeStyles(document, options.cssText, options.compute)+ const cssText = mergeCSSText(extractEmbeddedCSSText(html, browserDocument), options.cssText)+ return runtime.computeStyles(document, cssText, options.compute)}export async function browserHTMLToSceneGraph(diff --git a/packages/dom-css/src/convert.ts b/packages/dom-css/src/convert.tsindex a67aa6ba3..573f570e4 100644--- a/packages/dom-css/src/convert.ts+++ b/packages/dom-css/src/convert.ts@@ -1,5 +1,8 @@+import { parse, type DefaultTreeAdapterTypes } from 'parse5'+import type { SceneGraph } from '@open-pencil/core/scene-graph'+import { mergeCSSText } from './css-text'import { createCSSRuntime } from './runtime'import { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'import { designDocumentToSceneGraph, type ToSceneGraphOptions } from './to-scene-graph'@@ -23,13 +26,39 @@ function runtimeForOptions(runtime: CSSRuntime | undefined) {return runtime ?? createCSSRuntime()}+function getChildNodes(node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.ChildNode[] {+ return 'childNodes' in node ? node.childNodes : []+}++function textContent(node: DefaultTreeAdapterTypes.Node): string {+ if (node.nodeName === '#text' && 'value' in node) return node.value+ return getChildNodes(node).map(textContent).join('')+}++function collectStyleText(node: DefaultTreeAdapterTypes.Node, styles: string[]): void {+ if ('tagName' in node && node.tagName.toLowerCase() === 'style') {+ const css = textContent(node).trim()+ if (css) styles.push(css)+ return+ }++ for (const child of getChildNodes(node)) collectStyleText(child, styles)+}++function extractEmbeddedCSSText(html: string): string | undefined {+ const styles: string[] = []+ collectStyleText(parse(html), styles)+ return styles.length > 0 ? styles.join('\n') : undefined+}+export async function htmlToDesignDocument(html: string,options: HTMLToDesignDocumentOptions = {}): Promise<DesignDocument> {const runtime = runtimeForOptions(options.runtime)const document = runtime.parseHTML(html)- return runtime.computeStyles(document, options.cssText, options.compute)+ const cssText = mergeCSSText(extractEmbeddedCSSText(html), options.cssText)+ return runtime.computeStyles(document, cssText, options.compute)}export async function htmlToSceneGraph(diff --git a/packages/dom-css/src/css-text.ts b/packages/dom-css/src/css-text.tsnew file mode 100644index 000000000..c70cf34ce--- /dev/null+++ b/packages/dom-css/src/css-text.ts@@ -0,0 +1,4 @@+export function mergeCSSText(...parts: Array<string | undefined>): string | undefined {+ const text = parts.map((part) => part?.trim()).filter((part): part is string => !!part)+ return text.length > 0 ? text.join('\n') : undefined+}diff --git a/packages/dom-css/src/runtime/browser.ts b/packages/dom-css/src/runtime/browser.tsindex 8fc6428ab..01342cdb9 100644--- a/packages/dom-css/src/runtime/browser.ts+++ b/packages/dom-css/src/runtime/browser.ts@@ -92,6 +92,8 @@ function styleToRecord(style: CSSStyleDeclaration): Record<string, string> | undreturn Object.keys(entries).length > 0 ? entries : undefined}+const NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])+function domNodeToDesignNode(node: Node): DesignNode | null {if (node.nodeType === 3) {const text = node.textContent ?? ''@@ -101,6 +103,7 @@ function domNodeToDesignNode(node: Node): DesignNode | null {if (node.nodeType !== 1) return nullconst element = node as Element+ if (NON_RENDERED_TAGS.has(element.tagName.toLowerCase())) return nullconst children = Array.from(element.childNodes).map(domNodeToDesignNode).filter((child): child is DesignNode => child !== null)diff --git a/packages/dom-css/src/runtime/headless.ts b/packages/dom-css/src/runtime/headless.tsindex 1bb2937b7..309e91c79 100644--- a/packages/dom-css/src/runtime/headless.ts+++ b/packages/dom-css/src/runtime/headless.ts@@ -17,12 +17,15 @@ function isTextNode(return node.nodeName === '#text'}+const NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])+function childToDesignNode(node: DefaultTreeAdapterTypes.ChildNode): DesignNode | null {if (isTextNode(node)) {return node.value.trim().length > 0 ? { type: 'text', text: node.value } : null}if (!('tagName' in node)) return null+ if (NON_RENDERED_TAGS.has(node.tagName.toLowerCase())) return nullconst attrs = attrsToRecord(node.attrs)const element: DesignElement = {diff --git a/packages/dom-css/tests/conversion.test.ts b/packages/dom-css/tests/conversion.test.tsindex 0ca85206e..2279118e5 100644--- a/packages/dom-css/tests/conversion.test.ts+++ b/packages/dom-css/tests/conversion.test.ts@@ -167,6 +167,34 @@ describe('@open-pencil/dom-css conversion', () => {expect(card.effects[0]?.type).toBe('DROP_SHADOW')})+ it('applies embedded HTML style blocks without creating style layers', async () => {+ const graph = await htmlToSceneGraph(+ `<!doctype html>+ <html>+ <head>+ <style>+ .card { display: flex; flex-direction: column; gap: 10px; width: 280px; height: 140px; padding: 20px; }+ </style>+ </head>+ <body><article class="card"><h1>Embedded CSS</h1></article></body>+ </html>`,+ { runtime: createHeadlessCSSRuntime() }+ )+ const page = graph.getPages()[0]+ expect(page).toBeDefined()+ if (!page) return+ const card = graph.getChildren(page.id)[0]++ expect(card?.type).toBe('FRAME')+ if (card?.type !== 'FRAME') return+ expect(card.name).toBe('card')+ expect(card.width).toBe(280)+ expect(card.height).toBe(140)+ expect(card.itemSpacing).toBe(10)+ expect(card.paddingLeft).toBe(20)+ expect(graph.getChildren(page.id)).toHaveLength(1)+ })+it('keeps box-like inline controls as editable frames', async () => {const graph = await htmlToSceneGraph(fixtureHTML, {cssText: fixtureCSS,diff --git a/tests/e2e/dom-css/browser-runtime.spec.ts b/tests/e2e/dom-css/browser-runtime.spec.tsindex de9264e13..232be2823 100644--- a/tests/e2e/dom-css/browser-runtime.spec.ts+++ b/tests/e2e/dom-css/browser-runtime.spec.ts@@ -58,7 +58,7 @@ async function browserRuntimeComputeStyles()}-async function publicBrowserHTMLSceneGraph(page: Page, html: string, cssText: string) {+async function publicBrowserHTMLSceneGraph(page: Page, html: string, cssText = '') {if (!page.url().startsWith('http://localhost:1420')) {await page.goto('/')await page.setContent('<main></main>')@@ -517,6 +517,28 @@ test.describe('@open-pencil/dom-css browser CSS runtime oracle', () => {expect(card?.paddingLeft).toBe(24)})+ test('projects embedded HTML styles through public browser helpers', async ({ page }) => {+ const card = await publicBrowserHTMLSceneGraph(+ page,+ `<!doctype html>+ <html>+ <head>+ <style>+ .card { display: flex; flex-direction: column; gap: 14px; width: 300px; height: 160px; padding: 22px; }+ </style>+ </head>+ <body><article class="card"><h1>Embedded CSS</h1></article></body>+ </html>`+ )++ expect(card?.type).toBe('FRAME')+ expect(card?.width).toBe(300)+ expect(card?.height).toBe(160)+ expect(card?.layoutMode).toBe('VERTICAL')+ expect(card?.itemSpacing).toBe(14)+ expect(card?.paddingLeft).toBe(22)+ })+test('projects JSX through public browser helpers into scene graph', async ({ page }) => {const css = await compileTailwindCSS(tailwindCardClasses)const card = await publicBrowserSceneGraph(page, [...tailwindCardClasses], css)diff --git a/tests/engine/cli/dom.test.ts b/tests/engine/cli/dom.test.tsindex 52b473063..94bbd2d5e 100644--- a/tests/engine/cli/dom.test.ts+++ b/tests/engine/cli/dom.test.ts@@ -101,6 +101,44 @@ test('dom CLI writes DesignDOM JSON output', async () => {expect(document.children[0].computedStyle.width).toBe('240px')})+test('dom CLI reads embedded HTML styles without a sidecar CSS file', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-dom-cli-embedded-'))+ const htmlPath = join(dir, 'embedded.html')+ const output = join(dir, 'embedded.json')++ await Bun.write(+ htmlPath,+ `<!doctype html>+ <html>+ <head>+ <style>+ .card { display: flex; flex-direction: column; gap: 10px; width: 280px; height: 140px; padding: 20px; }+ </style>+ </head>+ <body><article class="card"><h1>Embedded CSS</h1></article></body>+ </html>`+ )++ const { stdout, stderr, exitCode } = await run([+ 'dom',+ htmlPath,+ '--format',+ 'json',+ '--output',+ output,+ '--json'+ ])++ expect(stderr).toBe('')+ expect(exitCode).toBe(0)+ expect(JSON.parse(stdout)).toMatchObject({ format: 'json', output, rootElements: 1 })++ const document = JSON.parse(await Bun.file(output).text())+ expect(document.children[0].tagName).toBe('article')+ expect(document.children[0].computedStyle.width).toBe('280px')+ expect(document.children[0].computedStyle.gap).toBe('10px')+})+test('dom CLI writes serialized HTML output', async () => {const { htmlPath, cssPath, dir } = await createFixture()const output = join(dir, 'card.out.html')