AI-native design editor. Open-source Figma alternative.
feat(figma-api): add getCSSAsync (#1743)
Danila Poyarkov5894051f8f8f
diff --git a/changes/1743/added.md b/changes/1743/added.mdnew file mode 100644index 000000000..6fc75875a--- /dev/null+++ b/changes/1743/added.md@@ -0,0 +1 @@+- Scripts get a layer's CSS with `getCSSAsync()`, the CSS OpenPencil's HTML export writes for it.diff --git a/changes/1743/fixed.md b/changes/1743/fixed.mdnew file mode 100644index 000000000..b75f71fc9--- /dev/null+++ b/changes/1743/fixed.md@@ -0,0 +1 @@+- HTML export draws linear, radial, and angular gradient fills and every stacked fill with its blend mode, writes the colour a variable-bound paint draws, and standalone pages define the tokens their layers use. Diamond gradients are still left out.diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex 99cc474a3..04fdcce94 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -1,4 +1,5 @@import type {+ BaseNodeMixin,BooleanOperationNode,ComponentNode,ComponentPropertyDefinitions,@@ -407,6 +408,11 @@ type GeometryMembersMatch = Expect<>const _geometryMembersMatch: GeometryMembersMatch = true+type CSSMembersMatch = Expect<+ Extends<Pick<FigmaNodeProxy, 'getCSSAsync'>, Pick<BaseNodeMixin, 'getCSSAsync'>>+>+const _cssMembersMatch: CSSMembersMatch = true+// --- Styles: each style's members are Figma's, apart from consumers, which read node proxies ---type BaseStyleKeys =diff --git a/packages/core/src/figma-api/css.ts b/packages/core/src/figma-api/css.tsnew file mode 100644index 000000000..526f49aad--- /dev/null+++ b/packages/core/src/figma-api/css.ts@@ -0,0 +1,28 @@+import { sceneNodeToDesignDocument } from '@open-pencil/dom-css/export'++import { graph, raw, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'+import { flushPendingLayout } from '#core/figma-api/pending-layout'+import { vectorElement } from '#core/io/formats/html/vectors'++/**+ * `getCSSAsync()` on every node, as Figma's `BaseNodeMixin` has it: the CSS OpenPencil's HTML+ * export writes for the layer, which draws it in a browser. A hidden layer gives the CSS it would+ * have shown; a page and the document give none.+ */+export function installCSSAccessors(target: object, internals: NodeProxyInternals): void {+ Object.defineProperty(target, 'getCSSAsync', {+ // Async, so a removed node rejects rather than throwing before a promise exists.+ async value(this: ProxyThis): Promise<Record<string, string>> {+ const scene = graph(this, internals)+ const node = raw(this, internals)+ if (node.type === 'CANVAS' || node.id === scene.rootId) return {}+ // A script's edits that nothing read yet are laid out first, as Figma lays them out.+ flushPendingLayout(scene)+ const element = sceneNodeToDesignDocument(scene, node.id, {+ vectorElement,+ shown: new Set([node.id])+ }).children.at(0)+ return element?.type === 'element' ? { ...element.inlineStyle } : {}+ }+ })+}diff --git a/packages/core/src/figma-api/members.ts b/packages/core/src/figma-api/members.tsindex ecebb10d6..76223f4fa 100644--- a/packages/core/src/figma-api/members.ts+++ b/packages/core/src/figma-api/members.ts@@ -1,4 +1,5 @@import type {+ BaseNodeMixin,BooleanOperationNode,ComponentSetNode,DocumentNode,@@ -101,6 +102,7 @@ export abstract class FigmaNodeMembers {declare guides: readonly Guide[]declare exportSettings: ExportMixin['exportSettings']declare exportAsync: ExportMixin['exportAsync']+ declare getCSSAsync: BaseNodeMixin['getCSSAsync']declare fillGeometry: GeometryMixin['fillGeometry']declare strokeGeometry: GeometryMixin['strokeGeometry']declare layoutWrap: stringdiff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 05d18c23d..b861e0cac 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -23,6 +23,7 @@ import { installVariableModeNodeProxyAccessors } from './accessors/variables'import { installVectorNodeProxyAccessors } from './accessors/vector'import { installVisualNodeProxyAccessors } from './accessors/visual'import { installComponentPropertyAccessors } from './components'+import { installCSSAccessors } from './css'import { installDevStatusAccessors } from './dev-status'import { installExportAccessors } from './export/accessors'import type { ExportHost } from './export/render'@@ -105,6 +106,7 @@ export class FigmaNodeProxy extends FigmaNodeMembers {if (type) installInstanceOverrideAccessors(this, internals, type)if (type) installStyleReferenceAccessors(this, internals, type, id === graph.rootId, MIXED)if (type && id !== graph.rootId) installExportAccessors(this, internals)+ installCSSAccessors(this, internals)if (type) installGeometryAccessors(this, internals, type)// Figma loads a page's layers on demand in dynamic-page mode and has `loadAsync` on pages// alone, as the editor loads a page's layers when it is first visited.diff --git a/packages/core/src/io/formats/html/index.ts b/packages/core/src/io/formats/html/index.tsindex 5d494b5de..294c7de68 100644--- a/packages/core/src/io/formats/html/index.ts+++ b/packages/core/src/io/formats/html/index.ts@@ -2,7 +2,7 @@ import { filename } from 'pathe/utils'import {exportHTMLBundle,- sceneNodeToDesignDocument,+ sceneNodesToDesignDocument,type DesignDocument} from '@open-pencil/dom-css/export'import type { SceneGraph } from '@open-pencil/scene-graph'@@ -12,14 +12,9 @@ import { exportWebFontFaceAssets } from '#core/text/web-font/assets'import { vectorElement } from './vectors'+/** The layers as one document, which keeps the tokens they reference for its stylesheet. */function designDocument(graph: SceneGraph, nodeIds: string[]): DesignDocument {- return {- type: 'document',- sourceGraph: graph,- children: nodeIds.flatMap(- (id) => sceneNodeToDesignDocument(graph, id, { vectorElement }).children- )- }+ return sceneNodesToDesignDocument(graph, nodeIds, { vectorElement })}/** `card.html` keeps its external files in `card.assets/` next to it, whatever the path style. */diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex cf0bd1ca8..f22aeabcd 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -329,24 +329,3 @@ export const SVG_STROKE_JOIN: Record<string, string> = {ROUND: 'round',BEVEL: 'bevel'}--export const SVG_BLEND_MODE: Record<string, string> = {- NORMAL: 'normal',- DARKEN: 'darken',- MULTIPLY: 'multiply',- COLOR_BURN: 'color-burn',- LIGHTEN: 'lighten',- LINEAR_BURN: 'plus-darker',- SCREEN: 'screen',- LINEAR_DODGE: 'plus-lighter',- COLOR_DODGE: 'color-dodge',- OVERLAY: 'overlay',- SOFT_LIGHT: 'soft-light',- HARD_LIGHT: 'hard-light',- DIFFERENCE: 'difference',- EXCLUSION: 'exclusion',- HUE: 'hue',- SATURATION: 'saturation',- COLOR: 'color',- LUMINOSITY: 'luminosity'-}diff --git a/packages/core/src/io/formats/svg/export.ts b/packages/core/src/io/formats/svg/export.tsindex 3bb43d5ce..e364dcdf7 100644--- a/packages/core/src/io/formats/svg/export.ts+++ b/packages/core/src/io/formats/svg/export.ts@@ -1,4 +1,5 @@import type { RenderColorSpace } from '@open-pencil/scene-graph/color'+import { CSS_BLEND_MODE } from '@open-pencil/scene-graph/css'import { normalizeDashPattern } from '#core/canvas/strokes'import { lineStrokePath } from '#core/canvas/strokes/line'@@ -13,8 +14,7 @@ import {resolveFill,solidFillOpacity,SVG_STROKE_CAP,- SVG_STROKE_JOIN,- SVG_BLEND_MODE+ SVG_STROKE_JOIN} from './defs'import {round,@@ -239,7 +239,7 @@ function buildGroupAttrs(if (node.opacity < 1) attrs.opacity = round(node.opacity)- const blend = SVG_BLEND_MODE[node.blendMode]+ const blend = CSS_BLEND_MODE[node.blendMode]if (blend && blend !== 'normal' && node.blendMode !== 'PASS_THROUGH') {attrs.style = `mix-blend-mode: ${blend}`}diff --git a/packages/core/tests/figma-api/css.test.ts b/packages/core/tests/figma-api/css.test.tsnew file mode 100644index 000000000..cdb5cba9e--- /dev/null+++ b/packages/core/tests/figma-api/css.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from 'bun:test'++import { createAPI } from '#core-tests/helpers/figma-api'++import { renderNodesToHTML } from '#core/io/formats/html'++const RED = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }] as const+const BLUE = [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }] as const++describe('getCSSAsync', () => {+ test('gives the CSS the HTML export writes for the layer', async () => {+ const figma = createAPI()+ const row = figma.createFrame()+ row.layoutMode = 'HORIZONTAL'+ row.itemSpacing = 8+ row.paddingLeft = 16+ row.fills = [...RED]+ row.strokes = [...BLUE]+ row.strokeWeight = 2+ row.cornerRadius = 8+ row.appendChild(figma.createRectangle())++ const css = await row.getCSSAsync()+ const { html } = await renderNodesToHTML(figma.graph, [row.id])++ expect(Object.keys(css).length).toBeGreaterThan(0)+ for (const [property, value] of Object.entries(css)) {+ expect(typeof value).toBe('string')+ expect(html).toContain(`${property}: ${value}`)+ }+ expect(css).toMatchObject({+ display: 'flex',+ gap: '8px',+ 'padding-left': '16px',+ 'background-color': '#FF0000',+ border: '2px solid #0000FF',+ 'border-radius': '8px'+ })+ })++ test('gives a hidden layer the CSS it would have shown', async () => {+ const figma = createAPI()+ const rect = figma.createRectangle()+ rect.resize(40, 20)+ rect.fills = [...RED]+ rect.visible = false+ expect(await rect.getCSSAsync()).toMatchObject({+ width: '40px',+ height: '20px',+ 'background-color': '#FF0000'+ })+ })++ test('writes a bound colour as the token the canvas draws', async () => {+ const figma = createAPI()+ const collection = figma.variables.createVariableCollection('Tokens')+ const brand = figma.variables.createVariable('brand/primary', collection, 'COLOR')+ brand.setValueForMode(collection.modes[0].modeId, { r: 0, g: 0.5, b: 1, a: 1 })+ const rect = figma.createRectangle()+ rect.fills = [+ figma.variables.setBoundVariableForPaint(+ { type: 'SOLID', color: { r: 0, g: 0, b: 0 } },+ 'color',+ brand+ )+ ]+ expect((await rect.getCSSAsync())['background-color']).toBe('var(--color-brand-primary)')+ })++ test('rejects for a removed layer rather than throwing', async () => {+ const figma = createAPI()+ const rect = figma.createRectangle()+ rect.remove()+ const css = rect.getCSSAsync()+ expect(css).toBeInstanceOf(Promise)+ await expect(css).rejects.toThrow()+ })++ test('gives pages and the document none', async () => {+ const figma = createAPI()+ expect(await figma.currentPage.getCSSAsync()).toEqual({})+ expect(await figma.root.getCSSAsync()).toEqual({})+ })+})diff --git a/packages/core/tests/io/formats/html/tokens.test.ts b/packages/core/tests/io/formats/html/tokens.test.tsnew file mode 100644index 000000000..4bf539a45--- /dev/null+++ b/packages/core/tests/io/formats/html/tokens.test.ts@@ -0,0 +1,38 @@+import { describe, expect, test } from 'bun:test'++import { createAPI } from '#core-tests/helpers/figma-api'++import { renderNodesToHTML } from '#core/io/formats/html'++describe('tokens in HTML export', () => {+ test('a standalone page defines every token its layers use', async () => {+ const figma = createAPI()+ const collection = figma.variables.createVariableCollection('Tokens')+ const mode = collection.modes[0].modeId+ const bound = (name: string, color: { r: number; g: number; b: number }) => {+ const variable = figma.variables.createVariable(name, collection, 'COLOR')+ variable.setValueForMode(mode, { ...color, a: 1 })+ const rect = figma.createRectangle()+ // A script binds a paint it gave another colour; the page draws the variable's.+ rect.fills = [+ figma.variables.setBoundVariableForPaint(+ { type: 'SOLID', color: { r: 0, g: 0, b: 0 } },+ 'color',+ variable+ )+ ]+ return rect.id+ }+ const ids = [+ bound('brand/primary', { r: 0, g: 0.5, b: 1 }),+ bound('brand/accent', { r: 1, g: 0, b: 0 })+ ]++ const { html } = await renderNodesToHTML(figma.graph, ids, { html: 'standalone' })++ expect(html).toContain('--color-brand-primary: #0080FF')+ expect(html).toContain('--color-brand-accent: #FF0000')+ expect(html).toContain('background-color: var(--color-brand-primary)')+ expect(html).toContain('background-color: var(--color-brand-accent)')+ })+})diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex a2b7ba235..13084f416 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -258,6 +258,10 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'- `node.outlineStroke()` adds the layer's stroke as a vector filled with the stroke's paints, named `<name> (Stroke)` (a group of glyph vectors for text), at the end of the page at the layer's position in its parent, as Figma does, and keeps the layer. It returns `null` without a visible stroke- These measure with a renderer: the canvas's in the desktop and browser apps, and a headless one in `open-pencil eval`. Before a document's canvas is ready, or on a host without a renderer, they throw `This host has no renderer to measure geometry with`+### CSS++- `node.getCSSAsync()` resolves to the CSS OpenPencil's HTML export writes for a layer, as a record of property names and values: its size, auto layout and its place in its parent's, its fills as `background-color` and `background-image` (gradients, and colours stacked above another fill, top first), borders, corner radius, effects, and for text its font and colour. Like the HTML export, it leaves out diamond gradients, draws a rotated elliptical radial gradient unrotated, since CSS cannot turn one, and leaves out an image fill, which the export draws as an `<img>` element that covers any fill above it. Bound variables are written as the custom properties of OpenPencil's token stylesheet, such as `var(--color-brand-primary)`. A hidden layer gives the CSS it would show, and pages and the document give `{}`. The values describe the same layer as Figma's Dev Mode, but are not written in its exact format+### PropertiesCommon node properties are readable/writable through the proxy, including:diff --git a/packages/dom-css/src/export/css.ts b/packages/dom-css/src/export/css.tsindex fab09d858..24830ebf3 100644--- a/packages/dom-css/src/export/css.ts+++ b/packages/dom-css/src/export/css.ts@@ -1,5 +1,6 @@import type { Effect, Fill, Stroke, TextLength } from '@open-pencil/scene-graph'import { colorToCSS, colorToHex } from '@open-pencil/scene-graph/color'+import { gradientPoint } from '@open-pencil/scene-graph/gradient'import type { Color } from '@open-pencil/scene-graph/primitives'import type { DesignStyleDeclaration } from '../types'@@ -54,3 +55,83 @@ export function lineHeightToCSS(length: TextLength): string {export function letterSpacingToCSS(length: TextLength): string {return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`}++/** A share of the layer's box as a CSS percentage. */+function percent(value: number): string {+ return `${Number((value * 100).toFixed(3))}%`+}++/** The stops, each at `place(position)`, its own position unless the gradient line differs. */+function gradientStopsCSS(fill: Fill, place: (position: number) => number = (p) => p): string {+ return (fill.gradientStops ?? [])+ .map(+ (stop) =>+ `${cssColor({ ...stop.color, a: stop.color.a * fill.opacity })} ${percent(place(stop.position))}`+ )+ .join(', ')+}++/**+ * Where a linear gradient's stops fall on CSS's gradient line, which runs through the box's+ * centre at the gradient's angle and ends where the corners meet it: a stop at `position` along+ * the paint's own handles lands at the share of that line its point lies at, so the colours sit+ * where the canvas draws them whatever the angle and the box.+ */+function cssLinePosition(+ fill: Fill,+ width: number,+ height: number,+ angle: number+): (position: number) => number {+ const t = fill.gradientTransform+ if (!t || width <= 0 || height <= 0) return (position) => position+ const start = gradientPoint(t, { x: 0, y: 0.5 })+ const end = gradientPoint(t, { x: 1, y: 0.5 })+ const radians = (angle * Math.PI) / 180+ const direction = { x: Math.sin(radians), y: -Math.cos(radians) }+ const length = Math.abs(width * direction.x) + Math.abs(height * direction.y)+ return (position) => {+ const x = (start.x + (end.x - start.x) * position) * width - width / 2+ const y = (start.y + (end.y - start.y) * position) * height - height / 2+ return (x * direction.x + y * direction.y) / length + 0.5+ }+}++/**+ * The CSS angle of a linear or angular gradient across a `width` by `height` box: 0deg points+ * up and 90deg right, measured from where the gradient starts to where it ends.+ */+function gradientAngle(fill: Fill, width: number, height: number): number {+ const t = fill.gradientTransform+ if (!t) return 90+ const start = gradientPoint(t, { x: 0, y: 0.5 })+ const end = gradientPoint(t, { x: 1, y: 0.5 })+ const degrees =+ (Math.atan2((end.x - start.x) * width, -(end.y - start.y) * height) * 180) / Math.PI+ return Number((((degrees % 360) + 360) % 360).toFixed(3))+}++/** A gradient fill as a CSS image over a `width` by `height` box, or undefined for a diamond. */+export function gradientToCSS(fill: Fill, width: number, height: number): string | undefined {+ const t = fill.gradientTransform ?? { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ const center = gradientPoint(t, { x: 0.5, y: 0.5 })+ if (fill.type === 'GRADIENT_LINEAR') {+ const angle = gradientAngle(fill, width, height)+ const stops = gradientStopsCSS(fill, cssLinePosition(fill, width, height, angle))+ return `linear-gradient(${angle}deg, ${stops})`+ }+ if (fill.type === 'GRADIENT_RADIAL') {+ const right = gradientPoint(t, { x: 1, y: 0.5 })+ const bottom = gradientPoint(t, { x: 0.5, y: 1 })+ const rx = Math.hypot(right.x - center.x, right.y - center.y)+ const ry = Math.hypot(bottom.x - center.x, bottom.y - center.y)+ const shape = `${percent(rx)} ${percent(ry)} at ${percent(center.x)} ${percent(center.y)}`+ return `radial-gradient(${shape}, ${gradientStopsCSS(fill)})`+ }+ if (fill.type === 'GRADIENT_ANGULAR') {+ const from = gradientAngle(fill, width, height)+ const at = `${percent(center.x)} ${percent(center.y)}`+ return `conic-gradient(from ${from}deg at ${at}, ${gradientStopsCSS(fill)})`+ }+ return undefined+}diff --git a/packages/dom-css/src/export/index.ts b/packages/dom-css/src/export/index.tsindex b10d674ea..3174a13c1 100644--- a/packages/dom-css/src/export/index.ts+++ b/packages/dom-css/src/export/index.ts@@ -2,6 +2,7 @@export {sceneGraphToDesignDocument,sceneNodeToDesignDocument,+ sceneNodesToDesignDocument,type SceneGraphToDesignOptions,type VectorElementRenderer} from './projection'diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.tsindex c53a705d9..b11005d86 100644--- a/packages/dom-css/src/export/projection.ts+++ b/packages/dom-css/src/export/projection.ts@@ -1,12 +1,14 @@import { fromUint8Array } from 'js-base64'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import type { Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { BLACK } from '@open-pencil/scene-graph/constants'+import { CSS_BLEND_MODE } from '@open-pencil/scene-graph/css'import { readIcon } from '@open-pencil/scene-graph/icons'import { imageMimeType } from '@open-pencil/scene-graph/images'import { layoutSizingInParent } from '@open-pencil/scene-graph/layout'import { shaderOfPaint } from '@open-pencil/scene-graph/shaders'import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'+import { resolvedPaintBindings } from '@open-pencil/scene-graph/variables'import { DesignTokens, type CSSModes } from '../tokens/references'import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'@@ -15,6 +17,7 @@ import {dropShadowToCSS,effectsToCSS,fillToCSS,+ gradientToCSS,letterSpacingToCSS,lineHeightToCSS,strokeColorToCSS@@ -271,6 +274,47 @@ function addShaderLayerStyle(style: DesignStyleDeclaration): void {style.isolation = 'isolate'}+/**+ * The layer's visible fills, painted bottom to top: its lowest solid fill as `background-color`,+ * and every gradient and every colour stacked above another fill as `background-image`, the top+ * one first, as CSS stacks them. A colour can only stack as an image, so it is written as a+ * gradient of itself. An image fill is the element's own image.+ */+function addBackground(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {+ const layers: { image: string; blend: string }[] = []+ let color: string | undefined+ node.fills.forEach((fill, index) => {+ if (!fill.visible) return+ const blend = layerBlendMode(fill.blendMode)+ if (fill.type === 'SOLID') {+ const value = css(`fills/${index}/color`, fillToCSS(fill) ?? '')+ if (color === undefined && layers.length === 0) color = value+ else layers.unshift({ image: `linear-gradient(${value}, ${value})`, blend })+ return+ }+ const gradient = gradientToCSS(fill, node.width, node.height)+ if (gradient) layers.unshift({ image: gradient, blend })+ // A paint below every colour, such as an image, leaves no colour for the bottom.+ else if (color === undefined) color = ''+ })+ if (layers.length > 0) {+ style['background-image'] = layers.map((layer) => layer.image).join(', ')+ if (layers.some((layer) => layer.blend !== 'normal')) {+ style['background-blend-mode'] = layers.map((layer) => layer.blend).join(', ')+ }+ }+ if (color) style['background-color'] = color+}++/**+ * A fill's blend mode as `background-blend-mode` takes it, which has no `plus-` modes: linear+ * burn and dodge blend normally there.+ */+function layerBlendMode(mode: Fill['blendMode']): string {+ const css = mode ? CSS_BLEND_MODE[mode] : undefined+ return css && !css.startsWith('plus-') ? css : 'normal'+}+function addImageStyle(style: DesignStyleDeclaration, node: SceneNode): void {const fill = node.fills.at(0)if (fill?.type !== 'IMAGE' || !fill.visible || shaderOfPaint(node, fill)) return@@ -315,8 +359,7 @@ function styleFromSceneNode(addSize(style, node, parent, css)addPositioning(style, node, parent)addSizeConstraints(style, node, css)- const fill = fillToCSS(node.fills.at(0))- if (fill) style['background-color'] = css('fills/0/color', fill)+ addBackground(style, node, css)addImageStyle(style, node)addStroke(style, node, css)Object.assign(style, effectsToCSS(node.effects))@@ -461,10 +504,14 @@ function sceneNodeToDesignNode(const entered = tokens?.enter(node, inherited, root)const modes = entered?.modes ?? inheritedconst attrs = { ...attrsForNode(graph, node, includeSourceIds), ...entered?.attrs }- const css: FieldCSS = (field, literal) => tokens?.reference(node, field, modes) ?? literal+ // A bound paint keeps the colour it was set with; the canvas draws its variable's value, so+ // the styles do too, and a token reference then matches what is drawn.+ const paints = resolvedPaintBindings(graph, node)+ const drawn = paints.fills || paints.strokes ? { ...node, ...paints } : node+ const css: FieldCSS = (field, literal) => tokens?.reference(drawn, field, modes) ?? literalif (node.type === 'TEXT') {- const content = textElementContent(node, styleFromTextNode(node, parent, css))+ const content = textElementContent(drawn, styleFromTextNode(drawn, parent, css))return {type: 'element',tagName: content.tagName,@@ -478,7 +525,7 @@ function sceneNodeToDesignNode(// An icon is one drawing, however many paths it has.if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {- const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css))+ const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(drawn, parent, css))if (vector) return vector}@@ -497,7 +544,7 @@ function sceneNodeToDesignNode(}}- const style = styleFromSceneNode(node, parent, css)+ const style = styleFromSceneNode(drawn, parent, css)const shader = layerShader(graph, node)if (shader) addShaderLayerStyle(style)return {@@ -547,16 +594,26 @@ export function sceneNodeToDesignDocument(nodeId: string,options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}): DesignDocument {- const node = graph.getNode(nodeId)+ return sceneNodesToDesignDocument(graph, [nodeId], options)+}++/**+ * Project several nodes, each with its own box, as one document: the tokens any of them+ * references are the document's, so its stylesheet defines them all.+ */+export function sceneNodesToDesignDocument(+ graph: SceneGraph,+ nodeIds: readonly string[],+ options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}+): DesignDocument {const context = projectionContext(graph, options)const modes = context.tokens?.defaultModes() ?? new Map<string, string>()- const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null- return {- type: 'document',- sourceGraph: graph,- tokens: context.tokens,- children: projected ? [projected] : []- }+ const children = nodeIds.flatMap((id) => {+ const node = graph.getNode(id)+ const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null+ return projected ? [projected] : []+ })+ return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }}export type { SceneGraphToDesignOptions as ToDesignDocumentOptions }diff --git a/packages/dom-css/tests/export/projection.test.ts b/packages/dom-css/tests/export/projection.test.tsindex 7c5b45b7a..5ff3d08a3 100644--- a/packages/dom-css/tests/export/projection.test.ts+++ b/packages/dom-css/tests/export/projection.test.ts@@ -5,7 +5,7 @@ import {type DesignElement,type DesignNode} from '@open-pencil/dom-css/export'-import { SceneGraph } from '@open-pencil/scene-graph'+import { SceneGraph, type Fill } from '@open-pencil/scene-graph'function element(node: DesignNode | undefined): DesignElement {if (node?.type !== 'element') throw new Error('Expected an element')@@ -78,4 +78,111 @@ describe('DOM projection sizes', () => {expect(title.inlineStyle?.height).toBeUndefined()expect(dot.inlineStyle).toMatchObject({ width: '20px', 'border-radius': '50%' })})++ test('paints every visible fill, the top one first, the lowest colour as the background colour', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const identity = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ const stops = [+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }+ ]+ const solid = (r: number, g: number, b: number, opacity = 1): Fill => ({+ type: 'SOLID',+ color: { r, g, b, a: 1 },+ opacity,+ visible: true+ })+ const gradient = (type: 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR'): Fill => ({+ ...solid(0, 0, 0),+ type,+ gradientTransform: identity,+ gradientStops: stops+ })+ const style = (fills: Fill[]) => {+ const node = graph.createNode('RECTANGLE', page.id, { width: 40, height: 20, fills })+ return element(sceneNodeToDesignDocument(graph, node.id).children[0]).inlineStyle+ }++ expect(style([gradient('GRADIENT_LINEAR')])).toMatchObject({+ 'background-image': 'linear-gradient(90deg, #FF0000 0%, #0000FF 100%)'+ })+ expect(style([gradient('GRADIENT_RADIAL')])?.['background-image']).toBe(+ 'radial-gradient(50% 50% at 50% 50%, #FF0000 0%, #0000FF 100%)'+ )+ expect(style([gradient('GRADIENT_ANGULAR')])?.['background-image']).toBe(+ 'conic-gradient(from 90deg at 50% 50%, #FF0000 0%, #0000FF 100%)'+ )+ // A colour above another fill can only stack as an image of itself.+ expect(style([solid(1, 0, 0), solid(0, 0, 1, 0.5)])).toMatchObject({+ 'background-image': 'linear-gradient(rgba(0, 0, 255, 0.5), rgba(0, 0, 255, 0.5))',+ 'background-color': '#FF0000'+ })+ expect(style([solid(1, 1, 1), gradient('GRADIENT_LINEAR')])).toMatchObject({+ 'background-image': 'linear-gradient(90deg, #FF0000 0%, #0000FF 100%)',+ 'background-color': '#FFFFFF'+ })+ const single = style([solid(1, 0, 0)])+ expect(single?.['background-color']).toBe('#FF0000')+ expect(single?.['background-image']).toBeUndefined()+ })++ test('puts a linear gradient’s stops where the canvas draws them on CSS’s gradient line', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const stops = [+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }+ ]+ const style = (gradientTransform: Fill['gradientTransform']) => {+ const fill: Fill = {+ type: 'GRADIENT_LINEAR',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ gradientTransform,+ gradientStops: stops+ }+ const node = graph.createNode('RECTANGLE', page.id, {+ width: 200,+ height: 100,+ fills: [fill]+ })+ return element(sceneNodeToDesignDocument(graph, node.id).children[0]).inlineStyle?.[+ 'background-image'+ ]+ }+ // Handles across the middle half of the box: the colours change across that half only.+ expect(style({ m00: 2, m01: 0, m02: -0.5, m10: 0, m11: 1, m12: 0 })).toBe(+ 'linear-gradient(90deg, #FF0000 25%, #0000FF 75%)'+ )+ // Handles from corner to corner of a wide box run the whole CSS line.+ expect(style({ m00: 0.5, m01: 0.5, m02: 0, m10: -0.5, m11: 0.5, m12: 0.5 })).toBe(+ 'linear-gradient(116.565deg, #FF0000 0%, #0000FF 100%)'+ )+ })++ test('blends each stacked fill as the canvas does', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const solid = (r: number, g: number, b: number, blendMode?: Fill['blendMode']): Fill => ({+ type: 'SOLID',+ color: { r, g, b, a: 1 },+ opacity: 1,+ visible: true,+ blendMode+ })+ const node = graph.createNode('RECTANGLE', page.id, {+ width: 40,+ height: 20,+ fills: [solid(1, 1, 0), solid(0, 1, 1, 'MULTIPLY'), solid(1, 0, 1)]+ })+ expect(+ element(sceneNodeToDesignDocument(graph, node.id).children[0]).inlineStyle+ ).toMatchObject({+ 'background-image': 'linear-gradient(#FF00FF, #FF00FF), linear-gradient(#00FFFF, #00FFFF)',+ 'background-blend-mode': 'normal, multiply',+ 'background-color': '#FFFF00'+ })+ })})diff --git a/packages/dom-css/tests/export/projection/tokens.test.ts b/packages/dom-css/tests/export/projection/tokens.test.tsindex a3e9fd289..caf45f9f3 100644--- a/packages/dom-css/tests/export/projection/tokens.test.ts+++ b/packages/dom-css/tests/export/projection/tokens.test.ts@@ -32,11 +32,17 @@ describe('token references in design-to-code', () => {expect(attrs).not.toHaveProperty('data-theme')})- test('keeps the literal value where the node no longer draws the token', () => {+ test('writes the colour the canvas draws for a bound paint, whatever colour the paint keeps', () => {+ // A script binding a paint keeps the colour it gave; the canvas draws the variable's value.const graph = designSystem()- const frame = card(graph, graph.getPages()[0].id, BLUE_300)-- expect(element(graph, frame.id).inlineStyle?.['background-color']).toBe('#94C4FC')+ const page = graph.getPages()[0].id+ const stale = card(graph, page, BLUE_300)+ const current = card(graph, page, BLUE_500)++ expect(element(graph, stale.id).inlineStyle?.['background-color']).toBe('var(--color-primary)')+ expect(element(graph, stale.id, false).inlineStyle?.['background-color']).toBe(+ element(graph, current.id, false).inlineStyle?.['background-color']+ )})test('keeps a length literal when the token is unitless', () => {diff --git a/packages/scene-graph/src/css/blend.ts b/packages/scene-graph/src/css/blend.tsnew file mode 100644index 000000000..23b6d82ca--- /dev/null+++ b/packages/scene-graph/src/css/blend.ts@@ -0,0 +1,27 @@+import type { BlendMode } from '../types'++/**+ * Each blend mode as CSS names it, for `mix-blend-mode` and `background-blend-mode`. Linear+ * burn and linear dodge are the `plus-` modes, which `mix-blend-mode` takes and+ * `background-blend-mode` does not.+ */+export const CSS_BLEND_MODE: Partial<Record<BlendMode, string>> = {+ NORMAL: 'normal',+ DARKEN: 'darken',+ MULTIPLY: 'multiply',+ COLOR_BURN: 'color-burn',+ LIGHTEN: 'lighten',+ LINEAR_BURN: 'plus-darker',+ SCREEN: 'screen',+ LINEAR_DODGE: 'plus-lighter',+ COLOR_DODGE: 'color-dodge',+ OVERLAY: 'overlay',+ SOFT_LIGHT: 'soft-light',+ HARD_LIGHT: 'hard-light',+ DIFFERENCE: 'difference',+ EXCLUSION: 'exclusion',+ HUE: 'hue',+ SATURATION: 'saturation',+ COLOR: 'color',+ LUMINOSITY: 'luminosity'+}diff --git a/packages/scene-graph/src/css/index.ts b/packages/scene-graph/src/css/index.tsindex 131734732..99d98bb5f 100644--- a/packages/scene-graph/src/css/index.ts+++ b/packages/scene-graph/src/css/index.ts@@ -1,3 +1,4 @@+export { CSS_BLEND_MODE } from './blend'export { parseCSSGridTracks } from './grid'export {parseCSSAlignItems,