Skip to content

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

fix: give gradient transforms as Figma's rows in design JSX and toJSON (#1369)

enzo-regera2db46fc618ac
diff --git a/changes/1369/fixed.md b/changes/1369/fixed.md
new file mode 100644
index 000000000..54bf7c1ba
--- /dev/null
+++ b/changes/1369/fixed.md
@@ -0,0 +1 @@
+- Design JSX takes a gradient's `transform`, and a paint's `gradientTransform` and `imageTransform`, as Figma's rows such as `[[0, 1, 0], [-1, 0, 1]]` as well as the matrix fields, refuses any other shape instead of drawing nothing, and exports them as rows.
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index d86f38e74..4883ea8cc 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -1,4 +1,4 @@
-import type { Fill, GradientStop, SceneNode, Stroke } from '@open-pencil/scene-graph'
+import type { Fill, GradientStop, SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'
import { normalizeColor } from '@open-pencil/scene-graph/color'
import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
import { newStrokeGeometry } from '@open-pencil/scene-graph/node-defaults'
@@ -91,6 +91,34 @@ export function figmaPaintToFill(
}
}
+/**
+ * Copies of `node`'s fills as Figma's plugin API reads them: bound colours resolved and named,
+ * transforms as two rows of three.
+ */
+export function figmaFills(sceneGraph: SceneGraph, node: SceneNode): WithFigmaTransforms<Fill>[] {
+ const bound = paintBindings(node, 'fills')
+ const fills = bound.size
+ ? (resolvedPaintBindings(sceneGraph, node).fills ?? node.fills)
+ : node.fills
+ return copyFills(fills).map((fill, index) =>
+ toFigmaPaint(withPaintBinding(fill, bound.get(index)))
+ )
+}
+
+/** Copies of `node`'s strokes as Figma's plugin API reads them, as {@link figmaFills} reads fills. */
+export function figmaStrokes(
+ sceneGraph: SceneGraph,
+ node: SceneNode
+): WithFigmaTransforms<Stroke>[] {
+ const bound = paintBindings(node, 'strokes')
+ const strokes = bound.size
+ ? (resolvedPaintBindings(sceneGraph, node).strokes ?? node.strokes)
+ : node.strokes
+ return copyStrokes(strokes).map((stroke, index) =>
+ toFigmaPaint(withPaintBinding(stroke, bound.get(index)))
+ )
+}
+
export function installVisualNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals,
@@ -101,17 +129,7 @@ export function installVisualNodeProxyAccessors(
// Text reads mixed while its characters are filled differently, and setting it fills them all.
get(this: ProxyThis): readonly WithFigmaTransforms<Fill>[] | symbol {
const node = raw(this, internals)
- if (node.type !== 'TEXT') {
- const bound = paintBindings(node, 'fills')
- const fills = bound.size
- ? (resolvedPaintBindings(graph(this, internals), node).fills ?? node.fills)
- : node.fills
- return Object.freeze(
- copyFills(fills).map((fill, index) =>
- toFigmaPaint(withPaintBinding(fill, bound.get(index)))
- )
- )
- }
+ if (node.type !== 'TEXT') return Object.freeze(figmaFills(graph(this, internals), node))
const fills = getTextStyle(node, 'fills', mixed)
// Text styles read for scripts already give Figma's paints.
return typeof fills === 'symbol'
@@ -132,15 +150,7 @@ export function installVisualNodeProxyAccessors(
strokes: {
get(this: ProxyThis): readonly WithFigmaTransforms<Stroke>[] {
const owner = raw(strokeOwner(this, internals), internals)
- const bound = paintBindings(owner, 'strokes')
- const strokes = bound.size
- ? (resolvedPaintBindings(graph(this, internals), owner).strokes ?? owner.strokes)
- : owner.strokes
- return Object.freeze(
- copyStrokes(strokes).map((stroke, index) =>
- toFigmaPaint(withPaintBinding(stroke, bound.get(index)))
- )
- )
+ return Object.freeze(figmaStrokes(graph(this, internals), owner))
},
// Figma paints carry no geometry; a stroke takes the node's weight and alignment, which
// outlast its strokes.
diff --git a/packages/core/src/figma-api/paints.ts b/packages/core/src/figma-api/paints.ts
index 3ac2375ec..30150000f 100644
--- a/packages/core/src/figma-api/paints.ts
+++ b/packages/core/src/figma-api/paints.ts
@@ -1,5 +1,8 @@
import type { Fill, GradientTransform } from '@open-pencil/scene-graph'
-import { IDENTITY_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'
+import {
+ gradientTransformRows,
+ IDENTITY_GRADIENT_TRANSFORM
+} from '@open-pencil/scene-graph/gradient'
import type { FigmaTransform } from './types'
@@ -14,14 +17,6 @@ export type WithFigmaTransforms<T> = Omit<T, TransformField> & {
imageTransform?: FigmaTransform
}
-/** A scene transform as Figma's plugin API gives it: two rows of three. */
-export function toFigmaTransform(t: GradientTransform): FigmaTransform {
- return [
- [t.m00, t.m01, t.m02],
- [t.m10, t.m11, t.m12]
- ]
-}
-
function isRow(value: unknown): value is [number, number, number] {
return (
Array.isArray(value) &&
@@ -82,7 +77,7 @@ export function toFigmaPaint<T extends Fill>(paint: T): WithFigmaTransforms<T> {
const image = imageTransform ?? (paint.type === 'IMAGE' ? IDENTITY_GRADIENT_TRANSFORM : undefined)
return {
...rest,
- ...(gradientTransform && { gradientTransform: toFigmaTransform(gradientTransform) }),
- ...(image && { imageTransform: toFigmaTransform(image) })
+ ...(gradientTransform && { gradientTransform: gradientTransformRows(gradientTransform) }),
+ ...(image && { imageTransform: gradientTransformRows(image) })
}
}
diff --git a/packages/core/src/figma-api/serialization.ts b/packages/core/src/figma-api/serialization.ts
index 7a8808688..79e627d5d 100644
--- a/packages/core/src/figma-api/serialization.ts
+++ b/packages/core/src/figma-api/serialization.ts
@@ -1,6 +1,7 @@
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { pluginChildren } from './accessors/sticky'
+import { figmaFills, figmaStrokes } from './accessors/visual'
import type { NodeProxyHost } from './proxy'
function resolveBindings(graph: SceneGraph, node: SceneNode): Record<string, unknown> | undefined {
@@ -53,8 +54,8 @@ export function nodeProxyToJSON(
width: n.width,
height: n.height
}
- if (n.fills.length > 0) obj.fills = n.fills
- if (n.strokes.length > 0) obj.strokes = n.strokes
+ if (n.fills.length > 0) obj.fills = figmaFills(graph, n)
+ if (n.strokes.length > 0) obj.strokes = figmaStrokes(graph, n)
if (n.effects.length > 0) obj.effects = n.effects
if (n.opacity !== 1) obj.opacity = n.opacity
if (n.cornerRadius > 0) obj.cornerRadius = n.cornerRadius
diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.ts
index 1ac24abd8..be966cea7 100644
--- a/packages/core/src/tools/modify/paint.ts
+++ b/packages/core/src/tools/modify/paint.ts
@@ -2,11 +2,10 @@ import { isValid, toUint8Array } from 'js-base64'
import * as v from 'valibot'
import { parseColor } from '@open-pencil/scene-graph/color'
-import { linearGradientTransform } from '@open-pencil/scene-graph/gradient'
+import { gradientTransformRows, linearGradientTransform } from '@open-pencil/scene-graph/gradient'
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { BLACK } from '#core/constants'
-import { toFigmaTransform } from '#core/figma-api/paints'
import { defineTool, nodeIdInputSchema, toolNumber } from '#core/tools/schema'
export const setFill = defineTool({
@@ -66,7 +65,7 @@ export const setFill = defineTool({
{ position: 0, color: c },
{ position: 1, color: cEnd }
],
- gradientTransform: toFigmaTransform(linearGradientTransform(start, end))
+ gradientTransform: gradientTransformRows(linearGradientTransform(start, end))
}
]
return { id, gradient, start: c, end: cEnd }
diff --git a/packages/core/tests/figma-api/paints.test.ts b/packages/core/tests/figma-api/paints.test.ts
index 89ef1516b..9135d8737 100644
--- a/packages/core/tests/figma-api/paints.test.ts
+++ b/packages/core/tests/figma-api/paints.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from 'bun:test'
-import { SceneGraph } from '@open-pencil/scene-graph'
+import { SceneGraph, type Fill } from '@open-pencil/scene-graph'
import { FigmaAPI } from '#core/figma-api'
@@ -129,3 +129,62 @@ describe('an image transform', () => {
])
})
})
+
+// `get_node`, `get_selection`, and `eval` print a layer through toJSON, so a script reads the same
+// paints there as through `fills` and `strokes`, and can assign them back.
+describe('a layer printed as JSON', () => {
+ // Laid out as a document read from a file holds it, with a colour bound to a variable.
+ function paintedRectangle() {
+ const { graph, figma } = api()
+ const collection = figma.variables.createVariableCollection('Tokens')
+ const blue = figma.variables.createVariable('blue', collection, 'COLOR')
+ blue.setValueForMode(collection.defaultModeId, { r: 0, g: 0, b: 1 })
+ const gradient: Fill = {
+ ...GRADIENT,
+ type: 'GRADIENT_LINEAR',
+ gradientStops: STOPS,
+ gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }
+ }
+ const rectangle = figma.createRectangle()
+ graph.updateNode(rectangle.id, {
+ fills: [
+ gradient,
+ { ...GRADIENT, type: 'IMAGE', imageHash: 'hash', imageScaleMode: 'FILL' },
+ { ...GRADIENT, type: 'SOLID' }
+ ],
+ strokes: [{ ...gradient, weight: 1, align: 'CENTER' }]
+ })
+ graph.bindVariable(rectangle.id, 'fills/2/color', blue.id)
+ return { figma, rectangle }
+ }
+
+ test('prints paints as fills and strokes read them', () => {
+ const { rectangle } = paintedRectangle()
+ const json = rectangle.toJSON()
+ expect(json.fills).toEqual(rectangle.fills)
+ expect(json.strokes).toEqual(rectangle.strokes)
+ expect(json.fills).toEqual([
+ expect.objectContaining({ gradientTransform: SWAPPED }),
+ expect.objectContaining({
+ imageTransform: [
+ [1, 0, 0],
+ [0, 1, 0]
+ ]
+ }),
+ expect.objectContaining({ color: { r: 0, g: 0, b: 1, a: 1 } })
+ ])
+ })
+
+ test('prints paints a script can assign to another layer', () => {
+ const { figma, rectangle } = paintedRectangle()
+ const { fills, strokes } = rectangle.toJSON()
+ const copy = figma.createRectangle()
+ expect(() => {
+ copy.fills = fills as never
+ copy.strokes = strokes as never
+ }).not.toThrow()
+ expect(copy.fills).toEqual(rectangle.fills)
+ expect(copy.strokes).toEqual(rectangle.strokes)
+ expect(copy.boundVariables).toEqual(rectangle.boundVariables)
+ })
+})
diff --git a/packages/design-jsx/src/export/paint.ts b/packages/design-jsx/src/export/paint.ts
index 1e48a459a..7f8c22113 100644
--- a/packages/design-jsx/src/export/paint.ts
+++ b/packages/design-jsx/src/export/paint.ts
@@ -1,5 +1,8 @@
import type { Effect, Fill, GradientTransform, SceneNode, Stroke } from '@open-pencil/scene-graph'
-import { isIdentityGradientTransform } from '@open-pencil/scene-graph/gradient'
+import {
+ gradientTransformRows,
+ isIdentityGradientTransform
+} from '@open-pencil/scene-graph/gradient'
import { shaderOfPaint } from '@open-pencil/scene-graph/shaders'
import { STROKE_ALIGN, STROKE_CAP, STROKE_JOIN } from '../enums'
@@ -17,6 +20,11 @@ function isIdentity(transform: GradientTransform | undefined): boolean {
return !transform || isIdentityGradientTransform(transform)
}
+/** A paint transform as authors write it, in Figma's rows. */
+function rows(transform: GradientTransform | undefined) {
+ return transform && gradientTransformRows(transform)
+}
+
/** Paints and effects imported from Figma often spell out the default blend mode. */
function blendMode(mode: Fill['blendMode']): Fill['blendMode'] {
return mode === 'NORMAL' || mode === 'PASS_THROUGH' ? undefined : mode
@@ -69,12 +77,16 @@ function fillValue(fill: Fill, node: SceneNode): JSXValue {
blendMode: blendMode(fill.blendMode),
transform: isIdentity(fill.gradientTransform)
? undefined
- : plainValue(fill.gradientTransform)
+ : plainValue(rows(fill.gradientTransform))
})
)
}
// Image, pattern, and other paints have no helper; they render back from their fields.
- return plainValue(fill)
+ return plainValue({
+ ...fill,
+ gradientTransform: rows(fill.gradientTransform),
+ imageTransform: rows(fill.imageTransform)
+ })
}
/** A single visible solid paint fits the `bg` or text `color` shorthand. */
diff --git a/packages/design-jsx/src/overrides/fills.ts b/packages/design-jsx/src/overrides/fills.ts
index e16ce116e..e652c7815 100644
--- a/packages/design-jsx/src/overrides/fills.ts
+++ b/packages/design-jsx/src/overrides/fills.ts
@@ -1,5 +1,8 @@
-import type { Fill } from '@open-pencil/scene-graph'
+import * as v from 'valibot'
+
+import type { Fill, GradientTransform } from '@open-pencil/scene-graph'
import { colorToFill } from '@open-pencil/scene-graph/color'
+import { paintTransformSchema } from '@open-pencil/scene-graph/paints'
import type { Color } from '@open-pencil/scene-graph/primitives'
export function isColor(value: unknown): value is Color {
@@ -28,6 +31,26 @@ export function isFillValue(value: unknown): value is string | Color | Fill {
return typeof value === 'string' || isColor(value) || isFill(value)
}
+const TRANSFORM_FIELDS = ['gradientTransform', 'imageTransform'] as const
+
+/** Worded as `parseScriptInput` words it; that lives in `schema.ts`, which imports this module. */
+function parseTransform(
+ field: (typeof TRANSFORM_FIELDS)[number],
+ value: unknown
+): GradientTransform {
+ const result = v.safeParse(paintTransformSchema, value)
+ if (result.success) return result.output
+ throw new Error(
+ `A paint's ${field} expects Figma's [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 }:\n${v.summarize(result.issues)}`
+ )
+}
+
export function fillFromValue(value: string | Color | Fill): Fill {
- return isFill(value) ? structuredClone(value) : colorToFill(value)
+ if (!isFill(value)) return colorToFill(value)
+ const fill = structuredClone(value)
+ // A paint written as an object, as export writes an image, gives its transforms as Figma's rows.
+ for (const field of TRANSFORM_FIELDS) {
+ if (fill[field] !== undefined) fill[field] = parseTransform(field, fill[field])
+ }
+ return fill
}
diff --git a/packages/design-jsx/src/paints.ts b/packages/design-jsx/src/paints.ts
index 2d95d12c5..7d34a522e 100644
--- a/packages/design-jsx/src/paints.ts
+++ b/packages/design-jsx/src/paints.ts
@@ -9,7 +9,11 @@ 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 {
+ IDENTITY_GRADIENT_TRANSFORM,
+ type GradientTransformRows
+} from '@open-pencil/scene-graph/gradient'
+import { paintTransformSchema } from '@open-pencil/scene-graph/paints'
import type { Color } from '@open-pencil/scene-graph/primitives'
import {
createShaderPaint,
@@ -30,7 +34,8 @@ export interface SolidPaintOptions {
}
export interface GradientPaintOptions extends SolidPaintOptions {
- transform?: GradientTransform
+ /** Figma's `gradientTransform`, as its plugin API's rows or as the matrix fields. */
+ transform?: GradientTransformRows | GradientTransform
}
const colorSchema = v.union([
@@ -65,6 +70,14 @@ function parseStops(type: GradientType, stops: unknown): PaintStop[] {
)
}
+function parseTransform(type: GradientType, transform: unknown): GradientTransform {
+ return parseScriptInput(
+ `${GRADIENT_HELPERS[type]}() expects a transform as Figma's [[a, b, c], [d, e, f]], such as [[0, 1, 0], [-1, 0, 1]], or { m00, m01, m02, m10, m11, m12 }`,
+ paintTransformSchema,
+ transform
+ )
+}
+
function toColor(color: PaintColor): Color {
return typeof color === 'string' ? parseColor(color) : color
}
@@ -98,7 +111,10 @@ export function gradient(
visible: options.visible ?? true,
blendMode: options.blendMode,
gradientStops: parseStops(type, stops).map(toStop),
- gradientTransform: options.transform ?? { ...IDENTITY_GRADIENT_TRANSFORM }
+ gradientTransform:
+ options.transform === undefined
+ ? { ...IDENTITY_GRADIENT_TRANSFORM }
+ : parseTransform(type, options.transform)
}
}
diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.md
index 3ed74323b..fc38e3e09 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]])]}`. 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.
+- `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. Write it as the plugin API's rows, as export does: `linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] })` runs top to bottom. A paint written as an object takes its `gradientTransform` and `imageTransform` as rows too; the matrix fields `{ m00, m01, m02, m10, m11, m12 }` are accepted as well.
- `shader(effects, { opacity, visible, blendMode })` fills a layer with a shader from the [`shaders`](https://shaders.com) library: an array of effects such as `bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}`, or a preset as shaders.com exports it, `{ components: [...] }`. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.
- `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.
diff --git a/packages/design-jsx/tests/export.test.ts b/packages/design-jsx/tests/export.test.ts
index 446050294..f6fddf6d4 100644
--- a/packages/design-jsx/tests/export.test.ts
+++ b/packages/design-jsx/tests/export.test.ts
@@ -232,6 +232,49 @@ describe('sceneNodeToJSX', () => {
expect(jsx).toContain('strokeWidth={2}')
})
+ // As Figma's plugin API gives them, so an author reads and writes the form a script does.
+ test("a gradient's transform exports as Figma's rows", () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ fills: [
+ {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ opacity: 1,
+ visible: true,
+ gradientStops: [
+ { color: { r: 1, g: 0, b: 0, a: 1 }, position: 0 },
+ { color: { r: 0, g: 0, b: 1, a: 1 }, position: 1 }
+ ],
+ gradientTransform: { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }
+ }
+ ]
+ })
+ expect(sceneNodeToJSX(node.id, graph)).toContain(
+ 'linearGradient([["#FF0000", 0], ["#0000FF", 1]], { transform: [[0, 1, 0], [-1, 0, 1]] })'
+ )
+ })
+
+ test("an image crop exports its window as Figma's rows", () => {
+ const graph = makeGraph()
+ const node = graph.createNode('RECTANGLE', pageId(graph), {
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ imageHash: 'abc123',
+ imageScaleMode: 'CROP',
+ imageTransform: { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }
+ }
+ ]
+ })
+ expect(sceneNodeToJSX(node.id, graph)).toContain(
+ 'imageTransform: [[0.5, 0, 0.25], [0, 0.5, 0.25]]'
+ )
+ })
+
test('hidden children are kept and marked hidden', () => {
const graph = makeGraph()
const frame = graph.createNode('FRAME', pageId(graph), {
diff --git a/packages/design-jsx/tests/paints.test.ts b/packages/design-jsx/tests/paints.test.ts
index 0133ca0c9..c05e83b79 100644
--- a/packages/design-jsx/tests/paints.test.ts
+++ b/packages/design-jsx/tests/paints.test.ts
@@ -1,11 +1,72 @@
import { describe, expect, test } from 'bun:test'
import { linearGradient, radialGradient } from '@open-pencil/design-jsx'
+import { DEFAULT_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'
const expected =
"linearGradient() expects an array of stops, such as [['#3b82f6', 0], ['#8b5cf6', 1]]"
+const stops: [string, number][] = [
+ ['#3b82f6', 0],
+ ['#8b5cf6', 1]
+]
+
+const transformExpected =
+ "linearGradient() expects a transform as Figma's [[a, b, c], [d, e, f]], such as [[0, 1, 0], [-1, 0, 1]], or { m00, m01, m02, m10, m11, m12 }"
+
describe('gradient helpers', () => {
+ // Figma's plugin API gives a paint's transform as two rows, and its default gradient runs top to
+ // bottom: [[0, 1, 0], [-1, 0, 1]]. Earlier design JSX exports printed the matrix fields.
+ test("take a transform as Figma's rows or as the matrix fields", () => {
+ const rows = linearGradient(stops, {
+ transform: [
+ [0, 1, 0],
+ [-1, 0, 1]
+ ]
+ })
+ expect(rows.gradientTransform).toEqual(DEFAULT_GRADIENT_TRANSFORM)
+ const transform = { m00: 2, m01: 0, m02: -0.5, m10: 0, m11: 1, m12: 0.2 }
+ expect(linearGradient(stops, { transform }).gradientTransform).toEqual(transform)
+ })
+
+ test.each([
+ ['one row', [[0, 1, 0]], 'Array'],
+ [
+ 'a third row',
+ [
+ [0, 1, 0],
+ [-1, 0, 1],
+ [0, 0, 1]
+ ],
+ 'Array'
+ ],
+ [
+ 'a fourth value in a row',
+ [
+ [0, 1, 0, 9],
+ [-1, 0, 1]
+ ],
+ 'Array'
+ ],
+ ['a missing field', { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1 }, 'Object'],
+ ['a surplus field', { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0, m20: 0 }, 'Object']
+ ])('refuse a transform with %s and name both forms', (_, transform, received) => {
+ expect(() => linearGradient(stops, { transform: transform as never })).toThrow(
+ `${transformExpected}:\n× Expected [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 } but received ${received}`
+ )
+ })
+
+ test('refuse a transform that is not finite', () => {
+ expect(() =>
+ linearGradient(stops, {
+ transform: [
+ [Number.POSITIVE_INFINITY, 0, 0],
+ [0, 1, 0]
+ ]
+ })
+ ).toThrow(transformExpected)
+ })
+
test('accept tuple and object stops', () => {
const fill = linearGradient([['#000000', 0], { color: '#ffffff', position: 1 }])
expect(fill.gradientStops?.map((stop) => stop.position)).toEqual([0, 1])
diff --git a/packages/design-jsx/tests/props-overrides.test.ts b/packages/design-jsx/tests/props-overrides.test.ts
index fcb90f422..c8ff36a63 100644
--- a/packages/design-jsx/tests/props-overrides.test.ts
+++ b/packages/design-jsx/tests/props-overrides.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, test } from 'bun:test'
import { designJSXProp } from '#design-jsx/index'
import { propsToOverrides } from '#design-jsx/props-overrides'
+import { DEFAULT_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'
+
describe('property names', () => {
test('reads the first name of a property that is set', () => {
expect(designJSXProp({ width: 10 }, 'w')).toBe(10)
@@ -42,3 +44,56 @@ describe('stack alignment', () => {
})
})
})
+
+// A paint written as an object, as export writes an image, gives its transforms as Figma's rows or
+// as the matrix fields earlier exports printed.
+describe('paints written as objects', () => {
+ const gradient = {
+ type: 'GRADIENT_LINEAR',
+ color: { r: 0, g: 0, b: 0, a: 0 },
+ opacity: 1,
+ visible: true,
+ gradientStops: []
+ }
+ const image = {
+ type: 'IMAGE',
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ opacity: 1,
+ visible: true,
+ imageHash: 'abc123',
+ imageScaleMode: 'CROP'
+ }
+ const crop = { m00: 0.5, m01: 0, m02: 0.25, m10: 0, m11: 0.5, m12: 0.25 }
+
+ function fills(...paints: object[]) {
+ return propsToOverrides({ fills: paints }, false, 'NONE').fills
+ }
+
+ test("read a transform given as Figma's rows or as the matrix fields", () => {
+ const rows = {
+ gradientTransform: [
+ [0, 1, 0],
+ [-1, 0, 1]
+ ]
+ }
+ const cropRows = {
+ imageTransform: [
+ [0.5, 0, 0.25],
+ [0, 0.5, 0.25]
+ ]
+ }
+ expect(fills({ ...gradient, ...rows }, { ...image, ...cropRows })).toEqual([
+ expect.objectContaining({ gradientTransform: DEFAULT_GRADIENT_TRANSFORM }),
+ expect.objectContaining({ imageTransform: crop })
+ ])
+ expect(fills({ ...image, imageTransform: crop })).toEqual([
+ expect.objectContaining({ imageTransform: crop })
+ ])
+ })
+
+ test('refuse a transform that is neither and name both forms', () => {
+ expect(() => fills({ ...image, imageTransform: [[1, 0, 0]] })).toThrow(
+ "A paint's imageTransform expects Figma's [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 }:\n× Expected [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 } but received Array"
+ )
+ })
+})
diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.md
index 6ec6bce4b..0963cc453 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]])]}`. 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.
+- `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. Write it as the plugin API's rows, as export does: `linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] })` runs top to bottom. A paint written as an object takes its `gradientTransform` and `imageTransform` as rows too; the matrix fields `{ m00, m01, m02, m10, m11, m12 }` are accepted as well.
- `shader(effects, { opacity, visible, blendMode })` fills a layer with a shader from the [`shaders`](https://shaders.com) library: an array of effects such as `bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}`, or a preset as shaders.com exports it, `{ components: [...] }`. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.
- `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.
diff --git a/packages/scene-graph/src/gradient.ts b/packages/scene-graph/src/gradient.ts
index 46db9f386..67ff8ff4d 100644
--- a/packages/scene-graph/src/gradient.ts
+++ b/packages/scene-graph/src/gradient.ts
@@ -46,6 +46,20 @@ export const DEFAULT_GRADIENT_TRANSFORM: GradientTransform = {
m12: 1
}
+/**
+ * A paint transform as Figma's plugin API gives and takes it, and as authors write it: two rows of
+ * three, `[[m00, m01, m02], [m10, m11, m12]]`.
+ */
+export type GradientTransformRows = [[number, number, number], [number, number, number]]
+
+/** `t` as Figma's plugin API gives a paint transform: two rows of three. */
+export function gradientTransformRows(t: GradientTransform): GradientTransformRows {
+ return [
+ [t.m00, t.m01, t.m02],
+ [t.m10, t.m11, t.m12]
+ ]
+}
+
/** How dark a new gradient's second stop is next to the fill colour, as in Figma. */
const DEFAULT_GRADIENT_SHADE = 0.6
diff --git a/packages/scene-graph/src/paints/schema.ts b/packages/scene-graph/src/paints/schema.ts
index ae57a0e61..59237e80a 100644
--- a/packages/scene-graph/src/paints/schema.ts
+++ b/packages/scene-graph/src/paints/schema.ts
@@ -2,10 +2,40 @@ import * as v from 'valibot'
import { colorSchema } from '../color/schema'
import { finiteNumberSchema, matrixSchema, vectorSchema } from '../primitives/schema'
-import type { FillType } from '../types'
+import type { FillType, GradientTransform } from '../types'
export const gradientStopSchema = v.object({ position: finiteNumberSchema, color: colorSchema })
+const transformRowSchema = v.strictTuple([
+ finiteNumberSchema,
+ finiteNumberSchema,
+ finiteNumberSchema
+])
+
+/**
+ * A paint's `gradientTransform` or `imageTransform` as an author writes it, read into the matrix
+ * fields: Figma's two rows of three, as its plugin API gives them, or the fields themselves. An
+ * extra row, value, or field is refused rather than dropped.
+ */
+export const paintTransformSchema = v.union(
+ [
+ v.pipe(
+ v.strictTuple([transformRowSchema, transformRowSchema]),
+ v.transform(([[m00, m01, m02], [m10, m11, m12]]): GradientTransform => ({
+ m00,
+ m01,
+ m02,
+ m10,
+ m11,
+ m12
+ }))
+ ),
+ v.strictObject(matrixSchema.entries)
+ ],
+ (issue) =>
+ `Expected [[a, b, c], [d, e, f]] or { m00, m01, m02, m10, m11, m12 } but received ${issue.received}`
+)
+
/** Every fill type, as a record so a type added to `FillType` fails to compile until listed. */
const FILL_TYPES = {
SOLID: true,
diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.md
index 6ec6bce4b..0963cc453 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]])]}`. 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.
+- `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. Write it as the plugin API's rows, as export does: `linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] })` runs top to bottom. A paint written as an object takes its `gradientTransform` and `imageTransform` as rows too; the matrix fields `{ m00, m01, m02, m10, m11, m12 }` are accepted as well.
- `shader(effects, { opacity, visible, blendMode })` fills a layer with a shader from the [`shaders`](https://shaders.com) library: an array of effects such as `bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}`, or a preset as shaders.com exports it, `{ components: [...] }`. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.
- `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.