Skip to content

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

fix(figma-api): resize as Figma does inside instances and at zero sizes (#1565)

Danila Poyarkovaedde5c63862
diff --git a/changes/1565/fixed.md b/changes/1565/fixed.md
new file mode 100644
index 000000000..4c6333ff5
--- /dev/null
+++ b/changes/1565/fixed.md
@@ -0,0 +1 @@
+- A script resizing a layer inside an instance leaves it as it is, as in Figma, instead of recording a size Figma drops, and `resize()` keeps every side at least 0.0001, except a line's height of 0.
diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.ts
index 8a2fb71b5..c9178a30c 100644
--- a/packages/core/src/figma-api/accessors/basic.ts
+++ b/packages/core/src/figma-api/accessors/basic.ts
@@ -1,4 +1,4 @@
-import { isEmptyObject, pickBy } from 'es-toolkit'
+import { isEmptyObject } from 'es-toolkit'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
@@ -29,6 +29,7 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
+import { invalid, numberProblem } from '#core/figma-api/accessors/text/messages'
import { flushPendingLayout } from '#core/figma-api/pending-layout'
import type { NodeProxyHost } from '#core/figma-api/proxy'
import { computeAbsoluteRenderBounds } from '#core/figma-api/render-bounds'
@@ -292,21 +293,66 @@ function resizedVectorGeometry(node: SceneNode, width: number, height: number):
return { ...geometry, strokeGeometry: [] }
}
-/** The least size Figma's `resize` gives a vector side; `resizeWithoutConstraints` allows zero. */
-const MIN_VECTOR_RESIZE = 0.0001
+/** The least size Figma's `resize` gives a side; `resizeWithoutConstraints` allows zero. */
+const MIN_RESIZE = 0.0001
-/** The size a resize gives a node: a vector cannot become 0×0, and `resize` keeps its sides above zero. */
+/**
+ * The size a resize gives a node, as Figma's does: it refuses a side that is not a number or is
+ * negative, and a vector cannot become 0×0. `resize` keeps the sides above zero, except a line's
+ * height of zero, which is the height a line has.
+ */
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)
+ const method = constrained ? 'resize' : 'resizeWithoutConstraints'
+ for (const [property, value] of [
+ ['width', width],
+ ['height', height]
+ ] as const) {
+ const problem =
+ numberProblem(value) ?? (value < 0 ? 'Too small: expected number to be >=0' : null)
+ if (problem) throw invalid(method, problem, property)
+ }
+ if (node.type === 'VECTOR' && 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) }
+ return {
+ width: Math.max(width, MIN_RESIZE),
+ height: node.type === 'LINE' && height === 0 ? 0 : Math.max(height, MIN_RESIZE)
+ }
+}
+
+interface ChangedSides {
+ width: boolean
+ height: boolean
+}
+
+/** Auto layout given a new size on an axis stops hugging along it, as in Figma; the other keeps on. */
+function resizedLayoutSizing(node: SceneNode, changed: ChangedSides): Partial<SceneNode> {
+ if (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL') return {}
+ const row = node.layoutMode === 'HORIZONTAL'
+ const sizing: Partial<SceneNode> = {}
+ if ((row ? changed.width : changed.height) && node.primaryAxisSizing !== 'FIXED')
+ sizing.primaryAxisSizing = 'FIXED'
+ if ((row ? changed.height : changed.width) && node.counterAxisSizing !== 'FIXED')
+ sizing.counterAxisSizing = 'FIXED'
+ return sizing
+}
+
+/**
+ * How a text sizes itself after a resize, as in Figma: a new height fixes it, and a new width alone
+ * leaves auto-width text sizing only its height.
+ */
+function resizedTextSizing(node: SceneNode, changed: ChangedSides): Partial<SceneNode> {
+ if (node.type !== 'TEXT') return {}
+ const mode = node.textAutoResize
+ if (changed.height && (mode === 'HEIGHT' || mode === 'WIDTH_AND_HEIGHT'))
+ return { textAutoResize: 'NONE' }
+ if (changed.width && mode === 'WIDTH_AND_HEIGHT') return { textAutoResize: 'HEIGHT' }
+ return {}
}
/**
@@ -326,6 +372,8 @@ function resizeNode(
const scene = graph(target, internals)
const node = raw(target, internals)
const { width, height } = resizedSize(node, requestedWidth, requestedHeight, constrained)
+ // Figma has no size for a layer inside an instance: the resize does nothing, and records nothing.
+ if (node.parentId && findInstanceAncestor(scene, node.parentId)) return
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.
@@ -334,39 +382,21 @@ function resizeNode(
? 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' &&
- (node.textAutoResize === 'WIDTH_AND_HEIGHT' || node.textAutoResize === 'HEIGHT')
// A locked ratio does not hold here; it takes the new size, as in Figma.
const recaptured = recapturedAspectRatio(node, width, height)
- // Auto layout given a size keeps it, as in Figma: hugging axes become fixed.
- const fixed = node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL'
- const sizing = fixed
- ? pickBy(
- { primaryAxisSizing: 'FIXED' as const, counterAxisSizing: 'FIXED' as const },
- (value, key) => node[key] !== value
- )
- : {}
- scene.updateNode(node.id, {
- width,
- height,
- ...geometry,
- ...recaptured,
- ...sizing,
- ...(fixesText ? { textAutoResize: 'NONE' as const } : {})
- })
+ const changed = { width: width !== size.width, height: height !== size.height }
+ const sizing = { ...resizedLayoutSizing(node, changed), ...resizedTextSizing(node, changed) }
+ scene.updateNode(node.id, { width, height, ...geometry, ...recaptured, ...sizing })
if (placed.size > 0 && size.width > 0 && size.height > 0) {
const changes = computeConstrainedResizeChanges(scene, node.id, size, { width, height }, placed)
for (const [id, change] of changes) scene.updateNode(id, change)
}
+ // A size the layer already has records nothing, as in Figma; a new one records both sides.
recordInstanceOverride(scene, node.id, [
- 'width',
- 'height',
+ ...(changed.width || changed.height ? ['width', 'height'] : []),
...Object.keys(geometry),
...Object.keys(recaptured),
- ...Object.keys(sizing),
- ...(fixesText ? ['textAutoResize'] : [])
+ ...Object.keys(sizing)
])
setTransform(target, internals, () => before)
}
diff --git a/packages/core/src/figma-api/accessors/shape.ts b/packages/core/src/figma-api/accessors/shape.ts
index f74cddd41..450b8b2af 100644
--- a/packages/core/src/figma-api/accessors/shape.ts
+++ b/packages/core/src/figma-api/accessors/shape.ts
@@ -6,22 +6,13 @@ import {
type NodeProxyInternals,
type ProxyThis
} from '#core/figma-api/accessor-utils'
-import { invalid, received } from '#core/figma-api/accessors/text/messages'
+import { invalid, numberProblem, 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}`
diff --git a/packages/core/src/figma-api/accessors/text/messages.ts b/packages/core/src/figma-api/accessors/text/messages.ts
index e98e40d1c..8d7eec183 100644
--- a/packages/core/src/figma-api/accessors/text/messages.ts
+++ b/packages/core/src/figma-api/accessors/text/messages.ts
@@ -8,3 +8,12 @@ export function received(value: unknown): string {
if (Array.isArray(value)) return 'array'
return value === null ? 'null' : typeof value
}
+
+/** Figma's complaint about `value` as a number at `at`, or null when it is one. */
+export function numberProblem(value: unknown, at = ''): string | null {
+ if (typeof value === 'number' && !Number.isNaN(value)) return null
+ if (value === undefined) return `Required value missing${at}`
+ // Shape and size 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}`
+}
diff --git a/packages/core/src/tools/modify/update.ts b/packages/core/src/tools/modify/update.ts
index ca51b9eac..a52e1fa09 100644
--- a/packages/core/src/tools/modify/update.ts
+++ b/packages/core/src/tools/modify/update.ts
@@ -3,8 +3,34 @@ import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
import { assertNodeEditable } from '#core/editor/capabilities'
+import type { FigmaNodeProxy } from '#core/figma-api'
import { toolNumber, nodeIdInputSchema, defineTool, nodeNotFound } from '#core/tools/schema'
+/** The size of a layer and how auto layout or its text sizes it, which a resize may change. */
+function sizing(node: FigmaNodeProxy) {
+ return {
+ width: node.width,
+ height: node.height,
+ layoutSizingHorizontal: node.layoutSizingHorizontal,
+ layoutSizingVertical: node.layoutSizingVertical,
+ textAutoResize: node.textAutoResize
+ }
+}
+
+/**
+ * Resizes a layer and names what the resize changed: a layer inside an instance keeps its size,
+ * as in Figma, while an auto layout frame or a text given its own size stops sizing itself.
+ */
+function resized(node: FigmaNodeProxy, width = node.width, height = node.height): string[] {
+ const before = sizing(node)
+ node.resize(width, height)
+ const after = sizing(node)
+ const changed = after.width !== before.width || after.height !== before.height ? ['size'] : []
+ for (const key of ['layoutSizingHorizontal', 'layoutSizingVertical', 'textAutoResize'] as const)
+ if (after[key] !== before[key]) changed.push(key)
+ return changed
+}
+
export const updateNode = defineTool({
name: 'update_node',
@@ -57,10 +83,8 @@ export const updateNode = defineTool({
node.y = args.y
updated.push('y')
}
- if (args.width !== undefined || args.height !== undefined) {
- node.resize(args.width ?? node.width, args.height ?? node.height)
- updated.push('size')
- }
+ if (args.width !== undefined || args.height !== undefined)
+ updated.push(...resized(node, args.width, args.height))
if (args.opacity !== undefined) {
node.opacity = args.opacity
updated.push('opacity')
diff --git a/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts b/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts
new file mode 100644
index 000000000..a82d1ebd9
--- /dev/null
+++ b/packages/core/tests/figma-api/accessors/basic/resize/limits.test.ts
@@ -0,0 +1,157 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, type FigmaNodeProxy } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { hasInstanceOverride } from '@open-pencil/scene-graph/instances'
+
+// Recorded in Figma desktop 126 (2026-10-27).
+
+const size = (node: FigmaNodeProxy) => [node.width, node.height]
+
+describe('resize to zero', () => {
+ test('resize keeps each side of any layer at 0.0001 or more', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ for (const create of [
+ () => figma.createFrame(),
+ () => figma.createRectangle(),
+ () => figma.createEllipse(),
+ () => figma.createStar(),
+ () => figma.createComponent()
+ ]) {
+ const node = create()
+ node.resize(0, 50)
+ expect(size(node)).toEqual([0.0001, 50])
+ node.resize(0, 0)
+ expect(size(node)).toEqual([0.0001, 0.0001])
+ node.resize(0.001, 0.00001)
+ expect(size(node)).toEqual([0.001, 0.0001])
+ }
+ })
+
+ test('a line keeps a height of zero, and resizeWithoutConstraints keeps any zero', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const line = figma.createLine()
+ line.resize(0, 0)
+ expect(size(line)).toEqual([0.0001, 0])
+ line.resize(50, 0.00001)
+ expect(size(line)).toEqual([50, 0.0001])
+ const frame = figma.createFrame()
+ frame.resizeWithoutConstraints(0, 0)
+ expect(size(frame)).toEqual([0, 0])
+ })
+
+ test('a negative side or one that is not a number is refused', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const frame = figma.createFrame()
+ expect(() => frame.resize(-5, 50)).toThrow(
+ 'in resize: Property "width" failed validation: Too small: expected number to be >=0'
+ )
+ expect(() => frame.resizeWithoutConstraints(5, -1)).toThrow(
+ 'in resizeWithoutConstraints: Property "height" failed validation: Too small: expected number to be >=0'
+ )
+ expect(() => frame.resize(Number.NaN, 5)).toThrow(
+ 'in resize: Property "width" failed validation: Expected number, received NaN'
+ )
+ expect(size(frame)).toEqual([100, 100])
+ })
+})
+
+describe('resize inside an instance', () => {
+ function instanceLayers() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const inner = figma.createComponent()
+ inner.resize(20, 20)
+ const card = figma.createComponent()
+ card.appendChild(inner.createInstance())
+ const rectangle = figma.createRectangle()
+ rectangle.resize(30, 30)
+ card.appendChild(rectangle)
+ const stack = figma.createComponent()
+ stack.layoutMode = 'VERTICAL'
+ const item = figma.createFrame()
+ item.resize(40, 40)
+ stack.appendChild(item)
+ const layers = [
+ ...(card.createInstance().children as FigmaNodeProxy[]),
+ ...(stack.createInstance().children as FigmaNodeProxy[])
+ ]
+ return { graph, layers }
+ }
+
+ test('does nothing to a free layer, a nested instance, or an auto layout child', () => {
+ const { graph, layers } = instanceLayers()
+ for (const resize of ['resize', 'resizeWithoutConstraints'] as const) {
+ for (const layer of layers) {
+ const before = size(layer)
+ layer[resize](55, 66)
+ expect(size(layer)).toEqual(before)
+ expect(hasInstanceOverride(graph, layer.id, 'width')).toBe(false)
+ }
+ }
+ })
+
+ test('still refuses a negative side', () => {
+ const { layers } = instanceLayers()
+ expect(() => layers[1].resize(-5, 10)).toThrow(
+ 'in resize: Property "width" failed validation: Too small: expected number to be >=0'
+ )
+ })
+})
+
+describe('resize to the size a layer has', () => {
+ test('records no size override on an instance, and a new size records both sides', () => {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const component = figma.createComponent()
+ component.resize(40, 30)
+ const instance = component.createInstance()
+
+ instance.resize(40, 30)
+ expect(hasInstanceOverride(graph, instance.id, 'width')).toBe(false)
+ expect(hasInstanceOverride(graph, instance.id, 'height')).toBe(false)
+
+ instance.resize(60, 30)
+ expect(hasInstanceOverride(graph, instance.id, 'width')).toBe(true)
+ expect(hasInstanceOverride(graph, instance.id, 'height')).toBe(true)
+ })
+})
+
+describe('sizing after a resize', () => {
+ function stack(figma: FigmaAPI) {
+ const frame = figma.createFrame()
+ frame.layoutMode = 'HORIZONTAL'
+ frame.primaryAxisSizingMode = 'AUTO'
+ frame.counterAxisSizingMode = 'AUTO'
+ const item = figma.createRectangle()
+ item.resize(40, 20)
+ frame.appendChild(item)
+ return frame
+ }
+
+ test('auto layout stops hugging only along an axis whose size changes', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const same = stack(figma)
+ same.resize(same.width, same.height)
+ expect([same.primaryAxisSizingMode, same.counterAxisSizingMode]).toEqual(['AUTO', 'AUTO'])
+ const wider = stack(figma)
+ wider.resize(60, wider.height)
+ expect([wider.primaryAxisSizingMode, wider.counterAxisSizingMode]).toEqual(['FIXED', 'AUTO'])
+ })
+
+ test('a text keeps sizing itself along the sides a resize leaves alone', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const after = (mode: 'WIDTH_AND_HEIGHT' | 'HEIGHT', width: number, height: number): string => {
+ const text = figma.createText()
+ text.characters = 'Label'
+ text.textAutoResize = mode
+ text.resize(text.width + width, text.height + height)
+ return text.textAutoResize
+ }
+ expect(after('WIDTH_AND_HEIGHT', 0, 0)).toBe('WIDTH_AND_HEIGHT')
+ expect(after('WIDTH_AND_HEIGHT', 20, 0)).toBe('HEIGHT')
+ expect(after('WIDTH_AND_HEIGHT', 0, 10)).toBe('NONE')
+ expect(after('HEIGHT', 20, 0)).toBe('HEIGHT')
+ expect(after('HEIGHT', 0, 10)).toBe('NONE')
+ })
+})
diff --git a/packages/core/tests/figma-api/components/instances.test.ts b/packages/core/tests/figma-api/components/instances.test.ts
index 80d4036d8..ccb0de9a8 100644
--- a/packages/core/tests/figma-api/components/instances.test.ts
+++ b/packages/core/tests/figma-api/components/instances.test.ts
@@ -152,7 +152,7 @@ describe('components', () => {
})
describe('instance child edits record overrides', () => {
- test('renaming and resizing an instance child survives component sync and export', () => {
+ test('renaming an instance child survives component sync; resizing it does nothing, as in Figma', () => {
const api = createAPI()
const component = api.createComponent()
const child = api.createRectangle()
@@ -164,12 +164,13 @@ describe('instance child edits record overrides', () => {
instanceChild.resize(32, 32)
expect(hasInstanceOverride(api.graph, instanceChild.id, 'name')).toBe(true)
- expect(hasInstanceOverride(api.graph, instanceChild.id, 'width')).toBe(true)
+ expect(hasInstanceOverride(api.graph, instanceChild.id, 'width')).toBe(false)
+ expect(instanceChild.width).toBe(24)
child.resize(40, 40)
child.name = 'component child'
api.graph.syncInstances(component.id)
expect(instanceChild.name).toBe('renamed')
- expect(instanceChild.width).toBe(32)
+ expect(instanceChild.width).toBe(40)
})
})
diff --git a/packages/core/tests/tools/modify/update.test.ts b/packages/core/tests/tools/modify/update.test.ts
new file mode 100644
index 000000000..a8c71a970
--- /dev/null
+++ b/packages/core/tests/tools/modify/update.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { updateNode } from '#core/tools/modify/update'
+
+describe('update_node', () => {
+ test('does not report a size it could not set on a layer inside an instance', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const component = figma.createComponent()
+ const rect = figma.createRectangle()
+ rect.resize(30, 30)
+ component.appendChild(rect)
+ const layer = component.createInstance().children[0]
+
+ const result = await updateNode.execute(figma, { id: layer.id, width: 60, name: 'Badge' })
+
+ expect(result).toEqual({ id: layer.id, updated: ['name'] })
+ expect(layer.width).toBe(30)
+ })
+
+ // Figma 126: a resize to the size a layer has changes nothing; a new width fixes only the width.
+ test('reports what a width-only resize changes on an auto layout frame', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const stack = figma.createFrame()
+ stack.layoutMode = 'VERTICAL'
+ stack.primaryAxisSizingMode = 'AUTO'
+ stack.counterAxisSizingMode = 'AUTO'
+ const item = figma.createRectangle()
+ item.resize(40, 20)
+ stack.appendChild(item)
+
+ const same = await updateNode.execute(figma, { id: stack.id, width: stack.width })
+ expect(same).toEqual({ id: stack.id, updated: [] })
+ const wider = await updateNode.execute(figma, { id: stack.id, width: stack.width + 20 })
+
+ expect(wider).toEqual({ id: stack.id, updated: ['size', 'layoutSizingHorizontal'] })
+ expect([stack.layoutSizingHorizontal, stack.layoutSizingVertical]).toEqual(['FIXED', 'HUG'])
+ })
+
+ test('reports what a width-only resize changes on an auto-width text', async () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ const text = figma.createText()
+ text.characters = 'Label'
+
+ const same = await updateNode.execute(figma, { id: text.id, width: text.width })
+ expect(same).toEqual({ id: text.id, updated: [] })
+ const wider = await updateNode.execute(figma, { id: text.id, width: text.width + 20 })
+
+ expect(wider).toEqual({ id: text.id, updated: ['size', 'textAutoResize'] })
+ expect(text.textAutoResize).toBe('HEIGHT')
+ })
+})