Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.14): system clipboard & cross-tab copy — OS-clipboard envelope, paste-image-from-OS, hostile-input sanitizer (D2) (#25)

Ashiq Hussain Mir20a2ba06a1e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4bca632..71c7643 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,48 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.14.1] — 2026-11-04
+
+### Added
+
+- **Daily-driver depth, part 2 — the system clipboard & cross-tab
+ copy (D2).** Copy used to be tab-local (a module-level array): the
+ moment you switched tabs it was gone, and pasting anything from the
+ OS — a screenshot, an image copied from another site — did nothing.
+ Now the OS clipboard carries a Canvix envelope, and OS images paste
+ straight onto the canvas.
+ - **Copy/cut mirror to the system clipboard**: a JSON envelope
+ (`application/x-canvix` custom MIME where supported, plus the same
+ JSON as `text/plain` so Firefox's writeText-only clipboard still
+ round-trips). The internal clipboard stays the same-tab fast
+ path — zero latency, no permissions.
+ - **One native paste pipeline** (the old mod+V keydown branch is
+ gone — keydown can't read clipboard contents): OS image file →
+ image element through the uploads-library rail (D1) with document
+ embed as fallback; Canvix envelope → sanitized elements; anything
+ else → the internal clipboard. Read-only designs never paste;
+ typing surfaces keep their default paste.
+ - **Clipboard files are captured synchronously** — the DataTransfer
+ (and its files) is neutered the moment the handler returns, so the
+ byte read starts inside the event and the File is rebuilt after.
+ The envelope text is likewise read synchronously.
+ - **Pasting is an untrusted-input surface**: `sanitizePastedElements`
+ keeps only known element types, caps every string (20 KB) / array
+ (600) / depth (8) / element count (50), forces finite clamped
+ geometry, strips `__proto__`/`constructor`/underscore keys, and
+ recurses the same gauntlet through group children — the document
+ pipeline only ever sees shapes it could have produced itself.
+ - **Ids are always remapped** on paste (`pasteElements`, the single
+ insertion path) — a paste can never collide with an existing
+ element id, locally or through collab.
+ - **Verification**: 12 new unit tests (the sanitizer gauntlet:
+ hostile types, prototype pollution, oversized payloads, depth
+ bombs, geometry clamps, group recursion; envelope round-trip;
+ DataTransfer stubs) + a 3-spec e2e: copy in tab A pastes in tab B
+ with a fresh id and the paste offset; an OS image lands as an
+ image element with a media-store src; a read-only viewer pressing
+ paste adds nothing (API truth).
+
## [0.14.0] — 2026-11-04
### Added
diff --git a/README.md b/README.md
index cc32dbc..e99be67 100644
--- a/README.md
+++ b/README.md
@@ -954,6 +954,16 @@ tool descriptions so agents pick the right format.
library-kept rows unless `--prune-library`). SVG exports inline
media images to data URLs so files stay portable
*(v0.14.0)*
+- [x] System clipboard & cross-tab copy (v0.14 D2) — copy/cut mirror a
+ Canvix JSON envelope to the OS clipboard (custom MIME + text/plain
+ fallback for Firefox), and one native paste pipeline handles it
+ all: OS image files (screenshots!) become image elements through
+ the uploads library, envelopes paste as sanitized elements, and
+ the internal clipboard remains the same-tab fast path. Pasted
+ data runs a hostile-input gauntlet (type allowlist, string/array/
+ depth/count caps, geometry clamps, prototype-pollution stripping)
+ and every paste remaps element ids. Read-only designs never
+ paste *(v0.14.1)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/package.json b/package.json
index 7af5711..e61696f 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.14.0",
+ "version": "0.14.1",
"private": false,
"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx
index 751a8d9..6ec6175 100644
--- a/src/components/editor/Editor.tsx
+++ b/src/components/editor/Editor.tsx
@@ -5,6 +5,7 @@ import dynamic from 'next/dynamic'
import { X, Keyboard, Eye } from 'lucide-react'
import { useAppStore } from '@/store/app-store'
import { useEditorStore, type PanelId } from '@/store/editor-store'
+import { readPastedElements, capturePastedImage, fileFromClipboard } from '@/lib/clipboard/system-clipboard'
import { TopBar } from './TopBar'
import { LeftRail } from './LeftRail'
import { ContextToolbar } from './PropertiesBar'
@@ -355,6 +356,66 @@ export default function Editor() {
return () => window.removeEventListener('keydown', onKey)
}, [save])
+ // ── v0.14 (D2): the paste pipeline ─────────────────────────
+ // ONE native handler (the keydown path can't read clipboardData):
+ // 1. an OS image file (screenshots, "copy image") → image element
+ // through the uploads-library rail (D1), embed as fallback
+ // 2. a Canvix envelope (custom MIME, or the text/plain fallback
+ // Firefox writes) → sanitized elements — cross-tab copy
+ // 3. otherwise the internal clipboard (same-tab latency path)
+ // Read-only designs never paste; typing surfaces keep their default.
+ useEffect(() => {
+ const isTyping = () => {
+ const el = document.activeElement
+ if (!el) return false
+ const tag = el.tagName
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (el as HTMLElement).isContentEditable
+ }
+ const onPaste = (e: ClipboardEvent) => {
+ if (isTyping()) return
+ const state = useEditorStore.getState()
+ if (state.readOnly) return
+ const dt = e.clipboardData
+ if (!dt) return
+
+ // read EVERYTHING synchronously — the DataTransfer is neutered
+ // the moment this handler returns (async continuations see '');
+ // for files that means starting the byte read inside the handler
+ const img = capturePastedImage(dt)
+ const els = readPastedElements(dt)
+
+ // 1. OS image → the media-store library rail (D1)
+ if (img) {
+ e.preventDefault()
+ void (async () => {
+ const file = await fileFromClipboard(img)
+ const { uploadImageToLibrary, addImageFromFile, addImageFromSrc } = await import('@/components/editor/add-element')
+ try {
+ const { src, w, h } = await uploadImageToLibrary(file)
+ addImageFromSrc(src, w, h)
+ } catch {
+ // library rail failed (quota/offline) → document embed
+ await addImageFromFile(file).catch(() => undefined)
+ }
+ })()
+ return
+ }
+ // 2. Canvix envelope (cross-tab / cross-window copy)
+ if (els.length) {
+ e.preventDefault()
+ state.pasteElements(els)
+ return
+ }
+ // 3. internal clipboard — the same-tab fast path
+ if (state.hasInternalClipboard()) {
+ e.preventDefault()
+ state.pasteClipboard()
+ }
+ }
+ window.addEventListener('paste', onPaste)
+ return () => window.removeEventListener('paste', onPaste)
+ }, [])
+
// ── drag & drop image files onto the canvas ───────────────
useEffect(() => {
const onDragOver = (e: DragEvent) => {
diff --git a/src/lib/clipboard/system-clipboard.test.ts b/src/lib/clipboard/system-clipboard.test.ts
new file mode 100644
index 0000000..077626c
--- /dev/null
+++ b/src/lib/clipboard/system-clipboard.test.ts
@@ -0,0 +1,182 @@
+// Unit tests for the system-clipboard module (v0.14 D2). Pasting is
+// an UNTRUSTED INPUT surface — anything on the OS clipboard can hand
+// us JSON — so the sanitizer is the security boundary these tests pin.
+
+import { describe, it, expect } from 'vitest'
+import {
+ serializeEnvelope,
+ parseEnvelope,
+ sanitizePastedElements,
+ readPastedElements,
+ capturePastedImage,
+ fileFromClipboard,
+ MAX_PASTE_ELEMENTS,
+ CANVIX_MIME,
+} from './system-clipboard'
+import type { AnyElement } from '@/lib/types'
+
+function textEl(overrides: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ type: 'text',
+ id: 't1',
+ x: 10,
+ y: 20,
+ width: 300,
+ height: 40,
+ rotation: 0,
+ opacity: 1,
+ visible: true,
+ locked: false,
+ text: 'hello',
+ fontSize: 32,
+ ...overrides,
+ }
+}
+
+describe('envelope round-trip', () => {
+ it('serialize → parse survives with identical content', () => {
+ const els = [textEl() as unknown as AnyElement]
+ const out = parseEnvelope(serializeEnvelope(els))
+ expect(out).toHaveLength(1)
+ expect(out[0]).toMatchObject({ type: 'text', text: 'hello', x: 10, y: 20 })
+ })
+
+ it('non-envelope JSON is rejected (no app tag)', () => {
+ expect(parseEnvelope(JSON.stringify({ elements: [textEl()] }))).toEqual([])
+ expect(parseEnvelope('{"app":"other","v":1,"elements":[]}')).toEqual([])
+ expect(parseEnvelope('not json at all')).toEqual([])
+ })
+})
+
+describe('sanitizePastedElements — the untrusted-input gauntlet', () => {
+ it('drops unknown element types entirely', () => {
+ const out = sanitizePastedElements([
+ textEl(),
+ { type: 'iframe', x: 0, y: 0, width: 10, height: 10, src: 'https://evil' },
+ { type: 'script' },
+ 'not even an object',
+ null,
+ ])
+ expect(out).toHaveLength(1)
+ expect(out[0].type).toBe('text')
+ })
+
+ it('strips prototype-pollution and underscore keys', () => {
+ const el = textEl({
+ __proto__: undefined,
+ constructor: undefined,
+ _m: 'hlc-stamp',
+ safe: 'kept',
+ })
+ const out = sanitizePastedElements([el])
+ const rec = out[0] as unknown as Record<string, unknown>
+ expect(rec.safe).toBe('kept')
+ expect(rec).not.toHaveProperty('constructor')
+ expect(rec).not.toHaveProperty('_m')
+ })
+
+ it('drops oversized strings and arrays, keeps the rest of the element', () => {
+ const el = textEl({
+ text: 'x'.repeat(50_000),
+ tags: new Array(1000).fill('tag'),
+ })
+ const out = sanitizePastedElements([el])
+ expect(out).toHaveLength(1)
+ const rec = out[0] as unknown as Record<string, unknown>
+ expect(rec).not.toHaveProperty('text')
+ expect(rec).not.toHaveProperty('tags')
+ expect(rec.fontSize).toBe(32)
+ })
+
+ it('caps the element count', () => {
+ const many = Array.from({ length: MAX_PASTE_ELEMENTS + 200 }, () => textEl({ id: 'x' }))
+ expect(sanitizePastedElements(many)).toHaveLength(MAX_PASTE_ELEMENTS)
+ })
+
+ it('clamps geometry to a sane canvas range and forces finite numbers', () => {
+ const out = sanitizePastedElements([
+ textEl({ x: NaN, y: -999_999, width: Infinity, height: 1e12, opacity: 42 }),
+ ])
+ const rec = out[0] as unknown as Record<string, number>
+ // NaN/Infinity are DROPPED by the value sanitizer (non-finite never
+ // survives), then the geometry clamp supplies the default
+ expect(rec.x).toBe(60) // NaN → dropped → default
+ expect(rec.y).toBe(-50_000) // clamped
+ expect(rec.width).toBe(300) // Infinity → dropped → default
+ expect(rec.height).toBe(50_000) // 1e12 is finite → clamped
+ expect(rec.opacity).toBe(1)
+ })
+
+ it('fills visible/locked/opacity defaults for stripped elements', () => {
+ const out = sanitizePastedElements([{ type: 'rect', id: 'r', x: 0, y: 0, width: 10, height: 10 }])
+ const rec = out[0] as unknown as Record<string, unknown>
+ expect(rec.visible).toBe(true)
+ expect(rec.locked).toBe(false)
+ expect(rec.opacity).toBe(1)
+ })
+
+ it('recurses into group children with the same rules', () => {
+ const el = {
+ type: 'group',
+ id: 'g',
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ children: [
+ textEl(),
+ { type: 'evil', x: 0, y: 0 },
+ textEl({ id: 't2', text: 'deep' }),
+ ],
+ }
+ const out = sanitizePastedElements([el])
+ const group = out[0] as unknown as { children: AnyElement[] }
+ expect(group.children).toHaveLength(2)
+ expect(group.children.map((c) => c.type)).toEqual(['text', 'text'])
+ })
+
+ it('survives deep nesting only to MAX_DEPTH (no stack bombs)', () => {
+ // build nested groups ~30 deep
+ let el: Record<string, unknown> = textEl()
+ for (let i = 0; i < 30; i++) {
+ el = { type: 'group', id: `g${i}`, x: 0, y: 0, width: 10, height: 10, children: [el] }
+ }
+ const out = sanitizePastedElements([el])
+ expect(out).toHaveLength(1) // outer group survives; deep child is dropped by depth cap
+ })
+})
+
+describe('readPastedElements / pastedImageFile (DataTransfer stubs)', () => {
+ function dt(types: Record<string, string>, items: { kind: string; type: string; file?: File }[] = []) {
+ return {
+ getData: (t: string) => types[t] ?? '',
+ items: items.map((i) => ({ ...i, getAsFile: () => i.file ?? null })),
+ } as unknown as DataTransfer
+ }
+
+ it('prefers the custom MIME, falls back to text/plain', () => {
+ const els = [textEl() as unknown as AnyElement]
+ const env = serializeEnvelope(els)
+ const fromMime = readPastedElements(dt({ [CANVIX_MIME]: env, 'text/plain': 'plain junk' }))
+ expect(fromMime).toHaveLength(1)
+ const fromText = readPastedElements(dt({ 'text/plain': env }))
+ expect(fromText).toHaveLength(1)
+ expect(readPastedElements(dt({}))).toEqual([])
+ })
+
+ it('captures the first image and rebuilds a byte-identical File', async () => {
+ const bytes = new Uint8Array([1, 2, 3, 4])
+ const file = new File([bytes], 'shot.png', { type: 'image/png' })
+ const capture = capturePastedImage(dt({}, [{ kind: 'file', type: 'image/png', file }]))
+ expect(capture).not.toBeNull()
+ expect(capture!.name).toBe('shot.png')
+ expect(capture!.type).toBe('image/png')
+ const rebuilt = await fileFromClipboard(capture!)
+ expect(rebuilt.size).toBe(4)
+ expect(new Uint8Array(await rebuilt.arrayBuffer())).toEqual(bytes)
+ expect(rebuilt.type).toBe('image/png')
+ // non-image / non-file items are ignored
+ expect(capturePastedImage(dt({}, [{ kind: 'string', type: 'text/plain' }]))).toBeNull()
+ expect(capturePastedImage(dt({}, [{ kind: 'file', type: 'text/csv', file }]))).toBeNull()
+ })
+})
diff --git a/src/lib/clipboard/system-clipboard.ts b/src/lib/clipboard/system-clipboard.ts
new file mode 100644
index 0000000..35c4ab7
--- /dev/null
+++ b/src/lib/clipboard/system-clipboard.ts
@@ -0,0 +1,213 @@
+// ─────────────────────────────────────────────────────────────
+// system-clipboard — cross-tab copy & OS paste (v0.14, D2).
+//
+// The in-editor clipboard stays the same-tab fast path (the store's
+// module-level array, zero latency, no permissions). This module adds
+// the SYSTEM side: copying writes a Canvix envelope to the OS
+// clipboard (custom MIME + text/plain fallback so Firefox — which
+// only supports writeText — still round-trips), and the paste path
+// accepts the envelope back, OS image files, or falls back to the
+// internal clipboard.
+//
+// Pasting is an UNTRUSTED INPUT surface: anything on the other side
+// of the OS clipboard can hand us JSON. sanitizePastedElements keeps
+// only known element types, caps every string/array/depth, forces
+// finite geometry, and drops dangerous keys — the document pipeline
+// only ever sees shapes it could have produced itself.
+// ─────────────────────────────────────────────────────────────
+
+import type { AnyElement, ElementType } from '@/lib/types'
+
+export const CANVIX_MIME = 'application/x-canvix'
+
+const KNOWN_TYPES: ReadonlySet<string> = new Set([
+ 'text', 'rect', 'ellipse', 'triangle', 'star', 'line', 'path', 'stroke',
+ 'image', 'sticker', 'group', 'table', 'frame', 'embed', 'audio', 'video', 'plugin',
+])
+
+export const MAX_PASTE_ELEMENTS = 50
+const MAX_STRING = 20_000
+const MAX_ARRAY = 600
+const MAX_DEPTH = 8
+const MAX_FILED_KEYS = 80
+
+interface Envelope {
+ app: 'canvix'
+ v: 1
+ elements: unknown[]
+}
+
+/** The JSON envelope written to the OS clipboard. */
+export function serializeEnvelope(elements: AnyElement[]): string {
+ const env: Envelope = { app: 'canvix', v: 1, elements }
+ return JSON.stringify(env)
+}
+
+/** deep-sanitize one pasted value; returns null when it must be dropped */
+function sanitizeValue(value: unknown, depth: number): unknown {
+ if (depth > MAX_DEPTH) return null
+ if (value === null || value === undefined) return null
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
+ if (typeof value === 'boolean') return value
+ if (typeof value === 'string') return value.length > MAX_STRING ? null : value
+ if (Array.isArray(value)) {
+ if (value.length > MAX_ARRAY) return null
+ const out: unknown[] = []
+ for (const v of value as unknown[]) {
+ const s = sanitizeValue(v, depth + 1)
+ if (s !== null) out.push(s)
+ }
+ return out
+ }
+ if (typeof value === 'object') {
+ const src = value as Record<string, unknown>
+ const keys = Object.keys(src)
+ if (keys.length > MAX_FILED_KEYS) return null
+ const out: Record<string, unknown> = {}
+ for (const k of keys) {
+ // prototype-pollution & dunder keys never survive a paste
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype' || k.startsWith('_')) continue
+ const s = sanitizeValue(src[k], depth + 1)
+ if (s !== null) out[k] = s
+ }
+ return out
+ }
+ return null
+}
+
+function clampNum(v: unknown, min: number, max: number, fallback: number): number {
+ const n = typeof v === 'number' && Number.isFinite(v) ? (v as number) : fallback
+ return Math.min(max, Math.max(min, Math.round(n * 100) / 100))
+}
+
+/**
+ * Validate + sanitize pasted elements. Only known types survive; ids
+ * are NOT trusted (the store remaps them); geometry is clamped to a
+ * sane canvas range; every nested value is capped. Returns at most
+ * MAX_PASTE_ELEMENTS elements.
+ */
+export function sanitizePastedElements(raw: unknown): AnyElement[] {
+ if (!Array.isArray(raw)) return []
+ const out: AnyElement[] = []
+ for (const item of raw.slice(0, MAX_PASTE_ELEMENTS)) {
+ if (!item || typeof item !== 'object') continue
+ const el = item as Record<string, unknown>
+ if (typeof el.type !== 'string' || !KNOWN_TYPES.has(el.type)) continue
+ const s = sanitizeValue(el, 0) as Record<string, unknown> | null
+ if (!s || typeof s.type !== 'string') continue
+ // geometry: finite, clamped to a generous canvas space
+ s.x = clampNum(s.x, -50_000, 50_000, 60)
+ s.y = clampNum(s.y, -50_000, 50_000, 60)
+ s.width = clampNum(s.width, 1, 50_000, 300)
+ s.height = clampNum(s.height, 1, 50_000, 200)
+ if (typeof s.visible !== 'boolean') s.visible = true
+ if (typeof s.locked !== 'boolean') s.locked = false
+ const opacity = typeof s.opacity === 'number' ? s.opacity : 1
+ s.opacity = Math.min(1, Math.max(0, opacity))
+ // groups carry children through the same gauntlet
+ if (s.type === 'group' && Array.isArray(s.children)) {
+ s.children = sanitizePastedElements(s.children)
+ }
+ out.push(s as unknown as AnyElement)
+ }
+ return out
+}
+
+/** Parse a text payload as a Canvix envelope (custom MIME or fallback). */
+export function parseEnvelope(text: string): AnyElement[] {
+ try {
+ const env = JSON.parse(text) as Partial<Envelope>
+ if (!env || env.app !== 'canvix' || !Array.isArray(env.elements)) return []
+ return sanitizePastedElements(env.elements)
+ } catch {
+ return []
+ }
+}
+
+/**
+ * Copy elements to the SYSTEM clipboard. Custom MIME when the browser
+ * supports ClipboardItem (Chromium/WebKit); text/plain envelope always
+ * (Firefox's writeText round-trips through the same parser). Returns
+ * false when neither path works (e.g. no permissions) — the internal
+ * clipboard still covers the same-tab case.
+ */
+export async function copySelectionToSystem(elements: AnyElement[]): Promise<boolean> {
+ if (!elements.length || typeof navigator === 'undefined' || !navigator.clipboard) return false
+ const envelope = serializeEnvelope(elements)
+ try {
+ if (typeof ClipboardItem !== 'undefined' && navigator.clipboard.write) {
+ await navigator.clipboard.write([
+ new ClipboardItem({
+ [CANVIX_MIME]: new Blob([envelope], { type: CANVIX_MIME }),
+ 'text/plain': new Blob([envelope], { type: 'text/plain' }),
+ }),
+ ])
+ return true
+ }
+ } catch {
+ // fall through to writeText
+ }
+ try {
+ await navigator.clipboard.writeText(envelope)
+ return true
+ } catch {
+ return false
+ }
+}
+
+/** Read Canvix elements from a paste event's clipboardData (MIME, then text). */
+export function readPastedElements(dt: DataTransfer): AnyElement[] {
+ try {
+ const custom = dt.getData(CANVIX_MIME)
+ if (custom) {
+ const els = parseEnvelope(custom)
+ if (els.length) return els
+ }
+ const text = dt.getData('text/plain')
+ if (text) {
+ const els = parseEnvelope(text)
+ if (els.length) return els
+ }
+ } catch {
+ // clipboard read blocked — the internal fallback still applies
+ }
+ return []
+}
+
+/** A synchronously-captured clipboard image: the byte read is STARTED
+ * inside the event handler (the DataTransfer and its files are
+ * neutered the moment the handler returns — a File handed to an async
+ * continuation reads as empty), the File is rebuilt later. */
+export interface ClipboardImageCapture {
+ name: string
+ type: string
+ bytes: Promise<ArrayBuffer>
+}
+
+/** Capture the first image on a paste DataTransfer (OS screenshot etc.).
+ * MUST be called synchronously inside the paste handler. */
+export function capturePastedImage(dt: DataTransfer): ClipboardImageCapture | null {
+ try {
+ for (const item of Array.from(dt.items ?? [])) {
+ if (item.kind === 'file' && item.type.startsWith('image/')) {
+ const file = item.getAsFile()
+ if (file) {
+ return {
+ name: file.name || 'image',
+ type: file.type || 'image/png',
+ // the read starts NOW — before the event handler returns
+ bytes: file.arrayBuffer(),
+ }
+ }
+ }
+ }
+ } catch {
+ // non-file paste
+ }
+ return null
+}
+
+/** Rebuild a real File from a capture (safe to await anywhere). */
+export async function fileFromClipboard(capture: ClipboardImageCapture): Promise<File> {
+ return new File([await capture.bytes], capture.name, { type: capture.type })
+}
diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts
index 6445e78..411bf31 100644
--- a/src/store/editor-store.ts
+++ b/src/store/editor-store.ts
@@ -160,6 +160,8 @@ interface EditorState {
copySelection: () => void
cutSelection: () => void
pasteClipboard: () => void
+ pasteElements: (elements: AnyElement[]) => void
+ hasInternalClipboard: () => boolean
moveLayer: (id: string, dir: 'up' | 'down' | 'front' | 'back') => void
reorderLayer: (dragId: string, targetIndex: number) => void
setLock: (ids: string[], locked: boolean) => void
@@ -533,19 +535,42 @@ export const useEditorStore = create<EditorState>((set, get) => ({
copySelection: () => {
const { selectedIds, pages, currentPage } = get()
clipboard = clone(pages[currentPage].elements.filter((e) => selectedIds.includes(e.id)))
+ // v0.14 (D2): mirror to the SYSTEM clipboard (custom MIME + text
+ // fallback) so another tab — or another Canvix window — can paste.
+ // Best-effort: no permissions → internal clipboard still works.
+ if (clipboard.length && typeof navigator !== 'undefined') {
+ void import('@/lib/clipboard/system-clipboard').then((m) =>
+ m.copySelectionToSystem(clipboard),
+ ).catch(() => { /* internal clipboard still covers same-tab */ })
+ }
},
cutSelection: () => {
const { selectedIds, pages, currentPage } = get()
if (!selectedIds.length) return
clipboard = clone(pages[currentPage].elements.filter((e) => selectedIds.includes(e.id)))
+ // v0.14 (D2): cut mirrors to the system clipboard too
+ if (typeof navigator !== 'undefined') {
+ void import('@/lib/clipboard/system-clipboard').then((m) =>
+ m.copySelectionToSystem(clipboard),
+ ).catch(() => { /* internal clipboard still covers same-tab */ })
+ }
get().deleteSelection()
},
pasteClipboard: () => {
if (!clipboard.length) return
+ get().pasteElements(clipboard)
+ },
+
+ // v0.14 (D2): the single insertion path for pasted elements —
+ // internal clipboard, system-clipboard envelope, whatever. Ids are
+ // ALWAYS remapped (a paste never reuses an existing element id) and
+ // the paste offset keeps stacks visually separated.
+ pasteElements: (elements: AnyElement[]) => {
+ if (!elements.length) return
get().pushHistory()
- const clones = clipboard.map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32, _m: nowHlc() }) as AnyElement)
+ const clones = elements.map((e) => ({ ...clone(e), id: uid(e.type), x: e.x + 32, y: e.y + 32, _m: nowHlc() }) as AnyElement)
const { pages, currentPage } = get()
const next = editPage(pages, currentPage)
next[currentPage].elements = [...next[currentPage].elements, ...clones]
@@ -553,6 +578,11 @@ export const useEditorStore = create<EditorState>((set, get) => ({
emit({ kind: 'elements:add', pageId: next[currentPage].id, elements: clones })
},
+ // v0.14 (D2): does the internal (same-tab) clipboard hold anything?
+ // The paste handler prefers system-clipboard content; this decides
+ // the internal fallback.
+ hasInternalClipboard: () => clipboard.length > 0,
+
moveLayer: (id, dir) => {
get().pushHistory()
const { pages, currentPage } = get()
diff --git a/tests/e2e/clipboard.spec.ts b/tests/e2e/clipboard.spec.ts
new file mode 100644
index 0000000..87dbaf0
--- /dev/null
+++ b/tests/e2e/clipboard.spec.ts
@@ -0,0 +1,181 @@
+import { test, expect, type Page } from '@playwright/test'
+import { writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+/**
+ * v0.14 (D2): the system clipboard — acceptance.
+ *
+ * 1. copy in TAB A pastes in TAB B (the envelope rides the OS
+ * clipboard — custom MIME on Chromium)
+ * 2. an OS image (screenshot-style clipboard content) lands as an
+ * image element through the uploads-library rail (D1)
+ * 3. read-only designs never paste
+ */
+
+const PNG_B64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR42mM4YROAFTEMLQkAVLdVAZV719MAAAAASUVORK5CYII='
+
+const TEXT_ELEMENT = {
+ id: 'txt_clip_e2e',
+ type: 'text',
+ text: 'clipboard payload',
+ x: 120,
+ y: 90,
+ width: 420,
+ height: 60,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ fontSize: 40,
+ fontFamily: 'Inter',
+ bold: true,
+ italic: false,
+ underline: false,
+ strike: false,
+ uppercase: false,
+ fill: '#1F2226',
+ align: 'left',
+ lineHeight: 1.25,
+ letterSpacing: 0,
+ shadow: { enabled: false, color: '#000000', blur: 0, offsetX: 0, offsetY: 0 },
+}
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `d2_${tag}_${Date.now().toString(36)}`
+ const res = await page.request.post('/api/auth/register', {
+ data: { username, password: `D2-E2e-${username}-17!q` },
+ })
+ expect(res.status()).toBeLessThan(300)
+ return username
+}
+
+async function createDesign(page: Page, name: string, elements: unknown[]): Promise<string> {
+ const res = await page.request.post('/api/designs', {
+ data: { name, width: 1080, height: 720, pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }] },
+ })
+ expect(res.status()).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+async function elementCount(page: Page, designId: string, pred: (e: Record<string, unknown>) => boolean): Promise<number> {
+ const res = await page.request.get(`/api/designs/${designId}`)
+ expect(res.status()).toBe(200)
+ const doc = (await res.json()) as { pages: { elements: Record<string, unknown>[] }[] }
+ return doc.pages[0].elements.filter(pred).length
+}
+
+test.describe('System clipboard (v0.14 D2)', () => {
+ test('copy in tab A pastes in tab B with a fresh element id', async ({ browser }) => {
+ const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] })
+ const pageA = await ctx.newPage()
+ const username = await register(pageA, 'xtab')
+ const designA = await createDesign(pageA, `cvx_d2_a_${username}`, [TEXT_ELEMENT])
+ await openEditor(pageA, designA)
+
+ // select the text element through the layers tab (Konva is DOM-opaque)
+ await pageA.getByRole('button', { name: 'Tools', exact: true }).click()
+ await pageA.getByRole('button', { name: 'Layers', exact: true }).click()
+ await pageA.getByText('clipboard payload', { exact: true }).click()
+
+ // copy → the envelope rides the OS clipboard
+ await pageA.keyboard.press('Control+c')
+ await pageA.waitForTimeout(1_000) // let the async clipboard write land
+
+ // TAB B — same browser context, so the system clipboard is shared
+ const designB = await createDesign(pageA, `cvx_d2_b_${username}`, [])
+ const pageB = await ctx.newPage()
+ await openEditor(pageB, designB)
+ await pageB.bringToFront()
+ await expect
+ .poll(() => elementCount(pageB, designB, () => true), { timeout: 5_000 })
+ .toBe(0) // nothing yet
+
+ await pageB.keyboard.press('Control+v')
+
+ // the element landed — same text, and a NEW id (never reuses ids)
+ await expect
+ .poll(() => elementCount(pageB, designB, (e) => e.type === 'text' && e.text === 'clipboard payload'), { timeout: 15_000 })
+ .toBe(1)
+ const res = await pageB.request.get(`/api/designs/${designB}`)
+ const doc = (await res.json()) as { pages: { elements: { id: string; type: string; text?: string; x: number }[] }[] }
+ const pasted = doc.pages[0].elements.find((e) => e.type === 'text')
+ expect(pasted?.id).not.toBe(TEXT_ELEMENT.id)
+ expect(pasted?.x).toBe(TEXT_ELEMENT.x + 32) // paste offset
+ await ctx.close()
+ })
+
+ test('an OS image on the clipboard lands as an image element (library rail)', async ({ browser }) => {
+ const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] })
+ const page = await ctx.newPage()
+ const username = await register(page, 'img')
+ const design = await createDesign(page, `cvx_d2_img_${username}`, [])
+ await openEditor(page, design)
+
+ // put a PNG on the OS clipboard the way a screenshot tool would
+ await page.evaluate(async (b64) => {
+ const blob = await (await fetch(`data:image/png;base64,${b64}`)).blob()
+ await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
+ }, PNG_B64)
+
+ await page.keyboard.press('Control+v')
+
+ // image element with a media-store src (the D1 rail), not a data URL
+ await expect
+ .poll(
+ () =>
+ elementCount(
+ page,
+ design,
+ (e) => e.type === 'image' && typeof e.src === 'string' && (e.src as string).startsWith('/api/media/'),
+ ),
+ { timeout: 20_000 },
+ )
+ .toBe(1)
+ await ctx.close()
+ })
+
+ test('read-only designs never paste', async ({ browser }) => {
+ // owner creates a design with content…
+ const ownerCtx = await browser.newContext()
+ const ownerPage = await ownerCtx.newPage()
+ const username = await register(ownerPage, 'owner')
+ const design = await createDesign(ownerPage, `cvx_d2_ro_${username}`, [TEXT_ELEMENT])
+ await ownerCtx.close()
+
+ // …an anonymous viewer opens it (read-only)
+ const viewerCtx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] })
+ const viewer = await viewerCtx.newPage()
+ await openEditor(viewer, design)
+
+ // seed the clipboard with a valid Canvix envelope…
+ await viewer.evaluate(async () => {
+ const env = JSON.stringify({
+ app: 'canvix',
+ v: 1,
+ elements: [{
+ id: 'hostile', type: 'text', text: 'should not land',
+ x: 10, y: 10, width: 200, height: 40, fontSize: 20, fontFamily: 'Inter',
+ fill: '#000', align: 'left', lineHeight: 1.25, letterSpacing: 0,
+ bold: false, italic: false, underline: false, strike: false, uppercase: false,
+ rotation: 0, opacity: 1, visible: true, locked: false,
+ shadow: { enabled: false, color: '#000', blur: 0, offsetX: 0, offsetY: 0 },
+ }],
+ })
+ await navigator.clipboard.write([new ClipboardItem({ 'text/plain': new Blob([env], { type: 'text/plain' }) })])
+ })
+ await viewer.keyboard.press('Control+v')
+ await viewer.waitForTimeout(2_500)
+
+ // …nothing was pasted (API truth — still exactly one element)
+ await expect.poll(() => elementCount(viewer, design, () => true), { timeout: 5_000 }).toBe(1)
+ await viewerCtx.close()
+ })
+})
diff --git a/tests/e2e/uploads-library.spec.ts b/tests/e2e/uploads-library.spec.ts
index 1a549c8..24d51a5 100644
--- a/tests/e2e/uploads-library.spec.ts
+++ b/tests/e2e/uploads-library.spec.ts
@@ -77,7 +77,7 @@ test.describe('Uploads library (v0.14 D1)', () => {
.poll(async () => {
const doc = await designDoc(page, designA)
return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
- }, { timeout: 20_000 })
+ }, { timeout: 45_000 })
.toBeGreaterThanOrEqual(1)
// the library lists the file with the quota line
@@ -105,7 +105,7 @@ test.describe('Uploads library (v0.14 D1)', () => {
.poll(async () => {
const doc = await designDoc(page, designB)
return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src === `/api/media/${mediaId}`).length
- }, { timeout: 20_000 })
+ }, { timeout: 45_000 })
.toBe(1)
// the SVG export inlines media images (portable, no /api/media refs)
@@ -133,7 +133,7 @@ test.describe('Uploads library (v0.14 D1)', () => {
.poll(async () => {
const doc = await designDoc(page, design)
return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
- }, { timeout: 20_000 })
+ }, { timeout: 45_000 })
.toBeGreaterThanOrEqual(1)
const doc = await designDoc(page, design)
@@ -163,7 +163,7 @@ test.describe('Uploads library (v0.14 D1)', () => {
.poll(async () => {
const doc = await designDoc(page, design)
return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
- }, { timeout: 20_000 })
+ }, { timeout: 45_000 })
.toBeGreaterThanOrEqual(1)
// the anonymous library lists it…