Skip to content

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

fix: match Figma when dragging, drawing, duplicating, and pasting (#894)

Danila Poyarkov69dbc36a7e77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ab01be610..3a92a7f8f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@
- `openpencil documents` is now a command group: list open documents with `openpencil documents list`.
- The MCP `close_file` tool no longer asks in the app whether to save unsaved changes, a question an agent could not answer and that left the call timing out. With unsaved changes it now fails unless `unsaved` is `"save"` or `"discard"`, and it is marked as a write tool.
- OpenPencil's plugin-data keys are defined once in `OPEN_PENCIL_PLUGIN_DATA` from `@open-pencil/scene-graph`, each with the schema that reads and writes it, and read or replaced with `readPluginData` and `withPluginData`. `@open-pencil/fig/node-change` no longer exports `OPEN_PENCIL_PLUGIN_ID` (now in `@open-pencil/scene-graph`), the `*_PLUGIN_KEY` constants, `upsertPluginData`, `removePluginData`, or `getOpenPencilPluginValue`; read a `.fig` record's value with `readNodeChangePluginData`. `@open-pencil/core` no longer exports `SOURCE_LIBRARY_PUBLICATION_PLUGIN_KEY`, and `SourceLibraryPublication` moved to `@open-pencil/scene-graph`.
+- `SceneGraph.hitTestFrame` is now `hitTestDropTarget`, which returns only layers that take a drop, as in Figma: it skips groups, boolean operations, component sets, and locked layers, follows rotation, and respects clipping. The editor's `adoptNodesIntoSection` is now `adoptCoveredLayers`, which also takes a frame, and leaves locked layers out.
### Added
@@ -58,6 +59,7 @@
### Changed
- HTML and Tailwind JSX export write variable-bound colors, spacing, radii, borders, sizes, type sizes, and opacity as the tokens they come from, such as `var(--color-primary)` or `bg-primary`, and put layers set to another mode in it with an attribute such as `data-theme="dark"`. Values CSS would not resolve as the canvas draws them stay literal, and standalone HTML includes the stylesheet for the tokens it uses.
+- Drag, draw, duplicate, and paste follow Figma. A dragged layer lands in the frame under the cursor and leaves its frame as soon as the cursor does; groups and locked frames never take a drop, a component set takes back only its own variants, and a layer inside a group stays in it unless dropped on another frame. Groups and booleans fit their children after a move or nudge, and a group whose last layer leaves is removed. Pressing inside a selected frame, group, or component set drags it rather than the layer under the cursor, and an auto layout child dragged out lands where you drop it. Hold Space while dragging to keep layers in their parents, Shift to move along one axis, or Control to drop into auto layout as an absolute-positioned layer. Locked layers stay put when the rest of the selection moves. Shapes drawn inside a frame, auto layout, or slot go into it, a frame drawn over layers takes in the ones it fully covers, and a section does so when moved or resized too. Wrapped auto layout inserts on the line under the cursor. Duplicates keep their names, and duplicating a main component with ⌘D or Alt-drag creates an instance. ⌘D duplicates in place, placing a lone top-level frame's copy to its right, and ⌘V keeps the copied position, centering an axis that doesn't fit the selected frame; **Paste here** still pastes at the cursor.
- Give popovers, menus, dropdowns, and pickers one look and motion: the same rounded panel with a thin outline that reads in light and dark themes, a short fade and grow from the side they open on, and an immediate close; with reduced motion they appear at once.
- Add and remove items the same way across the properties panel: a section's + adds an item and a row's − removes it, now including grid columns and rows and variant properties. The + of a component set adds Property 1 ready to rename instead of showing a form, and a variant is removed with Delete like any layer.
- Pick variables, shared styles, and swap components from one searchable list that groups preferred components first and works with the keyboard.
diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts
index c85f0c3a5..5b2d3b7a3 100644
--- a/packages/core/src/constants.ts
+++ b/packages/core/src/constants.ts
@@ -548,3 +548,5 @@ export const ROTATION_HANDLE_DISTANCE = 24
export const DEFAULT_TEXT_WIDTH = 200
export const DEFAULT_TEXT_HEIGHT = 24
export const AUTO_LAYOUT_BREAK_THRESHOLD = 8
+/** Space Figma leaves between a duplicated top-level frame and the layers to its left. */
+export const DUPLICATE_FRAME_GAP = 40
diff --git a/packages/core/src/editor/bridges/clipboard.ts b/packages/core/src/editor/bridges/clipboard.ts
index 2eab7734f..b4e35a84e 100644
--- a/packages/core/src/editor/bridges/clipboard.ts
+++ b/packages/core/src/editor/bridges/clipboard.ts
@@ -7,6 +7,7 @@ type SelectionActions = ReturnType<typeof createSelectionActions>
export function createClipboardBridge(clipboard: ClipboardActions, selection: SelectionActions) {
return {
duplicateSelected: () => clipboard.duplicateSelected(selection.getSelectedNodes()),
+ duplicateNode: clipboard.duplicateNode,
prepareCopy: () => clipboard.prepareCopy(selection.getSelectedNodes()),
pasteSnapshot: clipboard.pasteSnapshot,
pasteFromHTML: clipboard.pasteFromHTML,
diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.ts
index e0841aecc..449fff585 100644
--- a/packages/core/src/editor/clipboard.ts
+++ b/packages/core/src/editor/clipboard.ts
@@ -1,6 +1,7 @@
import { CommittedGraphEventError } from '@open-pencil/scene-graph'
import type { SceneNode } from '@open-pencil/scene-graph'
-import type { Vector } from '@open-pencil/scene-graph/primitives'
+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { parseFigmaClipboard, parseOpenPencilClipboard } from '#core/clipboard'
import { prepareClipboardImport } from '#core/clipboard/fig-import'
@@ -25,6 +26,23 @@ type PasteOptions = {
replaceSelection?: boolean
}
+/**
+ * A copy of the layer under the same parent, keeping its name as Figma does. A main component
+ * outside a component set duplicates as an instance of itself.
+ */
+export function duplicateNode(
+ ctx: Pick<EditorContext, 'graph'>,
+ node: SceneNode,
+ parentId: string,
+ position: Vector
+): SceneNode | null {
+ const parent = ctx.graph.getNode(parentId)
+ if (node.type === 'COMPONENT' && parent?.type !== 'COMPONENT_SET') {
+ return ctx.graph.createInstance(node.id, parentId, { name: node.name, ...position })
+ }
+ return ctx.graph.cloneTree(node.id, parentId, { name: node.name, ...position })
+}
+
export function createClipboardActions(ctx: EditorContext) {
function duplicateSelected(selectedNodes: SceneNode[]) {
const prevSelection = new Set(ctx.state.selectedIds)
@@ -36,14 +54,16 @@ export function createClipboardActions(ctx: EditorContext) {
const newRootIds: string[] = []
const allSnapshots = new Map<string, SceneNode>()
+ const placed: Rect[] = []
for (const node of topLevel) {
const parentId = node.parentId ?? ctx.state.currentPageId
- const clone = ctx.graph.cloneTree(node.id, parentId, {
- name: node.name + ' copy',
- x: node.x + 20,
- y: node.y + 20
- })
+ const position =
+ topLevel.length === 1
+ ? placementActions.duplicatePosition(node, placed)
+ : { x: node.x, y: node.y }
+ const clone = duplicateNode(ctx, node, parentId, position)
if (!clone) continue
+ placed.push(getAxisAlignedBoundsInParent([clone], parentId, ctx.graph))
newRootIds.push(clone.id)
const subtree = snapshotSubtree(ctx.graph, clone.id)
for (const [id, snap] of subtree) allSnapshots.set(id, snap)
@@ -216,8 +236,6 @@ export function createClipboardActions(ctx: EditorContext) {
const { id: _id, childIds: _childIds, children = [], parentId: _parentId, ...rest } = source
const node = ctx.graph.createNode(source.type, parentId, {
...structuredClone(rest),
- x: source.x + 20,
- y: source.y + 20,
childIds: []
})
copiedIds.set(source.id, node.id)
@@ -267,7 +285,8 @@ export function createClipboardActions(ctx: EditorContext) {
return created
}
- if (cursorPos) placementActions.centerNodesAt(created, cursorPos.x, cursorPos.y)
+ if (cursorPos) placementActions.centerNodesAtCanvasPoint(created, pasteTarget, cursorPos)
+ else placementActions.placePasted(created, nodes[0]?.parentId ?? undefined, pasteTarget)
computeAllLayouts(ctx.graph, ctx.state.currentPageId)
ctx.setSelectedIds(new Set(created))
@@ -394,6 +413,8 @@ export function createClipboardActions(ctx: EditorContext) {
...placementActions,
...fontActions,
duplicateSelected,
+ duplicateNode: (node: SceneNode, parentId: string, position: Vector) =>
+ duplicateNode(ctx, node, parentId, position),
...copyActions,
pasteSnapshot,
pasteFromHTML,
diff --git a/packages/core/src/editor/clipboard/placement.ts b/packages/core/src/editor/clipboard/placement.ts
index df0740b1a..5069057ad 100644
--- a/packages/core/src/editor/clipboard/placement.ts
+++ b/packages/core/src/editor/clipboard/placement.ts
@@ -1,9 +1,17 @@
import { isNotNil } from 'es-toolkit/predicate'
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
import { computeBounds } from '@open-pencil/scene-graph/geometry'
+import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
+import { DUPLICATE_FRAME_GAP } from '#core/constants'
import type { EditorContext } from '#core/editor/types'
+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)
@@ -17,5 +25,100 @@ export function createClipboardPlacementActions(ctx: EditorContext) {
}
}
- return { centerNodesAt }
+ /**
+ * 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.
+ */
+ function duplicatePosition(node: SceneNode, placed: readonly Rect[]): Vector {
+ const parentId = node.parentId ?? ctx.state.currentPageId
+ const parent = ctx.graph.getNode(parentId)
+ const topLevel = !parent || parent.type === 'CANVAS' || parent.type === 'SECTION'
+ if (node.type !== 'FRAME' || !topLevel) return { x: node.x, y: node.y }
+
+ const box = getAxisAlignedBoundsInParent([node], parentId, ctx.graph)
+ const others = [
+ ...ctx.graph
+ .getChildren(parentId)
+ .map((sibling) => getAxisAlignedBoundsInParent([sibling], parentId, ctx.graph)),
+ ...placed
+ ]
+ const candidate = { ...box, x: box.x + box.width + DUPLICATE_FRAME_GAP }
+ for (;;) {
+ const blocker = others.find((other) => overlaps(candidate, other))
+ if (!blocker) break
+ candidate.x = blocker.x + blocker.width + DUPLICATE_FRAME_GAP
+ }
+ return { x: node.x + candidate.x - box.x, y: node.y }
+ }
+
+ function translate(nodeIds: string[], dx: number, dy: number) {
+ for (const id of nodeIds) {
+ const node = ctx.graph.getNode(id)
+ if (node) ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })
+ }
+ }
+
+ /** The visible part of the canvas, or null when the editor has no viewport. */
+ function viewportRect(): Rect | null {
+ const { width, height } = ctx.getViewportSize()
+ if (width <= 0 || height <= 0) return null
+ const { panX, panY, zoom } = ctx.state
+ return { x: -panX / zoom, y: -panY / zoom, width: width / zoom, height: height / zoom }
+ }
+
+ /**
+ * 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.
+ */
+ function placePasted(nodeIds: string[], sourceParentId: string | undefined, targetId: string) {
+ const items = nodeIds.map((id) => ctx.graph.getNode(id)).filter(isNotNil)
+ if (items.length === 0) return
+ const 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)
+ }
+
+ if (target && target.type !== 'CANVAS') {
+ const box = computeBounds(items)
+ const fitsX = box.x >= 0 && box.x + box.width <= target.width
+ const fitsY = box.y >= 0 && box.y + box.height <= target.height
+ translate(
+ nodeIds,
+ fitsX ? 0 : (target.width - box.width) / 2 - box.x,
+ fitsY ? 0 : (target.height - box.height) / 2 - box.y
+ )
+ }
+
+ 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(
+ nodeIds,
+ view.x + view.width / 2 - origin.x,
+ view.y + view.height / 2 - origin.y
+ )
+ }
+ }
+
+ /** Centers layers of `parentId` on a canvas point. */
+ function centerNodesAtCanvasPoint(nodeIds: string[], parentId: string, point: Vector) {
+ const parent = ctx.graph.getNode(parentId)
+ const origin =
+ parent && parent.type !== 'CANVAS' ? ctx.graph.getAbsolutePosition(parentId) : { x: 0, y: 0 }
+ centerNodesAt(nodeIds, point.x - origin.x, point.y - origin.y)
+ }
+
+ return { centerNodesAt, centerNodesAtCanvasPoint, duplicatePosition, placePasted }
}
diff --git a/packages/core/src/editor/nudge.ts b/packages/core/src/editor/nudge.ts
index 136b9b662..40f583e00 100644
--- a/packages/core/src/editor/nudge.ts
+++ b/packages/core/src/editor/nudge.ts
@@ -1,6 +1,7 @@
import type { Vector } from '@open-pencil/scene-graph/primitives'
import { collectNodePositions, pushPositionUndo } from './history/position'
+import { fitEnclosingGroups } from './structure/group-bounds'
import type { EditorContext } from './types'
const NUDGE_COMMIT_DELAY = 300
@@ -16,7 +17,13 @@ export function createNudgeActions(ctx: EditorContext) {
nudgeCommitTimer = null
const finals = collectNodePositions(ctx, originals.keys())
- pushPositionUndo(ctx, 'Nudge', originals, finals)
+ const parentIds = [...originals.keys()].flatMap((id) => ctx.graph.getNode(id)?.parentId ?? [])
+ // Groups and booleans fit their nudged children, in the same undo step.
+ ctx.undo.runBatch('Nudge', () => {
+ pushPositionUndo(ctx, 'Nudge', originals, finals)
+ fitEnclosingGroups(ctx, parentIds)
+ })
+ ctx.requestRender()
}
function nudgeSelected(dx: number, dy: number) {
diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.ts
index b3212f319..8a3ecc859 100644
--- a/packages/core/src/editor/shapes.ts
+++ b/packages/core/src/editor/shapes.ts
@@ -8,9 +8,10 @@ import {
SECTION_DEFAULT_STROKE
} from '#core/constants'
+import { prepareSlotEdits } from './components/slots'
+import { adoptCoveredLayers } from './shapes/adopt'
import { createFramePresetActions } from './shapes/frame-presets'
import { createPenActions } from './shapes/pen'
-import { adoptNodesIntoSection as adoptNodesIntoSectionImpl } from './shapes/section-adopt'
import type { EditorContext } from './types'
export type { PenDragOptions } from './shapes/pen'
@@ -44,6 +45,10 @@ export function createShapeActions(ctx: EditorContext) {
): string {
const fill = DEFAULT_FILLS[type] ?? DEFAULT_FILLS.RECTANGLE
const pid = parentId ?? ctx.state.currentPageId
+ // Inside an instance only a slot takes new layers, and the instance claims it first.
+ if (!prepareSlotEdits(ctx, [pid])) {
+ throw new Error('Cannot add a layer to the locked part of an instance')
+ }
const overrides: Partial<SceneNode> = {
x,
y,
@@ -92,7 +97,7 @@ export function createShapeActions(ctx: EditorContext) {
createShape,
...penActions,
...framePresetActions,
- adoptNodesIntoSection: (sectionId: string) => adoptNodesIntoSectionImpl(ctx, sectionId),
+ adoptCoveredLayers: (containerId: string) => adoptCoveredLayers(ctx, containerId),
setTool
}
}
diff --git a/packages/core/src/editor/shapes/adopt.ts b/packages/core/src/editor/shapes/adopt.ts
new file mode 100644
index 000000000..29ed77396
--- /dev/null
+++ b/packages/core/src/editor/shapes/adopt.ts
@@ -0,0 +1,64 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+import type { Rect } from '@open-pencil/scene-graph/primitives'
+
+import type { EditorContext } from '#core/editor/types'
+
+function covers(outer: Rect, inner: Rect) {
+ return (
+ inner.x >= outer.x &&
+ inner.y >= outer.y &&
+ inner.x + inner.width <= outer.x + outer.width &&
+ inner.y + inner.height <= outer.y + outer.height
+ )
+}
+
+function adoptable(container: SceneNode, sibling: SceneNode) {
+ if (sibling.id === container.id || sibling.locked) return false
+ // Sections only go into pages and other sections.
+ return sibling.type !== 'SECTION' || container.type === 'SECTION'
+}
+
+/**
+ * Moves the unlocked siblings a frame or section fully covers into it, as Figma does when one is
+ * drawn over layers or a section is moved or resized over them. Layers keep their places on the
+ * canvas.
+ */
+export function adoptCoveredLayers(ctx: EditorContext, containerId: string) {
+ const container = ctx.graph.getNode(containerId)
+ if (container?.type !== 'SECTION' && container?.type !== 'FRAME') return
+
+ const parentId = container.parentId ?? ctx.state.currentPageId
+ const area = getAxisAlignedBoundsInParent([container], parentId, ctx.graph)
+ const adopted = ctx.graph
+ .getChildren(parentId)
+ .filter(
+ (sibling) =>
+ adoptable(container, sibling) &&
+ covers(area, getAxisAlignedBoundsInParent([sibling], parentId, ctx.graph))
+ )
+ if (adopted.length === 0) return
+
+ const before = adopted.map((node) => ({ id: node.id, x: node.x, y: node.y }))
+ for (const node of adopted) ctx.graph.reparentNode(node.id, containerId)
+ const after = adopted.map((node) => {
+ const moved = ctx.graph.getNode(node.id)
+ return { id: node.id, x: moved?.x ?? node.x, y: moved?.y ?? node.y }
+ })
+
+ ctx.undo.push({
+ label: 'Adopt covered layers',
+ forward: () => {
+ for (const op of after) {
+ ctx.graph.reparentNode(op.id, containerId)
+ ctx.graph.updateNode(op.id, { x: op.x, y: op.y })
+ }
+ },
+ inverse: () => {
+ for (const op of before) {
+ ctx.graph.reparentNode(op.id, parentId)
+ ctx.graph.updateNode(op.id, { x: op.x, y: op.y })
+ }
+ }
+ })
+}
diff --git a/packages/core/src/editor/shapes/section-adopt.ts b/packages/core/src/editor/shapes/section-adopt.ts
deleted file mode 100644
index c0d99798b..000000000
--- a/packages/core/src/editor/shapes/section-adopt.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import type { EditorContext } from '#core/editor/types'
-
-export function adoptNodesIntoSection(ctx: EditorContext, sectionId: string) {
- const section = ctx.graph.getNode(sectionId)
- if (section?.type !== 'SECTION') return
-
- const parentId = section.parentId ?? ctx.state.currentPageId
- const siblings = ctx.graph.getChildren(parentId)
-
- const sx = section.x
- const sy = section.y
- const sx2 = sx + section.width
- const sy2 = sy + section.height
-
- const toAdopt: string[] = []
- for (const sibling of siblings) {
- if (sibling.id === sectionId) continue
- const nx = sibling.x
- const ny = sibling.y
- const nx2 = nx + sibling.width
- const ny2 = ny + sibling.height
- if (nx >= sx && ny >= sy && nx2 <= sx2 && ny2 <= sy2) {
- toAdopt.push(sibling.id)
- }
- }
-
- if (toAdopt.length === 0) return
-
- const undoOps: Array<{
- id: string
- oldParent: string
- oldX: number
- oldY: number
- newX: number
- newY: number
- }> = []
- for (const id of toAdopt) {
- const node = ctx.graph.getNode(id)
- if (!node) continue
- const newX = node.x - sx
- const newY = node.y - sy
- undoOps.push({ id, oldParent: parentId, oldX: node.x, oldY: node.y, newX, newY })
- ctx.graph.reparentNode(id, sectionId)
- ctx.graph.updateNode(id, { x: newX, y: newY })
- }
-
- ctx.undo.push({
- label: 'Adopt into section',
- forward: () => {
- for (const op of undoOps) {
- ctx.graph.reparentNode(op.id, sectionId)
- ctx.graph.updateNode(op.id, { x: op.newX, y: op.newY })
- }
- },
- inverse: () => {
- for (const op of undoOps) {
- ctx.graph.reparentNode(op.id, op.oldParent)
- ctx.graph.updateNode(op.id, { x: op.oldX, y: op.oldY })
- }
- }
- })
-}
diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.ts
index 34a93843f..d8641979d 100644
--- a/packages/core/src/editor/structure.ts
+++ b/packages/core/src/editor/structure.ts
@@ -2,6 +2,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'
import { DEFAULT_FRAME_FILL } from '#core/constants'
import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'
+import { fitEnclosingGroups } from '#core/editor/structure/group-bounds'
import { wrapInAutoLayout as wrapInAutoLayoutImpl } from './structure/auto-layout-wrap'
import {
@@ -164,6 +165,7 @@ export function createStructureActions(ctx: EditorContext) {
isTopLevel,
acceptsChildren: (parentId: string) => acceptsChildren(ctx, parentId),
acceptingParent: (parentId: string) => acceptingParent(ctx, parentId),
+ fitEnclosingGroups: (parentIds: Iterable<string>) => fitEnclosingGroups(ctx, parentIds),
...reorderActions,
reparentNodes,
wrapSelectionInContainer,
diff --git a/packages/core/src/editor/structure/group-bounds.ts b/packages/core/src/editor/structure/group-bounds.ts
new file mode 100644
index 000000000..c6562b009
--- /dev/null
+++ b/packages/core/src/editor/structure/group-bounds.ts
@@ -0,0 +1,103 @@
+import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
+import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'
+
+import type { EditorContext } from '#core/editor/types'
+
+/** Containers whose bounds follow their children, as in Figma. */
+const FITTED_TYPES = new Set<NodeType>(['GROUP', 'BOOLEAN_OPERATION'])
+
+type Placement = Pick<SceneNode, 'x' | 'y' | 'width' | 'height'>
+
+function placement(node: SceneNode): Placement {
+ return { x: node.x, y: node.y, width: node.width, height: node.height }
+}
+
+/** Groups and booleans holding the parents, innermost first. */
+function fittedAncestors(ctx: EditorContext, parentIds: Iterable<string>): SceneNode[] {
+ const found = new Map<string, { node: SceneNode; depth: number }>()
+ for (const parentId of parentIds) {
+ const chain: SceneNode[] = []
+ for (let node = ctx.graph.getNode(parentId); node && FITTED_TYPES.has(node.type);) {
+ chain.push(node)
+ node = ctx.graph.getNode(node.parentId ?? '')
+ }
+ for (const [index, node] of chain.entries()) {
+ found.set(node.id, {
+ node,
+ depth: Math.max(found.get(node.id)?.depth ?? 0, chain.length - index)
+ })
+ }
+ }
+ return [...found.values()].sort((a, b) => b.depth - a.depth).map(({ node }) => node)
+}
+
+interface FitRecord {
+ before: Map<string, Placement>
+ after: Map<string, Placement>
+ removed: Array<{ node: SceneNode; index: number }>
+}
+
+/** Moves the group to its children's bounds, shifting them back so they stay put. */
+function fitGroup(ctx: EditorContext, group: SceneNode, children: SceneNode[], record: FitRecord) {
+ if (!group.parentId || group.rotation !== 0 || group.flipX || group.flipY) return
+ const bounds = getAxisAlignedBoundsInParent(children, group.parentId, ctx.graph)
+ const dx = bounds.x - group.x
+ const dy = bounds.y - group.y
+ if (dx === 0 && dy === 0 && bounds.width === group.width && bounds.height === group.height) {
+ return
+ }
+ for (const node of [group, ...children]) {
+ if (!record.before.has(node.id)) record.before.set(node.id, placement(node))
+ }
+ ctx.graph.updateNode(group.id, bounds)
+ for (const child of children) {
+ ctx.graph.updateNode(child.id, { x: child.x - dx, y: child.y - dy })
+ }
+ for (const node of [group, ...children]) {
+ const current = ctx.graph.getNode(node.id)
+ if (current) record.after.set(node.id, placement(current))
+ }
+}
+
+/** A group left without layers goes away; an empty boolean stays, as in Figma. */
+function removeEmptyGroup(ctx: EditorContext, group: SceneNode, record: FitRecord) {
+ if (group.type !== 'GROUP' || !group.parentId) return
+ const index = ctx.graph.getNode(group.parentId)?.childIds.indexOf(group.id) ?? -1
+ record.removed.push({ node: structuredClone(group), index })
+ ctx.graph.deleteNode(group.id)
+}
+
+/**
+ * Refits the groups and booleans around these parents to their children after a move, keeping
+ * every child where it is on the canvas. Rotated or flipped containers keep their bounds.
+ */
+export function fitEnclosingGroups(ctx: EditorContext, parentIds: Iterable<string>) {
+ const record: FitRecord = { before: new Map(), after: new Map(), removed: [] }
+ for (const group of fittedAncestors(ctx, parentIds)) {
+ const children = ctx.graph.getChildren(group.id)
+ if (children.length === 0) removeEmptyGroup(ctx, group, record)
+ else fitGroup(ctx, group, children, record)
+ }
+
+ const { before, after, removed } = record
+ if (before.size === 0 && removed.length === 0) return
+ const apply = (placements: Map<string, Placement>) => {
+ for (const [id, value] of placements) ctx.graph.updateNode(id, value)
+ }
+ ctx.undo.push({
+ label: 'Fit groups',
+ forward: () => {
+ apply(after)
+ for (const { node } of removed) ctx.graph.deleteNode(node.id)
+ },
+ inverse: () => {
+ // Outer groups were removed after inner ones, so they come back first.
+ for (const { node, index } of removed.toReversed()) {
+ const parentId = node.parentId ?? ctx.state.currentPageId
+ ctx.graph.createNode(node.type, parentId, { ...structuredClone(node), childIds: [] })
+ if (index >= 0) ctx.graph.insertChildAt(node.id, parentId, index)
+ }
+ apply(before)
+ }
+ })
+}
diff --git a/packages/core/tests/editor/clipboard/placement.test.ts b/packages/core/tests/editor/clipboard/placement.test.ts
new file mode 100644
index 000000000..31cbb0d00
--- /dev/null
+++ b/packages/core/tests/editor/clipboard/placement.test.ts
@@ -0,0 +1,156 @@
+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'
+
+// Each case matches Cmd+D or Cmd+V observed in Figma desktop 126.
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ editor = createEditor({ getViewportSize: () => ({ width: 800, height: 600 }) })
+ return editor.state.currentPageId
+}
+
+function node(type: SceneNode['type'], parentId: string, props: Partial<SceneNode> = {}) {
+ return editor.graph.createNode(type, parentId, { width: 40, height: 40, ...props })
+}
+
+function selected() {
+ const [id] = editor.state.selectedIds
+ const found = editor.graph.getNode(id)
+ if (!found) throw new Error('Expected a selected layer')
+ return found
+}
+
+async function copy(id: string) {
+ editor.select([id])
+ const payload = await editor.prepareCopy()
+ if (!payload.snapshot) throw new Error('Missing snapshot')
+ return payload.snapshot
+}
+
+describe('duplicate placement', () => {
+ test('duplicates a layer on top of the original', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 200 })
+ for (const original of [node('RECTANGLE', page, { x: 100, y: 100 }), node('FRAME', frame.id, { x: 50, y: 50 })]) {
+ editor.select([original.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ parentId: original.parentId, x: original.x, y: original.y })
+ }
+ })
+
+ test('puts a duplicated top-level frame in the first free place to its right', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 150 })
+ editor.select([frame.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ x: 240, y: 0 })
+ })
+
+ test('skips past top-level layers in the way', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 150 })
+ node('FRAME', page, { x: 250, width: 100, height: 100 })
+ editor.select([frame.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ x: 390, y: 0 })
+ })
+
+ test('treats a frame in a section as top-level', () => {
+ const page = setup()
+ const section = node('SECTION', page, { width: 600, height: 300 })
+ node('FRAME', section.id, { x: 140, y: 50, width: 100, height: 100 })
+ const frame = node('FRAME', section.id, { x: 20, y: 50, width: 100, height: 100 })
+ editor.select([frame.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ parentId: section.id, x: 280, y: 50 })
+ })
+
+ test('duplicates a multi-selection in place, keeping names', () => {
+ const page = setup()
+ const a = node('FRAME', page, { name: 'A', width: 100, height: 100 })
+ const b = node('FRAME', page, { name: 'B', x: 140, width: 100, height: 100 })
+ editor.select([a.id, b.id])
+ editor.duplicateSelected()
+ const copies = [...editor.state.selectedIds].map((id) => editor.graph.getNode(id))
+ expect(copies.map((n) => [n?.name, n?.x, n?.y])).toEqual([
+ ['A', 0, 0],
+ ['B', 140, 0]
+ ])
+ })
+
+ test('duplicates a main component as an instance, but a variant as a variant', () => {
+ const page = setup()
+ const component = node('COMPONENT', page, { name: 'C', width: 100, height: 100 })
+ editor.select([component.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ type: 'INSTANCE', componentId: component.id, name: 'C' })
+
+ const set = node('COMPONENT_SET', page, { y: 300, width: 300, height: 140 })
+ const variant = node('COMPONENT', set.id, { name: 'v=a', width: 60, height: 60 })
+ editor.select([variant.id])
+ editor.duplicateSelected()
+ expect(selected()).toMatchObject({ type: 'COMPONENT', parentId: set.id })
+ })
+})
+
+describe('paste placement', () => {
+ test('keeps the offset a layer had inside its frame', async () => {
+ const page = setup()
+ const source = node('FRAME', page, { width: 200, height: 200 })
+ const box = node('RECTANGLE', source.id, { x: 20, y: 30 })
+ const target = node('FRAME', page, { x: 300, width: 200, height: 200 })
+ const snapshot = await copy(box.id)
+ editor.select([target.id])
+ await editor.pasteSnapshot(snapshot)
+ expect(selected()).toMatchObject({ parentId: target.id, x: 20, y: 30 })
+ })
+
+ test('centers each axis that does not fit in the frame', async () => {
+ const page = setup()
+ const source = node('FRAME', page, { width: 200, height: 200 })
+ const box = node('RECTANGLE', source.id, { x: 150, y: 150 })
+ const target = node('FRAME', page, { x: 300, width: 100, height: 100 })
+ const snapshot = await copy(box.id)
+ editor.select([target.id])
+ await editor.pasteSnapshot(snapshot)
+ expect(selected()).toMatchObject({ parentId: target.id, x: 30, y: 30 })
+ })
+
+ test('keeps the canvas position of a top-level layer', async () => {
+ const page = setup()
+ const box = node('RECTANGLE', page, { x: 20, y: 30 })
+ const target = node('FRAME', page, { x: 300, width: 200, height: 200 })
+ const leaf = node('RECTANGLE', target.id, { x: 100, y: 100 })
+ const snapshot = await copy(box.id)
+ await editor.pasteSnapshot(snapshot)
+ expect(selected()).toMatchObject({ parentId: page, x: 20, y: 30 })
+
+ // Inside a frame its x falls outside, so only x is centered.
+ editor.select([leaf.id])
+ await editor.pasteSnapshot(snapshot)
+ expect(selected()).toMatchObject({ parentId: target.id, x: 80, y: 30 })
+ })
+
+ test('centers layers that would land out of view', async () => {
+ const page = setup()
+ const box = node('RECTANGLE', page, { x: 5000, y: 5000 })
+ const snapshot = await copy(box.id)
+ await editor.pasteSnapshot(snapshot)
+ expect(selected()).toMatchObject({ parentId: page, x: 380, y: 280 })
+ })
+
+ test('Paste here centers on the cursor inside the target frame', async () => {
+ const page = setup()
+ const box = node('RECTANGLE', page)
+ const target = node('FRAME', page, { x: 300, y: 100, width: 200, height: 200 })
+ const snapshot = await copy(box.id)
+ editor.select([target.id])
+ await editor.pasteSnapshot(snapshot, { x: 400, y: 200 })
+ expect(selected()).toMatchObject({ parentId: target.id, x: 80, y: 80 })
+ })
+})
diff --git a/packages/core/tests/editor/components/slots/content.test.ts b/packages/core/tests/editor/components/slots/content.test.ts
index 4e62cbfc2..852c8bba6 100644
--- a/packages/core/tests/editor/components/slots/content.test.ts
+++ b/packages/core/tests/editor/components/slots/content.test.ts
@@ -33,6 +33,17 @@ const names = (editor: ReturnType<typeof createEditor>, node: SceneNode) =>
editor.graph.getChildren(node.id).map((child) => child.name)
describe('editing instance slots', () => {
+ test('a shape created in a slot claims it, and the rest of the instance refuses one', () => {
+ const { editor, instance, slot } = setup()
+ editor.createShape('RECTANGLE', 0, 0, 10, 10, slot.id, 'Drawn')
+ expect(names(editor, slot)).toContain('Drawn')
+ expect(ownsSlotContent(editor.graph, slot, 'card:body')).toBe(true)
+
+ const before = editor.graph.nodes.size
+ expect(() => editor.createShape('RECTANGLE', 0, 0, 10, 10, instance.id)).toThrow()
+ expect(editor.graph.nodes.size).toBe(before)
+ })
+
test('moving a layer into an untouched slot claims it, and one undo restores both', () => {
const { editor, pageId, instance, free, slot } = setup()
// As the canvas does: reparent on drop, then record the move.
diff --git a/packages/docs/user-guide/auto-layout.md b/packages/docs/user-guide/auto-layout.md
index 7cd34519a..7fc437ea4 100644
--- a/packages/docs/user-guide/auto-layout.md
+++ b/packages/docs/user-guide/auto-layout.md
@@ -61,7 +61,9 @@ Each child in an auto-layout frame can have its own sizing mode:
## Drag Reordering
-Within an auto-layout frame, drag a child to reorder it among its siblings. A visual insertion indicator shows where the child will be dropped.
+Within an auto-layout frame, drag a child to reorder it among its siblings. A visual insertion indicator shows where the child will be dropped. Dragging a node from elsewhere into an auto-layout frame inserts it the same way; in a wrapping frame, it goes into the line under the cursor. Drawing inside an auto-layout frame adds the new node to the end of its flow.
+
+Hold <kbd>⌃</kbd> (<kbd>Ctrl</kbd> on Windows and Linux) while dragging to ignore auto layout: the node is dropped where you release it as an absolute-positioned child.
## Properties Panel
diff --git a/packages/docs/user-guide/drawing-shapes.md b/packages/docs/user-guide/drawing-shapes.md
index 96c5e27e1..6bec85485 100644
--- a/packages/docs/user-guide/drawing-shapes.md
+++ b/packages/docs/user-guide/drawing-shapes.md
@@ -14,7 +14,7 @@ The bottom toolbar provides tools for creating shapes, frames, and sections. Sel
| Ellipse | <kbd>O</kbd> | Draws an ellipse |
| Line | <kbd>L</kbd> | Draws a line |
| Frame | <kbd>F</kbd> | Draws a frame (container for other nodes) |
-| Section | <kbd>S</kbd> | Draws a section (auto-adopts overlapping siblings) |
+| Section | <kbd>S</kbd> | Draws a section (takes in the siblings it fully covers) |
## Shapes Flyout
@@ -74,11 +74,11 @@ Click **+** to add an effect. Each effect row is collapsible with inline control
## Frames and Sections
-**Frames** are containers. Drag shapes into a frame to make them children. Frames can clip their content (off by default) and support [auto layout](./auto-layout).
+**Frames** are containers. Drag shapes into a frame to make them children, or start drawing inside one: a new shape goes into the frame under the point where you start, except locked frames, and joins the end of an auto-layout flow. Drawing a frame over existing nodes puts the unlocked ones it fully covers inside it. Frames can clip their content (off by default) and support [auto layout](./auto-layout).
Select the Frame tool to browse collapsible presets for phones, tablets, desktops, presentations, watches, paper, social media, Figma Community assets, and archived devices in the Design panel. Choosing a preset creates a named frame centered in the viewport and returns to the Select tool. With an existing frame selected, use its Frame preset dropdown to resize it without changing its name.
-**Sections** are top-level containers that automatically adopt overlapping sibling nodes when drawn. They're useful for organizing large canvases into logical areas. Sections display a title pill that you can drag.
+**Sections** are top-level containers that take in the sibling nodes they fully cover when drawn, moved, or resized. They're useful for organizing large canvases into logical areas. Sections display a title pill that you can drag.
## Keyboard Shortcuts
diff --git a/packages/docs/user-guide/selection-and-manipulation.md b/packages/docs/user-guide/selection-and-manipulation.md
index 61e2f4010..d18b54c62 100644
--- a/packages/docs/user-guide/selection-and-manipulation.md
+++ b/packages/docs/user-guide/selection-and-manipulation.md
@@ -26,6 +26,16 @@ Selected nodes show 8 resize handles (4 corners + 4 edge midpoints). Drag any ha
- <kbd>Shift</kbd> + drag a corner handle to constrain proportions
+## Moving into and out of frames
+
+A dragged node lands in the frame under the cursor when you release it, however little of it is inside, and leaves its frame as soon as the cursor does. Groups and locked frames never take dropped nodes, and a component set takes back only its own variants; a node inside a group stays in it unless you drop it on a different frame, and the group resizes to fit what it holds. A group whose last node leaves is removed. Pressing inside a selected frame, group, or component set drags it rather than the node under the cursor.
+
+- <kbd>Shift</kbd> + drag — lock the move to one axis
+- Hold <kbd>Space</kbd> while dragging — keep the nodes in their current parents
+- <kbd>⌃</kbd> + drag (<kbd>Ctrl</kbd> + drag on Windows and Linux) — turn off snapping; dropped into an auto-layout frame, the node is positioned absolutely
+
+Locked nodes in a selection stay where they are when the rest of it moves.
+
## Rotating
Hover just outside a corner handle to see the rotation cursor. Drag to rotate.
@@ -35,7 +45,13 @@ Hover just outside a corner handle to see the rotation cursor. Drag to rotate.
## Duplicating
- <kbd>Alt</kbd> + drag (<kbd>⌥</kbd> + drag on Mac) — duplicate the selected node and move the copy
-- <kbd>⌘</kbd><kbd>D</kbd> — duplicate in place
+- <kbd>⌘</kbd><kbd>D</kbd> — duplicate in place; a lone top-level frame's copy, on the page or in a section, goes into the first free space to its right
+
+Duplicates keep their names. Duplicating a main component this way creates an instance of it.
+
+## Pasting
+
+<kbd>⌘</kbd><kbd>V</kbd> keeps the copied position. Pasted into a selected frame, nodes keep their offset from the frame they were copied from, and are centered along any axis where they don't fit; nodes that would land out of view are centered in it. Use **Paste here** in the [context menu](./context-menu) to paste at the cursor.
## Deleting
@@ -59,7 +75,7 @@ Move selected nodes to a different page via the [context menu](./context-menu).
## Sections
-Drawing a section on the canvas automatically adopts overlapping sibling nodes as children of the new section.
+A section takes in the sibling nodes it fully covers when you draw it, move it, or resize it over them.
## Keyboard Shortcuts
@@ -68,6 +84,9 @@ Drawing a section on the canvas automatically adopts overlapping sibling nodes a
| Select all | <kbd>⌘</kbd><kbd>A</kbd> | <kbd>Ctrl</kbd> + <kbd>A</kbd> |
| Duplicate | <kbd>⌘</kbd><kbd>D</kbd> | <kbd>Ctrl</kbd> + <kbd>D</kbd> |
| Duplicate + move | <kbd>⌥</kbd> + drag | <kbd>Alt</kbd> + drag |
+| Move along one axis | <kbd>⇧</kbd> + drag | <kbd>Shift</kbd> + drag |
+| Keep current parent | <kbd>Space</kbd> while dragging | <kbd>Space</kbd> while dragging |
+| Move without snapping | <kbd>⌃</kbd> + drag | <kbd>Ctrl</kbd> + drag |
| Delete | <kbd>⌫</kbd> / Delete | <kbd>Backspace</kbd> / Delete |
| Nudge 1 px | <kbd>Arrow keys</kbd> | Arrow keys |
| Nudge 10 px | <kbd>⇧</kbd> + Arrow keys | <kbd>Shift</kbd> + <kbd>Arrow</kbd> keys |
diff --git a/packages/scene-graph/src/hit-test.ts b/packages/scene-graph/src/hit-test.ts
index 5665795cd..2033c1ea0 100644
--- a/packages/scene-graph/src/hit-test.ts
+++ b/packages/scene-graph/src/hit-test.ts
@@ -160,46 +160,94 @@ export function hitTestDeep(
return hitTestChildren(graph, px, py, scope, true)
}
-function hitTestFrameChildren(
+/** Whether the point lies inside the node's rotated and flipped bounds. */
+export function isPointInNode(graph: SceneGraph, nodeId: string, px: number, py: number): boolean {
+ const node = graph.nodes.get(nodeId)
+ return node !== undefined && containsPoint(px, py, node, graph, new Map())
+}
+
+/** Which layers take a drop, and which are only looked through, as in Figma. */
+interface DropRules {
+ takes: (node: SceneNode) => boolean
+ passThrough: ReadonlySet<NodeType>
+}
+
+const LAYER_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'COMPONENT', 'INSTANCE'])
+const COMPONENT_TARGETS = new Set<NodeType>(['FRAME', 'SECTION', 'INSTANCE'])
+
+function dropRules(options: DropTargetOptions): DropRules {
+ const { componentSetIds } = options
+ if (!componentSetIds) {
+ return {
+ takes: (node) => LAYER_TARGETS.has(node.type),
+ passThrough: new Set(['GROUP', 'COMPONENT_SET'])
+ }
+ }
+ // Components never go into other components, and a set only takes back its own variants.
+ return {
+ takes: (node) =>
+ COMPONENT_TARGETS.has(node.type) ||
+ (node.type === 'COMPONENT_SET' && componentSetIds.has(node.id)),
+ passThrough: new Set(['GROUP'])
+ }
+}
+
+function dropTargetIn(
graph: SceneGraph,
px: number,
py: number,
- parentId: string,
- offsetX: number,
- offsetY: number,
- excludeIds: Set<string>
+ parent: SceneNode,
+ excludeIds: ReadonlySet<string>,
+ rules: DropRules,
+ transformCache: Map<string, boolean>
): SceneNode | null {
- const parent = graph.nodes.get(parentId)
- if (!parent) return null
-
- let best: SceneNode | null = null
+ // A clipped-away part of a child is not under the cursor.
+ if (
+ parent.type !== 'CANVAS' &&
+ parent.clipsContent &&
+ !containsPoint(px, py, parent, graph, transformCache)
+ )
+ return null
- for (const childId of parent.childIds) {
+ for (let i = parent.childIds.length - 1; i >= 0; i--) {
+ const childId = parent.childIds[i]
if (excludeIds.has(childId)) continue
const child = graph.nodes.get(childId)
- if (!child || child.internalOnly || !child.visible) continue
-
- const ax = offsetX + child.x
- const ay = offsetY + child.y
+ if (!child || child.internalOnly || !child.visible || child.locked) continue
+ const target = rules.takes(child)
+ if (!target && !rules.passThrough.has(child.type)) continue
- if (!CONTAINER_TYPES.has(child.type)) continue
- if (px < ax || px > ax + child.width || py < ay || py > ay + child.height) continue
-
- best = child
-
- const deeper = hitTestFrameChildren(graph, px, py, childId, ax, ay, excludeIds)
- if (deeper) best = deeper
+ const deeper = dropTargetIn(graph, px, py, child, excludeIds, rules, transformCache)
+ if (deeper) return deeper
+ if (target && containsPoint(px, py, child, graph, transformCache)) return child
}
- return best
+ return null
+}
+
+export interface DropTargetOptions {
+ /**
+ * Set when the dropped layers are all main components: the component sets they come from.
+ * Components then go only into frames, sections, instances, and those sets.
+ */
+ componentSetIds?: ReadonlySet<string>
}
-export function hitTestFrame(
+/**
+ * The topmost unlocked frame, section, component, or instance under the point, in its rotated
+ * shape and inside its clipping ancestors. Groups and component sets are looked through but never
+ * returned, except that a set takes dropped components; locked layers and their contents are
+ * skipped.
+ */
+export function hitTestDropTarget(
graph: SceneGraph,
px: number,
py: number,
- excludeIds: Set<string>,
- scopeId?: string
+ excludeIds: ReadonlySet<string>,
+ scopeId?: string,
+ options: DropTargetOptions = {}
): SceneNode | null {
- return hitTestFrameChildren(graph, px, py, scopeId ?? graph.rootId, 0, 0, excludeIds)
+ const scope = graph.nodes.get(scopeId ?? graph.rootId)
+ if (!scope) return null
+ return dropTargetIn(graph, px, py, scope, excludeIds, dropRules(options), new Map())
}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 34c2d7453..3c00a28d9 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -58,6 +58,7 @@ import { BufferedSceneEmitter } from './buffered-events'
import { cloneNodeProps } from './copy'
import { bindNodeEvents } from './events'
import * as HitTest from './hit-test'
+export type { DropTargetOptions } from './hit-test'
import * as Instances from './instances'
import Matrix, { type Mat3 } from './matrix'
import { CONTAINER_TYPES, createDefaultNode } from './node-defaults'
@@ -700,13 +701,18 @@ export class SceneGraph {
return HitTest.hitTestDeep(this, px, py, scopeId)
}
- hitTestFrame(
+ isPointInNode(nodeId: string, px: number, py: number): boolean {
+ return HitTest.isPointInNode(this, nodeId, px, py)
+ }
+
+ hitTestDropTarget(
px: number,
py: number,
- excludeIds: Set<string>,
- scopeId?: string
+ excludeIds: ReadonlySet<string>,
+ scopeId?: string,
+ options?: HitTest.DropTargetOptions
): SceneNode | null {
- return HitTest.hitTestFrame(this, px, py, excludeIds, scopeId)
+ return HitTest.hitTestDropTarget(this, px, py, excludeIds, scopeId, options)
}
cloneTree(
diff --git a/packages/scene-graph/tests/basic/drop-target.test.ts b/packages/scene-graph/tests/basic/drop-target.test.ts
new file mode 100644
index 000000000..650431ac1
--- /dev/null
+++ b/packages/scene-graph/tests/basic/drop-target.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, type NodeType, type SceneNode } from '@open-pencil/scene-graph'
+
+import { pageId, rect } from './helpers'
+
+// Each expectation matches a drag observed in Figma desktop 126 with real pointer input.
+
+function container(
+ graph: SceneGraph,
+ type: NodeType,
+ parentId: string,
+ props: Partial<SceneNode> = {}
+) {
+ return graph.createNode(type, parentId, { x: 0, y: 0, width: 200, height: 200, ...props })
+}
+
+function dropAt(graph: SceneGraph, x: number, y: number, exclude: string[] = []) {
+ return graph.hitTestDropTarget(x, y, new Set(exclude), pageId(graph))?.id ?? null
+}
+
+describe('hitTestDropTarget', () => {
+ test('takes the frame under the cursor however little of the layer is inside', () => {
+ const graph = new SceneGraph()
+ const frame = container(graph, 'FRAME', pageId(graph))
+ expect(dropAt(graph, 190, 100)).toBe(frame.id)
+ expect(dropAt(graph, 205, 150)).toBeNull()
+ })
+
+ test('takes the topmost of overlapping frames', () => {
+ const graph = new SceneGraph()
+ container(graph, 'FRAME', pageId(graph))
+ const top = container(graph, 'FRAME', pageId(graph), { x: 100, y: 100 })
+ expect(dropAt(graph, 150, 150)).toBe(top.id)
+ })
+
+ test('takes the deepest frame', () => {
+ const graph = new SceneGraph()
+ const outer = container(graph, 'FRAME', pageId(graph), { width: 400, height: 400 })
+ const inner = container(graph, 'FRAME', outer.id, { x: 50, y: 50, width: 100, height: 100 })
+ expect(dropAt(graph, 100, 100)).toBe(inner.id)
+ expect(dropAt(graph, 300, 300)).toBe(outer.id)
+ })
+
+ test('never takes groups, boolean operations, or component sets', () => {
+ const graph = new SceneGraph()
+ container(graph, 'GROUP', pageId(graph))
+ container(graph, 'BOOLEAN_OPERATION', pageId(graph))
+ container(graph, 'COMPONENT_SET', pageId(graph))
+ expect(dropAt(graph, 100, 100)).toBeNull()
+ })
+
+ test('looks through groups and component sets to the frames inside', () => {
+ const graph = new SceneGraph()
+ const group = container(graph, 'GROUP', pageId(graph))
+ const framed = container(graph, 'FRAME', group.id, { width: 100, height: 100 })
+ const set = container(graph, 'COMPONENT_SET', pageId(graph), { x: 300 })
+ const variant = container(graph, 'COMPONENT', set.id, { width: 100, height: 100 })
+ expect(dropAt(graph, 50, 50)).toBe(framed.id)
+ expect(dropAt(graph, 350, 50)).toBe(variant.id)
+ })
+
+ test('takes components', () => {
+ const graph = new SceneGraph()
+ const component = container(graph, 'COMPONENT', pageId(graph))
+ expect(dropAt(graph, 100, 100)).toBe(component.id)
+ })
+
+ test('skips locked frames and their contents', () => {
+ const graph = new SceneGraph()
+ const locked = container(graph, 'FRAME', pageId(graph), { locked: true })
+ container(graph, 'FRAME', locked.id, { width: 100, height: 100 })
+ expect(dropAt(graph, 50, 50)).toBeNull()
+ })
+
+ test('skips hidden frames and excluded layers', () => {
+ const graph = new SceneGraph()
+ container(graph, 'FRAME', pageId(graph), { visible: false })
+ const dragged = container(graph, 'FRAME', pageId(graph), { x: 300 })
+ expect(dropAt(graph, 100, 100)).toBeNull()
+ expect(dropAt(graph, 350, 100, [dragged.id])).toBeNull()
+ })
+
+ test('uses the rotated shape, not its bounding box', () => {
+ const graph = new SceneGraph()
+ // Rotated 45° about its center; the box corner (5, 5) lies outside the diamond.
+ const frame = container(graph, 'FRAME', pageId(graph), { rotation: 45 })
+ expect(dropAt(graph, 100, 100)).toBe(frame.id)
+ expect(dropAt(graph, 5, 5)).toBeNull()
+ })
+
+ test('ignores the clipped-away part of a child frame', () => {
+ const graph = new SceneGraph()
+ const clipping = container(graph, 'FRAME', pageId(graph), { clipsContent: true })
+ container(graph, 'FRAME', clipping.id, { x: 150, y: 50, width: 200, height: 100 })
+ expect(dropAt(graph, 300, 100)).toBeNull()
+ })
+
+ test('takes the overflowing part of a child frame when its parent does not clip', () => {
+ const graph = new SceneGraph()
+ const parent = container(graph, 'FRAME', pageId(graph), { clipsContent: false })
+ const child = container(graph, 'FRAME', parent.id, { x: 150, y: 50, width: 200, height: 100 })
+ expect(dropAt(graph, 300, 100)).toBe(child.id)
+ })
+
+ test('takes only a dragged variant back into its own component set', () => {
+ const graph = new SceneGraph()
+ const set = container(graph, 'COMPONENT_SET', pageId(graph), { width: 300 })
+ const variant = container(graph, 'COMPONENT', set.id, { width: 60, height: 60 })
+ const sibling = container(graph, 'COMPONENT', set.id, { x: 100, width: 100, height: 100 })
+ const own = { componentSetIds: new Set([set.id]) }
+ const foreign = { componentSetIds: new Set([pageId(graph)]) }
+ const drop = (x: number, y: number, options: typeof own) =>
+ graph.hitTestDropTarget(x, y, new Set([variant.id]), pageId(graph), options)?.id ?? null
+ expect(drop(150, 50, own)).toBe(set.id)
+ expect(drop(250, 150, own)).toBe(set.id)
+ expect(drop(150, 50, foreign)).toBeNull()
+ expect(dropAt(graph, 150, 50, [variant.id])).toBe(sibling.id)
+ })
+
+ test('isPointInNode follows rotation', () => {
+ const graph = new SceneGraph()
+ const frame = container(graph, 'FRAME', pageId(graph), { rotation: 45 })
+ expect(graph.isPointInNode(frame.id, 100, 100)).toBe(true)
+ expect(graph.isPointInNode(frame.id, 5, 5)).toBe(false)
+ })
+
+ test('ignores shapes covering a frame', () => {
+ const graph = new SceneGraph()
+ const frame = container(graph, 'FRAME', pageId(graph))
+ rect(graph, 'Cover', 0, 0, 200, 200)
+ expect(dropAt(graph, 100, 100)).toBe(frame.id)
+ })
+})
diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.ts
index 691c902bb..fb65b085a 100644
--- a/packages/vue/src/canvas/useCanvasInput.ts
+++ b/packages/vue/src/canvas/useCanvasInput.ts
@@ -315,7 +315,7 @@ export function useCanvasInput(
return
}
if (d.type === 'move') {
- handleMoveMove(d, cx, cy, sx, sy, editor, e.ctrlKey)
+ handleMoveMove(d, cx, cy, sx, sy, editor, { ctrlKey: e.ctrlKey, shiftKey: e.shiftKey })
return
}
if (d.type === 'text-select') {
@@ -466,6 +466,20 @@ export function useCanvasInput(
},
{ capture: true }
)
+ // Space during a move keeps layers in their parents, as in Figma, instead of switching to the hand.
+ function holdParentsDuringMove(event: KeyboardEvent, held: boolean) {
+ if (event.code !== 'Space' || drag.value?.type !== 'move' || !isEnabled()) return
+ event.preventDefault()
+ event.stopImmediatePropagation()
+ drag.value.keepParents = held
+ if (held) editor.setDropTarget(null)
+ }
+ useEventListener(window, 'keydown', (event) => holdParentsDuringMove(event, true), {
+ capture: true
+ })
+ useEventListener(window, 'keyup', (event) => holdParentsDuringMove(event, false), {
+ capture: true
+ })
useEventListener(window, 'blur', () => {
resetMeasurementModifiers()
cancelPointerInteraction()
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 536617ac6..e6c43cbed 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -348,7 +348,6 @@
"collapseEffectSettings": "Effekteinstellungen einklappen",
"toggleExportPreview": "Exportvorschau umschalten",
"untitled": "Unbenannt",
- "nodeCopyString": " Kopie",
"xAxis": "X-Achse",
"yAxis": "Y-Achse",
"rotation": "Drehung",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index fea4df837..bb8244d9e 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -1,6 +1,5 @@
{
"untitled": "Sin título",
- "nodeCopyString": " copia",
"layers": "Capas",
"pages": "Páginas",
"design": "Diseño",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 005e9ecf5..4b1bf9cee 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -348,7 +348,6 @@
"collapseEffectSettings": "Réduire les réglages de l’effet",
"toggleExportPreview": "Afficher/masquer l’aperçu d’export",
"untitled": "Sans titre",
- "nodeCopyString": " copie",
"xAxis": "Axe X",
"yAxis": "Axe Y",
"rotation": "Rotation",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 429ca0b59..38bccb2b3 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -348,7 +348,6 @@
"collapseEffectSettings": "Comprimi impostazioni effetto",
"toggleExportPreview": "Mostra/nascondi anteprima esportazione",
"untitled": "Senza titolo",
- "nodeCopyString": " copia",
"xAxis": "Asse X",
"yAxis": "Asse Y",
"rotation": "Rotazione",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 9b2dc8dc3..18d175f1f 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -1,6 +1,5 @@
{
"untitled": "無題",
- "nodeCopyString": " コピー",
"layers": "レイヤー",
"pages": "ページ",
"design": "デザイン",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index c4e647930..f0c986eae 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -354,7 +354,6 @@
"collapseEffectSettings": "Zwiń ustawienia efektu",
"toggleExportPreview": "Przełącz podgląd eksportu",
"untitled": "Bez tytułu",
- "nodeCopyString": " kopia",
"xAxis": "Oś X",
"yAxis": "Oś Y",
"rotation": "Obrót",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index b9ac1db31..8fce76ce1 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -354,7 +354,6 @@
"collapseEffectSettings": "Свернуть настройки эффекта",
"toggleExportPreview": "Показать/скрыть предпросмотр экспорта",
"untitled": "Без названия",
- "nodeCopyString": " копия",
"xAxis": "Ось X",
"yAxis": "Ось Y",
"rotation": "Поворот",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index b3f21867b..9db49b84b 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -342,7 +342,6 @@
"collapseEffectSettings": "收起效果设置",
"toggleExportPreview": "切换导出预览",
"untitled": "未命名",
- "nodeCopyString": " 副本",
"xAxis": "X 轴",
"yAxis": "Y 轴",
"rotation": "旋转",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 2d78cb42e..5b7281b31 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -4,7 +4,6 @@ import { i18n } from '#vue/i18n/create'
export const panelMessageDefaults = {
untitled: 'Untitled',
- nodeCopyString: ' copy',
individualPadding: 'Individual padding',
layers: 'Layers',
pages: 'Pages',
diff --git a/packages/vue/src/shared/input/auto-layout.ts b/packages/vue/src/shared/input/auto-layout.ts
index c11a6ed8f..f343fc067 100644
--- a/packages/vue/src/shared/input/auto-layout.ts
+++ b/packages/vue/src/shared/input/auto-layout.ts
@@ -68,7 +68,7 @@ export function filteredToRealIndex(
parentId: string,
insertIndex: number,
editor: Editor,
- movingIds = editor.state.selectedIds
+ movingIds: ReadonlySet<string> = editor.state.selectedIds
): number {
const allChildren = editor.graph.getChildren(parentId)
let realIndex = 0
@@ -86,34 +86,124 @@ export function filteredToRealIndex(
return realIndex
}
-export function computeAutoLayoutIndicatorForFrame(
+interface FlowLine {
+ /** Index of the line's first child among the frame's flow children. */
+ offset: number
+ children: SceneNode[]
+ crossStart: number
+ crossEnd: number
+}
+
+/** Splits wrapped children into lines along the cross axis; one line when nothing wraps. */
+function flowLines(parent: SceneNode, children: SceneNode[], isRow: boolean, editor: Editor) {
+ const lines: FlowLine[] = []
+ for (const [index, child] of children.entries()) {
+ const abs = editor.graph.getAbsolutePosition(child.id)
+ const start = isRow ? abs.y : abs.x
+ const end = start + (isRow ? child.height : child.width)
+ const line = parent.layoutWrap === 'WRAP' ? lines.at(-1) : lines[0]
+ if (line && (parent.layoutWrap !== 'WRAP' || start < line.crossEnd)) {
+ line.children.push(child)
+ line.crossStart = Math.min(line.crossStart, start)
+ line.crossEnd = Math.max(line.crossEnd, end)
+ } else {
+ lines.push({ offset: index, children: [child], crossStart: start, crossEnd: end })
+ }
+ }
+ return lines
+}
+
+/** The wrapped line under the cursor, or the nearest one. */
+function lineAt(lines: FlowLine[], cross: number): FlowLine | undefined {
+ return lines.find((line, i) => {
+ const next = lines.at(i + 1)
+ return !next || cross < (line.crossEnd + next.crossStart) / 2
+ })
+}
+
+function autoLayoutInsertion(
parent: SceneNode,
cx: number,
cy: number,
editor: Editor,
- movingIds = editor.state.selectedIds
+ movingIds: ReadonlySet<string>
) {
const children = editor.graph
.getChildren(parent.id)
.filter((c) => c.layoutPositioning !== 'ABSOLUTE' && !movingIds.has(c.id))
- const parentAbs = editor.graph.getAbsolutePosition(parent.id)
const isRow = parent.layoutMode === 'HORIZONTAL'
const rtlRow = isRTLRow(parent, isRow, editor)
+ const line = lineAt(flowLines(parent, children, isRow, editor), isRow ? cy : cx)
+ const lineChildren = line?.children ?? []
- let insertIndex = children.length
- for (let i = 0; i < children.length; i++) {
- const childAbs = editor.graph.getAbsolutePosition(children[i].id)
- const mid = isRow ? childAbs.x + children[i].width / 2 : childAbs.y + children[i].height / 2
+ let lineIndex = lineChildren.length
+ for (let i = 0; i < lineChildren.length; i++) {
+ const childAbs = editor.graph.getAbsolutePosition(lineChildren[i].id)
+ const mid = isRow
+ ? childAbs.x + lineChildren[i].width / 2
+ : childAbs.y + lineChildren[i].height / 2
const cursor = isRow ? cx : cy
const shouldInsertBefore = rtlRow ? cursor > mid : cursor < mid
if (shouldInsertBefore) {
- insertIndex = i
+ lineIndex = i
break
}
}
+ const insertIndex = (line?.offset ?? 0) + lineIndex
const realIndex = filteredToRealIndex(parent.id, insertIndex, editor, movingIds)
+ return { line, lineIndex, realIndex, isRow }
+}
+
+/** Where layers dropped at the cursor go among an auto layout frame's children. */
+export function autoLayoutInsertIndex(
+ parent: SceneNode,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ movingIds: ReadonlySet<string>
+) {
+ return autoLayoutInsertion(parent, cx, cy, editor, movingIds).realIndex
+}
+
+/** Where the indicator spans across the flow: the whole frame, or the wrapped line it joins. */
+function indicatorCrossExtent(
+ parent: SceneNode,
+ parentAbs: Vector,
+ isRow: boolean,
+ line: FlowLine | undefined
+) {
+ if (parent.layoutWrap === 'WRAP' && line) {
+ return { crossStart: line.crossStart, crossLength: line.crossEnd - line.crossStart }
+ }
+ if (isRow) {
+ return {
+ crossStart: parentAbs.y + parent.paddingTop,
+ crossLength: parent.height - parent.paddingTop - parent.paddingBottom
+ }
+ }
+ return {
+ crossStart: parentAbs.x + parent.paddingLeft,
+ crossLength: parent.width - parent.paddingLeft - parent.paddingRight
+ }
+}
+
+export function computeAutoLayoutIndicatorForFrame(
+ parent: SceneNode,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ movingIds: ReadonlySet<string> = editor.state.selectedIds
+) {
+ const { line, lineIndex, realIndex, isRow } = autoLayoutInsertion(
+ parent,
+ cx,
+ cy,
+ editor,
+ movingIds
+ )
+ const parentAbs = editor.graph.getAbsolutePosition(parent.id)
if (movingIds.size === 1) {
const movingId = [...movingIds][0]
const movingNode = editor.graph.getNode(movingId)
@@ -125,17 +215,14 @@ export function computeAutoLayoutIndicatorForFrame(
}
const indicatorPos = computeIndicatorPosition(
- children,
- insertIndex,
+ line?.children ?? [],
+ lineIndex,
parent,
parentAbs,
isRow,
editor
)
- const crossStart = isRow ? parentAbs.y + parent.paddingTop : parentAbs.x + parent.paddingLeft
- const crossLength = isRow
- ? parent.height - parent.paddingTop - parent.paddingBottom
- : parent.width - parent.paddingLeft - parent.paddingRight
+ const { crossStart, crossLength } = indicatorCrossExtent(parent, parentAbs, isRow, line)
editor.setLayoutInsertIndicator({
parentId: parent.id,
diff --git a/packages/vue/src/shared/input/draw.ts b/packages/vue/src/shared/input/draw.ts
index 3c34615ff..adcb1d8fc 100644
--- a/packages/vue/src/shared/input/draw.ts
+++ b/packages/vue/src/shared/input/draw.ts
@@ -1,20 +1,49 @@
import { DEFAULT_TEXT_HEIGHT, DEFAULT_TEXT_WIDTH } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
+import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
+import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'
+import Matrix from '@open-pencil/scene-graph/matrix'
+import { findDrawParent } from '#vue/shared/input/drop-target'
import { TOOL_TO_NODE } from '#vue/shared/input/types'
import type { DragDraw, DragState } from '#vue/shared/input/types'
-export function startTextDraw(
+/** Maps canvas points into the axes of the parent a layer is drawn in. */
+function parentSpace(editor: Editor, parentId: string): DragDraw['toLocal'] {
+ const parent = editor.graph.getNode(parentId)
+ if (!parent || parent.type === 'CANVAS') return (x, y) => ({ x, y })
+ const toLocal = Matrix.invert(getWorldMatrix(parent, editor.graph)) ?? Matrix.identity()
+ return (x, y) => {
+ const [lx, ly] = Matrix.mapPoints(toLocal, [x, y])
+ return { x: lx, y: ly }
+ }
+}
+
+function startDraw(
+ type: NodeType,
+ label: string,
cx: number,
cy: number,
editor: Editor,
setDrag: (d: DragState) => void
) {
- editor.undo.beginBatch('Create text')
- const nodeId = editor.createShape('TEXT', cx, cy, 0, 0)
- editor.graph.updateNode(nodeId, { text: '' })
+ editor.undo.beginBatch(label)
+ const parentId = findDrawParent(cx, cy, type, editor)
+ const toLocal = parentSpace(editor, parentId)
+ const start = toLocal(cx, cy)
+ const nodeId = editor.createShape(type, start.x, start.y, 0, 0, parentId)
+ if (type === 'TEXT') editor.graph.updateNode(nodeId, { text: '' })
editor.select([nodeId])
- setDrag(createDraw(editor, nodeId, cx, cy))
+ setDrag(createDraw(editor, nodeId, start.x, start.y, toLocal))
+}
+
+export function startTextDraw(
+ cx: number,
+ cy: number,
+ editor: Editor,
+ setDrag: (d: DragState) => void
+) {
+ startDraw('TEXT', 'Create text', cx, cy, editor, setDrag)
}
export function startShapeDraw(
@@ -26,15 +55,13 @@ export function startShapeDraw(
const nodeType = TOOL_TO_NODE[editor.state.activeTool]
if (!nodeType) return
- editor.undo.beginBatch('Create shape')
- const nodeId = editor.createShape(nodeType, cx, cy, 0, 0)
- editor.select([nodeId])
- setDrag(createDraw(editor, nodeId, cx, cy))
+ startDraw(nodeType, 'Create shape', cx, cy, editor, setDrag)
}
export function handleDrawMove(d: DragDraw, cx: number, cy: number, shiftKey: boolean) {
- let w = cx - d.startX
- let h = cy - d.startY
+ const point = d.toLocal(cx, cy)
+ let w = point.x - d.startX
+ let h = point.y - d.startY
if (shiftKey) {
const size = Math.max(Math.abs(w), Math.abs(h))
@@ -50,7 +77,28 @@ export function handleDrawMove(d: DragDraw, cx: number, cy: number, shiftKey: bo
})
}
-function createDraw(editor: Editor, nodeId: string, startX: number, startY: number): DragDraw {
+/** Gives a layer made by a click its default size; returns whether it was only clicked. */
+function settleDrawnSize(preview: ReturnType<Editor['beginNodePreview']>, node: SceneNode) {
+ const clicked = node.width < 2 && node.height < 2
+ if (node.type === 'TEXT') {
+ preview.update(node.id, {
+ width: clicked ? DEFAULT_TEXT_WIDTH : node.width,
+ height: clicked ? DEFAULT_TEXT_HEIGHT : node.height,
+ textAutoResize: clicked ? 'WIDTH_AND_HEIGHT' : 'NONE'
+ })
+ } else if (clicked) {
+ preview.update(node.id, { width: 100, height: 100 })
+ }
+ return clicked
+}
+
+function createDraw(
+ editor: Editor,
+ nodeId: string,
+ startX: number,
+ startY: number,
+ toLocal: DragDraw['toLocal']
+): DragDraw {
const graph = editor.graph
const preview = editor.beginNodePreview('Draw dimensions')
let finished = false
@@ -72,18 +120,15 @@ function createDraw(editor: Editor, nodeId: string, startX: number, startY: numb
finished = true
const node = graph.getNode(nodeId)
try {
- if (node?.type === 'TEXT') {
- const isPointText = node.width < 2 && node.height < 2
- preview.update(nodeId, {
- width: isPointText ? DEFAULT_TEXT_WIDTH : node.width,
- height: isPointText ? DEFAULT_TEXT_HEIGHT : node.height,
- textAutoResize: isPointText ? 'WIDTH_AND_HEIGHT' : 'NONE'
- })
- } else if (node && node.width < 2 && node.height < 2) {
- preview.update(nodeId, { width: 100, height: 100 })
- }
+ const clicked = node ? settleDrawnSize(preview, node) : false
preview.commit()
- if (node?.type === 'SECTION') editor.adoptNodesIntoSection(node.id)
+ // Drawn into auto layout, the layer joins the flow at the end.
+ const parent = graph.getNode(node?.parentId ?? '')
+ if (parent && parent.layoutMode !== 'NONE') editor.runLayoutForNode(parent.id)
+ // A frame made by a click, not drawn over anything, takes nothing in.
+ if (node?.type === 'SECTION' || (node?.type === 'FRAME' && !clicked)) {
+ editor.adoptCoveredLayers(node.id)
+ }
editor.undo.commitBatch()
} catch (error) {
preview.cancel()
@@ -106,6 +151,7 @@ function createDraw(editor: Editor, nodeId: string, startX: number, startY: numb
type: 'draw',
startX,
startY,
+ toLocal,
nodeId,
update: (changes) => {
if (!finished) preview.update(nodeId, changes)
diff --git a/packages/vue/src/shared/input/drop-target.ts b/packages/vue/src/shared/input/drop-target.ts
index a14183ea4..670d3db47 100644
--- a/packages/vue/src/shared/input/drop-target.ts
+++ b/packages/vue/src/shared/input/drop-target.ts
@@ -1,43 +1,72 @@
import type { Editor } from '@open-pencil/core/editor'
-import type { SceneNode } from '@open-pencil/scene-graph'
+import type { NodeType, SceneNode } from '@open-pencil/scene-graph'
-export function findMoveDropTarget(cx: number, cy: number, editor: Editor): SceneNode | null {
- let dropTarget = editor.graph.hitTestFrame(
- cx,
- cy,
- editor.state.selectedIds,
- editor.state.currentPageId
- )
- const movingSection = [...editor.state.selectedIds].some(
- (id) => editor.graph.getNode(id)?.type === 'SECTION'
- )
- if (
- movingSection &&
- dropTarget &&
- dropTarget.type !== 'SECTION' &&
- dropTarget.type !== 'CANVAS'
- ) {
+/** Parents a layer stays in while dragged until it lands on another frame. */
+const ENCLOSING_TYPES = new Set<NodeType>(['GROUP', 'BOOLEAN_OPERATION'])
+/** Containers that never take a drawn layer. */
+const NOT_DRAWN_INTO = new Set<NodeType>(['GROUP', 'BOOLEAN_OPERATION', 'COMPONENT_SET'])
+
+function acceptingTarget(target: SceneNode | null, editor: Editor): SceneNode | null {
+ if (!target) return null
+ // Only an instance's slots take layers; anywhere else in it drops into its parent.
+ const accepting = editor.graph.getNode(editor.acceptingParent(target.id))
+ if (!accepting || accepting.type === 'CANVAS' || !editor.acceptsChildren(accepting.id))
+ return null
+ return accepting
+}
+
+/** The frame a dragged layer lands in under the cursor; null is the page. */
+export function findMoveDropTarget(
+ cx: number,
+ cy: number,
+ editor: Editor,
+ excludeIds: ReadonlySet<string> = editor.state.selectedIds
+): SceneNode | null {
+ const moving = [...excludeIds].map((id) => editor.graph.getNode(id))
+ const components = moving.length > 0 && moving.every((node) => node?.type === 'COMPONENT')
+ const componentSetIds = components
+ ? new Set(moving.flatMap((node) => (node?.parentId ? [node.parentId] : [])))
+ : undefined
+ let dropTarget = editor.graph.hitTestDropTarget(cx, cy, excludeIds, editor.state.currentPageId, {
+ componentSetIds
+ })
+ const movingSection = moving.some((node) => node?.type === 'SECTION')
+ if (movingSection && dropTarget && dropTarget.type !== 'SECTION') {
dropTarget = null
}
- // Only an instance's slots take layers; anywhere else in it drops into its parent.
- if (dropTarget) {
- const accepting = editor.graph.getNode(editor.acceptingParent(dropTarget.id))
- dropTarget = accepting && accepting.type !== 'CANVAS' ? accepting : null
+ return acceptingTarget(dropTarget, editor)
+}
+
+function takesDrawnLayer(target: SceneNode, type: NodeType) {
+ if (NOT_DRAWN_INTO.has(target.type)) return false
+ // Sections only go into pages and other sections.
+ return type !== 'SECTION' || target.type === 'SECTION'
+}
+
+/** The parent a new layer drawn from this point goes into. */
+export function findDrawParent(cx: number, cy: number, type: NodeType, editor: Editor): string {
+ let target = editor.graph.hitTestDropTarget(cx, cy, new Set(), editor.state.currentPageId)
+ while (target && target.type !== 'CANVAS' && !takesDrawnLayer(target, type)) {
+ target = target.parentId ? (editor.graph.getNode(target.parentId) ?? null) : null
}
- return dropTarget
+ return acceptingTarget(target, editor)?.id ?? editor.state.currentPageId
}
-export function reparentOutsideNodes(editor: Editor) {
- for (const id of editor.state.selectedIds) {
- const node = editor.graph.getNode(id)
- if (!node?.parentId || editor.isTopLevel(node.parentId)) continue
- const parent = editor.graph.getNode(node.parentId)
- if (!parent || (parent.type !== 'FRAME' && parent.type !== 'SECTION')) continue
- const outsideX = node.x + node.width < 0 || node.x > parent.width
- const outsideY = node.y + node.height < 0 || node.y > parent.height
- if (outsideX || outsideY) {
- const grandparentId = parent.parentId ?? editor.state.currentPageId
- editor.reparentNodes([id], editor.acceptingParent(grandparentId))
- }
+/** The frame or page that holds a layer, looking past the groups it sits in. */
+function enclosingContainer(id: string, editor: Editor): string {
+ let parent = editor.graph.getNode(editor.graph.getNode(id)?.parentId ?? '')
+ while (parent?.parentId && ENCLOSING_TYPES.has(parent.type)) {
+ parent = editor.graph.getNode(parent.parentId)
}
+ return parent?.id ?? editor.state.currentPageId
+}
+
+/**
+ * Moves dropped layers into the frame under the cursor, or onto the page. A layer that lands in
+ * the frame already holding it keeps its group.
+ */
+export function reparentDroppedNodes(editor: Editor, ids: string[], targetId: string | null) {
+ const target = targetId ?? editor.state.currentPageId
+ const moving = ids.filter((id) => enclosingContainer(id, editor) !== target)
+ if (moving.length > 0) editor.reparentNodes(moving, target)
}
diff --git a/packages/vue/src/shared/input/duplicate-drag.ts b/packages/vue/src/shared/input/duplicate-drag.ts
index acb4cac50..c2a91df1b 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 { useI18n } from '#vue/i18n/useI18n.js'
import type { DragOriginal } from '#vue/shared/input/drag-original'
import type { DragState } from '#vue/shared/input/types'
@@ -12,16 +11,13 @@ export function duplicateAndDrag(
editor: Editor
): { originals: Map<string, DragOriginal>; drag: DragState } {
const previousSelection = new Set(editor.state.selectedIds)
- const { panels } = useI18n()
const newIds: string[] = []
const newOriginals = new Map<string, DragOriginal>()
for (const id of previousSelection) {
const source = editor.graph.getNode(id)
if (!source) continue
const parentId = source.parentId ?? editor.state.currentPageId
- const clone = editor.graph.cloneTree(id, parentId, {
- name: source.name + panels.value.nodeCopyString || ' copy'
- })
+ const clone = editor.duplicateNode(source, parentId, { x: source.x, y: source.y })
if (!clone) continue
newIds.push(clone.id)
newOriginals.set(clone.id, {
diff --git a/packages/vue/src/shared/input/move.ts b/packages/vue/src/shared/input/move.ts
index 8e43874aa..b39c718bc 100644
--- a/packages/vue/src/shared/input/move.ts
+++ b/packages/vue/src/shared/input/move.ts
@@ -1,4 +1,7 @@
+import type { SceneNode } from '@open-pencil/scene-graph'
+
import {
+ autoLayoutInsertIndex,
computeAutoLayoutIndicator,
computeAutoLayoutIndicatorForFrame
} from '#vue/shared/input/auto-layout'
@@ -6,7 +9,7 @@ import {
isPastPointerDragThreshold,
POINTER_DRAG_START_THRESHOLD_PX
} from '#vue/shared/input/drag-threshold'
-import { findMoveDropTarget, reparentOutsideNodes } from '#vue/shared/input/drop-target'
+import { findMoveDropTarget, reparentDroppedNodes } from '#vue/shared/input/drop-target'
export { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'
import { AUTO_LAYOUT_BREAK_THRESHOLD } from '@open-pencil/core/constants'
import type { Editor } from '@open-pencil/core/editor'
@@ -49,6 +52,38 @@ export function detectAutoLayoutParent(editor: Editor): string | undefined {
return undefined
}
+/** Keys held during a move. Figma maps Control to both, Shift to an axis lock. */
+export interface MoveModifiers {
+ /** Turns off snapping and drops into auto layout as an absolute-positioned layer. */
+ ctrlKey?: boolean
+ /** Locks the move to the axis it has travelled furthest along. */
+ shiftKey?: boolean
+}
+
+function lockToAxis(dx: number, dy: number, lock: boolean) {
+ if (!lock) return { dx, dy }
+ return Math.abs(dx) >= Math.abs(dy) ? { dx, dy: 0 } : { dx: 0, dy }
+}
+
+/**
+ * Where Control drops layers among an auto layout frame's children. Like Figma, layers from
+ * elsewhere go in at the cursor; layers already in the frame go on top.
+ */
+function absoluteInsertIndex(
+ d: DragMove,
+ target: SceneNode | null,
+ cx: number,
+ cy: number,
+ editor: Editor,
+ moving: ReadonlySet<string>
+) {
+ if (!d.ignoreAutoLayout || !target || target.layoutMode === 'NONE') return undefined
+ // The graph clamps an index past the end, which puts the layers on top.
+ if ([...d.originals.values()].some((orig) => orig.parentId === target.id))
+ return target.childIds.length
+ return autoLayoutInsertIndex(target, cx, cy, editor, moving)
+}
+
function isPastDragStartThreshold(d: DragMove, sx: number, sy: number) {
return isPastPointerDragThreshold(d.startScreenX, d.startScreenY, sx, sy)
}
@@ -60,21 +95,21 @@ export function handleMoveMove(
sx: number,
sy: number,
editor: Editor,
- disableSnapping = false
+ modifiers: MoveModifiers = {}
) {
d.currentX = cx
d.currentY = cy
+ d.ignoreAutoLayout = modifiers.ctrlKey === true
if (!d.dragStarted) {
if (!isPastDragStartThreshold(d, sx, sy)) return
d.dragStarted = true
}
- let dx = cx - d.startX
- let dy = cy - d.startY
+ let { dx, dy } = lockToAxis(cx - d.startX, cy - d.startY, modifiers.shiftKey === true)
if (d.autoLayoutParentId && !d.brokeFromAutoLayout) {
- if (isInsideAutoLayoutDragBounds(d.autoLayoutParentId, cx, cy, editor)) {
+ if (!d.ignoreAutoLayout && isInsideAutoLayoutDragBounds(d.autoLayoutParentId, cx, cy, editor)) {
computeAutoLayoutIndicator(d, cx, cy, editor)
return
}
@@ -82,12 +117,13 @@ export function handleMoveMove(
editor.setLayoutInsertIndicator(null)
}
- const dropTarget = findMoveDropTarget(cx, cy, editor)
- const dropParent = dropTarget ? editor.graph.getNode(dropTarget.id) : null
+ const moving = new Set(d.originals.keys())
+ const dropTarget = d.keepParents ? null : findMoveDropTarget(cx, cy, editor, moving)
+ d.absoluteInsertIndex = absoluteInsertIndex(d, dropTarget, cx, cy, editor, moving)
- if (dropParent && dropParent.layoutMode !== 'NONE') {
- computeAutoLayoutIndicatorForFrame(dropParent, cx, cy, editor)
- editor.setDropTarget(dropParent.id)
+ if (dropTarget && dropTarget.layoutMode !== 'NONE' && !d.ignoreAutoLayout) {
+ computeAutoLayoutIndicatorForFrame(dropTarget, cx, cy, editor)
+ editor.setDropTarget(dropTarget.id)
let firstApplied: { dx: number; dy: number } | null = null
for (const [id, orig] of d.originals) {
const previewX = Math.round(orig.x + dx)
@@ -105,9 +141,9 @@ export function handleMoveMove(
editor.setLayoutInsertIndicator(null)
- const snapped = applyMoveSnap(d, dx, dy, editor, disableSnapping)
- dx = snapped.dx
- dy = snapped.dy
+ const snapped = applyMoveSnap(d, dx, dy, editor, modifiers.ctrlKey === true)
+ // Snapping must not pull the layer off a locked axis.
+ ;({ dx, dy } = lockToAxis(snapped.dx, snapped.dy, modifiers.shiftKey === true))
d.appliedDx = dx
d.appliedDy = dy
@@ -136,17 +172,76 @@ function restoreOriginalPositions(d: DragMove, editor: Editor) {
}
}
+function isLeavingAutoLayout(d: DragMove, id: string, editor: Editor) {
+ const node = editor.graph.getNode(id)
+ const parent = editor.graph.getNode(node?.parentId ?? '')
+ if (d.keepParents || !parent || parent.layoutMode === 'NONE') return false
+ if (node?.layoutPositioning === 'ABSOLUTE') return false
+ return (editor.state.dropTargetId ?? editor.state.currentPageId) !== parent.id
+}
+
function applyFinalPositions(d: DragMove, editor: Editor) {
for (const [id, orig] of d.originals) {
- editor.updateNode(id, { x: orig.x + d.appliedDx, y: orig.y + d.appliedDy })
+ const position = { x: orig.x + d.appliedDx, y: orig.y + d.appliedDy }
+ // Laying out now would snap the layer back into its slot before it leaves the frame.
+ if (isLeavingAutoLayout(d, id, editor)) editor.graph.updateNode(id, position)
+ else editor.updateNode(id, position)
}
}
+/** Closes the gaps moved layers leave in auto layout frames. */
+function layOutOriginalParents(d: DragMove, editor: Editor) {
+ for (const parentId of new Set([...d.originals.values()].map((orig) => orig.parentId))) {
+ if (editor.graph.getNode(parentId)?.layoutMode !== 'NONE') editor.runLayoutForNode(parentId)
+ }
+}
+
+/** Control into auto layout: absolute first, so layout keeps the positions the move writes. */
+function ignoreTargetAutoLayout(d: DragMove, editor: Editor) {
+ const targetId = editor.state.dropTargetId
+ const target = targetId ? editor.graph.getNode(targetId) : null
+ if (d.keepParents || !d.ignoreAutoLayout || !target || target.layoutMode === 'NONE') return
+ for (const id of d.originals.keys()) {
+ if (editor.graph.getNode(id)?.layoutPositioning === 'ABSOLUTE') continue
+ editor.updateNodeWithUndo(id, { layoutPositioning: 'ABSOLUTE' }, 'Ignore auto layout')
+ }
+}
+
+function dropMovedNodes(d: DragMove, editor: Editor) {
+ const ids = [...d.originals.keys()]
+ reparentDroppedNodes(editor, ids, editor.state.dropTargetId)
+ for (const id of ids) {
+ if (editor.graph.getNode(id)?.type === 'SECTION') editor.adoptCoveredLayers(id)
+ }
+}
+
+function movedParentIds(d: DragMove, editor: Editor) {
+ const ids = new Set<string>()
+ for (const [id, orig] of d.originals) {
+ ids.add(orig.parentId)
+ const parentId = editor.graph.getNode(id)?.parentId
+ if (parentId) ids.add(parentId)
+ }
+ return ids
+}
+
+function placeAbsoluteDrop(d: DragMove, editor: Editor) {
+ const targetId = editor.state.dropTargetId
+ const index = d.absoluteInsertIndex
+ if (!targetId || index === undefined) return
+ const ids = [...d.originals.keys()].filter(
+ (id) => editor.graph.getNode(id)?.parentId === targetId
+ )
+ for (const [offset, id] of ids.entries())
+ editor.reorderChildWithUndo(id, targetId, index + offset)
+}
+
export function handleMoveUp(d: DragMove, editor: Editor) {
if (!d.dragStarted) {
editor.setLayoutInsertIndicator(null)
editor.setSnapGuides([])
editor.setDropTarget(null)
+ if (d.selectOnClick) editor.select([d.selectOnClick])
return
}
@@ -183,14 +278,11 @@ export function handleMoveUp(d: DragMove, editor: Editor) {
// The batch keeps a slot claim in the same undo step; it carries the edit's own name.
editor.undo.runBatch(d.duplicated ? 'Duplicate' : 'Move', () => {
if (moved) {
+ ignoreTargetAutoLayout(d, editor)
restoreOriginalPositions(d, editor)
applyFinalPositions(d, editor)
- const dropId = editor.state.dropTargetId
- if (dropId) {
- editor.reparentNodes([...editor.state.selectedIds], dropId)
- } else {
- reparentOutsideNodes(editor)
- }
+ if (!d.keepParents) dropMovedNodes(d, editor)
+ layOutOriginalParents(d, editor)
}
if (d.duplicated) {
editor.commitDuplicateMove(
@@ -200,6 +292,10 @@ export function handleMoveUp(d: DragMove, editor: Editor) {
} else if (moved) {
editor.commitMoveWithReparent(d.originals)
}
+ // After the move is recorded, so undo restores the order before taking the layers back out.
+ if (moved && !d.keepParents) placeAbsoluteDrop(d, editor)
+ // Groups and booleans the layers left or moved inside fit their children again.
+ if (moved) editor.fitEnclosingGroups(movedParentIds(d, editor))
})
editor.setDropTarget(null)
}
diff --git a/packages/vue/src/shared/input/resize.ts b/packages/vue/src/shared/input/resize.ts
index 3b2310b41..2c8a87c14 100644
--- a/packages/vue/src/shared/input/resize.ts
+++ b/packages/vue/src/shared/input/resize.ts
@@ -229,6 +229,18 @@ function clearResizedRawGeometry(editor: Editor, nodeId: string): void {
export function commitResizePreview(dragState: DragResize, editor: Editor) {
// See applyResize — reactive drag state must not leak into graph writes.
const d = toRaw(dragState)
+ if (editor.graph.getNode(d.nodeId)?.type !== 'SECTION') {
+ commitResizeGeometry(d, editor)
+ return
+ }
+ // A section resized over layers takes in the ones it now covers, in the same undo step.
+ editor.undo.runBatch('Resize', () => {
+ commitResizeGeometry(d, editor)
+ editor.adoptCoveredLayers(d.nodeId)
+ })
+}
+
+function commitResizeGeometry(d: DragResize, editor: Editor) {
optionalEditorState(editor)?.snapGuides.splice(0)
const node = editor.graph.getNode(d.nodeId)
if (!node) return
diff --git a/packages/vue/src/shared/input/select.ts b/packages/vue/src/shared/input/select.ts
index 06834e1eb..9c686f215 100644
--- a/packages/vue/src/shared/input/select.ts
+++ b/packages/vue/src/shared/input/select.ts
@@ -6,7 +6,12 @@ import type { Editor } from '@open-pencil/core/editor'
import type { SceneNode } from '@open-pencil/scene-graph'
import { tryStartResize } from '#vue/shared/input/resize'
-import { createSelectionMoveDrag, selectionIsLocked } from '#vue/shared/input/select/move'
+import {
+ createSelectionMoveDrag,
+ clickSelectsInside,
+ pressesSelection,
+ selectionIsLocked
+} from '#vue/shared/input/select/move'
import type { DragState } from '#vue/shared/input/types'
export interface HitTestFns {
@@ -56,7 +61,8 @@ export function handleSelectDown(
return
}
- if (!editor.state.selectedIds.has(hit.id) && !e.shiftKey) {
+ const keepsSelection = !e.shiftKey && pressesSelection(hit, cx, cy, editor)
+ if (!editor.state.selectedIds.has(hit.id) && !e.shiftKey && !keepsSelection) {
editor.select([hit.id])
} else if (e.shiftKey) {
editor.select([hit.id], true)
@@ -64,5 +70,10 @@ export function handleSelectDown(
if (selectionIsLocked(editor)) return
- setDrag(createSelectionMoveDrag(cx, cy, sx, sy, editor, e.altKey))
+ const drag = createSelectionMoveDrag(cx, cy, sx, sy, editor, e.altKey)
+ // A click without dragging still selects a layer inside a selected frame; groups need a double-click.
+ if (drag.type === 'move' && keepsSelection && !editor.state.selectedIds.has(hit.id)) {
+ drag.selectOnClick = clickSelectsInside(hit, editor) ? hit.id : undefined
+ }
+ setDrag(drag)
}
diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.ts
index 55ce9953a..1d57e3f58 100644
--- a/packages/vue/src/shared/input/select/move.ts
+++ b/packages/vue/src/shared/input/select/move.ts
@@ -1,11 +1,47 @@
import type { Editor } 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'
+function isLockedInTree(id: string, editor: Editor) {
+ for (
+ let node = editor.graph.getNode(id);
+ node;
+ node = editor.graph.getNode(node.parentId ?? '')
+ ) {
+ if (node.locked) return true
+ }
+ return false
+}
+
+/** Whether nothing selected can move: locked layers, and layers inside locked ones, stay put. */
export function selectionIsLocked(editor: Editor) {
- return [...editor.state.selectedIds].every((id) => editor.graph.getNode(id)?.locked)
+ return [...editor.state.selectedIds].every((id) => isLockedInTree(id, editor))
+}
+
+/**
+ * Whether pressing `hit` should drag the current selection, as in Figma: the hit lies inside a
+ * selected layer, or a selected layer under the point lies inside the hit group or boolean.
+ */
+export function pressesSelection(hit: SceneNode, cx: number, cy: number, editor: Editor) {
+ return [...editor.state.selectedIds].some((id) => {
+ if (id === hit.id) return false
+ if (editor.graph.isDescendant(hit.id, id)) return true
+ return editor.graph.isDescendant(id, hit.id) && editor.graph.isPointInNode(id, cx, cy)
+ })
+}
+
+/** Whether clicking `hit` inside the selection selects it: not when a selected group holds it. */
+export function clickSelectsInside(hit: SceneNode, editor: Editor) {
+ for (let node = editor.graph.getNode(hit.parentId ?? ''); node;) {
+ if (editor.state.selectedIds.has(node.id)) {
+ return node.type !== 'GROUP' && node.type !== 'BOOLEAN_OPERATION'
+ }
+ node = editor.graph.getNode(node.parentId ?? '')
+ }
+ return false
}
function autoLayoutMoveTarget(id: string, editor: Editor): string {
@@ -31,6 +67,7 @@ function autoLayoutMoveTarget(id: string, editor: Editor): string {
function collectMoveOriginals(editor: Editor) {
const originals = new Map<string, MoveOriginal>()
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) {
diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.ts
index cde1c573f..f97e95d01 100644
--- a/packages/vue/src/shared/input/types.ts
+++ b/packages/vue/src/shared/input/types.ts
@@ -17,8 +17,11 @@ export type CornerPosition = 'nw' | 'ne' | 'se' | 'sw'
export interface DragDraw {
type: 'draw'
+ /** Start point in the parent's axes. */
startX: number
startY: number
+ /** Maps a canvas point into the parent's axes. */
+ toLocal: (x: number, y: number) => Vector
nodeId: string
update: (changes: Partial<SceneNode>) => void
commit: () => void
@@ -41,6 +44,14 @@ export interface DragMove {
duplicatedPreviousSelection?: Set<string>
autoLayoutParentId?: string
brokeFromAutoLayout?: boolean
+ /** Space is held: layers keep their parents wherever they are dropped. */
+ keepParents?: boolean
+ /** Control is held: auto layout frames take the layers as absolute-positioned children. */
+ ignoreAutoLayout?: boolean
+ /** Selected instead if the press ends as a click without dragging. */
+ selectOnClick?: string
+ /** Where Control drops layers among an auto layout frame's children. */
+ absoluteInsertIndex?: number
}
export interface DragPan {
diff --git a/packages/vue/tests/shared/input/draw-parent.test.ts b/packages/vue/tests/shared/input/draw-parent.test.ts
new file mode 100644
index 000000000..3c50e6ffc
--- /dev/null
+++ b/packages/vue/tests/shared/input/draw-parent.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { createEditor, type Editor, type Tool } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { handleDrawMove, startShapeDraw } from '#vue/shared/input/draw'
+import type { DragState } from '#vue/shared/input/types'
+
+// Each case replays a drawing observed in Figma desktop 126 with real pointer input.
+
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ editor = createEditor()
+ return editor.state.currentPageId
+}
+
+function node(type: SceneNode['type'], parentId: string, props: Partial<SceneNode> = {}) {
+ return editor.graph.createNode(type, parentId, { width: 40, height: 40, ...props })
+}
+
+function draw(tool: Tool, from: [number, number], to: [number, number] = from) {
+ editor.setTool(tool)
+ let drag: DragState | null = null
+ startShapeDraw(from[0], from[1], editor, (d) => {
+ drag = d
+ })
+ const drawing = drag as DragState | null
+ if (drawing?.type !== 'draw') throw new Error('Expected a drawing')
+ if (to !== from) handleDrawMove(drawing, to[0], to[1], false)
+ drawing.commit()
+ const created = editor.graph.getNode(drawing.nodeId)
+ if (!created) throw new Error('Expected a drawn layer')
+ return created
+}
+
+describe('drawing into containers', () => {
+ test('puts the layer in the frame under the start point, even when it ends outside', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { x: 100, y: 100, width: 200, height: 200 })
+ const rect = draw('RECTANGLE', [250, 250], [400, 400])
+ expect(rect.parentId).toBe(frame.id)
+ expect(rect).toMatchObject({ x: 150, y: 150, width: 150, height: 150 })
+ })
+
+ test('adds the layer to the end of an auto layout flow', () => {
+ const page = setup()
+ const row = node('FRAME', page, {
+ width: 300,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ itemSpacing: 10,
+ paddingLeft: 10,
+ paddingTop: 10
+ })
+ node('RECTANGLE', row.id, { width: 60, height: 60 })
+ const rect = draw('RECTANGLE', [150, 20], [190, 60])
+ expect(rect.parentId).toBe(row.id)
+ expect(rect).toMatchObject({ x: 80, y: 10 })
+ })
+
+ test('skips groups and locked frames', () => {
+ const page = setup()
+
+ node('GROUP', page, { x: 500, width: 200, height: 200 })
+ expect(draw('RECTANGLE', [550, 50], [580, 80]).parentId).toBe(page)
+
+ node('FRAME', page, { x: 800, width: 200, height: 200, locked: true })
+ expect(draw('RECTANGLE', [850, 50], [880, 80]).parentId).toBe(page)
+ })
+
+ test('draws in the axes of a rotated frame', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 200, rotation: 90 })
+ const rect = draw('RECTANGLE', [100, 100], [150, 150])
+ expect(rect.parentId).toBe(frame.id)
+ expect(rect.width).toBeCloseTo(50)
+ expect(rect.height).toBeCloseTo(50)
+ })
+
+ test('a drawn frame adopts the unlocked layers it fully covers', () => {
+ const page = setup()
+ const covered = node('RECTANGLE', page, { x: 20, y: 20 })
+ const partial = node('RECTANGLE', page, { x: 120, y: 120, width: 60, height: 60 })
+ const locked = node('RECTANGLE', page, { x: 60, y: 20, locked: true })
+ const section = node('SECTION', page, { x: 20, y: 80, width: 30, height: 30 })
+ const frame = draw('FRAME', [-20, -20], [150, 150])
+ expect(covered.parentId).toBe(frame.id)
+ expect(editor.graph.getAbsolutePosition(covered.id)).toEqual({ x: 20, y: 20 })
+ expect(partial.parentId).toBe(page)
+ expect(locked.parentId).toBe(page)
+ expect(section.parentId).toBe(page)
+
+ editor.undoAction()
+ expect(covered.parentId).toBe(page)
+ expect(editor.graph.getNode(frame.id)).toBeUndefined()
+ })
+
+ test('a frame made by a click adopts nothing', () => {
+ const page = setup()
+ const small = node('RECTANGLE', page, { x: 10, y: 10, width: 10, height: 10 })
+ draw('FRAME', [0, 0])
+ expect(small.parentId).toBe(page)
+ })
+
+ test('a drawn rectangle adopts nothing', () => {
+ const page = setup()
+ const covered = node('RECTANGLE', page, { x: 20, y: 20 })
+ draw('RECTANGLE', [-20, -20], [150, 150])
+ expect(covered.parentId).toBe(page)
+ })
+})
diff --git a/packages/vue/tests/shared/input/move/containers.test.ts b/packages/vue/tests/shared/input/move/containers.test.ts
new file mode 100644
index 000000000..02d7b7008
--- /dev/null
+++ b/packages/vue/tests/shared/input/move/containers.test.ts
@@ -0,0 +1,184 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { autoLayoutInsertIndex } from '#vue/shared/input/auto-layout'
+import { handleMoveMove, handleMoveUp } from '#vue/shared/input/move'
+import {
+ clickSelectsInside,
+ createSelectionMoveDrag,
+ pressesSelection
+} from '#vue/shared/input/select/move'
+
+import { createMoveHarness, type MoveHarness } from './harness'
+
+// Each case replays an interaction observed in Figma desktop 126 with real pointer input.
+
+let h: MoveHarness
+
+afterEach(() => h.editor.dispose())
+
+function setup() {
+ h = createMoveHarness()
+ return h
+}
+
+function variants() {
+ const { node, page } = setup()
+ const set = node('COMPONENT_SET', page, { width: 300, height: 140 })
+ const variant = node('COMPONENT', set.id, { x: 20, y: 20, width: 60, height: 60 })
+ const sibling = node('COMPONENT', set.id, { x: 180, y: 20, width: 100, height: 100 })
+ return { set, variant, sibling }
+}
+
+describe('component sets', () => {
+ test('a variant stays in its set while dropped over it, even onto a sibling', () => {
+ const { set, variant } = variants()
+ h.drag([variant.id], [50, 50], [100, 70])
+ expect(h.parentOf(variant.id)).toBe(set.id)
+ h.drag([variant.id], [100, 70], [230, 70])
+ expect(h.parentOf(variant.id)).toBe(set.id)
+ })
+
+ test('a variant leaves its set for a frame or the page', () => {
+ const { variant } = variants()
+ const frame = h.node('FRAME', h.page, { x: 500, width: 200, height: 200 })
+ h.drag([variant.id], [50, 50], [600, 100])
+ expect(h.parentOf(variant.id)).toBe(frame.id)
+ h.drag([variant.id], [600, 100], [600, 500])
+ expect(h.parentOf(variant.id)).toBe(h.page)
+ })
+
+ test('a set does not take components from elsewhere, nor a component another', () => {
+ const { set } = variants()
+ const loose = h.node('COMPONENT', h.page, { x: 600, width: 60, height: 60 })
+ h.drag([loose.id], [630, 30], [150, 100])
+ expect(h.parentOf(loose.id)).toBe(h.page)
+
+ const big = h.node('COMPONENT', h.page, { y: 400, width: 200, height: 200 })
+ h.drag([loose.id], [150, 100], [100, 500])
+ expect(h.parentOf(loose.id)).toBe(h.page)
+ expect(h.parentOf(big.id)).toBe(h.page)
+ expect(h.childIds(set.id)).toHaveLength(2)
+ })
+})
+
+describe('Alt-drag duplicates', () => {
+ test('a main component becomes an instance at the drop, keeping the name', () => {
+ const { node, page, editor } = setup()
+ const component = node('COMPONENT', page, { name: 'C', width: 100, height: 100 })
+ editor.select([component.id])
+ const move = createSelectionMoveDrag(50, 50, 50, 50, editor, true)
+ if (move.type !== 'move') throw new Error('Expected a move drag')
+ handleMoveMove(move, 300, 50, 300, 50, editor)
+ handleMoveUp(move, editor)
+ const [copyId] = editor.state.selectedIds
+ expect(editor.graph.getNode(copyId)).toMatchObject({
+ type: 'INSTANCE',
+ componentId: component.id,
+ name: 'C',
+ x: 250
+ })
+ expect(editor.graph.getNode(component.id)?.x).toBe(0)
+ })
+})
+
+describe('groups and booleans', () => {
+ function grouped(type: 'GROUP' | 'BOOLEAN_OPERATION' = 'GROUP') {
+ const { node, page } = setup()
+ const group = node(type, page, { width: 160, height: 160 })
+ const a = node('RECTANGLE', group.id, { width: 60, height: 60 })
+ const b = node('RECTANGLE', group.id, { x: 100, y: 100, width: 60, height: 60 })
+ return { group, a, b }
+ }
+
+ test.each(['GROUP', 'BOOLEAN_OPERATION'] as const)(
+ '%s fits its children again after one moves, keeping canvas positions',
+ (type) => {
+ const { group, a, b } = grouped(type)
+ h.drag([a.id], [20, 20], [300, 300])
+ expect(h.editor.graph.getNode(group.id)).toMatchObject({ x: 100, y: 100, width: 240 })
+ expect(h.editor.graph.getAbsolutePosition(a.id)).toEqual({ x: 280, y: 280 })
+ expect(h.editor.graph.getAbsolutePosition(b.id)).toEqual({ x: 100, y: 100 })
+
+ h.editor.undoAction()
+ expect(h.editor.graph.getNode(group.id)).toMatchObject({ x: 0, y: 0, width: 160 })
+ expect(h.editor.graph.getAbsolutePosition(a.id)).toEqual({ x: 0, y: 0 })
+ }
+ )
+
+ test('a group whose layers all leave goes away, and undo brings it back', () => {
+ const { group, a, b } = grouped()
+ const frame = h.node('FRAME', h.page, { x: 400, width: 300, height: 300 })
+ h.drag([a.id, b.id], [30, 30], [450, 50])
+ expect(h.editor.graph.getNode(group.id)).toBeUndefined()
+ expect(h.parentOf(a.id)).toBe(frame.id)
+
+ h.editor.undoAction()
+ expect(h.childIds(group.id)).toEqual([a.id, b.id])
+ expect(h.parentOf(group.id)).toBe(h.page)
+ })
+
+ test('nudging a group child fits the group', () => {
+ const { group, a } = grouped()
+ h.editor.select([a.id])
+ h.editor.nudgeSelected(-20, 0)
+ h.editor.flushNudge()
+ expect(h.editor.graph.getNode(group.id)).toMatchObject({ x: -20, width: 180 })
+ })
+})
+
+describe('auto layout', () => {
+ const flow = { itemSpacing: 10, paddingLeft: 10, paddingTop: 10, paddingRight: 10 }
+
+ test('a child dragged out lands where it was dropped', () => {
+ const { node, page, editor } = setup()
+ const row = node('FRAME', page, { width: 300, height: 100, layoutMode: 'HORIZONTAL', ...flow })
+ const a = node('RECTANGLE', row.id, { width: 60, height: 60 })
+ const b = node('RECTANGLE', row.id, { width: 60, height: 60 })
+ editor.runLayoutForNode(row.id)
+ h.drag([a.id], [40, 40], [500, 300])
+ expect(h.parentOf(a.id)).toBe(page)
+ expect(editor.graph.getNode(a.id)).toMatchObject({ x: 470, y: 270 })
+ expect(editor.graph.getNode(b.id)).toMatchObject({ x: 10, y: 10 })
+ })
+
+ test('a wrapped frame inserts on the line under the cursor', () => {
+ const { node, page, editor } = setup()
+ const wrap = node('FRAME', page, {
+ width: 160,
+ height: 200,
+ layoutMode: 'HORIZONTAL',
+ layoutWrap: 'WRAP',
+ counterAxisSpacing: 10,
+ ...flow
+ })
+ for (let i = 0; i < 3; i++) node('RECTANGLE', wrap.id, { width: 60, height: 60 })
+ editor.runLayoutForNode(wrap.id)
+ expect(autoLayoutInsertIndex(wrap, 100, 110, editor, new Set())).toBe(3)
+ expect(autoLayoutInsertIndex(wrap, 20, 110, editor, new Set())).toBe(2)
+ expect(autoLayoutInsertIndex(wrap, 100, 40, editor, new Set())).toBe(1)
+ })
+})
+
+describe('pressing inside the selection', () => {
+ test('drags a selected container rather than the child under the cursor', () => {
+ const { node, page, editor } = setup()
+ const outer = node('FRAME', page, { width: 500, height: 500 })
+ const nested = node('FRAME', outer.id, { x: 50, y: 50, width: 300, height: 300 })
+ const child = node('RECTANGLE', nested.id, { x: 50, y: 50, width: 60, height: 60 })
+ editor.select([nested.id])
+ expect(pressesSelection(child, 130, 130, editor)).toBe(true)
+ // A click without dragging still selects the child of a frame.
+ expect(clickSelectsInside(child, editor)).toBe(true)
+ })
+
+ test('keeps a selected group child when the group is hit, and a selected group on click', () => {
+ const { node, page, editor } = setup()
+ const group = node('GROUP', page, { width: 160, height: 160 })
+ const a = node('RECTANGLE', group.id, { width: 60, height: 60 })
+ editor.select([a.id])
+ expect(pressesSelection(group, 20, 20, editor)).toBe(true)
+ expect(pressesSelection(group, 120, 120, editor)).toBe(false)
+ editor.select([group.id])
+ expect(clickSelectsInside(a, editor)).toBe(false)
+ })
+})
diff --git a/packages/vue/tests/shared/input/move/drop.test.ts b/packages/vue/tests/shared/input/move/drop.test.ts
new file mode 100644
index 000000000..b25f3d07e
--- /dev/null
+++ b/packages/vue/tests/shared/input/move/drop.test.ts
@@ -0,0 +1,164 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import type { Editor } from '@open-pencil/core/editor'
+
+import { createMoveHarness, type MoveHarness } from './harness'
+
+// Each case replays a drag observed in Figma desktop 126 with real pointer input.
+
+let h: MoveHarness
+let editor: Editor
+
+afterEach(() => editor.dispose())
+
+function setup() {
+ h = createMoveHarness()
+ editor = h.editor
+ return h.page
+}
+
+const node: MoveHarness['node'] = (...args) => h.node(...args)
+const drag: MoveHarness['drag'] = (...args) => h.drag(...args)
+const parentOf: MoveHarness['parentOf'] = (id) => h.parentOf(id)
+
+describe('dropping moved layers', () => {
+ test('nests a layer when the cursor is inside a frame, however little of it is', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 200 })
+ const box = node('RECTANGLE', page, { x: 400, width: 100, height: 100 })
+ drag([box.id], [405, 5], [190, 100])
+ expect(parentOf(box.id)).toBe(frame.id)
+ })
+
+ test('takes a layer out of its frame as soon as the cursor leaves it', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 200 })
+ const child = node('RECTANGLE', frame.id, { x: 160, y: 80 })
+ drag([child.id], [198, 100], [212, 100])
+ expect(parentOf(child.id)).toBe(page)
+ expect(editor.graph.getAbsolutePosition(child.id)).toEqual({ x: 174, y: 80 })
+
+ editor.undoAction()
+ expect(parentOf(child.id)).toBe(frame.id)
+ })
+
+ test('keeps a layer in its group unless it lands on another frame', () => {
+ const page = setup()
+ const group = node('GROUP', page, { width: 200, height: 200 })
+ const child = node('RECTANGLE', group.id)
+ drag([child.id], [20, 20], [400, 100])
+ expect(parentOf(child.id)).toBe(group.id)
+
+ const frame = node('FRAME', page, { x: 600, width: 200, height: 200 })
+ drag([child.id], [400, 100], [700, 100])
+ expect(parentOf(child.id)).toBe(frame.id)
+ })
+
+ test('never drops into groups or locked frames', () => {
+ const page = setup()
+ node('GROUP', page, { width: 200, height: 200 })
+ node('FRAME', page, { x: 300, width: 200, height: 200, locked: true })
+ const box = node('RECTANGLE', page, { x: 600 })
+ drag([box.id], [620, 20], [100, 100])
+ expect(parentOf(box.id)).toBe(page)
+ drag([box.id], [100, 100], [400, 100])
+ expect(parentOf(box.id)).toBe(page)
+ })
+
+ test('leaves locked layers of a mixed selection in place', () => {
+ const page = setup()
+ const free = node('RECTANGLE', page)
+ const locked = node('RECTANGLE', page, { x: 100, locked: true })
+ drag([free.id, locked.id], [20, 20], [20, 120])
+ expect(editor.graph.getNode(free.id)?.y).toBe(100)
+ expect(editor.graph.getNode(locked.id)?.y).toBe(0)
+ })
+
+ test('keeps parents while Space is held', () => {
+ const page = setup()
+ const frame = node('FRAME', page, { width: 200, height: 200 })
+ const other = node('FRAME', page, { x: 300, width: 200, height: 200 })
+ const child = node('RECTANGLE', frame.id, { x: 80, y: 80 })
+ const keepParents = (move: { keepParents?: boolean }) => {
+ move.keepParents = true
+ }
+ drag([child.id], [100, 100], [400, 100], {}, keepParents)
+ expect(parentOf(child.id)).toBe(frame.id)
+ expect(editor.graph.getAbsolutePosition(child.id).x).toBe(380)
+ expect(editor.graph.getChildren(other.id)).toHaveLength(0)
+ })
+
+ test('Shift locks the move to its longer axis', () => {
+ const page = setup()
+ const box = node('RECTANGLE', page, { x: 400, y: 50 })
+ drag([box.id], [420, 70], [520, 160], { shiftKey: true })
+ expect(editor.graph.getNode(box.id)).toMatchObject({ x: 500, y: 50 })
+ drag([box.id], [520, 70], [550, 170], { shiftKey: true })
+ expect(editor.graph.getNode(box.id)).toMatchObject({ x: 500, y: 150 })
+ })
+
+ test('Control drops into auto layout as an absolute-positioned layer', () => {
+ const page = setup()
+ const row = node('FRAME', page, { width: 300, height: 100, layoutMode: 'HORIZONTAL' })
+ const box = node('RECTANGLE', page, { x: 400, y: 50 })
+ drag([box.id], [420, 70], [75, 50], { ctrlKey: true })
+ expect(parentOf(box.id)).toBe(row.id)
+ expect(editor.graph.getNode(box.id)).toMatchObject({
+ layoutPositioning: 'ABSOLUTE',
+ x: 55,
+ y: 30
+ })
+
+ editor.undoAction()
+ expect(parentOf(box.id)).toBe(page)
+ expect(editor.graph.getNode(box.id)?.layoutPositioning).toBe('AUTO')
+ })
+
+ test('Control puts a layer from elsewhere at the cursor among auto layout children', () => {
+ const page = setup()
+ const row = node('FRAME', page, { width: 300, height: 100, layoutMode: 'HORIZONTAL' })
+ const a = node('RECTANGLE', row.id, { name: 'a', x: 10, y: 10, width: 60, height: 60 })
+ const b = node('RECTANGLE', row.id, { name: 'b', x: 80, y: 10, width: 60, height: 60 })
+ const box = node('RECTANGLE', page, { x: 400, y: 50 })
+ const order = () => editor.graph.getChildren(row.id).map((child) => child.id)
+
+ drag([box.id], [420, 70], [75, 50], { ctrlKey: true })
+ expect(order()).toEqual([a.id, box.id, b.id])
+
+ editor.undoAction()
+ expect(order()).toEqual([a.id, b.id])
+ expect(parentOf(box.id)).toBe(page)
+
+ editor.redoAction()
+ expect(order()).toEqual([a.id, box.id, b.id])
+ expect(editor.graph.getNode(box.id)).toMatchObject({ x: 55, y: 30 })
+ })
+
+ test('Control puts a layer already in the auto layout frame on top', () => {
+ const page = setup()
+ const row = node('FRAME', page, { width: 300, height: 100, layoutMode: 'HORIZONTAL' })
+ const a = node('RECTANGLE', row.id, { x: 10, y: 10, width: 60, height: 60 })
+ const b = node('RECTANGLE', row.id, { x: 80, y: 10, width: 60, height: 60 })
+ drag([a.id], [40, 40], [60, 60], { ctrlKey: true })
+ expect(editor.graph.getChildren(row.id).map((child) => child.id)).toEqual([b.id, a.id])
+ expect(editor.graph.getNode(a.id)).toMatchObject({
+ layoutPositioning: 'ABSOLUTE',
+ x: 30,
+ y: 30
+ })
+ })
+
+ test('a moved section adopts the layers it fully covers', () => {
+ const page = setup()
+ const section = node('SECTION', page, { x: 400, width: 200, height: 200 })
+ const covered = node('RECTANGLE', page, { x: 50, y: 50 })
+ const partial = node('RECTANGLE', page, { x: 180, y: 50, width: 60 })
+ drag([section.id], [500, 100], [100, 100])
+ expect(parentOf(covered.id)).toBe(section.id)
+ expect(parentOf(partial.id)).toBe(page)
+
+ editor.undoAction()
+ expect(parentOf(covered.id)).toBe(page)
+ expect(editor.graph.getNode(section.id)?.x).toBe(400)
+ })
+})
diff --git a/packages/vue/tests/shared/input/move/harness.ts b/packages/vue/tests/shared/input/move/harness.ts
new file mode 100644
index 000000000..79b661d12
--- /dev/null
+++ b/packages/vue/tests/shared/input/move/harness.ts
@@ -0,0 +1,43 @@
+import { createEditor } from '@open-pencil/core/editor'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import { handleMoveMove, handleMoveUp, type MoveModifiers } from '#vue/shared/input/move'
+import { createSelectionMoveDrag } from '#vue/shared/input/select/move'
+import type { DragMove } from '#vue/shared/input/types'
+
+/** An editor with helpers that replay a canvas move the way pointer input drives it. */
+export function createMoveHarness() {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+
+ function node(type: SceneNode['type'], parentId: string, props: Partial<SceneNode> = {}) {
+ return editor.graph.createNode(type, parentId, { width: 40, height: 40, ...props })
+ }
+
+ function drag(
+ ids: string[],
+ from: [number, number],
+ to: [number, number],
+ modifiers: MoveModifiers = {},
+ during?: (move: DragMove) => void
+ ) {
+ editor.select(ids)
+ const move = createSelectionMoveDrag(from[0], from[1], from[0], from[1], editor, false)
+ if (move.type !== 'move') throw new Error('Expected a move drag')
+ during?.(move)
+ handleMoveMove(move, to[0], to[1], to[0], to[1], editor, modifiers)
+ handleMoveUp(move, editor)
+ }
+
+ function parentOf(id: string) {
+ return editor.graph.getNode(id)?.parentId
+ }
+
+ function childIds(id: string) {
+ return editor.graph.getChildren(id).map((child) => child.id)
+ }
+
+ return { editor, page, node, drag, parentOf, childIds }
+}
+
+export type MoveHarness = ReturnType<typeof createMoveHarness>
diff --git a/packages/vue/tests/shared/input/section-resize.test.ts b/packages/vue/tests/shared/input/section-resize.test.ts
new file mode 100644
index 000000000..4eaf079d6
--- /dev/null
+++ b/packages/vue/tests/shared/input/section-resize.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+import { applyResize, commitResizePreview } from '#vue/shared/input/resize'
+import type { DragResize } from '#vue/shared/input/types'
+
+describe('section resize', () => {
+ test('adopts the layers it grows over in the same undo step', () => {
+ const editor = createEditor()
+ try {
+ const page = editor.state.currentPageId
+ const section = editor.graph.createNode('SECTION', page, { width: 100, height: 100 })
+ const box = editor.graph.createNode('RECTANGLE', page, {
+ x: 150,
+ y: 150,
+ width: 40,
+ height: 40
+ })
+ const drag: DragResize = {
+ type: 'resize',
+ handle: 'se',
+ startX: 100,
+ startY: 100,
+ origRect: { x: 0, y: 0, width: 100, height: 100 },
+ nodeId: section.id,
+ origVectorNetwork: null,
+ origFillGeometry: [],
+ origStrokeGeometry: [],
+ origDerivedTextGlyphs: null,
+ origStrokes: [],
+ origTextPathData: null,
+ origTextPathBox: null,
+ origChildren: null
+ }
+
+ applyResize(drag, 250, 250, false, editor)
+ commitResizePreview(drag, editor)
+ expect(editor.graph.getNode(box.id)?.parentId).toBe(section.id)
+
+ editor.undoAction()
+ expect(editor.graph.getNode(box.id)?.parentId).toBe(page)
+ expect(editor.graph.getNode(section.id)?.width).toBe(100)
+ } finally {
+ editor.dispose()
+ }
+ })
+})
diff --git a/src/app/shell/keyboard/clipboard.ts b/src/app/shell/keyboard/clipboard.ts
index 0431377ab..5bd2774dd 100644
--- a/src/app/shell/keyboard/clipboard.ts
+++ b/src/app/shell/keyboard/clipboard.ts
@@ -77,20 +77,21 @@ export function bindEditorClipboard(store: EditorStore) {
return
}
+ // Like Figma, Paste keeps the copied position; Paste here in the canvas menu uses the cursor.
const html = e.clipboardData?.getData('text/html') ?? ''
if (html) {
- void pasteClipboardHTML(store, html, cursorPos)
+ void pasteClipboardHTML(store, html)
return
}
if (isTauri()) {
- void tauriSystemClipboard.paste(store, cursorPos)
+ void tauriSystemClipboard.paste(store, undefined)
return
}
const memoryHTML = getInMemoryClipboardHTML()
if (memoryHTML) {
- void pasteClipboardHTML(store, memoryHTML, cursorPos)
+ void pasteClipboardHTML(store, memoryHTML)
}
})
}
diff --git a/tests/e2e/editor/duplicate-undo.spec.ts b/tests/e2e/editor/duplicate-undo.spec.ts
index 82cfbe5eb..127a640bd 100644
--- a/tests/e2e/editor/duplicate-undo.spec.ts
+++ b/tests/e2e/editor/duplicate-undo.spec.ts
@@ -33,7 +33,7 @@ test('undo after option-drag duplicate removes the copy', async () => {
await editor.canvas.altDrag(180, 165, 340, 165)
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])
+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
await editor.canvas.undo()
await expect.poll(rectangleCount).toBe(1)
@@ -52,12 +52,12 @@ test('undo after option-drag duplicate removes the copy', async () => {
await editor.page.keyboard.up('Meta')
await editor.canvas.waitForRender()
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])
+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })
await editor.page.waitForTimeout(1500)
await expect.poll(rectangleCount).toBe(2)
- await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle copy'])
+ await expect.poll(layerItems).toEqual(['Rectangle', 'Rectangle'])
await expect.poll(historyState).toMatchObject({ canUndo: true, undoLabel: 'Duplicate' })
editor.canvas.assertNoErrors()
})
diff --git a/tests/engine/vue/input/move-threshold.test.ts b/tests/engine/vue/input/move-threshold.test.ts
index 488ba85b3..fee607e58 100644
--- a/tests/engine/vue/input/move-threshold.test.ts
+++ b/tests/engine/vue/input/move-threshold.test.ts
@@ -74,7 +74,7 @@ describe('selection move drag threshold', () => {
test('Control bypasses object and pixel snapping during movement', () => {
const { editor, drag, nodeId } = setupMoveDrag()
- handleMoveMove(drag, 16.25, 27.75, 110, 200, editor, true)
+ handleMoveMove(drag, 16.25, 27.75, 110, 200, editor, { ctrlKey: true })
handleMoveUp(drag, editor)
expect(editor.graph.getNode(nodeId)).toMatchObject({ x: 16.25, y: 27.75 })
@@ -101,7 +101,7 @@ describe('selection move drag threshold', () => {
const drag = createSelectionMoveDrag(0, 0, 0, 0, editor, false)
if (drag.type !== 'move') throw new Error('Expected move drag')
- handleMoveMove(drag, 74, 43, 100, 100, editor, true)
+ handleMoveMove(drag, 74, 43, 100, 100, editor, { ctrlKey: true })
const angle = (-30 * Math.PI) / 180
expect(drag.appliedDx).toBeCloseTo(74 * Math.cos(angle) - 43 * Math.sin(angle), 3)
diff --git a/tools/checks/architecture/src/steiger-rules/support.ts b/tools/checks/architecture/src/steiger-rules/support.ts
index 6cc8bdf60..99f3b1bf6 100644
--- a/tools/checks/architecture/src/steiger-rules/support.ts
+++ b/tools/checks/architecture/src/steiger-rules/support.ts
@@ -58,7 +58,7 @@ export const PACKAGE_ALIAS_OWNERS: Record<string, string> = {
'#core-tests/': 'packages/core/tests/',
'#fig/': 'packages/fig/',
'#fig-tests/': 'packages/fig/tests/',
- '#vue/': 'packages/vue/src/',
+ '#vue/': 'packages/vue/',
'#cli/': 'packages/cli/',
'#mcp/': 'packages/mcp/src/'
}