diff --git a/packages/studio/src/hooks/useAppHotkeys.ts b/packages/studio/src/hooks/useAppHotkeys.ts index adc6f36f4a..db5a1b3d71 100644 --- a/packages/studio/src/hooks/useAppHotkeys.ts +++ b/packages/studio/src/hooks/useAppHotkeys.ts @@ -289,9 +289,14 @@ function dispatchPlainKey(event: KeyboardEvent, key: string, cb: HotkeyCallbacks return; } } - const { selectedElementId, elements } = usePlayerStore.getState(); - if (selectedElementId) { - const el = elements.find((e) => (e.key ?? e.id) === selectedElementId); + // Delete acts on the primary selection OR the marquee multi-selection — + // the delete handler expands a clip that is part of the multi-selection + // into an atomic delete of the whole selection (single undo). + const { selectedElementId, selectedElementIds, elements } = usePlayerStore.getState(); + const selectionKeys = new Set(selectedElementIds); + if (selectedElementId) selectionKeys.add(selectedElementId); + if (selectionKeys.size > 0) { + const el = elements.find((e) => selectionKeys.has(e.key ?? e.id)); if (el) { event.preventDefault(); void cb.handleTimelineElementDelete(el); diff --git a/packages/studio/src/hooks/useTimelineEditing.ts b/packages/studio/src/hooks/useTimelineEditing.ts index 0822351547..1882f91ce1 100644 --- a/packages/studio/src/hooks/useTimelineEditing.ts +++ b/packages/studio/src/hooks/useTimelineEditing.ts @@ -372,71 +372,95 @@ export function useTimelineEditing({ isRecordingRef, forceReloadSdkSession, }); + // Atomic multi-clip delete: ONE pass that removes every element from the + // source (grouped per owning file), then ONE content-driven duration sync + + // ONE save (single undo entry) + one reload — mirroring the batched pattern + // in persistTimelineElementsMove. The single-clip delete is the same path + // with a one-element list. // fallow-ignore-next-line complexity - const handleTimelineElementDelete = useCallback( + const handleTimelineElementsDelete = useCallback( // fallow-ignore-next-line complexity - async (element: TimelineElement) => { + async (elementsToDelete: TimelineElement[]) => { if (isRecordingRef?.current) { showToast("Cannot edit timeline while recording", "error"); return; } const pid = projectIdRef.current; if (!pid) throw new Error("No active project"); - const label = getTimelineElementLabel(element); - const targetPath = element.sourceFile || activeCompPath || "index.html"; + if (elementsToDelete.length === 0) return; + const count = elementsToDelete.length; + const label = count === 1 ? getTimelineElementLabel(elementsToDelete[0]) : `${count} clips`; try { - const originalContent = await readFileContent(pid, targetPath); - const patchTarget = buildPatchTarget(element); - if (!patchTarget) { - throw new Error(`Timeline element ${element.id} is missing a patchable target`); + // Group by owning source file — one read → remove-all → duration-sync + // cycle per file, all folded into a single history entry below. + const groups = new Map(); + for (const element of elementsToDelete) { + const targetPath = element.sourceFile || activeCompPath || "index.html"; + const bucket = groups.get(targetPath); + if (bucket) bucket.push(element); + else groups.set(targetPath, [element]); } - const removeResponse = await fetch( - `/api/projects/${pid}/file-mutations/remove-element/${encodeURIComponent(targetPath)}`, - { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ target: patchTarget }), - }, - ); - if (!removeResponse.ok) { - throw new Error(`Failed to delete ${element.id} from ${targetPath}`); + const originals = new Map(); + const patchedFiles: Record = {}; + for (const [targetPath, groupElements] of groups) { + const originalContent = await readFileContent(pid, targetPath); + originals.set(targetPath, originalContent); + let content = originalContent; + for (const element of groupElements) { + const patchTarget = buildPatchTarget(element); + if (!patchTarget) { + throw new Error(`Timeline element ${element.id} is missing a patchable target`); + } + const removeResponse = await fetch( + `/api/projects/${pid}/file-mutations/remove-element/${encodeURIComponent(targetPath)}`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ target: patchTarget }), + }, + ); + if (!removeResponse.ok) { + throw new Error(`Failed to delete ${element.id} from ${targetPath}`); + } + const removeData = (await removeResponse.json()) as { + changed?: boolean; + content?: string; + }; + content = typeof removeData.content === "string" ? removeData.content : content; + } + // Content-driven duration: shrink the composition to the furthest + // remaining clip end, read from the post-removal SOURCE (raw + // data-duration), so deleting the last/longest clip removes trailing + // empty space. Measured from the source, not the store, whose + // durations are runtime-truncated (HANDOFF-3 §6.1 feedback loop). + const deleteContentEnd = furthestClipEndFromSource(content); + patchedFiles[targetPath] = setCompositionDurationToContent(content, deleteContentEnd); + // Optimistically reflect the shrunk length in the readout/seek bar. + if (deleteContentEnd > 0 && targetPath === (activeCompPath || "index.html")) { + usePlayerStore.getState().setDuration(deleteContentEnd); + } } - const removeData = (await removeResponse.json()) as { - changed?: boolean; - content?: string; - }; - const removedContent = - typeof removeData.content === "string" ? removeData.content : originalContent; - // Content-driven duration: shrink the composition to the furthest remaining - // clip end, read from the post-removal SOURCE (raw data-duration), so - // deleting the last/longest clip removes trailing empty space. Measured - // from the source, not the store, whose durations are runtime-truncated - // (HANDOFF-3 §6.1 feedback loop). - const deleteContentEnd = furthestClipEndFromSource(removedContent); - const patchedContent = setCompositionDurationToContent(removedContent, deleteContentEnd); - // Optimistically reflect the shrunk length in the readout/seek bar. - if (deleteContentEnd > 0) usePlayerStore.getState().setDuration(deleteContentEnd); domEditSaveTimestampRef.current = Date.now(); await saveProjectFilesWithHistory({ projectId: pid, - label: "Delete timeline clip", + label: count === 1 ? "Delete timeline clip" : `Delete ${count} timeline clips`, kind: "timeline", - files: { [targetPath]: patchedContent }, - readFile: async () => originalContent, + files: patchedFiles, + readFile: async (path) => originals.get(path) ?? "", writeFile: writeProjectFile, recordEdit, }); + const deletedKeys = new Set(elementsToDelete.map((e) => e.key ?? e.id)); usePlayerStore .getState() - .setElements( - timelineElements.filter((te) => (te.key ?? te.id) !== (element.key ?? element.id)), - ); + .setElements(timelineElements.filter((te) => !deletedKeys.has(te.key ?? te.id))); usePlayerStore.getState().setSelectedElementId(null); + usePlayerStore.getState().clearSelectedElementIds(); forceReloadSdkSession?.(); reloadPreview(); - showToast(`Deleted ${label}. Use Undo to restore it.`, "info"); + showToast(`Deleted ${label}. Use Undo to restore ${count === 1 ? "it" : "them"}.`, "info"); } catch (error) { - const message = error instanceof Error ? error.message : "Failed to delete timeline clip"; + const message = error instanceof Error ? error.message : "Failed to delete timeline clips"; showToast(message); } }, @@ -452,6 +476,26 @@ export function useTimelineEditing({ forceReloadSdkSession, ], ); + + const handleTimelineElementDelete = useCallback( + (element: TimelineElement) => { + // Deleting a clip that is part of the marquee multi-selection deletes the + // WHOLE selection (standard NLE behavior) — one atomic pass, single undo. + // A delete on a clip outside the selection only removes that clip. + const { selectedElementIds } = usePlayerStore.getState(); + const key = element.key ?? element.id; + if (selectedElementIds.size > 1 && selectedElementIds.has(key)) { + const byKey = new Map(timelineElements.map((te) => [te.key ?? te.id, te])); + const targets = [...selectedElementIds] + .map((id) => byKey.get(id)) + .filter((te): te is TimelineElement => te != null); + if (!targets.some((te) => (te.key ?? te.id) === key)) targets.push(element); + return handleTimelineElementsDelete(targets); + } + return handleTimelineElementsDelete([element]); + }, + [handleTimelineElementsDelete, timelineElements], + ); // fallow-ignore-next-line complexity const handleTimelineAssetDrop = useCallback( // fallow-ignore-next-line complexity @@ -645,6 +689,7 @@ export function useTimelineEditing({ handleTimelineElementMove, handleTimelineElementsMove, handleTimelineElementResize, + handleTimelineElementsDelete, handleToggleTrackHidden, handleToggleElementHidden, handleTimelineElementDelete, diff --git a/packages/studio/src/player/components/Timeline.test.ts b/packages/studio/src/player/components/Timeline.test.ts index f6f5258391..c770f7e818 100644 --- a/packages/studio/src/player/components/Timeline.test.ts +++ b/packages/studio/src/player/components/Timeline.test.ts @@ -18,7 +18,14 @@ import { shouldHandleTimelineDeleteKey, shouldAutoScrollTimeline, } from "./Timeline"; -import { RULER_H, TRACK_H } from "./timelineLayout"; +import { + GUTTER, + MIN_TIMELINE_EXTENT_S, + RULER_H, + TRACK_H, + getTimelineDisplayContentWidth, + getTimelineFitPps, +} from "./timelineLayout"; import { formatTime } from "../lib/time"; import { usePlayerStore } from "../store/playerStore"; import { TimelineEditProvider } from "../../contexts/TimelineEditContext"; @@ -390,6 +397,80 @@ describe("shouldAutoScrollTimeline", () => { }); }); +describe("getTimelineFitPps (min 60s extent)", () => { + const viewport = 632; // usable width = 632 - GUTTER - 2 = 598 + + it("computes fit pps against the 60s floor for short compositions", () => { + // A 10s comp maps 60s onto the viewport → the comp takes ~1/6 of the width. + const pps = getTimelineFitPps(viewport, 10); + expect(pps).toBeCloseTo((viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S); + expect(10 * pps).toBeCloseTo((viewport - GUTTER - 2) / 6); + }); + + it("keeps filling the viewport with the composition when it is 60s or longer", () => { + expect(getTimelineFitPps(viewport, 60)).toBeCloseTo((viewport - GUTTER - 2) / 60); + expect(getTimelineFitPps(viewport, 120)).toBeCloseTo((viewport - GUTTER - 2) / 120); + }); + + it("falls back to 100 pps before the viewport is measured", () => { + expect(getTimelineFitPps(0, 10)).toBe(100); + expect(getTimelineFitPps(GUTTER, 10)).toBe(100); + expect(getTimelineFitPps(Number.NaN, 10)).toBe(100); + }); + + it("uses the floor for zero/invalid durations", () => { + expect(getTimelineFitPps(viewport, 0)).toBeCloseTo( + (viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S, + ); + expect(getTimelineFitPps(viewport, Number.NaN)).toBeCloseTo( + (viewport - GUTTER - 2) / MIN_TIMELINE_EXTENT_S, + ); + }); +}); + +describe("getTimelineDisplayContentWidth", () => { + it("always spans at least MIN_TIMELINE_EXTENT_S seconds of content", () => { + // 10s of content at 20 pps = 200px; the floor keeps 60s (1200px) rendered. + expect( + getTimelineDisplayContentWidth({ trackContentWidth: 200, viewportWidth: 400, pps: 20 }), + ).toBe(MIN_TIMELINE_EXTENT_S * 20); + }); + + it("still fills the viewport when that is larger than the 60s floor", () => { + expect( + getTimelineDisplayContentWidth({ trackContentWidth: 200, viewportWidth: 2000, pps: 5 }), + ).toBe(2000 - GUTTER - 2); + }); + + it("tracks a drag ghost past every other bound (drag-to-extend)", () => { + expect( + getTimelineDisplayContentWidth({ + trackContentWidth: 500, + viewportWidth: 400, + pps: 5, + dragGhostEndPx: 5000, + }), + ).toBe(5000); + }); + + it("tracks a resize (trim) ghost past every other bound (trim-to-extend)", () => { + expect( + getTimelineDisplayContentWidth({ + trackContentWidth: 500, + viewportWidth: 400, + pps: 5, + resizeGhostEndPx: 4200, + }), + ).toBe(4200); + }); + + it("keeps long content authoritative", () => { + expect( + getTimelineDisplayContentWidth({ trackContentWidth: 9000, viewportWidth: 400, pps: 50 }), + ).toBe(9000); + }); +}); + describe("getTimelineScrollLeftForZoomTransition", () => { it("resets horizontal scroll when switching from manual zoom back to fit", () => { expect(getTimelineScrollLeftForZoomTransition("manual", "fit", 480)).toBe(0); diff --git a/packages/studio/src/player/components/Timeline.tsx b/packages/studio/src/player/components/Timeline.tsx index f3226bfcdd..d599ab9589 100644 --- a/packages/studio/src/player/components/Timeline.tsx +++ b/packages/studio/src/player/components/Timeline.tsx @@ -28,6 +28,8 @@ import { GUTTER, generateTicks, getTimelineCanvasHeight, + getTimelineDisplayContentWidth, + getTimelineFitPps, shouldShowTimelineShortcutHint, } from "./timelineLayout"; import { useResolvedTimelineEditCallbacks } from "./useResolvedTimelineEditCallbacks"; @@ -272,10 +274,9 @@ export const Timeline = memo(function Timeline({ const selectedElementRef = useRef(selectedElement); selectedElementRef.current = selectedElement; - const fitPps = - viewportWidth > GUTTER && effectiveDuration > 0 - ? (viewportWidth - GUTTER - 2) / effectiveDuration - : 100; + // Fit pps maps at least MIN_TIMELINE_EXTENT_S onto the viewport, so short + // comps show a 60s ruler with usable empty space (see getTimelineFitPps). + const fitPps = getTimelineFitPps(viewportWidth, effectiveDuration); const pps = getTimelinePixelsPerSecond(fitPps, zoomMode, manualZoomPercent); ppsRef.current = pps; const trackContentWidth = Math.max(0, effectiveDuration * pps); @@ -289,15 +290,23 @@ export const Timeline = memo(function Timeline({ const dragGhostEndPx = draggedClip?.started ? (draggedClip.previewStart + draggedClip.element.duration) * pps + DRAG_EXTEND_MARGIN_PX : 0; - // The timeline canvas always fills at least the viewport width: when the content - // is shorter than the visible area (e.g. zoomed out), the ruler + empty track - // lanes keep going into the space instead of leaving dead black — CapCut-style. - // Only the RENDERED extent grows; clip positions/durations are untouched. - const displayContentWidth = Math.max( + // Trim-to-extend: same mechanic for a right-edge RESIZE — the rendered extent + // tracks the trim preview's end so the edge auto-scroll zone always has room + // to keep stepping while the trim grows past the current timeline width. + const resizeGhostEndPx = resizingClip?.started + ? (resizingClip.previewStart + resizingClip.previewDuration) * pps + DRAG_EXTEND_MARGIN_PX + : 0; + // The timeline canvas always fills at least the viewport width AND the + // MIN_TIMELINE_EXTENT_S floor: the ruler + empty track lanes keep going into + // the space instead of leaving dead black — CapCut-style. Only the RENDERED + // extent grows; clip positions/durations are untouched. + const displayContentWidth = getTimelineDisplayContentWidth({ trackContentWidth, - viewportWidth - GUTTER - 2, + viewportWidth, + pps, dragGhostEndPx, - ); + resizeGhostEndPx, + }); const displayDuration = pps > 0 ? displayContentWidth / pps : effectiveDuration; const clipStateVersion = useMemo( () => diff --git a/packages/studio/src/player/components/TimelineCanvas.tsx b/packages/studio/src/player/components/TimelineCanvas.tsx index e0254b4796..d9e0574895 100644 --- a/packages/studio/src/player/components/TimelineCanvas.tsx +++ b/packages/studio/src/player/components/TimelineCanvas.tsx @@ -364,6 +364,7 @@ export const TimelineCanvas = memo(function TimelineCanvas({ element: el, edge, originClientX: e.clientX, + originScrollLeft: scrollRef.current?.scrollLeft ?? 0, previewStart: el.start, previewDuration: el.duration, previewPlaybackStart: el.playbackStart, diff --git a/packages/studio/src/player/components/timelineClipDragCommit.test.ts b/packages/studio/src/player/components/timelineClipDragCommit.test.ts index c181959c32..7771b8c94c 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.test.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.test.ts @@ -81,6 +81,81 @@ describe("commitDraggedClipMove", () => { expect(map.b).toEqual({ start: 10, track: 0 }); }); + it("multi-selection time-move shifts EVERY selected clip by the drag delta (atomic)", () => { + const elements = [el("a", 0, 2, 3), el("b", 1, 10, 3), el("c", 2, 20, 3)]; + const onMoveElement = vi.fn(); + const onMoveElements = vi.fn(); + // Drag 'a' +5s on its own lane while {a, b} are marquee-selected. + commitDraggedClipMove(drag(elements[0], { previewStart: 7, previewTrack: 0 }), { + elements, + trackOrder: [0, 1, 2], + updateElement: vi.fn(), + onMoveElement, + onMoveElements, + selectedKeys: new Set(["a", "b"]), + }); + expect(onMoveElement).not.toHaveBeenCalled(); + expect(onMoveElements).toHaveBeenCalledTimes(1); + const map = editMap(onMoveElements.mock.calls[0][0]); + expect(map.a).toEqual({ start: 7, track: 0 }); + expect(map.b).toEqual({ start: 15, track: 1 }); // same +5 delta, keeps its lane + expect(map.c).toBeUndefined(); // unselected clips untouched + }); + + it("multi-selection move clamps shifted clips at 0 and applies the store update optimistically", () => { + const elements = [el("a", 0, 6, 3), el("b", 1, 2, 3)]; + const updateElement = vi.fn(); + const onMoveElements = vi.fn(); + // Drag 'a' −5s: b would land at −3 → clamps to 0. + commitDraggedClipMove(drag(elements[0], { previewStart: 1, previewTrack: 0 }), { + elements, + trackOrder: [0, 1], + updateElement, + onMoveElements, + selectedKeys: new Set(["a", "b"]), + }); + const map = editMap(onMoveElements.mock.calls[0][0]); + expect(map.a).toEqual({ start: 1, track: 0 }); + expect(map.b).toEqual({ start: 0, track: 1 }); + expect(updateElement).toHaveBeenCalledWith("a", { start: 1, track: 0 }); + expect(updateElement).toHaveBeenCalledWith("b", { start: 0, track: 1 }); + }); + + it("a multi-selection that does NOT include the dragged clip moves only the dragged clip", () => { + const elements = [el("a", 0, 0, 3), el("b", 1, 10, 3)]; + const onMoveElement = vi.fn(); + const onMoveElements = vi.fn(); + commitDraggedClipMove(drag(elements[0], { previewStart: 6, previewTrack: 0 }), { + elements, + trackOrder: [0, 1], + updateElement: vi.fn(), + onMoveElement, + onMoveElements, + selectedKeys: new Set(["b", "x"]), + }); + expect(onMoveElements).not.toHaveBeenCalled(); + expect(onMoveElement).toHaveBeenCalledTimes(1); + expect(onMoveElement.mock.calls[0][1]).toEqual({ start: 6, track: 0 }); + }); + + it("multi-selection lane change: dragged clip changes track, the rest of the selection shifts in time only", () => { + const elements = [el("a", 0, 0, 3), el("b", 1, 10, 3), el("c", 2, 20, 3)]; + const onMoveElements = vi.fn(); + // Drag 'a' +4s down onto lane 1 (non-overlapping with b) while {a, c} selected. + commitDraggedClipMove(drag(elements[0], { previewStart: 4, previewTrack: 1 }), { + elements, + trackOrder: [0, 1, 2], + updateElement: vi.fn(), + onMoveElements, + selectedKeys: new Set(["a", "c"]), + }); + const map = editMap(onMoveElements.mock.calls[0][0]); + expect(map.a.start).toBe(4); // dragged: new time + new (normalized) lane + expect(map.c.start).toBe(24); // selected passenger: same +4 delta + expect(map.c.track).not.toBe(map.a.track); // passenger keeps its own lane + expect(map.b.start).toBe(10); // unselected: time untouched + }); + it("inserting a new lane slots the dragged clip in and shifts the rest (fractional → normalized)", () => { const elements = [el("a", 0, 0, 5), el("b", 1, 0, 5), el("c", 2, 0, 5)]; const onMoveElement = vi.fn(); diff --git a/packages/studio/src/player/components/timelineClipDragCommit.ts b/packages/studio/src/player/components/timelineClipDragCommit.ts index 68d3b1aa80..daf57aba16 100644 --- a/packages/studio/src/player/components/timelineClipDragCommit.ts +++ b/packages/studio/src/player/components/timelineClipDragCommit.ts @@ -16,9 +16,36 @@ export interface DragCommitDeps { onMoveElement?: (element: TimelineElement, updates: StartTrack) => Promise | void; /** Atomic multi-clip persist (single undo) for lane changes + track inserts. */ onMoveElements?: (edits: TimelineMoveEdit[]) => Promise | void; + /** + * The current multi-selection (store.selectedElementIds). When the dragged + * clip is part of a multi-selection (size > 1), the WHOLE selection moves by + * the dragged clip's time delta — the standard NLE gesture. Track changes + * apply to the dragged clip only; the others keep their lanes. + */ + selectedKeys?: ReadonlySet | null; } const keyOf = (e: TimelineElement) => e.key ?? e.id; +const round3 = (v: number) => Math.round(v * 1000) / 1000; + +/** Optimistically apply + persist a batch of moves with rollback on failure. */ +function persistMoveEdits(edits: TimelineMoveEdit[], deps: DragCommitDeps): void { + if (edits.length === 0) return; + const { updateElement, onMoveElement, onMoveElements } = deps; + const prev = edits.map((e) => ({ + key: keyOf(e.element), + start: e.element.start, + track: e.element.track, + })); + for (const e of edits) updateElement(keyOf(e.element), e.updates); + const persisted = onMoveElements + ? onMoveElements(edits) + : Promise.all(edits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates)))); + Promise.resolve(persisted).catch((error) => { + for (const p of prev) updateElement(p.key, { start: p.start, track: p.track }); + console.error("[Timeline] Failed to persist clip edits", error); + }); +} /** * A fractional track value for a NEW lane inserted at boundary `insertRow` in @@ -45,13 +72,29 @@ export function insertTrackValue(trackOrder: number[], insertRow: number): numbe */ // fallow-ignore-next-line complexity export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDeps): void { - const { elements, trackOrder, updateElement, onMoveElement, onMoveElements } = deps; + const { elements, trackOrder, updateElement, onMoveElement, selectedKeys } = deps; const dragKey = keyOf(drag.element); const isTopologyChange = drag.insertRow != null || drag.previewTrack !== drag.element.track; + // Multi-selection drag: engaged only when the dragged clip is itself part of + // a multi-selection. Every selected clip shifts by the same time delta + // (clamped ≥ 0); only the dragged clip changes track. + const multiKeys = + selectedKeys && selectedKeys.size > 1 && selectedKeys.has(dragKey) ? selectedKeys : null; + const delta = drag.previewStart - drag.element.start; + const movedStart = (e: TimelineElement): number => + keyOf(e) === dragKey ? drag.previewStart : Math.max(0, round3(e.start + delta)); // ── Pure time-move (same lane) ────────────────────────────────────────────── if (!isTopologyChange) { - if (drag.previewStart === drag.element.start) return; + if (delta === 0) return; + if (multiKeys) { + const edits: TimelineMoveEdit[] = elements + .filter((e) => multiKeys.has(keyOf(e))) + .map((e) => ({ element: e, updates: { start: movedStart(e), track: e.track } })) + .filter((e) => e.updates.start !== e.element.start); + persistMoveEdits(edits, deps); + return; + } const updates = { start: drag.previewStart, track: drag.element.track }; const prev = { start: drag.element.start, track: drag.element.track }; updateElement(dragKey, updates); @@ -65,31 +108,20 @@ export function commitDraggedClipMove(drag: DraggedClipState, deps: DragCommitDe // ── Lane change / new track: normalize the whole set, persist all atomically ─ const targetTrack = drag.insertRow != null ? insertTrackValue(trackOrder, drag.insertRow) : drag.previewTrack; - const candidate = elements.map((e) => - keyOf(e) === dragKey ? { ...e, start: drag.previewStart, track: targetTrack } : e, - ); + const candidate = elements.map((e) => { + if (keyOf(e) === dragKey) return { ...e, start: drag.previewStart, track: targetTrack }; + if (multiKeys?.has(keyOf(e))) return { ...e, start: movedStart(e) }; + return e; + }); const normalized = normalizeToZones(candidate); const bySrc = new Map(elements.map((e) => [keyOf(e), e])); const edits: TimelineMoveEdit[] = []; for (const norm of normalized) { const src = bySrc.get(keyOf(norm)); if (!src) continue; - const start = keyOf(norm) === dragKey ? drag.previewStart : src.start; + const start = + keyOf(norm) === dragKey || multiKeys?.has(keyOf(norm)) ? movedStart(src) : src.start; edits.push({ element: src, updates: { start, track: norm.track } }); } - if (edits.length === 0) return; - - const prev = edits.map((e) => ({ - key: keyOf(e.element), - start: e.element.start, - track: e.element.track, - })); - for (const e of edits) updateElement(keyOf(e.element), e.updates); - const persisted = onMoveElements - ? onMoveElements(edits) - : Promise.all(edits.map((e) => Promise.resolve(onMoveElement?.(e.element, e.updates)))); - Promise.resolve(persisted).catch((error) => { - for (const p of prev) updateElement(p.key, { start: p.start, track: p.track }); - console.error("[Timeline] Failed to persist clip edits", error); - }); + persistMoveEdits(edits, deps); } diff --git a/packages/studio/src/player/components/timelineLayout.ts b/packages/studio/src/player/components/timelineLayout.ts index fbd75c5755..dad916ed16 100644 --- a/packages/studio/src/player/components/timelineLayout.ts +++ b/packages/studio/src/player/components/timelineLayout.ts @@ -14,6 +14,15 @@ export const CLIP_HANDLE_W = 18; * rendered width (see Timeline.tsx displayContentWidth). */ export const DRAG_EXTEND_MARGIN_PX = 160; +/** + * The rendered timeline always spans at least this many seconds of ruler + + * track lanes, even when the composition is shorter — the empty space on the + * right is a real, drag/drop-enabled surface (clips can be moved into it; the + * composition grows on commit, content-driven). In fit mode the fit pps is + * derived against this floor, so a 10s comp renders as ~1/6 of the viewport + * with 60s of ruler after it. + */ +export const MIN_TIMELINE_EXTENT_S = 60; const TIMELINE_SCROLL_BUFFER = 20; /* ── Timeline duration ─────────────────────────────────────────────── */ @@ -137,6 +146,45 @@ export function formatTimelineTickLabel(time: number, duration: number, majorInt return formatTime(safeTime); } +/* ── Width / duration derivation ──────────────────────────────────── */ +/** + * Fit-mode pixels-per-second: fill the viewport with the composition, but + * never map fewer than MIN_TIMELINE_EXTENT_S seconds onto it — a short comp + * takes a fraction of the width and the remaining ruler runs to 1:00. + * Manual zoom multiplies this base, so the floor only anchors the default. + */ +export function getTimelineFitPps(viewportWidth: number, effectiveDuration: number): number { + const safeDuration = + Number.isFinite(effectiveDuration) && effectiveDuration > 0 ? effectiveDuration : 0; + const span = Math.max(safeDuration, MIN_TIMELINE_EXTENT_S); + if (!Number.isFinite(viewportWidth) || viewportWidth <= GUTTER) return 100; + return (viewportWidth - GUTTER - 2) / span; +} + +/** + * The rendered timeline extent in px. Always covers, whichever is largest: + * the actual clip content, the visible viewport (no dead black after short + * content — CapCut-style), a live drag or resize ghost plus the auto-scroll + * margin (drag/trim-to-extend), and the MIN_TIMELINE_EXTENT_S floor. Only the + * RENDERED extent grows; clip positions/durations are untouched. + */ +export function getTimelineDisplayContentWidth(input: { + trackContentWidth: number; + viewportWidth: number; + pps: number; + dragGhostEndPx?: number; + resizeGhostEndPx?: number; +}): number { + const safePps = Number.isFinite(input.pps) ? Math.max(input.pps, 0) : 0; + return Math.max( + input.trackContentWidth, + input.viewportWidth - GUTTER - 2, + input.dragGhostEndPx ?? 0, + input.resizeGhostEndPx ?? 0, + MIN_TIMELINE_EXTENT_S * safePps, + ); +} + /* ── Scroll / zoom helpers ────────────────────────────────────────── */ export function shouldAutoScrollTimeline( zoomMode: ZoomMode, diff --git a/packages/studio/src/player/components/timelineMarquee.test.ts b/packages/studio/src/player/components/timelineMarquee.test.ts index f137eff095..4154de25e8 100644 --- a/packages/studio/src/player/components/timelineMarquee.test.ts +++ b/packages/studio/src/player/components/timelineMarquee.test.ts @@ -2,12 +2,45 @@ import { describe, it, expect } from "vitest"; import { MARQUEE_DRAG_THRESHOLD_PX, isMarqueeDrag, + isTimelineRulerPress, getMarqueeRect, getTimelineClipRect, computeMarqueeSelection, } from "./timelineMarquee"; import { GUTTER, TRACK_H, RULER_H, CLIP_Y } from "./timelineLayout"; +describe("isTimelineRulerPress", () => { + const rectTop = 500; // scroll container's viewport top + + it("treats a press inside the ruler band as a ruler press (unscrolled)", () => { + expect(isTimelineRulerPress(rectTop, rectTop)).toBe(true); + expect(isTimelineRulerPress(rectTop + RULER_H - 1, rectTop)).toBe(true); + }); + + it("treats a press below the ruler band as a body press", () => { + expect(isTimelineRulerPress(rectTop + RULER_H, rectTop)).toBe(false); + expect(isTimelineRulerPress(rectTop + RULER_H + 100, rectTop)).toBe(false); + }); + + it("stays a ruler press when the body is scrolled down (sticky ruler)", () => { + // The ruler is position:sticky — scrolled down, its VISUAL band is still + // the top RULER_H px of the container. Content-space math + // (clientY - rectTop + scrollTop) would report y = 10 + 300 = 310 ≥ RULER_H + // and misclassify this as a body/marquee press; viewport-space math must + // still classify it as a ruler press regardless of scrollTop. + const scrollTop = 300; + const clientY = rectTop + 10; // visually on the stuck ruler + const contentSpaceY = clientY - rectTop + scrollTop; + expect(contentSpaceY).toBeGreaterThanOrEqual(RULER_H); // the old, broken signal + expect(isTimelineRulerPress(clientY, rectTop)).toBe(true); + }); + + it("honors a custom ruler height", () => { + expect(isTimelineRulerPress(rectTop + 30, rectTop, 32)).toBe(true); + expect(isTimelineRulerPress(rectTop + 33, rectTop, 32)).toBe(false); + }); +}); + describe("isMarqueeDrag", () => { it("treats sub-threshold movement as a click, not a drag", () => { expect(isMarqueeDrag(100, 50, 100, 50)).toBe(false); diff --git a/packages/studio/src/player/components/timelineMarquee.ts b/packages/studio/src/player/components/timelineMarquee.ts index 83e418b823..eead787811 100644 --- a/packages/studio/src/player/components/timelineMarquee.ts +++ b/packages/studio/src/player/components/timelineMarquee.ts @@ -15,6 +15,24 @@ export interface MarqueeClipInput { track: number; } +/** + * Ruler-vs-body decision for a pointerdown on the timeline scroll container. + * + * The ruler is `position: sticky; top: 0` — once the body is scrolled down its + * VISUAL position stays pinned to the container top while its LAYOUT position + * scrolls away. The hit test must therefore use VIEWPORT-space y (clientY + * relative to the scroll container's bounding rect), NOT content-space y + * (clientY - rect.top + scrollTop), which misclassifies a press on the stuck + * ruler as a body/marquee press whenever scrollTop > 0. + */ +export function isTimelineRulerPress( + clientY: number, + scrollRectTop: number, + rulerHeight: number = RULER_H, +): boolean { + return clientY - scrollRectTop < rulerHeight; +} + export function isMarqueeDrag( originX: number, originY: number, diff --git a/packages/studio/src/player/components/useTimelineClipDrag.ts b/packages/studio/src/player/components/useTimelineClipDrag.ts index 01594c48ef..4ae5e63322 100644 --- a/packages/studio/src/player/components/useTimelineClipDrag.ts +++ b/packages/studio/src/player/components/useTimelineClipDrag.ts @@ -54,6 +54,14 @@ export interface ResizingClipState { element: TimelineElement; edge: "start" | "end"; originClientX: number; + /** + * scrollLeft at gesture start. Edge auto-scroll moves the content under a + * stationary pointer, so the trim math folds (current − origin) scrollLeft + * into the pointer x — mirroring resolveTimelineMove's scroll compensation. + * Optional so pre-existing constructors/tests stay valid; when absent the + * first preview update captures the current scrollLeft. + */ + originScrollLeft?: number; previewStart: number; previewDuration: number; previewPlaybackStart?: number; @@ -260,6 +268,127 @@ export function useTimelineClipDrag({ [scrollRef, ppsRef, durationRef, trackOrderRef, buildSnapTargets], ); + // Recompute the trim preview for a pointer x. Shared by the pointermove + // resize branch and the edge auto-scroll stepper (which re-runs it as the + // content scrolls under a stationary pointer, so the trim keeps tracking). + // fallow-ignore-next-line complexity + const applyResizePointer = useCallback( + // fallow-ignore-next-line complexity + (resize: ResizingClipState, clientX: number) => { + const scroll = scrollRef.current; + // Scroll compensation: auto-scroll moves the content while the pointer + // stays put, so fold the scroll delta into the pointer x (mirrors + // resolveTimelineMove's originScrollLeft handling). + const originScrollLeft = resize.originScrollLeft ?? scroll?.scrollLeft ?? 0; + const effectiveClientX = + clientX + ((scroll?.scrollLeft ?? originScrollLeft) - originScrollLeft); + + const sourceRemaining = + resize.element.sourceDuration != null + ? Math.max( + 0, + (resize.element.sourceDuration - (resize.element.playbackStart ?? 0)) / + Math.max(resize.element.playbackRate ?? 1, 0.1), + ) + : Number.POSITIVE_INFINITY; + const normalizedTag = resize.element.tag.toLowerCase(); + const canSeedPlaybackStart = normalizedTag === "audio" || normalizedTag === "video"; + const playbackRate = Math.max(resize.element.playbackRate ?? 1, 0.1); + // Trim limit = available source media only — NOT the composition length. + // Duration is content-driven (the comp grows/shrinks to fit on commit), so + // capping a trim at the current comp end both blocked extending the last + // clip rightward and, after a far move, collapsed a clip to the sliver + // between its start and the comp end (the 8s→0.95s audio incident). + // Images/text/shapes have no source, so they extend freely. + const maxEnd = resize.element.start + sourceRemaining; + let nextResize = resolveTimelineResize( + { + start: resize.element.start, + duration: resize.element.duration, + originClientX: resize.originClientX, + pixelsPerSecond: ppsRef.current, + minStart: 0, + maxEnd, + playbackStart: + resize.edge === "start" && canSeedPlaybackStart + ? (resize.element.playbackStart ?? 0) + : resize.element.playbackStart, + playbackRate: resize.element.playbackRate, + }, + resize.edge, + effectiveClientX, + ); + + // Snap edge to unified targets (beats + clip edges + playhead) when available. + // The snap must stay inside the same limits resolveTimelineResize enforces, + // or it would push the edge past the available source media / composition end. + // The music track defines the beats, so it must not snap to them — + // but it still snaps to the playhead and other clip edges. + const trimTargets = buildSnapTargets( + resize.element.key ?? resize.element.id, + !isMusicTrack(resize.element), + ); + if (trimTargets.length > 0) { + const snapSecs = TIMELINE_SNAP_PX / Math.max(ppsRef.current, 1); + if (resize.edge === "end") { + const edgeTime = nextResize.start + nextResize.duration; + const snapped = snapTimelineTime(edgeTime, trimTargets, snapSecs).time; + // Stay within [start+minDuration, maxEnd] so the snap can't create a + // degenerate clip or run past the source/composition limit. + const snappedDuration = Math.round((snapped - nextResize.start) * 1000) / 1000; + if (snapped !== edgeTime && snapped <= maxEnd + 1e-6 && snappedDuration >= 0.05) { + nextResize = { ...nextResize, duration: snappedDuration }; + } + } else { + const snapped = snapTimelineTime(nextResize.start, trimTargets, snapSecs).time; + const delta = nextResize.start - snapped; // >0 when snapping left + // Leftward snap reveals more source; cap so playbackStart can't go < 0. + const maxLeftDelta = + nextResize.playbackStart != null + ? nextResize.playbackStart / playbackRate + : Number.POSITIVE_INFINITY; + // Also require the resulting duration to stay >= minDuration so a + // rightward snap (delta < 0) can't collapse the clip to zero/negative. + const snappedDuration = Math.round((nextResize.duration + delta) * 1000) / 1000; + if ( + snapped !== nextResize.start && + snapped >= 0 && + delta <= maxLeftDelta + 1e-6 && + snappedDuration >= 0.05 + ) { + nextResize = { + ...nextResize, + start: snapped, + duration: snappedDuration, + playbackStart: + nextResize.playbackStart != null + ? Math.round( + Math.max(0, nextResize.playbackStart - delta * playbackRate) * 1000, + ) / 1000 + : undefined, + }; + } + } + } + + setResizingClip((prev) => + prev + ? { + ...prev, + started: true, + originScrollLeft, + previewStart: nextResize.start, + previewDuration: nextResize.duration, + previewPlaybackStart: nextResize.playbackStart, + } + : prev, + ); + }, + [scrollRef, ppsRef, buildSnapTargets], + ); + const applyResizePointerRef = useRef(applyResizePointer); + applyResizePointerRef.current = applyResizePointer; + const stopClipDragAutoScroll = useCallback(() => { clipDragPointerRef.current = null; if (clipDragScrollRaf.current) { @@ -271,9 +400,10 @@ export function useTimelineClipDrag({ const stepClipDragAutoScroll = useCallback(() => { clipDragScrollRaf.current = 0; const drag = draggedClipRef.current; + const resize = resizingClipRef.current; const pointer = clipDragPointerRef.current; const scroll = scrollRef.current; - if (!drag || !pointer || !scroll) return; + if ((!drag && !resize) || !pointer || !scroll) return; const rect = scroll.getBoundingClientRect(); const delta = resolveTimelineAutoScroll(rect, pointer.clientX, pointer.clientY); @@ -287,9 +417,15 @@ export function useTimelineClipDrag({ scroll.scrollLeft = nextScrollLeft; scroll.scrollTop = nextScrollTop; - setDraggedClip((prev) => - prev ? updateDraggedClipPreview(prev, pointer.clientX, pointer.clientY) : prev, - ); + if (drag) { + setDraggedClip((prev) => + prev ? updateDraggedClipPreview(prev, pointer.clientX, pointer.clientY) : prev, + ); + } else if (resize) { + // Re-run the trim preview so the edge keeps tracking while the content + // scrolls under the stationary pointer (scroll-compensated pointer x). + applyResizePointerRef.current(resize, pointer.clientX); + } clipDragScrollRaf.current = requestAnimationFrame(stepClipDragAutoScroll); }, [scrollRef, updateDraggedClipPreview]); @@ -340,105 +476,11 @@ export function useTimelineClipDrag({ setShowPopover(false); setRangeSelectionRef.current?.(null); - const sourceRemaining = - resize.element.sourceDuration != null - ? Math.max( - 0, - (resize.element.sourceDuration - (resize.element.playbackStart ?? 0)) / - Math.max(resize.element.playbackRate ?? 1, 0.1), - ) - : Number.POSITIVE_INFINITY; - const normalizedTag = resize.element.tag.toLowerCase(); - const canSeedPlaybackStart = normalizedTag === "audio" || normalizedTag === "video"; - const playbackRate = Math.max(resize.element.playbackRate ?? 1, 0.1); - // Trim limit = available source media only — NOT the composition length. - // Duration is content-driven (the comp grows/shrinks to fit on commit), so - // capping a trim at the current comp end both blocked extending the last - // clip rightward and, after a far move, collapsed a clip to the sliver - // between its start and the comp end (the 8s→0.95s audio incident). - // Images/text/shapes have no source, so they extend freely. - const maxEnd = resize.element.start + sourceRemaining; - let nextResize = resolveTimelineResize( - { - start: resize.element.start, - duration: resize.element.duration, - originClientX: resize.originClientX, - pixelsPerSecond: ppsRef.current, - minStart: 0, - maxEnd, - playbackStart: - resize.edge === "start" && canSeedPlaybackStart - ? (resize.element.playbackStart ?? 0) - : resize.element.playbackStart, - playbackRate: resize.element.playbackRate, - }, - resize.edge, - e.clientX, - ); - - // Snap edge to unified targets (beats + clip edges + playhead) when available. - // The snap must stay inside the same limits resolveTimelineResize enforces, - // or it would push the edge past the available source media / composition end. - // The music track defines the beats, so it must not snap to them — - // but it still snaps to the playhead and other clip edges. - const trimTargets = buildSnapTargets( - resize.element.key ?? resize.element.id, - !isMusicTrack(resize.element), - ); - if (trimTargets.length > 0) { - const snapSecs = TIMELINE_SNAP_PX / Math.max(ppsRef.current, 1); - if (resize.edge === "end") { - const edgeTime = nextResize.start + nextResize.duration; - const snapped = snapTimelineTime(edgeTime, trimTargets, snapSecs).time; - // Stay within [start+minDuration, maxEnd] so the snap can't create a - // degenerate clip or run past the source/composition limit. - const snappedDuration = Math.round((snapped - nextResize.start) * 1000) / 1000; - if (snapped !== edgeTime && snapped <= maxEnd + 1e-6 && snappedDuration >= 0.05) { - nextResize = { ...nextResize, duration: snappedDuration }; - } - } else { - const snapped = snapTimelineTime(nextResize.start, trimTargets, snapSecs).time; - const delta = nextResize.start - snapped; // >0 when snapping left - // Leftward snap reveals more source; cap so playbackStart can't go < 0. - const maxLeftDelta = - nextResize.playbackStart != null - ? nextResize.playbackStart / playbackRate - : Number.POSITIVE_INFINITY; - // Also require the resulting duration to stay >= minDuration so a - // rightward snap (delta < 0) can't collapse the clip to zero/negative. - const snappedDuration = Math.round((nextResize.duration + delta) * 1000) / 1000; - if ( - snapped !== nextResize.start && - snapped >= 0 && - delta <= maxLeftDelta + 1e-6 && - snappedDuration >= 0.05 - ) { - nextResize = { - ...nextResize, - start: snapped, - duration: snappedDuration, - playbackStart: - nextResize.playbackStart != null - ? Math.round( - Math.max(0, nextResize.playbackStart - delta * playbackRate) * 1000, - ) / 1000 - : undefined, - }; - } - } - } - - setResizingClip((prev) => - prev - ? { - ...prev, - started: true, - previewStart: nextResize.start, - previewDuration: nextResize.duration, - previewPlaybackStart: nextResize.playbackStart, - } - : prev, - ); + applyResizePointerRef.current(resize, e.clientX); + // Edge auto-scroll during a trim, exactly like the move branch — lets a + // right-edge trim keep extending past the current viewport (the stepper + // re-runs the scroll-compensated preview each frame). + syncClipDragAutoScrollRef.current(e.clientX, e.clientY); return; } @@ -537,13 +579,15 @@ export function useTimelineClipDrag({ clearSuppressedClick(); // Commit the drag — insert (new track), main-track ripple (reflow contiguous), - // or a plain single-clip move. See timelineClipDragCommit. + // a plain single-clip move, or a multi-selection move (every selected clip + // shifts by the dragged clip's time delta). See timelineClipDragCommit. commitDraggedClipMove(drag, { elements: elementsRef.current, trackOrder: trackOrderRef.current, updateElement, onMoveElement: onMoveElementRef.current, onMoveElements: onMoveElementsRef.current, + selectedKeys: usePlayerStore.getState().selectedElementIds, }); }; diff --git a/packages/studio/src/player/components/useTimelineRangeSelection.ts b/packages/studio/src/player/components/useTimelineRangeSelection.ts index 7a720b5db9..d25299af62 100644 --- a/packages/studio/src/player/components/useTimelineRangeSelection.ts +++ b/packages/studio/src/player/components/useTimelineRangeSelection.ts @@ -2,11 +2,12 @@ import { useRef, useState, useCallback, useEffect } from "react"; import { buildClipRangeSelection, type TimelineRangeSelection } from "./timelineEditing"; import type { TimelineElement } from "../store/playerStore"; import { liveTime, usePlayerStore } from "../store/playerStore"; -import { GUTTER, RULER_H } from "./timelineLayout"; +import { GUTTER } from "./timelineLayout"; import { computeMarqueeSelection, getMarqueeRect, isMarqueeDrag, + isTimelineRulerPress, type MarqueeClipInput, } from "./timelineMarquee"; import type { Rect } from "../../utils/marqueeGeometry"; @@ -122,8 +123,12 @@ export function useTimelineRangeSelection({ setRangeSelection(null); setShowPopover(false); const point = toContentPoint(e.clientX, e.clientY); - // Ruler press → scrub the playhead (the standard scrub surface). - if (!point || point.y < RULER_H) { + // Ruler press → scrub the playhead (the standard scrub surface). The + // ruler is sticky, so this decision uses VIEWPORT-space y — content-space + // y (which folds in scrollTop) breaks once the body is scrolled down and + // the stuck ruler visually overlays scrolled-away track rows. + const scrollRect = scrollRef.current?.getBoundingClientRect(); + if (!point || !scrollRect || isTimelineRulerPress(e.clientY, scrollRect.top)) { isDragging.current = true; seekFromX(e.clientX); return;