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(editor): improve timeline clip dragging and crop resize behavior

Augustus Otue9f57d7888ef
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 6e56875d..2f04e875 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -4511,23 +4511,30 @@ export const Preview: React.FC = () => {
return null;
}, [cropMode, cropClipId, timelineTracks]);
- const cropVideoSrc = useMemo(() => {
+ const cropMediaData = useMemo(() => {
if (!cropMode || !cropClipId || !cropClip) return null;
const mediaItem = getMediaItem(cropClip.mediaId);
if (!mediaItem) return null;
+ let src: string | null = null;
if (mediaItem.blob) {
- return URL.createObjectURL(mediaItem.blob);
+ src = URL.createObjectURL(mediaItem.blob);
+ } else if (mediaItem.originalUrl) {
+ src = mediaItem.originalUrl;
}
- if (mediaItem.originalUrl) {
- return mediaItem.originalUrl;
- }
+ if (!src) return null;
- return null;
+ return {
+ src,
+ type: mediaItem.type as "video" | "image",
+ };
}, [cropMode, cropClipId, cropClip, getMediaItem]);
+ const cropVideoSrc = cropMediaData?.src ?? null;
+ const cropMediaType = cropMediaData?.type ?? "video";
+
const shouldShowCropMode = cropMode && cropClipId && cropClip && cropVideoSrc;
return (
@@ -4540,6 +4547,7 @@ export const Preview: React.FC = () => {
<CropModeView
clip={cropClip!}
videoSrc={cropVideoSrc}
+ mediaType={cropMediaType}
currentTime={playheadPosition}
canvasWidth={canvasSize.width}
canvasHeight={canvasSize.height}
diff --git a/apps/web/src/components/editor/preview/CropModeView.tsx b/apps/web/src/components/editor/preview/CropModeView.tsx
index a0f57708..c6345d6d 100644
--- a/apps/web/src/components/editor/preview/CropModeView.tsx
+++ b/apps/web/src/components/editor/preview/CropModeView.tsx
@@ -5,6 +5,7 @@ import type { Clip } from "@openreel/core";
interface CropModeViewProps {
clip: Clip;
videoSrc: string;
+ mediaType: "video" | "image";
currentTime: number;
canvasWidth: number;
canvasHeight: number;
@@ -42,6 +43,7 @@ const ASPECT_RATIOS = [
export const CropModeView: React.FC<CropModeViewProps> = ({
clip,
videoSrc,
+ mediaType,
currentTime,
canvasWidth,
canvasHeight,
@@ -51,6 +53,7 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const videoDisplayRef = useRef<HTMLVideoElement>(null);
+ const imageDisplayRef = useRef<HTMLImageElement>(null);
const initialCrop = clip.transform.crop || {
x: 0,
y: 0,
@@ -68,37 +71,65 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
- const video = videoDisplayRef.current;
- if (!video) return;
-
setIsLoading(true);
- const handleLoadedMetadata = () => {
- if (video.videoWidth > 0 && video.videoHeight > 0) {
- setVideoSize({
- width: video.videoWidth,
- height: video.videoHeight,
- });
+ if (mediaType === "image") {
+ const image = imageDisplayRef.current;
+ if (!image) return;
+
+ const handleLoad = () => {
+ if (image.naturalWidth > 0 && image.naturalHeight > 0) {
+ setVideoSize({
+ width: image.naturalWidth,
+ height: image.naturalHeight,
+ });
+ setIsLoading(false);
+ }
+ };
+
+ const handleError = () => {
+ console.error("[CropModeView] Image load error");
setIsLoading(false);
- }
- };
+ };
- const handleError = () => {
- console.error("[CropModeView] Video load error");
- setIsLoading(false);
- };
+ image.addEventListener("load", handleLoad);
+ image.addEventListener("error", handleError);
+ image.src = videoSrc;
- video.addEventListener("loadedmetadata", handleLoadedMetadata);
- video.addEventListener("error", handleError);
+ return () => {
+ image.removeEventListener("load", handleLoad);
+ image.removeEventListener("error", handleError);
+ };
+ } else {
+ const video = videoDisplayRef.current;
+ if (!video) return;
+
+ const handleLoadedMetadata = () => {
+ if (video.videoWidth > 0 && video.videoHeight > 0) {
+ setVideoSize({
+ width: video.videoWidth,
+ height: video.videoHeight,
+ });
+ setIsLoading(false);
+ }
+ };
+
+ const handleError = () => {
+ console.error("[CropModeView] Video load error");
+ setIsLoading(false);
+ };
- video.src = videoSrc;
- video.currentTime = currentTime;
+ video.addEventListener("loadedmetadata", handleLoadedMetadata);
+ video.addEventListener("error", handleError);
+ video.src = videoSrc;
+ video.currentTime = currentTime;
- return () => {
- video.removeEventListener("loadedmetadata", handleLoadedMetadata);
- video.removeEventListener("error", handleError);
- };
- }, [videoSrc, currentTime]);
+ return () => {
+ video.removeEventListener("loadedmetadata", handleLoadedMetadata);
+ video.removeEventListener("error", handleError);
+ };
+ }
+ }, [videoSrc, currentTime, mediaType]);
const handleMouseDown = (e: React.MouseEvent, handle: DragHandle) => {
e.preventDefault();
@@ -127,10 +158,12 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
Math.min(1 - cropStart.height, cropStart.y + deltaY),
);
} else if (dragHandle === "nw") {
- const maxDeltaX = cropStart.x;
- const maxDeltaY = cropStart.y;
- const clampedDeltaX = Math.min(deltaX, maxDeltaX);
- const clampedDeltaY = Math.min(deltaY, maxDeltaY);
+ const minDeltaX = -cropStart.x;
+ const maxDeltaX = cropStart.width - 0.05;
+ const minDeltaY = -cropStart.y;
+ const maxDeltaY = cropStart.height - 0.05;
+ const clampedDeltaX = Math.max(minDeltaX, Math.min(deltaX, maxDeltaX));
+ const clampedDeltaY = Math.max(minDeltaY, Math.min(deltaY, maxDeltaY));
if (lockedAspect) {
const avgDelta = (clampedDeltaX + clampedDeltaY) / 2;
@@ -145,8 +178,9 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
newCrop.height = cropStart.height - clampedDeltaY;
}
} else if (dragHandle === "ne") {
- const maxDeltaY = cropStart.y;
- const clampedDeltaY = Math.min(deltaY, maxDeltaY);
+ const minDeltaY = -cropStart.y;
+ const maxDeltaY = cropStart.height - 0.05;
+ const clampedDeltaY = Math.max(minDeltaY, Math.min(deltaY, maxDeltaY));
if (lockedAspect) {
const avgDelta = (-deltaX + clampedDeltaY) / 2;
@@ -159,8 +193,9 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
newCrop.height = cropStart.height - clampedDeltaY;
}
} else if (dragHandle === "sw") {
- const maxDeltaX = cropStart.x;
- const clampedDeltaX = Math.min(deltaX, maxDeltaX);
+ const minDeltaX = -cropStart.x;
+ const maxDeltaX = cropStart.width - 0.05;
+ const clampedDeltaX = Math.max(minDeltaX, Math.min(deltaX, maxDeltaX));
if (lockedAspect) {
const avgDelta = (clampedDeltaX - deltaY) / 2;
@@ -194,8 +229,9 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
);
}
} else if (dragHandle === "n") {
- const maxDelta = cropStart.y;
- const clampedDelta = Math.min(deltaY, maxDelta);
+ const minDelta = -cropStart.y;
+ const maxDelta = cropStart.height - 0.05;
+ const clampedDelta = Math.max(minDelta, Math.min(deltaY, maxDelta));
newCrop.y = cropStart.y + clampedDelta;
newCrop.height = cropStart.height - clampedDelta;
} else if (dragHandle === "s") {
@@ -204,8 +240,9 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
Math.max(0.1, cropStart.height + deltaY),
);
} else if (dragHandle === "w") {
- const maxDelta = cropStart.x;
- const clampedDelta = Math.min(deltaX, maxDelta);
+ const minDelta = -cropStart.x;
+ const maxDelta = cropStart.width - 0.05;
+ const clampedDelta = Math.max(minDelta, Math.min(deltaX, maxDelta));
newCrop.x = cropStart.x + clampedDelta;
newCrop.width = cropStart.width - clampedDelta;
} else if (dragHandle === "e") {
@@ -388,14 +425,23 @@ export const CropModeView: React.FC<CropModeViewProps> = ({
opacity: isLoading ? 0 : 1,
}}
>
- <video
- ref={videoDisplayRef}
- className="w-full h-full"
- style={{ objectFit: "contain" }}
- muted
- playsInline
- preload="metadata"
- />
+ {mediaType === "image" ? (
+ <img
+ ref={imageDisplayRef}
+ className="w-full h-full"
+ style={{ objectFit: "contain" }}
+ alt="Crop preview"
+ />
+ ) : (
+ <video
+ ref={videoDisplayRef}
+ className="w-full h-full"
+ style={{ objectFit: "contain" }}
+ muted
+ playsInline
+ preload="metadata"
+ />
+ )}
{!isLoading && videoSize.width > 0 && (
<>
diff --git a/apps/web/src/components/editor/timeline/ClipComponent.tsx b/apps/web/src/components/editor/timeline/ClipComponent.tsx
index 8f20cd54..f1bc5828 100644
--- a/apps/web/src/components/editor/timeline/ClipComponent.tsx
+++ b/apps/web/src/components/editor/timeline/ClipComponent.tsx
@@ -30,6 +30,10 @@ interface ClipComponentProps {
) => void;
}
+const AUTO_SCROLL_THRESHOLD = 80;
+const AUTO_SCROLL_SPEED = 10;
+const DRAG_THRESHOLD = 5;
+
export const ClipComponent: React.FC<ClipComponentProps> = ({
clip,
track,
@@ -48,7 +52,10 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const { playheadPosition } = useTimelineStore();
const mediaItem = getMediaItem(clip.mediaId);
const [isDragging, setIsDragging] = useState(false);
+ const [isPendingDrag, setIsPendingDrag] = useState(false);
const [dragOffset, setDragOffset] = useState(0);
+ const [dragYOffset, setDragYOffset] = useState(0);
+ const [isInvalidDrop, setIsInvalidDrop] = useState(false);
const [isTrimming, setIsTrimming] = useState(false);
const [trimEdge, setTrimEdge] = useState<"left" | "right" | null>(null);
const trimStartRef = useRef<{
@@ -60,6 +67,18 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
startTime: clip.startTime,
duration: clip.duration,
});
+ const dragStartRef = useRef<{ mouseY: number; clipY: number; scrollTop: number }>({
+ mouseY: 0,
+ clipY: 0,
+ scrollTop: 0,
+ });
+ const mousePositionRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const pendingDropRef = useRef<{ time: number; targetTrackId?: string }>({ time: 0 });
+ const dragPendingRef = useRef<{ active: boolean; startX: number; startY: number }>({
+ active: false,
+ startX: 0,
+ startY: 0,
+ });
const clipRef = useRef<HTMLDivElement>(null);
const left = clip.startTime * pixelsPerSecond;
@@ -71,7 +90,7 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
const clipStyle = getClipStyle(track.type);
const handleClick = (e: React.MouseEvent) => {
- if (isDragging) return;
+ if (isDragging || isPendingDrag) return;
e.stopPropagation();
onSelect(clip.id, e.shiftKey || e.metaKey);
};
@@ -81,14 +100,23 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
e.stopPropagation();
const rect = clipRef.current?.parentElement?.getBoundingClientRect();
- if (!rect) return;
+ const clipRect = clipRef.current?.getBoundingClientRect();
+ if (!rect || !clipRect) return;
const clickX = e.clientX - rect.left;
const clipStartX = clip.startTime * pixelsPerSecond;
setDragOffset(clickX - clipStartX);
- setIsDragging(true);
- onSelect(clip.id, e.shiftKey || e.metaKey);
+ dragStartRef.current = {
+ mouseY: e.clientY,
+ clipY: clipRect.top - rect.top,
+ scrollTop: timelineRef.current?.scrollTop || 0,
+ };
+ mousePositionRef.current = { x: e.clientX, y: e.clientY };
+ dragPendingRef.current = { active: true, startX: e.clientX, startY: e.clientY };
+ setDragYOffset(0);
+ setIsInvalidDrop(false);
+ setIsPendingDrag(true);
};
const handleTrimMouseDown =
@@ -105,10 +133,73 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
document.body.style.cursor = "ew-resize";
};
+ useEffect(() => {
+ if (!isPendingDrag) return;
+
+ const handlePendingMouseMove = (e: MouseEvent) => {
+ const dx = e.clientX - dragPendingRef.current.startX;
+ const dy = e.clientY - dragPendingRef.current.startY;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+
+ if (distance >= DRAG_THRESHOLD) {
+ dragPendingRef.current.active = false;
+ setIsPendingDrag(false);
+ setIsDragging(true);
+ }
+ };
+
+ const handlePendingMouseUp = (e: MouseEvent) => {
+ dragPendingRef.current.active = false;
+ setIsPendingDrag(false);
+ onSelect(clip.id, e.shiftKey || e.metaKey);
+ };
+
+ window.addEventListener("mousemove", handlePendingMouseMove);
+ window.addEventListener("mouseup", handlePendingMouseUp);
+
+ return () => {
+ window.removeEventListener("mousemove", handlePendingMouseMove);
+ window.removeEventListener("mouseup", handlePendingMouseUp);
+ };
+ }, [isPendingDrag, clip.id, onSelect]);
+
useEffect(() => {
if (!isDragging) return;
+ let animationFrameId: number | null = null;
+
+ const scrollLoop = () => {
+ if (!timelineRef.current) {
+ animationFrameId = requestAnimationFrame(scrollLoop);
+ return;
+ }
+
+ const timeline = timelineRef.current;
+ const timelineRect = timeline.getBoundingClientRect();
+ const mouseY = mousePositionRef.current.y;
+ const timelineTop = timelineRect.top;
+ const timelineBottom = timelineRect.bottom;
+ const canScrollUp = timeline.scrollTop > 0;
+ const canScrollDown = timeline.scrollTop < timeline.scrollHeight - timeline.clientHeight;
+
+ const distanceFromTop = mouseY - timelineTop;
+ const distanceFromBottom = timelineBottom - mouseY;
+
+ if (distanceFromTop < AUTO_SCROLL_THRESHOLD && canScrollUp) {
+ timeline.scrollTop -= AUTO_SCROLL_SPEED;
+ } else if (distanceFromBottom < AUTO_SCROLL_THRESHOLD && canScrollDown) {
+ timeline.scrollTop += AUTO_SCROLL_SPEED;
+ }
+
+ animationFrameId = requestAnimationFrame(scrollLoop);
+ };
+
+ animationFrameId = requestAnimationFrame(scrollLoop);
+
const handleMouseMove = (e: MouseEvent) => {
+ mousePositionRef.current.x = e.clientX;
+ mousePositionRef.current.y = e.clientY;
+
const rect = clipRef.current?.parentElement?.getBoundingClientRect();
const timelineRect = timelineRef.current?.getBoundingClientRect();
if (!rect || !timelineRect) return;
@@ -125,14 +216,21 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
pixelsPerSecond,
);
+ const currentScrollTop = timelineRef.current?.scrollTop || 0;
+ const scrollDelta = currentScrollTop - dragStartRef.current.scrollTop;
+ const yDelta = (e.clientY - dragStartRef.current.mouseY) + scrollDelta;
+ setDragYOffset(yDelta);
+
const scrollTop = timelineRef.current?.scrollTop || 0;
const mouseY = e.clientY - timelineRect.top + scrollTop;
let targetTrackId: string | undefined;
+ let hoveredTrackType: string | undefined;
let cumulativeY = 0;
for (const t of allTracks) {
const height = trackHeights.get(t.id) || 60;
if (mouseY >= cumulativeY && mouseY < cumulativeY + height) {
+ hoveredTrackType = t.type;
if (t.type === track.type && t.id !== track.id) {
targetTrackId = t.id;
}
@@ -141,12 +239,27 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
cumulativeY += height;
}
- onMoveClip(clip.id, snapResult.time, targetTrackId);
+ const isOverDifferentTrackType = hoveredTrackType !== undefined && hoveredTrackType !== track.type;
+ setIsInvalidDrop(isOverDifferentTrackType);
+
+ pendingDropRef.current = { time: snapResult.time, targetTrackId };
+ onMoveClip(clip.id, snapResult.time, undefined);
onSnapIndicator(snapResult.snapped ? snapResult.time : null);
};
const handleMouseUp = () => {
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId);
+ }
+
+ const { time, targetTrackId } = pendingDropRef.current;
+ if (targetTrackId) {
+ onMoveClip(clip.id, time, targetTrackId);
+ }
+
setIsDragging(false);
+ setDragYOffset(0);
+ setIsInvalidDrop(false);
onSnapIndicator(null);
};
@@ -154,6 +267,9 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
window.addEventListener("mouseup", handleMouseUp);
return () => {
+ if (animationFrameId !== null) {
+ cancelAnimationFrame(animationFrameId);
+ }
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
@@ -228,19 +344,24 @@ export const ClipComponent: React.FC<ClipComponentProps> = ({
onClick={handleClick}
onMouseDown={handleMouseDown}
className={`group absolute top-1 bottom-1 rounded-lg overflow-hidden shadow-sm ${
- isDragging ? "cursor-grabbing opacity-80 z-20" : "cursor-grab"
+ isDragging
+ ? `cursor-grabbing z-50 ${isInvalidDrop ? "opacity-50 ring-2 ring-red-500 border-red-500" : "opacity-90 shadow-xl"}`
+ : "cursor-grab"
} ${
- isSelected
+ isSelected && !isDragging
? "ring-2 ring-primary border-primary z-10"
- : "border-opacity-30 hover:border-opacity-60 hover:brightness-110"
+ : !isDragging ? "border-opacity-30 hover:border-opacity-60 hover:brightness-110" : ""
} ${clipStyle.bg} border ${clipStyle.border} ${
track.locked ? "cursor-not-allowed opacity-60" : ""
}`}
style={{
- transform: `translateX(${left}px)`,
+ transform: isDragging
+ ? `translate(${left}px, ${dragYOffset}px)`
+ : `translateX(${left}px)`,
width: `${width}px`,
willChange: isInteracting ? 'transform, width' : 'auto',
transition: isInteracting ? 'none' : 'opacity 150ms, box-shadow 150ms',
+ pointerEvents: isDragging ? 'none' : 'auto',
}}
>
{isVideo &&