Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

fix(timeline): scrub responsiveness, undo grouping, multi-clip drag, gaps, duplicate (#64)

Augustus Otu448e6a60cc8e
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 7d00faac..0eff7303 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -4488,16 +4488,10 @@ export const Preview: React.FC = () => {
const lastPlayheadForRenderRef = useRef<number>(playheadPosition);
const modifiedRenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const renderInFlightRef = useRef<boolean>(false);
+ const pendingRenderTimeRef = useRef<number | null>(null);
useEffect(() => {
if (isPlaying) return;
- if (isScrubbing) {
- releaseScrubVideoElements();
- lastModifiedAtRef.current = project.modifiedAt;
- lastPlayheadForRenderRef.current = playheadPosition;
- lastPreviewRenderTimeRef.current = playheadPosition;
- return;
- }
if (isInteractingRef.current) {
lastModifiedAtRef.current = project.modifiedAt;
@@ -4522,28 +4516,41 @@ export const Preview: React.FC = () => {
}
lastPreviewRenderTimeRef.current = playheadPosition;
- const doRender = async () => {
- if (renderInFlightRef.current) return;
+ const doRender = async (time: number) => {
+ if (renderInFlightRef.current) {
+ // Coalesce: remember the latest requested position and render it
+ // once the current render completes. This is what makes scrubbing
+ // feel responsive even when each render is slower than mouse moves.
+ pendingRenderTimeRef.current = time;
+ return;
+ }
renderInFlightRef.current = true;
try {
- const rendered = await renderFrameDirectly(playheadPosition);
+ const rendered = await renderFrameDirectly(time);
if (!rendered) {
- renderFallbackFrame(playheadPosition);
+ renderFallbackFrame(time);
}
} finally {
renderInFlightRef.current = false;
+ const next = pendingRenderTimeRef.current;
+ if (next !== null && next !== time) {
+ pendingRenderTimeRef.current = null;
+ doRender(next);
+ } else {
+ pendingRenderTimeRef.current = null;
+ }
}
};
if (playheadChanged) {
- doRender();
+ doRender(playheadPosition);
} else if (modifiedChanged) {
if (modifiedRenderTimerRef.current) {
clearTimeout(modifiedRenderTimerRef.current);
}
modifiedRenderTimerRef.current = setTimeout(() => {
modifiedRenderTimerRef.current = null;
- doRender();
+ doRender(playheadPosition);
}, 150);
}
diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsx
index 70d5a7c7..ce15e04f 100644
--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx
+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx
@@ -64,6 +64,12 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const [isInvalidDrop, setIsInvalidDrop] = useState(false);
const [isTrimming, setIsTrimming] = useState(false);
const [trimEdge, setTrimEdge] = useState<"left" | "right" | null>(null);
+ // Snapshot of every additional selected clip at drag start. Multi-clip
+ // drag applies the same time delta to each entry so they stay locked
+ // together as the dragged clip moves.
+ const multiDragSnapshotRef = useRef<
+ Array<{ clipId: string; startTime: number; trackId: string }>
+ >([]);
const trimStartRef = useRef<{
mouseX: number;
startTime: number;
@@ -125,6 +131,24 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
setDragYOffset(0);
setIsInvalidDrop(false);
setIsPendingDrag(true);
+
+ // If this clip is part of a multi-selection, snapshot the other
+ // selected clips' start positions so we can drag them as a group.
+ const selectedIds = useUIStore.getState().getSelectedClipIds();
+ if (selectedIds.length > 1 && selectedIds.includes(clip.id)) {
+ const snapshot: Array<{ clipId: string; startTime: number; trackId: string }> = [];
+ for (const t of allTracks) {
+ for (const c of t.clips) {
+ if (c.id === clip.id) continue;
+ if (!selectedIds.includes(c.id)) continue;
+ if (t.locked) continue;
+ snapshot.push({ clipId: c.id, startTime: c.startTime, trackId: t.id });
+ }
+ }
+ multiDragSnapshotRef.current = snapshot;
+ } else {
+ multiDragSnapshotRef.current = [];
+ }
};
const handleTrimMouseDown =
@@ -175,6 +199,13 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
useEffect(() => {
if (!isDragging) return;
+ // Wrap the entire drag in a single history group so undo collapses
+ // all the per-frame moves (and any companion clips) into one step.
+ const projectStore = useProjectStore.getState();
+ projectStore.beginHistoryGroup(
+ multiDragSnapshotRef.current.length > 0 ? "Move clips" : "Move clip",
+ );
+
let animationFrameId: number | null = null;
const scrollLoop = () => {
@@ -254,9 +285,29 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
pendingDropRef.current = { time: snapResult.time, targetTrackId };
onMoveClip(clip.id, snapResult.time, undefined);
+
+ // Move every companion clip in the multi-selection by the same
+ // delta. Cross-track moves of the primary don't take any
+ // companions along — that gets too lossy when they live on tracks
+ // of a different type — but same-track drags stay locked.
+ if (multiDragSnapshotRef.current.length > 0) {
+ const deltaTime = snapResult.time - clip.startTime;
+ for (const snap of multiDragSnapshotRef.current) {
+ const newStart = Math.max(0, snap.startTime + deltaTime);
+ onMoveClip(snap.clipId, newStart, undefined);
+ }
+ }
+
onSnapIndicator(snapResult.snapped && snapResult.snapPoint ? snapResult.snapPoint.time : null);
};
+ let groupClosed = false;
+ const closeGroup = () => {
+ if (groupClosed) return;
+ groupClosed = true;
+ projectStore.endHistoryGroup();
+ };
+
const handleMouseUp = () => {
if (animationFrameId !== null) {
cancelAnimationFrame(animationFrameId);
@@ -271,6 +322,8 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
setDragYOffset(0);
setIsInvalidDrop(false);
onSnapIndicator(null);
+ multiDragSnapshotRef.current = [];
+ closeGroup();
};
window.addEventListener("mousemove", handleMouseMove);
@@ -282,6 +335,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
}
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
+ closeGroup();
};
}, [
isDragging,
diff --git a/apps/web/src/components/editor/timeline/ClipContextMenu.tsx b/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
index 2911539b..6cbfc0ae 100644
--- a/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
+++ b/apps/web/src/components/editor/timeline/ClipContextMenu.tsx
@@ -9,6 +9,7 @@ import {
Volume2,
Film,
Image,
+ ArrowLeftToLine,
} from "lucide-react";
import type { Clip, Track } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
@@ -46,6 +47,7 @@ export const ClipContextMenu: React.FC<ClipContextMenuProps> = ({
copyEffects,
pasteEffects,
copiedEffects,
+ closeGapBeforeClip,
} = useProjectStore();
const { playheadPosition } = useTimelineStore();
@@ -53,6 +55,15 @@ export const ClipContextMenu: React.FC<ClipContextMenuProps> = ({
playheadPosition >= clip.startTime &&
playheadPosition <= clip.startTime + clip.duration;
+ const hasGapBeforeClip = React.useMemo(() => {
+ const sorted = [...track.clips].sort((a, b) => a.startTime - b.startTime);
+ const idx = sorted.findIndex((c) => c.id === clip.id);
+ if (idx < 0) return false;
+ const prev = idx > 0 ? sorted[idx - 1] : null;
+ const target = prev ? prev.startTime + prev.duration : 0;
+ return clip.startTime - target > 0.0001;
+ }, [track.clips, clip.id, clip.startTime]);
+
const mediaItem = getMediaItem(clip.mediaId);
const isVideo = track.type === "video";
const isAudio = track.type === "audio";
@@ -93,6 +104,11 @@ export const ClipContextMenu: React.FC<ClipContextMenuProps> = ({
onClose?.();
};
+ const handleCloseGap = async () => {
+ await closeGapBeforeClip(clip.id);
+ onClose?.();
+ };
+
const handleSeparateAudio = async () => {
await separateAudio(clip.id);
onClose?.();
@@ -137,7 +153,7 @@ export const ClipContextMenu: React.FC<ClipContextMenuProps> = ({
</ContextMenuItem>
<ContextMenuItem onClick={handleDuplicate}>
<Layers className="mr-2 h-4 w-4" />
- Duplicate to New Track
+ Duplicate
<ContextMenuShortcut>⌘D</ContextMenuShortcut>
</ContextMenuItem>
@@ -148,6 +164,10 @@ export const ClipContextMenu: React.FC<ClipContextMenuProps> = ({
Split at Playhead
<ContextMenuShortcut>S</ContextMenuShortcut>
</ContextMenuItem>
+ <ContextMenuItem onClick={handleCloseGap} disabled={!hasGapBeforeClip}>
+ <ArrowLeftToLine className="mr-2 h-4 w-4" />
+ Close Gap to Previous
+ </ContextMenuItem>
{(isVideo || isImage) && (
<>
diff --git a/apps/web/src/components/editor/timeline/TrackHeader.tsx b/apps/web/src/components/editor/timeline/TrackHeader.tsx
index b37cc317..60f8081f 100644
--- a/apps/web/src/components/editor/timeline/TrackHeader.tsx
+++ b/apps/web/src/components/editor/timeline/TrackHeader.tsx
@@ -1,5 +1,5 @@
import React, { useState, useRef, useEffect } from "react";
-import { Eye, EyeOff, Volume2, Lock, Trash2, ChevronDown, ChevronRight, Pencil } from "lucide-react";
+import { Eye, EyeOff, Volume2, Lock, Trash2, ChevronDown, ChevronRight, Pencil, AlignLeft } from "lucide-react";
import type { Track } from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { useTimelineStore } from "../../../stores/timeline-store";
@@ -29,7 +29,7 @@ export const TrackHeader: React.FC<TrackHeaderProps> = ({
onDrop,
keyframeCount = 0,
}) => {
- const { lockTrack, hideTrack, muteTrack, removeTrack, renameTrack } = useProjectStore();
+ const { lockTrack, hideTrack, muteTrack, removeTrack, renameTrack, consolidateTrack } = useProjectStore();
const { isTrackExpanded, toggleTrackExpanded, getTrackHeight } = useTimelineStore();
const isExpanded = isTrackExpanded(track.id);
@@ -49,6 +49,22 @@ export const TrackHeader: React.FC<TrackHeaderProps> = ({
await removeTrack(track.id);
};
+ const handleRemoveGaps = async () => {
+ await consolidateTrack(track.id);
+ };
+
+ // Only enable "Remove Gaps" if there's actually a gap on this track.
+ const hasGaps = React.useMemo(() => {
+ if (track.clips.length === 0) return false;
+ const sorted = [...track.clips].sort((a, b) => a.startTime - b.startTime);
+ if (sorted[0].startTime > 0.0001) return true;
+ for (let i = 1; i < sorted.length; i++) {
+ const prevEnd = sorted[i - 1].startTime + sorted[i - 1].duration;
+ if (sorted[i].startTime - prevEnd > 0.0001) return true;
+ }
+ return false;
+ }, [track.clips]);
+
const startRename = () => {
setRenameValue(track.name);
setIsRenaming(true);
@@ -185,6 +201,10 @@ export const TrackHeader: React.FC<TrackHeaderProps> = ({
<Pencil className="mr-2 h-4 w-4" />
Rename Track
</ContextMenuItem>
+ <ContextMenuItem onClick={handleRemoveGaps} disabled={!hasGaps}>
+ <AlignLeft className="mr-2 h-4 w-4" />
+ Remove Gaps
+ </ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem
onClick={handleRemoveTrack}
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index c1ddfe5a..d3c43544 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -161,6 +161,13 @@ export interface ProjectState {
startTime: number,
trackId?: string,
) => Promise<ActionResult>;
+ moveClips: (
+ moves: Array<{ clipId: string; startTime: number; trackId?: string }>,
+ ) => Promise<ActionResult>;
+ beginHistoryGroup: (description?: string) => void;
+ endHistoryGroup: () => void;
+ closeGapBeforeClip: (clipId: string) => Promise<ActionResult>;
+ consolidateTrack: (trackId: string) => Promise<ActionResult>;
trimClip: (
clipId: string,
inPoint?: number,
@@ -2499,6 +2506,86 @@ export const useProjectStore = create<ProjectState>()(
return result;
},
+ beginHistoryGroup: (description?: string) => {
+ const { actionExecutor } = get();
+ actionExecutor.getHistory().beginGroup(description);
+ },
+
+ endHistoryGroup: () => {
+ const { actionExecutor } = get();
+ actionExecutor.getHistory().endGroup();
+ },
+
+ closeGapBeforeClip: async (clipId: string) => {
+ const { project, actionExecutor } = get();
+ const action: Action = {
+ type: "clip/closeGapBefore",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: { clipId },
+ };
+ const result = await actionExecutor.execute(action, project);
+ if (result.success) {
+ set({ project: { ...project } });
+ }
+ return result;
+ },
+
+ consolidateTrack: async (trackId: string) => {
+ const { project, actionExecutor } = get();
+ const action: Action = {
+ type: "track/consolidate",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: { trackId },
+ };
+ const result = await actionExecutor.execute(action, project);
+ if (result.success) {
+ set({ project: { ...project } });
+ }
+ return result;
+ },
+
+ moveClips: async (
+ moves: Array<{ clipId: string; startTime: number; trackId?: string }>,
+ ) => {
+ if (moves.length === 0) {
+ return { success: true };
+ }
+ if (moves.length === 1) {
+ return get().moveClip(
+ moves[0].clipId,
+ moves[0].startTime,
+ moves[0].trackId,
+ );
+ }
+ const { actionExecutor } = get();
+ const history = actionExecutor.getHistory();
+ history.beginGroup("Move clips");
+ try {
+ let lastResult: ActionResult = { success: true };
+ for (const move of moves) {
+ const { project } = get();
+ const action: Action = {
+ type: "clip/move",
+ id: uuidv4(),
+ timestamp: Date.now(),
+ params: {
+ clipId: move.clipId,
+ startTime: move.startTime,
+ trackId: move.trackId,
+ },
+ };
+ lastResult = await actionExecutor.execute(action, project);
+ if (!lastResult.success) break;
+ set({ project: { ...project } });
+ }
+ return lastResult;
+ } finally {
+ history.endGroup();
+ }
+ },
+
trimClip: async (clipId: string, inPoint?: number, outPoint?: number) => {
const { project, actionExecutor } = get();
const action: Action = {
@@ -2881,7 +2968,7 @@ export const useProjectStore = create<ProjectState>()(
},
duplicateClip: async (clipId: string) => {
- const { getClip, project, addTrack } = get();
+ const { getClip, project, actionExecutor } = get();
const clip = getClip(clipId);
if (!clip) {
return {
@@ -2906,42 +2993,47 @@ export const useProjectStore = create<ProjectState>()(
};
}
- const trackResult = await addTrack(track.type);
- if (!trackResult.success) {
- return trackResult;
- }
-
- const { project: updatedProject, actionExecutor } = get();
- const newTrack = updatedProject.timeline.tracks.find(
- (t) => t.clips.length === 0 && t.type === track.type,
+ // Place the duplicate immediately after the original on the same
+ // track. If there's a clip already starting at that time, scan
+ // forward until we find the next gap large enough for the
+ // duplicate's full duration.
+ const sortedClips = [...track.clips].sort(
+ (a, b) => a.startTime - b.startTime,
);
-
- if (!newTrack) {
- return {
- success: false,
- error: {
- code: "TRACK_NOT_FOUND" as const,
- message: "Could not find newly created track",
- },
- };
+ let candidate = clip.startTime + clip.duration;
+ const epsilon = 0.0001;
+ for (const other of sortedClips) {
+ if (other.id === clip.id) continue;
+ if (other.startTime + other.duration <= candidate + epsilon) continue;
+ if (other.startTime >= candidate + clip.duration - epsilon) break;
+ candidate = other.startTime + other.duration;
}
- const projectCopy = structuredClone(updatedProject);
+ const projectCopy = structuredClone(project);
const action: Action = {
type: "clip/add",
id: uuidv4(),
timestamp: Date.now(),
params: {
- trackId: newTrack.id,
+ trackId: track.id,
mediaId: clip.mediaId,
- startTime: clip.startTime,
+ startTime: candidate,
duration: clip.duration,
inPoint: clip.inPoint,
outPoint: clip.outPoint,
volume: clip.volume,
effects: structuredClone(clip.effects),
+ audioEffects: clip.audioEffects
+ ? structuredClone(clip.audioEffects)
+ : undefined,
keyframes: clip.keyframes ? structuredClone(clip.keyframes) : undefined,
transform: clip.transform ? structuredClone(clip.transform) : undefined,
+ ...(clip.fade ? { fade: clip.fade } : {}),
+ ...(clip.speed !== undefined ? { speed: clip.speed } : {}),
+ ...(clip.reversed !== undefined ? { reversed: clip.reversed } : {}),
+ ...(clip.audioTrackIndex !== undefined
+ ? { audioTrackIndex: clip.audioTrackIndex }
+ : {}),
},
};
diff --git a/packages/core/src/actions/action-executor.ts b/packages/core/src/actions/action-executor.ts
index 749eb83e..ec8ed071 100644
--- a/packages/core/src/actions/action-executor.ts
+++ b/packages/core/src/actions/action-executor.ts
@@ -458,6 +458,16 @@ export class ActionExecutor {
mediaId: string;
startTime: number;
duration?: number;
+ inPoint?: number;
+ outPoint?: number;
+ volume?: number;
+ effects?: unknown[];
+ audioEffects?: unknown[];
+ keyframes?: unknown[];
+ transform?: Record<string, unknown>;
+ fade?: { fadeIn: number; fadeOut: number };
+ speed?: number;
+ reversed?: boolean;
audioTrackIndex?: number;
};
const track = timeline.tracks.find(
@@ -474,26 +484,34 @@ export class ActionExecutor {
(mediaItem?.metadata.duration && mediaItem.metadata.duration > 0
? mediaItem.metadata.duration
: 5);
+ const defaultTransform = {
+ position: { x: 0, y: 0 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ fitMode: "none" as const,
+ };
const newClip = {
id: crypto.randomUUID(),
mediaId: params.mediaId,
trackId: params.trackId,
startTime: params.startTime,
duration: clipDuration,
- inPoint: 0,
- outPoint: clipDuration,
- effects: [],
- audioEffects: [],
- transform: {
- position: { x: 0, y: 0 },
- scale: { x: 1, y: 1 },
- rotation: 0,
- anchor: { x: 0.5, y: 0.5 },
- opacity: 1,
- fitMode: "none" as const,
- },
- volume: 1,
- keyframes: [],
+ inPoint: params.inPoint ?? 0,
+ outPoint: params.outPoint ?? clipDuration,
+ effects: (params.effects as never[]) ?? [],
+ audioEffects: (params.audioEffects as never[]) ?? [],
+ transform: params.transform
+ ? { ...defaultTransform, ...params.transform }
+ : defaultTransform,
+ volume: params.volume ?? 1,
+ keyframes: (params.keyframes as never[]) ?? [],
+ ...(params.fade ? { fade: params.fade } : {}),
+ ...(params.speed !== undefined ? { speed: params.speed } : {}),
+ ...(params.reversed !== undefined
+ ? { reversed: params.reversed }
+ : {}),
...(params.audioTrackIndex !== undefined
? { audioTrackIndex: params.audioTrackIndex }
: {}),
@@ -805,6 +823,100 @@ export class ActionExecutor {
}
break;
}
+
+ case "clip/closeGapBefore": {
+ // Close the gap before the target clip by sliding it (and every
+ // later clip on the same track) left until it butts up against
+ // the preceding clip (or the start of the timeline).
+ const params = action.params as { clipId: string };
+ const clip = this.findClip(timeline, params.clipId);
+ if (clip) {
+ const track = timeline.tracks.find((t) => t.id === clip.trackId);
+ if (track) {
+ const sorted = [...track.clips].sort(
+ (a, b) => a.startTime - b.startTime,
+ );
+ const idx = sorted.findIndex((c) => c.id === clip.id);
+ if (idx >= 0) {
+ const prev = idx > 0 ? sorted[idx - 1] : null;
+ const target = prev ? prev.startTime + prev.duration : 0;
+ const gap = clip.startTime - target;
+ if (gap > 0) {
+ const shiftIds = new Set(
+ sorted.slice(idx).map((c) => c.id),
+ );
+ timeline.tracks = timeline.tracks.map((t: MutableTrack) => {
+ if (t.id !== track.id) return t;
+ return {
+ ...t,
+ clips: t.clips.map((c: MutableClip) =>
+ shiftIds.has(c.id)
+ ? { ...c, startTime: c.startTime - gap }
+ : c,
+ ),
+ };
+ });
+ }
+ }
+ }
+ }
+ break;
+ }
+
+ case "track/consolidate": {
+ // Walk the track left-to-right and shift each clip backward so
+ // there is no empty space between consecutive clips. Already
+ // packed tracks are left alone.
+ const params = action.params as { trackId: string };
+ timeline.tracks = timeline.tracks.map((t: MutableTrack) => {
+ if (t.id !== params.trackId) return t;
+ const sorted = [...t.clips].sort(
+ (a, b) => a.startTime - b.startTime,
+ );
+ let cursor = 0;
+ const newPositions = new Map<string, number>();
+ for (const c of sorted) {
+ const newStart = Math.max(0, cursor);
+ newPositions.set(c.id, newStart);
+ cursor = newStart + c.duration;
+ }
+ return {
+ ...t,
+ clips: t.clips.map((c: MutableClip) => {
+ const ns = newPositions.get(c.id);
+ return ns !== undefined && ns !== c.startTime
+ ? { ...c, startTime: ns }
+ : c;
+ }),
+ };
+ });
+ break;
+ }
+
+ case "track/restorePositions": {
+ // Inverse of track/consolidate — restore the captured per-clip
+ // start times.
+ const params = action.params as {
+ trackId: string;
+ positions: Array<{ clipId: string; startTime: number }>;
+ };
+ const lookup = new Map(
+ params.positions.map((p) => [p.clipId, p.startTime] as const),
+ );
+ timeline.tracks = timeline.tracks.map((t: MutableTrack) => {
+ if (t.id !== params.trackId) return t;
+ return {
+ ...t,
+ clips: t.clips.map((c: MutableClip) => {
+ const ns = lookup.get(c.id);
+ return ns !== undefined && ns !== c.startTime
+ ? { ...c, startTime: ns }
+ : c;
+ }),
+ };
+ });
+ break;
+ }
}
}
diff --git a/packages/core/src/actions/action-history.ts b/packages/core/src/actions/action-history.ts
index 67c4600d..95867041 100644
--- a/packages/core/src/actions/action-history.ts
+++ b/packages/core/src/actions/action-history.ts
@@ -51,6 +51,9 @@ const ACTION_DESCRIPTIONS: Record<
"project/updateSettings": () => "Update settings",
"media/import": () => "Import media",
"media/delete": () => "Delete media",
+ "clip/closeGapBefore": () => "Close gap",
+ "track/consolidate": () => "Remove gaps",
+ "track/restorePositions": () => "Restore positions",
};
function getActionDescription(action: Action): string {
@@ -62,6 +65,47 @@ function getActionDescription(action: Action): string {
return `${parts[0]}: ${parts[1] || "action"}`;
}
+// Action types whose rapid repetition (slider drags, etc.) should be
+// coalesced into a single undo step. Anything not in this set — clip/add,
+// clip/remove, track/add, etc. — is always treated as a discrete user
+// action even when fired in quick succession.
+const AUTO_GROUPABLE_TYPES = new Set<string>([
+ "transform/update",
+ "effect/update",
+ "audio/setVolume",
+ "audio/setFade",
+ "clip/move",
+ "clip/trim",
+ "clip/slip",
+ "clip/slide",
+ "clip/roll",
+ "keyframe/move",
+ "keyframe/update",
+ "project/updateSettings",
+]);
+
+// Param keys that identify the target entity. Two actions of the same
+// type are only grouped if they refer to the same target.
+const TARGET_PARAM_KEYS = [
+ "clipId",
+ "effectId",
+ "trackId",
+ "keyframeId",
+ "transitionId",
+ "subtitleId",
+];
+
+function getActionTargetId(action: Action): string | null {
+ const params = action.params as Record<string, unknown>;
+ for (const key of TARGET_PARAM_KEYS) {
+ const value = params[key];
+ if (typeof value === "string" && value.length > 0) {
+ return value;
+ }
+ }
+ return null;
+}
+
export class ActionHistory {
private undoStack: HistoryEntry[] = [];
private redoStack: HistoryEntry[] = [];
@@ -90,17 +134,32 @@ export class ActionHistory {
const timeSinceLastAction = now - this.lastActionTime;
this.lastActionTime = now;
- const shouldAutoGroup =
- timeSinceLastAction < this.autoGroupWindow &&
- this.undoStack.length > 0 &&
- this.undoStack[this.undoStack.length - 1].action.type === action.type;
-
+ const lastEntry =
+ this.undoStack.length > 0
+ ? this.undoStack[this.undoStack.length - 1]
+ : null;
+
+ // Only auto-group when:
+ // - The action type is one of the "rapid update" types (slider drag,
+ // trim handle, etc.) — not creation/deletion actions.
+ // - The previous entry has the same type AND targets the same entity
+ // (same clipId, effectId, etc.), so two distinct operations don't
+ // collapse just because they happened back-to-back.
let groupId = this.currentGroupId;
- if (shouldAutoGroup && !groupId) {
- groupId = `auto-${now}`;
- const lastEntry = this.undoStack[this.undoStack.length - 1];
- if (!lastEntry.groupId) {
- this.undoStack[this.undoStack.length - 1] = { ...lastEntry, groupId };
+ if (
+ !groupId &&
+ lastEntry &&
+ timeSinceLastAction < this.autoGroupWindow &&
+ lastEntry.action.type === action.type &&
+ AUTO_GROUPABLE_TYPES.has(action.type)
+ ) {
+ const lastTarget = getActionTargetId(lastEntry.action);
+ const currentTarget = getActionTargetId(action);
+ if (lastTarget !== null && lastTarget === currentTarget) {
+ groupId = lastEntry.groupId ?? `auto-${now}`;
+ if (!lastEntry.groupId) {
+ this.undoStack[this.undoStack.length - 1] = { ...lastEntry, groupId };
+ }
}
}
diff --git a/packages/core/src/actions/inverse-action-generator.ts b/packages/core/src/actions/inverse-action-generator.ts
index 88c5c324..3eb27540 100644
--- a/packages/core/src/actions/inverse-action-generator.ts
+++ b/packages/core/src/actions/inverse-action-generator.ts
@@ -231,7 +231,22 @@ export class InverseActionGenerator {
solo: track.solo,
});
}
+
+ case "track/consolidate" as TrackAction["type"]: {
+ const trackId = (action.params as { trackId: string }).trackId;
+ const track = timeline.tracks.find((t) => t.id === trackId);
+ if (!track) return null;
+ const positions = track.clips.map((c) => ({
+ clipId: c.id,
+ startTime: c.startTime,
+ }));
+ return this.createInverseAction(action, "track/restorePositions", {
+ trackId,
+ positions,
+ });
+ }
}
+ return null;
}
private generateClipInverse(
@@ -302,7 +317,23 @@ export class InverseActionGenerator {
affectedClips,
});
}
+
+ case "clip/closeGapBefore" as ClipAction["type"]: {
+ const params = action.params as { clipId: string };
+ const clip = this.findClip(timeline, params.clipId);
+ if (!clip) return null;
+ const track = timeline.tracks.find((t) => t.id === clip.trackId);
+ if (!track) return null;
+ const positions = track.clips
+ .filter((c) => c.startTime >= clip.startTime)
+ .map((c) => ({ clipId: c.id, startTime: c.startTime }));
+ return this.createInverseAction(action, "track/restorePositions", {
+ trackId: track.id,
+ positions,
+ });
+ }
}
+ return null;
}
private generateEffectInverse(