Skip to content

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

fix: auto layout undo, Hug and Fill sizing, and Ignore auto layout (#1057)

Danila Poyarkovf7ebd7493ccd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8e1ede1a..6fe2fd46d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -49,6 +49,7 @@
### Added
- 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.
- Round a rectangle's corners on the canvas, as in Figma: while the pointer is over a selected rectangle at least 108 screen pixels across, a handle sits inside each corner. Dragging one sets every corner while they are equal and only that corner while they differ, <kbd>⌥</kbd> swaps the two, and <kbd>⇧</kbd> rounds to tens; a label beside the pointer shows the radius.
- Comment on designs, as in Figma. Pick the **Comment** tool or press <kbd>C</kbd>, click the canvas, and type; the pin shows your avatar and stays on the top-level layer under it when that layer moves. Open a pin to reply, resolve, copy, or delete it. Comments take bold, italic, strikethrough, links, and numbered and bulleted lists, with Figma's shortcuts or Markdown, and Shift+Enter continues a list. While the Comment tool is active the right sidebar lists the document's threads with search, newest- or oldest-first order, and filters for resolved comments, your threads, and the current page; **View → Comments** (<kbd>⇧</kbd><kbd>C</kbd>), also in the zoom menu and a pin's right-click menu, hides pins outside the tool. Comments are saved in the document as OpenPencil plugin data, so they travel with the `.fig` file, its storage copy, and a collaboration room, comments two people add at the same time are both kept, and Figma and older versions of OpenPencil still open the file. Adding or resolving a comment marks the document as changed, but undo leaves comments alone. Scripts, the AI chat, and MCP clients can act on review feedback too: `openpencil.getComments()`, `addComment()`, and each comment's `reply()` and `resolve()` in `openpencil eval`, and the `get_comments`, `add_comment`, `reply_to_comment`, and `resolve_comment` tools.
- Edit a polygon's or star's corner radius, point count, and a star's inner ratio in the properties panel, as in Figma: **Count** from 3 to 60 and **Ratio** as a percentage.
@@ -164,6 +165,11 @@
- 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 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.
- A frame's name reads on the section it sits in: on a dark page, frames in a white section had white names on white. Names now fade more on light backgrounds than on dark ones, as Figma's do.
- `lineHeight` and `letterSpacing` in the plugin API and `eval` scripts read and write Figma's `{ unit, value }`, including percent of the font size and `{ unit: 'AUTO' }`; assigning those objects used to leave the text undrawn.
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index 755f4640d..2bfa1e35f 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -7,6 +7,11 @@ import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/c
import { ownsSlotContent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'
+import {
+ collectComponentPropertyIds,
+ firstUnclaimedLocalId,
+ layerSourceGuids
+} from '#core/io/formats/fig/export-setup'
import {
appendVariableNodeChanges,
assignSharedStyleGuids,
@@ -64,7 +69,10 @@ async function writeFigmaClipboardHTML(
const docGuid = { sessionID: 0, localID: 0 }
const canvasGuid = { sessionID: 0, localID: 1 }
- const localIdCounter = { value: 100 }
+ // Above every GUID the graph claims, as the document exporter starts, so no record collides.
+ const localIdCounter = {
+ value: Math.max(100, firstUnclaimedLocalId(graph, collectComponentPropertyIds(graph)))
+ }
const nodeChanges: KiwiNodeChange[] = [
makeDocumentNodeChange(docGuid, graph.documentColorSpace),
@@ -85,7 +93,14 @@ async function writeFigmaClipboardHTML(
const blobs: Uint8Array[] = []
const variableIds = new Map<string, GUID>()
const modeIds = new Map<string, GUID>()
- assignVariableGuids(graph, localIdCounter, variableIds, modeIds, assignedGuidValues, new Set())
+ assignVariableGuids(
+ graph,
+ localIdCounter,
+ variableIds,
+ modeIds,
+ assignedGuidValues,
+ layerSourceGuids(graph)
+ )
assignSharedStyleGuids(
[...graph.nodes.values()].filter((node) => node.sharedStyleType !== null),
localIdCounter,
diff --git a/packages/core/src/editor/alignment.ts b/packages/core/src/editor/alignment.ts
index 8fa348260..b55013f35 100644
--- a/packages/core/src/editor/alignment.ts
+++ b/packages/core/src/editor/alignment.ts
@@ -6,7 +6,7 @@ import type { Vector } from '@open-pencil/scene-graph/primitives'
import { createFlipRotateActions } from '#core/editor/alignment/flip-rotate'
-import { collectNodePositions, pushPositionUndo } from './history/position'
+import { collectNodePositions, commitPositionChange } from './history/position'
import type { EditorContext } from './types'
function computeAlignTarget(
@@ -208,8 +208,7 @@ export function createAlignmentActions(ctx: EditorContext) {
})
cursor += span.max - span.min + gap
}
- pushPositionUndo(ctx, 'Change spacing', originals, collectNodePositions(ctx, originals.keys()))
- for (const node of nodes) ctx.runLayoutForNode(node.id)
+ commitPositionChange(ctx, 'Change spacing', originals)
ctx.requestRender()
}
@@ -243,10 +242,7 @@ export function createAlignmentActions(ctx: EditorContext) {
alignMultipleNodes(ctx, nodes, axis, align)
}
- const finals = collectNodePositions(ctx, originals.keys())
- pushPositionUndo(ctx, 'Align', originals, finals)
-
- for (const id of nodeIds) ctx.runLayoutForNode(id)
+ commitPositionChange(ctx, 'Align', originals)
ctx.requestRender()
}
@@ -261,10 +257,7 @@ export function createAlignmentActions(ctx: EditorContext) {
nodes.map((node) => node.id)
)
distributeMultipleNodes(ctx, nodes, axis)
- const finals = collectNodePositions(ctx, originals.keys())
- pushPositionUndo(ctx, 'Distribute', originals, finals)
-
- for (const id of nodeIds) ctx.runLayoutForNode(id)
+ commitPositionChange(ctx, 'Distribute', originals)
ctx.requestRender()
}
diff --git a/packages/core/src/editor/history/position.ts b/packages/core/src/editor/history/position.ts
index 1e6aefb24..536d4c007 100644
--- a/packages/core/src/editor/history/position.ts
+++ b/packages/core/src/editor/history/position.ts
@@ -27,6 +27,24 @@ export function pushPositionUndo(
})
}
+/**
+ * Lays the moved layers out, then records one undo step from `originals` to where they ended up.
+ * Layers an auto layout holds in place snap back, so an edit that moves nothing records nothing.
+ */
+export function commitPositionChange(
+ ctx: EditorContext,
+ label: string,
+ originals: Map<string, Vector>
+): void {
+ for (const id of originals.keys()) ctx.runLayoutForNode(id)
+ const finals = collectNodePositions(ctx, originals.keys())
+ const moved = [...finals].some(([id, place]) => {
+ const before = originals.get(id)
+ return !before || before.x !== place.x || before.y !== place.y
+ })
+ if (moved) pushPositionUndo(ctx, label, originals, finals)
+}
+
function applyPositions(ctx: EditorContext, positions: Map<string, Vector>): void {
for (const [id, pos] of positions) {
ctx.graph.updateNode(id, pos)
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index f7df0b556..af860a3d2 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -9,6 +9,7 @@ export type { SnappingPreferences } from './preferences'
export { createDefaultEditorSharedState } from './state/shared'
export { editedGradient, editedGradientLayout } from './gradient-edit'
export type { SelectionSpacing } from './alignment'
+export type { MovePlace } from './undo'
export {
replaceSelectionColor,
selectionColors,
diff --git a/packages/core/src/editor/layout-mode.ts b/packages/core/src/editor/layout-mode.ts
index 42f7e9c5f..28b932c11 100644
--- a/packages/core/src/editor/layout-mode.ts
+++ b/packages/core/src/editor/layout-mode.ts
@@ -1,67 +1,55 @@
-import { pick } from 'es-toolkit/object'
-
import type { LayoutMode, SceneNode } from '@open-pencil/scene-graph'
-import { computeLayout } from '#core/layout'
-
+import type { NodePreview } from './node-preview'
import type { EditorContext } from './types'
-export function createLayoutModeActions(ctx: EditorContext) {
+export function createLayoutModeActions(
+ ctx: EditorContext,
+ beginNodePreview: (label: string) => NodePreview
+) {
+ /**
+ * Adding, switching, or removing auto layout moves and resizes children, nested layouts, and
+ * Hug ancestors. A node preview records every layer it changes, so one undo puts them all back
+ * where they were; setting the mode a frame already has records nothing.
+ */
function setLayoutMode(id: string, mode: LayoutMode) {
const node = ctx.graph.getNode(id)
- if (!node) return
-
- const previous = captureLayoutState(node)
- const updates = layoutModeUpdates(ctx, node, id, mode)
-
- ctx.graph.updateNode(id, updates)
- if (mode !== 'NONE') computeLayout(ctx.graph, id)
- ctx.runLayoutForNode(id)
-
- const updated = ctx.graph.getNode(id)
- if (!updated) return
- const finalState = pickState(updated, Object.keys(previous) as (keyof SceneNode)[])
-
- ctx.undo.push({
- label: mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout',
- forward: () => {
- ctx.graph.updateNode(id, finalState)
- if (mode !== 'NONE') computeLayout(ctx.graph, id)
- ctx.runLayoutForNode(id)
- },
- inverse: () => {
- ctx.graph.updateNode(id, previous)
- ctx.runLayoutForNode(id)
- }
- })
+ if (!node || node.layoutMode === mode) return
+ const preview = beginNodePreview(mode === 'NONE' ? 'Remove auto layout' : 'Add auto layout')
+ preview.update(id, layoutModeUpdates(ctx, node, id, mode))
+ preview.commit()
}
- return { setLayoutMode }
-}
-
-function captureLayoutState(node: SceneNode): Partial<SceneNode> {
- return {
- layoutMode: node.layoutMode,
- itemSpacing: node.itemSpacing,
- paddingTop: node.paddingTop,
- paddingRight: node.paddingRight,
- paddingBottom: node.paddingBottom,
- paddingLeft: node.paddingLeft,
- primaryAxisSizing: node.primaryAxisSizing,
- counterAxisSizing: node.counterAxisSizing,
- primaryAxisAlign: node.primaryAxisAlign,
- counterAxisAlign: node.counterAxisAlign,
- gridTemplateColumns: node.gridTemplateColumns,
- gridTemplateRows: node.gridTemplateRows,
- gridColumnGap: node.gridColumnGap,
- gridRowGap: node.gridRowGap,
- width: node.width,
- height: node.height
+ /**
+ * Takes layers out of their parent's auto layout or puts them back, as Figma's Ignore auto
+ * layout toggle does. A layer taken out stays where it is and keeps its sizing, which applies
+ * again when it returns; its siblings close the gap in the same undo step.
+ */
+ function setLayoutPositioning(ids: string[], positioning: SceneNode['layoutPositioning']) {
+ // Read every place first: taking one layer out moves the siblings after it.
+ const targets = ids.flatMap((id) => {
+ const node = ctx.graph.getNode(id)
+ const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined
+ if (!node || !parent || parent.layoutMode === 'NONE') return []
+ if (node.layoutPositioning === positioning) return []
+ return [{ id, x: node.x, y: node.y }]
+ })
+ if (targets.length === 0) return
+ const preview = beginNodePreview(
+ positioning === 'ABSOLUTE' ? 'Ignore auto layout' : 'Use auto layout'
+ )
+ for (const { id, x, y } of targets) {
+ preview.update(
+ id,
+ positioning === 'ABSOLUTE'
+ ? { layoutPositioning: positioning, x, y }
+ : { layoutPositioning: positioning }
+ )
+ }
+ preview.commit()
}
-}
-function pickState(node: SceneNode, keys: (keyof SceneNode)[]): Partial<SceneNode> {
- return pick(node, keys) as Partial<SceneNode>
+ return { setLayoutMode, setLayoutPositioning }
}
function layoutModeUpdates(
diff --git a/packages/core/src/editor/node-preview.ts b/packages/core/src/editor/node-preview.ts
index 24fc04725..3a669ed8c 100644
--- a/packages/core/src/editor/node-preview.ts
+++ b/packages/core/src/editor/node-preview.ts
@@ -1,4 +1,4 @@
-import { isEqual, pick } from 'es-toolkit'
+import { isEqual, pick, uniq } from 'es-toolkit'
import type { SceneNode } from '@open-pencil/scene-graph'
@@ -29,13 +29,17 @@ export function createNodePreviewActions(
const originals = new Map<string, Partial<SceneNode>>()
const targets = new Set<string>()
const layoutOnly = new Set<string>()
+ const editedBefore = new Map<string, string[]>()
let closed = false
let endInteraction: (() => void) | undefined
const subscriptions: Array<() => void> = []
function capture(node: SceneNode, changes: Partial<SceneNode>) {
if (!originals.has(node.id) && graph.isApplyingLayout) layoutOnly.add(node.id)
- if (!graph.isApplyingLayout) layoutOnly.delete(node.id)
+ if (!graph.isApplyingLayout) {
+ layoutOnly.delete(node.id)
+ markEdited(node, changes)
+ }
const previous = originals.get(node.id) ?? {}
const keys = (Object.keys(changes) as (keyof SceneNode)[]).filter(
(key) => !Object.hasOwn(previous, key)
@@ -44,6 +48,14 @@ export function createNodePreviewActions(
originals.set(node.id, previous)
}
+ // Fields count as edited while previewed, as a committed edit marks them, so the preview's
+ // own layout stops keeping geometry a file saved; cancel takes the marks back.
+ function markEdited(node: SceneNode, changes: Partial<SceneNode>) {
+ if (graph.isPreservingSourceMetadata) return
+ if (!editedBefore.has(node.id)) editedBefore.set(node.id, node.source.editedFields)
+ node.source.editedFields = uniq([...node.source.editedFields, ...Object.keys(changes)])
+ }
+
function close() {
closed = true
for (const stop of subscriptions) stop()
@@ -106,6 +118,10 @@ export function createNodePreviewActions(
close()
for (const [id, previous] of originals)
graph.updateNodePreview(id, structuredClone(previous))
+ for (const [id, fields] of editedBefore) {
+ const node = graph.getNode(id)
+ if (node) node.source.editedFields = fields
+ }
// Reconcile retained/tiled resources once; cancellation publishes no committed node edits.
if (originals.size) ctx.requestRender()
}
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index ec20c7385..33595fb4e 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -28,7 +28,9 @@ export function opacityFromBuffer(buffer: string): number {
}
export function createNodeActions(ctx: EditorContext) {
- const layoutModeActions = createLayoutModeActions(ctx)
+ // Function declarations below are hoisted, so the preview can wrap updateNode here.
+ const previewActions = createNodePreviewActions(ctx, updateNode)
+ const layoutModeActions = createLayoutModeActions(ctx, previewActions.beginNodePreview)
const nudgeActions = createNudgeActions(ctx)
const variableBindingActions = createVariableBindingActions(ctx)
@@ -113,7 +115,7 @@ export function createNodeActions(ctx: EditorContext) {
return {
updateNode,
- ...createNodePreviewActions(ctx, updateNode),
+ ...previewActions,
updateNodeWithUndo,
setOpacity,
...layoutModeActions,
diff --git a/packages/core/src/editor/structure/auto-layout-wrap.ts b/packages/core/src/editor/structure/auto-layout-wrap.ts
index d5fbacd2d..cc110e164 100644
--- a/packages/core/src/editor/structure/auto-layout-wrap.ts
+++ b/packages/core/src/editor/structure/auto-layout-wrap.ts
@@ -1,24 +1,40 @@
import type { LayoutMode, SceneNode } from '@open-pencil/scene-graph'
import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
import { wrapParentId } from '#core/editor/structure/container-wrap'
import type { EditorContext } from '#core/editor/types'
import { computeLayout } from '#core/layout'
-/** Wrap sibling layers in a new auto layout frame; returns the frame, or null if they are not siblings. */
+/** The place and size of each layer and everything inside it, which the new layout can change. */
+function captureGeometry(ctx: EditorContext, nodes: SceneNode[]): Map<string, Rect> {
+ const geometry = new Map<string, Rect>()
+ const visit = (node: SceneNode) => {
+ geometry.set(node.id, { x: node.x, y: node.y, width: node.width, height: node.height })
+ for (const child of ctx.graph.getChildren(node.id)) visit(child)
+ }
+ for (const node of nodes) visit(node)
+ return geometry
+}
+
+/**
+ * Wrap sibling layers in a new auto layout frame; returns the frame, or null if they are not
+ * siblings. The frame takes the slot of the topmost selected layer, as Figma places a new group,
+ * and undo puts every layer back in its old slot, place, and size.
+ */
export function wrapInAutoLayout(ctx: EditorContext, selectedNodes: SceneNode[]): string | null {
- const parentId = wrapParentId(ctx, selectedNodes)
- if (!parentId) return null
+ const wrapParent = wrapParentId(ctx, selectedNodes)
+ const parent = wrapParent ? ctx.graph.getNode(wrapParent) : undefined
+ if (!parent) return null
+ const parentId = parent.id
const prevSelection = new Set(ctx.state.selectedIds)
- const origPositions = selectedNodes.map((n) => ({ id: n.id, x: n.x, y: n.y, parentId }))
-
+ const order = [...parent.childIds]
+ const geometry = captureGeometry(ctx, selectedNodes)
const bounds = getAxisAlignedBoundsInParent(selectedNodes, parentId, ctx.graph)
-
const direction: LayoutMode =
selectedNodes.length <= 1 || bounds.height > bounds.width ? 'VERTICAL' : 'HORIZONTAL'
-
- const frame = ctx.graph.createNode('FRAME', parentId, {
+ const frameFields: Partial<SceneNode> = {
name: 'Frame',
x: bounds.x,
y: bounds.y,
@@ -30,37 +46,40 @@ export function wrapInAutoLayout(ctx: EditorContext, selectedNodes: SceneNode[])
primaryAxisAlign: 'MIN',
counterAxisAlign: 'MIN',
fills: []
- })
- const frameId = frame.id
-
+ }
+ // In reading order inside the new frame.
const sortedIds = selectedNodes
.map((n) => ({ id: n.id, pos: ctx.graph.getAbsolutePosition(n.id) }))
.sort((a, b) => a.pos.y - b.pos.y || a.pos.x - b.pos.x)
.map((n) => n.id)
+ // Just above the topmost selected layer, before the selected layers move into the frame.
+ const slot = Math.max(...selectedNodes.map((n) => order.indexOf(n.id))) + 1
- for (const id of sortedIds) {
- ctx.graph.reparentNode(id, frameId)
+ function wrap(frameId?: string): string {
+ const frame = ctx.graph.createNode('FRAME', parentId, {
+ ...frameFields,
+ ...(frameId ? { id: frameId } : {})
+ })
+ ctx.graph.insertChildAt(frame.id, parentId, slot)
+ for (const id of sortedIds) ctx.graph.reparentNode(id, frame.id)
+ computeLayout(ctx.graph, frame.id)
+ ctx.runLayoutForNode(frame.id)
+ ctx.setSelectedIds(new Set([frame.id]))
+ return frame.id
}
- computeLayout(ctx.graph, frameId)
- ctx.runLayoutForNode(frameId)
- ctx.setSelectedIds(new Set([frameId]))
-
+ const frameId = wrap()
ctx.undo.push({
label: 'Wrap in auto layout',
forward: () => {
- const f = ctx.graph.createNode('FRAME', parentId, { ...frame, id: frameId })
- for (const n of origPositions) ctx.graph.reparentNode(n.id, f.id)
- computeLayout(ctx.graph, f.id)
- ctx.runLayoutForNode(f.id)
- ctx.setSelectedIds(new Set([f.id]))
+ wrap(frameId)
},
inverse: () => {
- for (const orig of origPositions) {
- ctx.graph.reparentNode(orig.id, orig.parentId)
- ctx.graph.updateNode(orig.id, { x: orig.x, y: orig.y })
- }
+ for (const id of sortedIds) ctx.graph.reparentNode(id, parentId)
ctx.graph.deleteNode(frameId)
+ order.forEach((id, index) => ctx.graph.reorderChild(id, parentId, index))
+ for (const [id, rect] of geometry) ctx.graph.updateNode(id, rect)
+ ctx.runLayoutForNode(parentId)
ctx.setSelectedIds(prevSelection)
}
})
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index a6debf738..ca82200a3 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -6,6 +6,7 @@ import {
} from '@open-pencil/scene-graph'
import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/copy'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
import { weightToStyle } from '#core/text/fonts'
import { hasGlyphOutlines } from '#core/text/opentype'
@@ -104,10 +105,22 @@ function applyTextInstanceOverride(
export function createTextActions(ctx: EditorContext) {
let activeSession: TextEditSession | null = null
+ /**
+ * Typing resizes auto-sized text and lays out its auto-layout ancestors as it goes, so a Hug
+ * frame grows with its label while it is edited, as in Figma. A size in `changes`, measured
+ * from the edit's own paragraph, wins over the measurement. A keystroke that leaves the text's
+ * size as it was lays nothing out.
+ */
function updateTextEditNode(nodeId: string, changes: Partial<SceneNode>) {
const node = ctx.graph.getNode(nodeId)
if (!node) return
- ctx.graph.updateNode(nodeId, { ...changes, ...pathTextEditChanges(node, changes) })
+ const { width, height } = node
+ ctx.graph.updateNode(nodeId, {
+ ...textAutoResizeChanges(node, changes),
+ ...changes,
+ ...pathTextEditChanges(node, changes)
+ })
+ if (node.width !== width || node.height !== height) ctx.runLayoutForNode(nodeId)
}
function startTextEditing(nodeId: string) {
@@ -191,6 +204,7 @@ export function createTextActions(ctx: EditorContext) {
...afterPathText
})
restoreInstanceOverrides(ctx, instanceOverridesAfter)
+ ctx.runLayoutForNode(result.nodeId)
},
inverse: () => {
ctx.graph.updateNode(result.nodeId, {
@@ -200,6 +214,7 @@ export function createTextActions(ctx: EditorContext) {
...beforePathText
})
restoreInstanceOverrides(ctx, instanceOverridesBefore)
+ ctx.runLayoutForNode(result.nodeId)
}
})
if (before.text !== after.text) applyBoundTextEdit(ctx, result.nodeId, after.text)
diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.ts
index ad9c3ae6e..a8736c1db 100644
--- a/packages/core/src/editor/undo.ts
+++ b/packages/core/src/editor/undo.ts
@@ -23,6 +23,9 @@ import {
} from './history/snapshot'
import type { EditorContext } from './types'
+/** A layer's place for a move: position, parent, and slot among the parent's children. */
+export type MovePlace = { x: number; y: number; parentId: string; index?: number }
+
type ResizeOriginal = Rect &
Partial<
Pick<
@@ -79,31 +82,38 @@ export function createUndoActions(ctx: EditorContext) {
pushPositionUndo(ctx, 'Move', originals, collectNodePositions(ctx, originals.keys()))
}
- function commitMoveWithReparent(
- originals: Map<string, { x: number; y: number; parentId: string }>
- ) {
+ /**
+ * Records a move that may change parents. Undo and redo put each layer back in its parent at
+ * the slot it had, lowest slot first, so siblings keep their order.
+ */
+ function commitMoveWithReparent(originals: Map<string, MovePlace>) {
for (const id of originals.keys()) assertNodeEditable(ctx.graph, id)
- const finals = new Map<string, { x: number; y: number; parentId: string }>()
+ const finals = new Map<string, MovePlace>()
for (const [id] of originals) {
const n = ctx.graph.getNode(id)
- if (n) finals.set(id, { x: n.x, y: n.y, parentId: n.parentId ?? ctx.state.currentPageId })
+ if (!n) continue
+ const parentId = n.parentId ?? ctx.state.currentPageId
+ finals.set(id, {
+ x: n.x,
+ y: n.y,
+ parentId,
+ index: ctx.graph.getNode(parentId)?.childIds.indexOf(id)
+ })
+ }
+ const place = (places: Map<string, MovePlace>) => {
+ const ordered = [...places].sort(([, a], [, b]) => (a.index ?? 0) - (b.index ?? 0))
+ for (const [id, pos] of ordered) {
+ ctx.graph.reparentNode(id, pos.parentId)
+ if (pos.index !== undefined && pos.index >= 0)
+ ctx.graph.reorderChild(id, pos.parentId, pos.index)
+ ctx.graph.updateNode(id, { x: pos.x, y: pos.y })
+ }
+ for (const id of places.keys()) ctx.runLayoutForNode(id)
}
ctx.undo.push({
label: 'Move',
- forward: () => {
- for (const [id, pos] of finals) {
- ctx.graph.reparentNode(id, pos.parentId)
- ctx.graph.updateNode(id, { x: pos.x, y: pos.y })
- ctx.runLayoutForNode(id)
- }
- },
- inverse: () => {
- for (const [id, pos] of originals) {
- ctx.graph.reparentNode(id, pos.parentId)
- ctx.graph.updateNode(id, { x: pos.x, y: pos.y })
- ctx.runLayoutForNode(id)
- }
- }
+ forward: () => place(finals),
+ inverse: () => place(originals)
})
}
diff --git a/packages/core/src/figma-api/accessors/visual.ts b/packages/core/src/figma-api/accessors/visual.ts
index b2ba6180f..e035af7b1 100644
--- a/packages/core/src/figma-api/accessors/visual.ts
+++ b/packages/core/src/figma-api/accessors/visual.ts
@@ -1,4 +1,11 @@
-import { newStrokeGeometry, type Fill, type SceneNode, type Stroke } from '@open-pencil/scene-graph'
+import {
+ newStrokeGeometry,
+ type Color,
+ type Fill,
+ type GradientStop,
+ type SceneNode,
+ type Stroke
+} from '@open-pencil/scene-graph'
import { normalizeColor } from '@open-pencil/scene-graph/color'
import { copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
@@ -29,6 +36,28 @@ function paintDefaults(paint: Partial<Pick<Fill, 'opacity' | 'visible'>>) {
return { opacity: paint.opacity ?? 1, visible: paint.visible ?? true }
}
+/** A colour as Figma's plugin API takes it, RGB with an optional alpha. */
+type FigmaColor = Omit<Color, 'a'> & Partial<Pick<Color, 'a'>>
+
+/** A paint as Figma's plugin API takes it: RGB colours, optional opacity and visibility. */
+export type FigmaPaint = Omit<Fill, 'color' | 'opacity' | 'visible' | 'gradientStops'> &
+ Partial<Pick<Fill, 'opacity' | 'visible'>> & {
+ color?: FigmaColor
+ gradientStops?: Array<Omit<GradientStop, 'color'> & { color: FigmaColor }>
+ }
+
+export function figmaPaintToFill(fill: FigmaPaint): Fill {
+ return {
+ ...fill,
+ ...paintDefaults(fill),
+ color: normalizeColor(fill.color),
+ gradientStops: fill.gradientStops?.map((stop) => ({
+ ...stop,
+ color: normalizeColor(stop.color)
+ }))
+ }
+}
+
export function installVisualNodeProxyAccessors(
prototype: object,
internals: NodeProxyInternals,
@@ -40,17 +69,7 @@ export function installVisualNodeProxyAccessors(
return Object.freeze(copyFills(raw(this, internals).fills))
},
set(this: ProxyThis, value: readonly Fill[]) {
- updateNode(this, internals, {
- fills: value.map((fill) => ({
- ...fill,
- ...paintDefaults(fill),
- color: normalizeColor(fill.color),
- gradientStops: fill.gradientStops?.map((stop) => ({
- ...stop,
- color: normalizeColor(stop.color)
- }))
- }))
- })
+ updateNode(this, internals, { fills: value.map(figmaPaintToFill) })
}
},
strokes: {
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index a6750b29d..300994ef2 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -31,7 +31,11 @@ import {
type FigmaVectorNetwork,
type FigmaVectorPath
} from './accessors/vector'
-import { installVisualNodeProxyAccessors } from './accessors/visual'
+import {
+ figmaPaintToFill,
+ installVisualNodeProxyAccessors,
+ type FigmaPaint
+} from './accessors/visual'
import { installComponentPropertyAccessors } from './components'
import type { FigmaFontName } from './fonts'
import type { FigmaFrameNode, FigmaInstanceNode } from './node-types'
@@ -227,8 +231,8 @@ export class FigmaNodeProxy {
return getPageBackgrounds(this._raw())
}
- set backgrounds(value: readonly Fill[]) {
- setPageBackgrounds(this[INTERNAL_GRAPH], this._raw(), value)
+ set backgrounds(value: readonly FigmaPaint[]) {
+ setPageBackgrounds(this[INTERNAL_GRAPH], this._raw(), value.map(figmaPaintToFill))
}
/** The async form Figma requires in dynamic-page mode; same result as mainComponent. */
diff --git a/packages/core/src/io/formats/fig/export-setup.ts b/packages/core/src/io/formats/fig/export-setup.ts
index 791b8bb28..ccca397c8 100644
--- a/packages/core/src/io/formats/fig/export-setup.ts
+++ b/packages/core/src/io/formats/fig/export-setup.ts
@@ -121,7 +121,8 @@ function assignOwnLayerGuids(
* The first local ID the counter can mint in sessions 0 and 1: past every saved GUID and every
* ID that layers, collections, modes, variables and component properties are saved under.
*/
-function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly string[]): number {
+/** The first local ID above every GUID the graph's layers, variables, and properties claim. */
+export function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly string[]): number {
const ids = [...propertyIds]
for (const node of graph.nodes.values()) ids.push(node.source.id || node.id)
for (const [collectionId, collection] of graph.variableCollections) {
@@ -137,7 +138,16 @@ function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly string[]
return last + 1
}
-function collectComponentPropertyIds(graph: SceneGraph): string[] {
+/** The GUIDs layers keep from the file they were read from, which variables must not take. */
+export function layerSourceGuids(graph: SceneGraph): Set<string> {
+ const guids = new Set<string>()
+ for (const node of graph.nodes.values()) {
+ if (node.source.id) guids.add(node.source.id)
+ }
+ return guids
+}
+
+export function collectComponentPropertyIds(graph: SceneGraph): string[] {
const ids = new Set<string>()
for (const node of graph.getAllNodes()) {
for (const definition of node.componentPropertyDefinitions) ids.add(definition.id)
@@ -379,10 +389,7 @@ export async function prepareFigExport(
const modeIdToGuid = new Map<string, GUID>()
const propertyIdToGuid = new Map<string, GUID>()
- const nodeSourceGuidValues = new Set<string>()
- for (const node of graph.nodes.values()) {
- if (node.source.id) nodeSourceGuidValues.add(node.source.id)
- }
+ const nodeSourceGuidValues = layerSourceGuids(graph)
const propertyIds = collectComponentPropertyIds(graph)
// Before any canvas, variable or layer takes a counter GUID, so none collides.
localIdCounter.value = Math.max(
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 8c6d94297..2d96f632b 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -15,12 +15,15 @@ import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direct
import { applyYogaLayout } from './layout/apply'
import {
+ asFlatLeaf,
+ asLaidOutIn,
fillKeepsSizeInHuggingParent,
+ heldHugAxis,
ownAxisSizing,
setCrossAxisSizing,
setMainAxisSizing
} from './layout/axis-sizing'
-import { usesDetachedDerivedLayout } from './layout/derived'
+import { keepsSavedLayout, usesDetachedDerivedLayout } from './layout/derived'
import { applyEffectiveGeneratedTextLayout } from './layout/effective-generated-text'
import { buildGridTree, createGridChildNode } from './layout/grid'
import { sizeAutoResizingText } from './layout/text-auto-resize'
@@ -153,10 +156,13 @@ function buildYogaTree(
const stretchedAxis = parentStretchedAxis(graph, frame)
if (stretchedAxis === 'width') root.setWidth(frame.width)
if (stretchedAxis === 'height') root.setHeight(frame.height)
+ const heldAxis = heldHugAxis(graph, frame)
+ if (heldAxis === 'width') root.setWidth(frame.width)
+ if (heldAxis === 'height') root.setHeight(frame.height)
configureFlexContainer(root, frame, direction)
- const children = graph.getChildren(frame.id)
+ const children = graph.getChildren(frame.id).map((child) => asLaidOutIn(graph, child, frame))
for (const child of children) {
const yogaChild = createYogaNode()
@@ -307,6 +313,7 @@ function derivedMainAxisFitsParent(
child: SceneNode,
axis: 'width' | 'height'
): boolean {
+ if (!keepsSavedLayout(graph, parent)) return false
const children = graph
.getChildren(parent.id)
.filter((candidate) => candidate.visible && candidate.layoutPositioning !== 'ABSOLUTE')
@@ -362,7 +369,7 @@ function configureChildAsAutoLayout(
const selfAlign = mapAlignSelf(child.layoutAlignSelf)
if (selfAlign != null) yogaChild.setAlignSelf(selfAlign)
- if (usesDetachedDerivedLayout(child)) {
+ if (usesDetachedDerivedLayout(graph, child)) {
// The imported size is what the child's own hug produced, whether or not it also fills.
const derived = child.derivedLayout
if (ownAxisSizing(child, 'width') === 'HUG') yogaChild.setWidth(derived?.width ?? child.width)
@@ -374,8 +381,11 @@ function configureChildAsAutoLayout(
}
configureFlexContainer(yogaChild, child, direction)
+ const heldAxis = heldHugAxis(graph, child)
+ if (heldAxis === 'width' && widthSizing === 'HUG') yogaChild.setWidth(child.width)
+ if (heldAxis === 'height' && heightSizing === 'HUG') yogaChild.setHeight(child.height)
- const grandchildren = graph.getChildren(child.id)
+ const grandchildren = graph.getChildren(child.id).map((gc) => asLaidOutIn(graph, gc, child))
for (const gc of grandchildren) {
const yogaGC = createYogaNode()
if (gc.layoutPositioning === 'ABSOLUTE') {
@@ -469,10 +479,11 @@ function configureTextLeafWithoutMeasurer(
function configureChildAsLeaf(
yogaChild: YogaNode,
- child: SceneNode,
+ node: SceneNode,
parent: SceneNode,
graph: SceneGraph
): void {
+ const child = asFlatLeaf(node, parent)
const isRow = parent.layoutMode === 'HORIZONTAL'
const selfOverride = child.layoutAlignSelf !== 'AUTO'
const stretchCross = selfOverride
diff --git a/packages/core/src/layout/apply.ts b/packages/core/src/layout/apply.ts
index f9e411f95..9f0584b0a 100644
--- a/packages/core/src/layout/apply.ts
+++ b/packages/core/src/layout/apply.ts
@@ -2,7 +2,7 @@ import type { Node as YogaNode } from 'yoga-layout'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { usesDetachedDerivedLayout } from './derived'
+import { keepsSavedLayout, usesDetachedDerivedLayout } from './derived'
export type ComputeLayoutFn = (graph: SceneGraph, frameId: string) => void
@@ -38,7 +38,12 @@ function writeLayoutGeometry(graph: SceneGraph, id: string, geometry: LayoutGeom
if (Object.keys(changes).length > 0) graph.updateNode(id, changes)
}
-function applyFrameSize(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode): void {
+function applyFrameSize(
+ graph: SceneGraph,
+ frame: SceneNode,
+ yogaNode: YogaNode,
+ keepsSaved: boolean
+): void {
if (frame.layoutMode === 'GRID') {
if (frame.gridTemplateRows.length === 0) {
writeLayoutGeometry(graph, frame.id, { height: yogaNode.getComputedHeight() })
@@ -48,43 +53,33 @@ function applyFrameSize(graph: SceneGraph, frame: SceneNode, yogaNode: YogaNode)
if (frame.primaryAxisSizing !== 'HUG' && frame.counterAxisSizing !== 'HUG') return
- const computedW = yogaNode.getComputedWidth()
- const computedH = yogaNode.getComputedHeight()
const updates: LayoutGeometry = {}
-
- const derived = frame.derivedLayout
- if (frame.primaryAxisSizing === 'HUG') {
- if (frame.layoutMode === 'HORIZONTAL') updates.width = derived?.width ?? computedW
- else updates.height = derived?.height ?? computedH
- }
+ const derived = keepsSaved ? frame.derivedLayout : null
+ const primary = frame.layoutMode === 'HORIZONTAL' ? 'width' : 'height'
+ const counter = primary === 'width' ? 'height' : 'width'
+ const computed = (axis: 'width' | 'height') =>
+ axis === 'width' ? yogaNode.getComputedWidth() : yogaNode.getComputedHeight()
+ if (frame.primaryAxisSizing === 'HUG') updates[primary] = derived?.[primary] ?? computed(primary)
if (frame.counterAxisSizing === 'HUG') {
- if (frame.layoutMode === 'HORIZONTAL') {
- updates.height = preservesImportedHugCrossSize(graph, frame, 'height')
- ? frame.height
- : (derived?.height ?? computedH)
- } else {
- updates.width = preservesImportedHugCrossSize(graph, frame, 'width')
- ? frame.width
- : (derived?.width ?? computedW)
- }
+ updates[counter] =
+ keepsSaved && preservesImportedHugCrossSize(graph, frame, counter)
+ ? frame[counter]
+ : (derived?.[counter] ?? computed(counter))
}
writeLayoutGeometry(graph, frame.id, updates)
}
-function frameSourceIsFig(graph: SceneGraph, parentId: string | null): boolean {
- return parentId ? graph.getNode(parentId)?.source.format === 'fig' : false
-}
-
function computedChildPosition(
child: SceneNode,
yogaChild: YogaNode,
axis: 'x' | 'y',
- preservesImportedGeometry: boolean
+ preservesImportedGeometry: boolean,
+ keepsSaved: boolean
): number {
if (preservesImportedGeometry) return child[axis]
const computed = axis === 'x' ? yogaChild.getComputedLeft() : yogaChild.getComputedTop()
- if (child.type === 'INSTANCE') return computed
+ if (child.type === 'INSTANCE' || !keepsSaved) return computed
return child.derivedLayout?.[axis] ?? computed
}
@@ -102,33 +97,48 @@ function computedChildSize(
child: SceneNode,
yogaChild: YogaNode,
axis: 'width' | 'height',
- preservesImportedFrameGeometry: boolean
+ preservesImportedFrameGeometry: boolean,
+ keepsSaved: boolean
): number {
- if (preservesImportedFrameGeometry || preservesStaleImportedTextSize(child, axis)) {
+ if (
+ preservesImportedFrameGeometry ||
+ (keepsSaved && preservesStaleImportedTextSize(child, axis))
+ ) {
return child[axis]
}
const computed = axis === 'width' ? yogaChild.getComputedWidth() : yogaChild.getComputedHeight()
if (child.type === 'TEXT' && child.source.format === 'fig') {
return computed > 0 ? computed : child[axis]
}
+ if (!keepsSaved) return computed
return child.derivedLayout?.[axis] ?? computed
}
-function updateChildFromYoga(graph: SceneGraph, child: SceneNode, yogaChild: YogaNode): void {
+function updateChildFromYoga(
+ graph: SceneGraph,
+ frame: SceneNode,
+ child: SceneNode,
+ yogaChild: YogaNode,
+ keepsSaved: boolean
+): void {
if (!child.visible || child.layoutPositioning === 'ABSOLUTE') return
+ const savedFig = keepsSaved && child.source.format === 'fig'
const preservesImportedFrameGeometry =
- child.source.format === 'fig' &&
- frameSourceIsFig(graph, child.parentId) &&
- (child.type === 'FRAME' || child.type === 'LINE')
+ savedFig && frame.source.format === 'fig' && (child.type === 'FRAME' || child.type === 'LINE')
const preservesImportedPosition =
- preservesImportedFrameGeometry ||
- (child.source.format === 'fig' && Math.abs(child.rotation) > 0.001)
+ preservesImportedFrameGeometry || (savedFig && Math.abs(child.rotation) > 0.001)
writeLayoutGeometry(graph, child.id, {
- x: computedChildPosition(child, yogaChild, 'x', preservesImportedPosition),
- y: computedChildPosition(child, yogaChild, 'y', preservesImportedPosition),
- width: computedChildSize(child, yogaChild, 'width', preservesImportedFrameGeometry),
- height: computedChildSize(child, yogaChild, 'height', preservesImportedFrameGeometry)
+ 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
+ )
})
}
@@ -166,7 +176,8 @@ export function applyYogaLayout(
yogaNode: YogaNode,
computeLayout: ComputeLayoutFn
): void {
- applyFrameSize(graph, frame, yogaNode)
+ const keepsSaved = keepsSavedLayout(graph, frame)
+ applyFrameSize(graph, frame, yogaNode, keepsSaved)
const children = graph.getChildren(frame.id)
let yogaIndex = 0
@@ -175,12 +186,12 @@ export function applyYogaLayout(
const yogaChild = yogaNode.getChild(yogaIndex)
yogaIndex++
- updateChildFromYoga(graph, child, yogaChild)
+ updateChildFromYoga(graph, frame, child, yogaChild, keepsSaved)
if (!child.visible) continue
if (preservesImportedInstanceInternals(child)) continue
- if (usesDetachedDerivedLayout(child)) {
+ if (usesDetachedDerivedLayout(graph, child)) {
computeLayout(graph, child.id)
continue
}
diff --git a/packages/core/src/layout/axis-sizing.ts b/packages/core/src/layout/axis-sizing.ts
index a1e3f9ce9..92707d879 100644
--- a/packages/core/src/layout/axis-sizing.ts
+++ b/packages/core/src/layout/axis-sizing.ts
@@ -1,19 +1,93 @@
import { Align, type Node as YogaNode } from 'yoga-layout'
-import type { LayoutSizing, SceneNode } from '@open-pencil/scene-graph'
+import {
+ layoutSizing,
+ type LayoutSizing,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/scene-graph'
type Axis = 'width' | 'height'
/**
- * A fixed-size child that fills across a hugging parent still counts toward the hug, as in
- * Figma: the parent is at least as wide as the child was, and the child stretches beyond that.
+ * A Fill child along the axis its parent hugs keeps its own size there, as Figma lays it out: the
+ * parent hugs the child as it is, and neither collapses to nothing.
+ */
+export function asLaidOutIn(graph: SceneGraph, child: SceneNode, parent: SceneNode): SceneNode {
+ if (child.layoutGrow <= 0) return child
+ if (parent.layoutMode !== 'HORIZONTAL' && parent.layoutMode !== 'VERTICAL') return child
+ return layoutSizing(graph, parent, parent.layoutMode) === 'HUG'
+ ? { ...child, layoutGrow: 0 }
+ : child
+}
+
+/**
+ * Figma resizes a line or vector by scaling its geometry, so one with no extent along an axis
+ * keeps none there: it neither fills that axis nor stretches across it, and sits where its
+ * parent aligns the other children.
+ */
+export function asFlatLeaf(child: SceneNode, parent: SceneNode): SceneNode {
+ if (child.type !== 'LINE' && child.type !== 'VECTOR') return child
+ // A turned layer's own width and height do not run along the layout's axes.
+ if (child.rotation !== 0) return child
+ const isRow = parent.layoutMode === 'HORIZONTAL'
+ const main = isRow ? child.width : child.height
+ const cross = isRow ? child.height : child.width
+ if (main !== 0 && cross !== 0) return child
+ const align = parent.counterAxisAlign === 'STRETCH' ? 'MIN' : parent.counterAxisAlign
+ return {
+ ...child,
+ layoutGrow: main === 0 ? 0 : child.layoutGrow,
+ layoutAlignSelf: cross === 0 ? align : child.layoutAlignSelf
+ }
+}
+
+/**
+ * The counter axis a frame hugs but keeps its size on, because every child in its flow fills
+ * that axis and none has content of its own to hug, as Figma keeps it.
+ */
+export function heldHugAxis(graph: SceneGraph, frame: SceneNode): 'width' | 'height' | null {
+ if (frame.counterAxisSizing !== 'HUG') return null
+ if (frame.layoutMode !== 'HORIZONTAL' && frame.layoutMode !== 'VERTICAL') return null
+ const flow = graph
+ .getChildren(frame.id)
+ .filter((child) => child.visible && child.layoutPositioning !== 'ABSOLUTE')
+ const holds =
+ flow.length > 0 &&
+ flow.every(
+ (child) =>
+ child.layoutMode === 'NONE' &&
+ child.type !== 'TEXT' &&
+ (child.layoutAlignSelf === 'STRETCH' ||
+ (child.layoutAlignSelf === 'AUTO' && frame.counterAxisAlign === 'STRETCH'))
+ )
+ if (!holds) return null
+ return frame.layoutMode === 'HORIZONTAL' ? 'height' : 'width'
+}
+
+/** The fields that set how a layer sizes in its parent's layout. */
+const SIZING_FIELDS: ReadonlySet<string> = new Set([
+ 'layoutGrow',
+ 'layoutAlignSelf',
+ 'primaryAxisSizing',
+ 'counterAxisSizing'
+])
+
+/**
+ * A fixed-size child that fills across a hugging parent counts toward the hug with the size it
+ * has, as files Figma saved were laid out: the parent is at least as wide as the child was. Once
+ * Fill is set by an edit, the child counts only with its content, as Figma lays it out then.
*/
export function fillKeepsSizeInHuggingParent(
child: SceneNode,
parent: SceneNode,
axis: Axis
): boolean {
- return parent.counterAxisSizing === 'HUG' && ownAxisSizing(child, axis) === 'FIXED'
+ return (
+ parent.counterAxisSizing === 'HUG' &&
+ ownAxisSizing(child, axis) === 'FIXED' &&
+ !child.source.editedFields.some((field) => SIZING_FIELDS.has(field))
+ )
}
/** An auto-layout frame's own sizing along a screen axis, before any fill from its parent. */
diff --git a/packages/core/src/layout/derived.ts b/packages/core/src/layout/derived.ts
index 3ec5a6971..fbcb17d61 100644
--- a/packages/core/src/layout/derived.ts
+++ b/packages/core/src/layout/derived.ts
@@ -1,13 +1,86 @@
-import type { SceneNode } from '@open-pencil/scene-graph'
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-export function usesDetachedDerivedLayout(child: SceneNode): boolean {
+/** Edits that make saved geometry stale: layout fields, visibility, and text laid out again. */
+const LAYOUT_EDIT_FIELDS: ReadonlySet<string> = new Set([
+ ...SceneGraph.LAYOUT_AFFECTING_KEYS,
+ 'visible',
+ 'derivedLayout'
+])
+
+function hasEditedLayout(node: SceneNode): boolean {
+ return node.source.editedFields.some((field) => LAYOUT_EDIT_FIELDS.has(field))
+}
+
+/** The layers in each .fig frame's flow when layout first saw them, as its page opened. */
+const savedFlows = new WeakMap<SceneGraph, Map<string, string>>()
+/** Frames whose flow, or a flow inside it, lost or gained a layer since; kept until reload. */
+const restructured = new WeakMap<SceneGraph, Set<string>>()
+/** Frames that last laid out without their saved geometry, for the frames around them. */
+const reflowed = new WeakMap<SceneGraph, Set<string>>()
+
+function graphState<T>(states: WeakMap<SceneGraph, T>, graph: SceneGraph, create: () => T): T {
+ let state = states.get(graph)
+ if (!state) {
+ state = create()
+ states.set(graph, state)
+ }
+ return state
+}
+
+function flowOf(graph: SceneGraph, node: SceneNode): SceneNode[] {
+ return graph.getChildren(node.id).filter((child) => child.layoutPositioning !== 'ABSOLUTE')
+}
+
+/**
+ * Loading a file adds, moves, and removes layers too, so structure edits are told from it by
+ * comparing the layers in a frame's flow, in order, with those layout first saw. A layer that
+ * ignores auto layout, or stops ignoring it, leaves or joins the flow.
+ */
+function flowChanged(graph: SceneGraph, node: SceneNode, flow = flowOf(graph, node)): boolean {
+ const seen = graphState(savedFlows, graph, () => new Map<string, string>())
+ const ids = flow.map((child) => child.id).join(',')
+ const saved = seen.get(node.id)
+ if (saved === undefined) seen.set(node.id, ids)
+ return saved !== undefined && saved !== ids
+}
+
+/**
+ * Whether layout still keeps the geometry a file saved for `frame` and its flow: a frame read from
+ * a .fig file does until it or a layer in its flow has its layout edited, such as by adding auto
+ * layout or a gap, or a layer joins, leaves, or moves in its flow, or a flow inside it changes. Other
+ * frames keep geometry copied with them, as an instance's layers do.
+ */
+export function keepsSavedLayout(graph: SceneGraph, frame: SceneNode): boolean {
+ if (frame.source.format !== 'fig') return true
+ const stale = graphState(restructured, graph, () => new Set<string>())
+ if (stale.has(frame.id)) return false
+ const flow = flowOf(graph, frame)
+ // Layout runs inner frames first, so a changed flow deep inside is already marked.
+ if (
+ flowChanged(graph, frame, flow) ||
+ flow.some((child) => stale.has(child.id) || flowChanged(graph, child))
+ ) {
+ stale.add(frame.id)
+ return false
+ }
+ // A flow inside edited by now resizes this one, but a cancelled preview gives it back.
+ const last = graphState(reflowed, graph, () => new Set<string>())
+ const keeps =
+ !hasEditedLayout(frame) && !flow.some((child) => hasEditedLayout(child) || last.has(child.id))
+ if (keeps) last.delete(frame.id)
+ else last.add(frame.id)
+ return keeps
+}
+
+export function usesDetachedDerivedLayout(graph: SceneGraph, child: SceneNode): boolean {
const derived = child.derivedLayout
if (!derived || child.layoutMode === 'NONE' || child.layoutGrow > 0) return false
const isRow = child.layoutMode === 'HORIZONTAL'
const widthSizing = isRow ? child.primaryAxisSizing : child.counterAxisSizing
const heightSizing = isRow ? child.counterAxisSizing : child.primaryAxisSizing
return (
- (widthSizing === 'HUG' && derived.width !== undefined) ||
- (heightSizing === 'HUG' && derived.height !== undefined)
+ ((widthSizing === 'HUG' && derived.width !== undefined) ||
+ (heightSizing === 'HUG' && derived.height !== undefined)) &&
+ keepsSavedLayout(graph, child)
)
}
diff --git a/packages/core/tests/editor/layout/mode.test.ts b/packages/core/tests/editor/layout/mode.test.ts
new file mode 100644
index 000000000..3e2bf6151
--- /dev/null
+++ b/packages/core/tests/editor/layout/mode.test.ts
@@ -0,0 +1,175 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor } from '@open-pencil/core/editor'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+function scene() {
+ const editor = createEditor()
+ const outer = editor.graph.createNode('FRAME', editor.state.currentPageId, {
+ x: 100,
+ y: 100,
+ width: 500,
+ height: 300,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 24,
+ paddingTop: 20,
+ paddingRight: 20,
+ paddingBottom: 20,
+ paddingLeft: 20
+ })
+ const frame = editor.graph.createNode('FRAME', outer.id, { width: 260, height: 180 })
+ const first = editor.graph.createNode('RECTANGLE', frame.id, {
+ x: 20,
+ y: 35,
+ width: 90,
+ height: 40
+ })
+ const second = editor.graph.createNode('FRAME', frame.id, {
+ x: 145,
+ y: 95,
+ width: 80,
+ height: 55,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED',
+ paddingLeft: 10,
+ paddingTop: 10,
+ paddingRight: 10,
+ paddingBottom: 10,
+ layoutAlignSelf: 'STRETCH'
+ })
+ editor.graph.createNode('RECTANGLE', second.id, {
+ width: 60,
+ height: 20,
+ layoutGrow: 1
+ })
+ const sibling = editor.graph.createNode('RECTANGLE', outer.id, { width: 100, height: 70 })
+ editor.runLayoutForNode(outer.id)
+ editor.select([frame.id])
+ return { editor, outer, frame, first, second, sibling }
+}
+
+function layoutState(editor: Editor) {
+ return [...editor.graph.nodes.values()].map((node) => ({
+ id: node.id,
+ parentId: node.parentId,
+ childIds: [...node.childIds],
+ x: node.x,
+ y: node.y,
+ width: node.width,
+ height: node.height,
+ rotation: node.rotation,
+ layoutMode: node.layoutMode,
+ primaryAxisSizing: node.primaryAxisSizing,
+ counterAxisSizing: node.counterAxisSizing,
+ itemSpacing: node.itemSpacing,
+ paddingTop: node.paddingTop,
+ paddingRight: node.paddingRight,
+ paddingBottom: node.paddingBottom,
+ paddingLeft: node.paddingLeft,
+ gridTemplateColumns: structuredClone(node.gridTemplateColumns),
+ gridTemplateRows: structuredClone(node.gridTemplateRows)
+ }))
+}
+
+describe('layout mode history', () => {
+ for (const mode of ['VERTICAL', 'HORIZONTAL', 'GRID'] as const) {
+ test(`undo adding ${mode} restores children, descendants, and surrounding Hug layout exactly`, () => {
+ const { editor, frame, first } = scene()
+ try {
+ const before = layoutState(editor)
+ editor.setLayoutMode(frame.id, mode)
+ const after = layoutState(editor)
+ expect(after).not.toEqual(before)
+ expect(first.y).not.toBe(35)
+ for (let cycle = 0; cycle < 2; cycle++) {
+ editor.undoAction()
+ expect(layoutState(editor)).toEqual(before)
+ expect(editor.undo.canUndo).toBe(false)
+ editor.redoAction()
+ expect(layoutState(editor)).toEqual(after)
+ }
+ } finally {
+ editor.dispose()
+ }
+ })
+ }
+
+ test('switching direction and removing layout each restore the previous geometry in one undo step', () => {
+ const { editor, frame } = scene()
+ try {
+ editor.setLayoutMode(frame.id, 'VERTICAL')
+ const vertical = layoutState(editor)
+ editor.setLayoutMode(frame.id, 'HORIZONTAL')
+ const horizontal = layoutState(editor)
+ editor.setLayoutMode(frame.id, 'NONE')
+ editor.undoAction()
+ expect(layoutState(editor)).toEqual(horizontal)
+ editor.undoAction()
+ expect(layoutState(editor)).toEqual(vertical)
+ } finally {
+ editor.dispose()
+ }
+ })
+
+ test('setting the existing layout mode leaves undo history untouched', () => {
+ const { editor, frame } = scene()
+ try {
+ editor.setLayoutMode(frame.id, 'NONE')
+ expect(editor.undo.canUndo).toBe(false)
+ } finally {
+ editor.dispose()
+ }
+ })
+})
+
+test('undo wrapping a nested selection restores parent order and all affected geometry', () => {
+ const { editor, frame, first, second } = scene()
+ try {
+ editor.select([second.id, first.id])
+ const before = layoutState(editor)
+ editor.wrapInAutoLayout()
+ const after = layoutState(editor)
+ for (let cycle = 0; cycle < 2; cycle++) {
+ editor.undoAction()
+ expect(layoutState(editor)).toEqual(before)
+ expect(editor.state.selectedIds).toEqual(new Set([second.id, first.id]))
+ expect(frame.childIds).toEqual([first.id, second.id])
+ expect(editor.undo.canUndo).toBe(false)
+ editor.redoAction()
+ expect(layoutState(editor)).toEqual(after)
+ }
+ } finally {
+ editor.dispose()
+ }
+})
+
+// Figma places a new container in the slot of the topmost selected layer.
+test('the wrapper takes the slot of the topmost selected layer', () => {
+ const editor = createEditor()
+ try {
+ const parent = editor.graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 600,
+ height: 200
+ })
+ const [a, b, c, d] = ['A', 'B', 'C', 'D'].map((name, index) =>
+ editor.graph.createNode('RECTANGLE', parent.id, {
+ name,
+ x: 20 + index * 140,
+ y: 40,
+ width: 80,
+ height: 60
+ })
+ )
+ editor.select([d.id, b.id])
+ const frameId = editor.wrapInAutoLayout()
+ expect(parent.childIds).toEqual([a.id, c.id, expectDefined(frameId, 'wrapper')])
+ editor.undoAction()
+ expect(parent.childIds).toEqual([a.id, b.id, c.id, d.id])
+ } finally {
+ editor.dispose()
+ }
+})
diff --git a/packages/core/tests/editor/layout/positioning.test.ts b/packages/core/tests/editor/layout/positioning.test.ts
new file mode 100644
index 000000000..a2b818e7e
--- /dev/null
+++ b/packages/core/tests/editor/layout/positioning.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { layoutSizing } from '@open-pencil/scene-graph'
+
+/** A Hug row with padding and gap 10 around a 60 × 40 and a 50 × 30 rectangle. */
+function row() {
+ const editor = createEditor()
+ const { graph } = editor
+ const parent = graph.createNode('FRAME', editor.state.currentPageId, {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 10,
+ paddingLeft: 10,
+ paddingRight: 10,
+ paddingTop: 10,
+ paddingBottom: 10
+ })
+ const first = graph.createNode('RECTANGLE', parent.id, { width: 60, height: 40 })
+ const second = graph.createNode('RECTANGLE', parent.id, { width: 50, height: 30 })
+ editor.runLayoutForNode(parent.id)
+ return { editor, parent, first, second }
+}
+
+// Places and sizes read from Figma desktop 126 with the same layers.
+describe('ignoring auto layout', () => {
+ test('keeps the layer where it is and closes the gap, in one undo step', () => {
+ const { editor, parent, second } = row()
+ expect([parent.width, second.x, second.y]).toEqual([140, 80, 10])
+ editor.setLayoutPositioning([second.id], 'ABSOLUTE')
+ expect([parent.width, second.x, second.y]).toEqual([80, 80, 10])
+ editor.undoAction()
+ expect([second.layoutPositioning, parent.width]).toEqual(['AUTO', 140])
+ editor.redoAction()
+ editor.setLayoutPositioning([second.id], 'AUTO')
+ expect([parent.width, second.x, parent.childIds.indexOf(second.id)]).toEqual([140, 80, 1])
+ editor.dispose()
+ })
+
+ test('a Fill layer reads Fixed while it ignores the layout and fills again when back', () => {
+ const { editor, parent, second } = row()
+ editor.updateNodeWithUndo(parent.id, { primaryAxisSizing: 'FIXED', width: 300 })
+ editor.updateNodeWithUndo(second.id, { layoutGrow: 1 })
+ expect(second.width).toBe(210)
+ editor.setLayoutPositioning([second.id], 'ABSOLUTE')
+ expect([second.width, layoutSizing(editor.graph, second, 'HORIZONTAL')]).toEqual([210, 'FIXED'])
+ editor.setLayoutPositioning([second.id], 'AUTO')
+ expect(layoutSizing(editor.graph, second, 'HORIZONTAL')).toBe('FILL')
+ editor.dispose()
+ })
+
+ test('records nothing for layers outside an auto layout or already set', () => {
+ const { editor, parent, second } = row()
+ editor.setLayoutPositioning([parent.id, second.id], 'AUTO')
+ expect(editor.undo.canUndo).toBe(false)
+ editor.dispose()
+ })
+})
diff --git a/packages/core/tests/editor/selection/alignment.test.ts b/packages/core/tests/editor/selection/alignment.test.ts
index c356ce136..8a07c4caa 100644
--- a/packages/core/tests/editor/selection/alignment.test.ts
+++ b/packages/core/tests/editor/selection/alignment.test.ts
@@ -4,6 +4,7 @@ import { getNodeOrThrow } from '#core-tests/helpers/assert'
import { createRect, firstPageId } from '#core-tests/helpers/scene'
import { SceneGraph } from '@open-pencil/core'
+import { createEditor } from '@open-pencil/core/editor'
describe('single-node alignment to parent', () => {
function setup() {
@@ -125,3 +126,21 @@ describe('multi-node alignment', () => {
expect(getNodeOrThrow(graph, c.id).y).toBe(20)
})
})
+
+// Aligning layers an auto layout holds in place moves nothing, so it adds no undo step.
+test('aligning auto layout children records no undo step', () => {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const row = editor.graph.createNode('FRAME', pageId, {
+ width: 300,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const a = editor.graph.createNode('RECTANGLE', row.id, { width: 40, height: 40 })
+ const b = editor.graph.createNode('RECTANGLE', row.id, { width: 40, height: 60 })
+ editor.runLayoutForNode(row.id)
+ editor.alignNodes([a.id, b.id], 'vertical', 'max')
+ expect(editor.undo.canUndo).toBe(false)
+})
diff --git a/packages/core/tests/figma-api/page-backgrounds.test.ts b/packages/core/tests/figma-api/page-backgrounds.test.ts
new file mode 100644
index 000000000..f90a45b35
--- /dev/null
+++ b/packages/core/tests/figma-api/page-backgrounds.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Figma's plugin API takes a page background as a paint with an RGB colour and optional opacity
+// and visibility, as for fills.
+describe('page backgrounds in the plugin API', () => {
+ test('a background takes an RGB colour without alpha', () => {
+ const figma = new FigmaAPI(new SceneGraph())
+ figma.currentPage.backgrounds = [
+ { type: 'SOLID', color: { r: 30 / 255, g: 30 / 255, b: 30 / 255 } }
+ ]
+ const [background] = figma.currentPage.backgrounds
+ expect(background).toMatchObject({ type: 'SOLID', opacity: 1, visible: true })
+ expect(background?.color.r).toBeCloseTo(30 / 255, 6)
+ })
+})
diff --git a/packages/core/tests/layout/auto-layout/saved-geometry.test.ts b/packages/core/tests/layout/auto-layout/saved-geometry.test.ts
new file mode 100644
index 000000000..8cbc03614
--- /dev/null
+++ b/packages/core/tests/layout/auto-layout/saved-geometry.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '#core/editor'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+/** Marks layers as read from a .fig file, with the geometry the file saved for them. */
+function asSaved(graph: SceneGraph, nodes: SceneNode[]) {
+ for (const node of nodes) {
+ 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 }
+ })
+ )
+ }
+}
+
+function savedRow() {
+ const editor = createEditor()
+ const { graph } = editor
+ const row = graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 230,
+ height: 60,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 10,
+ paddingLeft: 10,
+ paddingRight: 10,
+ paddingTop: 10,
+ paddingBottom: 10
+ })
+ const first = graph.createNode('FRAME', row.id, { x: 10, y: 10, width: 100, height: 40 })
+ const second = graph.createNode('FRAME', row.id, { x: 120, y: 10, width: 100, height: 40 })
+ asSaved(graph, [row, first, second])
+ // Opening a file lays its pages out.
+ editor.runLayoutForNode(row.id)
+ return { editor, row, first, second }
+}
+
+/** Three saved Hug rows, each inside the last, around one 10 px layer. */
+function savedNest() {
+ const editor = createEditor()
+ const { graph } = editor
+ const hug = {
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 10,
+ paddingLeft: 10,
+ paddingRight: 10,
+ paddingTop: 10,
+ paddingBottom: 10
+ } as const
+ const outer = graph.createNode('FRAME', editor.state.currentPageId, { ...hug, width: 70, height: 70 })
+ const middle = graph.createNode('FRAME', outer.id, { ...hug, x: 10, y: 10, width: 50, height: 50 })
+ const inner = graph.createNode('FRAME', middle.id, { ...hug, x: 10, y: 10, width: 30, height: 30 })
+ const leaf = graph.createNode('RECTANGLE', inner.id, { x: 10, y: 10, width: 10, height: 10 })
+ asSaved(graph, [outer, middle, inner, leaf])
+ editor.runLayoutForNode(outer.id)
+ return { editor, outer, middle, inner }
+}
+
+describe('a frame read from a .fig file reflows once its layout is edited', () => {
+ test('adding auto layout hugs the layer and moves it into the flow', () => {
+ for (const mode of ['HORIZONTAL', 'VERTICAL'] as const) {
+ const editor = createEditor()
+ const frame = editor.graph.createNode('FRAME', editor.state.currentPageId, {
+ width: 480,
+ height: 360
+ })
+ const child = editor.graph.createNode('FRAME', frame.id, {
+ x: 220,
+ y: 150,
+ width: 140,
+ height: 90
+ })
+ asSaved(editor.graph, [frame, child])
+ editor.setLayoutMode(frame.id, mode)
+ expect([frame.width, frame.height, child.x, child.y]).toEqual([140, 90, 0, 0])
+ editor.undoAction()
+ expect([frame.width, frame.height, child.x, child.y]).toEqual([480, 360, 220, 150])
+ editor.dispose()
+ }
+ })
+
+ test('a new layer in the flow moves the saved ones along', () => {
+ const { editor, row, first, second } = savedRow()
+ const added = editor.graph.createNode('RECTANGLE', row.id, { width: 50, height: 40 })
+ editor.graph.reorderChild(added.id, row.id, 0)
+ editor.runLayoutForNode(row.id)
+ expect([row.width, added.x, first.x, second.x]).toEqual([290, 10, 70, 180])
+ editor.dispose()
+ })
+
+ test('removing a layer closes the gap it leaves', () => {
+ const { editor, row, first, second } = savedRow()
+ editor.graph.deleteNode(first.id)
+ editor.runLayoutForNode(row.id)
+ expect([row.width, second.x]).toEqual([120, 10])
+ editor.dispose()
+ })
+
+ test('a layer that ignores auto layout leaves the flow, and one added that way does not join it', () => {
+ const { editor, row, first, second } = savedRow()
+ const pinned = editor.graph.createNode('RECTANGLE', row.id, {
+ x: 300,
+ y: 0,
+ width: 20,
+ height: 20,
+ layoutPositioning: 'ABSOLUTE'
+ })
+ editor.runLayoutForNode(row.id)
+ expect([row.width, first.x, second.x, pinned.x]).toEqual([230, 10, 120, 300])
+ editor.setLayoutPositioning([first.id], 'ABSOLUTE')
+ expect([row.width, first.x, second.x]).toEqual([120, 10, 10])
+ editor.dispose()
+ })
+
+ test('a layer added to a nested flow resizes every Hug frame around it', () => {
+ const { editor, outer, middle, inner } = savedNest()
+ editor.graph.createNode('RECTANGLE', inner.id, { width: 10, height: 10 })
+ editor.runLayoutForNode(inner.id)
+ expect([inner.width, middle.width, outer.width]).toEqual([50, 70, 90])
+ editor.dispose()
+ })
+
+ test('a gap changed in a nested flow resizes every Hug frame around it, until undone', () => {
+ const { editor, outer, middle, inner } = savedNest()
+ editor.updateNodeWithUndo(inner.id, { paddingLeft: 30 })
+ expect([inner.width, middle.width, outer.width]).toEqual([50, 70, 90])
+ editor.undoAction()
+ expect([inner.width, middle.width, outer.width]).toEqual([30, 50, 70])
+ editor.dispose()
+ })
+
+ test('a new gap spaces the saved layers', () => {
+ const { editor, row, first, second } = savedRow()
+ editor.updateNodeWithUndo(row.id, { itemSpacing: 20 })
+ expect([row.width, first.x, second.x]).toEqual([240, 10, 130])
+ editor.dispose()
+ })
+
+ test('an unedited frame keeps the geometry the file saved', () => {
+ const { editor, row, first, second } = savedRow()
+ editor.graph.updateNode(first.id, { name: 'Renamed' })
+ editor.runLayoutForNode(row.id)
+ expect([row.width, first.x, second.x]).toEqual([230, 10, 120])
+ editor.dispose()
+ })
+})
diff --git a/packages/core/tests/layout/auto-layout/sizing/flat-leaves.test.ts b/packages/core/tests/layout/auto-layout/sizing/flat-leaves.test.ts
new file mode 100644
index 000000000..dcb3b76cd
--- /dev/null
+++ b/packages/core/tests/layout/auto-layout/sizing/flat-leaves.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from 'bun:test'
+
+import { computeAllLayouts } from '#core/layout'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+// Nuxt UI's separators, as Figma saved them in the Nuxt UI kit: a Fill line in a 20 px row stays a
+// line, centred, and a vector with no width keeps none.
+function row(child: 'LINE' | 'VECTOR') {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const frame = graph.createNode('FRAME', page.id, {
+ width: 104,
+ height: 20,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED',
+ counterAxisAlign: 'CENTER',
+ primaryAxisAlign: 'CENTER'
+ })
+ const node = graph.createNode(child, frame.id, {
+ width: child === 'LINE' ? 50 : 0,
+ height: child === 'LINE' ? 0 : 20,
+ layoutGrow: 1,
+ layoutAlignSelf: 'STRETCH'
+ })
+ computeAllLayouts(graph, page.id)
+ return node
+}
+
+describe('a line or vector with no extent on an axis', () => {
+ test('a Fill line fills along the row and stays a line across it', () => {
+ const line = row('LINE')
+ expect([line.x, line.y, line.width, line.height]).toEqual([0, 10, 104, 0])
+ })
+
+ test('a vector with no width keeps none along the row', () => {
+ const vector = row('VECTOR')
+ expect([vector.x, vector.width, vector.height]).toEqual([52, 0, 20])
+ })
+})
diff --git a/packages/core/tests/layout/auto-layout/sizing/hug-fill.test.ts b/packages/core/tests/layout/auto-layout/sizing/hug-fill.test.ts
new file mode 100644
index 000000000..8f1f86c72
--- /dev/null
+++ b/packages/core/tests/layout/auto-layout/sizing/hug-fill.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, test } from 'bun:test'
+
+import { FigmaAPI, type FigmaNodeProxy } from '#core/figma-api'
+import { computeAllLayouts } from '#core/layout'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+/** A Hug row with padding and gap 10 around a 60 × 40 and a 50 × 30 rectangle. */
+function hugRow() {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const layout = () => computeAllLayouts(graph, graph.getPages()[0].id)
+ const row = figma.createFrame()
+ row.layoutMode = 'HORIZONTAL'
+ row.paddingLeft = row.paddingRight = row.paddingTop = row.paddingBottom = 10
+ row.itemSpacing = 10
+ const first = figma.createRectangle()
+ first.resize(60, 40)
+ row.appendChild(first)
+ const child = figma.createRectangle()
+ child.resize(50, 30)
+ row.appendChild(child)
+ row.layoutSizingHorizontal = 'HUG'
+ row.layoutSizingVertical = 'HUG'
+ layout()
+ return { row, child, layout }
+}
+
+// Sizes read from Figma desktop 126's plugin API with the same layers.
+describe('Fill inside a Hug parent keeps sizes as Figma does', () => {
+ test('a child set to Fill along a Hug axis keeps its width', () => {
+ const { row, child, layout } = hugRow()
+ child.layoutSizingHorizontal = 'FILL'
+ layout()
+ expect([row.width, child.width]).toEqual([140, 50])
+ })
+
+ test('a parent set to Hug keeps the width its Fill child had', () => {
+ const { row, child, layout } = hugRow()
+ row.layoutSizingHorizontal = 'FIXED'
+ row.resize(320, row.height)
+ child.layoutSizingHorizontal = 'FILL'
+ layout()
+ expect(child.width).toBe(230)
+ row.layoutSizingHorizontal = 'HUG'
+ layout()
+ expect([row.width, child.width]).toEqual([320, 230])
+ })
+
+ test('Fill across a Hug axis stretches to the tallest sibling', () => {
+ const { row, child, layout } = hugRow()
+ child.layoutSizingVertical = 'FILL'
+ layout()
+ expect([row.height, child.height]).toEqual([60, 40])
+
+ row.layoutSizingVertical = 'FIXED'
+ row.resize(row.width, 100)
+ layout()
+ expect(child.height).toBe(80)
+ row.layoutSizingVertical = 'HUG'
+ layout()
+ expect([row.height, child.height]).toEqual([60, 40])
+ })
+})
+
+describe('when every child fills across a Hug axis', () => {
+ function column(children: (figma: FigmaAPI) => FigmaNodeProxy[]) {
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const layout = () => computeAllLayouts(graph, graph.getPages()[0].id)
+ const parent = figma.createFrame()
+ parent.layoutMode = 'VERTICAL'
+ parent.layoutSizingHorizontal = 'HUG'
+ parent.layoutSizingVertical = 'HUG'
+ const nodes = children(figma)
+ for (const node of nodes) parent.appendChild(node)
+ layout()
+ return { parent, nodes, layout }
+ }
+
+ test('layers without content of their own keep the width the parent had', () => {
+ const { parent, nodes, layout } = column((figma) =>
+ [100, 140].map((width) => {
+ const frame = figma.createFrame()
+ frame.resize(width, 30)
+ return frame
+ })
+ )
+ for (const node of nodes) node.layoutSizingHorizontal = 'FILL'
+ layout()
+ expect([parent.width, ...nodes.map((node) => node.width)]).toEqual([140, 140, 140])
+ })
+
+ test('a fixed sibling sets the width again', () => {
+ const { parent, nodes, layout } = column((figma) =>
+ [100, 140].map((width) => {
+ const frame = figma.createFrame()
+ frame.resize(width, 30)
+ return frame
+ })
+ )
+ nodes[0].layoutSizingHorizontal = 'FILL'
+ nodes[1].resize(60, 30)
+ layout()
+ expect([parent.width, ...nodes.map((node) => node.width)]).toEqual([60, 60, 60])
+ })
+
+ test('an auto layout child counts with its content, not its old width', () => {
+ const { parent, nodes, layout } = column((figma) => {
+ const fixed = figma.createFrame()
+ fixed.resize(60, 30)
+ const filled = figma.createFrame()
+ filled.layoutMode = 'HORIZONTAL'
+ filled.layoutSizingHorizontal = 'FIXED'
+ filled.layoutSizingVertical = 'FIXED'
+ filled.resize(200, 30)
+ return [fixed, filled]
+ })
+ nodes[1].layoutSizingHorizontal = 'FILL'
+ layout()
+ expect([parent.width, nodes[1].width]).toEqual([60, 60])
+ })
+})
diff --git a/packages/vue/src/controls/position/use.ts b/packages/vue/src/controls/position/use.ts
index 46492d923..646e5742c 100644
--- a/packages/vue/src/controls/position/use.ts
+++ b/packages/vue/src/controls/position/use.ts
@@ -75,6 +75,26 @@ export function usePosition() {
_cancelProp(nodes.value, key)
}
+ /** Whether every selected layer sits in an auto layout, where it can ignore that layout. */
+ const inAutoLayout = computed(
+ () =>
+ nodes.value.length > 0 &&
+ nodes.value.every((target) => {
+ const parent = target.parentId ? editor.graph.getNode(target.parentId) : undefined
+ return !!parent && parent.layoutMode !== 'NONE'
+ })
+ )
+ /** On only when every selected layer ignores its auto layout. */
+ const ignoresAutoLayout = computed(
+ () =>
+ inAutoLayout.value && nodes.value.every((target) => target.layoutPositioning === 'ABSOLUTE')
+ )
+
+ /** Figma's Ignore auto layout toggle: a mixed selection is taken out of its layouts. */
+ function toggleIgnoreAutoLayout() {
+ editor.setLayoutPositioning(ids.value, ignoresAutoLayout.value ? 'AUTO' : 'ABSOLUTE')
+ }
+
function align(axis: 'horizontal' | 'vertical', pos: 'min' | 'center' | 'max') {
editor.alignNodes(ids.value, axis, pos)
}
@@ -101,6 +121,9 @@ export function usePosition() {
width,
height,
rotation,
+ inAutoLayout,
+ ignoresAutoLayout,
+ toggleIgnoreAutoLayout,
updateProp,
commitProp,
cancelProp,
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index e870d5b0f..b9dd1e09f 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -109,6 +109,7 @@
"alignCenterHorizontally": "Horizontal zentrieren",
"alignCenterVertically": "Vertikal zentrieren",
"flipHorizontal": "Horizontal spiegeln",
+ "ignoreAutoLayout": "Auto-Layout ignorieren",
"flipVertical": "Vertikal spiegeln",
"rotate90": "90° drehen",
"mixedFillsHelp": "Klicke auf +, um gemischte Füllungen zu ersetzen",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 8b570d153..991f6a262 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -124,6 +124,7 @@
"alignCenterHorizontally": "Centrar horizontalmente",
"alignCenterVertically": "Centrar verticalmente",
"flipHorizontal": "Voltear horizontalmente",
+ "ignoreAutoLayout": "Ignorar diseño automático",
"flipVertical": "Voltear verticalmente",
"rotate90": "Girar 90°",
"mixedFillsHelp": "Haz clic en + para reemplazar rellenos mixtos",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 14458614f..d29380244 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -109,6 +109,7 @@
"alignCenterHorizontally": "Centrer horizontalement",
"alignCenterVertically": "Centrer verticalement",
"flipHorizontal": "Retourner horizontalement",
+ "ignoreAutoLayout": "Ignorer la mise en page automatique",
"flipVertical": "Retourner verticalement",
"rotate90": "Pivoter de 90°",
"mixedFillsHelp": "Cliquez sur + pour remplacer les remplissages mixtes",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index ea96ce543..d9269d23c 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -109,6 +109,7 @@
"alignCenterHorizontally": "Centra orizzontalmente",
"alignCenterVertically": "Centra verticalmente",
"flipHorizontal": "Rifletti orizzontalmente",
+ "ignoreAutoLayout": "Ignora layout automatico",
"flipVertical": "Rifletti verticalmente",
"rotate90": "Ruota di 90°",
"mixedFillsHelp": "Fai clic su + per sostituire i riempimenti misti",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 5ea5b6b25..a11fc6fb7 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -124,6 +124,7 @@
"alignCenterHorizontally": "水平方向の中央揃え",
"alignCenterVertically": "垂直方向の中央揃え",
"flipHorizontal": "水平方向に反転",
+ "ignoreAutoLayout": "オートレイアウトを無視",
"flipVertical": "垂直方向に反転",
"rotate90": "90°回転",
"mixedFillsHelp": "+ をクリックして混合塗りを置換",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 7ffb13c48..b5f4ae017 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -109,6 +109,7 @@
"alignCenterHorizontally": "Wyśrodkuj poziomo",
"alignCenterVertically": "Wyśrodkuj pionowo",
"flipHorizontal": "Odbij poziomo",
+ "ignoreAutoLayout": "Ignoruj auto layout",
"flipVertical": "Odbij pionowo",
"rotate90": "Obróć o 90°",
"mixedFillsHelp": "Kliknij +, aby zastąpić mieszane wypełnienia",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 0026018a0..d924de45f 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -91,6 +91,7 @@
"alignCenterVertically": "Выровнять по центру по вертикали",
"alignBottom": "Выровнять по нижнему краю",
"flipHorizontal": "Отразить по горизонтали",
+ "ignoreAutoLayout": "Игнорировать автолейаут",
"flipVertical": "Отразить по вертикали",
"rotate90": "Повернуть на 90°",
"mixedFillsHelp": "Нажмите +, чтобы заменить смешанные заливки",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 73791b3b6..291b00f86 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -91,6 +91,7 @@
"alignCenterVertically": "垂直居中",
"alignBottom": "底部对齐",
"flipHorizontal": "水平翻转",
+ "ignoreAutoLayout": "忽略自动布局",
"flipVertical": "垂直翻转",
"rotate90": "旋转 90°",
"mixedFillsHelp": "点击 + 替换混合填充",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 3d195a563..e3744a507 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -391,6 +391,7 @@ export const panelMessageDefaults = {
alignCenterVertically: 'Align center vertically',
alignBottom: 'Align bottom',
flipHorizontal: 'Flip horizontal',
+ ignoreAutoLayout: 'Ignore auto layout',
flipVertical: 'Flip vertical',
rotate90: 'Rotate 90°',
mixedFillsHelp: 'Click + to replace mixed fills',
diff --git a/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vue b/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vue
index 43612cc76..3cd5ac54f 100644
--- a/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vue
+++ b/packages/vue/src/primitives/PositionControls/PositionControlsRoot.vue
@@ -18,7 +18,10 @@ const {
panelProp,
x,
y,
- rotation
+ rotation,
+ inAutoLayout,
+ ignoresAutoLayout,
+ toggleIgnoreAutoLayout
} = usePosition()
const multiX = panelProp('x')
@@ -35,7 +38,8 @@ const actions = {
cancelProp,
align,
flip,
- rotate
+ rotate,
+ toggleIgnoreAutoLayout
}
</script>
@@ -49,6 +53,8 @@ const actions = {
:w-value="wValue"
:h-value="hValue"
:rotation-value="rotationValue"
+ :in-auto-layout="inAutoLayout"
+ :ignores-auto-layout="ignoresAutoLayout"
:mixed="MIXED"
:actions="actions"
/>
diff --git a/packages/vue/src/shared/input/drag-original.ts b/packages/vue/src/shared/input/drag-original.ts
deleted file mode 100644
index 8f0afbfdc..000000000
--- a/packages/vue/src/shared/input/drag-original.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type DragOriginal = { x: number; y: number; parentId: string }
diff --git a/packages/vue/src/shared/input/duplicate-drag.ts b/packages/vue/src/shared/input/duplicate-drag.ts
index c2a91df1b..9682417ee 100644
--- a/packages/vue/src/shared/input/duplicate-drag.ts
+++ b/packages/vue/src/shared/input/duplicate-drag.ts
@@ -1,6 +1,5 @@
-import type { Editor } from '@open-pencil/core/editor'
+import type { Editor, MovePlace } from '@open-pencil/core/editor'
-import type { DragOriginal } from '#vue/shared/input/drag-original'
import type { DragState } from '#vue/shared/input/types'
export function duplicateAndDrag(
@@ -9,10 +8,10 @@ export function duplicateAndDrag(
sx: number,
sy: number,
editor: Editor
-): { originals: Map<string, DragOriginal>; drag: DragState } {
+): { originals: Map<string, MovePlace>; drag: DragState } {
const previousSelection = new Set(editor.state.selectedIds)
const newIds: string[] = []
- const newOriginals = new Map<string, DragOriginal>()
+ const newOriginals = new Map<string, MovePlace>()
for (const id of previousSelection) {
const source = editor.graph.getNode(id)
if (!source) continue
diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.ts
index 1d57e3f58..a30ec507b 100644
--- a/packages/vue/src/shared/input/select/move.ts
+++ b/packages/vue/src/shared/input/select/move.ts
@@ -1,7 +1,6 @@
-import type { Editor } from '@open-pencil/core/editor'
+import type { Editor, MovePlace } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
-import type { DragOriginal as MoveOriginal } from '#vue/shared/input/drag-original'
import { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'
import type { DragState } from '#vue/shared/input/types'
@@ -65,23 +64,25 @@ function autoLayoutMoveTarget(id: string, editor: Editor): string {
}
function collectMoveOriginals(editor: Editor) {
- const originals = new Map<string, MoveOriginal>()
+ const originals = new Map<string, MovePlace>()
for (const selectedId of editor.state.selectedIds) {
if (isLockedInTree(selectedId, editor)) continue
const id = autoLayoutMoveTarget(selectedId, editor)
const node = editor.graph.getNode(id)
if (node) {
+ const parentId = node.parentId ?? editor.state.currentPageId
originals.set(id, {
x: node.x,
y: node.y,
- parentId: node.parentId ?? editor.state.currentPageId
+ parentId,
+ index: editor.graph.getNode(parentId)?.childIds.indexOf(id)
})
}
}
return originals
}
-function detectDragAutoLayoutParent(originals: Map<string, MoveOriginal>, editor: Editor) {
+function detectDragAutoLayoutParent(originals: Map<string, MovePlace>, editor: Editor) {
if (originals.size !== 1) return undefined
const [id, original] = [...originals][0]
const node = editor.graph.getNode(id)
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index 76b41caff..d3800bb9b 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -1,4 +1,4 @@
-import type { Tool } from '@open-pencil/core/editor'
+import type { MovePlace, Tool } from '@open-pencil/core/editor'
import type {
DerivedTextGlyph,
GeometryPath,
@@ -43,7 +43,7 @@ export interface DragMove {
startScreenX: number
startScreenY: number
dragStarted: boolean
- originals: Map<string, { x: number; y: number; parentId: string }>
+ originals: Map<string, MovePlace>
duplicated?: boolean
duplicatedPreviousSelection?: Set<string>
autoLayoutParentId?: string
diff --git a/packages/vue/tests/shared/input/move/history.test.ts b/packages/vue/tests/shared/input/move/history.test.ts
new file mode 100644
index 000000000..cb9baccd8
--- /dev/null
+++ b/packages/vue/tests/shared/input/move/history.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createMoveHarness } from './harness'
+
+describe('move history', () => {
+ // Undo puts a layer dragged out of a frame back in its old slot, not after its siblings.
+ test('undoing a drag out of a frame restores the sibling order', () => {
+ const { editor, page, node, drag, parentOf, childIds } = createMoveHarness()
+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }
+ const frame = node('FRAME', page, { x: 100, y: 100, width: 300, height: 100 })
+ const [a, b, c] = [0, 1, 2].map((index) =>
+ node('RECTANGLE', frame.id, { x: index * 60, y: 10, width: 50, height: 40 })
+ )
+ drag([b.id], [180, 130], [180, 330])
+ expect(parentOf(b.id)).toBe(page)
+
+ editor.undoAction()
+ expect(childIds(frame.id)).toEqual([a.id, b.id, c.id])
+ expect(editor.graph.getNode(b.id)).toMatchObject({ x: 60, y: 10 })
+
+ editor.redoAction()
+ expect(parentOf(b.id)).toBe(page)
+ expect(childIds(frame.id)).toEqual([a.id, c.id])
+ })
+})
diff --git a/src/components/properties/PositionSection.vue b/src/components/properties/PositionSection.vue
index 759f3a664..b58418794 100644
--- a/src/components/properties/PositionSection.vue
+++ b/src/components/properties/PositionSection.vue
@@ -26,8 +26,19 @@ function handleAlign(
</script>
<template>
- <PositionControlsRoot v-slot="{ active, xValue, yValue, rotationValue, actions }">
+ <PositionControlsRoot
+ v-slot="{ active, xValue, yValue, rotationValue, inAutoLayout, ignoresAutoLayout, actions }"
+ >
<PanelSection v-if="active" :label="panels.position">
+ <template v-if="inAutoLayout" #actions>
+ <IconButton
+ :label="panels.ignoreAutoLayout"
+ :active="ignoresAutoLayout"
+ @click="actions.toggleIgnoreAutoLayout"
+ >
+ <icon-lucide-scan class="size-3.5" />
+ </IconButton>
+ </template>
<div role="toolbar" :aria-label="panels.position" class="mb-1.5 flex justify-between">
<div class="flex gap-0.5">
<IconButton
diff --git a/tests/e2e/text/live-layout.spec.ts b/tests/e2e/text/live-layout.spec.ts
new file mode 100644
index 000000000..ed7516ea8
--- /dev/null
+++ b/tests/e2e/text/live-layout.spec.ts
@@ -0,0 +1,68 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+// Figma desktop 126 grows a Hug frame with its label as the label is typed, and keeps it fitting
+// through undo and redo.
+
+let page: Page
+let canvas: CanvasHelper
+
+test.describe.configure({ mode: 'serial' })
+
+test.beforeAll(async ({ browser }) => {
+ page = await browser.newPage()
+ await page.goto('/?test&no-rulers')
+ canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+})
+
+test.afterAll(async () => {
+ await page.close()
+})
+
+function sizes() {
+ return page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ const text = [...(store?.graph.getAllNodes() ?? [])].find((node) => node.type === 'TEXT')
+ const frame = text?.parentId ? store?.graph.getNode(text.parentId) : undefined
+ return { id: text?.id ?? '', text: text?.width ?? 0, frame: frame?.width ?? 0 }
+ })
+}
+
+test('a Hug frame grows with its label while it is typed', async () => {
+ await canvas.clearCanvas()
+ await canvas.selectTool('text')
+ await canvas.click(300, 300)
+ await page.keyboard.type('Hi')
+ await page.keyboard.press('Escape')
+ await canvas.waitForRender()
+ // Shift+A wraps the text in an auto layout frame that hugs it.
+ await page.keyboard.press('Shift+a')
+ await canvas.waitForRender()
+ const wrapped = await sizes()
+ expect(wrapped.frame).toBe(wrapped.text)
+
+ await page.evaluate((id) => {
+ const store = window.openPencil?.getStore?.()
+ store?.select([id])
+ store?.startTextEditing(id)
+ }, wrapped.id)
+ await page.keyboard.press('End')
+ await page.keyboard.type(' there, a longer label')
+ await canvas.waitForRender()
+ const typing = await sizes()
+ expect(typing.text).toBeGreaterThan(wrapped.text)
+ expect(typing.frame).toBe(typing.text)
+
+ await page.keyboard.press('Escape')
+ await canvas.waitForRender()
+ const committed = await sizes()
+ expect(committed.frame).toBe(committed.text)
+
+ await canvas.undo()
+ await expect.poll(sizes).toMatchObject({ text: wrapped.text, frame: wrapped.frame })
+ await canvas.redo()
+ await expect.poll(sizes).toMatchObject({ text: committed.text, frame: committed.frame })
+ canvas.assertNoErrors()
+})
diff --git a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
index 65dbf4a16..c8a607bb3 100644
--- a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
+++ b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
@@ -452,7 +452,7 @@ describe('imported auto-layout bounds', () => {
paddingLeft: 24
})
graph.updateNode(frame.id, { source: { ...frame.source, format: 'fig' } })
- graph.createNode('TEXT', frame.id, {
+ const text = graph.createNode('TEXT', frame.id, {
width: 333,
height: 30,
text: 'Bar Chart',
@@ -460,6 +460,7 @@ describe('imported auto-layout bounds', () => {
layoutAlignSelf: 'STRETCH',
derivedLayout: { width: 333, height: 30 }
})
+ graph.updateNode(text.id, { source: { ...text.source, format: 'fig' } })
computeAllLayouts(graph)