From 6e3a9ec7ecfeb1245f846ef58b4d218aa373978e Mon Sep 17 00:00:00 2001 From: vadi25 Date: Wed, 16 Jul 2025 20:24:16 +0200 Subject: [PATCH 01/10] fixed so only Projects can be created in production, so DB is safe from being saturated in production --- apps/web/src/stores/project-store.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts index efb9cc71..5017be2d 100644 --- a/apps/web/src/stores/project-store.ts +++ b/apps/web/src/stores/project-store.ts @@ -5,6 +5,7 @@ import { toast } from "sonner"; import { useMediaStore } from "./media-store"; import { useTimelineStore } from "./timeline-store"; import { generateUUID } from "@/lib/utils"; +import { env } from "@/env"; interface ProjectStore { activeProject: TProject | null; @@ -36,6 +37,16 @@ export const useProjectStore = create((set, get) => ({ isInitialized: false, createNewProject: async (name: string) => { + try { + if (process.env.NODE_ENV !== "development") { + toast.error("Project creation is disabled outside development environment"); + throw new Error("Not allowed in production"); + } + } catch (error) { + toast.error("Failed to create new project"); + throw error; + } + const newProject: TProject = { id: generateUUID(), name, From 0988a936ad0ed14781ffd038b80a24fbebc1a6ec Mon Sep 17 00:00:00 2001 From: vadi25 Date: Wed, 16 Jul 2025 20:37:13 +0200 Subject: [PATCH 02/10] added redirect to project page if users not authorized, to be change by rolegate in the future --- apps/web/src/app/projects/page.tsx | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/web/src/app/projects/page.tsx b/apps/web/src/app/projects/page.tsx index 499b999a..9fcb025b 100644 --- a/apps/web/src/app/projects/page.tsx +++ b/apps/web/src/app/projects/page.tsx @@ -1,7 +1,8 @@ -"use client"; +"use client" +import { redirect } from "next/navigation"; import Link from "next/link"; -import { useState } from "react"; +import React, { useState } from "react"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; @@ -28,8 +29,15 @@ import { useProjectStore } from "@/stores/project-store"; import { useRouter } from "next/navigation"; import { DeleteProjectDialog } from "@/components/delete-project-dialog"; import { RenameProjectDialog } from "@/components/rename-project-dialog"; +import { toast } from "sonner"; export default function ProjectsPage() { + + if (process.env.NODE_ENV !== "development") { + toast.error("You are not allowed to access this page"); + redirect("/"); + } + const { createNewProject, savedProjects, From 6ff4bcd09391096e7c231a53484fd30dca939690 Mon Sep 17 00:00:00 2001 From: Simon Orzel Date: Wed, 16 Jul 2025 23:31:51 +0200 Subject: [PATCH 03/10] feat: starts to refactor timeline --- .../src/components/editor/snap-indicator.tsx | 2 +- .../components/editor/timeline-playhead.tsx | 2 +- apps/web/src/components/editor/timeline.tsx | 473 +++++++----------- 3 files changed, 175 insertions(+), 302 deletions(-) diff --git a/apps/web/src/components/editor/snap-indicator.tsx b/apps/web/src/components/editor/snap-indicator.tsx index 83a1f678..846d0bbb 100644 --- a/apps/web/src/components/editor/snap-indicator.tsx +++ b/apps/web/src/components/editor/snap-indicator.tsx @@ -40,7 +40,7 @@ export function SnapIndicator({ return (
(null); + const tracksContainerRef = useRef(null); + + // Temporary refs for compatibility (should be removed when TimelinePlayhead is updated) const rulerScrollRef = useRef(null); const tracksScrollRef = useRef(null); - const trackLabelsRef = useRef(null); - const playheadRef = useRef(null); - const trackLabelsScrollRef = useRef(null); - const isUpdatingRef = useRef(false); - const lastRulerSync = useRef(0); - const lastTracksSync = useRef(0); - const lastVerticalSync = useRef(0); - // Timeline playhead ruler handlers + // Timeline playhead ruler handlers - temporarily keeping all refs for compatibility const { handleRulerMouseDown } = useTimelinePlayheadRuler({ currentTime, duration, @@ -132,7 +129,6 @@ export function Timeline() { }); // Selection box functionality - const tracksContainerRef = useRef(null); const { selectionBox, handleMouseDown: handleSelectionMouseDown, @@ -159,7 +155,7 @@ export function Timeline() { setCurrentSnapPoint(snapPoint); }, []); - // Timeline content click to seek handler + // Timeline content click to seek handler - simplified for single scroll area const handleTimelineContentClick = useCallback( (e: React.MouseEvent) => { console.log( @@ -230,7 +226,7 @@ export function Timeline() { Math.min( duration, (mouseX + scrollLeft) / - (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) + (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) ) ); @@ -244,11 +240,10 @@ export function Timeline() { duration, zoomLevel, seek, - rulerScrollRef, - tracksScrollRef, clearSelectedElements, isSelecting, justFinishedSelecting, + activeProject?.fps, ] ); @@ -504,84 +499,23 @@ export function Timeline() { clearSelectedElements(); }; - // --- Scroll synchronization effect --- + // Add wheel event listeners with passive: false to allow preventDefault 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; - const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector( - "[data-radix-scroll-area-viewport]" - ) as HTMLElement; + const timelineContainer = timelineRef.current; + if (!timelineContainer || !isInTimeline) return; - if (!rulerViewport || !tracksViewport) return; - - // Horizontal scroll synchronization between ruler and tracks - const handleRulerScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastRulerSync.current < 16) return; - lastRulerSync.current = now; - isUpdatingRef.current = true; - tracksViewport.scrollLeft = rulerViewport.scrollLeft; - isUpdatingRef.current = false; - }; - const handleTracksScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastTracksSync.current < 16) return; - lastTracksSync.current = now; - isUpdatingRef.current = true; - rulerViewport.scrollLeft = tracksViewport.scrollLeft; - isUpdatingRef.current = false; + const handleWheelCapture = (e: WheelEvent) => { + // Call the existing handleWheel function + handleWheel(e as any); }; - rulerViewport.addEventListener("scroll", handleRulerScroll); - tracksViewport.addEventListener("scroll", handleTracksScroll); - - // Vertical scroll synchronization between track labels and tracks content - if (trackLabelsViewport) { - const handleTrackLabelsScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastVerticalSync.current < 16) - return; - lastVerticalSync.current = now; - isUpdatingRef.current = true; - tracksViewport.scrollTop = trackLabelsViewport.scrollTop; - isUpdatingRef.current = false; - }; - const handleTracksVerticalScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastVerticalSync.current < 16) - 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 - ); - }; - } + // Add wheel event listener with passive: false to allow preventDefault + timelineContainer.addEventListener("wheel", handleWheelCapture, { passive: false }); return () => { - rulerViewport.removeEventListener("scroll", handleRulerScroll); - tracksViewport.removeEventListener("scroll", handleTracksScroll); + timelineContainer.removeEventListener("wheel", handleWheelCapture); }; - }, []); + }, [handleWheel, isInTimeline]); return (
setIsInTimeline(false)} > {/* Toolbar */} -
+
- {/* Play/Pause Button */}
diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index ca64129f..1ea41c70 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -17,6 +17,7 @@ import { TypeIcon, Lock, LockOpen, + Plus, } from "lucide-react"; import { Tooltip, @@ -37,7 +38,7 @@ import { useProjectStore } from "@/stores/project-store"; import { useTimelineZoom } from "@/hooks/use-timeline-zoom"; import { processMediaFiles } from "@/lib/media-processing"; import { toast } from "sonner"; -import { useState, useRef, useEffect, useCallback } from "react"; +import { useState, useRef, useEffect, useCallback, Fragment } from "react"; import { TimelineTrackContent } from "./timeline-track"; import { TimelinePlayhead, @@ -108,15 +109,18 @@ export function Timeline() { timelineRef.current?.clientWidth || 1000 // Minimum width ); - // Essential refs for timeline functionality - const playheadRef = useRef(null); - const tracksContainerRef = useRef(null); - - // Temporary refs for compatibility (should be removed when TimelinePlayhead is updated) + // Scroll synchronization and auto-scroll to playhead const rulerScrollRef = useRef(null); const tracksScrollRef = useRef(null); + const trackLabelsRef = useRef(null); + const playheadRef = useRef(null); + const trackLabelsScrollRef = useRef(null); + const isUpdatingRef = useRef(false); + const lastRulerSync = useRef(0); + const lastTracksSync = useRef(0); + const lastVerticalSync = useRef(0); - // Timeline playhead ruler handlers - temporarily keeping all refs for compatibility + // Timeline playhead ruler handlers const { handleRulerMouseDown } = useTimelinePlayheadRuler({ currentTime, duration, @@ -129,6 +133,7 @@ export function Timeline() { }); // Selection box functionality + const tracksContainerRef = useRef(null); const { selectionBox, handleMouseDown: handleSelectionMouseDown, @@ -155,7 +160,7 @@ export function Timeline() { setCurrentSnapPoint(snapPoint); }, []); - // Timeline content click to seek handler - simplified for single scroll area + // Timeline content click to seek handler const handleTimelineContentClick = useCallback( (e: React.MouseEvent) => { console.log( @@ -240,10 +245,11 @@ export function Timeline() { duration, zoomLevel, seek, + rulerScrollRef, + tracksScrollRef, clearSelectedElements, isSelecting, justFinishedSelecting, - activeProject?.fps, ] ); @@ -499,6 +505,85 @@ export function Timeline() { clearSelectedElements(); }; + // --- Scroll synchronization 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; + const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector( + "[data-radix-scroll-area-viewport]" + ) as HTMLElement; + + if (!rulerViewport || !tracksViewport) return; + + // Horizontal scroll synchronization between ruler and tracks + const handleRulerScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastRulerSync.current < 16) return; + lastRulerSync.current = now; + isUpdatingRef.current = true; + tracksViewport.scrollLeft = rulerViewport.scrollLeft; + isUpdatingRef.current = false; + }; + const handleTracksScroll = () => { + const now = Date.now(); + 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) { + const handleTrackLabelsScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastVerticalSync.current < 16) + return; + lastVerticalSync.current = now; + isUpdatingRef.current = true; + tracksViewport.scrollTop = trackLabelsViewport.scrollTop; + isUpdatingRef.current = false; + }; + const handleTracksVerticalScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastVerticalSync.current < 16) + 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); + }; + }, []); + // Add wheel event listeners with passive: false to allow preventDefault useEffect(() => { const timelineContainer = timelineRef.current; @@ -525,7 +610,7 @@ export function Timeline() { onMouseLeave={() => setIsInTimeline(false)} > {/* Toolbar */} -
+
@@ -692,178 +777,204 @@ export function Timeline() { {/* Timeline Container */} - + {/* Timeline Container with Grid Layout */} +
setIsInTimeline(true)} + onMouseLeave={() => setIsInTimeline(false)} + onMouseDown={handleSelectionMouseDown} + onClick={handleTimelineContentClick} + > +
+
0 ? `grid-rows-[20px_repeat(${tracks.length},minmax(0,max-content))]` : 'grid-rows-[20px_1fr]'}`}> - {/* Timeline Tracks Content */} -
- + {/* Top-Left Corner (Empty space above track labels) */} +
- - -
-
+ {/* Top Row (Sticky Ruler Header) */} +
+
+ {(() => { + // 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 + }; -
- {(() => { - // 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; - 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; - 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; - const isMainMarker = - time % (interval >= 1 ? Math.max(1, interval) : 1) === 0; + return ( +
+ - return ( -
- - {(() => { - const formatTime = (seconds: number) => { - const hours = Math.floor(seconds / 3600); - const minutes = Math.floor((seconds % 3600) / 60); - const secs = seconds % 60; + {(() => { + 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); - })()} - -
- ); - }).filter(Boolean); - })()} -
-
- {tracks.map((track, index) => ( -
- -
-
- -
- {track.muted && ( - - Muted + 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); + })()} - )} -
- - -
{ - // If clicking empty area (not on a element), deselect all elements - if ( - !(e.target as HTMLElement).closest( - ".timeline-element" - ) - ) { - clearSelectedElements(); - } - }} - > - -
-
- - toggleTrackMute(track.id)} - > - {track.muted ? "Unmute Track" : "Mute Track"} - - - Track settings (soon) - - -
-
- ))} - +
+ ); + }).filter(Boolean); + })()}
+
+ + {/* Track Rows */} + {tracks.map((track, index) => ( + + {/* Left Column (Sticky Track Labels) */} +
+
+ +
+ {track.muted && ( + + Muted + + )} +
+ + {/* Scrollable Track Content */} + + +
{ + // If clicking empty area (not on a element), deselect all elements + if ( + !(e.target as HTMLElement).closest( + ".timeline-element" + ) + ) { + clearSelectedElements(); + } + }} + > + +
+
+ + toggleTrackMute(track.id)} + > + {track.muted ? "Unmute Track" : "Mute Track"} + + + Track settings (soon) + + +
+
+ ))} + {/* Add Track Button - spans full width */} +
addTrack('media')} + className="col-span-1 sticky left-0 w-full flex items-center border-b border-muted bg-card/[0.99] hover:bg-card/50 transition-colors cursor-pointer z-[89]" + style={{ height: `${getTrackHeight("media")}px` }} + > +
+ +
+
- +
+ + {/* Overlay Components */} + + + + + +
+ +
); } From 9fa9f406fe2722cec1e0d65d9b3868acd1e99f87 Mon Sep 17 00:00:00 2001 From: Simon Orzel Date: Thu, 17 Jul 2025 01:59:39 +0200 Subject: [PATCH 07/10] feat: splits working code --- apps/web/src/components/editor/timeline.tsx | 956 ++---------------- .../src/components/editor/timeline/index.ts | 11 + .../timeline/timeline-action-handlers.tsx | 162 +++ .../timeline/timeline-content-click.tsx | 126 +++ .../editor/timeline/timeline-content.tsx | 123 +++ .../timeline/timeline-drag-handlers.tsx | 143 +++ .../{ => timeline}/timeline-playhead.tsx | 4 +- .../editor/timeline/timeline-ruler.tsx | 120 +++ .../editor/timeline/timeline-scroll-sync.tsx | 99 ++ .../editor/timeline/timeline-toolbar.tsx | 219 ++++ .../editor/timeline/timeline-tracks-area.tsx | 99 ++ .../timeline/timeline-wheel-handler.tsx | 33 + .../components/editor/timeline/track-icon.tsx | 18 + 13 files changed, 1231 insertions(+), 882 deletions(-) create mode 100644 apps/web/src/components/editor/timeline/index.ts create mode 100644 apps/web/src/components/editor/timeline/timeline-action-handlers.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-content-click.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-content.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-drag-handlers.tsx rename apps/web/src/components/editor/{ => timeline}/timeline-playhead.tsx (93%) create mode 100644 apps/web/src/components/editor/timeline/timeline-ruler.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-scroll-sync.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-toolbar.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-tracks-area.tsx create mode 100644 apps/web/src/components/editor/timeline/timeline-wheel-handler.tsx create mode 100644 apps/web/src/components/editor/timeline/track-icon.tsx diff --git a/apps/web/src/components/editor/timeline.tsx b/apps/web/src/components/editor/timeline.tsx index 1ea41c70..932896f4 100644 --- a/apps/web/src/components/editor/timeline.tsx +++ b/apps/web/src/components/editor/timeline.tsx @@ -1,61 +1,19 @@ "use client"; -import { ScrollArea } from "../ui/scroll-area"; -import { Button } from "../ui/button"; -import { - Scissors, - ArrowLeftToLine, - ArrowRightToLine, - Trash2, - Snowflake, - Copy, - SplitSquareHorizontal, - Pause, - Play, - Video, - Music, - TypeIcon, - Lock, - LockOpen, - Plus, -} from "lucide-react"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, - TooltipProvider, -} from "../ui/tooltip"; -import { - ContextMenu, - ContextMenuContent, - ContextMenuItem, - ContextMenuTrigger, -} from "../ui/context-menu"; +import { useState, useRef, useEffect, useCallback } from "react"; import { useTimelineStore } from "@/stores/timeline-store"; -import { useMediaStore } from "@/stores/media-store"; import { usePlaybackStore } from "@/stores/playback-store"; -import { useProjectStore } from "@/stores/project-store"; import { useTimelineZoom } from "@/hooks/use-timeline-zoom"; -import { processMediaFiles } from "@/lib/media-processing"; -import { toast } from "sonner"; -import { useState, useRef, useEffect, useCallback, Fragment } from "react"; -import { TimelineTrackContent } from "./timeline-track"; -import { - TimelinePlayhead, - useTimelinePlayheadRuler, -} from "./timeline-playhead"; -import { SelectionBox } from "./selection-box"; import { useSelectionBox } from "@/hooks/use-selection-box"; -import { SnapIndicator } from "./snap-indicator"; import { SnapPoint } from "@/hooks/use-timeline-snapping"; -import type { DragData, TimelineTrack } from "@/types/timeline"; -import { - getTrackHeight, - getCumulativeHeightBefore, - getTotalTracksHeight, - TIMELINE_CONSTANTS, - snapTimeToFrame, -} from "@/constants/timeline-constants"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; +import { TimelineToolbar } from "./timeline/timeline-toolbar"; +import { TimelineContent } from "./timeline/timeline-content"; +import { useTimelineDragHandlers } from "./timeline/timeline-drag-handlers"; +import { useTimelineActionHandlers } from "./timeline/timeline-action-handlers"; +import { useTimelineScrollSync } from "./timeline/timeline-scroll-sync"; +import { useTimelineContentClick } from "./timeline/timeline-content-click"; +import { useTimelineWheelHandler } from "./timeline/timeline-wheel-handler"; export function Timeline() { // Timeline shows all tracks (video, audio, effects) and their elements. @@ -64,32 +22,17 @@ export function Timeline() { const { tracks, - addTrack, - addElementToTrack, - removeElementFromTrack, getTotalDuration, selectedElements, clearSelectedElements, setSelectedElements, - splitElement, - splitAndKeepLeft, - splitAndKeepRight, - toggleTrackMute, - separateAudio, - undo, - redo, - snappingEnabled, - toggleSnapping, dragState, + snappingEnabled, } = useTimelineStore(); - const { mediaItems, addMediaItem } = useMediaStore(); - const { activeProject } = useProjectStore(); - const { currentTime, duration, seek, setDuration, isPlaying, toggle } = - usePlaybackStore(); + const { currentTime, duration, seek, setDuration } = usePlaybackStore(); const [isDragOver, setIsDragOver] = useState(false); const [isProcessing, setIsProcessing] = useState(false); const [progress, setProgress] = useState(0); - const dragCounterRef = useRef(0); const timelineRef = useRef(null); const rulerRef = useRef(null); const [isInTimeline, setIsInTimeline] = useState(false); @@ -100,8 +43,6 @@ export function Timeline() { isInTimeline, }); - // Old marquee selection removed - using new SelectionBox component instead - // Dynamic timeline width calculation based on playhead position and duration const dynamicTimelineWidth = Math.max( (duration || 0) * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel, // Base width from duration @@ -115,22 +56,6 @@ export function Timeline() { const trackLabelsRef = useRef(null); const playheadRef = useRef(null); const trackLabelsScrollRef = useRef(null); - const isUpdatingRef = useRef(false); - const lastRulerSync = useRef(0); - const lastTracksSync = useRef(0); - const lastVerticalSync = useRef(0); - - // Timeline playhead ruler handlers - const { handleRulerMouseDown } = useTimelinePlayheadRuler({ - currentTime, - duration, - zoomLevel, - seek, - rulerRef, - rulerScrollRef, - tracksScrollRef, - playheadRef, - }); // Selection box functionality const tracksContainerRef = useRef(null); @@ -160,98 +85,18 @@ export function Timeline() { setCurrentSnapPoint(snapPoint); }, []); - // Timeline content click to seek handler - const handleTimelineContentClick = useCallback( - (e: React.MouseEvent) => { - console.log( - JSON.stringify({ - timelineClick: { - isSelecting, - justFinishedSelecting, - willReturn: isSelecting || justFinishedSelecting, - }, - }) - ); - - // Don't seek if this was a selection box operation - if (isSelecting || justFinishedSelecting) { - return; - } - - // Don't seek if clicking on timeline elements, but still deselect - if ((e.target as HTMLElement).closest(".timeline-element")) { - return; - } - - // Don't seek if clicking on playhead - if (playheadRef.current?.contains(e.target as Node)) { - return; - } - - // Don't seek if clicking on track labels - if ((e.target as HTMLElement).closest("[data-track-labels]")) { - clearSelectedElements(); - return; - } - - // Clear selected elements when clicking empty timeline area - console.log(JSON.stringify({ clearingSelectedElements: true })); - clearSelectedElements(); - - // Determine if we're clicking in ruler or tracks area - const isRulerClick = (e.target as HTMLElement).closest( - "[data-ruler-area]" - ); - - let mouseX: number; - let scrollLeft = 0; - - if (isRulerClick) { - // Calculate based on ruler position - const rulerContent = rulerScrollRef.current?.querySelector( - "[data-radix-scroll-area-viewport]" - ) as HTMLElement; - if (!rulerContent) return; - const rect = rulerContent.getBoundingClientRect(); - 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; - } - - const rawTime = Math.max( - 0, - Math.min( - duration, - (mouseX + scrollLeft) / - (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) - ) - ); - - // Use frame snapping for timeline clicking - const projectFps = activeProject?.fps || 30; - const time = snapTimeToFrame(rawTime, projectFps); - - seek(time); - }, - [ - duration, - zoomLevel, - seek, - rulerScrollRef, - tracksScrollRef, - clearSelectedElements, - isSelecting, - justFinishedSelecting, - ] - ); + // Timeline content click handler + const { handleTimelineContentClick } = useTimelineContentClick({ + duration, + zoomLevel, + seek, + rulerScrollRef, + tracksScrollRef, + clearSelectedElements, + isSelecting, + justFinishedSelecting, + playheadRef, + }); // Update timeline duration when tracks change useEffect(() => { @@ -259,348 +104,40 @@ export function Timeline() { setDuration(Math.max(totalDuration, 10)); // Minimum 10 seconds for empty timeline }, [tracks, setDuration, getTotalDuration]); - // Old marquee system removed - using new SelectionBox component instead + // Drag handlers + const { dragProps } = useTimelineDragHandlers({ + isDragOver, + setIsDragOver, + isProcessing, + setIsProcessing, + progress, + setProgress, + }); - const handleDragEnter = (e: React.DragEvent) => { - // When something is dragged over the timeline, show overlay - e.preventDefault(); - // Don't show overlay for timeline elements - they're handled by tracks - if (e.dataTransfer.types.includes("application/x-timeline-element")) { - return; - } - dragCounterRef.current += 1; - if (!isDragOver) { - setIsDragOver(true); - } - }; + // Action handlers + const { + handleSplitSelected, + handleDuplicateSelected, + handleFreezeSelected, + handleSplitAndKeepLeft, + handleSplitAndKeepRight, + handleSeparateAudio, + handleDeleteSelected, + } = useTimelineActionHandlers(); - const handleDragOver = (e: React.DragEvent) => { - e.preventDefault(); - }; + // Scroll synchronization + useTimelineScrollSync({ + rulerScrollRef, + tracksScrollRef, + trackLabelsScrollRef, + }); - const handleDragLeave = (e: React.DragEvent) => { - e.preventDefault(); - - // Don't update state for timeline elements - they're handled by tracks - if (e.dataTransfer.types.includes("application/x-timeline-element")) { - return; - } - - dragCounterRef.current -= 1; - if (dragCounterRef.current === 0) { - setIsDragOver(false); - } - }; - - const handleDrop = async (e: React.DragEvent) => { - // When media is dropped, add it as a new track/element - e.preventDefault(); - setIsDragOver(false); - dragCounterRef.current = 0; - - // Ignore timeline element drags - they're handled by track-specific handlers - const hasTimelineElement = e.dataTransfer.types.includes( - "application/x-timeline-element" - ); - if (hasTimelineElement) { - return; - } - - const itemData = e.dataTransfer.getData("application/x-media-item"); - if (itemData) { - try { - const dragData: DragData = JSON.parse(itemData); - - if (dragData.type === "text") { - // Always create new text track to avoid overlaps - useTimelineStore.getState().addTextToNewTrack(dragData); - } else { - // Handle media items - const mediaItem = mediaItems.find( - (item: any) => item.id === dragData.id - ); - if (!mediaItem) { - toast.error("Media item not found"); - return; - } - - useTimelineStore.getState().addMediaToNewTrack(mediaItem); - } - } catch (error) { - console.error("Error parsing dropped item data:", error); - toast.error("Failed to add item to timeline"); - } - } else if (e.dataTransfer.files?.length > 0) { - // Handle file drops by creating new tracks - if (!activeProject) { - toast.error("No active project"); - return; - } - - setIsProcessing(true); - setProgress(0); - try { - const processedItems = await processMediaFiles( - e.dataTransfer.files, - (p) => setProgress(p) - ); - for (const processedItem of processedItems) { - await addMediaItem(activeProject.id, processedItem); - const currentMediaItems = useMediaStore.getState().mediaItems; - const addedItem = currentMediaItems.find( - (item) => - item.name === processedItem.name && item.url === processedItem.url - ); - if (addedItem) { - useTimelineStore.getState().addMediaToNewTrack(addedItem); - } - } - } catch (error) { - // Show error if file processing fails - console.error("Error processing external files:", error); - toast.error("Failed to process dropped files"); - } finally { - setIsProcessing(false); - setProgress(0); - } - } - }; - - const dragProps = { - onDragEnter: handleDragEnter, - onDragOver: handleDragOver, - onDragLeave: handleDragLeave, - onDrop: handleDrop, - }; - - // Action handlers for toolbar - const handleSplitSelected = () => { - if (selectedElements.length === 0) { - toast.error("No elements selected"); - return; - } - let splitCount = 0; - selectedElements.forEach(({ trackId, elementId }) => { - const track = tracks.find((t) => t.id === trackId); - const element = track?.elements.find((c) => c.id === elementId); - if (element && track) { - const effectiveStart = element.startTime; - const effectiveEnd = - element.startTime + - (element.duration - element.trimStart - element.trimEnd); - - if (currentTime > effectiveStart && currentTime < effectiveEnd) { - const newElementId = splitElement(trackId, elementId, currentTime); - if (newElementId) splitCount++; - } - } - }); - if (splitCount === 0) { - toast.error("Playhead must be within selected elements to split"); - } - }; - - const handleDuplicateSelected = () => { - if (selectedElements.length === 0) { - toast.error("No elements selected"); - return; - } - const canDuplicate = selectedElements.length === 1; - if (!canDuplicate) return; - - const newSelections: { trackId: string; elementId: string }[] = []; - - selectedElements.forEach(({ trackId, elementId }) => { - const track = tracks.find((t) => t.id === trackId); - const element = track?.elements.find((el) => el.id === elementId); - - if (element) { - const newStartTime = - element.startTime + - (element.duration - element.trimStart - element.trimEnd) + - 0.1; - - // Create element without id (will be generated by store) - const { id, ...elementWithoutId } = element; - - addElementToTrack(trackId, { - ...elementWithoutId, - startTime: newStartTime, - }); - - // We can't predict the new id, so just clear selection for now - // TODO: addElementToTrack could return the new element id - } - }); - - clearSelectedElements(); - }; - - const handleFreezeSelected = () => { - toast.info("Freeze frame functionality coming soon!"); - }; - - const handleSplitAndKeepLeft = () => { - if (selectedElements.length !== 1) { - toast.error("Select exactly one element"); - return; - } - const { trackId, elementId } = selectedElements[0]; - const track = tracks.find((t) => t.id === trackId); - const element = track?.elements.find((c) => c.id === elementId); - if (!element) return; - const effectiveStart = element.startTime; - const effectiveEnd = - element.startTime + - (element.duration - element.trimStart - element.trimEnd); - if (currentTime <= effectiveStart || currentTime >= effectiveEnd) { - toast.error("Playhead must be within selected element"); - return; - } - splitAndKeepLeft(trackId, elementId, currentTime); - }; - - const handleSplitAndKeepRight = () => { - if (selectedElements.length !== 1) { - toast.error("Select exactly one element"); - return; - } - const { trackId, elementId } = selectedElements[0]; - const track = tracks.find((t) => t.id === trackId); - const element = track?.elements.find((c) => c.id === elementId); - if (!element) return; - const effectiveStart = element.startTime; - const effectiveEnd = - element.startTime + - (element.duration - element.trimStart - element.trimEnd); - if (currentTime <= effectiveStart || currentTime >= effectiveEnd) { - toast.error("Playhead must be within selected element"); - return; - } - splitAndKeepRight(trackId, elementId, currentTime); - }; - - const handleSeparateAudio = () => { - if (selectedElements.length !== 1) { - toast.error("Select exactly one media element to separate audio"); - return; - } - const { trackId, elementId } = selectedElements[0]; - const track = tracks.find((t) => t.id === trackId); - if (!track || track.type !== "media") { - toast.error("Select a media element to separate audio"); - return; - } - separateAudio(trackId, elementId); - }; - - const handleDeleteSelected = () => { - if (selectedElements.length === 0) { - toast.error("No elements selected"); - return; - } - selectedElements.forEach(({ trackId, elementId }) => { - removeElementFromTrack(trackId, elementId); - }); - clearSelectedElements(); - }; - - // --- Scroll synchronization 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; - const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector( - "[data-radix-scroll-area-viewport]" - ) as HTMLElement; - - if (!rulerViewport || !tracksViewport) return; - - // Horizontal scroll synchronization between ruler and tracks - const handleRulerScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastRulerSync.current < 16) return; - lastRulerSync.current = now; - isUpdatingRef.current = true; - tracksViewport.scrollLeft = rulerViewport.scrollLeft; - isUpdatingRef.current = false; - }; - const handleTracksScroll = () => { - const now = Date.now(); - 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) { - const handleTrackLabelsScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastVerticalSync.current < 16) - return; - lastVerticalSync.current = now; - isUpdatingRef.current = true; - tracksViewport.scrollTop = trackLabelsViewport.scrollTop; - isUpdatingRef.current = false; - }; - const handleTracksVerticalScroll = () => { - const now = Date.now(); - if (isUpdatingRef.current || now - lastVerticalSync.current < 16) - 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); - }; - }, []); - - // Add wheel event listeners with passive: false to allow preventDefault - useEffect(() => { - const timelineContainer = timelineRef.current; - if (!timelineContainer || !isInTimeline) return; - - const handleWheelCapture = (e: WheelEvent) => { - // Call the existing handleWheel function - handleWheel(e as any); - }; - - // Add wheel event listener with passive: false to allow preventDefault - timelineContainer.addEventListener("wheel", handleWheelCapture, { passive: false }); - - return () => { - timelineContainer.removeEventListener("wheel", handleWheelCapture); - }; - }, [handleWheel, isInTimeline]); + // Wheel event handling + useTimelineWheelHandler({ + timelineRef, + isInTimeline, + handleWheel, + }); return (
setIsInTimeline(false)} > {/* Toolbar */} -
-
- - - - - - - {isPlaying ? "Pause (Space)" : "Play (Space)"} - - -
-
- {currentTime.toFixed(1)}s / {duration.toFixed(1)}s -
- {tracks.length === 0 && ( - <> -
- - - - - - Add a test clip to try playback - - - - )} -
- - - - - Split element (Ctrl+S) - - - - - - Split and keep left (Ctrl+Q) - - - - - - Split and keep right (Ctrl+W) - - - - - - Separate audio (Ctrl+D) - - - - - - Duplicate element (Ctrl+D) - - - - - - Freeze frame (F) - - - - - - Delete element (Delete) - - -
-
- - - - - - Auto snapping - - -
-
+ {/* Timeline Container */} - - {/* Timeline Container with Grid Layout */}
-
-
0 ? `grid-rows-[20px_repeat(${tracks.length},minmax(0,max-content))]` : 'grid-rows-[20px_1fr]'}`}> - - {/* Top-Left Corner (Empty space above track labels) */} -
- - {/* Top Row (Sticky Ruler Header) */} -
-
- {(() => { - // 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 ( -
- - - {(() => { - 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); - })()} - -
- ); - }).filter(Boolean); - })()} -
-
- - {/* Track Rows */} - {tracks.map((track, index) => ( - - {/* Left Column (Sticky Track Labels) */} -
-
- -
- {track.muted && ( - - Muted - - )} -
- - {/* Scrollable Track Content */} - - -
{ - // If clicking empty area (not on a element), deselect all elements - if ( - !(e.target as HTMLElement).closest( - ".timeline-element" - ) - ) { - clearSelectedElements(); - } - }} - > - -
-
- - toggleTrackMute(track.id)} - > - {track.muted ? "Unmute Track" : "Mute Track"} - - - Track settings (soon) - - -
-
- ))} - {/* Add Track Button - spans full width */} -
addTrack('media')} - className="col-span-1 sticky left-0 w-full flex items-center border-b border-muted bg-card/[0.99] hover:bg-card/50 transition-colors cursor-pointer z-[89]" - style={{ height: `${getTrackHeight("media")}px` }} - > -
- -
-
-
-
- - {/* Overlay Components */} - - - - -
- - -
- ); -} - -function TrackIcon({ track }: { track: TimelineTrack }) { - return ( - <> - {track.type === "media" && ( -
); } diff --git a/apps/web/src/components/editor/timeline/index.ts b/apps/web/src/components/editor/timeline/index.ts new file mode 100644 index 00000000..984293ce --- /dev/null +++ b/apps/web/src/components/editor/timeline/index.ts @@ -0,0 +1,11 @@ +export { Timeline } from "../timeline"; +export { TimelineToolbar } from "./timeline-toolbar"; +export { TimelineContent } from "./timeline-content"; +export { TimelineRuler } from "./timeline-ruler"; +export { TimelineTracksArea } from "./timeline-tracks-area"; +export { TrackIcon } from "./track-icon"; +export { useTimelineDragHandlers } from "./timeline-drag-handlers"; +export { useTimelineActionHandlers } from "./timeline-action-handlers"; +export { useTimelineScrollSync } from "./timeline-scroll-sync"; +export { useTimelineContentClick } from "./timeline-content-click"; +export { useTimelineWheelHandler } from "./timeline-wheel-handler"; diff --git a/apps/web/src/components/editor/timeline/timeline-action-handlers.tsx b/apps/web/src/components/editor/timeline/timeline-action-handlers.tsx new file mode 100644 index 00000000..ca12d71a --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-action-handlers.tsx @@ -0,0 +1,162 @@ +import { toast } from "sonner"; +import { useTimelineStore } from "@/stores/timeline-store"; +import { usePlaybackStore } from "@/stores/playback-store"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; + +export function useTimelineActionHandlers() { + const { + tracks, + addTrack, + addElementToTrack, + removeElementFromTrack, + selectedElements, + clearSelectedElements, + splitElement, + splitAndKeepLeft, + splitAndKeepRight, + separateAudio, + } = useTimelineStore(); + const { currentTime } = usePlaybackStore(); + + // Action handlers for toolbar + const handleSplitSelected = () => { + if (selectedElements.length === 0) { + toast.error("No elements selected"); + return; + } + let splitCount = 0; + selectedElements.forEach(({ trackId, elementId }) => { + const track = tracks.find((t) => t.id === trackId); + const element = track?.elements.find((c) => c.id === elementId); + if (element && track) { + const effectiveStart = element.startTime; + const effectiveEnd = + element.startTime + + (element.duration - element.trimStart - element.trimEnd); + + if (currentTime > effectiveStart && currentTime < effectiveEnd) { + const newElementId = splitElement(trackId, elementId, currentTime); + if (newElementId) splitCount++; + } + } + }); + if (splitCount === 0) { + toast.error("Playhead must be within selected elements to split"); + } + }; + + const handleDuplicateSelected = () => { + if (selectedElements.length === 0) { + toast.error("No elements selected"); + return; + } + const canDuplicate = selectedElements.length === 1; + if (!canDuplicate) return; + + const newSelections: { trackId: string; elementId: string }[] = []; + + selectedElements.forEach(({ trackId, elementId }) => { + const track = tracks.find((t) => t.id === trackId); + const element = track?.elements.find((el) => el.id === elementId); + + if (element) { + const newStartTime = + element.startTime + + (element.duration - element.trimStart - element.trimEnd) + + 0.1; + + // Create element without id (will be generated by store) + const { id, ...elementWithoutId } = element; + + addElementToTrack(trackId, { + ...elementWithoutId, + startTime: newStartTime, + }); + + // We can't predict the new id, so just clear selection for now + // TODO: addElementToTrack could return the new element id + } + }); + + clearSelectedElements(); + }; + + const handleFreezeSelected = () => { + toast.info("Freeze frame functionality coming soon!"); + }; + + const handleSplitAndKeepLeft = () => { + if (selectedElements.length !== 1) { + toast.error("Select exactly one element"); + return; + } + const { trackId, elementId } = selectedElements[0]; + const track = tracks.find((t) => t.id === trackId); + const element = track?.elements.find((c) => c.id === elementId); + if (!element) return; + const effectiveStart = element.startTime; + const effectiveEnd = + element.startTime + + (element.duration - element.trimStart - element.trimEnd); + if (currentTime <= effectiveStart || currentTime >= effectiveEnd) { + toast.error("Playhead must be within selected element"); + return; + } + splitAndKeepLeft(trackId, elementId, currentTime); + }; + + const handleSplitAndKeepRight = () => { + if (selectedElements.length !== 1) { + toast.error("Select exactly one element"); + return; + } + const { trackId, elementId } = selectedElements[0]; + const track = tracks.find((t) => t.id === trackId); + const element = track?.elements.find((c) => c.id === elementId); + if (!element) return; + const effectiveStart = element.startTime; + const effectiveEnd = + element.startTime + + (element.duration - element.trimStart - element.trimEnd); + if (currentTime <= effectiveStart || currentTime >= effectiveEnd) { + toast.error("Playhead must be within selected element"); + return; + } + splitAndKeepRight(trackId, elementId, currentTime); + }; + + const handleSeparateAudio = () => { + if (selectedElements.length !== 1) { + toast.error("Select exactly one media element to separate audio"); + return; + } + const { trackId, elementId } = selectedElements[0]; + const track = tracks.find((t) => t.id === trackId); + if (!track || track.type !== "media") { + toast.error("Select a media element to separate audio"); + return; + } + separateAudio(trackId, elementId); + }; + + const handleDeleteSelected = () => { + if (selectedElements.length === 0) { + toast.error("No elements selected"); + return; + } + selectedElements.forEach(({ trackId, elementId }) => { + removeElementFromTrack(trackId, elementId); + }); + clearSelectedElements(); + }; + + return { + handleSplitSelected, + handleDuplicateSelected, + handleFreezeSelected, + handleSplitAndKeepLeft, + handleSplitAndKeepRight, + handleSeparateAudio, + handleDeleteSelected, + }; +} diff --git a/apps/web/src/components/editor/timeline/timeline-content-click.tsx b/apps/web/src/components/editor/timeline/timeline-content-click.tsx new file mode 100644 index 00000000..9b86effc --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-content-click.tsx @@ -0,0 +1,126 @@ +import { useCallback } from "react"; +import { useProjectStore } from "@/stores/project-store"; +import { TIMELINE_CONSTANTS, snapTimeToFrame } from "@/constants/timeline-constants"; + +export interface TimelineContentClickProps { + duration: number; + zoomLevel: number; + seek: (time: number) => void; + rulerScrollRef: React.RefObject; + tracksScrollRef: React.RefObject; + clearSelectedElements: () => void; + isSelecting: boolean; + justFinishedSelecting: boolean; + playheadRef: React.RefObject; +} + +export function useTimelineContentClick({ + duration, + zoomLevel, + seek, + rulerScrollRef, + tracksScrollRef, + clearSelectedElements, + isSelecting, + justFinishedSelecting, + playheadRef, +}: TimelineContentClickProps) { + const { activeProject } = useProjectStore(); + + // Timeline content click to seek handler + const handleTimelineContentClick = useCallback( + (e: React.MouseEvent) => { + console.log( + JSON.stringify({ + timelineClick: { + isSelecting, + justFinishedSelecting, + willReturn: isSelecting || justFinishedSelecting, + }, + }) + ); + + // Don't seek if this was a selection box operation + if (isSelecting || justFinishedSelecting) { + return; + } + + // Don't seek if clicking on timeline elements, but still deselect + if ((e.target as HTMLElement).closest(".timeline-element")) { + return; + } + + // Don't seek if clicking on playhead + if (playheadRef.current?.contains(e.target as Node)) { + return; + } + + // Don't seek if clicking on track labels + if ((e.target as HTMLElement).closest("[data-track-labels]")) { + clearSelectedElements(); + return; + } + + // Clear selected elements when clicking empty timeline area + console.log(JSON.stringify({ clearingSelectedElements: true })); + clearSelectedElements(); + + // Determine if we're clicking in ruler or tracks area + const isRulerClick = (e.target as HTMLElement).closest( + "[data-ruler-area]" + ); + + let mouseX: number; + let scrollLeft = 0; + + if (isRulerClick) { + // Calculate based on ruler position + const rulerContent = rulerScrollRef.current?.querySelector( + "[data-radix-scroll-area-viewport]" + ) as HTMLElement; + if (!rulerContent) return; + const rect = rulerContent.getBoundingClientRect(); + 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; + } + + const rawTime = Math.max( + 0, + Math.min( + duration, + (mouseX + scrollLeft) / + (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel) + ) + ); + + // Use frame snapping for timeline clicking + const projectFps = activeProject?.fps || 30; + const time = snapTimeToFrame(rawTime, projectFps); + + seek(time); + }, + [ + duration, + zoomLevel, + seek, + rulerScrollRef, + tracksScrollRef, + clearSelectedElements, + isSelecting, + justFinishedSelecting, + playheadRef, + activeProject?.fps, + ] + ); + + return { handleTimelineContentClick }; +} diff --git a/apps/web/src/components/editor/timeline/timeline-content.tsx b/apps/web/src/components/editor/timeline/timeline-content.tsx new file mode 100644 index 00000000..a1fd6906 --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-content.tsx @@ -0,0 +1,123 @@ +import { SelectionBox } from "../selection-box"; +import { TimelinePlayhead } from "./timeline-playhead"; +import { SnapIndicator } from "../snap-indicator"; +import { TimelineRuler } from "./timeline-ruler"; +import { TimelineTracksArea } from "./timeline-tracks-area"; +import type { TimelineTrack } from "@/types/timeline"; +import type { SnapPoint } from "@/hooks/use-timeline-snapping"; + +export interface TimelineContentProps { + dynamicTimelineWidth: number; + tracks: TimelineTrack[]; + duration: number; + zoomLevel: number; + currentTime: number; + seek: (time: number) => void; + rulerRef: React.RefObject; + rulerScrollRef: React.RefObject; + tracksScrollRef: React.RefObject; + playheadRef: React.RefObject; + trackLabelsRef: React.RefObject; + timelineRef: React.RefObject; + handleSelectionMouseDown: (e: React.MouseEvent) => void; + handleTimelineContentClick: (e: React.MouseEvent) => void; + handleSnapPointChange: (snapPoint: SnapPoint | null) => void; + clearSelectedElements: () => void; + selectionBox: { + startPos: { x: number; y: number } | null; + currentPos: { x: number; y: number } | null; + isActive: boolean; + } | null; + tracksContainerRef: React.RefObject; + currentSnapPoint: SnapPoint | null; + showSnapIndicator: boolean; +} + +export function TimelineContent({ + dynamicTimelineWidth, + tracks, + duration, + zoomLevel, + currentTime, + seek, + rulerRef, + rulerScrollRef, + tracksScrollRef, + playheadRef, + trackLabelsRef, + timelineRef, + handleSelectionMouseDown, + handleTimelineContentClick, + handleSnapPointChange, + clearSelectedElements, + selectionBox, + tracksContainerRef, + currentSnapPoint, + showSnapIndicator, +}: TimelineContentProps) { + return ( +
+
0 ? `grid-rows-[20px_repeat(${tracks.length},minmax(0,max-content))]` : 'grid-rows-[20px_1fr]'}`}> + + {/* Top-Left Corner (Empty space above track labels) */} +
+ + {/* Top Row (Sticky Ruler Header) */} + + + {/* Track Rows */} + +
+ + {/* Overlay Components */} + + + + + +
+ ); +} diff --git a/apps/web/src/components/editor/timeline/timeline-drag-handlers.tsx b/apps/web/src/components/editor/timeline/timeline-drag-handlers.tsx new file mode 100644 index 00000000..e8c3dd9f --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-drag-handlers.tsx @@ -0,0 +1,143 @@ +import { useState, useRef } from "react"; +import { toast } from "sonner"; +import { useTimelineStore } from "@/stores/timeline-store"; +import { useMediaStore } from "@/stores/media-store"; +import { useProjectStore } from "@/stores/project-store"; +import { processMediaFiles } from "@/lib/media-processing"; +import type { DragData } from "@/types/timeline"; + +export interface TimelineDragHandlersProps { + isDragOver: boolean; + setIsDragOver: (isDragOver: boolean) => void; + isProcessing: boolean; + setIsProcessing: (isProcessing: boolean) => void; + progress: number; + setProgress: (progress: number) => void; +} + +export function useTimelineDragHandlers({ + isDragOver, + setIsDragOver, + isProcessing, + setIsProcessing, + progress, + setProgress, +}: TimelineDragHandlersProps) { + const { mediaItems, addMediaItem } = useMediaStore(); + const { activeProject } = useProjectStore(); + const dragCounterRef = useRef(0); + + const handleDragEnter = (e: React.DragEvent) => { + // When something is dragged over the timeline, show overlay + e.preventDefault(); + // Don't show overlay for timeline elements - they're handled by tracks + if (e.dataTransfer.types.includes("application/x-timeline-element")) { + return; + } + dragCounterRef.current += 1; + if (!isDragOver) { + setIsDragOver(true); + } + }; + + const handleDragOver = (e: React.DragEvent) => { + e.preventDefault(); + }; + + const handleDragLeave = (e: React.DragEvent) => { + e.preventDefault(); + + // Don't update state for timeline elements - they're handled by tracks + if (e.dataTransfer.types.includes("application/x-timeline-element")) { + return; + } + + dragCounterRef.current -= 1; + if (dragCounterRef.current === 0) { + setIsDragOver(false); + } + }; + + const handleDrop = async (e: React.DragEvent) => { + // When media is dropped, add it as a new track/element + e.preventDefault(); + setIsDragOver(false); + dragCounterRef.current = 0; + + // Ignore timeline element drags - they're handled by track-specific handlers + const hasTimelineElement = e.dataTransfer.types.includes( + "application/x-timeline-element" + ); + if (hasTimelineElement) { + return; + } + + const itemData = e.dataTransfer.getData("application/x-media-item"); + if (itemData) { + try { + const dragData: DragData = JSON.parse(itemData); + + if (dragData.type === "text") { + // Always create new text track to avoid overlaps + useTimelineStore.getState().addTextToNewTrack(dragData); + } else { + // Handle media items + const mediaItem = mediaItems.find( + (item: any) => item.id === dragData.id + ); + if (!mediaItem) { + toast.error("Media item not found"); + return; + } + + useTimelineStore.getState().addMediaToNewTrack(mediaItem); + } + } catch (error) { + console.error("Error parsing dropped item data:", error); + toast.error("Failed to add item to timeline"); + } + } else if (e.dataTransfer.files?.length > 0) { + // Handle file drops by creating new tracks + if (!activeProject) { + toast.error("No active project"); + return; + } + + setIsProcessing(true); + setProgress(0); + try { + const processedItems = await processMediaFiles( + e.dataTransfer.files, + (p) => setProgress(p) + ); + for (const processedItem of processedItems) { + await addMediaItem(activeProject.id, processedItem); + const currentMediaItems = useMediaStore.getState().mediaItems; + const addedItem = currentMediaItems.find( + (item) => + item.name === processedItem.name && item.url === processedItem.url + ); + if (addedItem) { + useTimelineStore.getState().addMediaToNewTrack(addedItem); + } + } + } catch (error) { + // Show error if file processing fails + console.error("Error processing external files:", error); + toast.error("Failed to process dropped files"); + } finally { + setIsProcessing(false); + setProgress(0); + } + } + }; + + const dragProps = { + onDragEnter: handleDragEnter, + onDragOver: handleDragOver, + onDragLeave: handleDragLeave, + onDrop: handleDrop, + }; + + return { dragProps }; +} diff --git a/apps/web/src/components/editor/timeline-playhead.tsx b/apps/web/src/components/editor/timeline/timeline-playhead.tsx similarity index 93% rename from apps/web/src/components/editor/timeline-playhead.tsx rename to apps/web/src/components/editor/timeline/timeline-playhead.tsx index 29d0a270..7e64a890 100644 --- a/apps/web/src/components/editor/timeline-playhead.tsx +++ b/apps/web/src/components/editor/timeline/timeline-playhead.tsx @@ -66,7 +66,7 @@ export function TimelinePlayhead({ return (
void; + rulerRef: React.RefObject; + rulerScrollRef: React.RefObject; + tracksScrollRef: React.RefObject; + playheadRef: React.RefObject; + handleSelectionMouseDown: (e: React.MouseEvent) => void; + handleTimelineContentClick: (e: React.MouseEvent) => void; +} + +export function TimelineRuler({ + duration, + zoomLevel, + currentTime, + seek, + rulerRef, + rulerScrollRef, + tracksScrollRef, + playheadRef, + handleSelectionMouseDown, + handleTimelineContentClick, +}: TimelineRulerProps) { + // Timeline playhead ruler handlers + const { handleRulerMouseDown } = useTimelinePlayheadRuler({ + currentTime, + duration, + zoomLevel, + seek, + rulerRef, + rulerScrollRef, + tracksScrollRef, + playheadRef, + }); + + return ( +
+
+ {(() => { + // 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 ( +
+ + {(() => { + 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); + })()} + +
+ ); + }).filter(Boolean); + })()} +
+
+ ); +} diff --git a/apps/web/src/components/editor/timeline/timeline-scroll-sync.tsx b/apps/web/src/components/editor/timeline/timeline-scroll-sync.tsx new file mode 100644 index 00000000..2318f977 --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-scroll-sync.tsx @@ -0,0 +1,99 @@ +import { useEffect, useRef } from "react"; + +export interface TimelineScrollSyncProps { + rulerScrollRef: React.RefObject; + tracksScrollRef: React.RefObject; + trackLabelsScrollRef: React.RefObject; +} + +export function useTimelineScrollSync({ + rulerScrollRef, + tracksScrollRef, + trackLabelsScrollRef, +}: TimelineScrollSyncProps) { + const isUpdatingRef = useRef(false); + const lastRulerSync = useRef(0); + const lastTracksSync = useRef(0); + const lastVerticalSync = useRef(0); + + // --- Scroll synchronization 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; + const trackLabelsViewport = trackLabelsScrollRef.current?.querySelector( + "[data-radix-scroll-area-viewport]" + ) as HTMLElement; + + if (!rulerViewport || !tracksViewport) return; + + // Horizontal scroll synchronization between ruler and tracks + const handleRulerScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastRulerSync.current < 16) return; + lastRulerSync.current = now; + isUpdatingRef.current = true; + tracksViewport.scrollLeft = rulerViewport.scrollLeft; + isUpdatingRef.current = false; + }; + const handleTracksScroll = () => { + const now = Date.now(); + 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) { + const handleTrackLabelsScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastVerticalSync.current < 16) + return; + lastVerticalSync.current = now; + isUpdatingRef.current = true; + tracksViewport.scrollTop = trackLabelsViewport.scrollTop; + isUpdatingRef.current = false; + }; + const handleTracksVerticalScroll = () => { + const now = Date.now(); + if (isUpdatingRef.current || now - lastVerticalSync.current < 16) + 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); + }; + }, []); + + return null; +} diff --git a/apps/web/src/components/editor/timeline/timeline-toolbar.tsx b/apps/web/src/components/editor/timeline/timeline-toolbar.tsx new file mode 100644 index 00000000..b3061fe7 --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-toolbar.tsx @@ -0,0 +1,219 @@ +import { Button } from "../../ui/button"; +import { + Scissors, + ArrowLeftToLine, + ArrowRightToLine, + Trash2, + Snowflake, + Copy, + SplitSquareHorizontal, + Pause, + Play, + Lock, + LockOpen, +} from "lucide-react"; +import { + Tooltip, + TooltipContent, + TooltipTrigger, + TooltipProvider, +} from "../../ui/tooltip"; +import { useTimelineStore } from "@/stores/timeline-store"; +import { usePlaybackStore } from "@/stores/playback-store"; +import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants"; + +export interface TimelineToolbarProps { + handleSplitSelected: () => void; + handleSplitAndKeepLeft: () => void; + handleSplitAndKeepRight: () => void; + handleSeparateAudio: () => void; + handleDuplicateSelected: () => void; + handleFreezeSelected: () => void; + handleDeleteSelected: () => void; +} + +export function TimelineToolbar({ + handleSplitSelected, + handleSplitAndKeepLeft, + handleSplitAndKeepRight, + handleSeparateAudio, + handleDuplicateSelected, + handleFreezeSelected, + handleDeleteSelected, +}: TimelineToolbarProps) { + const { + tracks, + addTrack, + addElementToTrack, + snappingEnabled, + toggleSnapping, + } = useTimelineStore(); + const { currentTime, duration, isPlaying, toggle } = usePlaybackStore(); + + return ( +
+
+ + + + + + + {isPlaying ? "Pause (Space)" : "Play (Space)"} + + +
+
+ {currentTime.toFixed(1)}s / {duration.toFixed(1)}s +
+ {tracks.length === 0 && ( + <> +
+ + + + + + Add a test clip to try playback + + + + )} +
+ + + + + Split element (Ctrl+S) + + + + + + Split and keep left (Ctrl+Q) + + + + + + Split and keep right (Ctrl+W) + + + + + + Separate audio (Ctrl+D) + + + + + + Duplicate element (Ctrl+D) + + + + + + Freeze frame (F) + + + + + + Delete element (Delete) + + +
+
+ + + + + + Auto snapping + + +
+
+ ); +} diff --git a/apps/web/src/components/editor/timeline/timeline-tracks-area.tsx b/apps/web/src/components/editor/timeline/timeline-tracks-area.tsx new file mode 100644 index 00000000..293c8cc9 --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-tracks-area.tsx @@ -0,0 +1,99 @@ +import { Fragment } from "react"; +import { Plus } from "lucide-react"; +import { + ContextMenu, + ContextMenuContent, + ContextMenuItem, + ContextMenuTrigger, +} from "../../ui/context-menu"; +import { useTimelineStore } from "@/stores/timeline-store"; +import { TimelineTrackContent } from "../timeline-track"; +import { TrackIcon } from "./track-icon"; +import { getTrackHeight } from "@/constants/timeline-constants"; +import type { TimelineTrack } from "@/types/timeline"; +import type { SnapPoint } from "@/hooks/use-timeline-snapping"; + +export interface TimelineTracksAreaProps { + tracks: TimelineTrack[]; + zoomLevel: number; + handleSnapPointChange: (snapPoint: SnapPoint | null) => void; + clearSelectedElements: () => void; +} + +export function TimelineTracksArea({ + tracks, + zoomLevel, + handleSnapPointChange, + clearSelectedElements, +}: TimelineTracksAreaProps) { + const { addTrack, toggleTrackMute } = useTimelineStore(); + + return ( + <> + {/* Track Rows */} + {tracks.map((track, index) => ( + + {/* Left Column (Sticky Track Labels) */} +
+
+ +
+ {track.muted && ( + + Muted + + )} +
+ + {/* Scrollable Track Content */} + + +
{ + // If clicking empty area (not on a element), deselect all elements + if ( + !(e.target as HTMLElement).closest( + ".timeline-element" + ) + ) { + clearSelectedElements(); + } + }} + > + +
+
+ + toggleTrackMute(track.id)} + > + {track.muted ? "Unmute Track" : "Mute Track"} + + + Track settings (soon) + + +
+
+ ))} + {/* Add Track Button - spans full width */} +
addTrack('media')} + className="col-span-1 sticky left-0 w-full flex items-center border-b border-muted bg-card/[0.99] hover:bg-card/50 transition-colors cursor-pointer z-[89]" + style={{ height: `${getTrackHeight("media")}px` }} + > +
+ +
+
+ + ); +} diff --git a/apps/web/src/components/editor/timeline/timeline-wheel-handler.tsx b/apps/web/src/components/editor/timeline/timeline-wheel-handler.tsx new file mode 100644 index 00000000..430d65ae --- /dev/null +++ b/apps/web/src/components/editor/timeline/timeline-wheel-handler.tsx @@ -0,0 +1,33 @@ +import { useEffect } from "react"; + +export interface TimelineWheelHandlerProps { + timelineRef: React.RefObject; + isInTimeline: boolean; + handleWheel: (e: React.WheelEvent) => void; +} + +export function useTimelineWheelHandler({ + timelineRef, + isInTimeline, + handleWheel, +}: TimelineWheelHandlerProps) { + // Add wheel event listeners with passive: false to allow preventDefault + useEffect(() => { + const timelineContainer = timelineRef.current; + if (!timelineContainer || !isInTimeline) return; + + const handleWheelCapture = (e: WheelEvent) => { + // Call the existing handleWheel function + handleWheel(e as any); + }; + + // Add wheel event listener with passive: false to allow preventDefault + timelineContainer.addEventListener("wheel", handleWheelCapture, { passive: false }); + + return () => { + timelineContainer.removeEventListener("wheel", handleWheelCapture); + }; + }, [handleWheel, isInTimeline, timelineRef]); + + return null; +} diff --git a/apps/web/src/components/editor/timeline/track-icon.tsx b/apps/web/src/components/editor/timeline/track-icon.tsx new file mode 100644 index 00000000..e250a0d8 --- /dev/null +++ b/apps/web/src/components/editor/timeline/track-icon.tsx @@ -0,0 +1,18 @@ +import { Video, Music, TypeIcon } from "lucide-react"; +import type { TimelineTrack } from "@/types/timeline"; + +export function TrackIcon({ track }: { track: TimelineTrack }) { + return ( + <> + {track.type === "media" && ( +