AI-native design editor. Open-source Figma alternative.
fix(core): scale vector geometry during API resize (#1456)
Danny Ward7972f82fe733
diff --git a/changes/1456/fixed.md b/changes/1456/fixed.mdnew file mode 100644index 000000000..a1d934b0a--- /dev/null+++ b/changes/1456/fixed.md@@ -0,0 +1 @@+- Resizing an imported SVG vector through the Plugin API scales its geometry to the requested dimensions.diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsindex 469561fd7..8a2fb71b5 100644--- a/packages/core/src/figma-api/accessors/basic.ts+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -1,4 +1,4 @@-import { pickBy } from 'es-toolkit'+import { isEmptyObject, pickBy } from 'es-toolkit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'@@ -11,6 +11,7 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'import {computeConstrainedResizeChanges,createResizeSnapshot,+ scaledGeometryChanges,type ResizeSnapshot} from '@open-pencil/scene-graph/resize'import { rescaleNodeTree } from '@open-pencil/scene-graph/scaling'@@ -40,6 +41,7 @@ import {import type { FigmaTransform } from '#core/figma-api/types'import { syncVariantName } from '#core/figma-api/variants'import { figmaRotation } from '#core/geometry/figma'+import { computeAccurateBounds } from '#core/vector/curve-math'const TRANSFORM_FIELDS: ReadonlySet<string> = new Set(NODE_TRANSFORM_FIELDS)@@ -260,6 +262,53 @@ function descendants(scene: SceneGraph, node: SceneNode): SceneNode[] {return scene.getChildren(node.id).flatMap((child) => [child, ...descendants(scene, child)])}+/**+ * A vector's path scaled to its new size, as Figma's resize does. The stroke keeps its weight: with+ * a network to stroke, the saved stroke outline goes and the stroke draws from the scaled path, as+ * when the path is set; without one, the outline is all that draws the stroke, so it scales too.+ */+function resizedVectorGeometry(node: SceneNode, width: number, height: number): Partial<SceneNode> {+ if (node.type !== 'VECTOR') return {}+ const strokesPath = (node.vectorNetwork?.vertices.length ?? 0) > 0+ const snapshot = createResizeSnapshot(node)+ const path = {+ ...snapshot,+ strokes: [],+ strokeGeometry: strokesPath ? [] : snapshot.strokeGeometry+ }+ // A side at zero keeps the path along it, as in Figma, so the next resize scales the path from+ // its own extent and gets the shape back.+ const bounds = node.vectorNetwork ? computeAccurateBounds(node.vectorNetwork) : null+ const fromWidth = node.width > 0 ? node.width : (bounds?.width ?? 0)+ const fromHeight = node.height > 0 ? node.height : (bounds?.height ?? 0)+ const geometry = scaledGeometryChanges(+ path,+ fromWidth,+ fromHeight,+ width || fromWidth,+ height || fromHeight+ )+ if (!strokesPath || isEmptyObject(geometry) || node.strokeGeometry.length === 0) return geometry+ return { ...geometry, strokeGeometry: [] }+}++/** The least size Figma's `resize` gives a vector side; `resizeWithoutConstraints` allows zero. */+const MIN_VECTOR_RESIZE = 0.0001++/** The size a resize gives a node: a vector cannot become 0×0, and `resize` keeps its sides above zero. */+function resizedSize(+ node: SceneNode,+ width: number,+ height: number,+ constrained: boolean+): { width: number; height: number } {+ if (node.type !== 'VECTOR') return { width, height }+ if (width === 0 && height === 0)+ throw new Error('Cannot set width and height of vector node to zero')+ if (!constrained) return { width, height }+ return { width: Math.max(width, MIN_VECTOR_RESIZE), height: Math.max(height, MIN_VECTOR_RESIZE) }+}+/*** Resizes a node keeping its top-left corner, as Figma's does, though it turns about its center.* `resize` places the layers inside by their constraints, as Figma's does, without making their@@ -269,13 +318,14 @@ function descendants(scene: SceneGraph, node: SceneNode): SceneNode[] {function resizeNode(target: ProxyThis,internals: NodeProxyInternals,- width: number,- height: number,+ requestedWidth: number,+ requestedHeight: number,constrained: boolean): void {assertEditable(target, internals)const scene = graph(target, internals)const node = raw(target, internals)+ const { width, height } = resizedSize(node, requestedWidth, requestedHeight, constrained)const before = containerTransform(node, scene)const size = { width: node.width, height: node.height }// An instance's layers follow its constraints however it is resized, as in Figma.@@ -283,6 +333,7 @@ function resizeNode(constrained || node.type === 'INSTANCE'? new Map(descendants(scene, node).map((child) => [child.id, createResizeSnapshot(child)])): new Map<string, ResizeSnapshot>()+ const geometry = resizedVectorGeometry(node, width, height)// Text given a size stops sizing itself to its content, as in Figma.const fixesText =node.type === 'TEXT' &&@@ -300,6 +351,7 @@ function resizeNode(scene.updateNode(node.id, {width,height,+ ...geometry,...recaptured,...sizing,...(fixesText ? { textAutoResize: 'NONE' as const } : {})@@ -311,6 +363,7 @@ function resizeNode(recordInstanceOverride(scene, node.id, ['width','height',+ ...Object.keys(geometry),...Object.keys(recaptured),...Object.keys(sizing),...(fixesText ? ['textAutoResize'] : [])diff --git a/packages/core/src/tools/create/vector.ts b/packages/core/src/tools/create/vector.tsindex 7916d3a32..8451e0e50 100644--- a/packages/core/src/tools/create/vector.ts+++ b/packages/core/src/tools/create/vector.ts@@ -23,6 +23,10 @@ function parseSVGVectorPath(path: string): VectorPathResult {}const bounds = computeAccurateBounds(network)+ // Figma's vectors cannot be 0×0, so a path that never leaves its start is not one.+ if (bounds.width === 0 && bounds.height === 0) {+ return { error: 'SVG path data must span some width or height' }+ }return {network: transformVectorNetwork([1, 0, -bounds.x, 0, 1, -bounds.y, 0, 0, 1], network),size: { width: bounds.width, height: bounds.height }@@ -70,8 +74,8 @@ export const createVector = defineTool({node.y = args.yif (args.name) node.name = args.nameif (parsedPath) {- figma.graph.updateNode(node.id, { vectorNetwork: parsedPath.network })if (parsedPath.size) node.resize(parsedPath.size.width, parsedPath.size.height)+ figma.graph.updateNode(node.id, { vectorNetwork: parsedPath.network })}if (args.fill) {node.fills = [{ type: 'SOLID', color: parseColor(args.fill), opacity: 1, visible: true }]diff --git a/packages/core/tests/figma-api/resize-constraints.test.ts b/packages/core/tests/figma-api/accessors/basic/resize/constraints.test.tssimilarity index 100%rename from packages/core/tests/figma-api/resize-constraints.test.tsrename to packages/core/tests/figma-api/accessors/basic/resize/constraints.test.tsdiff --git a/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts b/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.tsnew file mode 100644index 000000000..3ca0e09e0--- /dev/null+++ b/packages/core/tests/figma-api/accessors/basic/resize/vector-geometry.test.ts@@ -0,0 +1,139 @@+import { expect, test } from 'bun:test'++import { uniqBy } from 'es-toolkit'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { createSVGNodes } from '@open-pencil/core/io/formats/svg'+import { SceneGraph } from '@open-pencil/scene-graph'++const SVG =+ '<svg xmlns="http://www.w3.org/2000/svg"><rect width="318" height="80" rx="12" fill="#558855"/></svg>'++const STROKED_SVG =+ '<svg xmlns="http://www.w3.org/2000/svg"><rect x="2" y="2" width="314" height="76" fill="none" stroke="#000" stroke-width="4"/></svg>'++function importedVector(svg = SVG, graph = new SceneGraph()) {+ const root = createSVGNodes(graph, graph.getPages()[0].id, svg)+ if (!root) throw new Error('SVG import produced no nodes')+ const [node] = graph.getChildren(root.id)+ if (node?.type !== 'VECTOR') throw new Error('SVG rectangle did not import as a vector')+ const proxy = new FigmaAPI(graph).getNodeById(node.id)+ if (!proxy) throw new Error('Imported vector proxy was not found')+ return proxy+}++// Recorded in Figma 126: both methods squeeze the 12 px corners to 9.6 px tall.+const round = (value: number) => Math.round(value * 1000) / 1000++const RESIZED_VERTICES = [+ [12, 0],+ [306, 0],+ [318, 9.6],+ [318, 54.4],+ [306, 64],+ [12, 64],+ [0, 54.4],+ [0, 9.6]+]++for (const method of ['resize', 'resizeWithoutConstraints'] as const) {+ test(`${method} scales an imported vector's geometry with its box`, () => {+ // Regression for #1438: the SVG path must follow the new Plugin API dimensions.+ const vector = importedVector()++ vector[method](318, 64)++ const resizedNetwork = vector.vectorNetwork+ if (!resizedNetwork) throw new Error('Resized vector has no vector network')+ expect(vector.width).toBe(318)+ expect(vector.height).toBe(64)+ // Our SVG import keeps the closing point as its own vertex, which Figma merges.+ const vertices = uniqBy(+ resizedNetwork.vertices.map(({ x, y }) => [round(x), round(y)]),+ (point) => point.join(',')+ )+ expect(vertices).toEqual(RESIZED_VERTICES)+ })+}++// Figma 126: a 4 px stroke on a vector resized to half its height is still 4 px.+test('resize keeps the stroke weight and draws the stroke from the scaled path', () => {+ const graph = new SceneGraph()+ const vector = importedVector(STROKED_SVG, graph)+ graph.updateNode(vector.id, {+ strokeGeometry: [{ windingRule: 'NONZERO', commandsBlob: new Uint8Array([0]) }]+ })++ vector.resize(vector.width, vector.height / 2)++ expect(vector.strokeWeight).toBe(4)+ expect(graph.getNode(vector.id)?.strokeGeometry).toEqual([])+})++/** A path that moves to (x, y), enough for saved geometry to scale. */+function moveTo(x: number, y: number) {+ const commandsBlob = new Uint8Array(9)+ commandsBlob[0] = 1+ const view = new DataView(commandsBlob.buffer)+ view.setFloat32(1, x, true)+ view.setFloat32(5, y, true)+ return { windingRule: 'NONZERO' as const, commandsBlob }+}++test('a vector without a network keeps its saved stroke outline, scaled with the shape', () => {+ const graph = new SceneGraph()+ const vector = importedVector(STROKED_SVG, graph)+ graph.updateNode(vector.id, {+ vectorNetwork: null,+ fillGeometry: [moveTo(0, 76)],+ strokeGeometry: [moveTo(0, 76)]+ })++ vector.resize(vector.width, vector.height / 2)++ const node = graph.getNode(vector.id)+ expect(vector.strokeWeight).toBe(4)+ expect(node?.strokeGeometry).toHaveLength(1)+ const blob = node?.strokeGeometry[0]?.commandsBlob+ if (!blob) throw new Error('Resized vector lost its stroke outline')+ expect(new DataView(blob.buffer, blob.byteOffset).getFloat32(5, true)).toBeCloseTo(38)+})++// Recorded in Figma 126 for the same 318×80 rectangle.+test('a vector cannot be resized to 0×0', () => {+ const vector = importedVector()+ expect(() => vector.resize(0, 0)).toThrow('Cannot set width and height of vector node to zero')+ expect(() => vector.resizeWithoutConstraints(0, 0)).toThrow(+ 'Cannot set width and height of vector node to zero'+ )+ expect(vector.width).toBe(318)+})++test('resize keeps a vector side above zero, so the shape comes back', () => {+ const vector = importedVector()+ vector.resize(0, 80)+ expect(vector.width).toBeCloseTo(0.0001, 6)++ vector.resize(318, 80)+ const corners = vector.vectorNetwork?.vertices.slice(0, 3).map(({ x, y }) => [round(x), round(y)])+ expect(corners).toEqual([+ [12, 0],+ [306, 0],+ [318, 12]+ ])+})++test('resizeWithoutConstraints to a zero side keeps the path, so the shape comes back', () => {+ const vector = importedVector()+ vector.resizeWithoutConstraints(0, 64)+ expect(vector.width).toBe(0)+ expect(vector.height).toBe(64)++ vector.resizeWithoutConstraints(318, 80)+ const corners = vector.vectorNetwork?.vertices.slice(0, 3).map(({ x, y }) => [round(x), round(y)])+ expect(corners).toEqual([+ [12, 0],+ [306, 0],+ [318, 12]+ ])+})diff --git a/tests/engine/tools/create.test.ts b/tests/engine/tools/create.test.tsindex 929aae9a0..fcaf4c0dd 100644--- a/tests/engine/tools/create.test.ts+++ b/tests/engine/tools/create.test.ts@@ -230,7 +230,7 @@ describe('create_vector', () => {const tool = getTool('create_vector')const before = graph.nodes.size- for (const path of ['', 'not a path', 'null', 'M0 0 L']) {+ for (const path of ['', 'not a path', 'null', 'M0 0 L', 'M0 0 L0 0']) {const result = tool.execute(figma, { x: 0, y: 0, name: 'Ghost', path }) as ToolResultexpect(result.error).toBeDefined()expect(graph.nodes.size).toBe(before)