AI-native design editor. Open-source Figma alternative.
fix(layout): move layers that ignore auto layout by their constraints (#1060)
Danila Poyarkovf67973ed8466
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 672453081..3220d1b6c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -167,11 +167,12 @@- 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.- Polygons and stars draw and export to SVG with their corner radius and smoothing as Figma rounds them, inner star corners included, and copy to and from Figma with their point count and a star's inner ratio; they were drawn with sharp corners, also from `.fig` files, and pasted into Figma as empty shapes.- The font picker opens at the current font instead of the top of the list.- Undo after adding, switching, or removing auto layout, or wrapping layers in it with <kbd>⇧</kbd><kbd>A</kbd>, puts back every layer the layout moved or resized, and the new frame takes the place of the topmost layer it wraps, as in Figma. Setting the layout a frame already has, or aligning layers that auto layout places, no longer records an undo step, and undoing a drag out of an auto layout frame puts the layer back in its slot.- A Fill child in a Hug frame keeps its size, as in Figma, instead of collapsing the frame: along the layout the frame hugs the child as it is, and across it the frame hugs the other children, keeping its size when every child fills. A Fill line stays a line, placed where its row aligns the other layers.-- A frame in a reopened `.fig` file lays out again when you add auto layout, padding, or a gap to it, or add, move, or remove a layer in it or in an auto layout inside it, instead of keeping its layers where the file had them.+- A frame in a reopened `.fig` file lays out again when you resize it, add auto layout, padding, or a gap to it, or add, move, or remove a layer in it or in an auto layout inside it, instead of keeping its layers where the file had them; a Fill layer fills a resized frame while you drag.- A Hug frame grows with its text while the text is typed, as in Figma, instead of only when editing ends.- `figma.currentPage.backgrounds` in the plugin API and `eval` scripts takes Figma paints, as `fills` does.- Cmd+Z and Shift+Cmd+Z undo and redo while a fill, stroke, or colour picker is open, as in Figma, and undo reverts the picker's latest change rather than the edit before it.diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex 545737d00..42d6d8924 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -18,7 +18,7 @@ const io = new IORegistry(CLI_IO_FORMATS)export async function loadDocument(filePath: string): Promise<SceneGraph> {const bytes = new Uint8Array(await readFile(filePath))const { graph } = await io.readDocument({ name: filePath, data: bytes })- computeAllLayouts(graph)+ graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph))return graph}@@ -36,13 +36,13 @@ export async function writeFigDocument(graph: SceneGraph, filePath: string): Proexport function populateDocumentPage(graph: SceneGraph, pageId: string): boolean {const changed = populateFigPage(graph, pageId)- if (changed) computeAllLayouts(graph, pageId)+ if (changed) graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph, pageId))return changed}export function populateWholeDocument(graph: SceneGraph): boolean {const changed = populateAllFigPages(graph)- if (changed) computeAllLayouts(graph)+ if (changed) graph.applyDerivedLayoutDuring(() => computeAllLayouts(graph))return changed}diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.tsindex 9f0584b0a..fb682df14 100644--- a/packages/core/src/layout/apply.ts+++ b/packages/core/src/layout/apply.ts@@ -1,6 +1,7 @@import type { Node as YogaNode } from 'yoga-layout'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { layoutConstrainedChildRect } from '@open-pencil/scene-graph/resize'import { keepsSavedLayout, usesDetachedDerivedLayout } from './derived'@@ -25,33 +26,120 @@ type LayoutGeometry = Partial<Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>>/*** Writes only the geometry layout changed. Laying out a large page leaves most layers where they- * were, and each write would notify every graph listener for nothing.+ * were, and each write would notify every graph listener for nothing. A frame it resizes from+ * `before`, by default the size it has, places the layers its constraints govern; `constrained`+ * marks a write those constraints made, which places its own children in turn.*/-function writeLayoutGeometry(graph: SceneGraph, id: string, geometry: LayoutGeometry): void {+function writeLayoutGeometry(+ graph: SceneGraph,+ id: string,+ geometry: LayoutGeometry,+ computeLayout: ComputeLayoutFn,+ before?: { width: number; height: number },+ constrained = false+): void {const node = graph.getNode(id)if (!node) return+ const from = before ?? { width: node.width, height: node.height }const changes: LayoutGeometry = {}for (const key of ['x', 'y', 'width', 'height'] as const) {const value = geometry[key]if (value !== undefined && value !== node[key]) changes[key] = value}if (Object.keys(changes).length > 0) graph.updateNode(id, changes)+ if (!CONSTRAINT_PARENT_TYPES.has(node.type)) return+ // Laying out what a file holds, as a page opens or its fonts arrive, resizes a frame only where+ // our layout differs from the one the file saved; its children keep the places it saved.+ if (graph.isApplyingDerivedLayout && !constrained) return+ if (from.width !== node.width || from.height !== node.height) {+ constrainChildren(graph, node, from, computeLayout)+ }+}++/**+ * The size each Hug frame had after layout last ran on it. Keyed by the node, so a deleted+ * frame's entry goes with it and a restored one starts afresh.+ */+const huggedSizes = new WeakMap<SceneNode, { width: number; height: number }>()++const CONSTRAINT_PARENT_TYPES: ReadonlySet<SceneNode['type']> = new Set([+ 'FRAME',+ 'COMPONENT',+ 'COMPONENT_SET',+ 'INSTANCE'+])++/**+ * Places the children of a frame layout resized by their constraints: every child of a frame+ * without auto layout, and those that ignore an auto layout, as Figma keeps a badge pinned to the+ * right of a Hug button while its label grows. A child it resizes places its own children, and+ * lays out again when it has auto layout.+ */+function constrainChildren(+ graph: SceneGraph,+ frame: SceneNode,+ before: { width: number; height: number },+ computeLayout: ComputeLayoutFn+): void {+ for (const child of graph.getChildren(frame.id)) {+ if (frame.layoutMode !== 'NONE' && child.layoutPositioning !== 'ABSOLUTE') continue+ const size = { width: child.width, height: child.height }+ writeLayoutGeometry(+ graph,+ child.id,+ layoutConstrainedChildRect(+ child,+ before,+ frame,+ child.horizontalConstraint,+ child.verticalConstraint+ ),+ computeLayout,+ undefined,+ true+ )+ const resized = child.width !== size.width || child.height !== size.height+ if (resized && child.layoutMode !== 'NONE') computeLayout(graph, child.id)+ }+}++/**+ * The size a frame's constrained children move from as it hugs, or null when it hugs no axis.+ * An editor that resizes a Hug frame places its children for the size it sets, which layout then+ * hugs back, as when a parent stretches it; its children move only from the size it last hugged+ * to. An axis it does not hug keeps the size it has.+ */+function hugStart(frame: SceneNode): { width: number; height: number } | null {+ const row = frame.layoutMode === 'HORIZONTAL'+ const hugsWidth = (row ? frame.primaryAxisSizing : frame.counterAxisSizing) === 'HUG'+ const hugsHeight = (row ? frame.counterAxisSizing : frame.primaryAxisSizing) === 'HUG'+ if (!hugsWidth && !hugsHeight) {+ huggedSizes.delete(frame)+ return null+ }+ const hugged = huggedSizes.get(frame)+ return {+ width: hugsWidth && hugged ? hugged.width : frame.width,+ height: hugsHeight && hugged ? hugged.height : frame.height+ }}function applyFrameSize(graph: SceneGraph,frame: SceneNode,yogaNode: YogaNode,- keepsSaved: boolean+ keepsSaved: boolean,+ computeLayout: ComputeLayoutFn): void {if (frame.layoutMode === 'GRID') {if (frame.gridTemplateRows.length === 0) {- writeLayoutGeometry(graph, frame.id, { height: yogaNode.getComputedHeight() })+ writeLayoutGeometry(graph, frame.id, { height: yogaNode.getComputedHeight() }, computeLayout)}return}- if (frame.primaryAxisSizing !== 'HUG' && frame.counterAxisSizing !== 'HUG') return+ const before = hugStart(frame)+ if (!before) returnconst updates: LayoutGeometry = {}const derived = keepsSaved ? frame.derivedLayout : null@@ -67,7 +155,8 @@ function applyFrameSize(: (derived?.[counter] ?? computed(counter))}- writeLayoutGeometry(graph, frame.id, updates)+ writeLayoutGeometry(graph, frame.id, updates, computeLayout, before)+ huggedSizes.set(frame, { width: frame.width, height: frame.height })}function computedChildPosition(@@ -119,7 +208,8 @@ function updateChildFromYoga(frame: SceneNode,child: SceneNode,yogaChild: YogaNode,- keepsSaved: boolean+ keepsSaved: boolean,+ computeLayout: ComputeLayoutFn): void {if (!child.visible || child.layoutPositioning === 'ABSOLUTE') return@@ -128,18 +218,29 @@ function updateChildFromYoga(savedFig && frame.source.format === 'fig' && (child.type === 'FRAME' || child.type === 'LINE')const preservesImportedPosition =preservesImportedFrameGeometry || (savedFig && Math.abs(child.rotation) > 0.001)- writeLayoutGeometry(graph, child.id, {- x: computedChildPosition(child, yogaChild, 'x', preservesImportedPosition, keepsSaved),- y: computedChildPosition(child, yogaChild, 'y', preservesImportedPosition, keepsSaved),- width: computedChildSize(child, yogaChild, 'width', preservesImportedFrameGeometry, keepsSaved),- height: computedChildSize(- child,- yogaChild,- 'height',- preservesImportedFrameGeometry,- keepsSaved- )- })+ writeLayoutGeometry(+ graph,+ child.id,+ {+ x: computedChildPosition(child, yogaChild, 'x', preservesImportedPosition, keepsSaved),+ y: computedChildPosition(child, yogaChild, 'y', preservesImportedPosition, keepsSaved),+ width: computedChildSize(+ child,+ yogaChild,+ 'width',+ preservesImportedFrameGeometry,+ keepsSaved+ ),+ height: computedChildSize(+ child,+ yogaChild,+ 'height',+ preservesImportedFrameGeometry,+ keepsSaved+ )+ },+ computeLayout+ )}function preservesImportedInstanceInternals(child: SceneNode): boolean {@@ -177,7 +278,7 @@ export function applyYogaLayout(computeLayout: ComputeLayoutFn): void {const keepsSaved = keepsSavedLayout(graph, frame)- applyFrameSize(graph, frame, yogaNode, keepsSaved)+ applyFrameSize(graph, frame, yogaNode, keepsSaved, computeLayout)const children = graph.getChildren(frame.id)let yogaIndex = 0@@ -186,7 +287,7 @@ export function applyYogaLayout(const yogaChild = yogaNode.getChild(yogaIndex)yogaIndex++- updateChildFromYoga(graph, frame, child, yogaChild, keepsSaved)+ updateChildFromYoga(graph, frame, child, yogaChild, keepsSaved, computeLayout)if (!child.visible) continueif (preservesImportedInstanceInternals(child)) continuediff --git a/packages/core/tests/layout/auto-layout/absolute-constraints.test.ts b/packages/core/tests/layout/auto-layout/absolute-constraints.test.tsnew file mode 100644index 000000000..eae510337--- /dev/null+++ b/packages/core/tests/layout/auto-layout/absolute-constraints.test.ts@@ -0,0 +1,225 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '#core/editor'+import { FigmaAPI } from '#core/figma-api'+import { SceneGraph } from '@open-pencil/scene-graph'++// Each case repeats a Figma desktop 126 plugin API script; the numbers are what Figma reported.+// Figma lays out as a script edits, while ours lays out when geometry is read, so the cases read+// a frame's size where Figma would already have laid it out.++function button(figma: FigmaAPI) {+ const frame = figma.createFrame()+ frame.layoutMode = 'HORIZONTAL'+ frame.paddingLeft = frame.paddingRight = 16+ frame.paddingTop = frame.paddingBottom = 12+ frame.layoutSizingHorizontal = 'HUG'+ frame.layoutSizingVertical = 'HUG'+ const label = figma.createRectangle()+ label.resize(60, 24)+ frame.appendChild(label)+ expect([frame.width, frame.height]).toEqual([92, 48])+ return { frame, label }+}++const CASES = {+ 'MAX/MIN': {+ grown: [183.25, 64, 167.5, -8.5, 24, 24],+ shrunk: [52, 48, 36.5, -8.5, 24, 24]+ },+ 'CENTER/CENTER': {+ grown: [183.25, 64, 122.5, -0.5, 24, 24],+ shrunk: [52, 48, 56.5, -8.5, 24, 24]+ },+ 'STRETCH/STRETCH': {+ grown: [183.25, 64, 76.5, -8.5, 115, 40],+ shrunk: [52, 48, 76.5, -8.5, 16, 24]+ },+ 'SCALE/SCALE': {+ grown: [183.25, 64, 152.375, -11.3359375, 47.804348, 32],+ shrunk: [52, 48, 43.2421875, -8.5, 13.565217, 24]+ },+ 'MIN/MAX': {+ grown: [183.25, 64, 76.5, 7.5, 24, 24],+ shrunk: [52, 48, 76.5, -8.5, 24, 24]+ }+} as const++describe('a layer that ignores auto layout follows its constraints as its Hug frame resizes', () => {+ for (const [name, expected] of Object.entries(CASES)) {+ test(name, () => {+ const figma = new FigmaAPI(new SceneGraph())+ const { frame, label } = button(figma)+ const badge = figma.createFrame()+ badge.resize(24, 24)+ frame.appendChild(badge)+ badge.layoutPositioning = 'ABSOLUTE'+ badge.x = frame.width - 15.5+ badge.y = -8.5+ const [horizontal, vertical] = name.split('/') as [ConstraintName, ConstraintName]+ badge.constraints = { horizontal, vertical }+ const read = () => [frame.width, frame.height, badge.x, badge.y, badge.width, badge.height]+ expect(read()).toEqual([92, 48, 76.5, -8.5, 24, 24])+ label.resize(151.25, 40)+ read().forEach((value, i) => expect(value).toBeCloseTo(expected.grown[i], 5))+ label.resize(20, 24)+ read().forEach((value, i) => expect(value).toBeCloseTo(expected.shrunk[i], 5))+ })+ }++ test('Right and Left & right move by the parent size rounded to whole pixels', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const rows: number[][] = []+ for (const horizontal of ['STRETCH', 'CENTER'] as const) {+ const { frame, label } = button(figma)+ frame.paddingTop = frame.paddingBottom = 12+ const badge = figma.createFrame()+ badge.resize(24.5, 24)+ frame.appendChild(badge)+ badge.layoutPositioning = 'ABSOLUTE'+ badge.x = 76.5+ badge.y = 0+ badge.constraints = { horizontal, vertical: 'MIN' }+ expect(badge.x).toBe(76.5)+ for (const width of [70.3, 71.9, 95.5, 60]) {+ label.resize(width, 24)+ rows.push([badge.x, badge.width])+ }+ }+ expect(rows).toEqual([+ [76.5, 34.5],+ [76.5, 36.5],+ [76.5, 60.5],+ [76.5, 24.5],+ [81.5, 24.5],+ [82.5, 24.5],+ [94.5, 24.5],+ [76.5, 24.5]+ ])+ })++ test('a Fill frame carries its badge when the row around it resizes', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const outer = figma.createFrame()+ outer.layoutMode = 'HORIZONTAL'+ outer.layoutSizingHorizontal = 'FIXED'+ outer.layoutSizingVertical = 'FIXED'+ outer.resize(200, 60)+ const inner = figma.createFrame()+ outer.appendChild(inner)+ inner.layoutMode = 'HORIZONTAL'+ inner.layoutSizingHorizontal = 'FILL'+ inner.layoutSizingVertical = 'FIXED'+ inner.resize(inner.width, 40)+ const badge = figma.createFrame()+ badge.resize(20, 20)+ inner.appendChild(badge)+ badge.layoutPositioning = 'ABSOLUTE'+ badge.x = inner.width - 12+ badge.y = -8+ badge.constraints = { horizontal: 'MAX', vertical: 'MIN' }+ expect(inner.width).toBe(200)+ const rows = [400, 150].map((width) => {+ outer.resize(width, 60)+ return [inner.width, badge.x]+ })+ expect(rows).toEqual([+ [400, 388],+ [150, 138]+ ])+ })++ test('a stretched overlay places its own children by their constraints', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const { frame, label } = button(figma)+ const overlay = figma.createFrame()+ frame.appendChild(overlay)+ overlay.layoutPositioning = 'ABSOLUTE'+ overlay.resize(100, 56)+ overlay.x = -4+ overlay.y = -4+ overlay.constraints = { horizontal: 'STRETCH', vertical: 'STRETCH' }+ const dot = figma.createRectangle()+ dot.resize(10, 10)+ overlay.appendChild(dot)+ dot.x = 80+ dot.y = 40+ dot.constraints = { horizontal: 'MAX', vertical: 'MAX' }+ expect(overlay.width).toBe(100)+ label.resize(160, 50)+ expect([frame.width, frame.height]).toEqual([192, 74])+ expect([overlay.x, overlay.y, overlay.width, overlay.height]).toEqual([-4, -4, 200, 82])+ expect([dot.x, dot.y]).toEqual([180, 66])+ })++ test('a stretched overlay with auto layout lays out again', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const { frame, label } = button(figma)+ const overlay = figma.createFrame()+ frame.appendChild(overlay)+ overlay.layoutPositioning = 'ABSOLUTE'+ overlay.x = -10+ overlay.y = 0+ overlay.layoutMode = 'HORIZONTAL'+ overlay.primaryAxisAlignItems = 'MAX'+ overlay.layoutSizingHorizontal = 'FIXED'+ overlay.layoutSizingVertical = 'FIXED'+ overlay.resize(112, 30)+ overlay.constraints = { horizontal: 'STRETCH', vertical: 'MIN' }+ const chip = figma.createRectangle()+ chip.resize(20, 20)+ overlay.appendChild(chip)+ expect(chip.x).toBe(92)+ label.resize(140, 24)+ expect([frame.width, overlay.x, overlay.width, chip.x]).toEqual([172, -10, 192, 172])+ })+})++type ConstraintName = 'MIN' | 'MAX' | 'CENTER' | 'STRETCH' | 'SCALE'++test('a frame resized by hand, then set to Hug, moves its badge from the size it was given', () => {+ const figma = new FigmaAPI(new SceneGraph())+ const { frame } = button(figma)+ frame.layoutSizingHorizontal = 'FIXED'+ frame.resize(200, 48)+ const badge = figma.createFrame()+ badge.resize(24, 24)+ frame.appendChild(badge)+ badge.layoutPositioning = 'ABSOLUTE'+ badge.x = 184+ badge.constraints = { horizontal: 'MAX', vertical: 'MIN' }+ expect(frame.width).toBe(200)+ frame.layoutSizingHorizontal = 'HUG'+ expect([frame.width, badge.x]).toEqual([92, 76])+})++test('a badge keeps its place through editing the label and undoing it', () => {+ const editor = createEditor()+ const { graph } = editor+ const frame = graph.createNode('FRAME', editor.state.currentPageId, {+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ paddingLeft: 16,+ paddingRight: 16,+ paddingTop: 12,+ paddingBottom: 12+ })+ const label = graph.createNode('RECTANGLE', frame.id, { width: 60, height: 24 })+ editor.runLayoutForNode(frame.id)+ const badge = graph.createNode('FRAME', frame.id, {+ x: 84,+ y: -8,+ width: 24,+ height: 24,+ layoutPositioning: 'ABSOLUTE',+ horizontalConstraint: 'MAX'+ })+ editor.updateNodeWithUndo(label.id, { width: 150 })+ expect([frame.width, badge.x]).toEqual([182, 174])+ editor.undoAction()+ expect([frame.width, badge.x]).toEqual([92, 84])+ editor.redoAction()+ expect([frame.width, badge.x]).toEqual([182, 174])+ editor.dispose()+})diff --git a/packages/scene-graph/src/resize.ts b/packages/scene-graph/src/resize.tsindex 31d6cbc3a..f3792711a 100644--- a/packages/scene-graph/src/resize.ts+++ b/packages/scene-graph/src/resize.ts@@ -84,6 +84,57 @@ export function constrainedChildRect(}}+function layoutConstrainedAxis(+ position: number,+ size: number,+ parentBefore: number,+ parentAfter: number,+ constraint: ConstraintType+): { position: number; size: number } {+ const delta = Math.round(parentAfter) - Math.round(parentBefore)+ if (constraint === 'MAX') return { position: position + delta, size }+ if (constraint === 'CENTER') {+ return { position: position + Math.round(parentAfter / 2) - Math.round(parentBefore / 2), size }+ }+ if (constraint === 'STRETCH') return { position, size: Math.abs(size + delta) }+ if (constraint === 'SCALE' && parentBefore > 0) {+ const scale = parentAfter / parentBefore+ return { position: Math.round(position * scale * 128) / 128, size: size * scale }+ }+ return { position, size }+}++/**+ * Where a child goes when layout resizes its parent, as Figma places a layer that ignores auto+ * layout when its Hug frame grows (measured on desktop 126): Right and Left & right move or grow+ * it by the change in the parent's size rounded to whole pixels, Center by the change in its+ * rounded half, and Scale by the exact ratio, its position to 1/128 of a pixel. Sizes are not+ * rounded, so applying a run of changes one at a time lands where applying them at once does.+ */+export function layoutConstrainedChildRect(+ child: Rect,+ parentBefore: Pick<Rect, 'width' | 'height'>,+ parentAfter: Pick<Rect, 'width' | 'height'>,+ horizontal: ConstraintType,+ vertical: ConstraintType+): Rect {+ const x = layoutConstrainedAxis(+ child.x,+ child.width,+ parentBefore.width,+ parentAfter.width,+ horizontal+ )+ 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 }+}+export function scaledChildRect(child: Rect,parentBefore: Pick<Rect, 'width' | 'height'>,diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex d61903f57..fb56eb071 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -21,7 +21,7 @@ import { createClickCounter } from '#vue/shared/input/click-count'import { handleDrawMove } from '#vue/shared/input/draw'import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move'import { setupPanZoom } from '#vue/shared/input/pan-zoom'-import { applyResize, commitResizePreview } from '#vue/shared/input/resize'+import { applyResize, cancelResizePreview, commitResizePreview } from '#vue/shared/input/resize'import { updateHoverCursor } from '#vue/shared/input/select'import { resolveShapeHandleHover } from '#vue/shared/input/shape-handles'import { useSpaceHeld } from '#vue/shared/input/space-key'@@ -433,6 +433,7 @@ export function useCanvasInput(}function cancelPointerInteraction() {+ if (drag.value?.type === 'resize') cancelResizePreview(drag.value, editor)if (drag.value?.type === 'rotate') {const rotation = drag.valuedrag.value = nulldiff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.tsindex 2c8a87c14..f9d1b5229 100644--- a/packages/vue/src/shared/input/resize.ts+++ b/packages/vue/src/shared/input/resize.ts@@ -8,11 +8,13 @@ import { calibratePathTextLayout, reflowPathTextGlyphs } from '@open-pencil/coreimport { cloneVectorNetwork } 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'import {computeConstrainedResizeChanges,scaledGeometryChanges,type ResizeSnapshot} from '@open-pencil/scene-graph/resize'+import { markSourceFieldsEdited } from '@open-pencil/scene-graph/source-metadata'import { calculateResizeRect } from '#vue/shared/input/resize/rect'import { applyResizeSnap } from '#vue/shared/input/resize/snap'@@ -146,6 +148,7 @@ export function applyResize(const d = toRaw(dragState)const { changes, newRect } = resizeChanges(d, cx, cy, constrain, editor, disableSnapping)d.appliedRect = { ...newRect }+ markResized(d, newRect, editor)if (d.origRect.width > 0 && d.origRect.height > 0) {const reflow = reflowedPathTextChanges({@@ -226,6 +229,69 @@ function clearResizedRawGeometry(editor: Editor, nodeId: string): void {if (node.type !== 'TEXT') delete raw.vectorData}+function sameRect(a: Rect, b: Rect): boolean {+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height+}++/**+ * Resizing keeps the raw payload a file gave the layer but not its size, so once the drag+ * changes the rect, layout lays out a resized frame from a .fig again, during the drag too,+ * instead of keeping the sizes it saved.+ */+function markResized(d: DragResize, rect: Rect, editor: Editor) {+ const node = editor.graph.getNode(d.nodeId)+ if (!node || d.origEditedFields || sameRect(rect, d.origRect)) return+ d.origEditedFields = [...node.source.editedFields]+ markSourceFieldsEdited(node, ['width', 'height'])+}++/** A drag that ends where it began, or is cancelled, leaves the layer's edits as they were. */+function restoreEditedFields(d: DragResize, editor: Editor) {+ const node = editor.graph.getNode(d.nodeId)+ if (node && d.origEditedFields) node.source.editedFields = d.origEditedFields+ d.origEditedFields = undefined+}++function restoreResizePreview(d: DragResize, editor: Editor) {+ editor.graph.updateNodePreview(d.nodeId, d.origRect)+ for (const [childId, orig] of d.origChildren ?? []) {+ editor.graph.updateNodePreview(childId, {+ x: orig.x,+ y: orig.y,+ width: orig.width,+ height: orig.height,+ vectorNetwork: orig.vectorNetwork,+ fillGeometry: orig.fillGeometry,+ strokeGeometry: orig.strokeGeometry,+ derivedTextGlyphs: orig.derivedTextGlyphs,+ strokes: orig.strokes,+ textPathData: orig.textPathData,+ textPathBox: orig.textPathBox+ })+ }+}++/** Puts a resize the pointer abandoned back where it started. */+export function cancelResizePreview(dragState: DragResize, editor: Editor) {+ const d = toRaw(dragState)+ optionalEditorState(editor)?.snapGuides.splice(0)+ restoreResizePreview(d, editor)+ // The preview scaled the layer's own geometry too, which a commit would have replaced.+ editor.graph.updateNodePreview(d.nodeId, {+ vectorNetwork: d.origVectorNetwork,+ fillGeometry: d.origFillGeometry,+ strokeGeometry: d.origStrokeGeometry,+ derivedTextGlyphs: d.origDerivedTextGlyphs,+ strokes: d.origStrokes,+ textPathData: d.origTextPathData,+ textPathBox: d.origTextPathBox+ })+ editor.renderer?.invalidateVectorPath(d.nodeId)+ restoreEditedFields(d, editor)+ editor.graph.runPreviewUpdates(() => computeAllLayouts(editor.graph, d.nodeId))+ editor.requestRender()+}+export function commitResizePreview(dragState: DragResize, editor: Editor) {// See applyResize — reactive drag state must not leak into graph writes.const d = toRaw(dragState)@@ -244,6 +310,7 @@ function commitResizeGeometry(d: DragResize, editor: Editor) {optionalEditorState(editor)?.snapGuides.splice(0)const node = editor.graph.getNode(d.nodeId)if (!node) return+ if (!d.appliedRect || sameRect(d.appliedRect, d.origRect)) restoreEditedFields(d, editor)const finalChanges = snapshotResizeFinal(node)if (d.origChildren) {@@ -253,22 +320,7 @@ function commitResizeGeometry(d: DragResize, editor: Editor) {if (!child) continuefinalChildren.set(childId, snapshotResizeFinal(child))}- editor.graph.updateNodePreview(d.nodeId, d.origRect)- for (const [childId, orig] of d.origChildren) {- editor.graph.updateNodePreview(childId, {- x: orig.x,- y: orig.y,- width: orig.width,- height: orig.height,- vectorNetwork: orig.vectorNetwork,- fillGeometry: orig.fillGeometry,- strokeGeometry: orig.strokeGeometry,- derivedTextGlyphs: orig.derivedTextGlyphs,- strokes: orig.strokes,- textPathData: orig.textPathData,- textPathBox: orig.textPathBox- })- }+ restoreResizePreview(d, editor)// Resize is geometric — the raw Figma import payload (vectorData,// textPathStart, effects, ...) must survive or path-text reflow works// exactly once and export fidelity degrades.diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex d3800bb9b..7e6086486 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -83,6 +83,8 @@ export interface DragResize {origTextPathBox: Rect | nullorigChildren: Map<string, ResizeSnapshot> | nullappliedRect?: Rect+ /** The layer's edited fields before the drag marked its size, to put back if it changes nothing. */+ origEditedFields?: string[]}export interface DragMarquee {diff --git a/packages/vue/tests/shared/input/resize.test.ts b/packages/vue/tests/shared/input/resize.test.tsnew file mode 100644index 000000000..4dad79bb8--- /dev/null+++ b/packages/vue/tests/shared/input/resize.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, cancelResizePreview, commitResizePreview } from '#vue/shared/input/resize'+import type { DragResize } from '#vue/shared/input/types'++function drag(node: SceneNode): DragResize {+ return {+ type: 'resize',+ handle: 'e',+ startX: node.width,+ startY: node.height / 2,+ origRect: { x: node.x, y: node.y, width: node.width, height: node.height },+ nodeId: node.id,+ origVectorNetwork: null,+ origFillGeometry: [],+ origStrokeGeometry: [],+ origDerivedTextGlyphs: null,+ origStrokes: [],+ origTextPathData: null,+ origTextPathBox: null,+ origChildren: null+ }+}++describe('resizing a frame read from a .fig file', () => {+ test('its Fill children fill the new size while dragging and after', () => {+ const editor = createEditor()+ try {+ const { graph } = editor+ const row = graph.createNode('FRAME', editor.state.currentPageId, {+ width: 200,+ height: 40,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'FIXED',+ counterAxisSizing: 'FIXED',+ paddingLeft: 10,+ paddingRight: 10+ })+ const field = graph.createNode('FRAME', row.id, {+ x: 10,+ width: 180,+ height: 40,+ layoutGrow: 1+ })+ for (const node of [row, field]) {+ graph.applyImportedStateDuring(() =>+ graph.updateNode(node.id, {+ source: { ...node.source, format: 'fig', id: node.id },+ derivedLayout: { x: node.x, y: node.y, width: node.width, height: node.height }+ })+ )+ }+ editor.runLayoutForNode(row.id)++ const resize = drag(row)+ applyResize(resize, 300, 20, false, editor, true)+ expect([row.width, field.width]).toEqual([300, 280])+ commitResizePreview(resize, editor)+ expect([row.width, field.width]).toEqual([300, 280])+ editor.undoAction()+ expect([row.width, field.width]).toEqual([200, 180])+ } finally {+ editor.dispose()+ }+ })+})++describe('a resize that changes nothing', () => {+ test('leaves a layer read from a .fig file unedited, whether released or cancelled', () => {+ const editor = createEditor()+ try {+ const { graph } = editor+ const frame = graph.createNode('FRAME', editor.state.currentPageId, { width: 200, height: 40 })+ graph.applyImportedStateDuring(() =>+ graph.updateNode(frame.id, { source: { ...frame.source, format: 'fig', id: frame.id } })+ )+ const press = drag(frame)+ applyResize(press, 200, 20, false, editor, true)+ commitResizePreview(press, editor)+ expect(frame.source.editedFields).toEqual([])++ const cancelled = drag(frame)+ applyResize(cancelled, 260, 20, false, editor, true)+ expect(frame.width).toBe(260)+ cancelResizePreview(cancelled, editor)+ expect([frame.width, frame.source.editedFields]).toEqual([200, []])+ } finally {+ editor.dispose()+ }+ })+})++test('a cancelled resize gives a vector back its own geometry', () => {+ const editor = createEditor()+ try {+ const network = {+ vertices: [+ { x: 0, y: 0 },+ { x: 100, y: 50 }+ ],+ segments: [+ { start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }+ ],+ regions: []+ }+ const vector = editor.graph.createNode('VECTOR', editor.state.currentPageId, {+ width: 100,+ height: 50,+ vectorNetwork: network+ })+ const resize = { ...drag(vector), origVectorNetwork: structuredClone(network) }+ applyResize(resize, 200, 25, false, editor, true)+ expect(vector.vectorNetwork?.vertices[1]?.x).toBe(200)+ cancelResizePreview(resize, editor)+ expect([vector.width, vector.vectorNetwork?.vertices[1]?.x]).toEqual([100, 100])+ } finally {+ editor.dispose()+ }+})diff --git a/src/app/editor/fonts/status.ts b/src/app/editor/fonts/status.tsindex abcda85d3..c9ad11d49 100644--- a/src/app/editor/fonts/status.ts+++ b/src/app/editor/fonts/status.ts@@ -48,7 +48,9 @@ export function useDocumentFontStatus() {}))editor.renderer?.invalidateAllPictures()- computeAllLayouts(editor.graph, editor.state.currentPageId)+ editor.graph.applyDerivedLayoutDuring(() =>+ computeAllLayouts(editor.graph, editor.state.currentPageId)+ )preparation.update({ phase: 'preparing-render' })editor.requestRender()if (editor.renderer) {