Skip to content

Open source CapCut alternative.

TypeScript

feat(site): copy and paste between projects

David Le31c8a7140b67
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index 14caa438..3966907c 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -20,7 +20,7 @@ A project lives in one of three homes, chosen when it is created.
on-device speech)
```
-The user sees two places, Local and Cloud. Local is the Mac's engine once the app has connected and the browser's own storage otherwise, so a fully local project needs nothing installed. A project lives in exactly one home and the surfaces never proxy to each other.
+The user sees two places, Local and Cloud. Local is the Mac's engine once the app has connected and the browser's own storage otherwise, so a fully local project needs nothing installed. A project lives in exactly one home and the surfaces never proxy to each other. Copy and paste crosses homes: a selection or a media card copied in one project pastes into another with its media brought across, and a second paste of the same source finds the copy already there.
AI is hosted whatever the home: image, video, and voiceover generation and the assistant's Gemini models run through Donkey's authenticated inference routes against the user's credits, and the results land in the project like any other file. The cloud's routes are the engine's hosted twin, same shapes with session auth and credit metering.
@@ -44,4 +44,4 @@ The chat drives everything the editor can do through typed tools, and every tool
## Where it lives
-The editor, its stores, and the backend seam live under the site's `cut` folder; the engine and worker share its server code; the Mac app is a menu bar shell that ships the engine and screen recording.
+The editor, its stores, and the backend seam live under the site's `cut` folder; the engine and worker share its server code; the Mac app is a menu bar shell that ships the engine and screen recording. Every kind of item the timeline can select is one entry in the item-kind table beside the store, and copy, paste, templates and the media collector read that table, so a new kind is copyable and pasteable by construction.
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 433462b5..b8a98aea 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -23,6 +23,7 @@ import {
} from "@/cut/lib/exportClient";
import { EMPTY_LIBRARY, fileZoneAt, hasRefDrag, parseMentions, refCandidatesOf, selectionRefTokens } from "@/cut/lib/assetRef";
import { placeRefAtPlayhead } from "@/cut/lib/refPlace";
+import { pasteCutPayload, payloadAssets, payloadFromHtml, writeCutClipboard } from "@/cut/lib/cutClipboard";
import { useLibrary } from "@/cut/lib/queries";
import { copyableRefs } from "@/cut/lib/refCopy";
import { startUpload } from "@/cut/lib/importQueue";
@@ -1025,6 +1026,19 @@ export function Editor({
const files = pasted.filter((f) => isMediaFile(f) && !isFontFile(f));
if (files.length === 0) {
if (fonts.length > 0) return;
+ // A copy made in Cut — this tab, another tab, another project — rides
+ // the HTML flavor whole. It is the newest copy whichever tab made it,
+ // so it goes ahead of this tab's own timeline clipboard; a card copy
+ // from this same project falls through to its tokens below.
+ const payload = payloadFromHtml(e.clipboardData?.getData("text/html"));
+ const projectId = s.projectId;
+ if (payload && projectId && (payload.projectId !== projectId || payload.items.length > 0)) {
+ e.preventDefault();
+ void pasteCutPayload(payload, { projectId, at, library: libraryRef.current }).catch((err) =>
+ reportSwallowed("[cut] paste from another project failed", err)
+ );
+ return;
+ }
if (pasteOwn(at)) {
e.preventDefault();
return;
@@ -1036,7 +1050,6 @@ export function Editor({
const library = libraryRef.current;
const candidates = refCandidatesOf(s, library);
const refs = parseMentions(e.clipboardData?.getData("text/plain") ?? "", candidates).refs;
- const projectId = s.projectId;
if (refs.length === 0 || !projectId) return;
e.preventDefault();
void (async () => {
@@ -1150,7 +1163,14 @@ export function Editor({
const copied = s.copySelection();
if (copied) clearCopiedFrame();
if (copied || token) {
- void navigator.clipboard.writeText(token ?? "").catch(() => {});
+ // The copy leaves the tab whole: the items and the assets they
+ // play, so ⌘V in another tab or another project lands them.
+ const items = copied ? s.copiedItems() : [];
+ const payload =
+ copied && s.projectId
+ ? { v: 1 as const, projectId: s.projectId, items, assets: payloadAssets(items, s.assets) }
+ : null;
+ void writeCutClipboard(token ?? "", payload).catch(() => {});
e.preventDefault();
}
}
diff --git a/site/src/cut/lib/cutClipboard.test.ts b/site/src/cut/lib/cutClipboard.test.ts
new file mode 100644
index 00000000..a0ae24d8
--- /dev/null
+++ b/site/src/cut/lib/cutClipboard.test.ts
@@ -0,0 +1,195 @@
+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
+
+import { clipboardHtml, pasteCutPayload, payloadAssets, payloadFromHtml, type CutClipboardPayload } from "./cutClipboard";
+import { richDoc } from "./fixtures/richDoc";
+import { EMPTY_LIBRARY } from "./assetRef";
+import { setPlayhead } from "./playhead";
+import { setHostDocStore } from "./projectReference";
+import { storedAssets, useEditor, type TimelineClipboardItem } from "./store";
+import { emptySubtitles, isStickerOverlay, isTextOverlay, type MediaAsset, type ProjectDoc, type VideoClip } from "./types";
+
+/**
+ * ⌘C in one project, ⌘V in another. The copy leaves the tab whole — the
+ * items and the media they play — so the paste in the other project brings
+ * the media across once, remembers where it came from, and lands the items
+ * the way a paste made in that project lands.
+ */
+
+const rich = richDoc();
+const docs = new Map<string, ProjectDoc>([["rich", rich]]);
+const copies: string[] = [];
+setHostDocStore({
+ readDoc: async (id) => docs.get(id) ?? null,
+ copyMedia: async (_src, file) => {
+ copies.push(file);
+ return `copy-${file}`;
+ },
+});
+afterAll(() => setHostDocStore(null));
+
+const richAssets: MediaAsset[] = (rich.assets ?? []).map((a) => ({ ...a, url: "" }));
+const itemsOf = (ids: string[]): TimelineClipboardItem[] =>
+ ids.map((id) => {
+ const clip = rich.clips?.find((c) => c.id === id);
+ if (clip) return { kind: "clip", item: clip };
+ const audio = rich.audioClips?.find((c) => c.id === id);
+ if (audio) return { kind: "audio", item: audio };
+ const overlay = rich.overlays?.find((o) => o.id === id);
+ if (overlay) return { kind: "overlay", item: overlay };
+ const cue = rich.subtitles?.cues.find((c) => c.id === id);
+ if (cue) return { kind: "cue", item: cue };
+ throw new Error(`no item ${id}`);
+ });
+const payloadOf = (ids: string[], projectId = "rich"): CutClipboardPayload => {
+ const items = itemsOf(ids);
+ return { v: 1, projectId, items, assets: payloadAssets(items, richAssets) };
+};
+
+describe("the clipboard flavor", () => {
+ test("round-trips through the markup the OS wraps it in", () => {
+ const payload = payloadOf(["c0", "t1"]);
+ const html = clipboardHtml("@v1 @\"Brand line\"", payload);
+ expect(payloadFromHtml(html)).toEqual(payload);
+ // Chrome prefixes a charset; Windows wraps the fragment in CF_HTML.
+ expect(payloadFromHtml(`<meta charset='utf-8'>${html}`)).toEqual(payload);
+ expect(payloadFromHtml(`Version:0.9\r\nStartHTML:000\r\n<html><body><!--StartFragment-->${html}<!--EndFragment--></body></html>`)).toEqual(payload);
+ expect(payloadFromHtml("<b>someone else's</b>")).toBeNull();
+ expect(payloadFromHtml('<span data-donkeycut="notbase64!!">x</span>')).toBeNull();
+ expect(payloadFromHtml(null)).toBeNull();
+ });
+
+ test("a copy carries the media its items play: footage, sound, the sticker, the title's font", () => {
+ const assets = payloadAssets(itemsOf(["c0", "a0", "s1", "t1", "q0"]), richAssets);
+ expect(assets.map((a) => a.id).sort()).toEqual(["f0", "m0", "s0", "v0"]);
+ // Stored shape only: nothing runtime rides along.
+ expect("url" in assets[0]).toBe(false);
+ });
+});
+
+describe("pasting into another project", () => {
+ beforeEach(() => {
+ copies.length = 0;
+ useEditor.setState({
+ projectId: "p2",
+ clips: [],
+ transitions: [],
+ audioClips: [],
+ overlays: [],
+ assets: [],
+ subtitles: emptySubtitles(),
+ selection: null,
+ multiSelection: [],
+ });
+ setPlayhead(2);
+ });
+
+ test("brings the media across once and lands the items on it", async () => {
+ const payload = payloadOf(["c0", "a0", "s1", "t1", "q0"]);
+ expect(await pasteCutPayload(payload, { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).toBe(true);
+ const s = useEditor.getState();
+ expect(copies.sort()).toEqual(["arrow.png", "brand.ttf", "clip-0.mp4", "music.m4a"]);
+ expect(s.assets).toHaveLength(4);
+ expect(s.assets.every((a) => a.copiedFrom?.projectId === "rich")).toBe(true);
+ const footage = s.assets.find((a) => a.copiedFrom?.assetId === "v0")!;
+ // The notes and transcript written against the source came with it.
+ expect(footage.watch?.notes).toHaveLength(1);
+ expect(footage.speech?.segments).toHaveLength(1);
+ expect(s.clips).toHaveLength(1);
+ expect(s.clips[0]).toMatchObject({ assetId: footage.id, start: 2, speed: 1.25 });
+ expect(s.audioClips[0].assetId).toBe(s.assets.find((a) => a.copiedFrom?.assetId === "m0")!.id);
+ const sticker = s.overlays.find(isStickerOverlay)!;
+ expect(sticker.assetId).toBe(s.assets.find((a) => a.copiedFrom?.assetId === "s0")!.id);
+ const title = s.overlays.find(isTextOverlay)!;
+ expect(title.font).toBe(`asset:${s.assets.find((a) => a.type === "font")!.id}`);
+ expect(s.subtitles.cues).toHaveLength(1);
+ expect(s.subtitles.cues[0]).toMatchObject({ start: 2, text: "every feature" });
+
+ // Pasting the same copy again finds the media already here.
+ copies.length = 0;
+ expect(await pasteCutPayload(payload, { projectId: "p2", at: 20, library: EMPTY_LIBRARY })).toBe(true);
+ expect(copies).toEqual([]);
+ expect(useEditor.getState().assets).toHaveLength(4);
+ expect(useEditor.getState().clips).toHaveLength(2);
+ });
+
+ test("a keyed clip arrives without its removal, and a generated source lands as the user's import", async () => {
+ const clip = { ...rich.clips![0], removal: { mode: "auto", requested: true } as unknown as NonNullable<VideoClip["removal"]> };
+ const payload: CutClipboardPayload = {
+ v: 1,
+ projectId: "rich",
+ items: [{ kind: "clip", item: clip }, { kind: "audio", item: rich.audioClips![0] }],
+ assets: storedAssets(richAssets.filter((a) => a.id === "v0" || a.id === "m0")),
+ };
+ expect(await pasteCutPayload(payload, { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).toBe(true);
+ const s = useEditor.getState();
+ expect(s.clips[0].removal).toBeUndefined();
+ // The music was generated in the source; here it is a file the user brought in.
+ const music = s.assets.find((a) => a.copiedFrom?.assetId === "m0")!;
+ expect(music.origin).toBeUndefined();
+ expect(music.beats?.bpm).toBe(120);
+ });
+
+ test("a sticker stays a sticker when it crosses", async () => {
+ const payload: CutClipboardPayload = { v: 1, projectId: "rich", items: [], assets: storedAssets(richAssets.filter((a) => a.id === "s0")) };
+ expect(await pasteCutPayload(payload, { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).toBe(true);
+ const s = useEditor.getState();
+ expect(s.assets[0].origin).toBe("sticker");
+ expect(s.overlays.some(isStickerOverlay)).toBe(true);
+ });
+
+ test("a project that closes while the media lands takes none of it", async () => {
+ setHostDocStore({
+ readDoc: async (id) => docs.get(id) ?? null,
+ copyMedia: async (_src, file) => {
+ // The user switched projects while the bytes were on their way.
+ useEditor.setState({ projectId: "p3", assets: [], clips: [] });
+ return `copy-${file}`;
+ },
+ });
+ try {
+ await expect(pasteCutPayload(payloadOf(["c0"]), { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).rejects.toThrow(
+ "The project closed"
+ );
+ expect(useEditor.getState().assets).toHaveLength(0);
+ expect(useEditor.getState().clips).toHaveLength(0);
+ } finally {
+ setHostDocStore({
+ readDoc: async (id) => docs.get(id) ?? null,
+ copyMedia: async (_src, file) => {
+ copies.push(file);
+ return `copy-${file}`;
+ },
+ });
+ }
+ });
+
+ test("a copied card lands its asset the way its + button does", async () => {
+ const payload: CutClipboardPayload = { v: 1, projectId: "rich", items: [], assets: storedAssets(richAssets.filter((a) => a.id === "v1")) };
+ expect(await pasteCutPayload(payload, { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).toBe(true);
+ const s = useEditor.getState();
+ expect(s.assets).toHaveLength(1);
+ expect(s.clips).toHaveLength(1);
+ expect(s.clips[0].assetId).toBe(s.assets[0].id);
+ });
+
+ test("in the project the copy came from, the items paste as a same-tab copy would", async () => {
+ useEditor.setState({ projectId: "rich", assets: richAssets });
+ expect(await pasteCutPayload(payloadOf(["t0"]), { projectId: "rich", at: 2, library: EMPTY_LIBRARY })).toBe(true);
+ expect(copies).toEqual([]);
+ expect(useEditor.getState().overlays).toHaveLength(1);
+ // A card copy from this same project is its tokens' to place.
+ const card: CutClipboardPayload = { v: 1, projectId: "rich", items: [], assets: storedAssets(richAssets) };
+ expect(await pasteCutPayload(card, { projectId: "rich", at: 2, library: EMPTY_LIBRARY })).toBe(false);
+ });
+
+ test("a paste aimed at a project no longer open lands nothing", async () => {
+ expect(await pasteCutPayload(payloadOf(["c0"]), { projectId: "p9", at: 2, library: EMPTY_LIBRARY })).toBe(false);
+ expect(useEditor.getState().clips).toHaveLength(0);
+ });
+
+ test("a source project nothing can open is a plain error", async () => {
+ await expect(pasteCutPayload(payloadOf(["c0"], "gone"), { projectId: "p2", at: 2, library: EMPTY_LIBRARY })).rejects.toThrow(
+ "No project with id gone"
+ );
+ });
+});
diff --git a/site/src/cut/lib/cutClipboard.ts b/site/src/cut/lib/cutClipboard.ts
new file mode 100644
index 00000000..2bb66731
--- /dev/null
+++ b/site/src/cut/lib/cutClipboard.ts
@@ -0,0 +1,139 @@
+// What a ⌘C / Ctrl+C leaves on the system clipboard, and what a ⌘V / Ctrl+V
+// makes of it in another tab or another project.
+//
+// The text on the clipboard stays the mention tokens the chat composer reads.
+// Beside it rides an HTML flavor carrying the copy itself: the timeline items
+// whole, and the assets they play — or, for a card copied off a panel, the
+// assets alone. A paste in the project the copy came from lands the items as
+// a same-tab paste does; a paste in another project first brings the media
+// across from wherever that project lives (this browser's storage, the Mac's
+// engine, the cloud), remembers where each copy came from so the next paste
+// finds it, and then lands the items on the copies.
+
+import { refFromAsset } from "./assetRef";
+import { trackEditorTool } from "./editorWork";
+import { clipboardItemAcross, clipboardItemAssetIds, type TimelineClipboardItem } from "./itemKinds";
+import type { LibraryData } from "./library";
+import { landReferenceAssets, openReference } from "./projectReference";
+import { placeRefAtPlayhead } from "./refPlace";
+import { storedAssets, useEditor } from "./store";
+import type { MediaAsset, StoredAsset } from "./types";
+
+export interface CutClipboardPayload {
+ v: 1;
+ /** The project the copy was made in. */
+ projectId: string;
+ /** Timeline items, when the copy was a selection; empty for a card copy. */
+ items: TimelineClipboardItem[];
+ /** Every asset the items play — footage, sound, stickers, the fonts titles
+ * are set in — or the copied cards themselves. */
+ assets: StoredAsset[];
+}
+
+const ATTR = "data-donkeycut";
+
+/** The assets a set of copied items reaches once they leave the project:
+ * their media, their fonts — each kind says where its ids sit. */
+export function payloadAssets(items: TimelineClipboardItem[], assets: MediaAsset[]): StoredAsset[] {
+ const ids = new Set<string>();
+ for (const cb of items) for (const id of clipboardItemAssetIds(clipboardItemAcross(cb, (id) => id))) ids.add(id);
+ return storedAssets(assets.filter((a) => ids.has(a.id)));
+}
+
+const toBase64 = (text: string): string => {
+ const bytes = new TextEncoder().encode(text);
+ let bin = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return btoa(bin);
+};
+
+const fromBase64 = (b64: string): string =>
+ new TextDecoder().decode(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));
+
+const escapeHtml = (s: string) =>
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
+
+/** The HTML flavor: the tokens as visible text, the payload on the element.
+ * Base64 keeps the JSON clear of every re-serialization the clipboard does
+ * to markup on its way through the OS. */
+export const clipboardHtml = (text: string, payload: CutClipboardPayload): string =>
+ `<span ${ATTR}="${toBase64(JSON.stringify(payload))}">${escapeHtml(text)}</span>`;
+
+/** The payload out of pasted HTML, or null for markup that is not ours. */
+export function payloadFromHtml(html: string | null | undefined): CutClipboardPayload | null {
+ if (!html) return null;
+ const m = html.match(new RegExp(`${ATTR}="([A-Za-z0-9+/=]+)"`));
+ if (!m) return null;
+ try {
+ const p = JSON.parse(fromBase64(m[1])) as Partial<CutClipboardPayload>;
+ if (p.v !== 1 || typeof p.projectId !== "string" || !Array.isArray(p.items) || !Array.isArray(p.assets)) return null;
+ return { v: 1, projectId: p.projectId, items: p.items, assets: p.assets };
+ } catch {
+ return null;
+ }
+}
+
+/** Put a copy on the system clipboard: the tokens as text, the payload in
+ * the HTML flavor. A browser without `ClipboardItem` takes the text alone,
+ * and the copy pastes within its own tab from the timeline clipboard. */
+export async function writeCutClipboard(text: string, payload: CutClipboardPayload | null): Promise<void> {
+ const clip = navigator.clipboard;
+ if (!clip) return;
+ if (payload && typeof ClipboardItem !== "undefined" && typeof clip.write === "function") {
+ const html = clipboardHtml(text, payload);
+ await clip.write([
+ new ClipboardItem({
+ "text/plain": new Blob([text], { type: "text/plain" }),
+ "text/html": new Blob([html], { type: "text/html" }),
+ }),
+ ]);
+ return;
+ }
+ await clip.writeText(text);
+}
+
+/** The items on this project's assets: what crosses, on the copies' ids. */
+const remapItems = (items: TimelineClipboardItem[], idMap: Map<string, string>): TimelineClipboardItem[] =>
+ items.map((cb) => clipboardItemAcross(cb, (id) => idMap.get(id) ?? id));
+
+/**
+ * Land a pasted payload in the open project at `at`. Same project: the items
+ * go through the timeline clipboard, the way a copy made here pastes; a card
+ * copy is left to the mention tokens beside it. Another project: the assets
+ * come across first (a copy already here is found by where it came from),
+ * then the items land on them, or the cards land the way their + button
+ * lands them. False when nothing here was pasted.
+ */
+export async function pasteCutPayload(
+ payload: CutClipboardPayload,
+ ctx: { projectId: string; at: number; library: LibraryData }
+): Promise<boolean> {
+ const { projectId, at, library } = ctx;
+ const s = useEditor.getState();
+ if (s.projectId !== projectId) return false;
+ if (payload.projectId === projectId) {
+ if (payload.items.length === 0) return false;
+ s.setClipboard(payload.items);
+ return s.paste();
+ }
+ // The editor holds this project open until the copies have landed, the way
+ // it waits for a chat tool; a switch that beats the hold leaves the
+ // landing refused with the project it was for.
+ const landed = await trackEditorTool(async () => {
+ const ref = await openReference({ kind: "project", id: payload.projectId });
+ return landReferenceAssets(ref, payload.assets, projectId);
+ });
+ if (useEditor.getState().projectId !== projectId) return false;
+ if (payload.items.length === 0) {
+ let placed = false;
+ for (const l of landed) {
+ if (l.asset.type === "font") continue;
+ if (await placeRefAtPlayhead(refFromAsset(l.asset), { projectId, library, at })) placed = true;
+ }
+ return placed || landed.length > 0;
+ }
+ const idMap = new Map(landed.map((l) => [l.sourceId, l.asset.id]));
+ const st = useEditor.getState();
+ st.setClipboard(remapItems(payload.items, idMap));
+ return st.paste();
+}
diff --git a/site/src/cut/lib/itemKinds.test.ts b/site/src/cut/lib/itemKinds.test.ts
new file mode 100644
index 00000000..9445bd75
--- /dev/null
+++ b/site/src/cut/lib/itemKinds.test.ts
@@ -0,0 +1,125 @@
+import { beforeEach, describe, expect, test } from "bun:test";
+
+import { richDoc } from "./fixtures/richDoc";
+import { ITEM_KINDS, ITEM_KIND_IDS, clipboardItemAcross, clipboardItemAssetIds, clipboardItemFor, listedAssetIds, type ItemKind, type ItemOf } from "./itemKinds";
+import { payloadAssets } from "./cutClipboard";
+import { setPlayhead } from "./playhead";
+import { assetIdsInUse, useEditor } from "./store";
+import { emptySubtitles, type MediaAsset, type Selection } from "./types";
+
+/**
+ * Every kind of item the timeline can select is one entry in the item-kind
+ * table, and the table is what copy, paste, the cross-project paste, the
+ * template rail and the media collector read. This walks the table with one
+ * sample of each kind, so an entry that cannot copy, paste, remap or leave
+ * its project fails here — and a kind added to `Selection` without an entry
+ * fails to compile, in the table and in `SAMPLES` below.
+ */
+
+const rich = richDoc();
+
+/** One of each kind out of the fixture, with its expected asset ids. */
+const SAMPLES: { [K in ItemKind]: { id: string; assets: string[] } } = {
+ clip: { id: "c0", assets: ["v0"] },
+ audio: { id: "a0", assets: ["m0"] },
+ overlay: { id: "t1", assets: ["f0"] },
+ cue: { id: "q0", assets: [] },
+ transition: { id: "tr0", assets: [] },
+};
+
+const lists = () => ({
+ clips: rich.clips!,
+ audioClips: rich.audioClips!,
+ overlays: rich.overlays!,
+ transitions: rich.transitions!,
+ subtitles: { cues: rich.subtitles!.cues },
+});
+
+describe("the item-kind table", () => {
+ test("every selectable kind has an entry and a sample", () => {
+ expect(ITEM_KIND_IDS.sort()).toEqual((Object.keys(SAMPLES) as ItemKind[]).sort());
+ });
+
+ for (const kind of ITEM_KIND_IDS) {
+ const sample = SAMPLES[kind];
+ test(`${kind}: names its assets, remaps every one of them, and clones apart`, () => {
+ const cb = clipboardItemFor(lists(), { kind, id: sample.id } as NonNullable<Selection>)!;
+ expect(cb).not.toBeNull();
+ expect(cb.kind).toBe(kind);
+ expect(clipboardItemAssetIds(cb).sort()).toEqual([...sample.assets].sort());
+ // The clone shares nothing with the list's own item.
+ const original = (ITEM_KINDS[kind].list(lists()) as { id: string }[]).find((x) => x.id === sample.id)!;
+ expect(cb.item).toEqual(original as ItemOf[typeof kind]);
+ expect(cb.item).not.toBe(original);
+ // Every id the kind reports is an id the remap rewrites, and nothing else moves.
+ const across = clipboardItemAcross(cb, (id) => `${id}-b`);
+ expect(clipboardItemAssetIds(across).sort()).toEqual(sample.assets.map((id) => `${id}-b`).sort());
+ const back = clipboardItemAcross(across, (id) => id.replace(/-b$/, ""));
+ expect(clipboardItemAssetIds(back).sort()).toEqual([...sample.assets].sort());
+ });
+ }
+
+ test("what crosses a project boundary never names an asset that stays behind", () => {
+ const clip = { ...rich.clips![0], removal: { matte: { assetId: "matte-1" } } } as unknown as ItemOf["clip"];
+ expect(ITEM_KINDS.clip.assetIds(clip)).toEqual(["v0", "matte-1"]);
+ const across = ITEM_KINDS.clip.crossProject(clip);
+ expect(ITEM_KINDS.clip.assetIds(across)).toEqual(["v0"]);
+ for (const kind of ITEM_KIND_IDS) {
+ const cb = clipboardItemFor(lists(), { kind, id: SAMPLES[kind].id } as NonNullable<Selection>)!;
+ const stays = new Set(clipboardItemAssetIds(cb));
+ for (const id of clipboardItemAssetIds(clipboardItemAcross(cb, (id) => id))) expect(stays.has(id)).toBe(true);
+ }
+ });
+
+ test("the media collector, the clipboard and the table agree on what a timeline names", () => {
+ const l = lists();
+ const fromTable = listedAssetIds(l);
+ expect(assetIdsInUse({ ...l, subtitles: { ...l.subtitles, font: rich.subtitles!.font } })).toEqual(fromTable);
+ const items = ITEM_KIND_IDS.map((kind) => clipboardItemFor(l, { kind, id: SAMPLES[kind].id } as NonNullable<Selection>)!);
+ const assets: MediaAsset[] = rich.assets.map((a) => ({ ...a, url: "" }));
+ const carried = new Set(payloadAssets(items, assets).map((a) => a.id));
+ for (const cb of items) for (const id of clipboardItemAssetIds(cb)) expect(carried.has(id)).toBe(true);
+ });
+});
+
+describe("copy and paste, kind by kind", () => {
+ beforeEach(() => {
+ useEditor.setState({
+ projectId: "rich",
+ assets: rich.assets.map((a) => ({ ...a, url: "" })),
+ clips: rich.clips!,
+ transitions: rich.transitions!,
+ audioClips: rich.audioClips!,
+ overlays: rich.overlays!,
+ subtitles: rich.subtitles!,
+ selection: null,
+ multiSelection: [],
+ });
+ setPlayhead(30);
+ });
+
+ for (const kind of ITEM_KIND_IDS) {
+ test(`${kind} copies and pastes as a new item`, () => {
+ const s = useEditor.getState();
+ const sel = { kind, id: SAMPLES[kind].id } as NonNullable<Selection>;
+ useEditor.setState({ selection: sel, multiSelection: [sel] });
+ const before = ITEM_KINDS[kind].list(s).length;
+ expect(s.copySelection()).toBe(true);
+ expect(s.paste()).toBe(true);
+ const after = useEditor.getState();
+ const list = ITEM_KINDS[kind].list(after) as { id: string }[];
+ expect(list).toHaveLength(before + 1);
+ const fresh = after.selection!;
+ expect(fresh.kind).toBe(kind);
+ expect(fresh.id).not.toBe(SAMPLES[kind].id);
+ expect(list.some((x) => x.id === fresh.id)).toBe(true);
+ });
+ }
+
+ test("the empty caption track pastes a cue too", () => {
+ useEditor.setState({ subtitles: emptySubtitles() });
+ useEditor.getState().setClipboard([{ kind: "cue", item: rich.subtitles!.cues[0] }]);
+ expect(useEditor.getState().paste()).toBe(true);
+ expect(useEditor.getState().subtitles.cues).toHaveLength(1);
+ });
+});
diff --git a/site/src/cut/lib/refCopy.ts b/site/src/cut/lib/refCopy.ts
index 1a96bf56..cdd06129 100644
--- a/site/src/cut/lib/refCopy.ts
+++ b/site/src/cut/lib/refCopy.ts
@@ -28,8 +28,9 @@ import {
refToken,
type AssetRef,
} from "./assetRef";
+import { writeCutClipboard } from "./cutClipboard";
import { clearCopiedFrame } from "./stageFrame";
-import { useEditor } from "./store";
+import { storedAssets, useEditor } from "./store";
type RefsFn = () => AssetRef[];
@@ -160,7 +161,13 @@ export const refClipboardText = (refs: AssetRef[]) => refs.map(refToken).join("
*/
export function copyRefs(refs: AssetRef[]): boolean {
if (refs.length === 0) return false;
- void navigator.clipboard?.writeText(refClipboardText(refs.map(withHandle))).catch(() => {});
+ // A project asset's card carries the asset itself beside its token, so a
+ // paste in another project brings the media across.
+ const s = useEditor.getState();
+ const own = new Set(refs.filter((r) => r.scope === "project").map((r) => r.id));
+ const assets = storedAssets(s.assets.filter((a) => own.has(a.id)));
+ const payload = s.projectId && assets.length > 0 ? { v: 1 as const, projectId: s.projectId, items: [], assets } : null;
+ void writeCutClipboard(refClipboardText(refs.map(withHandle)), payload).catch(() => {});
// The newer copy owns the clipboard: the timeline's own copy and a copied
// preview frame step aside, so ⌘V on the timeline lands what was copied.
useEditor.getState().clearClipboard();