|
| 1 | +// Timeline asset/file drop + add-at-playhead handlers, extracted from |
| 2 | +// useTimelineEditing so that hook stays a wiring shell. Called unconditionally as |
| 3 | +// a sub-hook to preserve the parent's hook call order. |
| 4 | +import { useCallback } from "react"; |
| 5 | +import type { MutableRefObject } from "react"; |
| 6 | +import type { TimelineElement } from "../player"; |
| 7 | +import { usePlayerStore } from "../player"; |
| 8 | +import { resolveZoneDropPlacement } from "../player/components/timelineCollision"; |
| 9 | +import { isAudioTimelineElement } from "../utils/timelineInspector"; |
| 10 | +import { |
| 11 | + buildTimelineAssetId, |
| 12 | + extendCompositionDurationIfNeeded, |
| 13 | + buildTimelineAssetInsertHtml, |
| 14 | + buildTimelineFileDropPlacements, |
| 15 | + fitTimelineAssetGeometry, |
| 16 | + getTimelineAssetKind, |
| 17 | + insertTimelineAssetIntoSource, |
| 18 | + resolveTimelineAssetCompositionSize, |
| 19 | + resolveTimelineAssetSrc, |
| 20 | +} from "../utils/timelineAssetDrop"; |
| 21 | +import { saveProjectFilesWithHistory } from "../utils/studioFileHistory"; |
| 22 | +import { |
| 23 | + collectHtmlIds, |
| 24 | + resolveDroppedAssetDuration, |
| 25 | + resolveDroppedAssetDimensions, |
| 26 | +} from "../utils/studioHelpers"; |
| 27 | +import { generateId } from "../utils/generateId"; |
| 28 | +import { formatTimelineAttributeNumber, readFileContent } from "./timelineEditingHelpers"; |
| 29 | +import type { UseTimelineEditingOptions } from "./useTimelineEditingTypes"; |
| 30 | + |
| 31 | +export interface UseTimelineEditingDropsDeps extends Pick< |
| 32 | + UseTimelineEditingOptions, |
| 33 | + | "activeCompPath" |
| 34 | + | "timelineElements" |
| 35 | + | "showToast" |
| 36 | + | "writeProjectFile" |
| 37 | + | "recordEdit" |
| 38 | + | "domEditSaveTimestampRef" |
| 39 | + | "reloadPreview" |
| 40 | + | "uploadProjectFiles" |
| 41 | + | "isRecordingRef" |
| 42 | + | "forceReloadSdkSession" |
| 43 | +> { |
| 44 | + projectIdRef: MutableRefObject<string | null>; |
| 45 | +} |
| 46 | + |
| 47 | +export function useTimelineEditingDrops(deps: UseTimelineEditingDropsDeps) { |
| 48 | + const { |
| 49 | + projectIdRef, |
| 50 | + activeCompPath, |
| 51 | + timelineElements, |
| 52 | + showToast, |
| 53 | + writeProjectFile, |
| 54 | + recordEdit, |
| 55 | + domEditSaveTimestampRef, |
| 56 | + reloadPreview, |
| 57 | + uploadProjectFiles, |
| 58 | + isRecordingRef, |
| 59 | + forceReloadSdkSession, |
| 60 | + } = deps; |
| 61 | + |
| 62 | + // fallow-ignore-next-line complexity |
| 63 | + const handleTimelineAssetDrop = useCallback( |
| 64 | + // fallow-ignore-next-line complexity |
| 65 | + async ( |
| 66 | + assetPath: string, |
| 67 | + placement: Pick<TimelineElement, "start" | "track">, |
| 68 | + durationOverride?: number, |
| 69 | + ) => { |
| 70 | + if (isRecordingRef?.current) { |
| 71 | + showToast("Cannot edit timeline while recording", "error"); |
| 72 | + return; |
| 73 | + } |
| 74 | + const pid = projectIdRef.current; |
| 75 | + if (!pid) throw new Error("No active project"); |
| 76 | + const kind = getTimelineAssetKind(assetPath); |
| 77 | + if (!kind) { |
| 78 | + showToast("Only image, video, and audio assets can be dropped onto the timeline."); |
| 79 | + return; |
| 80 | + } |
| 81 | + const targetPath = activeCompPath || "index.html"; |
| 82 | + try { |
| 83 | + const originalContent = await readFileContent(pid, targetPath); |
| 84 | + const normalizedStart = Number(formatTimelineAttributeNumber(placement.start)); |
| 85 | + const duration = |
| 86 | + Number.isFinite(durationOverride) && durationOverride != null && durationOverride > 0 |
| 87 | + ? durationOverride |
| 88 | + : await resolveDroppedAssetDuration(pid, assetPath, kind); |
| 89 | + const normalizedDuration = Number(formatTimelineAttributeNumber(duration)); |
| 90 | + const newId = buildTimelineAssetId(assetPath, collectHtmlIds(originalContent)); |
| 91 | + const hfId = `hf-${generateId()}`; |
| 92 | + const compSize = resolveTimelineAssetCompositionSize(originalContent); |
| 93 | + const natural = |
| 94 | + kind === "audio" ? null : await resolveDroppedAssetDimensions(pid, assetPath, kind); |
| 95 | + const resolvedAssetSrc = resolveTimelineAssetSrc(targetPath, assetPath); |
| 96 | + |
| 97 | + const resolvedTargetPath = targetPath || "index.html"; |
| 98 | + const relevantElements = timelineElements.filter( |
| 99 | + (te) => (te.sourceFile || activeCompPath || "index.html") === resolvedTargetPath, |
| 100 | + ); |
| 101 | + const newElementZIndex = Math.max(1, relevantElements.length + 1); |
| 102 | + |
| 103 | + // Zone- and overlap-aware track: run the new clip through the same pure |
| 104 | + // drop decision a clip DRAG uses (visual lanes top / audio lanes bottom, |
| 105 | + // no same-track time overlap — relocate to the nearest free lane in the |
| 106 | + // kind zone, else a fresh track). Covers OS file drops, asset-panel |
| 107 | + // drops, and playhead adds alike, so adding an asset behaves exactly |
| 108 | + // like moving one. |
| 109 | + let resolvedTrack = placement.track; |
| 110 | + if (relevantElements.length > 0) { |
| 111 | + const order = [...new Set(relevantElements.map((te) => te.track))].sort((a, b) => a - b); |
| 112 | + const audioTracks = new Set( |
| 113 | + relevantElements.filter(isAudioTimelineElement).map((te) => te.track), |
| 114 | + ); |
| 115 | + const zoned = resolveZoneDropPlacement({ |
| 116 | + order, |
| 117 | + audioTracks, |
| 118 | + elements: relevantElements, |
| 119 | + desiredTrack: placement.track, |
| 120 | + deliberateInsertRow: null, |
| 121 | + start: normalizedStart, |
| 122 | + duration: normalizedDuration, |
| 123 | + dragKey: newId, |
| 124 | + isAudio: kind === "audio", |
| 125 | + }); |
| 126 | + // A needsInsert result means every lane in the kind zone is occupied at |
| 127 | + // this time — place on a fresh track; display normalization zones it. |
| 128 | + resolvedTrack = zoned.insertRow != null ? Math.max(...order) + 1 : zoned.track; |
| 129 | + } |
| 130 | + |
| 131 | + const patchedContent = extendCompositionDurationIfNeeded( |
| 132 | + insertTimelineAssetIntoSource( |
| 133 | + originalContent, |
| 134 | + buildTimelineAssetInsertHtml({ |
| 135 | + id: newId, |
| 136 | + hfId, |
| 137 | + assetPath: resolvedAssetSrc, |
| 138 | + kind, |
| 139 | + start: normalizedStart, |
| 140 | + duration: normalizedDuration, |
| 141 | + track: resolvedTrack, |
| 142 | + zIndex: newElementZIndex, |
| 143 | + geometry: fitTimelineAssetGeometry(natural, compSize), |
| 144 | + }), |
| 145 | + ), |
| 146 | + normalizedStart + normalizedDuration, |
| 147 | + ); |
| 148 | + |
| 149 | + domEditSaveTimestampRef.current = Date.now(); |
| 150 | + await saveProjectFilesWithHistory({ |
| 151 | + projectId: pid, |
| 152 | + label: "Add timeline asset", |
| 153 | + kind: "timeline", |
| 154 | + files: { [targetPath]: patchedContent }, |
| 155 | + readFile: async () => originalContent, |
| 156 | + writeFile: writeProjectFile, |
| 157 | + recordEdit, |
| 158 | + }); |
| 159 | + |
| 160 | + forceReloadSdkSession?.(); |
| 161 | + reloadPreview(); |
| 162 | + } catch (error) { |
| 163 | + const message = |
| 164 | + error instanceof Error ? error.message : "Failed to drop asset onto timeline"; |
| 165 | + showToast(message); |
| 166 | + } |
| 167 | + }, |
| 168 | + [ |
| 169 | + activeCompPath, |
| 170 | + recordEdit, |
| 171 | + showToast, |
| 172 | + timelineElements, |
| 173 | + writeProjectFile, |
| 174 | + domEditSaveTimestampRef, |
| 175 | + reloadPreview, |
| 176 | + isRecordingRef, |
| 177 | + forceReloadSdkSession, |
| 178 | + projectIdRef, |
| 179 | + ], |
| 180 | + ); |
| 181 | + // fallow-ignore-next-line complexity |
| 182 | + const handleTimelineFileDrop = useCallback( |
| 183 | + // fallow-ignore-next-line complexity |
| 184 | + async (files: File[], placement?: Pick<TimelineElement, "start" | "track">) => { |
| 185 | + if (isRecordingRef?.current) { |
| 186 | + showToast("Cannot edit timeline while recording", "error"); |
| 187 | + return; |
| 188 | + } |
| 189 | + const pid = projectIdRef.current; |
| 190 | + if (!pid) return; |
| 191 | + const uploaded = await uploadProjectFiles(files, "assets"); |
| 192 | + if (uploaded.length === 0) return; |
| 193 | + const durations: number[] = []; |
| 194 | + for (const assetPath of uploaded) { |
| 195 | + const kind = getTimelineAssetKind(assetPath); |
| 196 | + const duration = kind ? await resolveDroppedAssetDuration(pid, assetPath, kind) : 0; |
| 197 | + durations.push(Number(formatTimelineAttributeNumber(duration))); |
| 198 | + } |
| 199 | + const placements = buildTimelineFileDropPlacements( |
| 200 | + placement ?? { start: 0, track: 0 }, |
| 201 | + durations, |
| 202 | + ); |
| 203 | + for (const [index, assetPath] of uploaded.entries()) { |
| 204 | + await handleTimelineAssetDrop( |
| 205 | + assetPath, |
| 206 | + placements[index] ?? placements[0], |
| 207 | + durations[index], |
| 208 | + ); |
| 209 | + } |
| 210 | + }, |
| 211 | + [handleTimelineAssetDrop, uploadProjectFiles, isRecordingRef, showToast, projectIdRef], |
| 212 | + ); |
| 213 | + |
| 214 | + const handleAddAssetAtPlayhead = useCallback( |
| 215 | + async (assetPath: string) => { |
| 216 | + const pid = projectIdRef.current; |
| 217 | + if (!pid) return; |
| 218 | + const kind = getTimelineAssetKind(assetPath); |
| 219 | + if (!kind) { |
| 220 | + showToast("Only image, video, and audio assets can be added to the timeline."); |
| 221 | + return; |
| 222 | + } |
| 223 | + const start = usePlayerStore.getState().currentTime; |
| 224 | + const duration = await resolveDroppedAssetDuration(pid, assetPath, kind); |
| 225 | + // Add on track 0 at the playhead (no bump — placing onto an occupied track is fine). |
| 226 | + await handleTimelineAssetDrop(assetPath, { start, track: 0 }, duration); |
| 227 | + }, |
| 228 | + [handleTimelineAssetDrop, showToast, projectIdRef], |
| 229 | + ); |
| 230 | + |
| 231 | + return { handleTimelineAssetDrop, handleTimelineFileDrop, handleAddAssetAtPlayhead }; |
| 232 | +} |
0 commit comments