AI-native design editor. Open-source Figma alternative.
fix(clipboard): keep pasted layers' canvas angle and place them in canvas boxes (#1093)
Danila Poyarkov328021d70ff6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 527c502a7..b73365f8a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@### Changed- A selected layer resizes and rotates where Figma's does: every edge resizes along its whole length within 7.5 px outside it and up to a tenth of the side inside it, corners within 7.5 px, and the area outside a corner within 16 px rotates; a frame's name takes a press before rotation but not before resizing. Layers under 24 px keep these zones outside them, and a layer under 10 px on both sides has none, taking presses within 16 px across its centre instead. A selection draws Figma's four corner handles, without the edge midpoints, and none on such a small layer.+- Pasted layers keep how they were turned and flipped on the canvas, as in Figma, so a layer copied out of a rotated frame stays at its angle in an upright one, and paste to replace keeps the copied layer's angle too. Layers copied out of a frame or section keep their offset from its box on the canvas, and move into the frame only when they start past its far edge, or, for top-level layers, miss it: then layers that fit are centred on that axis, and larger ones go to the frame's top-left, or are centred if top-level. Layers overlapping an edge stay where they are, and layers copied from different places are placed each from its own.## 0.16.0-beta.1 — 2026-10-11diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex 38ee4bd0a..7a0f509a0 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -17,7 +17,11 @@ import { deleteIds, recreateSnapshots, restoreDeletedEntries } from './clipboardimport type { PasteHistoryOperation } from './clipboard/paste/replace'import { replaceTargetsWithCreated, selectedReplacementTargets } from './clipboard/paste/replace'import { pastedComponentIds, resolvePasteTarget } from './clipboard/paste/target'-import { createClipboardPlacementActions } from './clipboard/placement'+import {+ clipboardPlacement,+ createClipboardPlacementActions,+ type ClipboardPlacement+} from './clipboard/placement'import { acceptsChildren, prepareSlotEdits } from './components/slots'import { collectSubtrees, restoreSubtree, snapshotSubtree } from './history/subtree'import type { EditorContext } from './types'@@ -148,6 +152,7 @@ export function createClipboardActions(ctx: EditorContext) {}created = pasteOpenPencilNodes(dependencies.nodes,+ snapshot.placement,snapshot.images,dependencies.componentDependencies,cursorPos,@@ -162,7 +167,14 @@ export function createClipboardActions(ctx: EditorContext) {if (openPencil) {// One undo step for the paste and any slot it claims.const created = ctx.undo.runBatch('Paste', () =>- pasteOpenPencilNodes(openPencil.nodes, openPencil.images, [], cursorPos, options)+ pasteOpenPencilNodes(+ openPencil.nodes,+ clipboardPlacement(ctx.graph, openPencil.nodes),+ openPencil.images,+ [],+ cursorPos,+ options+ ))await fontActions.loadFontsForNodes(created)return@@ -211,6 +223,7 @@ export function createClipboardActions(ctx: EditorContext) {function pasteOpenPencilNodes(nodes: Array<SceneNode & { children?: SceneNode[] }>,+ placement: ClipboardPlacement,images: Map<string, Uint8Array>,dependencies: Array<SceneNode & { children?: SceneNode[] }> = [],cursorPos?: Vector,@@ -268,20 +281,15 @@ export function createClipboardActions(ctx: EditorContext) {})}if (created.length === 0) return created+ placementActions.keepCanvasTransforms(created, placement.transforms)if (replacementTargets.length > 0) {replaceTargetsWithCreated(ctx, created, replacementTargets, prevSelection)return created}- if (cursorPos) placementActions.centerNodesAtCanvasPoint(created, pasteTarget, cursorPos)- else- placementActions.placePasted(- created,- nodes[0]?.parentId ?? undefined,- pasteTarget,- requestedTarget- )+ if (cursorPos) placementActions.centerNodesAtCanvasPoint(created, cursorPos)+ else placementActions.placePasted(created, placement, pasteTarget, requestedTarget)computeAllLayouts(ctx.graph, ctx.state.currentPageId)ctx.setSelectedIds(new Set(created))diff --git a/packages/core/src/editor/clipboard/paste/replace.ts b/packages/core/src/editor/clipboard/paste/replace.tsindex b77529b6d..ef8509bca 100644--- a/packages/core/src/editor/clipboard/paste/replace.ts+++ b/packages/core/src/editor/clipboard/paste/replace.ts@@ -10,6 +10,7 @@ import {recreateSnapshots,restoreDeletedEntries} from '#core/editor/clipboard/history'+import { translateOnCanvas } from '#core/editor/clipboard/placement'import { collectSubtrees, snapshotSubtree } from '#core/editor/history/subtree'import type { EditorContext } from '#core/editor/types'import { computeAllLayouts } from '#core/layout'@@ -81,16 +82,14 @@ function pushPasteReplaceUndo(}/**- * Moves the replacement so its box starts where the targets' box did, as Figma does, in the axes- * of the parent it went into, so an offset, rotated, or flipped frame keeps it in their place.+ * Moves the replacement so its canvas box starts where the targets' did, as Figma does, so an+ * offset, rotated, or flipped frame keeps it in their place.*/function alignWithTargets(ctx: EditorContext, created: string[], targets: SceneNode[]) {const nodes = created.map((id) => ctx.graph.getNode(id)).filter(isNotNil)- const parentId = nodes[0]?.parentId ?? ctx.state.currentPageId- const from = getAxisAlignedBoundsInParent(nodes, parentId, ctx.graph)- const to = getAxisAlignedBoundsInParent(targets, parentId, ctx.graph)- for (const node of nodes)- ctx.graph.updateNode(node.id, { x: node.x + to.x - from.x, y: node.y + to.y - from.y })+ const from = getAxisAlignedBoundsInParent(nodes, ctx.graph.rootId, ctx.graph)+ const to = getAxisAlignedBoundsInParent(targets, ctx.graph.rootId, ctx.graph)+ translateOnCanvas(ctx.graph, created, to.x - from.x, to.y - from.y)}export function replaceTargetsWithCreated(diff --git a/packages/core/src/editor/clipboard/placement.ts b/packages/core/src/editor/clipboard/placement.tsindex 4859d637f..f8d5153cf 100644--- a/packages/core/src/editor/clipboard/placement.ts+++ b/packages/core/src/editor/clipboard/placement.ts@@ -1,13 +1,17 @@+import { groupBy } from 'es-toolkit'import { isNotNil } from 'es-toolkit/predicate'-import type { SceneNode } from '@open-pencil/scene-graph'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import {getAxisAlignedBoundsInParent,+ getAxisAlignedWorldBounds,+ getNodeLocalMatrix,getParentWorldMatrix,- getWorldMatrix+ getWorldMatrix,+ localTransformFromWorld} from '@open-pencil/scene-graph/coordinate'import { computeBounds } from '@open-pencil/scene-graph/geometry'-import Matrix from '@open-pencil/scene-graph/matrix'+import Matrix, { type Mat3 } from '@open-pencil/scene-graph/matrix'import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import { DUPLICATE_FRAME_GAP } from '#core/constants'@@ -17,14 +21,90 @@ function overlaps(a: Rect, b: Rect) {return a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height}-export function createClipboardPlacementActions(ctx: EditorContext) {- function centerNodesAt(nodeIds: string[], cx: number, cy: number) {- const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)- const bounds = computeBounds(items)- if (bounds.width === 0 && bounds.height === 0 && items.length === 0) return- translate(nodeIds, cx - (bounds.x + bounds.width / 2), cy - (bounds.y + bounds.height / 2))+/** The frame or section a layer was copied out of, and its box on the canvas then. */+export interface ClipboardSource {+ id: string+ box: Rect+}++/** Where copied layers sat on the canvas, which paste keeps as Figma does. */+export interface ClipboardPlacement {+ /** Each copied layer's canvas transform, in the order of the copied layers. */+ transforms: Mat3[]+ /** Where each copied layer came from; null for a top-level layer. */+ sources: Array<ClipboardSource | null>+}++/**+ * The placement of copied layers whose parents, if this document has them, are where they were+ * copied from. A layer whose parent it lacks counts as top-level.+ */+export function clipboardPlacement(+ graph: SceneGraph,+ roots: readonly SceneNode[]+): ClipboardPlacement {+ const parentOf = (node: SceneNode) => (node.parentId ? graph.getNode(node.parentId) : undefined)+ const transforms = roots.map((node) =>+ Matrix.multiply(getParentWorldMatrix(parentOf(node), graph), getNodeLocalMatrix(node))+ )+ const sources = roots.map((node) => {+ const parent = parentOf(node)+ if (!parent || parent.type === 'CANVAS' || parent.id === graph.rootId) return null+ return { id: parent.id, box: getAxisAlignedWorldBounds(parent, graph) }+ })+ return { transforms, sources }+}++/** The canvas box around layers, through every rotation and flip above them. */+function canvasBounds(graph: SceneGraph, nodes: readonly SceneNode[]): Rect {+ return getAxisAlignedBoundsInParent(nodes, graph.rootId, graph)+}++/** Moves layers by a distance on the canvas, whatever their parents' rotation and flips. */+export function translateOnCanvas(+ graph: SceneGraph,+ nodeIds: readonly string[],+ dx: number,+ dy: number+) {+ if (dx === 0 && dy === 0) return+ for (const id of nodeIds) {+ const node = graph.getNode(id)+ if (!node) continue+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ const toParent = Matrix.invert(getParentWorldMatrix(parent, graph))+ if (!toParent) continue+ const origin = Matrix.mapPoint(toParent, { x: 0, y: 0 })+ const moved = Matrix.mapPoint(toParent, { x: dx, y: dy })+ graph.updateNode(id, { x: node.x + moved.x - origin.x, y: node.y + moved.y - origin.y })}+}++/**+ * How far Figma moves pasted layers that come from one place to keep them in their frame's+ * canvas box. An axis counts as outside when the layers start at or past the frame's far edge,+ * or, for top-level layers, when they miss the frame on it; layers overlapping an edge stay. If+ * an axis is outside, layers that fit in the frame are centred on the outside axes; larger ones+ * go to the frame's top-left when they came out of a frame, or are centred when top-level.+ */+function frameFitShift(box: Rect, frame: Rect, fromFrame: boolean): Vector {+ const outside = (start: number, size: number, frameStart: number, frameSize: number) => {+ const offset = start - frameStart+ return offset >= frameSize || (!fromFrame && offset + size <= 0)+ }+ const outX = outside(box.x, box.width, frame.x, frame.width)+ const outY = outside(box.y, box.height, frame.y, frame.height)+ if (!outX && !outY) return { x: 0, y: 0 }+ const centred = {+ x: frame.x + (frame.width - box.width) / 2 - box.x,+ y: frame.y + (frame.height - box.height) / 2 - box.y+ }+ if (box.width <= frame.width && box.height <= frame.height)+ return { x: outX ? centred.x : 0, y: outY ? centred.y : 0 }+ return fromFrame ? { x: frame.x - box.x, y: frame.y - box.y } : centred+}+export function createClipboardPlacementActions(ctx: EditorContext) {/*** Where Figma puts a lone duplicate: on top of the original, except that a top-level frame, on* the page or in a section, goes to the first free place on its right.@@ -87,87 +167,113 @@ export function createClipboardPlacementActions(ctx: EditorContext) {*/function placeForeignPaste(nodeIds: string[], parentId: string, cursor?: Vector) {if (cursor) {- centerNodesAtCanvasPoint(nodeIds, parentId, cursor)+ centerNodesAtCanvasPoint(nodeIds, cursor)return}const view = viewportRect()if (view)- centerNodesAtCanvasPoint(nodeIds, parentId, {+ centerNodesAtCanvasPoint(nodeIds, {x: view.x + view.width / 2,y: view.y + view.height / 2})fitInside(nodeIds, parentId)}- /** Centers layers of `parentId` over another layer, wherever that layer sits. */- function centerOver(nodeIds: string[], parentId: string, overId: string) {+ function nodesOf(nodeIds: readonly string[]) {+ return nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)+ }++ /** Centers layers over another layer, wherever that layer sits. */+ function centerOver(nodeIds: string[], overId: string) {const over = ctx.graph.getNode(overId)if (!over) returncenterNodesAtCanvasPoint(nodeIds,- parentId,Matrix.mapPoint(getWorldMatrix(over, ctx.graph), { x: over.width / 2, y: over.height / 2 }))}+ /** Turns and flips pasted layers back to how they were drawn when copied, as Figma keeps them. */+ function keepCanvasTransforms(nodeIds: readonly string[], transforms: readonly Mat3[]) {+ for (const [index, world] of transforms.entries()) {+ const id = nodeIds.at(index)+ const node = id ? ctx.graph.getNode(id) : undefined+ if (!id || !node) continue+ const parent = node.parentId ? ctx.graph.getNode(node.parentId) : undefined+ const local = localTransformFromWorld(node, world, getParentWorldMatrix(parent, ctx.graph))+ if (local) ctx.graph.updateNode(id, local)+ }+ }+/**- * Places pasted layers as Figma does. Layers copied out of a frame keep their offset inside the- * frame they are pasted into; top-level layers keep their place on the canvas. An axis that- * does not fit inside the destination frame is centered in it, and layers that would land out- * of view are centered in the view. A paste that could not go into the selected layer- * (`requestedId`), such as an instance into its own main component, lands over that layer.+ * Places pasted layers as Figma does, in canvas boxes so a rotated or flipped frame changes+ * nothing. Layers copied out of a frame keep their offset from its box in the box of the frame+ * they are pasted into; top-level layers keep their place on the canvas. Layers Figma counts as+ * outside the destination frame move into it (`frameFitShift`), and layers that would land out+ * of view are centred in the view. A paste that could not go into the selected layer (`requestedId`), such+ * as an instance into its own main component, lands over that layer.*/function placePasted(nodeIds: string[],- sourceParentId: string | undefined,+ placement: ClipboardPlacement,targetId: string,requestedId = targetId) {if (requestedId !== targetId) {- centerOver(nodeIds, targetId, requestedId)+ centerOver(nodeIds, requestedId)return}- const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)- if (items.length === 0) return+ if (nodesOf(nodeIds).length === 0) returnconst target = ctx.graph.getNode(targetId)- const source = sourceParentId ? ctx.graph.getNode(sourceParentId) : undefined- const toCanvas = (node: SceneNode | undefined) =>- node && node.type !== 'CANVAS' ? ctx.graph.getAbsolutePosition(node.id) : { x: 0, y: 0 }-- // Copied coordinates are relative to the source frame, or absolute for top-level layers.- const relative = source !== undefined && source.type !== 'CANVAS'- if (!relative || target?.type === 'CANVAS') {- const from = relative ? toCanvas(source) : { x: 0, y: 0 }- const to = toCanvas(target)- translate(nodeIds, from.x - to.x, from.y - to.y)+ const frame =+ target && target.type !== 'CANVAS' ? getAxisAlignedWorldBounds(target, ctx.graph) : null+ if (frame) {+ // Layers from different places, such as a frame's child and a page-level layer, are placed+ // apart, each set as one block.+ const groups = groupBy(+ nodeIds.map((id, index) => ({ id, source: placement.sources.at(index) ?? null })),+ ({ source }) => source?.id ?? ''+ )+ for (const group of Object.values(groups)) {+ const ids = group.map(({ id }) => id)+ const { source } = group[0]+ if (source)+ translateOnCanvas(ctx.graph, ids, frame.x - source.box.x, frame.y - source.box.y)+ const shift = frameFitShift(canvasBounds(ctx.graph, nodesOf(ids)), frame, source !== null)+ translateOnCanvas(ctx.graph, ids, shift.x, shift.y)+ }}- fitInside(nodeIds, targetId)-const view = viewportRect()if (!view) return- const origin = toCanvas(target)- const box = computeBounds(items)- if (!overlaps({ ...box, x: box.x + origin.x, y: box.y + origin.y }, view)) {- centerNodesAt(+ const box = canvasBounds(ctx.graph, nodesOf(nodeIds))+ if (!overlaps(box, view)) {+ translateOnCanvas(+ ctx.graph,nodeIds,- view.x + view.width / 2 - origin.x,- view.y + view.height / 2 - origin.y+ view.x + (view.width - box.width) / 2 - box.x,+ view.y + (view.height - box.height) / 2 - box.y)}}- /** Centers layers of `parentId` on a canvas point, through the parent's rotation and flips. */- function centerNodesAtCanvasPoint(nodeIds: string[], parentId: string, point: Vector) {- const toParent = Matrix.invert(getParentWorldMatrix(ctx.graph.getNode(parentId), ctx.graph))- const local = toParent ? Matrix.mapPoint(toParent, point) : point- centerNodesAt(nodeIds, local.x, local.y)+ /** Centers layers on a canvas point, through their parents' rotation and flips. */+ function centerNodesAtCanvasPoint(nodeIds: string[], point: Vector) {+ const items = nodesOf(nodeIds)+ if (items.length === 0) return+ const box = canvasBounds(ctx.graph, items)+ translateOnCanvas(+ ctx.graph,+ nodeIds,+ point.x - (box.x + box.width / 2),+ point.y - (box.y + box.height / 2)+ )}return {- centerNodesAt,centerNodesAtCanvasPoint,duplicatePosition,+ keepCanvasTransforms,placeForeignPaste,placePasted}diff --git a/packages/core/src/editor/clipboard/snapshot.ts b/packages/core/src/editor/clipboard/snapshot.tsindex e0342b1a9..b8940c2a8 100644--- a/packages/core/src/editor/clipboard/snapshot.ts+++ b/packages/core/src/editor/clipboard/snapshot.ts@@ -1,5 +1,6 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { clipboardPlacement, type ClipboardPlacement } from './placement'import { captureClipboardVariables, type ClipboardVariables } from './variables'export type ClipboardNodeTree = SceneNode & { children?: ClipboardNodeTree[] }@@ -10,6 +11,8 @@ export interface ClipboardSnapshot {styleDefinitions: SceneNode[]variableDependencies: ClipboardVariablesnodes: ClipboardNodeTree[]+ /** Where the copied layers sat on the canvas when they were copied. */+ placement: ClipboardPlacementimages: Map<string, Uint8Array>}@@ -72,6 +75,7 @@ export function captureClipboardSnapshot(styleDefinitions,variableDependencies: captureClipboardVariables(graph, capturedNodes),nodes,+ placement: clipboardPlacement(graph, roots),images}}diff --git a/packages/core/tests/editor/clipboard/paste/replace.test.ts b/packages/core/tests/editor/clipboard/paste/replace.test.tsindex 642ba2116..0023d652a 100644--- a/packages/core/tests/editor/clipboard/paste/replace.test.ts+++ b/packages/core/tests/editor/clipboard/paste/replace.test.ts@@ -3,6 +3,7 @@ import { describe, expect, test } from 'bun:test'import { buildOpenPencilClipboardHTML } from '@open-pencil/core/clipboard'import { createEditor } from '@open-pencil/core/editor'import type { Editor } from '@open-pencil/core/editor'+import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'function copiedRectangleHTML(name = 'Pasted') {const source = createEditor()@@ -37,6 +38,21 @@ function copiedFrameHTML() {return buildOpenPencilClipboardHTML([frame], source.graph)}+function canvasBox(editor: Editor, id: string) {+ const node = editor.graph.getNode(id)+ if (!node) throw new Error(`Missing layer ${id}`)+ const box = getAxisAlignedWorldBounds(node, editor.graph)+ return { x: Math.round(box.x), y: Math.round(box.y) }+}++/** The layer's x and y axes on the canvas, rounded: `[1, 0, 0, 1]` when drawn upright. */+function canvasAxes(editor: Editor, id: string) {+ const node = editor.graph.getNode(id)+ if (!node) throw new Error(`Missing layer ${id}`)+ const [a, c, , b, d] = getWorldMatrix(node, editor.graph)+ return [a, b, c, d].map((value) => Math.round(value) + 0)+}+function createTarget(editor: Editor, parentId = editor.state.currentPageId) {return editor.graph.createNode('ELLIPSE', parentId, {name: 'Target',@@ -168,7 +184,7 @@ describe('paste to replace', () => {expect(editor.graph.getNode(frame.id)?.childIds).toEqual([before.id, createdId, after.id])})- test('starts the replacement where the target started, inside an offset, rotated, or flipped frame', async () => {+ test('starts the replacement where the target started on the canvas, upright, inside an offset, rotated, or flipped frame', async () => {const html = copiedRectangleHTML()const editor = createEditor()const frame = editor.graph.createNode('FRAME', editor.state.currentPageId, {@@ -178,16 +194,22 @@ describe('paste to replace', () => {height: 300})const target = createTarget(editor, frame.id)- for (const transform of [{}, { rotation: 90 }, { rotation: 0, flipY: true }]) {+ for (const transform of [+ {},+ { rotation: 90 },+ { rotation: 30 },+ { rotation: 0, flipY: true }+ ]) {editor.graph.updateNode(frame.id, transform)+ const start = canvasBox(editor, target.id)editor.select([target.id])await editor.pasteFromHTML(html, undefined, { replaceSelection: true })- // Figma keeps the target's top-left rather than its centre (desktop 126).- expect(editor.graph.getNode([...editor.state.selectedIds][0])).toMatchObject({- parentId: frame.id,- x: 100,- y: 100- })+ const [createdId] = editor.state.selectedIds+ // Figma keeps the target's canvas top-left, and the replacement as it was drawn when copied+ // (desktop 126).+ expect(editor.graph.getNode(createdId)?.parentId).toBe(frame.id)+ expect(canvasBox(editor, createdId)).toMatchObject({ x: start.x, y: start.y })+ expect(canvasAxes(editor, createdId)).toEqual([1, 0, 0, 1])editor.undo.undo()}})@@ -195,8 +217,16 @@ describe('paste to replace', () => {test('an instance replacing a layer inside its own component stays out of it', async () => {const editor = createEditor()const page = editor.state.currentPageId- const card = editor.graph.createNode('COMPONENT', page, { name: 'Card', width: 200, height: 200 })- const inner = editor.graph.createNode('FRAME', card.id, { name: 'Inner', width: 100, height: 100 })+ const card = editor.graph.createNode('COMPONENT', page, {+ name: 'Card',+ width: 200,+ height: 200+ })+ const inner = editor.graph.createNode('FRAME', card.id, {+ name: 'Inner',+ width: 100,+ height: 100+ })const target = createTarget(editor, inner.id)const instance = editor.graph.createInstance(card.id, page, { x: 400 })if (!instance) throw new Error('Expected an instance')diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.tsindex c293e7bdf..275ea5865 100644--- a/packages/core/tests/editor/clipboard/placement.test.ts+++ b/packages/core/tests/editor/clipboard/placement.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from 'bun:test'import { createEditor, type Editor } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'-import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import { getAxisAlignedWorldBounds, getWorldMatrix } from '@open-pencil/scene-graph/coordinate'import Matrix from '@open-pencil/scene-graph/matrix'// Each case matches Cmd+D or Cmd+V observed in Figma desktop 126.@@ -29,6 +29,33 @@ function worldCenter(layer: SceneNode) {return { x: Math.round(center.x), y: Math.round(center.y) }}+/** A layer's box on the canvas, rounded to tenths. */+function canvasBox(layer: SceneNode) {+ const box = getAxisAlignedWorldBounds(layer, editor.graph)+ const round = (value: number) => Math.round(value * 10) / 10 + 0+ return { x: round(box.x), y: round(box.y), width: round(box.width), height: round(box.height) }+}++/** A layer's x and y axes on the canvas, rounded, which say how it is turned and flipped. */+function canvasAxes(layer: SceneNode) {+ const [a, c, , b, d] = getWorldMatrix(layer, editor.graph)+ return [a, b, c, d].map((value) => Math.round(value * 1000) / 1000 + 0)+}++/** Where a layer's canvas box starts in a frame's canvas box. */+function offsetIn(layer: SceneNode, frame: SceneNode) {+ const box = getAxisAlignedWorldBounds(layer, editor.graph)+ const outer = getAxisAlignedWorldBounds(frame, editor.graph)+ const round = (value: number) => Math.round(value * 10) / 10 + 0+ return { x: round(box.x - outer.x), y: round(box.y - outer.y) }+}++async function pasteInto(snapshot: Awaited<ReturnType<typeof copy>>, targetId: string) {+ editor.select([targetId])+ await editor.pasteSnapshot(snapshot)+ return selected()+}+function selected() {const [id] = editor.state.selectedIdsconst found = editor.graph.getNode(id)@@ -217,3 +244,192 @@ describe('paste placement', () => {expect(selected()).toMatchObject({ parentId: holder.id, x: 80, y: 40 })})})++// Each case replays a paste into a frame observed in Figma desktop 126, which works in canvas+// boxes: what is rotated or flipped above the layers changes neither their offset nor the rules.+describe('paste orientation', () => {+ /** A page whose view takes in every frame these cases paste into. */+ function wideSetup() {+ const page = setup()+ editor.state.zoom = 0.2+ return page+ }++ function frames(page: string) {+ return {+ turned: node('FRAME', page, { x: 1000, y: 100, width: 300, height: 200, rotation: 30 }),+ upright: node('FRAME', page, { x: 1500, y: 100, width: 300, height: 200 }),+ back: node('FRAME', page, { x: 2000, y: 100, width: 300, height: 200, rotation: -45 }),+ flipped: node('FRAME', page, { x: 2500, y: 100, width: 300, height: 200, flipX: true })+ }+ }++ test('a layer keeps how it is turned and flipped on the canvas, in any frame', async () => {+ const page = wideSetup()+ const { turned, upright, back, flipped } = frames(page)+ const box = node('RECTANGLE', turned.id, { x: 40, y: 50, width: 60, height: 30 })+ const tilted = node('RECTANGLE', turned.id, {+ x: 150,+ y: 80,+ width: 30,+ height: 30,+ rotation: 20+ })+ const axes = canvasAxes(box)+ const snapshot = await copy(box.id)+ for (const target of [upright, back, flipped, turned]) {+ const pasted = await pasteInto(snapshot, target.id)+ expect(pasted.parentId).toBe(target.id)+ expect(canvasAxes(pasted)).toEqual(axes)+ expect(offsetIn(pasted, target)).toEqual(offsetIn(box, turned))+ }++ editor.select([box.id, tilted.id])+ const both = await editor.prepareCopy()+ if (!both.snapshot) throw new Error('Missing snapshot')+ editor.select([upright.id])+ await editor.pasteSnapshot(both.snapshot)+ const pasted = [...editor.state.selectedIds].map((id) => editor.graph.getNode(id))+ expect(pasted.map((layer) => layer && canvasAxes(layer))).toEqual([+ canvasAxes(box),+ canvasAxes(tilted)+ ])+ expect(pasted.map((layer) => layer && offsetIn(layer, upright))).toEqual([+ offsetIn(box, turned),+ offsetIn(tilted, turned)+ ])+ })++ test('a layer from an upright frame keeps its offset in a turned frame’s canvas box', async () => {+ const page = wideSetup()+ const { turned, upright } = frames(page)+ const small = node('FRAME', page, { x: 3000, y: 100, width: 120, height: 80, rotation: 60 })+ for (const [x, y, width] of [+ [40, 50, 60],+ [220, 160, 60]+ ]) {+ const box = node('RECTANGLE', upright.id, { x, y, width, height: 30 })+ const pasted = await pasteInto(await copy(box.id), turned.id)+ expect(canvasAxes(pasted)).toEqual([1, 0, 0, 1])+ expect(offsetIn(pasted, turned)).toEqual({ x, y })+ }+ // Wider than the frame's box, but starting inside it, so it stays.+ const wide = node('RECTANGLE', upright.id, { x: 50, y: 10, width: 200, height: 30 })+ expect(offsetIn(await pasteInto(await copy(wide.id), small.id), small)).toEqual({+ x: 50,+ y: 10+ })+ })++ test('a top-level layer keeps its canvas place and turn, centred on an axis off the frame', async () => {+ const page = wideSetup()+ const { turned } = frames(page)+ const box = node('RECTANGLE', page, { x: 1200, y: 600, width: 60, height: 30, rotation: 10 })+ const before = canvasBox(box)+ const pasted = await pasteInto(await copy(box.id), turned.id)+ const frame = canvasBox(turned)+ expect(canvasAxes(pasted)).toEqual(canvasAxes(box))+ expect(canvasBox(pasted).x).toBe(before.x)+ expect(canvasBox(pasted).y).toBeCloseTo(frame.y + (frame.height - before.height) / 2, 0)+ })++ test('a layer from a frame is centred only on an axis where it starts past the far edge', async () => {+ const page = wideSetup()+ const source = node('FRAME', page, { x: 1500, y: 100, width: 300, height: 200 })+ const target = node('FRAME', page, { x: 2000, y: 100, width: 120, height: 80 })+ for (const [x, width, expected] of [+ [50, 200, 50],+ [100, 30, 100],+ [119, 30, 119],+ [120, 30, 45],+ [130, 30, 45],+ [200, 30, 45],+ [-20, 60, -20],+ [-50, 30, -50]+ ]) {+ const box = node('RECTANGLE', source.id, { x, y: 10, width, height: 20 })+ expect(await pasteInto(await copy(box.id), target.id)).toMatchObject({ x: expected, y: 10 })+ }+ })++ test('a top-level layer is centred only on an axis where it misses the frame', async () => {+ const page = wideSetup()+ const target = node('FRAME', page, { x: 100, y: 100, width: 120, height: 80 })+ for (const [x, y, width, expected] of [+ [-50, 10, 30, { x: 45, y: 10 }],+ [-10, 10, 30, { x: -10, y: 10 }],+ [130, 10, 30, { x: 45, y: 10 }],+ [100, 10, 30, { x: 100, y: 10 }],+ [10, -50, 30, { x: 10, y: 30 }],+ [10, 100, 30, { x: 10, y: 30 }],+ [50, 10, 200, { x: 50, y: 10 }]+ ] as const) {+ const box = node('RECTANGLE', page, { x: 100 + x, y: 100 + y, width, height: 20 })+ expect(await pasteInto(await copy(box.id), target.id)).toMatchObject(expected)+ }+ })++ /** Copies layers together and pastes them into a frame, giving their places in it. */+ async function pasteTogether(layers: SceneNode[], targetId: string) {+ editor.select(layers.map((layer) => layer.id))+ const { snapshot } = await editor.prepareCopy()+ if (!snapshot) throw new Error('Missing snapshot')+ editor.select([targetId])+ await editor.pasteSnapshot(snapshot)+ return [...editor.state.selectedIds].map((id) => {+ const pasted = editor.graph.getNode(id)+ return pasted && [pasted.x, pasted.y]+ })+ }++ test('layers from one frame move as a block, to the top-left when larger than the frame', async () => {+ const page = wideSetup()+ const source = node('FRAME', page, { x: 1500, y: 100, width: 300, height: 200 })+ const target = node('FRAME', page, { x: 2000, y: 100, width: 120, height: 80 })+ const at = (x: number, y: number, height = 20) =>+ node('RECTANGLE', source.id, { x, y, width: 30, height })+ // The block starts inside, so it stays.+ expect(await pasteTogether([at(20, 10), at(200, 10)], target.id)).toEqual([+ [20, 10],+ [200, 10]+ ])+ // Past the right edge and fitting: centred across only.+ expect(await pasteTogether([at(200, 10), at(250, 10)], target.id)).toEqual([+ [20, 10],+ [70, 10]+ ])+ // Past the right edge and taller than the frame: to its top-left.+ expect(await pasteTogether([at(200, 10), at(200, 150)], target.id)).toEqual([+ [0, 0],+ [0, 140]+ ])+ expect(await pasteTogether([at(200, 10, 160)], target.id)).toEqual([[0, 0]])+ const wide = node('RECTANGLE', source.id, { x: 60, y: 100, width: 200, height: 20 })+ expect(await pasteTogether([wide], target.id)).toEqual([[0, 0]])+ })++ test('a top-level layer larger than the frame is centred both ways once it misses it', async () => {+ const page = wideSetup()+ const target = node('FRAME', page, { x: 100, y: 100, width: 120, height: 80 })+ const wide = node('RECTANGLE', page, { x: 110, y: 0, width: 200, height: 20 })+ const tall = node('RECTANGLE', page, { x: 300, y: 110, width: 30, height: 160 })+ expect(await pasteTogether([wide], target.id)).toEqual([[-40, 30]])+ expect(await pasteTogether([tall], target.id)).toEqual([[45, -40]])+ })++ test('a frame child and a page-level layer copied together are placed each from its own place', async () => {+ const page = wideSetup()+ const source = node('FRAME', page, { x: 1000, y: 100, width: 300, height: 200 })+ const child = node('RECTANGLE', source.id, { x: 40, y: 50, width: 60, height: 30 })+ const loose = node('RECTANGLE', page, { x: 1100, y: 400, width: 60, height: 30 })+ const target = node('FRAME', page, { x: 1500, y: 100, width: 400, height: 400 })+ for (const order of [+ [child, loose],+ [loose, child]+ ]) {+ const places = await pasteTogether(order, target.id)+ const byName = order.map((layer, index) => [layer.id, places[index]])+ expect(Object.fromEntries(byName)).toEqual({ [child.id]: [40, 50], [loose.id]: [170, 300] })+ }+ })+})