mirror of
https://github.com/OpenCut-app/OpenCut.git
synced 2026-07-13 21:52:53 +02:00
Merge pull request #283 from KhacTuanIT/feature/optimize-timeline-ruler
Optimize timeline performance
This commit is contained in:
@@ -16,6 +16,7 @@ import { usePanelStore } from "@/stores/panel-store";
|
|||||||
import { useProjectStore } from "@/stores/project-store";
|
import { useProjectStore } from "@/stores/project-store";
|
||||||
import { EditorProvider } from "@/components/editor-provider";
|
import { EditorProvider } from "@/components/editor-provider";
|
||||||
import { usePlaybackControls } from "@/hooks/use-playback-controls";
|
import { usePlaybackControls } from "@/hooks/use-playback-controls";
|
||||||
|
import { useDisableBrowserZoom } from "@/hooks/use-disable-browser-zoom";
|
||||||
import { Onboarding } from "@/components/onboarding";
|
import { Onboarding } from "@/components/onboarding";
|
||||||
|
|
||||||
export default function Editor() {
|
export default function Editor() {
|
||||||
@@ -39,6 +40,7 @@ export default function Editor() {
|
|||||||
const handledProjectIds = useRef<Set<string>>(new Set());
|
const handledProjectIds = useRef<Set<string>>(new Set());
|
||||||
const [isOnboardingOpen, setIsOnboardingOpen] = useState(true);
|
const [isOnboardingOpen, setIsOnboardingOpen] = useState(true);
|
||||||
|
|
||||||
|
useDisableBrowserZoom();
|
||||||
usePlaybackControls();
|
usePlaybackControls();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
@@ -83,7 +83,11 @@ export function PropertiesPanel() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (mediaItem?.type === "audio") {
|
if (mediaItem?.type === "audio") {
|
||||||
return <AudioProperties element={element} />;
|
return (
|
||||||
|
<div key={elementId}>
|
||||||
|
<AudioProperties element={element} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -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;
|
||||||
@@ -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" />
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,10 +2,7 @@
|
|||||||
|
|
||||||
import { useRef } from "react";
|
import { useRef } from "react";
|
||||||
import { TimelineTrack } from "@/types/timeline";
|
import { TimelineTrack } from "@/types/timeline";
|
||||||
import {
|
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
|
||||||
TIMELINE_CONSTANTS,
|
|
||||||
getTotalTracksHeight,
|
|
||||||
} from "@/constants/timeline-constants";
|
|
||||||
import { useTimelinePlayhead } from "@/hooks/use-timeline-playhead";
|
import { useTimelinePlayhead } from "@/hooks/use-timeline-playhead";
|
||||||
|
|
||||||
interface TimelinePlayheadProps {
|
interface TimelinePlayheadProps {
|
||||||
@@ -16,7 +13,6 @@ interface TimelinePlayheadProps {
|
|||||||
seek: (time: number) => void;
|
seek: (time: number) => void;
|
||||||
rulerRef: React.RefObject<HTMLDivElement>;
|
rulerRef: React.RefObject<HTMLDivElement>;
|
||||||
rulerScrollRef: React.RefObject<HTMLDivElement>;
|
rulerScrollRef: React.RefObject<HTMLDivElement>;
|
||||||
tracksScrollRef: React.RefObject<HTMLDivElement>;
|
|
||||||
trackLabelsRef?: React.RefObject<HTMLDivElement>;
|
trackLabelsRef?: React.RefObject<HTMLDivElement>;
|
||||||
timelineRef: React.RefObject<HTMLDivElement>;
|
timelineRef: React.RefObject<HTMLDivElement>;
|
||||||
playheadRef?: React.RefObject<HTMLDivElement>;
|
playheadRef?: React.RefObject<HTMLDivElement>;
|
||||||
@@ -31,7 +27,6 @@ export function TimelinePlayhead({
|
|||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
trackLabelsRef,
|
trackLabelsRef,
|
||||||
timelineRef,
|
timelineRef,
|
||||||
playheadRef: externalPlayheadRef,
|
playheadRef: externalPlayheadRef,
|
||||||
@@ -39,15 +34,13 @@ export function TimelinePlayhead({
|
|||||||
}: TimelinePlayheadProps) {
|
}: TimelinePlayheadProps) {
|
||||||
const internalPlayheadRef = useRef<HTMLDivElement>(null);
|
const internalPlayheadRef = useRef<HTMLDivElement>(null);
|
||||||
const playheadRef = externalPlayheadRef || internalPlayheadRef;
|
const playheadRef = externalPlayheadRef || internalPlayheadRef;
|
||||||
const { playheadPosition, handlePlayheadMouseDown } = useTimelinePlayhead({
|
const { playheadPosition, handleRulerMouseDown } = useTimelinePlayhead({
|
||||||
currentTime,
|
currentTime,
|
||||||
duration,
|
duration,
|
||||||
zoomLevel,
|
zoomLevel,
|
||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
playheadRef,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Use timeline container height minus a few pixels for breathing room
|
// Use timeline container height minus a few pixels for breathing room
|
||||||
@@ -66,14 +59,14 @@ export function TimelinePlayhead({
|
|||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={playheadRef}
|
ref={playheadRef}
|
||||||
className="absolute pointer-events-auto z-[100]"
|
className="absolute pointer-events-auto z-[50]"
|
||||||
style={{
|
style={{
|
||||||
left: `${leftPosition}px`,
|
left: `${leftPosition}px`,
|
||||||
top: 0,
|
top: 0,
|
||||||
height: `${totalHeight}px`,
|
height: `${totalHeight}px`,
|
||||||
width: "2px", // Slightly wider for better click target
|
width: "2px", // Slightly wider for better click target
|
||||||
}}
|
}}
|
||||||
onMouseDown={handlePlayheadMouseDown}
|
onMouseDown={handleRulerMouseDown}
|
||||||
>
|
>
|
||||||
{/* The playhead line spanning full height */}
|
{/* The playhead line spanning full height */}
|
||||||
<div
|
<div
|
||||||
@@ -96,21 +89,24 @@ export function useTimelinePlayheadRuler({
|
|||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
}: Omit<
|
||||||
playheadRef,
|
TimelinePlayheadProps,
|
||||||
}: Omit<TimelinePlayheadProps, "tracks" | "trackLabelsRef" | "timelineRef">) {
|
| "tracks"
|
||||||
const { handleRulerMouseDown, isDraggingRuler } = useTimelinePlayhead({
|
| "trackLabelsRef"
|
||||||
|
| "timelineRef"
|
||||||
|
| "tracksScrollRef"
|
||||||
|
| "playheadRef"
|
||||||
|
>) {
|
||||||
|
const { handleRulerMouseDown } = useTimelinePlayhead({
|
||||||
currentTime,
|
currentTime,
|
||||||
duration,
|
duration,
|
||||||
zoomLevel,
|
zoomLevel,
|
||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
playheadRef,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return { handleRulerMouseDown, isDraggingRuler };
|
return { handleRulerMouseDown };
|
||||||
}
|
}
|
||||||
|
|
||||||
export { TimelinePlayhead as default };
|
export { TimelinePlayhead as default };
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import {
|
|||||||
Music,
|
Music,
|
||||||
TypeIcon,
|
TypeIcon,
|
||||||
Lock,
|
Lock,
|
||||||
|
ZoomIn,
|
||||||
|
ZoomOut,
|
||||||
LockOpen,
|
LockOpen,
|
||||||
} from "lucide-react";
|
} from "lucide-react";
|
||||||
import {
|
import {
|
||||||
@@ -55,6 +57,9 @@ import {
|
|||||||
TIMELINE_CONSTANTS,
|
TIMELINE_CONSTANTS,
|
||||||
snapTimeToFrame,
|
snapTimeToFrame,
|
||||||
} from "@/constants/timeline-constants";
|
} 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() {
|
export function Timeline() {
|
||||||
// Timeline shows all tracks (video, audio, effects) and their elements.
|
// Timeline shows all tracks (video, audio, effects) and their elements.
|
||||||
@@ -94,10 +99,13 @@ export function Timeline() {
|
|||||||
const [isInTimeline, setIsInTimeline] = useState(false);
|
const [isInTimeline, setIsInTimeline] = useState(false);
|
||||||
|
|
||||||
// Timeline zoom functionality
|
// Timeline zoom functionality
|
||||||
const { zoomLevel, setZoomLevel, handleWheel } = useTimelineZoom({
|
const {
|
||||||
containerRef: timelineRef,
|
zoomLevel,
|
||||||
isInTimeline,
|
zoomStep,
|
||||||
});
|
handleChangeZoomLevel,
|
||||||
|
handleChangeZoomStep,
|
||||||
|
handleWheel,
|
||||||
|
} = useTimelineZoom();
|
||||||
|
|
||||||
// Old marquee selection removed - using new SelectionBox component instead
|
// Old marquee selection removed - using new SelectionBox component instead
|
||||||
|
|
||||||
@@ -110,7 +118,6 @@ export function Timeline() {
|
|||||||
|
|
||||||
// Scroll synchronization and auto-scroll to playhead
|
// Scroll synchronization and auto-scroll to playhead
|
||||||
const rulerScrollRef = useRef<HTMLDivElement>(null);
|
const rulerScrollRef = useRef<HTMLDivElement>(null);
|
||||||
const tracksScrollRef = useRef<HTMLDivElement>(null);
|
|
||||||
const trackLabelsRef = useRef<HTMLDivElement>(null);
|
const trackLabelsRef = useRef<HTMLDivElement>(null);
|
||||||
const playheadRef = useRef<HTMLDivElement>(null);
|
const playheadRef = useRef<HTMLDivElement>(null);
|
||||||
const trackLabelsScrollRef = useRef<HTMLDivElement>(null);
|
const trackLabelsScrollRef = useRef<HTMLDivElement>(null);
|
||||||
@@ -127,8 +134,6 @@ export function Timeline() {
|
|||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
playheadRef,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Selection box functionality
|
// Selection box functionality
|
||||||
@@ -198,14 +203,14 @@ export function Timeline() {
|
|||||||
clearSelectedElements();
|
clearSelectedElements();
|
||||||
|
|
||||||
// Determine if we're clicking in ruler or tracks area
|
// Determine if we're clicking in ruler or tracks area
|
||||||
const isRulerClick = (e.target as HTMLElement).closest(
|
const isTracksAreaClick = (e.target as HTMLElement).closest(
|
||||||
"[data-ruler-area]"
|
"[data-tracks-area]"
|
||||||
);
|
);
|
||||||
|
|
||||||
let mouseX: number;
|
let mouseX: number;
|
||||||
let scrollLeft = 0;
|
let scrollLeft = 0;
|
||||||
|
|
||||||
if (isRulerClick) {
|
if (isTracksAreaClick) {
|
||||||
// Calculate based on ruler position
|
// Calculate based on ruler position
|
||||||
const rulerContent = rulerScrollRef.current?.querySelector(
|
const rulerContent = rulerScrollRef.current?.querySelector(
|
||||||
"[data-radix-scroll-area-viewport]"
|
"[data-radix-scroll-area-viewport]"
|
||||||
@@ -215,14 +220,7 @@ export function Timeline() {
|
|||||||
mouseX = e.clientX - rect.left;
|
mouseX = e.clientX - rect.left;
|
||||||
scrollLeft = rulerContent.scrollLeft;
|
scrollLeft = rulerContent.scrollLeft;
|
||||||
} else {
|
} else {
|
||||||
// Calculate based on tracks content position
|
return;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const rawTime = Math.max(
|
const rawTime = Math.max(
|
||||||
@@ -245,7 +243,6 @@ export function Timeline() {
|
|||||||
zoomLevel,
|
zoomLevel,
|
||||||
seek,
|
seek,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
clearSelectedElements,
|
clearSelectedElements,
|
||||||
isSelecting,
|
isSelecting,
|
||||||
justFinishedSelecting,
|
justFinishedSelecting,
|
||||||
@@ -509,14 +506,11 @@ export function Timeline() {
|
|||||||
const rulerViewport = rulerScrollRef.current?.querySelector(
|
const rulerViewport = rulerScrollRef.current?.querySelector(
|
||||||
"[data-radix-scroll-area-viewport]"
|
"[data-radix-scroll-area-viewport]"
|
||||||
) as HTMLElement;
|
) as HTMLElement;
|
||||||
const tracksViewport = tracksScrollRef.current?.querySelector(
|
|
||||||
"[data-radix-scroll-area-viewport]"
|
|
||||||
) as HTMLElement;
|
|
||||||
const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector(
|
const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector(
|
||||||
"[data-radix-scroll-area-viewport]"
|
"[data-radix-scroll-area-viewport]"
|
||||||
) as HTMLElement;
|
) as HTMLElement;
|
||||||
|
|
||||||
if (!rulerViewport || !tracksViewport) return;
|
if (!rulerViewport) return;
|
||||||
|
|
||||||
// Horizontal scroll synchronization between ruler and tracks
|
// Horizontal scroll synchronization between ruler and tracks
|
||||||
const handleRulerScroll = () => {
|
const handleRulerScroll = () => {
|
||||||
@@ -524,7 +518,6 @@ export function Timeline() {
|
|||||||
if (isUpdatingRef.current || now - lastRulerSync.current < 16) return;
|
if (isUpdatingRef.current || now - lastRulerSync.current < 16) return;
|
||||||
lastRulerSync.current = now;
|
lastRulerSync.current = now;
|
||||||
isUpdatingRef.current = true;
|
isUpdatingRef.current = true;
|
||||||
tracksViewport.scrollLeft = rulerViewport.scrollLeft;
|
|
||||||
isUpdatingRef.current = false;
|
isUpdatingRef.current = false;
|
||||||
};
|
};
|
||||||
const handleTracksScroll = () => {
|
const handleTracksScroll = () => {
|
||||||
@@ -532,12 +525,10 @@ export function Timeline() {
|
|||||||
if (isUpdatingRef.current || now - lastTracksSync.current < 16) return;
|
if (isUpdatingRef.current || now - lastTracksSync.current < 16) return;
|
||||||
lastTracksSync.current = now;
|
lastTracksSync.current = now;
|
||||||
isUpdatingRef.current = true;
|
isUpdatingRef.current = true;
|
||||||
rulerViewport.scrollLeft = tracksViewport.scrollLeft;
|
|
||||||
isUpdatingRef.current = false;
|
isUpdatingRef.current = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
rulerViewport.addEventListener("scroll", handleRulerScroll);
|
rulerViewport.addEventListener("scroll", handleRulerScroll);
|
||||||
tracksViewport.addEventListener("scroll", handleTracksScroll);
|
|
||||||
|
|
||||||
// Vertical scroll synchronization between track labels and tracks content
|
// Vertical scroll synchronization between track labels and tracks content
|
||||||
if (trackLabelsViewport) {
|
if (trackLabelsViewport) {
|
||||||
@@ -547,7 +538,6 @@ export function Timeline() {
|
|||||||
return;
|
return;
|
||||||
lastVerticalSync.current = now;
|
lastVerticalSync.current = now;
|
||||||
isUpdatingRef.current = true;
|
isUpdatingRef.current = true;
|
||||||
tracksViewport.scrollTop = trackLabelsViewport.scrollTop;
|
|
||||||
isUpdatingRef.current = false;
|
isUpdatingRef.current = false;
|
||||||
};
|
};
|
||||||
const handleTracksVerticalScroll = () => {
|
const handleTracksVerticalScroll = () => {
|
||||||
@@ -556,30 +546,22 @@ export function Timeline() {
|
|||||||
return;
|
return;
|
||||||
lastVerticalSync.current = now;
|
lastVerticalSync.current = now;
|
||||||
isUpdatingRef.current = true;
|
isUpdatingRef.current = true;
|
||||||
trackLabelsViewport.scrollTop = tracksViewport.scrollTop;
|
|
||||||
isUpdatingRef.current = false;
|
isUpdatingRef.current = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
trackLabelsViewport.addEventListener("scroll", handleTrackLabelsScroll);
|
trackLabelsViewport.addEventListener("scroll", handleTrackLabelsScroll);
|
||||||
tracksViewport.addEventListener("scroll", handleTracksVerticalScroll);
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
rulerViewport.removeEventListener("scroll", handleRulerScroll);
|
rulerViewport.removeEventListener("scroll", handleRulerScroll);
|
||||||
tracksViewport.removeEventListener("scroll", handleTracksScroll);
|
|
||||||
trackLabelsViewport.removeEventListener(
|
trackLabelsViewport.removeEventListener(
|
||||||
"scroll",
|
"scroll",
|
||||||
handleTrackLabelsScroll
|
handleTrackLabelsScroll
|
||||||
);
|
);
|
||||||
tracksViewport.removeEventListener(
|
|
||||||
"scroll",
|
|
||||||
handleTracksVerticalScroll
|
|
||||||
);
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
rulerViewport.removeEventListener("scroll", handleRulerScroll);
|
rulerViewport.removeEventListener("scroll", handleRulerScroll);
|
||||||
tracksViewport.removeEventListener("scroll", handleTracksScroll);
|
|
||||||
};
|
};
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
@@ -739,6 +721,39 @@ export function Timeline() {
|
|||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent>Delete element (Delete)</TooltipContent>
|
<TooltipContent>Delete element (Delete)</TooltipContent>
|
||||||
</Tooltip>
|
</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>
|
</TooltipProvider>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-1">
|
<div className="flex items-center gap-1">
|
||||||
@@ -772,7 +787,6 @@ export function Timeline() {
|
|||||||
seek={seek}
|
seek={seek}
|
||||||
rulerRef={rulerRef}
|
rulerRef={rulerRef}
|
||||||
rulerScrollRef={rulerScrollRef}
|
rulerScrollRef={rulerScrollRef}
|
||||||
tracksScrollRef={tracksScrollRef}
|
|
||||||
trackLabelsRef={trackLabelsRef}
|
trackLabelsRef={trackLabelsRef}
|
||||||
timelineRef={timelineRef}
|
timelineRef={timelineRef}
|
||||||
playheadRef={playheadRef}
|
playheadRef={playheadRef}
|
||||||
@@ -790,114 +804,38 @@ export function Timeline() {
|
|||||||
/>
|
/>
|
||||||
{/* Timeline Header with Ruler */}
|
{/* Timeline Header with Ruler */}
|
||||||
<div className="flex bg-panel sticky top-0 z-10">
|
<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 h-5 px-3" />
|
||||||
<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>
|
|
||||||
|
|
||||||
{/* Timeline Ruler */}
|
<div className="flex-1 overflow-hidden h-5">
|
||||||
<div
|
|
||||||
className="flex-1 relative overflow-hidden h-4"
|
|
||||||
onWheel={handleWheel}
|
|
||||||
onMouseDown={handleSelectionMouseDown}
|
|
||||||
onClick={handleTimelineContentClick}
|
|
||||||
data-ruler-area
|
|
||||||
>
|
|
||||||
<ScrollArea className="w-full" ref={rulerScrollRef}>
|
<ScrollArea className="w-full" ref={rulerScrollRef}>
|
||||||
<div
|
<TimelineCanvasRulerWrapper
|
||||||
ref={rulerRef}
|
ref={rulerRef}
|
||||||
className="relative h-4 select-none cursor-default"
|
|
||||||
style={{
|
|
||||||
width: `${dynamicTimelineWidth}px`,
|
|
||||||
}}
|
|
||||||
onMouseDown={handleRulerMouseDown}
|
onMouseDown={handleRulerMouseDown}
|
||||||
>
|
>
|
||||||
{/* Time markers */}
|
<TimelineCanvasRuler
|
||||||
{(() => {
|
zoomLevel={zoomLevel}
|
||||||
// Calculate appropriate time interval based on zoom level
|
duration={duration}
|
||||||
const getTimeInterval = (zoom: number) => {
|
width={dynamicTimelineWidth}
|
||||||
const pixelsPerSecond =
|
/>
|
||||||
TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoom;
|
</TimelineCanvasRulerWrapper>
|
||||||
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>
|
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Tracks Area */}
|
{/* Tracks Area */}
|
||||||
<div className="flex-1 flex overflow-hidden">
|
<ScrollArea className="w-full h-full">
|
||||||
|
<div
|
||||||
|
className="flex-1 flex overflow-hidden overflow-y-auto"
|
||||||
|
data-tracks-area
|
||||||
|
>
|
||||||
{/* Track Labels */}
|
{/* Track Labels */}
|
||||||
{tracks.length > 0 && (
|
{tracks.length > 0 && (
|
||||||
<div
|
<div
|
||||||
ref={trackLabelsRef}
|
ref={trackLabelsRef}
|
||||||
className="w-48 flex-shrink-0 border-r bg-panel-accent overflow-y-auto"
|
className="w-48 flex-shrink-0 border-r bg-panel-accent "
|
||||||
data-track-labels
|
data-track-labels
|
||||||
>
|
>
|
||||||
<ScrollArea className="w-full h-full" ref={trackLabelsScrollRef}>
|
<div className="flex flex-col gap-1" ref={trackLabelsScrollRef}>
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
{tracks.map((track) => (
|
{tracks.map((track) => (
|
||||||
<div
|
<div
|
||||||
key={track.id}
|
key={track.id}
|
||||||
@@ -915,7 +853,6 @@ export function Timeline() {
|
|||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -933,7 +870,6 @@ export function Timeline() {
|
|||||||
containerRef={tracksContainerRef}
|
containerRef={tracksContainerRef}
|
||||||
isActive={selectionBox?.isActive || false}
|
isActive={selectionBox?.isActive || false}
|
||||||
/>
|
/>
|
||||||
<ScrollArea className="w-full h-full" ref={tracksScrollRef}>
|
|
||||||
<div
|
<div
|
||||||
className="relative flex-1"
|
className="relative flex-1"
|
||||||
style={{
|
style={{
|
||||||
@@ -987,11 +923,11 @@ export function Timeline() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -76,6 +76,11 @@ export const TIMELINE_CONSTANTS = {
|
|||||||
DEFAULT_TEXT_DURATION: 5,
|
DEFAULT_TEXT_DURATION: 5,
|
||||||
DEFAULT_IMAGE_DURATION: 5,
|
DEFAULT_IMAGE_DURATION: 5,
|
||||||
ZOOM_LEVELS: [0.25, 0.5, 1, 1.5, 2, 3, 4],
|
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;
|
} as const;
|
||||||
|
|
||||||
// FPS presets for project settings
|
// FPS presets for project settings
|
||||||
|
|||||||
@@ -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);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { snapTimeToFrame } from "@/constants/timeline-constants";
|
import { snapTimeToFrame } from "@/constants/timeline-constants";
|
||||||
import { useProjectStore } from "@/stores/project-store";
|
import { useProjectStore } from "@/stores/project-store";
|
||||||
import { useState, useEffect, useCallback } from "react";
|
import { useRef, useState, useCallback } from "react";
|
||||||
|
|
||||||
interface UseTimelinePlayheadProps {
|
interface UseTimelinePlayheadProps {
|
||||||
currentTime: number;
|
currentTime: number;
|
||||||
@@ -9,10 +9,15 @@ interface UseTimelinePlayheadProps {
|
|||||||
seek: (time: number) => void;
|
seek: (time: number) => void;
|
||||||
rulerRef: React.RefObject<HTMLDivElement>;
|
rulerRef: React.RefObject<HTMLDivElement>;
|
||||||
rulerScrollRef: 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({
|
export function useTimelinePlayhead({
|
||||||
currentTime,
|
currentTime,
|
||||||
duration,
|
duration,
|
||||||
@@ -20,138 +25,101 @@ export function useTimelinePlayhead({
|
|||||||
seek,
|
seek,
|
||||||
rulerRef,
|
rulerRef,
|
||||||
rulerScrollRef,
|
rulerScrollRef,
|
||||||
tracksScrollRef,
|
|
||||||
playheadRef,
|
|
||||||
}: UseTimelinePlayheadProps) {
|
}: UseTimelinePlayheadProps) {
|
||||||
// Playhead scrubbing state
|
// Get current project info (especially FPS) from global store
|
||||||
const [isScrubbing, setIsScrubbing] = useState(false);
|
const { activeProject } = useProjectStore();
|
||||||
const [scrubTime, setScrubTime] = useState<number | null>(null);
|
|
||||||
|
|
||||||
// Ruler drag detection state
|
// Ref to track if currently scrubbing
|
||||||
const [isDraggingRuler, setIsDraggingRuler] = useState(false);
|
const isScrubbingRef = useRef(false);
|
||||||
const [hasDraggedRuler, setHasDraggedRuler] = useState(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 =
|
const playheadPosition =
|
||||||
isScrubbing && scrubTime !== null ? scrubTime : currentTime;
|
isScrubbingRef.current && scrubTimeRef.current !== null
|
||||||
|
? scrubTimeRef.current
|
||||||
|
: currentTime;
|
||||||
|
|
||||||
// --- Playhead Scrubbing Handlers ---
|
/**
|
||||||
const handlePlayheadMouseDown = useCallback(
|
* Calculate timeline time (in seconds) based on mouse X position.
|
||||||
(e: React.MouseEvent) => {
|
* - Gets bounding rect of the ruler
|
||||||
e.preventDefault();
|
* - Adjusts for scroll position if ruler is scrollable
|
||||||
e.stopPropagation(); // Prevent ruler drag from triggering
|
* - Converts X pixel offset to seconds using current zoom level
|
||||||
setIsScrubbing(true);
|
* - Snaps to nearest frame using FPS
|
||||||
handleScrub(e);
|
*/
|
||||||
},
|
const getTimeFromMouse = useCallback(
|
||||||
[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(
|
|
||||||
(e: MouseEvent | React.MouseEvent) => {
|
(e: MouseEvent | React.MouseEvent) => {
|
||||||
const ruler = rulerRef.current;
|
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 rect = ruler.getBoundingClientRect();
|
||||||
const x = e.clientX - rect.left;
|
const scrollLeft = scrollArea.scrollLeft;
|
||||||
const rawTime = Math.max(0, Math.min(duration, x / (50 * zoomLevel)));
|
const x = e.clientX - rect.left + scrollLeft;
|
||||||
// Use frame snapping for playhead scrubbing
|
|
||||||
const projectStore = useProjectStore.getState();
|
// Calculate how many pixels represent one second, depending on zoom
|
||||||
const projectFps = projectStore.activeProject?.fps || 30;
|
const pixelsPerSecond = 50 * zoomLevel;
|
||||||
const time = snapTimeToFrame(rawTime, projectFps);
|
const rawTime = Math.max(0, Math.min(duration, x / pixelsPerSecond));
|
||||||
setScrubTime(time);
|
const time = snapTimeToFrame(rawTime, activeProject?.fps || 30);
|
||||||
seek(time); // update video preview in real time
|
return time;
|
||||||
},
|
},
|
||||||
[duration, zoomLevel, seek, rulerRef]
|
[rulerRef, rulerScrollRef, duration, zoomLevel, activeProject?.fps]
|
||||||
);
|
);
|
||||||
|
|
||||||
// Mouse move/up event handlers
|
/**
|
||||||
useEffect(() => {
|
* Handle mouse down event on the ruler:
|
||||||
if (!isScrubbing) return;
|
* - Starts scrubbing and updates playhead immediately
|
||||||
const onMouseMove = (e: MouseEvent) => {
|
* - Registers mousemove/mouseup events to allow scrubbing
|
||||||
handleScrub(e);
|
* - Updates time as mouse moves and seeks to new time
|
||||||
// Mark that we've dragged if ruler drag is active
|
* - Cleans up listeners and triggers re-render when scrubbing ends
|
||||||
if (isDraggingRuler) {
|
*/
|
||||||
setHasDraggedRuler(true);
|
const handleRulerMouseDown = useCallback(
|
||||||
}
|
(e: React.MouseEvent) => {
|
||||||
};
|
if (e.button !== 0) return;
|
||||||
const onMouseUp = (e: MouseEvent) => {
|
e.preventDefault();
|
||||||
setIsScrubbing(false);
|
const time = getTimeFromMouse(e);
|
||||||
if (scrubTime !== null) seek(scrubTime); // finalize seek
|
|
||||||
setScrubTime(null);
|
|
||||||
|
|
||||||
// Handle ruler click vs drag
|
isScrubbingRef.current = true;
|
||||||
if (isDraggingRuler) {
|
scrubTimeRef.current = time;
|
||||||
setIsDraggingRuler(false);
|
seek(time);
|
||||||
// If we didn't drag, treat it as a click-to-seek
|
|
||||||
if (!hasDraggedRuler) {
|
// Mouse move handler: update playhead and seek to new time
|
||||||
handleScrub(e);
|
const onMouseMove = (e: MouseEvent) => {
|
||||||
}
|
const t = getTimeFromMouse(e);
|
||||||
setHasDraggedRuler(false);
|
if (t !== scrubTimeRef.current) {
|
||||||
|
scrubTimeRef.current = t;
|
||||||
|
seek(t);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
window.addEventListener("mousemove", onMouseMove);
|
|
||||||
window.addEventListener("mouseup", onMouseUp);
|
// Mouse up handler: stop scrubbing, cleanup, and force re-render
|
||||||
return () => {
|
const onMouseUp = () => {
|
||||||
|
isScrubbingRef.current = false;
|
||||||
window.removeEventListener("mousemove", onMouseMove);
|
window.removeEventListener("mousemove", onMouseMove);
|
||||||
window.removeEventListener("mouseup", onMouseUp);
|
window.removeEventListener("mouseup", onMouseUp);
|
||||||
|
forceRerender((v) => v + 1);
|
||||||
};
|
};
|
||||||
}, [
|
|
||||||
isScrubbing,
|
|
||||||
scrubTime,
|
|
||||||
seek,
|
|
||||||
handleScrub,
|
|
||||||
isDraggingRuler,
|
|
||||||
hasDraggedRuler,
|
|
||||||
]);
|
|
||||||
|
|
||||||
// --- Playhead auto-scroll effect ---
|
// Attach listeners to window for drag outside the ruler area
|
||||||
useEffect(() => {
|
window.addEventListener("mousemove", onMouseMove);
|
||||||
const rulerViewport = rulerScrollRef.current?.querySelector(
|
window.addEventListener("mouseup", onMouseUp);
|
||||||
"[data-radix-scroll-area-viewport]"
|
},
|
||||||
) as HTMLElement;
|
[getTimeFromMouse, seek]
|
||||||
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]);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
playheadPosition,
|
playheadPosition, // Current playhead position (real-time while scrubbing)
|
||||||
handlePlayheadMouseDown,
|
handleRulerMouseDown, // Attach to the ruler's onMouseDown
|
||||||
handleRulerMouseDown,
|
|
||||||
isDraggingRuler,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
interface UseTimelineZoomProps {
|
||||||
containerRef: RefObject<HTMLDivElement>;
|
containerRef: RefObject<HTMLDivElement>;
|
||||||
@@ -7,48 +8,86 @@ interface UseTimelineZoomProps {
|
|||||||
|
|
||||||
interface UseTimelineZoomReturn {
|
interface UseTimelineZoomReturn {
|
||||||
zoomLevel: number;
|
zoomLevel: number;
|
||||||
|
zoomStep: number;
|
||||||
setZoomLevel: (zoomLevel: number | ((prev: number) => number)) => void;
|
setZoomLevel: (zoomLevel: number | ((prev: number) => number)) => void;
|
||||||
|
handleChangeZoomStep: (zoomStep: number) => void;
|
||||||
|
handleChangeZoomLevel: (zoomStep: number) => void;
|
||||||
handleWheel: (e: React.WheelEvent) => void;
|
handleWheel: (e: React.WheelEvent) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useTimelineZoom({
|
/**
|
||||||
containerRef,
|
* useTimelineZoom
|
||||||
isInTimeline = false,
|
*
|
||||||
}: UseTimelineZoomProps): UseTimelineZoomReturn {
|
* 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 [zoomLevel, setZoomLevel] = useState(1);
|
||||||
|
|
||||||
const handleWheel = useCallback((e: React.WheelEvent) => {
|
/**
|
||||||
// Only zoom if user is using pinch gesture (ctrlKey or metaKey is true)
|
* Calculate the current zoom step based on the zoom level and a base step constant.
|
||||||
if (e.ctrlKey || e.metaKey) {
|
* Ensures minimum step is 1 (prevents zero or negative step).
|
||||||
e.preventDefault();
|
*/
|
||||||
const delta = e.deltaY > 0 ? -0.15 : 0.15;
|
const zoomStep = useMemo(
|
||||||
setZoomLevel((prev) => Math.max(0.1, Math.min(10, prev + delta)));
|
() =>
|
||||||
}
|
Math.max(1, Math.round(zoomLevel / TIMELINE_CONSTANTS.ZOOM_STEP_BASE)),
|
||||||
// Otherwise, allow normal scrolling
|
[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(() => {
|
* Update the zoom level directly.
|
||||||
const preventZoom = (e: WheelEvent) => {
|
* The new value is clamped between the defined minimum and maximum levels.
|
||||||
if (
|
*/
|
||||||
isInTimeline &&
|
const handleChangeZoomLevel = useCallback((newLevel: number) => {
|
||||||
(e.ctrlKey || e.metaKey) &&
|
setZoomLevel(
|
||||||
containerRef.current?.contains(e.target as Node)
|
Math.max(
|
||||||
) {
|
TIMELINE_CONSTANTS.ZOOM_LEVEL_MIN,
|
||||||
e.preventDefault();
|
Math.min(TIMELINE_CONSTANTS.ZOOM_LEVEL_MAX, newLevel)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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)
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
document.addEventListener("wheel", preventZoom, { passive: false });
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
document.removeEventListener("wheel", preventZoom);
|
|
||||||
};
|
|
||||||
}, [isInTimeline, containerRef]);
|
|
||||||
|
|
||||||
|
// Return all handlers and state values for use in timeline components
|
||||||
return {
|
return {
|
||||||
zoomLevel,
|
zoomLevel, // Current zoom level
|
||||||
setZoomLevel,
|
zoomStep, // Current zoom step (calculated from zoomLevel)
|
||||||
handleWheel,
|
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
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { MediaType } from "@/stores/media-store";
|
import { MediaType } from "@/stores/media-store";
|
||||||
import { generateUUID } from "@/lib/utils";
|
import { generateUUID } from "@/lib/utils";
|
||||||
|
import { ReactNode } from "react";
|
||||||
|
|
||||||
export type TrackType = "media" | "text" | "audio";
|
export type TrackType = "media" | "text" | "audio";
|
||||||
|
|
||||||
@@ -155,3 +156,22 @@ export function validateElementTrackCompatibility(
|
|||||||
|
|
||||||
return { isValid: true };
|
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;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user