From cb8fd98c4fb0cd6abcfc7ad15c42c9e328617f7b Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 19:01:19 +0700 Subject: [PATCH 1/6] =?UTF-8?q?feat(canvas):=20cut=20frames=20and=20layers?= =?UTF-8?q?=20with=20=E2=8C=98X=20and=20the=20context=20menus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cut copies the selection the way ⌘C does, then removes it the way ⌫ does, as one undo step. Nothing is removed unless the copy landed; locked frames and layers are copied but stay; viewers cannot cut. A held ⌘X is ignored, so it never takes the element and then the frame under it. Closes #333 Co-Authored-By: Claude Opus 5.5 --- src/components/ElementContextMenu.tsx | 15 +++ src/components/FrameContextMenu.tsx | 14 +++ src/lib/elementClipboard.ts | 39 +++++++- src/lib/i18n/en/common.ts | 1 + src/lib/i18n/en/stage.ts | 1 + src/lib/i18n/pt-BR/common.ts | 1 + src/lib/i18n/pt-BR/stage.ts | 1 + src/pages/CanvasPage.tsx | 38 ++++---- tests/cutSelection.test.ts | 121 ++++++++++++++++++++++++ tests/elementContextMenuBrowser.test.ts | 3 +- 10 files changed, 212 insertions(+), 22 deletions(-) create mode 100644 tests/cutSelection.test.ts diff --git a/src/components/ElementContextMenu.tsx b/src/components/ElementContextMenu.tsx index b0b09edc0..ff2d7ae7c 100644 --- a/src/components/ElementContextMenu.tsx +++ b/src/components/ElementContextMenu.tsx @@ -9,6 +9,7 @@ import { hasFrameClip, pasteFrameCentered } from '../lib/frameClipboard' import { deleteLayer, duplicateLayer, setLayerHidden, setLayerLocked, shiftLayer } from '../lib/layerEdits' import { buildLayerTree, elementHtml, findLayer, isElementHidden, isElementLocked, layerName } from '../lib/layers' import { MOD_KEY } from '../lib/keys' +import { canEditOpenCanvas, useStore } from '../lib/store' import { useT } from '../lib/i18n' import { ContextMenuContent, ContextMenuItem, ContextMenuSeparator } from './ui/context-menu' import { MenuHint } from './ui/menu' @@ -79,6 +80,7 @@ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementI /* a copied standalone shape is a frame on the clipboard: its paste lands a second element on the canvas, as ⌘V does, not a layer in this frame */ const frameClip = hasFrameClip() + const canEdit = useStore(canEditOpenCanvas) return ( <> {MOD_KEY}C + { + if (!selector) return + writeCanvasClipboard(() => { + if (!copyPicked(frame, [selector])) return false + deleteLayer(frame, selector) + }) + }} + > + {t('common.cut')} + {MOD_KEY}X + { diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index 08300b30b..d2d270802 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -110,6 +110,20 @@ export function FrameContextMenu({ {!readOnly && ( <> + { + const frames = groupFrames() + if (!frames.length) return + writeCanvasClipboard(() => { + copyFrames(frames) + deleteSelection() + }) + }} + > + {groupSize > 1 ? t('stage.cutFrames', { count: groupSize }) : t('common.cut')} + {MOD_KEY}X + {onRename && ( (renameRequested.current = true)}> {t('panels.layersRename')} diff --git a/src/lib/elementClipboard.ts b/src/lib/elementClipboard.ts index 3a22f640f..8d2630b47 100644 --- a/src/lib/elementClipboard.ts +++ b/src/lib/elementClipboard.ts @@ -1,8 +1,9 @@ import type { Frame } from '../../shared/types' import { elementsHtml, insertElements, isElementLocked } from './layers' -import { isStandalonePick, saveFrameHtml } from './layerEdits' +import { deleteSelection, isStandalonePick, saveFrameHtml } from './layerEdits' import { copyFrames } from './frameClipboard' -import { useStore } from './store' +import { canEditOpenCanvas, pickedSelectors, useStore } from './store' +import { writeCanvasClipboard } from './canvasClipboard' import { ELEMENT_CLIP_KEY, ELEMENT_CLIP_STYLE_KEY, FRAME_CLIP_KEY } from './clipboardKeys' import { carriedCss, newScope, renameInCss, SCOPE_ATTR, withCarriedCss } from './styleCarry' @@ -22,6 +23,40 @@ export function copyPicked(frame: Frame, selectors: string[]): boolean { return copyLayers(frame, selectors) } +/** What ⌘C copies now: the picked elements, else the selected frames; + * null when nothing is selected. */ +function selectionCopy(): (() => boolean | void) | null { + const state = useStore.getState() + const picked = state.selectedElement + if (picked) { + const frame = state.canvas?.frames.find((f) => f.id === picked.frameId) + if (!frame) return null + const selectors = pickedSelectors(state) + return () => copyPicked(frame, selectors) + } + const frames = state.canvas?.frames.filter((f) => state.selectedIds.includes(f.id)) ?? [] + return frames.length ? () => copyFrames(frames) : null +} + +/** ⌘C: put the selection on the clipboard. False when there was nothing to copy. */ +export function copySelection(data?: DataTransfer): boolean { + const copy = selectionCopy() + return !!copy && writeCanvasClipboard(copy, data) +} + +/** ⌘X: copy the selection, then remove it the way ⌫ does (one undo step; + * locked frames and layers stay, copied). Editors only, and nothing is + * removed unless the copy landed. */ +export function cutSelection(data?: DataTransfer): boolean { + if (!canEditOpenCanvas(useStore.getState())) return false + const copy = selectionCopy() + if (!copy) return false + return writeCanvasClipboard(() => { + if (copy() === false) return false + deleteSelection() + }, data) +} + /** Copy the elements in document order; a paste lands them together. */ export function copyLayers(frame: Frame, selectors: string[]): boolean { const raw = elementsHtml(frame.html, selectors) diff --git a/src/lib/i18n/en/common.ts b/src/lib/i18n/en/common.ts index cc0674ce7..6ac080686 100644 --- a/src/lib/i18n/en/common.ts +++ b/src/lib/i18n/en/common.ts @@ -5,6 +5,7 @@ export const common = { delete: 'Delete', close: 'Close', copy: 'Copy', + cut: 'Cut', copied: 'Copied', back: 'Back', loading: 'Loading…', diff --git a/src/lib/i18n/en/stage.ts b/src/lib/i18n/en/stage.ts index f5e008d5e..26cf2d7d8 100644 --- a/src/lib/i18n/en/stage.ts +++ b/src/lib/i18n/en/stage.ts @@ -76,6 +76,7 @@ export const stage = { deleteElement: 'Delete element', deleteFrame: 'Delete frame', copyFrames: 'Copy {count} frames', + cutFrames: 'Cut {count} frames', duplicateFrames: 'Duplicate {count} frames', showFrames: 'Show {count} frames', hideFrames: 'Hide {count} frames', diff --git a/src/lib/i18n/pt-BR/common.ts b/src/lib/i18n/pt-BR/common.ts index a40eff00c..3d4a56e0c 100644 --- a/src/lib/i18n/pt-BR/common.ts +++ b/src/lib/i18n/pt-BR/common.ts @@ -6,6 +6,7 @@ export const common: Catalog['common'] = { delete: 'Excluir', close: 'Fechar', copy: 'Copiar', + cut: 'Recortar', copied: 'Copiado', back: 'Voltar', loading: 'Carregando…', diff --git a/src/lib/i18n/pt-BR/stage.ts b/src/lib/i18n/pt-BR/stage.ts index b7a881078..94aeb0787 100644 --- a/src/lib/i18n/pt-BR/stage.ts +++ b/src/lib/i18n/pt-BR/stage.ts @@ -76,6 +76,7 @@ export const stage: Catalog['stage'] = { deleteElement: 'Excluir elemento', deleteFrame: 'Excluir frame', copyFrames: 'Copiar {count} frames', + cutFrames: 'Recortar {count} frames', duplicateFrames: 'Duplicar {count} frames', showFrames: 'Mostrar {count} frames', hideFrames: 'Ocultar {count} frames', diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index 4c4e7afd6..e678fa6f1 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -62,7 +62,6 @@ import { importSources } from '../components/importSourceList' import { PresentMode } from '../components/PresentMode' import { getIdentity, setName } from '../lib/identity' import { - copyFrames, dropFiles, duplicateFrames, hasFrameClip, @@ -82,8 +81,8 @@ import { formatSelectionText, } from '../lib/layerEdits' import type { TextFormatCommand } from '../lib/richText' -import { copyPicked, hasElementClip, pasteLayer } from '../lib/elementClipboard' -import { isCanvasClipboard, writeCanvasClipboard } from '../lib/canvasClipboard' +import { copySelection, cutSelection, hasElementClip, pasteLayer } from '../lib/elementClipboard' +import { isCanvasClipboard } from '../lib/canvasClipboard' import { authClient } from '../lib/auth' import { avatarUrl } from '../../shared/avatar' import { posthog } from '../lib/posthog' @@ -519,25 +518,22 @@ export function CanvasPage({ return () => window.removeEventListener('keydown', onKey) }, [canvasId, guest, hideUiActive, presenting]) // eslint-disable-line react-hooks/exhaustive-deps - /* Native copy/paste events let us write the selection's token and read + /* Native copy/cut/paste events let us write the selection's token and read clipboard images without asking for clipboard-read permission. */ useEffect(() => { + /* a ClipboardEvent carries no repeat flag, so the keydown behind it is + remembered: a held ⌘X must not cut the element and then the frame + under it, as a held ⌫ must not delete them */ + let held = false + const onKeyDown = (e: KeyboardEvent) => void (held = e.repeat) + const ours = (e: ClipboardEvent) => + !isTypingTarget(e.target) && !window.getSelection()?.toString() && !!e.clipboardData function onCopy(e: ClipboardEvent) { - if (isTypingTarget(e.target) || window.getSelection()?.toString() || !e.clipboardData) return - const state = useStore.getState() - const picked = state.selectedElement - const frame = state.canvas?.frames.find((f) => f.id === picked?.frameId) - let copy: () => boolean | void - if (picked) { - if (!frame) return - const selectors = pickedSelectors(state) - copy = () => copyPicked(frame, selectors) - } else { - const frames = state.canvas?.frames.filter((f) => state.selectedIds.includes(f.id)) ?? [] - if (!frames.length) return - copy = () => copyFrames(frames) - } - if (writeCanvasClipboard(copy, e.clipboardData)) e.preventDefault() + if (ours(e) && copySelection(e.clipboardData!)) e.preventDefault() + } + function onCut(e: ClipboardEvent) { + if (!ours(e)) return + if (held || cutSelection(e.clipboardData!)) e.preventDefault() } function onPaste(e: ClipboardEvent) { if (isTypingTarget(e.target)) return @@ -571,10 +567,14 @@ export function CanvasPage({ pasteFrameCentered(canvasId) } } + window.addEventListener('keydown', onKeyDown, true) window.addEventListener('copy', onCopy) + window.addEventListener('cut', onCut) window.addEventListener('paste', onPaste) return () => { + window.removeEventListener('keydown', onKeyDown, true) window.removeEventListener('copy', onCopy) + window.removeEventListener('cut', onCut) window.removeEventListener('paste', onPaste) } }, [canvasId]) diff --git a/tests/cutSelection.test.ts b/tests/cutSelection.test.ts new file mode 100644 index 000000000..7d655f907 --- /dev/null +++ b/tests/cutSelection.test.ts @@ -0,0 +1,121 @@ +// @vitest-environment happy-dom +import { beforeEach, describe, expect, it, vi } from 'vitest' +import type { Canvas, Frame } from '../shared/types' + +vi.mock('../src/lib/posthog', () => ({ posthog: { capture: vi.fn() } })) +vi.mock('../src/lib/api', async (importOriginal) => ({ + ...(await importOriginal()), + api: { createFrame: vi.fn(), updateFrame: vi.fn(), deleteFrame: vi.fn(), getCanvas: vi.fn() }, +})) +const { api } = await import('../src/lib/api') +const { useStore } = await import('../src/lib/store') +const { clearHistory, undo } = await import('../src/lib/history') +const { hasFrameClip } = await import('../src/lib/frameClipboard') +const { hasElementClip, cutSelection } = await import('../src/lib/elementClipboard') +const { isCanvasClipboard } = await import('../src/lib/canvasClipboard') + +const frame = (id: string, extra: Partial = {}): Frame => ({ + id, + canvasId: 'c', + pageId: 'p', + name: id, + x: 0, + y: 0, + width: 100, + height: 100, + html: `

${id}

keep`, + createdAt: 0, + updatedAt: 0, + updatedBy: 'Me', + ...extra, +}) + +function clipboardData() { + const store = new Map() + return { + setData: (type: string, value: string) => void store.set(type, value), + getData: (type: string) => store.get(type) ?? '', + } as unknown as DataTransfer +} + +let db: Map + +function open(frames: Frame[], role: 'edit' | 'view' = 'edit') { + db = new Map(frames.map((f) => [f.id, f])) + const s = useStore.getState() + s.setCanvas({ id: 'c', name: 'T', frames, pages: [{ id: 'p', name: 'P' }], role } as unknown as Canvas) +} + +beforeEach(() => { + vi.resetAllMocks() + clearHistory() + localStorage.clear() + useStore.getState().select(null) + vi.mocked(api.deleteFrame).mockImplementation(async (id) => void db.delete(id)) + let n = 0 + vi.mocked(api.createFrame).mockImplementation(async (canvasId, input) => { + const made = { ...frame(`restored-${++n}`), ...input, canvasId } as Frame + db.set(made.id, made) + return made + }) + vi.mocked(api.updateFrame).mockImplementation(async (id, patch) => { + const next = { ...db.get(id)!, ...patch } as Frame + db.set(id, next) + return next + }) +}) + +describe('cut', () => { + it('puts the selected frames on the clipboard and removes them as one undo step', async () => { + open([frame('a'), frame('b'), frame('c')]) + useStore.getState().selectMany(['a', 'b']) + const data = clipboardData() + + expect(cutSelection(data)).toBe(true) + + expect(isCanvasClipboard(data)).toBe(true) + expect(hasFrameClip()).toBe(true) + await vi.waitFor(() => expect([...db.keys()]).toEqual(['c'])) + await undo() + await vi.waitFor(() => expect(db.size).toBe(3)) + }) + + it('keeps a locked frame while still copying it', async () => { + open([frame('a', { locked: true })]) + useStore.getState().select('a') + + expect(cutSelection(clipboardData())).toBe(true) + + expect(hasFrameClip()).toBe(true) + expect(api.deleteFrame).not.toHaveBeenCalled() + }) + + it('cuts a picked element out of its frame, not the frame', async () => { + open([frame('a')]) + useStore.getState().select('a') + useStore.getState().pickElement({ frameId: 'a', selector: 'body > p:nth-of-type(1)' }) + + expect(cutSelection(clipboardData())).toBe(true) + + expect(hasElementClip()).toBe(true) + expect(api.deleteFrame).not.toHaveBeenCalled() + await vi.waitFor(() => expect(db.get('a')?.html).not.toContain('

a

')) + expect(db.get('a')?.html).toContain('keep') + }) + + it('leaves a viewer’s selection alone', () => { + open([frame('a')], 'view') + useStore.getState().select('a') + + expect(cutSelection(clipboardData())).toBe(false) + + expect(hasFrameClip()).toBe(false) + expect(api.deleteFrame).not.toHaveBeenCalled() + }) + + it('does nothing with nothing selected', () => { + open([frame('a')]) + expect(cutSelection(clipboardData())).toBe(false) + expect(api.deleteFrame).not.toHaveBeenCalled() + }) +}) diff --git a/tests/elementContextMenuBrowser.test.ts b/tests/elementContextMenuBrowser.test.ts index 82a17aed9..1b5da491f 100644 --- a/tests/elementContextMenuBrowser.test.ts +++ b/tests/elementContextMenuBrowser.test.ts @@ -220,6 +220,7 @@ describe.skipIf(!findBrowserPath())('frame and element context menus', () => { await rightClick('#text') expect(await items()).toEqual([ 'Copy', + 'Cut', 'Paste', 'Duplicate', 'Hide', @@ -276,7 +277,7 @@ describe.skipIf(!findBrowserPath())('frame and element context menus', () => { it('does not open the frame or background menu in empty frame space', async () => { await page.mouse.click(500, 440, { button: 'right' }) await page.waitForFunction(() => document.querySelector('[role="menuitem"]')?.textContent?.startsWith('Copy')) - expect(await items()).toEqual(['Copy', 'Paste']) + expect(await items()).toEqual(['Copy', 'Cut', 'Paste']) expect(await page.evaluate(() => window.contextMenuHarness.selection())).toBeNull() }) From 6babe5eb813cf66dda796ab34f191a8bc6779cdf Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 19:33:40 +0700 Subject: [PATCH 2/6] test(canvas): cut every selected frame from the frame menu Co-Authored-By: Claude Opus 5.5 --- tests/elementContextMenuBrowser.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/elementContextMenuBrowser.test.ts b/tests/elementContextMenuBrowser.test.ts index 1b5da491f..4baff8a5d 100644 --- a/tests/elementContextMenuBrowser.test.ts +++ b/tests/elementContextMenuBrowser.test.ts @@ -92,7 +92,7 @@ describe.skipIf(!findBrowserPath())('frame and element context menus', () => { await page.setRequestInterception(true) page.on('request', async (request) => { const pathname = new URL(request.url()).pathname - if (pathname === '/api/frames/f') { + if (pathname === '/api/frames/f' || pathname === '/api/frames/other') { if (request.method() === 'PATCH') saved = { ...saved, ...JSON.parse(request.postData()!) } if (request.method() === 'DELETE') deletedFrames++ await request.respond({ status: 200, contentType: 'application/json', body: JSON.stringify(saved) }) @@ -369,6 +369,18 @@ describe.skipIf(!findBrowserPath())('frame and element context menus', () => { expect(deletedFrames).toBe(0) }) + it('cuts every selected frame from a title', async () => { + await page.evaluate((frame) => { + window.contextMenuHarness.seed([frame, { ...frame, id: 'other', x: 600 }]) + window.contextMenuHarness.selectMany(['f', 'other']) + }, saved) + await page.click('[data-frame-title]', { button: 'right' }) + await choose('Cut 2 frames') + await expect.poll(() => deletedFrames).toBe(2) + const clip = await page.evaluate(() => JSON.parse(localStorage.getItem('doop:frame-clipboard') ?? '{}')) + expect(clip.frames.map((f: Frame) => f.x)).toEqual([0, 540]) + }) + it('waits for the matching iframe document before using a position-based selector', async () => { const original = '
Keep
Target
' await page.evaluate((html) => window.contextMenuHarness.updateHtml(html), original) From 2888593337b890931a695dee9f5ff00e155e1e40 Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 19:54:38 +0700 Subject: [PATCH 3/6] docs(canvas): note cut in the canvas commands Co-Authored-By: Claude Opus 5.5 --- .context/TECHSTACK.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index e73283998..d962cbc5a 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -349,6 +349,10 @@ data-doop-webfonts>` for the roster families the frame names and does not load i the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and something is selected, so buttons, menus and the Layers tree keep theirs. The bracket chords are read by `code` too, since ⌥ changes the typed character on macOS. Tests: `selectionKeys.test.ts`. +- Cut (`cutSelection` in `src/lib/elementClipboard.ts`): ⌘X and the frame and element menus' Cut + copy the selection, then remove it the way ⌫ does (one undo step, locked frames and layers stay), + editors only and only once the copy landed. Tests: `cutSelection.test.ts`, the cut cases in + `elementContextMenuBrowser.test.ts`. - `src/lib/tools.ts` defines bottom-toolbar tools and shortcuts. `Stage.tsx` delegates drawing gestures and world-space previews to `CanvasDrawing.tsx`; Space/middle-button panning takes precedence over drawing. From c0eb540b43a5613bd9aa740eb3c9331b54011911 Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 20:10:27 +0700 Subject: [PATCH 4/6] refactor(canvas): drop the clipboard non-null assertions and the fake DataTransfer Co-Authored-By: Claude Opus 5.5 --- src/pages/CanvasPage.tsx | 12 +++++++----- tests/cutSelection.test.ts | 18 +++++------------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index e678fa6f1..eb42d4d57 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -526,14 +526,16 @@ export function CanvasPage({ under it, as a held ⌫ must not delete them */ let held = false const onKeyDown = (e: KeyboardEvent) => void (held = e.repeat) - const ours = (e: ClipboardEvent) => - !isTypingTarget(e.target) && !window.getSelection()?.toString() && !!e.clipboardData + /* the event's clipboard when the canvas owns it, not a field or a text selection */ + const canvasClipboard = (e: ClipboardEvent) => + isTypingTarget(e.target) || window.getSelection()?.toString() ? null : e.clipboardData function onCopy(e: ClipboardEvent) { - if (ours(e) && copySelection(e.clipboardData!)) e.preventDefault() + const data = canvasClipboard(e) + if (data && copySelection(data)) e.preventDefault() } function onCut(e: ClipboardEvent) { - if (!ours(e)) return - if (held || cutSelection(e.clipboardData!)) e.preventDefault() + const data = canvasClipboard(e) + if (data && (held || cutSelection(data))) e.preventDefault() } function onPaste(e: ClipboardEvent) { if (isTypingTarget(e.target)) return diff --git a/tests/cutSelection.test.ts b/tests/cutSelection.test.ts index 7d655f907..ecfec4b03 100644 --- a/tests/cutSelection.test.ts +++ b/tests/cutSelection.test.ts @@ -30,14 +30,6 @@ const frame = (id: string, extra: Partial = {}): Frame => ({ ...extra, }) -function clipboardData() { - const store = new Map() - return { - setData: (type: string, value: string) => void store.set(type, value), - getData: (type: string) => store.get(type) ?? '', - } as unknown as DataTransfer -} - let db: Map function open(frames: Frame[], role: 'edit' | 'view' = 'edit') { @@ -69,7 +61,7 @@ describe('cut', () => { it('puts the selected frames on the clipboard and removes them as one undo step', async () => { open([frame('a'), frame('b'), frame('c')]) useStore.getState().selectMany(['a', 'b']) - const data = clipboardData() + const data = new DataTransfer() expect(cutSelection(data)).toBe(true) @@ -84,7 +76,7 @@ describe('cut', () => { open([frame('a', { locked: true })]) useStore.getState().select('a') - expect(cutSelection(clipboardData())).toBe(true) + expect(cutSelection(new DataTransfer())).toBe(true) expect(hasFrameClip()).toBe(true) expect(api.deleteFrame).not.toHaveBeenCalled() @@ -95,7 +87,7 @@ describe('cut', () => { useStore.getState().select('a') useStore.getState().pickElement({ frameId: 'a', selector: 'body > p:nth-of-type(1)' }) - expect(cutSelection(clipboardData())).toBe(true) + expect(cutSelection(new DataTransfer())).toBe(true) expect(hasElementClip()).toBe(true) expect(api.deleteFrame).not.toHaveBeenCalled() @@ -107,7 +99,7 @@ describe('cut', () => { open([frame('a')], 'view') useStore.getState().select('a') - expect(cutSelection(clipboardData())).toBe(false) + expect(cutSelection(new DataTransfer())).toBe(false) expect(hasFrameClip()).toBe(false) expect(api.deleteFrame).not.toHaveBeenCalled() @@ -115,7 +107,7 @@ describe('cut', () => { it('does nothing with nothing selected', () => { open([frame('a')]) - expect(cutSelection(clipboardData())).toBe(false) + expect(cutSelection(new DataTransfer())).toBe(false) expect(api.deleteFrame).not.toHaveBeenCalled() }) }) From 2d793f4d2c0dcd419746a5bbaf554a5550e93d39 Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 20:14:42 +0700 Subject: [PATCH 5/6] refactor(canvas): share one cut helper and drop the held-key flag MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit cutWith runs the removal only once the copy landed, for ⌘X and both context menus. A held ⌘X is stopped by cancelling its repeat keydown in the existing key handler, so the separate capture listener goes away. Co-Authored-By: Claude Opus 5.5 --- src/components/ElementContextMenu.tsx | 12 +++++------ src/components/FrameContextMenu.tsx | 8 ++----- src/lib/canvasClipboard.ts | 8 +++++++ src/lib/elementClipboard.ts | 30 ++++++++++----------------- src/pages/CanvasPage.tsx | 14 ++++++------- 5 files changed, 33 insertions(+), 39 deletions(-) diff --git a/src/components/ElementContextMenu.tsx b/src/components/ElementContextMenu.tsx index ff2d7ae7c..b79ba7adb 100644 --- a/src/components/ElementContextMenu.tsx +++ b/src/components/ElementContextMenu.tsx @@ -4,7 +4,7 @@ import { copyElementLink } from '../lib/elementLink' import { copyElementPng, type ElementTarget } from '../lib/frameExport' import { useExportSettings } from '../lib/exportSettings' import { copyPicked, hasElementClip, pasteLayer } from '../lib/elementClipboard' -import { writeCanvasClipboard } from '../lib/canvasClipboard' +import { cutWith, writeCanvasClipboard } from '../lib/canvasClipboard' import { hasFrameClip, pasteFrameCentered } from '../lib/frameClipboard' import { deleteLayer, duplicateLayer, setLayerHidden, setLayerLocked, shiftLayer } from '../lib/layerEdits' import { buildLayerTree, elementHtml, findLayer, isElementHidden, isElementLocked, layerName } from '../lib/layers' @@ -95,11 +95,11 @@ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementI { - if (!selector) return - writeCanvasClipboard(() => { - if (!copyPicked(frame, [selector])) return false - deleteLayer(frame, selector) - }) + if (selector) + cutWith( + () => copyPicked(frame, [selector]), + () => deleteLayer(frame, selector), + ) }} > {t('common.cut')} diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index d2d270802..f4eddb255 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -2,7 +2,7 @@ import { useRef, useState, type MutableRefObject } from 'react' import type { Frame } from '../../shared/types' import { errorMessage } from '../lib/api' import { copyFrames, duplicateFrames, hasFrameClip, pasteFrameAtScreen } from '../lib/frameClipboard' -import { writeCanvasClipboard } from '../lib/canvasClipboard' +import { cutWith, writeCanvasClipboard } from '../lib/canvasClipboard' import { copyFramePng } from '../lib/frameExport' import { deleteFramesTracked } from '../lib/history' import { isStackLocked, setFramesHidden, setFramesLocked } from '../lib/layerEdits' @@ -114,11 +114,7 @@ export function FrameContextMenu({ disabled={allLocked} onSelect={() => { const frames = groupFrames() - if (!frames.length) return - writeCanvasClipboard(() => { - copyFrames(frames) - deleteSelection() - }) + if (frames.length) cutWith(() => copyFrames(frames), deleteSelection) }} > {groupSize > 1 ? t('stage.cutFrames', { count: groupSize }) : t('common.cut')} diff --git a/src/lib/canvasClipboard.ts b/src/lib/canvasClipboard.ts index 790ce2ac1..0ccd9b092 100644 --- a/src/lib/canvasClipboard.ts +++ b/src/lib/canvasClipboard.ts @@ -37,6 +37,14 @@ export function writeCanvasClipboard(copy: () => boolean | void, data?: DataTran } } +/** Cut: `remove` runs only once `copy` landed on the clipboard. */ +export function cutWith(copy: () => boolean | void, remove: () => unknown, data?: DataTransfer): boolean { + return writeCanvasClipboard(() => { + if (copy() === false) return false + remove() + }, data) +} + export function isCanvasClipboard(data: DataTransfer | null): boolean { const token = localStorage.getItem(TOKEN_KEY) return !!token && data?.getData('text/plain') === token diff --git a/src/lib/elementClipboard.ts b/src/lib/elementClipboard.ts index 8d2630b47..ca0e2a739 100644 --- a/src/lib/elementClipboard.ts +++ b/src/lib/elementClipboard.ts @@ -3,7 +3,7 @@ import { elementsHtml, insertElements, isElementLocked } from './layers' import { deleteSelection, isStandalonePick, saveFrameHtml } from './layerEdits' import { copyFrames } from './frameClipboard' import { canEditOpenCanvas, pickedSelectors, useStore } from './store' -import { writeCanvasClipboard } from './canvasClipboard' +import { cutWith, writeCanvasClipboard } from './canvasClipboard' import { ELEMENT_CLIP_KEY, ELEMENT_CLIP_STYLE_KEY, FRAME_CLIP_KEY } from './clipboardKeys' import { carriedCss, newScope, renameInCss, SCOPE_ATTR, withCarriedCss } from './styleCarry' @@ -23,38 +23,30 @@ export function copyPicked(frame: Frame, selectors: string[]): boolean { return copyLayers(frame, selectors) } -/** What ⌘C copies now: the picked elements, else the selected frames; - * null when nothing is selected. */ -function selectionCopy(): (() => boolean | void) | null { +/** Copy the picked elements, else the selected frames. False when nothing is selected. */ +function copySelectionNow(): boolean { const state = useStore.getState() const picked = state.selectedElement if (picked) { const frame = state.canvas?.frames.find((f) => f.id === picked.frameId) - if (!frame) return null - const selectors = pickedSelectors(state) - return () => copyPicked(frame, selectors) + return !!frame && copyPicked(frame, pickedSelectors(state)) } const frames = state.canvas?.frames.filter((f) => state.selectedIds.includes(f.id)) ?? [] - return frames.length ? () => copyFrames(frames) : null + if (!frames.length) return false + copyFrames(frames) + return true } /** ⌘C: put the selection on the clipboard. False when there was nothing to copy. */ -export function copySelection(data?: DataTransfer): boolean { - const copy = selectionCopy() - return !!copy && writeCanvasClipboard(copy, data) +export function copySelection(data: DataTransfer): boolean { + return writeCanvasClipboard(copySelectionNow, data) } /** ⌘X: copy the selection, then remove it the way ⌫ does (one undo step; * locked frames and layers stay, copied). Editors only, and nothing is * removed unless the copy landed. */ -export function cutSelection(data?: DataTransfer): boolean { - if (!canEditOpenCanvas(useStore.getState())) return false - const copy = selectionCopy() - if (!copy) return false - return writeCanvasClipboard(() => { - if (copy() === false) return false - deleteSelection() - }, data) +export function cutSelection(data: DataTransfer): boolean { + return canEditOpenCanvas(useStore.getState()) && cutWith(copySelectionNow, deleteSelection, data) } /** Copy the elements in document order; a paste lands them together. */ diff --git a/src/pages/CanvasPage.tsx b/src/pages/CanvasPage.tsx index eb42d4d57..d08329c83 100644 --- a/src/pages/CanvasPage.tsx +++ b/src/pages/CanvasPage.tsx @@ -420,6 +420,11 @@ export function CanvasPage({ e.preventDefault() if (canEdit && !e.repeat) deleteSelection() } + /* the same for a held ⌘X: cancelling its repeats stops their cut events */ + if (e.repeat && (e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'x') { + e.preventDefault() + return + } /* Figma's walk of the selection: ↩ into it, ⇧↩ out to the parent, Tab and ⇧Tab along the siblings. Only the bare keys, and only when no control (a button, a menu, the Layers tree) has the keyboard — there @@ -521,11 +526,6 @@ export function CanvasPage({ /* Native copy/cut/paste events let us write the selection's token and read clipboard images without asking for clipboard-read permission. */ useEffect(() => { - /* a ClipboardEvent carries no repeat flag, so the keydown behind it is - remembered: a held ⌘X must not cut the element and then the frame - under it, as a held ⌫ must not delete them */ - let held = false - const onKeyDown = (e: KeyboardEvent) => void (held = e.repeat) /* the event's clipboard when the canvas owns it, not a field or a text selection */ const canvasClipboard = (e: ClipboardEvent) => isTypingTarget(e.target) || window.getSelection()?.toString() ? null : e.clipboardData @@ -535,7 +535,7 @@ export function CanvasPage({ } function onCut(e: ClipboardEvent) { const data = canvasClipboard(e) - if (data && (held || cutSelection(data))) e.preventDefault() + if (data && cutSelection(data)) e.preventDefault() } function onPaste(e: ClipboardEvent) { if (isTypingTarget(e.target)) return @@ -569,12 +569,10 @@ export function CanvasPage({ pasteFrameCentered(canvasId) } } - window.addEventListener('keydown', onKeyDown, true) window.addEventListener('copy', onCopy) window.addEventListener('cut', onCut) window.addEventListener('paste', onPaste) return () => { - window.removeEventListener('keydown', onKeyDown, true) window.removeEventListener('copy', onCopy) window.removeEventListener('cut', onCut) window.removeEventListener('paste', onPaste) From 0fa673dd6270959665f3154c9b4e9cc301f3c329 Mon Sep 17 00:00:00 2001 From: kitravee Date: Mon, 9 Nov 2026 20:28:52 +0700 Subject: [PATCH 6/6] fix(canvas): keep menu cuts to what they copied while the clipboard answers The menus' Cut waits for navigator.clipboard before removing anything. The frame menu now removes the frames it copied, not whatever is selected when the write lands, and the element menu cancels when the frame changed in the meantime instead of saving its older HTML over the newer one. Co-Authored-By: Claude Opus 5.5 --- src/components/ElementContextMenu.tsx | 12 +-- src/components/FrameContextMenu.tsx | 15 ++-- tests/menuCut.test.tsx | 105 ++++++++++++++++++++++++++ 3 files changed, 122 insertions(+), 10 deletions(-) create mode 100644 tests/menuCut.test.tsx diff --git a/src/components/ElementContextMenu.tsx b/src/components/ElementContextMenu.tsx index b79ba7adb..610c4f556 100644 --- a/src/components/ElementContextMenu.tsx +++ b/src/components/ElementContextMenu.tsx @@ -95,11 +95,13 @@ function ElementMenuItems({ frame, selector, hit, onRename, onExport }: ElementI { - if (selector) - cutWith( - () => copyPicked(frame, [selector]), - () => deleteLayer(frame, selector), - ) + if (!selector) return + /* the clipboard answers later; a frame edited meanwhile is not saved over */ + const live = () => useStore.getState().canvas?.frames.find((f) => f.id === frame.id) + cutWith( + () => live()?.html === frame.html && copyPicked(frame, [selector]), + () => deleteLayer(frame, selector), + ) }} > {t('common.cut')} diff --git a/src/components/FrameContextMenu.tsx b/src/components/FrameContextMenu.tsx index f4eddb255..39f6b50cd 100644 --- a/src/components/FrameContextMenu.tsx +++ b/src/components/FrameContextMenu.tsx @@ -68,9 +68,10 @@ export function FrameContextMenu({ const group = s.canvas?.frames.filter((f) => ids.includes(f.id)) ?? [frame] return group.every((f) => f.locked) }) - function deleteSelection() { - /* locked frames stay, as they do on ⌫ */ - deleteFramesTracked(groupFrames().filter((f) => !f.locked)) + function deleteFrames(frames: Frame[]) { + /* locked frames stay, as they do on ⌫; the lock is read now, not when the menu opened */ + const ids = new Set(frames.map((f) => f.id)) + deleteFramesTracked(useStore.getState().canvas?.frames.filter((f) => ids.has(f.id) && !f.locked) ?? []) } const allReady = useStore((s) => { const ids = s.selectedIds.includes(frame.id) ? s.selectedIds : [frame.id] @@ -114,7 +115,11 @@ export function FrameContextMenu({ disabled={allLocked} onSelect={() => { const frames = groupFrames() - if (frames.length) cutWith(() => copyFrames(frames), deleteSelection) + if (frames.length) + cutWith( + () => copyFrames(frames), + () => deleteFrames(frames), + ) }} > {groupSize > 1 ? t('stage.cutFrames', { count: groupSize }) : t('common.cut')} @@ -172,7 +177,7 @@ export function FrameContextMenu({ {MOD_KEY}⇧L - + deleteFrames(groupFrames())}> {groupSize > 1 ? t('stage.deleteFrames', { count: groupSize }) : t('stage.deleteFrame')} ⌫ diff --git a/tests/menuCut.test.tsx b/tests/menuCut.test.tsx new file mode 100644 index 000000000..17f10ce12 --- /dev/null +++ b/tests/menuCut.test.tsx @@ -0,0 +1,105 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { act, type ReactNode } from 'react' +import { createRoot } from 'react-dom/client' +import type { Canvas, Frame } from '../shared/types' +import { ContextMenu, ContextMenuTrigger } from '../src/components/ui/context-menu' +import { TooltipProvider } from '../src/components/ui/tooltip' + +vi.mock('../src/lib/posthog', () => ({ posthog: { capture: vi.fn() } })) +vi.mock('../src/lib/api', async (importOriginal) => ({ + ...(await importOriginal()), + api: { createFrame: vi.fn(), updateFrame: vi.fn(), deleteFrame: vi.fn(), getCanvas: vi.fn() }, +})) +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +const { api } = await import('../src/lib/api') +const { useStore } = await import('../src/lib/store') +const { FrameContextMenu } = await import('../src/components/FrameContextMenu') +const { ElementContextMenu } = await import('../src/components/ElementContextMenu') + +const frame = (id: string, html = `

${id}

`): Frame => + ({ id, canvasId: 'c', pageId: 'p', name: id, x: 0, y: 0, width: 100, height: 100, html }) as Frame + +/* the system clipboard answers only when the test says so */ +let landWrite: () => void +beforeEach(() => { + vi.resetAllMocks() + vi.mocked(api.deleteFrame).mockResolvedValue(undefined) + vi.mocked(api.updateFrame).mockImplementation(async (id, patch) => ({ ...frame(id), ...patch }) as Frame) + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: () => new Promise((resolve) => (landWrite = resolve)) }, + }) +}) +afterEach(() => vi.restoreAllMocks()) + +function open(frames: Frame[]) { + useStore + .getState() + .setCanvas({ id: 'c', name: 'T', frames, pages: [{ id: 'p', name: 'P' }], role: 'edit' } as unknown as Canvas) +} + +async function pickCut(menu: ReactNode, label: string) { + const container = document.createElement('div') + document.body.appendChild(container) + const root = createRoot(container) + await act(async () => + root.render( + + + +
target
+
+ {menu} +
+
, + ), + ) + await act(async () => { + container + .querySelector('[data-target]')! + .dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, button: 2 })) + }) + const item = [...document.querySelectorAll('[role="menuitem"]')].find((el) => el.textContent?.startsWith(label)) + expect(item, `menu item ${label}`).toBeTruthy() + await act(async () => (item as HTMLElement).click()) + return async () => { + await act(async () => root.unmount()) + container.remove() + } +} + +it('cuts the frames it copied, not a selection made while the clipboard write was pending', async () => { + open([frame('a'), frame('b'), frame('c')]) + useStore.getState().selectMany(['a', 'b']) + const close = await pickCut(, 'Cut 2 frames') + try { + useStore.getState().selectMany(['a', 'c']) + await act(async () => landWrite()) + await vi.waitFor(() => expect(api.deleteFrame).toHaveBeenCalledTimes(2)) + expect( + vi + .mocked(api.deleteFrame) + .mock.calls.map(([id]) => id) + .sort(), + ).toEqual(['a', 'b']) + } finally { + await close() + } +}) + +it('keeps a collaborator’s change made while the clipboard write was pending', async () => { + const before = '

x

keep' + const after = '

x

keeptheirs' + open([frame('f', before)]) + const close = await pickCut(, 'Cut') + try { + useStore.getState().patchFrameLocal('f', { html: after }) + await act(async () => landWrite()) + expect(useStore.getState().canvas?.frames.find((f) => f.id === 'f')?.html).toContain('theirs') + expect(api.updateFrame).not.toHaveBeenCalled() + } finally { + await close() + } +})