summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-drag-clip.ts
blob: eb4d74355ed3a29133f2f7abe7a7e474fde0817c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import { useState, useEffect, useCallback, useRef } from "react";
import { useTimelineStore } from "@/stores/timeline-store";

interface DragState {
  isDragging: boolean;
  clipId: string | null;
  trackId: string | null;
  startMouseX: number;
  startClipTime: number;
  clickOffsetTime: number;
  currentTime: number;
}

export function useDragClip(zoomLevel: number) {
  const { tracks, updateClipStartTime, moveClipToTrack } = useTimelineStore();

  const [dragState, setDragState] = useState<DragState>({
    isDragging: false,
    clipId: null,
    trackId: null,
    startMouseX: 0,
    startClipTime: 0,
    clickOffsetTime: 0,
    currentTime: 0,
  });

  const timelineRef = useRef<HTMLDivElement>(null);
  const dragStateRef = useRef(dragState);

  // Keep ref in sync with state
  dragStateRef.current = dragState;

  const startDrag = useCallback(
    (
      e: React.MouseEvent,
      clipId: string,
      trackId: string,
      clipStartTime: number,
      clickOffsetTime: number
    ) => {
      e.preventDefault();
      e.stopPropagation();

      setDragState({
        isDragging: true,
        clipId,
        trackId,
        startMouseX: e.clientX,
        startClipTime: clipStartTime,
        clickOffsetTime,
        currentTime: clipStartTime,
      });
    },
    []
  );

  const updateDrag = useCallback(
    (e: MouseEvent) => {
      if (!dragState.isDragging || !timelineRef.current) {
        return;
      }

      const timelineRect = timelineRef.current.getBoundingClientRect();
      const mouseX = e.clientX - timelineRect.left;
      const mouseTime = Math.max(0, mouseX / (50 * zoomLevel));
      const adjustedTime = Math.max(0, mouseTime - dragState.clickOffsetTime);
      const snappedTime = Math.round(adjustedTime * 10) / 10;

      setDragState((prev) => ({
        ...prev,
        currentTime: snappedTime,
      }));
    },
    [dragState.isDragging, dragState.clickOffsetTime, zoomLevel]
  );

  const endDrag = useCallback(
    (targetTrackId?: string) => {
      if (!dragState.isDragging || !dragState.clipId || !dragState.trackId)
        return;

      const finalTrackId = targetTrackId || dragState.trackId;
      const finalTime = dragState.currentTime;

      // Check for overlaps
      const sourceTrack = tracks.find((t) => t.id === dragState.trackId);
      const targetTrack = tracks.find((t) => t.id === finalTrackId);
      const movingClip = sourceTrack?.clips.find(
        (c) => c.id === dragState.clipId
      );

      if (!movingClip || !targetTrack) {
        setDragState((prev) => ({ ...prev, isDragging: false }));
        return;
      }

      const movingClipDuration =
        movingClip.duration - movingClip.trimStart - movingClip.trimEnd;
      const movingClipEnd = finalTime + movingClipDuration;

      const hasOverlap = targetTrack.clips.some((existingClip) => {
        // Skip the clip being moved if it's on the same track
        if (
          dragState.trackId === finalTrackId &&
          existingClip.id === dragState.clipId
        ) {
          return false;
        }

        const existingStart = existingClip.startTime;
        const existingEnd =
          existingClip.startTime +
          (existingClip.duration -
            existingClip.trimStart -
            existingClip.trimEnd);

        return finalTime < existingEnd && movingClipEnd > existingStart;
      });

      if (!hasOverlap) {
        if (dragState.trackId === finalTrackId) {
          // Moving within same track
          updateClipStartTime(finalTrackId, dragState.clipId!, finalTime);
        } else {
          // Moving to different track
          moveClipToTrack(dragState.trackId!, finalTrackId, dragState.clipId!);
          requestAnimationFrame(() => {
            updateClipStartTime(finalTrackId, dragState.clipId!, finalTime);
          });
        }
      }

      setDragState({
        isDragging: false,
        clipId: null,
        trackId: null,
        startMouseX: 0,
        startClipTime: 0,
        clickOffsetTime: 0,
        currentTime: 0,
      });
    },
    [dragState, tracks, updateClipStartTime, moveClipToTrack]
  );

  const cancelDrag = useCallback(() => {
    setDragState({
      isDragging: false,
      clipId: null,
      trackId: null,
      startMouseX: 0,
      startClipTime: 0,
      clickOffsetTime: 0,
      currentTime: 0,
    });
  }, []);

  // Global mouse events
  useEffect(() => {
    if (!dragState.isDragging) return;

    const handleMouseMove = (e: MouseEvent) => updateDrag(e);
    const handleMouseUp = () => endDrag();
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") cancelDrag();
    };

    document.addEventListener("mousemove", handleMouseMove);
    document.addEventListener("mouseup", handleMouseUp);
    document.addEventListener("keydown", handleEscape);

    return () => {
      document.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseup", handleMouseUp);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [dragState.isDragging, updateDrag, endDrag, cancelDrag]);

  const getDraggedClipPosition = useCallback(
    (clipId: string) => {
      // Use ref to get current state, not stale closure
      const currentDragState = dragStateRef.current;
      const isMatch =
        currentDragState.isDragging && currentDragState.clipId === clipId;

      if (isMatch) {
        return currentDragState.currentTime;
      }
      return null;
    },
    [] // No dependencies needed since we use ref
  );

  const isValidDropTarget = useCallback(
    (trackId: string) => {
      if (!dragState.isDragging) return false;

      const sourceTrack = tracks.find((t) => t.id === dragState.trackId);
      const targetTrack = tracks.find((t) => t.id === trackId);

      if (!sourceTrack || !targetTrack) return false;

      // For now, allow drops on same track type
      return sourceTrack.type === targetTrack.type;
    },
    [dragState.isDragging, dragState.trackId, tracks]
  );

  return {
    // State
    isDragging: dragState.isDragging,
    draggedClipId: dragState.clipId,
    currentDragTime: dragState.currentTime,
    clickOffsetTime: dragState.clickOffsetTime,

    // Methods
    startDrag,
    endDrag,
    cancelDrag,
    getDraggedClipPosition,
    isValidDropTarget,

    // Refs
    timelineRef,
  };
}