AI-native design editor. Open-source Figma alternative.
feat(figma-api): add fillGeometry, strokeGeometry, and outlineStroke (#1723)
Danila Poyarkov01114fb5ec03
diff --git a/changes/1723/added.md b/changes/1723/added.mdnew file mode 100644index 000000000..3c0dc1ccd--- /dev/null+++ b/changes/1723/added.md@@ -0,0 +1 @@+- Scripts read a layer's `fillGeometry` and `strokeGeometry` and call `outlineStroke()` as in Figma, in the apps and in `open-pencil eval`.diff --git a/changes/1723/fixed.md b/changes/1723/fixed.mdnew file mode 100644index 000000000..ba83368e2--- /dev/null+++ b/changes/1723/fixed.md@@ -0,0 +1,3 @@+- Dashes a script sets with `dashPattern` now draw.+- New stars have Figma's inner radius.+- `figma.flatten()` and boolean operations in `open-pencil eval` and headless CLI tools make real vectors and fit their bounds, instead of a placeholder box.diff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex 27da4a1a7..e281b4db1 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -1,6 +1,6 @@import { defineCommand } from 'citty'-import { FigmaAPI, flushPendingLayout } from '@open-pencil/core/figma-api'+import { flushPendingLayout } from '@open-pencil/core/figma-api'import { compileScript } from '@open-pencil/core/tools'import { isAppMode, requireFile, rpc } from '#cli/app/client'@@ -14,6 +14,7 @@ import {populateWholeDocument,writeFigDocument} from '#cli/headless'+import { createHeadlessFigma } from '#cli/tool-data'function printResult(value: unknown, json: boolean) {if (json || !process.stdout.isTTY) {@@ -73,12 +74,7 @@ export default defineCommand({const graph = await loadDocument(file)populateWholeDocument(graph)await measureDocumentText(graph)- const figma = new FigmaAPI(graph)- // CanvasKit starts only when a script exports an image.- figma.exportImage = async (nodeIds, options) => {- const { headlessRenderNodes } = await import('@open-pencil/core/io/formats/raster')- return headlessRenderNodes(graph, options.pageId ?? figma.currentPageId, nodeIds, options)- }+ const figma = await createHeadlessFigma(graph)let result: unknowntry {diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex 8e9671cd9..fa2d985b3 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -1,11 +1,11 @@import { readFile, realpath } from 'node:fs/promises'import { dirname, resolve, sep } from 'node:path'-import { SkiaRenderer } from '@open-pencil/core/canvas'+import type { SkiaRenderer } from '@open-pencil/core/canvas'import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'import { headlessHTMLReader } from '@open-pencil/core/io/formats/html/import'-import { initCanvasKit } from '@open-pencil/core/io/formats/raster'+import { headlessRenderer, initCanvasKit } from '@open-pencil/core/io/formats/raster'import {computeAllLayouts,installTextMeasurer,@@ -52,21 +52,19 @@ export async function loadDocument(filePath: string): Promise<SceneGraph> {return graph}-let textMeasurer: Promise<void> | null = null+let textMeasurer: Promise<SkiaRenderer> | null = null/*** Measure text a script or tool lays out with CanvasKit and the fonts it loads, as the app* does, instead of the estimate that knows neither line breaks nor wrapping. The document as- * loaded keeps the layout its file gives it; only edits made afterwards are measured.+ * loaded keeps the layout its file gives it; only edits made afterwards are measured. Resolves+ * to the renderer that measures, which also measures geometry for the Figma API.*/-export function measureTextHeadlessly(): Promise<void> {+export function measureTextHeadlessly(): Promise<SkiaRenderer> {textMeasurer ??= (async () => {- const ck = await initCanvasKit()- const surface = ck.MakeSurface(1, 1)- if (!surface) throw new Error('CanvasKit could not make a surface to measure text')- const renderer = new SkiaRenderer(ck, surface)- await renderer.loadFonts()+ const renderer = await headlessRenderer()installTextMeasurer((node, maxWidth) => renderer.measureTextNode(node, maxWidth))+ return renderer})().catch((error: unknown) => {textMeasurer = nullthrow errordiff --git a/packages/cli/src/tool-data.ts b/packages/cli/src/tool-data.tsindex 9339d044c..9bcc4d7dd 100644--- a/packages/cli/src/tool-data.ts+++ b/packages/cli/src/tool-data.ts@@ -13,12 +13,21 @@ import {editDocument,loadDocument,measureDocumentText,+ measureTextHeadlessly,populateWholeDocument} from '#cli/headless'-/** A Figma API over a headless document, with CanvasKit raster export and pixel decoding. */+/**+ * A Figma API over a headless document, with CanvasKit raster export and pixel decoding, and+ * the renderer that measures text measuring geometry, booleans, and flatten too.+ */export async function createHeadlessFigma(graph: SceneGraph): Promise<FigmaAPI> {const figma = new FigmaAPI(graph)+ const renderer = await measureTextHeadlessly()+ // The process's one renderer keeps paths by layer id, which another document's layers share.+ renderer.nodePaths.clear()+ renderer.invalidateAllPictures()+ figma.setRenderer(renderer)figma.exportImage = (nodeIds, options) =>headlessRenderNodes(graph, options.pageId ?? figma.currentPageId, nodeIds, options)figma.rasterCodec = createCanvasKitRasterCodec(await initCanvasKit())diff --git a/packages/cli/tests/commands/eval.test.ts b/packages/cli/tests/commands/eval.test.tsindex 597c3ee22..fb87031da 100644--- a/packages/cli/tests/commands/eval.test.ts+++ b/packages/cli/tests/commands/eval.test.ts@@ -100,6 +100,44 @@ describe('eval CLI', () => {expect(heights.paragraph).toBeGreaterThan(heights.line * 2)})+ test('measures geometry, booleans, and flatten with the renderer that measures text', async () => {+ const script = `+ const rect = figma.createRectangle()+ rect.resize(40, 20)+ rect.strokes = [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }]+ rect.strokeWeight = 4+ const fill = rect.fillGeometry[0].data+ const strokes = rect.strokeGeometry.length+ const outline = rect.outlineStroke().name+ const flat = figma.flatten([figma.createStar()], figma.currentPage)+ return { fill, strokes, outline, flattened: flat.vectorNetwork.vertices.length > 0 }+ `+ const result = await cli(+ ['eval', join(FIXTURES, 'circle-text.fig'), '--stdin', '--json'],+ script+ )+ expect(result.exitCode).toBe(0)+ const measured = v.parse(+ v.pipe(+ v.string(),+ v.parseJson(),+ v.object({+ fill: v.string(),+ strokes: v.number(),+ outline: v.string(),+ flattened: v.boolean()+ })+ ),+ result.stdout+ )+ expect(measured).toEqual({+ fill: 'M0 0 L40 0 L40 20 L0 20 L0 0 Z',+ strokes: 1,+ outline: 'Rectangle (Stroke)',+ flattened: true+ })+ })+test('saves a script’s edits laid out, though the script never read them back', async () => {const out = join(await mkdtemp(join(tmpdir(), 'open-pencil-eval-')), 'badge.fig')// A hugging badge whose label a property shortens: its saved width fits the new label.diff --git a/packages/core/src/canvas/boolean.ts b/packages/core/src/canvas/boolean.tsindex e2f6e06fb..c19d69dfd 100644--- a/packages/core/src/canvas/boolean.ts+++ b/packages/core/src/canvas/boolean.ts@@ -100,7 +100,8 @@ export function baseShapePath(r: SkiaRenderer, node: SceneNode): Path | null {return r.makeNodeShapePath(node)}-function strokeSourcePath(r: SkiaRenderer, node: SceneNode): Path | null {+/** The path a layer's strokes follow: a vector's own paths, or its shape. */+export function strokeSourcePath(r: SkiaRenderer, node: SceneNode): Path | null {const network = node.type === 'VECTOR' ? r.getVectorPaths(node) : nullif (!network || network.length === 0) {return baseShapePath(r, node)diff --git a/packages/core/src/canvas/geometry.ts b/packages/core/src/canvas/geometry.tsnew file mode 100644index 000000000..9c540b305--- /dev/null+++ b/packages/core/src/canvas/geometry.ts@@ -0,0 +1,238 @@+import type { Path, PathBuilder } from 'canvaskit-wasm'++import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'++import { isOpenVectorNetwork } from '#core/vector/connectivity'++import { baseShapePath, makeBooleanOperationPath, strokeSourcePath } from './boolean'+import { appendVerb, forEachVerb } from './paths/verbs'+import type { SkiaRenderer } from './renderer'+import { nodeHasRadius } from './shapes'+import { getStrokeCapEntity, getStrokeJoinEntity, normalizeDashPattern } from './strokes'+import { makeLineSegmentPath } from './strokes/line'+import { dashPath } from './strokes/outlined-dashes'+import { sideStrokeRRects, type SideWeights } from './strokes/sides'++// The geometry Figma's plugin API reports for a layer (`fillGeometry`, `strokeGeometry`), in the+// layer's own box. Measured in Figma desktop 126.++/**+ * The outline of what a layer fills: its shape whatever its fills, a boolean's result, or each+ * region of a vector. Lines and open vectors fill nothing.+ */+export function fillGeometryPaths(r: SkiaRenderer, graph: SceneGraph, node: SceneNode): Path[] {+ if (node.type === 'LINE') return []+ if (node.type === 'BOOLEAN_OPERATION') {+ const result = makeBooleanOperationPath(r, node, graph)+ return result ? [result] : []+ }+ if (node.type === 'VECTOR') {+ const network = node.vectorNetwork+ if (network && isOpenVectorNetwork(network)) return []+ const regions = r.getVectorPaths(node)+ if (regions && regions.length > 0) return regions.map((region) => region.copy())+ }+ const shape = baseShapePath(r, node)+ return shape ? [shape] : []+}++/**+ * The band each visible stroke of a layer paints, centred on its edge: as wide as the stroke when+ * centred, and twice as wide when inside or outside, which Figma leaves for the fill to clip.+ * Null when no stroke paints.+ */+export function strokeGeometryPath(+ r: SkiaRenderer,+ graph: SceneGraph,+ node: SceneNode+): Path | null {+ const builder = new r.ck.PathBuilder()+ let painted = false+ for (const stroke of node.strokes) {+ // A side of its own weight paints whatever the stroke's weight says.+ if (!stroke.visible || (!node.independentStrokeWeights && stroke.weight <= 0)) continue+ const band = strokeBand(r, graph, node, stroke)+ if (!band) continue+ builder.addPath(band)+ band.delete()+ painted = true+ }+ const path = builder.detachAndDelete()+ if (painted) return path+ path.delete()+ return null+}++/** The path a stroke follows: a line's segment, a boolean's result, or the layer's own edge. */+function strokeSource(r: SkiaRenderer, graph: SceneGraph, node: SceneNode): Path | null {+ if (node.type === 'LINE') return makeLineSegmentPath(r, node)+ if (node.type === 'BOOLEAN_OPERATION') return makeBooleanOperationPath(r, node, graph)+ return strokeSourcePath(r, node)+}++function strokeBand(+ r: SkiaRenderer,+ graph: SceneGraph,+ node: SceneNode,+ stroke: Stroke+): Path | null {+ const network = node.type === 'VECTOR' ? node.vectorNetwork : null+ const pattern = normalizeDashPattern(stroke.dashPattern)+ const centred = stroke.align === 'CENTER' || (network !== null && isOpenVectorNetwork(network))+ const scale = centred ? 1 : 2+ const source = strokeSource(r, graph, node)+ if (!source) return null+ const options = (width: number) => ({+ width,+ cap: getStrokeCapEntity(r, stroke.cap ?? node.strokeCap),+ join: getStrokeJoinEntity(r, stroke.join ?? node.strokeJoin),+ miter_limit: node.strokeMiterLimit+ })+ try {+ if (node.independentStrokeWeights) {+ const ring = sidesBand(r, node, scale)+ if (!ring || pattern.length === 0) return ring+ const dashes = dashedSides(r, node, scale, (line, width) =>+ dashPath(r, line, pattern, options(width), false)+ )+ // Rounded corners: the straight dashes are kept within the ring the corners round off.+ const band =+ dashes && nodeHasRadius(node)+ ? r.ck.Path.MakeFromOp(dashes, ring, r.ck.PathOp.Intersect)+ : dashes+ if (band !== dashes) dashes?.delete()+ ring.delete()+ return band+ }+ const width = options(stroke.weight * scale)+ return pattern.length > 0+ ? dashedContours(r, source, pattern, width)+ : source.makeStroked(width)+ } finally {+ source.delete()+ }+}++/** `source` dashed contour by contour, each from its own start, as Figma dashes each loop. */+function dashedContours(+ r: SkiaRenderer,+ source: Path,+ pattern: readonly number[],+ options: Parameters<Path['makeStroked']>[0]+): Path | null {+ const builder = new r.ck.PathBuilder()+ for (const { path, closed } of contours(r, source)) {+ const dashes = dashPath(r, path, pattern, options, closed)+ path.delete()+ if (!dashes) continue+ builder.addPath(dashes)+ dashes.delete()+ }+ return builder.detachAndDelete()+}++/** Each contour of `source` as a path of its own, and whether it closes. */+function contours(r: SkiaRenderer, source: Path): { path: Path; closed: boolean }[] {+ const found: { path: Path; closed: boolean }[] = []+ let current: { builder: PathBuilder; closed: boolean } | null = null+ const finish = () => {+ if (current) found.push({ path: current.builder.detachAndDelete(), closed: current.closed })+ current = null+ }+ forEachVerb(r.ck, source, (verb, a) => {+ if (verb === r.ck.MOVE_VERB) {+ finish()+ current = { builder: new r.ck.PathBuilder(), closed: false }+ }+ if (!current) return+ if (verb === r.ck.CLOSE_VERB) current.closed = true+ appendVerb(r.ck, current.builder, verb, a)+ })+ finish()+ return found+}++/**+ * The dashes of a rectangle's sides of their own weights, as Figma builds them: each side dashed+ * along its own line at its own width, and a square at each corner whose two sides are stroked.+ */+function dashedSides(+ r: SkiaRenderer,+ node: SceneNode,+ scale: number,+ dashesAlong: (line: Path, width: number) => Path | null+): Path | null {+ const [top, right, bottom, left] = [+ node.borderTopWeight,+ node.borderRightWeight,+ node.borderBottomWeight,+ node.borderLeftWeight+ ].map((weight) => weight * scale)+ const { width: w, height: h } = node+ const sides: [number, number, number, number, number][] = [+ [top, 0, 0, w, 0],+ [right, w, 0, w, h],+ [bottom, w, h, 0, h],+ [left, 0, h, 0, 0]+ ]+ const builder = new r.ck.PathBuilder()+ for (const [width, x0, y0, x1, y1] of sides) {+ if (width <= 0) continue+ const line = new r.ck.PathBuilder()+ line.moveTo(x0, y0)+ line.lineTo(x1, y1)+ const path = line.detachAndDelete()+ const dashes = dashesAlong(path, width)+ path.delete()+ if (!dashes) continue+ builder.addPath(dashes)+ dashes.delete()+ }+ const corners: [number, number, number, number][] = [+ [left, top, 0, 0],+ [right, top, w, 0],+ [right, bottom, w, h],+ [left, bottom, 0, h]+ ]+ for (const [across, along, x, y] of corners) {+ if (across <= 0 || along <= 0) continue+ // The square outside the corner that neither side's own line reaches.+ const dx = x === 0 ? -across / 2 : across / 2+ const dy = y === 0 ? -along / 2 : along / 2+ builder.addRect(+ r.ck.LTRBRect(+ Math.min(x, x + dx),+ Math.min(y, y + dy),+ Math.max(x, x + dx),+ Math.max(y, y + dy)+ )+ )+ }+ return builder.detachAndDelete()+}++/**+ * A rectangle's stroke whose sides have their own weights: the ring between its two edges, or+ * null when no side has a weight.+ */+function sidesBand(r: SkiaRenderer, node: SceneNode, scale: number): Path | null {+ const weights: SideWeights = [+ node.borderTopWeight * scale,+ node.borderRightWeight * scale,+ node.borderBottomWeight * scale,+ node.borderLeftWeight * scale+ ]+ if (weights.every((weight) => weight <= 0)) return null+ const { outer, inner } = sideStrokeRRects(node, 'CENTER', 0, weights)+ const builder = new r.ck.PathBuilder()+ builder.addRRect(outer)+ const outside = builder.detachAndDelete()+ if (!inner) return outside+ const hole = new r.ck.PathBuilder()+ hole.addRRect(inner)+ const inside = hole.detachAndDelete()+ const ring = r.ck.Path.MakeFromOp(outside, inside, r.ck.PathOp.Difference)+ outside.delete()+ inside.delete()+ return ring+}diff --git a/packages/core/src/canvas/paths/verbs.ts b/packages/core/src/canvas/paths/verbs.tsnew file mode 100644index 000000000..43bff12ac--- /dev/null+++ b/packages/core/src/canvas/paths/verbs.ts@@ -0,0 +1,78 @@+import type { CanvasKit, Path, PathBuilder } from 'canvaskit-wasm'++import type { PathSink } from '#core/vector/path-helpers'++/** Calls `visit` with each verb of `path` and its coordinates, a conic's weight last. */+export function forEachVerb(+ ck: CanvasKit,+ path: Path,+ visit: (verb: number, args: Float32Array) => void+): void {+ const cmds = path.toCmds()+ const counts = new Map([+ [ck.MOVE_VERB, 2],+ [ck.LINE_VERB, 2],+ [ck.QUAD_VERB, 4],+ [ck.CONIC_VERB, 5],+ [ck.CUBIC_VERB, 6],+ [ck.CLOSE_VERB, 0]+ ])+ for (let index = 0; index < cmds.length;) {+ const verb = cmds[index]+ const count = counts.get(verb) ?? 0+ visit(verb, cmds.subarray(index + 1, index + 1 + count))+ index += 1 + count+ }+}++/** Adds one verb of a path, as `forEachVerb` gives it, to `builder`. */+export function appendVerb(+ ck: CanvasKit,+ builder: PathBuilder,+ verb: number,+ a: Float32Array+): void {+ if (verb === ck.MOVE_VERB) builder.moveTo(a[0], a[1])+ else if (verb === ck.LINE_VERB) builder.lineTo(a[0], a[1])+ else if (verb === ck.QUAD_VERB) builder.quadTo(a[0], a[1], a[2], a[3])+ else if (verb === ck.CONIC_VERB) builder.conicTo(a[0], a[1], a[2], a[3], a[4])+ else if (verb === ck.CUBIC_VERB) builder.cubicTo(a[0], a[1], a[2], a[3], a[4], a[5])+ else if (verb === ck.CLOSE_VERB) builder.close()+}++/**+ * Replays `path` into `sink`, which takes only cubics: a quad as the cubic it is, and a conic of+ * weight w as the cubic whose handles run 4w / 3(1 + w) of the way to its control point, which is+ * how arcs are drawn as cubics.+ */+export function tracePath(ck: CanvasKit, path: Path, sink: PathSink): void {+ let start: [number, number] = [0, 0]+ let at: [number, number] = [0, 0]+ forEachVerb(ck, path, (verb, a) => {+ if (verb === ck.MOVE_VERB) {+ start = at = [a[0], a[1]]+ sink.moveTo(a[0], a[1])+ } else if (verb === ck.LINE_VERB) {+ at = [a[0], a[1]]+ sink.lineTo(a[0], a[1])+ } else if (verb === ck.CUBIC_VERB) {+ at = [a[4], a[5]]+ sink.cubicTo(a[0], a[1], a[2], a[3], a[4], a[5])+ } else if (verb === ck.QUAD_VERB || verb === ck.CONIC_VERB) {+ const share = verb === ck.QUAD_VERB ? 2 / 3 : (4 * a[4]) / (3 * (1 + a[4]))+ const [x, y] = at+ at = [a[2], a[3]]+ sink.cubicTo(+ x + (a[0] - x) * share,+ y + (a[1] - y) * share,+ a[2] + (a[0] - a[2]) * share,+ a[3] + (a[1] - a[3]) * share,+ a[2],+ a[3]+ )+ } else if (verb === ck.CLOSE_VERB) {+ at = start+ sink.close()+ }+ })+}diff --git a/packages/core/src/canvas/strokes/outlined-dashes.ts b/packages/core/src/canvas/strokes/outlined-dashes.tsindex 8164c82da..db82c1d63 100644--- a/packages/core/src/canvas/strokes/outlined-dashes.ts+++ b/packages/core/src/canvas/strokes/outlined-dashes.ts@@ -3,6 +3,7 @@ import type { Canvas, CanvasKit, Path, PathBuilder } from 'canvaskit-wasm'import type { SceneNode, Stroke } from '@open-pencil/scene-graph'import type { Vector } from '@open-pencil/scene-graph/primitives'+import { appendVerb, forEachVerb } from '#core/canvas/paths/verbs'import type { SkiaRenderer } from '#core/canvas/renderer'import { makeSmoothRRectPath, nodeHasSmoothCorners } from '#core/canvas/shapes'import { getStrokeCapEntity, getStrokeJoinEntity } from '#core/canvas/strokes'@@ -74,12 +75,16 @@ function edgePath(r: SkiaRenderer, node: SceneNode): Path {return builder.detachAndDelete()}-/** All dashes along `edge`, stroked with `options`, as one path. */-function dashPath(+/**+ * All dashes along `edge`, one contour, stroked with `options`, as one path. A closed contour's+ * dashes run on past its start; an open one's stop at its end.+ */+export function dashPath(r: SkiaRenderer,edge: Path,pattern: readonly number[],- options: Parameters<Path['makeStroked']>[0]+ options: Parameters<Path['makeStroked']>[0],+ closed = true): Path | null {const pieces = outlinePieces(r, edge)const total = pieces.reduce((sum, [, length]) => sum + length, 0)@@ -90,9 +95,10 @@ function dashPath(? sideDashSpans(length, pattern).map(([s, e]): Span => [start + s, start + e]): []),- total+ total,+ closed)- const iter = new r.ck.ContourMeasureIter(edge, true, 1)+ const iter = new r.ck.ContourMeasureIter(edge, closed, 1)const contour = iter.next()iter.delete()if (!contour) return null@@ -101,7 +107,9 @@ function dashPath(for (const [start, end] of spans) {const line = new r.ck.PathBuilder()appendSegment(r.ck, line, contour.getSegment(start, Math.min(end, total), true), false)- if (end > total) appendSegment(r.ck, line, contour.getSegment(0, end - total, true), true)+ if (closed && end > total) {+ appendSegment(r.ck, line, contour.getSegment(0, end - total, true), true)+ }const centre = line.detachAndDelete()const outline = centre.makeStroked(options)centre.delete()@@ -168,14 +176,15 @@ function curveLength(r: SkiaRenderer, from: Vector, verb: number, args: Float32A* Spans in order along a closed outline of length `total`, with spans that touch joined into one,* the last running past `total` into the first when they meet where the outline starts.*/-function mergeTouching(spans: Span[], total: number): Span[] {+function mergeTouching(spans: Span[], total: number, closed: boolean): Span[] {const merged: Span[] = []for (const [start, end] of spans) {const last = merged.at(-1)if (last && start - last[1] < EPSILON) last[1] = Math.max(last[1], end)else merged.push([start, end])}- if (merged.length < 2) return merged+ // A closed contour's last dash runs on into its first; an open one's ends stay apart.+ if (!closed || merged.length < 2) return mergedconst first = merged[0]const last = merged[merged.length - 1]if (first[0] < EPSILON && total - last[1] < EPSILON) {@@ -185,29 +194,6 @@ function mergeTouching(spans: Span[], total: number): Span[] {return merged}-/** Calls `visit` with each verb of `path` and its coordinates, a conic's weight last. */-function forEachVerb(- ck: CanvasKit,- path: Path,- visit: (verb: number, args: Float32Array) => void-): void {- const cmds = path.toCmds()- const counts = new Map([- [ck.MOVE_VERB, 2],- [ck.LINE_VERB, 2],- [ck.QUAD_VERB, 4],- [ck.CONIC_VERB, 5],- [ck.CUBIC_VERB, 6],- [ck.CLOSE_VERB, 0]- ])- for (let index = 0; index < cmds.length;) {- const verb = cmds[index]- const count = counts.get(verb) ?? 0- visit(verb, cmds.subarray(index + 1, index + 1 + count))- index += 1 + count- }-}-/** Appends `segment` to `builder`, running on from its last point when `continues`. */function appendSegment(ck: CanvasKit,@@ -216,12 +202,8 @@ function appendSegment(continues: boolean): void {forEachVerb(ck, segment, (verb, a) => {- if (verb === ck.MOVE_VERB) {- if (!continues) builder.moveTo(a[0], a[1])- } else if (verb === ck.LINE_VERB) builder.lineTo(a[0], a[1])- else if (verb === ck.QUAD_VERB) builder.quadTo(a[0], a[1], a[2], a[3])- else if (verb === ck.CONIC_VERB) builder.conicTo(a[0], a[1], a[2], a[3], a[4])- else if (verb === ck.CUBIC_VERB) builder.cubicTo(a[0], a[1], a[2], a[3], a[4], a[5])+ if (verb === ck.CLOSE_VERB || (verb === ck.MOVE_VERB && continues)) return+ appendVerb(ck, builder, verb, a)})segment.delete()}diff --git a/packages/core/src/canvas/strokes/sides.ts b/packages/core/src/canvas/strokes/sides.tsindex a41ef7155..25225772d 100644--- a/packages/core/src/canvas/strokes/sides.ts+++ b/packages/core/src/canvas/strokes/sides.ts@@ -9,6 +9,9 @@ import { normalizeDashPattern } from '#core/canvas/strokes'/** Arc points per wedge: a chord across at most this many degrees stays clear of the ring. */const WEDGE_STEP = 30+/** The most times a dash pattern repeats along one side before it draws as a solid line. */+const MAX_DASH_REPEATS = 10_000+/** A rectangle's stroke weights, side by side: top, right, bottom, left. */export type SideWeights = readonly [number, number, number, number]@@ -142,8 +145,11 @@ export function fittedDashPattern(pattern: readonly number[]): { intervals: number[]; offset: number } | null {const period = pattern.reduce((sum, size) => sum + size, 0)- if (period <= 0 || length <= 0) return null- const scale = length / (Math.max(1, Math.round(length / period)) * period)+ if (!(period > 0) || !(length > 0)) return null+ const repeats = Math.max(1, Math.round(length / period))+ const scale = length / (repeats * period)+ // Dashes too fine to count, or a period too small to scale, draw as a solid line.+ if (repeats > MAX_DASH_REPEATS || !(scale > 0) || !Number.isFinite(scale)) return nullreturn { intervals: pattern.map((size) => size * scale), offset: (pattern[0] * scale) / 2 }}diff --git a/packages/core/src/figma-api/accessors/strokes.ts b/packages/core/src/figma-api/accessors/strokes.tsindex e599ed3fb..9978d7b01 100644--- a/packages/core/src/figma-api/accessors/strokes.ts+++ b/packages/core/src/figma-api/accessors/strokes.ts@@ -2,6 +2,7 @@ import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { newStrokeGeometry } from '@open-pencil/scene-graph/node-defaults'import {+ assertProxyEditable,nodeId,raw,strokeOwner,@@ -10,6 +11,7 @@ import {type ProxyThis} from '#core/figma-api/accessor-utils'import {+ setDashPattern,setIndependentStrokeWeight,setStrokeAlign,setStrokeWeight@@ -31,6 +33,7 @@ function independentWeight(internals: NodeProxyInternals, field: IndependentWeigreturn raw(this, internals)[field]},set(this: ProxyThis, value: number) {+ assertProxyEditable(this, internals)setIndependentStrokeWeight(graph(this, internals), nodeId(this, internals), field, value)}}@@ -47,6 +50,7 @@ export function installStrokeNodeProxyAccessors(return newStrokeGeometry(raw(strokeOwner(this, internals), internals)).weight},set(this: ProxyThis, value: number) {+ assertProxyEditable(strokeOwner(this, internals), internals)setStrokeWeight(graph(this, internals), raw(strokeOwner(this, internals), internals), value)}},@@ -55,6 +59,7 @@ export function installStrokeNodeProxyAccessors(return newStrokeGeometry(raw(strokeOwner(this, internals), internals)).align},set(this: ProxyThis, value: SceneNode['strokeAlign']) {+ assertProxyEditable(strokeOwner(this, internals), internals)setStrokeAlign(graph(this, internals), raw(strokeOwner(this, internals), internals), value)}},@@ -63,7 +68,8 @@ export function installStrokeNodeProxyAccessors(return Object.freeze([...raw(strokeOwner(this, internals), internals).dashPattern])},set(this: ProxyThis, value: readonly number[]) {- updateNode(strokeOwner(this, internals), internals, { dashPattern: [...value] })+ assertProxyEditable(strokeOwner(this, internals), internals)+ setDashPattern(graph(this, internals), raw(strokeOwner(this, internals), internals), value)}},strokeCap: {diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.tsindex 708c01579..96a9b80bd 100644--- a/packages/core/src/figma-api/accessors/visual.ts+++ b/packages/core/src/figma-api/accessors/visual.ts@@ -69,7 +69,7 @@ function setFills(setPaintBindings(graph(target, internals), raw(target, internals), 'fills', value)}-/** Figma paints carry no geometry; a stroke takes the weight and alignment the node keeps. */+/** Figma paints carry no geometry; a stroke takes the weight, alignment, and dashes the node keeps. */function setStrokes(target: ProxyThis,internals: NodeProxyInternals,@@ -78,10 +78,12 @@ function setStrokes(): void {const owner = strokeOwner(target, internals)const geometry = newStrokeGeometry(raw(owner, internals))+ const { dashPattern } = raw(owner, internals)const strokes = parseFigmaPaints(value, method, 'strokes').map((paint): Stroke => ({...paint,weight: geometry.weight,- align: geometry.align+ align: geometry.align,+ dashPattern: dashPattern.length > 0 ? [...dashPattern] : undefined}))const kept = newStrokeGeometry({strokes,diff --git a/packages/core/src/figma-api/compatibility.ts b/packages/core/src/figma-api/compatibility.tsindex 8f6897c8b..99cc474a3 100644--- a/packages/core/src/figma-api/compatibility.ts+++ b/packages/core/src/figma-api/compatibility.ts@@ -7,6 +7,7 @@ import type {Effect,EffectStyle,ExportMixin,+ GeometryMixin,FrameNode,GradientPaint,GridStyle,@@ -400,6 +401,12 @@ type ExportMembersMatch = Expect<>const _exportMembersMatch: ExportMembersMatch = true+type GeometryKeys = 'fillGeometry' | 'strokeGeometry'+type GeometryMembersMatch = Expect<+ Extends<Pick<FigmaNodeProxy, GeometryKeys>, Pick<GeometryMixin, GeometryKeys>>+>+const _geometryMembersMatch: GeometryMembersMatch = true+// --- Styles: each style's members are Figma's, apart from consumers, which read node proxies ---type BaseStyleKeys =diff --git a/packages/core/src/figma-api/geometry/accessors.ts b/packages/core/src/figma-api/geometry/accessors.tsnew file mode 100644index 000000000..7947622bb--- /dev/null+++ b/packages/core/src/figma-api/geometry/accessors.ts@@ -0,0 +1,103 @@+import type { SceneNode } from '@open-pencil/scene-graph'+import type { VectorPath } from '@open-pencil/scene-graph/vector-network'++import type { SkiaRenderer } from '#core/canvas'+import { fillGeometryPaths, strokeGeometryPath } from '#core/canvas/geometry'+import { outlineStrokeLayer } from '#core/canvas/outline-stroke'+import { graph, raw, type NodeProxyInternals, type ProxyThis } from '#core/figma-api/accessor-utils'+import { flushPendingLayout } from '#core/figma-api/pending-layout'+import type { FigmaNodeProxy, NodeProxyHost } from '#core/figma-api/proxy'+import { findPageId } from '#core/io/subgraph'++import { figmaVectorPaths } from './format'++/** The layers Figma's `GeometryMixin` gives `fillGeometry`, `strokeGeometry`, and `outlineStroke`. */+const GEOMETRY_TYPES: ReadonlySet<SceneNode['type']> = new Set([+ 'RECTANGLE',+ 'ELLIPSE',+ 'LINE',+ 'POLYGON',+ 'STAR',+ 'VECTOR',+ 'TEXT',+ 'FRAME',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE',+ 'BOOLEAN_OPERATION'+])++function host(target: ProxyThis, internals: NodeProxyInternals): NodeProxyHost {+ return target[internals.api] as NodeProxyHost+}++/** The host's renderer, which measures geometry, or the error a host without one gives. */+function renderer(target: ProxyThis, internals: NodeProxyInternals, member: string): SkiaRenderer {+ const measuring = host(target, internals).renderer+ if (!measuring) {+ throw new Error(`in ${member}: This host has no renderer to measure geometry with`)+ }+ return measuring+}++function frozenPaths(paths: VectorPath[]): readonly VectorPath[] {+ return Object.freeze(paths.map((path) => Object.freeze(path)))+}++/**+ * `fillGeometry`, `strokeGeometry`, and `outlineStroke` on the layers that have them in Figma,+ * measured by the host's renderer.+ */+export function installGeometryAccessors(+ target: object,+ internals: NodeProxyInternals,+ type: SceneNode['type']+): void {+ if (!GEOMETRY_TYPES.has(type)) return+ Object.defineProperty(target, 'fillGeometry', {+ get(this: ProxyThis): readonly VectorPath[] {+ const r = renderer(this, internals, 'get_fillGeometry')+ // A script's edits that nothing read yet are laid out first, as Figma lays them out.+ flushPendingLayout(graph(this, internals))+ const paths = fillGeometryPaths(r, graph(this, internals), raw(this, internals))+ try {+ return frozenPaths(figmaVectorPaths(r.ck, paths))+ } finally {+ for (const path of paths) path.delete()+ }+ }+ })+ Object.defineProperty(target, 'strokeGeometry', {+ get(this: ProxyThis): readonly VectorPath[] {+ const r = renderer(this, internals, 'get_strokeGeometry')+ flushPendingLayout(graph(this, internals))+ const path = strokeGeometryPath(r, graph(this, internals), raw(this, internals))+ if (!path) return frozenPaths([])+ try {+ // Figma reports a stroke as one path that fills its band, whatever the shape's own rule.+ return frozenPaths(+ figmaVectorPaths(r.ck, [path]).map((p) => ({ ...p, windingRule: 'NONZERO' }))+ )+ } finally {+ path.delete()+ }+ }+ })+ Object.defineProperty(target, 'outlineStroke', {+ value(this: ProxyThis): FigmaNodeProxy | null {+ const r = renderer(this, internals, 'outlineStroke')+ const scene = graph(this, internals)+ flushPendingLayout(scene)+ const node = raw(this, internals)+ const outlined = outlineStrokeLayer(r, node, scene)+ const pageId = findPageId(scene, node.id)+ if (!outlined || !pageId) return null+ // Figma adds the outline to the end of the page at the layer's own position in its parent,+ // and keeps the layer.+ const { stroke } = outlined+ const made = scene.createNode(stroke.type, pageId, stroke.props)+ for (const child of stroke.children) scene.createNode('VECTOR', made.id, child)+ return host(this, internals).wrapNode(made.id)+ }+ })+}diff --git a/packages/core/src/figma-api/geometry/format.ts b/packages/core/src/figma-api/geometry/format.tsnew file mode 100644index 000000000..3b624e75e--- /dev/null+++ b/packages/core/src/figma-api/geometry/format.ts@@ -0,0 +1,61 @@+import type { CanvasKit, Path } from 'canvaskit-wasm'++import type { VectorPath } from '@open-pencil/scene-graph/vector-network'++import { tracePath } from '#core/canvas/paths/verbs'+import { svgPathSink } from '#core/io/formats/svg/paths'+import type { PathSink } from '#core/vector/path-helpers'++/** A number as Figma writes path data: six significant digits, no trailing zeros. */+function figmaNumber(value: number): number {+ const rounded = Number(value.toPrecision(6))+ return Object.is(rounded, -0) ? 0 : rounded+}++/** `sink`, but a shape that ends away from its start runs back to it before closing, as Figma's do. */+function closingAtStart(sink: PathSink): PathSink {+ let start = ''+ let at = ''+ const key = (x: number, y: number) => `${figmaNumber(x)} ${figmaNumber(y)}`+ let startPoint: [number, number] = [0, 0]+ return {+ moveTo(x, y) {+ start = at = key(x, y)+ startPoint = [x, y]+ sink.moveTo(x, y)+ },+ lineTo(x, y) {+ at = key(x, y)+ sink.lineTo(x, y)+ },+ cubicTo(x1, y1, x2, y2, x, y) {+ at = key(x, y)+ sink.cubicTo(x1, y1, x2, y2, x, y)+ },+ close() {+ if (at !== start) sink.lineTo(...startPoint)+ at = start+ sink.close()+ }+ }+}++/**+ * `path` as Figma's `fillGeometry` and `strokeGeometry` write it: `M0 0 L40 0 C…`, commands spaced+ * apart, six significant digits, curves as cubics, each closed shape running back to its start.+ */+export function figmaPathData(ck: CanvasKit, path: Path): string {+ const parts: string[] = []+ tracePath(ck, path, closingAtStart(svgPathSink(parts, figmaNumber)))+ return parts.join(' ')+}++/** `paths` as Figma's `VectorPaths`, each with its winding rule; empty paths are left out. */+export function figmaVectorPaths(ck: CanvasKit, paths: readonly Path[]): VectorPath[] {+ return paths.flatMap((path) => {+ const data = figmaPathData(ck, path)+ if (!data) return []+ const evenOdd = path.getFillType().value === ck.FillType.EvenOdd.value+ return [{ windingRule: evenOdd ? 'EVENODD' : 'NONZERO', data }]+ })+}diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex 08b8faedb..2133b52de 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -22,7 +22,10 @@ import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { SkiaRenderer } from '#core/canvas'import { groupFitOptions } from '#core/canvas/boolean'import { IS_BROWSER, type InterfaceTheme } from '#core/constants'-import { invalidateBooleanAncestors } from '#core/editor/graph-events'+import {+ invalidateBooleanAncestors,+ rendererInvalidationForChanges+} from '#core/editor/graph-events'import { layerTheme, newLayerDefaults } from '#core/editor/shapes/defaults'import { booleanOperationPaints, createBooleanOperation } from '#core/editor/structure/boolean'import { wrapNodes } from '#core/editor/structure/container-wrap'@@ -144,10 +147,14 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {this._currentPageId = pages[0]?.id ?? graph.rootId}+ get renderer(): SkiaRenderer | null {+ return this._renderer+ }+/**- * The renderer that measures for the API: boolean results and flattened vectors. It keeps- * each boolean operation's result between readings, so the API tells it when a change lands- * inside one, as the editor does for its renderers.+ * The renderer that measures for the API: geometry, boolean results, and flattened vectors. It+ * keeps paths between readings, so the API tells it when a layer's shape changes or a change+ * lands inside a boolean operation, as the editor does for its renderers.*/setRenderer(renderer: SkiaRenderer | null): void {this._unbindRendererEvents?.()@@ -157,10 +164,16 @@ export class FigmaAPI extends FigmaStyleMethods implements NodeProxyHost {const graph = this.graphconst invalidate = (id: string | null | undefined) =>invalidateBooleanAncestors(graph, [renderer], id)+ // A layer's own paths are kept too, so an edit to its shape drops them, as the editor's do.+ const changed = (id: string, changes: Partial<CoreSceneNode>) => {+ invalidate(id)+ const { geometryCache } = rendererInvalidationForChanges(changes, { preview: false })+ if (geometryCache) renderer.invalidateVectorPath(id)+ }this._unbindRendererEvents = graph.onNodeEvents({created: (node) => invalidate(node.parentId),- updated: (id) => invalidate(id),- previewUpdated: (id) => invalidate(id),+ updated: (id, changes) => changed(id, changes),+ previewUpdated: (id, changes) => changed(id, changes),deleted: (_id, parentId) => invalidate(parentId),reparented: (id, oldParentId) => {invalidate(oldParentId)diff --git a/packages/core/src/figma-api/members.ts b/packages/core/src/figma-api/members.tsindex 12c42bc87..1ad1dcd54 100644--- a/packages/core/src/figma-api/members.ts+++ b/packages/core/src/figma-api/members.ts@@ -3,6 +3,7 @@ import type {ComponentSetNode,DocumentNode,ExportMixin,+ GeometryMixin,Guide,LeadingTrim,MinimalFillsMixin,@@ -94,6 +95,8 @@ export abstract class FigmaNodeMembers {declare guides: readonly Guide[]declare exportSettings: ExportMixin['exportSettings']declare exportAsync: ExportMixin['exportAsync']+ declare fillGeometry: GeometryMixin['fillGeometry']+ declare strokeGeometry: GeometryMixin['strokeGeometry']declare layoutWrap: stringdeclare primaryAxisSizingMode: stringdeclare counterAxisSizingMode: stringdiff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 32769b94a..948813479 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -4,6 +4,7 @@ import type { GroupFitOptions } from '@open-pencil/scene-graph/group-bounds'import { createsComponentCycle, recordInstanceOverride } from '@open-pencil/scene-graph/instances'import { slotPropertyId } from '@open-pencil/scene-graph/slots'+import type { SkiaRenderer } from '#core/canvas'import { assertNodeEditable } from '#core/editor/capabilities'import { prepareFollowedFieldEdit, fitGroupsAround } from './accessor-utils'@@ -25,6 +26,7 @@ import { installComponentPropertyAccessors } from './components'import { installDevStatusAccessors } from './dev-status'import { installExportAccessors } from './export/accessors'import type { ExportHost } from './export/render'+import { installGeometryAccessors } from './geometry/accessors'import { FigmaNodeMembers } from './members'import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'import { installInstanceOverrideAccessors } from './overrides'@@ -51,6 +53,8 @@ export interface NodeProxyHost extends ExportHost {readonly currentPageId: string/** How groups and booleans refit; booleans size to their result when a renderer is attached. */readonly groupFitOptions: GroupFitOptions+ /** The renderer that measures geometry, when the host has one. */+ readonly renderer: SkiaRenderer | null}export { MIXED }@@ -67,6 +71,8 @@ function assertNoComponentCycle(}export class FigmaNodeProxy extends FigmaNodeMembers {+ /** Installed by `installGeometryAccessors` on the layers Figma gives it. */+ declare outlineStroke: () => FigmaNodeProxy | null;[INTERNAL_ID]: string;[INTERNAL_GRAPH]: SceneGraph;[INTERNAL_API]: NodeProxyHost@@ -85,6 +91,7 @@ export class FigmaNodeProxy extends FigmaNodeMembers {if (type) installInstanceOverrideAccessors(this, internals, type)if (type) installStyleReferenceAccessors(this, internals, type, id === graph.rootId, MIXED)if (type && id !== graph.rootId) installExportAccessors(this, internals)+ if (type) installGeometryAccessors(this, internals, type)// Figma loads a page's layers on demand in dynamic-page mode and has `loadAsync` on pages// alone; every page here is already loaded.if (type === 'CANVAS')diff --git a/packages/core/src/figma-api/strokes.ts b/packages/core/src/figma-api/strokes.tsindex 6ee8f3863..9928cb9f2 100644--- a/packages/core/src/figma-api/strokes.ts+++ b/packages/core/src/figma-api/strokes.ts@@ -23,6 +23,19 @@ export function setStrokeAlign(graph: SceneGraph, node: SceneNode, align: StrokerecordInstanceOverride(graph, node.id, ['strokes', 'strokeAlign'])}+/** Dashes the layer's strokes: the renderer reads each stroke's pattern, Figma the layer's. */+export function setDashPattern(+ graph: SceneGraph,+ node: SceneNode,+ pattern: readonly number[]+): void {+ graph.updateNode(node.id, {+ dashPattern: [...pattern],+ strokes: node.strokes.map((stroke) => ({ ...copyStroke(stroke), dashPattern: [...pattern] }))+ })+ recordInstanceOverride(graph, node.id, ['strokes', 'dashPattern'])+}+export function setIndependentStrokeWeight(graph: SceneGraph,nodeId: string,diff --git a/packages/core/src/figma-api/surface.ts b/packages/core/src/figma-api/surface.tsindex 86e638c21..974220b2b 100644--- a/packages/core/src/figma-api/surface.ts+++ b/packages/core/src/figma-api/surface.ts@@ -11,6 +11,7 @@ export const FIGMA_API_HOST_MEMBERS = ['currentPageId','groupFitOptions','setRenderer',+ 'renderer','theme','exportImage','icons',diff --git a/packages/core/src/io/formats/raster/headless.ts b/packages/core/src/io/formats/raster/headless.tsindex 3146e4a77..fea1cdef0 100644--- a/packages/core/src/io/formats/raster/headless.ts+++ b/packages/core/src/io/formats/raster/headless.ts@@ -6,22 +6,49 @@ import { SkiaRenderer } from '#core/canvas'import { renderNodesToImage, renderThumbnail, type ExportFormat } from './render'-let cachedCk: CanvasKit | null = null-let cachedRenderer: SkiaRenderer | null = null+let cachedCk: Promise<CanvasKit> | null = null+let cachedRenderer: Promise<SkiaRenderer> | null = null-export async function initCanvasKit(): Promise<CanvasKit> {- if (cachedCk) return cachedCk- const CanvasKitInit = (await import('canvaskit-wasm/full')).default- const ckURL = import.meta.resolve('canvaskit-wasm/full')- cachedCk = await CanvasKitInit({- locateFile: (file: string) => new URL(file, ckURL).href+/**+ * The process's one CanvasKit, started once even when callers arrive together: objects made by+ * one instance must never meet another instance's memory.+ */+export function initCanvasKit(): Promise<CanvasKit> {+ cachedCk ??= loadCanvasKit().catch((error: unknown) => {+ cachedCk = null+ throw error})return cachedCk}+async function loadCanvasKit(): Promise<CanvasKit> {+ const CanvasKitInit = (await import('canvaskit-wasm/full')).default+ const ckURL = import.meta.resolve('canvaskit-wasm/full')+ return CanvasKitInit({ locateFile: (file: string) => new URL(file, ckURL).href })+}++/**+ * The one headless renderer a process keeps, fonts loaded: every renderer registers its own font+ * provider, which holds a copy of each font loaded after it, so a second one doubles that memory.+ * It keeps paths by layer id, which another document's layers share, so a caller measuring a+ * different document clears `nodePaths` and calls `invalidateAllPictures()` first, as+ * `headlessRenderNodes` does.+ */+export async function headlessRenderer(): Promise<SkiaRenderer> {+ return (await getRenderer()).renderer+}+async function getRenderer(): Promise<{ ck: CanvasKit; renderer: SkiaRenderer }> {const ck = await initCanvasKit()- if (cachedRenderer) return { ck, renderer: cachedRenderer }+ // Callers that arrive together share one renderer rather than each making their own.+ cachedRenderer ??= createRenderer(ck).catch((error: unknown) => {+ cachedRenderer = null+ throw error+ })+ return { ck, renderer: await cachedRenderer }+}++async function createRenderer(ck: CanvasKit): Promise<SkiaRenderer> {const surface = ck.MakeSurface(1, 1)if (!surface) throw new Error('Failed to create CanvasKit surface')const renderer = new SkiaRenderer(ck, surface)@@ -29,8 +56,7 @@ async function getRenderer(): Promise<{ ck: CanvasKit; renderer: SkiaRenderer }>renderer.viewportHeight = 1renderer.dpr = 1await renderer.loadFonts()- cachedRenderer = renderer- return { ck, renderer }+ return renderer}export async function headlessRenderNodes(diff --git a/packages/core/src/io/formats/raster/index.ts b/packages/core/src/io/formats/raster/index.tsindex 6b3db3003..e1287857e 100644--- a/packages/core/src/io/formats/raster/index.ts+++ b/packages/core/src/io/formats/raster/index.ts@@ -12,7 +12,12 @@ export {type ThumbnailFrame,type ExportFormat} from './render'-export { initCanvasKit, headlessRenderNodes, headlessRenderThumbnail } from './headless'+export {+ initCanvasKit,+ headlessRenderer,+ headlessRenderNodes,+ headlessRenderThumbnail+} from './headless'export {createCanvasKitRasterCodec,reencodeImage,diff --git a/packages/core/src/io/formats/svg/paths.ts b/packages/core/src/io/formats/svg/paths.tsindex 3ab95b633..33d268e59 100644--- a/packages/core/src/io/formats/svg/paths.ts+++ b/packages/core/src/io/formats/svg/paths.ts@@ -140,9 +140,15 @@ export function arcPath(node: Pick<SceneNode, 'width' | 'height' | 'arcData'>):return parts.join('')}-/** Path commands written as SVG path data into `parts`, as the canvas would build a path. */-export function svgPathSink(parts: string[]): PathSink {- const point = (x: number, y: number) => `${round(x)} ${round(y)}`+/**+ * Path commands written as SVG path data into `parts`, as the canvas would build a path, each+ * coordinate written by `format`.+ */+export function svgPathSink(+ parts: string[],+ format: (value: number) => number = (value) => round(value)+): PathSink {+ const point = (x: number, y: number) => `${format(x)} ${format(y)}`return {moveTo: (x, y) => parts.push(`M${point(x, y)}`),lineTo: (x, y) => parts.push(`L${point(x, y)}`),diff --git a/packages/core/tests/canvas/strokes/sides.test.ts b/packages/core/tests/canvas/strokes/sides.test.tsindex 6f2ae84e3..b9acd4740 100644--- a/packages/core/tests/canvas/strokes/sides.test.ts+++ b/packages/core/tests/canvas/strokes/sides.test.ts@@ -1,5 +1,8 @@import { afterAll, describe, expect, test } from 'bun:test'+import { expectDefined } from '#core-tests/helpers/assert'+import { expectFigmaRow, renderRow } from '#core-tests/helpers/figma-rows'+import { SkiaRenderer } from '@open-pencil/core/canvas'import { initCanvasKit } from '@open-pencil/core/io/formats/raster'import type { SceneGraph, SceneNode, Stroke } from '@open-pencil/scene-graph'@@ -7,9 +10,6 @@ import { createDefaultNode } from '@open-pencil/scene-graph/node-defaults'import { sideDashSpans, sideStrokeRRects } from '#core/canvas/strokes/sides'-import { expectDefined } from '#core-tests/helpers/assert'-import { expectFigmaRow, renderRow } from '#core-tests/helpers/figma-rows'-const ck = await initCanvasKit()const renderer = new SkiaRenderer(ck, expectDefined(ck.MakeSurface(1, 1)))afterAll(() => renderer.destroy())@@ -23,25 +23,24 @@ const FIGMA = {255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255],evenSharp: [- 0, 0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255,- 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0,- 255+ 0, 0, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255,+ 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255],evenRound: [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,- 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255,- 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,- 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0,+ 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255,+ 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,+ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0],evenRoundInside: [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 16, 0, 239, 255, 128, 0, 0, 255, 255, 128, 0, 0,- 255, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 16, 0, 239, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255,+ 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0, 255, 255, 128, 0, 0],sidesRound: [- 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,- 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255,- 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,- 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 223, 0, 0, 0, 0, 0, 0, 0, 0+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 144, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0,+ 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255,+ 255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0,+ 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 223, 0, 0, 0, 0, 0, 0, 0, 0]}@@ -96,7 +95,8 @@ describe('strokes with sides of their own weights, as in Figma', () => {(graph, hostId) => {dashed(graph, hostId)const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])- if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))+ if (frame)+ frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))},68,112,@@ -144,20 +144,24 @@ describe('strokes with sides of their own weights, as in Figma', () => {})test('draw nothing when no side has a weight', () => {- const empty = sidesFrame({- cornerRadius: 24,- borderTopWeight: 0,- borderRightWeight: 0,- borderBottomWeight: 0,- borderLeftWeight: 0- }, 1)+ const empty = sidesFrame(+ {+ cornerRadius: 24,+ borderTopWeight: 0,+ borderRightWeight: 0,+ borderBottomWeight: 0,+ borderLeftWeight: 0+ },+ 1+ )const values = renderRow(ck,renderer,(graph, hostId) => {empty(graph, hostId)const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])- if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))+ if (frame)+ frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))},70,112,@@ -268,7 +272,8 @@ describe('dashed rectangles, as in Figma', () => {(graph, hostId) => {scene(graph, hostId)const frame = graph.getNode(expectDefined(graph.getNode(hostId)).childIds[0])- if (frame) frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))+ if (frame)+ frame.strokes = frame.strokes.map((stroke) => ({ ...stroke, dashPattern: [20, 10] }))},70,112,@@ -277,3 +282,12 @@ describe('dashed rectangles, as in Figma', () => {expectFigmaRow(values, FIGMA.sidesRound)})})++describe('dash layout along a side', () => {+ test('draws a pattern too fine to lay out as one solid dash rather than looping', () => {+ // A denormal period scales every dash to 0; a tiny one would need more dashes than exist.+ expect(sideDashSpans(40, [1e-320, 1e-320])).toEqual([[0, 40]])+ expect(sideDashSpans(40, [1e-300, 1e-300])).toEqual([[0, 40]])+ expect(sideDashSpans(40, [4, 4]).length).toBeGreaterThan(1)+ })+})diff --git a/packages/core/tests/editor/components/library-capabilities.test.ts b/packages/core/tests/editor/components/library-capabilities.test.tsindex 1b8cb6286..5ea7b97e4 100644--- a/packages/core/tests/editor/components/library-capabilities.test.ts+++ b/packages/core/tests/editor/components/library-capabilities.test.ts@@ -44,6 +44,18 @@ describe('library definition capabilities', () => {proxy.opacity = 0.5}).toThrow(ReadOnlyLibraryDefinitionError)expect(() => proxy.remove()).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => {+ proxy.dashPattern = [4, 4]+ }).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => {+ proxy.strokeWeight = 4+ }).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => {+ proxy.strokeAlign = 'CENTER'+ }).toThrow(ReadOnlyLibraryDefinitionError)+ expect(() => {+ proxy.strokeTopWeight = 4+ }).toThrow(ReadOnlyLibraryDefinitionError)expect(graph.getNode(component.id)?.name).toBe('Remote button')const instanceProxy = figma.getNodeById(instance.id)if (!instanceProxy) throw new Error('Expected instance proxy')diff --git a/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts b/packages/core/tests/figma-api/accessors/strokes/geometry.test.tsindex aff3ef889..62e3f2277 100644--- a/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts+++ b/packages/core/tests/figma-api/accessors/strokes/geometry.test.ts@@ -81,4 +81,21 @@ describe('plugin API stroke geometry', () => {rect.rescale(2)expect([rect.strokeWeight, rect.strokeAlign]).toEqual([6, 'CENTER'])})++ test('dashes reach the strokes the renderer draws, before and after they are set', () => {+ const figma = api()+ const rect = figma.createRectangle()+ Reflect.set(rect, 'strokes', red)+ rect.dashPattern = [4, 2]+ expect(figma.graph.getNode(rect.id)?.strokes.map((stroke) => stroke.dashPattern)).toEqual([+ [4, 2]+ ])+ const later = figma.createRectangle()+ later.dashPattern = [6, 3]+ Reflect.set(later, 'strokes', red)+ expect(later.dashPattern).toEqual([6, 3])+ expect(figma.graph.getNode(later.id)?.strokes.map((stroke) => stroke.dashPattern)).toEqual([+ [6, 3]+ ])+ })})diff --git a/packages/core/tests/figma-api/geometry.test.ts b/packages/core/tests/figma-api/geometry.test.tsnew file mode 100644index 000000000..0c31ebe00--- /dev/null+++ b/packages/core/tests/figma-api/geometry.test.ts@@ -0,0 +1,350 @@+import { describe, expect, test } from 'bun:test'++import { attachTestRenderer, createAPI, registerTestFont } from '#core-tests/helpers/figma-api'++import type { SkiaRenderer } from '@open-pencil/core/canvas'+import type { FigmaAPI } from '@open-pencil/core/figma-api'++// Figma's answers measured in Figma desktop 126.++const RED = [{ type: 'SOLID', color: { r: 1, g: 0, b: 0 } }] as const+const BLUE = [{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }] as const++/** Figma's `strokeGeometry` for a 40 by 20 rectangle with a 4 px inside stroke. */+const FIGMA_INSIDE_4 =+ 'M0 0 L0 -4 L-4 -4 L-4 0 L0 0 Z M40 0 L44 0 L44 -4 L40 -4 L40 0 Z M40 20 L40 24 L44 24 L44 20 L40 20 Z M0 20 L-4 20 L-4 24 L0 24 L0 20 Z M0 0 L0 4 L40 4 L40 0 L40 -4 L0 -4 L0 0 Z M40 0 L36 0 L36 20 L40 20 L44 20 L44 0 L40 0 Z M40 20 L40 16 L0 16 L0 20 L0 24 L40 24 L40 20 Z M0 20 L4 20 L4 0 L0 0 L-4 0 L-4 20 L0 20 Z'+/** The same rectangle with a 4 px centred stroke. */+const FIGMA_CENTER_4 =+ 'M0 0 L0 -2 L-2 -2 L-2 0 L0 0 Z M40 0 L42 0 L42 -2 L40 -2 L40 0 Z M40 20 L40 22 L42 22 L42 20 L40 20 Z M0 20 L-2 20 L-2 22 L0 22 L0 20 Z M0 0 L0 2 L40 2 L40 0 L40 -2 L0 -2 L0 0 Z M40 0 L38 0 L38 20 L40 20 L42 20 L42 0 L40 0 Z M40 20 L40 18 L0 18 L0 20 L0 22 L40 22 L40 20 Z M0 20 L2 20 L2 0 L0 0 L-2 0 L-2 20 L0 20 Z'+/** With inside sides of 4, 0, 1, and 2 px, top first. */+const FIGMA_SIDES =+ 'M0 0 L0 -4 L-2 -4 L-2 0 L0 0 Z M0 20 L-2 20 L-2 21 L0 21 L0 20 Z M0 0 L0 4 L40 4 L40 0 L40 -4 L0 -4 L0 0 Z M40 20 L40 19 L0 19 L0 20 L0 21 L40 21 L40 20 Z M0 20 L2 20 L2 0 L0 0 L-2 0 L-2 20 L0 20 Z'+/** With a 2 px inside stroke dashed 4 on, 4 off. */+const FIGMA_DASHED =+ 'M0 0 L0 -1 L-1 -1 L-1 0 L0 0 Z M40 0 L41 0 L41 -1 L40 -1 L40 0 Z M40 20 L40 21 L41 21 L41 20 L40 20 Z M0 20 L-1 20 L-1 21 L0 21 L0 20 Z M0 0 L-1 0 L-1 1.66667 L0 1.66667 L1 1.66667 L1 0 L0 0 Z M0 5 L-1 5 L-1 8.33333 L0 8.33333 L1 8.33333 L1 5 L0 5 Z M0 11.6667 L-1 11.6667 L-1 15 L0 15 L1 15 L1 11.6667 L0 11.6667 Z M0 18.3333 L-1 18.3333 L-1 20 L0 20 L1 20 L1 18.3333 L0 18.3333 Z M0 20 L0 21 L2 21 L2 20 L2 19 L0 19 L0 20 Z M6 20 L6 21 L10 21 L10 20 L10 19 L6 19 L6 20 Z M14 20 L14 21 L18 21 L18 20 L18 19 L14 19 L14 20 Z M22 20 L22 21 L26 21 L26 20 L26 19 L22 19 L22 20 Z M30 20 L30 21 L34 21 L34 20 L34 19 L30 19 L30 20 Z M38 20 L38 21 L40 21 L40 20 L40 19 L38 19 L38 20 Z M40 20 L41 20 L41 18.3333 L40 18.3333 L39 18.3333 L39 20 L40 20 Z M40 15 L41 15 L41 11.6667 L40 11.6667 L39 11.6667 L39 15 L40 15 Z M40 8.33333 L41 8.33333 L41 5 L40 5 L39 5 L39 8.33333 L40 8.33333 Z M40 1.66667 L41 1.66667 L41 0 L40 0 L39 0 L39 1.66667 L40 1.66667 Z M40 0 L40 -1 L38 -1 L38 0 L38 1 L40 1 L40 0 Z M34 0 L34 -1 L30 -1 L30 0 L30 1 L34 1 L34 0 Z M26 0 L26 -1 L22 -1 L22 0 L22 1 L26 1 L26 0 Z M18 0 L18 -1 L14 -1 L14 0 L14 1 L18 1 L18 0 Z M10 0 L10 -1 L6 -1 L6 0 L6 1 L10 1 L10 0 Z M2 0 L2 -1 L0 -1 L0 0 L0 1 L2 1 L2 0 Z M0 0 L0 -2 L-2 -2 L-2 0 L0 0 Z M40 0 L42 0 L42 -2 L40 -2 L40 0 Z M40 20 L40 22 L42 22 L42 20 L40 20 Z M0 20 L-2 20 L-2 22 L0 22 L0 20 Z M0 0 L-2 0 L-2 1.66667 L0 1.66667 L2 1.66667 L2 0 L0 0 Z M0 5 L-2 5 L-2 8.33333 L0 8.33333 L2 8.33333 L2 5 L0 5 Z M0 11.6667 L-2 11.6667 L-2 15 L0 15 L2 15 L2 11.6667 L0 11.6667 Z M0 18.3333 L-2 18.3333 L-2 20 L0 20 L2 20 L2 18.3333 L0 18.3333 Z M0 20 L0 22 L2 22 L2 20 L2 18 L0 18 L0 20 Z M6 20 L6 22 L10 22 L10 20 L10 18 L6 18 L6 20 Z M14 20 L14 22 L18 22 L18 20 L18 18 L14 18 L14 20 Z M22 20 L22 22 L26 22 L26 20 L26 18 L22 18 L22 20 Z M30 20 L30 22 L34 22 L34 20 L34 18 L30 18 L30 20 Z M38 20 L38 22 L40 22 L40 20 L40 18 L38 18 L38 20 Z M40 20 L42 20 L42 18.3333 L40 18.3333 L38 18.3333 L38 20 L40 20 Z M40 15 L42 15 L42 11.6667 L40 11.6667 L38 11.6667 L38 15 L40 15 Z M40 8.33333 L42 8.33333 L42 5 L40 5 L38 5 L38 8.33333 L40 8.33333 Z M40 1.66667 L42 1.66667 L42 0 L40 0 L38 0 L38 1.66667 L40 1.66667 Z M40 0 L40 -2 L38 -2 L38 0 L38 2 L40 2 L40 0 Z M34 0 L34 -2 L30 -2 L30 0 L30 2 L34 2 L34 0 Z M26 0 L26 -2 L22 -2 L22 0 L22 2 L26 2 L26 0 Z M18 0 L18 -2 L14 -2 L14 0 L14 2 L18 2 L18 0 Z M10 0 L10 -2 L6 -2 L6 0 L6 2 L10 2 L10 0 Z M2 0 L2 -2 L0 -2 L0 0 L0 2 L2 2 L2 0 Z'+/** A 40 by 20 and a 20 by 40 rectangle united, with a 2 px centred stroke. */+const FIGMA_BOOLEAN =+ 'M40 0 L41 0 L41 -1 L40 -1 L40 0 Z M40 20 L40 21 L41 21 L41 20 L40 20 Z M20 20 L20 19 L19 19 L19 20 L20 20 Z M20 40 L20 41 L21 41 L21 40 L20 40 Z M0 40 L-1 40 L-1 41 L0 41 L0 40 Z M0 0 L0 -1 L-1 -1 L-1 0 L0 0 Z M40 0 L39 0 L39 20 L40 20 L41 20 L41 0 L40 0 Z M40 20 L40 19 L20 19 L20 20 L20 21 L40 21 L40 20 Z M20 20 L19 20 L19 40 L20 40 L21 40 L21 20 L20 20 Z M20 40 L20 39 L0 39 L0 40 L0 41 L20 41 L20 40 Z M0 40 L1 40 L1 0 L0 0 L-1 0 L-1 40 L0 40 Z M0 0 L0 1 L40 1 L40 0 L40 -1 L0 -1 L0 0 Z'+/** Inside sides of 4, 0, 1, and 2 px, top first, dashed 4 on, 4 off. */+const FIGMA_SIDES_DASHED =+ 'M0 0 L0 -2 L-1 -2 L-1 0 L0 0 Z M0 20 L-1 20 L-1 20.5 L0 20.5 L0 20 Z M0 0 L-1 0 L-1 1.66667 L0 1.66667 L1 1.66667 L1 0 L0 0 Z M0 5 L-1 5 L-1 8.33333 L0 8.33333 L1 8.33333 L1 5 L0 5 Z M0 11.6667 L-1 11.6667 L-1 15 L0 15 L1 15 L1 11.6667 L0 11.6667 Z M0 18.3333 L-1 18.3333 L-1 20 L0 20 L1 20 L1 18.3333 L0 18.3333 Z M0 20 L0 20.5 L2 20.5 L2 20 L2 19.5 L0 19.5 L0 20 Z M6 20 L6 20.5 L10 20.5 L10 20 L10 19.5 L6 19.5 L6 20 Z M14 20 L14 20.5 L18 20.5 L18 20 L18 19.5 L14 19.5 L14 20 Z M22 20 L22 20.5 L26 20.5 L26 20 L26 19.5 L22 19.5 L22 20 Z M30 20 L30 20.5 L34 20.5 L34 20 L34 19.5 L30 19.5 L30 20 Z M38 20 L38 20.5 L40 20.5 L40 20 L40 19.5 L38 19.5 L38 20 Z M40 0 L40 -2 L38 -2 L38 0 L38 2 L40 2 L40 0 Z M34 0 L34 -2 L30 -2 L30 0 L30 2 L34 2 L34 0 Z M26 0 L26 -2 L22 -2 L22 0 L22 2 L26 2 L26 0 Z M18 0 L18 -2 L14 -2 L14 0 L14 2 L18 2 L18 0 Z M10 0 L10 -2 L6 -2 L6 0 L6 2 L10 2 L10 0 Z M2 0 L2 -2 L0 -2 L0 0 L0 2 L2 2 L2 0 Z M0 0 L0 -4 L-2 -4 L-2 0 L0 0 Z M0 20 L-2 20 L-2 21 L0 21 L0 20 Z M0 0 L-2 0 L-2 1.66667 L0 1.66667 L2 1.66667 L2 0 L0 0 Z M0 5 L-2 5 L-2 8.33333 L0 8.33333 L2 8.33333 L2 5 L0 5 Z M0 11.6667 L-2 11.6667 L-2 15 L0 15 L2 15 L2 11.6667 L0 11.6667 Z M0 18.3333 L-2 18.3333 L-2 20 L0 20 L2 20 L2 18.3333 L0 18.3333 Z M0 20 L0 21 L2 21 L2 20 L2 19 L0 19 L0 20 Z M6 20 L6 21 L10 21 L10 20 L10 19 L6 19 L6 20 Z M14 20 L14 21 L18 21 L18 20 L18 19 L14 19 L14 20 Z M22 20 L22 21 L26 21 L26 20 L26 19 L22 19 L22 20 Z M30 20 L30 21 L34 21 L34 20 L34 19 L30 19 L30 20 Z M38 20 L38 21 L40 21 L40 20 L40 19 L38 19 L38 20 Z M40 0 L40 -4 L38 -4 L38 0 L38 4 L40 4 L40 0 Z M34 0 L34 -4 L30 -4 L30 0 L30 4 L34 4 L34 0 Z M26 0 L26 -4 L22 -4 L22 0 L22 4 L26 4 L26 0 Z M18 0 L18 -4 L14 -4 L14 0 L14 4 L18 4 L18 0 Z M10 0 L10 -4 L6 -4 L6 0 L6 4 L10 4 L10 0 Z M2 0 L2 -4 L0 -4 L0 0 L0 4 L2 4 L2 0 Z'+/** A 2 px inside top side and no others, the stroke's own weight 0. */+const FIGMA_TOP_SIDE = 'M0 0 L0 2 L40 2 L40 0 L40 -2 L0 -2 L0 0 Z'+/** Two 20 px square loops of one vector, a 2 px centred stroke dashed 4 on, 4 off. */+const FIGMA_TWO_LOOPS =+ 'M0 0 L0 -1 L-1 -1 L-1 0 L0 0 Z M20 0 L21 0 L21 -1 L20 -1 L20 0 Z M20 20 L20 21 L21 21 L21 20 L20 20 Z M0 20 L-1 20 L-1 21 L0 21 L0 20 Z M40 0 L40 -1 L39 -1 L39 0 L40 0 Z M60 0 L61 0 L61 -1 L60 -1 L60 0 Z M60 20 L60 21 L61 21 L61 20 L60 20 Z M40 20 L39 20 L39 21 L40 21 L40 20 Z M0 0 L-1 0 L-1 1.66667 L0 1.66667 L1 1.66667 L1 0 L0 0 Z M0 5 L-1 5 L-1 8.33333 L0 8.33333 L1 8.33333 L1 5 L0 5 Z M0 11.6667 L-1 11.6667 L-1 15 L0 15 L1 15 L1 11.6667 L0 11.6667 Z M0 18.3333 L-1 18.3333 L-1 20 L0 20 L1 20 L1 18.3333 L0 18.3333 Z M0 20 L0 21 L1.66667 21 L1.66667 20 L1.66667 19 L0 19 L0 20 Z M5 20 L5 21 L8.33333 21 L8.33333 20 L8.33333 19 L5 19 L5 20 Z M11.6667 20 L11.6667 21 L15 21 L15 20 L15 19 L11.6667 19 L11.6667 20 Z M18.3333 20 L18.3333 21 L20 21 L20 20 L20 19 L18.3333 19 L18.3333 20 Z M20 20 L21 20 L21 18.3333 L20 18.3333 L19 18.3333 L19 20 L20 20 Z M20 15 L21 15 L21 11.6667 L20 11.6667 L19 11.6667 L19 15 L20 15 Z M20 8.33333 L21 8.33333 L21 5 L20 5 L19 5 L19 8.33333 L20 8.33333 Z M20 1.66667 L21 1.66667 L21 0 L20 0 L19 0 L19 1.66667 L20 1.66667 Z M20 0 L20 -1 L18.3333 -1 L18.3333 0 L18.3333 1 L20 1 L20 0 Z M15 0 L15 -1 L11.6667 -1 L11.6667 0 L11.6667 1 L15 1 L15 0 Z M8.33333 0 L8.33333 -1 L5 -1 L5 0 L5 1 L8.33333 1 L8.33333 0 Z M1.66667 0 L1.66667 -1 L0 -1 L0 0 L0 1 L1.66667 1 L1.66667 0 Z M40 0 L39 0 L39 1.66667 L40 1.66667 L41 1.66667 L41 0 L40 0 Z M40 5 L39 5 L39 8.33333 L40 8.33333 L41 8.33333 L41 5 L40 5 Z M40 11.6667 L39 11.6667 L39 15 L40 15 L41 15 L41 11.6667 L40 11.6667 Z M40 18.3333 L39 18.3333 L39 20 L40 20 L41 20 L41 18.3333 L40 18.3333 Z M40 20 L40 21 L41.6667 21 L41.6667 20 L41.6667 19 L40 19 L40 20 Z M45 20 L45 21 L48.3333 21 L48.3333 20 L48.3333 19 L45 19 L45 20 Z M51.6667 20 L51.6667 21 L55 21 L55 20 L55 19 L51.6667 19 L51.6667 20 Z M58.3333 20 L58.3333 21 L60 21 L60 20 L60 19 L58.3333 19 L58.3333 20 Z M60 20 L61 20 L61 18.3333 L60 18.3333 L59 18.3333 L59 20 L60 20 Z M60 15 L61 15 L61 11.6667 L60 11.6667 L59 11.6667 L59 15 L60 15 Z M60 8.33333 L61 8.33333 L61 5 L60 5 L59 5 L59 8.33333 L60 8.33333 Z M60 1.66667 L61 1.66667 L61 0 L60 0 L59 0 L59 1.66667 L60 1.66667 Z M60 0 L60 -1 L58.3333 -1 L58.3333 0 L58.3333 1 L60 1 L60 0 Z M55 0 L55 -1 L51.6667 -1 L51.6667 0 L51.6667 1 L55 1 L55 0 Z M48.3333 0 L48.3333 -1 L45 -1 L45 0 L45 1 L48.3333 1 L48.3333 0 Z M41.6667 0 L41.6667 -1 L40 -1 L40 0 L40 1 L41.6667 1 L41.6667 0 Z'+/** A 30 px line with a 2 px stroke. */+const FIGMA_LINE_2 = 'M0 -1 L0 0 L30 0 L30 -1 L30 -2 L0 -2 L0 -1 Z'+/** An open V, 20 wide and 10 deep, with a 2 px stroke. */+const FIGMA_OPEN_V =+ 'M10 10 L9.29289 10.7071 L10 11.4142 L10.7071 10.7071 L10 10 Z M0 0 L-0.707107 0.707107 L9.29289 10.7071 L10 10 L10.7071 9.29289 L0.707107 -0.707107 L0 0 Z M10 10 L10.7071 10.7071 L20.7071 0.707107 L20 0 L19.2929 -0.707107 L9.29289 9.29289 L10 10 Z'++/**+ * Whether two path data strings fill the same area. Figma builds a stroke from a piece per edge+ * and per corner, Skia from one outline, so the text differs where the area does not.+ */+function sameArea(renderer: SkiaRenderer, a: string, b: string): boolean {+ const { ck } = renderer+ // A union with itself fills each piece of Figma's once where they overlap.+ const [first, second] = [a, b].map((data) => {+ const read = ck.Path.MakeFromSVGString(data)+ if (!read) throw new Error('unreadable path data')+ const filled = ck.Path.MakeFromOp(read, read, ck.PathOp.Union)+ read.delete()+ if (!filled) throw new Error('union failed')+ return filled+ })+ const difference = ck.Path.MakeFromOp(first, second, ck.PathOp.XOR)+ first.delete()+ second.delete()+ if (!difference) throw new Error('XOR failed')+ const [left, top, right, bottom] = difference.computeTightBounds()+ difference.delete()+ return right - left < 1e-3 || bottom - top < 1e-3+}++async function setup(): Promise<{ figma: FigmaAPI; renderer: SkiaRenderer }> {+ const figma = createAPI()+ return { figma, renderer: await attachTestRenderer(figma) }+}++function rectangle(figma: FigmaAPI, props: Record<string, unknown> = {}) {+ const rect = figma.createRectangle()+ rect.resize(40, 20)+ rect.fills = [...RED]+ Object.assign(rect, props)+ return rect+}++describe('fillGeometry', () => {+ test('is the shape’s outline, whatever its fills or visibility', async () => {+ const { figma } = await setup()+ const outline = [{ windingRule: 'NONZERO', data: 'M0 0 L40 0 L40 20 L0 20 L0 0 Z' }] as const+ expect(rectangle(figma).fillGeometry).toEqual(outline)+ expect(rectangle(figma, { fills: [] }).fillGeometry).toEqual(outline)+ expect(rectangle(figma, { visible: false }).fillGeometry).toEqual(outline)+ })++ test('draws an ellipse with Figma’s curves', async () => {+ const { figma } = await setup()+ const ellipse = figma.createEllipse()+ ellipse.resize(20, 20)+ expect(ellipse.fillGeometry).toEqual([+ {+ windingRule: 'NONZERO',+ data: 'M20 10 C20 15.5228 15.5228 20 10 20 C4.47715 20 0 15.5228 0 10 C0 4.47715 4.47715 0 10 0 C15.5228 0 20 4.47715 20 10 Z'+ }+ ])+ })++ test('draws Figma’s default star', async () => {+ const { figma } = await setup()+ const star = figma.createStar()+ star.resize(20, 20)+ expect(star.fillGeometry).toEqual([+ {+ windingRule: 'NONZERO',+ data: 'M10 0 L12.2451 6.90983 L19.5106 6.90983 L13.6327 11.1803 L15.8779 18.0902 L10 13.8197 L4.12215 18.0902 L6.36729 11.1803 L0.489435 6.90983 L7.75486 6.90983 L10 0 Z'+ }+ ])+ })++ test('follows a vector edited after it was read', async () => {+ const { figma } = await setup()+ const vector = figma.createVector()+ vector.vectorPaths = [{ windingRule: 'NONZERO', data: 'M 0 0 L 10 0 L 10 10 Z' }]+ expect(vector.fillGeometry[0]?.data).toBe('M0 0 L10 0 L10 10 L0 0 Z')+ vector.vectorPaths = [{ windingRule: 'NONZERO', data: 'M 0 0 L 20 0 L 20 20 Z' }]+ expect(vector.fillGeometry[0]?.data).toBe('M0 0 L20 0 L20 20 L0 0 Z')+ })++ test('is empty for a line and an open vector', async () => {+ const { figma } = await setup()+ const line = figma.createLine()+ line.resize(30, 0)+ const open = figma.createVector()+ open.vectorPaths = [{ windingRule: 'NONE', data: 'M 0 0 L 10 10 L 20 0' }]+ expect(line.fillGeometry).toEqual([])+ expect(open.fillGeometry).toEqual([])+ })+})++describe('strokeGeometry', () => {+ test('is empty without a visible stroke of some weight', async () => {+ const { figma } = await setup()+ expect(rectangle(figma).strokeGeometry).toEqual([])+ expect(rectangle(figma, { strokes: [...BLUE], strokeWeight: 0 }).strokeGeometry).toEqual([])+ const hidden = [{ ...BLUE[0], visible: false }]+ expect(rectangle(figma, { strokes: hidden, strokeWeight: 4 }).strokeGeometry).toEqual([])+ })++ test('centres the band, twice as wide for an inside or outside stroke', async () => {+ const { figma, renderer } = await setup()+ const cases = [+ [{ strokeAlign: 'INSIDE', strokeWeight: 4 }, FIGMA_INSIDE_4],+ [{ strokeAlign: 'OUTSIDE', strokeWeight: 4 }, FIGMA_INSIDE_4],+ [{ strokeAlign: 'CENTER', strokeWeight: 4 }, FIGMA_CENTER_4],+ [+ { strokeTopWeight: 4, strokeRightWeight: 0, strokeBottomWeight: 1, strokeLeftWeight: 2 },+ FIGMA_SIDES+ ],+ // A hidden layer still has its stroke.+ [{ strokeAlign: 'CENTER', strokeWeight: 4, visible: false }, FIGMA_CENTER_4]+ ] as const+ for (const [props, figmaData] of cases) {+ const [stroke] = rectangle(figma, { strokes: [...BLUE], ...props }).strokeGeometry+ expect(stroke.windingRule).toBe('NONZERO')+ expect(sameArea(renderer, stroke.data, figmaData)).toBe(true)+ }+ })++ test('dashes the band as Figma does', async () => {+ const { figma, renderer } = await setup()+ const dashed = rectangle(figma, { strokes: [...BLUE], strokeWeight: 2, dashPattern: [4, 4] })+ expect(sameArea(renderer, dashed.strokeGeometry[0].data, FIGMA_DASHED)).toBe(true)+ // The comparison tells bands apart.+ expect(sameArea(renderer, FIGMA_INSIDE_4, FIGMA_CENTER_4)).toBe(false)+ })++ test('strokes a boolean along its result', async () => {+ const { figma, renderer } = await setup()+ const wide = figma.createRectangle()+ wide.resize(40, 20)+ const tall = figma.createRectangle()+ tall.resize(20, 40)+ const union = figma.union([wide, tall], figma.currentPage)+ union.strokes = [...BLUE]+ union.strokeWeight = 2+ union.strokeAlign = 'CENTER'+ expect(sameArea(renderer, union.strokeGeometry[0].data, FIGMA_BOOLEAN)).toBe(true)+ })++ test('strokes sides of their own weights, dashed or with the stroke’s own weight 0', async () => {+ const { figma, renderer } = await setup()+ const sides = {+ strokeTopWeight: 4,+ strokeRightWeight: 0,+ strokeBottomWeight: 1,+ strokeLeftWeight: 2+ }+ const dashed = rectangle(figma, { strokes: [...BLUE], ...sides, dashPattern: [4, 4] })+ expect(sameArea(renderer, dashed.strokeGeometry[0].data, FIGMA_SIDES_DASHED)).toBe(true)+ const top = rectangle(figma, {+ strokes: [...BLUE],+ strokeTopWeight: 2,+ strokeRightWeight: 0,+ strokeBottomWeight: 0,+ strokeLeftWeight: 0+ })+ expect(sameArea(renderer, top.strokeGeometry[0].data, FIGMA_TOP_SIDE)).toBe(true)+ })++ test('keeps dashed sides of a rounded layer within its rounded stroke', async () => {+ const { figma, renderer } = await setup()+ const sides = {+ strokeTopWeight: 4,+ strokeRightWeight: 2,+ strokeBottomWeight: 1,+ strokeLeftWeight: 2+ }+ const solid = rectangle(figma, { strokes: [...BLUE], cornerRadius: 8, ...sides })+ const dashed = rectangle(figma, {+ strokes: [...BLUE],+ cornerRadius: 8,+ ...sides,+ dashPattern: [4, 4]+ })+ const { ck } = renderer+ const ring = ck.Path.MakeFromSVGString(solid.strokeGeometry[0].data)+ const dashes = ck.Path.MakeFromSVGString(dashed.strokeGeometry[0].data)+ if (!ring || !dashes) throw new Error('unreadable path data')+ const outside = ck.Path.MakeFromOp(dashes, ring, ck.PathOp.Difference)+ if (!outside) throw new Error('difference failed')+ expect(outside.isEmpty()).toBe(true)+ for (const path of [ring, dashes, outside]) path.delete()+ })++ test('dashes every loop of a vector', async () => {+ const { figma, renderer } = await setup()+ const loops = figma.createVector()+ loops.vectorPaths = [+ {+ windingRule: 'NONZERO',+ data: 'M 0 0 L 20 0 L 20 20 L 0 20 Z M 40 0 L 60 0 L 60 20 L 40 20 Z'+ }+ ]+ loops.strokes = [...BLUE]+ loops.strokeWeight = 2+ loops.strokeAlign = 'CENTER'+ loops.dashPattern = [4, 4]+ expect(sameArea(renderer, loops.strokeGeometry[0].data, FIGMA_TWO_LOOPS)).toBe(true)+ })++ test('measures the layout a script left pending', async () => {+ const { figma } = await setup()+ const frame = figma.createFrame()+ frame.layoutMode = 'HORIZONTAL'+ frame.primaryAxisSizingMode = 'AUTO'+ frame.counterAxisSizingMode = 'AUTO'+ const child = figma.createRectangle()+ child.resize(30, 10)+ frame.appendChild(child)+ child.resize(50, 10)+ expect(frame.fillGeometry).toEqual([+ { windingRule: 'NONZERO', data: 'M0 0 L50 0 L50 10 L0 10 L0 0 Z' }+ ])+ })++ test('strokes a line and an open vector along their path', async () => {+ const { figma, renderer } = await setup()+ const line = figma.createLine()+ line.resize(30, 0)+ line.strokes = [...BLUE]+ line.strokeWeight = 2+ const open = figma.createVector()+ open.vectorPaths = [{ windingRule: 'NONE', data: 'M 0 0 L 10 10 L 20 0' }]+ open.strokes = [...BLUE]+ open.strokeWeight = 2+ expect(sameArea(renderer, line.strokeGeometry[0].data, FIGMA_LINE_2)).toBe(true)+ expect(sameArea(renderer, open.strokeGeometry[0].data, FIGMA_OPEN_V)).toBe(true)+ })+})++describe('outlineStroke', () => {+ test('adds the stroke as a vector at the end of the page and keeps the layer', async () => {+ const { figma } = await setup()+ const frame = figma.createFrame()+ frame.x = 1000+ frame.y = 500+ const rect = rectangle(figma, {+ name: 'R',+ x: 5,+ y: 7,+ strokes: [...BLUE],+ strokeWeight: 4,+ strokeAlign: 'INSIDE',+ opacity: 0.5+ })+ frame.appendChild(rect)+ const outline = rect.outlineStroke()+ expect(outline).not.toBeNull()+ expect(outline?.type).toBe('VECTOR')+ expect(outline?.name).toBe('R (Stroke)')+ // Figma puts it on the page at the layer's place in its parent.+ expect(outline?.parent?.id).toBe(figma.currentPage.id)+ expect(figma.currentPage.children.at(-1)?.id).toBe(outline?.id)+ expect([outline?.x, outline?.y, outline?.width, outline?.height]).toEqual([5, 7, 40, 20])+ expect(outline?.fills).toMatchObject([{ type: 'SOLID', color: { r: 0, g: 0, b: 1 } }])+ expect(outline?.strokes).toEqual([])+ expect(outline?.opacity).toBe(0.5)+ expect(rect.removed).toBe(false)+ })++ test('is null without a visible stroke', async () => {+ const { figma } = await setup()+ expect(rectangle(figma).outlineStroke()).toBeNull()+ const hidden = [{ ...BLUE[0], visible: false }]+ expect(rectangle(figma, { strokes: hidden, strokeWeight: 4 }).outlineStroke()).toBeNull()+ })++ test('outlines text as a group of glyph vectors', async () => {+ const { figma } = await setup()+ await registerTestFont('Inter')+ await figma.loadFontAsync({ family: 'Inter', style: 'Regular' })+ const text = figma.createText()+ text.name = 'T'+ text.characters = 'Hi'+ text.strokes = [...BLUE]+ const outline = text.outlineStroke()+ expect(outline?.type).toBe('GROUP')+ expect(outline?.name).toBe('T (Stroke)')+ expect(outline?.children.length).toBeGreaterThan(0)+ expect(outline?.children.every((glyph) => glyph.type === 'VECTOR')).toBe(true)+ })+})++describe('geometry members', () => {+ test('exist where Figma has them', () => {+ const figma = createAPI()+ const group = figma.group([figma.createRectangle()], figma.currentPage)+ for (const node of [figma.createRectangle(), figma.createFrame(), figma.createLine()]) {+ expect('fillGeometry' in node && 'strokeGeometry' in node && 'outlineStroke' in node).toBe(+ true+ )+ }+ for (const node of [group, figma.currentPage, figma.createSection()]) {+ expect('fillGeometry' in node || 'outlineStroke' in node).toBe(false)+ }+ })++ test('say so on a host without a renderer', () => {+ const figma = createAPI()+ const rect = figma.createRectangle()+ expect(() => rect.fillGeometry).toThrow(+ 'in get_fillGeometry: This host has no renderer to measure geometry with'+ )+ expect(() => rect.outlineStroke()).toThrow(+ 'in outlineStroke: This host has no renderer to measure geometry with'+ )+ })+})diff --git a/packages/core/tests/helpers/figma-api.ts b/packages/core/tests/helpers/figma-api.tsindex 424d7a056..5cbdbea0b 100644--- a/packages/core/tests/helpers/figma-api.ts+++ b/packages/core/tests/helpers/figma-api.ts@@ -5,7 +5,9 @@ import type {TextNode} from '@figma/plugin-typings/plugin-api-standalone'+import type { SkiaRenderer } from '@open-pencil/core/canvas'import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'+import { headlessRenderer } from '@open-pencil/core/io/formats/raster'import { fontManager } from '@open-pencil/core/text'import { SceneGraph, type Fill } from '@open-pencil/scene-graph'import type { Color } from '@open-pencil/scene-graph/primitives'@@ -84,3 +86,17 @@ export function createStackHost() {const order = () => host.children.map((child: FigmaNodeProxy) => child.name)return { figma, host, rect, order }}++/**+ * Attaches the process's headless renderer to `api`, as the app and `open-pencil eval` do, so+ * geometry, booleans, and flatten measure real paths. One renderer serves every test, as each new+ * one would keep its own copy of every font loaded after it; the paths it keeps by layer id are+ * cleared, since another document's layers share those ids.+ */+export async function attachTestRenderer(api: FigmaAPI): Promise<SkiaRenderer> {+ const renderer = await headlessRenderer()+ renderer.nodePaths.clear()+ renderer.invalidateAllPictures()+ api.setRenderer(renderer)+ return renderer+}diff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex 30c65ab3b..4f0883c27 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -252,6 +252,12 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'- `node.exportAsync(settings?)` on layers and pages writes `PNG` and `JPG` (sized by a `SCALE`, `WIDTH`, or `HEIGHT` constraint, cropped to the layer's box with `useAbsoluteBounds`), `SVG` as bytes, `SVG_STRING` as a string (with layer names as element ids when `svgIdAttribute` is set), and `PDF`. PNG and JPG need a renderer: the desktop app, the browser app, and `open-pencil eval` have one. SVG text stays `<text>` whatever `svgOutlineText` says, colour profiles are not applied, and `contentsOnly: false` exports the layer alone. A hidden or empty layer is refused with `The layer draws nothing to export`, where Figma exports a 1×1 image. OpenPencil also refuses an image at less than 0.01 or more than 1024 times the layer's size, or larger than 8192 by 8192 pixels. `JSON_REST_V1` and video formats are refused- `node.exportSettings` reads and sets the exports a layer keeps, with Figma's options and defaults; exports in formats Figma has no setting for, such as WebP or PowerPoint, are left out+### Geometry++- `node.fillGeometry` and `node.strokeGeometry` on shapes, text, frames, components, instances, and boolean operations give Figma's `VectorPaths` in the layer's own box. `fillGeometry` is the outline of the layer's shape whatever its fills, and empty for lines and open vectors. `strokeGeometry` is the band every visible stroke covers, centred on the edge and twice the weight wide for inside and outside strokes, with dashes and per-side weights. It covers the same area as Figma's, though Figma writes a stroke as a piece per edge and corner where OpenPencil writes its outline+- `node.outlineStroke()` adds the layer's stroke as a vector filled with the stroke's paints, named `<name> (Stroke)` (a group of glyph vectors for text), at the end of the page at the layer's position in its parent, as Figma does, and keeps the layer. It returns `null` without a visible stroke+- These measure with a renderer: the canvas's in the desktop and browser apps, and a headless one in `open-pencil eval`. Before a document's canvas is ready, or on a host without a renderer, they throw `This host has no renderer to measure geometry with`+### PropertiesCommon node properties are readable/writable through the proxy, including:diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex 1d4a8abbe..ae5aaa044 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -187,7 +187,8 @@ export function createDefaultNode(textTruncation: 'DISABLED',autoRename: true,pointCount: 5,- starInnerRadius: 0.38,+ // Figma's: the golden-ratio star, whose inner points line up with its outer ones.+ starInnerRadius: (3 - Math.sqrt(5)) / 2,shapeWithTextType: 'SQUARE',shapeUserHeight: 0,shapeTruncates: false,