AI-native design editor. Open-source Figma alternative.
feat(dom-css): round-trip CSS cards
Danila Poyarkov8fd4cbc10515
diff --git a/packages/dom-css/README.md b/packages/dom-css/README.mdindex a11be534a..7bc00b966 100644--- a/packages/dom-css/README.md+++ b/packages/dom-css/README.md@@ -8,7 +8,7 @@ Current scope:- DOM-shaped `DesignDocument` / `DesignElement` types- Browser-backed runtime adapter for native HTML parsing, serialization, and computed-style extraction-- Headless runtime adapter with `parse5` HTML parsing and CSSOM-backed style computation for basic selectors+- Headless runtime adapter with `parse5` HTML parsing and CSSOM-backed style computation for basic selectors, cascade order, inheritance, and common shorthands- Initial SceneGraph ⇄ DesignDOM conversion helpers for simple HTML/CSS-shaped layoutsPlanned scope:diff --git a/packages/dom-css/src/css-values.ts b/packages/dom-css/src/css-values.tsindex 816b99082..50d51a96a 100644--- a/packages/dom-css/src/css-values.ts+++ b/packages/dom-css/src/css-values.ts@@ -1,5 +1,5 @@import { colorToCSS, parseColor } from '@open-pencil/core/color'-import type { Fill, SceneNode } from '@open-pencil/core/scene-graph'+import type { Effect, Fill, SceneNode, Stroke } from '@open-pencil/core/scene-graph'import type { Color } from '@open-pencil/core/types'import type { DesignStyleDeclaration } from './types'@@ -32,6 +32,56 @@ export function colorToFillFromCSS(value: string | undefined): Fill[] {return [{ type: 'SOLID', color, opacity: color.a, visible: true }]}+export function strokeToCSS(stroke: Stroke | undefined): string | undefined {+ if (!stroke?.visible) return undefined+ return `${stroke.weight}px solid ${colorToCSS({ ...stroke.color, a: stroke.opacity })}`+}++export function colorToStrokeFromCSS(+ colorValue: string | undefined,+ weightValue: string | undefined+): Stroke[] {+ const color = parseCSSColor(colorValue)+ const weight = parseCSSNumber(weightValue)+ if (!color || weight === null || weight <= 0) return []+ return [{ color, weight, opacity: color.a, visible: true, align: 'INSIDE' }]+}++export function dropShadowToCSS(effect: Effect | undefined): string | undefined {+ if (effect?.type !== 'DROP_SHADOW' || !effect.visible) return undefined+ return `${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${colorToCSS({ ...effect.color, a: effect.color.a })}`+}++export function dropShadowFromCSS(value: string | undefined): Effect[] {+ if (!value || value.trim() === 'none') return []++ const colorMatch = value.match(+ /(?:rgba?|hsla?)\([^)]*\)|#[\da-fA-F]{3,8}|\b(?:black|white|red|green|blue)\b/+ )+ const color = parseCSSColor(colorMatch?.[0])+ if (!color) return []++ const numericPart = colorMatch ? value.replace(colorMatch[0], '') : value+ const numbers = numericPart+ .trim()+ .split(/\s+/)+ .map(parseCSSNumber)+ .filter((number): number is number => number !== null)+ const [offsetX = 0, offsetY = 0, radius = 0, spread = 0] = numbers++ return [+ {+ type: 'DROP_SHADOW',+ color,+ offset: { x: offsetX, y: offsetY },+ radius,+ spread,+ visible: true,+ blendMode: 'NORMAL'+ }+ ]+}+export function pickStyle(elementStyle: DesignStyleDeclaration | undefined, property: string) {return elementStyle?.[property]}diff --git a/packages/dom-css/src/from-scene-graph.ts b/packages/dom-css/src/from-scene-graph.tsindex dda83673d..62ea023a1 100644--- a/packages/dom-css/src/from-scene-graph.ts+++ b/packages/dom-css/src/from-scene-graph.ts@@ -2,7 +2,7 @@ import { colorToCSS } from '@open-pencil/core/color'import { BLACK } from '@open-pencil/core/constants'import type { SceneGraph, SceneNode } from '@open-pencil/core/scene-graph'-import { fillToCSS, sceneNodeSizeStyle } from './css-values'+import { dropShadowToCSS, fillToCSS, sceneNodeSizeStyle, strokeToCSS } from './css-values'import type { DesignDocument, DesignNode, DesignStyleDeclaration } from './types'export interface SceneGraphToDesignOptions {@@ -20,6 +20,10 @@ function styleFromSceneNode(node: SceneNode): DesignStyleDeclaration {const style = sceneNodeSizeStyle(node)const fill = fillToCSS(node.fills[0])if (fill) style['background-color'] = fill+ const stroke = strokeToCSS(node.strokes[0])+ if (stroke) style.border = stroke+ const shadow = dropShadowToCSS(node.effects[0])+ if (shadow) style['box-shadow'] = shadowif (node.opacity < 1) style.opacity = String(node.opacity)if (node.cornerRadius > 0) style['border-radius'] = `${node.cornerRadius}px`diff --git a/packages/dom-css/src/headless-css.ts b/packages/dom-css/src/headless-css.tsindex a24844dce..1bb37b302 100644--- a/packages/dom-css/src/headless-css.ts+++ b/packages/dom-css/src/headless-css.ts@@ -3,17 +3,32 @@ import { parse, type CSSStyleDeclarationLike, type CSSStyleRuleLike } from '@aceimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from './types'interface HeadlessCSSRule {- selectors: string[]+ selector: string+ specificity: number+ order: numberstyle: DesignStyleDeclaration}+interface AncestorContext {+ element: DesignElement+ parent: AncestorContext | null+}++const INHERITED_PROPERTIES = new Set([+ 'color',+ 'font-family',+ 'font-size',+ 'font-weight',+ 'line-height'+])+function styleToRecord(style: CSSStyleDeclarationLike): DesignStyleDeclaration {const result: DesignStyleDeclaration = {}for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {const value = style.getPropertyValue(property)if (property && value) result[property] = value}- return result+ return expandStyleShorthands(result)}function isStyleRule(rule: unknown): rule is CSSStyleRuleLike {@@ -27,14 +42,79 @@ function isStyleRule(rule: unknown): rule is CSSStyleRuleLike {}function parseRules(cssText: string): HeadlessCSSRule[] {+ let order = 0const sheet = parse(cssText)- return sheet.cssRules.filter(isStyleRule).map((rule) => ({- selectors: rule.selectorText+ return sheet.cssRules.filter(isStyleRule).flatMap((rule) => {+ const style = styleToRecord(rule.style)+ return rule.selectorText.split(',').map((selector) => selector.trim())- .filter((selector) => selector.length > 0),- style: styleToRecord(rule.style)- }))+ .filter((selector) => selector.length > 0)+ .map((selector) => ({+ selector,+ specificity: selectorSpecificity(selector),+ order: order++,+ style+ }))+ })+}++function expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {+ const result = { ...style }+ expandBoxShorthand(result, 'margin')+ expandBoxShorthand(result, 'padding')+ expandBorderShorthand(result)+ expandBackgroundShorthand(result)+ return result+}++function expandBoxShorthand(style: DesignStyleDeclaration, property: 'margin' | 'padding') {+ const value = style[property]+ if (!value) return++ const parts = splitWhitespace(value)+ const [top, right = top, bottom = top, left = right] = parts+ if (!top || !right || !bottom || !left) return++ style[`${property}-top`] ??= top+ style[`${property}-right`] ??= right+ style[`${property}-bottom`] ??= bottom+ style[`${property}-left`] ??= left+}++function expandBorderShorthand(style: DesignStyleDeclaration) {+ const value = style.border+ if (!value) return++ const parts = splitWhitespace(value)+ const color = parts.find(isLikelyColor)+ const width = parts.find((part) => /^\d/.test(part))+ 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 = splitWhitespace(value).find(isLikelyColor)+ if (color) style['background-color'] = color+}++function splitWhitespace(value: string): string[] {+ return value+ .trim()+ .split(/\s+/)+ .filter((part) => part.length > 0)+}++function isLikelyColor(value: string): boolean {+ return (+ value.startsWith('#') ||+ value.startsWith('rgb') ||+ value.startsWith('hsl') ||+ ['black', 'white', 'transparent', 'red', 'green', 'blue'].includes(value.toLowerCase())+ )}function classList(element: DesignElement): Set<string> {@@ -42,31 +122,118 @@ function classList(element: DesignElement): Set<string> {return new Set(className.split(/\s+/).filter((name) => name.length > 0))}+function elementId(element: DesignElement): string | undefined {+ return 'id' in element.attrs ? element.attrs.id : 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+ return idCount * 100 + classCount * 10 + tagCount+}+function matchesSimpleSelector(element: DesignElement, selector: string): boolean {- if (selector.includes(' ') || selector.includes('>') || selector.includes(':')) return false- if (selector.startsWith('.')) return classList(element).has(selector.slice(1))- if (selector.startsWith('#')) return element.attrs.id === selector.slice(1)- return element.tagName.toLowerCase() === selector.toLowerCase()+ if (selector.includes(':') || selector.includes('[')) return false++ const idMatch = selector.match(/#([\w-]+)/)+ if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false++ const classes = selector.match(/\.[\w-]+/g) ?? []+ const elementClasses = classList(element)+ 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()}-function matchesRule(element: DesignElement, rule: HeadlessCSSRule): boolean {- return rule.selectors.some((selector) => matchesSimpleSelector(element, selector))+function matchesSelector(+ element: DesignElement,+ selector: string,+ parent: AncestorContext | null+): boolean {+ const childParts = selector.split('>').map((part) => part.trim())+ if (childParts.length > 1) return matchesChildSelector(element, childParts, parent)++ const descendantParts = selector.split(/\s+/).filter((part) => part.length > 0)+ if (descendantParts.length > 1) return matchesDescendantSelector(element, descendantParts, parent)++ return matchesSimpleSelector(element, selector)}-function applyComputedStyles(node: DesignNode, rules: HeadlessCSSRule[]): DesignNode {- if (node.type === 'text') return node+function matchesSelectorParts(+ element: DesignElement,+ parts: string[],+ parent: AncestorContext | null,+ directParentOnly: boolean+): boolean {+ const current = parts.at(-1)+ if (!current || !matchesSimpleSelector(element, current)) return false- const computedStyle: DesignStyleDeclaration = {}- for (const rule of rules) {- if (matchesRule(node, rule)) Object.assign(computedStyle, rule.style)+ let ancestor = parent+ for (const selector of parts.slice(0, -1).reverse()) {+ if (!directParentOnly) {+ while (ancestor && !matchesSimpleSelector(ancestor.element, selector)) {+ ancestor = ancestor.parent+ }+ }+ if (!ancestor || !matchesSimpleSelector(ancestor.element, selector)) return false+ ancestor = ancestor.parent}- Object.assign(computedStyle, node.inlineStyle)+ return true+}+function matchesChildSelector(+ element: DesignElement,+ parts: string[],+ parent: AncestorContext | null+): boolean {+ return matchesSelectorParts(element, parts, parent, true)+}++function matchesDescendantSelector(+ element: DesignElement,+ parts: string[],+ parent: AncestorContext | null+): boolean {+ return matchesSelectorParts(element, parts, parent, false)+}++function applyComputedStyles(+ node: DesignNode,+ rules: HeadlessCSSRule[],+ parent: AncestorContext | null,+ inheritedStyle: DesignStyleDeclaration+): DesignNode {+ if (node.type === 'text') return node++ const computedStyle: DesignStyleDeclaration = pickInheritedStyle(inheritedStyle)+ const matchingRules = rules+ .filter((rule) => matchesSelector(node, rule.selector, parent))+ .sort((left, right) => left.specificity - right.specificity || left.order - right.order)++ for (const rule of matchingRules) Object.assign(computedStyle, rule.style)+ Object.assign(computedStyle, expandStyleShorthands(node.inlineStyle ?? {}))++ const context = { element: node, parent }return {...node,computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,- children: node.children.map((child) => applyComputedStyles(child, rules))+ children: node.children.map((child) =>+ applyComputedStyles(child, rules, context, computedStyle)+ )+ }+}++function pickInheritedStyle(style: DesignStyleDeclaration): DesignStyleDeclaration {+ const inherited: DesignStyleDeclaration = {}+ for (const property of INHERITED_PROPERTIES) {+ const value = style[property]+ if (value) inherited[property] = value}+ return inherited}export function computeHeadlessStyles(document: DesignDocument, cssText = ''): DesignDocument {@@ -77,6 +244,6 @@ export function computeHeadlessStyles(document: DesignDocument, cssText = ''): Dreturn {...document,- children: document.children.map((child) => applyComputedStyles(child, rules))+ children: document.children.map((child) => applyComputedStyles(child, rules, null, {}))}}diff --git a/packages/dom-css/src/runtime/headless.ts b/packages/dom-css/src/runtime/headless.tsindex efbc94f09..1bb2937b7 100644--- a/packages/dom-css/src/runtime/headless.ts+++ b/packages/dom-css/src/runtime/headless.ts@@ -19,7 +19,7 @@ function isTextNode(function childToDesignNode(node: DefaultTreeAdapterTypes.ChildNode): DesignNode | null {if (isTextNode(node)) {- return node.value.length > 0 ? { type: 'text', text: node.value } : null+ return node.value.trim().length > 0 ? { type: 'text', text: node.value } : null}if (!('tagName' in node)) return nulldiff --git a/packages/dom-css/src/serialize.ts b/packages/dom-css/src/serialize.tsindex f9dea2755..ce41ccead 100644--- a/packages/dom-css/src/serialize.ts+++ b/packages/dom-css/src/serialize.ts@@ -29,8 +29,17 @@ function serializeText(node: DesignText): string {return escapeText(node.text)}+function serializeStyle(node: DesignElement): string | undefined {+ if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return undefined+ return Object.entries(node.inlineStyle)+ .filter(([, value]) => value !== '')+ .map(([property, value]) => `${property}: ${value}`)+ .join('; ')+}+function serializeAttrs(node: DesignElement): string {- const attrs = Object.entries(node.attrs)+ const style = serializeStyle(node)+ const attrs = Object.entries({ ...node.attrs, ...(style ? { style } : {}) }).filter(([, value]) => value !== '').map(([name, value]) => `${name}="${escapeAttr(value)}"`)diff --git a/packages/dom-css/src/to-scene-graph.ts b/packages/dom-css/src/to-scene-graph.tsindex 96a6cac8f..fe2b80a33 100644--- a/packages/dom-css/src/to-scene-graph.ts+++ b/packages/dom-css/src/to-scene-graph.ts@@ -1,6 +1,13 @@import { SceneGraph, type Fill, type SceneNode } from '@open-pencil/core/scene-graph'-import { colorToFillFromCSS, mergedStyle, parseCSSNumber, pickStyle } from './css-values'+import {+ colorToFillFromCSS,+ colorToStrokeFromCSS,+ dropShadowFromCSS,+ mergedStyle,+ parseCSSNumber,+ pickStyle+} from './css-values'import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from './types'export interface DesignDocumentToSceneGraphOptions {@@ -55,6 +62,15 @@ function applyElementStyle(node: SceneNode, style: DesignStyleDeclaration): voidconst fills = fillsFromStyle(style, 'background-color')if (fills.length > 0) node.fills = fills+ const strokes = colorToStrokeFromCSS(+ pickStyle(style, 'border-color'),+ pickStyle(style, 'border-width')+ )+ if (strokes.length > 0) node.strokes = strokes++ const effects = dropShadowFromCSS(pickStyle(style, 'box-shadow'))+ if (effects.length > 0) node.effects = effects+const opacity = parseCSSNumber(pickStyle(style, 'opacity'))if (opacity !== null) node.opacity = opacitydiff --git a/tests/engine/dom-css/conversion.test.ts b/tests/engine/dom-css/conversion.test.tsindex 06fcc257d..5a05ec6d9 100644--- a/tests/engine/dom-css/conversion.test.ts+++ b/tests/engine/dom-css/conversion.test.ts@@ -1,11 +1,50 @@import { describe, expect, it } from 'bun:test'+import { colorToCSS } from '@open-pencil/core/color'import {+ createHeadlessCSSRuntime,designDocumentToSceneGraph,sceneGraphToDesignDocument,+ serializeHTML,type DesignDocument} from '@open-pencil/dom-css'+const slate900 = colorToCSS({ r: 17 / 255, g: 24 / 255, b: 39 / 255, a: 1 })+const slateShadow = colorToCSS({ r: 15 / 255, g: 23 / 255, b: 42 / 255, a: 0.12 })+const slate200 = colorToCSS({ r: 229 / 255, g: 231 / 255, b: 235 / 255, a: 1 })++const cardHTML = `+ <article class="card">+ <h1 class="title">OpenPencil</h1>+ <p class="description">Design with code-shaped CSS.</p>+ </article>+`++const cardCSS = `+ .card {+ display: flex;+ flex-direction: column;+ gap: 12px;+ padding: 24px;+ width: 320px;+ height: 180px;+ border: 1px solid ${slate200};+ border-radius: 16px;+ background: white;+ box-shadow: 0px 8px 24px 0px ${slateShadow};+ color: ${slate900};+ }+ .card .title {+ font-size: 24px;+ font-weight: 700;+ line-height: 32px;+ }+ .description {+ font-size: 14px;+ line-height: 20px;+ }+`+const cardDocument: DesignDocument = {type: 'document',children: [@@ -64,6 +103,39 @@ describe('@open-pencil/dom-css conversion', () => {expect(title?.fontWeight).toBe(700)})+ it('projects a parsed and styled HTML/CSS card into a scene graph', async () => {+ const runtime = createHeadlessCSSRuntime()+ const document = await runtime.computeStyles(runtime.parseHTML(cardHTML), cardCSS)+ const graph = designDocumentToSceneGraph(document)+ const page = graph.getPages()[0]+ const card = page ? graph.getChildren(page.id)[0] : undefined++ expect(card?.type).toBe('FRAME')+ if (card?.type !== 'FRAME') return+ expect(card.width).toBe(320)+ expect(card.height).toBe(180)+ expect(card.layoutMode).toBe('VERTICAL')+ expect(card.itemSpacing).toBe(12)+ expect(card.paddingLeft).toBe(24)+ expect(card.fills[0]?.type).toBe('SOLID')+ expect(card.strokes[0]?.weight).toBe(1)+ expect(card.effects[0]?.type).toBe('DROP_SHADOW')+ expect(card.effects[0]?.radius).toBe(24)++ const [title, description] = graph.getChildren(card.id)+ expect(title?.type).toBe('TEXT')+ expect(title?.fontSize).toBe(24)+ expect(title?.fills[0]?.type).toBe('SOLID')+ expect(description?.type).toBe('TEXT')+ expect(description?.fontSize).toBe(14)++ const roundTrip = sceneGraphToDesignDocument(graph)+ const html = serializeHTML(roundTrip)+ expect(html).toContain('OpenPencil')+ expect(html).toContain('Design with code-shaped CSS.')+ expect(html).toContain('box-shadow')+ })+it('projects a scene graph back into DesignDOM', () => {const graph = designDocumentToSceneGraph(cardDocument)const document = sceneGraphToDesignDocument(graph)diff --git a/tests/engine/dom-css/runtime.test.ts b/tests/engine/dom-css/runtime.test.tsindex 550cbf12d..f37feacec 100644--- a/tests/engine/dom-css/runtime.test.ts+++ b/tests/engine/dom-css/runtime.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'bun:test'+import { colorToCSS } from '@open-pencil/core/color'import {createCSSRuntime,createHeadlessCSSRuntime,@@ -7,6 +8,9 @@ import {type DesignDocument} from '@open-pencil/dom-css'+const slate900 = colorToCSS({ r: 17 / 255, g: 24 / 255, b: 39 / 255, a: 1 })+const slate700 = colorToCSS({ r: 31 / 255, g: 41 / 255, b: 55 / 255, a: 1 })+const documentFixture: DesignDocument = {type: 'document',children: [@@ -55,13 +59,53 @@ describe('@open-pencil/dom-css', () => {const runtime = createHeadlessCSSRuntime()const document = await runtime.computeStyles(documentFixture,- '.card { width: 320px; color: rgb(17, 24, 39); } #missing { color: red; }'+ `.card { width: 320px; color: ${slate900}; } #missing { color: red; }`)const card = document.children[0]expect(card?.type).toBe('element')if (card?.type !== 'element') returnexpect(card.computedStyle?.width).toBe('320px')- expect(card.computedStyle?.color).toBe('rgb(17, 24, 39)')+ expect(card.computedStyle?.color).toBe(slate900)+ })++ it('applies specificity, descendant selectors, child selectors, inheritance, and shorthands', async () => {+ const runtime = createHeadlessCSSRuntime()+ const parsed = runtime.parseHTML(`+ <article id="hero" class="card featured">+ <header><h1 class="title">OpenPencil</h1></header>+ </article>+ `)+ const document = await runtime.computeStyles(+ parsed,+ `+ article { color: ${slate900}; padding: 8px 16px; }+ .card { width: 300px; color: ${slate700}; }+ article.card > header { gap: 12px; }+ .card .title { font-size: 24px; }+ #hero { width: 320px; background: white; }+ `+ )+ const card = document.children[0]++ expect(card?.type).toBe('element')+ if (card?.type !== 'element') return+ expect(card.computedStyle?.width).toBe('320px')+ expect(card.computedStyle?.color).toBe(slate700)+ expect(card.computedStyle?.['padding-top']).toBe('8px')+ expect(card.computedStyle?.['padding-right']).toBe('16px')+ expect(card.computedStyle?.['background-color']).toBe('white')++ const header = card.children.find((child) => child.type === 'element')+ expect(header?.type).toBe('element')+ if (header?.type !== 'element') return+ expect(header.computedStyle?.gap).toBe('12px')+ expect(header.computedStyle?.color).toBe(slate700)++ const title = header.children[0]+ expect(title?.type).toBe('element')+ if (title?.type !== 'element') return+ expect(title.computedStyle?.['font-size']).toBe('24px')+ expect(title.computedStyle?.color).toBe(slate700)})})