AI-native design editor. Open-source Figma alternative.
feat(editor): reorder auto layout children by arrow keys and drags as Figma does (#1065)
Danila Poyarkovcb58d59e5e66
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4cd4885b3..84d1be48b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,7 @@### Breaking changes+- `AUTO_LAYOUT_BREAK_THRESHOLD` is removed from `@open-pencil/core/constants`: a layer dragged out of auto layout now leaves by how far its own edge is past the frame, not by a cursor margin.- `SceneNode` from `@open-pencil/scene-graph` has `targetAspectRatio`, the size whose proportions a locked layer keeps, so code that builds `SceneNode` objects itself must include it.- `useFlatReorderDrag` from `@open-pencil/vue` takes `operations`, which drops each target accepts, and `onCombine`, for dropping onto an item, and `FlatReorderInstruction` is now any list-item `Instruction`, so it can be `'combine'` when a list opts in; code that switches on its `operation` needs that case.- The editor `Tool` type from `@open-pencil/core` and `@open-pencil/vue` includes `'COMMENT'`, and `EDITOR_TOOLS` and `TOOL_SHORTCUTS` list the Comment tool on <kbd>C</kbd>, so a `Record<Tool, …>` needs a `COMMENT` entry and toolbars built on `ToolbarRoot` show it. The canvas places nothing while it is active; the app's comments layer does.@@ -49,6 +50,8 @@### Added+- Drag several layers along an auto layout row or column together, as in Figma: they move as one block in their order, wherever you grab them, and layers selected in different rows each move along their own row. A layer dragged along a flow takes the next slot once its leading edge reaches the next layer's centre, as Figma reorders, instead of once the cursor does.+- Move a layer in an auto layout row or column with the arrow keys, as in Figma: Right and Left move it one slot along a row, Down and Up along a column, Shift too, and the arrows across the flow do nothing. With several layers selected, each moves one slot and one at the end stays; a run of keys is one undo step.- Lock a layer's aspect ratio with the button beside its width and height, as in Figma: typing either side changes the other, handles keep the ratio (<kbd>Ctrl</kbd> frees it for one drag, which then keeps the new size), a Fill layer in auto layout takes its other side from the ratio, and a constraint keeps it when exactly one axis follows the frame. The lock reads from and writes to `.fig` files and the clipboard, and the plugin API has `lockAspectRatio()`, `unlockAspectRatio()`, `targetAspectRatio`, and `constrainProportions`.- See the selection as a Vue or React component in the Code tab, as the Storybook export generates them: a component set with its variants as props and its behaviour's Reka UI or Radix parts, any other layer as a plain component of the elements it draws, with shaders playing through `shaders/vue` or `shaders/react`. HTML there now shows the selection as markup, images as file paths, and still rewrites it live when edited; with nothing selected it keeps the starter for writing new layers. A CSS/Tailwind switch styles HTML and components with a readable stylesheet or with Tailwind utilities, their states as variants such as `data-[state=checked]:`, and edited HTML is built with Tailwind's utilities; React with Tailwind replaces the Tailwind JSX format. In HTML, Vue, and React, as in Design JSX, the element around the cursor marks its layer on the canvas and design issues are underlined on the layer's class. `export -f storybook --css tailwind` styles the exported Vue and React components the same way.- Talk with the people in a shared room in a voice call, as in Figma: the headphones beside the avatars start or join it, a ring marks who is in the call and lights up while they speak, and the call's popover chooses the microphone and, where the browser allows, the speakers. Audio goes peer to peer, and only to the people in the call.@@ -120,6 +123,7 @@- Customize the toolbar in **Settings → Toolbar**, also opened from **Customize toolbar…** when you right-click it: hide tools, reorder them, and choose which share a flyout, on desktop and mobile alike. Hidden tools keep their shortcuts, **Move** always stays, and tools added in later versions join their default flyout in a customized toolbar.### Changed+- A layer dragged out of an auto layout frame leaves it as in Figma, once its edge is 5 px past the frame across the flow or about 15 px along it, instead of after the cursor travels 96 px beyond it.- Bound variables show as a neutral chip in the properties panel instead of purple text, so they no longer read as components.- Import SVG as editable layers, as pasting it into Figma does, from `import_svg`, dropped files, and pasted markup ([#734](https://github.com/open-pencil/open-pencil/issues/734)). Each `<g>` becomes a group, each shape its own vector, and each `<text>` a text layer with its fonts, `<tspan>` styles, alignment, and rotation, named after its `id`, element opacity is kept, and clipped content sits in a clip path group whose mask is drawn from the clip's shapes. The imported frame is white, clips its content, and is named after the root `<svg>` `id`; an SVG without a size imports as a group. Shapes are no longer merged into one multi-color vector.- With **Snap to Pixel Grid** on, moved layers and resized edges land on whole pixels at any zoom, and drawn layers start and end on whole pixels, as in Figma; zoomed in, moves and resizes could leave fractions before, and drawing was not snapped.@@ -169,6 +173,7 @@### Fixed+- ⌘Z right after arrow-key nudges undoes the nudges instead of the edit before them.- <kbd>⇧</kbd>-dragging a corner handle follows the side the pointer stretched most relative to the layer's size, as Figma does, instead of the side it moved more pixels along.- The AI provider list labels its "Your agents" and "Providers" groups in the app language instead of always in English.- Tooltips no longer appear when a popover such as the colour picker focuses its first control on open; they still show for keyboard focus. Moving the pointer along a row of buttons switches tooltips at once instead of blinking out, and tooltips centre on their control instead of sitting a few pixels off.diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.tsindex 84d9324bb..841d2823d 100644--- a/packages/core/src/constants.ts+++ b/packages/core/src/constants.ts@@ -570,6 +570,5 @@ export const HANDLE_HIT_RADIUS = 6export const ROTATION_HANDLE_DISTANCE = 24export const DEFAULT_TEXT_WIDTH = 200export 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 = 40diff --git a/packages/core/src/editor/bridges/undo.ts b/packages/core/src/editor/bridges/undo.tsindex a495fad7f..ba420d796 100644--- a/packages/core/src/editor/bridges/undo.ts+++ b/packages/core/src/editor/bridges/undo.ts@@ -4,7 +4,15 @@ import type { createUndoActions } from '#core/editor/undo'type SelectionActions = ReturnType<typeof createSelectionActions>type UndoActions = ReturnType<typeof createUndoActions>-export function createUndoBridge(undoActions: UndoActions, selection: SelectionActions) {+/**+ * `flushPending` commits edits still being coalesced, such as a run of arrow keys, so undo right+ * after them undoes the run, not the edit before it.+ */+export function createUndoBridge(+ undoActions: UndoActions,+ selection: SelectionActions,+ flushPending: () => void+) {return {commitMove: undoActions.commitMove,commitMoveWithReparent: undoActions.commitMoveWithReparent,@@ -13,8 +21,14 @@ export function createUndoBridge(undoActions: UndoActions, selection: SelectionAcommitGroupResize: undoActions.commitGroupResize,commitRotation: undoActions.commitRotation,commitNodeUpdate: undoActions.commitNodeUpdate,- undoAction: () => undoActions.undoAction(selection.validateEnteredContainer),- redoAction: () => undoActions.redoAction(selection.validateEnteredContainer),+ undoAction: () => {+ flushPending()+ undoActions.undoAction(selection.validateEnteredContainer)+ },+ redoAction: () => {+ flushPending()+ undoActions.redoAction(selection.validateEnteredContainer)+ },snapshotPage: undoActions.snapshotPage,restorePageFromSnapshot: undoActions.restorePageFromSnapshot,capturePageChange: undoActions.capturePageChange,diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 11241085c..a8cca61c7 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -267,7 +267,7 @@ export function createEditor(options?: EditorOptions) {const clipboardBridge = createClipboardBridge(clipboard, selection)const componentBridge = createComponentBridge(components, selection, structure, pages)const structureBridge = createStructureBridge(structure, selection)- const undoBridge = createUndoBridge(undoActions, selection)+ const undoBridge = createUndoBridge(undoActions, selection, nodes.flushNudge)const lintFixBridge = createLintFixBridge(ctx, nodes, structure, clipboard)function setCanvasKit(ck: CanvasKit, renderer: SkiaRenderer) {diff --git a/packages/core/src/editor/nudge.ts b/packages/core/src/editor/nudge.tsindex 1848329eb..aa18918ca 100644--- a/packages/core/src/editor/nudge.ts+++ b/packages/core/src/editor/nudge.ts@@ -1,3 +1,6 @@+import { isEqual } from 'es-toolkit'++import type { SceneNode } from '@open-pencil/scene-graph'import type { Vector } from '@open-pencil/scene-graph/primitives'import { collectNodePositions, pushPositionUndo } from './history/position'@@ -6,15 +9,80 @@ import type { EditorContext } from './types'const NUDGE_COMMIT_DELAY = 300+/** The flow an arrow key moves a layer along: its row or column, or none. */+function flowParent(ctx: EditorContext, node: SceneNode): SceneNode | null {+ if (node.layoutPositioning === 'ABSOLUTE' || !node.parentId) return null+ const parent = ctx.graph.getNode(node.parentId)+ return parent?.layoutMode === 'HORIZONTAL' || parent?.layoutMode === 'VERTICAL' ? parent : null+}++/**+ * One slot along the flow for an arrow key, as Figma reorders auto layout children: Right and+ * Left in a row (mirrored when it runs right to left), Down and Up in a column, and nothing for+ * the arrows across it. Shift moves one slot too.+ */+function flowStep(parent: SceneNode, dx: number, dy: number): -1 | 0 | 1 {+ const along = parent.layoutMode === 'HORIZONTAL' ? dx : dy+ const visual =+ parent.layoutMode === 'HORIZONTAL' && parent.layoutDirection === 'RTL' ? -along : along+ if (visual === 0) return 0+ return visual > 0 ? 1 : -1+}++/**+ * The flow with each selected layer moved one slot by `step`; one already at the end of the+ * flow, or behind another selected layer that is, stays put.+ */+function steppedFlow(+ flow: readonly string[],+ selected: ReadonlySet<string>,+ step: 1 | -1+): string[] {+ const order = [...flow]+ const indices = step > 0 ? order.map((_, i) => order.length - 1 - i) : order.map((_, i) => i)+ for (const i of indices) {+ const j = i + step+ if (!selected.has(order[i]) || j < 0 || j >= order.length || selected.has(order[j])) continue+ ;[order[i], order[j]] = [order[j], order[i]]+ }+ return order+}+export function createNudgeActions(ctx: EditorContext) {let nudgeOriginals: Map<string, Vector> | null = null+ let reorderOriginals: Map<string, string[]> | null = nulllet nudgeCommitTimer: ReturnType<typeof setTimeout> | null = null+ function applyOrder(parentId: string, order: readonly string[]) {+ order.forEach((id, index) => ctx.graph.reorderChild(id, parentId, index))+ ctx.runLayoutForNode(parentId)+ }++ function commitReorder() {+ if (!reorderOriginals) return+ const originals = reorderOriginals+ reorderOriginals = null+ const finals = new Map(+ [...originals.keys()].map((id) => [id, [...(ctx.graph.getNode(id)?.childIds ?? [])]])+ )+ if ([...originals].every(([id, order]) => isEqual(order, finals.get(id)))) return+ ctx.undo.push({+ label: 'Reorder',+ forward: () => {+ for (const [id, order] of finals) applyOrder(id, order)+ },+ inverse: () => {+ for (const [id, order] of originals) applyOrder(id, order)+ }+ })+ }+function commitNudge() {+ nudgeCommitTimer = null+ commitReorder()if (!nudgeOriginals) returnconst originals = nudgeOriginalsnudgeOriginals = null- nudgeCommitTimer = nullconst finals = collectNodePositions(ctx, originals.keys())const parentIds = [...originals.keys()].flatMap((id) => ctx.graph.getNode(id)?.parentId ?? [])@@ -26,6 +94,41 @@ export function createNudgeActions(ctx: EditorContext) {ctx.requestRender()}+ /** Moves the selected layers in auto layout flows one slot; returns the layers it handled. */+ function reorderInFlows(movable: readonly string[], dx: number, dy: number): Set<string> {+ const byParent = new Map<string, Set<string>>()+ for (const id of movable) {+ const node = ctx.graph.getNode(id)+ const parent = node && flowParent(ctx, node)+ if (!parent) continue+ const selected = byParent.get(parent.id) ?? new Set<string>()+ selected.add(id)+ byParent.set(parent.id, selected)+ }+ const handled = new Set<string>()+ for (const [parentId, selected] of byParent) {+ for (const id of selected) handled.add(id)+ const parent = ctx.graph.getNode(parentId)+ const step = parent ? flowStep(parent, dx, dy) : 0+ if (!parent || step === 0) continue+ const children = ctx.graph.getChildren(parentId)+ const flowIds = children+ .filter((child) => child.layoutPositioning !== 'ABSOLUTE')+ .map((c) => c.id)+ const moved = steppedFlow(flowIds, selected, step)+ if (isEqual(moved, flowIds)) continue+ reorderOriginals ??= new Map()+ if (!reorderOriginals.has(parentId)) reorderOriginals.set(parentId, [...parent.childIds])+ // Layers that ignore the layout keep their places in the stack.+ let next = 0+ const order = children.map((child) =>+ child.layoutPositioning === 'ABSOLUTE' ? child.id : moved[next++]+ )+ applyOrder(parentId, order)+ }+ return handled+ }+function nudgeSelected(dx: number, dy: number) {const ids = [...ctx.state.selectedIds]if (ids.length === 0) return@@ -37,15 +140,18 @@ export function createNudgeActions(ctx: EditorContext) {}if (movable.length === 0) return- if (!nudgeOriginals) {+ const reordered = reorderInFlows(movable, dx, dy)+ const nudged = movable.filter((id) => !reordered.has(id))++ if (nudged.length > 0 && !nudgeOriginals) {nudgeOriginals = new Map()- for (const id of movable) {+ for (const id of nudged) {const node = ctx.graph.getNode(id)if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })}}- for (const id of movable) {+ for (const id of nudged) {const node = ctx.graph.getNode(id)if (!node) continuectx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })diff --git a/packages/core/src/editor/structure/reorder.ts b/packages/core/src/editor/structure/reorder.tsindex 28d4c520d..14c8b3a53 100644--- a/packages/core/src/editor/structure/reorder.ts+++ b/packages/core/src/editor/structure/reorder.ts@@ -84,18 +84,38 @@ export function createStructureReorderActions(ctx: EditorContext) {})}+ /**+ * Puts a frame's children in `childIds`. Only the children it moves need to be editable, so a+ * read-only library layer that keeps its place does not block reordering its siblings.+ */function applyChildOrder(parentId: string, childIds: readonly string[]) {assertNodeEditable(ctx.graph, parentId)- for (const childId of childIds) assertNodeEditable(ctx.graph, childId)const current = ctx.graph.getNode(parentId)?.childIds ?? []+ const moved = childIds.filter((childId, index) => current[index] !== childId)+ for (const childId of moved) assertNodeEditable(ctx.graph, childId)for (const [index, childId] of childIds.entries()) {- if (current[index] === childId) continue+ if (ctx.graph.getNode(parentId)?.childIds[index] === childId) continuectx.graph.insertChildAt(childId, parentId, index)}ctx.runLayoutForNode(parentId)ctx.requestRender()}+ /** Puts a frame's children in `order` as one undo step, laying the frame out once. */+ function setChildOrder(parentId: string, order: readonly string[], label = 'Reorder') {+ const before = ctx.graph.getNode(parentId)?.childIds+ if (!before || order.every((id, index) => id === before[index])) return+ if (!prepareSlotEdits(ctx, [parentId])) return+ const previous = [...before]+ const next = [...order]+ applyChildOrder(parentId, next)+ ctx.undo.push({+ label,+ forward: () => applyChildOrder(parentId, next),+ inverse: () => applyChildOrder(parentId, previous)+ })+ }+function moveSelectionInZOrder(label: string,reorder: (childIds: readonly string[], selectedIds: ReadonlySet<string>) => string[]@@ -181,6 +201,7 @@ export function createStructureReorderActions(ctx: EditorContext) {return {reorderInAutoLayout,+ setChildOrder,reorderChildWithUndo,bringForward,sendBackward,diff --git a/packages/core/tests/editor/nudge.test.ts b/packages/core/tests/editor/nudge.test.tsindex 6b01d1952..496b53aaa 100644--- a/packages/core/tests/editor/nudge.test.ts+++ b/packages/core/tests/editor/nudge.test.ts@@ -122,3 +122,74 @@ describe('nudgeSelected', () => {expect(getNodeOrThrow(editor.graph, rect.id).y).toBe(200)})})++// Orders read from Figma desktop 126 after the same keys on four 60 × 40 layers.+describe('arrow keys in an auto layout flow', () => {+ function flow(layoutMode: 'HORIZONTAL' | 'VERTICAL') {+ const editor = createEditor()+ const parent = editor.graph.createNode('FRAME', editor.state.currentPageId, {+ layoutMode,+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 10+ })+ const [a, b, c, d] = ['A', 'B', 'C', 'D'].map((name) =>+ editor.graph.createNode('RECTANGLE', parent.id, { name, width: 60, height: 40 })+ )+ editor.runLayoutForNode(parent.id)+ const order = () => parent.childIds.map((id) => editor.graph.getNode(id)?.name).join('')+ return { editor, parent, a, b, c, d, order }+ }++ test('move a layer one slot along a row, Shift too, and not across it', () => {+ const { editor, a, b, order } = flow('HORIZONTAL')+ editor.select([b.id])+ editor.nudgeSelected(1, 0)+ expect(order()).toBe('ACBD')+ editor.nudgeSelected(10, 0)+ expect(order()).toBe('ACDB')+ editor.nudgeSelected(0, 1)+ expect(order()).toBe('ACDB')+ editor.nudgeSelected(-1, 0)+ expect(order()).toBe('ACBD')+ editor.select([a.id])+ editor.nudgeSelected(10, 0)+ expect(order()).toBe('CABD')+ editor.dispose()+ })++ test('move a layer along a column with Down and Up', () => {+ const { editor, b, order } = flow('VERTICAL')+ editor.select([b.id])+ editor.nudgeSelected(0, 1)+ expect(order()).toBe('ACBD')+ editor.nudgeSelected(1, 0)+ expect(order()).toBe('ACBD')+ editor.nudgeSelected(0, -1)+ expect(order()).toBe('ABCD')+ editor.dispose()+ })++ test('move each selected layer one slot, and keep one at the end in place', () => {+ const { editor, a, c, order } = flow('HORIZONTAL')+ editor.select([a.id, c.id])+ editor.nudgeSelected(1, 0)+ expect(order()).toBe('BADC')+ editor.nudgeSelected(1, 0)+ expect(order()).toBe('BDAC')+ editor.dispose()+ })++ test('a run of keys is one undo step, even undone straight away', () => {+ const { editor, b, order } = flow('HORIZONTAL')+ editor.select([b.id])+ editor.nudgeSelected(1, 0)+ editor.nudgeSelected(1, 0)+ editor.undoAction()+ expect(order()).toBe('ABCD')+ expect(editor.undo.canUndo).toBe(false)+ editor.redoAction()+ expect(order()).toBe('ACDB')+ editor.dispose()+ })+})diff --git a/packages/core/tests/editor/structure/child-order.test.ts b/packages/core/tests/editor/structure/child-order.test.tsnew file mode 100644index 000000000..982ee28c7--- /dev/null+++ b/packages/core/tests/editor/structure/child-order.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'++describe('setting a frame’s child order', () => {+ test('moves the children in one undo step, past a read-only library layer that stays', () => {+ const editor = createEditor()+ try {+ const { graph } = editor+ const frame = graph.createNode('FRAME', editor.state.currentPageId, { layoutMode: 'HORIZONTAL' })+ const a = graph.createNode('RECTANGLE', frame.id, { name: 'A', width: 40, height: 40 })+ const b = graph.createNode('RECTANGLE', frame.id, { name: 'B', width: 40, height: 40 })+ const remote = graph.createNode('COMPONENT', frame.id, {+ name: 'Remote',+ width: 40,+ height: 40,+ librarySource: {+ identity: { libraryId: 'design-system', assetKey: 'badge', revisionId: 'r1' },+ sourceNodeId: 'source',+ readOnly: true+ }+ })+ const order = () => frame.childIds.map((id) => graph.getNode(id)?.name).join('')+ editor.setChildOrder(frame.id, [b.id, a.id, remote.id])+ expect(order()).toBe('BARemote')+ editor.undoAction()+ expect(order()).toBe('ABRemote')+ editor.redoAction()+ expect(order()).toBe('BARemote')+ expect(() => editor.setChildOrder(frame.id, [remote.id, b.id, a.id])).toThrow()+ } finally {+ editor.dispose()+ }+ })+})diff --git a/packages/vue/src/shared/input/flow-reorder.ts b/packages/vue/src/shared/input/flow-reorder.tsnew file mode 100644index 000000000..59c6184c6--- /dev/null+++ b/packages/vue/src/shared/input/flow-reorder.ts@@ -0,0 +1,159 @@+import type { Editor, MovePlace } from '@open-pencil/core/editor'+import { createSceneGeometry } from '@open-pencil/core/geometry'+import type { SceneNode } from '@open-pencil/scene-graph'+import { resolveNodeLayoutDirection } from '@open-pencil/scene-graph/text-direction'++/**+ * Layers dragged along their own auto layout flow, as one block: the selected layers of one+ * frame in their order, the other layers in its flow, and the slot the block starts in, the+ * number of other layers before the first selected one.+ */+export interface FlowDrag {+ parentId: string+ ids: string[]+ others: string[]+ start: number+}++function layoutDirection(node: SceneNode, editor: Editor): 'LTR' | 'RTL' {+ const parent = node.parentId ? editor.graph.getNode(node.parentId) : null+ return resolveNodeLayoutDirection(node, parent ? layoutDirection(parent, editor) : 'LTR')+}++function inFlow(child: SceneNode) {+ return child.visible && child.layoutPositioning !== 'ABSOLUTE'+}++/**+ * The flows a move drags along, or undefined when a moved layer is not in a row or column that+ * does not wrap, which keeps the cursor-based reorder.+ */+export function collectFlowDrags(+ originals: ReadonlyMap<string, MovePlace>,+ editor: Editor+): FlowDrag[] | undefined {+ const byParent = new Map<string, Set<string>>()+ for (const [id, original] of originals) {+ const node = editor.graph.getNode(id)+ const parent = editor.graph.getNode(original.parentId)+ if (!node || !parent || !inFlow(node)) return undefined+ if (parent.layoutMode !== 'HORIZONTAL' && parent.layoutMode !== 'VERTICAL') return undefined+ if (parent.layoutWrap === 'WRAP') return undefined+ const ids = byParent.get(parent.id) ?? new Set<string>()+ ids.add(id)+ byParent.set(parent.id, ids)+ }+ return [...byParent].map(([parentId, selected]) => {+ const children = editor.graph.getChildren(parentId)+ const flow = children.filter(inFlow)+ const others = flow.filter((child) => !selected.has(child.id)).map((child) => child.id)+ const first = flow.findIndex((child) => selected.has(child.id))+ return {+ parentId,+ ids: children.filter((child) => selected.has(child.id)).map((child) => child.id),+ others,+ start: flow.slice(0, first).filter((child) => !selected.has(child.id)).length+ }+ })+}++/**+ * The slot among the other layers the block is in after a drag of `dx`, `dy`, as Figma reorders+ * auto layout children while they are dragged: the block passes the next layer once its leading+ * edge reaches that layer's centre, laid out with the block in the slot it has reached. That is+ * a gap and half the layer past the layers it has passed, so the slot follows the drag along the+ * flow, in the frame's own axes, wherever the layer was grabbed.+ */+export function flowSlot(flow: FlowDrag, dx: number, dy: number, editor: Editor): number {+ const parent = editor.graph.getNode(flow.parentId)+ if (!parent) return flow.start+ const isRow = parent.layoutMode === 'HORIZONTAL'+ const drag = dragInFrame(flow.parentId, dx, dy, editor)+ const along = isRow ? drag.x : drag.y+ const delta = isRow && layoutDirection(parent, editor) === 'RTL' ? -along : along+ const sizes = flow.others.map((id) => {+ const node = editor.graph.getNode(id)+ return node ? (isRow ? node.width : node.height) : 0+ })+ const gap = parent.itemSpacing+ let slot = flow.start+ let passed = 0+ if (delta > 0) {+ while (slot < sizes.length && delta > passed + gap + sizes[slot] / 2) {+ passed += sizes[slot] + gap+ slot+++ }+ } else {+ while (slot > 0 && -delta > passed + gap + sizes[slot - 1] / 2) {+ passed += sizes[slot - 1] + gap+ slot--+ }+ }+ return slot+}++/**+ * The frame's children with the block in `slot`: the other children keep their order, layers+ * that ignore the layout or are hidden included, and the block goes before the other layer in+ * that slot.+ */+export function flowOrder(flow: FlowDrag, slot: number, editor: Editor): string[] {+ const parent = editor.graph.getNode(flow.parentId)+ if (!parent) return []+ const selected = new Set(flow.ids)+ const rest = parent.childIds.filter((id) => !selected.has(id))+ const before = flow.others.at(slot)+ const last = flow.others.at(-1)+ let at = rest.length+ if (before !== undefined) at = rest.indexOf(before)+ else if (last !== undefined) at = rest.indexOf(last) + 1+ return [...rest.slice(0, at), ...flow.ids, ...rest.slice(at)]+}++/** The scene's geometry as drawn, with a rotation in progress. */+function geometryOf(editor: Editor) {+ return createSceneGeometry(editor.graph, editor.state.rotationPreview)+}++/** A drag of `dx`, `dy` on the canvas in a frame's own axes, as a turned frame sees it. */+function dragInFrame(parentId: string, dx: number, dy: number, editor: Editor) {+ const parent = editor.graph.getNode(parentId)+ if (!parent) return { x: dx, y: dy }+ const geometry = geometryOf(editor)+ const origin = geometry.toLocal(parent, { x: 0, y: 0 })+ const moved = geometry.toLocal(parent, { x: dx, y: dy })+ return origin && moved ? { x: moved.x - origin.x, y: moved.y - origin.y } : { x: dx, y: dy }+}++/**+ * The selected layers' box in their frame's own space, after a drag of `dx`, `dy` on the canvas:+ * the bounds of their corners, so a turned or flipped layer, or a turned frame, counts with what+ * it covers along the frame's own axes.+ */+export function flowBlockBounds(flow: FlowDrag, dx: number, dy: number, editor: Editor) {+ const parent = editor.graph.getNode(flow.parentId)+ const geometry = geometryOf(editor)+ let left = Infinity+ let top = Infinity+ let right = -Infinity+ let bottom = -Infinity+ for (const id of flow.ids) {+ const node = editor.graph.getNode(id)+ if (!node || !parent) continue+ for (const corner of [+ { x: 0, y: 0 },+ { x: node.width, y: 0 },+ { x: node.width, y: node.height },+ { x: 0, y: node.height }+ ]) {+ const world = geometry.toWorld(node, corner)+ const local = geometry.toLocal(parent, { x: world.x + dx, y: world.y + dy })+ if (!local) continue+ left = Math.min(left, local.x)+ right = Math.max(right, local.x)+ top = Math.min(top, local.y)+ bottom = Math.max(bottom, local.y)+ }+ }+ return { left, top, right, bottom }+}diff --git a/packages/vue/src/shared/input/move.ts b/packages/vue/src/shared/input/move.tsindex b39c718bc..11e8da489 100644--- a/packages/vue/src/shared/input/move.ts+++ b/packages/vue/src/shared/input/move.ts@@ -3,6 +3,7 @@ import type { SceneNode } from '@open-pencil/scene-graph'import {autoLayoutInsertIndex,computeAutoLayoutIndicator,+ computeIndicatorPosition,computeAutoLayoutIndicatorForFrame} from '#vue/shared/input/auto-layout'import {@@ -11,33 +12,94 @@ import {} from '#vue/shared/input/drag-threshold'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'+import { flowBlockBounds, flowOrder, flowSlot, type FlowDrag } from '#vue/shared/input/flow-reorder'import { applyMoveSnap } from '#vue/shared/input/move-snap'import type { DragMove } from '#vue/shared/input/types'const AUTO_LAYOUT_REORDER_CLICK_SLOP = 3-const AUTO_LAYOUT_CROSS_AXIS_DRAG_TOLERANCE = 96+/**+ * How far past its auto layout frame's edge a dragged layer's near edge goes before the layer+ * leaves the frame, in canvas units, as measured in Figma desktop 126: 5 across the flow, and+ * 13 to 20 along it depending on the layer's size.+ */+const AUTO_LAYOUT_LEAVE_MARGIN_ACROSS = 5+const AUTO_LAYOUT_LEAVE_MARGIN_ALONG = 15export const MOVE_DRAG_START_THRESHOLD_PX = POINTER_DRAG_START_THRESHOLD_PX-function isInsideAutoLayoutDragBounds(parentId: string, cx: number, cy: number, editor: Editor) {+/** Whether layers whose box in the frame's own space is `bounds` stay close enough to its flow. */+function staysInAutoLayout(+ parentId: string,+ bounds: { left: number; top: number; right: number; bottom: number },+ editor: Editor+) {const parent = editor.graph.getNode(parentId)if (!parent) return false- const abs = editor.graph.getAbsolutePosition(parentId)+ // How far the layers' near edge is past the frame's edge on each of the frame's own axes, with+ // `bounds` in the frame's space; negative while they overlap.+ const pastX = Math.max(-bounds.right, bounds.left - parent.width)+ const pastY = Math.max(-bounds.bottom, bounds.top - parent.height)+ const isRow = parent.layoutMode === 'HORIZONTAL'+ const along = isRow ? pastX : pastY+ const across = isRow ? pastY : pastX+ return along <= AUTO_LAYOUT_LEAVE_MARGIN_ALONG && across <= AUTO_LAYOUT_LEAVE_MARGIN_ACROSS+}++/**+ * Keeps dragged layers in their flows while they stay close, as Figma does: each flow's block+ * takes the slot the drag has reached, which the indicator shows for the first flow that moved.+ * Returns false once a flow's layers leave it, and the move goes on as a free drag.+ */+function dragAlongFlows(d: DragMove, flows: FlowDrag[], dx: number, dy: number, editor: Editor) {+ if (d.ignoreAutoLayout) return false+ if (+ !flows.every((flow) =>+ staysInAutoLayout(flow.parentId, flowBlockBounds(flow, dx, dy, editor), editor)+ )+ )+ return false+ d.flowSlots = flows.map((flow) => flowSlot(flow, dx, dy, editor))+ const moved = flows.findIndex((flow, i) => d.flowSlots?.[i] !== flow.start)+ const flow = moved === -1 ? undefined : flows[moved]+ const parent = flow && editor.graph.getNode(flow.parentId)+ if (!flow || !parent) {+ editor.setLayoutInsertIndicator(null)+ return true+ }const isRow = parent.layoutMode === 'HORIZONTAL'- const mainStart = isRow ? abs.x : abs.y- const mainSize = isRow ? parent.width : parent.height- const crossStart = isRow ? abs.y : abs.x- const crossSize = isRow ? parent.height : parent.width- const main = isRow ? cx : cy- const cross = isRow ? cy : cx- return (- main >= mainStart - AUTO_LAYOUT_BREAK_THRESHOLD &&- main <= mainStart + mainSize + AUTO_LAYOUT_BREAK_THRESHOLD &&- cross >= crossStart - AUTO_LAYOUT_CROSS_AXIS_DRAG_TOLERANCE &&- cross <= crossStart + crossSize + AUTO_LAYOUT_CROSS_AXIS_DRAG_TOLERANCE+ const others = flow.others.flatMap((id) => editor.graph.getNode(id) ?? [])+ const parentAbs = editor.graph.getAbsolutePosition(parent.id)+ const position = computeIndicatorPosition(+ others,+ d.flowSlots[moved],+ parent,+ parentAbs,+ isRow,+ editor)+ editor.setLayoutInsertIndicator({+ parentId: parent.id,+ index: d.flowSlots[moved],+ x: isRow ? position : parentAbs.x + parent.paddingLeft,+ y: isRow ? parentAbs.y + parent.paddingTop : position,+ length: isRow+ ? parent.height - parent.paddingTop - parent.paddingBottom+ : parent.width - parent.paddingLeft - parent.paddingRight,+ direction: isRow ? 'VERTICAL' : 'HORIZONTAL'+ })+ return true+}++/** Puts each flow's block in the slot the drag reached, as one undo step. */+function dropAlongFlows(d: DragMove, flows: FlowDrag[], editor: Editor) {+ editor.undo.runBatch('Reorder', () => {+ for (const [i, flow] of flows.entries()) {+ const slot = d.flowSlots?.[i] ?? flow.start+ if (slot === flow.start) continue+ editor.setChildOrder(flow.parentId, flowOrder(flow, slot, editor))+ }+ })}export function detectAutoLayoutParent(editor: Editor): string | undefined {@@ -88,6 +150,37 @@ function isPastDragStartThreshold(d: DragMove, sx: number, sy: number) {return isPastPointerDragThreshold(d.startScreenX, d.startScreenY, sx, sy)}+/**+ * Keeps a move in the auto layout the layers started in while they stay close to it; returns+ * whether it did. Once they leave, the move goes on as a free drag.+ */+function keepsOwnAutoLayout(+ d: DragMove,+ dx: number,+ dy: number,+ cx: number,+ cy: number,+ editor: Editor+): boolean {+ if (d.flows) {+ if (dragAlongFlows(d, d.flows, dx, dy, editor)) return true+ d.flowSlots = undefined+ } else if (d.autoLayoutParentId && !d.ignoreAutoLayout) {+ // A wrapped flow, which still reorders by the cursor.+ const [id] = d.originals.keys()+ const block = { parentId: d.autoLayoutParentId, ids: id ? [id] : [], others: [], start: 0 }+ if (staysInAutoLayout(d.autoLayoutParentId, flowBlockBounds(block, dx, dy, editor), editor)) {+ computeAutoLayoutIndicator(d, cx, cy, editor)+ return true+ }+ } else if (!d.autoLayoutParentId) {+ return false+ }+ d.brokeFromAutoLayout = true+ editor.setLayoutInsertIndicator(null)+ return false+}+export function handleMoveMove(d: DragMove,cx: number,@@ -108,14 +201,7 @@ export function handleMoveMove(let { dx, dy } = lockToAxis(cx - d.startX, cy - d.startY, modifiers.shiftKey === true)- if (d.autoLayoutParentId && !d.brokeFromAutoLayout) {- if (!d.ignoreAutoLayout && isInsideAutoLayoutDragBounds(d.autoLayoutParentId, cx, cy, editor)) {- computeAutoLayoutIndicator(d, cx, cy, editor)- return- }- d.brokeFromAutoLayout = true- editor.setLayoutInsertIndicator(null)- }+ if (!d.brokeFromAutoLayout && keepsOwnAutoLayout(d, dx, dy, cx, cy, editor)) returnconst moving = new Set(d.originals.keys())const dropTarget = d.keepParents ? null : findMoveDropTarget(cx, cy, editor, moving)@@ -249,6 +335,13 @@ export function handleMoveUp(d: DragMove, editor: Editor) {editor.setLayoutInsertIndicator(null)editor.setSnapGuides([])+ // Slots exist only once the drag started, so a reached slot is a reorder however short the drag.+ if (d.flows && d.flowSlots && !d.brokeFromAutoLayout) {+ dropAlongFlows(d, d.flows, editor)+ editor.setDropTarget(null)+ return+ }+if (indicator) {if (getMoveDistance(d) < AUTO_LAYOUT_REORDER_CLICK_SLOP) {editor.setDropTarget(null)diff --git a/packages/vue/src/shared/input/select/move.ts b/packages/vue/src/shared/input/select/move.tsindex a30ec507b..a640af5a4 100644--- a/packages/vue/src/shared/input/select/move.ts+++ b/packages/vue/src/shared/input/select/move.ts@@ -2,6 +2,7 @@ import type { Editor, MovePlace } from '@open-pencil/core/editor'import type { SceneNode } from '@open-pencil/scene-graph'import { duplicateAndDrag } from '#vue/shared/input/duplicate-drag'+import { collectFlowDrags } from '#vue/shared/input/flow-reorder'import type { DragState } from '#vue/shared/input/types'function isLockedInTree(id: string, editor: Editor) {@@ -118,6 +119,7 @@ export function createSelectionMoveDrag(startScreenY: sy,dragStarted: false,originals,- autoLayoutParentId: detectDragAutoLayoutParent(originals, editor)+ autoLayoutParentId: detectDragAutoLayoutParent(originals, editor),+ flows: collectFlowDrags(originals, editor)}}diff --git a/packages/vue/src/shared/input/types.ts b/packages/vue/src/shared/input/types.tsindex 9ba69516a..d2f8a34de 100644--- a/packages/vue/src/shared/input/types.ts+++ b/packages/vue/src/shared/input/types.ts@@ -11,6 +11,7 @@ import type {import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'import type { ResizeSnapshot } from '@open-pencil/scene-graph/resize'+import type { FlowDrag } from '#vue/shared/input/flow-reorder'import type { LayerSizing } from '#vue/shared/input/resize/sizing'export type HandlePosition = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'@@ -50,6 +51,10 @@ export interface DragMove {duplicatedPreviousSelection?: Set<string>autoLayoutParentId?: stringbrokeFromAutoLayout?: boolean+ /** The auto layout flows the moved layers are dragged along, as blocks. */+ flows?: FlowDrag[]+ /** Each flow's slot for the block where the drag has reached. */+ flowSlots?: number[]/** 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. */diff --git a/packages/vue/tests/shared/input/move/auto-layout-leave.test.ts b/packages/vue/tests/shared/input/move/auto-layout-leave.test.tsnew file mode 100644index 000000000..3c1ca2bd2--- /dev/null+++ b/packages/vue/tests/shared/input/move/auto-layout-leave.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from 'bun:test'++import { getWorldMatrix } from '@open-pencil/scene-graph/coordinate'+import Matrix from '@open-pencil/scene-graph/matrix'++import { createMoveHarness } from './harness'++// Margins from Figma desktop 126: a child dragged by its centre out of a flow of 60 × 40 layers+// with padding and gap 10 leaves once its near edge is 5 past the frame across the flow, and+// about 15 along it.+function flow(layoutMode: 'HORIZONTAL' | 'VERTICAL', width = 60) {+ const harness = createMoveHarness()+ const { editor, page, node } = harness+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }+ const frame = node('FRAME', page, {+ layoutMode,+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 10,+ paddingLeft: 10,+ paddingRight: 10,+ paddingTop: 10,+ paddingBottom: 10+ })+ const [, b] = [60, width, 60].map((w, i) =>+ node('RECTANGLE', frame.id, { name: 'ABC'[i], width: w, height: 40 })+ )+ editor.runLayoutForNode(frame.id)+ const center: [number, number] = [b.x + b.width / 2, b.y + b.height / 2]+ /** Drags B by its centre until its edge is `past` beyond the frame's right or bottom edge. */+ const dragPast = (side: 'right' | 'bottom', past: number) => {+ const to: [number, number] =+ side === 'right'+ ? [frame.width + past + b.width / 2, center[1]]+ : [center[0], frame.height + past + b.height / 2]+ harness.drag([b.id], center, to)+ return harness.parentOf(b.id) === frame.id+ }+ return { dragPast }+}++describe('dragging a layer out of an auto layout flow', () => {+ for (const [layoutMode, across, along] of [+ ['HORIZONTAL', 'bottom', 'right'],+ ['VERTICAL', 'right', 'bottom']+ ] as const) {+ test(`${layoutMode}: across the flow it leaves once its edge is past the frame by more than 5`, () => {+ expect(flow(layoutMode).dragPast(across, 5)).toBe(true)+ expect(flow(layoutMode).dragPast(across, 5.5)).toBe(false)+ })++ test(`${layoutMode}: along the flow it leaves once its edge is past the frame by more than 15`, () => {+ expect(flow(layoutMode).dragPast(along, 15)).toBe(true)+ expect(flow(layoutMode).dragPast(along, 15.5)).toBe(false)+ })+ }+})++test('a turned row measures the drag along its own axes', () => {+ for (const [axis, stays] of [+ ['along', true],+ ['across', false]+ ] as const) {+ const harness = createMoveHarness()+ const { editor, page, node } = harness+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }+ const frame = node('FRAME', page, {+ x: 300,+ y: 300,+ rotation: 90,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 10,+ paddingLeft: 10,+ paddingRight: 10,+ paddingTop: 10,+ paddingBottom: 10+ })+ const [, b] = [0, 1, 2].map((i) =>+ node('RECTANGLE', frame.id, { name: 'ABC'[i], width: 60, height: 40 })+ )+ editor.runLayoutForNode(frame.id)+ const world = getWorldMatrix(frame, editor.graph)+ const toCanvas = (x: number, y: number) => Matrix.mapPoint(world, { x, y })+ const start = toCanvas(b.x + 30, b.y + 20)+ // 10 past the frame's end along the row, or past its bottom across it, in the frame's own space.+ const end =+ axis === 'along'+ ? toCanvas(frame.width + 10 + 30, b.y + 20)+ : toCanvas(b.x + 30, frame.height + 10 + 20)+ harness.drag([b.id], [start.x, start.y], [end.x, end.y])+ expect(harness.parentOf(b.id) === frame.id).toBe(stays)+ }+})diff --git a/packages/vue/tests/shared/input/move/auto-layout-reorder.test.ts b/packages/vue/tests/shared/input/move/auto-layout-reorder.test.tsnew file mode 100644index 000000000..ee27ac969--- /dev/null+++ b/packages/vue/tests/shared/input/move/auto-layout-reorder.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from 'bun:test'++import { createMoveHarness } from './harness'++// Orders from Figma desktop 126, which reorders auto layout children while they are dragged:+// rows of four 60 × 40 layers with padding and gap 10, dragged along the row.+function rows(count = 1) {+ const harness = createMoveHarness()+ const { editor, page, node } = harness+ editor.state.snappingPreferences = { geometry: false, objects: false, pixelGrid: false }+ const frames = Array.from({ length: count }, (_, r) => {+ const frame = node('FRAME', page, {+ y: r * 100,+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ itemSpacing: 10,+ paddingLeft: 10,+ paddingRight: 10,+ paddingTop: 10,+ paddingBottom: 10+ })+ for (const name of 'ABCD') node('RECTANGLE', frame.id, { name: `${name}${r}`, width: 60, height: 40 })+ editor.runLayoutForNode(frame.id)+ return frame+ })+ const named = (name: string) => {+ const found = [...editor.graph.getAllNodes()].find((n) => n.name === name)+ if (!found) throw new Error(`no ${name}`)+ return found+ }+ const order = () =>+ frames.map((f) => f.childIds.map((id) => editor.graph.getNode(id)?.name).join(' ')).join(' | ')+ /** Drags the selection by `dx` along the row from the centre of `grab`. */+ const dragBy = (picks: string[], grab: string, dx: number) => {+ const at = editor.graph.getAbsolutePosition(named(grab).id)+ const from: [number, number] = [at.x + 30, at.y + 20]+ harness.drag(+ picks.map((p) => named(p).id),+ from,+ [from[0] + dx, from[1]]+ )+ }+ return { editor, order, dragBy }+}++describe('dragging along an auto layout row', () => {+ test('a layer passes the next once its leading edge reaches that layer’s centre', () => {+ for (const [dx, expected] of [+ [40, 'A0 B0 C0 D0'],+ [45, 'A0 C0 B0 D0'],+ [110, 'A0 C0 B0 D0'],+ [115, 'A0 C0 D0 B0']+ ] as const) {+ const { order, dragBy } = rows()+ dragBy(['B0'], 'B0', dx)+ expect(order()).toBe(expected)+ }+ })++ test('several selected layers move as one block, wherever they are grabbed', () => {+ for (const [picks, grab, dx, expected] of [+ [['A0', 'C0'], 'A0', 45, 'B0 A0 C0 D0'],+ [['A0', 'C0'], 'C0', 115, 'B0 D0 A0 C0'],+ [['B0', 'D0'], 'B0', -45, 'B0 D0 A0 C0'],+ [['A0', 'D0'], 'A0', 100, 'B0 A0 D0 C0'],+ // The block cannot pass the start, so the layers keep their order.+ [['A0', 'D0'], 'D0', -150, 'A0 B0 C0 D0']+ ] as const) {+ const { editor, order, dragBy } = rows()+ dragBy([...picks], grab, dx)+ expect(order()).toBe(expected)+ editor.undoAction()+ expect(order()).toBe('A0 B0 C0 D0')+ }+ })++ test('layers selected in two rows each move along their own row', () => {+ const { order, dragBy } = rows(2)+ dragBy(['B0', 'B1'], 'B0', 120)+ expect(order()).toBe('A0 C0 D0 B0 | A1 C1 D1 B1')+ })+})diff --git a/src/constants.ts b/src/constants.tsindex 5b29e71b3..a2c89c2cd 100644--- a/src/constants.ts+++ b/src/constants.ts@@ -132,7 +132,6 @@ export const ROTATION_SNAP_DEGREES = 15export const CORNER_ROTATE_ZONE = 16export const DEFAULT_TEXT_WIDTH = 200export const DEFAULT_TEXT_HEIGHT = 24-export const AUTO_LAYOUT_BREAK_THRESHOLD = 8export const HANDLE_HIT_RADIUS = 6export const ACP_PERMISSION_TIMEOUT_MS = 60_000diff --git a/tests/e2e/editor/auto-layout/drag.spec.ts b/tests/e2e/editor/auto-layout/drag.spec.tsindex f8951f5e3..b69ad4a03 100644--- a/tests/e2e/editor/auto-layout/drag.spec.ts+++ b/tests/e2e/editor/auto-layout/drag.spec.ts@@ -66,13 +66,14 @@ test('dragging selected nested instance content reorders its auto-layout item',height: 24})+ store.runLayoutForNode(frame.id)store.select([secondText.id])store.requestRender()return { frame: frame.id, first: first.id, second: second.id, secondText: secondText.id }})await canvas.waitForRender()- await canvas.drag(370, 228, 230, 228, 12)+ await canvas.drag(310, 140, 170, 140, 12)await canvas.waitForRender()const childIds = await page.evaluate((frameId) => {@@ -135,6 +136,7 @@ test('auto-layout drag does not show an insert indicator before order changes',height: 24})+ store.runLayoutForNode(frame.id)store.select([secondText.id])store.requestRender()return { frame: frame.id, first: first.id, second: second.id }@@ -143,9 +145,9 @@ test('auto-layout drag does not show an insert indicator before order changes',const box = await canvas.canvas.boundingBox()if (!box) throw new Error('Canvas has no bounding box')- await page.mouse.move(box.x + 370, box.y + 228)+ await page.mouse.move(box.x + 310, box.y + 140)await page.mouse.down()- await page.mouse.move(box.x + 365, box.y + 228, { steps: 3 })+ await page.mouse.move(box.x + 305, box.y + 140, { steps: 3 })await canvas.waitForRender()const indicator = await page.evaluate(() => {