@@ -38,16 +49,7 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
`;
beforeEach(() => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.includes("/file-mutations/remove-element/")) {
- return new Response(JSON.stringify({ changed: true, content: html }), { status: 200 });
- }
- return new Response(JSON.stringify({ content: html }), { status: 200 });
- }),
- );
+ stubRemoveElementsFetch(html, html);
});
afterEach(() => {
@@ -118,6 +120,23 @@ describe("useTimelineDeleteOps: ripple undo label", () => {
);
});
+ it("removes a multi-clip selection with one request, however many clips it holds", async () => {
+ const handleTimelineGroupMove = vi.fn().mockResolvedValue(undefined);
+ const { elements, getHook } = mountDeleteHarness({ handleTimelineGroupMove });
+
+ await act(async () => {
+ await getHook().handleTimelineElementsDelete(elements);
+ });
+
+ const removals = vi
+ .mocked(fetch)
+ .mock.calls.filter(([url]) => String(url).includes("/file-mutations/remove-element"));
+ expect(removals).toHaveLength(1);
+ const [, init] = removals[0] as [unknown, RequestInit];
+ const body = JSON.parse(String(init.body));
+ expect(body.targets).toHaveLength(elements.length);
+ });
+
it("shows exactly one toast when a ripple fails to persist after a committed delete", async () => {
const handleTimelineGroupMove = vi.fn().mockRejectedValue(new Error("persist failed"));
const showToast = vi.fn();
@@ -162,18 +181,7 @@ describe("useTimelineDeleteOps: undo race", () => {
`;
beforeEach(() => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: RequestInfo | URL) => {
- const url = String(input);
- if (url.includes("/file-mutations/remove-element/")) {
- return new Response(JSON.stringify({ changed: true, content: htmlAfterDeletingC }), {
- status: 200,
- });
- }
- return new Response(JSON.stringify({ content: html }), { status: 200 });
- }),
- );
+ stubRemoveElementsFetch(html, htmlAfterDeletingC);
});
afterEach(() => {
diff --git a/packages/studio/src/hooks/useTimelineDeleteOps.ts b/packages/studio/src/hooks/useTimelineDeleteOps.ts
index 79ec4baee70..b4ff3bec82b 100644
--- a/packages/studio/src/hooks/useTimelineDeleteOps.ts
+++ b/packages/studio/src/hooks/useTimelineDeleteOps.ts
@@ -121,38 +121,32 @@ export function useTimelineDeleteOps({
writeFile: writeProjectFile,
recordEdit,
rewrite: async (originalContent) => {
- // Remove every selected element before saving once. The server rewrites
- // the file per call, so `removedContent` after the last one holds them
- // all — which is what makes this a single history entry, and a single
- // undo, rather than one per clip.
- let removedContent = originalContent;
- for (const target of sameFile) {
+ // One request removes every selected element and rewrites the file once, so a
+ // large selection is a single round trip and a single history entry.
+ const patchTargets = sameFile.map((target) => {
const patchTarget = buildPatchTarget(target);
if (!patchTarget) {
throw new Error(`Timeline element ${target.id} is missing a patchable target`);
}
-
- const removeResponse = await fetch(
- buildProjectApiPath(
- pid,
- `/file-mutations/remove-element/${encodeURIComponent(targetPath)}`,
- ),
- {
- method: "POST",
- headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
- body: JSON.stringify({ target: patchTarget }),
- },
- );
- if (!removeResponse.ok) {
- throw new Error(`Failed to delete ${target.id} from ${targetPath}`);
- }
-
- const removeData = (await removeResponse.json()) as {
- changed?: boolean;
- content?: string;
- };
- if (typeof removeData.content === "string") removedContent = removeData.content;
+ return patchTarget;
+ });
+ const removeResponse = await fetch(
+ buildProjectApiPath(
+ pid,
+ `/file-mutations/remove-elements/${encodeURIComponent(targetPath)}`,
+ ),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json", ...studioWriteHeaders() },
+ body: JSON.stringify({ targets: patchTargets }),
+ },
+ );
+ if (!removeResponse.ok) {
+ throw new Error(`Failed to delete ${sameFile.length} clips from ${targetPath}`);
}
+ const removeData = (await removeResponse.json()) as { content?: string };
+ const removedContent =
+ typeof removeData.content === "string" ? removeData.content : originalContent;
// Shrink to the furthest remaining clip end, read from the post-removal source:
// store durations are runtime-truncated.
const deleteContentEnd = furthestClipEndFromSource(removedContent);
diff --git a/packages/studio/src/hooks/useTimelineEditing.test.tsx b/packages/studio/src/hooks/useTimelineEditing.test.tsx
index d6c933d5477..65bdd3dcc66 100644
--- a/packages/studio/src/hooks/useTimelineEditing.test.tsx
+++ b/packages/studio/src/hooks/useTimelineEditing.test.tsx
@@ -1296,7 +1296,7 @@ describe("useTimelineEditing duration rollback on failed persist", () => {
if (url.includes("/api/projects/p1/files/")) {
return jsonResponse({ content: DELETE_SOURCE });
}
- if (url.includes("/api/projects/p1/file-mutations/remove-element/")) {
+ if (url.includes("/api/projects/p1/file-mutations/remove-elements/")) {
return jsonResponse({ changed: true, content: DELETE_REMOVED_SOURCE });
}
throw new Error(`Unexpected fetch: ${url}`);
diff --git a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
index eec421f1a0c..096d68c180c 100644
--- a/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
+++ b/packages/studio/src/player/components/timelineClipDragGestureLifecycle.ts
@@ -195,7 +195,7 @@ export function mountTimelineClipDragGestureLifecycle({
event.clientX - blocked.originClientX,
event.clientY - blocked.originClientY,
);
- const threshold = blocked.intent === "move" ? 4 : 2;
+ const threshold = blocked.intent === "move" || blocked.intent === "edit-many" ? 4 : 2;
if (!blocked.started && distance < threshold) return;
if (!blocked.started) {
blocked.started = true;
diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts
new file mode 100644
index 00000000000..1e9a732b51e
--- /dev/null
+++ b/packages/studio/src/player/components/timelineClipGestureHandlers.test.ts
@@ -0,0 +1,94 @@
+// @vitest-environment happy-dom
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { PointerEvent as ReactPointerEvent } from "react";
+import { usePlayerStore, type TimelineElement } from "../store/playerStore";
+import { createClipGestureHandlers, type ClipGestureDeps } from "./timelineClipGestureHandlers";
+import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing";
+
+afterEach(() => usePlayerStore.getState().reset());
+
+const clips: TimelineElement[] = Array.from({ length: 6 }, (_, i) => ({
+ id: `clip-${i}`,
+ domId: `clip-${i}`,
+ tag: "div",
+ start: i,
+ duration: 1,
+ track: i,
+}));
+const capabilities = { canMove: true, canTrimStart: true, canTrimEnd: true, readOnly: false };
+
+function grabFirstClip(count: number, gesture: "move" | "resize", locked: number[] = []) {
+ const store = usePlayerStore.getState();
+ store.setElements(
+ clips.map((clip, i) => (locked.includes(i) ? { ...clip, timelineLocked: true } : clip)),
+ );
+ store.setSelectedElementIds(new Set(clips.slice(0, count).map((c) => c.id)));
+ const setDraggedClip = vi.fn();
+ const setResizingClip = vi.fn();
+ const blockedClipRef = { current: null as { intent: string } | null };
+ const deps = {
+ pps: 100,
+ onMoveElement: vi.fn(),
+ onResizeElement: vi.fn(),
+ blockedClipRef,
+ suppressClickRef: { current: false },
+ scrollRef: { current: null },
+ setShowPopover: vi.fn(),
+ setRangeSelection: vi.fn(),
+ setResizingClip,
+ setDraggedClip,
+ setSelectedElementId: vi.fn(),
+ } as unknown as ClipGestureDeps;
+ const handlers = createClipGestureHandlers(clips[0], clips[0].id, clips[0], capabilities, deps);
+ const event = {
+ button: 0,
+ clientX: 50,
+ clientY: 5,
+ pointerId: 1,
+ stopPropagation: vi.fn(),
+ currentTarget: { getBoundingClientRect: () => ({ left: 0, width: 100 }) },
+ } as unknown as ReactPointerEvent;
+ if (gesture === "move") handlers.onPointerDown(event);
+ else handlers.onResizeStart("end", event);
+ return { setDraggedClip, setResizingClip, blockedClipRef };
+}
+
+describe("hand-editing a multi-selection", () => {
+ it("moves up to the limit by hand", () => {
+ const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "move");
+ expect(setDraggedClip).toHaveBeenCalledOnce();
+ expect(blockedClipRef.current).toBeNull();
+ });
+
+ it("refuses to start a drag above the limit and asks for the toast", () => {
+ const { setDraggedClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "move");
+ expect(setDraggedClip).not.toHaveBeenCalled();
+ expect(blockedClipRef.current?.intent).toBe("edit-many");
+ });
+
+ it("resizes up to the limit by hand", () => {
+ const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS, "resize");
+ expect(setResizingClip).toHaveBeenCalledOnce();
+ expect(blockedClipRef.current).toBeNull();
+ });
+
+ it("refuses to start a resize above the limit and asks for the toast", () => {
+ const { setResizingClip, blockedClipRef } = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize");
+ expect(setResizingClip).not.toHaveBeenCalled();
+ expect(blockedClipRef.current?.intent).toBe("edit-many");
+ });
+
+ it("counts the clips a move would change: locked ones in the selection stay put", () => {
+ const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [3, 4]);
+ expect(allowed.setDraggedClip).toHaveBeenCalledOnce();
+ const refused = grabFirstClip(MAX_HAND_EDIT_CLIPS + 2, "move", [4]);
+ expect(refused.setDraggedClip).not.toHaveBeenCalled();
+ });
+
+ it("counts the clips a trim would change: a locked member leaves a trim of the grabbed clip alone", () => {
+ const allowed = grabFirstClip(MAX_HAND_EDIT_CLIPS + 1, "resize", [3]);
+ expect(allowed.setResizingClip).toHaveBeenCalledOnce();
+ expect(allowed.blockedClipRef.current).toBeNull();
+ });
+});
diff --git a/packages/studio/src/player/components/timelineClipGestureHandlers.ts b/packages/studio/src/player/components/timelineClipGestureHandlers.ts
index 4d69d460fb6..29ffd28bdb9 100644
--- a/packages/studio/src/player/components/timelineClipGestureHandlers.ts
+++ b/packages/studio/src/player/components/timelineClipGestureHandlers.ts
@@ -8,7 +8,11 @@ import {
import type { TimelineEditCapabilities } from "./timelineEditCapabilities";
import type { TimelineEditCallbacks } from "./timelineCallbacks";
import { CLIP_HANDLE_W } from "./timelineLayout";
-import { selectClipWithLinks, toggleClipWithLinks } from "./timelineLinkSelection";
+import {
+ exceedsHandEditLimit,
+ selectClipWithLinks,
+ toggleClipWithLinks,
+} from "./timelineLinkSelection";
import { SPLIT_BOUNDARY_EPSILON_S } from "../../utils/timelineElementSplit";
export interface ClipGestureDeps {
@@ -73,6 +77,7 @@ function isIntentBlocked(
*/
function resolvePointerDownAction(
e: ReactPointerEvent,
+ grabbed: TimelineElement,
capabilities: TimelineEditCapabilities,
onResizeElement: ClipGestureDeps["onResizeElement"],
onMoveElement: ClipGestureDeps["onMoveElement"],
@@ -93,6 +98,8 @@ function resolvePointerDownAction(
}
if (!onMoveElement || !capabilities.canMove) return { kind: "ignore" };
+ if (exceedsHandEditLimit(grabbed, e.altKey, null))
+ return { kind: "block", intent: "edit-many", rect };
return { kind: "move", rect };
}
@@ -129,6 +136,17 @@ export function createClipGestureHandlers(
const onResizeStart = (edge: "start" | "end", e: ReactPointerEvent): void => {
if (!canStartResize(edge, e, capabilities, onResizeElement)) return;
e.stopPropagation();
+ if (exceedsHandEditLimit(el, e.altKey, edge)) {
+ blockedClipRef.current = {
+ pointerId: e.pointerId,
+ element: el,
+ intent: "edit-many",
+ originClientX: e.clientX,
+ originClientY: e.clientY,
+ started: false,
+ };
+ return;
+ }
blockedClipRef.current = null;
setShowPopover(false);
setRangeSelection(null);
@@ -147,7 +165,7 @@ export function createClipGestureHandlers(
};
const onPointerDown = (e: ReactPointerEvent): void => {
- const action = resolvePointerDownAction(e, capabilities, onResizeElement, onMoveElement);
+ const action = resolvePointerDownAction(e, el, capabilities, onResizeElement, onMoveElement);
if (action.kind === "ignore") return;
if (action.kind === "block") {
diff --git a/packages/studio/src/player/components/timelineEditing.ts b/packages/studio/src/player/components/timelineEditing.ts
index e6cea2885af..dc57741044e 100644
--- a/packages/studio/src/player/components/timelineEditing.ts
+++ b/packages/studio/src/player/components/timelineEditing.ts
@@ -248,7 +248,9 @@ export interface TimelinePromptElement {
track: number;
}
-export type BlockedTimelineEditIntent = "move" | "resize-start" | "resize-end";
+export type BlockedTimelineEditIntent = "move" | "edit-many" | "resize-start" | "resize-end";
+
+export const MAX_HAND_EDIT_CLIPS = 3;
export interface TimelineRangeSelection {
start: number;
diff --git a/packages/studio/src/player/components/timelineLinkSelection.ts b/packages/studio/src/player/components/timelineLinkSelection.ts
index 3d5db3de61b..3b8ea614392 100644
--- a/packages/studio/src/player/components/timelineLinkSelection.ts
+++ b/packages/studio/src/player/components/timelineLinkSelection.ts
@@ -1,5 +1,13 @@
import { usePlayerStore, type TimelineElement } from "../store/playerStore";
-import { expandToLinkedMembers, linkedMembersOf } from "./audioClipLink";
+import {
+ dropMisalignedTrimPartners,
+ expandToLinkedMembers,
+ linkedGestureKeys,
+ linkedMembersOf,
+} from "./audioClipLink";
+import { buildTimelineGroupResizeMembers } from "./timelineGroupEditing";
+import { resolveGroupMovers } from "./timelineMultiDragPreview";
+import { MAX_HAND_EDIT_CLIPS } from "./timelineEditing";
import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";
/**
@@ -39,3 +47,29 @@ export function toggleClipWithLinks(key: string, altKey: boolean): TimelineEleme
const primary = usePlayerStore.getState().selectedElementId;
return state.elements.find((el) => (el.key ?? el.id) === primary) ?? null;
}
+
+/** Whether a hand drag on `grabbed` (trimming `edge`, or null to move) would change more clips than allowed. */
+export function exceedsHandEditLimit(
+ grabbed: TimelineElement,
+ altKey: boolean,
+ edge: "start" | "end" | null,
+): boolean {
+ const { selectedElementIds, elements } = usePlayerStore.getState();
+ const grabbedKey = grabbed.key ?? grabbed.id;
+ const keys = linkedGestureKeys(
+ selectedElementIds,
+ grabbed,
+ elements,
+ altKey,
+ isLinkedSelectionOn(),
+ );
+ const changed = edge
+ ? buildTimelineGroupResizeMembers(
+ elements,
+ dropMisalignedTrimPartners(keys, grabbed, elements, edge),
+ grabbedKey,
+ edge,
+ )
+ : resolveGroupMovers(elements, keys, grabbedKey);
+ return (changed?.length ?? 1) > MAX_HAND_EDIT_CLIPS;
+}
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx
index 5c3587f98e7..9b338a7f85e 100644
--- a/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx
+++ b/packages/studio/src/player/components/useTimelineClipDrag.keyboard.test.tsx
@@ -49,6 +49,7 @@ function mount(order = [0, 1, 2]) {
const host = document.createElement("div");
const root = createRoot(host);
const onMoveElements = vi.fn();
+ const onBlockedEditAttempt = vi.fn();
const trackOrderRef = { current: order };
const trackInsertLayoutRef = { current: buildTimelineTrackInsertLayout(order, groups) };
let state: ReturnType
;
@@ -68,6 +69,7 @@ function mount(order = [0, 1, 2]) {
},
onMoveElement: vi.fn(),
onMoveElements,
+ onBlockedEditAttempt,
setShowPopover: () => {},
setRangeSelectionRef: { current: null },
});
@@ -83,6 +85,7 @@ function mount(order = [0, 1, 2]) {
key,
clip,
onMoveElements,
+ onBlockedEditAttempt,
root,
elements,
changeOrder(next: number[]) {
@@ -161,3 +164,14 @@ it("leaves Space on a nested fade slider to the slider", () => {
expect(event.defaultPrevented).toBe(false);
act(() => view.root.unmount());
});
+
+it("does not pick up a clip held in a selection above the hand-move limit", () => {
+ const view = mount();
+ usePlayerStore.getState().setSelection(["top", "hero", "tail", "bottom"], "hero");
+ view.key(" ");
+ expect(view.drag).toBeNull();
+ expect(view.onBlockedEditAttempt).toHaveBeenCalledWith(
+ expect.objectContaining({ id: "hero" }),
+ "edit-many",
+ );
+});
diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts
index 3e4610e7ce3..3ae3516c87e 100644
--- a/packages/studio/src/player/components/useTimelineClipDrag.ts
+++ b/packages/studio/src/player/components/useTimelineClipDrag.ts
@@ -29,6 +29,7 @@ import type {
} from "./timelineClipDragTypes";
import { getTimelineElementIndexes } from "../lib/timelineElementIndexes";
import { dropMisalignedTrimPartners, linkedGestureKeys } from "./audioClipLink";
+import { exceedsHandEditLimit } from "./timelineLinkSelection";
import { isLinkedSelectionOn } from "../../utils/linkedClipPreferences";
import { useTimelineClipCapabilities } from "./timelineReadOnly";
import { timelineClipFocusId } from "./timelineNavigationIdentity";
@@ -158,11 +159,8 @@ export function useTimelineClipDrag({
const elementsRef = useRef(elements);
elementsRef.current = elements;
- // Perf (frozen-per-gesture): the snap-target set and the audio-track set are
- // fixed for the duration of one drag/resize (the store is not re-authored mid
- // gesture), so build each ONCE and reuse it across every pointermove and every
- // auto-scroll frame. Both caches are cleared at gesture teardown
- // (stopClipDragAutoScroll), so the next gesture rebuilds against fresh state.
+ // The snap-target and audio-track sets are fixed for one drag/resize (the store is not
+ // re-authored mid gesture): built once, reused per pointermove, cleared at teardown.
const snapTargetsCacheRef = useRef