AI-native design editor. Open-source Figma alternative.
feat: lock a layer's aspect ratio as Figma does (#1064)
Danila Poyarkovab87326424bb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a41f71ce..4cd4885b3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- `SceneNode` from `@open-pencil/scene-graph` has `targetAspectRatio`, the size whose proportions a locked layer keeps, so code that builds `SceneNode` objects itself must include it.- `useFlatReorderDrag` from `@open-pencil/vue` takes `operations`, which drops each target accepts, and `onCombine`, for dropping onto an item, and `FlatReorderInstruction` is now any list-item `Instruction`, so it can be `'combine'` when a list opts in; code that switches on its `operation` needs that case.- The editor `Tool` type from `@open-pencil/core` and `@open-pencil/vue` includes `'COMMENT'`, and `EDITOR_TOOLS` and `TOOL_SHORTCUTS` list the Comment tool on <kbd>C</kbd>, so a `Record<Tool, …>` needs a `COMMENT` entry and toolbars built on `ToolbarRoot` show it. The canvas places nothing while it is active; the app's comments layer does.- A paint's `gradientTransform` follows Figma's convention everywhere: it maps the layer's unit square onto gradient space, where a linear gradient runs from (0, 0.5) to (1, 0.5). Gradients made in OpenPencil before this release, which used the inverse, draw differently; code that builds gradients by hand should use `linearGradientTransform` and `ellipticalGradientTransform` from the new `@open-pencil/scene-graph/gradient`, which also has Figma's default transform and stops. `isGradientFill` and `GradientFillType` moved there from `@open-pencil/core/geometry`, and `linearGradientEndpoints` is removed from the canvas module.@@ -48,6 +49,7 @@### Added+- Lock a layer's aspect ratio with the button beside its width and height, as in Figma: typing either side changes the other, handles keep the ratio (<kbd>Ctrl</kbd> frees it for one drag, which then keeps the new size), a Fill layer in auto layout takes its other side from the ratio, and a constraint keeps it when exactly one axis follows the frame. The lock reads from and writes to `.fig` files and the clipboard, and the plugin API has `lockAspectRatio()`, `unlockAspectRatio()`, `targetAspectRatio`, and `constrainProportions`.- See the selection as a Vue or React component in the Code tab, as the Storybook export generates them: a component set with its variants as props and its behaviour's Reka UI or Radix parts, any other layer as a plain component of the elements it draws, with shaders playing through `shaders/vue` or `shaders/react`. HTML there now shows the selection as markup, images as file paths, and still rewrites it live when edited; with nothing selected it keeps the starter for writing new layers. A CSS/Tailwind switch styles HTML and components with a readable stylesheet or with Tailwind utilities, their states as variants such as `data-[state=checked]:`, and edited HTML is built with Tailwind's utilities; React with Tailwind replaces the Tailwind JSX format. In HTML, Vue, and React, as in Design JSX, the element around the cursor marks its layer on the canvas and design issues are underlined on the layer's class. `export -f storybook --css tailwind` styles the exported Vue and React components the same way.- Talk with the people in a shared room in a voice call, as in Figma: the headphones beside the avatars start or join it, a ring marks who is in the call and lights up while they speak, and the call's popover chooses the microphone and, where the browser allows, the speakers. Audio goes peer to peer, and only to the people in the call.- Take a layer out of its auto layout with **Ignore auto layout** at the top of the Position section, as in Figma: the layer stays where it is, its siblings close the gap in the same undo step, and it keeps its sizing, so a Fill layer fills again when it returns.@@ -167,6 +169,7 @@### Fixed+- <kbd>⇧</kbd>-dragging a corner handle follows the side the pointer stretched most relative to the layer's size, as Figma does, instead of the side it moved more pixels along.- The AI provider list labels its "Your agents" and "Providers" groups in the app language instead of always in English.- Tooltips no longer appear when a popover such as the colour picker focuses its first control on open; they still show for keyboard focus. Moving the pointer along a row of buttons switches tooltips at once instead of blinking out, and tooltips centre on their control instead of sitting a few pixels off.- A layer that ignores auto layout follows its constraints when its auto layout frame resizes, as in Figma: a badge pinned to the right of a Hug button stays on its corner as the label grows or shrinks, a centred one stays centred, and one set to Left & right or Scale stretches with the frame, also inside a Fill frame and for the layers in a stretched overlay. Layers in a reopened `.fig` file keep the places the file saved until an edit resizes their frame.diff --git a/packages/core/src/figma-api/accessors/basic.ts b/packages/core/src/figma-api/accessors/basic.tsindex 1429488b5..85b6125b7 100644--- a/packages/core/src/figma-api/accessors/basic.ts+++ b/packages/core/src/figma-api/accessors/basic.ts@@ -4,6 +4,7 @@ import {FITTED_CONTAINER_TYPES,TRANSFORM_FIELDS as NODE_TRANSFORM_FIELDS,findInstanceAncestor,+ recapturedAspectRatio,recordInstanceOverride,rescaleNodeTree,slotPropertyId,@@ -216,14 +217,18 @@ export function installBasicNodeProxyAccessors(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)scene.updateNode(node.id, {width,height,+ ...recaptured,...(fixesText ? { textAutoResize: 'NONE' as const } : {})})recordInstanceOverride(scene, node.id, ['width','height',+ ...Object.keys(recaptured),...(fixesText ? ['textAutoResize'] : [])])setTransform(this, internals, () => before)diff --git a/packages/core/src/figma-api/accessors/layout.ts b/packages/core/src/figma-api/accessors/layout.tsindex ad5f73779..40048e2a7 100644--- a/packages/core/src/figma-api/accessors/layout.ts+++ b/packages/core/src/figma-api/accessors/layout.ts@@ -1,14 +1,18 @@import {+ aspectRatioLockEditable,layoutSizing,layoutSizingError,layoutSizingUpdates,+ lockedAspectRatioTarget,type LayoutMode,type LayoutSizing,type LayoutSizingAxis,- type SceneNode+ type SceneNode,+ type Vector} from '@open-pencil/scene-graph'import {+ assertProxyEditable,graph,raw,updateNode,@@ -74,7 +78,40 @@ export function installLayoutNodeProxyAccessors(minWidth: simpleAccessor(internals, 'minWidth'),maxWidth: simpleAccessor(internals, 'maxWidth'),minHeight: simpleAccessor(internals, 'minHeight'),- maxHeight: simpleAccessor(internals, 'maxHeight')+ maxHeight: simpleAccessor(internals, 'maxHeight'),+ targetAspectRatio: {+ get(this: ProxyThis): Vector | null {+ const target = raw(this, internals).targetAspectRatio+ return target ? { ...target } : null+ }+ },+ constrainProportions: {+ get(this: ProxyThis): boolean {+ return raw(this, internals).targetAspectRatio !== null+ },+ set(this: ProxyThis, value: boolean) {+ setAspectRatioLock(this, internals, value)+ }+ }+ })++ Object.assign(prototype, {+ lockAspectRatio(this: ProxyThis): void {+ setAspectRatioLock(this, internals, true)+ },+ unlockAspectRatio(this: ProxyThis): void {+ setAspectRatioLock(this, internals, false)+ }+ })+}++/** Figma ignores the call, without an error, on a layer inside an instance. */+function setAspectRatioLock(target: ProxyThis, internals: NodeProxyInternals, locked: boolean) {+ assertProxyEditable(target, internals)+ const node = raw(target, internals)+ if (!aspectRatioLockEditable(graph(target, internals), node)) return+ updateNode(target, internals, {+ targetAspectRatio: locked ? lockedAspectRatioTarget(node.width, node.height) : null})}diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.tsindex 300994ef2..f315239a3 100644--- a/packages/core/src/figma-api/proxy.ts+++ b/packages/core/src/figma-api/proxy.ts@@ -15,7 +15,7 @@ import {setNodeStrokeOkHCL} from '@open-pencil/scene-graph/color'import type { OkHCLColor, OkHCLPayload } from '@open-pencil/scene-graph/color'-import type { Rect } from '@open-pencil/scene-graph/primitives'+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import { assertNodeEditable } from '#core/editor/capabilities'import type { FigmaEffect } from '#core/figma-api/effects'@@ -130,6 +130,11 @@ export class FigmaNodeProxy {declare maxWidth: number | nulldeclare minHeight: number | nulldeclare maxHeight: number | null+ declare readonly targetAspectRatio: Vector | null+ /** @deprecated Figma's alias for whether `targetAspectRatio` is set. */+ declare constrainProportions: boolean+ declare lockAspectRatio: () => void+ declare unlockAspectRatio: () => voiddeclare vectorPaths: readonly FigmaVectorPath[]declare vectorNetwork: FigmaVectorNetworkdeclare setVectorNetworkAsync: (vectorNetwork: FigmaVectorNetwork) => Promise<void>diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.tsindex 2d96f632b..0d3d64c3e 100644--- a/packages/core/src/layout.ts+++ b/packages/core/src/layout.ts@@ -44,6 +44,7 @@ import {import { estimateTextSize, getTextMeasurer } from './layout/text-measurement'import {applyMinMaxConstraints,+ applyLockedAspectRatio,configureAbsoluteChild,configureNonTextLeaf,createYogaNode,@@ -273,6 +274,7 @@ function configureChildAsGrid(const selfAlign = mapAlignSelf(child.layoutAlignSelf)if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)+ applyLockedAspectRatio(yogaChild, child, parent)applyMinMaxConstraints(yogaChild, child)const grandchildren = graph.getChildren(child.id)@@ -368,6 +370,7 @@ function configureChildAsAutoLayout(const selfAlign = mapAlignSelf(child.layoutAlignSelf)if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)+ applyLockedAspectRatio(yogaChild, child, parent)if (usesDetachedDerivedLayout(graph, child)) {// The imported size is what the child's own hug produced, whether or not it also fills.@@ -520,6 +523,7 @@ function configureChildAsLeaf(const selfAlign = mapAlignSelf(child.layoutAlignSelf)if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)+ applyLockedAspectRatio(yogaChild, child, parent)applyMinMaxConstraints(yogaChild, child)}diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.tsindex fb682df14..15bb639e3 100644--- a/packages/core/src/layout/apply.ts+++ b/packages/core/src/layout/apply.ts@@ -1,6 +1,6 @@import type { Node as YogaNode } from 'yoga-layout'-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { enforcedAspectRatio, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { layoutConstrainedChildRect } from '@open-pencil/scene-graph/resize'import { keepsSavedLayout, usesDetachedDerivedLayout } from './derived'@@ -92,7 +92,8 @@ function constrainChildren(before,frame,child.horizontalConstraint,- child.verticalConstraint+ child.verticalConstraint,+ enforcedAspectRatio(child)),computeLayout,undefined,diff --git a/packages/core/src/layout/yoga-helpers.ts b/packages/core/src/layout/yoga-helpers.tsindex 019b18ceb..788e5a7b6 100644--- a/packages/core/src/layout/yoga-helpers.ts+++ b/packages/core/src/layout/yoga-helpers.ts@@ -7,7 +7,13 @@ import Yoga, {type Node as YogaNode} from 'yoga-layout'-import type { GridTrack, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import {+ enforcedAspectRatio,+ layoutSizingInParent,+ type GridTrack,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'const yogaConfig = Yoga.Config.create()yogaConfig.setPointScaleFactor(0)@@ -50,6 +56,33 @@ export function configureNonTextLeaf(}}+/**+ * A locked aspect ratio sizes the axis Fill does not drive, as Figma lays it out: Fill along the+ * parent's primary axis drives when set, else Fill across it, and the other axis follows even past+ * the parent's edge. An axis that hugs keeps its own size.+ */+export function applyLockedAspectRatio(+ yogaNode: YogaNode,+ node: SceneNode,+ parent: SceneNode+): void {+ const ratio = enforcedAspectRatio(node)+ if (ratio === null) return+ const width = layoutSizingInParent(parent, node, 'HORIZONTAL')+ const height = layoutSizingInParent(parent, node, 'VERTICAL')+ const primaryIsWidth = parent.layoutMode !== 'VERTICAL'+ const primary = primaryIsWidth ? width : height+ const cross = primaryIsWidth ? height : width+ let drivesWidth: boolean+ if (primary === 'FILL') drivesWidth = primaryIsWidth+ else if (cross === 'FILL') drivesWidth = !primaryIsWidth+ else return+ if ((drivesWidth ? height : width) === 'HUG') return+ yogaNode.setAspectRatio(ratio)+ if (drivesWidth) yogaNode.setHeight('auto')+ else yogaNode.setWidth('auto')+}+export function applyMinMaxConstraints(yogaNode: YogaNode, node: SceneNode): void {if (node.minWidth != null) yogaNode.setMinWidth(node.minWidth)if (node.maxWidth != null) yogaNode.setMaxWidth(node.maxWidth)diff --git a/packages/core/tests/figma-api/aspect-ratio.test.ts b/packages/core/tests/figma-api/aspect-ratio.test.tsnew file mode 100644index 000000000..54928e83f--- /dev/null+++ b/packages/core/tests/figma-api/aspect-ratio.test.ts@@ -0,0 +1,99 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++function createAPI() {+ return new FigmaAPI(new SceneGraph())+}++// Expected values were observed by running the same scripts in live Figma on 2026-10-10.++describe('aspect ratio lock', () => {+ test('locking stores the current size and unlocking clears it', () => {+ const api = createAPI()+ const rect = api.createRectangle()+ rect.resize(200, 100)+ expect(rect.targetAspectRatio).toBeNull()+ expect(rect.constrainProportions).toBe(false)++ rect.lockAspectRatio()+ expect(rect.targetAspectRatio).toEqual({ x: 200, y: 100 })+ expect(rect.constrainProportions).toBe(true)++ rect.unlockAspectRatio()+ expect(rect.targetAspectRatio).toBeNull()+ expect(rect.constrainProportions).toBe(false)+ })++ test('constrainProportions locks and unlocks', () => {+ const api = createAPI()+ const rect = api.createRectangle()+ rect.resize(200, 100)+ rect.constrainProportions = true+ expect(rect.targetAspectRatio).toEqual({ x: 200, y: 100 })+ rect.constrainProportions = false+ expect(rect.targetAspectRatio).toBeNull()+ })++ test('resize ignores the lock and stores the new size', () => {+ const api = createAPI()+ const rect = api.createRectangle()+ rect.resize(200, 100)+ rect.lockAspectRatio()+ rect.resize(400, 100)+ expect([rect.width, rect.height]).toEqual([400, 100])+ expect(rect.targetAspectRatio).toEqual({ x: 400, y: 100 })+ rect.resizeWithoutConstraints(300, 300)+ expect(rect.targetAspectRatio).toEqual({ x: 300, y: 300 })+ })++ test('rescale keeps the stored size', () => {+ const api = createAPI()+ const rect = api.createRectangle()+ rect.resize(200, 100)+ rect.lockAspectRatio()+ rect.rescale(2)+ expect([rect.width, rect.height]).toEqual([400, 200])+ expect(rect.targetAspectRatio).toEqual({ x: 200, y: 100 })+ })++ test('a fill child keeps its ratio as its frame grows', () => {+ const api = createAPI()+ const frame = api.createFrame()+ frame.layoutMode = 'HORIZONTAL'+ frame.resize(300, 300)+ frame.primaryAxisSizingMode = 'FIXED'+ frame.counterAxisSizingMode = 'FIXED'+ const child = api.createRectangle()+ child.resize(100, 50)+ frame.appendChild(child)+ child.lockAspectRatio()+ child.layoutSizingHorizontal = 'FILL'+ expect([child.width, child.height]).toEqual([300, 150])+ frame.resize(500, 300)+ expect([child.width, child.height]).toEqual([500, 250])+ })++ test('instances take the lock from their component and can unlock it', () => {+ const api = createAPI()+ const component = api.createComponent()+ component.resize(100, 50)+ component.lockAspectRatio()+ const instance = component.createInstance()+ expect(instance.targetAspectRatio).toEqual({ x: 100, y: 50 })+ instance.unlockAspectRatio()+ expect(instance.targetAspectRatio).toBeNull()+ })++ test('a layer inside an instance keeps its component lock', () => {+ const api = createAPI()+ const component = api.createComponent()+ component.resize(100, 100)+ component.appendChild(api.createRectangle())+ const instance = component.createInstance()+ const inner = instance.children[0]+ inner.lockAspectRatio()+ expect(inner.targetAspectRatio).toBeNull()+ })+})diff --git a/packages/core/tests/layout/auto-layout/aspect-ratio.test.ts b/packages/core/tests/layout/auto-layout/aspect-ratio.test.tsnew file mode 100644index 000000000..0bc43b995--- /dev/null+++ b/packages/core/tests/layout/auto-layout/aspect-ratio.test.ts@@ -0,0 +1,152 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '#core/figma-api'+import { computeAllLayouts } from '@open-pencil/core/layout'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++// Sizes recorded from Figma with locked layers in fixed auto layout frames, no padding or gap.+function row(graph: SceneGraph, overrides: Partial<SceneNode> = {}) {+ const page = graph.getPages()[0].id+ return graph.createNode('FRAME', page, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ width: 300,+ height: 100,+ ...overrides+ })+}++function locked(graph: SceneGraph, parentId: string, overrides: Partial<SceneNode> = {}) {+ return graph.createNode('RECTANGLE', parentId, {+ width: 100,+ height: 50,+ targetAspectRatio: { x: 100, y: 50 },+ ...overrides+ })+}++function size(graph: SceneGraph, id: string) {+ const node = graph.getNode(id)+ return [node?.width, node?.height]+}++describe('locked aspect ratio in auto layout', () => {+ test('fill along the row sizes the height, past the frame', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { width: 500 })+ const child = locked(graph, frame.id, { layoutGrow: 1 })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([500, 250])+ })++ test('fill shares the row with other fills and keeps its ratio', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { width: 400 })+ const other = graph.createNode('RECTANGLE', frame.id, { width: 50, height: 50, layoutGrow: 1 })+ const child = locked(graph, frame.id, { layoutGrow: 1 })+ computeAllLayouts(graph)+ expect(size(graph, other.id)).toEqual([200, 50])+ expect(size(graph, child.id)).toEqual([200, 100])+ })++ test('fill along the column sizes the width, also when it fills across', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { layoutMode: 'VERTICAL', width: 300, height: 400 })+ const child = locked(graph, frame.id, { layoutGrow: 1, layoutAlignSelf: 'STRETCH' })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([800, 400])+ })++ test('fill across the column sizes the height', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { layoutMode: 'VERTICAL', width: 300, height: 400 })+ const child = locked(graph, frame.id, { layoutAlignSelf: 'STRETCH' })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([300, 150])+ })++ test('a frame that hugs across takes the derived size', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { width: 400, height: 10, counterAxisSizing: 'HUG' })+ const child = locked(graph, frame.id, { layoutGrow: 1 })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([400, 200])+ expect(size(graph, frame.id)).toEqual([400, 200])+ })++ test('a maximum width caps the fill and the height follows', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { width: 400 })+ const child = locked(graph, frame.id, { layoutGrow: 1, maxWidth: 200 })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([200, 100])+ })++ test('a locked auto layout frame that fills keeps its ratio', () => {+ const graph = new SceneGraph()+ const frame = row(graph, { width: 500 })+ const child = graph.createNode('FRAME', frame.id, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ width: 100,+ height: 50,+ layoutGrow: 1,+ targetAspectRatio: { x: 100, y: 50 }+ })+ computeAllLayouts(graph)+ expect(size(graph, child.id)).toEqual([500, 250])+ })++ test('a fixed size ignores the lock', () => {+ const graph = new SceneGraph()+ const frame = row(graph)+ const fixed = locked(graph, frame.id, { width: 80 })+ computeAllLayouts(graph)+ expect(size(graph, fixed.id)).toEqual([80, 50])+ })+})++// Live Figma, 2026-10-10: a locked 100×50 layer at 50,50 that ignores auto layout, in a Hug row+// that grows from 200 to 300 wide.+describe('a locked layer that ignores auto layout as its Hug frame grows', () => {+ const CASES = {+ 'STRETCH/MIN': [50, 50, 200, 100],+ 'STRETCH/CENTER': [50, 25, 200, 100],+ 'SCALE/MAX': [75, 25, 150, 75],+ 'STRETCH/STRETCH': [50, 50, 200, 50]+ } as const++ for (const [name, expected] of Object.entries(CASES)) {+ test(name, () => {+ const figma = new FigmaAPI(new SceneGraph())+ const frame = figma.createFrame()+ frame.layoutMode = 'HORIZONTAL'+ frame.resize(10, 200)+ frame.counterAxisSizingMode = 'FIXED'+ frame.primaryAxisSizingMode = 'AUTO'+ for (const side of ['paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom'] as const)+ frame[side] = 0+ const spacer = figma.createRectangle()+ spacer.resize(200, 10)+ frame.appendChild(spacer)+ // Figma has laid the frame out by now; ours lays out when its size is read.+ expect(frame.width).toBe(200)+ const layer = figma.createRectangle()+ frame.appendChild(layer)+ layer.layoutPositioning = 'ABSOLUTE'+ layer.x = 50+ layer.y = 50+ layer.resize(100, 50)+ const [horizontal, vertical] = name.split('/') as ['STRETCH' | 'SCALE', ConstraintName]+ layer.constraints = { horizontal, vertical }+ layer.lockAspectRatio()+ spacer.resize(300, 10)+ expect(frame.width).toBe(300)+ expect([layer.x, layer.y, layer.width, layer.height]).toEqual([...expected])+ })+ }+})++type ConstraintName = 'MIN' | 'CENTER' | 'MAX' | 'STRETCH'diff --git a/packages/docs/programmable/sdk/api/composables/use-layout.md b/packages/docs/programmable/sdk/api/composables/use-layout.mdindex fc7b5c638..d8da51229 100644--- a/packages/docs/programmable/sdk/api/composables/use-layout.md+++ b/packages/docs/programmable/sdk/api/composables/use-layout.md@@ -54,6 +54,16 @@ For one-step commit and Escape rollback across a sizing-mode change, variable denumeric value, compose the NumberField with `BindableValue` using a provider that implementsinteraction batches. Merely focusing the field does not switch its sizing mode.+## Aspect ratio lock++```ts+const { aspectRatioLocked, aspectRatioLockable, toggleAspectRatioLock } = useLayout()+```++`toggleAspectRatioLock()` locks the selected layer to its current proportions or unlocks it.+While it is locked, `updateAxisSize()` changes both sides. `aspectRatioLockable` is false for a+layer inside an instance, which keeps its component's lock.+## Size limits```tsdiff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.tsindex b1c3954ce..734772503 100644--- a/packages/fig/src/node-change/convert.ts+++ b/packages/fig/src/node-change/convert.ts@@ -451,6 +451,12 @@ function maximumSizeDimension(size: NodeChange['maxSize'], axis: 'x' | 'y'): numreturn typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null}+function targetAspectRatio(nc: NodeChange): SceneNode['targetAspectRatio'] {+ const value = nc.targetAspectRatio?.value+ if (!value || !Number.isFinite(value.x) || !Number.isFinite(value.y)) return null+ return { x: value.x, y: value.y }+}+function convertLayoutProps(nc: NodeChange): Pick<@@ -677,6 +683,7 @@ export function nodeChangeToProps(maxWidth: maximumSizeDimension(nc.maxSize, 'x'),minHeight: minimumSizeDimension(nc.minSize, 'y'),maxHeight: maximumSizeDimension(nc.maxSize, 'y'),+ targetAspectRatio: targetAspectRatio(nc),isMask: nc.mask ?? false,maskType: (nc.maskType ?? 'ALPHA') as 'ALPHA' | 'VECTOR' | 'LUMINANCE',maskIsOutline: nc.maskIsOutline ?? false,@@ -1119,7 +1126,6 @@ export const FIGMA_RAW_NODE_FIELD_KEYS = ['borderLeftWeight','minSize','maxSize',- 'targetAspectRatio','gridRows','gridColumns','gridRowAnchor',diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.tsindex cd500b9f9..a56b88dca 100644--- a/packages/fig/src/node-change/serialize.ts+++ b/packages/fig/src/node-change/serialize.ts@@ -207,6 +207,7 @@ function preserveTrailingPadding(}function serializeSizeConstraints(node: SceneNode, nc: KiwiNodeChange): void {+ if (node.targetAspectRatio) nc.targetAspectRatio = { value: { ...node.targetAspectRatio } }if (node.minWidth != null || node.minHeight != null) {nc.minSize = { value: { x: node.minWidth ?? 0, y: node.minHeight ?? 0 } }}diff --git a/packages/fig/tests/node-change/export/aspect-ratio.test.ts b/packages/fig/tests/node-change/export/aspect-ratio.test.tsnew file mode 100644index 000000000..351e160e3--- /dev/null+++ b/packages/fig/tests/node-change/export/aspect-ratio.test.ts@@ -0,0 +1,40 @@+import { describe, expect, test } from 'bun:test'++import { nodeChangeToProps, sceneNodeToKiwi } from '#fig/node-change/index'++import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'++function serialize(overrides: Partial<SceneNode>) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const node = graph.createNode('RECTANGLE', page.id, overrides)+ return sceneNodeToKiwi(node, { sessionID: 1, localID: 1 }, 0, { value: 2 }, graph, [])[0]+}++// Copied from live Figma, 2026-10-10: a locked layer carries only `targetAspectRatio`.+describe('Figma aspect ratio lock', () => {+ test('imports the stored size of a locked layer', () => {+ const props = nodeChangeToProps(+ {+ type: 'RECTANGLE',+ size: { x: 300, y: 110 },+ targetAspectRatio: { value: { x: 300, y: 110 } }+ } as NodeChange,+ []+ )+ expect(props.targetAspectRatio).toEqual({ x: 300, y: 110 })+ expect(nodeChangeToProps({ type: 'RECTANGLE' } as NodeChange, []).targetAspectRatio).toBeNull()+ })++ test('exports the stored size and leaves free layers without it', () => {+ expect(+ serialize({+ width: 200,+ height: 100,+ targetAspectRatio: { x: 200, y: 100 }+ })+ ).toMatchObject({ targetAspectRatio: { value: { x: 200, y: 100 } } })+ expect(serialize({ width: 200, height: 100 }).targetAspectRatio).toBeUndefined()+ })+})diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.tsindex b20deca85..59cc0121a 100644--- a/packages/kiwi/src/fig/codec.ts+++ b/packages/kiwi/src/fig/codec.ts@@ -270,6 +270,7 @@ export interface NodeChange {stackCounterSpacing?: numberminSize?: { value?: Vector }maxSize?: { value?: Vector }+ targetAspectRatio?: { value?: Vector }// FrameclipsContent?: booleanframeMaskDisabled?: booleandiff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.tsindex b849d863f..add036930 100644--- a/packages/scene-graph/src/copy.ts+++ b/packages/scene-graph/src/copy.ts@@ -295,6 +295,7 @@ export function cloneNodeProps(: null,textPathData: src.textPathData ? structuredClone(src.textPathData) : null,textPathBox: src.textPathBox ? { ...src.textPathBox } : null,- gridPosition: src.gridPosition ? { ...src.gridPosition } : null+ gridPosition: src.gridPosition ? { ...src.gridPosition } : null,+ targetAspectRatio: src.targetAspectRatio ? { ...src.targetAspectRatio } : null}}diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 811f8ca9f..37010577c 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -534,7 +534,8 @@ export class SceneGraph {'minWidth','maxWidth','minHeight',- 'maxHeight'+ 'maxHeight',+ 'targetAspectRatio'])runPreviewUpdates(fn: () => void, beforeUpdate?: NodePreviewObserver): void {diff --git a/packages/scene-graph/src/instances/fields.ts b/packages/scene-graph/src/instances/fields.tsindex cf392b061..0e05a7c10 100644--- a/packages/scene-graph/src/instances/fields.ts+++ b/packages/scene-graph/src/instances/fields.ts@@ -16,6 +16,7 @@ export const INSTANCE_SYNC_PROPS: (keyof SceneNode)[] = ['maxWidth','minHeight','maxHeight',+ 'targetAspectRatio','fills','strokes','effects',diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.tsindex 624579f8e..ee7e9a3a2 100644--- a/packages/scene-graph/src/instances/sync.ts+++ b/packages/scene-graph/src/instances/sync.ts@@ -45,6 +45,8 @@ export function copyProp(} else if (key === 'gridPosition') {// Shallow copy the grid position object — all fields are primitivessetSceneProp(target, key, source.gridPosition ? { ...source.gridPosition } : null)+ } else if (key === 'targetAspectRatio') {+ setSceneProp(target, key, source.targetAspectRatio ? { ...source.targetAspectRatio } : null)} else {const value = source[key]setSceneProp(target, key, Array.isArray(value) ? structuredClone(value) : value)diff --git a/packages/scene-graph/src/layout/aspect-ratio.ts b/packages/scene-graph/src/layout/aspect-ratio.tsnew file mode 100644index 000000000..9c8de1c16--- /dev/null+++ b/packages/scene-graph/src/layout/aspect-ratio.ts@@ -0,0 +1,52 @@+import type { SceneGraph } from '../index'+import { findInstanceAncestor } from '../instances'+import type { Vector } from '../primitives'+import type { SceneNode } from '../types'++type AspectRatioNode = Pick<SceneNode, 'type' | 'targetAspectRatio' | 'textAutoResize'>++/** The value Figma's `lockAspectRatio()` stores: the size the layer has when it is locked. */+export function lockedAspectRatioTarget(width: number, height: number): Vector {+ return { x: width, y: height }+}++/** Whether the lock can change: a layer inside an instance keeps its component's, as in Figma. */+export function aspectRatioLockEditable(graph: SceneGraph, node: SceneNode): boolean {+ return !node.parentId || !findInstanceAncestor(graph, node.parentId)+}++/**+ * The width-to-height ratio a resize keeps, or `null` when the layer's proportions are free.+ * Text that sizes itself to its content keeps the lock without following it, as in Figma.+ */+export function enforcedAspectRatio(node: AspectRatioNode): number | null {+ const target = node.targetAspectRatio+ if (!target || !(target.x > 0) || !(target.y > 0)) return null+ if (node.type === 'TEXT' && node.textAutoResize !== 'NONE') return null+ return target.x / target.y+}++/**+ * A resize that ignores a locked ratio, such as Figma's plugin `resize()` or a Control-drag,+ * keeps the lock and stores the new size as the ratio to keep.+ */+export function recapturedAspectRatio(+ node: Pick<SceneNode, 'targetAspectRatio'>,+ width: number,+ height: number+): Partial<Pick<SceneNode, 'targetAspectRatio'>> {+ if (!node.targetAspectRatio) return {}+ if (node.targetAspectRatio.x === width && node.targetAspectRatio.y === height) return {}+ return { targetAspectRatio: lockedAspectRatioTarget(width, height) }+}++/** The size that keeps `ratio` when one axis is set to `value`. */+export function sizeKeepingAspectRatio(+ ratio: number,+ axis: 'width' | 'height',+ value: number+): { width: number; height: number } {+ return axis === 'width'+ ? { width: value, height: value / ratio }+ : { width: value * ratio, height: value }+}diff --git a/packages/scene-graph/src/layout/index.ts b/packages/scene-graph/src/layout/index.tsindex 8c3f79eaa..aa00a421c 100644--- a/packages/scene-graph/src/layout/index.ts+++ b/packages/scene-graph/src/layout/index.ts@@ -1,3 +1,4 @@+export * from './aspect-ratio'export * from './guides'export * from './keywords'export * from './sizing'diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.tsindex 18990d4ea..3141c8ce9 100644--- a/packages/scene-graph/src/node-defaults.ts+++ b/packages/scene-graph/src/node-defaults.ts@@ -155,6 +155,7 @@ export function createDefaultNode(maxWidth: null,minHeight: null,maxHeight: null,+ targetAspectRatio: null,isMask: false,maskType: 'ALPHA',maskIsOutline: false,diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.tsindex f3792711a..92fb7ad7c 100644--- a/packages/scene-graph/src/resize.ts+++ b/packages/scene-graph/src/resize.ts@@ -5,6 +5,7 @@ import {copyStrokes,scaleGeometryPaths} from './copy'+import { enforcedAspectRatio } from './layout/aspect-ratio'import type { Rect } from './primitives'import type { ConstraintType, DerivedTextGlyph, SceneNode, Stroke, VectorNetwork } from './types'import { cloneVectorNetwork } from './vector-network'@@ -61,21 +62,51 @@ function constrainedAxis(return { position, size }}+type AxisPlacement = { position: number; size: number }++const FLEXIBLE_CONSTRAINTS: ReadonlySet<ConstraintType> = new Set(['STRETCH', 'SCALE'])++/** The axis at `size`, keeping the edge or centre its constraint pins where it was placed. */+function resizedInPlace(+ placed: AxisPlacement,+ size: number,+ constraint: ConstraintType+): AxisPlacement {+ if (constraint === 'MAX') return { position: placed.position + placed.size - size, size }+ if (constraint === 'CENTER') return { position: placed.position + (placed.size - size) / 2, size }+ return { position: placed.position, size }+}++/**+ * A locked aspect ratio holds when exactly one axis follows the parent, as in Figma: that axis+ * sizes the other. With both axes following the parent, or neither, the ratio gives way.+ */+function keepLockedRatio(+ x: AxisPlacement,+ y: AxisPlacement,+ horizontal: ConstraintType,+ vertical: ConstraintType,+ aspectRatio: number | null+): { x: AxisPlacement; y: AxisPlacement } {+ const flexibleX = FLEXIBLE_CONSTRAINTS.has(horizontal)+ if (aspectRatio === null || flexibleX === FLEXIBLE_CONSTRAINTS.has(vertical)) return { x, y }+ return flexibleX+ ? { x, y: resizedInPlace(y, x.size / aspectRatio, vertical) }+ : { x: resizedInPlace(x, y.size * aspectRatio, horizontal), y }+}++/** A child's box after its parent resizes, keeping a locked aspect ratio as Figma does. */export function constrainedChildRect(child: Rect,parentBefore: Pick<Rect, 'width' | 'height'>,parentAfter: Pick<Rect, 'width' | 'height'>,horizontal: ConstraintType,- vertical: ConstraintType+ vertical: ConstraintType,+ aspectRatio: number | null = null): Rect {- const x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)- const y = constrainedAxis(- child.y,- child.height,- parentBefore.height,- parentAfter.height,- vertical- )+ let x = constrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal)+ let y = constrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical)+ ;({ x, y } = keepLockedRatio(x, y, horizontal, vertical, aspectRatio))return {x: Math.round(x.position),y: Math.round(y.position),@@ -116,23 +147,22 @@ export function layoutConstrainedChildRect(parentBefore: Pick<Rect, 'width' | 'height'>,parentAfter: Pick<Rect, 'width' | 'height'>,horizontal: ConstraintType,- vertical: ConstraintType+ vertical: ConstraintType,+ aspectRatio: number | null = null): Rect {- const x = layoutConstrainedAxis(- child.x,- child.width,- parentBefore.width,- parentAfter.width,- horizontal+ const placed = keepLockedRatio(+ layoutConstrainedAxis(child.x, child.width, parentBefore.width, parentAfter.width, horizontal),+ layoutConstrainedAxis(child.y, child.height, parentBefore.height, parentAfter.height, vertical),+ horizontal,+ vertical,+ aspectRatio)- const y = layoutConstrainedAxis(- child.y,- child.height,- parentBefore.height,- parentAfter.height,- vertical- )- return { x: x.position, y: y.position, width: x.size, height: y.size }+ return {+ x: placed.x.position,+ y: placed.y.position,+ width: placed.x.size,+ height: placed.y.size+ }}export function scaledChildRect(@@ -341,7 +371,8 @@ export function computeConstrainedResizeChanges(parentBefore,parentAfter,child.horizontalConstraint,- child.verticalConstraint+ child.verticalConstraint,+ enforcedAspectRatio(child))const childChanges: Partial<SceneNode> = {...rect,diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.tsindex e331a0361..bb96e193d 100644--- a/packages/scene-graph/src/types.ts+++ b/packages/scene-graph/src/types.ts@@ -584,6 +584,11 @@ export interface SceneNode {maxWidth: number | nullminHeight: number | nullmaxHeight: number | null+ /**+ * The size whose proportions the layer keeps, as Figma stores it: the width and height it had+ * when the ratio was locked, not a reduced ratio. Null leaves the proportions free.+ */+ targetAspectRatio: Vector | nullisMask: booleanmaskType: MaskTypediff --git a/packages/scene-graph/tests/basic/layout-affecting-keys.test.ts b/packages/scene-graph/tests/basic/layout-affecting-keys.test.tsindex 35b501d38..a4cd28887 100644--- a/packages/scene-graph/tests/basic/layout-affecting-keys.test.ts+++ b/packages/scene-graph/tests/basic/layout-affecting-keys.test.ts@@ -47,7 +47,8 @@ describe('LAYOUT_AFFECTING_KEYS membership', () => {'minWidth','maxWidth','minHeight',- 'maxHeight'+ 'maxHeight',+ 'targetAspectRatio']) {expect(keys.has(k)).toBe(true)}@@ -69,8 +70,8 @@ describe('LAYOUT_AFFECTING_KEYS membership', () => {// layoutPositioning,layoutGrow,layoutAlignSelf,strokesIncludedInLayout = 4// horizontalConstraint,verticalConstraint = 2// gridTemplateColumns,gridTemplateRows,gridColumnGap,gridRowGap,gridPosition = 5- // minWidth,maxWidth,minHeight,maxHeight = 4- // Total: 36- expect(SceneGraph.LAYOUT_AFFECTING_KEYS.size).toBe(36)+ // minWidth,maxWidth,minHeight,maxHeight,targetAspectRatio = 5+ // Total: 37+ expect(SceneGraph.LAYOUT_AFFECTING_KEYS.size).toBe(37)})})diff --git a/packages/scene-graph/tests/layout/aspect-ratio.test.ts b/packages/scene-graph/tests/layout/aspect-ratio.test.tsnew file mode 100644index 000000000..7e8c08a95--- /dev/null+++ b/packages/scene-graph/tests/layout/aspect-ratio.test.ts@@ -0,0 +1,41 @@+import { describe, expect, test } from 'bun:test'++import {+ enforcedAspectRatio,+ recapturedAspectRatio,+ SceneGraph,+ sizeKeepingAspectRatio+} from '@open-pencil/scene-graph'++describe('aspect ratio lock', () => {+ test('a locked layer keeps the ratio of its stored size', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const rect = graph.createNode('RECTANGLE', page, { targetAspectRatio: { x: 32, y: 16 } })+ expect(enforcedAspectRatio(rect)).toBe(2)+ expect(sizeKeepingAspectRatio(2, 'width', 300)).toEqual({ width: 300, height: 150 })+ expect(sizeKeepingAspectRatio(2, 'height', 50)).toEqual({ width: 100, height: 50 })+ })++ test('free, degenerate, and auto-resizing text layers keep no ratio', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const free = graph.createNode('RECTANGLE', page)+ const flat = graph.createNode('LINE', page, { targetAspectRatio: { x: 100, y: 0 } })+ const text = graph.createNode('TEXT', page, {+ textAutoResize: 'WIDTH_AND_HEIGHT',+ targetAspectRatio: { x: 29, y: 15 }+ })+ expect(enforcedAspectRatio(free)).toBeNull()+ expect(enforcedAspectRatio(flat)).toBeNull()+ expect(enforcedAspectRatio(text)).toBeNull()+ expect(enforcedAspectRatio({ ...text, textAutoResize: 'NONE' })).toBeCloseTo(29 / 15)+ })++ test('a resize that ignores the lock stores the new size only on locked layers', () => {+ expect(recapturedAspectRatio({ targetAspectRatio: { x: 2, y: 1 } }, 300, 110)).toEqual({+ targetAspectRatio: { x: 300, y: 110 }+ })+ expect(recapturedAspectRatio({ targetAspectRatio: null }, 300, 110)).toEqual({})+ })+})diff --git a/packages/scene-graph/tests/resize.test.ts b/packages/scene-graph/tests/resize.test.tsnew file mode 100644index 000000000..e0f165515--- /dev/null+++ b/packages/scene-graph/tests/resize.test.ts@@ -0,0 +1,65 @@+import { describe, expect, test } from 'bun:test'++import type { ConstraintType } from '@open-pencil/scene-graph'+import { constrainedChildRect } from '@open-pencil/scene-graph/resize'++// Live Figma, 2026-10-10: a locked 100×50 rectangle at 50,50 in a 200×200 frame.+const child = { x: 50, y: 50, width: 100, height: 50 }+const square = { width: 200, height: 200 }++function resized(+ horizontal: ConstraintType,+ vertical: ConstraintType,+ after: { width: number; height: number },+ ratio: number | null = 2+) {+ return constrainedChildRect(child, square, after, horizontal, vertical, ratio)+}++describe('constraints with a locked aspect ratio', () => {+ test('the one axis that follows the parent sizes the other', () => {+ expect(resized('STRETCH', 'MIN', { width: 300, height: 200 })).toEqual({+ x: 50,+ y: 50,+ width: 200,+ height: 100+ })+ expect(resized('MIN', 'STRETCH', { width: 200, height: 400 })).toEqual({+ x: 50,+ y: 50,+ width: 500,+ height: 250+ })+ expect(resized('SCALE', 'MIN', { width: 300, height: 200 })).toEqual({+ x: 75,+ y: 50,+ width: 150,+ height: 75+ })+ })++ test('the derived axis keeps the edge or centre its constraint pins', () => {+ const wider = { width: 300, height: 200 }+ expect(resized('STRETCH', 'MAX', wider)).toEqual({ x: 50, y: 0, width: 200, height: 100 })+ expect(resized('STRETCH', 'CENTER', wider)).toEqual({ x: 50, y: 25, width: 200, height: 100 })+ const taller = { width: 200, height: 400 }+ expect(resized('MAX', 'SCALE', taller)).toEqual({ x: -50, y: 100, width: 200, height: 100 })+ expect(resized('CENTER', 'SCALE', taller)).toEqual({ x: 0, y: 100, width: 200, height: 100 })+ })++ test('the ratio gives way when both axes or neither follow the parent', () => {+ const wider = { width: 300, height: 200 }+ expect(resized('STRETCH', 'STRETCH', wider)).toEqual({ x: 50, y: 50, width: 200, height: 50 })+ expect(resized('SCALE', 'SCALE', wider)).toEqual({ x: 75, y: 50, width: 150, height: 50 })+ expect(resized('CENTER', 'CENTER', wider)).toEqual({ x: 100, y: 50, width: 100, height: 50 })+ })++ test('an unlocked child follows each constraint on its own', () => {+ expect(resized('STRETCH', 'MIN', { width: 300, height: 200 }, null)).toEqual({+ x: 50,+ y: 50,+ width: 200,+ height: 50+ })+ })+})diff --git a/packages/vue/src/controls/layout/helpers.ts b/packages/vue/src/controls/layout/helpers.tsindex 998b12a39..cfc1f834e 100644--- a/packages/vue/src/controls/layout/helpers.ts+++ b/packages/vue/src/controls/layout/helpers.ts@@ -3,9 +3,13 @@ import type { ComputedRef } from 'vue'import type { Editor } from '@open-pencil/core/editor'import {+ aspectRatioLockEditable,+ enforcedAspectRatio,layoutSizing,layoutSizingOptions,layoutSizingUpdates,+ lockedAspectRatioTarget,+ sizeKeepingAspectRatio,type GridTrack,type LayoutAlign,type LayoutCounterAlign,@@ -246,13 +250,35 @@ export function createLayoutActions({)}+ function fixedAxisPatch(n: SceneNode, axis: LayoutAxis): Partial<SceneNode> {+ return axisSizingForNode(editor.graph, n, axis) === 'FIXED'+ ? {}+ : axisSizingPatchForNode(editor.graph, n, axis, 'FIXED')+ }++ // A locked layer keeps its ratio as either side is typed, as in Figma.function updateAxisSize(axis: LayoutAxis, value: number) {const n = node.valueif (!n) return- const sizing = axisSizingForNode(editor.graph, n, axis)- const sizingPatch =- sizing !== 'FIXED' ? axisSizingPatchForNode(editor.graph, n, axis, 'FIXED') : {}- preview.update([n.id], { ...sizingPatch, [axis]: value }, `Change ${axis}`)+ const ratio = enforcedAspectRatio(n)+ if (ratio === null) {+ preview.update([n.id], { ...fixedAxisPatch(n, axis), [axis]: value }, `Change ${axis}`)+ return+ }+ const size = sizeKeepingAspectRatio(ratio, axis, value)+ const patch = { ...fixedAxisPatch(n, 'width'), ...fixedAxisPatch(n, 'height'), ...size }+ preview.update([n.id], patch, `Change ${axis}`)+ }++ function toggleAspectRatioLock() {+ const n = node.value+ if (!n || !aspectRatioLockEditable(editor.graph, n)) return+ const locked = n.targetAspectRatio !== null+ editor.updateNodeWithUndo(+ n.id,+ { targetAspectRatio: locked ? null : lockedAspectRatioTarget(n.width, n.height) },+ 'Toggle aspect ratio lock'+ )}function commitAxisSize(_axis: LayoutAxis, _value: number, _previous: number) {@@ -299,6 +325,7 @@ export function createLayoutActions({setAxisSizing,updateAxisSize,commitAxisSize,+ toggleAspectRatioLock,setAlignment,setGapAuto,setLayoutDirection@@ -354,9 +381,16 @@ export function createLayoutSizingState(const widthSizingOptions = computed(sizingOptions)const heightSizingOptions = computed(sizingOptions)+ const aspectRatioLocked = computed(() => node.value?.targetAspectRatio != null)+ const aspectRatioLockable = computed(() => {+ const n = node.value+ return !!n && aspectRatioLockEditable(editor.graph, n)+ })return {isInAutoLayout,+ aspectRatioLocked,+ aspectRatioLockable,isGrid,isFlex,widthSizing,diff --git a/packages/vue/src/controls/layout/use.ts b/packages/vue/src/controls/layout/use.tsindex eaaa2122b..3d8a45eb2 100644--- a/packages/vue/src/controls/layout/use.ts+++ b/packages/vue/src/controls/layout/use.ts@@ -30,7 +30,9 @@ export function useLayout() {widthSizing,heightSizing,widthSizingOptions,- heightSizingOptions+ heightSizingOptions,+ aspectRatioLocked,+ aspectRatioLockable} = createLayoutSelectionState(editor, panels)const {@@ -61,6 +63,8 @@ export function useLayout() {heightSizing,widthSizingOptions,heightSizingOptions,+ aspectRatioLocked,+ aspectRatioLockable,alignGrid,showIndividualPadding,hasUniformPadding,@@ -80,6 +84,7 @@ export function useLayout() {setAxisSizing: layoutActions.setAxisSizing,updateAxisSize: layoutActions.updateAxisSize,commitAxisSize: layoutActions.commitAxisSize,+ toggleAspectRatioLock: layoutActions.toggleAspectRatioLock,setHorizontalPadding,commitHorizontalPadding,setVerticalPadding,diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex 0eb780f3d..96ccec2b6 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -79,6 +79,7 @@"addPage": "Seite hinzufügen","toggleVisibility": "Sichtbarkeit umschalten","independentCornerRadii": "Unabhängige Eckenradien",+ "lockAspectRatio": "Seitenverhältnis sperren","detachVariable": "Variable lösen","applyVariable": "Variable anwenden","noVariablesFound": "Keine Variablen gefunden",diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex c3784a6a3..0e8f52d9e 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -94,6 +94,7 @@"addPage": "Añadir página","toggleVisibility": "Alternar visibilidad","independentCornerRadii": "Redondeo de esquina independientes",+ "lockAspectRatio": "Bloquear relación de aspecto","detachVariable": "Desvincular variable","applyVariable": "Aplicar variable","noVariablesFound": "No se encontraron variables",diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex b8fed5c5a..1f73491ed 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -79,6 +79,7 @@"addPage": "Ajouter une page","toggleVisibility": "Basculer la visibilité","independentCornerRadii": "Rayons de coin indépendants",+ "lockAspectRatio": "Verrouiller les proportions","detachVariable": "Détacher la variable","applyVariable": "Appliquer la variable","noVariablesFound": "Aucune variable trouvée",diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex de53cd103..a98fda85a 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -79,6 +79,7 @@"addPage": "Aggiungi pagina","toggleVisibility": "Attiva/disattiva visibilità","independentCornerRadii": "Raggi angolo indipendenti",+ "lockAspectRatio": "Blocca proporzioni","detachVariable": "Scollega variabile","applyVariable": "Applica variabile","noVariablesFound": "Nessuna variabile trovata",diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex bf0ce23ee..341682c3a 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -94,6 +94,7 @@"addPage": "ページを追加","toggleVisibility": "表示/非表示の切り替え","independentCornerRadii": "個別の角丸",+ "lockAspectRatio": "縦横比を固定","detachVariable": "変数のリンクを解除","applyVariable": "変数を適用","noVariablesFound": "変数が見つかりません",diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex e0f0f034d..d5a8ec745 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -79,6 +79,7 @@"addPage": "Dodaj stronę","toggleVisibility": "Przełącz widoczność","independentCornerRadii": "Niezależne promienie rogów",+ "lockAspectRatio": "Zablokuj proporcje","detachVariable": "Odłącz zmienną","applyVariable": "Zastosuj zmienną","noVariablesFound": "Nie znaleziono zmiennych",diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex e1f19a730..f2db9b92b 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -79,6 +79,7 @@"addPage": "Добавить страницу","toggleVisibility": "Переключить видимость","independentCornerRadii": "Независимые радиусы углов",+ "lockAspectRatio": "Зафиксировать пропорции","detachVariable": "Отвязать переменную","applyVariable": "Применить переменную","noVariablesFound": "Переменные не найдены",diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 0e7278bd2..2849d6640 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -79,6 +79,7 @@"addPage": "添加页面","toggleVisibility": "切换可见性","independentCornerRadii": "独立圆角半径",+ "lockAspectRatio": "锁定宽高比","detachVariable": "解除变量绑定","applyVariable": "应用变量","noVariablesFound": "未找到变量",diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 60e7299a7..0e28f7e4f 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -379,6 +379,7 @@ export const panelMessageDefaults = {addPage: 'Add page',toggleVisibility: 'Toggle visibility',independentCornerRadii: 'Independent corner radii',+ lockAspectRatio: 'Lock aspect ratio',detachVariable: 'Detach variable',applyVariable: 'Apply variable',noVariablesFound: 'No variables found',diff --git a/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vue b/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vueindex 2da15eea6..d17fe2e46 100644--- a/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vue+++ b/packages/vue/src/primitives/LayoutControls/LayoutControlsRoot.vue@@ -19,6 +19,7 @@ const actions = {setAxisSizing: ctx.setAxisSizing,updateAxisSize: ctx.updateAxisSize,commitAxisSize: ctx.commitAxisSize,+ toggleAspectRatioLock: ctx.toggleAspectRatioLock,setHorizontalPadding: ctx.setHorizontalPadding,commitHorizontalPadding: ctx.commitHorizontalPadding,setVerticalPadding: ctx.setVerticalPadding,@@ -51,6 +52,8 @@ provideLayoutControls(:height-sizing="ctx.heightSizing.value":width-sizing-options="ctx.widthSizingOptions.value":height-sizing-options="ctx.heightSizingOptions.value"+ :aspect-ratio-locked="ctx.aspectRatioLocked.value"+ :aspect-ratio-lockable="ctx.aspectRatioLockable.value":align-grid="ctx.alignGrid.value":show-individual-padding="ctx.showIndividualPadding.value":has-uniform-padding="ctx.hasUniformPadding.value"diff --git a/packages/vue/src/primitives/LayoutControls/types.ts b/packages/vue/src/primitives/LayoutControls/types.tsindex 615a38286..9cb205e00 100644--- a/packages/vue/src/primitives/LayoutControls/types.ts+++ b/packages/vue/src/primitives/LayoutControls/types.ts@@ -15,6 +15,7 @@ type LayoutActionKey =| 'setAxisSizing'| 'updateAxisSize'| 'commitAxisSize'+ | 'toggleAspectRatioLock'| 'setHorizontalPadding'| 'commitHorizontalPadding'| 'setVerticalPadding'diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.tsindex f9d1b5229..104b15459 100644--- a/packages/vue/src/shared/input/resize.ts+++ b/packages/vue/src/shared/input/resize.ts@@ -1,11 +1,12 @@export { constrainToAspectRatio } from '#vue/shared/input/resize/rect'export { tryStartResize } from '#vue/shared/input/resize/start'+import { isEqual } from 'es-toolkit'import { toRaw } from 'vue'import type { Editor } from '@open-pencil/core/editor'import { computeAllLayouts } from '@open-pencil/core/layout'import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/core/text'-import { cloneVectorNetwork } from '@open-pencil/scene-graph'+import { cloneVectorNetwork, recapturedAspectRatio } from '@open-pencil/scene-graph'import type { SceneNode } from '@open-pencil/scene-graph'import { copyDerivedGlyphs, copyGeometryPaths, copyStrokes } from '@open-pencil/scene-graph/copy'import type { Rect } from '@open-pencil/scene-graph/primitives'@@ -17,6 +18,7 @@ import {import { markSourceFieldsEdited } from '@open-pencil/scene-graph/source-metadata'import { calculateResizeRect } from '#vue/shared/input/resize/rect'+import { draggedSizing, layerSizing } from '#vue/shared/input/resize/sizing'import { applyResizeSnap } from '#vue/shared/input/resize/snap'import { optionalEditorState } from '#vue/shared/input/snap'import type { DragResize } from '#vue/shared/input/types'@@ -60,25 +62,37 @@ function reflowedPathTextChanges(}}+/**+ * The ratio a drag keeps, as Figma's handles keep it: a locked layer keeps its own unless Control+ * frees it, and Shift keeps the ratio the drag started from.+ */+function keptAspectRatio(d: DragResize, shiftKey: boolean, ctrlKey: boolean): number | null {+ if (d.lockedAspectRatio !== null && !ctrlKey) return d.lockedAspectRatio+ const { width, height } = d.origRect+ return shiftKey && width > 0 && height > 0 ? width / height : null+}+function resizeChanges(d: DragResize,cx: number,cy: number,- constrain: boolean,+ shiftKey: boolean,editor: Editor,- disableSnapping: boolean+ ctrlKey: boolean) {const { origRect } = d+ const aspect = keptAspectRatio(d, shiftKey, ctrlKey)+ // Control sets a lock aside even when Shift keeps the same ratio; the commit stores the size.+ d.freesLock = d.lockedAspectRatio !== null && ctrlKeyconst calculatedRect = calculateResizeRect(d.handle,origRect,cx - d.startX,cy - d.startY,- constrain+ aspect)- const newRect = constrain- ? calculatedRect- : applyResizeSnap(d, calculatedRect, editor, disableSnapping)+ const newRect =+ aspect !== null ? calculatedRect : applyResizeSnap(d, calculatedRect, editor, ctrlKey)const changes: Partial<SceneNode> = {...newRect,@@ -133,21 +147,28 @@ function applyConstrainedChildren(}}+/** Control both frees a locked ratio and turns snapping off, as in Figma. */export function applyResize(dragState: DragResize,cx: number,cy: number,- constrain: boolean,+ shiftKey: boolean,editor: Editor,- disableSnapping = false+ ctrlKey = false) {// Drag state lives in Vue-reactive input state; nested arrays read through// it are reactive proxies. Writing those into the graph poisons it for// structuredClone consumers (export subgraph clone, undo snapshots) with// DataCloneError. Unwrap once — also keeps the drag hot path off proxies.const d = toRaw(dragState)- const { changes, newRect } = resizeChanges(d, cx, cy, constrain, editor, disableSnapping)+ const { changes, newRect } = resizeChanges(d, cx, cy, shiftKey, editor, ctrlKey)d.appliedRect = { ...newRect }+ const node = editor.graph.getNode(d.nodeId)+ if (node) {+ d.origSizing ??= layerSizing(node)+ d.appliedSizing = draggedSizing(editor.graph, node, d.origSizing, d.origRect, newRect)+ Object.assign(changes, d.appliedSizing)+ }markResized(d, newRect, editor)if (d.origRect.width > 0 && d.origRect.height > 0) {const reflow = reflowedPathTextChanges(@@ -286,6 +307,7 @@ export function cancelResizePreview(dragState: DragResize, editor: Editor) {textPathData: d.origTextPathData,textPathBox: d.origTextPathBox})+ if (d.origSizing) editor.graph.updateNodePreview(d.nodeId, d.origSizing)editor.renderer?.invalidateVectorPath(d.nodeId)restoreEditedFields(d, editor)editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))@@ -295,14 +317,28 @@ export function cancelResizePreview(dragState: DragResize, editor: Editor) {export function commitResizePreview(dragState: DragResize, editor: Editor) {// See applyResize — reactive drag state must not leak into graph writes.const d = toRaw(dragState)- if (editor.graph.getNode(d.nodeId)?.type !== 'SECTION') {+ const node = editor.graph.getNode(d.nodeId)+ // A section resized over layers takes in the ones it now covers, a lock that Control set aside+ // takes the new size, and an axis that stopped hugging or filling stays fixed, in one undo step.+ const adoptsLayers = node?.type === 'SECTION'+ const recaptured = node && d.freesLock ? recapturedAspectRatio(node, node.width, node.height) : {}+ const fixesSizing =+ d.origSizing !== undefined &&+ d.appliedSizing !== undefined &&+ !isEqual(d.origSizing, d.appliedSizing)+ if (!adoptsLayers && !recaptured.targetAspectRatio && !fixesSizing) {commitResizeGeometry(d, editor)return}- // A section resized over layers takes in the ones it now covers, in the same undo step.editor.undo.runBatch('Resize', () => {+ // Recorded from the sizing the layer started with, so undo puts it back.+ if (fixesSizing && d.origSizing && d.appliedSizing) {+ editor.graph.updateNodePreview(d.nodeId, d.origSizing)+ editor.updateNodeWithUndo(d.nodeId, d.appliedSizing, 'Resize')+ }commitResizeGeometry(d, editor)- editor.adoptCoveredLayers(d.nodeId)+ if (recaptured.targetAspectRatio) editor.updateNodeWithUndo(d.nodeId, recaptured, 'Resize')+ if (adoptsLayers) editor.adoptCoveredLayers(d.nodeId)})}diff --git a/packages/vue/src/shared/input/resize/rect.ts b/packages/vue/src/shared/input/resize/rect.tsindex 0436a33f9..7c812d6b3 100644--- a/packages/vue/src/shared/input/resize/rect.ts+++ b/packages/vue/src/shared/input/resize/rect.ts@@ -2,33 +2,45 @@ import type { Rect } from '@open-pencil/scene-graph/primitives'import type { HandlePosition } from '#vue/shared/input/types'+/** `value` at least `min` long, keeping the direction it was dragged in. */+function atLeast(value: number, min: number): number {+ return Math.sign(value || 1) * Math.max(Math.abs(value), min)+}++/**+ * Fits a dragged box to `aspect` (width over height), as Figma does: an edge handle sizes the+ * other axis around its centre, a corner handle follows the axis the pointer changed most and+ * keeps the opposite corner in place. The side that drives stays long enough for the other to+ * keep a whole pixel, so the box keeps its ratio at its smallest.+ */export function constrainToAspectRatio(handle: HandlePosition,origRect: Rect,width: number,height: number,- dx: number,- dy: number+ aspect: number): Rect {- let x = handle.includes('w') ? origRect.x + origRect.width - Math.abs(width) : origRect.x+ const minWidth = Math.max(1, aspect)+ const minHeight = Math.max(1, 1 / aspect)const isTop = handle === 'nw' || handle === 'n' || handle === 'ne'- let y = isTop ? origRect.y + origRect.height - Math.abs(height) : origRect.y- const aspect = origRect.width / origRect.height-- if (handle === 'n' || handle === 's') {- width = Math.abs(height) * aspect- x = origRect.x + (origRect.width - width) / 2- } else if (handle === 'e' || handle === 'w') {- height = Math.abs(width) / aspect- y = origRect.y + (origRect.height - height) / 2- } else if (Math.abs(dx) > Math.abs(dy)) {- height = (Math.abs(width) / aspect) * Math.sign(height || 1)- if (isTop) y = origRect.y + origRect.height - Math.abs(height)+ const isEdge = handle === 'n' || handle === 's' || handle === 'e' || handle === 'w'+ const widthDrives = isEdge+ ? handle === 'e' || handle === 'w'+ : Math.abs(width) > Math.abs(height) * aspect+ if (widthDrives) {+ width = atLeast(width, minWidth)+ height = (Math.abs(width) / aspect) * (isEdge ? 1 : Math.sign(height || 1))} else {- width = Math.abs(height) * aspect * Math.sign(width || 1)- if (handle.includes('w')) x = origRect.x + origRect.width - Math.abs(width)+ height = atLeast(height, minHeight)+ width = Math.abs(height) * aspect * (isEdge ? 1 : Math.sign(width || 1))}+ // Signed sizes: a handle dragged past the opposite edge lands the box on the far side.+ let x = handle.includes('w') ? origRect.x + origRect.width - width : origRect.x+ let y = isTop ? origRect.y + origRect.height - height : origRect.y+ if (handle === 'n' || handle === 's') x = origRect.x + (origRect.width - width) / 2+ if (handle === 'e' || handle === 'w') y = origRect.y + (origRect.height - height) / 2+return { x, y, width, height }}@@ -37,7 +49,7 @@ export function calculateResizeRect(origRect: Rect,dx: number,dy: number,- constrain: boolean+ aspect: number | null): Rect {let { x, y, width, height } = origRect@@ -57,8 +69,8 @@ export function calculateResizeRect(height = origRect.height - dy}- if (constrain && origRect.width > 0 && origRect.height > 0) {- ;({ x, y, width, height } = constrainToAspectRatio(handle, origRect, width, height, dx, dy))+ if (aspect !== null) {+ ;({ x, y, width, height } = constrainToAspectRatio(handle, origRect, width, height, aspect))}if (width < 0) {diff --git a/packages/vue/src/shared/input/resize/sizing.ts b/packages/vue/src/shared/input/resize/sizing.tsnew file mode 100644index 000000000..818b085c5--- /dev/null+++ b/packages/vue/src/shared/input/resize/sizing.ts@@ -0,0 +1,51 @@+import { pick } from 'es-toolkit'++import {+ layoutSizing,+ layoutSizingUpdates,+ type LayoutSizingAxis,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'+import type { Rect } from '@open-pencil/scene-graph/primitives'++const SIZING_FIELDS = [+ 'primaryAxisSizing',+ 'counterAxisSizing',+ 'layoutGrow',+ 'layoutAlignSelf'+] as const satisfies readonly (keyof SceneNode)[]++export type LayerSizing = Pick<SceneNode, (typeof SIZING_FIELDS)[number]>++const AXES: readonly ['width' | 'height', LayoutSizingAxis][] = [+ ['width', 'HORIZONTAL'],+ ['height', 'VERTICAL']+]++export function layerSizing(node: SceneNode): LayerSizing {+ return pick(node, SIZING_FIELDS)+}++/**+ * The sizing a handle drag leaves the layer with, as Figma sets it: an axis the drag resized stops+ * hugging or filling and becomes fixed, so layout keeps the dragged size, while an axis it left+ * alone keeps its sizing. Text hugs by its auto-resize, which a drag sets elsewhere.+ */+export function draggedSizing(+ graph: SceneGraph,+ node: SceneNode,+ original: LayerSizing,+ origRect: Rect,+ rect: Rect+): LayerSizing {+ const sizing = { ...original }+ if (node.type === 'TEXT') return sizing+ const base = { ...node, ...original }+ for (const [dimension, axis] of AXES) {+ if (rect[dimension] === origRect[dimension]) continue+ if (layoutSizing(graph, base, axis) === 'FIXED') continue+ Object.assign(sizing, pick(layoutSizingUpdates(graph, base, axis, 'FIXED'), SIZING_FIELDS))+ }+ return sizing+}diff --git a/packages/vue/src/shared/input/resize/start.ts b/packages/vue/src/shared/input/resize/start.tsindex 4c67e6942..a55ab511e 100644--- a/packages/vue/src/shared/input/resize/start.ts+++ b/packages/vue/src/shared/input/resize/start.ts@@ -1,4 +1,5 @@import type { Editor } from '@open-pencil/core/editor'+import { enforcedAspectRatio } from '@open-pencil/scene-graph'import { collectResizeDescendants, createResizeSnapshot } from '@open-pencil/scene-graph/resize'import { getHitHandleByMatrix } from '#vue/shared/input/geometry'@@ -33,6 +34,7 @@ export function tryStartResize(cx: number, cy: number, editor: Editor): DragResiorigTextPathData: snap.textPathData,origTextPathBox: snap.textPathBox,origChildren: collectResizeDescendants(editor.graph, id),+ lockedAspectRatio: enforcedAspectRatio(node),appliedRect: { x: node.x, y: node.y, width: node.width, height: node.height }}}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 7e6086486..9ba69516a 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -11,6 +11,8 @@ import type {import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { ResizeSnapshot } from '@open-pencil/scene-graph/resize'+import type { LayerSizing } from '#vue/shared/input/resize/sizing'+export type HandlePosition = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'export type CornerPosition = 'nw' | 'ne' | 'se' | 'sw'@@ -82,9 +84,17 @@ export interface DragResize {origTextPathData: TextPathData | nullorigTextPathBox: Rect | nullorigChildren: Map<string, ResizeSnapshot> | null+ /** The ratio the layer is locked to, kept unless Control frees it. */+ lockedAspectRatio: number | null+ /** Whether the latest step set the lock aside, so the commit stores the new size. */+ freesLock?: booleanappliedRect?: Rect/** The layer's edited fields before the drag marked its size, to put back if it changes nothing. */origEditedFields?: string[]+ /** The layer's sizing before the drag, taken on its first step. */+ origSizing?: LayerSizing+ /** The sizing the latest step left, which the commit keeps. */+ appliedSizing?: LayerSizing}export interface DragMarquee {diff --git a/packages/vue/tests/shared/input/resize.test.ts b/packages/vue/tests/shared/input/resize.test.tsindex 4dad79bb8..e691d5c84 100644--- a/packages/vue/tests/shared/input/resize.test.ts+++ b/packages/vue/tests/shared/input/resize.test.ts@@ -21,6 +21,7 @@ function drag(node: SceneNode): DragResize {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: null}}diff --git a/packages/vue/tests/shared/input/resize/aspect-ratio.test.ts b/packages/vue/tests/shared/input/resize/aspect-ratio.test.tsnew file mode 100644index 000000000..f179f796f--- /dev/null+++ b/packages/vue/tests/shared/input/resize/aspect-ratio.test.ts@@ -0,0 +1,122 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import type { SceneNode } from '@open-pencil/scene-graph'++import { applyResize, commitResizePreview } from '#vue/shared/input/resize'+import { tryStartResize } from '#vue/shared/input/resize/start'+import type { DragResize } from '#vue/shared/input/types'++// Handle drags recorded in live Figma, 2026-10-10, on a 200×100 rectangle at 200,150.+const HANDLES: Record<DragResize['handle'], [number, number]> = {+ nw: [0, 0],+ n: [0.5, 0],+ ne: [1, 0],+ e: [1, 0.5],+ se: [1, 1],+ s: [0.5, 1],+ sw: [0, 1],+ w: [0, 0.5]+}++function drag(+ handle: DragResize['handle'],+ dx: number,+ dy: number,+ { locked = true, shift = false, ctrl = false } = {}+) {+ const editor = createEditor()+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }+ const node = editor.graph.createNode('RECTANGLE', editor.state.currentPageId, {+ x: 200,+ y: 150,+ width: 200,+ height: 100,+ targetAspectRatio: locked ? { x: 200, y: 100 } : null+ })+ editor.select([node.id])+ const [fx, fy] = HANDLES[handle]+ const startX = 200 + fx * 200+ const startY = 150 + fy * 100+ const state = tryStartResize(startX, startY, editor)+ if (!state) throw new Error(`No ${handle} handle at ${startX},${startY}`)+ applyResize(state, startX + dx, startY + dy, shift, editor, ctrl)+ commitResizePreview(state, editor)+ return { editor, node: editor.graph.getNode(node.id) as SceneNode }+}++function box(node: SceneNode) {+ return { x: node.x, y: node.y, width: node.width, height: node.height }+}++describe('resizing a locked layer on the canvas', () => {+ test('a corner follows the axis the pointer changed most', () => {+ expect(box(drag('se', 100, 10).node)).toEqual({ x: 200, y: 150, width: 300, height: 150 })+ expect(box(drag('se', 10, 100).node)).toEqual({ x: 200, y: 150, width: 400, height: 200 })+ expect(box(drag('se', 60, 40).node)).toEqual({ x: 200, y: 150, width: 280, height: 140 })+ expect(box(drag('nw', -100, -10).node)).toEqual({ x: 100, y: 100, width: 300, height: 150 })+ })++ test('a corner keeps the larger of the two boxes, also when shrinking', () => {+ expect(box(drag('se', -50, 0).node)).toEqual({ x: 200, y: 150, width: 200, height: 100 })+ expect(box(drag('se', -50, 10).node)).toEqual({ x: 200, y: 150, width: 220, height: 110 })+ expect(box(drag('se', -100, -10).node)).toEqual({ x: 200, y: 150, width: 180, height: 90 })+ })++ test('a handle dragged past the opposite edge lands the box beyond it', () => {+ expect(box(drag('w', 300, 0).node)).toEqual({ x: 400, y: 175, width: 100, height: 50 })+ expect(box(drag('n', 0, 150).node)).toEqual({ x: 250, y: 250, width: 100, height: 50 })+ expect(box(drag('nw', 300, 150).node)).toEqual({ x: 400, y: 250, width: 100, height: 50 })+ })++ test('an edge sizes the other axis around its centre', () => {+ expect(box(drag('e', 100, 0).node)).toEqual({ x: 200, y: 125, width: 300, height: 150 })+ expect(box(drag('s', 0, 50).node)).toEqual({ x: 150, y: 150, width: 300, height: 150 })+ })++ test('the lock keeps the stored size, and Shift adds nothing', () => {+ const { node } = drag('se', 100, 10, { shift: true })+ expect(box(node)).toEqual({ x: 200, y: 150, width: 300, height: 150 })+ expect(node.targetAspectRatio).toEqual({ x: 200, y: 100 })+ })++ test('Control frees the lock and the new size becomes the ratio, in one undo step', () => {+ const { editor, node } = drag('se', 100, 10, { ctrl: true })+ expect(box(node)).toEqual({ x: 200, y: 150, width: 300, height: 110 })+ expect(node.targetAspectRatio).toEqual({ x: 300, y: 110 })++ editor.undo.undo()+ const restored = editor.graph.getNode(node.id) as SceneNode+ expect(box(restored)).toEqual({ x: 200, y: 150, width: 200, height: 100 })+ expect(restored.targetAspectRatio).toEqual({ x: 200, y: 100 })+ })++ test('Control with Shift still stores the new size as the ratio', () => {+ const { node } = drag('se', 100, 10, { ctrl: true, shift: true })+ expect(box(node)).toEqual({ x: 200, y: 150, width: 300, height: 150 })+ expect(node.targetAspectRatio).toEqual({ x: 300, y: 150 })+ })++ test('the ratio holds at the smallest size an edge can reach', () => {+ expect(box(drag('e', -199.5, 0).node)).toEqual({ x: 200, y: 199.5, width: 2, height: 1 })+ })++ test('Shift keeps the ratio of an unlocked layer for one drag', () => {+ const unlocked = { locked: false, shift: true }+ expect(box(drag('e', 100, 0, unlocked).node)).toEqual({+ x: 200,+ y: 125,+ width: 300,+ height: 150+ })+ const { node } = drag('se', 60, 40, unlocked)+ expect(box(node)).toEqual({ x: 200, y: 150, width: 280, height: 140 })+ expect(node.targetAspectRatio).toBeNull()+ expect(box(drag('se', 100, 10, { locked: false }).node)).toEqual({+ x: 200,+ y: 150,+ width: 300,+ height: 110+ })+ })+})diff --git a/packages/vue/tests/shared/input/resize/sizing.test.ts b/packages/vue/tests/shared/input/resize/sizing.test.tsnew file mode 100644index 000000000..8297e95b9--- /dev/null+++ b/packages/vue/tests/shared/input/resize/sizing.test.ts@@ -0,0 +1,80 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++import { applyResize, cancelResizePreview, commitResizePreview } from '#vue/shared/input/resize'+import { tryStartResize } from '#vue/shared/input/resize/start'+import type { DragResize } from '#vue/shared/input/types'++// Handle drags on a Hug × Hug auto layout frame of two 100×100 frames at 200,150, recorded in+// live Figma on 2026-10-10: [x, y, width, height, horizontal sizing, vertical sizing].+const CASES: [DragResize["handle"], number, number, boolean, (number | string)[]][] = [+ ['e', 60, 0, false, [200, 150, 260, 100, 'FIXED', 'HUG']],+ ['s', 0, 40, false, [200, 150, 200, 140, 'HUG', 'FIXED']],+ ['se', 60, 40, false, [200, 150, 260, 140, 'FIXED', 'FIXED']],+ ['e', 60, 0, true, [200, 135, 260, 130, 'FIXED', 'FIXED']],+ ['s', 0, 40, true, [160, 150, 280, 140, 'FIXED', 'FIXED']],+ ['se', 60, 40, true, [200, 150, 280, 140, 'FIXED', 'FIXED']],+ ['e', -60, 0, true, [200, 165, 140, 70, 'FIXED', 'FIXED']]+]++function hugFrame(locked: boolean) {+ const editor = createEditor()+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }+ const page = editor.state.currentPageId+ const a = editor.graph.createNode('FRAME', page, { x: 200, y: 150, width: 100, height: 100 })+ const b = editor.graph.createNode('FRAME', page, { x: 300, y: 150, width: 100, height: 100 })+ editor.select([a.id, b.id])+ const id = editor.wrapInAutoLayout()+ if (!id) throw new Error('No auto layout frame')+ if (locked) editor.updateNodeWithUndo(id, { targetAspectRatio: { x: 200, y: 100 } })+ editor.select([id])+ return { editor, id }+}++function startDrag(editor: ReturnType<typeof createEditor>, id: string, handle: string) {+ const node = editor.graph.getNode(id)+ if (!node) throw new Error('Missing frame')+ const x = node.x + (handle === 's' ? node.width / 2 : node.width)+ const y = node.y + (handle === 'e' ? node.height / 2 : node.height)+ const drag = tryStartResize(x, y, editor)+ if (!drag) throw new Error(`No ${handle} handle`)+ return { drag, x, y }+}++function read(editor: ReturnType<typeof createEditor>, id: string): (number | string)[] {+ const node = editor.graph.getNode(id)+ if (!node) throw new Error('Missing frame')+ const row = node.layoutMode === 'HORIZONTAL'+ return [+ node.x,+ node.y,+ node.width,+ node.height,+ row ? node.primaryAxisSizing : node.counterAxisSizing,+ row ? node.counterAxisSizing : node.primaryAxisSizing+ ]+}++describe('dragging a handle of a Hug frame', () => {+ for (const [handle, dx, dy, locked, expected] of CASES) {+ test(`${locked ? 'locked' : 'free'} ${handle} ${dx},${dy} fixes the axes it resizes`, () => {+ const { editor, id } = hugFrame(locked)+ const { drag, x, y } = startDrag(editor, id, handle)+ applyResize(drag, x + dx, y + dy, false, editor)+ commitResizePreview(drag, editor)+ expect(read(editor, id)).toEqual(expected)++ editor.undoAction()+ expect(read(editor, id)).toEqual([200, 150, 200, 100, 'HUG', 'HUG'])+ })+ }++ test('a cancelled drag leaves the frame hugging', () => {+ const { editor, id } = hugFrame(true)+ const { drag, x, y } = startDrag(editor, id, 'se')+ applyResize(drag, x + 60, y + 40, false, editor)+ cancelResizePreview(drag, editor)+ expect(read(editor, id)).toEqual([200, 150, 200, 100, 'HUG', 'HUG'])+ })+})diff --git a/packages/vue/tests/shared/input/section-resize.test.ts b/packages/vue/tests/shared/input/section-resize.test.tsindex 4eaf079d6..7a265d799 100644--- a/packages/vue/tests/shared/input/section-resize.test.ts+++ b/packages/vue/tests/shared/input/section-resize.test.ts@@ -31,6 +31,7 @@ describe('section resize', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: null}diff --git a/src/components/properties/layout/size/SizeControls.vue b/src/components/properties/layout/size/SizeControls.vueindex e6426d0b0..5a889eeec 100644--- a/src/components/properties/layout/size/SizeControls.vue+++ b/src/components/properties/layout/size/SizeControls.vue@@ -6,6 +6,7 @@ import { useI18n, useLayoutControlsContext } from '@open-pencil/vue'import SizeAxisField from '@/components/properties/layout/size/SizeAxisField.vue'import SizeLimitField from '@/components/properties/layout/size/SizeLimitField.vue'import type { SizeLimitItem } from '@/components/properties/layout/size/types'+import IconButton from '@/components/ui/button/IconButton.vue'import PanelGrid from '@/components/ui/panel/PanelGrid.vue'const ctx = useLayoutControlsContext()@@ -51,6 +52,18 @@ const visibleSizeLimits = computed(() =><PanelGrid :columns="1"><SizeAxisField axis="width" icon="W" :label="panels.width" /><SizeAxisField axis="height" icon="H" :label="panels.height" />+ <template v-if="ctx.aspectRatioLockable" #actions>+ <IconButton+ :label="panels.lockAspectRatio"+ size="xs"+ toggle+ :active="ctx.aspectRatioLocked"+ data-test-id="aspect-ratio-lock"+ @click="ctx.toggleAspectRatioLock"+ >+ <icon-lucide-proportions class="size-3" />+ </IconButton>+ </template></PanelGrid><PanelGrid v-if="visibleSizeLimits.length" :columns="2" class="mt-1.5">diff --git a/tests/engine/io/fig/import/raw-field-coverage.test.ts b/tests/engine/io/fig/import/raw-field-coverage.test.tsindex 0a108f13e..17bfb9c68 100644--- a/tests/engine/io/fig/import/raw-field-coverage.test.ts+++ b/tests/engine/io/fig/import/raw-field-coverage.test.ts@@ -119,7 +119,6 @@ const RAW_FIELD_COVERAGE = {'styleType','textExplicitLayoutVersion','textUserLayoutVersion',- 'targetAspectRatio','transitionInfo','userFacingVersion','variableConsumptionMap',diff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.tsindex 389f7bb33..4c1897a5a 100644--- a/tests/engine/io/fig/import/schema-coverage.test.ts+++ b/tests/engine/io/fig/import/schema-coverage.test.ts@@ -373,10 +373,10 @@ describe('Figma Kiwi schema coverage', () => {expect(Object.fromEntries([...buckets].map(([bucket, items]) => [bucket, items.length]))).toEqual({- modeled: 123,+ modeled: 124,schemaTag: 60,internalBookkeeping: 16,- rawPreserved: 46,+ rawPreserved: 45,styleLibraryMetadata: 38,componentInstanceMetadata: 32,textMetadata: 23,diff --git a/tests/engine/vue/controls/constraints.test.ts b/tests/engine/vue/controls/constraints.test.tsindex 37a839ee1..738f46394 100644--- a/tests/engine/vue/controls/constraints.test.ts+++ b/tests/engine/vue/controls/constraints.test.ts@@ -132,6 +132,7 @@ describe('constraint resize geometry', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: new Map([[nested.id, original(nested)],[grandchild.id, original(grandchild)]@@ -181,6 +182,7 @@ describe('constraint resize geometry', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: collectResizeDescendants(graph, root.id)}diff --git a/tests/engine/vue/input/resize/geometry.test.ts b/tests/engine/vue/input/resize/geometry.test.tsindex 2cb9ada44..16eaa94ef 100644--- a/tests/engine/vue/input/resize/geometry.test.ts+++ b/tests/engine/vue/input/resize/geometry.test.ts@@ -78,6 +78,7 @@ function dragFor(node: SceneNode, origChildren: DragResize['origChildren'] = nulorigStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren}}diff --git a/tests/engine/vue/input/resize/path-text/basic.test.ts b/tests/engine/vue/input/resize/path-text/basic.test.tsindex 6a395a4b0..332fa91d4 100644--- a/tests/engine/vue/input/resize/path-text/basic.test.ts+++ b/tests/engine/vue/input/resize/path-text/basic.test.ts@@ -129,6 +129,7 @@ describe('resize scales path-text stroke geometry and glyphs', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: new Map([[text.id, origChild]])}@@ -216,6 +217,7 @@ describe('resize scales path-text stroke geometry and glyphs', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: new Map([[text.id, origChild]])}) as DragResizediff --git a/tests/engine/vue/input/resize/path-text/reflow.test.ts b/tests/engine/vue/input/resize/path-text/reflow.test.tsindex 7f964925f..9087fe80d 100644--- a/tests/engine/vue/input/resize/path-text/reflow.test.ts+++ b/tests/engine/vue/input/resize/path-text/reflow.test.ts@@ -173,6 +173,7 @@ describe('group resize reflows path text instead of squashing it', () => {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: new Map([[text.id, origChild]])}@@ -277,6 +278,7 @@ describe('direct (non-group) resize reflows path text instead of squashing it',origStrokes: copyStrokes(text.strokes),origTextPathData: structuredClone(expectDefined(text.textPathData)),origTextPathBox: { ...box },+ lockedAspectRatio: null,origChildren: null}@@ -404,6 +406,7 @@ describe('resize + export integration: real commit path clears stale raw payloadorigStrokes: copyStrokes(text.strokes),origTextPathData: structuredClone(expectDefined(text.textPathData)),origTextPathBox: { ...box },+ lockedAspectRatio: null,origChildren: null}diff --git a/tests/engine/vue/input/resize/snapping.test.ts b/tests/engine/vue/input/resize/snapping.test.tsindex b1ade09b6..9d7ea8c9d 100644--- a/tests/engine/vue/input/resize/snapping.test.ts+++ b/tests/engine/vue/input/resize/snapping.test.ts@@ -29,6 +29,7 @@ function setup(handle: DragResize['handle'] = 'se') {origStrokes: [],origTextPathData: null,origTextPathBox: null,+ lockedAspectRatio: null,origChildren: null}return { editor, nodeId: node.id, drag }