Skip to content

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

fix: share CSS value parsing between dom-css and design JSX (#910)

Danila Poyarkov09accf78dfb8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 441919467..02c5c0ad1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -79,6 +79,8 @@
### Fixed
+- Import HTML and CSS with the right shadow and border colors. A shadow whose color follows its lengths, as CSS usually writes it, and a `border` with a color function such as `rgb(226, 232, 240)` came in black. Every layer of a `box-shadow` list now imports, `inset` ones as inner shadows, and lengths in `%`, `em`, or `vh` are no longer read as pixels.
+- Accept a CSS `box-shadow` list in design JSX's `shadow` prop: the color may come first, a fourth length sets the spread, several layers add several shadows, and `inset` makes an inner shadow. A color before the lengths or a spread made the shadow black.
- Read `repeat()` and `minmax()` in design JSX grid tracks, such as `columns="repeat(7, 1fr)"`, which collapsed the grid to near-zero columns. A track the grid cannot express sizes to its content instead of to 0.
- Lay out text set to fill its container the way Figma does: fill text in an auto-layout row now shares the free space with its siblings instead of keeping its old width and overflowing the row.
- Report what `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient` expect when design JSX passes them something other than an array of stops, such as `linearGradient('#3b82f6')`, instead of failing with `stops.map is not a function`, so an AI agent can correct the call.
diff --git a/packages/design-jsx/src/overrides/effects.ts b/packages/design-jsx/src/overrides/effects.ts
index 865f32326..27d09ced4 100644
--- a/packages/design-jsx/src/overrides/effects.ts
+++ b/packages/design-jsx/src/overrides/effects.ts
@@ -1,6 +1,6 @@
import type { Effect, SceneNode } from '@open-pencil/scene-graph'
-import { parseColor } from '@open-pencil/scene-graph/color'
import { TRANSPARENT } from '@open-pencil/scene-graph/constants'
+import { parseCSSShadows } from '@open-pencil/scene-graph/css'
function isEffect(value: unknown): value is Effect {
return (
@@ -12,28 +12,16 @@ function isEffect(value: unknown): value is Effect {
)
}
-function shadowShorthand(value: string): Effect | null {
- const parts = value.split(/\s+/)
- if (parts.length < 4) return null
- return {
- type: 'DROP_SHADOW',
- color: parseColor(parts.slice(3).join(' ')),
- offset: { x: Number.parseFloat(parts[0]), y: Number.parseFloat(parts[1]) },
- radius: Number.parseFloat(parts[2]),
- spread: 0,
- visible: true
- }
-}
-
-/** `effects` takes structured effects; `shadow` and `blur` append one drop shadow or layer blur. */
+/** `effects` takes structured effects; `shadow` appends its shadows and `blur` a layer blur. */
export function applyEffectOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
if (Array.isArray(props.effects)) {
const effects = props.effects.filter(isEffect).map((effect) => structuredClone(effect))
if (effects.length > 0) o.effects = effects
}
- const shadow = typeof props.shadow === 'string' ? shadowShorthand(props.shadow) : null
- if (shadow) o.effects = [...(o.effects ?? []), shadow]
+ // A CSS shadow list, as `box-shadow` takes it.
+ const shadows = typeof props.shadow === 'string' ? parseCSSShadows(props.shadow) : []
+ if (shadows.length > 0) o.effects = [...(o.effects ?? []), ...shadows]
if (typeof props.blur === 'number') {
o.effects = [
diff --git a/packages/design-jsx/src/props-overrides.ts b/packages/design-jsx/src/props-overrides.ts
index 7f2697b0b..a02537b6b 100644
--- a/packages/design-jsx/src/props-overrides.ts
+++ b/packages/design-jsx/src/props-overrides.ts
@@ -1,6 +1,6 @@
import type { Fill, LayoutMode, SceneNode } from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
-import { parseCSSGridTracks } from '@open-pencil/scene-graph/css'
+import { parseCSSGridTracks, parseCSSNumber } from '@open-pencil/scene-graph/css'
import type { Color, JSONObject } from '@open-pencil/scene-graph/primitives'
import { applyEffectOverrides } from './overrides/effects'
@@ -68,11 +68,7 @@ function parseDirection(value: unknown): SceneNode['textDirection'] | undefined
function numberFromPx(value: unknown): number | undefined {
if (typeof value === 'number') return value
- if (typeof value !== 'string') return undefined
- const trimmed = value.trim()
- if (!trimmed.endsWith('px')) return undefined
- const parsed = Number.parseFloat(trimmed.slice(0, -2))
- return Number.isFinite(parsed) ? parsed : undefined
+ return typeof value === 'string' ? (parseCSSNumber(value) ?? undefined) : undefined
}
function normalizeStyleProps(props: Record<string, unknown>): Record<string, unknown> {
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 68ff12859..29315c532 100644
--- a/packages/design-jsx/src/reference/authoring.md
+++ b/packages/design-jsx/src/reference/authoring.md
@@ -20,7 +20,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `bg` / `fill`, `stroke`, and text `color` accept colors and supported variable references. Set colors explicitly for predictable contrast. `fills` accepts structured paints; gradient helpers include `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient`, each taking an array of stops and optional `{ opacity, transform }`: `fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}`.
- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.
- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.
-- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow="offsetX offsetY blur #color"` and `blur` are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
+- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/packages/design-jsx/tests/grid.test.ts b/packages/design-jsx/tests/grid.test.ts
index 06b807e54..ba1d37052 100644
--- a/packages/design-jsx/tests/grid.test.ts
+++ b/packages/design-jsx/tests/grid.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from 'bun:test'
import { jsxNodeFields, parseJSXAttributes } from '#design-jsx/index'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, type GridTrack } from '@open-pencil/scene-graph'
function columns(value: string) {
const graph = new SceneGraph()
@@ -11,29 +11,23 @@ function columns(value: string) {
.gridTemplateColumns
}
-const FR = { sizing: 'FR', value: 1 }
+const fr = (value: number): GridTrack => ({ sizing: 'FR', value })
+const fixed = (value: number): GridTrack => ({ sizing: 'FIXED', value })
+const FR = fr(1)
+const AUTO: GridTrack = { sizing: 'AUTO', value: 0 }
describe('grid track lists', () => {
- test.each([
- ['1fr 200px 1fr', [FR, { sizing: 'FIXED', value: 200 }, FR]],
+ test.each<[string, GridTrack[]]>([
+ ['1fr 200px 1fr', [FR, fixed(200), FR]],
['repeat(3, 1fr)', [FR, FR, FR]],
- [
- 'repeat(2, 40px 1fr)',
- [{ sizing: 'FIXED', value: 40 }, FR, { sizing: 'FIXED', value: 40 }, FR]
- ],
- ['minmax(0, 1fr) auto', [FR, { sizing: 'AUTO', value: 0 }]],
- [
- '2fr 64',
- [
- { sizing: 'FR', value: 2 },
- { sizing: 'FIXED', value: 64 }
- ]
- ]
+ ['repeat(2, 40px 1fr)', [fixed(40), FR, fixed(40), FR]],
+ ['minmax(0, 1fr) auto', [FR, AUTO]],
+ ['2fr 64', [fr(2), fixed(64)]]
])('%p', (value, tracks) => {
expect(columns(value)).toEqual(tracks)
})
test('sizes a track the grid cannot express to its content, not to zero', () => {
- expect(columns('10rem 1fr')).toEqual([{ sizing: 'AUTO', value: 0 }, FR])
+ expect(columns('10em 1fr')).toEqual([AUTO, FR])
})
})
diff --git a/packages/design-jsx/tests/overrides/effects.test.ts b/packages/design-jsx/tests/overrides/effects.test.ts
new file mode 100644
index 000000000..db4a57c3f
--- /dev/null
+++ b/packages/design-jsx/tests/overrides/effects.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, test } from 'bun:test'
+
+import { jsxNodeFields, parseJSXAttributes } from '#design-jsx/index'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+function effects(attributes: string) {
+ const graph = new SceneGraph()
+ return jsxNodeFields(graph, 'FRAME', parseJSXAttributes(attributes), graph.getPages()[0].id)
+ .fields.effects
+}
+
+const RED = { r: 1, g: 0, b: 0, a: 1 }
+
+describe('the shadow prop', () => {
+ test.each([
+ ['the color last', 'shadow="0 4 8 #ff0000"'],
+ ['the color first', 'shadow="rgb(255 0 0) 0 4px 8px"']
+ ])('reads a shadow with %s', (_case, attributes) => {
+ expect(effects(attributes)).toEqual([
+ {
+ type: 'DROP_SHADOW',
+ color: RED,
+ offset: { x: 0, y: 4 },
+ radius: 8,
+ spread: 0,
+ visible: true
+ }
+ ])
+ })
+
+ test('reads spread and every layer of a shadow list', () => {
+ expect(effects('shadow="0 4 8 2 #ff0000, inset 0 1 0 #000"')).toMatchObject([
+ { type: 'DROP_SHADOW', spread: 2, color: RED },
+ { type: 'INNER_SHADOW', offset: { x: 0, y: 1 } }
+ ])
+ })
+})
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 61f183d9a..6457a2b08 100644
--- a/packages/docs/reference/design-authoring.md
+++ b/packages/docs/reference/design-authoring.md
@@ -22,7 +22,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `bg` / `fill`, `stroke`, and text `color` accept colors and supported variable references. Set colors explicitly for predictable contrast. `fills` accepts structured paints; gradient helpers include `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient`, each taking an array of stops and optional `{ opacity, transform }`: `fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}`.
- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.
- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.
-- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow="offsetX offsetY blur #color"` and `blur` are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
+- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/packages/dom-css/src/import/css-values.ts b/packages/dom-css/src/import/css-values.ts
index 5c20679aa..8143cbf99 100644
--- a/packages/dom-css/src/import/css-values.ts
+++ b/packages/dom-css/src/import/css-values.ts
@@ -1,29 +1,8 @@
-import valueParser, { type Node } from 'postcss-value-parser'
-
-import type { Effect, Fill, Stroke } from '@open-pencil/scene-graph'
-import { parseColor } from '@open-pencil/scene-graph/color'
-import type { Color } from '@open-pencil/scene-graph/primitives'
+import type { Fill, Stroke } from '@open-pencil/scene-graph'
+import { parseCSSColor, parseCSSNumber } from '@open-pencil/scene-graph/css'
import type { DesignStyleDeclaration } from '../types'
-const TRANSPARENT_KEYWORDS = new Set(['transparent', 'rgba(0, 0, 0, 0)', 'rgb(0 0 0 / 0)'])
-
-export function parseCSSNumber(value: string | undefined): number | null {
- if (!value) return null
- const trimmed = value.trim()
- if (trimmed.length === 0 || trimmed === 'auto') return null
- const parsed = Number.parseFloat(trimmed)
- if (!Number.isFinite(parsed)) return null
- return trimmed.endsWith('rem') ? parsed * 16 : parsed
-}
-
-export function parseCSSColor(value: string | undefined): Color | null {
- if (!value) return null
- const trimmed = value.trim()
- if (trimmed.length === 0 || TRANSPARENT_KEYWORDS.has(trimmed.toLowerCase())) return null
- return parseColor(trimmed)
-}
-
export function colorToFillFromCSS(value: string | undefined): Fill[] {
const color = parseCSSColor(value)
if (!color) return []
@@ -40,61 +19,6 @@ export function colorToStrokeFromCSS(
return [{ type: 'SOLID', color, weight, opacity: color.a, visible: true, align: 'INSIDE' }]
}
-function firstShadowLayerNodes(value: string): Node[] {
- const nodes: Node[] = []
- for (const node of valueParser(value).nodes) {
- if (node.type === 'div' && node.value === ',') return nodes
- nodes.push(node)
- }
- return nodes
-}
-
-function shadowColorFromNodes(nodes: Node[]): Color | null {
- for (const node of nodes) {
- if (node.type === 'function') {
- const color = parseCSSColor(valueParser.stringify(node))
- if (color) return color
- continue
- }
-
- if (node.type !== 'word') continue
- const color = parseCSSColor(node.value)
- if (color) return color
- }
- return null
-}
-
-function shadowNumbersFromNodes(nodes: Node[]): number[] {
- return nodes
- .filter((node) => node.type === 'word' && valueParser.unit(node.value) !== false)
- .map((node) => parseCSSNumber(node.value))
- .filter((number): number is number => number !== null)
-}
-
-export function dropShadowFromCSS(value: string | undefined): Effect[] {
- if (!value || value.trim() === 'none') return []
-
- const nodes = firstShadowLayerNodes(value)
- if (nodes.some((node) => node.type === 'word' && node.value === 'inset')) return []
-
- const color = shadowColorFromNodes(nodes)
- if (!color) return []
-
- const [offsetX = 0, offsetY = 0, radius = 0, spread = 0] = shadowNumbersFromNodes(nodes)
-
- 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/import/scene-graph.ts b/packages/dom-css/src/import/scene-graph.ts
index ea752a649..867ba0a73 100644
--- a/packages/dom-css/src/import/scene-graph.ts
+++ b/packages/dom-css/src/import/scene-graph.ts
@@ -8,17 +8,11 @@ import {
type Stroke
} from '@open-pencil/scene-graph'
import { TRANSPARENT } from '@open-pencil/scene-graph/constants'
+import { 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,
- dropShadowFromCSS,
- mergedStyle,
- parseCSSNumber,
- pickStyle
-} from './css-values'
+import { colorToFillFromCSS, colorToStrokeFromCSS, mergedStyle, pickStyle } from './css-values'
const DOM_CSS_PLUGIN_ID = 'open-pencil-dom-css'
const IMAGE_SOURCE_URL_KEY = 'image-source-url'
@@ -307,7 +301,7 @@ function applyElementStyle(
setBorderWeights(node, style, strokes[0])
}
- const effects = dropShadowFromCSS(pickStyle(style, 'box-shadow'))
+ const effects = parseCSSShadows(pickStyle(style, 'box-shadow'))
if (effects.length > 0) node.effects = effects
const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
@@ -353,7 +347,7 @@ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
if (opacity !== null) node.opacity = opacity
- const effects = dropShadowFromCSS(pickStyle(style, 'text-shadow'))
+ const effects = parseCSSShadows(pickStyle(style, 'text-shadow'))
if (effects.length > 0) node.effects = effects
const fontFamily = pickStyle(style, 'font-family')
diff --git a/packages/dom-css/src/runtime/headless-css.ts b/packages/dom-css/src/runtime/headless-css.ts
index 6c08f65ed..0bf1133b1 100644
--- a/packages/dom-css/src/runtime/headless-css.ts
+++ b/packages/dom-css/src/runtime/headless-css.ts
@@ -5,6 +5,9 @@ import {
type CSSStyleRuleLike
} from '@acemir/cssom'
+import { tryParseColor } from '@open-pencil/scene-graph/color'
+import { parseCSSNumber, splitCSSValue } from '@open-pencil/scene-graph/css'
+
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
interface HeadlessCSSRule {
@@ -129,7 +132,7 @@ function expandBoxShorthand(style: DesignStyleDeclaration, property: 'margin' |
const value = style[property]
if (!value) return
- const parts = splitWhitespace(value)
+ const parts = splitCSSValue(value)
const [top, right = top, bottom = top, left = right] = parts
if (!top || !right || !bottom || !left) return
@@ -143,9 +146,9 @@ 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))
+ const parts = splitCSSValue(value)
+ 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
}
@@ -154,24 +157,13 @@ function expandBackgroundShorthand(style: DesignStyleDeclaration) {
const value = style.background
if (!value || style['background-color']) return
- const color = splitWhitespace(value).find(isLikelyColor)
+ const color = splitCSSValue(value).find(isColor)
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())
- )
+/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */
+function isColor(value: string): boolean {
+ return tryParseColor(value) !== null
}
function classList(element: DesignElement): Set<string> {
diff --git a/packages/scene-graph/src/color/index.ts b/packages/scene-graph/src/color/index.ts
index fa9342cc0..b08c021c6 100644
--- a/packages/scene-graph/src/color/index.ts
+++ b/packages/scene-graph/src/color/index.ts
@@ -10,9 +10,10 @@ import type { Color } from '../primitives'
const toRGB = converter('rgb')
-export function parseColor(input: string): Color {
+/** A CSS color, or null when `input` is not one. */
+export function tryParseColor(input: string): Color | null {
const parsed = parse(input)
- if (!parsed) return { ...BLACK }
+ if (!parsed) return null
const rgb = toRGB(parsed)
return {
r: rgb.r,
@@ -22,6 +23,11 @@ export function parseColor(input: string): Color {
}
}
+/** A CSS color, or black when `input` is not one. */
+export function parseColor(input: string): Color {
+ return tryParseColor(input) ?? { ...BLACK }
+}
+
export function colorToHex(color: Color): string {
return formatHex({ mode: 'rgb', r: color.r, g: color.g, b: color.b }).toUpperCase()
}
diff --git a/packages/scene-graph/src/css/grid.ts b/packages/scene-graph/src/css/grid.ts
index f3cb649c4..f5a6fdf82 100644
--- a/packages/scene-graph/src/css/grid.ts
+++ b/packages/scene-graph/src/css/grid.ts
@@ -1,6 +1,7 @@
import valueParser, { type FunctionNode, type Node } from 'postcss-value-parser'
import type { GridTrack } from '../types'
+import { parseCSSNumber } from './values'
/** Bounds a `repeat()` count, which a typo could make huge. */
const MAX_REPEATED_TRACKS = 100
@@ -28,11 +29,11 @@ function argumentsOf(node: FunctionNode): Node[][] {
function wordTrack(word: string): GridTrack {
const dimension = valueParser.unit(word)
- if (!dimension) return autoTrack()
- const value = Number(dimension.number)
- if (dimension.unit === 'fr') return { sizing: 'FR', value: value || 1 }
- if (dimension.unit === '' || dimension.unit === 'px') return { sizing: 'FIXED', value }
- return autoTrack()
+ if (dimension && dimension.unit.toLowerCase() === 'fr') {
+ return { sizing: 'FR', value: Number(dimension.number) || 1 }
+ }
+ const pixels = parseCSSNumber(word)
+ return pixels === null ? autoTrack() : { sizing: 'FIXED', value: pixels }
}
function functionTracks(node: FunctionNode): GridTrack[] {
diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.ts
index 2ce9b95be..b836936fd 100644
--- a/packages/scene-graph/src/css/index.ts
+++ b/packages/scene-graph/src/css/index.ts
@@ -1 +1,3 @@
export { parseCSSGridTracks } from './grid'
+export { parseCSSShadows } from './shadows'
+export { parseCSSColor, parseCSSNumber, splitCSSValue } from './values'
diff --git a/packages/scene-graph/src/css/shadows.ts b/packages/scene-graph/src/css/shadows.ts
new file mode 100644
index 000000000..05564cbf4
--- /dev/null
+++ b/packages/scene-graph/src/css/shadows.ts
@@ -0,0 +1,68 @@
+import valueParser, { type Node } from 'postcss-value-parser'
+
+import { tryParseColor } from '../color'
+import { BLACK } from '../constants'
+import type { Color } from '../primitives'
+import type { Effect } from '../types'
+import { parseCSSNumber } from './values'
+
+/** The layers of a shadow list, split at its top-level commas. */
+function layersOf(nodes: Node[]): Node[][] {
+ const layers: Node[][] = []
+ let current: Node[] = []
+ for (const node of nodes) {
+ if (node.type === 'div' && node.value === ',') {
+ layers.push(current)
+ current = []
+ } else if (node.type !== 'space' && node.type !== 'comment') {
+ current.push(node)
+ }
+ }
+ layers.push(current)
+ return layers
+}
+
+/**
+ * One layer: `inset`, two to four lengths, and a color in any order. Without a color it is
+ * black, as `currentColor` usually is; a layer with anything else, such as `none`, is dropped.
+ */
+function shadowOf(nodes: Node[]): Effect[] {
+ let inset = false
+ let color: Color | null = null
+ const lengths: number[] = []
+ for (const node of nodes) {
+ if (node.type === 'word' && node.value.toLowerCase() === 'inset') {
+ inset = true
+ continue
+ }
+ const length = node.type === 'word' ? parseCSSNumber(node.value) : null
+ if (length !== null) {
+ lengths.push(length)
+ continue
+ }
+ const parsed = tryParseColor(valueParser.stringify(node))
+ if (!parsed || color) return []
+ color = parsed
+ }
+ if (lengths.length < 2 || lengths.length > 4 || color?.a === 0) return []
+ const [x = 0, y = 0, radius = 0, spread = 0] = lengths
+ return [
+ {
+ type: inset ? 'INNER_SHADOW' : 'DROP_SHADOW',
+ color: color ?? { ...BLACK },
+ offset: { x, y },
+ radius,
+ spread,
+ visible: true
+ }
+ ]
+}
+
+/**
+ * The shadows of a CSS `box-shadow` or `text-shadow` list, such as
+ * `0 4px 8px rgb(0 0 0 / 0.2), inset 0 1px #fff`: drop shadows, and inner shadows for `inset`.
+ */
+export function parseCSSShadows(value: string | undefined): Effect[] {
+ if (!value) return []
+ return layersOf(valueParser(value).nodes).flatMap(shadowOf)
+}
diff --git a/packages/scene-graph/src/css/values.ts b/packages/scene-graph/src/css/values.ts
new file mode 100644
index 000000000..0037f1c8a
--- /dev/null
+++ b/packages/scene-graph/src/css/values.ts
@@ -0,0 +1,42 @@
+import valueParser from 'postcss-value-parser'
+
+import { tryParseColor } from '../color'
+import type { Color } from '../primitives'
+
+/** Pixels in a rem, as browsers use by default. */
+const ROOT_FONT_SIZE = 16
+
+/**
+ * A CSS number in pixels: unitless, `px`, or `rem`. Null for `auto`, for units that depend on
+ * what the value applies to (`%`, `em`, `vh`), and for anything that is not a number.
+ */
+export function parseCSSNumber(value: string | undefined): number | null {
+ if (!value) return null
+ const dimension = valueParser.unit(value.trim())
+ if (!dimension) return null
+ const number = Number(dimension.number)
+ if (!Number.isFinite(number)) return null
+ switch (dimension.unit.toLowerCase()) {
+ case '':
+ case 'px':
+ return number
+ case 'rem':
+ return number * ROOT_FONT_SIZE
+ default:
+ return null
+ }
+}
+
+/** A CSS color that paints something; null for an invalid or fully transparent one. */
+export function parseCSSColor(value: string | undefined): Color | null {
+ if (!value) return null
+ const color = tryParseColor(value.trim())
+ return color && color.a > 0 ? color : null
+}
+
+/** The space-separated parts of a CSS value, keeping functions such as `rgb(0, 0, 0)` whole. */
+export function splitCSSValue(value: string): string[] {
+ return valueParser(value)
+ .nodes.filter((node) => node.type !== 'space' && node.type !== 'comment')
+ .map((node) => valueParser.stringify(node))
+}
diff --git a/packages/scene-graph/tests/css/grid.test.ts b/packages/scene-graph/tests/css/grid.test.ts
index 6ed9dce2a..c117fde50 100644
--- a/packages/scene-graph/tests/css/grid.test.ts
+++ b/packages/scene-graph/tests/css/grid.test.ts
@@ -1,26 +1,29 @@
import { describe, expect, test } from 'bun:test'
+import type { GridTrack } from '@open-pencil/scene-graph'
import { parseCSSGridTracks } from '@open-pencil/scene-graph/css'
-const FR = { sizing: 'FR', value: 1 }
-const AUTO = { sizing: 'AUTO', value: 0 }
-const fixed = (value: number) => ({ sizing: 'FIXED', value })
+const fr = (value: number): GridTrack => ({ sizing: 'FR', value })
+const fixed = (value: number): GridTrack => ({ sizing: 'FIXED', value })
+const FR = fr(1)
+const AUTO: GridTrack = { sizing: 'AUTO', value: 0 }
describe('parseCSSGridTracks', () => {
- test.each([
+ test.each<[string, GridTrack[]]>([
['1fr 200px 1fr', [FR, fixed(200), FR]],
- ['2fr 64', [{ sizing: 'FR', value: 2 }, fixed(64)]],
+ ['2fr 64', [fr(2), fixed(64)]],
['repeat(3, 1fr)', [FR, FR, FR]],
['repeat(2, 40px 1fr)', [fixed(40), FR, fixed(40), FR]],
['minmax(0, 1fr) auto', [FR, AUTO]],
['repeat(2, minmax(0, 1fr) 100px)', [FR, fixed(100), FR, fixed(100)]],
- [' REPEAT( 2 , 1fr ) 120px ', [FR, FR, fixed(120)]]
+ [' REPEAT( 2 , 1fr ) 120px ', [FR, FR, fixed(120)]],
+ ['10rem 1fr', [fixed(160), FR]]
])('%p', (value, tracks) => {
expect(parseCSSGridTracks(value)).toEqual(tracks)
})
- test.each([
- ['a length the grid cannot express', '10rem 1fr', [AUTO, FR]],
+ test.each<[string, string, GridTrack[]]>([
+ ['a length relative to the font', '10em 1fr', [AUTO, FR]],
['a sizing function', 'fit-content(200px) 1fr', [AUTO, FR]],
['a repeat that depends on the container', 'repeat(auto-fill, 100px)', [AUTO]]
])('sizes %s to its content, not to zero', (_case, value, tracks) => {
diff --git a/packages/scene-graph/tests/css/shadows.test.ts b/packages/scene-graph/tests/css/shadows.test.ts
new file mode 100644
index 000000000..9185e9949
--- /dev/null
+++ b/packages/scene-graph/tests/css/shadows.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { Color, Effect } from '@open-pencil/scene-graph'
+import { parseCSSShadows } from '@open-pencil/scene-graph/css'
+
+const RED: Color = { r: 1, g: 0, b: 0, a: 1 }
+
+function shadow(fields: Partial<Effect>): Effect {
+ return {
+ type: 'DROP_SHADOW',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ offset: { x: 0, y: 4 },
+ radius: 8,
+ spread: 0,
+ visible: true,
+ ...fields
+ }
+}
+
+describe('parseCSSShadows', () => {
+ test.each([
+ ['the color last', '0 4px 8px red'],
+ ['the color first', 'red 0 4px 8px'],
+ ['a color function with spaces', '0 4px 8px rgb(255 0 0)']
+ ])('reads a shadow with %s', (_case, value) => {
+ expect(parseCSSShadows(value)).toEqual([shadow({ color: RED })])
+ })
+
+ test('reads spread, rem lengths, and a translucent color', () => {
+ expect(parseCSSShadows('0 0.25rem 8px 2px rgba(0, 0, 0, 0.5)')).toEqual([
+ shadow({ spread: 2, color: { r: 0, g: 0, b: 0, a: 0.5 } })
+ ])
+ })
+
+ test('reads each layer, with inset ones as inner shadows', () => {
+ expect(parseCSSShadows('0 4px 8px red, inset 0 1px #000')).toEqual([
+ shadow({ color: RED }),
+ shadow({ type: 'INNER_SHADOW', offset: { x: 0, y: 1 }, radius: 0 })
+ ])
+ })
+
+ test('uses black when a layer has no color', () => {
+ expect(parseCSSShadows('0 4px 8px')).toEqual([shadow({})])
+ })
+
+ test.each(['none', '', '0', 'red', '0 4px 8px transparent', '0 4px 8px red blue'])(
+ 'reads no shadow from %p',
+ (value) => {
+ expect(parseCSSShadows(value)).toEqual([])
+ }
+ )
+})
diff --git a/packages/scene-graph/tests/css/values.test.ts b/packages/scene-graph/tests/css/values.test.ts
new file mode 100644
index 000000000..a08d13d69
--- /dev/null
+++ b/packages/scene-graph/tests/css/values.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from 'bun:test'
+
+import { parseCSSColor, parseCSSNumber } from '@open-pencil/scene-graph/css'
+
+describe('parseCSSNumber', () => {
+ test.each([
+ ['12', 12],
+ ['12px', 12],
+ [' -4.5PX ', -4.5],
+ ['0.75rem', 12],
+ ['.5', 0.5]
+ ])('reads %p as %p pixels', (value, pixels) => {
+ expect(parseCSSNumber(value)).toBe(pixels)
+ })
+
+ test.each([undefined, '', 'auto', '50%', '1.5em', '10vh', 'calc(1px + 2px)', 'abc'])(
+ 'reads no pixels from %p',
+ (value) => {
+ expect(parseCSSNumber(value)).toBeNull()
+ }
+ )
+})
+
+describe('parseCSSColor', () => {
+ test('reads a color', () => {
+ expect(parseCSSColor(' #ff0000 ')).toEqual({ r: 1, g: 0, b: 0, a: 1 })
+ })
+
+ test.each([undefined, '', 'nope', 'transparent', 'rgba(0, 0, 0, 0)', 'rgb(0 0 0 / 0)', '#0000'])(
+ 'reads no color from %p, which paints nothing',
+ (value) => {
+ expect(parseCSSColor(value)).toBeNull()
+ }
+ )
+})
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 61f183d9a..6457a2b08 100644
--- a/skills/open-pencil/references/design-authoring.md
+++ b/skills/open-pencil/references/design-authoring.md
@@ -22,7 +22,7 @@ This reference describes scene creation, not React DOM output. Use the `render`
- `bg` / `fill`, `stroke`, and text `color` accept colors and supported variable references. Set colors explicitly for predictable contrast. `fills` accepts structured paints; gradient helpers include `linearGradient`, `radialGradient`, `angularGradient`, and `diamondGradient`, each taking an array of stops and optional `{ opacity, transform }`: `fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}`.
- `stroke` describes one stroke, refined by `strokeWidth`, `strokeAlign` (`"inside"`, `"center"`, `"outside"`), `strokeDash`, `strokeCap`, and `strokeJoin`. `strokes` takes several, as objects with `color`, `weight`, `align`, `dash`, `cap`, `join`, and `visible`; `strokeWeights={{ top, right, bottom, left }}` sets per-side widths. `dashPattern` sets the node's own dash pattern, separate from the per-stroke `strokeDash`.
- `rounded` and `roundedTL`/`roundedTR`/`roundedBL`/`roundedBR` control corners. `strokeWidth`, `opacity`, `rotate`, and `blendMode` control appearance. `overflow="hidden"` clips content; do not hide accidental text overflow to make a broken layout appear correct.
-- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow="offsetX offsetY blur #color"` and `blur` are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
+- `effects` accepts structured effects such as `dropShadow`, `innerShadow`, and `layerBlur`. `shadow` takes a CSS `box-shadow` list, such as `shadow="0 4 8 #0002, inset 0 1 0 #fff"`, and `blur` a layer blur radius; both are convenient shorthands. Effect helpers take `radius`, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
- Text content belongs inside `Text`. Use `size`, `font`, `weight`, `italic`, `lineHeight`, `letterSpacing`, `textAlign`, `textAlignVertical`, `textDecoration`, and `textCase`. Verify fonts actually load before judging dimensions; do not assume every font is available.
- `Icon` uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
- Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.
diff --git a/tests/engine/dom-css/conversion.test.ts b/tests/engine/dom-css/conversion.test.ts
index 6351bf309..27d054ae5 100644
--- a/tests/engine/dom-css/conversion.test.ts
+++ b/tests/engine/dom-css/conversion.test.ts
@@ -12,6 +12,7 @@ import {
tailwindHTMLToSceneGraph
} from '@open-pencil/dom-css'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { parseColor } from '@open-pencil/scene-graph/color'
import {
DOM_CSS_COLORS,
@@ -222,8 +223,11 @@ describe('@open-pencil/dom-css conversion', () => {
expect(card.paddingLeft).toBe(24)
expect(card.fills[0]?.type).toBe('SOLID')
expect(card.strokes[0]?.weight).toBe(1)
+ // A color function in the `border` shorthand, and a shadow color after its lengths.
+ expect(card.strokes[0]?.color).toEqual(parseColor(DOM_CSS_COLORS.slate200))
expect(card.effects[0]?.type).toBe('DROP_SHADOW')
expect(card.effects[0]?.radius).toBe(24)
+ expect(card.effects[0]?.color).toEqual(parseColor(DOM_CSS_COLORS.slateShadow))
const [title, description] = graph.getChildren(card.id)
expect(title?.type).toBe('TEXT')