Skip to content

Write HTML. Render video. Built for agents.

feat(studio): copy, paste and duplicate clip groups on the timeline (#4064)

Miguel Ángel0b6d1039ed0a
diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx
index 525bc6396a..153f3250c4 100644
--- a/packages/studio/src/App.tsx
+++ b/packages/studio/src/App.tsx
@@ -211,7 +211,7 @@ export function StudioApp() {
const domEditDeleteBridge: DomEditDelete = (s, o) => handleDomEditElementDeleteRef.current(s, o);
const resetKeyframesRef = useRef<() => boolean>(() => false);
const deleteSelectedKeyframesRef = useRef<() => void>(() => {});
- const { handleCopy, handlePaste, handleCut } = useClipboard({
+ const { handleCopy, handlePaste, handleCut, handleDuplicate, canPaste } = useClipboard({
projectId,
activeCompPath,
domEditSelectionRef: domEditSelectionBridgeRef,
@@ -219,7 +219,7 @@ export function StudioApp() {
writeProjectFile: fileManager.writeProjectFile,
recordEdit: editHistory.recordEdit,
reloadPreview,
- handleTimelineElementDelete: timelineEditing.handleTimelineElementDelete,
+ handleTimelineElementsDelete: timelineEditing.handleTimelineElementsDelete,
handleDomEditElementDelete: domEditDeleteBridge,
previewIframeRef,
});
@@ -240,6 +240,7 @@ export function StudioApp() {
handleCopy,
handlePaste,
handleCut,
+ handleDuplicate,
onResetKeyframes: () => resetKeyframesRef.current(),
onDeleteSelectedKeyframes: () => deleteSelectedKeyframesRef.current(),
onAfterUndoRedo: () => invalidateGsapCacheRef.current(),
@@ -538,6 +539,10 @@ export function StudioApp() {
handleTimelineElementSplit={timelineEditing.handleTimelineElementSplit}
handleRazorSplit={timelineEditing.handleRazorSplit}
handleRazorSplitAll={timelineEditing.handleRazorSplitAll}
+ onCopyClip={handleCopy}
+ onPasteClip={handlePaste}
+ onDuplicateClip={handleDuplicate}
+ canPasteClip={canPaste}
setCompIdToSrc={setCompIdToSrc}
setCompositionLoading={setCompositionLoading}
shouldShowMotionPath={shouldShowMotionPath}
diff --git a/packages/studio/src/components/EditorShell.selectionSync.test.tsx b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
index a29657abe0..736c6ede69 100644
--- a/packages/studio/src/components/EditorShell.selectionSync.test.tsx
+++ b/packages/studio/src/components/EditorShell.selectionSync.test.tsx
@@ -86,6 +86,10 @@ describe("EditorShell timeline selection sync", () => {
handleTimelineElementSplit={vi.fn()}
handleRazorSplit={vi.fn()}
handleRazorSplitAll={vi.fn()}
+ onCopyClip={vi.fn(() => false)}
+ onPasteClip={vi.fn(async () => {})}
+ onDuplicateClip={vi.fn(async () => false)}
+ canPasteClip={vi.fn(() => false)}
setCompIdToSrc={vi.fn()}
setCompositionLoading={vi.fn()}
shouldShowMotionPath={false}
diff --git a/packages/studio/src/components/EditorShell.tsx b/packages/studio/src/components/EditorShell.tsx
index f2ab2f3755..25a97c6f2f 100644
--- a/packages/studio/src/components/EditorShell.tsx
+++ b/packages/studio/src/components/EditorShell.tsx
@@ -55,6 +55,10 @@ export interface EditorShellProps extends TimelineEditCallbackDeps {
files: File[],
placement?: TimelineDropPlacement,
) => Promise<void> | void;
+ onCopyClip: () => boolean;
+ onPasteClip: () => Promise<void>;
+ onDuplicateClip: () => Promise<boolean>;
+ canPasteClip: () => boolean;
setCompIdToSrc: (map: Map<string, string>) => void;
setCompositionLoading: (loading: boolean) => void;
shouldShowMotionPath: boolean;
@@ -93,6 +97,10 @@ export function EditorShell({
handleTimelineElementSplit,
handleRazorSplit,
handleRazorSplitAll,
+ onCopyClip,
+ onPasteClip,
+ onDuplicateClip,
+ canPasteClip,
setCompIdToSrc,
setCompositionLoading,
shouldShowMotionPath,
@@ -181,6 +189,10 @@ export function EditorShell({
onBlockDrop={handleTimelineBlockDrop}
onCompositionDrop={handleTimelineCompositionDrop}
onDeleteElement={handleTimelineElementDelete}
+ onCopyClip={onCopyClip}
+ onPasteClip={onPasteClip}
+ onDuplicateClip={onDuplicateClip}
+ canPasteClip={canPasteClip}
previewOverlay={
<PreviewOverlays
shouldShowMotionPath={shouldShowMotionPath}
@@ -219,6 +231,10 @@ interface EditorShellBodyProps {
placement: TimelineDropPlacement,
) => Promise<void> | void;
onDeleteElement: (element: TimelineElement) => Promise<void> | void;
+ onCopyClip: () => boolean;
+ onPasteClip: () => Promise<void>;
+ onDuplicateClip: () => Promise<boolean>;
+ canPasteClip: () => boolean;
}
function EditorShellBody({
@@ -235,6 +251,10 @@ function EditorShellBody({
onBlockDrop,
onCompositionDrop,
onDeleteElement,
+ onCopyClip,
+ onPasteClip,
+ onDuplicateClip,
+ canPasteClip,
}: EditorShellBodyProps) {
const { compositionStack, updateCompositionStack, containerRef } = useNLEContext();
@@ -289,6 +309,10 @@ function EditorShellBody({
onBlockDrop={onBlockDrop}
onCompositionDrop={onCompositionDrop}
onDeleteElement={onDeleteElement}
+ onCopyClip={onCopyClip}
+ onPasteClip={onPasteClip}
+ onDuplicateClip={onDuplicateClip}
+ canPasteClip={canPasteClip}
onSelectTimelineElement={onSelectTimelineElement}
timelineFooter={
captionEditMode ? (
diff --git a/packages/studio/src/components/editor/SnapToolbar.test.tsx b/packages/studio/src/components/editor/SnapToolbar.test.tsx
index aa8650e5a5..4ec7f89ee3 100644
--- a/packages/studio/src/components/editor/SnapToolbar.test.tsx
+++ b/packages/studio/src/components/editor/SnapToolbar.test.tsx
@@ -53,6 +53,7 @@ function AppHotkeyHarness() {
handleCopy: vi.fn(() => false),
handlePaste: vi.fn(async () => undefined),
handleCut: vi.fn(async () => false),
+ handleDuplicate: vi.fn(async () => false),
onResetKeyframes: vi.fn(() => false),
onDeleteSelectedKeyframes: vi.fn(),
});
diff --git a/packages/studio/src/components/nle/TimelinePane.tsx b/packages/studio/src/components/nle/TimelinePane.tsx
index ca40802056..d93fcd9ea7 100644
--- a/packages/studio/src/components/nle/TimelinePane.tsx
+++ b/packages/studio/src/components/nle/TimelinePane.tsx
@@ -102,6 +102,12 @@ export interface TimelinePaneProps {
) => Promise<void> | void;
onBlockedEditAttempt?: (element: TimelineElement, intent: BlockedTimelineEditIntent) => void;
onSelectTimelineElement?: (element: TimelineElement | null) => void;
+ /** Copy/paste/duplicate act on the store's own selection, not a passed
+ * element, so unlike onDeleteElement they need no composition-basis wrapper. */
+ onCopyClip?: () => boolean;
+ onPasteClip?: () => Promise<void>;
+ onDuplicateClip?: () => Promise<boolean>;
+ canPasteClip?: () => boolean;
}
// fallow-ignore-next-line complexity
@@ -116,6 +122,10 @@ export function TimelinePane({
onCompositionDrop,
onBlockedEditAttempt,
onSelectTimelineElement,
+ onCopyClip,
+ onPasteClip,
+ onDuplicateClip,
+ canPasteClip,
}: TimelinePaneProps) {
const {
seek,
@@ -288,6 +298,10 @@ export function TimelinePane({
onBlockedEditAttempt={onBlockedEditAttempt}
onSplitElement={handleSplitElement}
onSelectElement={onSelectTimelineElement}
+ onCopyClip={onCopyClip}
+ onPasteClip={onPasteClip}
+ onDuplicateClip={onDuplicateClip}
+ canPasteClip={canPasteClip}
/>
</div>
{timelineFooter && <div className="flex-shrink-0">{timelineFooter}</div>}
diff --git a/packages/studio/src/hooks/appHotkeysDispatch.ts b/packages/studio/src/hooks/appHotkeysDispatch.ts
index d0acbd67a7..6c4e62991e 100644
--- a/packages/studio/src/hooks/appHotkeysDispatch.ts
+++ b/packages/studio/src/hooks/appHotkeysDispatch.ts
@@ -46,6 +46,7 @@ export interface HotkeyCallbacks {
handleCopy: () => boolean;
handlePaste: () => Promise<void>;
handleCut: () => Promise<boolean>;
+ handleDuplicate: () => Promise<boolean>;
onResetKeyframes: () => boolean;
onDeleteSelectedKeyframes: () => void;
onToggleRecording?: () => void;
@@ -127,6 +128,16 @@ export function dispatchModifierKey(
}
return true;
}
+ if (key === "d") {
+ // Always own this key here, even with nothing selected — otherwise the
+ // browser's own Cmd+D (bookmark this page) fires over the editor.
+ event.preventDefault();
+ if (usePlayerStore.getState().selectedElementId) {
+ trackStudioEvent("keyboard_shortcut", { action: "duplicate" });
+ void cb.handleDuplicate();
+ }
+ return true;
+ }
}
return false;
}
diff --git a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
index 40ce5e0d6c..fb9979c8b4 100644
--- a/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
+++ b/packages/studio/src/hooks/useAppHotkeys.textEditing.test.tsx
@@ -93,6 +93,7 @@ function Harness() {
handleCopy: vi.fn(() => false),
handlePaste: vi.fn(async () => undefined),
handleCut: vi.fn(async () => false),
+ handleDuplicate: vi.fn(async () => false),
onResetKeyframes: vi.fn(() => false),
onDeleteSelectedKeyframes: keyframeDelete,
});
diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts
index a7d138dcbd..79101d9220 100644
--- a/packages/studio/src/hooks/useAppHotkeys.ts
+++ b/packages/studio/src/hooks/useAppHotkeys.ts
@@ -114,6 +114,7 @@ interface UseAppHotkeysParams {
handleCopy: () => boolean;
handlePaste: () => Promise<void>;
handleCut: () => Promise<boolean>;
+ handleDuplicate: () => Promise<boolean>;
onResetKeyframes: () => boolean;
onDeleteSelectedKeyframes: () => void;
onAfterUndoRedo?: () => void;
@@ -150,6 +151,7 @@ export function useAppHotkeys({
handleCopy,
handlePaste,
handleCut,
+ handleDuplicate,
onResetKeyframes,
onDeleteSelectedKeyframes,
onAfterUndoRedo,
@@ -255,6 +257,7 @@ export function useAppHotkeys({
handleCopy,
handlePaste,
handleCut,
+ handleDuplicate,
onResetKeyframes,
onDeleteSelectedKeyframes,
onToggleRecording,
diff --git a/packages/studio/src/hooks/useClipboard.test.ts b/packages/studio/src/hooks/useClipboard.test.ts
new file mode 100644
index 0000000000..0f13256a3d
--- /dev/null
+++ b/packages/studio/src/hooks/useClipboard.test.ts
@@ -0,0 +1,234 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from "vitest";
+import { pasteTimelineClips, resolveFreeTrack, type PlacedClip } from "./useClipboard";
+import { extendRootDurationInSource } from "../utils/rootDuration";
+import type { TimelineClipboardClip } from "../utils/clipboardPayload";
+import type { TimelineElement } from "../player";
+
+const ROOT =
+ '<div id="claude-paper" data-composition-id="claude-paper" data-start="0" data-duration="10"></div>';
+
+function clip(id: string, start: number, duration: number, track: number): TimelineClipboardClip {
+ return {
+ html: `<audio id="${id}" src="typenew.mp3" data-start="${start}" data-duration="${duration}" data-track-index="${track}"></audio>`,
+ start,
+ duration,
+ track,
+ };
+}
+
+function liveElement(track: number, start: number, duration: number): TimelineElement {
+ return { id: `x-${track}`, tag: "audio", start, duration, track, authoredTrack: track };
+}
+
+describe("resolveFreeTrack", () => {
+ it("keeps the preferred track when nothing occupies it", () => {
+ const track = resolveFreeTrack({ track: 5, start: 10, duration: 1 }, []);
+ expect(track).toBe(5);
+ });
+
+ it("bumps to a new track when the preferred one overlaps in time", () => {
+ const taken: PlacedClip[] = [{ track: 5, start: 10.2, duration: 0.5 }];
+ const track = resolveFreeTrack({ track: 5, start: 10, duration: 1 }, taken);
+ expect(track).toBe(6);
+ });
+
+ it("keeps the preferred track when an occupant on it does not overlap in time", () => {
+ const taken: PlacedClip[] = [{ track: 5, start: 50, duration: 1 }];
+ const track = resolveFreeTrack({ track: 5, start: 10, duration: 1 }, taken);
+ expect(track).toBe(5);
+ });
+
+ it("picks the next track above the highest taken one, not just +1 from preferred", () => {
+ const taken: PlacedClip[] = [
+ { track: 5, start: 10, duration: 1 },
+ { track: 9, start: 30, duration: 1 },
+ ];
+ const track = resolveFreeTrack({ track: 5, start: 10.1, duration: 1 }, taken);
+ expect(track).toBe(10);
+ });
+});
+
+describe("pasteTimelineClips", () => {
+ it("anchors a single clip's data-start at the anchor time and keeps its track", () => {
+ const { content, ids } = pasteTimelineClips(ROOT, [clip("sfx-23", 21.61, 0.57, 132)], 40, []);
+ expect(content).toContain('data-start="40"');
+ expect(content).toContain('data-track-index="132"');
+ expect(ids).toEqual(["sfx-23"]);
+ });
+
+ it("preserves each clip's relative offset from the group's earliest clip", () => {
+ const clips = [
+ clip("sfx-23", 21.61, 0.57, 132),
+ clip("sfx-24", 21.73, 0.57, 133),
+ clip("sfx-25", 21.84, 0.57, 134),
+ ];
+ const { content } = pasteTimelineClips(ROOT, clips, 40, []);
+ // Offsets from the earliest clip (21.61): 0, 0.12, 0.23 -> 40, 40.12, 40.23
+ expect(content).toContain('id="sfx-23" src="typenew.mp3" data-start="40"');
+ expect(content).toContain('id="sfx-24" src="typenew.mp3" data-start="40.12"');
+ expect(content).toContain('id="sfx-25" src="typenew.mp3" data-start="40.23"');
+ });
+
+ it("moves a clip to a new track when its original track is occupied at the target time", () => {
+ const live = [liveElement(132, 40, 0.57)];
+ const { content } = pasteTimelineClips(ROOT, [clip("sfx-23", 21.61, 0.57, 132)], 40, live);
+ expect(content).not.toContain('data-track-index="132"');
+ expect(content).toMatch(/data-track-index="133"/);
+ });
+
+ it("strips the copied data-hf-id so a fresh one mints on next save", () => {
+ const clipWithHfId: TimelineClipboardClip = {
+ html: '<audio data-hf-id="hf-75o7" id="sfx-type-0" src="typenew.mp3" data-start="7.8" data-duration="0.57" data-track-index="109"></audio>',
+ start: 7.8,
+ duration: 0.57,
+ track: 109,
+ };
+ const { content } = pasteTimelineClips(ROOT, [clipWithHfId], 40, []);
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("strips a nested descendant's data-hf-id too, not just the root's", () => {
+ // A composition-instance clip's descendants carry their own hf-ids; a
+ // clone must remint all of them, not just the root, or the descendants
+ // collide with their originals the same way the root would.
+ const nested: TimelineClipboardClip = {
+ html: '<div data-hf-id="hf-root" id="comp-1" data-start="7.8" data-duration="0.57" data-track-index="109"><span data-hf-id="hf-child"></span></div>',
+ start: 7.8,
+ duration: 0.57,
+ track: 109,
+ };
+ const { content } = pasteTimelineClips(ROOT, [nested], 40, []);
+ expect(content).not.toContain("hf-root");
+ expect(content).not.toContain("hf-child");
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("does not strip text content that happens to contain the data-hf-id string", () => {
+ const withText: TimelineClipboardClip = {
+ html: '<div id="cap-1" data-start="7.8" data-duration="0.57" data-track-index="109"><span>talking about data-hf-id="hf-xyz" in my video</span></div>',
+ start: 7.8,
+ duration: 0.57,
+ track: 109,
+ };
+ const { content } = pasteTimelineClips(ROOT, [withText], 40, []);
+ expect(content).toContain('talking about data-hf-id="hf-xyz" in my video');
+ });
+
+ it("bumps the second clip in a batch off the first clip's own new track when their offsets collide", () => {
+ // Both clips start life a track apart but paste to overlapping times on
+ // the SAME track, so the second must dodge the first's placement, not
+ // just the live elements it was checked against.
+ const clips = [clip("sfx-23", 21.61, 0.57, 132), clip("sfx-24", 21.7, 0.57, 132)];
+ const { content } = pasteTimelineClips(ROOT, clips, 40, []);
+ expect(content).toContain(
+ 'id="sfx-23" src="typenew.mp3" data-start="40" data-duration="0.57" data-track-index="132"',
+ );
+ expect(content).toContain(
+ 'id="sfx-24" src="typenew.mp3" data-start="40.09" data-duration="0.57" data-track-index="133"',
+ );
+ });
+
+ it("dedupes an id that already exists in the target file", () => {
+ const withExisting = ROOT.replace(
+ "</div>",
+ '<audio id="sfx-23" data-start="1" data-duration="1" data-track-index="0"></audio></div>',
+ );
+ const { content, ids } = pasteTimelineClips(
+ withExisting,
+ [clip("sfx-23", 21.61, 0.57, 132)],
+ 40,
+ [],
+ );
+ expect(ids[0]).not.toBe("sfx-23");
+ expect(ids[0]).toMatch(/^sfx-23-\d+$/);
+ expect(content).toContain(`id="${ids[0]}"`);
+ });
+
+ it("strips a single-quoted data-hf-id, not just a double-quoted one", () => {
+ const singleQuoted: TimelineClipboardClip = {
+ html: '<audio data-hf-id=\'hf-75o7\' id="sfx-type-0" src="typenew.mp3" data-start="7.8" data-duration="0.57" data-track-index="109"></audio>',
+ start: 7.8,
+ duration: 0.57,
+ track: 109,
+ };
+ const { content } = pasteTimelineClips(ROOT, [singleQuoted], 40, []);
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("strips data-hf-id even when an earlier attribute value contains a literal >", () => {
+ // A `>` inside title's value would close a bracket-scoped tag regex
+ // early, leaving data-hf-id (which comes after it) outside the matched
+ // span and unstripped. A real parser doesn't have this failure mode.
+ const gtInAttr: TimelineClipboardClip = {
+ html: '<div title="a > b" id="cap-1" data-hf-id="hf-xyz" data-start="7.8" data-duration="0.57" data-track-index="109"></div>',
+ start: 7.8,
+ duration: 0.57,
+ track: 109,
+ };
+ const { content } = pasteTimelineClips(ROOT, [gtInAttr], 40, []);
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("still strips data-hf-id from bare text with no element root", () => {
+ const noRoot: TimelineClipboardClip = {
+ html: 'text mentioning data-hf-id="hf-leak" with no tag at all',
+ start: 0,
+ duration: 1,
+ track: 0,
+ };
+ const { content } = pasteTimelineClips(ROOT, [noRoot], 0, []);
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("still strips data-hf-id from a tag the HTML parser hoists out of body (e.g. title)", () => {
+ // A <title> never reaches DOMParser's body, so stripHfIds's DOM walk sees
+ // no root element here -- this exercises the regex fallback, not the walk.
+ const hoisted: TimelineClipboardClip = {
+ html: '<title data-hf-id="hf-leak">x</title>',
+ start: 0,
+ duration: 1,
+ track: 0,
+ };
+ const { content } = pasteTimelineClips(ROOT, [hoisted], 0, []);
+ expect(content).not.toContain("data-hf-id");
+ });
+
+ it("captures the root's own id, not a data-id that happens to precede it", () => {
+ const withDataId: TimelineClipboardClip = {
+ html: '<audio data-id="not-the-id" id="sfx-23" src="typenew.mp3" data-start="21.61" data-duration="0.57" data-track-index="132"></audio>',
+ start: 21.61,
+ duration: 0.57,
+ track: 132,
+ };
+ const { ids } = pasteTimelineClips(ROOT, [withDataId], 40, []);
+ expect(ids).toEqual(["sfx-23"]);
+ });
+
+ it("reports the furthest clip end across the whole batch as requiredEnd, not just the last clip's", () => {
+ // The batch is placed in order sfx-23, sfx-24, sfx-25, but sfx-24 ends up
+ // the furthest forward once offsets are applied; requiredEnd must track
+ // the max across all placed clips, not whichever one the loop saw last.
+ const clips = [
+ clip("sfx-23", 21.61, 0.57, 132),
+ clip("sfx-24", 21.9, 5, 133),
+ clip("sfx-25", 21.73, 0.1, 134),
+ ];
+ const { requiredEnd } = pasteTimelineClips(ROOT, clips, 40, []);
+ expect(requiredEnd).toBeCloseTo(40.29 + 5, 2);
+ });
+});
+
+describe("pasteTimelineClips + extendRootDurationInSource", () => {
+ it("grows the root composition's duration when a paste lands past its current end", () => {
+ const pasted = pasteTimelineClips(ROOT, [clip("sfx-23", 21.61, 0.57, 132)], 40, []);
+ const extended = extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ expect(extended).toContain('data-duration="40.57"');
+ });
+
+ it("leaves the root composition's duration unchanged when the paste fits inside it", () => {
+ const pasted = pasteTimelineClips(ROOT, [clip("sfx-23", 1, 0.5, 132)], 2, []);
+ const extended = extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ expect(extended).toContain('data-duration="10"');
+ });
+});
diff --git a/packages/studio/src/hooks/useClipboard.ts b/packages/studio/src/hooks/useClipboard.ts
index 6baf87c7cf..ee546d99ea 100644
--- a/packages/studio/src/hooks/useClipboard.ts
+++ b/packages/studio/src/hooks/useClipboard.ts
@@ -2,14 +2,23 @@ import { useCallback, useRef } from "react";
import type { TimelineElement } from "../player";
import { usePlayerStore } from "../player";
import type { DomEditSelection } from "../components/editor/domEditing";
-import { type ClipboardPayload, deduplicateIds, insertAsSibling } from "../utils/clipboardPayload";
+import {
+ type ClipboardPayload,
+ type TimelineClipboardClip,
+ ID_ATTR_RE,
+ deduplicateIds,
+ insertAsSibling,
+} from "../utils/clipboardPayload";
import { collectHtmlIds } from "../utils/studioHelpers";
import { insertTimelineAssetIntoSource } from "../utils/timelineAssetDrop";
+import { extendRootDurationInSource } from "../utils/rootDuration";
import { saveProjectFilesWithHistory } from "../utils/studioFileHistory";
import type { EditHistoryKind } from "../utils/editHistory";
import { formatTimelineAttributeNumber } from "../player/components/timelineEditing";
import { findElementForSelection } from "../components/editor/domEditingElement";
-import { readFileContent } from "./timelineEditingHelpers";
+import { findTimelineElementInIframe, readFileContent } from "./timelineEditingHelpers";
+import { buildTimelineElementKey } from "../player/lib/timelineElementHelpers";
+import { timeRangesOverlap } from "../player/components/timelineCollision";
interface RecordEditInput {
label: string;
@@ -26,11 +35,34 @@ interface UseClipboardOptions {
writeProjectFile: (path: string, content: string) => Promise<void>;
recordEdit: (input: RecordEditInput) => Promise<void>;
reloadPreview: () => void;
- handleTimelineElementDelete: (element: TimelineElement) => Promise<void>;
+ handleTimelineElementsDelete: (elements: TimelineElement[]) => Promise<void>;
handleDomEditElementDelete: (selection: DomEditSelection) => Promise<void>;
previewIframeRef: React.MutableRefObject<HTMLIFrameElement | null>;
}
+/** The timeline element(s) a copy/cut/duplicate acts on: the multi-selection
+ * when one is active, else the single primary selection. */
+function getSelectedElements(): TimelineElement[] {
+ const { selectedElementId, selectedElementIds, elements } = usePlayerStore.getState();
+ if (!selectedElementId) return [];
+ const ids = selectedElementIds.size > 1 ? selectedElementIds : new Set([selectedElementId]);
+ return elements.filter((el) => ids.has(el.key ?? el.id));
+}
+
+function elementKey(domId: string, sourceFile: string): string {
+ return buildTimelineElementKey({ id: domId, fallbackIndex: 0, domId, sourceFile });
+}
+
+/** "Paste clip" / "Paste clips" — the edit-history label, no count shown. */
+function clipLabel(verb: string, clipCount: number): string {
+ return `${verb} ${clipCount > 1 ? "clips" : "clip"}`;
+}
+
+/** "Pasted clip" / "Pasted 3 clips" — the toast message, count shown once plural. */
+function clipToast(verbPast: string, clipCount: number): string {
+ return clipCount > 1 ? `${verbPast} ${clipCount} clips` : `${verbPast} clip`;
+}
+
function getElementOuterHtml(
iframeRef: React.MutableRefObject<HTMLIFrameElement | null>,
selection: DomEditSelection,
@@ -47,6 +79,94 @@ function getElementOuterHtml(
return findElementForSelection(doc, selection, activeCompositionPath)?.outerHTML ?? null;
}
+export interface PlacedClip {
+ track: number;
+ start: number;
+ duration: number;
+}
+
+function tracksOverlap(a: PlacedClip, b: PlacedClip): boolean {
+ return (
+ a.track === b.track &&
+ timeRangesOverlap(a.start, a.start + a.duration, b.start, b.start + b.duration)
+ );
+}
+
+/** CapCut: keeps the preferred track if free at the new time, else the next
+ * unused track index. Exported so placement is tested with values directly. */
+export function resolveFreeTrack(preferred: PlacedClip, taken: readonly PlacedClip[]): number {
+ if (!taken.some((t) => tracksOverlap(preferred, t))) return preferred.track;
+ const maxTrack = taken.reduce((max, t) => Math.max(max, t.track), preferred.track);
+ return maxTrack + 1;
+}
+
+/** Strips data-hf-id from the root and every descendant so a clone re-mints
+ * its own. DOMParser, not a bracket-scoped regex, so a `>` inside an earlier
+ * attribute value or a single-quoted id can't defeat the strip. */
+function stripHfIds(html: string, parser: DOMParser): string {
+ const root = parser.parseFromString(html, "text/html").body.firstElementChild;
+ if (!root) {
+ // A tag the HTML parser hoists out of <body> (title/meta/style/base/link)
+ // never reaches the walk above — fall back to a direct strip so
+ // data-hf-id still can't survive, even though no real clip root is one
+ // of these tags today.
+ return html.replace(/\sdata-hf-id=("[^"]*"|'[^']*')/g, "");
+ }
+ root.querySelectorAll("[data-hf-id]").forEach((el) => el.removeAttribute("data-hf-id"));
+ root.removeAttribute("data-hf-id");
+ return root.outerHTML;
+}
+
+/** Shared insertion path for paste and duplicate, anchored at the playhead or
+ * the selection's end respectively. Returns the final ids so the caller can
+ * select what it just placed, and the furthest end any clip lands at so the
+ * caller can grow the root composition's duration to cover it. */
+export function pasteTimelineClips(
+ content: string,
+ clips: readonly TimelineClipboardClip[],
+ anchorTime: number,
+ liveElements: readonly TimelineElement[],
+): { content: string; ids: string[]; requiredEnd: number } {
+ const groupMinStart = Math.min(...clips.map((c) => c.start));
+ let existingIds = collectHtmlIds(content);
+ const taken: PlacedClip[] = liveElements.map((el) => ({
+ track: el.authoredTrack ?? el.track,
+ start: el.start,
+ duration: el.duration,
+ }));
+ const ids: string[] = [];
+ let result = content;
+ let requiredEnd = 0;
+ const domParser = new DOMParser();
+ for (const clip of clips) {
+ const stripped = stripHfIds(clip.html, domParser);
+ const deduped = deduplicateIds(stripped, existingIds);
+ existingIds = existingIds.concat(collectHtmlIds(deduped));
+ const newStart = anchorTime + (clip.start - groupMinStart);
+ const newTrack = resolveFreeTrack(
+ { track: clip.track, start: newStart, duration: clip.duration },
+ taken,
+ );
+ taken.push({ track: newTrack, start: newStart, duration: clip.duration });
+ requiredEnd = Math.max(requiredEnd, newStart + clip.duration);
+
+ // Only rewrite the outermost opening tag. The non-global regex matches
+ // the first occurrence, which is always in the root tag since outerHTML
+ // starts with it. Nested clips keep their own timing and track.
+ const rootTagEnd = deduped.indexOf(">");
+ const rootTag = rootTagEnd >= 0 ? deduped.slice(0, rootTagEnd + 1) : deduped;
+ const patchedRootTag = rootTag
+ .replace(/data-start="[^"]*"/, `data-start="${formatTimelineAttributeNumber(newStart)}"`)
+ .replace(/data-track-index="[^"]*"/, `data-track-index="${newTrack}"`);
+ const withPatched = patchedRootTag + deduped.slice(rootTagEnd + 1);
+ result = insertTimelineAssetIntoSource(result, withPatched);
+
+ const id = patchedRootTag.match(ID_ATTR_RE)?.[1];
+ if (id) ids.push(id);
+ }
+ return { content: result, ids, requiredEnd };
+}
+
export function useClipboard({
projectId,
activeCompPath,
@@ -55,7 +175,7 @@ export function useClipboard({
writeProjectFile,
recordEdit,
reloadPreview,
- handleTimelineElementDelete,
+ handleTimelineElementsDelete,
handleDomEditElementDelete,
previewIframeRef,
}: UseClipboardOptions) {
@@ -63,47 +183,50 @@ export function useClipboard({
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
- // The copy-mode branches predate this change; this diff only replaces its
- // duplicated DOM lookup with the canonical composition-aware resolver.
- // fallow-ignore-next-line complexity
- const handleCopy = useCallback((): boolean => {
- const { selectedElementId, elements } = usePlayerStore.getState();
-
- // Timeline clip copy
- if (selectedElementId) {
- const element = elements.find((el) => (el.key ?? el.id) === selectedElementId);
- if (!element) return false;
- const targetPath = element.sourceFile || activeCompPath || "index.html";
-
- let html: string | null = null;
- try {
- const doc = previewIframeRef.current?.contentDocument;
- if (doc) {
- html =
- findElementForSelection(
- doc,
- {
- hfId: element.hfId,
- id: element.domId,
- selector: element.selector,
- selectorIndex: element.selectorIndex,
- sourceFile: targetPath,
- },
- activeCompPath,
- )?.outerHTML ?? null;
- }
- } catch {
- // cross-origin frame
- }
+ // Resolved through findTimelineElementInIframe, the same composition-aware
+ // lookup every other timeline editor uses — unlike findElementForSelection,
+ // it can address a composition-instance clip's root.
+ const collectSelectedClips = useCallback((): {
+ elements: TimelineElement[];
+ clips: TimelineClipboardClip[];
+ } | null => {
+ const selected = getSelectedElements();
+ if (selected.length === 0) return null;
+ const clips: TimelineClipboardClip[] = [];
+ for (const element of selected) {
+ const html =
+ findTimelineElementInIframe(previewIframeRef.current, element, activeCompPath)?.outerHTML ??
+ null;
if (!html) {
- showToast("Unable to copy this element.", "info");
- return false;
+ showToast(`Unable to copy "${element.label ?? element.id}".`, "info");
+ return null;
}
+ clips.push({
+ html,
+ start: element.start,
+ duration: element.duration,
+ // authoredTrack, not track: `track` can be a display-lane number
+ // remapped by normalizeToZones, and writing THAT into data-track-index
+ // re-targets the wrong track in the sparse authored file.
+ track: element.authoredTrack ?? element.track,
+ });
+ }
+ return { elements: selected, clips };
+ }, [activeCompPath, previewIframeRef, showToast]);
- const payload: ClipboardPayload = { kind: "timeline-clip", html, sourceFile: targetPath };
- clipboardRef.current = payload;
- showToast("Copied clip", "info");
+ // Two independent copy modes (timeline clip vs DOM element) in one handler.
+ // fallow-ignore-next-line complexity
+ const handleCopy = useCallback((): boolean => {
+ if (usePlayerStore.getState().selectedElementId) {
+ const result = collectSelectedClips();
+ if (!result) return false;
+ const targetPath = result.elements[0]?.sourceFile || activeCompPath || "index.html";
+ clipboardRef.current = { kind: "timeline-clip", clips: result.clips, sourceFile: targetPath };
+ showToast(
+ result.clips.length > 1 ? `Copied ${result.clips.length} clips` : "Copied clip",
+ "info",
+ );
return true;
}
@@ -116,21 +239,23 @@ export function useClipboard({
return false;
}
const targetPath = domSelection.sourceFile || activeCompPath || "index.html";
- const payload: ClipboardPayload = {
+ clipboardRef.current = {
kind: "dom-element",
html,
sourceFile: targetPath,
originSelector: domSelection.selector,
originSelectorIndex: domSelection.selectorIndex,
};
- clipboardRef.current = payload;
showToast("Copied element", "info");
return true;
}
+ showToast("Nothing selected to copy.", "info");
return false;
- }, [activeCompPath, domEditSelectionRef, previewIframeRef, showToast]);
+ }, [activeCompPath, collectSelectedClips, domEditSelectionRef, previewIframeRef, showToast]);
+ // Two independent paste modes (timeline clip vs DOM element) behind one guarded save.
+ // fallow-ignore-next-line complexity
const handlePaste = useCallback(async () => {
const payload = clipboardRef.current;
if (!payload) {
@@ -143,24 +268,19 @@ export function useClipboard({
const targetPath = activeCompPath || "index.html";
try {
const originalContent = await readFileContent(pid, targetPath);
- const existingIds = collectHtmlIds(originalContent);
- const deduped = deduplicateIds(payload.html, existingIds);
-
let patchedContent: string;
+ let pastedIds: string[] = [];
+
if (payload.kind === "timeline-clip") {
- // Only rewrite data-start on the outermost opening tag. The non-global
- // regex matches the first occurrence, which is always in the root tag
- // since outerHTML starts with it. Nested clips keep their own timing.
- const { currentTime } = usePlayerStore.getState();
- const rootTagEnd = deduped.indexOf(">");
- const rootTag = rootTagEnd >= 0 ? deduped.slice(0, rootTagEnd + 1) : deduped;
- const patchedRootTag = rootTag.replace(
- /data-start="[^"]*"/,
- `data-start="${formatTimelineAttributeNumber(currentTime)}"`,
- );
- const withNewStart = patchedRootTag + deduped.slice(rootTagEnd + 1);
- patchedContent = insertTimelineAssetIntoSource(originalContent, withNewStart);
+ const { currentTime, elements } = usePlayerStore.getState();
+ const pasted = pasteTimelineClips(originalContent, payload.clips, currentTime, elements);
+ // A clip pasted past the current composition end would exist in the
+ // file but never appear on the timeline or in playback/export (the
+ // root's data-duration is what actually bounds the render).
+ patchedContent = extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ pastedIds = pasted.ids;
} else {
+ const deduped = deduplicateIds(payload.html, collectHtmlIds(originalContent));
patchedContent = insertAsSibling(
originalContent,
deduped,
@@ -169,9 +289,14 @@ export function useClipboard({
);
}
+ const label =
+ payload.kind === "timeline-clip"
+ ? clipLabel("Paste", payload.clips.length)
+ : "Paste element";
+
await saveProjectFilesWithHistory({
projectId: pid,
- label: payload.kind === "timeline-clip" ? "Paste clip" : "Paste element",
+ label,
kind: "timeline" as EditHistoryKind,
files: { [targetPath]: patchedContent },
readFile: async () => originalContent,
@@ -179,25 +304,92 @@ export function useClipboard({
recordEdit,
});
+ // CapCut: the pasted clip(s) become the selection; the playhead does not
+ // move. reloadPreview is a bare refresh-key bump with no selection
+ // snapshot of its own; calling setSelection before it is what makes the
+ // post-reload store state land on the pasted ids instead of stale ones.
+ if (pastedIds.length > 0) {
+ usePlayerStore.getState().setSelection(pastedIds.map((id) => elementKey(id, targetPath)));
+ }
reloadPreview();
- showToast(payload.kind === "timeline-clip" ? "Pasted clip" : "Pasted element", "info");
+ showToast(
+ payload.kind === "timeline-clip"
+ ? clipToast("Pasted", payload.clips.length)
+ : "Pasted element",
+ "info",
+ );
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to paste";
showToast(message);
}
}, [activeCompPath, recordEdit, reloadPreview, showToast, writeProjectFile]);
+ // Duplicates the current selection in place, immediately after it, without
+ // touching the clipboard — a pending copy must survive a Cmd+D. Shares
+ // pasteTimelineClips with handlePaste; only the anchor and clip source
+ // differ (the selection's own end here, the playhead there).
+ const handleDuplicate = useCallback(async (): Promise<boolean> => {
+ const result = collectSelectedClips();
+ if (!result) return false;
+ const pid = projectIdRef.current;
+ if (!pid) return false;
+
+ const { elements, clips } = result;
+ const targetPath = elements[0]?.sourceFile || activeCompPath || "index.html";
+ const anchorTime = Math.max(...elements.map((el) => el.start + el.duration));
+
+ try {
+ const originalContent = await readFileContent(pid, targetPath);
+ const liveElements = usePlayerStore.getState().elements;
+ const pasted = pasteTimelineClips(originalContent, clips, anchorTime, liveElements);
+ const patchedContent = extendRootDurationInSource(pasted.content, pasted.requiredEnd);
+ const ids = pasted.ids;
+
+ await saveProjectFilesWithHistory({
+ projectId: pid,
+ label: clipLabel("Duplicate", clips.length),
+ kind: "timeline" as EditHistoryKind,
+ files: { [targetPath]: patchedContent },
+ readFile: async () => originalContent,
+ writeFile: writeProjectFile,
+ recordEdit,
+ });
+
+ // The duplicate becomes the selection, mirroring CapCut's own paste
+ // convention — there is no CapCut Duplicate to match directly (Cmd+D is
+ // a no-op there); this is our own choice for consistency with paste.
+ // Select before reloading, same reason as handlePaste above.
+ if (ids.length > 0) {
+ usePlayerStore.getState().setSelection(ids.map((id) => elementKey(id, targetPath)));
+ }
+ reloadPreview();
+ showToast(clipToast("Duplicated", clips.length), "info");
+ return true;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : "Failed to duplicate";
+ showToast(message);
+ return false;
+ }
+ }, [
+ activeCompPath,
+ collectSelectedClips,
+ recordEdit,
+ reloadPreview,
+ showToast,
+ writeProjectFile,
+ ]);
+
const handleCut = useCallback(async (): Promise<boolean> => {
+ const selected = getSelectedElements();
const copied = handleCopy();
if (!copied) return false;
- const { selectedElementId, elements } = usePlayerStore.getState();
- if (selectedElementId) {
- const element = elements.find((el) => (el.key ?? el.id) === selectedElementId);
- if (element) {
- await handleTimelineElementDelete(element);
- return true;
- }
+ if (selected.length > 0) {
+ // One call for the whole selection, not one per element: the batched
+ // delete writes and records history once, so a multi-clip Cmd+X undoes
+ // in a single Cmd+Z instead of needing one per clip.
+ await handleTimelineElementsDelete(selected);
+ return true;
}
const domSelection = domEditSelectionRef.current;
@@ -206,7 +398,9 @@ export function useClipboard({
return true;
}
return true;
- }, [handleCopy, domEditSelectionRef, handleTimelineElementDelete, handleDomEditElementDelete]);
+ }, [handleCopy, domEditSelectionRef, handleTimelineElementsDelete, handleDomEditElementDelete]);
+
+ const canPaste = useCallback(() => clipboardRef.current !== null, []);
- return { handleCopy, handlePaste, handleCut };
+ return { handleCopy, handlePaste, handleCut, handleDuplicate, canPaste };
}
diff --git a/packages/studio/src/player/components/ClipContextMenu.tsx b/packages/studio/src/player/components/ClipContextMenu.tsx
index c7ccde2d12..cd705ec471 100644
--- a/packages/studio/src/player/components/ClipContextMenu.tsx
+++ b/packages/studio/src/player/components/ClipContextMenu.tsx
@@ -1,6 +1,6 @@
import { memo } from "react";
import { createPortal } from "react-dom";
-import type { TimelineElement } from "../store/playerStore";
+import { usePlayerStore, type TimelineElement } from "../store/playerStore";
import { canSplitElement } from "../../utils/timelineElementSplit";
import { useContextMenuDismiss } from "../../hooks/useContextMenuDismiss";
import { useMenuKeyboardNav } from "./menuKeyboardNav";
@@ -13,8 +13,14 @@ interface ClipContextMenuProps {
onClose: () => void;
onSplit: (element: TimelineElement, splitTime: number) => void;
onDelete: (element: TimelineElement) => void;
+ onCopy?: () => boolean;
+ onPaste?: () => Promise<void>;
+ onDuplicate?: () => Promise<boolean>;
+ canPaste?: boolean;
}
+// A menu with many independently gated items (Split/Delete/Copy/Paste/Duplicate).
+// fallow-ignore-next-line complexity
export const ClipContextMenu = memo(function ClipContextMenu({
x,
y,
@@ -23,15 +29,22 @@ export const ClipContextMenu = memo(function ClipContextMenu({
onClose,
onSplit,
onDelete,
+ onCopy,
+ onPaste,
+ onDuplicate,
+ canPaste,
}: ClipContextMenuProps) {
const menuRef = useContextMenuDismiss(onClose);
useMenuKeyboardNav(menuRef);
-
- const menuWidth = 200;
- const menuHeight = 80;
- const overflowY = y + menuHeight - window.innerHeight;
- const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x;
- const adjustedY = overflowY > 0 ? y - overflowY - 8 : y;
+ // The right-clicked clip's own id: a member of the live multi-selection
+ // means Copy/Duplicate act on the whole group, matching onContextMenuClip's
+ // selection-preserving behaviour for a right-click inside it.
+ const selectionSize = usePlayerStore((s) => {
+ const id = element.key ?? element.id;
+ return s.selectedElementIds.size > 1 && s.selectedElementIds.has(id)
+ ? s.selectedElementIds.size
+ : 1;
+ });
const isSplittable = canSplitElement(element) && ["video", "audio", "img"].includes(element.tag);
const canSplit =
@@ -43,6 +56,23 @@ export const ClipContextMenu = memo(function ClipContextMenu({
? `Split at ${currentTime.toFixed(2)}s`
: "Split (move playhead inside clip)";
+ const clipboardItemCount = [onCopy, onPaste, onDuplicate].filter(Boolean).length;
+ const rowCount = (splitLabel ? 1 : 0) + clipboardItemCount + 1; // + Delete, always present
+ const dividerCount = (splitLabel ? 1 : 0) + (clipboardItemCount > 0 ? 1 : 0);
+ const menuWidth = 200;
+ const menuHeight = rowCount * 30 + dividerCount * 9 + 8;
+ const overflowY = y + menuHeight - window.innerHeight;
+ const adjustedX = x + menuWidth > window.innerWidth ? x - menuWidth : x;
+ const adjustedY = overflowY > 0 ? y - overflowY - 8 : y;
+
+ // Same enabled/disabled menu-item pattern as the sibling TrackGapContextMenu.
+ const itemClass = (enabled: boolean) =>
+ `w-full flex items-center justify-between px-3 py-1.5 text-xs text-left outline-none${
+ enabled
+ ? " focus-visible:bg-neutral-800 text-neutral-300 hover:bg-neutral-800 cursor-pointer"
+ : " text-neutral-600 cursor-not-allowed"
+ }`;
+
return createPortal(
<div
ref={menuRef}
@@ -76,6 +106,56 @@ export const ClipContextMenu = memo(function ClipContextMenu({
</>
)}
+ {(onCopy || onPaste || onDuplicate) && (
+ <>
+ {onCopy && (
+ <button
+ type="button"
+ role="menuitem"
+ className={itemClass(true)}
+ onClick={() => {
+ onCopy();
+ onClose();
+ }}
+ >
+ <span>{selectionSize > 1 ? `Copy ${selectionSize} clips` : "Copy"}</span>
+ <span className="text-neutral-500 text-[10px] ml-3">⌘C</span>
+ </button>
+ )}
+ {onPaste && (
+ <button
+ type="button"
+ role="menuitem"
+ className={itemClass(!!canPaste)}
+ disabled={!canPaste}
+ onClick={() => {
+ if (!canPaste) return;
+ void onPaste();
+ onClose();
+ }}
+ >
+ <span>Paste</span>
+ <span className="text-neutral-500 text-[10px] ml-3">⌘V</span>
+ </button>
+ )}
+ {onDuplicate && (
+ <button
+ type="button"
+ role="menuitem"
+ className={itemClass(true)}
+ onClick={() => {
+ void onDuplicate();
+ onClose();
+ }}
+ >
+ <span>{selectionSize > 1 ? `Duplicate ${selectionSize} clips` : "Duplicate"}</span>
+ <span className="text-neutral-500 text-[10px] ml-3">⌘D</span>
+ </button>
+ )}
+ <div className="my-1 border-t border-neutral-700/60" />
+ </>
+ )}
+
<button
type="button"
role="menuitem"
diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx
index bff828af1f..f2b803cc44 100644
--- a/packages/studio/src/player/components/Timeline.tsx
+++ b/packages/studio/src/player/components/Timeline.tsx
@@ -43,6 +43,7 @@ import { useTimelineClipRenderWindow } from "./useTimelineClipRenderWindow";
import { useTimelineActiveClips } from "./useTimelineActiveClips";
import { useTimelineLaneMoveRefresh } from "./useTimelineLaneMoveRefresh";
import { useTimelineLogicalFocus } from "./useTimelineLogicalFocus";
+import { useClipContextMenu } from "./useTimelineClipContextMenu";
export {
shouldAutoScrollTimeline,
@@ -79,6 +80,10 @@ export const Timeline = memo(function Timeline({
onBlockedEditAttempt: onBlockedEditAttemptOverride,
onSplitElement: onSplitElementOverride,
onSelectElement,
+ onCopyClip,
+ onPasteClip,
+ onDuplicateClip,
+ canPasteClip,
theme: themeOverrides,
sessionEpoch = 0,
}: TimelineProps = {}) {
@@ -208,6 +213,7 @@ export const Timeline = memo(function Timeline({
onMoveElement: pinnedOnMoveElement,
onMoveElements: pinnedOnMoveElements,
});
+ const onContextMenuClip = useClipContextMenu(onSelectElement, dismissGapMenu, setClipContextMenu);
const {
draggedClip,
@@ -548,18 +554,7 @@ export const Timeline = memo(function Timeline({
onShiftClickKeyframe={onShiftClickKeyframe}
onMoveKeyframe={onMoveKeyframe}
onContextMenuKeyframe={onContextMenuKeyframe}
- onContextMenuClip={(e, el) => {
- e.preventDefault();
- setSelectedElementId(el.key ?? el.id);
- onSelectElement?.(el);
- dismissGapMenu();
- setClipContextMenu({
- x: e.clientX,
- y: e.clientY,
- element: el,
- sessionEpoch: usePlayerStore.getState().timelineSessionEpoch,
- });
- }}
+ onContextMenuClip={onContextMenuClip}
onContextMenuLane={(e, track, time) => {
if (draggedClip?.started || resizingClip) return;
setClipContextMenu(null);
@@ -588,6 +583,10 @@ export const Timeline = memo(function Timeline({
onSplitElement={onSplitElement}
pinZoomBeforeEdit={pinZoomBeforeEdit}
onDeleteElement={_onDeleteElement}
+ onCopyClip={onCopyClip}
+ onPasteClip={onPasteClip}
+ onDuplicateClip={onDuplicateClip}
+ canPasteClip={canPasteClip}
gapContextMenu={gapMenuModel}
onDismissGapContextMenu={dismissGapMenu}
onCloseTrackGap={closeTrackGap}
diff --git a/packages/studio/src/player/components/TimelineOverlays.tsx b/packages/studio/src/player/components/TimelineOverlays.tsx
index c9335f5c29..53da7ace6a 100644
--- a/packages/studio/src/player/components/TimelineOverlays.tsx
+++ b/packages/studio/src/player/components/TimelineOverlays.tsx
@@ -52,6 +52,10 @@ interface TimelineOverlaysProps {
onSplitElement: TimelineEditCallbacks["onSplitElement"];
pinZoomBeforeEdit: () => void;
onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
+ onCopyClip?: () => boolean;
+ onPasteClip?: () => Promise<void>;
+ onDuplicateClip?: () => Promise<boolean>;
+ canPasteClip?: () => boolean;
gapContextMenu: TrackGapContextMenuState | null;
onDismissGapContextMenu: () => void;
onCloseTrackGap: () => void;
@@ -119,6 +123,10 @@ export function TimelineOverlays({
onSplitElement,
pinZoomBeforeEdit,
onDeleteElement,
+ onCopyClip,
+ onPasteClip,
+ onDuplicateClip,
+ canPasteClip,
gapContextMenu,
onDismissGapContextMenu,
onCloseTrackGap,
@@ -249,6 +257,10 @@ export function TimelineOverlays({
pinZoomBeforeEdit();
onDeleteElement?.(element);
}}
+ onCopy={onCopyClip}
+ onPaste={onPasteClip}
+ onDuplicate={onDuplicateClip}
+ canPaste={canPasteClip?.() ?? false}
/>
)}
diff --git a/packages/studio/src/player/components/TimelineTypes.ts b/packages/studio/src/player/components/TimelineTypes.ts
index 2908f026e6..eb2e6ebb4c 100644
--- a/packages/studio/src/player/components/TimelineTypes.ts
+++ b/packages/studio/src/player/components/TimelineTypes.ts
@@ -22,5 +22,9 @@ export interface TimelineProps extends TimelineDropCallbacks, TimelineEditOverri
renderClipOverlay?: (element: TimelineElement) => ReactNode;
onDeleteElement?: (element: TimelineElement) => Promise<void> | void;
onSelectElement?: (element: TimelineElement | null) => void;
+ onCopyClip?: () => boolean;
+ onPasteClip?: () => Promise<void>;
+ onDuplicateClip?: () => Promise<boolean>;
+ canPasteClip?: () => boolean;
theme?: Partial<TimelineTheme>;
}
diff --git a/packages/studio/src/player/components/useTimelineClipContextMenu.ts b/packages/studio/src/player/components/useTimelineClipContextMenu.ts
new file mode 100644
index 0000000000..28c545df2e
--- /dev/null
+++ b/packages/studio/src/player/components/useTimelineClipContextMenu.ts
@@ -0,0 +1,32 @@
+import { useCallback } from "react";
+import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import type { ClipContextMenuState } from "./TimelineOverlays";
+
+/** A clicked member of an active multi-selection keeps the whole group
+ * selected, so the context menu it opens acts on all of it. */
+export function useClipContextMenu(
+ onSelectElement: ((element: TimelineElement | null) => void) | undefined,
+ dismissGapMenu: () => void,
+ setClipContextMenu: (state: ClipContextMenuState | null) => void,
+) {
+ const selectedElementIds = usePlayerStore((s) => s.selectedElementIds);
+ const setSelectedElementId = usePlayerStore((s) => s.setSelectedElementId);
+ return useCallback(
+ (e: React.MouseEvent, el: TimelineElement) => {
+ e.preventDefault();
+ const id = el.key ?? el.id;
+ if (!(selectedElementIds.size > 1 && selectedElementIds.has(id))) {
+ setSelectedElementId(id);
+ onSelectElement?.(el);
+ }
+ dismissGapMenu();
+ setClipContextMenu({
+ x: e.clientX,
+ y: e.clientY,
+ element: el,
+ sessionEpoch: usePlayerStore.getState().timelineSessionEpoch,
+ });
+ },
+ [selectedElementIds, setSelectedElementId, onSelectElement, dismissGapMenu, setClipContextMenu],
+ );
+}
diff --git a/packages/studio/src/utils/clipboardPayload.test.ts b/packages/studio/src/utils/clipboardPayload.test.ts
index 548876b664..b91c5eb806 100644
--- a/packages/studio/src/utils/clipboardPayload.test.ts
+++ b/packages/studio/src/utils/clipboardPayload.test.ts
@@ -33,10 +33,41 @@ describe("deduplicateIds", () => {
});
describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
- it("round-trips a timeline clip payload", () => {
+ it("round-trips a single-clip timeline payload", () => {
const payload: ClipboardPayload = {
kind: "timeline-clip",
- html: '<img id="photo" src="a.png" data-start="1" data-duration="3" />',
+ clips: [
+ {
+ html: '<img id="photo" src="a.png" data-start="1" data-duration="3" />',
+ start: 1,
+ duration: 3,
+ track: 0,
+ },
+ ],
+ sourceFile: "index.html",
+ };
+ const json = serializeClipboardPayload(payload);
+ const parsed = deserializeClipboardPayload(json);
+ expect(parsed).toEqual(payload);
+ });
+
+ it("round-trips a group timeline-clip payload", () => {
+ const payload: ClipboardPayload = {
+ kind: "timeline-clip",
+ clips: [
+ {
+ html: '<img id="a" data-start="1" data-duration="0.5" />',
+ start: 1,
+ duration: 0.5,
+ track: 0,
+ },
+ {
+ html: '<img id="b" data-start="2" data-duration="0.5" />',
+ start: 2,
+ duration: 0.5,
+ track: 1,
+ },
+ ],
sourceFile: "index.html",
};
const json = serializeClipboardPayload(payload);
@@ -59,4 +90,13 @@ describe("serializeClipboardPayload / deserializeClipboardPayload", () => {
expect(deserializeClipboardPayload("not json")).toBeNull();
expect(deserializeClipboardPayload('{"kind":"unknown"}')).toBeNull();
});
+
+ it("returns null for a timeline-clip payload with no clips", () => {
+ const json = serializeClipboardPayload({
+ kind: "timeline-clip",
+ clips: [],
+ sourceFile: "index.html",
+ });
+ expect(deserializeClipboardPayload(json)).toBeNull();
+ });
});
diff --git a/packages/studio/src/utils/clipboardPayload.ts b/packages/studio/src/utils/clipboardPayload.ts
index 8e9bfb1720..d51af2adc4 100644
--- a/packages/studio/src/utils/clipboardPayload.ts
+++ b/packages/studio/src/utils/clipboardPayload.ts
@@ -2,35 +2,35 @@ import { COMPOSITION_ROOT_OPEN_TAG_RE } from "./compositionPatterns";
const CLIPBOARD_MARKER = "hyperframes-clipboard:v1";
-export interface ClipboardPayload {
- kind: "timeline-clip" | "dom-element";
+/** One clip's copied markup plus the original placement needed to preserve
+ * relative offsets and tracks across a group paste. */
+export interface TimelineClipboardClip {
html: string;
- sourceFile: string;
- originSelector?: string;
- originSelectorIndex?: number;
+ start: number;
+ duration: number;
+ track: number;
}
-interface SerializedPayload {
- _marker: string;
- kind: "timeline-clip" | "dom-element";
- html: string;
- sourceFile: string;
- originSelector?: string;
- originSelectorIndex?: number;
-}
+export type ClipboardPayload =
+ | { kind: "timeline-clip"; clips: TimelineClipboardClip[]; sourceFile: string }
+ | {
+ kind: "dom-element";
+ html: string;
+ sourceFile: string;
+ originSelector?: string;
+ originSelectorIndex?: number;
+ };
+
+type SerializedPayload = { _marker: string } & ClipboardPayload;
export function serializeClipboardPayload(payload: ClipboardPayload): string {
- const data: SerializedPayload = {
- _marker: CLIPBOARD_MARKER,
- kind: payload.kind,
- html: payload.html,
- sourceFile: payload.sourceFile,
- originSelector: payload.originSelector,
- originSelectorIndex: payload.originSelectorIndex,
- };
+ const data: SerializedPayload = { _marker: CLIPBOARD_MARKER, ...payload };
return JSON.stringify(data);
}
+// Each branch validates one wire shape at the trust boundary; splitting further
+// would fragment one parse into partial validators with no independent reuse.
+// fallow-ignore-next-line complexity
export function deserializeClipboardPayload(json: string): ClipboardPayload | null {
let parsed: unknown;
try {
@@ -41,16 +41,35 @@ export function deserializeClipboardPayload(json: string): ClipboardPayload | nu
if (!parsed || typeof parsed !== "object") return null;
const obj = parsed as Record<string, unknown>;
if (obj._marker !== CLIPBOARD_MARKER) return null;
- if (obj.kind !== "timeline-clip" && obj.kind !== "dom-element") return null;
- if (typeof obj.html !== "string" || typeof obj.sourceFile !== "string") return null;
- return {
- kind: obj.kind,
- html: obj.html,
- sourceFile: obj.sourceFile,
- originSelector: typeof obj.originSelector === "string" ? obj.originSelector : undefined,
- originSelectorIndex:
- typeof obj.originSelectorIndex === "number" ? obj.originSelectorIndex : undefined,
- };
+ if (typeof obj.sourceFile !== "string") return null;
+ if (obj.kind === "timeline-clip") {
+ if (!Array.isArray(obj.clips)) return null;
+ const clips = obj.clips.filter((c): c is TimelineClipboardClip => {
+ const clip = c as Partial<TimelineClipboardClip> | null;
+ return (
+ !!clip &&
+ typeof clip === "object" &&
+ typeof clip.html === "string" &&
+ typeof clip.start === "number" &&
+ typeof clip.duration === "number" &&
+ typeof clip.track === "number"
+ );
+ });
+ if (clips.length === 0) return null;
+ return { kind: "timeline-clip", clips, sourceFile: obj.sourceFile };
+ }
+ if (obj.kind === "dom-element") {
+ if (typeof obj.html !== "string") return null;
+ return {
+ kind: "dom-element",
+ html: obj.html,
+ sourceFile: obj.sourceFile,
+ originSelector: typeof obj.originSelector === "string" ? obj.originSelector : undefined,
+ originSelectorIndex:
+ typeof obj.originSelectorIndex === "number" ? obj.originSelectorIndex : undefined,
+ };
+ }
+ return null;
}
/**
@@ -59,6 +78,7 @@ export function deserializeClipboardPayload(json: string): ClipboardPayload | nu
* the composition root if the selector doesn't match — so paste never silently
* drops the content.
*/
+// fallow-ignore-next-line complexity
export function insertAsSibling(
source: string,
newHtml: string,
@@ -110,6 +130,7 @@ export function insertAsSibling(
return source + newHtml;
}
+// fallow-ignore-next-line complexity
function findClosingTagPosition(html: string, openTagStart: number): number {
// Find the end of the opening tag
const openTagEnd = html.indexOf(">", openTagStart);
@@ -156,9 +177,13 @@ function findClosingTagPosition(html: string, openTagStart: number): number {
return -1;
}
+/** An `id="..."` attribute, not `data-id="..."` or similar — only matches
+ * when preceded by whitespace, the way every generated attribute is. */
+export const ID_ATTR_RE = /(?<=\s)id="([^"]+)"/;
+
export function deduplicateIds(html: string, existingIds: string[]): string {
const existingSet = new Set(existingIds);
- return html.replace(/(?<=\s)id="([^"]+)"/g, (full, id: string) => {
+ return html.replace(new RegExp(ID_ATTR_RE.source, "g"), (full, id: string) => {
if (!existingSet.has(id)) return full;
let counter = 2;
while (existingSet.has(`${id}-${counter}`)) counter++;