Skip to content

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

fix(dom-css): import HTML laid out as browsers lay it out (#1022)

Danila Poyarkov167a54c2ca12
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5135fa3e..53162ec6f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -158,6 +158,9 @@
- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Save HTML imported with `openpencil import` with its layout applied: layers in a flex container sit where its padding and gap place them instead of all at the top left (#788).
+- Import HTML and CSS laid out as a browser lays it out, in `openpencil import` and the app's HTML import. Block elements stack and fill their parent's width, inline elements and buttons hug their content, flex items stretch across their container by default, `flex: 1` and `width: 100%` fill, padding and borders sit outside a `width` or `height` unless `box-sizing: border-box`, `display: none` is left out, and text wraps or hugs its content instead of taking an estimated size. Before, block elements became fixed 100 × 100 frames without layout, so `openpencil import` left their children at the top left (#788).
+- Apply rules that use the universal selector, such as Tailwind's `box-sizing: border-box` base style, when HTML and Tailwind are converted headlessly, and let a `padding-inline` or `padding-block` override a less specific rule's padding.
+- Keep exported HTML at the size it has in OpenPencil when a box has padding or a border: it declares `box-sizing: border-box`, so its width includes them in HTML used without OpenPencil's standalone stylesheet.
- Size design JSX text in a frame without auto layout, such as text an AI agent or MCP client renders into a plain frame, to its content instead of 100 × 100.
- Size text in `.pen` files from its font instead of estimating its width from the number of characters; wrapping text without a width wraps at the width of its content.
- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).
diff --git a/packages/core/tests/io/formats/html/import.test.ts b/packages/core/tests/io/formats/html/import.test.ts
new file mode 100644
index 000000000..d1311ee7b
--- /dev/null
+++ b/packages/core/tests/io/formats/html/import.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, test } from 'bun:test'
+
+import { readHTMLDocument } from '@open-pencil/core/io/formats/html/import'
+
+// The layout from #788: a phone-sized column with a title, a card, and a button.
+const DEMO = `<div style="width:390px;height:844px;background:#0b0f1a;display:flex;flex-direction:column;padding:24px;gap:16px">
+ <div style="font-size:28px;font-weight:700;color:#fff">D-claro</div>
+ <div style="background:#151b2b;border-radius:16px;padding:20px;color:#fff">Saldo disponible</div>
+ <button style="background:#2563eb;border-radius:12px;padding:14px;color:#fff">Enviar dinero</button>
+</div>`
+
+describe('reading HTML', () => {
+ test('lays out block children and flex items as a browser does', async () => {
+ const { graph } = await readHTMLDocument(DEMO)
+ const node = (id: string | undefined) => {
+ const found = id === undefined ? undefined : graph.getNode(id)
+ if (!found) throw new Error(`Missing layer ${id}`)
+ return found
+ }
+ const column = node(graph.getPages()[0]?.childIds[0])
+ const [title, card, button] = column.childIds.map(node)
+
+ // Padding sits outside the 390px width, as CSS's content-box sizing puts it, and each
+ // child fills that width, one below the other 16px apart.
+ expect(column).toMatchObject({ width: 438, height: 892 })
+ expect(title).toMatchObject({ x: 24, y: 24, width: 390 })
+ expect(card).toMatchObject({ x: 24, y: title.y + title.height + 16, width: 390 })
+ expect(button).toMatchObject({ x: 24, y: card.y + card.height + 16, width: 390 })
+
+ // The card wraps its padding around the text, and the button centers its label.
+ const cardText = node(card.childIds[0])
+ expect(cardText).toMatchObject({ x: 20, y: 20 })
+ expect(card.height).toBe(cardText.height + 40)
+ const label = node(button.childIds[0])
+ expect(label.x * 2 + label.width).toBeCloseTo(390, 0)
+ })
+})
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index 370cf1f76..2e739c42d 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -258,6 +258,22 @@ function addLayoutChild(
if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`
}
+const SIZE_PROPERTIES = ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height']
+
+/**
+ * A layer's size includes its padding and stroke, as auto layout measures it. CSS sizes the
+ * content box unless told otherwise, so a sized box with padding or a border says so.
+ */
+function addBoxSizing(style: DesignStyleDeclaration): void {
+ const sized = SIZE_PROPERTIES.some((property) => Object.hasOwn(style, property))
+ const boxed = Object.keys(style).some(
+ (property) =>
+ property.startsWith('padding') ||
+ (property.startsWith('border') && !property.endsWith('radius'))
+ )
+ if (sized && boxed) style['box-sizing'] = 'border-box'
+}
+
function styleFromSceneNode(
node: SceneNode,
parent: SceneNode | undefined,
@@ -297,6 +313,7 @@ function styleFromSceneNode(
addPadding(style, node, css)
}
+ addBoxSizing(style)
return style
}
diff --git a/packages/dom-css/src/import/flow.ts b/packages/dom-css/src/import/flow.ts
new file mode 100644
index 000000000..8d1354f2e
--- /dev/null
+++ b/packages/dom-css/src/import/flow.ts
@@ -0,0 +1,244 @@
+import { pick } from 'es-toolkit'
+
+import {
+ autoLayoutSizingFields,
+ fillSizingFields,
+ layoutSizing,
+ textAutoResizeFor,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+import {
+ parseCSSAlignItems,
+ parseCSSFlexDirection,
+ parseCSSJustifyContent,
+ parseCSSNumber
+} from '@open-pencil/scene-graph/css'
+
+import type { DesignElement, DesignStyleDeclaration } from '../types'
+import { pickStyle } from './css-values'
+
+/**
+ * How CSS lays an element and its children out, mapped onto auto layout: block flow stacks
+ * children vertically and stretches block-level ones across, a flex container is a stack in its
+ * direction that stretches items across by default, and inline-level content hugs.
+ */
+export type FlowKind = 'block' | 'flex' | 'inline'
+
+/** The layout a child is placed in: its parent's flow, or none at the top of the page. */
+export type ParentFlow = FlowKind | 'none'
+
+const INLINE_TAGS = new Set([
+ 'a',
+ 'abbr',
+ 'b',
+ 'code',
+ 'em',
+ 'i',
+ 'kbd',
+ 'label',
+ 'small',
+ 'span',
+ 'strong',
+ 'sub',
+ 'sup',
+ 'u'
+])
+const INLINE_BLOCK_TAGS = new Set(['button', 'img', 'input', 'select', 'textarea'])
+/** Elements browsers center their text in by default. */
+const CENTERED_TAGS = new Set(['button'])
+
+/** What a run of text takes from its element: the properties CSS inherits, and decoration. */
+const TEXT_PROPERTIES = [
+ 'color',
+ 'font-family',
+ 'font-size',
+ 'font-style',
+ 'font-weight',
+ 'letter-spacing',
+ 'line-height',
+ 'text-align',
+ 'text-decoration-line',
+ 'text-shadow',
+ 'text-transform',
+ 'white-space'
+]
+
+/**
+ * The style a run of text directly inside an element takes from it. The element's own box,
+ * position, and opacity stay on the element, so the text is neither placed nor faded twice.
+ */
+export function inheritedTextStyle(
+ element: DesignElement,
+ style: DesignStyleDeclaration
+): DesignStyleDeclaration {
+ const inherited = pick(style, TEXT_PROPERTIES)
+ if (!inherited['text-align'] && CENTERED_TAGS.has(element.tagName.toLowerCase())) {
+ inherited['text-align'] = 'center'
+ }
+ return inherited
+}
+
+/** The element's `display`, or the one browsers give its tag by default. */
+export function elementDisplay(element: DesignElement, style: DesignStyleDeclaration): string {
+ const display = pickStyle(style, 'display')?.trim().toLowerCase()
+ if (display) return display
+ const tag = element.tagName.toLowerCase()
+ if (INLINE_TAGS.has(tag)) return 'inline'
+ return INLINE_BLOCK_TAGS.has(tag) ? 'inline-block' : 'block'
+}
+
+/**
+ * The flow an element lays its own children out in. An `inline-block` sits in a line but holds
+ * a block of its own, so only a plain `inline` element lays its children out in a line.
+ */
+export function flowOf(display: string): FlowKind {
+ if (display === 'flex' || display === 'inline-flex') return 'flex'
+ return display === 'inline' ? 'inline' : 'block'
+}
+
+/** Whether the element sits in a line rather than on its own row, so it hugs its content. */
+export function isInlineLevel(display: string): boolean {
+ return display.startsWith('inline')
+}
+
+function textAlignAxis(element: DesignElement, style: DesignStyleDeclaration) {
+ const align = pickStyle(style, 'text-align')?.trim().toLowerCase()
+ if (align === 'center') return 'CENTER'
+ if (align === 'right' || align === 'end') return 'MAX'
+ if (align) return 'MIN'
+ return CENTERED_TAGS.has(element.tagName.toLowerCase()) ? 'CENTER' : 'MIN'
+}
+
+/** The auto layout an element's own flow gives its children. */
+export function applyContainerLayout(
+ node: SceneNode,
+ element: DesignElement,
+ style: DesignStyleDeclaration,
+ flow: FlowKind
+): void {
+ if (flow === 'flex') {
+ node.layoutMode = parseCSSFlexDirection(pickStyle(style, 'flex-direction')) ?? 'HORIZONTAL'
+ node.primaryAxisAlign = parseCSSJustifyContent(pickStyle(style, 'justify-content')) ?? 'MIN'
+ // Flex items stretch across the container unless `align-items` says otherwise.
+ node.counterAxisAlign = parseCSSAlignItems(pickStyle(style, 'align-items')) ?? 'STRETCH'
+ node.layoutWrap = pickStyle(style, 'flex-wrap') === 'wrap' ? 'WRAP' : 'NO_WRAP'
+ return
+ }
+ if (flow === 'block') {
+ node.layoutMode = 'VERTICAL'
+ // Browsers center a button's content both ways.
+ if (CENTERED_TAGS.has(element.tagName.toLowerCase())) {
+ node.primaryAxisAlign = 'CENTER'
+ node.counterAxisAlign = 'CENTER'
+ }
+ return
+ }
+ // Inline content runs in a line, aligned by `text-align`.
+ node.layoutMode = 'HORIZONTAL'
+ node.primaryAxisAlign = textAlignAxis(element, style)
+ node.counterAxisAlign = 'CENTER'
+}
+
+function grows(style: DesignStyleDeclaration): boolean {
+ const grow = parseCSSNumber(pickStyle(style, 'flex-grow'))
+ if (grow !== null) return grow > 0
+ const flex = pickStyle(style, 'flex')?.trim().split(/\s+/)[0]
+ if (flex === 'auto') return true
+ const shorthand = parseCSSNumber(flex)
+ return shorthand !== null && shorthand > 0
+}
+
+function isFullSize(style: DesignStyleDeclaration, property: 'width' | 'height'): boolean {
+ return pickStyle(style, property)?.trim() === '100%'
+}
+
+interface BoxSize {
+ fixedWidth: boolean
+ fixedHeight: boolean
+}
+
+/** Fill from the parent's flow: block children across, growing items along, `100%` either way. */
+function applyParentFill(
+ graph: SceneGraph,
+ node: SceneNode,
+ style: DesignStyleDeclaration,
+ display: string,
+ parentFlow: ParentFlow,
+ { fixedWidth, fixedHeight }: BoxSize
+): void {
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ const parentLayout = parent?.layoutMode ?? 'NONE'
+ if (!parent || parentLayout === 'NONE' || node.layoutPositioning === 'ABSOLUTE') return
+ const fill = (axis: 'HORIZONTAL' | 'VERTICAL') =>
+ Object.assign(node, fillSizingFields(parentLayout, axis))
+ const mainAxis = parentLayout === 'VERTICAL' ? 'VERTICAL' : 'HORIZONTAL'
+ // A box sized to its content, as an inline-block, a flex item, or an absolute box is, has no
+ // width of its own for block children to fill; they size it instead.
+ const block = parentFlow === 'block' && !isInlineLevel(display) && !fixedWidth
+ if (block && hasDefiniteWidth(graph, parent)) fill('HORIZONTAL')
+ if (parentFlow === 'flex' && grows(style)) fill(mainAxis)
+ if (isFullSize(style, 'width')) fill('HORIZONTAL')
+ if (isFullSize(style, 'height')) fill('VERTICAL')
+ if (parentFlow === 'flex') keepFixedCrossSize(node, parent, mainAxis, { fixedWidth, fixedHeight })
+}
+
+/** An item with its own cross size keeps it in a stretching flex container, as in CSS. */
+function keepFixedCrossSize(
+ node: SceneNode,
+ parent: SceneNode,
+ mainAxis: 'HORIZONTAL' | 'VERTICAL',
+ { fixedWidth, fixedHeight }: BoxSize
+): void {
+ const crossFixed = mainAxis === 'VERTICAL' ? fixedWidth : fixedHeight
+ const inheritsStretch = node.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH'
+ if (crossFixed && inheritsStretch) node.layoutAlignSelf = 'MIN'
+}
+
+function hasDefiniteWidth(graph: SceneGraph, node: SceneNode): boolean {
+ return layoutSizing(graph, node, 'HORIZONTAL') !== 'HUG'
+}
+
+/**
+ * Text wraps where its width is fixed or fills a parent with a width of its own, and hugs its
+ * content otherwise. It is measured when the document is laid out.
+ */
+function applyTextSizing(graph: SceneGraph, node: SceneNode, size: BoxSize): void {
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
+ const fillsWidth =
+ parent !== undefined &&
+ hasDefiniteWidth(graph, parent) &&
+ layoutSizing(graph, node, 'HORIZONTAL') === 'FILL'
+ const wraps = size.fixedWidth || fillsWidth
+ node.textAutoResize = wraps ? textAutoResizeFor(false, !size.fixedHeight) : 'WIDTH_AND_HEIGHT'
+ // Wrapping text starts at its content's width.
+ if (!size.fixedWidth) node.width = 0
+ if (!size.fixedHeight) node.height = 0
+}
+
+/**
+ * How a child sizes in its parent's flow, as CSS sizes it: an explicit size is fixed, block-level
+ * children of block flow and items of a stretching flex container fill across, a growing flex
+ * item fills along, `100%` fills, and everything else hugs. Text that fills its width wraps.
+ */
+export function applyFlowSizing(
+ graph: SceneGraph,
+ node: SceneNode,
+ style: DesignStyleDeclaration,
+ display: string,
+ parentFlow: ParentFlow
+): void {
+ const size: BoxSize = {
+ fixedWidth: parseCSSNumber(pickStyle(style, 'width')) !== null,
+ fixedHeight: parseCSSNumber(pickStyle(style, 'height')) !== null
+ }
+ if (node.layoutMode !== 'NONE' && node.layoutMode !== 'GRID') {
+ const own = (fixed: boolean) => (fixed ? 'FIXED' : 'HUG')
+ Object.assign(
+ node,
+ autoLayoutSizingFields(node.layoutMode, own(size.fixedWidth), own(size.fixedHeight))
+ )
+ }
+ applyParentFill(graph, node, style, display, parentFlow, size)
+ if (node.type === 'TEXT') applyTextSizing(graph, node, size)
+}
diff --git a/packages/dom-css/src/import/scene-graph.ts b/packages/dom-css/src/import/scene-graph.ts
index cea7c57ef..61d693023 100644
--- a/packages/dom-css/src/import/scene-graph.ts
+++ b/packages/dom-css/src/import/scene-graph.ts
@@ -8,18 +8,19 @@ import {
type Stroke
} from '@open-pencil/scene-graph'
import { TRANSPARENT } from '@open-pencil/scene-graph/constants'
-import {
- parseCSSAlignItems,
- parseCSSAlignSelf,
- parseCSSFlexDirection,
- parseCSSJustifyContent,
- parseCSSNumber,
- parseCSSShadows
-} from '@open-pencil/scene-graph/css'
+import { parseCSSAlignSelf, parseCSSNumber, parseCSSShadows } from '@open-pencil/scene-graph/css'
import { computeImageHash } from '@open-pencil/scene-graph/images'
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
import { colorToFillFromCSS, colorToStrokeFromCSS, mergedStyle, pickStyle } from './css-values'
+import {
+ applyContainerLayout,
+ applyFlowSizing,
+ elementDisplay,
+ flowOf,
+ inheritedTextStyle,
+ type ParentFlow
+} from './flow'
const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'
const IMAGE_SOURCE_URL_KEY = 'image-source-url'
@@ -198,6 +199,43 @@ function applyPositioning(node: SceneNode, style: DesignStyleDeclaration): void
if (top !== null) node.y = top
}
+/**
+ * What CSS adds outside an explicit size: padding and borders, unless `box-sizing: border-box`
+ * puts them inside it as auto layout does.
+ */
+function contentBoxExtras(style: DesignStyleDeclaration): { width: number; height: number } {
+ if (pickStyle(style, 'box-sizing')?.trim() === 'border-box') return { width: 0, height: 0 }
+ // A border takes room once it has a style other than none, its CSS default, whatever its color.
+ const borderStyle = borderStyleFromCSS(style)
+ const bordered = borderStyle !== undefined && borderStyle !== 'none' && borderStyle !== 'hidden'
+ const side = (name: 'top' | 'right' | 'bottom' | 'left', axis: 'block' | 'inline') =>
+ (firstCSSNumber(style, `padding-${name}`, `padding-${axis}`, 'padding') ?? 0) +
+ (bordered ? (firstCSSNumber(style, `border-${name}-width`, 'border-width') ?? 0) : 0)
+ return {
+ width: side('left', 'inline') + side('right', 'inline'),
+ height: side('top', 'block') + side('bottom', 'block')
+ }
+}
+
+/** Explicit sizes count the padding and borders CSS places outside them. */
+function applyBoxSizing(node: SceneNode, style: DesignStyleDeclaration): void {
+ const extras = contentBoxExtras(style)
+ const width = firstCSSNumber(style, 'width')
+ const height = firstCSSNumber(style, 'height')
+ // A size `aspect-ratio` derives from the other is a content size too.
+ const ratio = aspectRatioFromCSS(pickStyle(style, 'aspect-ratio')) !== null
+ if (extras.width > 0) {
+ if (width !== null || (ratio && height !== null)) node.width += extras.width
+ if (node.minWidth !== null) node.minWidth += extras.width
+ if (node.maxWidth !== null) node.maxWidth += extras.width
+ }
+ if (extras.height > 0) {
+ if (height !== null || (ratio && width !== null)) node.height += extras.height
+ if (node.minHeight !== null) node.minHeight += extras.height
+ if (node.maxHeight !== null) node.maxHeight += extras.height
+ }
+}
+
function applyPadding(node: SceneNode, style: DesignStyleDeclaration): void {
node.paddingTop = firstCSSNumber(style, 'padding-top', 'padding-block', 'padding') ?? 0
node.paddingRight = firstCSSNumber(style, 'padding-right', 'padding-inline', 'padding') ?? 0
@@ -263,6 +301,7 @@ function applyElementStyle(
style: DesignStyleDeclaration
): void {
setNodeBox(node, style)
+ applyBoxSizing(node, style)
applyPositioning(node, style)
applyPadding(node, style)
@@ -297,15 +336,6 @@ function applyElementStyle(
const alignSelf = parseCSSAlignSelf(pickStyle(style, 'align-self')) ?? 'AUTO'
if (alignSelf !== 'AUTO') node.layoutAlignSelf = alignSelf
-
- const display = pickStyle(style, 'display')
- if (display === 'flex' || display === 'inline-flex') {
- node.layoutMode = parseCSSFlexDirection(pickStyle(style, 'flex-direction')) ?? 'HORIZONTAL'
- node.primaryAxisAlign = parseCSSJustifyContent(pickStyle(style, 'justify-content')) ?? 'MIN'
- node.counterAxisAlign = parseCSSAlignItems(pickStyle(style, 'align-items')) ?? 'MIN'
- node.layoutWrap = pickStyle(style, 'flex-wrap') === 'wrap' ? 'WRAP' : 'NO_WRAP'
- applyFlexGap(node, style)
- }
}
function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
@@ -358,15 +388,13 @@ function createTextNode(
graph: SceneGraph,
parentId: string,
text: string,
- style: DesignStyleDeclaration
+ style: DesignStyleDeclaration,
+ display: string,
+ parentFlow: ParentFlow
) {
- const node = graph.createNode('TEXT', parentId, {
- name: text.slice(0, 32) || 'Text',
- text,
- width: Math.max(text.length * 8, 1),
- height: 20
- })
+ const node = graph.createNode('TEXT', parentId, { name: text.slice(0, 32) || 'Text', text })
applyTextStyle(node, style)
+ applyFlowSizing(graph, node, style, display, parentFlow)
return node
}
@@ -413,14 +441,25 @@ function hasBoxStyle(style: DesignStyleDeclaration): boolean {
].some((property) => pickStyle(style, property) !== undefined)
}
-function createElementNode(graph: SceneGraph, parentId: string, element: DesignElement): SceneNode {
+function hasContent(element: DesignElement): boolean {
+ return element.children.some((child) => child.type !== 'text' || child.text.trim().length > 0)
+}
+
+function createElementNode(
+ graph: SceneGraph,
+ parentId: string,
+ element: DesignElement,
+ parentFlow: ParentFlow
+): SceneNode | null {
const style = mergedStyle(element)
+ const display = elementDisplay(element, style)
+ if (display === 'none') return null
if (
isTextLikeElement(element) &&
!hasBoxStyle(style) &&
element.children.every((child) => child.type === 'text')
) {
- return createTextNode(graph, parentId, textContent(element), style)
+ return createTextNode(graph, parentId, textContent(element), style, display, parentFlow)
}
const node = graph.createNode('FRAME', parentId, {
@@ -428,9 +467,16 @@ function createElementNode(graph: SceneGraph, parentId: string, element: DesignE
clipsContent: false
})
applyElementStyle(graph, node, element, style)
+ // A box without content keeps its own size, as an image does, unless it declares a layout.
+ const flow = hasContent(element) || flowOf(display) === 'flex' ? flowOf(display) : null
+ if (flow) {
+ applyContainerLayout(node, element, style, flow)
+ if (flow === 'flex') applyFlexGap(node, style)
+ }
+ applyFlowSizing(graph, node, style, display, parentFlow)
for (const child of element.children) {
- createDesignNode(graph, node.id, child, style)
+ createDesignNode(graph, node.id, child, flow ?? 'none', inheritedTextStyle(element, style))
}
return node
@@ -440,14 +486,17 @@ function createDesignNode(
graph: SceneGraph,
parentId: string,
node: DesignNode,
+ parentFlow: ParentFlow,
inheritedStyle: DesignStyleDeclaration = {}
): SceneNode | null {
if (node.type === 'text') {
if (node.text.trim().length === 0) return null
- return createTextNode(graph, parentId, node.text, inheritedStyle)
+ // Text runs in block flow and flex containers are blocks of their own, as CSS boxes them.
+ const display = parentFlow === 'inline' ? 'inline' : 'block'
+ return createTextNode(graph, parentId, node.text, inheritedStyle, display, parentFlow)
}
- return createElementNode(graph, parentId, node)
+ return createElementNode(graph, parentId, node, parentFlow)
}
function fitPageToChildren(page: SceneNode, graph: SceneGraph): void {
@@ -467,7 +516,7 @@ export function designDocumentToSceneGraph(
page.name = options.pageName ?? 'DesignDOM'
for (const child of document.children) {
- createDesignNode(graph, page.id, child)
+ createDesignNode(graph, page.id, child, 'none')
}
fitPageToChildren(page, graph)
diff --git a/packages/dom-css/src/runtime/browser.ts b/packages/dom-css/src/runtime/browser.ts
index e34ed6c25..303b3843c 100644
--- a/packages/dom-css/src/runtime/browser.ts
+++ b/packages/dom-css/src/runtime/browser.ts
@@ -35,6 +35,7 @@ const DEFAULT_COMPUTED_PROPERTIES = [
'border-top-right-radius',
'border-top-width',
'box-shadow',
+ 'box-sizing',
'color',
'column-gap',
'display',
diff --git a/packages/dom-css/src/runtime/headless-css.ts b/packages/dom-css/src/runtime/headless-css.ts
index 0bf1133b1..0bd0eb7cb 100644
--- a/packages/dom-css/src/runtime/headless-css.ts
+++ b/packages/dom-css/src/runtime/headless-css.ts
@@ -119,46 +119,74 @@ function resolveSimpleCalc(value: string): string {
return `${unit === 'rem' ? base * multiplier * 16 : base * multiplier}px`
}
+const BORDER_STYLES = new Set([
+ 'none',
+ 'hidden',
+ 'dotted',
+ 'dashed',
+ 'solid',
+ 'double',
+ 'groove',
+ 'ridge',
+ 'inset',
+ 'outset'
+])
+
+/**
+ * Shorthands as the longhands they set, in declaration order, so a later declaration wins over
+ * an earlier one whether it is a shorthand, a logical side, or a single side, as in CSS.
+ */
function expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {
- const result = { ...style }
- expandBoxShorthand(result, 'margin')
- expandBoxShorthand(result, 'padding')
- expandBorderShorthand(result)
- expandBackgroundShorthand(result)
+ const result: DesignStyleDeclaration = {}
+ for (const [property, value] of Object.entries(style)) {
+ result[property] = value
+ Object.assign(result, longhandsOf(property, value))
+ }
return result
}
-function expandBoxShorthand(style: DesignStyleDeclaration, property: 'margin' | 'padding') {
- const value = style[property]
- if (!value) return
-
- const parts = splitCSSValue(value)
- const [top, right = top, bottom = top, left = right] = parts
- if (!top || !right || !bottom || !left) return
+function longhandsOf(property: string, value: string): DesignStyleDeclaration {
+ if (property === 'margin' || property === 'padding') return boxSides(property, value)
+ const logical = /^(margin|padding)-(inline|block)$/u.exec(property)
+ if (logical) return logicalSides(property, value, logical[2] === 'inline')
+ if (property === 'border') return borderLonghands(value)
+ if (property === 'background') {
+ const color = splitCSSValue(value).find(isColor)
+ return color ? { 'background-color': color } : {}
+ }
+ return {}
+}
- style[`${property}-top`] ??= top
- style[`${property}-right`] ??= right
- style[`${property}-bottom`] ??= bottom
- style[`${property}-left`] ??= left
+function boxSides(property: string, value: string): DesignStyleDeclaration {
+ const [top, right = top, bottom = top, left = right] = splitCSSValue(value)
+ if (!top || !right || !bottom || !left) return {}
+ return {
+ [`${property}-top`]: top,
+ [`${property}-right`]: right,
+ [`${property}-bottom`]: bottom,
+ [`${property}-left`]: left
+ }
}
-function expandBorderShorthand(style: DesignStyleDeclaration) {
- const value = style.border
- if (!value) return
+/** `padding-inline` and `padding-block` as the sides they set in left-to-right, horizontal text. */
+function logicalSides(property: string, value: string, inline: boolean): DesignStyleDeclaration {
+ const box = property.slice(0, property.lastIndexOf('-'))
+ const [first, second = first] = splitCSSValue(value)
+ if (!first || !second) return {}
+ const [start, end] = inline ? ['left', 'right'] : ['top', 'bottom']
+ return { [`${box}-${start}`]: first, [`${box}-${end}`]: second }
+}
+function borderLonghands(value: string): DesignStyleDeclaration {
const parts = splitCSSValue(value)
+ const longhands: DesignStyleDeclaration = {}
const color = parts.find(isColor)
const width = parts.find((part) => parseCSSNumber(part) !== null)
- if (color) style['border-color'] ??= color
- if (width) style['border-width'] ??= width
-}
-
-function expandBackgroundShorthand(style: DesignStyleDeclaration) {
- const value = style.background
- if (!value || style['background-color']) return
-
- const color = splitCSSValue(value).find(isColor)
- if (color) style['background-color'] = color
+ const style = parts.find((part) => BORDER_STYLES.has(part.toLowerCase()))
+ if (color) longhands['border-color'] = color
+ if (width) longhands['border-width'] = width
+ if (style) longhands['border-style'] = style.toLowerCase()
+ return longhands
}
/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */
@@ -178,9 +206,8 @@ function elementId(element: DesignElement): string | undefined {
function selectorSpecificity(selector: string): number {
const idCount = selector.match(/#[\w-]+/g)?.length ?? 0
const classCount = selector.match(/\.[\w-]+/g)?.length ?? 0
- const tagCount = selector
- .split(/[\s>]+/)
- .filter((part) => part && !part.startsWith('.') && !part.startsWith('#')).length
+ // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.
+ const tagCount = selector.split(/[\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length
return idCount * 100 + classCount * 10 + tagCount
}
@@ -195,7 +222,8 @@ function matchesSimpleSelector(element: DesignElement, selector: string): boolea
if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false
const tag = selector.replace(/#[\w-]+/g, '').replace(/\.[\w-]+/g, '')
- return tag.length === 0 || element.tagName.toLowerCase() === tag.toLowerCase()
+ // The universal selector, as Tailwind's preflight uses for `box-sizing`, matches any element.
+ return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()
}
function matchesSelector(
diff --git a/packages/dom-css/tests/import/conversion.test.ts b/packages/dom-css/tests/import/conversion.test.ts
index 1ca4148b0..c6c0a32ad 100644
--- a/packages/dom-css/tests/import/conversion.test.ts
+++ b/packages/dom-css/tests/import/conversion.test.ts
@@ -191,8 +191,9 @@ describe('@open-pencil/dom-css conversion', () => {
expect(card?.type).toBe('FRAME')
if (card?.type !== 'FRAME') return
- expect(card.width).toBe(320)
- expect(card.height).toBe(180)
+ // CSS sizes the content box: padding and borders come on top.
+ expect(card.width).toBe(320 + 2 * 24 + 2 * 1)
+ expect(card.height).toBe(180 + 2 * 24 + 2 * 1)
expect(card.layoutMode).toBe('VERTICAL')
expect(card.itemSpacing).toBe(12)
expect(card.paddingLeft).toBe(24)
@@ -221,8 +222,8 @@ describe('@open-pencil/dom-css conversion', () => {
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.width).toBe(280 + 2 * 20)
+ expect(card.height).toBe(140 + 2 * 20)
expect(card.itemSpacing).toBe(10)
expect(card.paddingLeft).toBe(20)
expect(graph.getChildren(page.id)).toHaveLength(1)
@@ -243,7 +244,7 @@ describe('@open-pencil/dom-css conversion', () => {
expect(input?.type).toBe('FRAME')
if (navbar?.type !== 'FRAME' || input?.type !== 'FRAME') return
expect(navbar.primaryAxisAlign).toBe('SPACE_BETWEEN')
- expect(input.width).toBe(312)
+ expect(input.width).toBe(312 + 2 * 12 + 2 * 1)
expect(input.paddingLeft).toBe(12)
const badge = graph.getChildren(navbar.id)[1]
diff --git a/packages/dom-css/tests/import/flow.test.ts b/packages/dom-css/tests/import/flow.test.ts
new file mode 100644
index 000000000..47babe334
--- /dev/null
+++ b/packages/dom-css/tests/import/flow.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'bun:test'
+
+import { createHeadlessCSSRuntime, htmlToSceneGraph } from '#dom-css/index'
+
+import { layoutSizing, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+
+async function importHTML(html: string) {
+ const graph = await htmlToSceneGraph(html, { runtime: createHeadlessCSSRuntime() })
+ const byName = (name: string): SceneNode => {
+ const node = [...graph.getAllNodes()].find((candidate) => candidate.name === name)
+ if (!node) throw new Error(`Missing ${name}`)
+ return node
+ }
+ const sizing = (node: SceneNode) => [
+ layoutSizing(graph, node, 'HORIZONTAL'),
+ layoutSizing(graph, node, 'VERTICAL')
+ ]
+ return { graph, byName, sizing }
+}
+
+function textIn(graph: SceneGraph, parent: SceneNode): SceneNode {
+ const text = graph.getChildren(parent.id).find((child) => child.type === 'TEXT')
+ if (!text) throw new Error(`No text in ${parent.name}`)
+ return text
+}
+
+describe('HTML flow as auto layout', () => {
+ it('stacks block flow vertically and stretches block children across', async () => {
+ const { graph, byName, sizing } = await importHTML(
+ `<div id="page" style="width:390px"><div id="card" style="padding:20px">Saldo</div></div>`
+ )
+ expect(byName('page').layoutMode).toBe('VERTICAL')
+ const card = byName('card')
+ expect(card.layoutMode).toBe('VERTICAL')
+ expect(card.paddingTop).toBe(20)
+ expect(sizing(card)).toEqual(['FILL', 'HUG'])
+ // Text in a block wraps at the block's width.
+ expect(textIn(graph, card).textAutoResize).toBe('HEIGHT')
+ })
+
+ it('hugs inline-level content and centers a button label', async () => {
+ const { graph, byName, sizing } = await importHTML(
+ `<div><button id="send" style="padding:14px">Enviar</button><span id="tag" style="padding:4px">New</span></div>`
+ )
+ const send = byName('send')
+ expect(send).toMatchObject({ primaryAxisAlign: 'CENTER', counterAxisAlign: 'CENTER' })
+ expect(sizing(send)).toEqual(['HUG', 'HUG'])
+ const tag = byName('tag')
+ expect(tag.layoutMode).toBe('HORIZONTAL')
+ expect(sizing(tag)).toEqual(['HUG', 'HUG'])
+ expect(textIn(graph, send).textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ })
+
+ it('stacks block children inside an inline-block, which sits in a line itself', async () => {
+ const { byName, sizing } = await importHTML(
+ `<div style="width:300px"><div id="chip" style="display:inline-block"><div>Title</div><div>Detail</div></div></div>`
+ )
+ const chip = byName('chip')
+ expect(chip.layoutMode).toBe('VERTICAL')
+ expect(sizing(chip)).toEqual(['HUG', 'HUG'])
+ })
+
+ it('adds padding to a size derived from aspect-ratio', async () => {
+ const { byName } = await importHTML(
+ `<div id="square" style="width:100px;aspect-ratio:1;padding:10px"></div>`
+ )
+ expect(byName('square')).toMatchObject({ width: 120, height: 120 })
+ })
+
+ it('stretches flex items across unless they set their own cross size', async () => {
+ const { byName, sizing } = await importHTML(
+ `<div id="column" style="display:flex;flex-direction:column;width:300px">
+ <div id="stretched" style="padding:8px">A</div>
+ <div id="narrow" style="width:120px;height:20px"></div>
+ <div id="grown" style="flex:1">B</div>
+ </div>`
+ )
+ expect(byName('column').counterAxisAlign).toBe('STRETCH')
+ expect(sizing(byName('stretched'))).toEqual(['FILL', 'HUG'])
+ expect(sizing(byName('narrow'))).toEqual(['FIXED', 'FIXED'])
+ expect(sizing(byName('grown'))[1]).toBe('FILL')
+ })
+
+ it('places padding and borders outside an explicit size unless border-box', async () => {
+ const { byName } = await importHTML(
+ `<div id="content" style="width:100px;height:50px;padding:10px;border:2px solid #000">A</div>
+ <div id="border" style="width:100px;padding:10px;box-sizing:border-box">B</div>`
+ )
+ expect(byName('content')).toMatchObject({ width: 124, height: 74 })
+ expect(byName('border').width).toBe(100)
+ })
+
+ it('gives a border room by its style, also in the default current color', async () => {
+ const { byName } = await importHTML(
+ `<div id="styled" style="width:100px;border:2px solid">A</div>
+ <div id="unstyled" style="width:100px;border-width:2px">B</div>`
+ )
+ expect(byName('styled').width).toBe(104)
+ // A border without a style is none, so it takes no room.
+ expect(byName('unstyled').width).toBe(100)
+ })
+
+ it('hugs text in a stretching row and in boxes sized to their content', async () => {
+ const { graph, byName, sizing } = await importHTML(
+ `<nav style="display:flex;width:400px"><div id="links" style="display:flex;gap:8px"><a>Docs</a></div></nav>
+ <div style="position:relative;width:200px"><div id="badge" style="position:absolute;padding:2px 8px">Popular</div></div>`
+ )
+ // A row stretches its items across, which is no reason for text to stop sizing itself.
+ expect(textIn(graph, byName('links')).textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ // An absolute box sizes to its content, so its text hugs rather than filling it.
+ const badge = byName('badge')
+ expect(sizing(badge)).toEqual(['HUG', 'HUG'])
+ expect(textIn(graph, badge).textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ })
+
+ it('gives text only what CSS inherits, centering it in a button', async () => {
+ const { graph, byName } = await importHTML(
+ `<div style="position:relative;width:200px"><div id="badge" style="position:absolute;left:120px;top:8px;opacity:0.5;color:#ff0000">Popular</div></div>
+ <button id="send" style="width:200px">Send</button>`
+ )
+ const text = textIn(graph, byName('badge'))
+ // The badge's position and opacity are its own; its color is the text's.
+ expect(text).toMatchObject({ layoutPositioning: 'AUTO', x: 0, y: 0, opacity: 1 })
+ expect(text.fills[0]?.type).toBe('SOLID')
+ expect(textIn(graph, byName('send')).textAlignHorizontal).toBe('CENTER')
+ })
+
+ it('fills a 100% width and leaves out display: none', async () => {
+ const { graph, byName, sizing } = await importHTML(
+ `<div style="display:flex"><div id="wide" style="width:100%">A</div><div id="hidden" style="display:none">B</div></div>`
+ )
+ expect(sizing(byName('wide'))[0]).toBe('FILL')
+ expect([...graph.getAllNodes()].some((node) => node.name === 'hidden')).toBe(false)
+ })
+})
diff --git a/packages/dom-css/tests/import/jsx.test.tsx b/packages/dom-css/tests/import/jsx.test.tsx
index 8bc7a18f0..37ed9920a 100644
--- a/packages/dom-css/tests/import/jsx.test.tsx
+++ b/packages/dom-css/tests/import/jsx.test.tsx
@@ -65,8 +65,9 @@ describe('@open-pencil/dom-css JSX', () => {
expect(card?.type).toBe('FRAME')
if (card?.type !== 'FRAME') return
- expect(card.width).toBe(320)
- expect(card.height).toBe(160)
+ // CSS sizes the content box, so padding comes on top.
+ expect(card.width).toBe(320 + 2 * 24)
+ expect(card.height).toBe(160 + 2 * 24)
expect(card.layoutMode).toBe('VERTICAL')
expect(card.paddingLeft).toBe(24)
diff --git a/packages/dom-css/tests/runtime.test.ts b/packages/dom-css/tests/runtime.test.ts
index 76794fac5..3650cb4e7 100644
--- a/packages/dom-css/tests/runtime.test.ts
+++ b/packages/dom-css/tests/runtime.test.ts
@@ -110,6 +110,46 @@ describe('@open-pencil/dom-css runtime', () => {
expect(section.inlineStyle?.width).toBe('320px')
})
+ it('applies the universal selector below any tag or class', async () => {
+ const runtime = createHeadlessCSSRuntime()
+ const parsed = runtime.parseHTML('<div class="card"><p>Text</p></div>')
+ const document = await runtime.computeStyles(
+ parsed,
+ `*, ::before, ::after { box-sizing: border-box; margin: 0; }
+ p { margin: 4px; }`
+ )
+ const card = document.children[0]
+ expect(card?.type).toBe('element')
+ if (card?.type !== 'element') return
+ expect(card.computedStyle?.['box-sizing']).toBe('border-box')
+ const text = card.children.find((child) => child.type === 'element')
+ expect(text?.type === 'element' ? text.computedStyle?.margin : undefined).toBe('4px')
+ })
+
+ it('lets the later declaration of a side win, whether it is logical or physical', async () => {
+ const runtime = createHeadlessCSSRuntime()
+ const parsed = runtime.parseHTML('<div class="a">A</div><div class="b">B</div>')
+ const document = await runtime.computeStyles(
+ parsed,
+ `.a { padding-left: 4px; padding-inline: 12px; }
+ .b { padding: 8px; padding-left: 2px; }`
+ )
+ const [a, b] = document.children
+ expect(a?.type === 'element' ? a.computedStyle?.['padding-left'] : undefined).toBe('12px')
+ expect(b?.type === 'element' ? b.computedStyle?.['padding-left'] : undefined).toBe('2px')
+ })
+
+ it('scores *.card like .card, so the later rule wins', async () => {
+ const runtime = createHeadlessCSSRuntime()
+ const parsed = runtime.parseHTML('<div class="card">A</div>')
+ const document = await runtime.computeStyles(
+ parsed,
+ '*.card { color: #0000ff; } .card { color: #ff0000; }'
+ )
+ const card = document.children[0]
+ expect(card?.type === 'element' ? card.computedStyle?.color : undefined).toBe('#ff0000')
+ })
+
it('computes selector specificity, inheritance, and shorthands', async () => {
const runtime = createHeadlessCSSRuntime()
const parsed = runtime.parseHTML(`
diff --git a/tests/e2e/dom-css/browser-runtime.spec.ts b/tests/e2e/dom-css/browser-runtime.spec.ts
index 7324ae2b6..b5019ecae 100644
--- a/tests/e2e/dom-css/browser-runtime.spec.ts
+++ b/tests/e2e/dom-css/browser-runtime.spec.ts
@@ -485,8 +485,9 @@ test.describe('@open-pencil/dom-css browser CSS runtime oracle', () => {
)
expect(card?.type).toBe('FRAME')
- expect(card?.width).toBe(320)
- expect(card?.height).toBe(176)
+ // The box the browser draws: padding outside the content-box width and height.
+ expect(card?.width).toBe(320 + 2 * 24)
+ expect(card?.height).toBe(176 + 2 * 24)
expect(card?.layoutMode).toBe('VERTICAL')
expect(card?.itemSpacing).toBe(12)
expect(card?.paddingLeft).toBe(24)
@@ -507,8 +508,8 @@ test.describe('@open-pencil/dom-css browser CSS runtime oracle', () => {
)
expect(card?.type).toBe('FRAME')
- expect(card?.width).toBe(300)
- expect(card?.height).toBe(160)
+ expect(card?.width).toBe(300 + 2 * 22)
+ expect(card?.height).toBe(160 + 2 * 22)
expect(card?.layoutMode).toBe('VERTICAL')
expect(card?.itemSpacing).toBe(14)
expect(card?.paddingLeft).toBe(22)
diff --git a/tests/engine/dom-css/conversion.test.ts b/tests/engine/dom-css/conversion.test.ts
index 27d054ae5..28351ec43 100644
--- a/tests/engine/dom-css/conversion.test.ts
+++ b/tests/engine/dom-css/conversion.test.ts
@@ -165,7 +165,7 @@ describe('@open-pencil/dom-css conversion', () => {
const card = page ? graph.getChildren(page.id)[0] : undefined
expect(card?.type).toBe('FRAME')
- expect(card?.width).toBe(320)
+ expect(card?.width).toBe(320 + 2 * 24 + 2 * 1)
expect(card?.layoutMode).toBe('VERTICAL')
})
@@ -180,6 +180,7 @@ describe('@open-pencil/dom-css conversion', () => {
const card = page ? graph.getChildren(page.id)[0] : undefined
expect(card?.type).toBe('FRAME')
+ // Tailwind's preflight makes every box border-box, so padding stays inside.
expect(card?.width).toBe(320)
expect(card?.height).toBe(176)
expect(card?.itemSpacing).toBe(12)
@@ -192,8 +193,8 @@ describe('@open-pencil/dom-css conversion', () => {
const card = page ? graph.getChildren(page.id)[0] : undefined
expect(card?.type).toBe('FRAME')
- expect(card?.width).toBe(320)
- expect(card?.height).toBe(160)
+ expect(card?.width).toBe(320 + 2 * 24)
+ expect(card?.height).toBe(160 + 2 * 24)
expect(card?.layoutMode).toBe('VERTICAL')
expect(card?.itemSpacing).toBe(12)
expect(card?.paddingTop).toBe(24)
@@ -216,8 +217,8 @@ describe('@open-pencil/dom-css conversion', () => {
expect(card?.type).toBe('FRAME')
if (card?.type !== 'FRAME') return
- expect(card.width).toBe(320)
- expect(card.height).toBe(180)
+ expect(card.width).toBe(320 + 2 * 24 + 2 * 1)
+ expect(card.height).toBe(180 + 2 * 24 + 2 * 1)
expect(card.layoutMode).toBe('VERTICAL')
expect(card.itemSpacing).toBe(12)
expect(card.paddingLeft).toBe(24)
@@ -297,10 +298,8 @@ describe('@open-pencil/dom-css conversion', () => {
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)
+ // Without a border style, CSS's default none, the borders take no room.
+ expect(panel).toMatchObject({ minWidth: 240, maxWidth: 480, minHeight: 120, maxHeight: 320 })
expect(panel.clipsContent).toBe(true)
expect(panel.independentStrokeWeights).toBe(true)
expect(panel.borderTopWeight).toBe(1)
@@ -321,7 +320,10 @@ describe('@open-pencil/dom-css conversion', () => {
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).toMatchObject({
+ 'min-width': '240px',
+ 'box-sizing': 'border-box'
+ })
expect(roundTripPanel.inlineStyle?.['border-top-width']).toBe('1px')
expect(roundTripPanel.inlineStyle?.['border-left-width']).toBe('4px')
expect(roundTripPanel.inlineStyle?.['border-bottom-left-radius']).toBe('16px')
@@ -465,7 +467,7 @@ describe('@open-pencil/dom-css conversion', () => {
})
const page = graph.getPages()[0]
const shell = expectFrame(page ? graph.getChildren(page.id)[0] : undefined)
- expect(shell.width).toBe(480)
+ expect(shell.width).toBe(480 + 2 * 32)
expect(shell.layoutMode).toBe('VERTICAL')
expect(shell.itemSpacing).toBe(24)
expect(shell.paddingLeft).toBe(32)
@@ -486,9 +488,9 @@ describe('@open-pencil/dom-css conversion', () => {
expect(badge.cornerRadius).toBe(9999)
expect(graph.getChildren(badge.id)[0]?.type).toBe('TEXT')
- expect(dialog.width).toBe(360)
- expect(dialog.minWidth).toBe(320)
- expect(dialog.maxWidth).toBe(420)
+ expect(dialog.width).toBe(360 + 2 * 24 + 2 * 1)
+ expect(dialog.minWidth).toBe(320 + 2 * 24 + 2 * 1)
+ expect(dialog.maxWidth).toBe(420 + 2 * 24 + 2 * 1)
expect(dialog.itemSpacing).toBe(16)
expect(dialog.effects[0]?.type).toBe('DROP_SHADOW')
expect(dialog.effects[0]?.radius).toBe(40)
@@ -496,8 +498,8 @@ describe('@open-pencil/dom-css conversion', () => {
const [, , inputNode, buttonNode] = graph.getChildren(dialog.id)
const input = expectFrame(inputNode)
const button = expectFrame(buttonNode)
- expect(input.width).toBe(312)
- expect(input.height).toBe(40)
+ expect(input.width).toBe(312 + 2 * 12 + 2 * 1)
+ expect(input.height).toBe(40 + 2 * 1)
expect(input.cornerRadius).toBe(8)
expect(button.layoutMode).toBe('HORIZONTAL')
expect(button.primaryAxisAlign).toBe('CENTER')
@@ -584,7 +586,7 @@ describe('@open-pencil/dom-css conversion', () => {
if (card?.type !== 'element') return
expect(card.tagName).toBe('div')
- expect(card.inlineStyle?.width).toBe('320px')
+ expect(card.inlineStyle).toMatchObject({ width: '368px', 'box-sizing': 'border-box' })
expect(card.inlineStyle?.display).toBe('flex')
expect(card.inlineStyle?.['flex-direction']).toBe('column')
expect(card.attrs['data-open-pencil-node-id']).toBeTruthy()
diff --git a/tests/engine/dom-css/jsx.test.ts b/tests/engine/dom-css/jsx.test.ts
index 0eeae09ed..5f3c7488d 100644
--- a/tests/engine/dom-css/jsx.test.ts
+++ b/tests/engine/dom-css/jsx.test.ts
@@ -47,8 +47,9 @@ describe('@open-pencil/dom-css JSX authoring', () => {
const card = page ? graph.getChildren(page.id)[0] : undefined
expect(card?.type).toBe('FRAME')
- expect(card?.width).toBe(320)
- expect(card?.height).toBe(160)
+ // CSS sizes the content box, so padding comes on top.
+ expect(card?.width).toBe(320 + 2 * 24)
+ expect(card?.height).toBe(160 + 2 * 24)
expect(card?.paddingLeft).toBe(24)
})