This commit is contained in:
Maze Winther 2025-07-17 17:22:53 +02:00
commit 4e5e9756c8
11 changed files with 461 additions and 326 deletions

View File

@ -16,6 +16,7 @@ import { usePanelStore } from "@/stores/panel-store";
import { useProjectStore } from "@/stores/project-store";
import { EditorProvider } from "@/components/editor-provider";
import { usePlaybackControls } from "@/hooks/use-playback-controls";
import { useDisableBrowserZoom } from "@/hooks/use-disable-browser-zoom";
import { Onboarding } from "@/components/onboarding";
export default function Editor() {
@ -39,6 +40,7 @@ export default function Editor() {
const handledProjectIds = useRef<Set<string>>(new Set());
const [isOnboardingOpen, setIsOnboardingOpen] = useState(true);
useDisableBrowserZoom();
usePlaybackControls();
useEffect(() => {

View File

@ -83,7 +83,11 @@ export function PropertiesPanel() {
);
if (mediaItem?.type === "audio") {
return <AudioProperties element={element} />;
return (
<div key={elementId}>
<AudioProperties element={element} />
</div>
);
}
return (

View File

@ -0,0 +1,24 @@
import { TimelineCanvasRulerWrapperProps } from "@/types/timeline";
import React, { forwardRef } from "react";
/**
* Wrapper div around the canvas-based timeline ruler.
* Captures mouse events for scrubbing and ensures pointer events are properly enabled.
*/
const TimelineCanvasRulerWrapper = forwardRef<
HTMLDivElement,
TimelineCanvasRulerWrapperProps
>(({ children, onMouseDown, className = "" }, ref) => {
return (
<div
ref={ref}
className={`relative overflow-hidden h-5 w-full select-none cursor-pointer ${className}`}
onMouseDown={onMouseDown}
data-ruler-wrapper
>
{children}
</div>
);
});
export default TimelineCanvasRulerWrapper;

View File

@ -0,0 +1,78 @@
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { TimelineCanvasRulerProps } from "@/types/timeline";
import React, { useRef, useEffect } from "react";
/**
* TimelineCanvasRuler renders the timeline ticks and labels using Canvas.
* Should be wrapped by TimelineCanvasRulerWrapper for interaction handling.
*/
export default function TimelineCanvasRuler({
zoomLevel,
duration,
width,
height = 20,
}: TimelineCanvasRulerProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const ctx = canvasRef.current?.getContext("2d");
if (!ctx) return;
ctx.clearRect(0, 0, width, height);
const pixelsPerSecond = TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel;
const getTimeInterval = () => {
if (pixelsPerSecond >= 200) return 0.1;
if (pixelsPerSecond >= 100) return 0.5;
if (pixelsPerSecond >= 50) return 1;
if (pixelsPerSecond >= 25) return 2;
if (pixelsPerSecond >= 12) return 5;
if (pixelsPerSecond >= 6) return 10;
return 30;
};
const mainInterval = getTimeInterval();
const tickPerMain = 5;
const subInterval = mainInterval / tickPerMain;
const totalTicks = Math.ceil(duration / subInterval) + 1;
for (let i = 0; i < totalTicks; i++) {
const time = i * subInterval;
const x = time * pixelsPerSecond;
const isMain = i % tickPerMain === 0;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, isMain ? height * 0.3 : height * 0.1);
ctx.strokeStyle = isMain ? "#999" : "#ccc";
ctx.lineWidth = isMain ? 1 : 0.5;
ctx.stroke();
// Label
if (isMain) {
ctx.fillStyle = "#666";
ctx.font = "10px sans-serif";
const mins = Math.floor(time / 60);
const secs = Math.floor(time % 60);
let label = "";
let xTranslate = 10;
if (mainInterval < 1) {
label = `${time.toFixed(1)}s`;
} else if (mins > 0) {
label = `${mins}:${secs.toString().padStart(2, "0")}`;
} else {
label = `${secs}s`;
xTranslate = 5;
}
ctx.fillText(label, x - xTranslate, height - 4);
}
}
}, [zoomLevel, duration, width, height]);
return (
<canvas ref={canvasRef} width={width} height={height} className="block" />
);
}

View File

@ -2,10 +2,7 @@
import { useRef } from "react";
import { TimelineTrack } from "@/types/timeline";
import {
TIMELINE_CONSTANTS,
getTotalTracksHeight,
} from "@/constants/timeline-constants";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { useTimelinePlayhead } from "@/hooks/use-timeline-playhead";
interface TimelinePlayheadProps {
@ -16,7 +13,6 @@ interface TimelinePlayheadProps {
seek: (time: number) => void;
rulerRef: React.RefObject<HTMLDivElement>;
rulerScrollRef: React.RefObject<HTMLDivElement>;
tracksScrollRef: React.RefObject<HTMLDivElement>;
trackLabelsRef?: React.RefObject<HTMLDivElement>;
timelineRef: React.RefObject<HTMLDivElement>;
playheadRef?: React.RefObject<HTMLDivElement>;
@ -31,7 +27,6 @@ export function TimelinePlayhead({
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
trackLabelsRef,
timelineRef,
playheadRef: externalPlayheadRef,
@ -39,15 +34,13 @@ export function TimelinePlayhead({
}: TimelinePlayheadProps) {
const internalPlayheadRef = useRef<HTMLDivElement>(null);
const playheadRef = externalPlayheadRef || internalPlayheadRef;
const { playheadPosition, handlePlayheadMouseDown } = useTimelinePlayhead({
const { playheadPosition, handleRulerMouseDown } = useTimelinePlayhead({
currentTime,
duration,
zoomLevel,
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
});
// Use timeline container height minus a few pixels for breathing room
@ -66,14 +59,14 @@ export function TimelinePlayhead({
return (
<div
ref={playheadRef}
className="absolute pointer-events-auto z-[100]"
className="absolute pointer-events-auto z-[50]"
style={{
left: `${leftPosition}px`,
top: 0,
height: `${totalHeight}px`,
width: "2px", // Slightly wider for better click target
}}
onMouseDown={handlePlayheadMouseDown}
onMouseDown={handleRulerMouseDown}
>
{/* The playhead line spanning full height */}
<div
@ -96,21 +89,24 @@ export function useTimelinePlayheadRuler({
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
}: Omit<TimelinePlayheadProps, "tracks" | "trackLabelsRef" | "timelineRef">) {
const { handleRulerMouseDown, isDraggingRuler } = useTimelinePlayhead({
}: Omit<
TimelinePlayheadProps,
| "tracks"
| "trackLabelsRef"
| "timelineRef"
| "tracksScrollRef"
| "playheadRef"
>) {
const { handleRulerMouseDown } = useTimelinePlayhead({
currentTime,
duration,
zoomLevel,
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
});
return { handleRulerMouseDown, isDraggingRuler };
return { handleRulerMouseDown };
}
export { TimelinePlayhead as default };

View File

@ -16,6 +16,8 @@ import {
Music,
TypeIcon,
Lock,
ZoomIn,
ZoomOut,
LockOpen,
} from "lucide-react";
import {
@ -55,6 +57,9 @@ import {
TIMELINE_CONSTANTS,
snapTimeToFrame,
} from "@/constants/timeline-constants";
import { Slider } from "../ui/slider";
import TimelineCanvasRuler from "./timeline-canvas/timeline-canvas-ruler";
import TimelineCanvasRulerWrapper from "./timeline-canvas/timeline-canvas-ruler-wrapper";
export function Timeline() {
// Timeline shows all tracks (video, audio, effects) and their elements.
@ -94,10 +99,13 @@ export function Timeline() {
const [isInTimeline, setIsInTimeline] = useState(false);
// Timeline zoom functionality
const { zoomLevel, setZoomLevel, handleWheel } = useTimelineZoom({
containerRef: timelineRef,
isInTimeline,
});
const {
zoomLevel,
zoomStep,
handleChangeZoomLevel,
handleChangeZoomStep,
handleWheel,
} = useTimelineZoom();
// Old marquee selection removed - using new SelectionBox component instead
@ -110,7 +118,6 @@ export function Timeline() {
// Scroll synchronization and auto-scroll to playhead
const rulerScrollRef = useRef<HTMLDivElement>(null);
const tracksScrollRef = useRef<HTMLDivElement>(null);
const trackLabelsRef = useRef<HTMLDivElement>(null);
const playheadRef = useRef<HTMLDivElement>(null);
const trackLabelsScrollRef = useRef<HTMLDivElement>(null);
@ -127,8 +134,6 @@ export function Timeline() {
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
});
// Selection box functionality
@ -198,14 +203,14 @@ export function Timeline() {
clearSelectedElements();
// Determine if we're clicking in ruler or tracks area
const isRulerClick = (e.target as HTMLElement).closest(
"[data-ruler-area]"
const isTracksAreaClick = (e.target as HTMLElement).closest(
"[data-tracks-area]"
);
let mouseX: number;
let scrollLeft = 0;
if (isRulerClick) {
if (isTracksAreaClick) {
// Calculate based on ruler position
const rulerContent = rulerScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
@ -215,14 +220,7 @@ export function Timeline() {
mouseX = e.clientX - rect.left;
scrollLeft = rulerContent.scrollLeft;
} else {
// Calculate based on tracks content position
const tracksContent = tracksScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
if (!tracksContent) return;
const rect = tracksContent.getBoundingClientRect();
mouseX = e.clientX - rect.left;
scrollLeft = tracksContent.scrollLeft;
return;
}
const rawTime = Math.max(
@ -245,7 +243,6 @@ export function Timeline() {
zoomLevel,
seek,
rulerScrollRef,
tracksScrollRef,
clearSelectedElements,
isSelecting,
justFinishedSelecting,
@ -509,14 +506,11 @@ export function Timeline() {
const rulerViewport = rulerScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
const tracksViewport = tracksScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
if (!rulerViewport || !tracksViewport) return;
if (!rulerViewport) return;
// Horizontal scroll synchronization between ruler and tracks
const handleRulerScroll = () => {
@ -524,7 +518,6 @@ export function Timeline() {
if (isUpdatingRef.current || now - lastRulerSync.current < 16) return;
lastRulerSync.current = now;
isUpdatingRef.current = true;
tracksViewport.scrollLeft = rulerViewport.scrollLeft;
isUpdatingRef.current = false;
};
const handleTracksScroll = () => {
@ -532,12 +525,10 @@ export function Timeline() {
if (isUpdatingRef.current || now - lastTracksSync.current < 16) return;
lastTracksSync.current = now;
isUpdatingRef.current = true;
rulerViewport.scrollLeft = tracksViewport.scrollLeft;
isUpdatingRef.current = false;
};
rulerViewport.addEventListener("scroll", handleRulerScroll);
tracksViewport.addEventListener("scroll", handleTracksScroll);
// Vertical scroll synchronization between track labels and tracks content
if (trackLabelsViewport) {
@ -547,7 +538,6 @@ export function Timeline() {
return;
lastVerticalSync.current = now;
isUpdatingRef.current = true;
tracksViewport.scrollTop = trackLabelsViewport.scrollTop;
isUpdatingRef.current = false;
};
const handleTracksVerticalScroll = () => {
@ -556,30 +546,22 @@ export function Timeline() {
return;
lastVerticalSync.current = now;
isUpdatingRef.current = true;
trackLabelsViewport.scrollTop = tracksViewport.scrollTop;
isUpdatingRef.current = false;
};
trackLabelsViewport.addEventListener("scroll", handleTrackLabelsScroll);
tracksViewport.addEventListener("scroll", handleTracksVerticalScroll);
return () => {
rulerViewport.removeEventListener("scroll", handleRulerScroll);
tracksViewport.removeEventListener("scroll", handleTracksScroll);
trackLabelsViewport.removeEventListener(
"scroll",
handleTrackLabelsScroll
);
tracksViewport.removeEventListener(
"scroll",
handleTracksVerticalScroll
);
};
}
return () => {
rulerViewport.removeEventListener("scroll", handleRulerScroll);
tracksViewport.removeEventListener("scroll", handleTracksScroll);
};
}, []);
@ -739,6 +721,39 @@ export function Timeline() {
</TooltipTrigger>
<TooltipContent>Delete element (Delete)</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger asChild>
<Button
className="ml-auto"
variant="text"
size="icon"
onClick={() => handleChangeZoomLevel(zoomLevel - 0.15)}
>
<ZoomOut className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Zoom Out</TooltipContent>
</Tooltip>
<Slider
className="max-w-24"
max={TIMELINE_CONSTANTS.MAX_ZOOM_STEP}
min={0}
step={1}
value={[zoomStep]}
onValueChange={(value) => handleChangeZoomStep(value[0])}
/>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="text"
size="icon"
onClick={() => handleChangeZoomLevel(zoomLevel + 0.15)}
>
<ZoomIn className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>Zoom In</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
<div className="flex items-center gap-1">
@ -772,7 +787,6 @@ export function Timeline() {
seek={seek}
rulerRef={rulerRef}
rulerScrollRef={rulerScrollRef}
tracksScrollRef={tracksScrollRef}
trackLabelsRef={trackLabelsRef}
timelineRef={timelineRef}
playheadRef={playheadRef}
@ -790,114 +804,38 @@ export function Timeline() {
/>
{/* Timeline Header with Ruler */}
<div className="flex bg-panel sticky top-0 z-10">
{/* Track Labels Header */}
<div className="w-48 flex-shrink-0 bg-muted/30 border-r flex items-center justify-between px-3 py-2">
{/* Empty space */}
<span className="text-sm font-medium text-muted-foreground opacity-0">
.
</span>
</div>
<div className="w-48 flex-shrink-0 bg-muted/30 border-r h-5 px-3" />
{/* Timeline Ruler */}
<div
className="flex-1 relative overflow-hidden h-4"
onWheel={handleWheel}
onMouseDown={handleSelectionMouseDown}
onClick={handleTimelineContentClick}
data-ruler-area
>
<div className="flex-1 overflow-hidden h-5">
<ScrollArea className="w-full" ref={rulerScrollRef}>
<div
<TimelineCanvasRulerWrapper
ref={rulerRef}
className="relative h-4 select-none cursor-default"
style={{
width: `${dynamicTimelineWidth}px`,
}}
onMouseDown={handleRulerMouseDown}
>
{/* Time markers */}
{(() => {
// Calculate appropriate time interval based on zoom level
const getTimeInterval = (zoom: number) => {
const pixelsPerSecond =
TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoom;
if (pixelsPerSecond >= 200) return 0.1; // Every 0.1s when very zoomed in
if (pixelsPerSecond >= 100) return 0.5; // Every 0.5s when zoomed in
if (pixelsPerSecond >= 50) return 1; // Every 1s at normal zoom
if (pixelsPerSecond >= 25) return 2; // Every 2s when zoomed out
if (pixelsPerSecond >= 12) return 5; // Every 5s when more zoomed out
if (pixelsPerSecond >= 6) return 10; // Every 10s when very zoomed out
return 30; // Every 30s when extremely zoomed out
};
const interval = getTimeInterval(zoomLevel);
const markerCount = Math.ceil(duration / interval) + 1;
return Array.from({ length: markerCount }, (_, i) => {
const time = i * interval;
if (time > duration) return null;
const isMainMarker =
time % (interval >= 1 ? Math.max(1, interval) : 1) === 0;
return (
<div
key={i}
className={`absolute top-0 bottom-0 ${
isMainMarker
? "border-l border-muted-foreground/40"
: "border-l border-muted-foreground/20"
}`}
style={{
left: `${time * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel}px`,
}}
>
<span
className={`absolute top-1 left-1 text-[0.6rem] ${
isMainMarker
? "text-muted-foreground font-medium"
: "text-muted-foreground/70"
}`}
>
{(() => {
const formatTime = (seconds: number) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
if (hours > 0) {
return `${hours}:${minutes.toString().padStart(2, "0")}:${Math.floor(secs).toString().padStart(2, "0")}`;
} else if (minutes > 0) {
return `${minutes}:${Math.floor(secs).toString().padStart(2, "0")}`;
} else if (interval >= 1) {
return `${Math.floor(secs)}s`;
} else {
return `${secs.toFixed(1)}s`;
}
};
return formatTime(time);
})()}
</span>
</div>
);
}).filter(Boolean);
})()}
</div>
<TimelineCanvasRuler
zoomLevel={zoomLevel}
duration={duration}
width={dynamicTimelineWidth}
/>
</TimelineCanvasRulerWrapper>
</ScrollArea>
</div>
</div>
{/* Tracks Area */}
<div className="flex-1 flex overflow-hidden">
{/* Track Labels */}
{tracks.length > 0 && (
<div
ref={trackLabelsRef}
className="w-48 flex-shrink-0 border-r bg-panel-accent overflow-y-auto"
data-track-labels
>
<ScrollArea className="w-full h-full" ref={trackLabelsScrollRef}>
<div className="flex flex-col gap-1">
<ScrollArea className="w-full h-full">
<div
className="flex-1 flex overflow-hidden overflow-y-auto"
data-tracks-area
>
{/* Track Labels */}
{tracks.length > 0 && (
<div
ref={trackLabelsRef}
className="w-48 flex-shrink-0 border-r bg-panel-accent "
data-track-labels
>
<div className="flex flex-col gap-1" ref={trackLabelsScrollRef}>
{tracks.map((track) => (
<div
key={track.id}
@ -915,25 +853,23 @@ export function Timeline() {
</div>
))}
</div>
</ScrollArea>
</div>
)}
</div>
)}
{/* Timeline Tracks Content */}
<div
className="flex-1 relative overflow-hidden"
onWheel={handleWheel}
onMouseDown={handleSelectionMouseDown}
onClick={handleTimelineContentClick}
ref={tracksContainerRef}
>
<SelectionBox
startPos={selectionBox?.startPos || null}
currentPos={selectionBox?.currentPos || null}
containerRef={tracksContainerRef}
isActive={selectionBox?.isActive || false}
/>
<ScrollArea className="w-full h-full" ref={tracksScrollRef}>
{/* Timeline Tracks Content */}
<div
className="flex-1 relative overflow-hidden"
onWheel={handleWheel}
onMouseDown={handleSelectionMouseDown}
onClick={handleTimelineContentClick}
ref={tracksContainerRef}
>
<SelectionBox
startPos={selectionBox?.startPos || null}
currentPos={selectionBox?.currentPos || null}
containerRef={tracksContainerRef}
isActive={selectionBox?.isActive || false}
/>
<div
className="relative flex-1"
style={{
@ -987,9 +923,9 @@ export function Timeline() {
</>
)}
</div>
</ScrollArea>
</div>
</div>
</div>
</ScrollArea>
</div>
</div>
);

View File

@ -76,6 +76,11 @@ export const TIMELINE_CONSTANTS = {
DEFAULT_TEXT_DURATION: 5,
DEFAULT_IMAGE_DURATION: 5,
ZOOM_LEVELS: [0.25, 0.5, 1, 1.5, 2, 3, 4],
ZOOM_LEVEL_MIN: 0.1,
ZOOM_LEVEL_MAX: 10,
ZOOM_STEP_BASE: 0.15,
MAX_ZOOM_STEP: 66,
ZOOM_STEP: 1,
} as const;
// FPS presets for project settings

View File

@ -0,0 +1,63 @@
import { useEffect } from "react";
/**
* useDisableBrowserZoom
*
* This React hook prevents users from zooming in/out the browser window using keyboard shortcuts,
* mouse wheel, or gesture events (such as pinch-to-zoom on trackpads or touch devices).
*
* Typical use case: apps with fixed-size UIs, custom editors, or when zooming would break layout.
*
* NOTE: Disabling browser zoom may negatively affect accessibility and user experience.
* Use with caution, especially for public-facing applications.
*/
export const useDisableBrowserZoom = () => {
useEffect(() => {
/**
* Prevents browser zoom when user holds Ctrl (or Cmd on Mac) and scrolls the mouse wheel.
*/
const handleWheel = (e: WheelEvent) => {
if (e.ctrlKey) {
e.preventDefault();
}
};
/**
* Prevents browser zoom via keyboard shortcuts:
* Ctrl/Cmd + '+', '-', '=', or '0' (reset zoom)
* Some keyboards emit '=' for '+' (without Shift).
*/
const handleKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey) {
const key = e.key;
if (key === "+" || key === "-" || key === "0" || key === "=") {
e.preventDefault();
}
}
};
/**
* Prevents pinch-zoom gestures on supported browsers (mainly Safari/macOS/iOS).
* gesturestart, gesturechange, and gestureend are non-standard and not supported everywhere.
*/
const handleGesture = (e: Event) => {
e.preventDefault();
};
// Attach event listeners (passive: false is required for preventDefault to work)
window.addEventListener("wheel", handleWheel, { passive: false });
window.addEventListener("keydown", handleKeyDown, { passive: false });
window.addEventListener("gesturestart", handleGesture, { passive: false });
window.addEventListener("gesturechange", handleGesture, { passive: false });
window.addEventListener("gestureend", handleGesture, { passive: false });
// Cleanup listeners on unmount to avoid memory leaks
return () => {
window.removeEventListener("wheel", handleWheel);
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("gesturestart", handleGesture);
window.removeEventListener("gesturechange", handleGesture);
window.removeEventListener("gestureend", handleGesture);
};
}, []);
};

View File

@ -1,6 +1,6 @@
import { snapTimeToFrame } from "@/constants/timeline-constants";
import { useProjectStore } from "@/stores/project-store";
import { useState, useEffect, useCallback } from "react";
import { useRef, useState, useCallback } from "react";
interface UseTimelinePlayheadProps {
currentTime: number;
@ -9,10 +9,15 @@ interface UseTimelinePlayheadProps {
seek: (time: number) => void;
rulerRef: React.RefObject<HTMLDivElement>;
rulerScrollRef: React.RefObject<HTMLDivElement>;
tracksScrollRef: React.RefObject<HTMLDivElement>;
playheadRef?: React.RefObject<HTMLDivElement>;
}
/**
* useTimelinePlayhead
*
* Custom hook to manage playhead (scrubbing) logic for a timeline editor.
* Handles mouse interaction for timeline ruler, calculates time from mouse,
* and enables smooth scrubbing without unnecessary re-renders.
*/
export function useTimelinePlayhead({
currentTime,
duration,
@ -20,138 +25,101 @@ export function useTimelinePlayhead({
seek,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
}: UseTimelinePlayheadProps) {
// Playhead scrubbing state
const [isScrubbing, setIsScrubbing] = useState(false);
const [scrubTime, setScrubTime] = useState<number | null>(null);
// Get current project info (especially FPS) from global store
const { activeProject } = useProjectStore();
// Ruler drag detection state
const [isDraggingRuler, setIsDraggingRuler] = useState(false);
const [hasDraggedRuler, setHasDraggedRuler] = useState(false);
// Ref to track if currently scrubbing
const isScrubbingRef = useRef(false);
// Ref to hold the playhead time while scrubbing (does not trigger re-render)
const scrubTimeRef = useRef<number | null>(null);
// State to force re-render when scrubbing ends
const [_, forceRerender] = useState(0);
/**
* Determines the actual playhead position:
* - If scrubbing, use the value in scrubTimeRef
* - Otherwise, use the currentTime (controlled by external state)
*/
const playheadPosition =
isScrubbing && scrubTime !== null ? scrubTime : currentTime;
isScrubbingRef.current && scrubTimeRef.current !== null
? scrubTimeRef.current
: currentTime;
// --- Playhead Scrubbing Handlers ---
const handlePlayheadMouseDown = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation(); // Prevent ruler drag from triggering
setIsScrubbing(true);
handleScrub(e);
},
[duration, zoomLevel]
);
// Ruler mouse down handler
const handleRulerMouseDown = useCallback(
(e: React.MouseEvent) => {
// Only handle left mouse button
if (e.button !== 0) return;
// Don't interfere if clicking on the playhead itself
if (playheadRef?.current?.contains(e.target as Node)) return;
e.preventDefault();
setIsDraggingRuler(true);
setHasDraggedRuler(false);
// Start scrubbing immediately
setIsScrubbing(true);
handleScrub(e);
},
[duration, zoomLevel]
);
const handleScrub = useCallback(
/**
* Calculate timeline time (in seconds) based on mouse X position.
* - Gets bounding rect of the ruler
* - Adjusts for scroll position if ruler is scrollable
* - Converts X pixel offset to seconds using current zoom level
* - Snaps to nearest frame using FPS
*/
const getTimeFromMouse = useCallback(
(e: MouseEvent | React.MouseEvent) => {
const ruler = rulerRef.current;
if (!ruler) return;
const scrollArea = rulerScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
if (!ruler || !scrollArea) return 0;
const rect = ruler.getBoundingClientRect();
const x = e.clientX - rect.left;
const rawTime = Math.max(0, Math.min(duration, x / (50 * zoomLevel)));
// Use frame snapping for playhead scrubbing
const projectStore = useProjectStore.getState();
const projectFps = projectStore.activeProject?.fps || 30;
const time = snapTimeToFrame(rawTime, projectFps);
setScrubTime(time);
seek(time); // update video preview in real time
const scrollLeft = scrollArea.scrollLeft;
const x = e.clientX - rect.left + scrollLeft;
// Calculate how many pixels represent one second, depending on zoom
const pixelsPerSecond = 50 * zoomLevel;
const rawTime = Math.max(0, Math.min(duration, x / pixelsPerSecond));
const time = snapTimeToFrame(rawTime, activeProject?.fps || 30);
return time;
},
[duration, zoomLevel, seek, rulerRef]
[rulerRef, rulerScrollRef, duration, zoomLevel, activeProject?.fps]
);
// Mouse move/up event handlers
useEffect(() => {
if (!isScrubbing) return;
const onMouseMove = (e: MouseEvent) => {
handleScrub(e);
// Mark that we've dragged if ruler drag is active
if (isDraggingRuler) {
setHasDraggedRuler(true);
}
};
const onMouseUp = (e: MouseEvent) => {
setIsScrubbing(false);
if (scrubTime !== null) seek(scrubTime); // finalize seek
setScrubTime(null);
/**
* Handle mouse down event on the ruler:
* - Starts scrubbing and updates playhead immediately
* - Registers mousemove/mouseup events to allow scrubbing
* - Updates time as mouse moves and seeks to new time
* - Cleans up listeners and triggers re-render when scrubbing ends
*/
const handleRulerMouseDown = useCallback(
(e: React.MouseEvent) => {
if (e.button !== 0) return;
e.preventDefault();
const time = getTimeFromMouse(e);
// Handle ruler click vs drag
if (isDraggingRuler) {
setIsDraggingRuler(false);
// If we didn't drag, treat it as a click-to-seek
if (!hasDraggedRuler) {
handleScrub(e);
isScrubbingRef.current = true;
scrubTimeRef.current = time;
seek(time);
// Mouse move handler: update playhead and seek to new time
const onMouseMove = (e: MouseEvent) => {
const t = getTimeFromMouse(e);
if (t !== scrubTimeRef.current) {
scrubTimeRef.current = t;
seek(t);
}
setHasDraggedRuler(false);
}
};
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
return () => {
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
};
}, [
isScrubbing,
scrubTime,
seek,
handleScrub,
isDraggingRuler,
hasDraggedRuler,
]);
};
// --- Playhead auto-scroll effect ---
useEffect(() => {
const rulerViewport = rulerScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
const tracksViewport = tracksScrollRef.current?.querySelector(
"[data-radix-scroll-area-viewport]"
) as HTMLElement;
if (!rulerViewport || !tracksViewport) return;
const playheadPx = playheadPosition * 50 * zoomLevel; // TIMELINE_CONSTANTS.PIXELS_PER_SECOND = 50
const viewportWidth = rulerViewport.clientWidth;
const scrollMin = 0;
const scrollMax = rulerViewport.scrollWidth - viewportWidth;
// Center the playhead if it's not visible (100px buffer)
const desiredScroll = Math.max(
scrollMin,
Math.min(scrollMax, playheadPx - viewportWidth / 2)
);
if (
playheadPx < rulerViewport.scrollLeft + 100 ||
playheadPx > rulerViewport.scrollLeft + viewportWidth - 100
) {
rulerViewport.scrollLeft = tracksViewport.scrollLeft = desiredScroll;
}
}, [playheadPosition, duration, zoomLevel, rulerScrollRef, tracksScrollRef]);
// Mouse up handler: stop scrubbing, cleanup, and force re-render
const onMouseUp = () => {
isScrubbingRef.current = false;
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
forceRerender((v) => v + 1);
};
// Attach listeners to window for drag outside the ruler area
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
},
[getTimeFromMouse, seek]
);
return {
playheadPosition,
handlePlayheadMouseDown,
handleRulerMouseDown,
isDraggingRuler,
playheadPosition, // Current playhead position (real-time while scrubbing)
handleRulerMouseDown, // Attach to the ruler's onMouseDown
};
}

View File

@ -1,4 +1,5 @@
import { useState, useCallback, useEffect, RefObject } from "react";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { useState, useCallback, RefObject, useMemo } from "react";
interface UseTimelineZoomProps {
containerRef: RefObject<HTMLDivElement>;
@ -7,48 +8,86 @@ interface UseTimelineZoomProps {
interface UseTimelineZoomReturn {
zoomLevel: number;
zoomStep: number;
setZoomLevel: (zoomLevel: number | ((prev: number) => number)) => void;
handleChangeZoomStep: (zoomStep: number) => void;
handleChangeZoomLevel: (zoomStep: number) => void;
handleWheel: (e: React.WheelEvent) => void;
}
export function useTimelineZoom({
containerRef,
isInTimeline = false,
}: UseTimelineZoomProps): UseTimelineZoomReturn {
/**
* useTimelineZoom
*
* Custom hook to manage zoom logic for a timeline component.
* Handles zoom state, step calculation, level changes, and mouse wheel zooming (with ctrl/meta).
*/
export function useTimelineZoom(): UseTimelineZoomReturn {
// Current zoom level (1 = default)
const [zoomLevel, setZoomLevel] = useState(1);
const handleWheel = useCallback((e: React.WheelEvent) => {
// Only zoom if user is using pinch gesture (ctrlKey or metaKey is true)
if (e.ctrlKey || e.metaKey) {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.15 : 0.15;
setZoomLevel((prev) => Math.max(0.1, Math.min(10, prev + delta)));
}
// Otherwise, allow normal scrolling
/**
* Calculate the current zoom step based on the zoom level and a base step constant.
* Ensures minimum step is 1 (prevents zero or negative step).
*/
const zoomStep = useMemo(
() =>
Math.max(1, Math.round(zoomLevel / TIMELINE_CONSTANTS.ZOOM_STEP_BASE)),
[zoomLevel]
);
/**
* Update the zoom level using a given step.
* The zoom level is clamped to a minimum value defined in constants.
*/
const handleChangeZoomStep = useCallback((newStep: number) => {
setZoomLevel(
Math.max(
TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
newStep * TIMELINE_CONSTANTS.ZOOM_STEP_BASE
)
);
}, []);
// Prevent browser zooming in/out when in timeline
useEffect(() => {
const preventZoom = (e: WheelEvent) => {
if (
isInTimeline &&
(e.ctrlKey || e.metaKey) &&
containerRef.current?.contains(e.target as Node)
) {
e.preventDefault();
}
};
/**
* Update the zoom level directly.
* The new value is clamped between the defined minimum and maximum levels.
*/
const handleChangeZoomLevel = useCallback((newLevel: number) => {
setZoomLevel(
Math.max(
TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
Math.min(TIMELINE_CONSTANTS.ZOOM_LEVEL_MAX, newLevel)
)
);
}, []);
document.addEventListener("wheel", preventZoom, { passive: false });
return () => {
document.removeEventListener("wheel", preventZoom);
};
}, [isInTimeline, containerRef]);
/**
* Handle zooming using mouse wheel + ctrl/meta key (like browser zoom).
* Prevents default browser behavior and updates zoom level accordingly.
*/
const handleWheel = useCallback((e: React.WheelEvent) => {
if (e.ctrlKey || e.metaKey) {
e.preventDefault?.();
const delta =
e.deltaY > 0
? -TIMELINE_CONSTANTS.ZOOM_STEP_BASE
: TIMELINE_CONSTANTS.ZOOM_STEP_BASE;
setZoomLevel((prev) =>
Math.max(
TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
Math.min(TIMELINE_CONSTANTS.ZOOM_LEVEL_MAX, prev + delta)
)
);
}
}, []);
// Return all handlers and state values for use in timeline components
return {
zoomLevel,
setZoomLevel,
handleWheel,
zoomLevel, // Current zoom level
zoomStep, // Current zoom step (calculated from zoomLevel)
setZoomLevel, // Directly set the zoom level (accepts value or updater function)
handleChangeZoomStep, // Change zoom by step value
handleChangeZoomLevel, // Change zoom by level value
handleWheel, // Handler for mouse wheel zooming
};
}

View File

@ -1,5 +1,6 @@
import { MediaType } from "@/stores/media-store";
import { generateUUID } from "@/lib/utils";
import { ReactNode } from "react";
export type TrackType = "media" | "text" | "audio";
@ -155,3 +156,22 @@ export function validateElementTrackCompatibility(
return { isValid: true };
}
export interface TimelineTick {
left: number;
label?: string;
isMajor?: boolean;
}
export interface TimelineCanvasRulerWrapperProps {
children: ReactNode;
onMouseDown?: (e: React.MouseEvent<HTMLDivElement>) => void;
className?: string;
}
export interface TimelineCanvasRulerProps {
zoomLevel: number;
duration: number;
width: number;
height?: number;
}