fuck malware, fuck you

This commit is contained in:
Maze Winther
2026-01-18 05:44:25 +01:00
parent 0934db2aba
commit f18e9f4b4e
59 changed files with 1850 additions and 2100 deletions
@@ -1,4 +1,3 @@
{
"/editor/[project_id]/page": "app/editor/[project_id]/page.js",
"/projects/page": "app/projects/page.js"
"/editor/[project_id]/page": "app/editor/[project_id]/page.js"
}
+1 -5
View File
@@ -1,5 +1 @@
{
"/_app": "pages/_app.js",
"/_document": "pages/_document.js",
"/_error": "pages/_error.js"
}
{}
File diff suppressed because one or more lines are too long
@@ -60,15 +60,15 @@ function ProjectSettingsTabs() {
<div className="flex-1 p-5">
<BackgroundView />
</div>
<div className="bg-panel/85 sticky -bottom-0 flex flex-col backdrop-blur-lg">
{/* <div className="bg-panel/85 sticky -bottom-0 flex flex-col backdrop-blur-lg">
<Separator />
<Button className="text-muted-foreground hover:text-foreground/85 h-auto w-fit !bg-transparent p-5 py-4 text-xs shadow-none">
Custom background
<PlusIcon />
</Button>
</div>
</div> */}
{/* another ui, looks so beautiful I don't wanna remove it */}
{/* another ui */}
{/* <div className="flex flex-col justify-center items-center pb-5 sticky bottom-0">
<Button className="w-fit h-auto gap-1.5 px-3.5 py-1.5 bg-foreground hover:bg-foreground/85 text-background rounded-full">
<span className="text-sm">Custom</span>
@@ -1,17 +1,16 @@
"use client";
import { useTimelineStore } from "@/stores/timeline-store";
import { ScrollArea } from "../../ui/scroll-area";
import { AudioProperties } from "./audio-properties";
import { VideoProperties } from "./video-properties";
import { TextProperties } from "./text-properties";
import { SquareSlashIcon } from "lucide-react";
import { useEditor } from "@/hooks/use-editor";
import { useElementSelection } from "@/hooks/timeline/element/use-element-selection";
export function PropertiesPanel() {
const { selectedElements } = useTimelineStore();
const editor = useEditor();
const editor = useEditor();
const { selectedElements } = useElementSelection();
const elementsWithTracks = editor.timeline.getElementsWithTracks({
elements: selectedElements,
@@ -9,6 +9,7 @@ interface TimelineBookmarksRowProps {
bookmarksScrollRef: React.RefObject<HTMLDivElement>;
handleWheel: (e: React.WheelEvent) => void;
handleTimelineContentClick: (e: React.MouseEvent) => void;
handleRulerTrackingMouseDown: (e: React.MouseEvent) => void;
handleRulerMouseDown: (e: React.MouseEvent) => void;
}
@@ -18,6 +19,7 @@ export function TimelineBookmarksRow({
bookmarksScrollRef,
handleWheel,
handleTimelineContentClick,
handleRulerTrackingMouseDown,
handleRulerMouseDown,
}: TimelineBookmarksRowProps) {
const editor = useEditor();
@@ -28,6 +30,7 @@ export function TimelineBookmarksRow({
className="relative mt-0.5 h-4 flex-1 overflow-hidden"
onWheel={handleWheel}
onClick={handleTimelineContentClick}
onMouseDown={handleRulerTrackingMouseDown}
data-bookmarks-area
>
<ScrollArea className="scrollbar-hidden w-full" ref={bookmarksScrollRef}>
@@ -0,0 +1,21 @@
import { getDropLineY } from "@/lib/timeline/drop-utils";
import type { TimelineTrack, DropTarget } from "@/types/timeline";
interface DragLineProps {
dropTarget: DropTarget | null;
tracks: TimelineTrack[];
isVisible: boolean;
}
export function DragLine({ dropTarget, tracks, isVisible }: DragLineProps) {
if (!isVisible || !dropTarget) return null;
const y = getDropLineY({ dropTarget, tracks });
return (
<div
className="bg-primary pointer-events-none absolute left-0 right-0 z-50 h-0.5"
style={{ top: `${y}px` }}
/>
);
}
+152 -74
View File
@@ -1,7 +1,7 @@
"use client";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Eye, VolumeOff, Volume2 } from "lucide-react";
import { Eye, EyeOff, VolumeOff, Volume2, LucideIcon, EyeIcon, Trash2 } from "lucide-react";
import {
ContextMenu,
ContextMenuContent,
@@ -13,7 +13,7 @@ import { useState, useRef, useCallback } from "react";
import { TimelineTrackContent } from "./timeline-track";
import { TimelinePlayhead } from "./timeline-playhead";
import { SelectionBox } from "../selection-box";
import { useSelectionBox } from "@/hooks/use-selection-box";
import { useSelectionBox } from "@/hooks/timeline/use-selection-box";
import { SnapIndicator } from "./snap-indicator";
import { SnapPoint } from "@/hooks/timeline/use-timeline-snapping";
import type { TimelineTrack } from "@/types/timeline";
@@ -21,17 +21,18 @@ import {
TIMELINE_CONSTANTS,
TRACK_ICONS,
} from "@/constants/timeline-constants";
import { useElementInteraction } from "@/hooks/timeline/use-element-interaction";
import { useElementInteraction } from "@/hooks/timeline/element/use-element-interaction";
import {
getTrackHeight,
getCumulativeHeightBefore,
getTotalTracksHeight,
canTracktHaveAudio,
canTrackBeHidden,
isMainTrack,
} from "@/lib/timeline";
import { TimelineToolbar } from "./timeline-toolbar";
import { useScrollSync } from "@/hooks/use-scroll-sync";
import { useElementSelection } from "@/hooks/use-element-selection";
import { useScrollSync } from "@/hooks/timeline/use-scroll-sync";
import { useElementSelection } from "@/hooks/timeline/element/use-element-selection";
import { useTimelineInteractions } from "@/hooks/timeline/use-timeline-interactions";
import { useTimelineDragDrop } from "@/hooks/timeline/use-timeline-drag-drop";
import { TimelineRuler } from "./timeline-ruler";
@@ -39,17 +40,18 @@ import { TimelineBookmarksRow } from "./bookmarks";
import { useTimelineStore } from "@/stores/timeline-store";
import { useEditor } from "@/hooks/use-editor";
import { useTimelinePlayhead } from "@/hooks/timeline/use-timeline-playhead";
import { DragLine } from "./drag-line";
export function Timeline() {
const tracksContainerHeight = { min: 200, max: 800 };
const { snappingEnabled } = useTimelineStore();
const { clearSelection, setSelection } = useElementSelection();
const { clearElementSelection, setElementSelection } = useElementSelection();
const editor = useEditor();
const timeline = editor.timeline;
const tracks = timeline.getTracks();
const seek = (time: number) => editor.playback.seek({ time });
// Refs
// refs
const timelineRef = useRef<HTMLDivElement>(null);
const rulerRef = useRef<HTMLDivElement>(null);
const tracksContainerRef = useRef<HTMLDivElement>(null);
@@ -60,7 +62,7 @@ export function Timeline() {
const trackLabelsScrollRef = useRef<HTMLDivElement>(null);
const bookmarksScrollRef = useRef<HTMLDivElement>(null);
// State
// state
const [isInTimeline, setIsInTimeline] = useState(false);
const [currentSnapPoint, setCurrentSnapPoint] = useState<SnapPoint | null>(
null,
@@ -84,26 +86,20 @@ export function Timeline() {
zoomLevel,
timelineRef,
tracksContainerRef,
tracksScrollRef,
onSnapPointChange: handleSnapPointChange,
});
const timelineDuration = timeline.getTotalDuration() || 0;
const paddedDuration =
timelineDuration + TIMELINE_CONSTANTS.PLAYHEAD_LOOKAHEAD_SECONDS;
const dynamicTimelineWidth = Math.max(
paddedDuration * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel,
timelineRef.current?.clientWidth || 1000,
);
const { handleRulerMouseDown: handlePlayheadRulerMouseDown } =
useTimelinePlayhead({
zoomLevel,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
});
const { handleRulerMouseDown } = useTimelinePlayhead({
zoomLevel,
rulerRef,
rulerScrollRef,
tracksScrollRef,
playheadRef,
});
const { dragProps } = useTimelineDragDrop({
const { isDragOver, dropTarget, dragProps } = useTimelineDragDrop({
containerRef: tracksContainerRef,
zoomLevel,
});
@@ -115,26 +111,39 @@ export function Timeline() {
} = useSelectionBox({
containerRef: tracksContainerRef,
onSelectionComplete: (elements) => {
setSelection(elements);
setElementSelection({ elements });
},
tracksScrollRef,
zoomLevel,
});
const timelineDuration = timeline.getTotalDuration() || 0;
const paddedDuration =
timelineDuration + TIMELINE_CONSTANTS.PLAYHEAD_LOOKAHEAD_SECONDS;
const dynamicTimelineWidth = Math.max(
paddedDuration * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel,
timelineRef.current?.clientWidth || 1000,
);
const showSnapIndicator =
dragState.isDragging && snappingEnabled && currentSnapPoint !== null;
const { handleTimelineMouseDown, handleTimelineContentClick } =
useTimelineInteractions({
playheadRef,
rulerScrollRef,
tracksScrollRef,
zoomLevel,
duration: timeline.getTotalDuration(),
isSelecting,
clearSelectedElements: clearSelection,
seek,
});
const {
handleTracksMouseDown,
handleTracksClick,
handleRulerMouseDown,
handleRulerClick,
} = useTimelineInteractions({
playheadRef,
trackLabelsRef,
rulerScrollRef,
tracksScrollRef,
zoomLevel,
duration: timeline.getTotalDuration(),
isSelecting,
clearSelectedElements: clearElementSelection,
seek,
});
useScrollSync({
rulerScrollRef,
@@ -194,8 +203,9 @@ export function Timeline() {
rulerRef={rulerRef}
rulerScrollRef={rulerScrollRef}
handleWheel={handleWheel}
handleTimelineContentClick={handleTimelineContentClick}
handleRulerMouseDown={handleRulerMouseDown}
handleTimelineContentClick={handleRulerClick}
handleRulerTrackingMouseDown={handleRulerMouseDown}
handleRulerMouseDown={handlePlayheadRulerMouseDown}
/>
</div>
<div className="flex">
@@ -207,8 +217,9 @@ export function Timeline() {
dynamicTimelineWidth={dynamicTimelineWidth}
bookmarksScrollRef={bookmarksScrollRef}
handleWheel={handleWheel}
handleTimelineContentClick={handleTimelineContentClick}
handleRulerMouseDown={handleRulerMouseDown}
handleTimelineContentClick={handleRulerClick}
handleRulerTrackingMouseDown={handleRulerMouseDown}
handleRulerMouseDown={handlePlayheadRulerMouseDown}
/>
</div>
</div>
@@ -231,39 +242,41 @@ export function Timeline() {
}}
>
<div className="flex min-w-0 flex-1 items-center justify-end gap-2">
{canTracktHaveAudio(track) && (
<>
{track.muted ? (
<VolumeOff
className="text-destructive h-4 w-4 cursor-pointer"
onClick={() =>
timeline.toggleTrackMute({
trackId: track.id,
})
}
/>
) : (
<Volume2
className="text-muted-foreground h-4 w-4 cursor-pointer"
onClick={() =>
timeline.toggleTrackMute({
trackId: track.id,
})
}
/>
)}
</>
{/* Debug main track */}
{isMainTrack(track) && (
<div className="size-2 rounded-full bg-red-500" />
)}
{canTrackBeHidden(track) && (
<Eye
className="text-muted-foreground h-4 w-4 cursor-pointer"
{canTracktHaveAudio(track) && (
<TrackToggleIcon
isOff={track.muted}
icons={{
on: Volume2,
off: VolumeOff,
}}
onClick={() =>
timeline.toggleTrackHidden({
editor.timeline.toggleTrackMute({
trackId: track.id,
})
}
/>
)}
{canTrackBeHidden(track) && (
<TrackToggleIcon
isOff={track.hidden}
icons={{
on: Eye,
off: EyeOff,
}}
onClick={() =>
editor.timeline.toggleTrackVisibility({
trackId: track.id,
})
}
/>
)}
<TrackIcon track={track} />
</div>
</div>
@@ -282,10 +295,10 @@ export function Timeline() {
handleWheel(e);
}}
onMouseDown={(e) => {
handleTimelineMouseDown(e);
handleTracksMouseDown(e);
handleSelectionMouseDown(e);
}}
onClick={handleTimelineContentClick}
onClick={handleTracksClick}
ref={tracksContainerRef}
>
<SelectionBox
@@ -294,6 +307,12 @@ export function Timeline() {
containerRef={tracksContainerRef}
isActive={selectionBox?.isActive || false}
/>
<DragLine
dropTarget={dropTarget}
tracks={timeline.getTracks()}
isVisible={isDragOver}
/>
<ScrollArea className="h-full w-full" ref={tracksScrollRef}>
<div
className="relative flex-1"
@@ -337,7 +356,7 @@ export function Timeline() {
/>
</div>
</ContextMenuTrigger>
<ContextMenuContent className="z-200">
<ContextMenuContent className="z-200 w-40">
<ContextMenuItem
onClick={(e) => {
e.stopPropagation();
@@ -346,12 +365,42 @@ export function Timeline() {
});
}}
>
{canTracktHaveAudio(track) && track.muted
? "Unmute track"
: "Mute track"}
<Volume2 />
<span>
{canTracktHaveAudio(track) && track.muted
? "Unmute track"
: "Mute track"}
</span>
</ContextMenuItem>
<ContextMenuItem onClick={(e) => e.stopPropagation()}>
Track settings (soon)
<ContextMenuItem
onClick={(e) => {
e.stopPropagation();
timeline.toggleTrackVisibility({
trackId: track.id,
});
}}
>
<>
<EyeIcon />
<span>
{canTrackBeHidden(track) && track.hidden
? "Show track"
: "Hide track"}
</span>
</>
</ContextMenuItem>
<ContextMenuItem
onClick={(e) => {
e.stopPropagation();
timeline.removeTrack({
trackId: track.id,
});
}}
variant="destructive"
>
<Trash2 />
Delete track
</ContextMenuItem>
</ContextMenuContent>
</ContextMenu>
@@ -370,3 +419,32 @@ export function Timeline() {
function TrackIcon({ track }: { track: TimelineTrack }) {
return <>{TRACK_ICONS[track.type]}</>;
}
function TrackToggleIcon({
isOff,
icons,
onClick,
}: {
isOff: boolean;
icons: {
on: LucideIcon;
off: LucideIcon;
};
onClick: () => void;
}) {
return (
<>
{isOff ? (
<icons.off
className="text-destructive size-4 cursor-pointer"
onClick={onClick}
/>
) : (
<icons.on
className="text-muted-foreground size-4 cursor-pointer"
onClick={onClick}
/>
)}
</>
);
}
@@ -12,11 +12,11 @@ import {
VolumeX,
ArrowUpDown,
} from "lucide-react";
import { useEffect, useRef } from "react";
import { useEditor } from "@/hooks/use-editor";
import { useTimelineStore } from "@/stores/timeline-store";
import { useAssetsPanelStore } from "@/stores/assets-panel-store";
import AudioWaveform from "./audio-waveform";
import { useTimelineElementResize } from "@/hooks/timeline/use-element-resize";
import { useTimelineElementResize } from "@/hooks/timeline/element/use-element-resize";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import {
getTrackClasses,
@@ -40,6 +40,7 @@ import type {
import { MediaAsset } from "@/types/assets";
import { mediaSupportsAudio } from "@/lib/media-utils";
import { type TAction, invokeAction } from "@/lib/actions";
import { useElementSelection } from "@/hooks/timeline/element/use-element-selection";
interface TimelineElementProps {
element: TimelineElementType;
@@ -64,7 +65,8 @@ export function TimelineElement({
dragState,
}: TimelineElementProps) {
const editor = useEditor();
const { selectedElements } = useTimelineStore();
const lastDragStateRef = useRef(false);
const { selectedElements } = useElementSelection();
const { requestRevealMedia } = useAssetsPanelStore();
const mediaAssets = editor.media.getAssets();
@@ -77,7 +79,12 @@ export function TimelineElement({
const hasAudio = mediaSupportsAudio({ media: mediaAsset });
const { handleResizeStart } = useTimelineElementResize({
const {
handleResizeStart,
isResizing,
currentStartTime,
currentDuration,
} = useTimelineElementResize({
element,
track,
zoomLevel,
@@ -88,15 +95,16 @@ export function TimelineElement({
selected.elementId === element.id && selected.trackId === track.id,
);
const elementWidth =
element.duration * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel;
const isBeingDragged = dragState.elementId === element.id;
const elementStartTime =
isBeingDragged && dragState.isDragging
? dragState.currentTime
: element.startTime;
const elementLeft = elementStartTime * 50 * zoomLevel;
const displayedStartTime = isResizing ? currentStartTime : elementStartTime;
const displayedDuration = isResizing ? currentDuration : element.duration;
const elementWidth =
displayedDuration * TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel;
const elementLeft = displayedStartTime * 50 * zoomLevel;
const handleAction = ({
action,
@@ -122,9 +130,8 @@ export function TimelineElement({
<ContextMenu>
<ContextMenuTrigger asChild>
<div
className={`timeline-element absolute top-0 h-full select-none ${
isBeingDragged ? "z-50" : "z-10"
}`}
className={`timeline-element absolute top-0 h-full select-none ${isBeingDragged ? "z-30" : "z-10"
}`}
style={{ left: `${elementLeft}px`, width: `${elementWidth}px` }}
data-element-id={element.id}
data-track-id={track.id}
@@ -166,7 +173,7 @@ export function TimelineElement({
isMuted={isMuted}
selectedCount={selectedElements.length}
onClick={(event) =>
handleAction({ action: "toggle-mute-selected", event })
handleAction({ action: "toggle-elements-muted-selected", event })
}
/>
)}
@@ -177,7 +184,10 @@ export function TimelineElement({
isCurrentElementSelected={isCurrentElementSelected}
selectedCount={selectedElements.length}
onClick={(event) =>
handleAction({ action: "toggle-visibility-selected", event })
handleAction({
action: "toggle-elements-visibility-selected",
event,
})
}
/>
)}
@@ -260,7 +270,7 @@ function ElementInner({
{
type: track.type,
},
)} ${isBeingDragged ? "z-50" : "z-10"} ${canElementBeHidden(element) && element.hidden ? "opacity-50" : ""}`}
)} ${isBeingDragged ? "z-30" : "z-10"} ${canElementBeHidden(element) && element.hidden ? "opacity-50" : ""}`}
onClick={(e) => onElementClick(e, element)}
onMouseDown={(e) => onElementMouseDown(e, element)}
onContextMenu={(e) => onElementMouseDown(e, element)}
@@ -87,7 +87,7 @@ export function TimelinePlayhead({
return (
<div
ref={playheadRef}
className="pointer-events-auto absolute z-40"
className="pointer-events-auto absolute z-60"
style={{
left: `${leftPosition}px`,
top: 0,
@@ -11,6 +11,7 @@ interface TimelineRulerProps {
rulerScrollRef: React.RefObject<HTMLDivElement>;
handleWheel: (e: React.WheelEvent) => void;
handleTimelineContentClick: (e: React.MouseEvent) => void;
handleRulerTrackingMouseDown: (e: React.MouseEvent) => void;
handleRulerMouseDown: (e: React.MouseEvent) => void;
}
@@ -21,6 +22,7 @@ export function TimelineRuler({
rulerScrollRef,
handleWheel,
handleTimelineContentClick,
handleRulerTrackingMouseDown,
handleRulerMouseDown,
}: TimelineRulerProps) {
const editor = useEditor();
@@ -50,6 +52,7 @@ export function TimelineRuler({
className="relative h-4 flex-1 overflow-hidden"
onWheel={handleWheel}
onClick={handleTimelineContentClick}
onMouseDown={handleRulerTrackingMouseDown}
data-ruler-area
>
<ScrollArea className="scrollbar-hidden w-full" ref={rulerScrollRef}>
@@ -1,5 +1,4 @@
import { useEditor } from "@/hooks/use-editor";
import { useElementSelection } from "@/hooks/use-element-selection";
import {
TooltipProvider,
Tooltip,
@@ -37,6 +36,8 @@ import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { EditableTimecode } from "@/components/ui/editable-timecode";
import { ScenesView } from "../scenes-view";
import { type TAction, invokeAction } from "@/lib/actions";
import { cn } from "@/lib/utils";
import { useTimelineStore } from "@/stores/timeline-store";
export function TimelineToolbar({
zoomLevel,
@@ -49,13 +50,13 @@ export function TimelineToolbar({
const newZoomLevel =
direction === "in"
? Math.min(
TIMELINE_CONSTANTS.ZOOM_MAX,
zoomLevel + TIMELINE_CONSTANTS.ZOOM_STEP,
)
TIMELINE_CONSTANTS.ZOOM_MAX,
zoomLevel + TIMELINE_CONSTANTS.ZOOM_STEP,
)
: Math.max(
TIMELINE_CONSTANTS.ZOOM_MIN,
zoomLevel - TIMELINE_CONSTANTS.ZOOM_STEP,
);
TIMELINE_CONSTANTS.ZOOM_MIN,
zoomLevel - TIMELINE_CONSTANTS.ZOOM_STEP,
);
setZoomLevel({ zoom: newZoomLevel });
};
@@ -75,13 +76,9 @@ export function TimelineToolbar({
}
function ToolbarLeftSection() {
const { selectedElements } = useElementSelection();
const editor = useEditor();
const currentTime = editor.playback.getCurrentTime();
const duration = editor.timeline.getTotalDuration();
const isPlaying = editor.playback.getIsPlaying();
const activeProject = editor.project.getActive();
const currentBookmarked = editor.scenes.isBookmarked({ time: currentTime });
const handleAction = ({
@@ -114,11 +111,7 @@ function ToolbarLeftSection() {
<div className="bg-border mx-2 h-10 w-px" />
<TimeDisplay
currentTime={currentTime}
duration={duration}
fps={activeProject.settings.fps}
/>
<TimeDisplay />
<div className="bg-border mx-1 h-10 w-px" />
@@ -148,9 +141,9 @@ function ToolbarLeftSection() {
<ToolbarButton
icon={<SplitSquareHorizontal />}
tooltip="Coming soon" /* Separate audio */
tooltip="Coming soon" /* separate audio */
disabled={true}
onClick={({ event }) => {}}
onClick={({ event }) => { }}
/>
<ToolbarButton
@@ -163,9 +156,9 @@ function ToolbarLeftSection() {
<ToolbarButton
icon={<Snowflake />}
tooltip="Coming soon" /* Freeze frame */
tooltip="Coming soon" /* freeze frame */
disabled={true}
onClick={({ event }) => {}}
onClick={({ event }) => { }}
/>
<ToolbarButton
@@ -196,31 +189,26 @@ function ToolbarLeftSection() {
);
}
function TimeDisplay({
currentTime,
duration,
fps,
}: {
currentTime: number;
duration: number;
fps: number;
}) {
function TimeDisplay() {
const editor = useEditor();
const currentTime = editor.playback.getCurrentTime();
const totalDuration = editor.timeline.getTotalDuration();
const fps = editor.project.getActive().settings.fps;
return (
<div className="flex flex-row items-center justify-center px-2">
<EditableTimecode
time={currentTime}
duration={duration}
duration={totalDuration}
format="HH:MM:SS:FF"
fps={fps}
onTimeChange={(time) => editor.playback.seek({ time })}
onTimeChange={({ time }) => editor.playback.seek({ time })}
className="text-center"
/>
<div className="text-muted-foreground px-2 font-mono text-xs">/</div>
<div className="text-muted-foreground text-center font-mono text-xs">
{formatTimeCode({
timeInSeconds: duration,
timeInSeconds: totalDuration,
format: "HH:MM:SS:FF",
fps,
})}
@@ -242,7 +230,7 @@ function SceneSelector() {
<ScenesView>
<SplitButtonRight
disabled={scenesCount === 1}
onClick={() => {}}
onClick={() => { }}
type="button"
>
<LayersIcon className="size-4" />
@@ -262,19 +250,21 @@ function ToolbarRightSection({
onZoomChange: (zoom: number) => void;
onZoom: (options: { direction: "in" | "out" }) => void;
}) {
const { snappingEnabled, rippleEditingEnabled, toggleSnapping, toggleRippleEditing } = useTimelineStore();
return (
<div className="flex items-center gap-1">
<TooltipProvider delayDuration={500}>
<ToolbarButton
icon={<Magnet />}
icon={<Magnet className={cn(snappingEnabled ? "text-primary" : "")} />}
tooltip="Auto snapping"
onClick={() => {}}
onClick={() => toggleSnapping()}
/>
<ToolbarButton
icon={<Link />}
icon={<Link className={cn(rippleEditingEnabled ? "text-primary" : "")} />}
tooltip="Ripple editing"
onClick={() => {}}
onClick={() => toggleRippleEditing()}
/>
</TooltipProvider>
@@ -1,11 +1,11 @@
"use client";
import { useElementSelection } from "@/hooks/use-element-selection";
import { useElementSelection } from "@/hooks/timeline/element/use-element-selection";
import { TimelineElement } from "./timeline-element";
import { TimelineTrack } from "@/types/timeline";
import type { TimelineElement as TimelineElementType } from "@/types/timeline";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { useEdgeAutoScroll } from "@/hooks/use-edge-auto-scroll";
import { useEdgeAutoScroll } from "@/hooks/timeline/use-edge-auto-scroll";
import { ElementDragState } from "@/types/timeline";
import { useEditor } from "@/hooks/use-editor";
@@ -39,7 +39,7 @@ export function TimelineTrackContent({
onElementClick,
}: TimelineTrackContentProps) {
const editor = useEditor();
const { isSelected, clearSelection } = useElementSelection();
const { isElementSelected, clearElementSelection } = useElementSelection();
const duration = editor.timeline.getTotalDuration();
@@ -52,14 +52,17 @@ export function TimelineTrackContent({
});
return (
<div className="hover:bg-muted/20 size-full" onClick={clearSelection}>
<div
className="hover:bg-muted/20 size-full"
onClick={clearElementSelection}
>
<div className="track-elements-container relative h-full min-w-full">
{track.elements.length === 0 ? (
<div className="text-muted-foreground border-muted/30 flex size-full items-center justify-center rounded-sm border-2 border-dashed text-xs" />
) : (
<>
{track.elements.map((element) => {
const isElementSelected = isSelected({
const isSelected = isElementSelected({
trackId: track.id,
elementId: element.id,
});
@@ -70,7 +73,7 @@ export function TimelineTrackContent({
element={element}
track={track}
zoomLevel={zoomLevel}
isSelected={isElementSelected}
isSelected={isSelected}
onElementMouseDown={(event, element) =>
onElementMouseDown({ event, element, track })
}
@@ -8,7 +8,7 @@ import {
useKeybindingsListener,
useKeybindingDisabler,
} from "@/hooks/use-keybindings";
import { useEditorActions } from "@/hooks/use-editor-actions";
import { useEditorActions } from "@/hooks/actions/use-editor-actions";
interface EditorProviderProps {
projectId: string;
@@ -10,7 +10,7 @@ interface EditableTimecodeProps {
duration: number;
format?: TTimeCode;
fps: number;
onTimeChange?: (time: number) => void;
onTimeChange?: ({ time }: { time: number }) => void;
className?: string;
disabled?: boolean;
}
@@ -54,43 +54,57 @@ export function EditableTimecode({
return;
}
// Clamp time to valid range
const clampedTime = Math.max(
0,
duration ? Math.min(duration, parsedTime) : parsedTime,
);
onTimeChange?.(clampedTime);
onTimeChange?.({ time: clampedTime });
setIsEditing(false);
setInputValue("");
setHasError(false);
enterPressedRef.current = false;
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
e.preventDefault();
const handleKeyDown = ({
key,
preventDefault,
}: React.KeyboardEvent<HTMLInputElement>) => {
if (key === "Enter") {
preventDefault();
enterPressedRef.current = true;
applyEdit();
} else if (e.key === "Escape") {
e.preventDefault();
} else if (key === "Escape") {
preventDefault();
cancelEditing();
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
const handleInputChange = ({
target,
}: React.ChangeEvent<HTMLInputElement>) => {
setInputValue(target.value);
setHasError(false);
};
const handleBlur = () => {
// Only apply edit if Enter wasn't pressed (to avoid double processing)
if (!enterPressedRef.current && isEditing) {
applyEdit();
}
};
// Focus input when entering edit mode
const handleDisplayKeyDown = ({
key,
preventDefault,
}: React.KeyboardEvent<HTMLSpanElement>) => {
if (disabled) return;
if (key === "Enter" || key === " ") {
preventDefault();
startEditing();
}
};
useEffect(() => {
if (isEditing && inputRef.current) {
inputRef.current.focus();
@@ -123,6 +137,9 @@ export function EditableTimecode({
return (
<span
onClick={startEditing}
onKeyDown={handleDisplayKeyDown}
role="button"
tabIndex={disabled ? -1 : 0}
className={cn(
"text-primary cursor-pointer font-mono text-xs tabular-nums",
"hover:bg-muted/50 -mx-1 px-1 transition-colors hover:rounded",
-763
View File
@@ -1,763 +0,0 @@
"use client";
import * as React from "react";
import { Slot as SlotPrimitive } from "radix-ui";
import { VariantProps, cva } from "class-variance-authority";
import { PanelLeft } from "lucide-react";
import { useIsMobile } from "../../hooks/use-mobile";
import { cn } from "../../lib/utils";
import { Button } from "./button";
import { Input } from "./input";
import { Separator } from "./separator";
import { Sheet, SheetContent, SheetTitle } from "./sheet";
import { Skeleton } from "./skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "./tooltip";
const SIDEBAR_COOKIE_NAME = "sidebar:state";
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = "16rem";
const SIDEBAR_WIDTH_MOBILE = "18rem";
const SIDEBAR_WIDTH_ICON = "3rem";
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
type SidebarContext = {
state: "expanded" | "collapsed";
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContext | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
}
const SidebarProvider = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
>(
(
{
defaultOpen = true,
open: openProp,
onOpenChange: setOpenProp,
className,
style,
children,
...props
},
ref
) => {
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState);
} else {
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open]
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile
? setOpenMobile((open) => !open)
: setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault();
toggleSidebar();
}
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed";
const contextValue = React.useMemo<SidebarContext>(
() => ({
state,
open,
setOpen,
isMobile,
openMobile,
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
);
return (
<SidebarContext.Provider value={contextValue}>
<TooltipProvider delayDuration={0}>
<div
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper flex min-h-svh w-full has-data-[variant=inset]:bg-sidebar",
className
)}
ref={ref}
{...props}
>
{children}
</div>
</TooltipProvider>
</SidebarContext.Provider>
);
}
);
SidebarProvider.displayName = "SidebarProvider";
const Sidebar = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
side?: "left" | "right";
variant?: "sidebar" | "floating" | "inset";
collapsible?: "offcanvas" | "icon" | "none";
}
>(
(
{
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
className,
children,
...props
},
ref
) => {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
return (
<div
className={cn(
"flex h-full w-(--sidebar-width) flex-col bg-sidebar text-sidebar-foreground",
className
)}
ref={ref}
{...props}
>
{children}
</div>
);
}
if (isMobile) {
return (
<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
<SheetContent
data-sidebar="sidebar"
data-mobile="true"
className="w-(--sidebar-width) bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
>
<SheetTitle className="sr-only">Navigation Menu</SheetTitle>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
);
}
return (
<div
ref={ref}
className="group peer hidden md:block text-sidebar-foreground"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-variant={variant}
data-side={side}
>
{/* This is what handles the sidebar gap on desktop */}
<div
className={cn(
"duration-200 relative h-full w-(--sidebar-width) bg-transparent transition-[width] ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
)}
/>
<div
className={cn(
"duration-200 fixed h-[calc(100vh-4rem)] top-16 z-10 hidden w-(--sidebar-width) transition-[left,right,width] ease-linear md:flex",
side === "left"
? "left-0 border-r group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 border-l group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
className
)}
{...props}
>
<div
data-sidebar="sidebar"
className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow-sm"
>
{children}
</div>
</div>
</div>
);
}
);
Sidebar.displayName = "Sidebar";
const SidebarTrigger = React.forwardRef<
React.ElementRef<typeof Button>,
React.ComponentProps<typeof Button>
>(({ className, onClick, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<Button
ref={ref}
data-sidebar="trigger"
variant="text"
size="icon"
className={cn("h-8 w-8", className)}
onClick={(event) => {
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeft />
<span className="sr-only">Toggle Sidebar</span>
</Button>
);
});
SidebarTrigger.displayName = "SidebarTrigger";
const SidebarRail = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button">
>(({ className, ...props }, ref) => {
const { toggleSidebar } = useSidebar();
return (
<button
ref={ref}
data-sidebar="rail"
aria-label="Toggle Sidebar"
tabIndex={-1}
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full hover:group-data-[collapsible=offcanvas]:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
)}
{...props}
/>
);
});
SidebarRail.displayName = "SidebarRail";
const SidebarInset = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"main">
>(({ className, ...props }, ref) => {
return (
<main
ref={ref}
className={cn(
"relative flex min-h-svh flex-1 flex-col bg-background",
"peer-data-[variant=inset]:min-h-[calc(100svh-(--spacing(4)))] md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm",
className
)}
{...props}
/>
);
});
SidebarInset.displayName = "SidebarInset";
const SidebarInput = React.forwardRef<
React.ElementRef<typeof Input>,
React.ComponentProps<typeof Input>
>(({ className, ...props }, ref) => {
return (
<Input
ref={ref}
data-sidebar="input"
className={cn(
"h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
className
)}
{...props}
/>
);
});
SidebarInput.displayName = "SidebarInput";
const SidebarHeader = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
});
SidebarHeader.displayName = "SidebarHeader";
const SidebarFooter = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
{...props}
/>
);
});
SidebarFooter.displayName = "SidebarFooter";
const SidebarSeparator = React.forwardRef<
React.ElementRef<typeof Separator>,
React.ComponentProps<typeof Separator>
>(({ className, ...props }, ref) => {
return (
<Separator
ref={ref}
data-sidebar="separator"
className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
});
SidebarSeparator.displayName = "SidebarSeparator";
const SidebarContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
)}
{...props}
/>
);
});
SidebarContent.displayName = "SidebarContent";
const SidebarGroup = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => {
return (
<div
ref={ref}
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
{...props}
/>
);
});
SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "div";
return (
<Comp
ref={ref as any}
data-sidebar="group-label"
className={cn(
"duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-hidden ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
{...props}
/>
);
});
SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarGroupAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & { asChild?: boolean }
>(({ className, asChild = false, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "button";
return (
<Comp
ref={ref as any}
data-sidebar="group-action"
className={cn(
"absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
);
});
SidebarGroupAction.displayName = "SidebarGroupAction";
const SidebarGroupContent = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
{...props}
/>
));
SidebarGroupContent.displayName = "SidebarGroupContent";
const SidebarMenu = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
{...props}
/>
));
SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ className, ...props }, ref) => (
<li
ref={ref}
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
{...props}
/>
));
SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
outline:
"bg-background shadow-[0_0_0_1px_var(--sidebar-border)] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_var(--sidebar-accent)]",
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
);
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>
>(
(
{
asChild = false,
isActive = false,
variant = "default",
size = "default",
tooltip,
className,
...props
},
ref
) => {
const Comp = asChild ? SlotPrimitive.Slot : "button";
const { isMobile, state } = useSidebar();
const button = (
<Comp
ref={ref as any}
data-sidebar="menu-button"
data-size={size}
data-active={isActive}
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
);
if (!tooltip) {
return button;
}
if (typeof tooltip === "string") {
tooltip = {
children: tooltip,
};
}
return (
<Tooltip>
<TooltipTrigger asChild>{button}</TooltipTrigger>
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
{...tooltip}
/>
</Tooltip>
);
}
);
SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarMenuAction = React.forwardRef<
HTMLButtonElement,
React.ComponentProps<"button"> & {
asChild?: boolean;
showOnHover?: boolean;
}
>(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "button";
return (
<Comp
ref={ref as any}
data-sidebar="menu-action"
className={cn(
"absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-hidden ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className
)}
{...props}
/>
);
});
SidebarMenuAction.displayName = "SidebarMenuAction";
const SidebarMenuBadge = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
<div
ref={ref}
data-sidebar="menu-badge"
className={cn(
"absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground select-none pointer-events-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
));
SidebarMenuBadge.displayName = "SidebarMenuBadge";
const SidebarMenuSkeleton = React.forwardRef<
HTMLDivElement,
React.ComponentProps<"div"> & {
showIcon?: boolean;
}
>(({ className, showIcon = false, ...props }, ref) => {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
ref={ref}
data-sidebar="menu-skeleton"
className={cn("rounded-md h-8 flex gap-2 px-2 items-center", className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
<Skeleton
className="h-4 flex-1 max-w-(--skeleton-width)"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
} as React.CSSProperties
}
/>
</div>
);
});
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton";
const SidebarMenuSub = React.forwardRef<
HTMLUListElement,
React.ComponentProps<"ul">
>(({ className, ...props }, ref) => (
<ul
ref={ref}
data-sidebar="menu-sub"
className={cn(
"mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
));
SidebarMenuSub.displayName = "SidebarMenuSub";
const SidebarMenuSubItem = React.forwardRef<
HTMLLIElement,
React.ComponentProps<"li">
>(({ ...props }, ref) => <li ref={ref} {...props} />);
SidebarMenuSubItem.displayName = "SidebarMenuSubItem";
const SidebarMenuSubButton = React.forwardRef<
HTMLAnchorElement,
React.ComponentProps<"a"> & {
asChild?: boolean;
size?: "sm" | "md";
isActive?: boolean;
}
>(({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
const Comp = asChild ? SlotPrimitive.Slot : "a";
return (
<Comp
ref={ref as any}
data-sidebar="menu-sub-button"
data-size={size}
data-active={isActive}
className={cn(
"flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-hidden ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
)}
{...props}
/>
);
});
SidebarMenuSubButton.displayName = "SidebarMenuSubButton";
export {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupAction,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarInput,
SidebarInset,
SidebarMenu,
SidebarMenuAction,
SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSkeleton,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarProvider,
SidebarRail,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};
-31
View File
@@ -1,31 +0,0 @@
"use client";
import { useToast } from "../../hooks/use-toast";
import {
Toast,
ToastClose,
ToastDescription,
ToastProvider,
ToastTitle,
ToastViewport,
} from "./toast";
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(({ id, title, description, action, ...props }) => (
<Toast key={id} {...props}>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && <ToastDescription>{description}</ToastDescription>}
</div>
{action}
<ToastClose />
</Toast>
))}
<ToastViewport />
</ToastProvider>
);
}
+4
View File
@@ -5,6 +5,7 @@ import { ProjectManager } from "./managers/project-manager";
import { MediaManager } from "./managers/media-manager";
import { RendererManager } from "./managers/renderer-manager";
import { CommandManager } from "./managers/commands";
import { SaveManager } from "./managers/save-manager";
import { buildScene } from "@/services/renderer/scene-builder";
import { SceneExporter } from "@/services/renderer/scene-exporter";
import type { ExportOptions } from "@/types/export";
@@ -19,6 +20,7 @@ export class EditorCore {
public readonly project: ProjectManager;
public readonly media: MediaManager;
public readonly renderer: RendererManager;
public readonly save: SaveManager;
private constructor() {
this.command = new CommandManager();
@@ -28,6 +30,8 @@ export class EditorCore {
this.project = new ProjectManager(this);
this.media = new MediaManager(this);
this.renderer = new RendererManager(this);
this.save = new SaveManager(this);
this.save.start();
}
static getInstance(): EditorCore {
+15 -24
View File
@@ -8,6 +8,7 @@ import type { TimelineElement } from "@/types/timeline";
import { storageService } from "@/lib/storage/storage-service";
import { toast } from "sonner";
import { generateUUID } from "@/lib/utils";
import { UpdateProjectSettingsCommand } from "@/lib/commands/project";
import {
DEFAULT_FPS,
DEFAULT_CANVAS_SIZE,
@@ -130,6 +131,7 @@ export class ProjectManager {
this.notify();
}
this.editor.save.pause();
await this.ensureStorageMigrations();
this.editor.media.clearAllAssets();
this.editor.scenes.clearScenes();
@@ -159,6 +161,7 @@ export class ProjectManager {
} finally {
this.isLoading = false;
this.notify();
this.editor.save.resume();
}
}
@@ -339,27 +342,20 @@ export class ProjectManager {
async updateSettings({
settings,
pushHistory = true,
}: {
settings: Partial<TProjectSettings>;
pushHistory?: boolean;
}): Promise<void> {
if (!this.active) return;
const updatedProject: TProject = {
...this.active,
settings: { ...this.active.settings, ...settings },
metadata: { ...this.active.metadata, updatedAt: new Date() },
};
try {
await storageService.saveProject({ project: updatedProject });
this.active = updatedProject;
this.notify();
} catch (error) {
console.error("Failed to update settings:", error);
toast.error("Failed to update settings", {
description: "Please try again",
});
const command = new UpdateProjectSettingsCommand(settings);
if (pushHistory) {
this.editor.command.execute({ command });
return;
}
command.execute();
}
async updateThumbnail({ thumbnail }: { thumbnail: string }): Promise<void> {
@@ -369,15 +365,10 @@ export class ProjectManager {
...this.active,
metadata: { ...this.active.metadata, thumbnail, updatedAt: new Date() },
};
try {
await storageService.saveProject({ project: updatedProject });
this.active = updatedProject;
this.notify();
this.updateMetadata(updatedProject);
} catch (error) {
console.error("Failed to update thumbnail:", error);
}
this.active = updatedProject;
this.notify();
this.updateMetadata(updatedProject);
this.editor.save.markDirty();
}
async prepareExit(): Promise<void> {
+105
View File
@@ -0,0 +1,105 @@
import type { EditorCore } from "@/core";
type SaveManagerOptions = {
debounceMs?: number;
};
export class SaveManager {
private debounceMs: number;
private isPaused = false;
private isSaving = false;
private hasPendingSave = false;
private saveTimer: ReturnType<typeof setTimeout> | null = null;
private unsubscribeHandlers: Array<() => void> = [];
constructor(
private editor: EditorCore,
{ debounceMs = 800 }: SaveManagerOptions = {},
) {
this.debounceMs = debounceMs;
}
start(): void {
if (this.unsubscribeHandlers.length > 0) return;
this.unsubscribeHandlers = [
this.editor.scenes.subscribe(() => {
this.markDirty();
}),
this.editor.timeline.subscribe(() => {
this.markDirty();
}),
];
}
stop(): void {
for (const unsubscribe of this.unsubscribeHandlers) {
unsubscribe();
}
this.unsubscribeHandlers = [];
this.clearTimer();
}
pause(): void {
this.isPaused = true;
}
resume(): void {
this.isPaused = false;
if (this.hasPendingSave) {
this.queueSave();
}
}
markDirty(
{ force = false }: { force?: boolean } = {},
): void {
if (this.isPaused && !force) return;
this.hasPendingSave = true;
this.queueSave();
}
async flush(): Promise<void> {
this.hasPendingSave = true;
await this.saveNow();
}
private queueSave(): void {
if (this.isSaving) return;
if (this.saveTimer) {
clearTimeout(this.saveTimer);
}
this.saveTimer = setTimeout(() => {
void this.saveNow();
}, this.debounceMs);
}
private async saveNow(): Promise<void> {
if (this.isSaving) return;
if (!this.hasPendingSave) return;
const activeProject = this.editor.project.getActiveOrNull();
if (!activeProject) return;
if (this.editor.project.getIsLoading()) return;
if (this.editor.project.getMigrationState().isMigrating) return;
this.isSaving = true;
this.hasPendingSave = false;
this.clearTimer();
try {
await this.editor.project.saveCurrentProject();
} finally {
this.isSaving = false;
if (this.hasPendingSave) {
this.queueSave();
}
}
}
private clearTimer(): void {
if (!this.saveTimer) return;
clearTimeout(this.saveTimer);
this.saveTimer = null;
}
}
+32 -165
View File
@@ -1,23 +1,24 @@
import type { EditorCore } from "@/core";
import type { TScene } from "@/types/timeline";
import type { TimelineTrack, TScene } from "@/types/timeline";
import { storageService } from "@/lib/storage/storage-service";
import { toast } from "sonner";
import {
updateSceneInArray,
getMainScene,
ensureMainScene,
buildDefaultScene,
canDeleteScene,
getFallbackSceneAfterDelete,
findCurrentScene,
} from "@/lib/scene-utils";
import {
getFrameTime,
toggleBookmarkInArray,
removeBookmarkFromArray,
isBookmarkAtTime,
} from "@/lib/timeline/bookmark-utils";
import { ensureMainTrack } from "@/lib/timeline/track-utils";
import {
CreateSceneCommand,
DeleteSceneCommand,
RemoveBookmarkCommand,
RenameSceneCommand,
ToggleBookmarkCommand,
} from "@/lib/commands/scene";
export class ScenesManager {
private active: TScene | null = null;
@@ -33,16 +34,13 @@ export class ScenesManager {
name: string;
isMain: boolean;
}): Promise<string> {
const newScene = buildDefaultScene({ name, isMain });
const updatedScenes = [...this.list, newScene];
try {
await this.updateProjectWithScenes({ updatedScenes });
return newScene.id;
} catch (error) {
console.error("Failed to create scene:", error);
throw error;
if (!this.editor.project.getActive()) {
throw new Error("No active project");
}
const command = new CreateSceneCommand(name, isMain);
this.editor.command.execute({ command });
return command.getSceneId();
}
async deleteScene({ sceneId }: { sceneId: string }): Promise<void> {
@@ -57,23 +55,12 @@ export class ScenesManager {
throw new Error(reason);
}
const updatedScenes = this.list.filter((s) => s.id !== sceneId);
const newCurrentScene = getFallbackSceneAfterDelete({
scenes: updatedScenes,
deletedSceneId: sceneId,
currentSceneId: this.active?.id || null,
});
try {
await this.updateProjectWithScenes({
updatedScenes,
updatedSceneId: newCurrentScene?.id,
});
} catch (error) {
console.error("Failed to delete scene:", error);
throw error;
if (!this.editor.project.getActive()) {
throw new Error("No active project");
}
const command = new DeleteSceneCommand(sceneId);
this.editor.command.execute({ command });
}
async renameScene({
@@ -83,21 +70,12 @@ export class ScenesManager {
sceneId: string;
name: string;
}): Promise<void> {
const updatedScenes = updateSceneInArray({
scenes: this.list,
sceneId,
updates: { name, updatedAt: new Date() },
});
try {
await this.updateProjectWithScenes({
updatedScenes,
updatedSceneId: sceneId,
});
} catch (error) {
console.error("Failed to rename scene:", error);
throw error;
if (!this.editor.project.getActive()) {
throw new Error("No active project");
}
const command = new RenameSceneCommand(sceneId, name);
this.editor.command.execute({ command });
}
async switchToScene({ sceneId }: { sceneId: string }): Promise<void> {
@@ -119,7 +97,6 @@ export class ScenesManager {
},
};
await storageService.saveProject({ project: updatedProject });
this.editor.project.setActiveProject({ project: updatedProject });
}
@@ -128,39 +105,8 @@ export class ScenesManager {
}
async toggleBookmark({ time }: { time: number }): Promise<void> {
const activeScene = this.getActiveScene();
if (!activeScene || !this.active) return;
const activeProject = this.editor.project.getActive();
if (!activeProject) return;
const frameTime = getFrameTime({
time,
fps: activeProject.settings.fps,
});
const updatedBookmarks = toggleBookmarkInArray({
bookmarks: activeScene.bookmarks,
frameTime,
});
const updatedScenes = updateSceneInArray({
scenes: this.list,
sceneId: activeScene.id,
updates: { bookmarks: updatedBookmarks },
});
try {
await this.updateProjectWithScenes({
updatedScenes,
updatedSceneId: activeScene.id,
});
} catch (error) {
console.error("Failed to update scene bookmarks:", error);
toast.error("Failed to update bookmarks", {
description: "Please try again",
});
}
const command = new ToggleBookmarkCommand(time);
this.editor.command.execute({ command });
}
isBookmarked({ time }: { time: number }): boolean {
@@ -178,43 +124,8 @@ export class ScenesManager {
}
async removeBookmark({ time }: { time: number }): Promise<void> {
const activeScene = this.getActiveScene();
if (!activeScene || !this.active) return;
const activeProject = this.editor.project.getActive();
if (!activeProject) return;
const frameTime = getFrameTime({
time,
fps: activeProject.settings.fps,
});
const updatedBookmarks = removeBookmarkFromArray({
bookmarks: activeScene.bookmarks,
frameTime,
});
if (updatedBookmarks.length === activeScene.bookmarks.length) {
return;
}
const updatedScenes = updateSceneInArray({
scenes: this.list,
sceneId: activeScene.id,
updates: { bookmarks: updatedBookmarks },
});
try {
await this.updateProjectWithScenes({
updatedScenes,
updatedSceneId: activeScene.id,
});
} catch (error) {
console.error("Failed to update scene bookmarks:", error);
toast.error("Failed to remove bookmark", {
description: "Please try again",
});
}
const command = new RemoveBookmarkCommand(time);
this.editor.command.execute({ command });
}
async loadProjectScenes({ projectId }: { projectId: string }): Promise<void> {
@@ -245,8 +156,8 @@ export class ScenesManager {
updatedAt: new Date(),
},
};
await storageService.saveProject({ project: updatedProject });
this.editor.project.setActiveProject({ project: updatedProject });
this.editor.save.markDirty({ force: true });
}
}
}
@@ -292,17 +203,8 @@ export class ScenesManager {
},
};
storageService
.saveProject({ project: updatedProject })
.then(() => {
this.editor.project.setActiveProject({ project: updatedProject });
})
.catch((error) => {
console.error(
"Failed to save project with background scene:",
error,
);
});
this.editor.project.setActiveProject({ project: updatedProject });
this.editor.save.markDirty({ force: true });
}
}
}
@@ -347,9 +249,6 @@ export class ScenesManager {
updatedAt: new Date(),
},
};
storageService.saveProject({ project: updatedProject }).catch((error) => {
console.error("Failed to persist scenes:", error);
});
this.editor.project.setActiveProject({ project: updatedProject });
}
}
@@ -366,7 +265,7 @@ export class ScenesManager {
updateSceneTracks({
tracks,
}: {
tracks: import("@/types/timeline").TimelineTrack[];
tracks: TimelineTrack[];
}): void {
if (!this.active) return;
@@ -421,36 +320,4 @@ export class ScenesManager {
return { scenes: ensuredScenes, hasAddedMainTrack };
}
private async updateProjectWithScenes({
updatedScenes,
updatedSceneId,
}: {
updatedScenes: TScene[];
updatedSceneId?: string;
}): Promise<void> {
const activeProject = this.editor.project.getActive();
if (!activeProject) {
throw new Error("No active project");
}
const updatedScene = updatedSceneId
? updatedScenes.find((s) => s.id === updatedSceneId)
: this.active;
const updatedProject = {
...activeProject,
scenes: updatedScenes,
metadata: {
...activeProject.metadata,
updatedAt: new Date(),
},
};
await storageService.saveProject({ project: updatedProject });
this.editor.project.setActiveProject({ project: updatedProject });
this.list = updatedScenes;
this.active = updatedScene || null;
this.notify();
}
}
+9 -17
View File
@@ -12,6 +12,7 @@ import {
AddTrackCommand,
RemoveTrackCommand,
ToggleTrackMuteCommand,
ToggleTrackVisibilityCommand,
AddElementToTrackCommand,
UpdateElementTrimCommand,
UpdateElementDurationCommand,
@@ -54,20 +55,17 @@ export class TimelineManager {
}
updateElementTrim({
trackId,
elementId,
trimStart,
trimEnd,
pushHistory = true,
}: {
trackId: string;
elementId: string;
trimStart: number;
trimEnd: number;
pushHistory?: boolean;
}): void {
const command = new UpdateElementTrimCommand(
trackId,
elementId,
trimStart,
trimEnd,
@@ -118,17 +116,20 @@ export class TimelineManager {
targetTrackId,
elementId,
newStartTime,
createTrack,
}: {
sourceTrackId: string;
targetTrackId: string;
elementId: string;
newStartTime: number;
createTrack?: { type: TrackType; index: number };
}): void {
const command = new MoveElementCommand(
sourceTrackId,
targetTrackId,
elementId,
newStartTime,
createTrack,
);
this.editor.command.execute({ command });
}
@@ -138,6 +139,11 @@ export class TimelineManager {
this.editor.command.execute({ command });
}
toggleTrackVisibility({ trackId }: { trackId: string }): void {
const command = new ToggleTrackVisibilityCommand(trackId);
this.editor.command.execute({ command });
}
splitElements({
elements,
splitTime,
@@ -257,20 +263,6 @@ export class TimelineManager {
this.editor.command.execute({ command });
}
checkElementOverlap({
trackId,
startTime,
duration,
excludeElementId,
}: {
trackId: string;
startTime: number;
duration: number;
excludeElementId?: string;
}): boolean {
throw new Error("Not implemented");
}
getTracks(): TimelineTrack[] {
return this.editor.scenes.getActiveScene()?.tracks ?? [];
}
@@ -1,16 +1,17 @@
"use client";
import { useTimelineStore } from "@/stores/timeline-store";
import { useActionHandler } from "@/hooks/use-action-handler";
import { useEditor } from "./use-editor";
import { useActionHandler } from "@/hooks/actions/use-action-handler";
import { useEditor } from "../use-editor";
import { PasteCommand } from "@/lib/commands/timeline/clipboard/paste";
import { toast } from "sonner";
import { useElementSelection } from "../timeline/element/use-element-selection";
export function useEditorActions() {
const editor = useEditor();
const activeProject = editor.project.getActive();
const timelineStore = useTimelineStore.getState();
const selectedElements = timelineStore.selectedElements;
const { selectedElements, setElementSelection } = useElementSelection();
const { clipboard, setClipboard, toggleSnapping } = useTimelineStore();
useActionHandler(
"toggle-play",
@@ -191,7 +192,7 @@ export function useEditorActions() {
elementId: element.id,
})),
);
timelineStore.setSelectedElements({ elements: allElements });
setElementSelection({ elements: allElements });
},
undefined,
);
@@ -205,7 +206,7 @@ export function useEditorActions() {
);
useActionHandler(
"toggle-mute-selected",
"toggle-elements-muted-selected",
() => {
editor.timeline.toggleElementsMuted({ elements: selectedElements });
},
@@ -213,7 +214,7 @@ export function useEditorActions() {
);
useActionHandler(
"toggle-visibility-selected",
"toggle-elements-visibility-selected",
() => {
editor.timeline.toggleElementsVisibility({ elements: selectedElements });
},
@@ -244,7 +245,7 @@ export function useEditorActions() {
};
});
timelineStore.setClipboard({ items });
setClipboard({ items });
},
undefined,
);
@@ -252,7 +253,6 @@ export function useEditorActions() {
useActionHandler(
"paste-selected",
() => {
const clipboard = timelineStore.clipboard;
if (!clipboard?.items.length) return;
const currentTime = editor.playback.getCurrentTime();
@@ -266,7 +266,7 @@ export function useEditorActions() {
useActionHandler(
"toggle-snapping",
() => {
timelineStore.toggleSnapping();
toggleSnapping();
},
undefined,
);
@@ -7,10 +7,11 @@ import {
type RefObject,
} from "react";
import { useEditor } from "@/hooks/use-editor";
import { useElementSelection } from "@/hooks/use-element-selection";
import { useElementSelection } from "@/hooks/timeline/element/use-element-selection";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { snapTimeToFrame } from "@/lib/time-utils";
import { computeDropTarget } from "@/lib/timeline/drop-utils";
import { generateUUID } from "@/lib/utils";
import type {
ElementDragState,
TimelineElement,
@@ -24,6 +25,7 @@ interface UseElementInteractionProps {
zoomLevel: number;
timelineRef: RefObject<HTMLDivElement | null>;
tracksContainerRef: RefObject<HTMLDivElement | null>;
tracksScrollRef: RefObject<HTMLDivElement | null>;
onSnapPointChange?: (snapPoint: SnapPoint | null) => void;
}
@@ -32,27 +34,80 @@ const initialDragState: ElementDragState = {
elementId: null,
trackId: null,
startMouseX: 0,
startMouseY: 0,
startElementTime: 0,
clickOffsetTime: 0,
currentTime: 0,
};
interface PendingDragState {
elementId: string;
trackId: string;
startMouseX: number;
startMouseY: number;
startElementTime: number;
clickOffsetTime: number;
}
function getMouseTimeFromClientX({
clientX,
containerRect,
zoomLevel,
scrollLeft,
}: {
clientX: number;
containerRect: DOMRect;
zoomLevel: number;
scrollLeft: number;
}): number {
const mouseX = clientX - containerRect.left + scrollLeft;
return Math.max(
0,
mouseX / (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel),
);
}
function getClickOffsetTime({
clientX,
elementRect,
zoomLevel,
}: {
clientX: number;
elementRect: DOMRect;
zoomLevel: number;
}): number {
const clickOffsetX = clientX - elementRect.left;
return clickOffsetX / (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel);
}
function getElementDuration({ element }: { element: TimelineElement }): number {
return element.duration - element.trimStart - element.trimEnd;
}
interface StartDragParams
extends Omit<ElementDragState, "isDragging" | "currentTime"> {
initialCurrentTime: number;
}
export function useElementInteraction({
zoomLevel,
timelineRef,
tracksContainerRef,
tracksScrollRef,
onSnapPointChange,
}: UseElementInteractionProps) {
const editor = useEditor();
const tracks = editor.timeline.getTracks();
const {
isSelected,
select,
isElementSelected,
selectElement,
handleElementClick: handleSelectionClick,
} = useElementSelection();
const [dragState, setDragState] =
useState<ElementDragState>(initialDragState);
const [isPendingDrag, setIsPendingDrag] = useState(false);
const pendingDragRef = useRef<PendingDragState | null>(null);
const lastMouseXRef = useRef(0);
const mouseDownLocationRef = useRef<{ x: number; y: number } | null>(null);
@@ -61,17 +116,20 @@ export function useElementInteraction({
elementId,
trackId,
startMouseX,
startMouseY,
startElementTime,
clickOffsetTime,
}: Omit<ElementDragState, "isDragging" | "currentTime">) => {
initialCurrentTime,
}: StartDragParams) => {
setDragState({
isDragging: true,
elementId,
trackId,
startMouseX,
startMouseY,
startElementTime,
clickOffsetTime,
currentTime: startElementTime,
currentTime: initialCurrentTime,
});
},
[],
@@ -81,37 +139,77 @@ export function useElementInteraction({
setDragState(initialDragState);
}, []);
// mouse move: update drag time
useEffect(() => {
if (!dragState.isDragging) return;
if (!dragState.isDragging && !isPendingDrag) return;
const handleMouseMove = ({ clientX }: MouseEvent) => {
if (!timelineRef.current) return;
const handleMouseMove = ({ clientX, clientY }: MouseEvent) => {
let startedDragThisEvent = false;
const timeline = timelineRef.current;
const scrollContainer = tracksScrollRef.current;
if (!timeline || !scrollContainer) return;
lastMouseXRef.current = clientX;
if (isPendingDrag && pendingDragRef.current) {
const deltaX = Math.abs(clientX - pendingDragRef.current.startMouseX);
const deltaY = Math.abs(clientY - pendingDragRef.current.startMouseY);
if (deltaX > DRAG_THRESHOLD_PX || deltaY > DRAG_THRESHOLD_PX) {
const activeProject = editor.project.getActive();
if (!activeProject) return;
const scrollLeft = scrollContainer.scrollLeft;
const mouseTime = getMouseTimeFromClientX({
clientX,
containerRect: scrollContainer.getBoundingClientRect(),
zoomLevel,
scrollLeft,
});
const adjustedTime = Math.max(
0,
mouseTime - pendingDragRef.current.clickOffsetTime,
);
const snappedTime = snapTimeToFrame({
time: adjustedTime,
fps: activeProject.settings.fps,
});
startDrag({
...pendingDragRef.current,
initialCurrentTime: snappedTime,
});
startedDragThisEvent = true;
pendingDragRef.current = null;
setIsPendingDrag(false);
} else {
return;
}
}
if (startedDragThisEvent) {
return;
}
if (dragState.elementId && dragState.trackId) {
const alreadySelected = isSelected({
const alreadySelected = isElementSelected({
trackId: dragState.trackId,
elementId: dragState.elementId,
});
if (!alreadySelected) {
select({
selectElement({
trackId: dragState.trackId,
elementId: dragState.elementId,
});
}
}
const rect = timelineRef.current.getBoundingClientRect();
const mouseX = clientX - rect.left;
const mouseTime = Math.max(
0,
mouseX / (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel),
);
const adjustedTime = Math.max(0, mouseTime - dragState.clickOffsetTime);
const activeProject = editor.project.getActive();
if (!activeProject) return;
const scrollLeft = scrollContainer.scrollLeft;
const mouseTime = getMouseTimeFromClientX({
clientX,
containerRect: scrollContainer.getBoundingClientRect(),
zoomLevel,
scrollLeft,
});
const adjustedTime = Math.max(0, mouseTime - dragState.clickOffsetTime);
const fps = activeProject.settings.fps;
const snappedTime = snapTimeToFrame({ time: adjustedTime, fps });
setDragState((previousDragState) => ({
@@ -128,13 +226,15 @@ export function useElementInteraction({
dragState.elementId,
dragState.trackId,
zoomLevel,
isSelected,
select,
isElementSelected,
selectElement,
editor.project,
timelineRef,
tracksScrollRef,
isPendingDrag,
startDrag,
]);
// mouse up: resolve drop
useEffect(() => {
if (!dragState.isDragging) return;
@@ -164,12 +264,24 @@ export function useElementInteraction({
return;
}
const elementDuration =
movingElement.duration -
movingElement.trimStart -
movingElement.trimEnd;
const mouseX = clientX - containerRect.left;
const elementDuration = getElementDuration({ element: movingElement });
const scrollLeft = tracksScrollRef.current?.scrollLeft ?? 0;
const scrollContainerRect =
tracksScrollRef.current?.getBoundingClientRect();
const mouseX = scrollContainerRect
? clientX - scrollContainerRect.left + scrollLeft
: clientX - containerRect.left + scrollLeft;
const mouseY = clientY - containerRect.top;
if (mouseDownLocationRef.current) {
const deltaX = Math.abs(clientX - mouseDownLocationRef.current.x);
const deltaY = Math.abs(clientY - mouseDownLocationRef.current.y);
if (deltaX <= DRAG_THRESHOLD_PX && deltaY <= DRAG_THRESHOLD_PX) {
mouseDownLocationRef.current = null;
endDrag();
onSnapPointChange?.(null);
return;
}
}
const dropTarget = computeDropTarget({
elementType: movingElement.type,
@@ -181,27 +293,19 @@ export function useElementInteraction({
elementDuration,
pixelsPerSecond: TIMELINE_CONSTANTS.PIXELS_PER_SECOND,
zoomLevel,
excludeElementId: movingElement.id,
});
const activeProject = editor.project.getActive();
if (!activeProject) {
endDrag();
onSnapPointChange?.(null);
return;
}
const fps = activeProject.settings.fps;
const snappedTime = snapTimeToFrame({ time: dropTarget.xPosition, fps });
const snappedTime = dragState.currentTime;
if (dropTarget.isNewTrack) {
const newTrackId = editor.timeline.addTrack({
type: sourceTrack.type,
index: dropTarget.trackIndex,
});
const newTrackId = generateUUID();
editor.timeline.moveElement({
sourceTrackId: dragState.trackId,
targetTrackId: newTrackId,
elementId: dragState.elementId,
newStartTime: snappedTime,
createTrack: { type: sourceTrack.type, index: dropTarget.trackIndex },
});
} else {
const targetTrack = tracks[dropTarget.trackIndex];
@@ -230,11 +334,24 @@ export function useElementInteraction({
tracks,
endDrag,
onSnapPointChange,
editor.project,
editor.timeline,
tracksContainerRef,
tracksScrollRef,
]);
useEffect(() => {
if (!isPendingDrag) return;
const handleMouseUp = () => {
pendingDragRef.current = null;
setIsPendingDrag(false);
onSnapPointChange?.(null);
};
document.addEventListener("mouseup", handleMouseUp);
return () => document.removeEventListener("mouseup", handleMouseUp);
}, [isPendingDrag, onSnapPointChange]);
const handleElementMouseDown = useCallback(
({
event,
@@ -253,7 +370,7 @@ export function useElementInteraction({
// right-click
if (isRightClick) {
const alreadySelected = isSelected({
const alreadySelected = isElementSelected({
trackId: track.id,
elementId: element.id,
});
@@ -277,22 +394,24 @@ export function useElementInteraction({
}
// start drag
const elementRect = (
event.currentTarget as HTMLElement
).getBoundingClientRect();
const clickOffsetX = event.clientX - elementRect.left;
const clickOffsetTime =
clickOffsetX / (TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel);
startDrag({
const clickOffsetTime = getClickOffsetTime({
clientX: event.clientX,
elementRect: (
event.currentTarget as HTMLElement
).getBoundingClientRect(),
zoomLevel,
});
pendingDragRef.current = {
elementId: element.id,
trackId: track.id,
startMouseX: event.clientX,
startMouseY: event.clientY,
startElementTime: element.startTime,
clickOffsetTime,
});
};
setIsPendingDrag(true);
},
[zoomLevel, startDrag, isSelected, handleSelectionClick],
[zoomLevel, isElementSelected, handleSelectionClick],
);
const handleElementClick = useCallback(
@@ -321,15 +440,15 @@ export function useElementInteraction({
if (event.metaKey || event.ctrlKey || event.shiftKey) return;
// single click: select if not selected
const alreadySelected = isSelected({
const alreadySelected = isElementSelected({
trackId: track.id,
elementId: element.id,
});
if (!alreadySelected) {
select({ trackId: track.id, elementId: element.id });
selectElement({ trackId: track.id, elementId: element.id });
}
},
[isSelected, select],
[isElementSelected, selectElement],
);
return {
@@ -1,10 +1,7 @@
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { TimelineElement, TimelineTrack } from "@/types/timeline";
import { snapTimeToFrame } from "@/lib/time-utils";
import { EditorCore } from "@/core";
import { UpdateElementTrimCommand } from "@/lib/commands/timeline/element/update-element-trim";
import { UpdateElementStartTimeCommand } from "@/lib/commands/timeline/element/update-element-start-time";
import { UpdateElementDurationCommand } from "@/lib/commands/timeline/element/update-element-duration";
export interface ResizeState {
elementId: string;
@@ -35,6 +32,10 @@ export function useTimelineElementResize({
const [currentTrimEnd, setCurrentTrimEnd] = useState(element.trimEnd);
const [currentStartTime, setCurrentStartTime] = useState(element.startTime);
const [currentDuration, setCurrentDuration] = useState(element.duration);
const currentTrimStartRef = useRef(element.trimStart);
const currentTrimEndRef = useRef(element.trimEnd);
const currentStartTimeRef = useRef(element.startTime);
const currentDurationRef = useRef(element.duration);
useEffect(() => {
if (!resizing) return;
@@ -82,6 +83,10 @@ export function useTimelineElementResize({
setCurrentTrimEnd(element.trimEnd);
setCurrentStartTime(element.startTime);
setCurrentDuration(element.duration);
currentTrimStartRef.current = element.trimStart;
currentTrimEndRef.current = element.trimEnd;
currentStartTimeRef.current = element.startTime;
currentDurationRef.current = element.duration;
};
const canExtendElementDuration = () => {
@@ -126,6 +131,9 @@ export function useTimelineElementResize({
setCurrentTrimStart(newTrimStart);
setCurrentStartTime(newStartTime);
setCurrentDuration(newDuration);
currentTrimStartRef.current = newTrimStart;
currentStartTimeRef.current = newStartTime;
currentDurationRef.current = newDuration;
} else if (calculated < 0) {
if (canExtendElementDuration()) {
const extensionAmount = Math.abs(calculated);
@@ -143,6 +151,9 @@ export function useTimelineElementResize({
setCurrentTrimStart(0);
setCurrentStartTime(newStartTime);
setCurrentDuration(newDuration);
currentTrimStartRef.current = 0;
currentStartTimeRef.current = newStartTime;
currentDurationRef.current = newDuration;
} else {
const trimDelta = 0 - resizing.initialTrimStart;
const newStartTime = snapTimeToFrame({
@@ -157,6 +168,9 @@ export function useTimelineElementResize({
setCurrentTrimStart(0);
setCurrentStartTime(newStartTime);
setCurrentDuration(newDuration);
currentTrimStartRef.current = 0;
currentStartTimeRef.current = newStartTime;
currentDurationRef.current = newDuration;
}
}
} else {
@@ -176,6 +190,8 @@ export function useTimelineElementResize({
setCurrentDuration(newDuration);
setCurrentTrimEnd(0);
currentDurationRef.current = newDuration;
currentTrimEndRef.current = 0;
} else {
const extensionToLimit = resizing.initialTrimEnd;
const newDuration = snapTimeToFrame({
@@ -185,6 +201,8 @@ export function useTimelineElementResize({
setCurrentDuration(newDuration);
setCurrentTrimEnd(0);
currentDurationRef.current = newDuration;
currentTrimEndRef.current = 0;
}
} else {
const maxTrimEnd = sourceDuration - resizing.initialTrimStart - 0.1;
@@ -201,6 +219,8 @@ export function useTimelineElementResize({
setCurrentTrimEnd(finalTrimEnd);
setCurrentDuration(newDuration);
currentTrimEndRef.current = finalTrimEnd;
currentDurationRef.current = newDuration;
}
}
};
@@ -208,36 +228,36 @@ export function useTimelineElementResize({
const handleResizeEnd = () => {
if (!resizing) return;
const trimStartChanged = currentTrimStart !== resizing.initialTrimStart;
const trimEndChanged = currentTrimEnd !== resizing.initialTrimEnd;
const startTimeChanged = currentStartTime !== resizing.initialStartTime;
const durationChanged = currentDuration !== resizing.initialDuration;
const finalTrimStart = currentTrimStartRef.current;
const finalTrimEnd = currentTrimEndRef.current;
const finalStartTime = currentStartTimeRef.current;
const finalDuration = currentDurationRef.current;
const trimStartChanged = finalTrimStart !== resizing.initialTrimStart;
const trimEndChanged = finalTrimEnd !== resizing.initialTrimEnd;
const startTimeChanged = finalStartTime !== resizing.initialStartTime;
const durationChanged = finalDuration !== resizing.initialDuration;
if (trimStartChanged || trimEndChanged) {
const trimCommand = new UpdateElementTrimCommand(
track.id,
element.id,
currentTrimStart,
currentTrimEnd,
);
editor.command.execute({ command: trimCommand });
editor.timeline.updateElementTrim({
elementId: element.id,
trimStart: finalTrimStart,
trimEnd: finalTrimEnd,
});
}
if (startTimeChanged) {
const startTimeCommand = new UpdateElementStartTimeCommand(
[{ trackId: track.id, elementId: element.id }],
currentStartTime,
);
editor.command.execute({ command: startTimeCommand });
editor.timeline.updateElementStartTime({
elements: [{ trackId: track.id, elementId: element.id }],
startTime: finalStartTime,
});
}
if (durationChanged) {
const durationCommand = new UpdateElementDurationCommand(
track.id,
element.id,
currentDuration,
);
editor.command.execute({ command: durationCommand });
editor.timeline.updateElementDuration({
trackId: track.id,
elementId: element.id,
duration: finalDuration,
});
}
setResizing(null);
@@ -4,28 +4,29 @@ import { useTimelineStore } from "@/stores/timeline-store";
type ElementRef = { trackId: string; elementId: string };
export function useElementSelection() {
const selectedElements = useTimelineStore((s) => s.selectedElements);
const setSelectedElements = useTimelineStore((s) => s.setSelectedElements);
const { selectedElements, setSelectedElements } = useTimelineStore();
const isSelected = useCallback(
const isElementSelected = useCallback(
({ trackId, elementId }: ElementRef) =>
selectedElements.some(
(el) => el.trackId === trackId && el.elementId === elementId,
(element) =>
element.trackId === trackId && element.elementId === elementId,
),
[selectedElements],
);
const select = useCallback(
const selectElement = useCallback(
({ trackId, elementId }: ElementRef) => {
setSelectedElements({ elements: [{ trackId, elementId }] });
},
[setSelectedElements],
);
const addToSelection = useCallback(
const addElementToSelection = useCallback(
({ trackId, elementId }: ElementRef) => {
const alreadySelected = selectedElements.some(
(el) => el.trackId === trackId && el.elementId === elementId,
(element) =>
element.trackId === trackId && element.elementId === elementId,
);
if (alreadySelected) return;
@@ -36,38 +37,40 @@ export function useElementSelection() {
[selectedElements, setSelectedElements],
);
const removeFromSelection = useCallback(
const removeElementFromSelection = useCallback(
({ trackId, elementId }: ElementRef) => {
setSelectedElements({
elements: selectedElements.filter(
(el) => !(el.trackId === trackId && el.elementId === elementId),
(element) =>
!(element.trackId === trackId && element.elementId === elementId),
),
});
},
[selectedElements, setSelectedElements],
);
const toggleSelection = useCallback(
const toggleElementSelection = useCallback(
({ trackId, elementId }: ElementRef) => {
const alreadySelected = selectedElements.some(
(el) => el.trackId === trackId && el.elementId === elementId,
(element) =>
element.trackId === trackId && element.elementId === elementId,
);
if (alreadySelected) {
removeFromSelection({ trackId, elementId });
removeElementFromSelection({ trackId, elementId });
} else {
addToSelection({ trackId, elementId });
addElementToSelection({ trackId, elementId });
}
},
[selectedElements, addToSelection, removeFromSelection],
[selectedElements, addElementToSelection, removeElementFromSelection],
);
const clearSelection = useCallback(() => {
const clearElementSelection = useCallback(() => {
setSelectedElements({ elements: [] });
}, [setSelectedElements]);
const setSelection = useCallback(
(elements: ElementRef[]) => {
const setElementSelection = useCallback(
({ elements }: { elements: ElementRef[] }) => {
setSelectedElements({ elements });
},
[setSelectedElements],
@@ -85,37 +88,23 @@ export function useElementSelection() {
isMultiKey,
}: ElementRef & { isMultiKey: boolean }) => {
if (isMultiKey) {
toggleSelection({ trackId, elementId });
toggleElementSelection({ trackId, elementId });
} else {
select({ trackId, elementId });
selectElement({ trackId, elementId });
}
},
[toggleSelection, select],
);
/**
* Ensures element is selected without toggling.
* Used for drag operations where we want to select if not already.
*/
const ensureSelected = useCallback(
({ trackId, elementId }: ElementRef) => {
if (!isSelected({ trackId, elementId })) {
select({ trackId, elementId });
}
},
[isSelected, select],
[toggleElementSelection, selectElement],
);
return {
selectedElements,
isSelected,
select,
setSelection,
addToSelection,
removeFromSelection,
toggleSelection,
clearSelection,
isElementSelected,
selectElement,
setElementSelection,
addElementToSelection,
removeElementFromSelection,
toggleElementSelection,
clearElementSelection,
handleElementClick,
ensureSelected,
};
}
@@ -1,7 +1,7 @@
import { useState, useEffect, useCallback } from "react";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { getCumulativeHeightBefore, getTrackHeight } from "@/lib/timeline";
import { useEditor } from "./use-editor";
import { useEditor } from "../use-editor";
interface UseSelectionBoxProps {
containerRef: React.RefObject<HTMLElement>;
@@ -1,11 +1,12 @@
import { useCallback, useRef } from "react";
import type { RefObject } from "react";
import type { MutableRefObject, RefObject } from "react";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
import { snapTimeToFrame } from "@/lib/time-utils";
import { useEditor } from "../use-editor";
interface UseTimelineInteractionsProps {
playheadRef: RefObject<HTMLDivElement>;
trackLabelsRef: RefObject<HTMLDivElement>;
rulerScrollRef: RefObject<HTMLDivElement>;
tracksScrollRef: RefObject<HTMLDivElement>;
zoomLevel: number;
@@ -15,8 +16,47 @@ interface UseTimelineInteractionsProps {
seek: (time: number) => void;
}
function resetMouseTracking({
mouseTrackingRef,
}: {
mouseTrackingRef: MutableRefObject<{
isMouseDown: boolean;
downX: number;
downY: number;
downTime: number;
}>;
}) {
mouseTrackingRef.current = {
isMouseDown: false,
downX: 0,
downY: 0,
downTime: 0,
};
}
function setMouseTracking({
mouseTrackingRef,
event,
}: {
mouseTrackingRef: MutableRefObject<{
isMouseDown: boolean;
downX: number;
downY: number;
downTime: number;
}>;
event: React.MouseEvent;
}) {
mouseTrackingRef.current = {
isMouseDown: true,
downX: event.clientX,
downY: event.clientY,
downTime: event.timeStamp,
};
}
export function useTimelineInteractions({
playheadRef,
trackLabelsRef,
rulerScrollRef,
tracksScrollRef,
zoomLevel,
@@ -35,69 +75,58 @@ export function useTimelineInteractions({
downTime: 0,
});
const handleTimelineMouseDown = useCallback(
(e: React.MouseEvent) => {
const target = e.target as HTMLElement;
const handleTracksMouseDown = useCallback((event: React.MouseEvent) => {
if (event.button !== 0) return;
setMouseTracking({ mouseTrackingRef, event });
}, []);
const isTimelineBackground =
!target.closest(".timeline-element") &&
!playheadRef.current?.contains(target) &&
!target.closest("[data-track-labels]");
if (isTimelineBackground) {
mouseTrackingRef.current = {
isMouseDown: true,
downX: e.clientX,
downY: e.clientY,
downTime: e.timeStamp,
};
}
},
[playheadRef],
);
const handleRulerMouseDown = useCallback((event: React.MouseEvent) => {
if (event.button !== 0) return;
setMouseTracking({ mouseTrackingRef, event });
}, []);
const shouldProcessTimelineClick = useCallback(
(e: React.MouseEvent) => {
const target = e.target as HTMLElement;
({ event }: { event: React.MouseEvent }) => {
const target = event.target as HTMLElement;
const { isMouseDown, downX, downY, downTime } = mouseTrackingRef.current;
if (!isMouseDown) return false;
const deltaX = Math.abs(e.clientX - downX);
const deltaY = Math.abs(e.clientY - downY);
const deltaTime = e.timeStamp - downTime;
const deltaX = Math.abs(event.clientX - downX);
const deltaY = Math.abs(event.clientY - downY);
const deltaTime = event.timeStamp - downTime;
if (deltaX > 5 || deltaY > 5 || deltaTime > 500) return false;
if (isSelecting) return false;
if (target.closest(".timeline-element")) return false;
if (playheadRef.current?.contains(target)) return false;
if (target.closest("[data-track-labels]")) {
if (trackLabelsRef.current?.contains(target)) {
clearSelectedElements();
return false;
}
return true;
},
[isSelecting, clearSelectedElements, playheadRef],
[isSelecting, clearSelectedElements, playheadRef, trackLabelsRef],
);
const handleTimelineSeek = useCallback(
(e: React.MouseEvent) => {
const isRulerClick = (e.target as HTMLElement).closest(
"[data-ruler-area]",
);
const scrollContainer = isRulerClick
? rulerScrollRef.current
: tracksScrollRef.current;
({
event,
source,
}: {
event: React.MouseEvent;
source: "ruler" | "tracks";
}) => {
const scrollContainer =
source === "ruler" ? rulerScrollRef.current : tracksScrollRef.current;
if (!scrollContainer) return;
const rect = scrollContainer.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseX = event.clientX - rect.left;
const scrollLeft = scrollContainer.scrollLeft;
const rawTime = Math.max(
@@ -116,32 +145,41 @@ export function useTimelineInteractions({
[
duration,
zoomLevel,
seek,
rulerScrollRef,
tracksScrollRef,
seek,
activeProject?.settings.fps,
],
);
const handleTimelineContentClick = useCallback(
(e: React.MouseEvent) => {
mouseTrackingRef.current = {
isMouseDown: false,
downX: 0,
downY: 0,
downTime: 0,
};
const handleTracksClick = useCallback(
(event: React.MouseEvent) => {
resetMouseTracking({ mouseTrackingRef });
if (shouldProcessTimelineClick(e)) {
if (shouldProcessTimelineClick({ event })) {
clearSelectedElements();
handleTimelineSeek(e);
handleTimelineSeek({ event, source: "tracks" });
}
},
[shouldProcessTimelineClick, handleTimelineSeek, clearSelectedElements],
);
const handleRulerClick = useCallback(
(event: React.MouseEvent) => {
resetMouseTracking({ mouseTrackingRef });
if (shouldProcessTimelineClick({ event })) {
clearSelectedElements();
handleTimelineSeek({ event, source: "ruler" });
}
},
[shouldProcessTimelineClick, handleTimelineSeek, clearSelectedElements],
);
return {
handleTimelineMouseDown,
handleTimelineContentClick,
handleTracksMouseDown,
handleTracksClick,
handleRulerMouseDown,
handleRulerClick,
};
}
@@ -1,6 +1,6 @@
import { snapTimeToFrame } from "@/lib/time-utils";
import { useState, useEffect, useCallback, useRef } from "react";
import { useEdgeAutoScroll } from "@/hooks/use-edge-auto-scroll";
import { useEdgeAutoScroll } from "@/hooks/timeline/use-edge-auto-scroll";
import { useEditor } from "../use-editor";
import { TIMELINE_CONSTANTS } from "@/constants/timeline-constants";
@@ -16,7 +16,7 @@ export interface SnapResult {
}
export interface UseTimelineSnappingOptions {
snapThreshold?: number; // Distance in pixels to trigger snapping
snapThreshold?: number;
enableElementSnapping?: boolean;
enablePlayheadSnapping?: boolean;
}
@@ -27,21 +27,21 @@ export function useTimelineSnapping({
enablePlayheadSnapping = true,
}: UseTimelineSnappingOptions = {}) {
const findSnapPoints = useCallback(
(
tracks: TimelineTrack[],
currentTime: number,
playheadTime: number,
zoomLevel: number,
excludeElementId?: string,
): SnapPoint[] => {
({
tracks,
playheadTime,
excludeElementId,
}: {
tracks: Array<TimelineTrack>;
playheadTime: number;
excludeElementId?: string;
}): SnapPoint[] => {
const snapPoints: SnapPoint[] = [];
// Add element snap points
if (enableElementSnapping) {
tracks.forEach((track) => {
track.elements.forEach((element) => {
// Skip the element being dragged
if (element.id === excludeElementId) return;
for (const track of tracks) {
for (const element of track.elements) {
if (element.id === excludeElementId) continue;
const elementStart = element.startTime;
const elementEnd = element.startTime + element.duration;
@@ -60,11 +60,10 @@ export function useTimelineSnapping({
trackId: track.id,
},
);
});
});
}
}
}
// Add playhead snap point
if (enablePlayheadSnapping) {
snapPoints.push({
time: playheadTime,
@@ -78,24 +77,28 @@ export function useTimelineSnapping({
);
const snapToNearestPoint = useCallback(
(
targetTime: number,
snapPoints: SnapPoint[],
zoomLevel: number,
): SnapResult => {
({
targetTime,
snapPoints,
zoomLevel,
}: {
targetTime: number;
snapPoints: Array<SnapPoint>;
zoomLevel: number;
}): SnapResult => {
const pixelsPerSecond = TIMELINE_CONSTANTS.PIXELS_PER_SECOND * zoomLevel;
const thresholdInSeconds = snapThreshold / pixelsPerSecond;
let closestSnapPoint: SnapPoint | null = null;
let closestDistance = Infinity;
snapPoints.forEach((snapPoint) => {
for (const snapPoint of snapPoints) {
const distance = Math.abs(targetTime - snapPoint.time);
if (distance < thresholdInSeconds && distance < closestDistance) {
closestDistance = distance;
closestSnapPoint = snapPoint;
}
});
}
return {
snappedTime: closestSnapPoint
@@ -109,34 +112,38 @@ export function useTimelineSnapping({
);
const snapElementEdge = useCallback(
(
targetTime: number,
elementDuration: number,
tracks: TimelineTrack[],
playheadTime: number,
zoomLevel: number,
excludeElementId?: string,
snapToStart = true, // true for start edge, false for end edge
): SnapResult => {
const snapPoints = findSnapPoints(
({
targetTime,
elementDuration,
tracks,
playheadTime,
zoomLevel,
excludeElementId,
snapToStart = true,
}: {
targetTime: number;
elementDuration: number;
tracks: Array<TimelineTrack>;
playheadTime: number;
zoomLevel: number;
excludeElementId?: string;
snapToStart?: boolean;
}): SnapResult => {
const snapPoints = findSnapPoints({
tracks,
targetTime,
playheadTime,
zoomLevel,
excludeElementId,
);
});
// For end edge snapping, we need to account for element duration
const effectiveTargetTime = snapToStart
? targetTime
: targetTime + elementDuration;
const snapResult = snapToNearestPoint(
effectiveTargetTime,
const snapResult = snapToNearestPoint({
targetTime: effectiveTargetTime,
snapPoints,
zoomLevel,
);
});
// Adjust the snapped time back for end edge
if (!snapToStart && snapResult.snapPoint) {
snapResult.snappedTime = snapResult.snappedTime - elementDuration;
}
-23
View File
@@ -1,23 +0,0 @@
import { useEffect } from "react";
interface UseFilePasteOptions {
onFilesPaste: (files: File[]) => void;
}
export function useFilePaste({ onFilesPaste }: UseFilePasteOptions) {
useEffect(() => {
function handlePaste(e: ClipboardEvent) {
if (!e.clipboardData?.files.length) return;
const files = Array.from(e.clipboardData.files);
if (files.length > 0) {
e.preventDefault();
onFilesPaste(files);
}
}
window.addEventListener("paste", handlePaste);
return () => window.removeEventListener("paste", handlePaste);
}, [onFilesPaste]);
}
@@ -17,8 +17,7 @@ export interface KeyboardShortcut {
icon?: React.ReactNode;
}
// Convert key binding format to display format
const formatKey = (key: string): string => {
function formatKey({ key }: { key: string }): string {
return key
.replace("ctrl", getPlatformSpecialKey())
.replace("alt", getPlatformAlternateKey())
@@ -34,27 +33,24 @@ const formatKey = (key: string): string => {
.replace("delete", "Delete")
.replace("backspace", "Backspace")
.replace("-", "+");
};
}
export const useKeyboardShortcutsHelp = () => {
export function useKeyboardShortcutsHelp() {
const { keybindings } = useKeybindingsStore();
const shortcuts = useMemo(() => {
const result: KeyboardShortcut[] = [];
// Group keybindings by action
const actionToKeys: Record<string, Array<string>> = {};
const actionToKeys: Record<string, string[]> = {};
for (const [key, action] of Object.entries(keybindings)) {
if (action) {
if (!actionToKeys[action]) {
actionToKeys[action] = [];
}
actionToKeys[action].push(formatKey(key));
actionToKeys[action].push(formatKey({ key }));
}
}
// Convert to shortcuts format
for (const [actionId, keys] of Object.entries(actionToKeys)) {
if (!Object.prototype.hasOwnProperty.call(ACTIONS, actionId)) {
continue;
@@ -71,7 +67,6 @@ export const useKeyboardShortcutsHelp = () => {
});
}
// Sort shortcuts by category first, then by description to ensure consistent ordering
return result.sort((a, b) => {
if (a.category !== b.category) {
return a.category.localeCompare(b.category);
@@ -83,4 +78,4 @@ export const useKeyboardShortcutsHelp = () => {
return {
shortcuts,
};
};
}
-21
View File
@@ -1,21 +0,0 @@
import * as React from "react";
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
undefined
);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener("change", onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener("change", onChange);
}, []);
return !!isMobile;
}
-28
View File
@@ -1,28 +0,0 @@
import { useEffect } from 'react';
interface UsePreventScrollOptions {
enabled?: boolean;
element?: HTMLElement;
}
export function usePreventScroll({ enabled = true, element }: UsePreventScrollOptions = {}) {
useEffect(() => {
if (!enabled) return;
const targetElement = element || document.body;
const originalOverflow = targetElement.style.overflow;
const originalPaddingRight = targetElement.style.paddingRight;
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
targetElement.style.overflow = 'hidden';
if (scrollbarWidth > 0) {
targetElement.style.paddingRight = `${scrollbarWidth}px`;
}
return () => {
targetElement.style.overflow = originalOverflow;
targetElement.style.paddingRight = originalPaddingRight;
};
}, [enabled, element]);
}
@@ -1,93 +0,0 @@
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { useEditor } from "@/hooks/use-editor";
export function useProjectInitialize({ projectId }: { projectId: string }) {
const router = useRouter();
const handledProjectIds = useRef<Set<string>>(new Set());
const isInitializingRef = useRef<boolean>(false);
const editor = useEditor();
const activeProject = editor.project.getActive();
useEffect(() => {
let isCancelled = false;
const initProject = async () => {
if (!projectId) {
return;
}
if (isInitializingRef.current) {
return;
}
if (activeProject?.metadata.id === projectId) {
return;
}
if (editor.project.isInvalidProjectId({ id: projectId })) {
return;
}
if (handledProjectIds.current.has(projectId)) {
return;
}
isInitializingRef.current = true;
handledProjectIds.current.add(projectId);
try {
await editor.project.loadProject({ id: projectId });
if (isCancelled) {
return;
}
isInitializingRef.current = false;
} catch (error) {
if (isCancelled) {
return;
}
const isProjectNotFound =
error instanceof Error &&
(error.message.includes("not found") ||
error.message.includes("does not exist") ||
error.message.includes("Project not found"));
if (isProjectNotFound) {
editor.project.markProjectIdAsInvalid({ id: projectId });
try {
const newProjectId = await editor.project.createNewProject({
name: "Untitled Project",
});
if (isCancelled) {
return;
}
router.replace(`/editor/${newProjectId}`);
} catch (createError) {
console.error("Failed to create new project:", createError);
}
} else {
console.error(
"Project loading failed with recoverable error:",
error,
);
handledProjectIds.current.delete(projectId);
}
isInitializingRef.current = false;
}
};
initProject();
return () => {
isCancelled = true;
isInitializingRef.current = false;
};
}, [projectId, editor, router]);
}
-191
View File
@@ -1,191 +0,0 @@
"use client";
// Inspired by react-hot-toast library
import * as React from "react";
import type { ToastActionElement, ToastProps } from "../components/ui/toast";
const TOAST_LIMIT = 1;
const TOAST_REMOVE_DELAY = 1_000_000;
type ToasterToast = ToastProps & {
id: string;
title?: React.ReactNode;
description?: React.ReactNode;
action?: ToastActionElement;
};
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const;
let count = 0;
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER;
return count.toString();
}
type ActionType = typeof actionTypes;
type Action =
| {
type: ActionType["ADD_TOAST"];
toast: ToasterToast;
}
| {
type: ActionType["UPDATE_TOAST"];
toast: Partial<ToasterToast>;
}
| {
type: ActionType["DISMISS_TOAST"];
toastId?: ToasterToast["id"];
}
| {
type: ActionType["REMOVE_TOAST"];
toastId?: ToasterToast["id"];
};
interface State {
toasts: ToasterToast[];
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>();
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: "REMOVE_TOAST",
toastId,
});
}, TOAST_REMOVE_DELAY);
toastTimeouts.set(toastId, timeout);
};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
};
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
};
case "DISMISS_TOAST": {
const { toastId } = action;
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId);
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id);
});
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
};
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
}
};
const listeners: Array<(state: State) => void> = [];
let memoryState: State = { toasts: [] };
function dispatch(action: Action) {
memoryState = reducer(memoryState, action);
listeners.forEach((listener) => {
listener(memoryState);
});
}
type Toast = Omit<ToasterToast, "id">;
function toast({ ...props }: Toast) {
const id = genId();
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
});
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id });
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss();
},
},
});
return {
id,
dismiss,
update,
};
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState);
React.useEffect(() => {
listeners.push(setState);
return () => {
const index = listeners.indexOf(setState);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [state]);
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
};
}
export { useToast, toast };
+2 -2
View File
@@ -115,11 +115,11 @@ export const ACTIONS = {
category: "selection",
defaultShortcuts: ["ctrl+d"],
},
"toggle-mute-selected": {
"toggle-elements-muted-selected": {
description: "Mute/unmute selected elements",
category: "selection",
},
"toggle-visibility-selected": {
"toggle-elements-visibility-selected": {
description: "Show/hide selected elements",
category: "selection",
},
+1
View File
@@ -3,3 +3,4 @@ export { Command } from "./base-command";
export * from "./timeline";
export * from "./media";
export * from "./scene";
export * from "./project";
@@ -0,0 +1 @@
export * from "./update-project-settings";
@@ -0,0 +1,46 @@
import { Command } from "@/lib/commands/base-command";
import { EditorCore } from "@/core";
import type { TProject, TProjectSettings } from "@/types/project";
export class UpdateProjectSettingsCommand extends Command {
private savedSettings: TProjectSettings | null = null;
private savedUpdatedAt: Date | null = null;
constructor(private updates: Partial<TProjectSettings>) {
super();
}
execute(): void {
const editor = EditorCore.getInstance();
const activeProject = editor.project.getActiveOrNull();
if (!activeProject) return;
this.savedSettings = activeProject.settings;
this.savedUpdatedAt = activeProject.metadata.updatedAt;
const updatedProject: TProject = {
...activeProject,
settings: { ...activeProject.settings, ...this.updates },
metadata: { ...activeProject.metadata, updatedAt: new Date() },
};
editor.project.setActiveProject({ project: updatedProject });
editor.save.markDirty();
}
undo(): void {
if (!this.savedSettings || !this.savedUpdatedAt) return;
const editor = EditorCore.getInstance();
const activeProject = editor.project.getActiveOrNull();
if (!activeProject) return;
const updatedProject: TProject = {
...activeProject,
settings: this.savedSettings,
metadata: { ...activeProject.metadata, updatedAt: this.savedUpdatedAt },
};
editor.project.setActiveProject({ project: updatedProject });
editor.save.markDirty();
}
}
@@ -97,11 +97,15 @@ export class AddElementToTrackCommand extends Command {
settings: {
canvasSize: { width: asset.width, height: asset.height },
},
pushHistory: false,
});
}
if (asset?.type === "video" && asset?.fps) {
editor.project.updateSettings({ settings: { fps: asset.fps } });
editor.project.updateSettings({
settings: { fps: asset.fps },
pushHistory: false,
});
}
}
@@ -1,7 +1,10 @@
import { Command } from "@/lib/commands/base-command";
import { EditorCore } from "@/core";
import type { TimelineTrack, TimelineElement } from "@/types/timeline";
import { validateElementTrackCompatibility } from "@/lib/timeline/track-utils";
import type { TimelineTrack, TimelineElement, TrackType } from "@/types/timeline";
import {
buildEmptyTrack,
validateElementTrackCompatibility,
} from "@/lib/timeline/track-utils";
export class MoveElementCommand extends Command {
private savedState: TimelineTrack[] | null = null;
@@ -11,6 +14,7 @@ export class MoveElementCommand extends Command {
private targetTrackId: string,
private elementId: string,
private newStartTime: number,
private createTrack?: { type: TrackType; index: number },
) {
super();
}
@@ -27,7 +31,17 @@ export class MoveElementCommand extends Command {
return;
}
const targetTrack = this.savedState.find((t) => t.id === this.targetTrackId);
let targetTrack = this.savedState.find((t) => t.id === this.targetTrackId);
let tracksToUpdate = this.savedState;
if (!targetTrack && this.createTrack) {
const newTrack = buildEmptyTrack({
id: this.targetTrackId,
type: this.createTrack.type,
});
tracksToUpdate = [...this.savedState];
tracksToUpdate.splice(this.createTrack.index, 0, newTrack);
targetTrack = newTrack;
}
if (!targetTrack) {
console.error("Target track not found");
return;
@@ -50,7 +64,7 @@ export class MoveElementCommand extends Command {
const isSameTrack = this.sourceTrackId === this.targetTrackId;
const updatedTracks = this.savedState.map((track) => {
const updatedTracks = tracksToUpdate.map((track) => {
if (isSameTrack && track.id === this.sourceTrackId) {
return {
...track,
@@ -6,7 +6,6 @@ export class UpdateElementTrimCommand extends Command {
private savedState: TimelineTrack[] | null = null;
constructor(
private trackId: string,
private elementId: string,
private trimStart: number,
private trimEnd: number,
@@ -18,14 +17,13 @@ export class UpdateElementTrimCommand extends Command {
const editor = EditorCore.getInstance();
this.savedState = editor.timeline.getTracks();
const updatedTracks = this.savedState.map((t) => {
if (t.id !== this.trackId) return t;
const newElements = t.elements.map((el) =>
el.id === this.elementId
? { ...el, trimStart: this.trimStart, trimEnd: this.trimEnd }
: el,
const updatedTracks = this.savedState.map((track) => {
const newElements = track.elements.map((element) =>
element.id === this.elementId
? { ...element, trimStart: this.trimStart, trimEnd: this.trimEnd }
: element,
);
return { ...t, elements: newElements } as typeof t;
return { ...track, elements: newElements } as typeof track;
});
editor.timeline.updateTracks(updatedTracks);
@@ -2,6 +2,7 @@ import { Command } from "@/lib/commands/base-command";
import type { TrackType, TimelineTrack } from "@/types/timeline";
import { generateUUID } from "@/lib/utils";
import { EditorCore } from "@/core";
import { buildEmptyTrack } from "@/lib/timeline/track-utils";
export class AddTrackCommand extends Command {
private trackId: string;
@@ -19,34 +20,10 @@ export class AddTrackCommand extends Command {
const editor = EditorCore.getInstance();
this.savedState = editor.timeline.getTracks();
const trackName =
this.type === "video"
? "Video track"
: this.type === "text"
? "Text track"
: this.type === "audio"
? "Audio track"
: this.type === "sticker"
? "Sticker track"
: "Track";
const newTrack: TimelineTrack =
this.type === "video"
? {
id: this.trackId,
name: trackName,
type: "video",
elements: [],
muted: false,
isMain: false,
}
: {
id: this.trackId,
name: trackName,
type: this.type,
elements: [],
muted: false,
};
const newTrack: TimelineTrack = buildEmptyTrack({
id: this.trackId,
type: this.type,
});
let updatedTracks: TimelineTrack[];
if (this.index !== undefined) {
@@ -1,3 +1,4 @@
export { AddTrackCommand } from "./add-track";
export { RemoveTrackCommand } from "./remove-track";
export { ToggleTrackMuteCommand } from "./toggle-track-mute";
export { ToggleTrackVisibilityCommand } from "./toggle-track-visibility";
@@ -0,0 +1,40 @@
import { Command } from "@/lib/commands/base-command";
import type { TimelineTrack } from "@/types/timeline";
import { EditorCore } from "@/core";
import { canTrackBeHidden } from "@/lib/timeline";
export class ToggleTrackVisibilityCommand extends Command {
private savedState: TimelineTrack[] | null = null;
constructor(private trackId: string) {
super();
}
execute(): void {
const editor = EditorCore.getInstance();
this.savedState = editor.timeline.getTracks();
const targetTrack = this.savedState.find(
(track) => track.id === this.trackId,
);
if (!targetTrack) {
return;
}
const updatedTracks = this.savedState.map((track) => {
if (track.id === this.trackId && canTrackBeHidden(track)) {
return { ...track, hidden: !track.hidden };
}
return track;
});
editor.timeline.updateTracks(updatedTracks);
}
undo(): void {
if (this.savedState) {
const editor = EditorCore.getInstance();
editor.timeline.updateTracks(this.savedState);
}
}
}
@@ -100,14 +100,6 @@ class StorageService {
if (!serializedProject) return null;
console.log(
"[storage] loadProject scenes",
JSON.stringify({
projectId: id,
scenes: serializedProject.scenes ?? [],
}),
);
const scenes =
serializedProject.scenes?.map((scene) => ({
id: scene.id,
+2
View File
@@ -94,6 +94,7 @@ export function computeDropTarget({
elementDuration,
pixelsPerSecond,
zoomLevel,
excludeElementId,
}: ComputeDropTargetParams): DropTarget {
const xPosition = isExternalDrop
? playheadTime
@@ -159,6 +160,7 @@ export function computeDropTarget({
elements: track.elements,
startTime: xPosition,
endTime,
excludeElementId,
});
if (isTrackCompatible && !hasOverlap) {
+62
View File
@@ -67,6 +67,67 @@ export function getTotalTracksHeight({
return tracksHeight + gapsHeight;
}
export function buildEmptyTrack({
id,
type,
name,
}: {
id: string;
type: TrackType;
name?: string;
}): TimelineTrack {
const trackName =
name ??
(type === "video"
? "Video track"
: type === "text"
? "Text track"
: type === "audio"
? "Audio track"
: type === "sticker"
? "Sticker track"
: "Track");
switch (type) {
case "video":
return {
id,
name: trackName,
type: "video",
elements: [],
hidden: false,
muted: false,
isMain: false,
};
case "text":
return {
id,
name: trackName,
type: "text",
elements: [],
hidden: false,
};
case "sticker":
return {
id,
name: trackName,
type: "sticker",
elements: [],
hidden: false,
};
case "audio":
return {
id,
name: trackName,
type: "audio",
elements: [],
muted: false,
};
default:
throw new Error(`Unsupported track type: ${type}`);
}
}
export function isMainTrack(track: TimelineTrack): track is VideoTrack {
return track.type === "video" && track.isMain === true;
}
@@ -94,6 +155,7 @@ export function ensureMainTrack({
elements: [],
muted: false,
isMain: true,
hidden: false,
};
return [mainTrack, ...tracks];
}
@@ -20,13 +20,7 @@ export type BuildSceneParams = {
};
export function buildScene(params: BuildSceneParams) {
const {
tracks,
mediaAssets,
duration,
canvasSize,
background
} = params;
const { tracks, mediaAssets, duration, canvasSize, background } = params;
const rootNode = new RootNode({ duration });
const mediaMap = new Map(mediaAssets.map((m) => [m.id, m]));
@@ -34,8 +28,10 @@ export function buildScene(params: BuildSceneParams) {
const elements = tracks
.slice()
.reverse()
.filter((track) => !(canTracktHaveAudio(track) && track.muted))
.flatMap((track): TimelineElement[] => track.elements);
.filter((track) => !("hidden" in track && track.hidden))
.flatMap((track): TimelineElement[] =>
track.elements.filter((element) => !("hidden" in element && element.hidden)),
);
const contentNodes = [];
@@ -101,7 +97,10 @@ export function buildScene(params: BuildSceneParams) {
contentNodes,
}),
);
} else if (background.type === "color" && background.color !== "transparent") {
} else if (
background.type === "color" &&
background.color !== "transparent"
) {
rootNode.add(new ColorNode({ color: background.color }));
}
+2
View File
@@ -154,6 +154,7 @@ export interface ElementDragState {
elementId: string | null;
trackId: string | null;
startMouseX: number;
startMouseY: number;
startElementTime: number;
clickOffsetTime: number;
currentTime: number;
@@ -176,6 +177,7 @@ export interface ComputeDropTargetParams {
elementDuration: number;
pixelsPerSecond: number;
zoomLevel: number;
excludeElementId?: string;
}
export interface ClipboardItem {