Skip to content

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

feat(dom-css): deepen browser runtime mapping

Danila Poyarkov6e7e268c855a
diff --git a/packages/dom-css/src/from-scene-graph.ts b/packages/dom-css/src/from-scene-graph.ts
index cd8769e41..d39a24644 100644
--- a/packages/dom-css/src/from-scene-graph.ts
+++ b/packages/dom-css/src/from-scene-graph.ts
@@ -31,16 +31,53 @@ function alignItemsToCSS(value: SceneNode['counterAxisAlign']): string | undefin
return undefined
}
+function addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode): void {
+ if (node.minWidth !== null) style['min-width'] = `${node.minWidth}px`
+ if (node.maxWidth !== null) style['max-width'] = `${node.maxWidth}px`
+ if (node.minHeight !== null) style['min-height'] = `${node.minHeight}px`
+ if (node.maxHeight !== null) style['max-height'] = `${node.maxHeight}px`
+}
+
+function addCornerRadii(style: DesignStyleDeclaration, node: SceneNode): void {
+ if (node.independentCorners) {
+ if (node.topLeftRadius > 0) style['border-top-left-radius'] = `${node.topLeftRadius}px`
+ if (node.topRightRadius > 0) style['border-top-right-radius'] = `${node.topRightRadius}px`
+ if (node.bottomRightRadius > 0)
+ style['border-bottom-right-radius'] = `${node.bottomRightRadius}px`
+ if (node.bottomLeftRadius > 0) style['border-bottom-left-radius'] = `${node.bottomLeftRadius}px`
+ return
+ }
+
+ if (node.cornerRadius > 0) style['border-radius'] = `${node.cornerRadius}px`
+}
+
+function addStroke(style: DesignStyleDeclaration, node: SceneNode): void {
+ const stroke = strokeToCSS(node.strokes[0])
+ if (!stroke) return
+ if (!node.independentStrokeWeights) {
+ style.border = stroke
+ return
+ }
+
+ style['border-style'] = 'solid'
+ style['border-color'] = stroke.split(' solid ').at(1) ?? 'currentColor'
+ if (node.borderTopWeight > 0) style['border-top-width'] = `${node.borderTopWeight}px`
+ if (node.borderRightWeight > 0) style['border-right-width'] = `${node.borderRightWeight}px`
+ if (node.borderBottomWeight > 0) style['border-bottom-width'] = `${node.borderBottomWeight}px`
+ if (node.borderLeftWeight > 0) style['border-left-width'] = `${node.borderLeftWeight}px`
+}
+
function styleFromSceneNode(node: SceneNode): DesignStyleDeclaration {
const style = sceneNodeSizeStyle(node)
+ addSizeConstraints(style, node)
const fill = fillToCSS(node.fills[0])
if (fill) style['background-color'] = fill
- const stroke = strokeToCSS(node.strokes[0])
- if (stroke) style.border = stroke
+ addStroke(style, node)
const shadow = dropShadowToCSS(node.effects[0])
if (shadow) style['box-shadow'] = shadow
if (node.opacity < 1) style.opacity = String(node.opacity)
- if (node.cornerRadius > 0) style['border-radius'] = `${node.cornerRadius}px`
+ addCornerRadii(style, node)
+ if (node.clipsContent) style.overflow = 'hidden'
if (node.layoutMode !== 'NONE') {
style.display = 'flex'
diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.ts
index d05203839..15740b99b 100644
--- a/packages/dom-css/src/index.ts
+++ b/packages/dom-css/src/index.ts
@@ -4,6 +4,7 @@ export { designDocumentToSceneGraph } from './to-scene-graph'
export { sceneGraphToDesignDocument } from './from-scene-graph'
export { compileTailwindCSS } from './tailwind'
export type { ToDesignDocumentOptions } from './from-scene-graph'
+export type { BrowserCSSRuntimeOptions } from './runtime'
export type { CompileTailwindCSSOptions } from './tailwind'
export type { ToSceneGraphOptions } from './to-scene-graph'
export type {
diff --git a/packages/dom-css/src/runtime/browser.ts b/packages/dom-css/src/runtime/browser.ts
index 48a6b713c..734522c79 100644
--- a/packages/dom-css/src/runtime/browser.ts
+++ b/packages/dom-css/src/runtime/browser.ts
@@ -7,6 +7,11 @@ import type {
DesignNode
} from '../types'
+export interface BrowserCSSRuntimeOptions {
+ document?: Document
+ sandbox?: 'shadow-root' | 'iframe'
+}
+
const DEFAULT_COMPUTED_PROPERTIES = [
'align-items',
'background-color',
@@ -37,7 +42,12 @@ const DEFAULT_COMPUTED_PROPERTIES = [
'justify-content',
'letter-spacing',
'line-height',
+ 'max-height',
+ 'max-width',
+ 'min-height',
+ 'min-width',
'opacity',
+ 'overflow',
'padding-bottom',
'padding-left',
'padding-right',
@@ -47,7 +57,8 @@ const DEFAULT_COMPUTED_PROPERTIES = [
'width'
] as const
-function requireBrowserDocument(): Document {
+function resolveBrowserDocument(documentOverride: Document | undefined): Document {
+ if (documentOverride) return documentOverride
if (typeof document === 'undefined') {
throw new TypeError('Browser CSS runtime requires a DOM document')
}
@@ -72,12 +83,15 @@ function styleToRecord(style: CSSStyleDeclaration): Record<string, string> | und
}
function domNodeToDesignNode(node: Node): DesignNode | null {
- if (node.nodeType === Node.TEXT_NODE) {
+ const view = node.ownerDocument?.defaultView
+ if (!view) return null
+
+ if (node.nodeType === view.Node.TEXT_NODE) {
const text = node.textContent ?? ''
return text.length > 0 ? { type: 'text', text } : null
}
- if (node.nodeType !== Node.ELEMENT_NODE || !(node instanceof Element)) return null
+ if (node.nodeType !== view.Node.ELEMENT_NODE || !(node instanceof view.Element)) return null
const children = Array.from(node.childNodes)
.map(domNodeToDesignNode)
@@ -88,13 +102,15 @@ function domNodeToDesignNode(node: Node): DesignNode | null {
tagName: node.tagName.toLowerCase(),
attrs: attributesToRecord(node),
children,
- inlineStyle: node instanceof HTMLElement ? styleToRecord(node.style) : undefined
+ inlineStyle: node instanceof view.HTMLElement ? styleToRecord(node.style) : undefined
}
}
-function parseHTML(html: string): DesignDocument {
- requireBrowserDocument()
- const parsed = new DOMParser().parseFromString(html, 'text/html')
+function parseHTMLWithDocument(browserDocument: Document, html: string): DesignDocument {
+ const Parser = browserDocument.defaultView?.DOMParser
+ if (!Parser) throw new TypeError('Browser CSS runtime requires DOMParser')
+ const parser = new Parser()
+ const parsed = parser.parseFromString(html, 'text/html')
return {
type: 'document',
children: Array.from(parsed.body.childNodes)
@@ -109,7 +125,8 @@ function collectElementPairs(
pairs: [DesignElement, Element][]
): void {
if (designNode.type === 'text') return
- if (!(domNode instanceof Element)) return
+ const view = domNode.ownerDocument?.defaultView
+ if (!view || !(domNode instanceof view.Element)) return
pairs.push([designNode, domNode])
@@ -140,14 +157,16 @@ function computedStyleToRecord(
return entries
}
-async function computeStyles(
- designDocument: DesignDocument,
- cssText = '',
- options: CSSComputeOptions = {}
-): Promise<DesignDocument> {
- const browserDocument = requireBrowserDocument()
- const host = browserDocument.createElement('div')
- host.style.cssText = [
+function requestFrame(browserDocument: Document): Promise<void> {
+ const requestAnimationFrame = browserDocument.defaultView?.requestAnimationFrame
+ if (!requestAnimationFrame) return Promise.resolve()
+ return new Promise((resolve) => {
+ requestAnimationFrame(() => resolve())
+ })
+}
+
+function applySandboxHostStyle(element: HTMLElement): void {
+ element.style.cssText = [
'position: fixed',
'left: -100000px',
'top: 0',
@@ -157,6 +176,16 @@ async function computeStyles(
'pointer-events: none',
'contain: layout style paint'
].join(';')
+}
+
+async function computeStylesInShadowRoot(
+ browserDocument: Document,
+ designDocument: DesignDocument,
+ cssText: string,
+ options: CSSComputeOptions
+): Promise<DesignDocument> {
+ const host = browserDocument.createElement('div')
+ applySandboxHostStyle(host)
const shadow = host.attachShadow({ mode: 'open' })
const style = browserDocument.createElement('style')
@@ -169,33 +198,79 @@ async function computeStyles(
browserDocument.body.append(host)
try {
- await new Promise<void>((resolve) => {
- requestAnimationFrame(() => resolve())
- })
-
- const nextDocument = structuredClone(designDocument)
- const pairs: [DesignElement, Element][] = []
- const domChildren = Array.from(content.childNodes)
- for (const [index, child] of nextDocument.children.entries()) {
- const domChild = domChildren.at(index)
- if (domChild) collectElementPairs(child, domChild, pairs)
- }
-
- for (const [designElement, domElement] of pairs) {
- designElement.computedStyle = computedStyleToRecord(getComputedStyle(domElement), options)
- }
-
- return nextDocument
+ await requestFrame(browserDocument)
+ return copyComputedStyles(designDocument, content, options)
} finally {
host.remove()
}
}
-export function createBrowserCSSRuntime(): CSSRuntime {
+async function computeStylesInIframe(
+ browserDocument: Document,
+ designDocument: DesignDocument,
+ cssText: string,
+ options: CSSComputeOptions
+): Promise<DesignDocument> {
+ const iframe = browserDocument.createElement('iframe')
+ applySandboxHostStyle(iframe)
+ browserDocument.body.append(iframe)
+
+ try {
+ const iframeDocument = iframe.contentDocument
+ if (!iframeDocument) throw new TypeError('Browser CSS runtime could not create iframe document')
+ iframeDocument.open()
+ iframeDocument.write(`<!doctype html><html><head></head><body></body></html>`)
+ iframeDocument.close()
+
+ const style = iframeDocument.createElement('style')
+ style.textContent = cssText
+ iframeDocument.head.append(style)
+
+ const content = iframeDocument.createElement('div')
+ content.innerHTML = serializeHTML(designDocument)
+ iframeDocument.body.append(content)
+
+ await requestFrame(iframeDocument)
+ return copyComputedStyles(designDocument, content, options)
+ } finally {
+ iframe.remove()
+ }
+}
+
+function copyComputedStyles(
+ designDocument: DesignDocument,
+ content: Element,
+ options: CSSComputeOptions
+): DesignDocument {
+ const view = content.ownerDocument.defaultView
+ if (!view) throw new TypeError('Browser CSS runtime requires getComputedStyle')
+
+ const nextDocument = structuredClone(designDocument)
+ const pairs: [DesignElement, Element][] = []
+ const domChildren = Array.from(content.childNodes)
+ for (const [index, child] of nextDocument.children.entries()) {
+ const domChild = domChildren.at(index)
+ if (domChild) collectElementPairs(child, domChild, pairs)
+ }
+
+ for (const [designElement, domElement] of pairs) {
+ designElement.computedStyle = computedStyleToRecord(view.getComputedStyle(domElement), options)
+ }
+
+ return nextDocument
+}
+
+export function createBrowserCSSRuntime(options: BrowserCSSRuntimeOptions = {}): CSSRuntime {
+ const browserDocument = resolveBrowserDocument(options.document)
+ const sandbox = options.sandbox ?? 'shadow-root'
+
return {
kind: 'browser',
- parseHTML,
+ parseHTML: (html) => parseHTMLWithDocument(browserDocument, html),
serializeHTML,
- computeStyles
+ computeStyles: (designDocument, cssText = '', computeOptions = {}) =>
+ sandbox === 'iframe'
+ ? computeStylesInIframe(browserDocument, designDocument, cssText, computeOptions)
+ : computeStylesInShadowRoot(browserDocument, designDocument, cssText, computeOptions)
}
}
diff --git a/packages/dom-css/src/runtime/index.ts b/packages/dom-css/src/runtime/index.ts
index 7af260ea3..0ef6ee693 100644
--- a/packages/dom-css/src/runtime/index.ts
+++ b/packages/dom-css/src/runtime/index.ts
@@ -3,6 +3,7 @@ import { createBrowserCSSRuntime } from './browser'
import { createHeadlessCSSRuntime } from './headless'
export { createBrowserCSSRuntime } from './browser'
+export type { BrowserCSSRuntimeOptions } from './browser'
export { createHeadlessCSSRuntime } from './headless'
export function createCSSRuntime(): CSSRuntime {
diff --git a/packages/dom-css/src/to-scene-graph.ts b/packages/dom-css/src/to-scene-graph.ts
index a7721c246..fb278e460 100644
--- a/packages/dom-css/src/to-scene-graph.ts
+++ b/packages/dom-css/src/to-scene-graph.ts
@@ -1,4 +1,4 @@
-import { SceneGraph, type Fill, type SceneNode } from '@open-pencil/core/scene-graph'
+import { SceneGraph, type Fill, type SceneNode, type Stroke } from '@open-pencil/core/scene-graph'
import {
colorToFillFromCSS,
@@ -52,8 +52,74 @@ function fillsFromStyle(style: DesignStyleDeclaration, property: string): Fill[]
function setNodeBox(node: SceneNode, style: DesignStyleDeclaration): void {
const width = firstCSSNumber(style, 'width')
const height = firstCSSNumber(style, 'height')
+ const minWidth = firstCSSNumber(style, 'min-width')
+ const maxWidth = firstCSSNumber(style, 'max-width')
+ const minHeight = firstCSSNumber(style, 'min-height')
+ const maxHeight = firstCSSNumber(style, 'max-height')
if (width !== null) node.width = width
if (height !== null) node.height = height
+ if (minWidth !== null) node.minWidth = minWidth
+ if (maxWidth !== null) node.maxWidth = maxWidth
+ if (minHeight !== null) node.minHeight = minHeight
+ if (maxHeight !== null) node.maxHeight = maxHeight
+}
+
+function firstStrokeColor(style: DesignStyleDeclaration) {
+ return (
+ pickStyle(style, 'border-color') ??
+ pickStyle(style, 'border-top-color') ??
+ pickStyle(style, 'border-right-color') ??
+ pickStyle(style, 'border-bottom-color') ??
+ pickStyle(style, 'border-left-color')
+ )
+}
+
+function firstStrokeWeight(style: DesignStyleDeclaration) {
+ return firstCSSNumber(
+ style,
+ 'border-width',
+ 'border-top-width',
+ 'border-right-width',
+ 'border-bottom-width',
+ 'border-left-width'
+ )
+}
+
+function setBorderWeights(node: SceneNode, style: DesignStyleDeclaration, stroke: Stroke): void {
+ const top = firstCSSNumber(style, 'border-top-width') ?? stroke.weight
+ const right = firstCSSNumber(style, 'border-right-width') ?? stroke.weight
+ const bottom = firstCSSNumber(style, 'border-bottom-width') ?? stroke.weight
+ const left = firstCSSNumber(style, 'border-left-width') ?? stroke.weight
+ node.borderTopWeight = top
+ node.borderRightWeight = right
+ node.borderBottomWeight = bottom
+ node.borderLeftWeight = left
+ node.independentStrokeWeights = [top, right, bottom, left].some(
+ (weight) => weight !== stroke.weight
+ )
+}
+
+function applyCornerRadii(node: SceneNode, style: DesignStyleDeclaration): void {
+ const cornerRadius = firstCSSNumber(style, 'border-radius')
+ const topLeft = firstCSSNumber(style, 'border-top-left-radius')
+ const topRight = firstCSSNumber(style, 'border-top-right-radius')
+ const bottomRight = firstCSSNumber(style, 'border-bottom-right-radius')
+ const bottomLeft = firstCSSNumber(style, 'border-bottom-left-radius')
+
+ if (cornerRadius !== null) node.cornerRadius = cornerRadius
+ if (topLeft === null && topRight === null && bottomRight === null && bottomLeft === null) return
+
+ const fallback = cornerRadius ?? 0
+ node.topLeftRadius = topLeft ?? fallback
+ node.topRightRadius = topRight ?? fallback
+ node.bottomRightRadius = bottomRight ?? fallback
+ node.bottomLeftRadius = bottomLeft ?? fallback
+ node.independentCorners = [
+ node.topLeftRadius,
+ node.topRightRadius,
+ node.bottomRightRadius,
+ node.bottomLeftRadius
+ ].some((radius) => radius !== fallback)
}
function primaryAxisAlignFromCSS(value: string | undefined): SceneNode['primaryAxisAlign'] {
@@ -78,10 +144,13 @@ function applyElementStyle(node: SceneNode, style: DesignStyleDeclaration): void
if (fills.length > 0) node.fills = fills
const strokes = colorToStrokeFromCSS(
- pickStyle(style, 'border-color'),
- pickStyle(style, 'border-width')
+ firstStrokeColor(style),
+ firstStrokeWeight(style)?.toString()
)
- if (strokes.length > 0) node.strokes = strokes
+ if (strokes.length > 0) {
+ node.strokes = strokes
+ setBorderWeights(node, style, strokes[0])
+ }
const effects = dropShadowFromCSS(pickStyle(style, 'box-shadow'))
if (effects.length > 0) node.effects = effects
@@ -89,8 +158,9 @@ function applyElementStyle(node: SceneNode, style: DesignStyleDeclaration): void
const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
if (opacity !== null) node.opacity = opacity
- const cornerRadius = firstCSSNumber(style, 'border-radius')
- if (cornerRadius !== null) node.cornerRadius = cornerRadius
+ applyCornerRadii(node, style)
+
+ if (pickStyle(style, 'overflow') === 'hidden') node.clipsContent = true
const display = pickStyle(style, 'display')
if (display === 'flex' || display === 'inline-flex') {
diff --git a/tests/engine/dom-css/conversion.test.ts b/tests/engine/dom-css/conversion.test.ts
index b3e571484..9bfa58687 100644
--- a/tests/engine/dom-css/conversion.test.ts
+++ b/tests/engine/dom-css/conversion.test.ts
@@ -71,6 +71,70 @@ describe('@open-pencil/dom-css conversion', () => {
expect(html).toContain('box-shadow')
})
+ it('maps CSS shape constraints, clipping, corners, and borders', () => {
+ const graph = designDocumentToSceneGraph({
+ type: 'document',
+ children: [
+ {
+ type: 'element',
+ tagName: 'div',
+ attrs: { class: 'panel' },
+ computedStyle: {
+ width: '320px',
+ height: '160px',
+ 'min-width': '240px',
+ 'max-width': '480px',
+ 'min-height': '120px',
+ 'max-height': '320px',
+ overflow: 'hidden',
+ 'border-top-color': 'rgb(229, 231, 235)',
+ 'border-top-width': '1px',
+ 'border-right-width': '2px',
+ 'border-bottom-width': '3px',
+ 'border-left-width': '4px',
+ 'border-top-left-radius': '4px',
+ 'border-top-right-radius': '8px',
+ 'border-bottom-right-radius': '12px',
+ 'border-bottom-left-radius': '16px'
+ },
+ children: []
+ }
+ ]
+ })
+ const page = graph.getPages()[0]
+ const panel = page ? graph.getChildren(page.id)[0] : undefined
+
+ expect(panel?.type).toBe('FRAME')
+ if (panel?.type !== 'FRAME') return
+ expect(panel.minWidth).toBe(240)
+ expect(panel.maxWidth).toBe(480)
+ expect(panel.minHeight).toBe(120)
+ expect(panel.maxHeight).toBe(320)
+ expect(panel.clipsContent).toBe(true)
+ expect(panel.independentStrokeWeights).toBe(true)
+ expect(panel.borderTopWeight).toBe(1)
+ expect(panel.borderRightWeight).toBe(2)
+ expect(panel.borderBottomWeight).toBe(3)
+ expect(panel.borderLeftWeight).toBe(4)
+ expect(panel.independentCorners).toBe(true)
+ expect(panel.topLeftRadius).toBe(4)
+ expect(panel.topRightRadius).toBe(8)
+ expect(panel.bottomRightRadius).toBe(12)
+ expect(panel.bottomLeftRadius).toBe(16)
+
+ const roundTrip = sceneGraphToDesignDocument(graph)
+ const root = roundTrip.children[0]
+ expect(root?.type).toBe('element')
+ if (root?.type !== 'element') return
+ const roundTripPanel = root.children[0]
+ expect(roundTripPanel?.type).toBe('element')
+ if (roundTripPanel?.type !== 'element') return
+ expect(roundTripPanel.inlineStyle?.overflow).toBe('hidden')
+ expect(roundTripPanel.inlineStyle?.['min-width']).toBe('240px')
+ expect(roundTripPanel.inlineStyle?.['border-left-width']).toBe('4px')
+ expect(roundTripPanel.inlineStyle?.['border-bottom-left-radius']).toBe('16px')
+ })
+
it('maps CSS flex alignment into scene graph auto-layout alignment', () => {
const graph = designDocumentToSceneGraph({
type: 'document',