TimelapseEditorModal.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import { useState, useRef, useEffect, useCallback } from 'react';
  2. import { useQuery, useMutation } from '@tanstack/react-query';
  3. import {
  4. X,
  5. Save,
  6. Film,
  7. Play,
  8. Pause,
  9. Scissors,
  10. Gauge,
  11. Music,
  12. Upload,
  13. Trash2,
  14. Volume2,
  15. VolumeX,
  16. Loader2,
  17. } from 'lucide-react';
  18. import { Button } from './Button';
  19. import { api } from '../api/client';
  20. import { useToast } from '../contexts/ToastContext';
  21. import { formatMediaTime } from '../utils/date';
  22. interface TimelapseEditorModalProps {
  23. archiveId: number;
  24. timelapseSrc: string;
  25. onClose: () => void;
  26. onSave?: () => void;
  27. }
  28. const SPEED_OPTIONS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4];
  29. export function TimelapseEditorModal({
  30. archiveId,
  31. timelapseSrc,
  32. onClose,
  33. onSave,
  34. }: TimelapseEditorModalProps) {
  35. const { showToast } = useToast();
  36. const videoRef = useRef<HTMLVideoElement>(null);
  37. const audioRef = useRef<HTMLAudioElement>(null);
  38. // Video state
  39. const [isPlaying, setIsPlaying] = useState(false);
  40. const [currentTime, setCurrentTime] = useState(0);
  41. const [duration, setDuration] = useState(0);
  42. // Editor state
  43. const [trimStart, setTrimStart] = useState(0);
  44. const [trimEnd, setTrimEnd] = useState(0);
  45. const [speed, setSpeed] = useState(1);
  46. const [audioFile, setAudioFile] = useState<File | null>(null);
  47. const [audioUrl, setAudioUrl] = useState<string | null>(null);
  48. const [audioVolume, setAudioVolume] = useState(0.8);
  49. const [audioMuted, setAudioMuted] = useState(false);
  50. // Fetch video info
  51. const { data: videoInfo, isLoading: isLoadingInfo } = useQuery({
  52. queryKey: ['timelapse-info', archiveId],
  53. queryFn: () => api.getTimelapseInfo(archiveId),
  54. });
  55. // Fetch thumbnails
  56. const { data: thumbnailData } = useQuery({
  57. queryKey: ['timelapse-thumbnails', archiveId],
  58. queryFn: () => api.getTimelapseThumbnails(archiveId, 15),
  59. });
  60. // Process mutation
  61. const processMutation = useMutation({
  62. mutationFn: () =>
  63. api.processTimelapse(
  64. archiveId,
  65. {
  66. trimStart,
  67. trimEnd,
  68. speed,
  69. saveMode: 'replace',
  70. },
  71. audioFile || undefined
  72. ),
  73. onSuccess: (data) => {
  74. showToast(data.message, 'success');
  75. onSave?.();
  76. onClose();
  77. },
  78. onError: (error: Error) => {
  79. showToast(error.message || 'Processing failed', 'error');
  80. },
  81. });
  82. // Initialize trimEnd when duration is available
  83. useEffect(() => {
  84. if (videoInfo?.duration && trimEnd === 0) {
  85. setTrimEnd(videoInfo.duration);
  86. }
  87. }, [videoInfo?.duration, trimEnd]);
  88. // Close on Escape
  89. useEffect(() => {
  90. const handleKeyDown = (e: KeyboardEvent) => {
  91. if (e.key === 'Escape') {
  92. onClose();
  93. }
  94. };
  95. window.addEventListener('keydown', handleKeyDown);
  96. return () => window.removeEventListener('keydown', handleKeyDown);
  97. }, [onClose]);
  98. // Video event handlers
  99. useEffect(() => {
  100. const video = videoRef.current;
  101. if (!video) return;
  102. const handleTimeUpdate = () => {
  103. const time = video.currentTime;
  104. setCurrentTime(time);
  105. // Loop within trim region
  106. if (time >= trimEnd) {
  107. video.currentTime = trimStart;
  108. }
  109. };
  110. const handleDurationChange = () => {
  111. setDuration(video.duration);
  112. if (trimEnd === 0) {
  113. setTrimEnd(video.duration);
  114. }
  115. };
  116. const handlePlay = () => setIsPlaying(true);
  117. const handlePause = () => setIsPlaying(false);
  118. video.addEventListener('timeupdate', handleTimeUpdate);
  119. video.addEventListener('durationchange', handleDurationChange);
  120. video.addEventListener('play', handlePlay);
  121. video.addEventListener('pause', handlePause);
  122. return () => {
  123. video.removeEventListener('timeupdate', handleTimeUpdate);
  124. video.removeEventListener('durationchange', handleDurationChange);
  125. video.removeEventListener('play', handlePlay);
  126. video.removeEventListener('pause', handlePause);
  127. };
  128. }, [trimStart, trimEnd]);
  129. // Sync audio with video
  130. useEffect(() => {
  131. const audio = audioRef.current;
  132. const video = videoRef.current;
  133. if (!audio || !video || !audioUrl) return;
  134. audio.currentTime = video.currentTime;
  135. audio.playbackRate = video.playbackRate;
  136. if (isPlaying && !audioMuted) {
  137. audio.play().catch(() => {});
  138. } else {
  139. audio.pause();
  140. }
  141. }, [isPlaying, audioUrl, audioMuted]);
  142. // Update audio volume
  143. useEffect(() => {
  144. if (audioRef.current) {
  145. audioRef.current.volume = audioMuted ? 0 : audioVolume;
  146. }
  147. }, [audioVolume, audioMuted]);
  148. // Update playback rate
  149. useEffect(() => {
  150. if (videoRef.current) {
  151. videoRef.current.playbackRate = speed;
  152. }
  153. if (audioRef.current) {
  154. audioRef.current.playbackRate = speed;
  155. }
  156. }, [speed]);
  157. const togglePlay = useCallback(() => {
  158. const video = videoRef.current;
  159. if (!video) return;
  160. if (isPlaying) {
  161. video.pause();
  162. } else {
  163. // Start from trim start if before it
  164. if (video.currentTime < trimStart) {
  165. video.currentTime = trimStart;
  166. }
  167. video.play();
  168. }
  169. }, [isPlaying, trimStart]);
  170. const handleSeek = (time: number) => {
  171. const video = videoRef.current;
  172. if (!video) return;
  173. video.currentTime = Math.max(trimStart, Math.min(trimEnd, time));
  174. };
  175. const handleAudioUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
  176. const file = e.target.files?.[0];
  177. if (!file) return;
  178. // Cleanup previous URL
  179. if (audioUrl) {
  180. URL.revokeObjectURL(audioUrl);
  181. }
  182. setAudioFile(file);
  183. setAudioUrl(URL.createObjectURL(file));
  184. };
  185. const removeAudio = () => {
  186. if (audioUrl) {
  187. URL.revokeObjectURL(audioUrl);
  188. }
  189. setAudioFile(null);
  190. setAudioUrl(null);
  191. };
  192. // Cleanup on unmount
  193. useEffect(() => {
  194. return () => {
  195. if (audioUrl) {
  196. URL.revokeObjectURL(audioUrl);
  197. }
  198. };
  199. }, [audioUrl]);
  200. const trimmedDuration = trimEnd - trimStart;
  201. const outputDuration = trimmedDuration / speed;
  202. if (isLoadingInfo) {
  203. return (
  204. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80">
  205. <div className="flex items-center gap-3 text-white">
  206. <Loader2 className="w-6 h-6 animate-spin" />
  207. Loading video info...
  208. </div>
  209. </div>
  210. );
  211. }
  212. return (
  213. <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80">
  214. <div className="relative bg-bambu-dark-secondary rounded-xl max-w-5xl w-full mx-4 max-h-[90vh] overflow-hidden flex flex-col">
  215. {/* Header */}
  216. <div className="flex items-center justify-between p-4 border-b border-bambu-dark-tertiary shrink-0">
  217. <h3 className="text-lg font-semibold text-white flex items-center gap-2">
  218. <Film className="w-5 h-5 text-bambu-green" />
  219. Edit Timelapse
  220. </h3>
  221. <div className="flex items-center gap-2">
  222. <Button
  223. variant="primary"
  224. size="sm"
  225. onClick={() => processMutation.mutate()}
  226. disabled={processMutation.isPending}
  227. >
  228. {processMutation.isPending ? (
  229. <>
  230. <Loader2 className="w-4 h-4 animate-spin" />
  231. Processing...
  232. </>
  233. ) : (
  234. <>
  235. <Save className="w-4 h-4" />
  236. Save
  237. </>
  238. )}
  239. </Button>
  240. <button
  241. onClick={onClose}
  242. className="p-1 hover:bg-bambu-dark-tertiary rounded transition-colors"
  243. >
  244. <X className="w-5 h-5 text-bambu-gray" />
  245. </button>
  246. </div>
  247. </div>
  248. {/* Content */}
  249. <div className="flex-1 overflow-y-auto p-4 space-y-4">
  250. {/* Video Preview */}
  251. <div className="relative">
  252. <video
  253. ref={videoRef}
  254. src={timelapseSrc}
  255. className="w-full rounded-lg bg-black"
  256. onClick={togglePlay}
  257. muted={!!audioUrl}
  258. />
  259. {/* Play overlay */}
  260. {!isPlaying && (
  261. <button
  262. onClick={togglePlay}
  263. className="absolute inset-0 flex items-center justify-center bg-black/30 hover:bg-black/40 transition-colors"
  264. >
  265. <div className="p-4 bg-bambu-green rounded-full">
  266. <Play className="w-8 h-8 text-white" />
  267. </div>
  268. </button>
  269. )}
  270. {/* Hidden audio element for music overlay preview */}
  271. {audioUrl && (
  272. <audio ref={audioRef} src={audioUrl} loop />
  273. )}
  274. </div>
  275. {/* Timeline with Thumbnails */}
  276. <div className="space-y-2">
  277. <div className="flex items-center gap-2 text-sm text-bambu-gray">
  278. <Scissors className="w-4 h-4" />
  279. <span>Trim</span>
  280. <span className="ml-auto">
  281. {formatMediaTime(trimStart)} - {formatMediaTime(trimEnd)} ({formatMediaTime(trimmedDuration)})
  282. </span>
  283. </div>
  284. {/* Thumbnail strip */}
  285. <div className="relative h-16 bg-bambu-dark rounded-lg overflow-hidden">
  286. {/* Thumbnails background */}
  287. <div className="absolute inset-0 flex">
  288. {thumbnailData?.thumbnails.map((thumb, i) => (
  289. <div
  290. key={i}
  291. className="flex-1 bg-cover bg-center"
  292. style={{
  293. backgroundImage: `url(data:image/jpeg;base64,${thumb})`,
  294. }}
  295. />
  296. ))}
  297. </div>
  298. {/* Trim overlay - grayed out areas */}
  299. <div
  300. className="absolute inset-y-0 left-0 bg-black/60"
  301. style={{ width: `${(trimStart / duration) * 100}%` }}
  302. />
  303. <div
  304. className="absolute inset-y-0 right-0 bg-black/60"
  305. style={{ width: `${((duration - trimEnd) / duration) * 100}%` }}
  306. />
  307. {/* Selected region border */}
  308. <div
  309. className="absolute inset-y-0 border-2 border-bambu-green"
  310. style={{
  311. left: `${(trimStart / duration) * 100}%`,
  312. right: `${((duration - trimEnd) / duration) * 100}%`,
  313. }}
  314. />
  315. {/* Current time indicator */}
  316. <div
  317. className="absolute top-0 bottom-0 w-0.5 bg-white shadow-lg"
  318. style={{ left: `${(currentTime / duration) * 100}%` }}
  319. />
  320. {/* Trim handles */}
  321. <input
  322. type="range"
  323. min={0}
  324. max={duration}
  325. step={0.1}
  326. value={trimStart}
  327. onChange={(e) => {
  328. const val = parseFloat(e.target.value);
  329. if (val < trimEnd - 1) {
  330. setTrimStart(val);
  331. if (videoRef.current && videoRef.current.currentTime < val) {
  332. videoRef.current.currentTime = val;
  333. }
  334. }
  335. }}
  336. className="absolute inset-0 w-full opacity-0 cursor-ew-resize"
  337. style={{ clipPath: 'inset(0 50% 0 0)' }}
  338. />
  339. <input
  340. type="range"
  341. min={0}
  342. max={duration}
  343. step={0.1}
  344. value={trimEnd}
  345. onChange={(e) => {
  346. const val = parseFloat(e.target.value);
  347. if (val > trimStart + 1) {
  348. setTrimEnd(val);
  349. }
  350. }}
  351. className="absolute inset-0 w-full opacity-0 cursor-ew-resize"
  352. style={{ clipPath: 'inset(0 0 0 50%)' }}
  353. />
  354. </div>
  355. {/* Playback scrubber */}
  356. <input
  357. type="range"
  358. min={0}
  359. max={duration}
  360. step={0.1}
  361. value={currentTime}
  362. onChange={(e) => handleSeek(parseFloat(e.target.value))}
  363. className="w-full h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  364. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  365. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full
  366. [&::-webkit-slider-thumb]:cursor-pointer"
  367. />
  368. {/* Play controls */}
  369. <div className="flex items-center justify-center gap-2">
  370. <button
  371. onClick={togglePlay}
  372. className="p-2 bg-bambu-green hover:bg-bambu-green-dark rounded-lg transition-colors"
  373. >
  374. {isPlaying ? (
  375. <Pause className="w-5 h-5 text-white" />
  376. ) : (
  377. <Play className="w-5 h-5 text-white" />
  378. )}
  379. </button>
  380. </div>
  381. </div>
  382. {/* Speed Control */}
  383. <div className="space-y-2">
  384. <div className="flex items-center gap-2 text-sm text-bambu-gray">
  385. <Gauge className="w-4 h-4" />
  386. <span>Speed</span>
  387. <span className="ml-auto">{speed}x (output: {formatMediaTime(outputDuration)})</span>
  388. </div>
  389. <div className="flex gap-1">
  390. {SPEED_OPTIONS.map((s) => (
  391. <button
  392. key={s}
  393. onClick={() => setSpeed(s)}
  394. className={`flex-1 px-2 py-2 text-sm rounded transition-colors ${
  395. speed === s
  396. ? 'bg-bambu-green text-white'
  397. : 'bg-bambu-dark text-bambu-gray hover:bg-bambu-dark-tertiary'
  398. }`}
  399. >
  400. {s}x
  401. </button>
  402. ))}
  403. </div>
  404. </div>
  405. {/* Audio Upload */}
  406. <div className="space-y-2">
  407. <div className="flex items-center gap-2 text-sm text-bambu-gray">
  408. <Music className="w-4 h-4" />
  409. <span>Music Overlay</span>
  410. </div>
  411. {audioFile ? (
  412. <div className="flex items-center gap-3 p-3 bg-bambu-dark rounded-lg">
  413. <Music className="w-5 h-5 text-bambu-green" />
  414. <div className="flex-1 min-w-0">
  415. <p className="text-sm text-white truncate">{audioFile.name}</p>
  416. <p className="text-xs text-bambu-gray">
  417. {(audioFile.size / 1024 / 1024).toFixed(1)} MB
  418. </p>
  419. </div>
  420. {/* Volume control */}
  421. <button
  422. onClick={() => setAudioMuted(!audioMuted)}
  423. className="p-2 hover:bg-bambu-dark-tertiary rounded transition-colors"
  424. >
  425. {audioMuted ? (
  426. <VolumeX className="w-4 h-4 text-bambu-gray" />
  427. ) : (
  428. <Volume2 className="w-4 h-4 text-bambu-green" />
  429. )}
  430. </button>
  431. <input
  432. type="range"
  433. min={0}
  434. max={1}
  435. step={0.1}
  436. value={audioVolume}
  437. onChange={(e) => setAudioVolume(parseFloat(e.target.value))}
  438. className="w-20 h-1 bg-bambu-dark-tertiary rounded-lg appearance-none cursor-pointer
  439. [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:h-3
  440. [&::-webkit-slider-thumb]:bg-bambu-green [&::-webkit-slider-thumb]:rounded-full"
  441. />
  442. <button
  443. onClick={removeAudio}
  444. className="p-2 hover:bg-red-100 dark:hover:bg-red-500/20 rounded transition-colors"
  445. >
  446. <Trash2 className="w-4 h-4 text-red-600 dark:text-red-400" />
  447. </button>
  448. </div>
  449. ) : (
  450. <label className="flex flex-col items-center justify-center gap-2 p-6 border-2 border-dashed border-bambu-dark-tertiary rounded-lg cursor-pointer hover:border-bambu-green/50 transition-colors">
  451. <Upload className="w-8 h-8 text-bambu-gray" />
  452. <span className="text-sm text-bambu-gray">
  453. Drop audio file or click to upload
  454. </span>
  455. <span className="text-xs text-bambu-gray/60">
  456. MP3, WAV, M4A, AAC, OGG
  457. </span>
  458. <input
  459. type="file"
  460. accept=".mp3,.wav,.m4a,.aac,.ogg,audio/*"
  461. onChange={handleAudioUpload}
  462. className="hidden"
  463. />
  464. </label>
  465. )}
  466. </div>
  467. {/* Summary */}
  468. <div className="p-3 bg-bambu-dark rounded-lg text-sm space-y-1">
  469. <p className="text-bambu-gray">
  470. <span className="text-white">Original:</span> {formatMediaTime(duration)} @ {videoInfo?.width}x{videoInfo?.height}
  471. </p>
  472. <p className="text-bambu-gray">
  473. <span className="text-white">Output:</span> {formatMediaTime(outputDuration)} @ {speed}x speed
  474. {audioFile && ` + music overlay`}
  475. </p>
  476. </div>
  477. </div>
  478. {/* Processing overlay */}
  479. {processMutation.isPending && (
  480. <div className="absolute inset-0 bg-black/80 flex flex-col items-center justify-center gap-4">
  481. <Loader2 className="w-12 h-12 text-bambu-green animate-spin" />
  482. <p className="text-white text-lg">Processing timelapse...</p>
  483. <p className="text-bambu-gray text-sm">This may take a few moments</p>
  484. </div>
  485. )}
  486. </div>
  487. </div>
  488. );
  489. }