Skip to content
4 changes: 4 additions & 0 deletions .context/TECHSTACK.md
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,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`.
- Canvas commands (`src/lib/actions/`): every editor command is one entry in `registry.ts` (id,
label key in the `actions` catalog, menu and section, chords, `edit`, `enabled`, `checked`,
`run`), and the keyboard (`dispatchActionKey`, called first by `CanvasPage`'s keydown), the ⌘K
Expand Down
19 changes: 18 additions & 1 deletion src/components/ElementContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
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'
import { MOD_KEY } from '../lib/keys'
import { canEditOpenCanvas, useStore } from '../lib/store'

Check failure on line 12 in src/components/ElementContextMenu.tsx

View workflow job for this annotation

GitHub Actions / lint

oxlint

src/components/ElementContextMenu.tsx:12:29: Identifier `useStore` has already been declared
import { useT } from '../lib/i18n'
import { useStore } from '../lib/store'
import { changeInstance, componentContextOf, goToMain, promptMakeComponent } from '../lib/components'
Expand Down Expand Up @@ -84,6 +85,7 @@
/* 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 (
<>
<ContextMenuItem
Expand All @@ -95,6 +97,21 @@
{t('common.copy')}
<MenuHint>{MOD_KEY}C</MenuHint>
</ContextMenuItem>
<ContextMenuItem
disabled={!canEdit || !exists || locked}
onSelect={() => {
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')}
<MenuHint>{MOD_KEY}X</MenuHint>
</ContextMenuItem>
<ContextMenuItem
disabled={frameClip ? false : locked || !hasElementClip() || (!!selector && !exists)}
onSelect={() => {
Expand Down
25 changes: 20 additions & 5 deletions src/components/FrameContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -110,6 +111,20 @@ export function FrameContextMenu({
</ContextMenuItem>
{!readOnly && (
<>
<ContextMenuItem
disabled={allLocked}
onSelect={() => {
const frames = groupFrames()
if (frames.length)
cutWith(
() => copyFrames(frames),
() => deleteFrames(frames),
)
}}
>
{groupSize > 1 ? t('stage.cutFrames', { count: groupSize }) : t('common.cut')}
<MenuHint>{MOD_KEY}X</MenuHint>
</ContextMenuItem>
{onRename && (
<ContextMenuItem disabled={isStackLocked(frame)} onSelect={() => (renameRequested.current = true)}>
{t('panels.layersRename')}
Expand Down Expand Up @@ -162,7 +177,7 @@ export function FrameContextMenu({
<MenuHint>{MOD_KEY}⇧L</MenuHint>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem tone="danger" disabled={allLocked} onSelect={deleteSelection}>
<ContextMenuItem tone="danger" disabled={allLocked} onSelect={() => deleteFrames(groupFrames())}>
{groupSize > 1 ? t('stage.deleteFrames', { count: groupSize }) : t('stage.deleteFrame')}
<MenuHint>⌫</MenuHint>
</ContextMenuItem>
Expand Down
8 changes: 8 additions & 0 deletions src/lib/canvasClipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 29 additions & 2 deletions src/lib/elementClipboard.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { Frame } from '../../shared/types'
import { elementsHtml, insertElements, isElementLocked, replaceElementsWith } 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 { 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'

Expand All @@ -22,6 +23,32 @@ export function copyPicked(frame: Frame, selectors: string[]): boolean {
return copyLayers(frame, selectors)
}

/** 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)
return !!frame && copyPicked(frame, pickedSelectors(state))
}
const frames = state.canvas?.frames.filter((f) => state.selectedIds.includes(f.id)) ?? []
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 {
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 {
return canEditOpenCanvas(useStore.getState()) && cutWith(copySelectionNow, 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)
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n/en/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export const common = {
delete: 'Delete',
close: 'Close',
copy: 'Copy',
cut: 'Cut',
copied: 'Copied',
back: 'Back',
loading: 'Loading…',
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n/en/stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n/pt-BR/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const common: Catalog['common'] = {
delete: 'Excluir',
close: 'Fechar',
copy: 'Copiar',
cut: 'Recortar',
copied: 'Copiado',
back: 'Voltar',
loading: 'Carregando…',
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n/pt-BR/stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
40 changes: 20 additions & 20 deletions src/pages/CanvasPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CAPTURE_PREFIX, pasteWebCapture } from '../lib/webCapture'
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'
import { canEditOpenCanvas, pickedSelectors, roleOf, useStore } from '../lib/store'
import { canEditOpenCanvas, roleOf, useStore } from '../lib/store'
import { MOD_KEY, PRESENT_SHORTCUT_HINT, isControlTarget, isTypingTarget } from '../lib/keys'
import { enterSelection, exitSelection, selectSibling } from '../lib/selectionKeys'
import { dispatchActionKey, setActionHost, type ActionHost } from '../lib/actions/registry'
Expand Down Expand Up @@ -61,7 +61,6 @@ import { LinkDialog } from '../components/LinkDialog'
import { FrameHistoryModal } from '../components/FrameHistoryModal'
import { getIdentity, setName } from '../lib/identity'
import {
copyFrames,
dropFiles,
hasFrameClip,
hasIncoming,
Expand All @@ -72,8 +71,8 @@ import {
} from '../lib/frameClipboard'
import { clearHistory } from '../lib/history'
import { deleteSelection, nudgeSelection } from '../lib/layerEdits'
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 { openSupportChat, posthog } from '../lib/posthog'
Expand Down Expand Up @@ -400,6 +399,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
Expand Down Expand Up @@ -429,25 +433,19 @@ export function CanvasPage({
return () => window.removeEventListener('keydown', onKey)
}, [canvasId, 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(() => {
/* 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 (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()
const data = canvasClipboard(e)
if (data && copySelection(data)) e.preventDefault()
}
function onCut(e: ClipboardEvent) {
const data = canvasClipboard(e)
if (data && cutSelection(data)) e.preventDefault()
}
function onPaste(e: ClipboardEvent) {
if (isTypingTarget(e.target)) return
Expand Down Expand Up @@ -482,9 +480,11 @@ export function CanvasPage({
}
}
window.addEventListener('copy', onCopy)
window.addEventListener('cut', onCut)
window.addEventListener('paste', onPaste)
return () => {
window.removeEventListener('copy', onCopy)
window.removeEventListener('cut', onCut)
window.removeEventListener('paste', onPaste)
}
}, [canvasId])
Expand Down
Loading
Loading