Skip to content

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

fix(figma-api): take shape fields and paint transforms as Figma does (#1380)

Danila Poyarkovde9d5ab70cea
diff --git a/changes/1380/breaking.md b/changes/1380/breaking.md
new file mode 100644
index 000000000..88a40f5cf
--- /dev/null
+++ b/changes/1380/breaking.md
@@ -0,0 +1 @@
+- The plugin API takes and gives a paint's `gradientTransform` and `imageTransform` as Figma does, two rows of three such as `[[1, 0, 0], [0, 1, 0]]`, and rejects the `{ m00, … }` object form and a gradient without a transform.
diff --git a/changes/1380/fixed.md b/changes/1380/fixed.md
new file mode 100644
index 000000000..652740f24
--- /dev/null
+++ b/changes/1380/fixed.md
@@ -0,0 +1 @@
+- Scripts can set a polygon or star's `pointCount`, a star's `innerRadius`, and an ellipse's `arcData`, which did nothing before, and saving a document whose gradients a script set no longer fails.
diff --git a/packages/core/src/figma-api/accessors/shape.ts b/packages/core/src/figma-api/accessors/shape.ts
new file mode 100644
index 000000000..f74cddd41
--- /dev/null
+++ b/packages/core/src/figma-api/accessors/shape.ts
@@ -0,0 +1,110 @@
+import type { ArcData, SceneNode } from '@open-pencil/scene-graph'
+
+import {
+ raw,
+ updateNode,
+ type NodeProxyInternals,
+ type ProxyThis
+} from '#core/figma-api/accessor-utils'
+import { invalid, received } from '#core/figma-api/accessors/text/messages'
+
+/** Figma caps a polygon or star at this many points, past which it keeps the cap. */
+const MAX_POINT_COUNT = 60
+
+const ARC_FIELDS = ['startingAngle', 'endingAngle', 'innerRadius'] as const
+
+/** Figma's complaint about `value` as a number at `at`, or null when it is one. */
+function numberProblem(value: unknown, at = ''): string | null {
+ if (typeof value === 'number' && !Number.isNaN(value)) return null
+ if (value === undefined) return `Required value missing${at}`
+ // These setters spell it as JavaScript does, unlike the text ones `received` follows.
+ const kind = Number.isNaN(value) ? 'NaN' : received(value)
+ return `Expected number, received ${kind}${at}`
+}
+
+/** Figma's complaint about a ratio outside 0 to 1, or null. */
+function ratioProblem(value: number, at = ''): string | null {
+ if (value < 0) return `Too small: expected number to be >=0${at}`
+ if (value > 1) return `Too big: expected number to be <=1${at}`
+ return null
+}
+
+function parsePointCount(value: unknown): number {
+ const problem =
+ numberProblem(value) ??
+ (Number.isInteger(value) ? null : 'Expected int, received number') ??
+ ((value as number) < 3 ? 'Too small: expected number to be >=3' : null)
+ if (problem) throw invalid('set_pointCount', problem, 'pointCount')
+ return Math.min(value as number, MAX_POINT_COUNT)
+}
+
+function parseInnerRadius(value: unknown): number {
+ const problem = numberProblem(value) ?? ratioProblem(value as number)
+ if (problem) throw invalid('set_innerRadius', problem, 'innerRadius')
+ return value as number
+}
+
+/** Figma checks every field and lists each problem on its own line. */
+function parseArcData(value: unknown): ArcData {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
+ throw invalid('set_arcData', `Expected object, received ${received(value)}`, 'arcData')
+ }
+ const fields = value as Partial<Record<(typeof ARC_FIELDS)[number], unknown>>
+ // Each field read once, so a getter cannot pass the checks and then store something else.
+ const values = ARC_FIELDS.map((field) => fields[field])
+ const problems = values.map((value, index) => numberProblem(value, ` at .${ARC_FIELDS[index]}`))
+ const [startingAngle, endingAngle, innerRadius] = values
+ if (!problems[2]) problems[2] = ratioProblem(innerRadius as number, ' at .innerRadius')
+ const listed = problems.filter((problem) => problem !== null)
+ if (listed.length > 0) throw invalid('set_arcData', listed.join('\n'), 'arcData')
+ return {
+ startingAngle: startingAngle as number,
+ endingAngle: endingAngle as number,
+ innerRadius: innerRadius as number
+ }
+}
+
+/** An ellipse without arc data is a whole one, which Figma reports as a full turn. */
+const WHOLE_ELLIPSE: ArcData = { startingAngle: 0, endingAngle: 2 * Math.PI, innerRadius: 0 }
+
+/**
+ * The members of Figma's `PolygonNode`, `StarNode`, and `EllipseNode` that shape them: a point
+ * count, a star's inner radius, and an ellipse's arc. Installed on the proxies of those nodes
+ * alone, as Figma has them on no other node.
+ */
+export function installShapeNodeProxyAccessors(
+ target: object,
+ internals: NodeProxyInternals,
+ type: SceneNode['type']
+): void {
+ if (type === 'POLYGON' || type === 'STAR') {
+ Object.defineProperty(target, 'pointCount', {
+ get(this: ProxyThis): number {
+ return raw(this, internals).pointCount
+ },
+ set(this: ProxyThis, value: number) {
+ updateNode(this, internals, { pointCount: parsePointCount(value) })
+ }
+ })
+ }
+ if (type === 'STAR') {
+ Object.defineProperty(target, 'innerRadius', {
+ get(this: ProxyThis): number {
+ return raw(this, internals).starInnerRadius
+ },
+ set(this: ProxyThis, value: number) {
+ updateNode(this, internals, { starInnerRadius: parseInnerRadius(value) })
+ }
+ })
+ }
+ if (type === 'ELLIPSE') {
+ Object.defineProperty(target, 'arcData', {
+ get(this: ProxyThis): Readonly<ArcData> {
+ return Object.freeze({ ...(raw(this, internals).arcData ?? WHOLE_ELLIPSE) })
+ },
+ set(this: ProxyThis, value: ArcData) {
+ updateNode(this, internals, { arcData: parseArcData(value) })
+ }
+ })
+ }
+}
diff --git a/packages/core/src/figma-api/accessors/text/ranges.ts b/packages/core/src/figma-api/accessors/text/ranges.ts
index 78700ff31..985ce417c 100644
--- a/packages/core/src/figma-api/accessors/text/ranges.ts
+++ b/packages/core/src/figma-api/accessors/text/ranges.ts
@@ -182,7 +182,9 @@ function fillsFromPaints(method: string, value: unknown): CharacterStyleOverride
const problem = paintProblem(paint, index)
if (problem) throw invalid(method, problem)
}
- return (value as FigmaPaint[]).map(figmaPaintToFill)
+ return (value as FigmaPaint[]).map((paint, index) =>
+ figmaPaintToFill(paint, index, method, 'value')
+ )
}
/**
diff --git a/packages/core/src/figma-api/accessors/vector.ts b/packages/core/src/figma-api/accessors/vector.ts
index 77d201708..47ba708be 100644
--- a/packages/core/src/figma-api/accessors/vector.ts
+++ b/packages/core/src/figma-api/accessors/vector.ts
@@ -5,7 +5,6 @@ import {
validateVectorNetwork
} from '@open-pencil/scene-graph'
import type {
- Fill,
GeometryPath,
HandleMirroring,
VectorNetwork as SceneVectorNetwork,
@@ -24,6 +23,8 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { figmaPaintToFill, type FigmaPaint } from '#core/figma-api/accessors/visual'
+import { toFigmaPaint } from '#core/figma-api/paints'
import { geometryBlobToSVGPath, vectorNetworkToSVGPaths } from '#core/io/formats/svg/paths'
import { computeAccurateBounds } from '#core/vector/curve-math'
import { regenerateFillGeometry } from '#core/vector/fill-geometry'
@@ -36,7 +37,7 @@ export interface FigmaVectorPath {
interface FigmaVectorRegion {
readonly windingRule: WindingRule
readonly loops: ReadonlyArray<ReadonlyArray<number>>
- readonly fills?: readonly Fill[]
+ readonly fills?: readonly FigmaPaint[]
readonly fillStyleId?: string
}
@@ -115,7 +116,9 @@ function geometryForRegions(regions: readonly FigmaVectorRegion[]): GeometryPath
return regions.map((region) => ({
windingRule: region.windingRule,
commandsBlob: new Uint8Array(),
- fills: region.fills ? copyFills([...region.fills]) : [],
+ fills: (region.fills ?? []).map((paint, index) =>
+ figmaPaintToFill(paint, index, 'set_vectorNetwork', 'vectorNetwork')
+ ),
fillStyleId: region.fillStyleId ?? ''
}))
}
@@ -245,7 +248,7 @@ function readVectorNetwork(target: ProxyThis, internals: NodeProxyInternals): Fi
windingRule: region.windingRule,
loops: Object.freeze(region.loops.map((loop) => Object.freeze([...loop]))),
fillStyleId: geometry?.fillStyleId ?? '',
- fills: Object.freeze(copyFills(geometry?.fills ?? []))
+ fills: Object.freeze(copyFills(geometry?.fills ?? []).map(toFigmaPaint))
})
})
return Object.freeze({
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index 8170d05dd..6b0359562 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -19,6 +19,7 @@ import {
type ProxyThis
} from '#core/figma-api/accessor-utils'
import { parseFigmaEffects, toFigmaEffect, type FigmaEffect } from '#core/figma-api/effects'
+import { sceneTransforms, toFigmaPaint, type WithFigmaTransforms } from '#core/figma-api/paints'
import { getTextStyle } from '#core/figma-api/text/style'
import {
paintBindings,
@@ -63,20 +64,30 @@ function paintDefaults(paint: Partial<Pick<Fill, 'opacity' | 'visible'>>) {
type FigmaColor = Omit<Color, 'a'> & Partial<Pick<Color, 'a'>>
/**
- * A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility, and the
- * variable its colour is bound to.
+ * A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility, transforms
+ * as two rows of three, and the variable its colour is bound to.
*/
-export type FigmaPaint = Omit<Fill, 'color' | 'opacity' | 'visible' | 'gradientStops'> &
+export type FigmaPaint = WithFigmaTransforms<
+ Omit<Fill, 'color' | 'opacity' | 'visible' | 'gradientStops'>
+> &
Partial<Pick<Fill, 'opacity' | 'visible'>> & {
color?: FigmaColor
gradientStops?: Array<Omit<GradientStop, 'color'> & { color: FigmaColor }>
boundVariables?: { color?: FigmaVariableAlias }
}
-export function figmaPaintToFill({ boundVariables: _bound, ...fill }: FigmaPaint): Fill {
+/** The scene paint for a Figma paint at `index` in the list a script passes to `method`. */
+export function figmaPaintToFill(
+ paint: FigmaPaint,
+ index = 0,
+ method = 'set_fills',
+ property = 'fills'
+): Fill {
+ const { boundVariables: _bound, gradientTransform: _g, imageTransform: _i, ...fill } = paint
return {
...fill,
...paintDefaults(fill),
+ ...sceneTransforms(paint, index, method, property),
color: normalizeColor(fill.color),
gradientStops: fill.gradientStops?.map((stop) => ({
...stop,
@@ -93,7 +104,7 @@ export function installVisualNodeProxyAccessors(
Object.defineProperties(prototype, {
fills: {
// Text reads mixed while its characters are filled differently, and setting it fills them all.
- get(this: ProxyThis): readonly Fill[] | symbol {
+ get(this: ProxyThis): readonly WithFigmaTransforms<Fill>[] | symbol {
const node = raw(this, internals)
if (node.type !== 'TEXT') {
const bound = paintBindings(node, 'fills')
@@ -101,15 +112,20 @@ export function installVisualNodeProxyAccessors(
? (resolvedPaintBindings(graph(this, internals), node).fills ?? node.fills)
: node.fills
return Object.freeze(
- copyFills(fills).map((fill, index) => withPaintBinding(fill, bound.get(index)))
+ copyFills(fills).map((fill, index) =>
+ toFigmaPaint(withPaintBinding(fill, bound.get(index)))
+ )
)
}
const fills = getTextStyle(node, 'fills', mixed)
- return typeof fills === 'symbol' ? fills : Object.freeze(fills as Fill[])
+ // Text styles read for scripts already give Figma's paints.
+ return typeof fills === 'symbol'
+ ? fills
+ : Object.freeze(fills as WithFigmaTransforms<Fill>[])
},
set(this: ProxyThis, value: readonly FigmaPaint[]) {
const node = raw(this, internals)
- const fills = value.map(figmaPaintToFill)
+ const fills = value.map((paint, index) => figmaPaintToFill(paint, index))
updateNode(
this,
internals,
@@ -119,21 +135,23 @@ export function installVisualNodeProxyAccessors(
}
},
strokes: {
- get(this: ProxyThis): readonly Stroke[] {
+ 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) => withPaintBinding(stroke, bound.get(index)))
+ copyStrokes(strokes).map((stroke, index) =>
+ toFigmaPaint(withPaintBinding(stroke, bound.get(index)))
+ )
)
},
// Figma paints carry no geometry; a stroke takes the node's weight and alignment, which
// outlast its strokes.
set(
this: ProxyThis,
- value: readonly (Omit<Stroke, 'weight' | 'align'> &
+ value: readonly (WithFigmaTransforms<Omit<Stroke, 'weight' | 'align'>> &
Partial<Pick<Stroke, 'weight' | 'align'>> & {
boundVariables?: { color?: FigmaVariableAlias }
})[]
@@ -142,13 +160,22 @@ export function installVisualNodeProxyAccessors(
const geometry = newStrokeGeometry(raw(owner, internals))
// The script keeps its paint objects; the node gets its own copies of every nested value.
const strokes = copyStrokes(
- value.map(({ boundVariables: _bound, ...stroke }) => ({
- ...stroke,
- ...paintDefaults(stroke),
- weight: stroke.weight ?? geometry.weight,
- align: stroke.align ?? geometry.align,
- color: normalizeColor(stroke.color)
- }))
+ value.map((paint, index) => {
+ const {
+ boundVariables: _bound,
+ gradientTransform: _g,
+ imageTransform: _i,
+ ...stroke
+ } = paint
+ return {
+ ...stroke,
+ ...paintDefaults(stroke),
+ ...sceneTransforms(paint, index, 'set_strokes', 'strokes'),
+ weight: stroke.weight ?? geometry.weight,
+ align: stroke.align ?? geometry.align,
+ color: normalizeColor(stroke.color)
+ }
+ })
)
const kept = newStrokeGeometry({
strokes,
diff --git a/packages/core/src/figma-api/paints.ts b/packages/core/src/figma-api/paints.ts
new file mode 100644
index 000000000..3ac2375ec
--- /dev/null
+++ b/packages/core/src/figma-api/paints.ts
@@ -0,0 +1,88 @@
+import type { Fill, GradientTransform } from '@open-pencil/scene-graph'
+import { IDENTITY_GRADIENT_TRANSFORM } from '@open-pencil/scene-graph/gradient'
+
+import type { FigmaTransform } from './types'
+
+/** The transforms a paint carries: gradients map the layer onto gradient space, images crop. */
+const TRANSFORM_FIELDS = ['gradientTransform', 'imageTransform'] as const
+
+type TransformField = (typeof TRANSFORM_FIELDS)[number]
+
+/** A paint as Figma's plugin API gives and takes it, its transforms as two rows of three. */
+export type WithFigmaTransforms<T> = Omit<T, TransformField> & {
+ gradientTransform?: FigmaTransform
+ 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) &&
+ value.length === 3 &&
+ value.every((item) => typeof item === 'number' && Number.isFinite(item))
+ )
+}
+
+/** Figma's complaint about `value` as a transform, or null when it is two rows of three numbers. */
+function transformProblem(value: unknown): string | null {
+ if (value === undefined) return 'Required value missing'
+ if (!Array.isArray(value))
+ return `Expected array, received ${value === null ? 'null' : typeof value}`
+ if (value.length < 2) return 'Too small: expected array to have exactly 2 items'
+ if (value.length > 2) return 'Too big: expected array to have exactly 2 items'
+ return value.every(isRow) ? null : 'Expected array of 3 numbers'
+}
+
+/** Whether Figma requires `field` on a paint of `type`, as it does a gradient's transform. */
+function requires(type: Fill['type'], field: TransformField): boolean {
+ return field === 'gradientTransform' && type.startsWith('GRADIENT_')
+}
+
+/**
+ * The scene transforms of a paint a script passes to `method`, at `index` in `property`. Figma
+ * takes only two rows of three numbers and throws the way its `fills` and `strokes` setters do.
+ */
+export function sceneTransforms(
+ paint: { type: Fill['type'] } & Partial<Record<TransformField, unknown>>,
+ index: number,
+ method = 'set_fills',
+ property = 'fills'
+): Partial<Record<TransformField, GradientTransform>> {
+ const transforms: Partial<Record<TransformField, GradientTransform>> = {}
+ for (const field of TRANSFORM_FIELDS) {
+ const value = paint[field]
+ if (value === undefined && !requires(paint.type, field)) continue
+ const problem = transformProblem(value)
+ if (problem) {
+ const at = `[${index}].${field}`
+ throw new Error(
+ `in ${method}: Property "${property}" failed validation: Expected ${at} to be one of ` +
+ `the following, but none matched:\n ${problem} at ${at}`
+ )
+ }
+ const [[m00, m01, m02], [m10, m11, m12]] = value as FigmaTransform
+ transforms[field] = { m00, m01, m02, m10, m11, m12 }
+ }
+ return transforms
+}
+
+/**
+ * `paint` with its transforms as Figma gives them: two rows of three. An image paint reports the
+ * identity when it has none, as Figma's do outside crop mode.
+ */
+export function toFigmaPaint<T extends Fill>(paint: T): WithFigmaTransforms<T> {
+ const { gradientTransform, imageTransform, ...rest } = paint
+ const image = imageTransform ?? (paint.type === 'IMAGE' ? IDENTITY_GRADIENT_TRANSFORM : undefined)
+ return {
+ ...rest,
+ ...(gradientTransform && { gradientTransform: toFigmaTransform(gradientTransform) }),
+ ...(image && { imageTransform: toFigmaTransform(image) })
+ }
+}
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index ac9529134..2625d42d8 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -5,6 +5,7 @@ import {
slotPropertyId
} from '@open-pencil/scene-graph'
import type {
+ ArcData,
GroupFitOptions,
HyperlinkTarget,
SceneGraph,
@@ -25,6 +26,7 @@ import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'
import { installBasicNodeProxyAccessors } from './accessors/basic'
import { installConnectorNodeProxyAccessors } from './accessors/connector'
import { installLayoutNodeProxyAccessors } from './accessors/layout'
+import { installShapeNodeProxyAccessors } from './accessors/shape'
import { installStickyNodeProxyAccessors, pluginChildren } from './accessors/sticky'
import { installStrokeNodeProxyAccessors } from './accessors/strokes'
import { installTextNodeProxyAccessors } from './accessors/text'
@@ -49,6 +51,7 @@ import type { FigmaFontName } from './fonts'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
import { installInstanceOverrideAccessors, type FigmaInstanceOverride } from './overrides'
import { getPageBackgrounds, setPageBackgrounds } from './page-backgrounds'
+import { toFigmaPaint, type WithFigmaTransforms } from './paints'
import { installPluginDataMethods, type PluginDataMethods } from './plugin-data'
import { nodeProxyToJSON } from './serialization'
import { installShapeWithTextAccessors } from './shape-with-text'
@@ -110,8 +113,8 @@ export class FigmaNodeProxy {
declare readonly absoluteBoundingBox: Rect
declare readonly absoluteRenderBounds: Rect | null
- declare fills: readonly Fill[] | symbol
- declare strokes: readonly Stroke[]
+ declare fills: readonly WithFigmaTransforms<Fill>[] | symbol
+ declare strokes: readonly WithFigmaTransforms<Stroke>[]
declare effects: readonly FigmaEffect[]
declare opacity: number
declare visible: boolean
@@ -157,6 +160,9 @@ export class FigmaNodeProxy {
declare constrainProportions: boolean
declare lockAspectRatio: () => void
declare unlockAspectRatio: () => void
+ declare pointCount: number
+ declare innerRadius: number
+ declare arcData: Readonly<ArcData>
declare vectorPaths: readonly FigmaVectorPath[]
declare vectorNetwork: FigmaVectorNetwork
declare setVectorNetworkAsync: (vectorNetwork: FigmaVectorNetwork) => Promise<void>
@@ -269,13 +275,10 @@ export class FigmaNodeProxy {
this[INTERNAL_ID] = id
this[INTERNAL_GRAPH] = graph
this[INTERNAL_API] = api
- if (graph.getNode(id)?.type === 'VECTOR') {
- installVectorNodeProxyAccessors(
- this,
- { id: INTERNAL_ID, graph: INTERNAL_GRAPH, api: INTERNAL_API },
- MIXED
- )
- }
+ const type = graph.getNode(id)?.type
+ const internals = { id: INTERNAL_ID, graph: INTERNAL_GRAPH, api: INTERNAL_API }
+ if (type === 'VECTOR') installVectorNodeProxyAccessors(this, internals, MIXED)
+ if (type) installShapeNodeProxyAccessors(this, internals, type)
}
private _update(changes: Partial<SceneNode>): void {
@@ -330,12 +333,15 @@ export class FigmaNodeProxy {
// --- Components ---
- get backgrounds(): readonly Fill[] {
- return getPageBackgrounds(this._raw())
+ get backgrounds(): readonly WithFigmaTransforms<Fill>[] {
+ return Object.freeze(getPageBackgrounds(this._raw()).map(toFigmaPaint))
}
set backgrounds(value: readonly FigmaPaint[]) {
- setPageBackgrounds(this[INTERNAL_GRAPH], this._raw(), value.map(figmaPaintToFill))
+ const fills = value.map((paint, index) =>
+ figmaPaintToFill(paint, index, 'set_backgrounds', 'backgrounds')
+ )
+ setPageBackgrounds(this[INTERNAL_GRAPH], this._raw(), fills)
}
/** The async form Figma requires in dynamic-page mode; same result as mainComponent. */
diff --git a/packages/core/src/figma-api/text/style.ts b/packages/core/src/figma-api/text/style.ts
index 3ae04d1b2..09d4117ad 100644
--- a/packages/core/src/figma-api/text/style.ts
+++ b/packages/core/src/figma-api/text/style.ts
@@ -11,6 +11,7 @@ import {
import { copyFills } from '@open-pencil/scene-graph/copy'
import { weightToStyleName } from '#core/figma-api/fonts'
+import { toFigmaPaint, type WithFigmaTransforms } from '#core/figma-api/paints'
import { variableAlias } from '#core/figma-api/variables/values'
import { characterStyles, nodeStyle, type CharacterStyle } from '#core/text/character-style'
@@ -60,7 +61,7 @@ function underlined(style: CharacterStyle): boolean {
/** Figma's paint for an underline colour of its own, or automatic, following the text. */
function decorationColor(style: CharacterStyle) {
const paint = style.textDecorationFills.at(0)
- return paint ? { value: copyFills([paint])[0] } : { value: 'AUTO' as const }
+ return paint ? { value: toFigmaPaint(copyFills([paint])[0]) } : { value: 'AUTO' as const }
}
function fontFeatureMap(style: CharacterStyle): Record<string, boolean> {
@@ -99,7 +100,7 @@ const FIELD_READERS: Record<TextSegmentField, (context: FieldContext) => unknown
textCase: ({ style }) => style.textCase,
lineHeight: ({ style }) => pixels(style.lineHeight),
letterSpacing: ({ style }) => ({ unit: 'PIXELS', value: style.letterSpacing }),
- fills: ({ style }) => copyFills(style.fills),
+ fills: ({ style }) => copyFills(style.fills).map(toFigmaPaint),
textStyleId: ({ style }) => style.textStyleId ?? '',
fillStyleId: ({ style }) => style.fillStyleId ?? '',
listOptions: ({ node, paragraph }) => ({
@@ -249,4 +250,4 @@ export function rangeHasUnderline(node: SceneNode, start: number, end: number):
return characterStyles(node, start, end).some(underlined)
}
-export type FigmaDecorationColor = { value: 'AUTO' } | { value: Fill }
+export type FigmaDecorationColor = { value: 'AUTO' } | { value: WithFigmaTransforms<Fill> }
diff --git a/packages/core/src/tools/modify/paint.ts b/packages/core/src/tools/modify/paint.ts
index df61a2d35..c99b6c9a8 100644
--- a/packages/core/src/tools/modify/paint.ts
+++ b/packages/core/src/tools/modify/paint.ts
@@ -6,6 +6,7 @@ import { 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 { toolNumber, nodeIdInput } from '#core/tools/input'
import { defineTool } from '#core/tools/schema'
@@ -66,7 +67,7 @@ export const setFill = defineTool({
{ position: 0, color: c },
{ position: 1, color: cEnd }
],
- gradientTransform: linearGradientTransform(start, end)
+ gradientTransform: toFigmaTransform(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
new file mode 100644
index 000000000..442c3b267
--- /dev/null
+++ b/packages/core/tests/figma-api/paints.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { FigmaAPI } from '#core/figma-api'
+
+const STOPS = [
+ { position: 0, color: { r: 1, g: 0, b: 0, a: 1 } },
+ { position: 1, color: { r: 0, g: 0, b: 1, a: 1 } }
+]
+
+/** What the proxies' paint types ask of a gradient beside its stops and transform. */
+const GRADIENT = { color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }
+
+const SWAPPED = [
+ [0, 1, 0],
+ [-1, 0, 1]
+] as [[number, number, number], [number, number, number]]
+
+function api() {
+ const graph = new SceneGraph()
+ return { graph, figma: new FigmaAPI(graph) }
+}
+
+// Figma's plugin API takes and gives a paint's transforms as two rows of three, as measured with
+// the same scripts in Figma.
+describe('a gradient transform', () => {
+ test('goes in and comes out as two rows of three, on fills and strokes alike', () => {
+ const { graph, figma } = api()
+ const rectangle = figma.createRectangle()
+ const paint = {
+ ...GRADIENT,
+ type: 'GRADIENT_LINEAR' as const,
+ gradientTransform: SWAPPED,
+ gradientStops: STOPS
+ }
+ // Strokes carry the node's weight and alignment too, which Figma's paint type leaves out.
+ const stroke = { ...paint, weight: 1, align: 'CENTER' as const }
+ rectangle.fills = [paint]
+ rectangle.strokes = [stroke]
+ expect(rectangle.fills).toEqual([expect.objectContaining({ gradientTransform: SWAPPED })])
+ expect(rectangle.strokes).toEqual([expect.objectContaining({ gradientTransform: SWAPPED })])
+ const stored = { m00: 0, m01: 1, m02: 0, m10: -1, m11: 0, m12: 1 }
+ expect(graph.getNode(rectangle.id)?.fills[0].gradientTransform).toEqual(stored)
+ expect(graph.getNode(rectangle.id)?.strokes[0].gradientTransform).toEqual(stored)
+ })
+
+ test('round-trips from one layer to another', () => {
+ const { figma } = api()
+ const source = figma.createRectangle()
+ source.fills = [
+ { ...GRADIENT, type: 'GRADIENT_RADIAL', gradientTransform: SWAPPED, gradientStops: STOPS }
+ ]
+ const target = figma.createEllipse()
+ target.fills = source.fills
+ expect(target.fills).toEqual(source.fills)
+ })
+
+ test('is required, and only as rows', () => {
+ const rectangle = api().figma.createRectangle()
+ const failure = (setter: string, at: string, problem: string) =>
+ `in set_${setter}: Property "${setter}" failed validation: Expected ${at} to be one of the ` +
+ `following, but none matched:\n ${problem} at ${at}`
+ expect(() => {
+ rectangle.fills = [{ type: 'GRADIENT_LINEAR', gradientStops: STOPS }] as never
+ }).toThrow(failure('fills', '[0].gradientTransform', 'Required value missing'))
+ expect(() => {
+ rectangle.strokes = [
+ { type: 'SOLID', color: { r: 1, g: 0, b: 0 } },
+ {
+ type: 'GRADIENT_LINEAR',
+ gradientTransform: { m00: 1, m01: 0, m02: 0, m10: 0, m11: 1, m12: 0 } as never,
+ gradientStops: STOPS
+ }
+ ] as never
+ }).toThrow(failure('strokes', '[1].gradientTransform', 'Expected array, received object'))
+ expect(() => {
+ rectangle.fills = [
+ {
+ type: 'GRADIENT_LINEAR',
+ gradientTransform: [[1, 0, 0]],
+ gradientStops: STOPS
+ }
+ ] as never
+ }).toThrow(
+ failure(
+ 'fills',
+ '[0].gradientTransform',
+ 'Too small: expected array to have exactly 2 items'
+ )
+ )
+ expect(() => {
+ rectangle.fills = [
+ {
+ type: 'GRADIENT_LINEAR',
+ gradientTransform: [
+ [1, 0, 0],
+ [0, 1, 0],
+ [0, 0, 1]
+ ],
+ gradientStops: STOPS
+ }
+ ] as never
+ }).toThrow(
+ failure('fills', '[0].gradientTransform', 'Too big: expected array to have exactly 2 items')
+ )
+ })
+})
+
+describe('an image transform', () => {
+ test('reads the identity when the paint has none', () => {
+ const { graph, figma } = api()
+ const rectangle = figma.createRectangle()
+ graph.updateNode(rectangle.id, {
+ fills: [
+ {
+ type: 'IMAGE',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ opacity: 1,
+ visible: true,
+ imageHash: 'hash',
+ imageScaleMode: 'FILL'
+ }
+ ]
+ })
+ expect(rectangle.fills).toEqual([
+ expect.objectContaining({
+ imageTransform: [
+ [1, 0, 0],
+ [0, 1, 0]
+ ]
+ })
+ ])
+ })
+})
diff --git a/packages/core/tests/figma-api/points-and-arcs.test.ts b/packages/core/tests/figma-api/points-and-arcs.test.ts
new file mode 100644
index 000000000..5077f58a8
--- /dev/null
+++ b/packages/core/tests/figma-api/points-and-arcs.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { FigmaAPI } from '#core/figma-api'
+
+function api() {
+ const graph = new SceneGraph()
+ return { graph, figma: new FigmaAPI(graph) }
+}
+
+// Measured with the same scripts in Figma's plugin API.
+describe('a polygon or star point count', () => {
+ test('reshapes the layer', () => {
+ const { graph, figma } = api()
+ const polygon = figma.createPolygon()
+ expect(polygon.pointCount).toBe(3)
+ polygon.pointCount = 6
+ expect(polygon.pointCount).toBe(6)
+ expect(graph.getNode(polygon.id)?.pointCount).toBe(6)
+ const star = figma.createStar()
+ expect(star.pointCount).toBe(5)
+ })
+
+ test('stops at 60 points', () => {
+ const polygon = api().figma.createPolygon()
+ polygon.pointCount = 1000
+ expect(polygon.pointCount).toBe(60)
+ })
+
+ test('takes only whole numbers of at least 3', () => {
+ const polygon = api().figma.createPolygon()
+ const message = (problem: string) =>
+ `in set_pointCount: Property "pointCount" failed validation: ${problem}`
+ expect(() => (polygon.pointCount = 2)).toThrow(
+ message('Too small: expected number to be >=3')
+ )
+ expect(() => (polygon.pointCount = 3.6)).toThrow(message('Expected int, received number'))
+ expect(() => (polygon.pointCount = Number.NaN)).toThrow(
+ message('Expected number, received NaN')
+ )
+ expect(polygon.pointCount).toBe(3)
+ })
+})
+
+describe('a star inner radius', () => {
+ test('sets how deep the star cuts in, between 0 and 1', () => {
+ const { graph, figma } = api()
+ const star = figma.createStar()
+ star.innerRadius = 0.25
+ expect(star.innerRadius).toBe(0.25)
+ expect(graph.getNode(star.id)?.starInnerRadius).toBe(0.25)
+ const message = (problem: string) =>
+ `in set_innerRadius: Property "innerRadius" failed validation: ${problem}`
+ expect(() => (star.innerRadius = -0.5)).toThrow(message('Too small: expected number to be >=0'))
+ expect(() => (star.innerRadius = 1.5)).toThrow(message('Too big: expected number to be <=1'))
+ expect(() => (star.innerRadius = Number.NaN)).toThrow(message('Expected number, received NaN'))
+ })
+})
+
+describe('an ellipse arc', () => {
+ test('reads a whole turn on a whole ellipse', () => {
+ const arc = api().figma.createEllipse().arcData
+ expect(arc.startingAngle).toBe(0)
+ expect(arc.endingAngle).toBeCloseTo(2 * Math.PI, 6)
+ expect(arc.innerRadius).toBe(0)
+ })
+
+ test('cuts the ellipse to an arc, keeping angles past a turn or below zero', () => {
+ const { graph, figma } = api()
+ const ellipse = figma.createEllipse()
+ ellipse.arcData = { startingAngle: 1, endingAngle: 7, innerRadius: 0.5 }
+ expect(ellipse.arcData).toEqual({ startingAngle: 1, endingAngle: 7, innerRadius: 0.5 })
+ expect(graph.getNode(ellipse.id)?.arcData).toEqual({
+ startingAngle: 1,
+ endingAngle: 7,
+ innerRadius: 0.5
+ })
+ ellipse.arcData = { startingAngle: -1, endingAngle: -4, innerRadius: 0 }
+ expect(ellipse.arcData.endingAngle).toBe(-4)
+ })
+
+ test('gives a frozen copy', () => {
+ const ellipse = api().figma.createEllipse()
+ const arc = ellipse.arcData
+ expect(Object.isFrozen(arc)).toBe(true)
+ })
+
+ test('lists every missing or invalid field', () => {
+ const ellipse = api().figma.createEllipse()
+ const message = (problem: string) =>
+ `in set_arcData: Property "arcData" failed validation: ${problem}`
+ expect(() => (ellipse.arcData = { startingAngle: 0 } as never)).toThrow(
+ message('Required value missing at .endingAngle\nRequired value missing at .innerRadius')
+ )
+ expect(() => (ellipse.arcData = { startingAngle: 0, endingAngle: 3, innerRadius: 2 })).toThrow(
+ message('Too big: expected number to be <=1 at .innerRadius')
+ )
+ expect(() => (ellipse.arcData = null as never)).toThrow(
+ message('Expected object, received null')
+ )
+ })
+})
+
+describe('shape members on other layers', () => {
+ test('exist only on the layers Figma gives them to', () => {
+ const { figma } = api()
+ const rectangle = figma.createRectangle()
+ expect('pointCount' in rectangle).toBe(false)
+ expect('arcData' in rectangle).toBe(false)
+ expect('arcData' in figma.createStar()).toBe(false)
+ expect('innerRadius' in figma.createPolygon()).toBe(false)
+ })
+})
diff --git a/tests/engine/figma/api/helpers.ts b/tests/engine/figma/api/helpers.ts
index 0c08b5174..21e92d4c8 100644
--- a/tests/engine/figma/api/helpers.ts
+++ b/tests/engine/figma/api/helpers.ts
@@ -33,10 +33,13 @@ export function asPageNode(
* A solid paint that satisfies both the OpenPencil `Fill` and the Figma `SolidPaint` shape, as the
* node proxies expose the intersection of the two.
*/
+/** A solid paint both the scene graph and the plugin API take: it carries no transform. */
+type SolidFill = Omit<Fill, 'gradientTransform' | 'imageTransform'> & SolidPaint
+
export function solidFill(
color: Color,
overrides: { opacity?: number; visible?: boolean } = {}
-): Fill & SolidPaint {
+): SolidFill {
return {
type: 'SOLID',
color,
@@ -49,7 +52,7 @@ export function solidFill(
export function solidStroke(
color: Color,
stroke: { weight: number; align: Stroke['align']; opacity?: number; visible?: boolean }
-): Stroke & SolidPaint {
+): SolidFill & Pick<Stroke, 'weight' | 'align'> {
return {
...solidFill(color, stroke),
weight: stroke.weight,