AI-native design editor. Open-source Figma alternative.
fix(canvas): draw gradients in Figma's transform convention (#1039)
Danila Poyarkov20dc5269871b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f6596d337..00da15439 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- A paint's `gradientTransform` follows Figma's convention everywhere: it maps the layer's unit square onto gradient space, where a linear gradient runs from (0, 0.5) to (1, 0.5). Gradients made in OpenPencil before this release, which used the inverse, draw differently; code that builds gradients by hand should use `linearGradientTransform` and `ellipticalGradientTransform` from the new `@open-pencil/scene-graph/gradient`, which also has Figma's default transform and stops. `isGradientFill` and `GradientFillType` moved there from `@open-pencil/core/geometry`, and `linearGradientEndpoints` is removed from the canvas module.- `useStrokeControls` from `@open-pencil/vue` acts on the whole selection: `updateAlign`, `selectSide`, and `updateBorderWeight` no longer take a node, and `currentAlign()` and `borderWeight(side)` read the selection and return `MIXED` when it differs. `useEffectsControls().scrubEffect` and `commitEffect` no longer take a node. `useTypography` edits every selected text layer and adds `nodes`, `merged`, and `fontFeature`. The `panels.layersCount` message is now `panels.selectedCount`.- The app renders `render` JSX itself and no longer accepts the pre-rendered tree that earlier versions of `openpencil-mcp` send, so an older `openpencil-mcp` fails to render into this app version; update it with the app.- `VectorizedPath` from `@open-pencil/core/vector` replaces `clipNetworks` with `clips`, each the clip path's `id` and one network per clip shape, and adds `elements`, the groups and shape a path was drawn from. `SVGVectorizeResult` adds `texts`, the SVG's text placed in the target space, and `SVGImportData` from `@open-pencil/core/io` adds the root `name` and whether the SVG is `sized`.@@ -155,6 +156,7 @@### Fixed+- Gradients from Figma files and Figma pastes draw as they do in Figma: they ran backwards or sat in the wrong place unless they were symmetric, because the canvas applied Figma's gradient transform the wrong way round. SVG export and import keep a gradient exactly, and a new gradient starts as Figma's does, top to bottom from the fill colour to a darker shade, keeping its transform when switched between linear, radial, angular, and diamond.- Changing stroke position, per-side stroke weights, or an effect with several layers selected changes all of them, not only the first.- Draw layer blur, drop and inner shadows, and background blur with Figma's falloff. They spread about 15% too far, with a long faint edge Figma does not draw; SVG export keeps Figma's own `stdDeviation` of half the radius.- Load the fonts of SVG text before placing it from `import_svg`, so centred and right-aligned text sits where Figma puts it; `figma.loadFontAsync` in scripts now loads the font instead of doing nothing.diff --git a/packages/core/src/canvas/fills.ts b/packages/core/src/canvas/fills.tsindex a7f817c1d..ea3d201b7 100644--- a/packages/core/src/canvas/fills.ts+++ b/packages/core/src/canvas/fills.ts@@ -1,6 +1,7 @@import type { Canvas, Paint } from 'canvaskit-wasm'import type { SceneNode, SceneGraph, Fill } from '@open-pencil/scene-graph'+import { invertGradientTransform } from '@open-pencil/scene-graph/gradient'import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'import { figmaBlendModeToSkia } from './blend'@@ -280,39 +281,27 @@ function applyPatternFill(return true}+/** Gradient space to the layer's pixels: Figma's transform maps the other way, so it is inverted. */function makeGradientLocalMatrix(r: SkiaRenderer,width: number,height: number,transform: NonNullable<Fill['gradientTransform']>) {+ const t = invertGradientTransform(transform)return r.ck.Matrix.multiply(r.ck.Matrix.scaled(width, height), [- transform.m00,- transform.m01,- transform.m02,- transform.m10,- transform.m11,- transform.m12,+ t.m00,+ t.m01,+ t.m02,+ t.m10,+ t.m11,+ t.m12,0,0,1])}-export function linearGradientEndpoints(- width: number,- height: number,- transform: NonNullable<Fill['gradientTransform']>-) {- return {- start: {- x: (transform.m00 + transform.m02) * width,- y: (transform.m10 + transform.m12) * height- },- end: { x: transform.m02 * width, y: transform.m12 * height }- }-}-/** Resolves one gradient stop's color, so a stroke resolves its own bindings, not a fill's. */export type ResolveGradientStop = (color: Color, stopIndex: number) => Color@@ -352,25 +341,22 @@ export function applyGradientFill(}if (fill.type === 'GRADIENT_LINEAR') {- const { start, end } = linearGradientEndpoints(w, h, t)- const startX = start.x- const startY = start.y- const endX = end.x- const endY = end.y+ // Drawn in gradient space, so its bands follow the transform's second axis as in Figma+ // rather than running square to the line on a stretched layer.const shader = r.ck.Shader.MakeLinearGradient(- [startX, startY],- [endX, endY],+ [0, 0.5],+ [1, 0.5],colors,positions,- r.ck.TileMode.Clamp+ r.ck.TileMode.Clamp,+ makeGradientLocalMatrix(r, w, h, t))setShader(shader)} else if (fill.type === 'GRADIENT_DIAMOND') {setShader(makeDiamondGradient(r, colors, positions, makeGradientLocalMatrix(r, w, h, t)))} else if (fill.type === 'GRADIENT_RADIAL') {- // Figma's gradientTransform maps gradient space (center 0.5,0.5, radius 0.5)- // to the node's normalized [0,1] coordinate space. The full local matrix- // converts to pixel coordinates: scale(w, h) * gradientTransform.+ // Gradient space is centred on (0.5, 0.5) with radius 0.5; the local matrix takes it to the+ // layer's pixels.const localMatrix = makeGradientLocalMatrix(r, w, h, t)const shader = r.ck.Shader.MakeRadialGradient([0.5, 0.5],diff --git a/packages/core/src/editor/gradient-edit.ts b/packages/core/src/editor/gradient-edit.tsindex 29c29c271..c57a26437 100644--- a/packages/core/src/editor/gradient-edit.ts+++ b/packages/core/src/editor/gradient-edit.ts@@ -1,9 +1,9 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { isGradientFill } from '@open-pencil/scene-graph/gradient'import {createSceneGeometry,gradientHandleLayout,- isGradientFill,type GradientHandleLayout,type RotationPreview,type ViewportTransformdiff --git a/packages/core/src/geometry/gradient.ts b/packages/core/src/geometry/gradient.tsindex 2c1161fc0..518c9988d 100644--- a/packages/core/src/geometry/gradient.ts+++ b/packages/core/src/geometry/gradient.ts@@ -1,16 +1,18 @@-import type { Fill, GradientStop, GradientTransform, Vector } from '@open-pencil/scene-graph'+import type { GradientStop, GradientTransform, Vector } from '@open-pencil/scene-graph'+import {+ applyGradientTransform,+ ellipticalGradientTransform,+ invertGradientTransform,+ linearGradientTransform,+ type GradientFillType+} from '@open-pencil/scene-graph/gradient'/**- * On-canvas gradient handles, as Figma desktop 126 draws and drags them. A gradient's transform- * maps gradient space into the layer's unit square; a linear gradient runs from (1, 0) to (0, 0)- * of gradient space, the others are centred on (0.5, 0.5) with radius 0.5.+ * On-canvas gradient handles, as Figma desktop 126 draws and drags them, built on the paint+ * convention in `@open-pencil/scene-graph/gradient`.*/export type GradientHandle = 'start' | 'end' | 'center' | 'radius-x' | 'radius-y'-export type GradientFillType = Extract<- Fill['type'],- 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND'->export interface GradientHandles {start: Vector@@ -23,20 +25,10 @@ export interface GradientHandles {/** Figma's 15° steps while Shift is held. */const SNAP_ANGLE = Math.PI / 12-export function isGradientFill(type: Fill['type']): type is GradientFillType {- return (- type === 'GRADIENT_LINEAR' ||- type === 'GRADIENT_RADIAL' ||- type === 'GRADIENT_ANGULAR' ||- type === 'GRADIENT_DIAMOND'- )-}--function point(t: GradientTransform, width: number, height: number, x: number, y: number) {- return {- x: (t.m00 * x + t.m01 * y + t.m02) * width,- y: (t.m10 * x + t.m11 * y + t.m12) * height- }+/** Where a point of gradient space falls in a `width` × `height` layer. */+function point(toLayer: GradientTransform, width: number, height: number, x: number, y: number) {+ const unit = applyGradientTransform(toLayer, { x, y })+ return { x: unit.x * width, y: unit.y * height }}/** The handles in the layer's own pixels. */@@ -46,17 +38,18 @@ export function gradientHandles(width: number,height: number): GradientHandles {+ const toLayer = invertGradientTransform(t)if (type === 'GRADIENT_LINEAR') {- const start = point(t, width, height, 1, 0)- const end = point(t, width, height, 0, 0)+ const start = point(toLayer, width, height, 0, 0.5)+ const end = point(toLayer, width, height, 1, 0.5)return { start, end, center: { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 } }}- const center = point(t, width, height, 0.5, 0.5)+ const center = point(toLayer, width, height, 0.5, 0.5)return {start: center,- end: point(t, width, height, 1, 0.5),+ end: point(toLayer, width, height, 1, 0.5),center,- radiusY: point(t, width, height, 0.5, 1)+ radiusY: point(toLayer, width, height, 0.5, 1)}}@@ -70,7 +63,13 @@ export function gradientStopPoint(): Vector {if (type === 'GRADIENT_ANGULAR') {const angle = position * 2 * Math.PI- return point(t, width, height, 0.5 + 0.5 * Math.cos(angle), 0.5 + 0.5 * Math.sin(angle))+ return point(+ invertGradientTransform(t),+ width,+ height,+ 0.5 + 0.5 * Math.cos(angle),+ 0.5 + 0.5 * Math.sin(angle)+ )}const { start, end } = gradientHandles(type, t, width, height)return { x: start.x + (end.x - start.x) * position, y: start.y + (end.y - start.y) * position }@@ -85,13 +84,9 @@ export function gradientStopPosition(local: Vector): number {if (type === 'GRADIENT_ANGULAR') {- const det = t.m00 * t.m11 - t.m01 * t.m10- if (Math.abs(det) < 1e-12 || width <= 0 || height <= 0) return 0- const ux = local.x / width - t.m02- const uy = local.y / height - t.m12- const gx = (t.m11 * ux - t.m01 * uy) / det- const gy = (-t.m10 * ux + t.m00 * uy) / det- const turn = Math.atan2(gy - 0.5, gx - 0.5) / (2 * Math.PI)+ if (width <= 0 || height <= 0) return 0+ const g = applyGradientTransform(t, { x: local.x / width, y: local.y / height })+ const turn = Math.atan2(g.y - 0.5, g.x - 0.5) / (2 * Math.PI)return turn < 0 ? turn + 1 : turn}const { start, end } = gradientHandles(type, t, width, height)@@ -112,6 +107,10 @@ function snapDirection(origin: Vector, position: Vector, snap: boolean): Vectorreturn { x: origin.x + Math.cos(angle) * length, y: origin.y + Math.sin(angle) * length }}+function unit(p: Vector, width: number, height: number): Vector {+ return { x: p.x / width, y: p.y / height }+}+/*** The transform after dragging one handle to a point in the layer's pixels. Only that handle* moves, exactly with the pointer; Shift turns its direction in 15° steps and keeps its length.@@ -128,25 +127,29 @@ export function moveGradientHandle(if (width <= 0 || height <= 0) return originalconst handles = gradientHandles(type, original, width, height)if (handle === 'center') {+ // Moving the centre slides the whole gradient: gradient space shifts the other way.+ const dx = (position.x - handles.center.x) / width+ const dy = (position.y - handles.center.y) / heightreturn {...original,- m02: original.m02 + (position.x - handles.center.x) / width,- m12: original.m12 + (position.y - handles.center.y) / height+ m02: original.m02 - (original.m00 * dx + original.m01 * dy),+ m12: original.m12 - (original.m10 * dx + original.m11 * dy)}}if (type === 'GRADIENT_LINEAR') {const start = handle === 'start' ? snapDirection(handles.end, position, snap) : handles.startconst end = handle === 'end' ? snapDirection(handles.start, position, snap) : handles.endif (Math.hypot(start.x - end.x, start.y - end.y) < 0.001) return original- return {- ...original,- m00: (start.x - end.x) / width,- m10: (start.y - end.y) / height,- m01: -(start.y - end.y) / height,- m11: (start.x - end.x) / width,- m02: end.x / width,- m12: end.y / height- }+ const toLayer = invertGradientTransform(original)+ const along = Math.hypot(toLayer.m00 * width, toLayer.m10 * height)+ const across = Math.hypot(toLayer.m01 * width, toLayer.m11 * height)+ return linearGradientTransform(+ unit(start, width, height),+ unit(end, width, height),+ width,+ height,+ along > 1e-9 ? across / along : height / width+ )}const center = handles.centerlet radiusX = handles.end@@ -166,19 +169,16 @@ export function moveGradientHandle(} else if (handle === 'radius-y') {radiusY = snapDirection(center, position, snap)}- const m00 = (2 * (radiusX.x - center.x)) / width- const m10 = (2 * (radiusX.y - center.y)) / height- const m01 = (2 * (radiusY.x - center.x)) / width- const m11 = (2 * (radiusY.y - center.y)) / height- if (Math.abs(m00 * m11 - m01 * m10) < 1e-8) return original- return {- m00,- m01,- m10,- m11,- m02: center.x / width - (m00 + m01) / 2,- m12: center.y / height - (m10 + m11) / 2- }+ const ax = radiusX.x - center.x+ const ay = radiusX.y - center.y+ const bx = radiusY.x - center.x+ const by = radiusY.y - center.y+ if (Math.abs(ax * by - ay * bx) < 1e-6) return original+ return ellipticalGradientTransform(+ unit(center, width, height),+ unit(radiusX, width, height),+ unit(radiusY, width, height)+ )}/** Screen-pixel sizes of the handles, measured on Figma desktop 126. */diff --git a/packages/core/src/geometry/index.ts b/packages/core/src/geometry/index.tsindex 26f5c6fd6..a5fe34cab 100644--- a/packages/core/src/geometry/index.ts+++ b/packages/core/src/geometry/index.ts@@ -24,11 +24,9 @@ export {gradientStopPoint,gradientStopPosition,hitTestGradientHandles,- isGradientFill,moveGradientHandle} from './gradient'export type {- GradientFillType,GradientHandle,GradientHandleLayout,GradientHandles,diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.tsindex 504e5e1bd..f475522cd 100644--- a/packages/core/src/io/formats/svg/defs.ts+++ b/packages/core/src/io/formats/svg/defs.ts@@ -7,6 +7,11 @@ import {getDefaultRenderColorSpace,type RenderColorSpace} from '@open-pencil/scene-graph/color'+import {+ gradientPoint,+ invertGradientTransform,+ isIdentityGradientTransform+} from '@open-pencil/scene-graph/gradient'import type { Color } from '@open-pencil/scene-graph/primitives'import { svg, type SVGNode } from './node'@@ -58,45 +63,55 @@ function createGradientDef(const id = nextDefId(ctx, 'grad')+ // Gradient space in bounding-box units, mapped onto the layer as the canvas draws it.+ const toLayer = invertGradientTransform(t)+ const transform = isIdentityGradientTransform(toLayer)+ ? undefined+ : `matrix(${[toLayer.m00, toLayer.m10, toLayer.m01, toLayer.m11, toLayer.m02, toLayer.m12].map((v) => round(v, 6)).join(' ')})`+if (fill.type === 'GRADIENT_LINEAR') {- const startX = round(t.m02 * 100)- const startY = round(t.m12 * 100)- const endX = round((t.m00 + t.m02) * 100)- const endY = round((t.m10 + t.m12) * 100)return {id,node: svg('linearGradient',{id,- x1: `${startX}%`,- y1: `${startY}%`,- x2: `${endX}%`,- y2: `${endY}%`,- gradientUnits: 'objectBoundingBox'+ x1: 0,+ y1: 0.5,+ x2: 1,+ y2: 0.5,+ gradientUnits: 'objectBoundingBox',+ gradientTransform: transform},...stopNodes)}}+ // SVG has no diamond gradient, so a diamond exports as the radial one it is closest to.if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {- const cx = round(t.m02 * 100)- const cy = round(t.m12 * 100)- const r = round(Math.hypot(t.m00, t.m10) * 100)return {id,node: svg('radialGradient',- { id, cx: `${cx}%`, cy: `${cy}%`, r: `${r}%`, gradientUnits: 'objectBoundingBox' },+ {+ id,+ cx: 0.5,+ cy: 0.5,+ r: 0.5,+ gradientUnits: 'objectBoundingBox',+ gradientTransform: transform+ },...stopNodes)}}+ // Nor an angular one: it exports as a radial gradient around its centre.if (fill.type === 'GRADIENT_ANGULAR') {- const cx = round(t.m02 * node.width)- const cy = round(t.m12 * node.height)+ const center = gradientPoint(t, { x: 0.5, y: 0.5 })+ const cx = round(center.x * node.width)+ const cy = round(center.y * node.height)const r = Math.max(node.width, node.height)return {id,diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.tsindex 75197858c..df61a2d35 100644--- a/packages/core/src/tools/modify/paint.ts+++ b/packages/core/src/tools/modify/paint.ts@@ -2,7 +2,8 @@ import { isValid, toUint8Array } from 'js-base64'import * as v from 'valibot'import { parseColor } from '@open-pencil/scene-graph/color'-import type { Matrix } from '@open-pencil/scene-graph/primitives'+import { linearGradientTransform } from '@open-pencil/scene-graph/gradient'+import type { Vector } from '@open-pencil/scene-graph/primitives'import { BLACK } from '#core/constants'import { toolNumber, nodeIdInput } from '#core/tools/input'@@ -35,12 +36,26 @@ export const setFill = defineTool({if (gradient && color_end) {const cEnd = parseColor(color_end)- const transforms: Record<string, Matrix> = {- 'top-bottom': { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 },- 'bottom-top': { m00: 0, m01: -1, m02: 1, m10: 1, m11: 0, m12: 0 },- 'left-right': { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },- 'right-left': { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 1 }+ // Edge middles of the layer's unit square that each direction runs between.+ const ends: Record<string, [Vector, Vector]> = {+ 'top-bottom': [+ { x: 0.5, y: 0 },+ { x: 0.5, y: 1 }+ ],+ 'bottom-top': [+ { x: 0.5, y: 1 },+ { x: 0.5, y: 0 }+ ],+ 'left-right': [+ { x: 0, y: 0.5 },+ { x: 1, y: 0.5 }+ ],+ 'right-left': [+ { x: 1, y: 0.5 },+ { x: 0, y: 0.5 }+ ]}+ const [start, end] = ends[gradient] ?? ends['top-bottom']node.fills = [{type: 'GRADIENT_LINEAR',@@ -51,7 +66,7 @@ export const setFill = defineTool({{ position: 0, color: c },{ position: 1, color: cEnd }],- gradientTransform: transforms[gradient] ?? transforms['top-bottom']+ gradientTransform: linearGradientTransform(start, end)}]return { id, gradient, start: c, end: cEnd }diff --git a/packages/core/src/vector/vectorize/svg/gradients.ts b/packages/core/src/vector/vectorize/svg/gradients.tsindex 56c831783..0e89e87f0 100644--- a/packages/core/src/vector/vectorize/svg/gradients.ts+++ b/packages/core/src/vector/vectorize/svg/gradients.ts@@ -6,16 +6,20 @@* flat colors. Without this, those paths fall back to the default solid color* (black). Gradient geometry is given in userSpaceOnUse viewBox coordinates; we* map the endpoints through the same transform pipeline as the path data, then- * normalize into each node's bounding box (objectBoundingBox) space, matching the- * gradientTransform convention used by the SVG exporter (see io/formats/svg/defs).+ * normalize into each node's bounding box and build the transform in Figma's convention+ * (see geometry/gradient).*/import type { Fill, GradientStop } from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'-import type { Color, Matrix, Rect, Vector } from '@open-pencil/scene-graph/primitives'+import {+ ellipticalGradientTransform,+ linearGradientTransformFromAxes+} from '@open-pencil/scene-graph/gradient'+import type { Color, Rect, Vector } from '@open-pencil/scene-graph/primitives'import { parseSVGDocument } from '#core/io/formats/svg/document'-import { mapSVGPointToViewport, type SVGViewportMapping } from './transform'+import { mapSVGPointToViewport, transformSVGPoint, type SVGViewportMapping } from './transform'interface RawStop {offset: number@@ -142,10 +146,17 @@ export function resolveGradientFill(if (nodeBounds.width <= 0 || nodeBounds.height <= 0) return nullconst toLocal = (px: number, py: number): Vector => {- const mapped =- grad.units === 'objectBoundingBox'- ? { x: nodeBounds.x + px * nodeBounds.width, y: nodeBounds.y + py * nodeBounds.height }- : mapSVGPointToViewport(px, py, elementTransform, grad.transform, viewport)+ let mapped: Vector+ if (grad.units === 'objectBoundingBox') {+ // The gradient's own transform works in bounding-box units here.+ const box = transformSVGPoint(px, py, grad.transform)+ mapped = {+ x: nodeBounds.x + box.x * nodeBounds.width,+ y: nodeBounds.y + box.y * nodeBounds.height+ }+ } else {+ mapped = mapSVGPointToViewport(px, py, elementTransform, grad.transform, viewport)+ }return {x: (mapped.x - nodeBounds.x) / nodeBounds.width,y: (mapped.y - nodeBounds.y) / nodeBounds.height@@ -159,14 +170,7 @@ export function resolveGradientFill(const center = toLocal(grad.cx, grad.cy)const edgeX = toLocal(grad.cx + grad.r, grad.cy)const edgeY = toLocal(grad.cx, grad.cy + grad.r)- const transform: Matrix = {- m00: edgeX.x - center.x,- m01: edgeY.x - center.x,- m02: center.x,- m10: edgeX.y - center.y,- m11: edgeY.y - center.y,- m12: center.y- }+ const transform = ellipticalGradientTransform(center, edgeX, edgeY)return {type: 'GRADIENT_RADIAL',color: baseColor,@@ -179,16 +183,13 @@ export function resolveGradientFill(const start = toLocal(grad.x1, grad.y1)const end = toLocal(grad.x2, grad.y2)- const ax = end.x - start.x- const ay = end.y - start.y- const transform: Matrix = {- m00: ax,- m01: -ay,- m02: start.x,- m10: ay,- m11: ax,- m12: start.y- }+ // SVG bands run square to the line in the gradient's own units; mapping a square step through+ // the same transforms keeps them where SVG draws them.+ const acrossEnd = toLocal(grad.x1 - (grad.y2 - grad.y1), grad.y1 + (grad.x2 - grad.x1))+ const transform = linearGradientTransformFromAxes(start, end, {+ x: acrossEnd.x - start.x,+ y: acrossEnd.y - start.y+ })return {type: 'GRADIENT_LINEAR',color: baseColor,diff --git a/packages/core/src/vector/vectorize/svg/transform.ts b/packages/core/src/vector/vectorize/svg/transform.tsindex a9717a5ad..2cf8d4b7b 100644--- a/packages/core/src/vector/vectorize/svg/transform.ts+++ b/packages/core/src/vector/vectorize/svg/transform.ts@@ -58,6 +58,19 @@ export function mapSVGPathToViewport(d: string, mapping: SVGViewportMapping): st.toString()}+/** A point through an SVG transform attribute, such as a gradient's own transform. */+export function transformSVGPoint(x: number, y: number, transform: string | null): Vector {+ if (!transform) return { x, y }+ let point: Vector = { x, y }+ svgpath(`M${x} ${y}`)+ .transform(transform)+ .abs()+ .iterate((segment) => {+ if (segment[0] === 'M') point = { x: segment[1], y: segment[2] }+ })+ return point+}+export function mapSVGPointToViewport(x: number,y: number,diff --git a/packages/core/tests/geometry/gradient.test.ts b/packages/core/tests/geometry/gradient.test.tsindex 68e80b6da..5fe2d15a6 100644--- a/packages/core/tests/geometry/gradient.test.ts+++ b/packages/core/tests/geometry/gradient.test.ts@@ -9,8 +9,9 @@ import {} from '#core/geometry'import type { Vector } from '@open-pencil/scene-graph'-// A 200 × 140 layer with a linear gradient from its left edge's middle to its right edge's middle.-const LEFT_TO_RIGHT = { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 0.5 }+// A 200 × 140 layer with a linear gradient from its left edge's middle to its right edge's middle:+// Figma's identity transform.+const LEFT_TO_RIGHT = { 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: 0.5, color: { r: 1, g: 1, b: 0, a: 1 } },@@ -40,6 +41,19 @@ describe('gradient handles', () => {close(handles.end, { x: 200, y: 10 })})+ // Figma desktop 126, a 400 × 120 layer: dragging the end of a left-to-right gradient to+ // (300, 120) gave this transform, keeping the second axis square to the line on screen.+ test('a dragged end keeps the second axis as Figma does', () => {+ const moved = moveGradientHandle('GRADIENT_LINEAR', LEFT_TO_RIGHT, 400, 120, 'end', {+ x: 300,+ y: 120+ })+ const figma = [1.2820513, 0.0769231, -0.0384615, -0.8547009, 1.2820513, -0.1410256]+ expect([moved.m00, moved.m01, moved.m02, moved.m10, moved.m11, moved.m12].map((v) => +v.toFixed(5))).toEqual(+ figma.map((v) => +v.toFixed(5))+ )+ })+// Figma desktop 126: the pointer at −10.2° from the start lands on −15°, at the pointer's distance.test('Shift turns an end in 15° steps and keeps its distance', () => {const pointer = { x: 195.5, y: 35 }@@ -88,11 +102,11 @@ describe('gradient handles', () => {const above = gradientHandleLayout('GRADIENT_LINEAR', LEFT_TO_RIGHT, STOPS, 200, 140, screen)expect(above.stops[1]?.center.y).toBeLessThan(70)// Its first stop at the right edge and its last at the left.- const reversed = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0.5 }+ const reversed = { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 1 }const below = gradientHandleLayout('GRADIENT_LINEAR', reversed, STOPS, 200, 140, screen)expect(below.stops[1]?.center.y).toBeGreaterThan(70)// Its first stop at the top edge and its last at the bottom.- const downward = { m00: 0, m01: 1, m02: 0.5, m10: -1, m11: 0, m12: 1 }+ const downward = { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }const right = gradientHandleLayout('GRADIENT_LINEAR', downward, STOPS, 200, 140, screen)expect(right.stops[1]?.center.x).toBeGreaterThan(100)})diff --git a/packages/design-jsx/src/export/paint.ts b/packages/design-jsx/src/export/paint.tsindex f16aa6895..93f72f061 100644--- a/packages/design-jsx/src/export/paint.ts+++ b/packages/design-jsx/src/export/paint.ts@@ -1,4 +1,5 @@import type { Effect, Fill, GradientTransform, SceneNode, Stroke } from '@open-pencil/scene-graph'+import { isIdentityGradientTransform } from '@open-pencil/scene-graph/gradient'import { formatColor, formatShadow } from './helpers'import { helperCall, plainValue, type HelperCall, type JSXProp, type JSXValue } from './value'@@ -10,13 +11,8 @@ const GRADIENT_HELPERS: Partial<Record<Fill['type'], string>> = {GRADIENT_DIAMOND: 'diamondGradient'}-const IDENTITY_TRANSFORM: GradientTransform = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }-function isIdentity(transform: GradientTransform | undefined): boolean {- if (!transform) return true- return (Object.keys(IDENTITY_TRANSFORM) as (keyof GradientTransform)[]).every(- (key) => transform[key] === IDENTITY_TRANSFORM[key]- )+ return !transform || isIdentityGradientTransform(transform)}/** Paints and effects imported from Figma often spell out the default blend mode. */diff --git a/packages/design-jsx/src/paints.ts b/packages/design-jsx/src/paints.tsindex d7029f0b0..e93f54b95 100644--- a/packages/design-jsx/src/paints.ts+++ b/packages/design-jsx/src/paints.ts@@ -9,6 +9,7 @@ import type {} from '@open-pencil/scene-graph'import { colorToFill, parseColor } from '@open-pencil/scene-graph/color'import { TRANSPARENT } from '@open-pencil/scene-graph/constants'+import { IDENTITY_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'import type { Color } from '@open-pencil/scene-graph/primitives'import { parseScriptInput } from './validation'@@ -26,15 +27,6 @@ export interface GradientPaintOptions extends SolidPaintOptions {transform?: GradientTransform}-const DEFAULT_GRADIENT_TRANSFORM: GradientTransform = {- m00: 1,- m01: 0,- m02: 0,- m10: 0,- m11: 1,- m12: 0-}-const colorSchema = v.union([v.string(),v.object({ r: v.number(), g: v.number(), b: v.number(), a: v.number() })@@ -100,7 +92,7 @@ export function gradient(visible: options.visible ?? true,blendMode: options.blendMode,gradientStops: parseStops(type, stops).map(toStop),- gradientTransform: options.transform ?? DEFAULT_GRADIENT_TRANSFORM+ gradientTransform: options.transform ?? { ...IDENTITY_GRADIENT_TRANSFORM }}}diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 0795bff39..f1b256ff7 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -17,7 +17,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Paint, text, and artwork-- `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]])]}`.+- `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]])]}`. Without a `transform` a linear gradient runs left to right and the others are centred; `transform` is Figma's `gradientTransform`, mapping the layer's unit square onto gradient space.- `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` 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.diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 851b26cd2..c9197f51f 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -19,7 +19,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Paint, text, and artwork-- `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]])]}`.+- `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]])]}`. Without a `transform` a linear gradient runs left to right and the others are centred; `transform` is Figma's `gradientTransform`, mapping the layer's unit square onto gradient space.- `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` 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.diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.mdindex 57f338ead..059f57db2 100644--- a/packages/scene-graph/AGENTS.md+++ b/packages/scene-graph/AGENTS.md@@ -20,4 +20,5 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.- Export named types and primitives (`Color`, `Vector`, `Rect`, `SceneNode`, `Effect`, `Fill`, `Stroke`) from the public entry; downstream packages reuse them instead of respelling shapes.+- A paint's `gradientTransform` follows Figma's convention, mapping the layer's unit square onto gradient space; read, build, and invert it only through `@open-pencil/scene-graph/gradient`, which renderers, handles, exporters, importers, and tools all share (`packages/scene-graph/tests/gradient.test.ts`, `tests/engine/render/canvas/gradient.test.ts`).- `Stroke` extends `Fill`, so a stroke is a paint plus its geometry; add a paint field to `Fill` and both get it, and copy it in `copyFill`, which `copyStroke` reuses (`packages/scene-graph/src/copy.ts`).diff --git a/packages/scene-graph/package.json b/packages/scene-graph/package.jsonindex a4f328fee..377690827 100644--- a/packages/scene-graph/package.json+++ b/packages/scene-graph/package.json@@ -167,6 +167,12 @@"import": "./dist/resize.js","default": "./dist/resize.js"},+ "./gradient": {+ "types": "./dist/gradient.d.ts",+ "bun": "./src/gradient.ts",+ "import": "./dist/gradient.js",+ "default": "./dist/gradient.js"+ },"./random": {"types": "./dist/random.d.ts","bun": "./src/random.ts",diff --git a/packages/scene-graph/src/gradient.ts b/packages/scene-graph/src/gradient.tsnew file mode 100644index 000000000..46db9f386--- /dev/null+++ b/packages/scene-graph/src/gradient.ts@@ -0,0 +1,166 @@+import type { Color, Vector } from './primitives'+import type { Fill, GradientStop, GradientTransform } from './types'++/**+ * Gradient paints in Figma's convention. A paint's `gradientTransform` maps the layer's unit+ * square to gradient space, as Figma's plugin API, `.fig` files, and the clipboard store it. In+ * gradient space a linear gradient runs from (0, 0.5) to (1, 0.5); radial, angular, and diamond+ * gradients are centred on (0.5, 0.5) with radius 0.5, and an angular one starts at +x and turns+ * clockwise. Every reader and writer of gradients goes through this module.+ */++export type GradientFillType = Extract<+ Fill['type'],+ 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND'+>++export function isGradientFill(type: Fill['type']): type is GradientFillType {+ return (+ type === 'GRADIENT_LINEAR' ||+ type === 'GRADIENT_RADIAL' ||+ type === 'GRADIENT_ANGULAR' ||+ type === 'GRADIENT_DIAMOND'+ )+}++/** Left to right for a linear gradient; centred and filling the layer for the others. */+export const IDENTITY_GRADIENT_TRANSFORM: GradientTransform = {+ m00: 1,+ m01: 0,+ m02: 0,+ m10: 0,+ m11: 1,+ m12: 0+}++/**+ * Figma's transform when a fill becomes a gradient: top to bottom, and centred when switched to+ * another kind (Figma desktop 126).+ */+export const DEFAULT_GRADIENT_TRANSFORM: GradientTransform = {+ m00: 0,+ m01: 1,+ m02: 0,+ m10: -1,+ m11: 0,+ m12: 1+}++/** How dark a new gradient's second stop is next to the fill colour, as in Figma. */+const DEFAULT_GRADIENT_SHADE = 0.6++/** Figma's stops for a new gradient: the fill colour, then a 60% shade of it. */+export function defaultGradientStops(color: Color): GradientStop[] {+ return [+ { color: { ...color }, position: 0 },+ {+ color: {+ r: color.r * DEFAULT_GRADIENT_SHADE,+ g: color.g * DEFAULT_GRADIENT_SHADE,+ b: color.b * DEFAULT_GRADIENT_SHADE,+ a: color.a+ },+ position: 1+ }+ ]+}++export function isIdentityGradientTransform(t: GradientTransform): boolean {+ return (Object.keys(IDENTITY_GRADIENT_TRANSFORM) as (keyof GradientTransform)[]).every(+ (key) => t[key] === IDENTITY_GRADIENT_TRANSFORM[key]+ )+}++/**+ * The inverse affine map; a singular one falls back to the identity. Inverting a+ * `gradientTransform` gives the map from gradient space to the layer's unit square.+ */+export function invertGradientTransform(t: GradientTransform): GradientTransform {+ const det = t.m00 * t.m11 - t.m01 * t.m10+ if (Math.abs(det) < 1e-12) return IDENTITY_GRADIENT_TRANSFORM+ const m00 = t.m11 / det+ const m01 = -t.m01 / det+ const m10 = -t.m10 / det+ const m11 = t.m00 / det+ return {+ m00,+ m01,+ m02: -(m00 * t.m02 + m01 * t.m12),+ m10,+ m11,+ m12: -(m10 * t.m02 + m11 * t.m12)+ }+}++/** A point through an affine map. */+export function applyGradientTransform(t: GradientTransform, point: Vector): Vector {+ return {+ x: t.m00 * point.x + t.m01 * point.y + t.m02,+ y: t.m10 * point.x + t.m11 * point.y + t.m12+ }+}++/** Where a point of gradient space falls in the layer's unit square. */+export function gradientPoint(t: GradientTransform, point: Vector): Vector {+ return applyGradientTransform(invertGradientTransform(t), point)+}++/**+ * The transform of a linear gradient from `start` to `end` whose bands run along `across`, all in+ * the layer's unit square, such as an SVG gradient mapped through its own transform.+ */+export function linearGradientTransformFromAxes(+ start: Vector,+ end: Vector,+ across: Vector+): GradientTransform {+ return invertGradientTransform({+ m00: end.x - start.x,+ m01: across.x,+ m02: start.x - across.x / 2,+ m10: end.y - start.y,+ m11: across.y,+ m12: start.y - across.y / 2+ })+}++/**+ * The transform of a linear gradient from `start` to `end`, both in the layer's unit square, in a+ * `width` × `height` layer. Its second axis is square to the line on screen and `ratio` times as+ * long; Figma keeps that ratio when a handle is dragged (measured on desktop 126), and it starts+ * as the layer's height over its width.+ */+export function linearGradientTransform(+ start: Vector,+ end: Vector,+ width = 1,+ height = 1,+ ratio = height / width+): GradientTransform {+ const axis = { x: end.x - start.x, y: end.y - start.y }+ return linearGradientTransformFromAxes(start, end, {+ x: (-axis.y * height * ratio) / width,+ y: (axis.x * width * ratio) / height+ })+}++/**+ * The transform of a radial, angular, or diamond gradient from its centre and the ends of its two+ * radii, all in the layer's unit square.+ */+export function ellipticalGradientTransform(+ center: Vector,+ radiusX: Vector,+ radiusY: Vector+): GradientTransform {+ const xAxis = { x: 2 * (radiusX.x - center.x), y: 2 * (radiusX.y - center.y) }+ const yAxis = { x: 2 * (radiusY.x - center.x), y: 2 * (radiusY.y - center.y) }+ return invertGradientTransform({+ m00: xAxis.x,+ m01: yAxis.x,+ m02: center.x - (xAxis.x + yAxis.x) / 2,+ m10: xAxis.y,+ m11: yAxis.y,+ m12: center.y - (xAxis.y + yAxis.y) / 2+ })+}diff --git a/packages/scene-graph/tests/gradient.test.ts b/packages/scene-graph/tests/gradient.test.tsnew file mode 100644index 000000000..d90e96a3c--- /dev/null+++ b/packages/scene-graph/tests/gradient.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from 'bun:test'++import {+ DEFAULT_GRADIENT_TRANSFORM,+ IDENTITY_GRADIENT_TRANSFORM,+ defaultGradientStops,+ ellipticalGradientTransform,+ gradientPoint,+ invertGradientTransform,+ linearGradientTransform+} from '@open-pencil/scene-graph/gradient'+import type { GradientTransform } from '@open-pencil/scene-graph'++function values(t: GradientTransform) {+ return [t.m00, t.m01, t.m02, t.m10, t.m11, t.m12].map((v) => +v.toFixed(6) + 0)+}++describe('gradient paints in Figma convention', () => {+ test('the identity runs from the left edge middle to the right edge middle', () => {+ expect(gradientPoint(IDENTITY_GRADIENT_TRANSFORM, { x: 0, y: 0.5 })).toEqual({ x: 0, y: 0.5 })+ expect(gradientPoint(IDENTITY_GRADIENT_TRANSFORM, { x: 1, y: 0.5 })).toEqual({ x: 1, y: 0.5 })+ })++ // Figma desktop 126 gives a fill switched to Linear this transform: top to bottom.+ test("Figma's default runs top to bottom", () => {+ expect(values(linearGradientTransform({ x: 0.5, y: 0 }, { x: 0.5, y: 1 }))).toEqual(+ values(DEFAULT_GRADIENT_TRANSFORM)+ )+ expect(gradientPoint(DEFAULT_GRADIENT_TRANSFORM, { x: 0.5, y: 0.5 })).toEqual({ x: 0.5, y: 0.5 })+ })++ test('a transform and its inverse undo each other', () => {+ const t = { m00: 2, m01: 0.3, m02: -0.2, m10: -0.4, m11: 1.5, m12: 0.1 }+ const back = invertGradientTransform(invertGradientTransform(t))+ expect(values(back)).toEqual(values(t))+ })++ test('an elliptical gradient is centred where its centre was given', () => {+ const t = ellipticalGradientTransform({ x: 0.35, y: 0.4 }, { x: 0.6, y: 0.4 }, { x: 0.35, y: 0.73 })+ const center = gradientPoint(t, { x: 0.5, y: 0.5 })+ expect(center.x).toBeCloseTo(0.35, 6)+ expect(center.y).toBeCloseTo(0.4, 6)+ expect(gradientPoint(t, { x: 1, y: 0.5 }).x).toBeCloseTo(0.6, 6)+ })++ // Figma desktop 126 turns FF4D33 into a gradient to 992E1F.+ test('a new gradient runs from the fill colour to a 60% shade of it', () => {+ const [first, second] = defaultGradientStops({ r: 1, g: 0x4d / 255, b: 0x33 / 255, a: 1 })+ expect(first?.position).toBe(0)+ const hex = [second?.color.r, second?.color.g, second?.color.b].map((c) =>+ Math.round((c ?? 0) * 255)+ )+ expect(hex).toEqual([0x99, 0x2e, 0x1f])+ })+})diff --git a/packages/scene-graph/tsdown.config.ts b/packages/scene-graph/tsdown.config.tsindex 60aafff15..183f24190 100644--- a/packages/scene-graph/tsdown.config.ts+++ b/packages/scene-graph/tsdown.config.ts@@ -24,6 +24,7 @@ export default defineConfig({coordinate: './src/coordinate.ts',matrix: './src/matrix.ts',geometry: './src/geometry.ts',+ gradient: './src/gradient.ts',guides: './src/guides.ts',layout: './src/layout/index.ts',resize: './src/resize.ts',diff --git a/packages/vue/src/primitives/Fill/useFill.ts b/packages/vue/src/primitives/Fill/useFill.tsindex 8707de63e..33c93b45c 100644--- a/packages/vue/src/primitives/Fill/useFill.ts+++ b/packages/vue/src/primitives/Fill/useFill.ts@@ -3,6 +3,7 @@ import type { Ref } from 'vue'import type { Fill, GradientStop } from '@open-pencil/scene-graph'import { colorToCSS } from '@open-pencil/scene-graph/color'+import { DEFAULT_GRADIENT_TRANSFORM, defaultGradientStops } from '@open-pencil/scene-graph/gradient'import type { Color } from '@open-pencil/scene-graph/primitives'import type { FillCategory } from './types'@@ -58,17 +59,14 @@ export function useFill(fill: Ref<Fill>, onUpdate: (fill: Fill) => void) {function toGradient() {if (category.value === 'GRADIENT') return- const gradientStops: GradientStop[] = fill.value.gradientStops?.length+ const gradientStops = fill.value.gradientStops?.length? structuredClone(fill.value.gradientStops)- : [- { color: { ...fill.value.color }, position: 0 },- { color: { r: 1, g: 1, b: 1, a: 1 }, position: 1 }- ]+ : defaultGradientStops(fill.value.color)onUpdate({...fill.value,type: 'GRADIENT_LINEAR',gradientStops,- gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 0, m12: 0.5 }+ gradientTransform: fill.value.gradientTransform ?? { ...DEFAULT_GRADIENT_TRANSFORM }})}diff --git a/packages/vue/src/primitives/GradientEditor/useGradientStops.ts b/packages/vue/src/primitives/GradientEditor/useGradientStops.tsindex 6cdfcb6c1..f797b2a67 100644--- a/packages/vue/src/primitives/GradientEditor/useGradientStops.ts+++ b/packages/vue/src/primitives/GradientEditor/useGradientStops.ts@@ -2,6 +2,7 @@ import { computed, ref, type Ref } from 'vue'import type { Fill, GradientStop, GradientTransform } from '@open-pencil/scene-graph'import { colorToCSS } from '@open-pencil/scene-graph/color'+import { DEFAULT_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'import type { Color } from '@open-pencil/scene-graph/primitives'import { useColorModel } from '#vue/controls/color-model/use'@@ -19,13 +20,6 @@ const SUBTYPES: { value: GradientSubtype; label: string }[] = [{ value: 'GRADIENT_DIAMOND', label: 'Diamond' }]-const DEFAULT_TRANSFORMS: Record<GradientSubtype, GradientTransform> = {- GRADIENT_LINEAR: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 0, m12: 0.5 },- GRADIENT_RADIAL: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 },- GRADIENT_ANGULAR: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 },- GRADIENT_DIAMOND: { m00: 0.5, m01: 0, m02: 0.5, m10: 0, m11: 0.5, m12: 0.5 }-}-/*** Returns gradient-stop state and mutation helpers for a fill.*@@ -53,9 +47,13 @@ export function useGradientStops(fill: Ref<Fill>, onUpdate: (fill: Fill) => voidonUpdate({ ...fill.value, gradientStops: newStops })}+ /** Figma keeps the transform across kinds, so a radial gradient grows from the linear line. */function setSubtype(type: GradientSubtype) {if (type === fill.value.type) return- onUpdate({ ...fill.value, type, gradientTransform: DEFAULT_TRANSFORMS[type] })+ const gradientTransform: GradientTransform = fill.value.gradientTransform ?? {+ ...DEFAULT_GRADIENT_TRANSFORM+ }+ onUpdate({ ...fill.value, type, gradientTransform })}function selectStop(index: number) {diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 851b26cd2..c9197f51f 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -19,7 +19,7 @@ This reference describes scene creation, not React DOM output. Use the `render`## Paint, text, and artwork-- `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]])]}`.+- `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]])]}`. Without a `transform` a linear gradient runs left to right and the others are centred; `transform` is Figma's `gradientTransform`, mapping the layer's unit square onto gradient space.- `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` 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.diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.pngindex a71b5e37d..73b28ae0a 100644Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png differdiff --git a/tests/e2e/canvas/gradient-handles.spec.ts b/tests/e2e/canvas/gradient-handles.spec.tsindex e854d9fab..9232cd678 100644--- a/tests/e2e/canvas/gradient-handles.spec.ts+++ b/tests/e2e/canvas/gradient-handles.spec.ts@@ -37,13 +37,13 @@ test('dragging an end dot moves that end, and closing the picker leaves one undoawait editor.canvas.drag(end.x, end.y, target.x, target.y)await editor.canvas.waitForRender()- const moved = await gradient.fill(nodeId)- // The end, (m02, m12), follows the pointer to (200, 10) within the half screen pixel it lands- // on; the start, end plus (m00, m10), stays at the left edge's middle.- expect(moved?.transform?.m02).toBeCloseTo(1, 2)- expect(moved?.transform?.m12).toBeCloseTo(10 / 140, 2)- expect(moved?.transform?.m00).toBeCloseTo(-1, 2)- expect(moved?.transform?.m10).toBeCloseTo(60 / 140, 2)+ // The end follows the pointer to (200, 10), within the half screen pixel it lands on; the start+ // stays at the left edge's middle.+ const ends = await gradient.ends(nodeId)+ expect(ends?.start.x).toBeCloseTo(0, 0)+ expect(ends?.start.y).toBeCloseTo(70, 0)+ expect(ends?.end.x).toBeCloseTo(200, 0)+ expect(ends?.end.y).toBeCloseTo(10, 0)await expect(editor.page.getByTestId('fill-picker-gradient-bar')).toBeVisible()// Shortcuts wait for open popovers to close; closing the picker also hides the handles.diff --git a/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-strokes-openpencil-darwin.png b/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-strokes-openpencil-darwin.pngindex cdcbbeb9b..107600580 100644Binary files a/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-strokes-openpencil-darwin.png and b/tests/e2e/canvas/stroke-paint-visual.spec.ts-snapshots/gradient-strokes-openpencil-darwin.png differdiff --git a/tests/engine/io/svg/export/render.test.ts b/tests/engine/io/svg/export/render.test.tsindex 2fa3d5f23..29a61942f 100644--- a/tests/engine/io/svg/export/render.test.ts+++ b/tests/engine/io/svg/export/render.test.ts@@ -353,10 +353,37 @@ describe('renderNodesToSVG()', () => {})const result = exportSVGOrThrow(graph, [node.id])expect(result).toContain('<linearGradient')+ // Figma's identity transform runs from the left edge's middle to the right edge's.+ expect(result).toContain('x1="0" y1="0.5" x2="1" y2="0.5"')+ expect(result).not.toContain('gradientTransform')expect(result).toContain('<stop')expect(result).toContain('url(#grad')})+ test("linear gradient keeps Figma's transform", () => {+ const graph = makeGraph()+ const node = graph.createNode('RECTANGLE', pageId(graph), {+ width: 100,+ height: 60,+ fills: [+ {+ type: 'GRADIENT_LINEAR',+ color: { r: 0, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ gradientStops: [+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }+ ],+ // Figma's default: top to bottom.+ gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }+ }+ ]+ })+ const result = exportSVGOrThrow(graph, [node.id])+ expect(result).toContain('gradientTransform="matrix(0 1 -1 0 1 0)"')+ })+test('radial gradient', () => {const graph = makeGraph()const node = graph.createNode('RECTANGLE', pageId(graph), {diff --git a/tests/engine/io/svg/import.test.ts b/tests/engine/io/svg/import.test.tsindex de417446c..1e6e14bfd 100644--- a/tests/engine/io/svg/import.test.ts+++ b/tests/engine/io/svg/import.test.ts@@ -104,6 +104,36 @@ describe('import_svg', () => {expect(exported.match(/fill="url\(#/g)).toHaveLength(2)})+ // Gradients export in Figma's convention with an exact gradientTransform, so a turned gradient on+ // a stretched layer comes back with the transform it left with.+ test('a turned linear gradient survives an SVG round trip', async () => {+ const page = expectDefined(graph.getPages()[0])+ const c = Math.SQRT1_2+ const rect = graph.createNode('RECTANGLE', page.id, {+ width: 200,+ height: 120,+ fills: [+ {+ type: 'GRADIENT_LINEAR',+ color: { r: 1, g: 0, b: 0, a: 1 },+ opacity: 1,+ visible: true,+ gradientStops: [+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }+ ],+ gradientTransform: { m00: c, m01: c, m02: 0.5 - c, m10: -c, m11: c, m12: 0.5 }+ }+ ]+ })+ const exported = expectDefined(renderNodesToSVG(graph, page.id, [rect.id]))+ const result = (await importSVG.execute(figma, { svg: exported })) as { id: string }+ const imported = expectDefined(graph.getChildren(result.id)[0]?.fills[0]?.gradientTransform)+ const original = expectDefined(rect.fills[0]?.gradientTransform)+ for (const key of ['m00', 'm01', 'm02', 'm10', 'm11', 'm12'] as const)+ expect(imported[key]).toBeCloseTo(original[key], 4)+ })+test('respects viewBox dimensions', async () => {const result = (await importSVG.execute(figma, {svg: '<svg viewBox="0 0 200 100"><path d="M0 0 L200 100"/></svg>'diff --git a/tests/engine/render/canvas/diamond-gradient.test.ts b/tests/engine/render/canvas/diamond-gradient.test.tsindex 2e51c74ac..98a85903f 100644--- a/tests/engine/render/canvas/diamond-gradient.test.ts+++ b/tests/engine/render/canvas/diamond-gradient.test.ts@@ -77,7 +77,7 @@ test('diamond gradients preserve transformed contours and intermediate stops', acolor: black,opacity: 1,visible: true,- gradientTransform: { m00: 0, m01: -1, m02: 1.005, m10: 0.5, m11: 0, m12: 0.255 },+ gradientTransform: { m00: 0, m01: 2, m02: -0.51, m10: -1, m11: 0, m12: 1.005 },gradientStops: [{ position: 0, color: black },{ position: 0.5, color: { r: 1, g: 0, b: 0, a: 1 } },diff --git a/tests/engine/render/canvas/gradient.test.ts b/tests/engine/render/canvas/gradient.test.tsindex 013f76642..d5cb3f6bf 100644--- a/tests/engine/render/canvas/gradient.test.ts+++ b/tests/engine/render/canvas/gradient.test.ts@@ -1,19 +1,176 @@import { describe, expect, test } from 'bun:test'-import { linearGradientEndpoints } from '#core/canvas/fills'--describe('canvas gradients', () => {- test('maps figma linear gradient start color to transformed x-axis endpoint', () => {- const endpoints = linearGradientEndpoints(188, 270, {- m00: 0,- m01: 1,- m02: 0,- m10: -1,- m11: 0,- m12: 1- })+import type { Fill, GradientTransform } from '@open-pencil/scene-graph'+import { SceneGraph } from '@open-pencil/scene-graph'++import { initCanvasKit } from '#cli/headless'+import { SkiaRenderer } from '#core/canvas/renderer'++import { expectDefined } from '#tests/helpers/assert'++const WIDTH = 200+const HEIGHT = 120+const STOPS = [+ { position: 0, color: { r: 1, g: 0.2, b: 0.1, a: 1 } },+ { position: 0.5, color: { r: 1, g: 0.9, b: 0.2, a: 1 } },+ { position: 1, color: { r: 0.1, g: 0.3, b: 1, a: 1 } }+]++type Hue = 'red' | 'yellow' | 'blue'- expect(endpoints.start).toEqual({ x: 0, y: 0 })- expect(endpoints.end).toEqual({ x: 0, y: 270 })+function hue([r, g, b]: number[]): Hue | 'other' {+ if (r > 200 && g < 120 && b < 120) return 'red'+ if (r > 200 && g > 180 && b < 120) return 'yellow'+ if (b > 200 && r < 120) return 'blue'+ return 'other'+}++async function render(type: Fill['type'], transform: number[]) {+ const ck = await initCanvasKit()+ const surface = expectDefined(ck.MakeSurface(WIDTH, HEIGHT), 'surface')+ const renderer = new SkiaRenderer(ck, surface)+ const graph = new SceneGraph()+ const page = expectDefined(graph.getPages()[0], 'page')+ const [m00, m01, m02, m10, m11, m12] = transform+ const gradientTransform: GradientTransform = { m00, m01, m02, m10, m11, m12 }+ const node = graph.createNode('RECTANGLE', page.id, {+ width: WIDTH,+ height: HEIGHT,+ fills: [+ {+ type,+ color: STOPS[0].color,+ opacity: 1,+ visible: true,+ gradientStops: STOPS,+ gradientTransform+ }+ ]})+ try {+ const canvas = surface.getCanvas()+ canvas.clear(ck.TRANSPARENT)+ renderer.renderShape(canvas, node, graph)+ surface.flush()+ const image = surface.makeImageSnapshot()+ try {+ const pixels = expectDefined(+ image.readPixels(0, 0, {+ width: WIDTH,+ height: HEIGHT,+ colorType: ck.ColorType.RGBA_8888,+ alphaType: ck.AlphaType.Unpremul,+ colorSpace: ck.ColorSpace.SRGB+ }),+ 'pixels'+ )+ return (x: number, y: number) =>+ hue(Array.from(pixels.slice((y * WIDTH + x) * 4, (y * WIDTH + x) * 4 + 3)))+ } finally {+ image.delete()+ }+ } finally {+ renderer.destroy()+ }+}++const C = Math.SQRT1_2++// Each case was drawn in Figma desktop 126 on a 200 × 120 rectangle with the same stops and+// transform (the plugin API's gradientTransform, which `.fig` files and the clipboard store as+// is); the points are where Figma shows red, the yellow middle stop, and blue.+const FIGMA_CASES: Array<{+ name: string+ type: Fill['type']+ transform: number[]+ expected: Array<[number, number, Hue]>+}> = [+ {+ name: 'identity runs left to right',+ type: 'GRADIENT_LINEAR',+ transform: [1, 0, 0, 0, 1, 0],+ expected: [+ [5, 60, 'red'],+ [100, 60, 'yellow'],+ [195, 60, 'blue']+ ]+ },+ {+ name: "Figma's default runs top to bottom",+ type: 'GRADIENT_LINEAR',+ transform: [0, 1, 0, -1, 0, 1],+ expected: [+ [100, 3, 'red'],+ [100, 60, 'yellow'],+ [100, 117, 'blue']+ ]+ },+ {+ name: 'a turned gradient keeps its bands along the second axis',+ type: 'GRADIENT_LINEAR',+ transform: [C, C, 0.5 - C, -C, C, 0.5],+ expected: [+ [3, 3, 'red'],+ [40, 96, 'yellow'],+ [160, 24, 'yellow'],+ [197, 117, 'blue']+ ]+ },+ {+ name: 'a scaled and offset gradient',+ type: 'GRADIENT_LINEAR',+ transform: [2, 0, -0.5, 0, 1, 0.2],+ expected: [+ [30, 60, 'red'],+ [100, 60, 'yellow'],+ [170, 60, 'blue']+ ]+ },+ {+ name: 'radial centred where the transform puts (0.5, 0.5)',+ type: 'GRADIENT_RADIAL',+ transform: [2, 0, -0.2, 0, 1.5, -0.1],+ expected: [+ [70, 48, 'red'],+ [195, 115, 'blue']+ ]+ },+ {+ name: 'angular starts at +x and turns clockwise',+ type: 'GRADIENT_ANGULAR',+ transform: [1, 0, 0, 0, 1, 0],+ expected: [+ [180, 66, 'red'],+ [20, 60, 'yellow'],+ [180, 54, 'blue']+ ]+ },+ {+ name: "angular with Figma's default starts downward",+ type: 'GRADIENT_ANGULAR',+ transform: [0, 1, 0, -1, 0, 1],+ expected: [+ [94, 115, 'red'],+ [100, 5, 'yellow'],+ [106, 115, 'blue']+ ]+ },+ {+ name: 'diamond centred where the transform puts (0.5, 0.5)',+ type: 'GRADIENT_DIAMOND',+ transform: [2, 0, -0.2, 0, 1.5, -0.1],+ expected: [+ [70, 48, 'red'],+ [195, 115, 'blue']+ ]+ }+]++describe('gradients match Figma', () => {+ for (const { name, type, transform, expected } of FIGMA_CASES) {+ test(name, async () => {+ const at = await render(type, transform)+ expect(expected.map(([x, y]) => at(x, y))).toEqual(expected.map(([, , hue]) => hue))+ })+ }})diff --git a/tests/engine/render/canvas/text.test.ts b/tests/engine/render/canvas/text.test.tsindex 24efa21bf..4cf0a2817 100644--- a/tests/engine/render/canvas/text.test.ts+++ b/tests/engine/render/canvas/text.test.ts@@ -592,8 +592,9 @@ describe('renderText headless visual', () => {const g = pixels[i + 1]const b = pixels[i + 2]if (g > 220) continue- if (x < 110 && b > r + 40) blueTextPixels++- if (x >= 110 && r > b + 40) redTextPixels+++ // Figma's identity transform runs left to right: the first stop, red, is on the left.+ if (x < 110 && r > b + 40) redTextPixels+++ if (x >= 110 && b > r + 40) blueTextPixels++}}diff --git a/tests/engine/vector/vectorize.test.ts b/tests/engine/vector/vectorize.test.tsindex c0901a9c8..cc7d88d37 100644--- a/tests/engine/vector/vectorize.test.ts+++ b/tests/engine/vector/vectorize.test.ts@@ -359,10 +359,14 @@ describe('svgToVectorPaths', () => {)const transform = expectDefined(fill.gradientTransform, 'gradient transform')expect(fill.type).toBe('GRADIENT_RADIAL')+ // A circle filling the box, turned a quarter: Figma's default transform, which maps the layer+ // onto gradient space.expect(transform.m00).toBeCloseTo(0, 3)- expect(transform.m10).toBeCloseTo(0.5, 3)- expect(transform.m01).toBeCloseTo(-0.5, 3)+ expect(transform.m01).toBeCloseTo(1, 3)+ expect(transform.m02).toBeCloseTo(0, 3)+ expect(transform.m10).toBeCloseTo(-1, 3)expect(transform.m11).toBeCloseTo(0, 3)+ expect(transform.m12).toBeCloseTo(1, 3)})test('still resolves a solid color fill alongside gradients', () => {diff --git a/tests/helpers/canvas/gradient-driver.ts b/tests/helpers/canvas/gradient-driver.tsindex 007a4ae1d..e6c22f774 100644--- a/tests/helpers/canvas/gradient-driver.ts+++ b/tests/helpers/canvas/gradient-driver.ts@@ -1,5 +1,7 @@import type { Page } from '@playwright/test'+import type * as Geometry from '@open-pencil/core/geometry'+import type * as GradientScene from '#tests/helpers/canvas/gradient'type GradientType = Parameters<typeof GradientScene.createGradientScene>[2]@@ -41,6 +43,24 @@ export function gradientDriver(page: () => Page) {}, nodeId)},+ /** A linear gradient's start and end in the layer's own pixels. */+ ends(nodeId: string) {+ return page().evaluate(async (id) => {+ const node = window.openPencil?.getStore?.().graph.getNode(id)+ const transform = node?.fills[0]?.gradientTransform+ if (!node || !transform) return null+ const geometryURL = '/packages/core/src/geometry/gradient.ts'+ const geometry: typeof Geometry = await import(geometryURL)+ const { start, end } = geometry.gradientHandles(+ 'GRADIENT_LINEAR',+ transform,+ node.width,+ node.height+ )+ return { start, end }+ }, nodeId)+ },+editedStop() {return page().evaluate(() => window.openPencil?.getStore?.().state.gradientEdit?.stop ?? null)},diff --git a/tests/helpers/canvas/gradient.ts b/tests/helpers/canvas/gradient.tsindex 9fea7a7d0..f95ea59a9 100644--- a/tests/helpers/canvas/gradient.ts+++ b/tests/helpers/canvas/gradient.ts@@ -2,12 +2,16 @@ import type { Fill, GradientTransform, SceneGraph } from '@open-pencil/scene-gratype GradientType = 'GRADIENT_LINEAR' | 'GRADIENT_RADIAL' | 'GRADIENT_ANGULAR' | 'GRADIENT_DIAMOND'-/** Linear from the left edge's middle to the right's; the others centred, filling the layer. */+/**+ * Figma's identity transform for each kind: linear from the left edge's middle to the right's, the+ * others centred and filling the layer.+ */+const IDENTITY: GradientTransform = { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }const TRANSFORMS: Record<GradientType, GradientTransform> = {- GRADIENT_LINEAR: { m00: -1, m01: 0, m02: 1, m10: 0, m11: -1, m12: 0.5 },- GRADIENT_RADIAL: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },- GRADIENT_ANGULAR: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 },- GRADIENT_DIAMOND: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 }+ GRADIENT_LINEAR: IDENTITY,+ GRADIENT_RADIAL: IDENTITY,+ GRADIENT_ANGULAR: IDENTITY,+ GRADIENT_DIAMOND: IDENTITY}/** A 200 × 140 rectangle at the origin with a red, yellow, and blue gradient fill. */