AI-native design editor. Open-source Figma alternative.
fix: everyday editing parity with Figma for layers, undo, pen and duplicates (#1146)
rcoenen2bbd9b6b8c07
diff --git a/changes/1146/fixed.md b/changes/1146/fixed.mdnew file mode 100644index 000000000..d72562807--- /dev/null+++ b/changes/1146/fixed.md@@ -0,0 +1,5 @@+- Dragging a layer down the layers panel drops it where the line shows, not one slot lower. Moving a layer into a frame or group from the panel keeps it where it's drawn on the canvas, and undo puts it back.+- Hiding, locking, renaming and moving layers to another page can be undone. Hiding or locking several layers at once is a single undo step.+- A duplicate is stacked directly above its original, rather than on top of everything.+- Redoing a pen path brings back its points, fill and stroke instead of an empty vector. Escape keeps the path drawn so far, as the pen tool guide says. The distance for closing a path no longer changes with zoom.+- Editing a vector's points no longer leaks memory on every redraw.diff --git a/packages/core/src/canvas/node-edit-overlay.ts b/packages/core/src/canvas/node-edit-overlay.tsindex 4ba6b3222..05488ac30 100644--- a/packages/core/src/canvas/node-edit-overlay.ts+++ b/packages/core/src/canvas/node-edit-overlay.ts@@ -139,12 +139,6 @@ function drawLiveShape(if (!inverse) returnconst localNetwork = transformVectorNetwork(inverse, { vertices, segments, regions })- const invalidatePathCaches = () => {- r.vectorPathCache.delete(nodeId)- r.fillGeometryCache.delete(nodeId)- r.strokeGeometryCache.delete(nodeId)- }-// Temporarily patch the node so renderShapeUncached uses our live network;// fills draw from fillGeometry blobs, so rebuild those from the live network.// Clear strokeGeometry so strokes use the live vector network instead of@@ -160,7 +154,7 @@ function drawLiveShape(node.vectorNetwork = localNetworknode.fillGeometry = regenerateFillGeometry(localNetwork, origFillGeometry)node.strokeGeometry = []- invalidatePathCaches()+ r.invalidateVectorPath(nodeId)canvas.translate(r.panX, r.panY)canvas.scale(r.zoom, r.zoom)canvas.concat(world)@@ -172,7 +166,7 @@ function drawLiveShape(node.vectorNetwork = origNetworknode.fillGeometry = origFillGeometrynode.strokeGeometry = origStrokeGeometry- invalidatePathCaches()+ r.invalidateVectorPath(nodeId)}}diff --git a/packages/core/src/editor/clipboard.ts b/packages/core/src/editor/clipboard.tsindex 397ed06d0..9e4b5f2d5 100644--- a/packages/core/src/editor/clipboard.ts+++ b/packages/core/src/editor/clipboard.ts@@ -55,12 +55,19 @@ export function createClipboardActions(ctx: EditorContext) {function duplicateSelected(selectedNodes: SceneNode[]) {const prevSelection = new Set(ctx.state.selectedIds)const selectedSet = new Set(selectedNodes.map((n) => n.id))- const topLevel = selectedNodes.filter((n) => !n.parentId || !selectedSet.has(n.parentId))+ const stackIndex = (node: SceneNode) =>+ ctx.graph.getNode(node.parentId ?? ctx.state.currentPageId)?.childIds.indexOf(node.id) ?? -1+ // Copy in stacking order, not selection order, so the copies stack as their originals do.+ const topLevel = selectedNodes+ .filter((n) => !n.parentId || !selectedSet.has(n.parentId))+ .sort((a, b) => stackIndex(a) - stackIndex(b))const parents = topLevel.map((node) => node.parentId ?? ctx.state.currentPageId)if (!prepareSlotEdits(ctx, parents)) returnconst newRootIds: string[] = []const allSnapshots = new Map<string, SceneNode>()+ // The topmost layer each parent's copies came from.+ const topSource = new Map<string, number>()const placed: Rect[] = []for (const node of topLevel) {@@ -69,14 +76,32 @@ export function createClipboardActions(ctx: EditorContext) {topLevel.length === 1? placementActions.duplicatePosition(node, placed): { x: node.x, y: node.y }+ const sourceIndex = ctx.graph.getNode(parentId)?.childIds.indexOf(node.id) ?? -1const clone = duplicateNode(ctx, node, parentId, position)if (!clone) continue+ topSource.set(parentId, Math.max(topSource.get(parentId) ?? -1, sourceIndex))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)}+ // Figma stacks the copies directly above the topmost layer they copy, in their own order,+ // not on top of everything in the parent.+ const stacked = new Map<string, number>()+ const stacking = newRootIds.flatMap((id) => {+ const parentId = ctx.graph.getNode(id)?.parentId+ const top = parentId ? topSource.get(parentId) : undefined+ if (!parentId || top === undefined || top < 0) return []+ const offset = stacked.get(parentId) ?? 0+ stacked.set(parentId, offset + 1)+ return [{ id, parentId, index: top + 1 + offset }]+ })+ const stack = () => {+ for (const { id, parentId, index } of stacking) ctx.graph.insertChildAt(id, parentId, index)+ }+ stack()+if (newRootIds.length > 0) {ctx.setSelectedIds(new Set(newRootIds))ctx.undo.push({@@ -88,6 +113,7 @@ export function createClipboardActions(ctx: EditorContext) {const parentId = snapshot.parentId ?? ctx.state.currentPageIdrestoreSubtree(ctx.graph, snapshot, parentId, allSnapshots)}+ stack()ctx.setSelectedIds(new Set(newRootIds))},inverse: () => {diff --git a/packages/core/src/editor/shapes.ts b/packages/core/src/editor/shapes.tsindex d30a6b3ec..8f7bca384 100644--- a/packages/core/src/editor/shapes.ts+++ b/packages/core/src/editor/shapes.ts@@ -50,13 +50,17 @@ export function createShapeActions(ctx: EditorContext) {}const node = ctx.graph.createNode(type, pid, overrides)const id = node.id- const snapshot = { ...node }+ // Callers finish the layer after this returns (the pen writes its path, fills and strokes),+ // so redo restores the layer as it was when undone, not as first created.+ let snapshot = { ...node }ctx.undo.push({label: `Create ${type.toLowerCase()}`,forward: () => {ctx.graph.createNode(snapshot.type, pid, snapshot)},inverse: () => {+ const current = ctx.graph.getNode(id)+ if (current) snapshot = { ...current }ctx.graph.deleteNode(id)const next = new Set(ctx.state.selectedIds)next.delete(id)diff --git a/packages/core/src/editor/structure.ts b/packages/core/src/editor/structure.tsindex 184ec1469..dae4fcb49 100644--- a/packages/core/src/editor/structure.ts+++ b/packages/core/src/editor/structure.ts@@ -1,4 +1,6 @@-import { createsComponentCycle, type SceneNode } from '@open-pencil/scene-graph'+import { pick } from 'es-toolkit'++import { createsComponentCycle, TRANSFORM_FIELDS, type SceneNode } from '@open-pencil/scene-graph'import { acceptingParent, acceptsChildren, prepareSlotEdits } from '#core/editor/components/slots'import { fitEnclosingGroupsWithUndo } from '#core/editor/structure/group-bounds'@@ -105,11 +107,36 @@ export function createStructureActions(ctx: EditorContext) {function moveToPage(pageId: string) {const targetPage = ctx.graph.getNode(pageId)if (targetPage?.type !== 'CANVAS') return- const ids = [...ctx.state.selectedIds]- for (const id of ids) {- ctx.graph.reparentNode(id, pageId)+ // Where each layer was, read before any of them moves: put back in this order, each lands at+ // its own index again.+ const origins = [...ctx.state.selectedIds]+ .flatMap((id) => {+ const node = ctx.graph.getNode(id)+ const parent = node?.parentId ? ctx.graph.getNode(node.parentId) : undefined+ if (!node || !parent || parent.id === pageId) return []+ const index = parent.childIds.indexOf(id)+ return [{ id, parentId: parent.id, index, place: pick(node, TRANSFORM_FIELDS) }]+ })+ .sort((a, b) => a.index - b.index)+ if (origins.length === 0) return+ const parentIds = new Set(origins.map((origin) => origin.parentId))+ const move = () => {+ for (const { id } of origins) ctx.graph.reparentNode(id, pageId)+ for (const parentId of parentIds) ctx.runLayoutForNode(parentId)}+ move()ctx.setSelectedIds(new Set())+ ctx.undo.push({+ label: 'Move to page',+ forward: move,+ inverse: () => {+ for (const { id, parentId, index, place } of origins) {+ ctx.graph.reorderChild(id, parentId, index)+ ctx.graph.updateNode(id, place)+ }+ for (const parentId of parentIds) ctx.runLayoutForNode(parentId)+ }+ })}function selectedNodes(): SceneNode[] {@@ -143,8 +170,15 @@ export function createStructureActions(ctx: EditorContext) {function renameNode(id: string, name: string) {const node = ctx.graph.getNode(id)if (!node) return- const trimmedName = name.trim()- ctx.graph.updateNode(id, { name: trimmedName || defaultNodeName(node.type) })+ const previous = node.name+ const next = name.trim() || defaultNodeName(node.type)+ if (next === previous) return+ ctx.graph.updateNode(id, { name: next })+ ctx.undo.push({+ label: 'Rename',+ forward: () => ctx.graph.updateNode(id, { name: next }),+ inverse: () => ctx.graph.updateNode(id, { name: previous })+ })}return {diff --git a/packages/core/src/editor/structure/reorder.ts b/packages/core/src/editor/structure/reorder.tsindex 14c8b3a53..5b8eddb48 100644--- a/packages/core/src/editor/structure/reorder.ts+++ b/packages/core/src/editor/structure/reorder.ts@@ -1,3 +1,7 @@+import { pick } from 'es-toolkit'++import { createsComponentCycle, TRANSFORM_FIELDS } from '@open-pencil/scene-graph'+import { assertNodeEditable } from '#core/editor/capabilities'import { prepareSlotEdits } from '#core/editor/components/slots'import type { EditorContext } from '#core/editor/types'@@ -53,33 +57,39 @@ export function createStructureReorderActions(ctx: EditorContext) {})}+ /**+ * Moves a layer to `insertIndex` among `newParentId`'s children, counted without the layer. A+ * new parent keeps the layer where it is drawn, as moving it into a frame on the canvas does, and+ * is refused when it would put a component inside itself.+ */function reorderChildWithUndo(nodeId: string, newParentId: string, insertIndex: number) {assertNodeEditable(ctx.graph, nodeId)assertNodeEditable(ctx.graph, newParentId)const node = ctx.graph.getNode(nodeId)if (!node) returnconst origParentId = node.parentId ?? ctx.state.currentPageId+ const reparents = origParentId !== newParentId+ if (reparents && createsComponentCycle(ctx.graph, nodeId, newParentId)) returnif (!prepareSlotEdits(ctx, [origParentId, newParentId])) returnconst origIndex = ctx.graph.getNode(origParentId)?.childIds.indexOf(nodeId) ?? 0- const origX = node.x- const origY = node.y+ const origPlace = pick(node, TRANSFORM_FIELDS)- ctx.graph.reorderChild(nodeId, newParentId, insertIndex)- ctx.runLayoutForNode(newParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)+ const place = () => {+ if (reparents) ctx.graph.reparentNode(nodeId, newParentId)+ ctx.graph.reorderChild(nodeId, newParentId, insertIndex)+ ctx.runLayoutForNode(newParentId)+ if (reparents) ctx.runLayoutForNode(origParentId)+ }+ place()ctx.undo.push({label: 'Reorder',- forward: () => {- ctx.graph.reorderChild(nodeId, newParentId, insertIndex)- ctx.runLayoutForNode(newParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(origParentId)- },+ forward: place,inverse: () => {ctx.graph.reorderChild(nodeId, origParentId, origIndex)- ctx.graph.updateNode(nodeId, { x: origX, y: origY })+ ctx.graph.updateNode(nodeId, origPlace)ctx.runLayoutForNode(origParentId)- if (origParentId !== newParentId) ctx.runLayoutForNode(newParentId)+ if (reparents) ctx.runLayoutForNode(newParentId)}})}diff --git a/packages/core/src/editor/structure/state.ts b/packages/core/src/editor/structure/state.tsindex ef743730a..c596dcad0 100644--- a/packages/core/src/editor/structure/state.ts+++ b/packages/core/src/editor/structure/state.ts@@ -1,4 +1,8 @@-import { findInstanceAncestor, setInstanceOverride } from '@open-pencil/scene-graph'+import {+ cloneInstanceOverrideState,+ findInstanceAncestor,+ setInstanceOverride+} from '@open-pencil/scene-graph'import { assertNodeEditable } from '#core/editor/capabilities'import {@@ -16,9 +20,30 @@ export function createStructureStateActions(ctx: EditorContext) {// The property takes the value even where the layer already shows it, so the two agree.if (owner && bindsVisibility(node) && applyBoundVisibilityEdit(ctx, id, visible)) returnif (node.visible === visible) return- if (owner) setInstanceOverride(owner.instanceOverrides, owner.id, id, 'visible', true)- ctx.graph.updateNode(id, { visible })- if (node.parentId) ctx.runLayoutForNode(node.parentId)+ const previousOverrides = owner && cloneInstanceOverrideState(owner.instanceOverrides)+ const show = (shown: boolean) => {+ ctx.graph.updateNode(id, { visible: shown })+ const parentId = ctx.graph.getNode(id)?.parentId+ if (parentId) ctx.runLayoutForNode(parentId)+ }+ const forward = () => {+ const instance = findInstanceAncestor(ctx.graph, id)+ if (instance)+ setInstanceOverride(instance.instanceOverrides, instance.id, id, 'visible', true)+ show(visible)+ }+ forward()+ ctx.undo.push({+ label: visible ? 'Show layer' : 'Hide layer',+ forward,+ inverse: () => {+ if (owner && previousOverrides)+ ctx.graph.updateNode(owner.id, {+ instanceOverrides: cloneInstanceOverrideState(previousOverrides)+ })+ show(!visible)+ }+ })}function toggleNodeVisibility(id: string) {@@ -31,7 +56,13 @@ export function createStructureStateActions(ctx: EditorContext) {assertNodeEditable(ctx.graph, id)const node = ctx.graph.getNode(id)if (!node) return- ctx.graph.updateNode(id, { locked: !node.locked })+ const locked = !node.locked+ ctx.graph.updateNode(id, { locked })+ ctx.undo.push({+ label: locked ? 'Lock layer' : 'Unlock layer',+ forward: () => ctx.graph.updateNode(id, { locked }),+ inverse: () => ctx.graph.updateNode(id, { locked: !locked })+ })}function toggleVisibility() {@@ -42,12 +73,16 @@ export function createStructureStateActions(ctx: EditorContext) {const node = ctx.graph.getNode(id)return node ? [[id, !node.visible] as const] : []})- for (const [id, visible] of targets) setNodeVisibility(id, visible)+ ctx.undo.runBatch('Toggle visibility', () => {+ for (const [id, visible] of targets) setNodeVisibility(id, visible)+ })}function toggleLock() {for (const id of ctx.state.selectedIds) assertNodeEditable(ctx.graph, id)- for (const id of ctx.state.selectedIds) toggleNodeLock(id)+ ctx.undo.runBatch('Toggle lock', () => {+ for (const id of ctx.state.selectedIds) toggleNodeLock(id)+ })}return { toggleNodeVisibility, toggleNodeLock, toggleVisibility, toggleLock }diff --git a/packages/core/tests/editor/clipboard/duplicate-order.test.ts b/packages/core/tests/editor/clipboard/duplicate-order.test.tsnew file mode 100644index 000000000..e7cdbe15e--- /dev/null+++ b/packages/core/tests/editor/clipboard/duplicate-order.test.ts@@ -0,0 +1,55 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { createEditor, type Editor } from '@open-pencil/core/editor'++let editor: Editor++afterEach(() => editor.dispose())++/** Three rectangles on the page, bottom to top. */+function setup() {+ editor = createEditor()+ const page = editor.state.currentPageId+ const [a, b, c] = [0, 1, 2].map(+ (i) =>+ editor.graph.createNode('RECTANGLE', page, { x: i * 100, y: 0, width: 50, height: 50 }).id+ )+ return { page, a, b, c }+}++function node(id: string) {+ const found = editor.graph.getNode(id)+ if (!found) throw new Error('missing layer')+ return found+}++describe('duplicating', () => {+ test('puts the copy directly above its original, also on redo', () => {+ const { page, a, b, c } = setup()+ editor.select([a])+ editor.duplicateSelected()+ const [copy] = editor.state.selectedIds+ expect(node(page).childIds).toEqual([a, copy, b, c])+ editor.undo.undo()+ editor.undo.redo()+ expect(node(page).childIds).toEqual([a, copy, b, c])+ })++ test('stacks several copies above the topmost original, in their order', () => {+ const { page, a, b, c } = setup()+ editor.select([a, b])+ editor.duplicateSelected()+ const copies = node(page).childIds.filter((id) => ![a, b, c].includes(id))+ expect(node(page).childIds).toEqual([a, b, ...copies, c])+ expect(copies.map((id) => node(id).x)).toEqual([0, 100])+ })++ test('stacks the copies like their originals when selected top to bottom', () => {+ const { page, a, b, c } = setup()+ editor.select([c, a])+ editor.duplicateSelected()+ const copies = node(page).childIds.filter((id) => ![a, b, c].includes(id))+ expect(node(page).childIds).toEqual([a, b, c, ...copies])+ expect(copies.map((id) => node(id).x)).toEqual([0, 200])+ })+})diff --git a/packages/core/tests/editor/structure/layer-state-undo.test.ts b/packages/core/tests/editor/structure/layer-state-undo.test.tsnew file mode 100644index 000000000..ad4538b6b--- /dev/null+++ b/packages/core/tests/editor/structure/layer-state-undo.test.ts@@ -0,0 +1,68 @@+import { afterEach, describe, expect, test } from 'bun:test'++import { createEditor, type Editor } from '@open-pencil/core/editor'++let editor: Editor++afterEach(() => editor.dispose())++/** Three rectangles on the page, bottom to top. */+function setup() {+ editor = createEditor()+ const page = editor.state.currentPageId+ const [a, b, c] = [0, 1, 2].map(+ (i) =>+ editor.graph.createNode('RECTANGLE', page, { x: i * 100, y: 0, width: 50, height: 50 }).id+ )+ return { page, a, b, c }+}++function node(id: string) {+ const found = editor.graph.getNode(id)+ if (!found) throw new Error('missing layer')+ return found+}++describe('layer state undo', () => {+ test('hiding the selection undoes in one step and redoes', () => {+ const { a, b } = setup()+ editor.select([a, b])+ editor.toggleVisibility()+ expect([node(a).visible, node(b).visible]).toEqual([false, false])+ editor.undo.undo()+ expect([node(a).visible, node(b).visible]).toEqual([true, true])+ editor.undo.redo()+ expect([node(a).visible, node(b).visible]).toEqual([false, false])+ })++ test('locking from the layers panel undoes', () => {+ const { a } = setup()+ editor.toggleNodeLock(a)+ expect(node(a).locked).toBe(true)+ editor.undo.undo()+ expect(node(a).locked).toBe(false)+ })++ test('renaming undoes, and an unchanged name records nothing', () => {+ const { a } = setup()+ const original = node(a).name+ editor.renameNode(a, 'Card')+ editor.renameNode(a, ' Card ')+ editor.undo.undo()+ expect(node(a).name).toBe(original)+ expect(editor.undo.canUndo).toBe(false)+ })++ test('moving to another page undoes back to each layer’s place in the stack', () => {+ const { page, a, b, c } = setup()+ const other = editor.addPage('Other')+ editor.select([a, c])+ editor.moveToPage(other)+ expect(node(page).childIds).toEqual([b])+ editor.undo.undo()+ expect(node(page).childIds).toEqual([a, b, c])+ expect(node(c).x).toBe(200)+ editor.undo.redo()+ expect(node(other).childIds).toEqual([a, c])+ })+})diff --git a/packages/core/tests/editor/structure/panel-reorder.test.ts b/packages/core/tests/editor/structure/panel-reorder.test.tsnew file mode 100644index 000000000..b3fe274b2--- /dev/null+++ b/packages/core/tests/editor/structure/panel-reorder.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import { getAxisAlignedWorldBounds } from '@open-pencil/scene-graph/coordinate'++describe('moving a layer from the layers panel', () => {+ test('into a frame keeps it where it is drawn, and one undo puts it back', () => {+ const editor = createEditor()+ try {+ const page = editor.state.currentPageId+ const frame = editor.graph.createNode('FRAME', page, {+ x: 200,+ y: 100,+ width: 300,+ height: 300,+ rotation: 30+ })+ const layer = editor.graph.createNode('RECTANGLE', page, {+ x: 10,+ y: 20,+ width: 40,+ height: 40+ })+ const drawn = getAxisAlignedWorldBounds(layer, editor.graph)++ editor.reorderChildWithUndo(layer.id, frame.id, 0)+ const moved = editor.graph.getNode(layer.id)+ if (!moved) throw new Error('missing layer')+ expect(moved.parentId).toBe(frame.id)+ const after = getAxisAlignedWorldBounds(moved, editor.graph)+ expect(after.x).toBeCloseTo(drawn.x, 6)+ expect(after.y).toBeCloseTo(drawn.y, 6)++ editor.undo.undo()+ expect(editor.graph.getNode(layer.id)?.parentId).toBe(page)+ expect(editor.graph.getNode(layer.id)?.x).toBe(10)+ expect(editor.graph.getNode(layer.id)?.rotation).toBe(0)+ } finally {+ editor.dispose()+ }+ })++ test('is refused when it would make two components contain each other', () => {+ const editor = createEditor()+ try {+ const page = editor.state.currentPageId+ const a = editor.graph.createNode('COMPONENT', page, { width: 100, height: 100 })+ const b = editor.graph.createNode('COMPONENT', page, { x: 200, width: 100, height: 100 })+ editor.graph.createInstance(b.id, a.id)+ const instanceOfA = editor.graph.createInstance(a.id, page, { x: 400 })+ if (!instanceOfA) throw new Error('expected an instance')++ editor.reorderChildWithUndo(instanceOfA.id, b.id, 0)+ expect(editor.graph.getNode(instanceOfA.id)?.parentId).toBe(page)+ } finally {+ editor.dispose()+ }+ })+})diff --git a/packages/core/tests/editor/undo/create-shape.test.ts b/packages/core/tests/editor/undo/create-shape.test.tsindex 338a2349a..46a0d216d 100644--- a/packages/core/tests/editor/undo/create-shape.test.ts+++ b/packages/core/tests/editor/undo/create-shape.test.ts@@ -63,3 +63,26 @@ describe('create shape undo/redo', () => {expect(getNodeOrThrow(editor.graph, id).x).toBe(200)})})++describe('pen path undo/redo', () => {+ test('redo brings back the path, fills and strokes, not an empty vector', () => {+ const editor = createEditor()+ editor.setTool('PEN')+ editor.penAddVertex(0, 0)+ editor.penAddVertex(100, 0)+ editor.penAddVertex(100, 50)+ editor.penCommit(false)+ const id = [...editor.state.selectedIds][0]+ const drawn = getNodeOrThrow(editor.graph, id)+ expect(drawn.vectorNetwork?.segments).toHaveLength(2)++ editor.undo.undo()+ expect(editor.graph.getNode(id)).toBeUndefined()++ editor.undo.redo()+ const restored = getNodeOrThrow(editor.graph, id)+ expect(restored.vectorNetwork).toEqual(drawn.vectorNetwork)+ expect(restored.strokes).toEqual(drawn.strokes)+ expect(restored.fills).toEqual(drawn.fills)+ })+})diff --git a/packages/docs/es/user-guide/pen-tool.md b/packages/docs/es/user-guide/pen-tool.mdindex 56eb2f07a..4bd55d98d 100644--- a/packages/docs/es/user-guide/pen-tool.md+++ b/packages/docs/es/user-guide/pen-tool.md@@ -19,7 +19,7 @@ Cada punto amplía la ruta. Una línea de vista previa conecta el último punto## Cerrar o terminar-Haz clic en el primer punto para cerrar la ruta. Pulsa <kbd>Enter</kbd> para terminarla abierta o <kbd>Escape</kbd> para cancelar el dibujo actual.+Haz clic en el primer punto para cerrar la ruta. Pulsa <kbd>Enter</kbd> o <kbd>Escape</kbd> para terminarla abierta.## Continuar una rutadiff --git a/packages/docs/fr/user-guide/pen-tool.md b/packages/docs/fr/user-guide/pen-tool.mdindex 618b066ae..e7da4a456 100644--- a/packages/docs/fr/user-guide/pen-tool.md+++ b/packages/docs/fr/user-guide/pen-tool.md@@ -19,7 +19,7 @@ Chaque point prolonge le tracé. Une ligne d’aperçu relie le dernier point au## Fermer ou terminer-Cliquez sur le premier point pour fermer le tracé. Appuyez sur <kbd>Enter</kbd> pour le terminer ouvert ou sur <kbd>Escape</kbd> pour annuler le dessin actuel.+Cliquez sur le premier point pour fermer le tracé. Appuyez sur <kbd>Enter</kbd> ou <kbd>Escape</kbd> pour le terminer ouvert.## Continuer un tracédiff --git a/packages/docs/it/user-guide/pen-tool.md b/packages/docs/it/user-guide/pen-tool.mdindex 070fd0d2a..9c03a2c2e 100644--- a/packages/docs/it/user-guide/pen-tool.md+++ b/packages/docs/it/user-guide/pen-tool.md@@ -17,7 +17,7 @@ Ogni punto estende il tracciato. Una linea di anteprima collega l’ultimo punto## Chiudere o terminare-Fai clic sul primo punto per chiudere il tracciato. Premi <kbd>Enter</kbd> per terminarlo aperto o <kbd>Escape</kbd> per annullare il disegno corrente.+Fai clic sul primo punto per chiudere il tracciato. Premi <kbd>Enter</kbd> o <kbd>Escape</kbd> per terminarlo aperto.## Continuare un tracciatodiff --git a/packages/vue/src/canvas/pen/input.ts b/packages/vue/src/canvas/pen/input.tsindex 32ca493d5..079ac9a2a 100644--- a/packages/vue/src/canvas/pen/input.ts+++ b/packages/vue/src/canvas/pen/input.ts@@ -2,6 +2,7 @@ import type { Ref } from 'vue'import { PEN_CLOSE_THRESHOLD } from '@open-pencil/core/constants'import type { Editor } from '@open-pencil/core/editor'+import type { Vector } from '@open-pencil/scene-graph/primitives'import { createPenDrag, handlePenDragMove } from '#vue/canvas/pen/drag'import type { DragState } from '#vue/shared/input/types'@@ -9,6 +10,12 @@ import { handlePenNodeEditDown } from '#vue/shared/input/vector'type SetDrag = (drag: DragState) => void+/** Whether a canvas point lies within the close threshold, in screen pixels, of the path's start. */+function nearFirstVertex(cx: number, cy: number, first: Vector, editor: Editor) {+ const zoom = editor.renderer?.zoom ?? 1+ return Math.hypot(cx - first.x, cy - first.y) < PEN_CLOSE_THRESHOLD / zoom+}+export function startPenInput(e: MouseEvent,cx: number,@@ -29,8 +36,7 @@ export function startPenInput(const penState = editor.state.penStateif (penState && penState.vertices.length > 2) {const first = penState.vertices[0]- const dist = Math.hypot(cx - first.x, cy - first.y)- if (dist < PEN_CLOSE_THRESHOLD) {+ if (nearFirstVertex(cx, cy, first, editor)) {editor.penSetPendingClose(true)editor.penSetClosingToFirst(true)setDrag(createPenDrag(first.x, first.y))@@ -53,8 +59,7 @@ export function updatePenHover(cx: number, cy: number, editor: Editor): booleanconst first = editor.state.penState.vertices[0]if (editor.state.penState.vertices.length > 2) {- const dist = Math.hypot(cx - first.x, cy - first.y)- editor.penSetClosingToFirst(dist < PEN_CLOSE_THRESHOLD)+ editor.penSetClosingToFirst(nearFirstVertex(cx, cy, first, editor))}editor.requestRepaint()return truediff --git a/packages/vue/src/primitives/LayerTree/model.ts b/packages/vue/src/primitives/LayerTree/model.tsindex f8fffe496..55db7891e 100644--- a/packages/vue/src/primitives/LayerTree/model.ts+++ b/packages/vue/src/primitives/LayerTree/model.ts@@ -127,3 +127,12 @@ export function layerSelectionForTarget(}return next}++/**+ * Where a dropped layer goes among its new siblings: `index` in `childIds` counted without the+ * layer, so one dragged from earlier in the same parent lands one slot sooner.+ */+export function dropIndex(childIds: readonly string[], sourceId: string, index: number): number {+ const sourceIndex = childIds.indexOf(sourceId)+ return sourceIndex !== -1 && sourceIndex < index ? index - 1 : index+}diff --git a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts b/packages/vue/src/primitives/LayerTree/useLayerDrag.tsindex e6aa39638..612950172 100644--- a/packages/vue/src/primitives/LayerTree/useLayerDrag.ts+++ b/packages/vue/src/primitives/LayerTree/useLayerDrag.ts@@ -14,6 +14,7 @@ import { onScopeDispose, ref, watchEffect, type Ref } from 'vue'import type { Editor } from '@open-pencil/core/editor'import type { LayerDragInstruction } from '#vue/primitives/LayerTree/context'+import { dropIndex } from '#vue/primitives/LayerTree/model'interface DragItem {id: string@@ -125,11 +126,12 @@ export function useLayerDrag(const targetParent = editor.graph.getNode(targetParentId)if (!targetParent) returnconst targetIndex = targetParent.childIds.indexOf(targetId)+ const at = (index: number) => dropIndex(targetParent.childIds, sourceId, index)if (inst.type === 'reorder-above') {- editor.reorderChildWithUndo(sourceId, targetParentId, targetIndex)+ editor.reorderChildWithUndo(sourceId, targetParentId, at(targetIndex))} else if (inst.type === 'reorder-below') {- editor.reorderChildWithUndo(sourceId, targetParentId, targetIndex + 1)+ editor.reorderChildWithUndo(sourceId, targetParentId, at(targetIndex + 1))} else {const container = editor.graph.getNode(targetId)if (!container || !editor.graph.isContainer(targetId)) returndiff --git a/packages/vue/tests/primitives/LayerTree/model.test.ts b/packages/vue/tests/primitives/LayerTree/model.test.tsindex c80c81d9a..8375307b7 100644--- a/packages/vue/tests/primitives/LayerTree/model.test.ts+++ b/packages/vue/tests/primitives/LayerTree/model.test.ts@@ -3,6 +3,8 @@ import { describe, expect, test } from 'bun:test'import { SceneGraph, withIcon } from '@open-pencil/scene-graph'import { buildLayerTreeModel, patchLayerNode } from '@open-pencil/vue'+import { dropIndex } from '#vue/primitives/LayerTree/model'+describe('layer tree model', () => {test('marks icon frames, so rows can show them as icons', () => {const graph = new SceneGraph()@@ -39,3 +41,15 @@ describe('layer tree model', () => {expect(row.modeIds).toEqual([dark])})})++describe('drop index', () => {+ test('a layer dragged down past a later sibling lands right after it', () => {+ // Dropping A below B in [A, B, C]: B's index + 1 is 2, counted without A it is 1.+ expect(dropIndex(['A', 'B', 'C'], 'A', 2)).toBe(1)+ })++ test('a layer dragged up, or from another parent, keeps the target index', () => {+ expect(dropIndex(['A', 'B', 'C'], 'C', 1)).toBe(1)+ expect(dropIndex(['A', 'B', 'C'], 'X', 2)).toBe(2)+ })+})diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsindex 49630db33..b5f93d922 100644--- a/src/app/shell/keyboard/actions.ts+++ b/src/app/shell/keyboard/actions.ts@@ -76,8 +76,10 @@ export function createKeyboardActions({store.exitNodeEditMode(true)return}+ // Figma keeps the path drawn so far; a lone point has nothing to keep.if (store.state.penState) {- store.penCancel()+ if (store.state.penState.vertices.length >= 2) store.penCommit(false)+ else store.penCancel()return}if (store.state.enteredContainerId) {